9ff0f04ba3
Enable ANN rules in ruff.toml (flake8-annotations) and resolve all 221 violations: ANN201/ANN202 — return types on 168 public/private functions: - All 28 FastAPI routers: endpoints annotated with dict/list/specific schema/ StreamingResponse/FileResponse/JSONResponse as appropriate - main.py: lifespan→AsyncGenerator[None,None], exception handlers→JSONResponse - database.py: get_db→Generator[Session,None,None], proxy methods→correct types - middleware/request_context.py: dispatch→Response with Callable call_next type ANN001/ANN002/ANN003 — 32 missing argument types: - seed_demo.py: all db parameters typed as Session - domain/unit_of_work.py: __aexit__ exc_type/exc_val/exc_tb typed with TracebackType - services: audit_service user_id→UUID|None, heatmap_service query/model/builder, notification_service test→Test, tempo_service test→Test/user→User, test_workflow_service test_id→UUID, campaign_crud **fields→object, test_crud **fields→object (4 sites) ANN401 — 16 Any usages resolved: - Domain entities (campaign/technique/threat_actor/test_entity): replaced Any with actual ORM types via TYPE_CHECKING guards to avoid circular imports - detection_rule_service: test_id/detection_rule_id/evaluator_id→UUID - score_cache: kept Any with # noqa: ANN401 (genuinely generic cache) - jira_service/tempo_service: kept Any with # noqa: ANN401 (lazy optional deps) - d3fend_import_service: _to_str(v: Any) kept with # noqa: ANN401 ANN204/ANN205/ANN206 — special/static/class methods: - database.py proxy __call__/__getattr__: *args: object/**kwargs: object - schemas/test.py model_validate: obj→object, **kwargs→object - sa_technique_repository._int_type→type All 439 unit tests pass. ruff check app/ → All checks passed!
107 lines
3.5 KiB
Python
107 lines
3.5 KiB
Python
"""Campaign domain entity with lifecycle validation.
|
|
|
|
Pure domain logic — no framework imports.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import enum
|
|
import uuid
|
|
from dataclasses import dataclass, field
|
|
from typing import TYPE_CHECKING
|
|
|
|
from app.domain.errors import BusinessRuleViolation, InvalidStateTransition
|
|
|
|
if TYPE_CHECKING:
|
|
from app.models.campaign import Campaign as CampaignORM
|
|
|
|
|
|
class CampaignStatus(str, enum.Enum):
|
|
draft = "draft"
|
|
active = "active"
|
|
completed = "completed"
|
|
archived = "archived"
|
|
|
|
|
|
class CampaignType(str, enum.Enum):
|
|
custom = "custom"
|
|
apt_emulation = "apt_emulation"
|
|
kill_chain = "kill_chain"
|
|
compliance = "compliance"
|
|
|
|
|
|
VALID_TRANSITIONS: dict[CampaignStatus, list[CampaignStatus]] = {
|
|
CampaignStatus.draft: [CampaignStatus.active],
|
|
CampaignStatus.active: [CampaignStatus.completed],
|
|
CampaignStatus.completed: [CampaignStatus.archived],
|
|
CampaignStatus.archived: [],
|
|
}
|
|
|
|
|
|
@dataclass
|
|
class CampaignEntity:
|
|
name: str
|
|
type: CampaignType = CampaignType.custom
|
|
status: CampaignStatus = CampaignStatus.draft
|
|
id: uuid.UUID | None = None
|
|
description: str | None = None
|
|
threat_actor_id: uuid.UUID | None = None
|
|
created_by: uuid.UUID | None = None
|
|
target_platform: str | None = None
|
|
tags: list[str] = field(default_factory=list)
|
|
test_count: int = 0
|
|
|
|
def can_transition_to(self, target: CampaignStatus) -> bool:
|
|
return target in VALID_TRANSITIONS.get(self.status, [])
|
|
|
|
def activate(self) -> None:
|
|
if not self.can_transition_to(CampaignStatus.active):
|
|
raise InvalidStateTransition(
|
|
self.status.value, CampaignStatus.active.value,
|
|
[s.value for s in VALID_TRANSITIONS[self.status]],
|
|
)
|
|
if self.test_count == 0:
|
|
raise BusinessRuleViolation(
|
|
"Campaign must have at least one test to activate"
|
|
)
|
|
self.status = CampaignStatus.active
|
|
|
|
def complete(self) -> None:
|
|
if not self.can_transition_to(CampaignStatus.completed):
|
|
raise InvalidStateTransition(
|
|
self.status.value, CampaignStatus.completed.value,
|
|
[s.value for s in VALID_TRANSITIONS[self.status]],
|
|
)
|
|
self.status = CampaignStatus.completed
|
|
|
|
def archive(self) -> None:
|
|
if not self.can_transition_to(CampaignStatus.archived):
|
|
raise InvalidStateTransition(
|
|
self.status.value, CampaignStatus.archived.value,
|
|
[s.value for s in VALID_TRANSITIONS[self.status]],
|
|
)
|
|
self.status = CampaignStatus.archived
|
|
|
|
def ensure_modifiable(self) -> None:
|
|
if self.status not in (CampaignStatus.draft, CampaignStatus.active):
|
|
raise BusinessRuleViolation(
|
|
f"Cannot modify campaign in '{self.status.value}' state"
|
|
)
|
|
|
|
@classmethod
|
|
def from_orm(cls, orm: CampaignORM) -> CampaignEntity:
|
|
"""Build a CampaignEntity from a SQLAlchemy Campaign model."""
|
|
test_count = len(getattr(orm, "campaign_tests", None) or [])
|
|
return cls(
|
|
id=orm.id,
|
|
name=orm.name,
|
|
type=CampaignType(orm.type) if orm.type else CampaignType.custom,
|
|
status=CampaignStatus(orm.status) if orm.status else CampaignStatus.draft,
|
|
description=orm.description,
|
|
threat_actor_id=orm.threat_actor_id,
|
|
created_by=orm.created_by,
|
|
target_platform=orm.target_platform,
|
|
tags=orm.tags or [],
|
|
test_count=test_count,
|
|
)
|