Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(wave3+4): implement Wave 3 & 4 capability roadmap
Beenu Arora67a96605e678
diff --git a/services/actions/app/services/maturity.py b/services/actions/app/services/maturity.pynew file mode 100644index 000000000..d320cff1a--- /dev/null+++ b/services/actions/app/services/maturity.py@@ -0,0 +1,186 @@+"""+L0–L4 Auto-remediation maturity tier gate.++Each tenant has a maturity_tier (0–4) that controls which actions are allowed+to execute automatically versus requiring human approval.++ L0 — Observe: All actions routed to approval queue.+ L1 — Notify: MINIMAL blast-radius actions are automatic.+ L2 — Contain: LOW blast-radius actions are automatic.+ L3 — Remediate: MEDIUM blast-radius actions are automatic.+ L4 — Automate: HIGH blast-radius actions are automatic (with whitelist check).+"""++from __future__ import annotations++from dataclasses import dataclass, field+from enum import IntEnum+from typing import Any++from app.models.action import ACTION_BLAST_RADIUS, ActionRequest, ActionType, BlastRadius+++class MaturityTier(IntEnum):+ L0_OBSERVE = 0+ L1_NOTIFY = 1+ L2_CONTAIN = 2+ L3_REMEDIATE = 3+ L4_AUTOMATE = 4++ @property+ def label(self) -> str:+ return {+ 0: "L0-Observe",+ 1: "L1-Notify",+ 2: "L2-Contain",+ 3: "L3-Remediate",+ 4: "L4-Automate",+ }[int(self)]+++# Which blast-radius levels are allowed to auto-execute at each tier.+_AUTO_ALLOWED_AT_TIER: dict[MaturityTier, set[BlastRadius]] = {+ MaturityTier.L0_OBSERVE: set(),+ MaturityTier.L1_NOTIFY: {BlastRadius.MINIMAL},+ MaturityTier.L2_CONTAIN: {BlastRadius.MINIMAL, BlastRadius.LOW},+ MaturityTier.L3_REMEDIATE: {BlastRadius.MINIMAL, BlastRadius.LOW, BlastRadius.MEDIUM},+ MaturityTier.L4_AUTOMATE: {+ BlastRadius.MINIMAL,+ BlastRadius.LOW,+ BlastRadius.MEDIUM,+ BlastRadius.HIGH,+ },+}+++@dataclass+class GateDecision:+ """Result of a maturity gate evaluation."""++ action_id: str+ action_type: str+ blast_radius: str+ maturity_tier: int+ decision: str # 'auto' | 'queued_approval' | 'blocked'+ rationale: str = ""+ overrides_applied: list[str] = field(default_factory=list)+++@dataclass+class TenantMaturityConfig:+ """Maturity configuration for a single tenant."""++ tenant_id: str+ maturity_tier: int = 0+ action_overrides: dict[str, Any] = field(default_factory=dict)+ whitelist: list[dict[str, Any]] = field(default_factory=list)++ def tier(self) -> MaturityTier:+ return MaturityTier(self.maturity_tier)+++def evaluate_gate(request: ActionRequest, config: TenantMaturityConfig) -> GateDecision:+ """+ Evaluate whether *request* may auto-execute given *config*.++ Returns a :class:`GateDecision` with decision 'auto', 'queued_approval',+ or 'blocked'.+ """+ blast = ACTION_BLAST_RADIUS.get(request.action_type, BlastRadius.HIGH)+ tier = config.tier()+ overrides_applied: list[str] = []++ # ------------------------------------------------------------------+ # 1. Check per-action-type override in tenant config+ # ------------------------------------------------------------------+ action_key = request.action_type.value if hasattr(request.action_type, "value") else str(request.action_type)+ override = config.action_overrides.get(action_key, {})++ if override.get("block"):+ return GateDecision(+ action_id=str(request.id),+ action_type=action_key,+ blast_radius=blast.value,+ maturity_tier=int(tier),+ decision="blocked",+ rationale=f"Action type '{action_key}' is blocked by tenant override.",+ overrides_applied=["block_override"],+ )++ if override.get("force_auto"):+ overrides_applied.append("force_auto_override")+ return GateDecision(+ action_id=str(request.id),+ action_type=action_key,+ blast_radius=blast.value,+ maturity_tier=int(tier),+ decision="auto",+ rationale=f"Action type '{action_key}' is force-auto by tenant override.",+ overrides_applied=overrides_applied,+ )++ # ------------------------------------------------------------------+ # 2. Check whitelist (only relevant at L4 for HIGH blast-radius)+ # ------------------------------------------------------------------+ if blast == BlastRadius.HIGH and tier == MaturityTier.L4_AUTOMATE:+ whitelist_match = _check_whitelist(request, config.whitelist)+ if whitelist_match is None:+ return GateDecision(+ action_id=str(request.id),+ action_type=action_key,+ blast_radius=blast.value,+ maturity_tier=int(tier),+ decision="queued_approval",+ rationale=(+ f"HIGH blast-radius action at L4 requires whitelist entry. "+ f"No matching whitelist entry found for '{action_key}'."+ ),+ )+ overrides_applied.append(f"whitelist:{whitelist_match}")++ # ------------------------------------------------------------------+ # 3. Standard tier gate+ # ------------------------------------------------------------------+ allowed_radii = _AUTO_ALLOWED_AT_TIER.get(tier, set())+ if blast in allowed_radii:+ return GateDecision(+ action_id=str(request.id),+ action_type=action_key,+ blast_radius=blast.value,+ maturity_tier=int(tier),+ decision="auto",+ rationale=f"Tier {tier.label}: '{blast.value}' blast-radius auto-execution permitted.",+ overrides_applied=overrides_applied,+ )++ return GateDecision(+ action_id=str(request.id),+ action_type=action_key,+ blast_radius=blast.value,+ maturity_tier=int(tier),+ decision="queued_approval",+ rationale=(+ f"Tier {tier.label}: '{blast.value}' blast-radius requires human approval."+ ),+ overrides_applied=overrides_applied,+ )+++def _check_whitelist(+ request: ActionRequest, whitelist: list[dict[str, Any]]+) -> str | None:+ """+ Return the whitelist entry id/key if the action matches a whitelist entry,+ or None if no match.+ """+ action_key = request.action_type.value if hasattr(request.action_type, "value") else str(request.action_type)+ for entry in whitelist:+ if entry.get("action_type") != action_key:+ continue+ constraints: dict[str, Any] = entry.get("constraints", {})+ # Simple prefix constraint check on request.target+ if target_prefix := constraints.get("target_prefix"):+ if not request.target.startswith(target_prefix):+ continue+ return entry.get("id", "whitelist_entry")+ return Nonediff --git a/services/api/app/api/v1/endpoints/assets.py b/services/api/app/api/v1/endpoints/assets.pynew file mode 100644index 000000000..17463a9cf--- /dev/null+++ b/services/api/app/api/v1/endpoints/assets.py@@ -0,0 +1,219 @@+"""Asset inventory and vulnerability management endpoints."""++from __future__ import annotations++import uuid+from typing import Any++from fastapi import APIRouter, Depends, HTTPException, Query, status+from pydantic import BaseModel, Field+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.v1.endpoints.auth import get_current_user+from app.db.database import get_db+from app.models.asset import AlertAssetCorrelation, Asset, AssetVulnerability+from app.models.tenant import User++router = APIRouter(prefix="/assets", tags=["assets"])+++# ---------------------------------------------------------------------------+# Pydantic schemas+# ---------------------------------------------------------------------------+++class AssetCreate(BaseModel):+ asset_type: str = "host"+ name: str+ fqdn: str | None = None+ ip_addresses: list[str] | None = None+ cloud_provider: str | None = None+ cloud_region: str | None = None+ cloud_account: str | None = None+ os: str | None = None+ os_version: str | None = None+ criticality: str = "medium"+ tags: list[str] | None = None+ owner_email: str | None = None+ metadata: dict[str, Any] = Field(default_factory=dict)+++class AssetUpdate(AssetCreate):+ pass+++class AssetOut(AssetCreate):+ id: uuid.UUID+ tenant_id: uuid.UUID+ created_at: str+ updated_at: str+ last_seen: str+ first_seen: str++ class Config:+ from_attributes = True+++class VulnerabilityCreate(BaseModel):+ asset_id: uuid.UUID+ cve_id: str | None = None+ title: str+ description: str | None = None+ severity: str = "medium"+ cvss_score: float | None = None+ cvss_vector: str | None = None+ epss_score: float | None = None+ is_exploited: bool = False+ source: str+ external_id: str | None = None+ metadata: dict[str, Any] = Field(default_factory=dict)+++class VulnerabilityOut(VulnerabilityCreate):+ id: uuid.UUID+ tenant_id: uuid.UUID+ first_found: str+ last_found: str+ remediated_at: str | None++ class Config:+ from_attributes = True+++# ---------------------------------------------------------------------------+# Asset CRUD+# ---------------------------------------------------------------------------++[email protected]("", response_model=list[AssetOut])+async def list_assets(+ asset_type: str | None = Query(None),+ criticality: str | None = Query(None),+ limit: int = Query(50, le=500),+ offset: int = Query(0, ge=0),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[Asset]:+ q = select(Asset).where(Asset.tenant_id == current_user.tenant_id)+ if asset_type:+ q = q.where(Asset.asset_type == asset_type)+ if criticality:+ q = q.where(Asset.criticality == criticality)+ q = q.order_by(Asset.last_seen.desc()).offset(offset).limit(limit)+ result = await db.execute(q)+ return list(result.scalars().all())++[email protected]("", response_model=AssetOut, status_code=status.HTTP_201_CREATED)+async def create_asset(+ body: AssetCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> Asset:+ asset = Asset(**body.model_dump(), tenant_id=current_user.tenant_id)+ db.add(asset)+ await db.commit()+ await db.refresh(asset)+ return asset++[email protected]("/{asset_id}", response_model=AssetOut)+async def get_asset(+ asset_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> Asset:+ asset = await db.get(Asset, asset_id)+ if not asset or asset.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Asset not found")+ return asset++[email protected]("/{asset_id}", response_model=AssetOut)+async def update_asset(+ asset_id: uuid.UUID,+ body: AssetUpdate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> Asset:+ asset = await db.get(Asset, asset_id)+ if not asset or asset.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Asset not found")+ for k, v in body.model_dump(exclude_none=True).items():+ setattr(asset, k, v)+ await db.commit()+ await db.refresh(asset)+ return asset++[email protected]("/{asset_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_asset(+ asset_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> None:+ asset = await db.get(Asset, asset_id)+ if not asset or asset.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Asset not found")+ await db.delete(asset)+ await db.commit()+++# ---------------------------------------------------------------------------+# Vulnerability CRUD+# ---------------------------------------------------------------------------++[email protected]("/vulnerabilities", response_model=list[VulnerabilityOut])+async def list_vulnerabilities(+ severity: str | None = Query(None),+ is_exploited: bool | None = Query(None),+ limit: int = Query(50, le=500),+ offset: int = Query(0, ge=0),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[AssetVulnerability]:+ q = select(AssetVulnerability).where(AssetVulnerability.tenant_id == current_user.tenant_id)+ if severity:+ q = q.where(AssetVulnerability.severity == severity)+ if is_exploited is not None:+ q = q.where(AssetVulnerability.is_exploited == is_exploited)+ q = q.order_by(AssetVulnerability.last_found.desc()).offset(offset).limit(limit)+ result = await db.execute(q)+ return list(result.scalars().all())++[email protected]("/vulnerabilities", response_model=VulnerabilityOut, status_code=status.HTTP_201_CREATED)+async def create_vulnerability(+ body: VulnerabilityCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> AssetVulnerability:+ # ensure asset belongs to this tenant+ asset = await db.get(Asset, body.asset_id)+ if not asset or asset.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Asset not found")+ vuln = AssetVulnerability(**body.model_dump(), tenant_id=current_user.tenant_id)+ db.add(vuln)+ await db.commit()+ await db.refresh(vuln)+ return vuln++[email protected]("/{asset_id}/vulnerabilities", response_model=list[VulnerabilityOut])+async def list_asset_vulnerabilities(+ asset_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[AssetVulnerability]:+ asset = await db.get(Asset, asset_id)+ if not asset or asset.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Asset not found")+ q = (+ select(AssetVulnerability)+ .where(AssetVulnerability.asset_id == asset_id)+ .order_by(AssetVulnerability.severity, AssetVulnerability.last_found.desc())+ )+ result = await db.execute(q)+ return list(result.scalars().all())diff --git a/services/api/app/api/v1/endpoints/identity_graph.py b/services/api/app/api/v1/endpoints/identity_graph.pynew file mode 100644index 000000000..7318d07e7--- /dev/null+++ b/services/api/app/api/v1/endpoints/identity_graph.py@@ -0,0 +1,218 @@+"""Identity-centric correlation graph endpoints."""++from __future__ import annotations++import uuid+from datetime import datetime+from typing import Any++from fastapi import APIRouter, Depends, HTTPException, Query, status+from pydantic import BaseModel, Field+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.v1.endpoints.auth import get_current_user+from app.db.database import get_db+from app.models.identity_graph import AlertIdentityLink, IdentityEdge, IdentityNode+from app.models.tenant import User++router = APIRouter(prefix="/identity-graph", tags=["identity-graph"])+++# ---------------------------------------------------------------------------+# Pydantic schemas+# ---------------------------------------------------------------------------+++class NodeCreate(BaseModel):+ node_type: str+ external_id: str+ display_name: str | None = None+ source_system: str+ risk_score: float = 0.0+ privilege_tier: int = 0+ last_activity: datetime | None = None+ attributes: dict[str, Any] = Field(default_factory=dict)+++class NodeOut(NodeCreate):+ id: uuid.UUID+ tenant_id: uuid.UUID+ is_active: bool+ created_at: str+ updated_at: str++ class Config:+ from_attributes = True+++class EdgeCreate(BaseModel):+ source_id: uuid.UUID+ target_id: uuid.UUID+ edge_type: str+ weight: float = 1.0+ valid_until: datetime | None = None+ evidence: dict[str, Any] = Field(default_factory=dict)+++class EdgeOut(EdgeCreate):+ id: uuid.UUID+ tenant_id: uuid.UUID+ valid_from: str+ created_at: str++ class Config:+ from_attributes = True+++class AlertLinkCreate(BaseModel):+ alert_id: uuid.UUID+ node_id: uuid.UUID+ link_reason: str+ confidence: float = 1.0+++class AlertLinkOut(AlertLinkCreate):+ id: uuid.UUID+ tenant_id: uuid.UUID+ created_at: str++ class Config:+ from_attributes = True+++# ---------------------------------------------------------------------------+# Node endpoints+# ---------------------------------------------------------------------------++[email protected]("/nodes", response_model=list[NodeOut])+async def list_nodes(+ node_type: str | None = Query(None),+ source_system: str | None = Query(None),+ min_risk: float | None = Query(None),+ limit: int = Query(50, le=500),+ offset: int = Query(0, ge=0),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[IdentityNode]:+ q = select(IdentityNode).where(IdentityNode.tenant_id == current_user.tenant_id)+ if node_type:+ q = q.where(IdentityNode.node_type == node_type)+ if source_system:+ q = q.where(IdentityNode.source_system == source_system)+ if min_risk is not None:+ q = q.where(IdentityNode.risk_score >= min_risk)+ q = q.order_by(IdentityNode.risk_score.desc()).offset(offset).limit(limit)+ result = await db.execute(q)+ return list(result.scalars().all())++[email protected]("/nodes", response_model=NodeOut, status_code=status.HTTP_201_CREATED)+async def create_node(+ body: NodeCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> IdentityNode:+ node = IdentityNode(**body.model_dump(), tenant_id=current_user.tenant_id)+ db.add(node)+ await db.commit()+ await db.refresh(node)+ return node++[email protected]("/nodes/{node_id}", response_model=NodeOut)+async def get_node(+ node_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> IdentityNode:+ node = await db.get(IdentityNode, node_id)+ if not node or node.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Node not found")+ return node++[email protected]("/nodes/{node_id}/edges", response_model=list[EdgeOut])+async def get_node_edges(+ node_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[IdentityEdge]:+ node = await db.get(IdentityNode, node_id)+ if not node or node.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Node not found")+ result = await db.execute(+ select(IdentityEdge).where(+ IdentityEdge.tenant_id == current_user.tenant_id,+ (IdentityEdge.source_id == node_id) | (IdentityEdge.target_id == node_id),+ )+ )+ return list(result.scalars().all())+++# ---------------------------------------------------------------------------+# Edge endpoints+# ---------------------------------------------------------------------------++[email protected]("/edges", response_model=list[EdgeOut])+async def list_edges(+ edge_type: str | None = Query(None),+ limit: int = Query(100, le=1000),+ offset: int = Query(0, ge=0),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[IdentityEdge]:+ q = select(IdentityEdge).where(IdentityEdge.tenant_id == current_user.tenant_id)+ if edge_type:+ q = q.where(IdentityEdge.edge_type == edge_type)+ q = q.order_by(IdentityEdge.created_at.desc()).offset(offset).limit(limit)+ result = await db.execute(q)+ return list(result.scalars().all())++[email protected]("/edges", response_model=EdgeOut, status_code=status.HTTP_201_CREATED)+async def create_edge(+ body: EdgeCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> IdentityEdge:+ edge = IdentityEdge(**body.model_dump(), tenant_id=current_user.tenant_id)+ db.add(edge)+ await db.commit()+ await db.refresh(edge)+ return edge+++# ---------------------------------------------------------------------------+# Alert-identity links+# ---------------------------------------------------------------------------++[email protected]("/alert-links", response_model=AlertLinkOut, status_code=status.HTTP_201_CREATED)+async def link_alert_to_identity(+ body: AlertLinkCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> AlertIdentityLink:+ link = AlertIdentityLink(**body.model_dump(), tenant_id=current_user.tenant_id)+ db.add(link)+ await db.commit()+ await db.refresh(link)+ return link++[email protected]("/alert-links/{alert_id}", response_model=list[AlertLinkOut])+async def get_alert_identity_links(+ alert_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[AlertIdentityLink]:+ result = await db.execute(+ select(AlertIdentityLink).where(+ AlertIdentityLink.tenant_id == current_user.tenant_id,+ AlertIdentityLink.alert_id == alert_id,+ )+ )+ return list(result.scalars().all())diff --git a/services/api/app/api/v1/endpoints/insider_threat.py b/services/api/app/api/v1/endpoints/insider_threat.pynew file mode 100644index 000000000..75ef061da--- /dev/null+++ b/services/api/app/api/v1/endpoints/insider_threat.py@@ -0,0 +1,237 @@+"""Insider-threat module endpoints."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime+from typing import Any++from fastapi import APIRouter, Depends, HTTPException, Query, status+from pydantic import BaseModel, Field+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.v1.endpoints.auth import get_current_user+from app.db.database import get_db+from app.models.insider_threat import InsiderIndicator, InsiderPeerGroup, UserRiskProfile+from app.models.tenant import User++router = APIRouter(prefix="/insider-threat", tags=["insider-threat"])+++# ---------------------------------------------------------------------------+# Pydantic schemas+# ---------------------------------------------------------------------------+++class RiskProfileOut(BaseModel):+ id: uuid.UUID+ tenant_id: uuid.UUID+ user_id: uuid.UUID | None+ external_user_ref: str | None+ risk_score: float+ risk_tier: str+ failed_auth_24h: int+ off_hours_events_7d: int+ data_staging_score: float+ peer_anomaly_score: float+ privilege_delta: int+ is_watchlisted: bool+ watchlist_reason: str | None+ last_evaluated_at: str+ updated_at: str++ class Config:+ from_attributes = True+++class WatchlistUpdate(BaseModel):+ is_watchlisted: bool+ watchlist_reason: str | None = None+++class IndicatorOut(BaseModel):+ id: uuid.UUID+ tenant_id: uuid.UUID+ profile_id: uuid.UUID+ indicator_type: str+ severity: str+ description: str+ source_alert_id: uuid.UUID | None+ evidence: dict[str, Any]+ occurred_at: str+ acknowledged_at: str | None++ class Config:+ from_attributes = True+++class IndicatorCreate(BaseModel):+ profile_id: uuid.UUID+ indicator_type: str+ severity: str = "medium"+ description: str+ source_alert_id: uuid.UUID | None = None+ evidence: dict[str, Any] = Field(default_factory=dict)+ occurred_at: datetime | None = None+++class PeerGroupCreate(BaseModel):+ name: str+ description: str | None = None+ criteria: dict[str, Any] = Field(default_factory=dict)+++class PeerGroupOut(PeerGroupCreate):+ id: uuid.UUID+ tenant_id: uuid.UUID+ created_at: str++ class Config:+ from_attributes = True+++# ---------------------------------------------------------------------------+# Risk profiles+# ---------------------------------------------------------------------------++[email protected]("/profiles", response_model=list[RiskProfileOut])+async def list_profiles(+ risk_tier: str | None = Query(None),+ watchlisted_only: bool = Query(False),+ limit: int = Query(50, le=500),+ offset: int = Query(0, ge=0),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[UserRiskProfile]:+ q = select(UserRiskProfile).where(UserRiskProfile.tenant_id == current_user.tenant_id)+ if risk_tier:+ q = q.where(UserRiskProfile.risk_tier == risk_tier)+ if watchlisted_only:+ q = q.where(UserRiskProfile.is_watchlisted.is_(True))+ q = q.order_by(UserRiskProfile.risk_score.desc()).offset(offset).limit(limit)+ result = await db.execute(q)+ return list(result.scalars().all())++[email protected]("/profiles/{profile_id}", response_model=RiskProfileOut)+async def get_profile(+ profile_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> UserRiskProfile:+ profile = await db.get(UserRiskProfile, profile_id)+ if not profile or profile.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Profile not found")+ return profile++[email protected]("/profiles/{profile_id}/watchlist", response_model=RiskProfileOut)+async def update_watchlist(+ profile_id: uuid.UUID,+ body: WatchlistUpdate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> UserRiskProfile:+ profile = await db.get(UserRiskProfile, profile_id)+ if not profile or profile.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Profile not found")+ profile.is_watchlisted = body.is_watchlisted # type: ignore[assignment]+ profile.watchlist_reason = body.watchlist_reason # type: ignore[assignment]+ if body.is_watchlisted:+ profile.watchlisted_at = datetime.now(UTC) # type: ignore[assignment]+ profile.watchlisted_by = current_user.id # type: ignore[assignment]+ await db.commit()+ await db.refresh(profile)+ return profile+++# ---------------------------------------------------------------------------+# Indicators+# ---------------------------------------------------------------------------++[email protected]("/indicators", response_model=list[IndicatorOut])+async def list_indicators(+ severity: str | None = Query(None),+ indicator_type: str | None = Query(None),+ limit: int = Query(50, le=500),+ offset: int = Query(0, ge=0),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[InsiderIndicator]:+ q = select(InsiderIndicator).where(InsiderIndicator.tenant_id == current_user.tenant_id)+ if severity:+ q = q.where(InsiderIndicator.severity == severity)+ if indicator_type:+ q = q.where(InsiderIndicator.indicator_type == indicator_type)+ q = q.order_by(InsiderIndicator.occurred_at.desc()).offset(offset).limit(limit)+ result = await db.execute(q)+ return list(result.scalars().all())++[email protected]("/indicators", response_model=IndicatorOut, status_code=status.HTTP_201_CREATED)+async def create_indicator(+ body: IndicatorCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> InsiderIndicator:+ profile = await db.get(UserRiskProfile, body.profile_id)+ if not profile or profile.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Profile not found")+ data = body.model_dump()+ if data.get("occurred_at") is None:+ data["occurred_at"] = datetime.now(UTC)+ indicator = InsiderIndicator(**data, tenant_id=current_user.tenant_id)+ db.add(indicator)+ await db.commit()+ await db.refresh(indicator)+ return indicator++[email protected]("/indicators/{indicator_id}/acknowledge", response_model=IndicatorOut)+async def acknowledge_indicator(+ indicator_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> InsiderIndicator:+ indicator = await db.get(InsiderIndicator, indicator_id)+ if not indicator or indicator.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Indicator not found")+ indicator.acknowledged_by = current_user.id # type: ignore[assignment]+ indicator.acknowledged_at = datetime.now(UTC) # type: ignore[assignment]+ await db.commit()+ await db.refresh(indicator)+ return indicator+++# ---------------------------------------------------------------------------+# Peer groups+# ---------------------------------------------------------------------------++[email protected]("/peer-groups", response_model=list[PeerGroupOut])+async def list_peer_groups(+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[InsiderPeerGroup]:+ result = await db.execute(+ select(InsiderPeerGroup)+ .where(InsiderPeerGroup.tenant_id == current_user.tenant_id)+ .order_by(InsiderPeerGroup.name)+ )+ return list(result.scalars().all())++[email protected]("/peer-groups", response_model=PeerGroupOut, status_code=status.HTTP_201_CREATED)+async def create_peer_group(+ body: PeerGroupCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> InsiderPeerGroup:+ group = InsiderPeerGroup(**body.model_dump(), tenant_id=current_user.tenant_id)+ db.add(group)+ await db.commit()+ await db.refresh(group)+ return groupdiff --git a/services/api/app/api/v1/endpoints/mssp.py b/services/api/app/api/v1/endpoints/mssp.pynew file mode 100644index 000000000..2eda9fd80--- /dev/null+++ b/services/api/app/api/v1/endpoints/mssp.py@@ -0,0 +1,250 @@+"""MSSP parent-tenant console endpoints."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime+from typing import Any++from fastapi import APIRouter, Depends, HTTPException, Query, status+from pydantic import BaseModel+from sqlalchemy import select, update+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.v1.endpoints.auth import get_current_user+from app.db.database import get_db+from app.models.mssp import MSSPDelegation, MSSPTenantMetrics, MSSPTenantNote+from app.models.tenant import Tenant, User++router = APIRouter(prefix="/mssp", tags=["mssp"])+++# ---------------------------------------------------------------------------+# Pydantic schemas+# ---------------------------------------------------------------------------+++class ChildTenantOut(BaseModel):+ id: uuid.UUID+ name: str+ mssp_role: str+ created_at: str++ class Config:+ from_attributes = True+++class TenantNoteCreate(BaseModel):+ child_id: uuid.UUID+ body: str+++class TenantNoteOut(TenantNoteCreate):+ id: uuid.UUID+ parent_id: uuid.UUID+ author_id: uuid.UUID | None+ created_at: str++ class Config:+ from_attributes = True+++class DelegationCreate(BaseModel):+ child_tenant_id: uuid.UUID+ granted_role: str = "soc_analyst"+ expires_at: datetime | None = None+++class DelegationOut(DelegationCreate):+ id: uuid.UUID+ parent_tenant_id: uuid.UUID+ granted_by_user: uuid.UUID | None+ revoked_at: datetime | None+ created_at: str++ class Config:+ from_attributes = True+++class MetricsOut(BaseModel):+ tenant_id: uuid.UUID+ snapshot_at: str+ open_alerts: int+ critical_alerts: int+ open_cases: int+ mttr_minutes: float | None+ sla_breaches: int+ connector_count: int+ health_score: float | None++ class Config:+ from_attributes = True+++# ---------------------------------------------------------------------------+# Child-tenant management+# ---------------------------------------------------------------------------++[email protected]("/children", response_model=list[ChildTenantOut])+async def list_child_tenants(+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[Tenant]:+ """Return all child tenants of the current parent tenant."""+ result = await db.execute(+ select(Tenant).where(Tenant.parent_tenant_id == current_user.tenant_id)+ )+ return list(result.scalars().all())++[email protected]("/children/{child_id}/onboard", status_code=status.HTTP_200_OK)+async def onboard_child_tenant(+ child_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> dict[str, str]:+ """Link an existing tenant as a child of the current MSSP tenant."""+ child = await db.get(Tenant, child_id)+ if not child:+ raise HTTPException(status_code=404, detail="Tenant not found")+ if child.parent_tenant_id and child.parent_tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=409, detail="Tenant already has a parent")+ child.parent_tenant_id = current_user.tenant_id # type: ignore[assignment]+ child.mssp_role = "child" # type: ignore[assignment]+ parent = await db.get(Tenant, current_user.tenant_id)+ if parent:+ parent.mssp_role = "parent" # type: ignore[assignment]+ await db.commit()+ return {"status": "ok", "child_id": str(child_id)}+++# ---------------------------------------------------------------------------+# Cross-tenant notes+# ---------------------------------------------------------------------------++[email protected]("/notes", response_model=list[TenantNoteOut])+async def list_notes(+ child_id: uuid.UUID | None = Query(None),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[MSSPTenantNote]:+ q = select(MSSPTenantNote).where(MSSPTenantNote.parent_id == current_user.tenant_id)+ if child_id:+ q = q.where(MSSPTenantNote.child_id == child_id)+ q = q.order_by(MSSPTenantNote.created_at.desc())+ result = await db.execute(q)+ return list(result.scalars().all())++[email protected]("/notes", response_model=TenantNoteOut, status_code=status.HTTP_201_CREATED)+async def create_note(+ body: TenantNoteCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> MSSPTenantNote:+ note = MSSPTenantNote(+ parent_id=current_user.tenant_id,+ child_id=body.child_id,+ body=body.body,+ author_id=current_user.id,+ )+ db.add(note)+ await db.commit()+ await db.refresh(note)+ return note+++# ---------------------------------------------------------------------------+# Cross-tenant delegations+# ---------------------------------------------------------------------------++[email protected]("/delegations", response_model=list[DelegationOut])+async def list_delegations(+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[MSSPDelegation]:+ result = await db.execute(+ select(MSSPDelegation)+ .where(+ MSSPDelegation.parent_tenant_id == current_user.tenant_id,+ MSSPDelegation.revoked_at.is_(None),+ )+ .order_by(MSSPDelegation.created_at.desc())+ )+ return list(result.scalars().all())++[email protected]("/delegations", response_model=DelegationOut, status_code=status.HTTP_201_CREATED)+async def create_delegation(+ body: DelegationCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> MSSPDelegation:+ delegation = MSSPDelegation(+ parent_tenant_id=current_user.tenant_id,+ child_tenant_id=body.child_tenant_id,+ granted_role=body.granted_role,+ granted_by_user=current_user.id,+ expires_at=body.expires_at,+ )+ db.add(delegation)+ await db.commit()+ await db.refresh(delegation)+ return delegation++[email protected]("/delegations/{delegation_id}", status_code=status.HTTP_204_NO_CONTENT)+async def revoke_delegation(+ delegation_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> None:+ delegation = await db.get(MSSPDelegation, delegation_id)+ if not delegation or delegation.parent_tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Delegation not found")+ delegation.revoked_at = datetime.now(UTC) # type: ignore[assignment]+ await db.commit()+++# ---------------------------------------------------------------------------+# Tenant rollup metrics+# ---------------------------------------------------------------------------++[email protected]("/metrics", response_model=list[MetricsOut])+async def list_metrics(+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[MSSPTenantMetrics]:+ """Return the latest metrics snapshot for every child tenant."""+ # Get child tenant ids+ children_result = await db.execute(+ select(Tenant.id).where(Tenant.parent_tenant_id == current_user.tenant_id)+ )+ child_ids = [r for r in children_result.scalars().all()]+ if not child_ids:+ return []++ # Subquery: most recent snapshot per tenant+ subq = (+ select(+ MSSPTenantMetrics.tenant_id,+ MSSPTenantMetrics.snapshot_at,+ )+ .where(MSSPTenantMetrics.tenant_id.in_(child_ids))+ .order_by(MSSPTenantMetrics.tenant_id, MSSPTenantMetrics.snapshot_at.desc())+ .distinct(MSSPTenantMetrics.tenant_id)+ .subquery()+ )++ result = await db.execute(+ select(MSSPTenantMetrics).join(+ subq,+ (MSSPTenantMetrics.tenant_id == subq.c.tenant_id)+ & (MSSPTenantMetrics.snapshot_at == subq.c.snapshot_at),+ )+ )+ return list(result.scalars().all())diff --git a/services/api/app/api/v1/endpoints/posture.py b/services/api/app/api/v1/endpoints/posture.pynew file mode 100644index 000000000..b4be08c4e--- /dev/null+++ b/services/api/app/api/v1/endpoints/posture.py@@ -0,0 +1,222 @@+"""Cloud Security Posture Management (CSPM/KSPM) endpoints."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime+from typing import Any++from fastapi import APIRouter, Depends, HTTPException, Query, status+from pydantic import BaseModel, Field+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.v1.endpoints.auth import get_current_user+from app.db.database import get_db+from app.models.posture import PostureFinding, PostureScanRun+from app.models.tenant import User++router = APIRouter(prefix="/posture", tags=["posture"])+++# ---------------------------------------------------------------------------+# Pydantic schemas+# ---------------------------------------------------------------------------+++class FindingCreate(BaseModel):+ cloud_provider: str+ cloud_account: str | None = None+ cloud_region: str | None = None+ resource_type: str+ resource_id: str+ resource_name: str | None = None+ rule_id: str+ rule_title: str+ description: str | None = None+ severity: str = "medium"+ frameworks: list[str] | None = None+ control_ids: list[str] | None = None+ evidence: dict[str, Any] = Field(default_factory=dict)+ remediation_guide: str | None = None+++class FindingOut(FindingCreate):+ id: uuid.UUID+ tenant_id: uuid.UUID+ status: str+ auto_remediated: bool+ first_detected_at: str+ last_evaluated_at: str+ resolved_at: str | None = None++ class Config:+ from_attributes = True+++class ScanRunOut(BaseModel):+ id: uuid.UUID+ tenant_id: uuid.UUID+ cloud_provider: str+ cloud_account: str | None+ started_at: str+ completed_at: str | None+ status: str+ findings_total: int+ findings_new: int+ findings_closed: int+ error_message: str | None++ class Config:+ from_attributes = True+++class SuppressRequest(BaseModel):+ reason: str+++class PostureSummary(BaseModel):+ total: int+ critical: int+ high: int+ medium: int+ low: int+ open: int+ resolved: int+ suppressed: int+++# ---------------------------------------------------------------------------+# Findings endpoints+# ---------------------------------------------------------------------------++[email protected]("/findings", response_model=list[FindingOut])+async def list_findings(+ cloud_provider: str | None = Query(None),+ severity: str | None = Query(None),+ status_filter: str | None = Query(None, alias="status"),+ rule_id: str | None = Query(None),+ limit: int = Query(50, le=500),+ offset: int = Query(0, ge=0),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[PostureFinding]:+ q = select(PostureFinding).where(PostureFinding.tenant_id == current_user.tenant_id)+ if cloud_provider:+ q = q.where(PostureFinding.cloud_provider == cloud_provider)+ if severity:+ q = q.where(PostureFinding.severity == severity)+ if status_filter:+ q = q.where(PostureFinding.status == status_filter)+ if rule_id:+ q = q.where(PostureFinding.rule_id == rule_id)+ q = q.order_by(PostureFinding.last_evaluated_at.desc()).offset(offset).limit(limit)+ result = await db.execute(q)+ return list(result.scalars().all())++[email protected]("/findings", response_model=FindingOut, status_code=status.HTTP_201_CREATED)+async def ingest_finding(+ body: FindingCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> PostureFinding:+ finding = PostureFinding(**body.model_dump(), tenant_id=current_user.tenant_id)+ db.add(finding)+ await db.commit()+ await db.refresh(finding)+ return finding++[email protected]("/findings/{finding_id}", response_model=FindingOut)+async def get_finding(+ finding_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> PostureFinding:+ f = await db.get(PostureFinding, finding_id)+ if not f or f.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Finding not found")+ return f++[email protected]("/findings/{finding_id}/suppress", response_model=FindingOut)+async def suppress_finding(+ finding_id: uuid.UUID,+ body: SuppressRequest,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> PostureFinding:+ f = await db.get(PostureFinding, finding_id)+ if not f or f.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Finding not found")+ f.status = "suppressed" # type: ignore[assignment]+ f.suppressed_at = datetime.now(UTC) # type: ignore[assignment]+ f.suppressed_by = current_user.id # type: ignore[assignment]+ f.suppress_reason = body.reason # type: ignore[assignment]+ await db.commit()+ await db.refresh(f)+ return f++[email protected]("/findings/{finding_id}/resolve", response_model=FindingOut)+async def resolve_finding(+ finding_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> PostureFinding:+ f = await db.get(PostureFinding, finding_id)+ if not f or f.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Finding not found")+ f.status = "resolved" # type: ignore[assignment]+ f.resolved_at = datetime.now(UTC) # type: ignore[assignment]+ await db.commit()+ await db.refresh(f)+ return f++[email protected]("/summary", response_model=PostureSummary)+async def get_summary(+ cloud_provider: str | None = Query(None),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> PostureSummary:+ q = select(PostureFinding).where(PostureFinding.tenant_id == current_user.tenant_id)+ if cloud_provider:+ q = q.where(PostureFinding.cloud_provider == cloud_provider)+ result = await db.execute(q)+ findings = list(result.scalars().all())++ return PostureSummary(+ total=len(findings),+ critical=sum(1 for f in findings if f.severity == "critical"),+ high=sum(1 for f in findings if f.severity == "high"),+ medium=sum(1 for f in findings if f.severity == "medium"),+ low=sum(1 for f in findings if f.severity == "low"),+ open=sum(1 for f in findings if f.status == "open"),+ resolved=sum(1 for f in findings if f.status == "resolved"),+ suppressed=sum(1 for f in findings if f.status == "suppressed"),+ )+++# ---------------------------------------------------------------------------+# Scan runs+# ---------------------------------------------------------------------------++[email protected]("/scans", response_model=list[ScanRunOut])+async def list_scans(+ limit: int = Query(20, le=100),+ offset: int = Query(0, ge=0),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[PostureScanRun]:+ result = await db.execute(+ select(PostureScanRun)+ .where(PostureScanRun.tenant_id == current_user.tenant_id)+ .order_by(PostureScanRun.started_at.desc())+ .offset(offset)+ .limit(limit)+ )+ return list(result.scalars().all())diff --git a/services/api/app/api/v1/endpoints/remediation.py b/services/api/app/api/v1/endpoints/remediation.pynew file mode 100644index 000000000..f23d58b20--- /dev/null+++ b/services/api/app/api/v1/endpoints/remediation.py@@ -0,0 +1,189 @@+"""L0–L4 auto-remediation maturity tier endpoints."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime+from typing import Any++from fastapi import APIRouter, Depends, HTTPException, Query, status+from pydantic import BaseModel, Field+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.v1.endpoints.auth import get_current_user+from app.db.database import get_db+from app.models.remediation import RemediationGateLog, RemediationMaturity, RemediationWhitelist+from app.models.tenant import User++router = APIRouter(prefix="/remediation", tags=["remediation"])+++# ---------------------------------------------------------------------------+# Pydantic schemas+# ---------------------------------------------------------------------------+++class MaturityConfig(BaseModel):+ maturity_tier: int = Field(..., ge=0, le=4)+ action_overrides: dict[str, Any] = Field(default_factory=dict)+++class MaturityOut(BaseModel):+ id: uuid.UUID+ tenant_id: uuid.UUID+ maturity_tier: int+ action_overrides: dict[str, Any]+ changed_at: str+ created_at: str++ class Config:+ from_attributes = True+++class GateLogOut(BaseModel):+ id: uuid.UUID+ tenant_id: uuid.UUID+ action_id: uuid.UUID+ action_type: str+ blast_radius: str+ maturity_tier: int+ decision: str+ rationale: str | None+ actor: str+ created_at: str++ class Config:+ from_attributes = True+++class WhitelistCreate(BaseModel):+ action_type: str+ blast_radius: str+ constraints: dict[str, Any] = Field(default_factory=dict)+ expires_at: datetime | None = None+++class WhitelistOut(WhitelistCreate):+ id: uuid.UUID+ tenant_id: uuid.UUID+ approved_by: uuid.UUID | None+ created_at: str++ class Config:+ from_attributes = True+++# ---------------------------------------------------------------------------+# Maturity config endpoints+# ---------------------------------------------------------------------------++[email protected]("/config", response_model=MaturityOut)+async def get_maturity_config(+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> RemediationMaturity:+ result = await db.execute(+ select(RemediationMaturity).where(RemediationMaturity.tenant_id == current_user.tenant_id)+ )+ config = result.scalar_one_or_none()+ if not config:+ config = RemediationMaturity(+ tenant_id=current_user.tenant_id,+ maturity_tier=0,+ )+ db.add(config)+ await db.commit()+ await db.refresh(config)+ return config++[email protected]("/config", response_model=MaturityOut)+async def update_maturity_config(+ body: MaturityConfig,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> RemediationMaturity:+ result = await db.execute(+ select(RemediationMaturity).where(RemediationMaturity.tenant_id == current_user.tenant_id)+ )+ config = result.scalar_one_or_none()+ if not config:+ config = RemediationMaturity(tenant_id=current_user.tenant_id)+ db.add(config)++ config.maturity_tier = body.maturity_tier # type: ignore[assignment]+ config.action_overrides = body.action_overrides # type: ignore[assignment]+ config.changed_by = current_user.id # type: ignore[assignment]+ config.changed_at = datetime.now(UTC) # type: ignore[assignment]+ await db.commit()+ await db.refresh(config)+ return config+++# ---------------------------------------------------------------------------+# Gate log (audit trail)+# ---------------------------------------------------------------------------++[email protected]("/gate-log", response_model=list[GateLogOut])+async def list_gate_log(+ decision: str | None = Query(None),+ limit: int = Query(50, le=500),+ offset: int = Query(0, ge=0),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[RemediationGateLog]:+ q = select(RemediationGateLog).where(RemediationGateLog.tenant_id == current_user.tenant_id)+ if decision:+ q = q.where(RemediationGateLog.decision == decision)+ q = q.order_by(RemediationGateLog.created_at.desc()).offset(offset).limit(limit)+ result = await db.execute(q)+ return list(result.scalars().all())+++# ---------------------------------------------------------------------------+# Whitelist endpoints+# ---------------------------------------------------------------------------++[email protected]("/whitelist", response_model=list[WhitelistOut])+async def list_whitelist(+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[RemediationWhitelist]:+ result = await db.execute(+ select(RemediationWhitelist).where(RemediationWhitelist.tenant_id == current_user.tenant_id)+ )+ return list(result.scalars().all())++[email protected]("/whitelist", response_model=WhitelistOut, status_code=status.HTTP_201_CREATED)+async def add_to_whitelist(+ body: WhitelistCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> RemediationWhitelist:+ entry = RemediationWhitelist(+ **body.model_dump(),+ tenant_id=current_user.tenant_id,+ approved_by=current_user.id,+ )+ db.add(entry)+ await db.commit()+ await db.refresh(entry)+ return entry++[email protected]("/whitelist/{entry_id}", status_code=status.HTTP_204_NO_CONTENT)+async def remove_from_whitelist(+ entry_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> None:+ entry = await db.get(RemediationWhitelist, entry_id)+ if not entry or entry.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Whitelist entry not found")+ await db.delete(entry)+ await db.commit()diff --git a/services/api/app/api/v1/endpoints/reports.py b/services/api/app/api/v1/endpoints/reports.pynew file mode 100644index 000000000..0dac0bdbe--- /dev/null+++ b/services/api/app/api/v1/endpoints/reports.py@@ -0,0 +1,196 @@+"""Auto-generated board / executive report endpoints."""++from __future__ import annotations++import uuid+from datetime import datetime+from typing import Any++from fastapi import APIRouter, Depends, HTTPException, Query, status+from pydantic import BaseModel, Field+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.v1.endpoints.auth import get_current_user+from app.db.database import get_db+from app.models.report import ReportArtefact, ReportTemplate+from app.models.tenant import User++router = APIRouter(prefix="/reports", tags=["reports"])+++# ---------------------------------------------------------------------------+# Pydantic schemas+# ---------------------------------------------------------------------------+++class TemplateCreate(BaseModel):+ name: str+ report_type: str+ cron_schedule: str | None = None+ timezone: str = "UTC"+ sections: list[dict[str, Any]] = Field(default_factory=list)+ recipients: list[str] | None = None+ output_format: str = "pdf"+++class TemplateOut(TemplateCreate):+ id: uuid.UUID+ tenant_id: uuid.UUID+ is_enabled: bool+ last_run_at: str | None = None+ created_at: str+ updated_at: str++ class Config:+ from_attributes = True+++class ArtefactOut(BaseModel):+ id: uuid.UUID+ tenant_id: uuid.UUID+ template_id: uuid.UUID | None+ report_type: str+ title: str+ period_start: str+ period_end: str+ output_format: str+ file_size_bytes: int | None+ delivered_to: list[str] | None+ delivered_at: str | None+ generated_by: str+ status: str+ error_message: str | None+ created_at: str++ class Config:+ from_attributes = True+++class GenerateRequest(BaseModel):+ title: str+ report_type: str = "board_summary"+ period_start: datetime+ period_end: datetime+ output_format: str = "pdf"+ recipients: list[str] | None = None+++# ---------------------------------------------------------------------------+# Template endpoints+# ---------------------------------------------------------------------------++[email protected]("/templates", response_model=list[TemplateOut])+async def list_templates(+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[ReportTemplate]:+ result = await db.execute(+ select(ReportTemplate)+ .where(ReportTemplate.tenant_id == current_user.tenant_id)+ .order_by(ReportTemplate.name)+ )+ return list(result.scalars().all())++[email protected]("/templates", response_model=TemplateOut, status_code=status.HTTP_201_CREATED)+async def create_template(+ body: TemplateCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> ReportTemplate:+ template = ReportTemplate(+ **body.model_dump(),+ tenant_id=current_user.tenant_id,+ created_by=current_user.id,+ )+ db.add(template)+ await db.commit()+ await db.refresh(template)+ return template++[email protected]("/templates/{template_id}", response_model=TemplateOut)+async def get_template(+ template_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> ReportTemplate:+ tmpl = await db.get(ReportTemplate, template_id)+ if not tmpl or tmpl.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Template not found")+ return tmpl++[email protected]("/templates/{template_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_template(+ template_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> None:+ tmpl = await db.get(ReportTemplate, template_id)+ if not tmpl or tmpl.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Template not found")+ await db.delete(tmpl)+ await db.commit()+++# ---------------------------------------------------------------------------+# Artefact endpoints+# ---------------------------------------------------------------------------++[email protected]("/artefacts", response_model=list[ArtefactOut])+async def list_artefacts(+ report_type: str | None = Query(None),+ status_filter: str | None = Query(None, alias="status"),+ limit: int = Query(20, le=100),+ offset: int = Query(0, ge=0),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[ReportArtefact]:+ q = select(ReportArtefact).where(ReportArtefact.tenant_id == current_user.tenant_id)+ if report_type:+ q = q.where(ReportArtefact.report_type == report_type)+ if status_filter:+ q = q.where(ReportArtefact.status == status_filter)+ q = q.order_by(ReportArtefact.created_at.desc()).offset(offset).limit(limit)+ result = await db.execute(q)+ return list(result.scalars().all())++[email protected]("/generate", response_model=ArtefactOut, status_code=status.HTTP_202_ACCEPTED)+async def generate_report(+ body: GenerateRequest,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> ReportArtefact:+ """Enqueue a report generation job. Returns the artefact record immediately with status='pending'."""+ artefact = ReportArtefact(+ tenant_id=current_user.tenant_id,+ report_type=body.report_type,+ title=body.title,+ period_start=body.period_start,+ period_end=body.period_end,+ output_format=body.output_format,+ delivered_to=body.recipients,+ status="pending",+ generated_by=str(current_user.id),+ )+ db.add(artefact)+ await db.commit()+ await db.refresh(artefact)+ return artefact++[email protected]("/artefacts/{artefact_id}", response_model=ArtefactOut)+async def get_artefact(+ artefact_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> ReportArtefact:+ art = await db.get(ReportArtefact, artefact_id)+ if not art or art.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Artefact not found")+ return artdiff --git a/services/api/app/api/v1/endpoints/threat_intel.py b/services/api/app/api/v1/endpoints/threat_intel.pynew file mode 100644index 000000000..b576cdca5--- /dev/null+++ b/services/api/app/api/v1/endpoints/threat_intel.py@@ -0,0 +1,241 @@+"""Internal threat-intel generation endpoints."""++from __future__ import annotations++import uuid+from datetime import datetime+from typing import Any++from fastapi import APIRouter, Depends, HTTPException, Query, status+from pydantic import BaseModel, Field+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.v1.endpoints.auth import get_current_user+from app.db.database import get_db+from app.models.tenant import User+from app.models.threat_intel import ThreatActor, ThreatIntelFeed, ThreatIntelIOC++router = APIRouter(prefix="/threat-intel", tags=["threat-intel"])+++# ---------------------------------------------------------------------------+# Pydantic schemas+# ---------------------------------------------------------------------------+++class IOCCreate(BaseModel):+ ioc_type: str+ value: str+ confidence: int = Field(50, ge=0, le=100)+ severity: str = "medium"+ tlp: str = "amber"+ threat_actor: str | None = None+ campaign: str | None = None+ malware_family: str | None = None+ tags: list[str] | None = None+ source: str = "internal"+ source_ref: str | None = None+ expires_at: datetime | None = None+ linked_alerts: list[uuid.UUID] | None = None+ context: dict[str, Any] = Field(default_factory=dict)+++class IOCOut(IOCCreate):+ id: uuid.UUID+ tenant_id: uuid.UUID+ is_active: bool+ false_positive: bool+ first_seen: str+ last_seen: str+ created_at: str++ class Config:+ from_attributes = True+++class ThreatActorCreate(BaseModel):+ name: str+ aliases: list[str] | None = None+ motivation: str | None = None+ sophistication: str | None = None+ country_of_origin: str | None = None+ target_sectors: list[str] | None = None+ ttps: list[str] | None = None+ description: str | None = None+ first_observed: datetime | None = None+ last_activity: datetime | None = None+ context: dict[str, Any] = Field(default_factory=dict)+++class ThreatActorOut(ThreatActorCreate):+ id: uuid.UUID+ tenant_id: uuid.UUID+ is_active: bool+ created_at: str++ class Config:+ from_attributes = True+++class FeedCreate(BaseModel):+ name: str+ feed_type: str+ url: str | None = None+ api_key_ref: str | None = None+ poll_interval: int = 3600+ config: dict[str, Any] = Field(default_factory=dict)+++class FeedOut(FeedCreate):+ id: uuid.UUID+ tenant_id: uuid.UUID+ is_enabled: bool+ last_polled_at: str | None = None+ created_at: str++ class Config:+ from_attributes = True+++# ---------------------------------------------------------------------------+# IOC endpoints+# ---------------------------------------------------------------------------++[email protected]("/iocs", response_model=list[IOCOut])+async def list_iocs(+ ioc_type: str | None = Query(None),+ severity: str | None = Query(None),+ is_active: bool | None = Query(None),+ limit: int = Query(50, le=500),+ offset: int = Query(0, ge=0),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[ThreatIntelIOC]:+ q = select(ThreatIntelIOC).where(ThreatIntelIOC.tenant_id == current_user.tenant_id)+ if ioc_type:+ q = q.where(ThreatIntelIOC.ioc_type == ioc_type)+ if severity:+ q = q.where(ThreatIntelIOC.severity == severity)+ if is_active is not None:+ q = q.where(ThreatIntelIOC.is_active == is_active)+ q = q.order_by(ThreatIntelIOC.last_seen.desc()).offset(offset).limit(limit)+ result = await db.execute(q)+ return list(result.scalars().all())++[email protected]("/iocs", response_model=IOCOut, status_code=status.HTTP_201_CREATED)+async def create_ioc(+ body: IOCCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> ThreatIntelIOC:+ ioc = ThreatIntelIOC(**body.model_dump(), tenant_id=current_user.tenant_id)+ db.add(ioc)+ await db.commit()+ await db.refresh(ioc)+ return ioc++[email protected]("/iocs/{ioc_id}", response_model=IOCOut)+async def get_ioc(+ ioc_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> ThreatIntelIOC:+ ioc = await db.get(ThreatIntelIOC, ioc_id)+ if not ioc or ioc.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="IOC not found")+ return ioc++[email protected]("/iocs/{ioc_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_ioc(+ ioc_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> None:+ ioc = await db.get(ThreatIntelIOC, ioc_id)+ if not ioc or ioc.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="IOC not found")+ await db.delete(ioc)+ await db.commit()+++# ---------------------------------------------------------------------------+# Threat actor endpoints+# ---------------------------------------------------------------------------++[email protected]("/actors", response_model=list[ThreatActorOut])+async def list_actors(+ is_active: bool | None = Query(None),+ limit: int = Query(50, le=200),+ offset: int = Query(0, ge=0),+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[ThreatActor]:+ q = select(ThreatActor).where(ThreatActor.tenant_id == current_user.tenant_id)+ if is_active is not None:+ q = q.where(ThreatActor.is_active == is_active)+ q = q.order_by(ThreatActor.name).offset(offset).limit(limit)+ result = await db.execute(q)+ return list(result.scalars().all())++[email protected]("/actors", response_model=ThreatActorOut, status_code=status.HTTP_201_CREATED)+async def create_actor(+ body: ThreatActorCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> ThreatActor:+ actor = ThreatActor(**body.model_dump(), tenant_id=current_user.tenant_id)+ db.add(actor)+ await db.commit()+ await db.refresh(actor)+ return actor+++# ---------------------------------------------------------------------------+# Feed management endpoints+# ---------------------------------------------------------------------------++[email protected]("/feeds", response_model=list[FeedOut])+async def list_feeds(+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> list[ThreatIntelFeed]:+ result = await db.execute(+ select(ThreatIntelFeed)+ .where(ThreatIntelFeed.tenant_id == current_user.tenant_id)+ .order_by(ThreatIntelFeed.name)+ )+ return list(result.scalars().all())++[email protected]("/feeds", response_model=FeedOut, status_code=status.HTTP_201_CREATED)+async def create_feed(+ body: FeedCreate,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> ThreatIntelFeed:+ feed = ThreatIntelFeed(**body.model_dump(), tenant_id=current_user.tenant_id)+ db.add(feed)+ await db.commit()+ await db.refresh(feed)+ return feed++[email protected]("/feeds/{feed_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_feed(+ feed_id: uuid.UUID,+ db: AsyncSession = Depends(get_db),+ current_user: User = Depends(get_current_user),+) -> None:+ feed = await db.get(ThreatIntelFeed, feed_id)+ if not feed or feed.tenant_id != current_user.tenant_id:+ raise HTTPException(status_code=404, detail="Feed not found")+ await db.delete(feed)+ await db.commit()diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex cddeb46ba..a9ee4951a 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -6,6 +6,7 @@ from app.api.v1.endpoints import (alerts,api_keys,approvals,+ assets,audit,auth,cases,@@ -16,16 +17,23 @@ from app.api.v1.endpoints import (detection_rules,federated,graph,+ identity_graph,+ insider_threat,investigations,marketplace,+ mssp,oncall,passkeys,playbooks,plugins,+ posture,push,rbac,+ remediation,+ reports,sla,tenants,+ threat_intel,)api_router = APIRouter(prefix="/api/v1")@@ -55,3 +63,15 @@ api_router.include_router(push.router)api_router.include_router(oncall.router)api_router.include_router(approvals.router)api_router.include_router(passkeys.router)++# Wave 3 — operational maturity+api_router.include_router(assets.router)+api_router.include_router(mssp.router)+api_router.include_router(insider_threat.router)+api_router.include_router(remediation.router)++# Wave 4 — advanced capabilities+api_router.include_router(threat_intel.router)+api_router.include_router(posture.router)+api_router.include_router(identity_graph.router)+api_router.include_router(reports.router)diff --git a/services/api/app/models/__init__.py b/services/api/app/models/__init__.pyindex 04222b275..cc2d3d250 100644--- a/services/api/app/models/__init__.py+++ b/services/api/app/models/__init__.py@@ -2,15 +2,22 @@from app.db.database import Basefrom app.models.alert import Alert+from app.models.asset import AlertAssetCorrelation, Asset, AssetVulnerabilityfrom app.models.case import Case, CaseTask, CaseTimelinefrom app.models.connector import Connectorfrom app.models.detection_proposal import DetectionEvalBaseline, DetectionRuleProposalfrom app.models.detection_rule import DetectionRule+from app.models.identity_graph import AlertIdentityLink, IdentityEdge, IdentityNode+from app.models.insider_threat import InsiderIndicator, InsiderPeerGroup, UserRiskProfilefrom app.models.investigation import (InvestigationArtifact,InvestigationEvent,InvestigationRun,)+from app.models.mssp import MSSPDelegation, MSSPTenantMetrics, MSSPTenantNote+from app.models.posture import PostureDriftEvent, PostureFinding, PostureScanRun+from app.models.remediation import RemediationGateLog, RemediationMaturity, RemediationWhitelist+from app.models.report import ReportArtefact, ReportTemplatefrom app.models.responder import (AgentApproval,OnCallStatus,@@ -18,6 +25,7 @@ from app.models.responder import (PasskeyCredential,)from app.models.tenant import ApiKey, Tenant, User+from app.models.threat_intel import ThreatActor, ThreatIntelFeed, ThreatIntelIOC__all__ = ["Base",@@ -25,6 +33,10 @@ __all__ = ["User","ApiKey","Alert",+ "AlertAssetCorrelation",+ "AlertIdentityLink",+ "Asset",+ "AssetVulnerability","Case","CaseTask","CaseTimeline",@@ -32,11 +44,30 @@ __all__ = ["DetectionRule","DetectionRuleProposal","DetectionEvalBaseline",+ "IdentityEdge",+ "IdentityNode",+ "InsiderIndicator",+ "InsiderPeerGroup","InvestigationRun","InvestigationEvent","InvestigationArtifact",+ "MSSPDelegation",+ "MSSPTenantMetrics",+ "MSSPTenantNote","PasskeyCredential","PasskeyChallenge","OnCallStatus","AgentApproval",+ "PostureDriftEvent",+ "PostureFinding",+ "PostureScanRun",+ "RemediationGateLog",+ "RemediationMaturity",+ "RemediationWhitelist",+ "ReportArtefact",+ "ReportTemplate",+ "ThreatActor",+ "ThreatIntelFeed",+ "ThreatIntelIOC",+ "UserRiskProfile",]diff --git a/services/api/app/models/asset.py b/services/api/app/models/asset.pynew file mode 100644index 000000000..298b08c3d--- /dev/null+++ b/services/api/app/models/asset.py@@ -0,0 +1,86 @@+"""Asset inventory and vulnerability ORM models."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import Boolean, DateTime, Float, ForeignKey, String, Text+from sqlalchemy.dialects.postgresql import ARRAY, JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.db.database import Base+++class Asset(Base):+ __tablename__ = "assets"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ asset_type: Mapped[str] = mapped_column(String(50), default="host")+ name: Mapped[str] = mapped_column(String(512), nullable=False)+ fqdn: Mapped[str | None] = mapped_column(String(512), nullable=True)+ ip_addresses: Mapped[list[str] | None] = mapped_column(ARRAY(Text), nullable=True)+ cloud_provider: Mapped[str | None] = mapped_column(String(50), nullable=True)+ cloud_region: Mapped[str | None] = mapped_column(String(100), nullable=True)+ cloud_account: Mapped[str | None] = mapped_column(String(255), nullable=True)+ os: Mapped[str | None] = mapped_column(String(100), nullable=True)+ os_version: Mapped[str | None] = mapped_column(String(100), nullable=True)+ criticality: Mapped[str] = mapped_column(String(20), default="medium")+ tags: Mapped[list[str] | None] = mapped_column(ARRAY(Text), nullable=True)+ owner_email: Mapped[str | None] = mapped_column(String(255), nullable=True)+ last_seen: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ first_seen: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ metadata: Mapped[dict] = mapped_column(JSONB, default=dict)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(UTC),+ onupdate=lambda: datetime.now(UTC),+ )++ vulnerabilities: Mapped[list["AssetVulnerability"]] = relationship(+ "AssetVulnerability", back_populates="asset", lazy="noload"+ )+++class AssetVulnerability(Base):+ __tablename__ = "asset_vulnerabilities"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ asset_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("assets.id", ondelete="CASCADE"), nullable=False)+ cve_id: Mapped[str | None] = mapped_column(String(50), nullable=True)+ title: Mapped[str] = mapped_column(String(512), nullable=False)+ description: Mapped[str | None] = mapped_column(Text, nullable=True)+ severity: Mapped[str] = mapped_column(String(20), default="medium")+ cvss_score: Mapped[float | None] = mapped_column(Float, nullable=True)+ cvss_vector: Mapped[str | None] = mapped_column(String(100), nullable=True)+ epss_score: Mapped[float | None] = mapped_column(Float, nullable=True)+ is_exploited: Mapped[bool] = mapped_column(Boolean, default=False)+ source: Mapped[str] = mapped_column(String(100), nullable=False)+ external_id: Mapped[str | None] = mapped_column(String(255), nullable=True)+ first_found: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ last_found: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ remediated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ metadata: Mapped[dict] = mapped_column(JSONB, default=dict)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))++ asset: Mapped["Asset"] = relationship("Asset", back_populates="vulnerabilities")+++class AlertAssetCorrelation(Base):+ __tablename__ = "alert_asset_correlations"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ alert_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)+ asset_id: Mapped[uuid.UUID | None] = mapped_column(+ ForeignKey("assets.id", ondelete="SET NULL"), nullable=True+ )+ vuln_id: Mapped[uuid.UUID | None] = mapped_column(+ ForeignKey("asset_vulnerabilities.id", ondelete="SET NULL"), nullable=True+ )+ match_field: Mapped[str] = mapped_column(String(50), default="ip")+ confidence: Mapped[float] = mapped_column(Float, default=1.0)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))diff --git a/services/api/app/models/identity_graph.py b/services/api/app/models/identity_graph.pynew file mode 100644index 000000000..2e3280a10--- /dev/null+++ b/services/api/app/models/identity_graph.py@@ -0,0 +1,67 @@+"""Identity-centric correlation graph ORM models."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import DateTime, Float, ForeignKey, Integer, String, Text+from sqlalchemy.dialects.postgresql import JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.db.database import Base+++class IdentityNode(Base):+ __tablename__ = "identity_nodes"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ node_type: Mapped[str] = mapped_column(String(50), nullable=False)+ external_id: Mapped[str] = mapped_column(Text, nullable=False)+ display_name: Mapped[str | None] = mapped_column(Text, nullable=True)+ source_system: Mapped[str] = mapped_column(String(100), nullable=False)+ risk_score: Mapped[float] = mapped_column(Float, default=0.0)+ privilege_tier: Mapped[int] = mapped_column(Integer, default=0)+ is_active: Mapped[bool] = mapped_column(String(10), default=True)+ last_activity: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ attributes: Mapped[dict] = mapped_column(JSONB, default=dict)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(UTC),+ onupdate=lambda: datetime.now(UTC),+ )+++class IdentityEdge(Base):+ __tablename__ = "identity_edges"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ source_id: Mapped[uuid.UUID] = mapped_column(+ ForeignKey("identity_nodes.id", ondelete="CASCADE"), nullable=False+ )+ target_id: Mapped[uuid.UUID] = mapped_column(+ ForeignKey("identity_nodes.id", ondelete="CASCADE"), nullable=False+ )+ edge_type: Mapped[str] = mapped_column(String(50), nullable=False)+ weight: Mapped[float] = mapped_column(Float, default=1.0)+ valid_from: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ valid_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ evidence: Mapped[dict] = mapped_column(JSONB, default=dict)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+++class AlertIdentityLink(Base):+ __tablename__ = "alert_identity_links"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ alert_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)+ node_id: Mapped[uuid.UUID] = mapped_column(+ ForeignKey("identity_nodes.id", ondelete="CASCADE"), nullable=False+ )+ link_reason: Mapped[str] = mapped_column(String(50), nullable=False)+ confidence: Mapped[float] = mapped_column(Float, default=1.0)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))diff --git a/services/api/app/models/insider_threat.py b/services/api/app/models/insider_threat.pynew file mode 100644index 000000000..638a2c8a5--- /dev/null+++ b/services/api/app/models/insider_threat.py@@ -0,0 +1,84 @@+"""Insider-threat module ORM models."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Integer, String, Text+from sqlalchemy.dialects.postgresql import JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.db.database import Base+++class UserRiskProfile(Base):+ __tablename__ = "user_risk_profiles"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ user_id: Mapped[uuid.UUID | None] = mapped_column(+ ForeignKey("users.id", ondelete="CASCADE"), nullable=True+ )+ external_user_ref: Mapped[str | None] = mapped_column(String(255), nullable=True)+ risk_score: Mapped[float] = mapped_column(Float, default=0.0)+ risk_tier: Mapped[str] = mapped_column(String(20), default="low")+ # aggregated signals+ failed_auth_24h: Mapped[int] = mapped_column(Integer, default=0)+ off_hours_events_7d: Mapped[int] = mapped_column(Integer, default=0)+ data_staging_score: Mapped[float] = mapped_column(Float, default=0.0)+ peer_anomaly_score: Mapped[float] = mapped_column(Float, default=0.0)+ privilege_delta: Mapped[int] = mapped_column(Integer, default=0)+ # watchlist+ is_watchlisted: Mapped[bool] = mapped_column(Boolean, default=False)+ watchlist_reason: Mapped[str | None] = mapped_column(Text, nullable=True)+ watchlisted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ watchlisted_by: Mapped[uuid.UUID | None] = mapped_column(+ ForeignKey("users.id", ondelete="SET NULL"), nullable=True+ )+ # timestamps+ last_evaluated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(UTC),+ onupdate=lambda: datetime.now(UTC),+ )++ indicators: Mapped[list["InsiderIndicator"]] = relationship(+ "InsiderIndicator", back_populates="profile", lazy="noload"+ )+++class InsiderIndicator(Base):+ __tablename__ = "insider_indicators"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ profile_id: Mapped[uuid.UUID] = mapped_column(+ ForeignKey("user_risk_profiles.id", ondelete="CASCADE"), nullable=False+ )+ indicator_type: Mapped[str] = mapped_column(String(100), nullable=False)+ severity: Mapped[str] = mapped_column(String(20), default="medium")+ description: Mapped[str] = mapped_column(Text, nullable=False)+ source_alert_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)+ evidence: Mapped[dict] = mapped_column(JSONB, default=dict)+ occurred_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ acknowledged_by: Mapped[uuid.UUID | None] = mapped_column(+ ForeignKey("users.id", ondelete="SET NULL"), nullable=True+ )+ acknowledged_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))++ profile: Mapped["UserRiskProfile"] = relationship("UserRiskProfile", back_populates="indicators")+++class InsiderPeerGroup(Base):+ __tablename__ = "insider_peer_groups"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ name: Mapped[str] = mapped_column(String(255), nullable=False)+ description: Mapped[str | None] = mapped_column(Text, nullable=True)+ criteria: Mapped[dict] = mapped_column(JSONB, default=dict)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))diff --git a/services/api/app/models/mssp.py b/services/api/app/models/mssp.pynew file mode 100644index 000000000..a0eab4a17--- /dev/null+++ b/services/api/app/models/mssp.py@@ -0,0 +1,59 @@+"""MSSP parent-tenant console ORM models."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Integer, String, Text+from sqlalchemy.dialects.postgresql import JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.db.database import Base+++class MSSPTenantNote(Base):+ __tablename__ = "mssp_tenant_notes"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ parent_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ child_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ author_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)+ body: Mapped[str] = mapped_column(Text, nullable=False)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(UTC),+ onupdate=lambda: datetime.now(UTC),+ )+++class MSSPDelegation(Base):+ __tablename__ = "mssp_delegations"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ parent_tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ child_tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ granted_role: Mapped[str] = mapped_column(String(50), default="soc_analyst")+ granted_by_user: Mapped[uuid.UUID | None] = mapped_column(+ ForeignKey("users.id", ondelete="SET NULL"), nullable=True+ )+ expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+++class MSSPTenantMetrics(Base):+ __tablename__ = "mssp_tenant_metrics"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ snapshot_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ open_alerts: Mapped[int] = mapped_column(Integer, default=0)+ critical_alerts: Mapped[int] = mapped_column(Integer, default=0)+ open_cases: Mapped[int] = mapped_column(Integer, default=0)+ mttr_minutes: Mapped[float | None] = mapped_column(Float, nullable=True)+ sla_breaches: Mapped[int] = mapped_column(Integer, default=0)+ connector_count: Mapped[int] = mapped_column(Integer, default=0)+ health_score: Mapped[float | None] = mapped_column(Float, nullable=True)+ raw_data: Mapped[dict] = mapped_column(JSONB, default=dict)diff --git a/services/api/app/models/posture.py b/services/api/app/models/posture.pynew file mode 100644index 000000000..9623bb3e3--- /dev/null+++ b/services/api/app/models/posture.py@@ -0,0 +1,85 @@+"""CSPM / KSPM cloud security posture ORM models."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text+from sqlalchemy.dialects.postgresql import ARRAY, JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.db.database import Base+++class PostureFinding(Base):+ __tablename__ = "posture_findings"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ cloud_provider: Mapped[str] = mapped_column(String(20), nullable=False)+ cloud_account: Mapped[str | None] = mapped_column(String(255), nullable=True)+ cloud_region: Mapped[str | None] = mapped_column(String(100), nullable=True)+ resource_type: Mapped[str] = mapped_column(String(100), nullable=False)+ resource_id: Mapped[str] = mapped_column(Text, nullable=False)+ resource_name: Mapped[str | None] = mapped_column(Text, nullable=True)+ rule_id: Mapped[str] = mapped_column(String(100), nullable=False)+ rule_title: Mapped[str] = mapped_column(Text, nullable=False)+ description: Mapped[str | None] = mapped_column(Text, nullable=True)+ severity: Mapped[str] = mapped_column(String(20), default="medium")+ status: Mapped[str] = mapped_column(String(20), default="open")+ frameworks: Mapped[list[str] | None] = mapped_column(ARRAY(Text), nullable=True)+ control_ids: Mapped[list[str] | None] = mapped_column(ARRAY(Text), nullable=True)+ evidence: Mapped[dict] = mapped_column(JSONB, default=dict)+ remediation_guide: Mapped[str | None] = mapped_column(Text, nullable=True)+ auto_remediated: Mapped[bool] = mapped_column(Boolean, default=False)+ first_detected_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ last_evaluated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ resolved_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ suppressed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ suppressed_by: Mapped[uuid.UUID | None] = mapped_column(+ ForeignKey("users.id", ondelete="SET NULL"), nullable=True+ )+ suppress_reason: Mapped[str | None] = mapped_column(Text, nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(UTC),+ onupdate=lambda: datetime.now(UTC),+ )+++class PostureScanRun(Base):+ __tablename__ = "posture_scan_runs"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ cloud_provider: Mapped[str] = mapped_column(String(20), nullable=False)+ cloud_account: Mapped[str | None] = mapped_column(String(255), nullable=True)+ started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ status: Mapped[str] = mapped_column(String(20), default="running")+ findings_total: Mapped[int] = mapped_column(Integer, default=0)+ findings_new: Mapped[int] = mapped_column(Integer, default=0)+ findings_closed: Mapped[int] = mapped_column(Integer, default=0)+ error_message: Mapped[str | None] = mapped_column(Text, nullable=True)+ metadata: Mapped[dict] = mapped_column(JSONB, default=dict)+++class PostureDriftEvent(Base):+ __tablename__ = "posture_drift_events"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ resource_id: Mapped[str] = mapped_column(Text, nullable=False)+ resource_type: Mapped[str] = mapped_column(String(100), nullable=False)+ cloud_provider: Mapped[str] = mapped_column(String(20), nullable=False)+ change_type: Mapped[str] = mapped_column(String(20), nullable=False)+ attribute_path: Mapped[str] = mapped_column(Text, nullable=False)+ old_value: Mapped[str | None] = mapped_column(Text, nullable=True)+ new_value: Mapped[str | None] = mapped_column(Text, nullable=True)+ severity: Mapped[str] = mapped_column(String(20), default="medium")+ linked_finding: Mapped[uuid.UUID | None] = mapped_column(+ ForeignKey("posture_findings.id", ondelete="SET NULL"), nullable=True+ )+ detected_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))diff --git a/services/api/app/models/remediation.py b/services/api/app/models/remediation.pynew file mode 100644index 000000000..f5c439d80--- /dev/null+++ b/services/api/app/models/remediation.py@@ -0,0 +1,58 @@+"""L0–L4 auto-remediation maturity ORM models."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import DateTime, ForeignKey, Integer, String, Text+from sqlalchemy.dialects.postgresql import JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.db.database import Base+++class RemediationMaturity(Base):+ __tablename__ = "remediation_maturity"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(+ ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, unique=True+ )+ maturity_tier: Mapped[int] = mapped_column(Integer, default=0)+ action_overrides: Mapped[dict] = mapped_column(JSONB, default=dict)+ changed_by: Mapped[uuid.UUID | None] = mapped_column(+ ForeignKey("users.id", ondelete="SET NULL"), nullable=True+ )+ changed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+++class RemediationGateLog(Base):+ __tablename__ = "remediation_gate_log"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ action_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)+ action_type: Mapped[str] = mapped_column(String(100), nullable=False)+ blast_radius: Mapped[str] = mapped_column(String(20), nullable=False)+ maturity_tier: Mapped[int] = mapped_column(Integer, nullable=False)+ decision: Mapped[str] = mapped_column(String(20), nullable=False)+ rationale: Mapped[str | None] = mapped_column(Text, nullable=True)+ actor: Mapped[str] = mapped_column(String(100), default="system")+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+++class RemediationWhitelist(Base):+ __tablename__ = "remediation_whitelist"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ action_type: Mapped[str] = mapped_column(String(100), nullable=False)+ blast_radius: Mapped[str] = mapped_column(String(20), nullable=False)+ constraints: Mapped[dict] = mapped_column(JSONB, default=dict)+ approved_by: Mapped[uuid.UUID | None] = mapped_column(+ ForeignKey("users.id", ondelete="SET NULL"), nullable=True+ )+ expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))diff --git a/services/api/app/models/report.py b/services/api/app/models/report.pynew file mode 100644index 000000000..7e0e87a7c--- /dev/null+++ b/services/api/app/models/report.py@@ -0,0 +1,62 @@+"""Auto-generated board / executive reports ORM models."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import BigInteger, Boolean, DateTime, ForeignKey, String, Text+from sqlalchemy.dialects.postgresql import ARRAY, JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.db.database import Base+++class ReportTemplate(Base):+ __tablename__ = "report_templates"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ name: Mapped[str] = mapped_column(String(255), nullable=False)+ report_type: Mapped[str] = mapped_column(String(50), nullable=False)+ cron_schedule: Mapped[str | None] = mapped_column(String(100), nullable=True)+ timezone: Mapped[str] = mapped_column(String(50), default="UTC")+ sections: Mapped[list] = mapped_column(JSONB, default=list)+ recipients: Mapped[list[str] | None] = mapped_column(ARRAY(Text), nullable=True)+ output_format: Mapped[str] = mapped_column(String(10), default="pdf")+ is_enabled: Mapped[bool] = mapped_column(Boolean, default=True)+ last_run_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ created_by: Mapped[uuid.UUID | None] = mapped_column(+ ForeignKey("users.id", ondelete="SET NULL"), nullable=True+ )+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(UTC),+ onupdate=lambda: datetime.now(UTC),+ )+++class ReportArtefact(Base):+ __tablename__ = "report_artefacts"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ template_id: Mapped[uuid.UUID | None] = mapped_column(+ ForeignKey("report_templates.id", ondelete="SET NULL"), nullable=True+ )+ report_type: Mapped[str] = mapped_column(String(50), nullable=False)+ title: Mapped[str] = mapped_column(Text, nullable=False)+ period_start: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)+ period_end: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)+ output_format: Mapped[str] = mapped_column(String(10), default="pdf")+ body_b64: Mapped[str | None] = mapped_column(Text, nullable=True)+ storage_key: Mapped[str | None] = mapped_column(Text, nullable=True)+ file_size_bytes: Mapped[int | None] = mapped_column(BigInteger, nullable=True)+ data_snapshot: Mapped[dict] = mapped_column(JSONB, default=dict)+ delivered_to: Mapped[list[str] | None] = mapped_column(ARRAY(Text), nullable=True)+ delivered_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ generated_by: Mapped[str] = mapped_column(String(100), default="system")+ status: Mapped[str] = mapped_column(String(20), default="pending")+ error_message: Mapped[str | None] = mapped_column(Text, nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))diff --git a/services/api/app/models/threat_intel.py b/services/api/app/models/threat_intel.pynew file mode 100644index 000000000..5ab135d15--- /dev/null+++ b/services/api/app/models/threat_intel.py@@ -0,0 +1,84 @@+"""Internal threat-intel generation ORM models."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text+from sqlalchemy.dialects.postgresql import ARRAY, JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.db.database import Base+++class ThreatIntelIOC(Base):+ __tablename__ = "threat_intel_iocs"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ ioc_type: Mapped[str] = mapped_column(String(50), nullable=False)+ value: Mapped[str] = mapped_column(Text, nullable=False)+ confidence: Mapped[int] = mapped_column(Integer, default=50)+ severity: Mapped[str] = mapped_column(String(20), default="medium")+ tlp: Mapped[str] = mapped_column(String(10), default="amber")+ threat_actor: Mapped[str | None] = mapped_column(String(255), nullable=True)+ campaign: Mapped[str | None] = mapped_column(String(255), nullable=True)+ malware_family: Mapped[str | None] = mapped_column(String(255), nullable=True)+ tags: Mapped[list[str] | None] = mapped_column(ARRAY(Text), nullable=True)+ source: Mapped[str] = mapped_column(String(100), default="internal")+ source_ref: Mapped[str | None] = mapped_column(Text, nullable=True)+ first_seen: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ last_seen: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ is_active: Mapped[bool] = mapped_column(Boolean, default=True)+ false_positive: Mapped[bool] = mapped_column(Boolean, default=False)+ linked_alerts: Mapped[list[uuid.UUID] | None] = mapped_column(ARRAY(UUID(as_uuid=True)), nullable=True)+ context: Mapped[dict] = mapped_column(JSONB, default=dict)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(UTC),+ onupdate=lambda: datetime.now(UTC),+ )+++class ThreatActor(Base):+ __tablename__ = "threat_actors"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ name: Mapped[str] = mapped_column(String(255), nullable=False)+ aliases: Mapped[list[str] | None] = mapped_column(ARRAY(Text), nullable=True)+ motivation: Mapped[str | None] = mapped_column(String(100), nullable=True)+ sophistication: Mapped[str | None] = mapped_column(String(50), nullable=True)+ country_of_origin: Mapped[str | None] = mapped_column(String(100), nullable=True)+ target_sectors: Mapped[list[str] | None] = mapped_column(ARRAY(Text), nullable=True)+ ttps: Mapped[list[str] | None] = mapped_column(ARRAY(Text), nullable=True)+ description: Mapped[str | None] = mapped_column(Text, nullable=True)+ first_observed: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ last_activity: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ is_active: Mapped[bool] = mapped_column(Boolean, default=True)+ context: Mapped[dict] = mapped_column(JSONB, default=dict)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(UTC),+ onupdate=lambda: datetime.now(UTC),+ )+++class ThreatIntelFeed(Base):+ __tablename__ = "threat_intel_feeds"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)+ name: Mapped[str] = mapped_column(String(255), nullable=False)+ feed_type: Mapped[str] = mapped_column(String(50), nullable=False)+ url: Mapped[str | None] = mapped_column(Text, nullable=True)+ api_key_ref: Mapped[str | None] = mapped_column(String(255), nullable=True)+ poll_interval: Mapped[int] = mapped_column(Integer, default=3600)+ last_polled_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ is_enabled: Mapped[bool] = mapped_column(Boolean, default=True)+ config: Mapped[dict] = mapped_column(JSONB, default=dict)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))diff --git a/services/api/migrations/012_mssp_console.sql b/services/api/migrations/012_mssp_console.sqlnew file mode 100644index 000000000..677ad6f03--- /dev/null+++ b/services/api/migrations/012_mssp_console.sql@@ -0,0 +1,72 @@+-- Migration 012: MSSP parent-tenant console+-- Adds parent_tenant_id to support MSSP hierarchies (parent manages multiple child tenants).+-- Also adds tenant-level rollup metrics view used by the MSSP console.++BEGIN;++-- 1. Parent-tenant relationship -----------------------------------------------+ALTER TABLE tenants+ ADD COLUMN IF NOT EXISTS parent_tenant_id UUID REFERENCES tenants(id) ON DELETE SET NULL,+ ADD COLUMN IF NOT EXISTS mssp_role TEXT NOT NULL DEFAULT 'standalone'+ CHECK (mssp_role IN ('standalone', 'parent', 'child'));++CREATE INDEX IF NOT EXISTS idx_tenants_parent ON tenants (parent_tenant_id)+ WHERE parent_tenant_id IS NOT NULL;++-- 2. MSSP console cross-tenant notes / annotations ----------------------------+CREATE TABLE IF NOT EXISTS mssp_tenant_notes (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ parent_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ child_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ author_id UUID REFERENCES users(id) ON DELETE SET NULL,+ body TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_mssp_notes_parent ON mssp_tenant_notes (parent_id);+CREATE INDEX IF NOT EXISTS idx_mssp_notes_child ON mssp_tenant_notes (child_id);++-- 3. Cross-tenant delegation grants -------------------------------------------+-- Allows a parent-tenant user to act on behalf of a child tenant+-- without sharing credentials.+CREATE TABLE IF NOT EXISTS mssp_delegations (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ parent_tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ child_tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ granted_role TEXT NOT NULL DEFAULT 'soc_analyst',+ granted_by_user UUID REFERENCES users(id) ON DELETE SET NULL,+ expires_at TIMESTAMPTZ,+ revoked_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (parent_tenant_id, child_tenant_id)+);++CREATE INDEX IF NOT EXISTS idx_mssp_del_parent ON mssp_delegations (parent_tenant_id);+CREATE INDEX IF NOT EXISTS idx_mssp_del_child ON mssp_delegations (child_tenant_id);++-- 4. Rollup metrics snapshot (written by the agents service every 15 min) -----+CREATE TABLE IF NOT EXISTS mssp_tenant_metrics (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ snapshot_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ open_alerts INT NOT NULL DEFAULT 0,+ critical_alerts INT NOT NULL DEFAULT 0,+ open_cases INT NOT NULL DEFAULT 0,+ mttr_minutes FLOAT, -- mean time-to-resolve (last 24 h)+ sla_breaches INT NOT NULL DEFAULT 0,+ connector_count INT NOT NULL DEFAULT 0,+ health_score FLOAT, -- 0.0–1.0 composite+ raw_data JSONB NOT NULL DEFAULT '{}'+);++CREATE INDEX IF NOT EXISTS idx_mssp_metrics_tenant_ts+ ON mssp_tenant_metrics (tenant_id, snapshot_at DESC);++-- Latest snapshot per tenant (used by the console overview)+CREATE OR REPLACE VIEW mssp_tenant_latest_metrics AS+SELECT DISTINCT ON (tenant_id) *+FROM mssp_tenant_metrics+ORDER BY tenant_id, snapshot_at DESC;++COMMIT;diff --git a/services/api/migrations/013_asset_inventory.sql b/services/api/migrations/013_asset_inventory.sqlnew file mode 100644index 000000000..432ff8c1b--- /dev/null+++ b/services/api/migrations/013_asset_inventory.sql@@ -0,0 +1,94 @@+-- Migration 013: Asset inventory + vuln-to-alert correlation+-- Stores discovered assets, vulnerability scan findings, and links them to alerts.++BEGIN;++-- 1. Asset table ---------------------------------------------------------------+CREATE TABLE IF NOT EXISTS assets (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ asset_type TEXT NOT NULL DEFAULT 'host'+ CHECK (asset_type IN ('host', 'container', 'cloud_resource', 'user_account', 'service', 'network_device', 'domain', 'ip')),+ name TEXT NOT NULL,+ fqdn TEXT,+ ip_addresses TEXT[],+ cloud_provider TEXT, -- aws / gcp / azure / other+ cloud_region TEXT,+ cloud_account TEXT,+ os TEXT,+ os_version TEXT,+ criticality TEXT NOT NULL DEFAULT 'medium'+ CHECK (criticality IN ('critical', 'high', 'medium', 'low', 'info')),+ tags TEXT[],+ owner_email TEXT,+ last_seen TIMESTAMPTZ NOT NULL DEFAULT now(),+ first_seen TIMESTAMPTZ NOT NULL DEFAULT now(),+ metadata JSONB NOT NULL DEFAULT '{}',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_assets_tenant ON assets (tenant_id);+CREATE INDEX IF NOT EXISTS idx_assets_name ON assets (tenant_id, name);+CREATE INDEX IF NOT EXISTS idx_assets_fqdn ON assets (tenant_id, fqdn) WHERE fqdn IS NOT NULL;+CREATE INDEX IF NOT EXISTS idx_assets_type ON assets (tenant_id, asset_type);+-- GIN index for fast text-array lookups on ip_addresses and tags+CREATE INDEX IF NOT EXISTS idx_assets_ips ON assets USING GIN (ip_addresses);+CREATE INDEX IF NOT EXISTS idx_assets_tags ON assets USING GIN (tags);++-- 2. Vulnerability findings ---------------------------------------------------+CREATE TABLE IF NOT EXISTS asset_vulnerabilities (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ asset_id UUID NOT NULL REFERENCES assets(id) ON DELETE CASCADE,+ cve_id TEXT,+ title TEXT NOT NULL,+ description TEXT,+ severity TEXT NOT NULL DEFAULT 'medium'+ CHECK (severity IN ('critical', 'high', 'medium', 'low', 'info')),+ cvss_score FLOAT,+ cvss_vector TEXT,+ epss_score FLOAT, -- Exploit Prediction Scoring System (0-1)+ is_exploited BOOLEAN NOT NULL DEFAULT false,+ source TEXT NOT NULL, -- scanner name: tenable / qualys / trivy / etc.+ external_id TEXT, -- scanner-native finding ID+ first_found TIMESTAMPTZ NOT NULL DEFAULT now(),+ last_found TIMESTAMPTZ NOT NULL DEFAULT now(),+ remediated_at TIMESTAMPTZ,+ metadata JSONB NOT NULL DEFAULT '{}',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_vulns_tenant ON asset_vulnerabilities (tenant_id);+CREATE INDEX IF NOT EXISTS idx_vulns_asset ON asset_vulnerabilities (asset_id);+CREATE INDEX IF NOT EXISTS idx_vulns_cve ON asset_vulnerabilities (cve_id) WHERE cve_id IS NOT NULL;+CREATE INDEX IF NOT EXISTS idx_vulns_sev ON asset_vulnerabilities (tenant_id, severity);++-- 3. Vuln-to-alert correlation links ------------------------------------------+CREATE TABLE IF NOT EXISTS alert_asset_correlations (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ alert_id UUID NOT NULL, -- FK to alerts.id (no hard FK to avoid cross-schema dep)+ asset_id UUID REFERENCES assets(id) ON DELETE SET NULL,+ vuln_id UUID REFERENCES asset_vulnerabilities(id) ON DELETE SET NULL,+ match_field TEXT NOT NULL DEFAULT 'ip', -- how the link was derived+ confidence FLOAT NOT NULL DEFAULT 1.0,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_aacorel_alert ON alert_asset_correlations (tenant_id, alert_id);+CREATE INDEX IF NOT EXISTS idx_aacorel_asset ON alert_asset_correlations (asset_id) WHERE asset_id IS NOT NULL;+CREATE INDEX IF NOT EXISTS idx_aacorel_vuln ON alert_asset_correlations (vuln_id) WHERE vuln_id IS NOT NULL;++-- 4. Trigger to keep assets.updated_at current --------------------------------+CREATE OR REPLACE FUNCTION update_asset_ts()+RETURNS TRIGGER LANGUAGE plpgsql AS $$+BEGIN NEW.updated_at = now(); RETURN NEW; END;+$$;++DROP TRIGGER IF EXISTS trg_asset_ts ON assets;+CREATE TRIGGER trg_asset_ts+ BEFORE UPDATE ON assets+ FOR EACH ROW EXECUTE FUNCTION update_asset_ts();++COMMIT;diff --git a/services/api/migrations/014_insider_threat.sql b/services/api/migrations/014_insider_threat.sqlnew file mode 100644index 000000000..8a964ee95--- /dev/null+++ b/services/api/migrations/014_insider_threat.sql@@ -0,0 +1,90 @@+-- Migration 014: Insider-threat module+-- Tracks anomalous user-behaviour indicators and risk scores over time.++BEGIN;++-- 1. User behaviour baseline --------------------------------------------------+-- One row per user, updated by the fusion engine on each evaluation cycle.+CREATE TABLE IF NOT EXISTS user_risk_profiles (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ user_id UUID REFERENCES users(id) ON DELETE CASCADE,+ external_user_ref TEXT, -- email / UPN for users not in the local table+ risk_score FLOAT NOT NULL DEFAULT 0.0 CHECK (risk_score BETWEEN 0.0 AND 100.0),+ risk_tier TEXT NOT NULL DEFAULT 'low'+ CHECK (risk_tier IN ('critical', 'high', 'medium', 'low')),+ -- aggregated behavioural signals+ failed_auth_24h INT NOT NULL DEFAULT 0,+ off_hours_events_7d INT NOT NULL DEFAULT 0,+ data_staging_score FLOAT NOT NULL DEFAULT 0.0, -- 0–1+ peer_anomaly_score FLOAT NOT NULL DEFAULT 0.0, -- 0–1 vs. peer-group baseline+ privilege_delta INT NOT NULL DEFAULT 0, -- role/privilege changes in last 30d+ -- disposition+ is_watchlisted BOOLEAN NOT NULL DEFAULT false,+ watchlist_reason TEXT,+ watchlisted_at TIMESTAMPTZ,+ watchlisted_by UUID REFERENCES users(id) ON DELETE SET NULL,+ -- timestamps+ last_evaluated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, external_user_ref),+ UNIQUE (tenant_id, user_id)+);++CREATE INDEX IF NOT EXISTS idx_urp_tenant ON user_risk_profiles (tenant_id);+CREATE INDEX IF NOT EXISTS idx_urp_score ON user_risk_profiles (tenant_id, risk_score DESC);+CREATE INDEX IF NOT EXISTS idx_urp_watchlist ON user_risk_profiles (tenant_id) WHERE is_watchlisted;+CREATE INDEX IF NOT EXISTS idx_urp_user ON user_risk_profiles (user_id) WHERE user_id IS NOT NULL;++-- 2. Insider-threat indicator events -----------------------------------------+CREATE TABLE IF NOT EXISTS insider_indicators (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ profile_id UUID NOT NULL REFERENCES user_risk_profiles(id) ON DELETE CASCADE,+ indicator_type TEXT NOT NULL, -- 'off_hours_login', 'large_download', 'new_device', etc.+ severity TEXT NOT NULL DEFAULT 'medium'+ CHECK (severity IN ('critical', 'high', 'medium', 'low', 'info')),+ description TEXT NOT NULL,+ source_alert_id UUID, -- linked alert if applicable+ evidence JSONB NOT NULL DEFAULT '{}',+ occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ acknowledged_by UUID REFERENCES users(id) ON DELETE SET NULL,+ acknowledged_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_ii_tenant ON insider_indicators (tenant_id);+CREATE INDEX IF NOT EXISTS idx_ii_profile ON insider_indicators (profile_id);+CREATE INDEX IF NOT EXISTS idx_ii_type ON insider_indicators (tenant_id, indicator_type);+CREATE INDEX IF NOT EXISTS idx_ii_occurred ON insider_indicators (tenant_id, occurred_at DESC);++-- 3. Peer-group definitions ---------------------------------------------------+CREATE TABLE IF NOT EXISTS insider_peer_groups (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ description TEXT,+ criteria JSONB NOT NULL DEFAULT '{}', -- e.g. {"department":"Engineering","job_title_prefix":"SRE"}+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, name)+);++CREATE TABLE IF NOT EXISTS insider_peer_group_members (+ group_id UUID NOT NULL REFERENCES insider_peer_groups(id) ON DELETE CASCADE,+ profile_id UUID NOT NULL REFERENCES user_risk_profiles(id) ON DELETE CASCADE,+ PRIMARY KEY (group_id, profile_id)+);++-- 4. Trigger to keep updated_at current --------------------------------------+CREATE OR REPLACE FUNCTION update_urp_ts()+RETURNS TRIGGER LANGUAGE plpgsql AS $$+BEGIN NEW.updated_at = now(); RETURN NEW; END;+$$;++DROP TRIGGER IF EXISTS trg_urp_ts ON user_risk_profiles;+CREATE TRIGGER trg_urp_ts+ BEFORE UPDATE ON user_risk_profiles+ FOR EACH ROW EXECUTE FUNCTION update_urp_ts();++COMMIT;diff --git a/services/api/migrations/015_remediation_maturity.sql b/services/api/migrations/015_remediation_maturity.sqlnew file mode 100644index 000000000..483a33c1a--- /dev/null+++ b/services/api/migrations/015_remediation_maturity.sql@@ -0,0 +1,81 @@+-- Migration 015: L0–L4 auto-remediation maturity tiers+-- Tracks the per-tenant maturity posture and per-action-type configuration.++BEGIN;++-- 1. Maturity tier definition per tenant ----------------------------------------+-- One row per tenant. The maturity_tier controls which actions are permitted+-- to execute automatically vs. require human approval.+--+-- L0 — Observe: All actions require approval. No automation. (default)+-- L1 — Notify: Notifications and ticket creation are automatic.+-- L2 — Contain: Low-blast-radius containment actions are automatic.+-- L3 — Remediate: Medium-blast-radius remediation is automatic.+-- L4 — Automate: High-blast-radius actions may run automatically if+-- pre-approved criteria are satisfied.++CREATE TABLE IF NOT EXISTS remediation_maturity (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL UNIQUE REFERENCES tenants(id) ON DELETE CASCADE,+ maturity_tier INT NOT NULL DEFAULT 0 CHECK (maturity_tier BETWEEN 0 AND 4),+ -- optional label for display+ tier_label TEXT GENERATED ALWAYS AS (+ CASE maturity_tier+ WHEN 0 THEN 'L0-Observe'+ WHEN 1 THEN 'L1-Notify'+ WHEN 2 THEN 'L2-Contain'+ WHEN 3 THEN 'L3-Remediate'+ WHEN 4 THEN 'L4-Automate'+ END+ ) STORED,+ -- JSON config for fine-grained overrides per action_type+ action_overrides JSONB NOT NULL DEFAULT '{}',+ -- audit+ changed_by UUID REFERENCES users(id) ON DELETE SET NULL,+ changed_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_rem_maturity_tenant ON remediation_maturity (tenant_id);++-- 2. Per-action-type maturity gate log ------------------------------------------+-- Every time an action is submitted, record which tier gate it was evaluated+-- against so we can track automation coverage over time.++CREATE TABLE IF NOT EXISTS remediation_gate_log (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ action_id UUID NOT NULL, -- references the action service UUID+ action_type TEXT NOT NULL,+ blast_radius TEXT NOT NULL,+ maturity_tier INT NOT NULL,+ decision TEXT NOT NULL CHECK (decision IN ('auto', 'queued_approval', 'blocked')),+ rationale TEXT,+ actor TEXT NOT NULL DEFAULT 'system',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_gate_log_tenant ON remediation_gate_log (tenant_id);+CREATE INDEX IF NOT EXISTS idx_gate_log_action ON remediation_gate_log (action_id);+CREATE INDEX IF NOT EXISTS idx_gate_log_created ON remediation_gate_log (tenant_id, created_at DESC);++-- 3. Approved action-type whitelist per tenant ----------------------------------+-- At L3/L4, operators can pre-approve specific (action_type, blast_radius) combos+-- so they execute without per-incident human sign-off.++CREATE TABLE IF NOT EXISTS remediation_whitelist (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ action_type TEXT NOT NULL,+ blast_radius TEXT NOT NULL,+ -- optional JSONB constraints, e.g. {"target_prefix": "10.0.0."}+ constraints JSONB NOT NULL DEFAULT '{}',+ approved_by UUID REFERENCES users(id) ON DELETE SET NULL,+ expires_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, action_type)+);++CREATE INDEX IF NOT EXISTS idx_whitelist_tenant ON remediation_whitelist (tenant_id);++COMMIT;diff --git a/services/api/migrations/016_threat_intel.sql b/services/api/migrations/016_threat_intel.sqlnew file mode 100644index 000000000..3a3499082--- /dev/null+++ b/services/api/migrations/016_threat_intel.sql@@ -0,0 +1,109 @@+-- Migration 016: Internal threat-intel generation+-- Stores IOCs, threat actor profiles, and campaign data produced or enriched+-- by the AiSOC fusion engine.++BEGIN;++-- 1. IOC (Indicators of Compromise) catalogue -----------------------------------+CREATE TABLE IF NOT EXISTS threat_intel_iocs (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ ioc_type TEXT NOT NULL CHECK (ioc_type IN (+ 'ip', 'domain', 'url', 'file_hash_md5',+ 'file_hash_sha1', 'file_hash_sha256',+ 'email', 'asn', 'cidr', 'cve'+ )),+ value TEXT NOT NULL,+ -- confidence and scoring+ confidence INT NOT NULL DEFAULT 50 CHECK (confidence BETWEEN 0 AND 100),+ severity TEXT NOT NULL DEFAULT 'medium'+ CHECK (severity IN ('critical','high','medium','low','info')),+ tlp TEXT NOT NULL DEFAULT 'amber'+ CHECK (tlp IN ('red','amber','green','white')),+ -- attribution and classification+ threat_actor TEXT,+ campaign TEXT,+ malware_family TEXT,+ tags TEXT[],+ -- sourcing+ source TEXT NOT NULL DEFAULT 'internal',+ source_ref TEXT,+ first_seen TIMESTAMPTZ NOT NULL DEFAULT now(),+ last_seen TIMESTAMPTZ NOT NULL DEFAULT now(),+ expires_at TIMESTAMPTZ,+ -- status+ is_active BOOLEAN NOT NULL DEFAULT true,+ false_positive BOOLEAN NOT NULL DEFAULT false,+ -- related alerts (array of alert UUIDs as text for portability)+ linked_alerts UUID[],+ -- freeform context+ context JSONB NOT NULL DEFAULT '{}',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, ioc_type, value)+);++CREATE INDEX IF NOT EXISTS idx_ioc_tenant ON threat_intel_iocs (tenant_id);+CREATE INDEX IF NOT EXISTS idx_ioc_type_value ON threat_intel_iocs (tenant_id, ioc_type, value);+CREATE INDEX IF NOT EXISTS idx_ioc_active ON threat_intel_iocs (tenant_id) WHERE is_active;+CREATE INDEX IF NOT EXISTS idx_ioc_actor ON threat_intel_iocs (tenant_id, threat_actor) WHERE threat_actor IS NOT NULL;++-- 2. Threat actor profiles -------------------------------------------------------+CREATE TABLE IF NOT EXISTS threat_actors (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ aliases TEXT[],+ motivation TEXT, -- 'financial', 'espionage', 'hacktivism', etc.+ sophistication TEXT CHECK (sophistication IN ('minimal','novice','intermediate','advanced','expert')),+ country_of_origin TEXT,+ target_sectors TEXT[],+ ttps TEXT[], -- MITRE ATT&CK technique IDs+ description TEXT,+ first_observed TIMESTAMPTZ,+ last_activity TIMESTAMPTZ,+ is_active BOOLEAN NOT NULL DEFAULT true,+ context JSONB NOT NULL DEFAULT '{}',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, name)+);++CREATE INDEX IF NOT EXISTS idx_actor_tenant ON threat_actors (tenant_id);+CREATE INDEX IF NOT EXISTS idx_actor_active ON threat_actors (tenant_id) WHERE is_active;++-- 3. Intel feed subscriptions ----------------------------------------------------+CREATE TABLE IF NOT EXISTS threat_intel_feeds (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ feed_type TEXT NOT NULL CHECK (feed_type IN ('taxii', 'misp', 'stix', 'csv', 'json', 'internal')),+ url TEXT,+ api_key_ref TEXT, -- references credential vault key name+ poll_interval INT NOT NULL DEFAULT 3600, -- seconds+ last_polled_at TIMESTAMPTZ,+ is_enabled BOOLEAN NOT NULL DEFAULT true,+ config JSONB NOT NULL DEFAULT '{}',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, name)+);++CREATE INDEX IF NOT EXISTS idx_feed_tenant ON threat_intel_feeds (tenant_id);++-- 4. Updated-at triggers ---------------------------------------------------------+CREATE OR REPLACE FUNCTION update_ti_ts()+RETURNS TRIGGER LANGUAGE plpgsql AS $$+BEGIN NEW.updated_at = now(); RETURN NEW; END;+$$;++DROP TRIGGER IF EXISTS trg_ioc_ts ON threat_intel_iocs;+CREATE TRIGGER trg_ioc_ts+ BEFORE UPDATE ON threat_intel_iocs+ FOR EACH ROW EXECUTE FUNCTION update_ti_ts();++DROP TRIGGER IF EXISTS trg_actor_ts ON threat_actors;+CREATE TRIGGER trg_actor_ts+ BEFORE UPDATE ON threat_actors+ FOR EACH ROW EXECUTE FUNCTION update_ti_ts();++COMMIT;diff --git a/services/api/migrations/017_cspm.sql b/services/api/migrations/017_cspm.sqlnew file mode 100644index 000000000..5d61de3af--- /dev/null+++ b/services/api/migrations/017_cspm.sql@@ -0,0 +1,100 @@+-- Migration 017: Cloud Security Posture Management (CSPM / KSPM)+-- Stores posture findings, compliance framework mappings, and drift events.++BEGIN;++-- 1. Posture findings (CSPM / KSPM) ---------------------------------------------+CREATE TABLE IF NOT EXISTS posture_findings (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ -- cloud context+ cloud_provider TEXT NOT NULL CHECK (cloud_provider IN ('aws','azure','gcp','k8s','other')),+ cloud_account TEXT,+ cloud_region TEXT,+ resource_type TEXT NOT NULL, -- e.g. 's3_bucket', 'k8s_pod', 'iam_role'+ resource_id TEXT NOT NULL,+ resource_name TEXT,+ -- finding details+ rule_id TEXT NOT NULL, -- e.g. 'CIS-AWS-1.4', 'NSA-K8S-5.2'+ rule_title TEXT NOT NULL,+ description TEXT,+ severity TEXT NOT NULL DEFAULT 'medium'+ CHECK (severity IN ('critical','high','medium','low','info')),+ status TEXT NOT NULL DEFAULT 'open'+ CHECK (status IN ('open','resolved','suppressed','investigating')),+ -- compliance framework tags+ frameworks TEXT[], -- e.g. ['CIS','SOC2','PCI-DSS']+ control_ids TEXT[], -- framework control IDs+ -- evidence+ evidence JSONB NOT NULL DEFAULT '{}',+ remediation_guide TEXT,+ auto_remediated BOOLEAN NOT NULL DEFAULT false,+ -- lifecycle+ first_detected_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ last_evaluated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ resolved_at TIMESTAMPTZ,+ suppressed_at TIMESTAMPTZ,+ suppressed_by UUID REFERENCES users(id) ON DELETE SET NULL,+ suppress_reason TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_posture_tenant ON posture_findings (tenant_id);+CREATE INDEX IF NOT EXISTS idx_posture_status ON posture_findings (tenant_id, status);+CREATE INDEX IF NOT EXISTS idx_posture_severity ON posture_findings (tenant_id, severity);+CREATE INDEX IF NOT EXISTS idx_posture_resource ON posture_findings (tenant_id, resource_id);+CREATE INDEX IF NOT EXISTS idx_posture_rule ON posture_findings (tenant_id, rule_id);+CREATE INDEX IF NOT EXISTS idx_posture_provider ON posture_findings (tenant_id, cloud_provider);++-- 2. CSPM scan runs --------------------------------------------------------------+CREATE TABLE IF NOT EXISTS posture_scan_runs (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ cloud_provider TEXT NOT NULL,+ cloud_account TEXT,+ started_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ completed_at TIMESTAMPTZ,+ status TEXT NOT NULL DEFAULT 'running'+ CHECK (status IN ('running','completed','failed')),+ findings_total INT NOT NULL DEFAULT 0,+ findings_new INT NOT NULL DEFAULT 0,+ findings_closed INT NOT NULL DEFAULT 0,+ error_message TEXT,+ metadata JSONB NOT NULL DEFAULT '{}'+);++CREATE INDEX IF NOT EXISTS idx_scan_tenant ON posture_scan_runs (tenant_id, started_at DESC);++-- 3. Drift snapshots -------------------------------------------------------------+-- Records configuration state at a point in time so we can detect drift.+CREATE TABLE IF NOT EXISTS posture_drift_events (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ resource_id TEXT NOT NULL,+ resource_type TEXT NOT NULL,+ cloud_provider TEXT NOT NULL,+ change_type TEXT NOT NULL CHECK (change_type IN ('created','modified','deleted')),+ attribute_path TEXT NOT NULL,+ old_value TEXT,+ new_value TEXT,+ severity TEXT NOT NULL DEFAULT 'medium',+ linked_finding UUID REFERENCES posture_findings(id) ON DELETE SET NULL,+ detected_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_drift_tenant ON posture_drift_events (tenant_id, detected_at DESC);+CREATE INDEX IF NOT EXISTS idx_drift_resource ON posture_drift_events (tenant_id, resource_id);++-- 4. Updated-at trigger ----------------------------------------------------------+CREATE OR REPLACE FUNCTION update_posture_ts()+RETURNS TRIGGER LANGUAGE plpgsql AS $$+BEGIN NEW.updated_at = now(); RETURN NEW; END;+$$;++DROP TRIGGER IF EXISTS trg_posture_ts ON posture_findings;+CREATE TRIGGER trg_posture_ts+ BEFORE UPDATE ON posture_findings+ FOR EACH ROW EXECUTE FUNCTION update_posture_ts();++COMMIT;diff --git a/services/api/migrations/018_identity_graph.sql b/services/api/migrations/018_identity_graph.sqlnew file mode 100644index 000000000..0905efd8b--- /dev/null+++ b/services/api/migrations/018_identity_graph.sql@@ -0,0 +1,86 @@+-- Migration 018: Identity-centric correlation graph+-- Stores identity nodes (users, service accounts, devices) and edges+-- (relationships, auth events, privilege grants) for graph-based correlation.++BEGIN;++-- 1. Identity nodes --------------------------------------------------------------+CREATE TABLE IF NOT EXISTS identity_nodes (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ node_type TEXT NOT NULL CHECK (node_type IN (+ 'human_user', 'service_account', 'device',+ 'application', 'group', 'role'+ )),+ external_id TEXT NOT NULL, -- email, UPN, ARN, object ID, etc.+ display_name TEXT,+ source_system TEXT NOT NULL, -- 'okta', 'azure_ad', 'aws_iam', etc.+ -- risk context+ risk_score FLOAT NOT NULL DEFAULT 0.0 CHECK (risk_score BETWEEN 0.0 AND 100.0),+ -- privilege tier: 0=standard, 1=elevated, 2=admin, 3=super-admin+ privilege_tier INT NOT NULL DEFAULT 0 CHECK (privilege_tier BETWEEN 0 AND 3),+ is_active BOOLEAN NOT NULL DEFAULT true,+ last_activity TIMESTAMPTZ,+ attributes JSONB NOT NULL DEFAULT '{}',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, source_system, external_id)+);++CREATE INDEX IF NOT EXISTS idx_inode_tenant ON identity_nodes (tenant_id);+CREATE INDEX IF NOT EXISTS idx_inode_type ON identity_nodes (tenant_id, node_type);+CREATE INDEX IF NOT EXISTS idx_inode_risk ON identity_nodes (tenant_id, risk_score DESC);+CREATE INDEX IF NOT EXISTS idx_inode_priv ON identity_nodes (tenant_id, privilege_tier DESC);+CREATE INDEX IF NOT EXISTS idx_inode_extid ON identity_nodes (tenant_id, external_id);++-- 2. Identity edges (relationships) ---------------------------------------------+CREATE TABLE IF NOT EXISTS identity_edges (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ source_id UUID NOT NULL REFERENCES identity_nodes(id) ON DELETE CASCADE,+ target_id UUID NOT NULL REFERENCES identity_nodes(id) ON DELETE CASCADE,+ edge_type TEXT NOT NULL CHECK (edge_type IN (+ 'member_of', 'manages', 'owns', 'delegates_to',+ 'authenticated_to', 'assumed_role', 'accessed',+ 'created', 'lateral_movement_candidate'+ )),+ weight FLOAT NOT NULL DEFAULT 1.0,+ valid_from TIMESTAMPTZ NOT NULL DEFAULT now(),+ valid_until TIMESTAMPTZ,+ evidence JSONB NOT NULL DEFAULT '{}',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, source_id, target_id, edge_type)+);++CREATE INDEX IF NOT EXISTS idx_iedge_tenant ON identity_edges (tenant_id);+CREATE INDEX IF NOT EXISTS idx_iedge_source ON identity_edges (source_id);+CREATE INDEX IF NOT EXISTS idx_iedge_target ON identity_edges (target_id);+CREATE INDEX IF NOT EXISTS idx_iedge_type ON identity_edges (tenant_id, edge_type);++-- 3. Alert-to-identity correlation ----------------------------------------------+CREATE TABLE IF NOT EXISTS alert_identity_links (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ alert_id UUID NOT NULL,+ node_id UUID NOT NULL REFERENCES identity_nodes(id) ON DELETE CASCADE,+ link_reason TEXT NOT NULL, -- 'subject', 'actor', 'target', 'lateral_path'+ confidence FLOAT NOT NULL DEFAULT 1.0 CHECK (confidence BETWEEN 0.0 AND 1.0),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_alert_id_link_tenant ON alert_identity_links (tenant_id);+CREATE INDEX IF NOT EXISTS idx_alert_id_link_alert ON alert_identity_links (alert_id);+CREATE INDEX IF NOT EXISTS idx_alert_id_link_node ON alert_identity_links (node_id);++-- 4. Updated-at trigger ----------------------------------------------------------+CREATE OR REPLACE FUNCTION update_inode_ts()+RETURNS TRIGGER LANGUAGE plpgsql AS $$+BEGIN NEW.updated_at = now(); RETURN NEW; END;+$$;++DROP TRIGGER IF EXISTS trg_inode_ts ON identity_nodes;+CREATE TRIGGER trg_inode_ts+ BEFORE UPDATE ON identity_nodes+ FOR EACH ROW EXECUTE FUNCTION update_inode_ts();++COMMIT;diff --git a/services/api/migrations/019_board_reports.sql b/services/api/migrations/019_board_reports.sqlnew file mode 100644index 000000000..4117c84dc--- /dev/null+++ b/services/api/migrations/019_board_reports.sql@@ -0,0 +1,76 @@+-- Migration 019: Auto-generated board / executive reports+-- Stores scheduled report definitions and generated report artefacts.++BEGIN;++-- 1. Report template definitions -------------------------------------------------+CREATE TABLE IF NOT EXISTS report_templates (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ report_type TEXT NOT NULL CHECK (report_type IN (+ 'board_summary', 'executive_monthly', 'soc_weekly',+ 'compliance_quarterly', 'incident_postmortem', 'custom'+ )),+ -- schedule in cron syntax (UTC). NULL means on-demand only.+ cron_schedule TEXT,+ timezone TEXT NOT NULL DEFAULT 'UTC',+ -- content config+ sections JSONB NOT NULL DEFAULT '[]', -- ordered list of section configs+ recipients TEXT[], -- email addresses+ output_format TEXT NOT NULL DEFAULT 'pdf'+ CHECK (output_format IN ('pdf', 'html', 'json')),+ is_enabled BOOLEAN NOT NULL DEFAULT true,+ last_run_at TIMESTAMPTZ,+ created_by UUID REFERENCES users(id) ON DELETE SET NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, name)+);++CREATE INDEX IF NOT EXISTS idx_rpt_template_tenant ON report_templates (tenant_id);++-- 2. Generated report artefacts --------------------------------------------------+CREATE TABLE IF NOT EXISTS report_artefacts (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ template_id UUID REFERENCES report_templates(id) ON DELETE SET NULL,+ report_type TEXT NOT NULL,+ title TEXT NOT NULL,+ period_start TIMESTAMPTZ NOT NULL,+ period_end TIMESTAMPTZ NOT NULL,+ output_format TEXT NOT NULL DEFAULT 'pdf',+ -- storage: content stored as base64 in body_b64 for small reports,+ -- or as an object-store key in storage_key for large ones.+ body_b64 TEXT,+ storage_key TEXT,+ file_size_bytes BIGINT,+ -- structured data snapshot for re-rendering or API consumers+ data_snapshot JSONB NOT NULL DEFAULT '{}',+ -- delivery+ delivered_to TEXT[],+ delivered_at TIMESTAMPTZ,+ generated_by TEXT NOT NULL DEFAULT 'system',+ -- status+ status TEXT NOT NULL DEFAULT 'pending'+ CHECK (status IN ('pending','generating','completed','failed')),+ error_message TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_rpt_artefact_tenant ON report_artefacts (tenant_id, created_at DESC);+CREATE INDEX IF NOT EXISTS idx_rpt_artefact_template ON report_artefacts (template_id);+CREATE INDEX IF NOT EXISTS idx_rpt_artefact_status ON report_artefacts (tenant_id, status);++-- 3. Updated-at trigger ----------------------------------------------------------+CREATE OR REPLACE FUNCTION update_rpt_template_ts()+RETURNS TRIGGER LANGUAGE plpgsql AS $$+BEGIN NEW.updated_at = now(); RETURN NEW; END;+$$;++DROP TRIGGER IF EXISTS trg_rpt_template_ts ON report_templates;+CREATE TRIGGER trg_rpt_template_ts+ BEFORE UPDATE ON report_templates+ FOR EACH ROW EXECUTE FUNCTION update_rpt_template_ts();++COMMIT;