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
fix(replay): adapt reader output to the shape each connector normalize() reads (#1189)
Beenu Arorab120867427f8
diff --git a/apps/docs/docs/evaluation/replay.md b/apps/docs/docs/evaluation/replay.mdindex f77755898..4ce9a5580 100644--- a/apps/docs/docs/evaluation/replay.md+++ b/apps/docs/docs/evaluation/replay.md@@ -80,6 +80,12 @@ review state in its own lookup. It must return these fields: `event_id`,`rule_id`, `rule_name`, `urgency`, `disposition`, `review_time`, `reviewer`,`comment`.+It should also return the notable's asset and identity fields — `src`, `dest`,+`dvc`, `orig_host`, `user` and `src_user` — which is what the default search+does. `| fields` keeps only what it names, so a search that omits them+produces findings with no host and no user, and triage is then graded on an+alert that says who raised it and nothing about who it happened to.+### Microsoft SentinelReads incidents with `properties/status eq 'Closed'`, following `nextLink` so a@@ -91,6 +97,12 @@ sorted first.`Undetermined` to `unlabeled`. `classificationReason` and`classificationComment` are carried as the analyst's reason.+An incident's `properties` carry no account and no host, so the reader also+calls each incident's `entities` endpoint and attaches the result. The app+registration therefore needs to be able to read entities on the workspace; if+it cannot, the incident still contributes its analyst's classification and+reaches triage without a host or a user rather than failing the window.+### Elastic Security**Elastic ships no disposition field.** Closing a signal setsdiff --git a/services/actions/app/clients/qradar_client.py b/services/actions/app/clients/qradar_client.pyindex fc1c7dbb6..7d97bd5e6 100644--- a/services/actions/app/clients/qradar_client.py+++ b/services/actions/app/clients/qradar_client.py@@ -88,8 +88,23 @@ class QRadarClient:``closing_reason_name`` for the parser. An id the appliance does notresolve is left without a name, which the parser reads as ``unlabeled``rather than inventing a reason for it.++ ``fields`` excludes everything it does not name, so it also names what+ the connector's ``normalize()`` reads downstream: ``magnitude`` is the+ severity signal (``severity`` alone is a different 1-10 grade the+ connector does not read), ``offense_source`` is the one entity an+ offense indexes, and ``start_time`` is when it began. Omitting them+ left every replayed offense at a default severity with no host and no+ user.++ ``offense_type_name`` is resolved the same way and for the same reason+ as the closing reason: the offense carries only a number, and whether+ ``offense_source`` holds a username, a hostname or an address is+ exactly what that number says. Offense types are site-configurable, so+ the table is read from the appliance."""reasons = await self._closing_reasons()+ types = await self._offense_types()async with httpx.AsyncClient(timeout=self._timeout, verify=self._verify_ssl) as client:response = await client.get(f"{self._base}/api/siem/offenses",@@ -99,7 +114,10 @@ class QRadarClient:f"status = CLOSED and close_time >= {int(since.timestamp() * 1000)} "f"and close_time <= {int(until.timestamp() * 1000)}"),- "fields": ("id,description,status,severity,offense_type,close_time,last_updated_time,closing_reason_id,closing_user"),+ "fields": (+ "id,description,status,severity,magnitude,offense_type,offense_source,event_count,"+ "start_time,close_time,last_updated_time,closing_reason_id,closing_user"+ ),},)response.raise_for_status()@@ -109,9 +127,39 @@ class QRadarClient:name = reasons.get(offense.get("closing_reason_id"))if name is not None:offense["closing_reason_name"] = name+ type_name = types.get(offense.get("offense_type"))+ if type_name is not None:+ offense["offense_type_name"] = type_namelogger.info("qradar.closed_offenses", count=len(offenses))return list(offenses)+ async def _offense_types(self) -> dict[Any, str]:+ """Read the appliance's offense-type id to name table.++ Never raises, for the same reason the closing-reason lookup does not:+ an appliance that refuses this endpoint should yield offenses whose+ indexed entity is untyped, which downstream reads as "no host and no+ user recorded". Failing the whole history read over the lookup would+ turn a partial answer into no answer.++ ``property_name`` is preferred over ``name`` because it is the+ machine-readable half — ``hostName`` against the display string+ "Hostname" — and a site can rename the display string.+ """+ try:+ async with httpx.AsyncClient(timeout=self._timeout, verify=self._verify_ssl) as client:+ response = await client.get(+ f"{self._base}/api/siem/offense_types",+ headers=self._headers(),+ params={"fields": "id,name,property_name"},+ )+ response.raise_for_status()+ rows = response.json() if response.content else []+ except Exception as exc: # noqa: BLE001, a missing lookup degrades to an untyped entity+ logger.warning("qradar.offense_types_unavailable", error=str(exc))+ return {}+ return {row["id"]: str(row.get("property_name") or row.get("name") or "") for row in rows if "id" in row}+async def _closing_reasons(self) -> dict[Any, str]:"""Read the appliance's closing-reason id to text table.diff --git a/services/actions/app/clients/sentinel_client.py b/services/actions/app/clients/sentinel_client.pyindex 2ea3b3f6c..f946677f7 100644--- a/services/actions/app/clients/sentinel_client.py+++ b/services/actions/app/clients/sentinel_client.py@@ -110,6 +110,12 @@ class SentinelClient:The OData filter bounds the window server-side. ``Status eq 'Closed'``is the only status that carries a classification, so an open incidentcannot enter the corpus.++ Each incident is then given its ``entities``. An incident's+ ``properties`` carry a title, a severity and a classification and+ **no account and no host** — those live behind the incident's own+ entities endpoint — so without this second call every replayed+ Sentinel incident reached triage describing nobody."""results: list[dict[str, Any]] = []url: str | None = self._incidents_url()@@ -134,7 +140,45 @@ class SentinelClient:# would duplicate $filter and ARM rejects the request.url = body.get("nextLink")params = None- return results[:limit]+ incidents = results[:limit]+ for incident in incidents:+ entities = await self._incident_entities(client, token, str(incident.get("name") or ""))+ if entities:+ incident["entities"] = entities+ return incidents++ async def _incident_entities(+ self,+ client: httpx.AsyncClient,+ token: str,+ incident_id: str,+ ) -> list[dict[str, Any]]:+ """The accounts, hosts and addresses ARM associates with one incident.++ One request per incident, which is what the API offers: entities are a+ sub-resource and there is no expansion on the list call. A history read+ is a once-per-evaluation-window job rather than a hot path, so the cost+ is paid there instead of leaving the corpus without entities.++ Never raises. An incident whose entities cannot be read still carries+ its analyst's classification, which is the label the evaluation is+ graded against; dropping the whole window over a missing host would+ trade the measurement for one of its columns.+ """+ if not incident_id:+ return []+ try:+ response = await client.post(+ f"{self._incident_url(incident_id)}/entities",+ headers={"Authorization": f"Bearer {token}"},+ params={"api-version": API_VERSION},+ )+ response.raise_for_status()+ body = response.json() if response.content else {}+ except Exception as exc: # noqa: BLE001, a missing entity list degrades to no host and no user+ logger.warning("sentinel.incident_entities_unavailable", incident_id=incident_id, error=str(exc))+ return []+ return [entity for entity in body.get("entities") or [] if isinstance(entity, dict)]async def get_incident(self, incident_id: str) -> dict[str, Any]:"""Read one incident. Used as the writeback verification probe."""diff --git a/services/actions/app/clients/splunk_client.py b/services/actions/app/clients/splunk_client.pyindex d13309eaf..8c1b66927 100644--- a/services/actions/app/clients/splunk_client.py+++ b/services/actions/app/clients/splunk_client.py@@ -126,9 +126,17 @@ class SplunkClient:review lookup supplies its own SPL rather than being told its historycannot be read. The fields the parser needs are documented in`apps/docs/docs/evaluation/replay.md`.++ ``| fields`` keeps only what it names, so the asset and identity+ columns are named explicitly: without them a replayed notable reaches+ triage with no host and no user, and the agent is graded on an alert+ that says who raised it and nothing about who it happened to. These+ are Enterprise Security's own notable fields — assets correlate on+ ``src`` / ``dest`` / ``dvc`` and identities on ``user`` / ``src_user``."""spl = search_override or (- "`notable` | search status IN (5, 6) | fields event_id rule_id rule_name urgency disposition review_time reviewer comment _time"+ "`notable` | search status IN (5, 6) | fields event_id rule_id rule_name urgency disposition "+ "review_time reviewer comment _time src dest dvc orig_host user src_user")rows = await self.run_search(spl,diff --git a/services/actions/app/services/alert_history.py b/services/actions/app/services/alert_history.pyindex 40e765899..e5a2504f6 100644--- a/services/actions/app/services/alert_history.py+++ b/services/actions/app/services/alert_history.py@@ -58,6 +58,13 @@ from dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom typing import Any+from app.services.alert_history_adapters import (+ adapt_defender_alert,+ adapt_elastic_signal,+ adapt_qradar_offense,+ adapt_sentinel_incident,+ adapt_splunk_notable,+)from app.services.disposition_writeback import (BENIGN,BENIGN_TRUE_POSITIVE,@@ -91,10 +98,16 @@ __all__ = [class ClosedFinding:"""One finding a human already closed, with the label they chose.- ``raw`` carries the vendor payload untouched so the replay runner can hand- it to the same connector ``normalize()`` production uses, rather than- normalizing a second way here and grading the agent on an input shape it- never sees in production.+ ``raw`` carries the vendor payload in the shape that connector's+ ``normalize()`` reads, so the replay runner can hand it to the same+ mapping production uses rather than normalizing a second way here and+ grading the agent on an input shape it never sees.++ It is the row as the vendor sent it for three of the five vendors. The+ other two read a different endpoint of the same product than their+ connector polls, so :mod:`app.services.alert_history_adapters` restructures+ them first — see that module for which, and why a verbatim row was the+ wrong thing to carry."""vendor: str@@ -265,7 +278,7 @@ def parse_splunk_notable(row: Mapping[str, Any]) -> ClosedFinding:reason=_opt_str(row, "comment"),rule_id=_opt_str(row, "rule_id"),severity=(_opt_str(row, "urgency") or "").lower() or None,- raw=dict(row),+ raw=adapt_splunk_notable(row),)@@ -309,7 +322,7 @@ def parse_sentinel_incident(row: Mapping[str, Any]) -> ClosedFinding:reason=(": ".join(reason_parts) or None),rule_id=_first_rule_id(props.get("relatedAnalyticRuleIds")),severity=(_opt_str(props, "severity") or "").lower() or None,- raw=dict(row),+ raw=adapt_sentinel_incident(row),)@@ -362,7 +375,7 @@ def parse_elastic_signal(row: Mapping[str, Any]) -> ClosedFinding:reason=(str(src["kibana.alert.workflow_reason"]) if src.get("kibana.alert.workflow_reason") else None),rule_id=(str(src["kibana.alert.rule.uuid"]) if src.get("kibana.alert.rule.uuid") else None),severity=(str(src["kibana.alert.severity"]).lower() if src.get("kibana.alert.severity") else None),- raw=dict(row),+ raw=adapt_elastic_signal(row),)@@ -406,7 +419,7 @@ def parse_qradar_offense(row: Mapping[str, Any]) -> ClosedFinding:reason=(str(raw_label) or None),rule_id=(None if row.get("offense_type") is None else str(row.get("offense_type"))),severity=_qradar_severity(row.get("severity")),- raw=dict(row),+ raw=adapt_qradar_offense(row),)@@ -475,5 +488,5 @@ def parse_defender_alert(row: Mapping[str, Any]) -> ClosedFinding:reason=_opt_str(row, "determination"),rule_id=_opt_str(row, "detectionSource"),severity=(_opt_str(row, "severity") or "").lower() or None,- raw=dict(row),+ raw=adapt_defender_alert(row),)diff --git a/services/actions/app/services/alert_history_adapters.py b/services/actions/app/services/alert_history_adapters.pynew file mode 100644index 000000000..894da8f1c--- /dev/null+++ b/services/actions/app/services/alert_history_adapters.py@@ -0,0 +1,270 @@+"""Reader rows in the shape the production connector ``normalize()`` reads.++Fix-pass item 3.3.++:class:`~app.services.alert_history.ClosedFinding` carries ``raw`` so the+replay runner can hand it to the same ``normalize()`` production uses, rather+than normalizing a second way and grading the agent on an input shape it never+sees. That only works if the two agree about the row, and for two vendors they+did not: a reader and its connector read **different endpoints of the same+product**, and the connector's field lookups all missed.++The failure is silent, which is what makes it worth a module. Nothing raises —+every ``raw.get(...)`` simply returns ``None``, so the finding reaches triage+with a placeholder title, the connector's default severity and no host or+user, and the agent is graded on an alert that describes nobody.++Where the two endpoints differ, and where they do not+-----------------------------------------------------+======== ===================================== =====================================+Source Reader endpoint Connector endpoint+======== ===================================== =====================================+splunk ``/services/search/jobs`` review SPL the deployment's saved search+sentinel ARM ``…/incidents`` ARM ``…/incidents``+elastic ``<index>/_search`` (hits) ES|QL over the alerts index+qradar ``/api/siem/offenses`` ``/api/siem/offenses``+defender ``api.securitycenter…/api/alerts`` Graph ``alerts_v2``+======== ===================================== =====================================++Three of the five read the same resource their connector polls, so their+adapters pass the row through and say so. Writing a translation where none is+needed would be a second mapping to keep in step with the first, which is the+duplication :mod:`app.services.alert_history` exists to avoid. The two that do+translate are the two the fix-pass names.++What an adapter will not do+---------------------------+It will not add a field the vendor did not send. An adapter renames, lifts and+restructures what the reader read; a value that is absent stays absent, and+the triage input carries an empty host rather than a plausible one. A+fabricated entity on a record an analyst uses to decide containment is worse+than a missing one, because only one of the two is visible.++Vendor references, read before these mappings were written:++* Defender for Endpoint alert resource+ — https://learn.microsoft.com/en-us/defender-endpoint/api/alerts+* Microsoft Graph ``alerts_v2`` alert, ``userEvidence`` and ``deviceEvidence``+ — https://learn.microsoft.com/en-us/graph/api/resources/security-alert+* Elastic Security detection alert schema+ — https://www.elastic.co/docs/reference/security/fields-and-object-schemas/alert-schema+"""++from __future__ import annotations++from collections.abc import Mapping+from typing import Any++__all__ = [+ "ADAPTERS",+ "adapt_defender_alert",+ "adapt_elastic_signal",+ "adapt_qradar_offense",+ "adapt_sentinel_incident",+ "adapt_splunk_notable",+]++#: Every alert on the Defender for Endpoint alerts endpoint came from Defender+#: for Endpoint, so Graph's ``serviceSource`` is a property of the endpoint the+#: reader called rather than something inferred from the row.+_MDE_SERVICE_SOURCE = "microsoftDefenderForEndpoint"++#: Graph spells its evidence subtypes in ``@odata.type``; Defender for Endpoint+#: spells them in ``entityType``. Only these two are translated because they+#: are the two the connector reads. The rest are carried verbatim below.+_USER_EVIDENCE = "#microsoft.graph.security.userEvidence"+_DEVICE_EVIDENCE = "#microsoft.graph.security.deviceEvidence"+++def _first(row: Mapping[str, Any], *keys: str) -> Any:+ for key in keys:+ value = row.get(key)+ if value not in (None, ""):+ return value+ return None+++def adapt_splunk_notable(row: Mapping[str, Any]) -> dict[str, Any]:+ """Name the notable's title the way a saved-search row names it.++ Both endpoints return a Splunk search result, so the row is already the+ right kind of thing. One column disagrees: Enterprise Security's review+ data calls the correlation search ``rule_name`` while a saved-search feed+ calls it ``search_name``, which is what the connector reads — so without+ this every replayed notable was titled "Splunk Notable Event".++ The asset and identity columns are left exactly as Splunk sent them. They+ are standard notable fields and the connector reads them directly.+ """+ adapted = dict(row)+ if not adapted.get("search_name") and adapted.get("rule_name"):+ adapted["search_name"] = adapted["rule_name"]+ return adapted+++def adapt_sentinel_incident(row: Mapping[str, Any]) -> dict[str, Any]:+ """Pass through: the reader and the connector both read ARM incidents.++ ``entities`` rides along when the reader resolved it. It is not a property+ of the incident resource — it is the response of the incident's entities+ endpoint — so it is absent on a plain incident read and the connector+ treats it as optional.+ """+ return dict(row)+++def adapt_elastic_signal(row: Mapping[str, Any]) -> dict[str, Any]:+ """Flatten a ``_search`` hit into the document the connector reads.++ The reader keeps whole hits because ``_id`` is the signal's identity and+ lives on the envelope, not in ``_source``. The connector reads a flat+ document, so against a hit every lookup missed: the rule name, the+ severity and the timestamp are all one level down.++ Severity is the one that mattered most. ``normalize()`` falls back to+ ``medium`` when it cannot find a value, so a ``critical`` signal reached+ triage as a mid-grade one and nothing in the record said it had been+ downgraded.++ ``_id`` and ``_index`` are kept alongside the flattened source rather than+ dropped: the connector's identity fallback is ``_id``, and an operator+ reading ``raw_event`` needs to know which index the signal came from.+ """+ source = row.get("_source")+ flat: dict[str, Any] = dict(source) if isinstance(source, Mapping) else {}+ for envelope_key in ("_id", "_index"):+ if row.get(envelope_key) is not None:+ flat.setdefault(envelope_key, row[envelope_key])+ return flat+++def adapt_qradar_offense(row: Mapping[str, Any]) -> dict[str, Any]:+ """Pass through: the reader and the connector both read ``/siem/offenses``.++ ``closing_reason_name`` and ``offense_type_name`` ride along. Neither is an+ offense field — an offense carries only the numeric ids, and the reader+ resolves both against the appliance because QRadar lets a site define its+ own closing reasons and offense types.+ """+ return dict(row)+++def adapt_defender_alert(row: Mapping[str, Any]) -> dict[str, Any]:+ """Rebuild a Defender for Endpoint alert in the Graph ``alerts_v2`` shape.++ The two APIs describe the same alert and disagree about almost every name+ that matters here. The timestamps are the simple half+ (``alertCreationTime`` against ``createdDateTime``); evidence is the half+ that lost the host and the user. Defender for Endpoint tags an evidence+ entry with ``entityType`` and puts the account fields on the entry itself;+ Graph tags it with ``@odata.type`` and nests the account under+ ``userAccount``. The connector matches on ``@odata.type``, so no entry ever+ matched and both ``actor`` and ``host`` came out ``None``.++ The device entry is built from ``computerDnsName`` rather than from+ evidence. Defender for Endpoint reports the alert's machine on the alert+ itself, and an alert can carry file and process evidence without carrying a+ device entity at all.++ Evidence entries that are neither a user nor a device are carried through+ **unchanged**, keeping their Defender for Endpoint shape. The connector+ ignores them, they remain readable in ``raw_event``, and transliterating+ them would mean asserting per-type field mappings nothing here reads.+ ``classification`` and ``determination`` are carried verbatim for the same+ reason: the two vocabularies are not a lexical transform of one another+ (Defender for Endpoint's "Informational, expected activity" against+ Graph's ``informationalExpectedActivity``), and inventing the translation+ would put a guessed verdict next to the analyst's real one.+ """+ adapted = {k: v for k, v in row.items() if k not in {"evidence", "relatedUser", "incidentId"}}++ adapted["serviceSource"] = _MDE_SERVICE_SOURCE+ if row.get("incidentId") is not None:+ adapted["incidentId"] = str(row["incidentId"])+ for mde_key, graph_key in (+ ("alertCreationTime", "createdDateTime"),+ ("lastUpdateTime", "lastUpdateDateTime"),+ ("resolvedTime", "resolvedDateTime"),+ ("firstEventTime", "firstActivityDateTime"),+ ("lastEventTime", "lastActivityDateTime"),+ ):+ if row.get(mde_key) is not None:+ adapted[graph_key] = row[mde_key]++ evidence: list[dict[str, Any]] = []+ user_account = _mde_user_account(row)+ if user_account:+ evidence.append({"@odata.type": _USER_EVIDENCE, "userAccount": user_account})+ device = _mde_device(row)+ if device:+ evidence.append(device)+ evidence.extend(entry for entry in row.get("evidence") or [] if isinstance(entry, dict) and not _is_user_entity(entry))+ if evidence:+ adapted["evidence"] = evidence+ return adapted+++def _is_user_entity(entry: Mapping[str, Any]) -> bool:+ return str(entry.get("entityType") or "").lower() == "user"+++def _mde_user_account(row: Mapping[str, Any]) -> dict[str, Any]:+ """Collect the account fields Graph nests under ``userEvidence.userAccount``.++ ``relatedUser`` is the alert's own account and carries only a name and a+ domain; the ``User`` evidence entry carries the UPN and the SID. Both are+ read because a Defender for Endpoint alert can have either, and a merge+ rather than a choice avoids an alert losing its UPN because it also had a+ ``relatedUser``.+ """+ related = row.get("relatedUser")+ related = related if isinstance(related, Mapping) else {}+ entry: Mapping[str, Any] = next(+ (e for e in row.get("evidence") or [] if isinstance(e, Mapping) and _is_user_entity(e)),+ {},+ )++ account_name = _first(related, "userName") or _first(entry, "accountName")+ if not account_name and not _first(entry, "userPrincipalName"):+ return {}+ account = {+ "accountName": account_name,+ "domainName": _first(related, "domainName") or _first(entry, "domainName"),+ "userPrincipalName": _first(entry, "userPrincipalName"),+ "userSid": _first(entry, "userSid"),+ "azureAdUserId": _first(entry, "aadUserId"),+ }+ # Graph's own `displayName` has no Defender for Endpoint counterpart; the+ # connector prefers it over `accountName`, so leaving it unset keeps the+ # account name the connector reports rather than inventing a display name.+ return {k: v for k, v in account.items() if v}+++def _mde_device(row: Mapping[str, Any]) -> dict[str, Any]:+ dns_name = _first(row, "computerDnsName")+ machine_id = _first(row, "machineId")+ if not dns_name and not machine_id:+ return {}+ device: dict[str, Any] = {"@odata.type": _DEVICE_EVIDENCE}+ if dns_name:+ device["deviceDnsName"] = dns_name+ # Graph's `hostName` is the label without the domain suffix.+ device["hostName"] = str(dns_name).split(".", 1)[0]+ if machine_id:+ device["mdeDeviceId"] = machine_id+ if row.get("rbacGroupName"):+ device["rbacGroupName"] = row["rbacGroupName"]+ return device+++#: Keyed by the vendor name :class:`~app.services.alert_history.ClosedFinding`+#: records, so a vendor added to the readers without an adapter is a+#: ``KeyError`` at the one call site rather than a row that reaches triage+#: shaped for nobody.+ADAPTERS = {+ "splunk": adapt_splunk_notable,+ "sentinel": adapt_sentinel_incident,+ "elastic": adapt_elastic_signal,+ "qradar": adapt_qradar_offense,+ "defender": adapt_defender_alert,+}diff --git a/services/actions/tests/test_replay_input_shapes.py b/services/actions/tests/test_replay_input_shapes.pynew file mode 100644index 000000000..f18f8930f--- /dev/null+++ b/services/actions/tests/test_replay_input_shapes.py@@ -0,0 +1,515 @@+"""Reader output, the production ``normalize()``, and the triage input it feeds.++Fix-pass item 3.3.++The defect this gates+---------------------+A closed-finding reader and its connector read **different vendor endpoints**,+so two of the five returned a row the connector's ``normalize()`` could not+read at all: Elastic's reader returns ``_search`` hits while the connector+expects the flat document, and Defender's reader returns a Defender for+Endpoint alert while the connector expects a Microsoft Graph ``alerts_v2``+one. The symptom is not an exception — every lookup simply misses, so the+finding reaches triage with a fabricated default severity and no host or user,+and the agent is then graded on an alert that describes nobody.++Three vendor endpoints are involved per source and they are all real:++* Splunk ES notables, ``POST /services/search/jobs`` then the results endpoint+ — https://help.splunk.com/en/splunk-enterprise-security/administer+* Microsoft Sentinel incidents and their entities+ — https://learn.microsoft.com/en-us/rest/api/securityinsights/incidents/list-entities+* Elastic Security detection alerts, ``POST <index>/_search``+ — https://www.elastic.co/docs/reference/security/fields-and-object-schemas/alert-schema+* IBM QRadar offenses and offense types+ — https://ibmsecuritydocs.github.io/qradar_api_20.0/20.0--siem-offenses-GET.html+* Microsoft Defender for Endpoint alerts+ — https://learn.microsoft.com/en-us/defender-endpoint/api/alerts++Every payload below is **synthetic**, built to the shape those pages document.+None came from a customer.++Why this test spawns two subprocesses+-------------------------------------+The three links live in three deployables that all package their code as a+top-level ``app``, so one interpreter cannot import two of them: the second+``import app`` returns the first. ``services/actions`` runs in-process here+because it owns the readers; ``normalize()`` and the envelope builder run in+children with the peer service's directory on ``sys.path``.++The agents child pre-registers ``app`` and ``app.replay`` as namespace+packages before importing. That skips only ``__init__.py``, whose sole job is+re-exporting, and avoids dragging the whole agent graph — and its model+dependencies — into a test about dictionary shapes. The two modules that do+the work are loaded from their real files, unmodified; nothing here is a+stand-in for them.++What "present" means in the assertions+--------------------------------------+``alert["hostname"]``, ``alert["username"]`` and ``alert["severity"]`` on the+``aisoc.alerts.fused`` envelope, because those are the three keys+``build_state`` reads. A severity that is present but is the connector's+``medium`` default rather than the vendor's own value is a failure here: a+fabricated severity is worse than an absent one, since it reads as measured.++QRadar is asserted differently, and the reason is a property of the vendor+rather than of this code. An offense indexes exactly one entity —+``offense_source``, typed by ``offense_type`` — so an offense is host-indexed+or user-indexed and never both. Both mappings are proven, and the slot the+offense does not carry is asserted **empty**, because filling it would be a+fabricated entity on a forensic record.+"""++from __future__ import annotations++import asyncio+import json+import os+import subprocess+import sys+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++import httpx+import pytest+import respx+from app.clients.defender_client import DefenderClient+from app.clients.elastic_client import ElasticClient+from app.clients.qradar_client import QRadarClient+from app.clients.sentinel_client import SentinelClient+from app.clients.splunk_client import SplunkClient+from app.services.alert_history import (+ parse_defender_alert,+ parse_elastic_signal,+ parse_qradar_offense,+ parse_sentinel_incident,+ parse_splunk_notable,+)++REPO_ROOT = Path(__file__).resolve().parents[3]+CONNECTORS = REPO_ROOT / "services" / "connectors"+AGENTS = REPO_ROOT / "services" / "agents"++SINCE = datetime(2026, 9, 1, tzinfo=UTC)+UNTIL = datetime(2026, 9, 26, tzinfo=UTC)++#: One host and one account across all five payloads, so a value that reaches+#: the envelope from the wrong vendor's row cannot look like a pass.+HOST = "fin-wks-0423.corp.example.com"+USER = "m.okafor"++#: ``(module, class, constructor kwargs)`` for the connector each reader+#: feeds. Resolved in the child, where ``app`` is the connectors package.+_CONNECTORS: dict[str, tuple[str, str, dict[str, Any]]] = {+ "splunk": ("app.connectors.splunk", "SplunkConnector", {"base_url": "https://splunk:8089", "token": "t"}),+ "sentinel": (+ "app.connectors.microsoft_sentinel",+ "MicrosoftSentinelConnector",+ {"tenant_id": "t", "client_id": "c", "client_secret": "s", "subscription_id": "sub", "resource_group": "rg", "workspace": "ws"},+ ),+ "elastic": ("app.connectors.elastic", "ElasticConnector", {"base_url": "https://es:9200", "api_key": "k"}),+ "qradar": ("app.connectors.qradar", "QRadarConnector", {"console_url": "https://qradar", "sec_token": "t"}),+ "defender": ("app.connectors.azure_defender", "AzureDefenderConnector", {"tenant_id": "t", "client_id": "c", "client_secret": "s"}),+}+++# ---------------------------------------------------------------------------+# Recorded vendor payloads+# ---------------------------------------------------------------------------++_SPLUNK_RESULTS = {+ "results": [+ {+ "event_id": "A1B2@@notable@@1",+ "rule_id": "ESCU-Suspicious-Powershell",+ "rule_name": "Suspicious PowerShell Encoded Command",+ "urgency": "high",+ "disposition": "disposition:1",+ "review_time": "1790294400",+ "reviewer": "a.analyst",+ "comment": "Confirmed beacon, host isolated.",+ "_time": "1790290800",+ # The notable's asset and identity fields. Enterprise Security+ # correlates assets on src/dest/dvc and identities on user/src_user.+ "src": "10.21.4.88",+ "dest": HOST,+ "dvc": HOST,+ "user": USER,+ "src_user": USER,+ }+ ]+}++_SENTINEL_INCIDENTS = {+ "value": [+ {+ "id": "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.SecurityInsights/incidents/1111-2222",+ "name": "1111-2222",+ "properties": {+ "incidentNumber": 42,+ "title": "Mass download by a single user",+ "description": "A single account downloaded 4.2 GB in ten minutes.",+ "status": "Closed",+ "severity": "High",+ "classification": "BenignPositive",+ "classificationReason": "SuspiciousButExpected",+ "classificationComment": "Quarterly data export by the finance team.",+ "createdTimeUtc": "2026-09-20T08:00:00Z",+ "lastModifiedTimeUtc": "2026-09-20T10:00:00Z",+ "closedBy": {"userPrincipalName": "[email protected]"},+ "relatedAnalyticRuleIds": ["/rules/mass-download"],+ },+ }+ ]+}++_SENTINEL_ENTITIES = {+ "entities": [+ {+ "id": "/entities/acc-1",+ "name": "acc-1",+ "kind": "Account",+ "properties": {"accountName": USER, "friendlyName": USER, "upnSuffix": "example.com"},+ },+ {+ "id": "/entities/host-1",+ "name": "host-1",+ "kind": "Host",+ "properties": {"hostName": HOST, "friendlyName": HOST, "netBiosName": "FIN-WKS-0423"},+ },+ ],+ "metaData": [{"entityKind": "Account", "count": 1}, {"entityKind": "Host", "count": 1}],+}++#: A detection alert as `.alerts-security.alerts-*` stores it: the+#: `kibana.alert.*` fields as literal dotted keys, the ECS fields copied from+#: the source document as nested objects. `critical` is deliberate — it is the+#: value the connector's `medium` default silently replaces.+_ELASTIC_HITS = {+ "hits": {+ "hits": [+ {+ "_index": ".internal.alerts-security.alerts-default-000001",+ "_id": "sig-1",+ "_source": {+ "@timestamp": "2026-09-15T08:00:00.000Z",+ "kibana.alert.uuid": "sig-1",+ "kibana.alert.rule.name": "Potential Credential Dumping via LSASS",+ "kibana.alert.rule.uuid": "rule-abc",+ "kibana.alert.severity": "critical",+ "kibana.alert.risk_score": 73,+ "kibana.alert.reason": "process lsass.exe accessed by rundll32.exe",+ "kibana.alert.workflow_status": "closed",+ "kibana.alert.workflow_tags": ["false_positive"],+ "kibana.alert.workflow_status_updated_at": "2026-09-15T09:30:00.000Z",+ "kibana.alert.workflow_user": "d.analyst",+ "event": {"kind": "signal"},+ "host": {"name": HOST, "os": {"family": "windows"}},+ "user": {"name": USER, "domain": "CORP"},+ },+ }+ ]+ }+}++_QRADAR_REASONS = [+ {"id": 1, "text": "False-Positive, Tuned"},+ {"id": 3, "text": "Policy Violation"},+]++#: Offense types are site-configurable, which is why the reader resolves them+#: from the appliance instead of hardcoding the stock ids.+_QRADAR_OFFENSE_TYPES = [+ {"id": 0, "name": "Source IP", "property_name": "sourceIP", "custom": False, "database_type": "COMMON"},+ {"id": 3, "name": "Username", "property_name": "username", "custom": False, "database_type": "COMMON"},+ {"id": 7, "name": "Hostname", "property_name": "hostName", "custom": False, "database_type": "EVENTS"},+]++_QRADAR_OFFENSES = [+ {+ "id": 501,+ "description": "Multiple Login Failures for Single Username\n",+ "status": "CLOSED",+ "severity": 8,+ "magnitude": 7,+ "offense_type": 3,+ "offense_source": USER,+ "event_count": 42,+ "start_time": 1790287200000,+ "close_time": 1790294400000,+ "last_updated_time": 1790294400000,+ "closing_reason_id": 1,+ "closing_user": "e.analyst",+ },+ {+ "id": 502,+ "description": "Outbound Data Transfer\n",+ "status": "CLOSED",+ "severity": 9,+ "magnitude": 9,+ "offense_type": 7,+ "offense_source": HOST,+ "event_count": 11,+ "start_time": 1790290800000,+ "close_time": 1790298000000,+ "last_updated_time": 1790298000000,+ "closing_reason_id": 3,+ "closing_user": "f.analyst",+ },+]++_DEFENDER_ALERTS = {+ "value": [+ {+ "id": "da637472900382838869_1364969609",+ "incidentId": 1126093,+ "assignedTo": "g.analyst",+ "severity": "High",+ "status": "Resolved",+ "classification": "TruePositive",+ "determination": "Malware",+ "investigationState": "Benign",+ "detectionSource": "WindowsDefenderAtp",+ "category": "Execution",+ "title": "Low-reputation arbitrary code executed by signed executable",+ "description": "Binaries signed by Microsoft can be used to run low-reputation arbitrary code.",+ "alertCreationTime": "2026-09-18T10:00:00Z",+ "firstEventTime": "2026-09-18T09:58:00Z",+ "lastEventTime": "2026-09-18T09:59:00Z",+ "lastUpdateTime": "2026-09-18T12:00:00Z",+ "resolvedTime": "2026-09-18T12:00:00Z",+ "machineId": "111e6dd8c833c8a052ea231ec1b19adaf497b625",+ "computerDnsName": HOST,+ "threatFamilyName": None,+ "mitreTechniques": ["T1055"],+ "relatedUser": {"userName": USER, "domainName": "CORP"},+ "evidence": [+ {+ "entityType": "User",+ "evidenceCreationTime": "2026-09-18T10:00:01Z",+ "accountName": USER,+ "domainName": "CORP",+ "userSid": "S-1-5-21-11111607-1111760036-109187956-75141",+ "userPrincipalName": f"{USER}@example.com",+ "detectionStatus": None,+ },+ {+ "entityType": "Process",+ "evidenceCreationTime": "2026-09-18T10:00:01Z",+ "sha256": "a4752c71d81afd3d5865d24ddb11a6b0c615062fcc448d24050c2172d2cbccd6",+ "fileName": "rundll32.exe",+ "filePath": "C:\\Windows\\SysWOW64",+ "processCommandLine": "rundll32.exe c:\\temp\\suspicious.dll,RepeatAfterMe",+ "detectionStatus": "Detected",+ },+ ],+ }+ ]+}+++# ---------------------------------------------------------------------------+# The three links+# ---------------------------------------------------------------------------+++async def _read_all() -> dict[str, list[Any]]:+ """Drive each reader's real HTTP path against its recorded payload.++ Returns the parsed :class:`ClosedFinding` rows, and also asserts the two+ requests whose *contents* decide whether a real vendor would have returned+ the host and user at all. A mock hands back whatever it is given, so a+ reader that never asked Splunk for ``user`` or QRadar for ``magnitude``+ would otherwise pass here and return nothing in production.+ """+ out: dict[str, list[Any]] = {}++ with respx.mock:+ respx.post(url__regex=r".*/oauth2/v2\.0/token").mock(return_value=httpx.Response(200, json={"access_token": "tok"}))++ splunk_job = respx.post(url__regex=r"https://splunk:8089/services/search/jobs$").mock(+ return_value=httpx.Response(201, json={"sid": "sid-1"})+ )+ respx.get(url__regex=r".*/services/search/jobs/sid-1/results.*").mock(return_value=httpx.Response(200, json=_SPLUNK_RESULTS))+ rows = await SplunkClient(host="https://splunk:8089", token="t").list_closed_notables(SINCE, UNTIL)+ spl = splunk_job.calls[0].request.content.decode().replace("+", " ")+ for field in ("dest", "user"):+ assert f" {field}" in spl, f"the SPL does not project {field!r}, so a real Splunk returns no such column: {spl}"+ out["splunk"] = [parse_splunk_notable(r) for r in rows]++ respx.get(url__regex=r".*/providers/Microsoft\.SecurityInsights/incidents\?.*").mock(+ return_value=httpx.Response(200, json=_SENTINEL_INCIDENTS)+ )+ entities = respx.post(url__regex=r".*/incidents/1111-2222/entities.*").mock(+ return_value=httpx.Response(200, json=_SENTINEL_ENTITIES)+ )+ rows = await SentinelClient("t", "c", "s", "sub", "rg", "ws").list_closed_incidents(SINCE, UNTIL)+ assert entities.called, "an incident carries no host or account of its own; they come from the entities endpoint"+ out["sentinel"] = [parse_sentinel_incident(r) for r in rows]++ respx.post(url__regex=r"https://es:9200/.*/_search").mock(return_value=httpx.Response(200, json=_ELASTIC_HITS))+ rows = await ElasticClient(es_url="https://es:9200", api_key="k").list_closed_signals(SINCE, UNTIL)+ out["elastic"] = [parse_elastic_signal(r) for r in rows]++ respx.get(url__regex=r".*/api/siem/offense_closing_reasons.*").mock(return_value=httpx.Response(200, json=_QRADAR_REASONS))+ respx.get(url__regex=r".*/api/siem/offense_types.*").mock(return_value=httpx.Response(200, json=_QRADAR_OFFENSE_TYPES))+ offenses = respx.get(url__regex=r".*/api/siem/offenses\?.*").mock(return_value=httpx.Response(200, json=_QRADAR_OFFENSES))+ rows = await QRadarClient(base_url="https://qradar", api_token="t").list_closed_offenses(SINCE, UNTIL)+ query = str(offenses.calls[0].request.url)+ for field in ("magnitude", "offense_source"):+ assert field in query, f"the offenses read does not request {field!r}, so QRadar omits it from the response: {query}"+ out["qradar"] = [parse_qradar_offense(r) for r in rows]++ respx.get(url__regex=r"https://api\.securitycenter\.microsoft\.com/api/alerts.*").mock(+ return_value=httpx.Response(200, json=_DEFENDER_ALERTS)+ )+ rows = await DefenderClient("t", "c", "s").list_resolved_alerts(SINCE, UNTIL)+ out["defender"] = [parse_defender_alert(r) for r in rows]++ return out+++_CONNECTOR_CHILD = """+import importlib, json, sys+payload = json.load(sys.stdin)+out = {}+for vendor, spec in payload.items():+ cls = getattr(importlib.import_module(spec["module"]), spec["cls"])(**spec["kwargs"])+ out[vendor] = [cls.normalize(dict(row)) for row in spec["rows"]]+json.dump(out, sys.stdout)+"""++_AGENTS_CHILD = """+import json, pathlib, sys, types+root = pathlib.Path(sys.argv[1])+for name, rel in (("app", "app"), ("app.replay", "app/replay")):+ mod = types.ModuleType(name)+ mod.__path__ = [str(root / rel)]+ sys.modules[name] = mod+from app.replay.findings import HistoricalFinding+from app.replay.normalize import to_fused_envelope++payload = json.load(sys.stdin)+out = {}+for vendor, rows in payload.items():+ out[vendor] = [+ to_fused_envelope(+ HistoricalFinding.from_mapping(row["finding"]),+ row["normalized"],+ tenant_id="00000000-0000-0000-0000-000000000001",+ connector_id=vendor,+ )+ for row in rows+ ]+json.dump(out, sys.stdout)+"""+++def _child(source: str, cwd: Path, payload: Any, *args: str) -> Any:+ """Run one link in a child interpreter rooted at the peer service.++ ``PYTHONPATH`` is cleared rather than inherited. ``python -c`` puts the+ working directory first, which is how the child resolves ``app`` to the+ peer service — but an inherited ``PYTHONPATH`` naming this service would+ put *its* ``app`` on the path too, and the test would then grade one+ service's code while reporting the other's.++ A non-zero exit is a failure, never a skip: this test exists to prove the+ three links agree, and a child that could not start proves nothing while+ reporting green.+ """+ assert cwd.is_dir(), f"{cwd} is missing; this test needs the monorepo checkout, not one service"+ proc = subprocess.run( # noqa: S603 - fixed argv, no shell+ [sys.executable, "-c", source, *args],+ cwd=cwd,+ env={k: v for k, v in os.environ.items() if k != "PYTHONPATH"},+ input=json.dumps(payload),+ capture_output=True,+ text=True,+ timeout=180,+ )+ assert proc.returncode == 0, f"child in {cwd.name} failed:\n{proc.stderr}"+ return json.loads(proc.stdout)++[email protected](scope="module")+def chain() -> dict[str, list[dict[str, Any]]]:+ """Reader rows, the connector envelope, and the fused alert, per vendor."""+ findings = asyncio.run(_read_all())++ normalized = _child(+ _CONNECTOR_CHILD,+ CONNECTORS,+ {+ vendor: {+ "module": _CONNECTORS[vendor][0],+ "cls": _CONNECTORS[vendor][1],+ "kwargs": _CONNECTORS[vendor][2],+ "rows": [dict(f.raw) for f in rows],+ }+ for vendor, rows in findings.items()+ },+ )++ envelopes = _child(+ _AGENTS_CHILD,+ AGENTS,+ {+ vendor: [{"finding": f.as_dict(), "normalized": n} for f, n in zip(rows, normalized[vendor], strict=True)]+ for vendor, rows in findings.items()+ },+ str(AGENTS),+ )++ return {+ vendor: [+ {"finding": f.as_dict(), "normalized": n, "alert": e["alert"]}+ for f, n, e in zip(rows, normalized[vendor], envelopes[vendor], strict=True)+ ]+ for vendor, rows in findings.items()+ }++[email protected]("vendor", ["splunk", "sentinel", "elastic", "defender"])+def test_triage_input_carries_host_user_and_severity(chain, vendor):+ """The three fields an analyst needs survive reader to normalize to triage."""+ alert = chain[vendor][0]["alert"]+ assert alert["hostname"] == HOST, f"{vendor}: host lost between the reader and the triage input"+ assert alert["username"] == USER, f"{vendor}: user lost between the reader and the triage input"+ assert alert["severity"] in {"info", "low", "medium", "high", "critical"}, f"{vendor}: {alert['severity']!r}"+++ ("vendor", "expected"),+ [("splunk", "high"), ("sentinel", "high"), ("elastic", "critical"), ("defender", "high")],+)+def test_severity_is_the_vendors_own_not_a_default(chain, vendor, expected):+ """A connector default that replaces the vendor's severity reads as measured.++ Elastic is the case that motivates this: against a ``_search`` hit every+ lookup in ``normalize()`` missed and the alert reached triage at ``medium``+ while the signal said ``critical``.+ """+ assert chain[vendor][0]["alert"]["severity"] == expected+++def test_qradar_offense_source_lands_in_the_slot_its_type_names(chain):+ """An offense indexes one entity, so the other slot must stay empty.++ ``offense_source`` is a bare string and ``offense_type`` is what says+ whether it is a username, a hostname or an address. Writing it into both+ slots would put a username in the hostname column of a forensic record.+ """+ by_id = {str(row["finding"]["finding_id"]): row["alert"] for row in chain["qradar"]}++ user_offense = by_id["501"]+ assert user_offense["username"] == USER+ assert not user_offense["hostname"], "a Username offense carries no host; QRadar did not report one"++ host_offense = by_id["502"]+ assert host_offense["hostname"] == HOST+ assert not host_offense["username"], "a Hostname offense carries no account; QRadar did not report one"++ assert user_offense["severity"] == "high"+ assert host_offense["severity"] == "critical"diff --git a/services/connectors/app/connectors/azure_defender.py b/services/connectors/app/connectors/azure_defender.pyindex 9e52258e5..0b8ee3acb 100644--- a/services/connectors/app/connectors/azure_defender.py+++ b/services/connectors/app/connectors/azure_defender.py@@ -243,6 +243,13 @@ class AzureDefenderConnector(BaseConnector):"actor": actor,"actor_email": actor_email,"host": host,+ # `actor` and `host` are this connector's own spelling and every+ # consumer downstream reads `username` / `hostname`, so the user+ # was dropped at the boundary while the host happened to survive+ # on an alias. Both names are emitted; neither is load-bearing+ # alone.+ "username": actor,+ "hostname": host,"service_source": raw.get("serviceSource"),"tactics": raw.get("mitreTechniques", []),"category": raw.get("category"),diff --git a/services/connectors/app/connectors/elastic.py b/services/connectors/app/connectors/elastic.pyindex 01e70bd03..0e20835ae 100644--- a/services/connectors/app/connectors/elastic.py+++ b/services/connectors/app/connectors/elastic.py@@ -202,6 +202,28 @@ class ElasticConnector(BaseConnector):"title": raw.get("kibana.alert.rule.name") or raw.get("rule.name") or "Elastic Alert","description": raw.get("kibana.alert.reason") or raw.get("message", ""),"severity": severity_map.get(severity, "medium"),+ "hostname": _ecs(raw, "host.name"),+ "username": _ecs(raw, "user.name"),"raw_event": raw,"created_at": raw.get("@timestamp"),}+++def _ecs(raw: dict[str, Any], path: str) -> Any:+ """Read an ECS field that may be a dotted key or a nested object.++ A detection alert stores its ``kibana.alert.*`` fields as literal dotted+ keys while the ECS fields copied from the source document keep the nested+ shape they had there; an ES|QL response names every column with the dotted+ path. Both forms reach this method depending on which read produced the+ row, so both are accepted rather than picking one and silently returning+ nothing for the other.+ """+ if raw.get(path) not in (None, ""):+ return raw[path]+ node: Any = raw+ for part in path.split("."):+ if not isinstance(node, dict):+ return None+ node = node.get(part)+ return node if node not in (None, "") else Nonediff --git a/services/connectors/app/connectors/microsoft_sentinel.py b/services/connectors/app/connectors/microsoft_sentinel.pyindex 87305c2c8..30825496d 100644--- a/services/connectors/app/connectors/microsoft_sentinel.py+++ b/services/connectors/app/connectors/microsoft_sentinel.py@@ -162,8 +162,35 @@ class MicrosoftSentinelConnector(BaseConnector):"description": props.get("description", ""),"severity": severity_map.get(props.get("severity", "Medium"), "medium"),"status": props.get("status"),+ "hostname": _entity(raw, "Host", "hostName"),+ "username": _entity(raw, "Account", "accountName"),"tactics": props.get("additionalData", {}).get("tactics", []),"alert_count": props.get("additionalData", {}).get("alertsCount", 0),"raw_event": props,"created_at": props.get("createdTimeUtc"),}+++def _entity(raw: dict[str, Any], kind: str, field: str) -> Any:+ """The first entity of one kind, read off a row that may not carry any.++ ``entities`` is **not** a property of the ARM incident resource: an+ incident carries a title, a severity and a classification, and its+ accounts and hosts live behind the incident's own entities endpoint. So+ this is conditional by construction — a plain incident read has none, and+ a reader that resolved them attaches them here.++ ``friendlyName`` is the fallback because it is the only name some entity+ kinds record, and an incident with one unnamed host is more useful to an+ analyst than an incident with no host at all. The first entity of a kind+ is taken because an incident can span several and the rest stay in+ ``raw_event``.+ """+ for entity in raw.get("entities") or []:+ if not isinstance(entity, dict) or entity.get("kind") != kind:+ continue+ props = entity.get("properties") or {}+ value = props.get(field) or props.get("friendlyName")+ if value:+ return value+ return Nonediff --git a/services/connectors/app/connectors/qradar.py b/services/connectors/app/connectors/qradar.pyindex 61ec16b2d..86cb4710b 100644--- a/services/connectors/app/connectors/qradar.py+++ b/services/connectors/app/connectors/qradar.py@@ -28,6 +28,15 @@ logger = structlog.get_logger()_MAX_OFFENSES = 200+#: An offense indexes exactly one entity, in ``offense_source``, and+#: ``offense_type`` is what says which kind it is. Matched against the type's+#: ``property_name`` (or its display name), normalised to lowercase, because a+#: site can rename the display string and can add its own types from a custom+#: property. An unrecognised type yields neither a host nor a user, which is+#: the honest reading of "this offense is indexed on something else".+_HOSTNAME_TYPES = {"hostname", "host name"}+_USERNAME_TYPES = {"username", "user name"}+class QRadarConnector(BaseConnector):"""IBM QRadar SIEM offenses."""@@ -175,8 +184,28 @@ class QRadarConnector(BaseConnector):f"status={raw.get('status')}"),"external_id": str(raw.get("id") or ""),+ "hostname": _typed_offense_source(raw, _HOSTNAME_TYPES),+ "username": _typed_offense_source(raw, _USERNAME_TYPES),"src_ip": (raw.get("offense_source") if raw.get("offense_source_summary") == "IP" else None),"event_type": f"qradar.offense.{raw.get('offense_type', 'unknown')}","created_at": raw.get("start_time"),"raw_event": raw,}+++def _typed_offense_source(raw: dict[str, Any], kinds: set[str]) -> Any:+ """``offense_source`` when the offense's type says it holds this kind.++ Returning it unconditionally would put whatever the offense is indexed on+ — an address, an event name, a log source — into both the hostname and the+ username column, and a username in the hostname column of a forensic+ record is a fabricated entity, not an approximation.++ ``offense_type_name`` is resolved from the appliance by whoever read the+ offense, because the offense itself carries only a number and QRadar lets+ a site define its own types. An unresolved offense is left untyped rather+ than guessed at against the stock id table.+ """+ if str(raw.get("offense_type_name") or "").strip().lower() not in kinds:+ return None+ return raw.get("offense_source") or Nonediff --git a/services/connectors/app/connectors/splunk.py b/services/connectors/app/connectors/splunk.pyindex 6bcf5de89..968af460e 100644--- a/services/connectors/app/connectors/splunk.py+++ b/services/connectors/app/connectors/splunk.py@@ -37,6 +37,20 @@ _SEVERITY_BY_URGENCY = {}+def _first(raw: dict[str, Any], *keys: str) -> Any:+ """The first key carrying a value, treating an empty string as absent.++ A search result carries only the columns its search named, and Splunk+ renders a column it has no value for as ``""`` rather than omitting it, so+ a plain ``or`` chain over ``.get()`` would stop at the empty one.+ """+ for key in keys:+ value = raw.get(key)+ if value not in (None, ""):+ return value+ return None++class SplunkConnector(BaseConnector):connector_id = "splunk"connector_name = "Splunk SIEM"@@ -289,7 +303,12 @@ class SplunkConnector(BaseConnector):"description": raw.get("description", ""),"severity": _SEVERITY_BY_URGENCY.get(str(raw.get("urgency", "medium")).lower(), "medium"),"src_ip": raw.get("src", raw.get("src_ip")),- "hostname": raw.get("host"),+ # `host` is Splunk's own indexed-source metadata — on a notable it+ # names the search head, not the machine the detection is about.+ # Enterprise Security correlates assets on src/dest/dvc and+ # identities on user/src_user, which is why those are read too.+ "hostname": _first(raw, "host", "dest", "dvc", "orig_host"),+ "username": _first(raw, "user", "src_user"),"raw_event": raw,"created_at": raw.get("_time"),}