Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

fix(pipeline): canonical OCSF profiles, deterministic event_id, EDR containment (Wave 0) (#533)

Beenu Arora9199373b2876
diff --git a/docs/connectors/conformance-matrix.md b/docs/connectors/conformance-matrix.md
index 4ac43864e..2e91f164c 100644
--- a/docs/connectors/conformance-matrix.md
+++ b/docs/connectors/conformance-matrix.md
@@ -27,7 +27,7 @@
| cloudflare | saas | 2 | 1 | 1 | ✅ | ✅ | ✅ |
| cloudflare_zt | network | 4 | 1 | 3 | ✅ | ✅ | ✅ |
| confluence_audit | saas | 3 | 1 | 2 | ✅ | ✅ | ✅ |
-| cortex_xdr | edr | 3 | 2 | 1 | ✅ | ✅ | ✅ |
+| cortex_xdr | edr | 3 | 2 | 3 | ✅ | ✅ | ✅ |
| cortex_xsiam | siem | 3 | 2 | 5 | ✅ | ✅ | ✅ |
| crowdstrike | edr | 3 | 1 | 6 | ✅ | ✅ | ✅ |
| datadog | siem | 5 | 2 | 4 | ✅ | ✅ | ✅ |
@@ -66,7 +66,7 @@
| rapid7_insightidr | siem | 2 | 1 | 4 | ✅ | ✅ | ✅ |
| salesforce | saas | 4 | 2 | 4 | ✅ | ✅ | ✅ |
| securonix | siem | 3 | 1 | 2 | ✅ | ✅ | ✅ |
-| sentinelone | edr | 3 | 1 | 1 | ✅ | ✅ | ✅ |
+| sentinelone | edr | 3 | 1 | 4 | ✅ | ✅ | ✅ |
| servicenow | saas | 3 | 1 | 3 | ✅ | ✅ | ✅ |
| slack_audit | saas | 1 | 1 | 3 | ✅ | ✅ | ✅ |
| snowflake | saas | 5 | 1 | 4 | ✅ | ✅ | ✅ |
diff --git a/services/actions/app/clients/cortex_xdr_client.py b/services/actions/app/clients/cortex_xdr_client.py
new file mode 100644
index 000000000..46bcc6832
--- /dev/null
+++ b/services/actions/app/clients/cortex_xdr_client.py
@@ -0,0 +1,123 @@
+"""Cortex XDR client for the AiSOC action executor.
+
+Wraps the Cortex XDR public REST API
+(``https://<fqdn>/public_api/v1/``) for the endpoint containment actions the
+response layer needs: network-isolate a host and lift that isolation.
+
+Credentials are passed via :class:`ActionRequest.parameters`:
+
+* ``cortex_api_key_id`` — the API key *id* (the integer shown next to the key
+ in "Settings -> API Keys").
+* ``cortex_api_key`` — the API key secret. Cortex XDR "Advanced" keys sign
+ each request with a per-call nonce + timestamp (see :meth:`_headers`), which
+ is what this client implements.
+* ``cortex_fqdn`` — the tenant API FQDN
+ (e.g. ``api-example.xdr.us.paloaltonetworks.com``).
+
+API surface
+-----------
+
+We mirror the EDR client method shape (``contain_host`` / ``lift_containment``)
+so :class:`IsolateHostExecutor` can dispatch through a uniform interface. Both
+verbs first resolve ``hostname -> endpoint_id`` via ``get_endpoint`` because the
+isolate/unisolate endpoints act on an endpoint id, not a hostname.
+
+Design notes
+------------
+
+* Cortex XDR "Advanced" API keys require the same nonce/timestamp/SHA-256 auth
+ the pull connector uses, so this client is self-contained and needs no OAuth
+ refresh flow.
+* All HTTP traffic uses a 30s timeout; the isolate endpoint schedules the action
+ asynchronously on the endpoint, so a 200 means "accepted", not "isolated".
+"""
+
+from __future__ import annotations
+
+import hashlib
+import secrets
+import string
+from datetime import UTC, datetime
+from typing import Any
+
+import httpx
+import structlog
+
+logger = structlog.get_logger()
+
+
+class CortexXdrClient:
+ """Thin async wrapper over the Cortex XDR public API."""
+
+ def __init__(self, *, api_key_id: str, api_key: str, fqdn: str) -> None:
+ self._api_key_id = str(api_key_id)
+ self._api_key = api_key
+ self._fqdn = fqdn.rstrip("/")
+
+ def _headers(self) -> dict[str, str]:
+ # Cortex XDR "Advanced" auth: the vendor protocol signs each request by
+ # SHA-256'ing (api_key + nonce + timestamp). This is a per-request
+ # signature over an ephemeral 64-char nonce — NOT password-at-rest
+ # hashing, so a slow password hash (bcrypt/argon2) does not apply.
+ # SHA-256 is mandated by the Cortex XDR API; mirrors CortexXDRConnector.
+ nonce = "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(64))
+ timestamp = str(int(datetime.now(UTC).timestamp()) * 1000)
+ auth_string = f"{self._api_key}{nonce}{timestamp}"
+ signature = hashlib.sha256(auth_string.encode()).hexdigest() # lgtm[py/weak-sensitive-data-hashing]
+ return {
+ "x-xdr-auth-id": self._api_key_id,
+ "x-xdr-nonce": nonce,
+ "x-xdr-timestamp": timestamp,
+ "Authorization": signature,
+ "Content-Type": "application/json",
+ }
+
+ async def _resolve_endpoint_id(self, client: httpx.AsyncClient, hostname: str) -> str:
+ resp = await client.post(
+ f"https://{self._fqdn}/public_api/v1/endpoints/get_endpoint/",
+ headers=self._headers(),
+ json={"request_data": {"filters": [{"field": "hostname", "operator": "in", "value": [hostname]}]}},
+ )
+ resp.raise_for_status()
+ endpoints = resp.json().get("reply", {}).get("endpoints", [])
+ if not endpoints:
+ raise ValueError(f"No Cortex XDR endpoint found for hostname: {hostname}")
+ return str(endpoints[0]["endpoint_id"])
+
+ async def contain_host(self, hostname: str) -> dict[str, Any]:
+ """Network-isolate an endpoint from everything but Cortex XDR."""
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ endpoint_id = await self._resolve_endpoint_id(client, hostname)
+ resp = await client.post(
+ f"https://{self._fqdn}/public_api/v1/endpoints/isolate",
+ headers=self._headers(),
+ json={"request_data": {"endpoint_id": endpoint_id}},
+ )
+ resp.raise_for_status()
+ logger.info("cortex_xdr.contain_host.success", endpoint_id=endpoint_id, hostname=hostname)
+ return {
+ "success": True,
+ "action": "contain_host",
+ "endpoint_id": endpoint_id,
+ "hostname": hostname,
+ "action_id": resp.json().get("reply", {}).get("action_id"),
+ }
+
+ async def lift_containment(self, hostname: str) -> dict[str, Any]:
+ """Reconnect a previously isolated endpoint."""
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ endpoint_id = await self._resolve_endpoint_id(client, hostname)
+ resp = await client.post(
+ f"https://{self._fqdn}/public_api/v1/endpoints/unisolate",
+ headers=self._headers(),
+ json={"request_data": {"endpoint_id": endpoint_id}},
+ )
+ resp.raise_for_status()
+ logger.info("cortex_xdr.lift_containment.success", endpoint_id=endpoint_id, hostname=hostname)
+ return {
+ "success": True,
+ "action": "lift_containment",
+ "endpoint_id": endpoint_id,
+ "hostname": hostname,
+ "action_id": resp.json().get("reply", {}).get("action_id"),
+ }
diff --git a/services/actions/app/executors/endpoint.py b/services/actions/app/executors/endpoint.py
index adef509f3..b597714bf 100644
--- a/services/actions/app/executors/endpoint.py
+++ b/services/actions/app/executors/endpoint.py
@@ -34,6 +34,7 @@ from datetime import datetime
import structlog
+from app.clients.cortex_xdr_client import CortexXdrClient
from app.clients.crowdstrike_rtr import CrowdStrikeRTRClient
from app.clients.defender_client import DefenderClient
from app.clients.sentinelone_client import SentinelOneClient
@@ -81,6 +82,20 @@ def _s1_client(params: dict) -> SentinelOneClient | None:
return SentinelOneClient(console_url=console_url, api_token=api_token)
+def _cortex_client(params: dict) -> CortexXdrClient | None:
+ """Build a Cortex XDR client from request-scoped credentials.
+
+ Returns ``None`` when any field is missing so the executor falls through to
+ the next vendor / simulation.
+ """
+ api_key_id = params.get("cortex_api_key_id")
+ api_key = params.get("cortex_api_key")
+ fqdn = params.get("cortex_fqdn")
+ if not (api_key_id and api_key and fqdn):
+ return None
+ return CortexXdrClient(api_key_id=api_key_id, api_key=api_key, fqdn=fqdn)
+
+
async def _cs_contain_host_by_hostname(cs: CrowdStrikeRTRClient, hostname: str) -> dict:
"""Resolve hostname → device_id, then containment.
@@ -184,6 +199,30 @@ class IsolateHostExecutor(BaseExecutor):
completed_at=datetime.utcnow(),
)
+ # Cortex XDR fallback — same blast-radius + rollback contract so the
+ # rollback router can route ``vendor: cortex_xdr`` to ``lift_containment``.
+ cortex = _cortex_client(request.parameters)
+ if cortex:
+ try:
+ result = await cortex.contain_host(hostname)
+ return ActionResult(
+ action_id=request.id,
+ status=ActionStatus.COMPLETED,
+ blast_radius=BlastRadius.HIGH,
+ output=result,
+ rollback_data={"hostname": hostname, "vendor": "cortex_xdr"},
+ completed_at=datetime.utcnow(),
+ )
+ except Exception as exc:
+ logger.error("isolate_host.cortex_xdr.failed", hostname=hostname, error=str(exc))
+ return ActionResult(
+ action_id=request.id,
+ status=ActionStatus.FAILED,
+ blast_radius=BlastRadius.HIGH,
+ error=str(exc),
+ completed_at=datetime.utcnow(),
+ )
+
logger.warning(
"isolate_host.simulation",
hostname=hostname,
@@ -200,8 +239,9 @@ class IsolateHostExecutor(BaseExecutor):
"isolation_id": f"SIM-ISO-{hostname}",
"note": (
"Simulation mode — provide cs_client_id/cs_client_secret, "
- "mde_tenant_id/mde_client_id/mde_client_secret, or "
- "s1_console_url/s1_api_token to enable live execution." + _SIM_FUNNEL_CTA
+ "mde_tenant_id/mde_client_id/mde_client_secret, "
+ "s1_console_url/s1_api_token, or "
+ "cortex_api_key_id/cortex_api_key/cortex_fqdn to enable live execution." + _SIM_FUNNEL_CTA
),
},
rollback_data={"hostname": hostname},
diff --git a/services/actions/tests/test_cortex_xdr_client.py b/services/actions/tests/test_cortex_xdr_client.py
new file mode 100644
index 000000000..7faeea30c
--- /dev/null
+++ b/services/actions/tests/test_cortex_xdr_client.py
@@ -0,0 +1,70 @@
+"""Wave 0 — tests for :class:`CortexXdrClient`.
+
+Locks the wire shapes (hostname -> endpoint_id resolution, isolate/unisolate
+endpoints, Advanced-auth headers) so a Cortex XDR API drift breaks the test
+before a customer.
+"""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+import respx
+from app.clients.cortex_xdr_client import CortexXdrClient
+
+FQDN = "api-example.xdr.us.paloaltonetworks.com"
+
+
+def _client() -> CortexXdrClient:
+ return CortexXdrClient(api_key_id="42", api_key="secret", fqdn=FQDN)
+
+
+async def test_contain_host_resolves_endpoint_and_isolates() -> None:
+ captured: dict[str, object] = {}
+
+ def resolve(request: httpx.Request) -> httpx.Response:
+ captured["auth_id"] = request.headers.get("x-xdr-auth-id")
+ captured["has_nonce"] = bool(request.headers.get("x-xdr-nonce"))
+ return httpx.Response(200, json={"reply": {"endpoints": [{"endpoint_id": "ep-7"}]}})
+
+ def isolate(request: httpx.Request) -> httpx.Response:
+ captured["isolate_body"] = request.content.decode()
+ return httpx.Response(200, json={"reply": {"action_id": "act-1"}})
+
+ respx.post(f"https://{FQDN}/public_api/v1/endpoints/get_endpoint/").mock(side_effect=resolve)
+ respx.post(f"https://{FQDN}/public_api/v1/endpoints/isolate").mock(side_effect=isolate)
+
+ out = await _client().contain_host("ws-9")
+
+ assert out["success"] is True
+ assert out["endpoint_id"] == "ep-7"
+ assert out["action_id"] == "act-1"
+ assert captured["auth_id"] == "42"
+ assert captured["has_nonce"] is True
+ assert "ep-7" in str(captured["isolate_body"])
+
+
+async def test_contain_host_raises_when_no_endpoint() -> None:
+ respx.post(f"https://{FQDN}/public_api/v1/endpoints/get_endpoint/").mock(
+ return_value=httpx.Response(200, json={"reply": {"endpoints": []}})
+ )
+ with pytest.raises(ValueError, match="No Cortex XDR endpoint"):
+ await _client().contain_host("ghost")
+
+
+async def test_lift_containment_calls_unisolate() -> None:
+ respx.post(f"https://{FQDN}/public_api/v1/endpoints/get_endpoint/").mock(
+ return_value=httpx.Response(200, json={"reply": {"endpoints": [{"endpoint_id": "ep-7"}]}})
+ )
+ route = respx.post(f"https://{FQDN}/public_api/v1/endpoints/unisolate").mock(
+ return_value=httpx.Response(200, json={"reply": {"action_id": "act-2"}})
+ )
+ out = await _client().lift_containment("ws-9")
+ assert route.called
+ assert out["action"] == "lift_containment"
diff --git a/services/api/clickhouse/001_init.sql b/services/api/clickhouse/001_init.sql
index 2126b5e75..33c5d1aec 100644
--- a/services/api/clickhouse/001_init.sql
+++ b/services/api/clickhouse/001_init.sql
@@ -33,9 +33,16 @@ CREATE TABLE IF NOT EXISTS aisoc.raw_events (
mitre_techniques Array(String),
mitre_tactics Array(String),
iocs Array(String)
-) ENGINE = MergeTree()
+)
+-- ReplacingMergeTree collapses rows sharing the ORDER BY key, keeping the row
+-- with the greatest ingest_time. Ingest now stamps a replay-stable event_id
+-- (derived from tenant + connector + vendor id), so overlapping connector
+-- polls / backfills / Kafka replays of the same event dedup on merge instead of
+-- accumulating duplicate lake rows. Queries needing exact-once before a merge
+-- can still use `FINAL` or `LIMIT 1 BY event_id`.
+ENGINE = ReplacingMergeTree(ingest_time)
PARTITION BY (toYYYYMM(event_time), tenant_id)
-ORDER BY (tenant_id, event_time, class_uid)
+ORDER BY (tenant_id, event_time, class_uid, event_id)
TTL toDateTime(event_time) + INTERVAL 90 DAY
SETTINGS index_granularity = 8192;
diff --git a/services/connectors/app/connectors/cortex_xdr.py b/services/connectors/app/connectors/cortex_xdr.py
index 8dbd39a00..63a2036e9 100644
--- a/services/connectors/app/connectors/cortex_xdr.py
+++ b/services/connectors/app/connectors/cortex_xdr.py
@@ -58,10 +58,13 @@ class CortexXDRConnector(BaseConnector):
@classmethod
def capabilities(cls) -> tuple[Capability, ...]:
- # Today the runtime only implements ``fetch_alerts`` (incidents).
- # ``ISOLATE_HOST`` / ``KILL_PROCESS`` belong here once we wire the
- # Cortex XDR Endpoints API.
- return (Capability.PULL_ALERTS,)
+ # Endpoint isolation is executed by services/actions CortexXdrClient
+ # against the Cortex XDR Endpoints API (isolate / unisolate).
+ return (
+ Capability.PULL_ALERTS,
+ Capability.ISOLATE_HOST,
+ Capability.UNISOLATE_HOST,
+ )
def __init__(self, api_key_id: str, api_key: str, fqdn: str):
self._api_key_id = api_key_id
diff --git a/services/connectors/app/connectors/sentinelone.py b/services/connectors/app/connectors/sentinelone.py
index e6e9db210..09e24fd34 100644
--- a/services/connectors/app/connectors/sentinelone.py
+++ b/services/connectors/app/connectors/sentinelone.py
@@ -35,7 +35,15 @@ class SentinelOneConnector(BaseConnector):
@classmethod
def capabilities(cls) -> tuple[Capability, ...]:
- return (Capability.PULL_ALERTS,)
+ # Response actions are executed by services/actions SentinelOneClient
+ # (contain_host / lift_containment / quarantine_file are all live). PID
+ # kill + run_script are unsupported by the S1 API, so they're omitted.
+ return (
+ Capability.PULL_ALERTS,
+ Capability.ISOLATE_HOST,
+ Capability.UNISOLATE_HOST,
+ Capability.QUARANTINE_FILE,
+ )
@classmethod
def schema(cls) -> ConnectorSchema:
diff --git a/services/connectors/tests/test_edr_containment.py b/services/connectors/tests/test_edr_containment.py
new file mode 100644
index 000000000..55033f25e
--- /dev/null
+++ b/services/connectors/tests/test_edr_containment.py
@@ -0,0 +1,27 @@
+"""Wave 0 — SentinelOne and Cortex XDR connectors must declare the containment
+capabilities that services/actions can actually execute (honesty: no declared
+capability without a live execution path)."""
+
+from __future__ import annotations
+
+from app.connectors.base import Capability
+from app.connectors.cortex_xdr import CortexXDRConnector
+from app.connectors.sentinelone import SentinelOneConnector
+
+
+def test_sentinelone_declares_isolation_and_quarantine():
+ caps = set(SentinelOneConnector.capabilities())
+ assert Capability.PULL_ALERTS in caps
+ assert Capability.ISOLATE_HOST in caps
+ assert Capability.UNISOLATE_HOST in caps
+ assert Capability.QUARANTINE_FILE in caps
+ # S1 has no non-interactive script / PID-kill API — must NOT be claimed.
+ assert Capability.RUN_SCRIPT not in caps
+ assert Capability.KILL_PROCESS not in caps
+
+
+def test_cortex_xdr_declares_isolation():
+ caps = set(CortexXDRConnector.capabilities())
+ assert Capability.PULL_ALERTS in caps
+ assert Capability.ISOLATE_HOST in caps
+ assert Capability.UNISOLATE_HOST in caps
diff --git a/services/ingest/internal/normalizer/normalizer.go b/services/ingest/internal/normalizer/normalizer.go
index e9422f360..3b9855dc1 100644
--- a/services/ingest/internal/normalizer/normalizer.go
+++ b/services/ingest/internal/normalizer/normalizer.go
@@ -259,20 +259,91 @@ func New(cfg *config.Config) (*Normalizer, error) {
return n, nil
}
+// Canonical connector-envelope handling.
+//
+// Pull connectors normalize inside their own fetch_alerts and emit a canonical
+// envelope (source + raw_event + external_id/title/severity/src_ip/hostname/
+// created_at), NOT a raw vendor row. Only a handful of connector types have a
+// hand-written raw profile above, so historically every other connector (incl.
+// CrowdStrike and Okta, whose profile keys never matched their connector ids)
+// fell to the generic Network-Activity profile and lost its class + severity.
+// We instead detect the envelope and map its canonical fields directly,
+// defaulting to an OCSF Security Finding (class 2001, category 2) so vendor
+// alerts promote regardless of severity.
+var _canonicalSeverityMap = map[string]int{
+ "critical": 5, "high": 4, "medium": 3, "low": 2, "info": 1, "informational": 1,
+}
+
+var _canonicalFieldMap = map[string]string{
+ "title": "message",
+ "external_id": "finding.uid",
+ "src_ip": "src_endpoint.ip",
+ "hostname": "device.name",
+ "actor": "actor.user.name",
+}
+
+// canonicalClassByConnector overrides the default Security Finding class for
+// connector types whose canonical alerts are better modeled as another OCSF
+// class (identity providers -> Authentication 3002).
+var canonicalClassByConnector = map[string]struct {
+ classUID int
+ className string
+}{
+ "okta": {3002, "Authentication"},
+ "azure_entra": {3002, "Authentication"},
+ "auth0": {3002, "Authentication"},
+ "duo_security": {3002, "Authentication"},
+ "onepassword": {3002, "Authentication"},
+}
+
+func isCanonicalEnvelope(p map[string]interface{}) bool {
+ if p == nil {
+ return false
+ }
+ _, hasRaw := p["raw_event"]
+ _, hasSource := p["source"]
+ return hasRaw && hasSource
+}
+
+func canonicalProfile(connectorType string) connectorProfile {
+ classUID, className := 2001, "Security Finding"
+ if override, ok := canonicalClassByConnector[connectorType]; ok {
+ classUID, className = override.classUID, override.className
+ }
+ name := connectorType
+ if name == "" {
+ name = "Connector"
+ }
+ return connectorProfile{
+ product: OcsfProduct{Name: name, VendorName: name},
+ classUID: classUID,
+ className: className,
+ fieldMap: _canonicalFieldMap,
+ severityMap: _canonicalSeverityMap,
+ }
+}
+
// Normalize converts a raw event to a NormalizedEvent
func (n *Normalizer) Normalize(raw *RawEvent) (*NormalizedEvent, error) {
if raw.TenantID == "" {
return nil, fmt.Errorf("tenant_id is required")
}
- profile, ok := connectorProfiles[raw.ConnectorType]
- if !ok {
- if n.cfg.NormalizerMode == "strict" {
- return nil, fmt.Errorf("unknown connector type: %s", raw.ConnectorType)
+ var profile connectorProfile
+ if isCanonicalEnvelope(raw.Payload) {
+ // Connector-normalized envelope: map its canonical fields directly.
+ profile = canonicalProfile(raw.ConnectorType)
+ } else {
+ var ok bool
+ profile, ok = connectorProfiles[raw.ConnectorType]
+ if !ok {
+ if n.cfg.NormalizerMode == "strict" {
+ return nil, fmt.Errorf("unknown connector type: %s", raw.ConnectorType)
+ }
+ // Lenient: use generic profile
+ profile = connectorProfiles["splunk_enterprise"]
+ log.Warn().Str("connector_type", raw.ConnectorType).Msg("Using generic profile for unknown connector")
}
- // Lenient: use generic profile
- profile = connectorProfiles["splunk_enterprise"]
- log.Warn().Str("connector_type", raw.ConnectorType).Msg("Using generic profile for unknown connector")
}
warnings := []string{}
@@ -329,7 +400,11 @@ func (n *Normalizer) Normalize(raw *RawEvent) (*NormalizedEvent, error) {
ocsf["tenant_uid"] = raw.TenantID
ocsf["source_connector_id"] = raw.ConnectorID
- ocsf["event_id"] = generateEventID(raw)
+ // Replay-stable id: derived from tenant + connector + a stable vendor id
+ // (see generateEventID). Reused as the envelope ID + Kafka key below so a
+ // re-ingested event dedups end-to-end (Kafka key + ClickHouse event_id).
+ eventID := generateEventID(raw)
+ ocsf["event_id"] = eventID
// Preserve raw data
if rawBytes, err := json.Marshal(raw.Payload); err == nil {
@@ -388,14 +463,12 @@ func (n *Normalizer) Normalize(raw *RawEvent) (*NormalizedEvent, error) {
}
}
- eventID := uuid.New().String()
-
return &NormalizedEvent{
- ID: eventID,
- ConnectorID: raw.ConnectorID,
- TenantID: raw.TenantID,
- OcsfEvent: ocsf,
- NormalizationVersion: n.version,
+ ID: eventID,
+ ConnectorID: raw.ConnectorID,
+ TenantID: raw.TenantID,
+ OcsfEvent: ocsf,
+ NormalizationVersion: n.version,
NormalizationWarnings: warnings,
}, nil
}
diff --git a/services/ingest/internal/normalizer/normalizer_test.go b/services/ingest/internal/normalizer/normalizer_test.go
index 358f82693..16cbd7cd6 100644
--- a/services/ingest/internal/normalizer/normalizer_test.go
+++ b/services/ingest/internal/normalizer/normalizer_test.go
@@ -102,3 +102,66 @@ func TestGenerateEventIDContentFallback(t *testing.T) {
t.Error("identical replay produced different IDs")
}
}
+
+// A canonical connector envelope (source + raw_event) must be recognised and
+// mapped to an OCSF Security Finding regardless of connector_type, so
+// CrowdStrike/SentinelOne/etc. stop falling to the generic Network-Activity
+// profile (Wave 0).
+func TestCanonicalEnvelopeMapsToFinding(t *testing.T) {
+ n := newTestNormalizer()
+ raw := &RawEvent{
+ ConnectorID: "c1",
+ ConnectorType: "crowdstrike", // has no raw profile keyed "crowdstrike"
+ TenantID: "11111111-1111-1111-1111-111111111111",
+ ReceivedAt: "2026-08-02T00:00:00Z",
+ Payload: map[string]interface{}{
+ "source": "crowdstrike",
+ "external_id": "THREAT-9",
+ "title": "Malware Blocked",
+ "severity": "high",
+ "src_ip": "10.0.0.4",
+ "hostname": "ws-9",
+ "created_at": "2026-08-01T23:00:00Z",
+ "raw_event": map[string]interface{}{"id": "THREAT-9"},
+ },
+ }
+ ev, err := n.Normalize(raw)
+ if err != nil {
+ t.Fatalf("Normalize error: %v", err)
+ }
+ ocsf := ev.OcsfEvent
+ if ocsf["class_uid"] != 2001 {
+ t.Errorf("class_uid = %v, want 2001 (Security Finding, not generic 4001)", ocsf["class_uid"])
+ }
+ if ocsf["severity_id"] != 4 {
+ t.Errorf("severity_id = %v, want 4 (high preserved)", ocsf["severity_id"])
+ }
+ if ocsf["message"] != "Malware Blocked" {
+ t.Errorf("message = %v, want the canonical title", ocsf["message"])
+ }
+ // The envelope ID must be the replay-stable event_id, not a random UUID.
+ if ev.ID != ocsf["event_id"] {
+ t.Errorf("envelope ID %q != ocsf event_id %q (should be the deterministic id)", ev.ID, ocsf["event_id"])
+ }
+ if ev.ID != generateEventID(raw) {
+ t.Errorf("envelope ID is not the deterministic generateEventID value")
+ }
+}
+
+// Identity-provider canonical envelopes map to Authentication (3002).
+func TestCanonicalEnvelopeIdpMapsToAuthentication(t *testing.T) {
+ n := newTestNormalizer()
+ ev, err := n.Normalize(&RawEvent{
+ ConnectorID: "c2", ConnectorType: "okta", TenantID: "t-okta-uuid-1111-1111-111111111111",
+ Payload: map[string]interface{}{
+ "source": "okta", "external_id": "EVT-1", "title": "Suspicious sign-in",
+ "severity": "medium", "raw_event": map[string]interface{}{},
+ },
+ })
+ if err != nil {
+ t.Fatalf("Normalize error: %v", err)
+ }
+ if ev.OcsfEvent["class_uid"] != 3002 {
+ t.Errorf("okta canonical class_uid = %v, want 3002 (Authentication)", ev.OcsfEvent["class_uid"])
+ }
+}