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(detections): WS-B1 — Sigma bulk import pipeline with OCSF + provenance
beenu7e6736137670
diff --git a/services/api/app/models/detection_rule.py b/services/api/app/models/detection_rule.pyindex 3c3660bd7..8024f2f8f 100644--- a/services/api/app/models/detection_rule.py+++ b/services/api/app/models/detection_rule.py@@ -43,6 +43,12 @@ class DetectionRule(Base):is_builtin: Mapped[bool] = mapped_column(Boolean, default=False) # Platform-provided vs customversion: Mapped[int] = mapped_column(Integer, default=1)+ # Provenance for imported rules (Sigma bulk import, etc.).+ # Empty dict for native rules; populated for anything that came in+ # through ``app.services.detections.sigma_import``. See migration+ # 036_detection_rule_provenance.sql for the shape and indexing strategy.+ provenance: Mapped[dict] = mapped_column(JSONB, default=dict, nullable=False)+created_by_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))updated_at: Mapped[datetime] = mapped_column(diff --git a/services/api/app/services/detections/__init__.py b/services/api/app/services/detections/__init__.pynew file mode 100644index 000000000..d7e99620d--- /dev/null+++ b/services/api/app/services/detections/__init__.py@@ -0,0 +1,28 @@+"""Detection rule service modules.++This package collects the in-process services that manage AiSOC's detection+content. Today it owns:++* :mod:`app.services.detections.sigma_import` — bulk import of community+ Sigma rules with OCSF auto-mapping, MITRE ATT&CK extraction, and+ provenance tracking.+* :mod:`app.services.detections.ocsf_mapping` — translation between Sigma+ ``logsource`` blocks and OCSF v1.1 event class metadata.++Runtime evaluation of rules still lives in :mod:`app.services.rule_engine`;+this package handles authoring/import, not execution.+"""++from app.services.detections.sigma_import import (+ SigmaImportError,+ SigmaImportReport,+ SigmaImportResult,+ import_sigma_rules,+)++__all__ = [+ "SigmaImportError",+ "SigmaImportReport",+ "SigmaImportResult",+ "import_sigma_rules",+]diff --git a/services/api/app/services/detections/ocsf_mapping.py b/services/api/app/services/detections/ocsf_mapping.pynew file mode 100644index 000000000..47bae4215--- /dev/null+++ b/services/api/app/services/detections/ocsf_mapping.py@@ -0,0 +1,238 @@+"""OCSF v1.1 mapping for Sigma rules (WS-B1).++When we import a Sigma rule we want to record, alongside the rule itself,+the OCSF event class it most likely fires against. That lets the rest of+AiSOC reason about coverage in OCSF terms ("how many Authentication+findings can we generate today?") without re-parsing the rule body.++The mapping is intentionally conservative:++* We map ``logsource`` (the canonical Sigma classifier) to a single OCSF+ ``class_uid``/``category_uid`` pair. Sigma's logsource taxonomy is+ more fine-grained than OCSF's class taxonomy, so a one-to-many spread+ would create ambiguity in coverage reporting.+* When a Sigma rule's logsource doesn't fit anywhere obvious we fall+ back to ``DETECTION_FINDING`` (class_uid 2004), which is the OCSF+ catch-all for "a detection rule fired and we don't have a more+ specific class".++These constants mirror the TypeScript enums in+``packages/ocsf/src/types.ts``. Keep them in sync if OCSF ever adds new+class UIDs we care about.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Final+++# ─── Class / Category UIDs (mirrors packages/ocsf/src/types.ts) ──────────────+++class OcsfClassUid:+ """OCSF v1.1 class UIDs we currently auto-map to."""++ FILE_ACTIVITY: Final[int] = 1001+ PROCESS_ACTIVITY: Final[int] = 1007+ SECURITY_FINDING: Final[int] = 2001+ VULNERABILITY_FINDING: Final[int] = 2002+ COMPLIANCE_FINDING: Final[int] = 2003+ DETECTION_FINDING: Final[int] = 2004+ AUTHENTICATION: Final[int] = 3002+ NETWORK_ACTIVITY: Final[int] = 4001+ HTTP_ACTIVITY: Final[int] = 4002+ DNS_ACTIVITY: Final[int] = 4003+++class OcsfCategoryUid:+ """OCSF v1.1 category UIDs."""++ SYSTEM_ACTIVITY: Final[int] = 1+ FINDINGS: Final[int] = 2+ IDENTITY_ACTIVITY: Final[int] = 3+ NETWORK_ACTIVITY: Final[int] = 4+ DISCOVERY: Final[int] = 5+ APPLICATION_ACTIVITY: Final[int] = 6+++@dataclass(frozen=True, slots=True)+class OcsfClassRef:+ """Compact OCSF class reference attached to an imported rule.++ We store this on the rule (under ``provenance['ocsf']``) rather than+ deriving it on every coverage query — the mapping is stable across+ rule edits and the lookup is otherwise O(rules) per UI render.+ """++ class_uid: int+ class_name: str+ category_uid: int+ category_name: str++ def to_dict(self) -> dict[str, int | str]:+ return {+ "class_uid": self.class_uid,+ "class_name": self.class_name,+ "category_uid": self.category_uid,+ "category_name": self.category_name,+ }+++# ─── Class metadata (UID → human label) ──────────────────────────────────────++_CLASS_METADATA: Final[dict[int, tuple[str, int, str]]] = {+ # class_uid: (class_name, category_uid, category_name)+ OcsfClassUid.FILE_ACTIVITY: ("File Activity", OcsfCategoryUid.SYSTEM_ACTIVITY, "System Activity"),+ OcsfClassUid.PROCESS_ACTIVITY: ("Process Activity", OcsfCategoryUid.SYSTEM_ACTIVITY, "System Activity"),+ OcsfClassUid.SECURITY_FINDING: ("Security Finding", OcsfCategoryUid.FINDINGS, "Findings"),+ OcsfClassUid.DETECTION_FINDING: ("Detection Finding", OcsfCategoryUid.FINDINGS, "Findings"),+ OcsfClassUid.AUTHENTICATION: ("Authentication", OcsfCategoryUid.IDENTITY_ACTIVITY, "Identity & Access Management"),+ OcsfClassUid.NETWORK_ACTIVITY: ("Network Activity", OcsfCategoryUid.NETWORK_ACTIVITY, "Network Activity"),+ OcsfClassUid.HTTP_ACTIVITY: ("HTTP Activity", OcsfCategoryUid.NETWORK_ACTIVITY, "Network Activity"),+ OcsfClassUid.DNS_ACTIVITY: ("DNS Activity", OcsfCategoryUid.NETWORK_ACTIVITY, "Network Activity"),+}+++def _make_ref(class_uid: int) -> OcsfClassRef:+ name, cat_uid, cat_name = _CLASS_METADATA[class_uid]+ return OcsfClassRef(class_uid=class_uid, class_name=name, category_uid=cat_uid, category_name=cat_name)+++# ─── Sigma logsource → OCSF class lookup tables ──────────────────────────────+#+# The Sigma logsource block has up to three keys:+#+# product: the product family (windows, linux, macos, aws, azure, ...)+# category: what kind of event (process_creation, file_event, ...)+# service: the specific source (security, sysmon, sshd, cloudtrail, ...)+#+# We resolve in this order: (product, category) → (product, service) →+# (category alone) → fallback. Most Sigma rules carry product+category;+# cloud rules tend to use product+service (service=cloudtrail, etc.).++# (product, category) → class_uid. Most-specific match.+_PRODUCT_CATEGORY: Final[dict[tuple[str, str], int]] = {+ ("windows", "process_creation"): OcsfClassUid.PROCESS_ACTIVITY,+ ("windows", "process_access"): OcsfClassUid.PROCESS_ACTIVITY,+ ("windows", "process_termination"): OcsfClassUid.PROCESS_ACTIVITY,+ ("windows", "image_load"): OcsfClassUid.PROCESS_ACTIVITY,+ ("windows", "file_event"): OcsfClassUid.FILE_ACTIVITY,+ ("windows", "file_change"): OcsfClassUid.FILE_ACTIVITY,+ ("windows", "file_delete"): OcsfClassUid.FILE_ACTIVITY,+ ("windows", "file_rename"): OcsfClassUid.FILE_ACTIVITY,+ ("windows", "registry_event"): OcsfClassUid.SECURITY_FINDING,+ ("windows", "registry_set"): OcsfClassUid.SECURITY_FINDING,+ ("windows", "registry_add"): OcsfClassUid.SECURITY_FINDING,+ ("windows", "registry_delete"): OcsfClassUid.SECURITY_FINDING,+ ("windows", "network_connection"): OcsfClassUid.NETWORK_ACTIVITY,+ ("windows", "dns_query"): OcsfClassUid.DNS_ACTIVITY,+ ("windows", "pipe_created"): OcsfClassUid.SECURITY_FINDING,+ ("windows", "wmi_event"): OcsfClassUid.SECURITY_FINDING,+ ("windows", "create_remote_thread"): OcsfClassUid.PROCESS_ACTIVITY,+ ("windows", "raw_access_thread"): OcsfClassUid.PROCESS_ACTIVITY,+ ("windows", "driver_load"): OcsfClassUid.SECURITY_FINDING,+ ("linux", "process_creation"): OcsfClassUid.PROCESS_ACTIVITY,+ ("linux", "file_event"): OcsfClassUid.FILE_ACTIVITY,+ ("linux", "network_connection"): OcsfClassUid.NETWORK_ACTIVITY,+ ("macos", "process_creation"): OcsfClassUid.PROCESS_ACTIVITY,+ ("macos", "file_event"): OcsfClassUid.FILE_ACTIVITY,+ ("macos", "network_connection"): OcsfClassUid.NETWORK_ACTIVITY,+}++# (product, service) → class_uid. Used when category is missing (cloud rules).+_PRODUCT_SERVICE: Final[dict[tuple[str, str], int]] = {+ ("aws", "cloudtrail"): OcsfClassUid.SECURITY_FINDING,+ ("aws", "guardduty"): OcsfClassUid.SECURITY_FINDING,+ ("aws", "s3"): OcsfClassUid.SECURITY_FINDING,+ ("azure", "auditlogs"): OcsfClassUid.SECURITY_FINDING,+ ("azure", "signinlogs"): OcsfClassUid.AUTHENTICATION,+ ("azure", "activitylogs"): OcsfClassUid.SECURITY_FINDING,+ ("azure", "riskydetection"): OcsfClassUid.AUTHENTICATION,+ ("azure", "operationalmetrics"): OcsfClassUid.SECURITY_FINDING,+ ("gcp", "google_workspace.admin"): OcsfClassUid.SECURITY_FINDING,+ ("gcp", "gcp.audit"): OcsfClassUid.SECURITY_FINDING,+ ("okta", "okta"): OcsfClassUid.AUTHENTICATION,+ ("microsoft365", "exchange"): OcsfClassUid.SECURITY_FINDING,+ ("microsoft365", "threat_management"): OcsfClassUid.SECURITY_FINDING,+ ("github", "audit"): OcsfClassUid.SECURITY_FINDING,+ ("kubernetes", "audit"): OcsfClassUid.SECURITY_FINDING,+ ("windows", "security"): OcsfClassUid.AUTHENTICATION, # 4624/4625/4672+ ("windows", "sysmon"): OcsfClassUid.PROCESS_ACTIVITY,+ ("windows", "powershell"): OcsfClassUid.PROCESS_ACTIVITY,+ ("windows", "powershell-classic"): OcsfClassUid.PROCESS_ACTIVITY,+ ("windows", "system"): OcsfClassUid.SECURITY_FINDING,+ ("linux", "auditd"): OcsfClassUid.PROCESS_ACTIVITY,+ ("linux", "auth"): OcsfClassUid.AUTHENTICATION,+ ("linux", "syslog"): OcsfClassUid.SECURITY_FINDING,+ ("linux", "sshd"): OcsfClassUid.AUTHENTICATION,+}++# Category-only fallback. Used when product is unknown but the category+# itself is descriptive enough to commit to a class.+_CATEGORY_ONLY: Final[dict[str, int]] = {+ "process_creation": OcsfClassUid.PROCESS_ACTIVITY,+ "process_access": OcsfClassUid.PROCESS_ACTIVITY,+ "image_load": OcsfClassUid.PROCESS_ACTIVITY,+ "file_event": OcsfClassUid.FILE_ACTIVITY,+ "file_change": OcsfClassUid.FILE_ACTIVITY,+ "file_delete": OcsfClassUid.FILE_ACTIVITY,+ "network_connection": OcsfClassUid.NETWORK_ACTIVITY,+ "dns": OcsfClassUid.DNS_ACTIVITY,+ "dns_query": OcsfClassUid.DNS_ACTIVITY,+ "webserver": OcsfClassUid.HTTP_ACTIVITY,+ "proxy": OcsfClassUid.HTTP_ACTIVITY,+ "firewall": OcsfClassUid.NETWORK_ACTIVITY,+ "antivirus": OcsfClassUid.SECURITY_FINDING,+ "authentication": OcsfClassUid.AUTHENTICATION,+}+++def map_logsource_to_ocsf(logsource: dict | None) -> OcsfClassRef:+ """Map a Sigma ``logsource`` block to an OCSF class reference.++ Falls back to :pyattr:`OcsfClassUid.DETECTION_FINDING` when the+ logsource is empty or doesn't match any known taxonomy. We never+ raise — a missing/odd logsource is *common* in community rules and+ should not break a bulk import.++ Lookup precedence:++ 1. ``(product, category)`` — the most specific signal. Covers the+ bulk of Windows/Linux/macOS endpoint rules.+ 2. ``(product, service)`` — used when category is missing, which+ is the norm for cloud rules (``service: cloudtrail`` etc.).+ 3. ``category`` alone — covers product-agnostic rules.+ 4. Detection Finding fallback.+ """+ if not isinstance(logsource, dict):+ return _make_ref(OcsfClassUid.DETECTION_FINDING)++ product = (logsource.get("product") or "").strip().lower() or None+ category = (logsource.get("category") or "").strip().lower() or None+ service = (logsource.get("service") or "").strip().lower() or None++ if product and category:+ class_uid = _PRODUCT_CATEGORY.get((product, category))+ if class_uid is not None:+ return _make_ref(class_uid)++ if product and service:+ class_uid = _PRODUCT_SERVICE.get((product, service))+ if class_uid is not None:+ return _make_ref(class_uid)++ if category:+ class_uid = _CATEGORY_ONLY.get(category)+ if class_uid is not None:+ return _make_ref(class_uid)++ return _make_ref(OcsfClassUid.DETECTION_FINDING)+++__all__ = [+ "OcsfCategoryUid",+ "OcsfClassRef",+ "OcsfClassUid",+ "map_logsource_to_ocsf",+]diff --git a/services/api/app/services/detections/sigma_import.py b/services/api/app/services/detections/sigma_import.pynew file mode 100644index 000000000..43a4c717e--- /dev/null+++ b/services/api/app/services/detections/sigma_import.py@@ -0,0 +1,775 @@+"""Bulk Sigma import pipeline (WS-B1).++This module is the in-process counterpart to the offline batch importer in+``tools/detection_import/sigma_importer.py``. The offline importer writes+YAML files into ``detections/sigma-imports/`` for code review and+fixture-testing; this service ingests those same Sigma rules straight+into the runtime ``detection_rules`` table so a tenant can opt into the+community corpus without redeploying.++The pipeline does four things, in order, for every input rule:++1. **Validate** the upstream rule has the minimum fields a Sigma+ rule needs to be useful (``id``, ``title``, ``detection``).+2. **Auto-map** the Sigma ``logsource`` block to an OCSF v1.1 class so+ coverage queries can talk OCSF without re-parsing rules. See+ :mod:`app.services.detections.ocsf_mapping`.+3. **Extract** MITRE ATT&CK tactics and technique IDs from the Sigma+ ``tags:`` block. We canonicalise to upper-case (``T1078``) and we+ don't invent technique IDs from descriptions — if the upstream+ maintainer didn't tag it, we leave it untagged.+4. **Persist** with full provenance: source repo, upstream id, commit+ SHA, license, importer name, and import timestamp. The+ ``(source, source_id)`` pair makes re-imports idempotent: the same+ upstream rule across two import runs becomes ``UPDATE``, not a+ duplicate ``INSERT``.++The hand-off boundary is deliberate: a future API endpoint can call+:func:`import_sigma_rules` with a list of pre-parsed dicts and stay out+of the YAML-reading business. CLI plumbing (cloning the SigmaHQ repo,+walking files) lives in the orchestrator under ``tools/``.++Design constraints worth flagging for future maintainers:++* We never raise on a single bad rule — community Sigma quality varies+ wildly and one broken rule shouldn't abort an import of 2000+. Each+ failure is captured in :class:`SigmaImportReport.failures` for the+ caller to surface.+* We do not call ``rule_engine`` to validate the detection block at+ import time. Sigma's grammar is too loose to catch every runtime+ failure statically, and pySigma compilation is slow enough that+ doing it for every rule blows the import budget. Runtime evaluation+ errors surface in the alert pipeline with the rule id intact.+* Provenance is stored as JSONB and indexed on+ ``(source, source_id)`` — see migration+ ``036_detection_rule_provenance.sql``. Don't try to cram it into+ ``tags`` or ``suppression_config``; those are tenant-mutable.+"""++from __future__ import annotations++import logging+import uuid+from dataclasses import dataclass, field+from datetime import UTC, datetime+from typing import Any++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.detection_rule import DetectionRule+from app.services.detections.ocsf_mapping import OcsfClassRef, map_logsource_to_ocsf++logger = logging.getLogger(__name__)+++# ─── Public types ────────────────────────────────────────────────────────────+++class SigmaImportError(Exception):+ """Raised for errors that should abort the entire import run.++ Per-rule failures are captured in :class:`SigmaImportReport.failures`+ and don't raise — see the module docstring for rationale.+ """+++@dataclass(frozen=True, slots=True)+class SigmaImportResult:+ """The outcome for a single Sigma rule.++ ``rule_id`` is the AiSOC ``detection_rules.id`` (a UUID).+ ``source_id`` is the upstream Sigma rule id (also a UUID, but+ that's a coincidence — for non-Sigma sources it could be+ ``CAR-2021-04-001`` etc.).+ """++ rule_id: uuid.UUID+ source: str+ source_id: str+ title: str+ action: str # "inserted" | "updated" | "skipped"+ reason: str | None = None # for skipped/updated: human-readable why+++@dataclass(slots=True)+class SigmaImportReport:+ """Aggregate report from one :func:`import_sigma_rules` call.++ The shape mirrors what we want to surface in the import endpoint+ response and in CLI output, so callers don't have to reshape it.+ """++ inserted: list[SigmaImportResult] = field(default_factory=list)+ updated: list[SigmaImportResult] = field(default_factory=list)+ skipped: list[SigmaImportResult] = field(default_factory=list)+ failures: list[dict[str, Any]] = field(default_factory=list)++ @property+ def total_seen(self) -> int:+ return len(self.inserted) + len(self.updated) + len(self.skipped) + len(self.failures)++ @property+ def total_persisted(self) -> int:+ return len(self.inserted) + len(self.updated)++ def to_dict(self) -> dict[str, Any]:+ """Serialise to a JSON-friendly dict for API responses."""+ return {+ "summary": {+ "total_seen": self.total_seen,+ "inserted": len(self.inserted),+ "updated": len(self.updated),+ "skipped": len(self.skipped),+ "failures": len(self.failures),+ },+ "inserted": [_result_to_dict(r) for r in self.inserted],+ "updated": [_result_to_dict(r) for r in self.updated],+ "skipped": [_result_to_dict(r) for r in self.skipped],+ "failures": self.failures,+ }+++def _result_to_dict(r: SigmaImportResult) -> dict[str, Any]:+ return {+ "rule_id": str(r.rule_id),+ "source": r.source,+ "source_id": r.source_id,+ "title": r.title,+ "action": r.action,+ "reason": r.reason,+ }+++# ─── Status / quarantine policy ──────────────────────────────────────────────+#+# These mirror the offline importer's policy in+# ``tools/detection_import/sigma_importer.py`` — keep them in sync. The+# AiSOC ``status`` column maps loosely to detection lifecycle: ``testing``+# is the conservative default for community-imported content.++# Sigma statuses that we drop entirely.+_SIGMA_SKIP_STATUSES = frozenset({"deprecated", "unsupported"})++# Sigma statuses that get imported but disabled-by-default. Operators+# can flip them on once they've vetted the upstream rule.+_SIGMA_QUARANTINE_STATUSES = frozenset({"experimental", "test"})++# Severity normalisation. Sigma uses ``level``; we normalise to AiSOC's+# four-tier ``severity`` ladder. Anything we don't recognise becomes+# ``medium`` — never ``critical`` (would be a foot-gun for paging).+_SEVERITY_MAP: dict[str, str] = {+ "informational": "low",+ "info": "low",+ "low": "low",+ "medium": "medium",+ "high": "high",+ "critical": "critical",+}+++# ─── Tag / category helpers ──────────────────────────────────────────────────+++def _extract_mitre_techniques(tags: list[Any] | None) -> list[str]:+ """Pull MITRE ATT&CK technique IDs from a Sigma ``tags`` list.++ Sigma uses ``attack.t1078`` and ``attack.t1078.004`` style tags;+ we canonicalise to upper-case (``T1078``) and dedupe while+ preserving the order the upstream maintainer chose.++ We only recognise the ``attack.t<digits>(.subtechnique)?`` shape.+ Free-form tags like ``attack.persistence`` are *tactics*, handled+ separately by :func:`_extract_mitre_tactics`.+ """+ if not tags:+ return []++ out: list[str] = []+ seen: set[str] = set()+ for tag in tags:+ if not isinstance(tag, str):+ continue+ normalised = tag.strip().lower()+ if not normalised.startswith("attack.t"):+ continue+ # ``attack.t1078`` -> ``t1078``; ``attack.t1078.004`` stays.+ parts = normalised.split(".", 1)+ if len(parts) != 2:+ continue+ technique = parts[1].upper()+ # Sanity check: must look like ``T<digits>`` or ``T<digits>.<digits>``.+ # Cheap regex-free validation: starts with T, second char is a digit.+ if len(technique) < 2 or technique[0] != "T" or not technique[1].isdigit():+ continue+ if technique in seen:+ continue+ seen.add(technique)+ out.append(technique)+ return out+++# Canonical MITRE ATT&CK Enterprise tactics. The SigmaHQ tag+# specification (Tags_specification.md) uses underscore form+# (``attack.defense_evasion``), so that's our canonical key. Some+# community rules use hyphens; we normalise both forms before lookup.+_MITRE_TACTIC_LOOKUP: dict[str, tuple[str, str]] = {+ "reconnaissance": ("TA0043", "Reconnaissance"),+ "resource_development": ("TA0042", "Resource Development"),+ "initial_access": ("TA0001", "Initial Access"),+ "execution": ("TA0002", "Execution"),+ "persistence": ("TA0003", "Persistence"),+ "privilege_escalation": ("TA0004", "Privilege Escalation"),+ "defense_evasion": ("TA0005", "Defense Evasion"),+ "credential_access": ("TA0006", "Credential Access"),+ "discovery": ("TA0007", "Discovery"),+ "lateral_movement": ("TA0008", "Lateral Movement"),+ "collection": ("TA0009", "Collection"),+ "command_and_control": ("TA0011", "Command and Control"),+ "exfiltration": ("TA0010", "Exfiltration"),+ "impact": ("TA0040", "Impact"),+}+++def _extract_mitre_tactics(tags: list[Any] | None) -> list[str]:+ """Pull MITRE ATT&CK tactic *IDs* from a Sigma ``tags`` list.++ Returns the TA-code form (``TA0005``) so we can join against the+ canonical ATT&CK matrix without lossy string matching. Tags that+ don't map to a known tactic are silently ignored — community Sigma+ rules sometimes carry other ``attack.*`` tags (``attack.g0007``)+ that aren't tactics, and we don't want noise in the column.++ Accepts both ``attack.defense_evasion`` (Sigma canonical) and+ ``attack.defense-evasion`` (occasional hyphenated form) by+ normalising hyphens to underscores before the lookup.+ """+ if not tags:+ return []++ out: list[str] = []+ seen: set[str] = set()+ for tag in tags:+ if not isinstance(tag, str):+ continue+ normalised = tag.strip().lower()+ if not normalised.startswith("attack."):+ continue+ candidate = normalised.split(".", 1)[1]+ # Skip technique tags (``attack.t1078``) — those are handled+ # by ``_extract_mitre_techniques``.+ if candidate.startswith("t") and len(candidate) > 1 and candidate[1].isdigit():+ continue+ # Normalise hyphenated form to underscore form before lookup.+ candidate = candidate.replace("-", "_")+ match = _MITRE_TACTIC_LOOKUP.get(candidate)+ if match is None:+ continue+ ta_code, _name = match+ if ta_code in seen:+ continue+ seen.add(ta_code)+ out.append(ta_code)+ return out+++# Map upstream Sigma logsource buckets to AiSOC's six-folder taxonomy.+# Mirrors ``tools/detection_import/common.py::normalise_categories``.+_CATEGORY_ALIASES: dict[str, str] = {+ "aws": "cloud",+ "azure": "cloud",+ "gcp": "cloud",+ "m365": "cloud",+ "microsoft365": "cloud",+ "okta": "identity",+ "auth": "identity",+ "authentication": "identity",+ "windows": "endpoint",+ "linux": "endpoint",+ "macos": "endpoint",+ "process_creation": "endpoint",+ "file_event": "endpoint",+ "image_load": "endpoint",+ "registry_event": "endpoint",+ "proxy": "network",+ "firewall": "network",+ "dns": "network",+ "dns_query": "network",+ "network_connection": "network",+ "webserver": "application",+ "web": "application",+ "exfiltration": "data-exfil",+}++_NATIVE_CATEGORIES = frozenset({+ "cloud",+ "identity",+ "endpoint",+ "network",+ "application",+ "data-exfil",+})+++def _category_for(logsource: dict[str, Any] | None) -> str:+ """Pick the AiSOC category folder for a Sigma rule.++ Tries ``logsource.product`` first (most reliable for cloud rules),+ then ``logsource.category``, then ``logsource.service``. Falls back+ to ``endpoint`` because that's where the bulk of community Sigma+ rules belong and a wrong-but-present category is more useful than+ no category at all.+ """+ if not isinstance(logsource, dict):+ return "endpoint"++ for key in ("product", "category", "service"):+ candidate = logsource.get(key)+ if not candidate:+ continue+ candidate = str(candidate).strip().lower()+ if not candidate:+ continue+ if candidate in _CATEGORY_ALIASES:+ return _CATEGORY_ALIASES[candidate]+ if candidate in _NATIVE_CATEGORIES:+ return candidate+ return "endpoint"+++def _map_severity(level: Any) -> str:+ """Coerce Sigma's ``level`` field into AiSOC's severity enum.++ See :data:`_SEVERITY_MAP` for the policy. Anything unrecognised+ becomes ``medium`` — never ``critical``, to avoid auto-paging on+ upstream typos.+ """+ if not level:+ return "medium"+ return _SEVERITY_MAP.get(str(level).strip().lower(), "medium")+++# ─── Provenance ──────────────────────────────────────────────────────────────+++def _build_provenance(+ raw: dict[str, Any],+ *,+ source: str,+ source_commit: str | None,+ license_id: str,+ license_url: str,+ upstream_path: str | None,+ ocsf_ref: OcsfClassRef,+) -> dict[str, Any]:+ """Build the JSONB provenance block for a single imported rule.++ The shape is queried by:++ * the upcoming detection management UI (W-B3) — ``license`` is the+ filter for legal review,+ * re-import idempotency — ``(source, source_id)``,+ * the OCSF coverage heatmap (W-B3) — ``ocsf.class_uid``.++ Don't add fields here without a downstream consumer in mind; the+ column is JSONB and we'd rather keep the shape lean than attract+ drive-by additions.+ """+ return {+ "source": source,+ "source_id": str(raw.get("id") or "").strip(),+ "source_commit": (source_commit or "").strip() or None,+ "license": license_id,+ "license_url": license_url,+ "imported_at": datetime.now(UTC).isoformat(),+ "imported_by": "sigma_import_service",+ "upstream_path": upstream_path,+ "ocsf": ocsf_ref.to_dict(),+ "upstream_status": str(raw.get("status") or "").strip().lower() or None,+ }+++# ─── Conversion ──────────────────────────────────────────────────────────────+++@dataclass(slots=True)+class _NormalisedRule:+ """Internal carrier for the normalised view of a Sigma rule.++ Not exported — the public surface is :class:`SigmaImportResult`.+ """++ name: str+ description: str+ rule_body: str+ category: str+ severity: str+ status: str # "testing" | "disabled" (quarantine)+ enabled: bool # informational only; the column is ``status``+ mitre_tactics: list[str]+ mitre_techniques: list[str]+ tags: list[str]+ provenance: dict[str, Any]+++def _normalise_rule(+ raw: dict[str, Any],+ *,+ source: str,+ source_commit: str | None,+ license_id: str,+ license_url: str,+ upstream_path: str | None,+) -> _NormalisedRule | None:+ """Convert one Sigma rule dict into the AiSOC-shaped record.++ Returns ``None`` when the rule should be skipped entirely (deprecated+ upstream, missing detection block, etc.). Quarantined rules (Sigma+ ``experimental``/``test``) come back with ``status="disabled"`` so+ they land in the table but don't fire until an operator flips them.+ """+ upstream_id = str(raw.get("id") or "").strip()+ title = str(raw.get("title") or "").strip()+ if not upstream_id or not title:+ return None++ upstream_status = str(raw.get("status") or "").strip().lower()+ if upstream_status in _SIGMA_SKIP_STATUSES:+ return None++ detection = raw.get("detection")+ if not isinstance(detection, dict) or not detection:+ # No detection block ⇒ unusable; runtime engine would just NOOP.+ return None++ quarantined = upstream_status in _SIGMA_QUARANTINE_STATUSES++ description = str(raw.get("description") or title).strip()+ severity = _map_severity(raw.get("level"))+ raw_tags = raw.get("tags") or []+ techniques = _extract_mitre_techniques(raw_tags)+ tactics = _extract_mitre_tactics(raw_tags)++ logsource = raw.get("logsource") or {}+ category = _category_for(logsource)+ ocsf_ref = map_logsource_to_ocsf(logsource if isinstance(logsource, dict) else None)++ # We persist the full upstream rule as YAML in ``rule_body`` so the+ # runtime engine has everything pySigma might want (selections,+ # condition, falsepositives, tags). Deferring the YAML serialisation+ # to import time avoids a costly re-read at evaluation time.+ rule_body = _serialise_to_yaml(raw)++ provenance = _build_provenance(+ raw,+ source=source,+ source_commit=source_commit,+ license_id=license_id,+ license_url=license_url,+ upstream_path=upstream_path,+ ocsf_ref=ocsf_ref,+ )++ flat_tags = [t for t in raw_tags if isinstance(t, str)]++ return _NormalisedRule(+ name=title,+ description=description,+ rule_body=rule_body,+ category=category,+ severity=severity,+ # We never auto-promote community rules to ``enabled``. Native+ # rules ship enabled; imports default to ``testing`` (flips to+ # ``disabled`` for quarantine) so the operator opts in explicitly.+ status="disabled" if quarantined else "testing",+ enabled=not quarantined,+ mitre_tactics=tactics,+ mitre_techniques=techniques,+ tags=flat_tags,+ provenance=provenance,+ )+++def _serialise_to_yaml(raw: dict[str, Any]) -> str:+ """Round-trip the upstream Sigma rule to YAML for ``rule_body``.++ PyYAML is already a dependency of the rule engine, so importing it+ here doesn't widen the dependency surface. ``sort_keys=False`` so+ the output reads in the same order the Sigma maintainer wrote it+ in — much friendlier when a human inspects the row.+ """+ import yaml # local import: keeps module import cheap for non-import call sites++ return yaml.safe_dump(raw, sort_keys=False, allow_unicode=True)+++# ─── Persistence ─────────────────────────────────────────────────────────────+++async def _find_existing_rule(+ session: AsyncSession,+ *,+ source: str,+ source_id: str,+ tenant_id: uuid.UUID | None,+) -> DetectionRule | None:+ """Find an existing imported rule by ``(source, source_id, tenant)``.++ The provenance JSONB index makes this a single index scan — see the+ ``detection_rules_provenance_source_idx`` index in migration 036.+ """+ stmt = (+ select(DetectionRule)+ .where(+ DetectionRule.tenant_id.is_(None) if tenant_id is None else DetectionRule.tenant_id == tenant_id,+ DetectionRule.provenance["source"].astext == source,+ DetectionRule.provenance["source_id"].astext == source_id,+ )+ .limit(1)+ )+ result = await session.execute(stmt)+ return result.scalar_one_or_none()+++def _apply_normalised_to_rule(rule: DetectionRule, normalised: _NormalisedRule) -> None:+ """Copy the normalised view onto a (possibly existing) ORM row.++ Centralised so insert and update share the same field list — when+ we add a column to ``DetectionRule``, we add it once here and both+ paths pick it up.+ """+ rule.name = normalised.name+ rule.description = normalised.description+ rule.rule_language = "sigma"+ rule.rule_body = normalised.rule_body+ rule.category = normalised.category+ rule.severity = normalised.severity+ rule.status = normalised.status+ rule.mitre_tactics = list(normalised.mitre_tactics)+ rule.mitre_techniques = list(normalised.mitre_techniques)+ rule.tags = list(normalised.tags)+ rule.provenance = dict(normalised.provenance)+ # ``is_builtin`` flags content shipped by the platform. Imported+ # community content is *not* built-in — it's curated, but it can be+ # disabled or pruned by the operator at any time.+ rule.is_builtin = False+++# ─── Public API ──────────────────────────────────────────────────────────────+++async def import_sigma_rules(+ session: AsyncSession,+ rules: list[dict[str, Any]],+ *,+ source: str = "SigmaHQ/sigma",+ source_commit: str | None = None,+ license_id: str = "DRL-1.1",+ license_url: str = "https://github.com/SigmaHQ/Detection-Rule-License",+ tenant_id: uuid.UUID | None = None,+ upstream_paths: dict[str, str] | None = None,+) -> SigmaImportReport:+ """Import a batch of Sigma rules into the ``detection_rules`` table.++ The pipeline is intentionally batch-shaped — callers either ingest a+ full repo (CLI orchestrator) or a curated upload (future API). Both+ converge here. Idempotency is keyed on ``(source, source_id)``, so+ running the same input twice produces inserts the first time and+ updates (with the same field values) the second time.++ Args:+ session: an open async SQLAlchemy session. Caller owns commit/+ rollback. We flush after each rule so generated UUIDs are+ available for the report, but we don't commit — the caller+ decides whether to wrap many imports in a single transaction+ (typical for the CLI) or one each (typical for an API).+ rules: a list of parsed Sigma rule dicts (already YAML-loaded).+ Loading from disk is the caller's responsibility; this+ module stays I/O-light so it's testable without a tmpfs.+ source: provenance source identifier. Default+ ``SigmaHQ/sigma``; the CAR / Splunk / Chronicle importers+ pass their own value.+ source_commit: upstream commit SHA the rules came from. Stored+ short-form (7 chars) in provenance for audit.+ license_id: SPDX-ish license identifier for the upstream+ content. Default DRL-1.1 (Sigma's own license).+ license_url: link to the full license text. Surfaced in the+ management UI so operators can review attribution+ requirements per rule.+ tenant_id: optional tenant scope. ``None`` (default) means the+ rules are platform-wide and visible to every tenant. RLS+ policies on the table mean ``None`` rules never leak across+ tenants — they're explicitly platform content.+ upstream_paths: optional ``{source_id: upstream/path.yml}``+ map. Used by the CLI orchestrator to record where in the+ upstream repo a rule came from. The API import endpoint+ won't usually have this; the field is optional in+ provenance.++ Returns:+ :class:`SigmaImportReport` with per-rule outcomes and counts.++ Raises:+ :class:`SigmaImportError`: if the input shape is fundamentally+ wrong (e.g. ``rules`` is not a list). Per-rule problems are+ recorded in ``report.failures`` and don't raise.+ """+ if not isinstance(rules, list):+ raise SigmaImportError(f"`rules` must be a list, got {type(rules).__name__}")++ upstream_paths = upstream_paths or {}+ report = SigmaImportReport()++ for index, raw in enumerate(rules):+ if not isinstance(raw, dict):+ report.failures.append(+ {+ "index": index,+ "reason": "rule entry is not a dict",+ "type": type(raw).__name__,+ }+ )+ continue++ upstream_id = str(raw.get("id") or "").strip()+ title = str(raw.get("title") or "").strip()+ if not upstream_id:+ report.failures.append(+ {"index": index, "reason": "missing rule id", "title": title or None}+ )+ continue++ upstream_path = upstream_paths.get(upstream_id)++ try:+ normalised = _normalise_rule(+ raw,+ source=source,+ source_commit=source_commit,+ license_id=license_id,+ license_url=license_url,+ upstream_path=upstream_path,+ )+ except Exception as exc: # noqa: BLE001 -- per-rule failure isolation+ logger.exception("Sigma normalisation failed for %s", upstream_id)+ report.failures.append(+ {+ "index": index,+ "source_id": upstream_id,+ "title": title,+ "reason": f"normalisation error: {exc}",+ }+ )+ continue++ if normalised is None:+ # Skipped pre-DB: deprecated, no detection block, or+ # missing required fields. Surfaced as ``skipped`` rather+ # than ``failures`` because it's a deliberate filter, not+ # an error.+ report.skipped.append(+ SigmaImportResult(+ rule_id=uuid.uuid4(), # placeholder — never persisted+ source=source,+ source_id=upstream_id,+ title=title,+ action="skipped",+ reason=_skip_reason(raw),+ )+ )+ continue++ try:+ existing = await _find_existing_rule(+ session,+ source=source,+ source_id=upstream_id,+ tenant_id=tenant_id,+ )++ if existing is None:+ rule = DetectionRule(+ tenant_id=tenant_id,+ confidence=50,+ fp_rate=0.0,+ suppression_config={},+ threshold_config={},+ total_hits=0,+ version=1,+ )+ _apply_normalised_to_rule(rule, normalised)+ session.add(rule)+ await session.flush()+ report.inserted.append(+ SigmaImportResult(+ rule_id=rule.id,+ source=source,+ source_id=upstream_id,+ title=normalised.name,+ action="inserted",+ )+ )+ else:+ _apply_normalised_to_rule(existing, normalised)+ # Bump version on every update so the management UI can+ # show "this rule changed N times since you opted in".+ existing.version = (existing.version or 1) + 1+ await session.flush()+ report.updated.append(+ SigmaImportResult(+ rule_id=existing.id,+ source=source,+ source_id=upstream_id,+ title=normalised.name,+ action="updated",+ reason="re-import overwrote existing record",+ )+ )+ except Exception as exc: # noqa: BLE001 -- per-rule failure isolation+ logger.exception("Sigma persist failed for %s", upstream_id)+ report.failures.append(+ {+ "index": index,+ "source_id": upstream_id,+ "title": title,+ "reason": f"persist error: {exc}",+ }+ )+ continue++ logger.info(+ "Sigma import: %d inserted, %d updated, %d skipped, %d failed (source=%s commit=%s)",+ len(report.inserted),+ len(report.updated),+ len(report.skipped),+ len(report.failures),+ source,+ source_commit or "?",+ )+ return report+++def _skip_reason(raw: dict[str, Any]) -> str:+ """Best-effort human-readable reason for a skipped rule.++ Used purely for the import report; never branched on by callers.+ """+ status = str(raw.get("status") or "").strip().lower()+ if status in _SIGMA_SKIP_STATUSES:+ return f"upstream status={status}"+ detection = raw.get("detection")+ if not isinstance(detection, dict) or not detection:+ return "missing or empty detection block"+ if not str(raw.get("title") or "").strip():+ return "missing title"+ if not str(raw.get("id") or "").strip():+ return "missing id"+ return "did not pass normalisation"+++__all__ = [+ "SigmaImportError",+ "SigmaImportReport",+ "SigmaImportResult",+ "import_sigma_rules",+]diff --git a/services/api/migrations/036_detection_rule_provenance.sql b/services/api/migrations/036_detection_rule_provenance.sqlnew file mode 100644index 000000000..0f910e32e--- /dev/null+++ b/services/api/migrations/036_detection_rule_provenance.sql@@ -0,0 +1,70 @@+-- Migration 036: Bulk-import provenance for detection_rules (WS-B1)+--+-- The Sigma bulk-import pipeline (services/api/app/services/detections/sigma_import.py)+-- pulls hundreds of community rules per run. To make those imports honest+-- and re-runnable we need a structured ``provenance`` block on every rule+-- row — the same shape we already use on disk for offline imports+-- (tools/detection_import/common.py):+--+-- {+-- "source": "SigmaHQ/sigma",+-- "source_id": "<upstream uuid>",+-- "source_commit": "<short sha>",+-- "license": "DRL-1.1",+-- "license_url": "https://...",+-- "imported_at": "2026-05-09",+-- "imported_by": "sigma_importer",+-- "upstream_path": "rules/cloud/aws/aws_root_login.yml"+-- }+--+-- Why a dedicated column (and not just stuff it into ``tags``)?+-- 1. Idempotency. Re-running the importer must update an existing row+-- rather than create duplicates; the lookup key is+-- ``(provenance->>'source', provenance->>'source_id')``. We need+-- a real index for that query at corpus sizes ≥ 300 rules.+-- 2. Attribution. License + upstream path are not "tags"; they are+-- legal/audit metadata that must survive rule edits.+-- 3. Separation of concerns. ``tags`` already carries MITRE technique+-- IDs and category buckets used by the runtime engine; mixing+-- provenance into the same blob makes both harder to evolve.+--+-- We use ADD COLUMN IF NOT EXISTS so the migration tolerates two distinct+-- code paths through which the table reaches us:+-- * Dev installs that bootstrap the schema via SQLAlchemy's+-- ``Base.metadata.create_all`` (services/api/app/models/detection_rule.py)+-- — the column is created on first boot and this migration is a no-op.+-- * Legacy installs that originated from migration 001_init.sql+-- (which predates the rule_language/rule_body refactor and never+-- defined ``provenance``) — this migration adds the column without+-- touching the legacy rule_type/rule_content columns.++BEGIN;++-- 1. Add the column. JSONB instead of JSON: we will index it.+ALTER TABLE detection_rules+ ADD COLUMN IF NOT EXISTS provenance JSONB NOT NULL DEFAULT '{}'::jsonb;++-- 2. Idempotency lookup index.+-- Re-imports query by (source, source_id) to decide INSERT vs UPDATE.+-- We index the JSON path expressions directly so the planner can use+-- a single index scan rather than a sequential scan with a JSON cast.+-- NOT UNIQUE — a rule's source_id is unique per source, but the+-- business uniqueness is enforced by the importer (which we trust+-- far more than upstream contributors). A unique constraint here+-- would make a bad upstream rename break the entire import run; the+-- importer prefers to surface a warning and continue.+CREATE INDEX IF NOT EXISTS detection_rules_provenance_source_idx+ ON detection_rules ((provenance ->> 'source'), (provenance ->> 'source_id'));++-- 3. License rollup index. Operators who need to honour an upstream+-- license clause (DRL-1.1's attribution requirement, GPL's copyleft,+-- etc.) want a fast "list every imported rule under <license>" query.+-- Cheap to maintain — the license cardinality is single-digit.+CREATE INDEX IF NOT EXISTS detection_rules_provenance_license_idx+ ON detection_rules ((provenance ->> 'license'))+ WHERE provenance ? 'license';++COMMENT ON COLUMN detection_rules.provenance IS+ 'WS-B1: structured provenance block for imported rules. Empty {} for native AiSOC rules. Used by services/api/app/services/detections/sigma_import.py for idempotent re-imports.';++COMMIT;diff --git a/services/api/tests/services/__init__.py b/services/api/tests/services/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/api/tests/services/detections/__init__.py b/services/api/tests/services/detections/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/services/api/tests/services/detections/test_ocsf_mapping.py b/services/api/tests/services/detections/test_ocsf_mapping.pynew file mode 100644index 000000000..3d3e61c98--- /dev/null+++ b/services/api/tests/services/detections/test_ocsf_mapping.py@@ -0,0 +1,110 @@+"""Tests for the Sigma → OCSF logsource mapper.++The mapper is the smaller of the two WS-B1 modules — pure functions,+no I/O, no DB. The tests below pin the *contract* the import service+relies on:++* known logsource buckets resolve to the expected OCSF class+* unknown / empty logsource always resolves to DETECTION_FINDING+* the precedence rules (product+category > product+service > category)+ hold so a malformed cloud rule doesn't fall through to an endpoint+ category by accident.+"""++from __future__ import annotations++import pytest+from app.services.detections.ocsf_mapping import (+ OcsfClassUid,+ map_logsource_to_ocsf,+)+++class TestProductCategoryMapping:+ """Most Sigma rules carry product + category; this is the hot path."""++ def test_windows_process_creation_maps_to_process_activity(self) -> None:+ ref = map_logsource_to_ocsf({"product": "windows", "category": "process_creation"})+ assert ref.class_uid == OcsfClassUid.PROCESS_ACTIVITY+ assert ref.class_name == "Process Activity"++ def test_linux_file_event_maps_to_file_activity(self) -> None:+ ref = map_logsource_to_ocsf({"product": "linux", "category": "file_event"})+ assert ref.class_uid == OcsfClassUid.FILE_ACTIVITY++ def test_windows_dns_query_maps_to_dns_activity(self) -> None:+ ref = map_logsource_to_ocsf({"product": "windows", "category": "dns_query"})+ assert ref.class_uid == OcsfClassUid.DNS_ACTIVITY++ def test_case_insensitive(self) -> None:+ ref = map_logsource_to_ocsf({"product": "WINDOWS", "category": "PROCESS_CREATION"})+ assert ref.class_uid == OcsfClassUid.PROCESS_ACTIVITY+++class TestProductServiceMapping:+ """Cloud / SaaS rules typically use product + service (no category)."""++ def test_aws_cloudtrail_maps_to_security_finding(self) -> None:+ ref = map_logsource_to_ocsf({"product": "aws", "service": "cloudtrail"})+ assert ref.class_uid == OcsfClassUid.SECURITY_FINDING++ def test_azure_signinlogs_maps_to_authentication(self) -> None:+ ref = map_logsource_to_ocsf({"product": "azure", "service": "signinlogs"})+ assert ref.class_uid == OcsfClassUid.AUTHENTICATION++ def test_okta_maps_to_authentication(self) -> None:+ ref = map_logsource_to_ocsf({"product": "okta", "service": "okta"})+ assert ref.class_uid == OcsfClassUid.AUTHENTICATION++ def test_windows_security_maps_to_authentication(self) -> None:+ # 4624/4625/4672 are auth events — important they don't fall+ # through to PROCESS_ACTIVITY by accident.+ ref = map_logsource_to_ocsf({"product": "windows", "service": "security"})+ assert ref.class_uid == OcsfClassUid.AUTHENTICATION+++class TestCategoryFallback:+ """When product is missing but category is descriptive enough."""++ def test_proxy_maps_to_http_activity(self) -> None:+ ref = map_logsource_to_ocsf({"category": "proxy"})+ assert ref.class_uid == OcsfClassUid.HTTP_ACTIVITY++ def test_authentication_maps_to_authentication(self) -> None:+ ref = map_logsource_to_ocsf({"category": "authentication"})+ assert ref.class_uid == OcsfClassUid.AUTHENTICATION+++class TestPrecedence:+ """Product+category beats product+service beats category alone."""++ def test_product_category_wins_over_service(self) -> None:+ # product+category=PROCESS_ACTIVITY; product+service=AUTHENTICATION+ # The (product, category) lookup should win.+ ref = map_logsource_to_ocsf(+ {"product": "windows", "category": "process_creation", "service": "security"}+ )+ assert ref.class_uid == OcsfClassUid.PROCESS_ACTIVITY+++class TestFallback:+ @pytest.mark.parametrize("logsource", [None, {}, {"product": "weirdvendor"}])+ def test_unknown_logsource_falls_back_to_detection_finding(+ self, logsource: dict | None+ ) -> None:+ ref = map_logsource_to_ocsf(logsource)+ assert ref.class_uid == OcsfClassUid.DETECTION_FINDING+ assert ref.class_name == "Detection Finding"++ def test_non_dict_input_does_not_raise(self) -> None:+ # Sigma in the wild has produced strings here. We must not+ # crash an entire bulk import on one malformed rule.+ assert map_logsource_to_ocsf("garbage").class_uid == OcsfClassUid.DETECTION_FINDING # type: ignore[arg-type]+++class TestSerialisation:+ def test_to_dict_shape(self) -> None:+ ref = map_logsource_to_ocsf({"product": "windows", "category": "process_creation"})+ d = ref.to_dict()+ assert set(d.keys()) == {"class_uid", "class_name", "category_uid", "category_name"}+ assert d["class_uid"] == OcsfClassUid.PROCESS_ACTIVITYdiff --git a/services/api/tests/services/detections/test_sigma_import.py b/services/api/tests/services/detections/test_sigma_import.pynew file mode 100644index 000000000..20583ec99--- /dev/null+++ b/services/api/tests/services/detections/test_sigma_import.py@@ -0,0 +1,389 @@+"""Tests for the Sigma bulk-import service (WS-B1).++Two layers of coverage:++1. **Pure-function tests** — exercise the normalisation helpers+ (MITRE extraction, severity mapping, category bucketing,+ provenance shape) without touching the DB. These are the+ contract the orchestrator and API endpoint rely on.++2. **End-to-end pipeline test** — runs the full ``import_sigma_rules``+ call against an in-memory SQLite database. Verifies idempotency+ (re-import becomes update, not duplicate), partial-failure+ isolation (one bad rule doesn't sink the batch), and report+ shape.++We deliberately test against SQLite rather than the real Postgres+JSONB index because the *behavioural* contract is what matters for+this layer — the index is verified by the migration's existence and+the index's syntax (covered separately when migrations are applied+in the integration env).+"""++from __future__ import annotations++import uuid+from typing import Any++import pytest+import pytest_asyncio+from app.models.detection_rule import DetectionRule+from app.services.detections import sigma_import as si+from app.services.detections.ocsf_mapping import OcsfClassUid+from sqlalchemy import select+from sqlalchemy.dialects.postgresql import JSONB, UUID+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine+from sqlalchemy.ext.compiler import compiles+from sqlalchemy.orm import sessionmaker+++# ─── SQLite-friendly compilation overrides for PG types ─────────────────────+#+# The model uses Postgres-only types (``JSONB``, ``UUID``) for production+# fidelity. For these tests we run against in-memory SQLite, so we register+# fallback DDL compilation hooks: JSONB → TEXT (we serialise JSON in the+# Python layer), UUID → CHAR(36). This is enough fidelity to exercise the+# persistence path; the JSONB index in migration 036 is a Postgres-only+# optimisation and not behavioural.+#+# These hooks are installed at module import time and are idempotent —+# pytest can re-import this file safely.+++@compiles(JSONB, "sqlite")+def _compile_jsonb_sqlite(_type_, _compiler_, **_kw_):+ return "TEXT"+++@compiles(UUID, "sqlite")+def _compile_uuid_sqlite(_type_, _compiler_, **_kw_):+ return "CHAR(36)"+++# ─── Fixtures ────────────────────────────────────────────────────────────────+++@pytest_asyncio.fixture+async def session() -> AsyncSession:+ """In-memory SQLite session with the detection_rules schema.++ The ``@compiles`` overrides above let SQLAlchemy emit valid SQLite+ DDL for the PG-specific column types in :class:`DetectionRule`.+ """+ engine = create_async_engine("sqlite+aiosqlite:///:memory:", future=True)+ async with engine.begin() as conn:+ # Only create the detection_rules table — we don't need the+ # rest of the schema, and creating everything pulls in models+ # (alerts, etc.) that have FK constraints on tenants.+ await conn.run_sync(lambda sync_conn: DetectionRule.__table__.create(sync_conn))++ Session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) # type: ignore[call-overload]+ async with Session() as s:+ yield s+ await engine.dispose()+++def _stable_sigma_rule(+ *,+ rule_id: str = "11111111-2222-3333-4444-555555555555",+ title: str = "Suspicious PowerShell Encoded Command",+ status: str = "stable",+ level: str = "high",+ product: str = "windows",+ category: str = "process_creation",+) -> dict[str, Any]:+ """Build a minimal but realistic Sigma rule dict."""+ return {+ "title": title,+ "id": rule_id,+ "status": status,+ "description": "Detects encoded PowerShell command-line invocations.",+ "references": ["https://attack.mitre.org/techniques/T1059/001/"],+ "author": "Test Suite",+ "date": "2024/01/01",+ "logsource": {"product": product, "category": category},+ "detection": {+ "selection": {+ "Image|endswith": "\\powershell.exe",+ "CommandLine|contains": " -EncodedCommand ",+ },+ "condition": "selection",+ },+ "level": level,+ "tags": [+ "attack.execution",+ "attack.t1059.001",+ "attack.defense_evasion",+ "attack.t1027",+ ],+ "falsepositives": ["Legitimate admin scripts"],+ }+++# ─── Pure-function tests ─────────────────────────────────────────────────────+++class TestExtractMitreTechniques:+ def test_extracts_techniques_and_subtechniques(self) -> None:+ techniques = si._extract_mitre_techniques(+ ["attack.t1078", "attack.t1078.004", "attack.execution"]+ )+ # Tactic tag (``attack.execution``) is not a technique and is+ # skipped. Sub-technique stays as-is, parent stays as-is.+ assert techniques == ["T1078", "T1078.004"]++ def test_dedupes_preserving_order(self) -> None:+ techniques = si._extract_mitre_techniques(+ ["attack.t1078", "attack.t1078", "attack.t1027"]+ )+ assert techniques == ["T1078", "T1027"]++ def test_ignores_garbage_tags(self) -> None:+ techniques = si._extract_mitre_techniques(+ ["attack.tasdf", "attack.", "not-a-tag", 42, None] # type: ignore[list-item]+ )+ assert techniques == []++ def test_empty_input_returns_empty_list(self) -> None:+ assert si._extract_mitre_techniques(None) == []+ assert si._extract_mitre_techniques([]) == []+++class TestExtractMitreTactics:+ def test_recognises_canonical_tactics(self) -> None:+ tactics = si._extract_mitre_tactics(+ ["attack.execution", "attack.persistence", "attack.t1078"]+ )+ # Technique tags are ignored here (handled by the technique+ # extractor); tactic tags become TA-codes.+ assert tactics == ["TA0002", "TA0003"]++ def test_ignores_unknown_tactic_names(self) -> None:+ tactics = si._extract_mitre_tactics(["attack.g0007", "attack.s0001"])+ assert tactics == []+++class TestSeverityMap:+ @pytest.mark.parametrize(+ "level,expected",+ [+ ("low", "low"),+ ("informational", "low"),+ ("medium", "medium"),+ ("high", "high"),+ ("critical", "critical"),+ ("garbage", "medium"), # unknown → safe medium, never critical+ (None, "medium"),+ ("", "medium"),+ ],+ )+ def test_severity_normalisation(self, level: Any, expected: str) -> None:+ assert si._map_severity(level) == expected+++class TestCategoryFor:+ @pytest.mark.parametrize(+ "logsource,expected",+ [+ ({"product": "windows"}, "endpoint"),+ ({"product": "aws"}, "cloud"),+ ({"product": "okta"}, "identity"),+ ({"category": "proxy"}, "network"),+ ({"category": "webserver"}, "application"),+ ({}, "endpoint"),+ (None, "endpoint"),+ ],+ )+ def test_category_bucket(self, logsource: dict | None, expected: str) -> None:+ assert si._category_for(logsource) == expected+++class TestNormaliseRule:+ def test_happy_path_produces_full_record(self) -> None:+ rule = _stable_sigma_rule()+ normalised = si._normalise_rule(+ rule,+ source="SigmaHQ/sigma",+ source_commit="abcdef1234567890",+ license_id="DRL-1.1",+ license_url="https://example/license",+ upstream_path="rules/windows/process_creation/proc_creation_win_powershell_encoded.yml",+ )++ assert normalised is not None+ assert normalised.name == "Suspicious PowerShell Encoded Command"+ assert normalised.severity == "high"+ assert normalised.category == "endpoint"+ assert normalised.status == "testing" # stable upstream → testing here+ assert normalised.mitre_techniques == ["T1059.001", "T1027"]+ assert normalised.mitre_tactics == ["TA0002", "TA0005"]++ # Provenance shape — this is the public contract for re-import+ # idempotency and the WS-B3 management UI.+ prov = normalised.provenance+ assert prov["source"] == "SigmaHQ/sigma"+ assert prov["source_id"] == rule["id"]+ assert prov["license"] == "DRL-1.1"+ assert prov["license_url"] == "https://example/license"+ assert prov["imported_by"] == "sigma_import_service"+ assert prov["upstream_status"] == "stable"+ assert prov["upstream_path"].startswith("rules/")+ assert prov["ocsf"]["class_uid"] == OcsfClassUid.PROCESS_ACTIVITY++ def test_experimental_status_quarantines_rule(self) -> None:+ rule = _stable_sigma_rule(status="experimental")+ normalised = si._normalise_rule(+ rule,+ source="SigmaHQ/sigma",+ source_commit="abc",+ license_id="DRL-1.1",+ license_url="https://x",+ upstream_path=None,+ )+ assert normalised is not None+ # Quarantined rules land in the table but disabled — the+ # operator must opt them in.+ assert normalised.status == "disabled"+ assert normalised.enabled is False++ @pytest.mark.parametrize("status", ["deprecated", "unsupported"])+ def test_skipped_statuses_return_none(self, status: str) -> None:+ rule = _stable_sigma_rule(status=status)+ normalised = si._normalise_rule(+ rule,+ source="SigmaHQ/sigma",+ source_commit="abc",+ license_id="DRL-1.1",+ license_url="https://x",+ upstream_path=None,+ )+ assert normalised is None++ def test_missing_detection_block_skips(self) -> None:+ rule = _stable_sigma_rule()+ rule.pop("detection")+ normalised = si._normalise_rule(+ rule,+ source="SigmaHQ/sigma",+ source_commit="abc",+ license_id="DRL-1.1",+ license_url="https://x",+ upstream_path=None,+ )+ assert normalised is None+++# ─── End-to-end pipeline tests ───────────────────────────────────────────────+++class TestImportSigmaRulesPipeline:+ @pytest.mark.asyncio+ async def test_inserts_new_rules(self, session: AsyncSession) -> None:+ rules = [_stable_sigma_rule(rule_id=f"00000000-0000-0000-0000-00000000000{i}") for i in range(3)]+ report = await si.import_sigma_rules(session, rules, source="SigmaHQ/sigma")++ assert report.total_seen == 3+ assert len(report.inserted) == 3+ assert len(report.updated) == 0+ assert len(report.failures) == 0++ result = await session.execute(select(DetectionRule))+ rows = list(result.scalars().all())+ assert len(rows) == 3+ # Provenance is populated for every imported rule.+ for row in rows:+ assert row.provenance["source"] == "SigmaHQ/sigma"+ assert row.rule_language == "sigma"+ assert row.is_builtin is False++ @pytest.mark.asyncio+ async def test_reimport_is_idempotent(self, session: AsyncSession) -> None:+ rules = [_stable_sigma_rule()]+ # First run inserts.+ first = await si.import_sigma_rules(session, rules)+ assert len(first.inserted) == 1+ first_id = first.inserted[0].rule_id++ # Second run with the same input should update, not insert.+ second = await si.import_sigma_rules(session, rules)+ assert len(second.inserted) == 0+ assert len(second.updated) == 1+ assert second.updated[0].rule_id == first_id++ # Only one row in the table.+ result = await session.execute(select(DetectionRule))+ assert len(list(result.scalars().all())) == 1++ @pytest.mark.asyncio+ async def test_update_bumps_version(self, session: AsyncSession) -> None:+ rules = [_stable_sigma_rule()]+ await si.import_sigma_rules(session, rules)+ await si.import_sigma_rules(session, rules)++ result = await session.execute(select(DetectionRule))+ row = result.scalar_one()+ # First import = v1; second import bumps to 2.+ assert row.version == 2++ @pytest.mark.asyncio+ async def test_partial_failure_isolation(self, session: AsyncSession) -> None:+ """One malformed rule must not sink the batch."""+ good = _stable_sigma_rule(rule_id="aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")+ bad_no_id: dict[str, Any] = {"title": "no id here", "detection": {"sel": {"a": "b"}, "condition": "sel"}}+ bad_not_dict = "not even a dict"++ report = await si.import_sigma_rules(+ session, [good, bad_no_id, bad_not_dict] # type: ignore[list-item]+ )+ assert len(report.inserted) == 1+ assert len(report.failures) == 2+ # Failures carry a reason string for the operator.+ assert all(isinstance(f.get("reason"), str) for f in report.failures)++ @pytest.mark.asyncio+ async def test_skipped_rules_appear_in_report(self, session: AsyncSession) -> None:+ deprecated = _stable_sigma_rule(status="deprecated")+ report = await si.import_sigma_rules(session, [deprecated])+ assert len(report.skipped) == 1+ assert "deprecated" in (report.skipped[0].reason or "")+ assert report.total_persisted == 0++ @pytest.mark.asyncio+ async def test_report_to_dict_is_json_safe(self, session: AsyncSession) -> None:+ report = await si.import_sigma_rules(session, [_stable_sigma_rule()])+ out = report.to_dict()+ # API endpoint will serialise this directly; make sure shape+ # matches what the OpenAPI schema will document.+ assert out["summary"] == {+ "total_seen": 1,+ "inserted": 1,+ "updated": 0,+ "skipped": 0,+ "failures": 0,+ }+ assert out["inserted"][0]["action"] == "inserted"+ assert isinstance(out["inserted"][0]["rule_id"], str)++ @pytest.mark.asyncio+ async def test_non_list_input_raises(self, session: AsyncSession) -> None:+ with pytest.raises(si.SigmaImportError):+ await si.import_sigma_rules(session, "not a list") # type: ignore[arg-type]++ @pytest.mark.asyncio+ async def test_tenant_scoped_rules_do_not_clash(self, session: AsyncSession) -> None:+ """Re-importing the same upstream rule for two different tenants+ produces two rows, not one. The provenance index includes the+ ``(source, source_id)`` lookup but the existence check is+ further scoped by ``tenant_id``."""+ rules = [_stable_sigma_rule()]+ tenant_a = uuid.uuid4()+ tenant_b = uuid.uuid4()++ await si.import_sigma_rules(session, rules, tenant_id=tenant_a)+ await si.import_sigma_rules(session, rules, tenant_id=tenant_b)++ result = await session.execute(select(DetectionRule))+ rows = list(result.scalars().all())+ assert len(rows) == 2+ tenant_ids = {r.tenant_id for r in rows}+ assert tenant_ids == {tenant_a, tenant_b}