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
depth(7.2): header, URL and attachment analysis, cited in the ledger (#1308)
Beenu Arora57591aac1b2d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1e88b9011..2235577c3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -231,6 +231,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **A reported message's headers, URLs and attachments are analysed once and+ cited where an auditor looks (depth 7.2).** Nothing in the tree read an+ `Authentication-Results` header before this — `grep -rl+ "authentication-results" services/` returned no match — so a message whose+ SPF and DMARC had both failed at the receiving boundary produced a verdict+ that had never looked. The analysis is three components in one pass, and+ the rule it turns on is that **an unanalysed artefact must never read as a+ clean one**, which is the same rule the submit path already applied to+ attachments and which `services/api/app/services/phishing/headers.py` now+ applies to authentication. SPF, DKIM and DMARC each carry three values, and+ the third is the point: `not_evaluated` is published rather than folded+ into either of the others, and `neutral`, `none`, `permerror` and+ `temperror` are **not** passes — treating them as passes is how a domain+ with a broken SPF record reads as authenticated. A URL on a deployment with+ no provider configured says so per URL rather than vanishing from the+ output, and that specific defect was found by a negative control that at+ first failed to fail, because the tests built their own result list instead+ of driving the producer. `analysed` and `unanalysed` are counted separately+ and never summed — in the dataclass, the response model and migration+ `111`'s column comment — because the sum is the number this product must+ not publish: five artefacts nothing examined, rendered as "5 artefacts, 0+ findings", says the opposite of what happened. The verdict is only ever+ raised, and SPF **and** DMARC must both fail to raise it, because a+ forwarded message routinely breaks SPF and flagging that would alert on+ every mailing list in the estate. Citations go into the investigation+ ledger as `evidence_cited` rows, one per component, written even when a+ component found nothing — a ledger with no row for the URL check cannot be+ told from one where the check passed. The ledger suite has no teardown by+ design: deleting a run cascades to its events, migration `008`'s trigger+ refuses, and defeating an append-only control to tidy a test fixture would+ be the wrong fix.- **Reported phish now goes from intake to purge (depth 7.1).** The gap wasnot that phishing was unhandled — `POST /phishing/submit` has triagedartefacts since migration 015 — but that nothing in the product coulddiff --git a/DEPTH_PROGRESS.md b/DEPTH_PROGRESS.mdindex daed72e35..8168ad034 100644--- a/DEPTH_PROGRESS.md+++ b/DEPTH_PROGRESS.md@@ -418,7 +418,7 @@ invented fields on the first run of the gate.## Phase 7: Phishing operations- [x] **7.1** Intake to purge (gap-closure Phase 10 / parity 6.4)-- [ ] **7.2** Header, URL and attachment analysis+- [x] **7.2** Header, URL and attachment analysis- [ ] **7.3** Adversary-in-the-middle session reuse## Phase 8: Enterprise gates@@ -455,6 +455,7 @@ invented fields on the first run of the gate.| 2026-10-09 | 4.1 | Reproduced: `check_cloud_native_collection.py` on the unmodified tree reported all three collection paths absent. Implemented `aws_cloudtrail_s3` (SQS-notified S3 objects; management events, data events and VPC flow logs; delete-after-emit), `gcp_pubsub` (REST pull on a log-sink subscription; ack-after-read) and `azure_event_hubs` (Capture blobs over the Data Lake Gen2 JSON API, with a focused Avro OCF reader). Negative controls recorded in the PR: deleting the SQS message before the object is read, acknowledging the Pub/Sub batch before it is built, ignoring the Avro union branch index, and ignoring the flow-log header line each fail a named test, and all were restored. Connectors suite 1014 -> 1098 passed. || 2026-10-09 | 3.1 | All 74 decided. 50 translated into `wd-*` rules derived from each original's own clauses and replayed through the real engine (162 assertions); 24 refused with a reason across five kinds. `MAX_UNREACHABLE` 119 → 45, published executable 2,603 → 2,529, windowed 18 → 68. Three findings recorded as D4–D6 below. || 2026-10-11 | 7.1 | Reproduced: against the unmodified tree, `registry.list_vendors_for_capability` returned `[]` for all five mailbox verbs and `dispatcher.dispatch` answered `executor_not_found` for `purge_email` over 79 registered builtin arms -- a phishing response that could block the sender's domain at the firewall and could not remove the message it arrived in. Added the five verbs to both halves of the vocabulary, two mail clients (Graph, Gmail with per-mailbox domain-wide delegation), ten vendor arms, migration `104`, three intake adapters, campaign grouping, the governed fan-out and a report-mailbox worker. Only documented vendor APIs: purge is a soft delete on both and `restore_email` is a real reverse; there is no tenant-wide sender block because neither vendor exposes one through these APIs, and the per-mailbox scope is in the summary an analyst reads rather than only in a docstring. Everything ships off. Negative controls recorded in the PR: defaulting the feature flag on reds four tests, inverting the verification probe's polarity reds two, reading the envelope sender instead of the preserved headers reds four adapter tests including the one asserting the report mailbox is not proposed for purge, incrementing `recipient_count` instead of recomputing it reds the grouping test, and dropping `recipient_count` from the per-mailbox dispatch reds the fan-out test -- which is the quiet way a SEVERE action becomes a MODERATE one. Gates: `check_action_contract` 86 -> 97 executors, `check_module_reachability` 981 -> 986 of 1014, `check_route_authz` 262 -> 265 authorizing with both ceilings unmoved, matrix 302 -> 303 rows. Actions suite 1158 -> 1228; api 44 new cases, 17 of them against a real Postgres with the full chain. Recorded as **PARTIAL**, not GATED: no Microsoft 365 or Google Workspace tenant was exercised (D-7.1). |+| 2026-10-11 | 7.2 | Reproduced: `grep -rl "authentication-results" services/` returned no match on the unmodified tree, so nothing in the product read a sender-authentication header and a message whose SPF and DMARC had both failed produced a verdict that had never looked. Built header analysis with a three-valued result, URL submission through the existing sandbox contract, the attachment hash lookup the submit path already had, and `evidence_cited` citations into the investigation ledger. Migration `111` stores the headers on the submission so a retriage replays them rather than re-fetching a message the purge has usually removed. `analysed` and `unanalysed` are counted separately in three places and summed in none. Negative controls: treating `none`/`neutral` as passes reds two tests; silently skipping an unanalysable URL reds three. **That second control is the finding worth keeping** -- it failed to fail on the first attempt, because every test built its own `ArtefactResult` list and never ran the producer, so five cases were added that drive `analyse_message` with the registry patched empty. A second finding came from the ledger suite's teardown: deleting a run cascades to its events and migration 008's trigger refuses, so the fixture was dropped rather than the append-only control defeated. Gates: matrix 303 -> 304 rows (300 GATED), `check_text_bind_casts` and `check_raw_sql_columns` clean over 6 new columns, `check_route_authz` unmoved. 45 new api cases, 6 of them against a real Postgres with the full chain. |### D-7.1 -- No Microsoft 365 or Google Workspace tenant was exerciseddiff --git a/ROADMAP.md b/ROADMAP.mdindex 2a7dc5819..125374b2a 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -45,7 +45,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **303 rows — 299 GATED / 4 PARTIAL / 0 NO GATE**. Four rows are PARTIAL. "A reported phishing message can be grouped into a campaign and purged across its recipients" is PARTIAL because no Microsoft 365 or Google Workspace tenant is reachable from CI or from this maintainer, so every vendor claim in depth 7.1 rests on the documented request shape and a recorded mock; it returns to GATED when a live tenant is available. "The retention window a tenant chooses is the one the lake honours" stays PARTIAL until a live ClickHouse test watches a row survive past the old 90-day boundary. "Cloud-native collection" stays PARTIAL until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification. And "SSO completes a sign-in": fix pass 4.1 drove both handlers end to end against real Postgres and real signed assertions, and it stays PARTIAL until the containerised-IdP leg of `sso-live.yml` has been observed to pass, because the identity providers in that suite are trust material this repository authors. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **304 rows — 300 GATED / 4 PARTIAL / 0 NO GATE**. Four rows are PARTIAL. "A reported phishing message can be grouped into a campaign and purged across its recipients" is PARTIAL because no Microsoft 365 or Google Workspace tenant is reachable from CI or from this maintainer, so every vendor claim in depth 7.1 rests on the documented request shape and a recorded mock; it returns to GATED when a live tenant is available. "The retention window a tenant chooses is the one the lake honours" stays PARTIAL until a live ClickHouse test watches a row survive past the old 90-day boundary. "Cloud-native collection" stays PARTIAL until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification. And "SSO completes a sign-in": fix pass 4.1 drove both handlers end to end against real Postgres and real signed assertions, and it stays PARTIAL until the containerised-IdP leg of `sso-live.yml` has been observed to pass, because the identity providers in that suite are trust material this repository authors. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 90473f0d5..ef13f1440 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 299 rows+The last row is the one worth reading first. It is the honest index: 300 rows`GATED`, 4 `PARTIAL`, and a ratchet that refuses to let a row sit at`NO GATE`. Re-read the figure from the table rather than from here — a countcopied into prose goes stale in silence, which is whydiff --git a/apps/docs/docs/operations/mailbox-remediation.md b/apps/docs/docs/operations/mailbox-remediation.mdindex 984d841a4..762ce1b81 100644--- a/apps/docs/docs/operations/mailbox-remediation.md+++ b/apps/docs/docs/operations/mailbox-remediation.md@@ -108,6 +108,68 @@ digits and long opaque tokens, so `Invoice 10452 overdue` andand why the basis is published. You are entitled to know which kind of claimyou are about to act on across forty mailboxes.+## What the analysis says, and what it refuses to say++Every reported message is analysed on intake and again on retriage: the+headers, up to five URLs, and every attachment digest the reporter supplied.++### Sender authentication has three values, not two++| Value | Means |+|---|---|+| `pass` | A receiving boundary evaluated the check and it passed |+| `fail` | A receiving boundary evaluated the check and it failed |+| `not_evaluated` | **Nobody checked** |++The third is the one that matters. A message with no `Authentication-Results`+header has not passed SPF — it has not been evaluated, usually because it+never crossed a boundary that evaluates. AiSOC publishes that as+`not_evaluated` and never folds it into either of the other two. The RFC 8601+tokens `none`, `neutral`, `policy`, `permerror` and `temperror` are also+`not_evaluated`, because each one means the check did not reach a verdict,+and reading them as passes is how a domain with a broken SPF record comes to+look authenticated.++Every method gets an entry even when no clause mentions it, so a console+cannot show "SPF fail" and silently omit DMARC.++### The verdict is only ever raised++A malicious artefact raises the verdict to `malware`. **SPF and DMARC both+failing** raises it to `phishing` — both, not either, because a forwarded+message routinely breaks SPF and a DMARC pass on DKIM alignment is the normal+outcome; flagging one failure alone would alert on every mailing list in the+estate. `not_evaluated` raises nothing and lowers nothing.++### Counts are never summed++The analysis reports `artefacts_analysed` and `artefacts_unanalysed`+separately and the API does not add them up. Five artefacts on a deployment+with no sandbox configured is an analysis that examined nothing, and a+surface rendering "5 artefacts, 0 findings" has said the opposite of what+happened. A URL that could not be submitted appears in the output saying so;+it does not vanish from it.++Attachments are **hash lookup only** on this path, never an upload. Intake+runs unattended on whatever arrives, and an unattended path that can upload is+one misconfiguration away from disclosing every attachment a tenant receives.+To have a file analysed, post it to `/sandbox/files`, where the tenant's+upload policy is enforced.++### Where the evidence goes++Each analysis writes one investigation-ledger run and one `evidence_cited`+event per component — headers, URLs, attachments — **including** components+that found nothing. A ledger with no row for the URL check cannot be told+from one where the check passed. The run id comes back on the response as+`analysis_run_id`, and `None` means the ledger write failed, which is+reported rather than hidden.++The headers are stored on the submission (migration `111`), so a retriage+replays them instead of re-fetching the message. That ordering is not+incidental: by the time anybody asks why a message was purged, the purge has+usually removed it.+## The purge, and what it will ask of you```bashdiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex e7ba4efd4..4f0dd3e33 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -311,11 +311,12 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| An outbound event webhook is signed, retried, and its failures are visible | `apps/docs/docs/operations/notifications.md` (outbound webhooks) | `ci.yml :: Python — Tests` (api, `test_delivery_5_2.py::TestWebhookSignature` and `::TestWebhookDelivery` — signature round-trip through the real client, a modified body and a re-stamped timestamp both refused, five malformed headers refused without raising, the 4xx/5xx split, the ladder ending in the dead-letter view, byte-identical bodies across attempts, and an undecryptable secret killing the delivery rather than sending it unsigned) | core | GATED | AiSOC could be told things and could tell nobody anything: `grep -rln outbound_webhook` over `services/` and `apps/` returned nothing. The signature is the shape Stripe, GitHub and Slack use, because a scheme nobody recognises is a scheme nobody verifies. The retry queue and the dead-letter list are one table at different points on one ladder, so there is no window where a delivery is in neither || The fix for `fake_tool_output` is measured on payloads authored after it was frozen, and that measurement carries no floor | `services/agents/tests/adversarial/behavioural_holdout.py`; `apps/docs/docs/benchmark.md` | `ci.yml :: Python — Tests` (`tests/adversarial/test_behavioural_holdout.py` pins the held-out flip, catch and unsafe-action rates **exactly**, in both directions, so a change moving any of them either way has to say so in the same commit; every payload is asserted to carry a steering phrase or an action trigger so the denominator cannot be padded with strings that were never going to work, asserted disjoint from the tuned corpus, and every declared seam asserted to have a payload) + `test_tool_result_channel.py` (the channel invariant the guard rule rests on, walked out of the service's syntax tree, plus a 20-entry good corpus and a negative control that lifts the rule from the table and watches the family reopen) | core | GATED | **Flip 85% and catch 10% on 20 held-out payloads, against 0% and 100% on the 3 tuned ones.** Published rather than closed, because tuning until they agree is the move this repository has measured the cost of. A worst-case probe rather than a neutral sample: the tuned payloads predate the fix and the held-out ones were aimed at named properties of it, so part of the gap is adversarial-versus-naive. The sharper finding is that the guard and the ledger-provenance demotion **share a detector**, so they are one control counted twice rather than two layers, which a test asserts. No floor and no ratchet, deliberately: a target on a held-out set is an instruction to tune against it, and a test fails if the two rates ever agree so that agreement cannot pass silently || A reported phishing message can be grouped into a campaign and purged across its recipients, at the tier the recipient count earns | `apps/docs/docs/operations/mailbox-remediation.md`; depth plan 7.1 | `ci.yml :: Python — Lint & Type-check` (`check_action_contract.py` — the five mailbox verbs are in both halves of the vocabulary, every one has an executor, `purge_email` declares `restore_email` as a platform reverse that exists, and the probe it declares is reachable through an `ActionType`; `check_module_reachability.py` — the intake adapters have a production caller, which is the report-mailbox worker rather than only the route) + `ci.yml :: Python — Tests` (actions, `test_mailbox_remediation.py` — 60 cases driving the real arms over `respx`: the Graph filter is asserted to carry the **bracketed** message id and to request `parentFolderId`, because a mock that answers whatever is asked cannot notice a field the query never requested; a hard `DELETE` route is wired to raise, so a purge that stopped being a soft delete fails rather than passes; a dry run is asserted to make **zero** HTTP calls; a mailbox with no copy answers FAILED with `match_count` 0 rather than counting toward a purge total; the rollback is asserted by call count and destination folder rather than by a boolean; and the verification probe's polarity has its own inverted-control test, because for a purge the confirming answer is an absence) + `ci.yml :: Python — Tests` (api, `test_phishing_intake_adapters.py` — 27 cases over the documented Graph, Gmail and `email_inbox` shapes, including the forwarded report where the reporter is the envelope sender) + `integration.yml` (api, `test_phishing_campaign_purge_live.py` — 17 cases against a real Postgres with the migration chain applied: two reports of one message join one campaign, `recipient_count` is recomputed rather than incremented, a 25-recipient campaign is `severe`/`mandatory_human` at every tier and every confidence, each mailbox gets its own dispatch carrying the campaign's count, and twenty of twenty-five purged is `partially_purged`) | core | PARTIAL (no Microsoft 365 or Google Workspace tenant is reachable from CI or from this maintainer, so every vendor claim rests on the documented request shape and a recorded mock. Two consequences stated rather than implied: nobody has observed Graph accept the `move` to `recoverableitemsdeletions` or Gmail accept the `trash`, and the Gmail filter and Graph inbox-rule bodies were written from the API reference rather than taken from a working call. Returns to GATED when a live tenant is available) | a maintainer-supplied M365 and Workspace test tenant |+| A reported message's sender authentication, URLs and attachments are analysed, and an unanalysed artefact never reads as a clean one | `apps/docs/docs/operations/mailbox-remediation.md`; depth plan 7.2 | `ci.yml :: Python — Tests` (api, `test_phishing_message_analysis.py` — 39 cases: every RFC 8601 non-verdict token (`none`, `neutral`, `policy`, `permerror`, `temperror`) and an absent header all resolve to `not_evaluated` rather than to a pass, each producing its own indicator; every method gets an entry even when no clause mentions it, so a console cannot render `SPF fail` and silently omit DMARC; the ARC-sealed header is read when the plain one is absent, which is the forwarded-report case; the verdict merge raises on SPF **and** DMARC failing and not on either alone; and a socket-patched test asserts header analysis reaches no network. Five of the cases drive `analyse_message` itself with the provider registry patched empty, because the hand-built-fixture version of this suite stayed green when the 'no provider configured' branch was deleted — a test that asserts on a fixture it wrote cannot notice a producer that stopped producing) + `integration.yml` (api, `test_phishing_analysis_ledger_live.py` — 6 cases against a real Postgres: one run and one `evidence_cited` row per component with `seq` dense from one, the unevaluated list carried in the payload, an unanalysed URL cited as unanalysed with 'not a clean verdict' in the summary, the rows immutable against migration 008's real trigger, and an unwritable ledger returning `None` rather than raising) | core | GATED | — |## Summary-- Total: 303-- GATED: 299+- Total: 304+- GATED: 300- PARTIAL: 4- NO GATE: 0diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 4892fe996..6424c87f0 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -33302,6 +33302,25 @@ components:campaign_created:type: booleantitle: Campaign Created+ analysis_run_id:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Analysis Run Id+ auth_results:+ additionalProperties:+ type: string+ type: object+ title: Auth Results+ artefacts_analysed:+ type: integer+ title: Artefacts Analysed+ default: 0+ artefacts_unanalysed:+ type: integer+ title: Artefacts Unanalysed+ default: 0grouping_basis:type: stringtitle: Grouping Basisdiff --git a/services/api/app/api/v1/endpoints/phishing.py b/services/api/app/api/v1/endpoints/phishing.pyindex dbfc73a43..d36743d45 100644--- a/services/api/app/api/v1/endpoints/phishing.py+++ b/services/api/app/api/v1/endpoints/phishing.py@@ -43,6 +43,7 @@ from app.core.airgap import AirgapViolation, enforce_airgap_for_urlfrom app.services.autonomy_effective import resolve_effective_tierfrom app.services.llm_safety import LLMContractViolation, safe_chat_completions_requestfrom app.services.model_aliases import chat_completions_url, resolve_api_key, resolve_model_alias+from app.services.phishing import analysis as phishing_analysisfrom app.services.phishing import campaigns as phishing_campaignsfrom app.services.phishing import intake as phishing_intakefrom app.services.phishing import purge as phishing_purge@@ -280,6 +281,61 @@ def _merge_attachment_verdict(result: TriageResult, indicators: list[dict[str, A)+def _merge_analysis_verdict(result: TriageResult, analysis: Any) -> TriageResult:+ """Fold a full message analysis into the triage result (depth 7.2).++ The same rule ``_merge_attachment_verdict`` follows, extended to the two+ components 7.2 adds, and it is one rule: **a verdict is only ever raised+ here.** An artefact nothing recognised says nothing about the message, and+ a header check nobody ran says less than that.++ Two sources can raise it:++ * a malicious verdict on an attachment or a URL, which is stronger+ evidence than any amount of keyword matching on the body;+ * **both** SPF and DMARC failing, which is the authentication result a+ receiving boundary has already judged. One failure alone does not,+ because a forwarded message routinely breaks SPF and a DMARC pass on+ DKIM alignment is the normal outcome — treating that as phishing would+ flag every mailing list in the estate.++ ``not_evaluated`` never raises anything, and never lowers anything+ either. It is carried into the indicators so an analyst sees it, which is+ the whole of what an unevaluated check is worth.+ """+ indicators = [*result.indicators, *analysis.as_indicators()]+ failed = set(analysis.headers.failed_methods)++ if analysis.malicious_count:+ return TriageResult(+ verdict="malware",+ confidence=max(result.confidence, 0.9),+ indicators=indicators,+ mitre_technique=result.mitre_technique or "T1566.001",+ summary=f"{result.summary} An artefact was identified as malicious by analysis.".strip(),+ )++ if {"spf", "dmarc"} <= failed and result.verdict in ("benign", "unknown"):+ return TriageResult(+ verdict="phishing",+ confidence=max(result.confidence, 0.75),+ indicators=indicators,+ mitre_technique=result.mitre_technique or "T1566",+ summary=(+ f"{result.summary} SPF and DMARC both failed at the receiving boundary, so the "+ f"sending domain did not authorise this message."+ ).strip(),+ )++ return TriageResult(+ verdict=result.verdict,+ confidence=result.confidence,+ indicators=indicators,+ mitre_technique=result.mitre_technique,+ summary=result.summary,+ )++def _row_to_submission(row: Any) -> SubmissionResponse:return SubmissionResponse(id=row.id,@@ -378,6 +434,17 @@ class ReportResponse(BaseModel):submission: SubmissionResponsecampaign_id: uuid.UUID | Nonecampaign_created: bool+ #: Where the header, URL and attachment analysis was cited. ``None``+ #: means the ledger write failed, which is reported rather than hidden:+ #: a citation nobody can find is the thing 7.2 exists to close.+ analysis_run_id: uuid.UUID | None = None+ #: SPF / DKIM / DMARC as ``pass | fail | not_evaluated``. The third value+ #: is published, never folded into either of the others.+ auth_results: dict[str, str] = Field(default_factory=dict)+ #: Never summed by this model, and a client that sums them has made the+ #: claim this split exists to prevent.+ artefacts_analysed: int = 0+ artefacts_unanalysed: int = 0#: Which attribute joined this report to its campaign, and whether that#: attribute is a fact about the message or a similarity judgement.#: Published rather than left to the reader to infer from the basis@@ -416,16 +483,19 @@ async def report(except ValueError as exc:raise HTTPException(status_code=422, detail=str(exc)) from exc- # The same triage the manual path runs, on the message's own text. The- # attachment lookups keep their honest "not analysed" indicator: an- # unanalysed attachment must never read as a clean one.+ # Depth 7.2. Headers, URLs and attachments in one pass, with the honest+ # states intact: an unevaluated SPF result, an unsubmitted URL and an+ # unanalysed attachment each say so rather than being omitted. This+ # replaces the submit path's attachment-only lookup, which it subsumes.+ analysis = await phishing_analysis.analyse_message(message)+try:result = await _triage("email", message.body_text, list(message.urls))except AirgapViolation:result = Noneif not result:result = _heuristic_triage(message.body_text, list(message.urls))- result = _merge_attachment_verdict(result, await _attachment_indicators(list(message.attachment_hashes)))+ result = _merge_analysis_verdict(result, analysis)now = datetime.now(UTC)sub_id = uuid.uuid4()@@ -434,11 +504,13 @@ async def report(id, tenant_id, submitted_by, artifact_kind, raw_content, sender, subject,urls, verdict, confidence, indicators, mitre_technique,internet_message_id, recipients, reported_by, intake_source,+ headers, auth_results, analysed_at, artefacts_analysed, artefacts_unanalysed,submitted_at, triaged_at, created_at) VALUES (:id, :tenant_id, :by, 'email', :content, :sender, :subject,CAST(:urls AS text[]), :verdict, :conf, CAST(:iocs AS jsonb), :mitre,:message_id, CAST(:recipients AS text[]), :reported_by, :source,+ CAST(:headers AS jsonb), CAST(:auth AS jsonb), :now, :analysed, :unanalysed,:now, :now, :now) RETURNING *""").bindparams(@@ -457,11 +529,28 @@ async def report(recipients=list(message.recipients),reported_by=message.reported_by,source=message.intake_source,+ headers=json.dumps(message.headers),+ auth=json.dumps(analysis.headers.authentication),+ analysed=analysis.analysed_count,+ unanalysed=analysis.unanalysed_count,now=now,)try:row = (await db.execute(insert)).fetchone()campaign = await phishing_campaigns.record_report(db, tenant_id=user.tenant_id, message=message, submission_id=sub_id)+ # Cited before the commit, so an analysis and its citations land+ # together or not at all. A submission whose evidence rows are+ # missing is the state an auditor cannot distinguish from one that+ # was never analysed.+ run_id = await phishing_analysis.cite_to_ledger(+ db, tenant_id=user.tenant_id, submission_id=sub_id, message=message, analysis=analysis+ )+ if run_id is not None:+ await db.execute(+ text("UPDATE aisoc_phishing_submissions SET analysis_run_id = :run WHERE id = :id AND tenant_id = :tenant_id").bindparams(+ run=run_id, id=sub_id, tenant_id=user.tenant_id+ )+ )await db.commit()except Exception as exc:await db.rollback()@@ -475,6 +564,10 @@ async def report(grouping_basis=campaign.grouping_basis if campaign else "",grouping_is_factual=(campaign.grouping_basis in phishing_campaigns.FACTUAL_BASES) if campaign else False,recipient_count=campaign.recipient_count if campaign else 0,+ analysis_run_id=run_id,+ auth_results=analysis.headers.authentication,+ artefacts_analysed=analysis.analysed_count,+ artefacts_unanalysed=analysis.unanalysed_count,)@@ -645,18 +738,36 @@ async def retriage(result = Noneif not result:result = _heuristic_triage(existing.raw_content, list(existing.urls or []))- # Re-run the attachment lookups too: a retriage exists because something- # changed, and a provider that had never seen the file may have now.+ # Re-run the whole analysis, not only the attachment lookups: a retriage+ # exists because something changed, and that is as true of a sandbox that+ # has since seen the URL as of one that has since seen the file. The+ # headers come from the row rather than from a mailbox, which is the+ # reason migration 111 stores them -- by the time anybody asks why, the+ # purge has usually removed the message.prior_hashes = [str(i.get("value")) for i in (existing.indicators or []) if isinstance(i, dict) and i.get("kind") == "hash" and i.get("value")]- result = _merge_attachment_verdict(result, await _attachment_indicators(list(dict.fromkeys(prior_hashes))))+ replayed = phishing_intake.ReportedMessage(+ intake_source=str(getattr(existing, "intake_source", "manual") or "manual"),+ internet_message_id=str(getattr(existing, "internet_message_id", "") or ""),+ sender=existing.sender or "",+ subject=existing.subject or "",+ recipients=tuple(getattr(existing, "recipients", None) or ()),+ urls=tuple(existing.urls or ()),+ attachment_hashes=tuple(dict.fromkeys(prior_hashes)),+ headers=dict(getattr(existing, "headers", None) or {}),+ body_text=existing.raw_content or "",+ )+ analysis = await phishing_analysis.analyse_message(replayed)+ result = _merge_analysis_verdict(result, analysis)now = datetime.now(UTC)q = text("""UPDATE aisoc_phishing_submissionsSET verdict = :verdict, confidence = :conf, indicators = CAST(:iocs AS jsonb),- mitre_technique = :mitre, triaged_at = :now+ mitre_technique = :mitre, triaged_at = :now,+ auth_results = CAST(:auth AS jsonb), analysed_at = :now,+ artefacts_analysed = :analysed, artefacts_unanalysed = :unanalysedWHERE id = :id AND tenant_id = :tenant_id RETURNING *""").bindparams(id=submission_id,@@ -665,10 +776,24 @@ async def retriage(conf=result.confidence,iocs=json.dumps(result.indicators),mitre=result.mitre_technique,+ auth=json.dumps(analysis.headers.authentication),+ analysed=analysis.analysed_count,+ unanalysed=analysis.unanalysed_count,now=now,)try:row = (await db.execute(q)).fetchone()+ # Cited here too: an analysis that ran and left no record is exactly+ # the state 7.2 exists to close.+ run_id = await phishing_analysis.cite_to_ledger(+ db, tenant_id=user.tenant_id, submission_id=submission_id, message=replayed, analysis=analysis+ )+ if run_id is not None:+ await db.execute(+ text("UPDATE aisoc_phishing_submissions SET analysis_run_id = :run WHERE id = :id AND tenant_id = :tenant_id").bindparams(+ run=run_id, id=submission_id, tenant_id=user.tenant_id+ )+ )await db.commit()return _row_to_submission(row)except Exception as exc:diff --git a/services/api/app/services/phishing/analysis.py b/services/api/app/services/phishing/analysis.pynew file mode 100644index 000000000..03f76bf01--- /dev/null+++ b/services/api/app/services/phishing/analysis.py@@ -0,0 +1,413 @@+"""Headers, URLs and attachments analysed once, and cited where an auditor looks.++Depth 7.2. The three analyses already had homes of a sort — headers nowhere,+URLs nowhere, attachment digests through+:func:`app.services.sandbox.enrichment.enrich_file_hash` — and none of them+left a record anybody could replay. A verdict an analyst cannot trace back to+what produced it is a verdict they have to re-derive, which is most of the+work the product claims to remove.++So this module does two things: it runs the three analyses over one reported+message, and it writes what each one found into the investigation ledger as+``evidence_cited`` rows.++The honesty rule, restated because it is the whole point+---------------------------------------------------------+**An unanalysed artefact must never read as a clean one.** The submit path+already refuses to skip an empty attachment block, and this module extends the+same rule to the other two:++* no sender-authentication header is ``not_evaluated``, three times over, each+ with its own indicator saying no boundary recorded a verdict;+* no configured sandbox is ``not_analysed`` per URL, naming the absence,+ never an empty list;+* a provider that could not be reached is ``could_not_check``, which is not+ ``benign``.++Counting is the discipline that makes it stick: :class:`MessageAnalysis`+carries ``analysed`` and ``unanalysed`` separately, so a caller cannot add+them up by accident and a surface cannot render zero findings as zero risk.++Why URLs are submitted and attachments are not+-----------------------------------------------+A URL is a public address; sending one to a sandbox discloses that somebody+is interested in it, which the upload policy treats as acceptable and+``analyse_url`` does not gate. An attachment is the customer's file, and+sending it is a disclosure the tenant has to have allowed — so this path does+hash lookup only, exactly as ``POST /phishing/submit`` does, and the door for+an actual upload stays ``POST /sandbox/files`` where the policy is enforced.++Nothing here raises+--------------------+A sandbox outage, an unreachable ledger or a provider returning nonsense all+degrade to a recorded "could not check". An analysis that fails loudly in the+middle of phishing triage takes the triage with it.+"""++from __future__ import annotations++import json+import uuid+from dataclasses import dataclass, field+from datetime import UTC, datetime+from typing import Any++import structlog+from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession++from app.services.phishing.headers import HeaderAnalysis, analyse_headers+from app.services.phishing.intake import ReportedMessage+from app.services.sandbox.enrichment import enrich_file_hash+from app.services.sandbox.registry import build_registry+from app.services.sandbox.service import analyse_url++logger = structlog.get_logger(__name__)++#: How many URLs are submitted per message. A phishing mail routinely carries+#: twenty links, nineteen of which are the sender's footer; submitting all of+#: them spends a provider's quota on an unsubscribe link.+MAX_URLS_ANALYSED = 5++#: Matches the submit path's cap, so the two agree about how much of a+#: message is examined.+MAX_ATTACHMENTS_ANALYSED = 10++#: The ledger `kind` an auditor filters on. Already in migration 008's+#: documented vocabulary, so this reuses it rather than widening the column.+EVIDENCE_KIND = "evidence_cited"++#: The agent name every row here carries. Not an LLM agent — this analysis+#: places no model call — and named so plainly that a reader of the ledger+#: cannot mistake it for one.+ANALYSIS_AGENT = "aisoc-phishing-analysis"+++@dataclass+class ArtefactResult:+ """One URL or one attachment, and what came back."""++ kind: str+ value: str+ outcome: str+ detail: str+ provider: str = ""+ verdict: str = ""++ @property+ def analysed(self) -> bool:+ """``True`` only when a provider returned a verdict.++ ``pending`` is deliberately not analysed: a submission accepted is+ not a result, and the same distinction keeps ``awaiting_completion``+ out of the executed set on the action side.+ """+ return self.outcome == "known"+++@dataclass+class MessageAnalysis:+ headers: HeaderAnalysis+ urls: list[ArtefactResult] = field(default_factory=list)+ attachments: list[ArtefactResult] = field(default_factory=list)+ #: The ledger run these citations were written to, when one was written.+ run_id: uuid.UUID | None = None++ @property+ def artefacts(self) -> list[ArtefactResult]:+ return [*self.urls, *self.attachments]++ @property+ def analysed_count(self) -> int:+ return sum(1 for a in self.artefacts if a.analysed)++ @property+ def unanalysed_count(self) -> int:+ """Counted separately from the analysed ones, never summed with them.++ Three URLs and two attachments with no provider configured is an+ analysis that examined nothing, and a surface that renders "5+ artefacts, 0 findings" has said the opposite of what happened.+ """+ return sum(1 for a in self.artefacts if not a.analysed)++ @property+ def malicious_count(self) -> int:+ return sum(1 for a in self.artefacts if a.verdict == "malicious")++ def as_indicators(self) -> list[dict[str, Any]]:+ """Everything found, in the shape the submissions table already holds."""+ out = self.headers.as_indicators()+ for artefact in self.artefacts:+ out.append(+ {+ "kind": artefact.kind,+ "value": artefact.value,+ "note": artefact.detail,+ **({"provider": artefact.provider} if artefact.provider else {}),+ **({"verdict": artefact.verdict} if artefact.verdict else {}),+ }+ )+ return out++ def summary(self) -> str:+ parts = [self.headers.summary()]+ if self.artefacts:+ parts.append(+ f"{self.analysed_count} of {len(self.artefacts)} artefact(s) were analysed"+ + (f", {self.malicious_count} malicious" if self.malicious_count else "")+ + (f"; {self.unanalysed_count} could not be" if self.unanalysed_count else "")+ )+ return ". ".join(parts)+++async def _analyse_urls(urls: tuple[str, ...]) -> list[ArtefactResult]:+ results: list[ArtefactResult] = []+ try:+ registry = build_registry()+ usable = registry.usable_names()+ except Exception as exc: # noqa: BLE001 - a registry failure is "could not check"+ logger.warning("phishing_analysis.registry_failed", error=str(exc)[:300])+ usable = []+ registry = None # type: ignore[assignment]++ for url in urls[:MAX_URLS_ANALYSED]:+ if not usable or registry is None:+ results.append(+ ArtefactResult(+ kind="url",+ value=url,+ outcome="no_provider",+ detail=(+ "This URL was not analysed: no file-and-URL analysis provider is configured "+ "for this deployment. This is not a clean verdict."+ ),+ )+ )+ continue+ for name in usable:+ provider = registry.get(name)+ if provider is None: # pragma: no cover - usable_names said otherwise+ continue+ try:+ result = await analyse_url(provider, url, registry=registry)+ except Exception as exc: # noqa: BLE001+ logger.warning("phishing_analysis.url_failed", provider=name, error=str(exc)[:300])+ results.append(+ ArtefactResult(+ kind="url",+ value=url,+ outcome="could_not_check",+ detail=f"{name} could not be reached, so this URL was not checked. This is not a clean verdict.",+ provider=name,+ )+ )+ continue+ verdict = ""+ if result.report is not None and not isinstance(result.report.verdict, type(None)):+ raw = getattr(result.report.verdict, "value", None)+ verdict = str(raw) if raw else ""+ results.append(+ ArtefactResult(+ kind="url",+ value=url,+ outcome=result.outcome,+ detail=result.detail or f"{name}: {result.outcome}",+ provider=name,+ verdict=verdict,+ )+ )+ return results+++async def _analyse_attachments(hashes: tuple[str, ...]) -> list[ArtefactResult]:+ """Hash lookup only. The same rule and the same wording as the submit path."""+ results: list[ArtefactResult] = []+ for digest in hashes[:MAX_ATTACHMENTS_ANALYSED]:+ try:+ block = (await enrich_file_hash(digest)).get("file_analysis") or {}+ except Exception: # noqa: BLE001 - a sandbox outage must not fail the analysis+ logger.warning("phishing_analysis.attachment_failed", digest=str(digest)[:64].replace("\n", " "))+ results.append(+ ArtefactResult(+ kind="hash",+ value=digest,+ outcome="could_not_check",+ detail="attachment could not be checked: analysis provider unavailable. This is not a clean verdict.",+ )+ )+ continue+ if not block:+ results.append(+ ArtefactResult(+ kind="hash",+ value=digest,+ outcome="no_provider",+ detail=(+ "attachment was not analysed: no file-analysis provider is configured for this "+ "deployment. This is not a clean verdict."+ ),+ )+ )+ continue+ for unchecked in block.get("could_not_check") or []:+ results.append(+ ArtefactResult(+ kind="hash",+ value=digest,+ outcome="could_not_check",+ detail=f"could not be checked by {unchecked.get('provider')}: not a clean result",+ provider=str(unchecked.get("provider") or ""),+ )+ )+ for finding in block.get("findings") or []:+ results.append(+ ArtefactResult(+ kind="hash",+ value=digest,+ outcome="known",+ detail=f"{finding.get('provider')} verdict: {finding.get('verdict')}",+ provider=str(finding.get("provider") or ""),+ verdict=str(finding.get("verdict") or ""),+ )+ )+ return results+++async def analyse_message(message: ReportedMessage) -> MessageAnalysis:+ """Headers, URLs and attachments. No database, no ledger, no model."""+ return MessageAnalysis(+ headers=analyse_headers(message.headers, reported_sender=message.sender),+ urls=await _analyse_urls(message.urls),+ attachments=await _analyse_attachments(message.attachment_hashes),+ )+++async def cite_to_ledger(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ submission_id: uuid.UUID,+ message: ReportedMessage,+ analysis: MessageAnalysis,+) -> uuid.UUID | None:+ """Write the analysis into the investigation ledger as cited evidence.++ One run per analysed message and one ``evidence_cited`` event per+ component, because that is the grain an auditor asks at: "what did the+ header check say", not "what did the phishing path do".++ ``seq`` is assigned densely from one, and the table's unique constraint on+ ``(run_id, seq)`` makes a gap or a collision a write failure rather than a+ silently reordered timeline.++ Returns the run id, or ``None`` when the write failed. A ledger that could+ not be written is logged at ``warning`` and does not fail the analysis:+ the finding is still worth having, and the caller is told it is uncited by+ the ``None``. It is deliberately not swallowed at ``debug`` — a citation+ nobody can find is the defect this function exists to close.+ """+ run_id = uuid.uuid4()+ now = datetime.now(UTC)+ try:+ await db.execute(+ text("""+ INSERT INTO investigation_runs+ (id, tenant_id, case_id, alert_summary, raw_alert, model_used, status,+ iterations, started_at, completed_at, created_at)+ VALUES+ (:id, :tenant_id, :case_id, :summary, CAST(:raw AS jsonb), NULL, 'completed',+ 1, :now, :now, :now)+ """).bindparams(+ id=run_id,+ tenant_id=tenant_id,+ # The submission is the case this run belongs to. `case_id` is+ # a free-text external reference by design (migration 008), so+ # it is prefixed rather than left as a bare uuid that reads+ # like a case id and is not one.+ case_id=f"phishing-submission:{submission_id}",+ summary=analysis.summary()[:4000],+ raw=_json({"internet_message_id": message.internet_message_id, "sender": message.sender, "subject": message.subject}),+ now=now,+ )+ )++ seq = 0+ for kind, summary, payload in _citations(message, analysis):+ seq += 1+ await db.execute(+ text("""+ INSERT INTO investigation_events+ (id, run_id, tenant_id, seq, ts, kind, agent, summary, payload, duration_ms, created_at)+ VALUES+ (:id, :run_id, :tenant_id, :seq, :now, :kind, :agent, :summary, CAST(:payload AS jsonb), 0, :now)+ """).bindparams(+ id=uuid.uuid4(),+ run_id=run_id,+ tenant_id=tenant_id,+ seq=seq,+ now=now,+ kind=kind,+ agent=ANALYSIS_AGENT,+ summary=summary[:4000],+ payload=_json(payload),+ )+ )+ except Exception as exc: # noqa: BLE001 - an uncitable analysis is still an analysis+ logger.warning("phishing_analysis.ledger_write_failed", error=str(exc)[:500], submission_id=str(submission_id))+ return None++ analysis.run_id = run_id+ return run_id+++def _citations(message: ReportedMessage, analysis: MessageAnalysis) -> list[tuple[str, str, dict[str, Any]]]:+ """``(kind, summary, payload)`` per ledger row.++ Three rows at minimum, and the third is the one that matters: an analysis+ that examined no artefact still writes a row saying so. A ledger with no+ row for the URL check is indistinguishable from one where the check passed.+ """+ rows: list[tuple[str, str, dict[str, Any]]] = [+ (+ EVIDENCE_KIND,+ f"Sender authentication: {analysis.headers.summary()}",+ {+ "component": "headers",+ "authentication": analysis.headers.authentication,+ "failed": list(analysis.headers.failed_methods),+ "not_evaluated": list(analysis.headers.unevaluated_methods),+ "missing_headers": list(analysis.headers.missing_headers),+ "findings": [{"kind": f.kind, "detail": f.detail, "severity_hint": f.severity_hint} for f in analysis.headers.findings],+ "hop_count": analysis.headers.hop_count,+ },+ )+ ]+ for component, artefacts in (("urls", analysis.urls), ("attachments", analysis.attachments)):+ analysed = sum(1 for a in artefacts if a.analysed)+ if not artefacts:+ summary = f"No {component} were present in this message."+ else:+ summary = f"{analysed} of {len(artefacts)} {component[:-1]}(s) analysed" + (+ f"; {len(artefacts) - analysed} not analysed, which is not a clean verdict" if analysed < len(artefacts) else ""+ )+ rows.append(+ (+ EVIDENCE_KIND,+ summary,+ {+ "component": component,+ "analysed": analysed,+ "unanalysed": len(artefacts) - analysed,+ "items": [+ {"value": a.value, "outcome": a.outcome, "provider": a.provider, "verdict": a.verdict, "detail": a.detail}+ for a in artefacts+ ],+ },+ )+ )+ return rows+++def _json(payload: dict[str, Any]) -> str:+ return json.dumps(payload, default=str)diff --git a/services/api/app/services/phishing/headers.py b/services/api/app/services/phishing/headers.pynew file mode 100644index 000000000..8561c186b--- /dev/null+++ b/services/api/app/services/phishing/headers.py@@ -0,0 +1,324 @@+"""What the headers of a reported message say, and what they refuse to say.++Depth 7.2: "headers, sender authentication results, URLs and attachments go+through the existing sandbox providers and enrichment, cited in the ledger".+This module is the headers-and-authentication half.++The one rule that shapes everything here+-----------------------------------------+**An absent header is not a passing one.** SPF, DKIM and DMARC each have a+third state that matters more than the other two put together: *nobody+checked*. A message with no ``Authentication-Results`` has not passed SPF — it+has not been evaluated, usually because it never crossed a boundary that+evaluates it. Rendering that as a green tick is the same defect as a phishing+verdict carrying no attachment indicator, which the submit path already+refuses to produce.++So every finding here carries a three-valued result, ``pass`` / ``fail`` /+``not_evaluated``, and the summary counts the third separately rather than+folding it into either side.++What is parsed, and why each one+---------------------------------+* **Authentication-Results** (RFC 8601) — the receiving boundary's own verdict+ on SPF, DKIM and DMARC. The most load-bearing header in a phishing triage+ and the one most often missing.+* **Received-SPF** — a second, older statement of the SPF result. Read as a+ fallback only, because when the two disagree the ``Authentication-Results``+ one is the boundary's considered answer.+* **Return-Path against From** — a mismatch is how the envelope sender and the+ displayed sender come apart, which is most of what SPF alignment is about.+ Common and benign on mailing lists, which is why it is `informational`+ rather than a finding on its own.+* **Reply-To against From** — the shape of a reply-to-me redirect, and the one+ an analyst asks about first in a business-email-compromise case.+* **Display name against address** — a display name containing an address that+ is not the sender's is impersonation with no ambiguity about intent.+* **Received hop count** — not a verdict, a *measurement*. One hop on a+ message claiming to be from a large provider is odd; so are twelve.++Severity is deliberately not computed here+-------------------------------------------+This module answers "what do the headers say". Deciding what that is worth is+the triage path's job, and a module that both measured and judged would make+the judgement unauditable. The caller gets findings and a count.++Nothing here reaches the network. Header analysis on a reported message must+work on a deployment with no provider configured and no outbound access, and+it does.+"""++from __future__ import annotations++import re+from dataclasses import dataclass, field+from email.utils import parseaddr+from enum import Enum+from typing import Any++__all__ = [+ "AuthMethod",+ "AuthResult",+ "HeaderAnalysis",+ "HeaderFinding",+ "analyse_headers",+]+++class AuthResult(str, Enum):+ """Three values, and the third is the point.++ ``NOT_EVALUATED`` is not a failure and it is emphatically not a pass. It+ means no receiving boundary recorded a verdict, which on a forwarded+ report is common and on a direct delivery is itself worth noticing.+ """++ PASS = "pass"+ FAIL = "fail"+ NOT_EVALUATED = "not_evaluated"+++class AuthMethod(str, Enum):+ SPF = "spf"+ DKIM = "dkim"+ DMARC = "dmarc"+++#: Result tokens RFC 8601 defines, mapped onto the three states. ``neutral``,+#: ``none``, ``policy``, ``permerror`` and ``temperror`` are **not** passes:+#: each one means the check did not reach a verdict, and treating them as+#: passes is how a message with a broken SPF record reads as authenticated.+_RESULT_TOKENS: dict[str, AuthResult] = {+ "pass": AuthResult.PASS,+ "fail": AuthResult.FAIL,+ "softfail": AuthResult.FAIL,+ "hardfail": AuthResult.FAIL,+ "none": AuthResult.NOT_EVALUATED,+ "neutral": AuthResult.NOT_EVALUATED,+ "policy": AuthResult.NOT_EVALUATED,+ "permerror": AuthResult.NOT_EVALUATED,+ "temperror": AuthResult.NOT_EVALUATED,+}++_AUTH_CLAUSE = re.compile(r"\b(spf|dkim|dmarc)\s*=\s*([a-z]+)", re.IGNORECASE)+_RECEIVED_SPF = re.compile(r"^\s*([a-z]+)", re.IGNORECASE)+#: An address embedded in a display name. Deliberately narrow: it must look+#: like an address, because "Billing (accounts)" is not impersonation.+_ADDRESS_IN_NAME = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")+++@dataclass(frozen=True)+class HeaderFinding:+ """One observation. ``kind`` is stable; ``detail`` is for a human."""++ kind: str+ detail: str+ #: ``finding`` means something is wrong; ``informational`` means something+ #: is worth knowing and is routinely benign. Separated so a console can+ #: show the first without burying it in the second.+ severity_hint: str = "finding"+ evidence: dict[str, Any] = field(default_factory=dict)+++@dataclass(frozen=True)+class HeaderAnalysis:+ authentication: dict[str, str]+ findings: tuple[HeaderFinding, ...]+ hop_count: int+ #: Headers that were not present at all. Published rather than inferred+ #: from an empty value, because "the header said nothing" and "there was+ #: no header" send an analyst to different places: the first is a+ #: boundary that evaluated and declined, the second is a message that+ #: crossed no boundary which evaluates.+ missing_headers: tuple[str, ...]++ @property+ def failed_methods(self) -> tuple[str, ...]:+ return tuple(sorted(m for m, r in self.authentication.items() if r == AuthResult.FAIL.value))++ @property+ def unevaluated_methods(self) -> tuple[str, ...]:+ return tuple(sorted(m for m, r in self.authentication.items() if r == AuthResult.NOT_EVALUATED.value))++ def as_indicators(self) -> list[dict[str, Any]]:+ """The shape ``aisoc_phishing_submissions.indicators`` already holds.++ Produced here rather than in the endpoint so the wording an analyst+ reads is beside the logic that earned it. Every unevaluated method+ produces an indicator of its own: silence about a check nobody ran is+ the thing this module exists to prevent.+ """+ out: list[dict[str, Any]] = []+ for method, result in sorted(self.authentication.items()):+ if result == AuthResult.FAIL.value:+ note = f"{method.upper()} failed at the receiving boundary"+ elif result == AuthResult.NOT_EVALUATED.value:+ note = f"{method.upper()} was not evaluated: no receiving boundary recorded a verdict. This is not a pass."+ else:+ note = f"{method.upper()} passed at the receiving boundary"+ out.append({"kind": "header", "value": f"{method}={result}", "note": note})+ for finding in self.findings:+ out.append(+ {+ "kind": "header",+ "value": finding.kind,+ "note": finding.detail,+ "severity_hint": finding.severity_hint,+ **({"evidence": finding.evidence} if finding.evidence else {}),+ }+ )+ return out++ def summary(self) -> str:+ if not self.authentication:+ return (+ "No sender-authentication results are present in this message's headers. "+ "Nothing was checked, which is not the same as nothing being wrong."+ )+ parts = [f"{m.upper()} {r}" for m, r in sorted(self.authentication.items())]+ return "; ".join(parts) + f"; {len(self.findings)} header finding(s) across {self.hop_count} delivery hop(s)"+++def _first_address(raw: str) -> str:+ _name, addr = parseaddr(raw or "")+ return addr.strip().lower()+++def _display_name(raw: str) -> str:+ name, _addr = parseaddr(raw or "")+ return name.strip()+++def _domain_of(address: str) -> str:+ return address.rsplit("@", 1)[-1].lower() if "@" in address else ""+++def _parse_authentication(headers: dict[str, str]) -> tuple[dict[str, str], list[str]]:+ """``{method: result}`` plus the headers that were absent.++ Both ``Authentication-Results`` and its ARC-sealed sibling are read, in+ that order. ARC carries a *forwarder's* record of what an earlier boundary+ concluded, which is exactly the case a reported forward presents and which+ a reader of the plain header alone would see as "not evaluated".+ """+ results: dict[str, str] = {}+ missing: list[str] = []++ combined = "\n".join(filter(None, (headers.get("authentication-results", ""), headers.get("arc-authentication-results", ""))))+ if not combined:+ missing.append("Authentication-Results")+ for method, token in _AUTH_CLAUSE.findall(combined):+ key = method.lower()+ value = _RESULT_TOKENS.get(token.lower(), AuthResult.NOT_EVALUATED).value+ # First statement wins. A multi-hop header lists the outermost+ # boundary first, and that is the one whose verdict the recipient's+ # mail system acted on.+ results.setdefault(key, value)++ received_spf = headers.get("received-spf", "")+ if AuthMethod.SPF.value not in results:+ if received_spf:+ match = _RECEIVED_SPF.match(received_spf)+ token = match.group(1).lower() if match else ""+ results[AuthMethod.SPF.value] = _RESULT_TOKENS.get(token, AuthResult.NOT_EVALUATED).value+ else:+ missing.append("Received-SPF")++ # Every method the product reports on gets an entry, so a console cannot+ # render "SPF fail" and silently omit DMARC because no clause mentioned+ # it. Absent is `not_evaluated`, which is the honest word for it.+ for method in (AuthMethod.SPF, AuthMethod.DKIM, AuthMethod.DMARC):+ results.setdefault(method.value, AuthResult.NOT_EVALUATED.value)+ return results, missing+++def analyse_headers(headers: dict[str, str], *, reported_sender: str = "") -> HeaderAnalysis:+ """Read a reported message's headers. No network, no provider, no model.++ ``headers`` is the lowercased name → value mapping+ :class:`app.services.phishing.intake.ReportedMessage` carries. Repeated+ headers arrive newline-joined, which is how the hop count is recovered.+ """+ normalised = {str(k).lower(): str(v) for k, v in (headers or {}).items()}+ authentication, missing = _parse_authentication(normalised)+ findings: list[HeaderFinding] = []++ from_header = normalised.get("from", "")+ from_address = _first_address(from_header) or reported_sender.lower()+ from_domain = _domain_of(from_address)++ return_path = _first_address(normalised.get("return-path", ""))+ if return_path and from_address and _domain_of(return_path) != from_domain:+ findings.append(+ HeaderFinding(+ kind="return_path_mismatch",+ detail=(+ f"The envelope sender ({return_path}) is on a different domain from the displayed "+ f"sender ({from_address}). Routine on mailing lists and bulk senders; it is also the "+ f"shape SPF alignment exists to catch."+ ),+ severity_hint="informational",+ evidence={"return_path": return_path, "from": from_address},+ )+ )++ reply_to = _first_address(normalised.get("reply-to", ""))+ if reply_to and from_address and reply_to != from_address and _domain_of(reply_to) != from_domain:+ findings.append(+ HeaderFinding(+ kind="reply_to_redirect",+ detail=(+ f"Replies go to {reply_to}, on a different domain from the sender ({from_address}). "+ f"This is the mechanism of a reply-chain redirect."+ ),+ evidence={"reply_to": reply_to, "from": from_address},+ )+ )++ display = _display_name(from_header)+ embedded = _ADDRESS_IN_NAME.findall(display)+ impersonated = [a.lower() for a in embedded if a.lower() != from_address]+ if impersonated:+ findings.append(+ HeaderFinding(+ kind="display_name_impersonation",+ detail=(+ f"The display name contains {impersonated[0]}, which is not the sending address "+ f"({from_address}). A mail client shows the display name."+ ),+ evidence={"display_name": display, "claimed": impersonated[0], "actual": from_address},+ )+ )++ received = normalised.get("received", "")+ hop_count = len([line for line in received.split("\n") if line.strip()]) if received else 0+ if hop_count == 0:+ missing.append("Received")+ findings.append(+ HeaderFinding(+ kind="no_received_chain",+ detail=(+ "No Received headers are present, so the delivery path cannot be reconstructed. On a "+ "report that arrived as an attachment or through an API this is expected; on a direct "+ "delivery it is not."+ ),+ severity_hint="informational",+ )+ )++ for method in sorted(authentication):+ if authentication[method] == AuthResult.FAIL.value:+ findings.append(+ HeaderFinding(+ kind=f"{method}_fail",+ detail=f"{method.upper()} failed at the receiving boundary for {from_domain or 'the sending domain'}.",+ evidence={"method": method, "domain": from_domain},+ )+ )++ return HeaderAnalysis(+ authentication=authentication,+ findings=tuple(findings),+ hop_count=hop_count,+ missing_headers=tuple(dict.fromkeys(missing)),+ )diff --git a/services/api/migrations/111_phishing_message_analysis.sql b/services/api/migrations/111_phishing_message_analysis.sqlnew file mode 100644index 000000000..0db7b65c6--- /dev/null+++ b/services/api/migrations/111_phishing_message_analysis.sql@@ -0,0 +1,76 @@+-- 111_phishing_message_analysis.sql — the headers a reported message carried,+-- and whether anything actually examined it.+--+-- Depth plan 7.2. The submissions table has held an `indicators` JSONB array+-- since migration 015 and that is the right home for *findings*. It is the+-- wrong home for two other things, and conflating them is what this migration+-- separates.+--+-- `headers` — the raw internet headers, as delivered+-- --------------------------------------------------+-- Stored because the analysis has to be re-runnable. A retriage that has to+-- re-fetch the message from a mailbox cannot run after a purge has removed+-- it, which is precisely the order a real phishing response happens in:+-- analyse, decide, purge, and *then* somebody asks why. The headers are the+-- evidence, so they are kept with the submission rather than with the+-- mailbox.+--+-- JSONB and not text, because the analysis reads it as a name → value map and+-- re-parsing an RFC 5322 block on every read would put a parser between the+-- evidence and the reader.+--+-- `analysis_run_id` — where the citations went+-- ---------------------------------------------+-- The ledger run this submission's analysis was written to. Nullable with no+-- foreign key, deliberately: `investigation_runs` is retained on a different+-- schedule from phishing submissions, so a cascade would delete evidence when+-- a run aged out, and a RESTRICT would make run retention fail. A dangling id+-- reads as "the citations have aged out", which is true and recoverable; a+-- deleted submission reads as "this was never analysed", which is not.+--+-- `analysed_at` / `artefacts_analysed` / `artefacts_unanalysed`+-- --------------------------------------------------------------+-- The two counts are stored separately and never summed, because the sum is+-- the number this product must not publish. Three URLs and two attachments on+-- a deployment with no provider configured is an analysis that examined+-- nothing, and a surface rendering "5 artefacts, 0 findings" has said the+-- opposite of what happened. A reader can compute the total; nothing can+-- recover the split from a total.+--+-- `analysed_at` is NULL until an analysis has run, which is distinct from an+-- analysis that ran and found nothing. The honest empty state for a column+-- nobody has written is an empty state, never a confident zero.+--+-- Reversible: DROP COLUMN.++ALTER TABLE aisoc_phishing_submissions+ ADD COLUMN IF NOT EXISTS headers JSONB NOT NULL DEFAULT '{}'::jsonb;++ALTER TABLE aisoc_phishing_submissions+ ADD COLUMN IF NOT EXISTS auth_results JSONB NOT NULL DEFAULT '{}'::jsonb;++ALTER TABLE aisoc_phishing_submissions+ ADD COLUMN IF NOT EXISTS analysis_run_id UUID;++ALTER TABLE aisoc_phishing_submissions+ ADD COLUMN IF NOT EXISTS analysed_at TIMESTAMPTZ;++ALTER TABLE aisoc_phishing_submissions+ ADD COLUMN IF NOT EXISTS artefacts_analysed INTEGER NOT NULL DEFAULT 0;++ALTER TABLE aisoc_phishing_submissions+ ADD COLUMN IF NOT EXISTS artefacts_unanalysed INTEGER NOT NULL DEFAULT 0;++COMMENT ON COLUMN aisoc_phishing_submissions.auth_results IS+ 'SPF, DKIM and DMARC as {method: pass|fail|not_evaluated}. The third value is the point: a '+ 'message with no Authentication-Results has not passed SPF, it has not been evaluated, and '+ 'rendering that as a pass is the defect this column exists to make impossible.';++COMMENT ON COLUMN aisoc_phishing_submissions.artefacts_unanalysed IS+ 'Counted separately from artefacts_analysed and never summed with it. The sum is the number '+ 'this product must not publish: a surface that renders "5 artefacts, 0 findings" for five '+ 'artefacts nothing examined has said the opposite of what happened.';++COMMENT ON COLUMN aisoc_phishing_submissions.analysed_at IS+ 'NULL until an analysis has run. Distinct from an analysis that ran and found nothing: the '+ 'honest empty state for a column nobody has written is empty, never a confident zero.';diff --git a/services/api/tests/test_phishing_analysis_ledger_live.py b/services/api/tests/test_phishing_analysis_ledger_live.pynew file mode 100644index 000000000..935b1c3a2--- /dev/null+++ b/services/api/tests/test_phishing_analysis_ledger_live.py@@ -0,0 +1,211 @@+"""The citations land in the ledger, and an auditor can find them.++Depth 7.2 says the analysis is "cited in the ledger". That is a claim about+rows, so it is tested against rows. The ledger's immutability trigger, the+``(run_id, seq)`` unique constraint and the tenant foreign keys are all+properties of the real schema; a session double would answer whatever it was+asked and prove none of them.++Skips without a database rather than passing without one.+"""++from __future__ import annotations++import os+import uuid++import pytest+import pytest_asyncio+from app.services.phishing.analysis import ArtefactResult, MessageAnalysis, cite_to_ledger+from app.services.phishing.headers import analyse_headers+from app.services.phishing.intake import ReportedMessage+from sqlalchemy import text+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++DSN = os.environ.get("DATABASE_URL", "")+REQUIRED = os.environ.get("MSSP_ISOLATION_REQUIRED", "").strip() not in ("", "0", "false")++TENANT = uuid.UUID("0e700000-0000-0000-0000-00000000007b")+PHISH = "[email protected]"++HEADERS = {+ "from": f'"Billing Dept" <{PHISH}>',+ "to": "[email protected]",+ "reply-to": "[email protected]",+ "authentication-results": "mx.example.com; spf=fail; dkim=none; dmarc=fail",+ "received": "from mx1.example.com by mail.example.com",+}+++@pytest_asyncio.fixture+async def db():+ if "postgres" not in DSN and not REQUIRED:+ pytest.skip("needs a live Postgres with the migration chain applied (integration.yml)")+ engine = create_async_engine(DSN)+ try:+ async with engine.connect() as probe:+ await probe.execute(text("SELECT 1"))+ except Exception as exc:+ await engine.dispose()+ if REQUIRED:+ pytest.fail(f"MSSP_ISOLATION_REQUIRED is set and no database answered at DATABASE_URL: {type(exc).__name__}: {exc}")+ pytest.skip(f"no database at DATABASE_URL ({type(exc).__name__}) — runs in integration.yml")++ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as session:+ await session.execute(+ text("""+ INSERT INTO tenants (id, name, slug)+ VALUES (:id, 'Depth 7.2 analysis', 'depth-72-analysis')+ ON CONFLICT (id) DO NOTHING+ """).bindparams(id=TENANT)+ )+ await session.commit()+ yield session+ await engine.dispose()+++# There is deliberately no teardown that removes ledger rows. The first+# attempt at one failed with `investigation_events rows are immutable+# (attempted DELETE)`: the FK from events to runs is ON DELETE CASCADE, so+# deleting a run asks Postgres to delete its events, and migration 008's+# trigger refuses. That is the append-only control working exactly as+# designed, and writing a test fixture that defeats it would be the wrong+# fix. Every assertion below is scoped by the `run_id` its own call+# returned, so the rows accumulating between runs cannot affect it.+++def _message() -> ReportedMessage:+ return ReportedMessage(+ intake_source="m365_graph",+ internet_message_id="<[email protected]>",+ sender=PHISH,+ subject="Invoice overdue",+ headers=HEADERS,+ )+++def _analysis(*, analysed: int = 0, unanalysed: int = 0) -> MessageAnalysis:+ urls = [+ ArtefactResult(kind="url", value=f"https://a{i}.example.net", outcome="known", detail="clean", verdict="benign")+ for i in range(analysed)+ ]+ urls += [+ ArtefactResult(+ kind="url",+ value=f"https://b{i}.example.net",+ outcome="no_provider",+ detail="not analysed: no provider is configured. This is not a clean verdict.",+ )+ for i in range(unanalysed)+ ]+ return MessageAnalysis(headers=analyse_headers(HEADERS), urls=urls)+++async def test_one_run_and_one_event_per_component(db) -> None:+ submission_id = uuid.uuid4()+ run_id = await cite_to_ledger(db, tenant_id=TENANT, submission_id=submission_id, message=_message(), analysis=_analysis())+ await db.commit()++ assert run_id is not None+ run = (await db.execute(text("SELECT case_id, status FROM investigation_runs WHERE id = :i").bindparams(i=run_id))).fetchone()+ assert run.case_id == f"phishing-submission:{submission_id}"+ assert run.status == "completed"++ rows = (+ await db.execute(+ text("SELECT seq, kind, agent, summary, payload FROM investigation_events WHERE run_id = :i ORDER BY seq").bindparams(i=run_id)+ )+ ).fetchall()+ assert [r.seq for r in rows] == [1, 2, 3], "seq must be dense from one; the unique constraint makes a gap a write failure"+ assert {r.kind for r in rows} == {"evidence_cited"}+ assert {r.agent for r in rows} == {"aisoc-phishing-analysis"}+ assert [r.payload["component"] for r in rows] == ["headers", "urls", "attachments"]+++async def test_the_header_citation_records_what_was_not_evaluated(db) -> None:+ run_id = await cite_to_ledger(db, tenant_id=TENANT, submission_id=uuid.uuid4(), message=_message(), analysis=_analysis())+ await db.commit()+ payload = (+ (await db.execute(text("SELECT payload FROM investigation_events WHERE run_id = :i AND seq = 1").bindparams(i=run_id)))+ .fetchone()+ .payload+ )+ assert sorted(payload["failed"]) == ["dmarc", "spf"]+ assert payload["not_evaluated"] == ["dkim"]+ assert payload["hop_count"] == 1+ assert any(f["kind"] == "reply_to_redirect" for f in payload["findings"])+++async def test_an_unanalysed_url_is_cited_as_unanalysed(db) -> None:+ """The row an auditor reads must not be able to imply a clean result."""+ run_id = await cite_to_ledger(+ db, tenant_id=TENANT, submission_id=uuid.uuid4(), message=_message(), analysis=_analysis(analysed=1, unanalysed=2)+ )+ await db.commit()+ row = (+ await db.execute(text("SELECT summary, payload FROM investigation_events WHERE run_id = :i AND seq = 2").bindparams(i=run_id))+ ).fetchone()+ assert row.payload["analysed"] == 1+ assert row.payload["unanalysed"] == 2+ assert "not a clean verdict" in row.summary+ assert all("not a clean verdict" in item["detail"] for item in row.payload["items"] if item["outcome"] == "no_provider")+++async def test_the_citations_are_immutable_once_written(db) -> None:+ """Asserted against the real trigger, which a session double does not have."""+ run_id = await cite_to_ledger(db, tenant_id=TENANT, submission_id=uuid.uuid4(), message=_message(), analysis=_analysis())+ await db.commit()+ with pytest.raises(Exception, match="immutable"):+ await db.execute(text("UPDATE investigation_events SET summary = 'edited' WHERE run_id = :i").bindparams(i=run_id))+ await db.rollback()+++async def test_an_unwritable_ledger_returns_none_rather_than_raising(db) -> None:+ """An uncitable analysis is still an analysis, and the caller is told.++ A tenant id with no row violates the foreign key, which is the closest+ reachable analogue of a ledger that will not accept a write.+ """+ analysis = _analysis()+ run_id = await cite_to_ledger(db, tenant_id=uuid.uuid4(), submission_id=uuid.uuid4(), message=_message(), analysis=analysis)+ await db.rollback()+ assert run_id is None+ assert analysis.run_id is None+++async def test_the_submission_columns_migration_111_added_accept_the_analysis(db) -> None:+ """The second half of 'which code path writes this': the columns have a writer."""+ submission_id = uuid.uuid4()+ await db.execute(+ text("""+ INSERT INTO aisoc_phishing_submissions+ (id, tenant_id, artifact_kind, verdict, headers, auth_results, analysed_at,+ artefacts_analysed, artefacts_unanalysed)+ VALUES (:id, :t, 'email', 'phishing', CAST(:h AS jsonb), CAST(:a AS jsonb), now(), 1, 2)+ """).bindparams(+ id=submission_id,+ t=TENANT,+ h='{"from": "[email protected]"}',+ a='{"spf": "fail", "dkim": "not_evaluated", "dmarc": "fail"}',+ )+ )+ await db.commit()+ row = (+ await db.execute(+ text(+ "SELECT auth_results, artefacts_analysed, artefacts_unanalysed, analysed_at FROM aisoc_phishing_submissions WHERE id = :i"+ ).bindparams(i=submission_id)+ )+ ).fetchone()+ assert row.auth_results["dkim"] == "not_evaluated"+ assert (row.artefacts_analysed, row.artefacts_unanalysed) == (1, 2)+ assert row.analysed_at is not None+ await db.execute(text("DELETE FROM aisoc_phishing_submissions WHERE id = :i").bindparams(i=submission_id))+ await db.commit()diff --git a/services/api/tests/test_phishing_message_analysis.py b/services/api/tests/test_phishing_message_analysis.pynew file mode 100644index 000000000..4e60f97f4--- /dev/null+++ b/services/api/tests/test_phishing_message_analysis.py@@ -0,0 +1,361 @@+"""Headers, URLs and attachments: what was found, and what was not checked.++The reproduction this file pins is the absence: before depth 7.2 nothing in+the tree read an ``Authentication-Results`` header. ``grep -rl+"authentication-results" services/`` returned no match, so a reported message+whose SPF and DMARC both failed at the receiving boundary produced a triage+verdict that had never looked.++Everything else here guards the one rule the module turns on — **an+unanalysed artefact must never read as a clean one** — in the three places it+can be broken:++* a result token that is not a pass being treated as one (``neutral``,+ ``none``, ``permerror``, ``temperror``, and the absent header itself);+* an artefact nothing examined being omitted rather than reported;+* the analysed and unanalysed counts being summed, which is how five+ artefacts nobody checked render as "5 artefacts, 0 findings".+"""++from __future__ import annotations++import pytest+from app.services.phishing.analysis import ArtefactResult, MessageAnalysis, _citations+from app.services.phishing.headers import AuthResult, analyse_headers+from app.services.phishing.intake import ReportedMessage, from_graph_message++PHISH = "[email protected]"+VICTIM = "[email protected]"++FULL_FAIL = {+ "from": f'"Billing Dept" <{PHISH}>',+ "to": VICTIM,+ "return-path": "<[email protected]>",+ "reply-to": "[email protected]",+ "authentication-results": (+ "mx.example.com; spf=fail smtp.mailfrom=phish.example.net; dkim=none; dmarc=fail header.from=phish.example.net"+ ),+ "received": "from mx1.example.com by mail.example.com\nfrom relay.phish.example.net by mx1.example.com",+ "subject": "Action required",+}++CLEAN_PASS = {+ "from": "Finance <[email protected]>",+ "to": VICTIM,+ "return-path": "<[email protected]>",+ "authentication-results": "mx.example.com; spf=pass smtp.mailfrom=example.com; dkim=pass header.d=example.com; dmarc=pass",+ "received": "from mx1.example.com by mail.example.com",+ "subject": "Q3 numbers",+}+++class TestTheThirdValueIsThePoint:+ def test_an_absent_authentication_results_header_is_not_a_pass(self) -> None:+ """The reproduction. Nothing in the tree read this header before 7.2."""+ analysis = analyse_headers({"from": f"<{PHISH}>", "to": VICTIM})+ assert analysis.authentication == {+ "spf": AuthResult.NOT_EVALUATED.value,+ "dkim": AuthResult.NOT_EVALUATED.value,+ "dmarc": AuthResult.NOT_EVALUATED.value,+ }+ assert analysis.failed_methods == ()+ assert set(analysis.unevaluated_methods) == {"spf", "dkim", "dmarc"}+ assert "Authentication-Results" in analysis.missing_headers++ @pytest.mark.parametrize("token", ["none", "neutral", "policy", "permerror", "temperror"])+ def test_a_non_verdict_token_is_not_evaluated_rather_than_a_pass(self, token: str) -> None:+ """Treating these as passes is how a broken SPF record reads as authenticated."""+ analysis = analyse_headers({"authentication-results": f"mx; spf={token}", "from": f"<{PHISH}>"})+ assert analysis.authentication["spf"] == AuthResult.NOT_EVALUATED.value++ @pytest.mark.parametrize("token", ["fail", "softfail", "hardfail"])+ def test_every_failure_spelling_is_a_failure(self, token: str) -> None:+ analysis = analyse_headers({"authentication-results": f"mx; spf={token}", "from": f"<{PHISH}>"})+ assert analysis.authentication["spf"] == AuthResult.FAIL.value++ def test_every_method_gets_an_entry_even_when_no_clause_mentions_it(self) -> None:+ """Otherwise a console renders 'SPF fail' and silently omits DMARC."""+ analysis = analyse_headers({"authentication-results": "mx; spf=fail", "from": f"<{PHISH}>"})+ assert set(analysis.authentication) == {"spf", "dkim", "dmarc"}+ assert analysis.authentication["dmarc"] == AuthResult.NOT_EVALUATED.value++ def test_an_unevaluated_method_produces_its_own_indicator_saying_so(self) -> None:+ notes = [i["note"] for i in analyse_headers({"from": f"<{PHISH}>"}).as_indicators()]+ assert sum("not a pass" in n for n in notes) == 3++ def test_the_arc_sealed_header_is_read_when_the_plain_one_is_absent(self) -> None:+ """A forwarded report is exactly the case where only ARC carries the verdict."""+ analysis = analyse_headers({"arc-authentication-results": "i=1; mx; spf=fail; dmarc=fail", "from": f"<{PHISH}>"})+ assert analysis.authentication["spf"] == AuthResult.FAIL.value+ assert analysis.authentication["dmarc"] == AuthResult.FAIL.value++ def test_received_spf_is_a_fallback_and_the_considered_answer_wins(self) -> None:+ both = analyse_headers(+ {"authentication-results": "mx; spf=fail", "received-spf": "pass (example.com: domain of x designates y)", "from": f"<{PHISH}>"}+ )+ assert both.authentication["spf"] == AuthResult.FAIL.value+ fallback = analyse_headers({"received-spf": "pass (example.com: ...)", "from": f"<{PHISH}>"})+ assert fallback.authentication["spf"] == AuthResult.PASS.value+++class TestWhatTheHeadersGiveAway:+ def test_a_reply_to_on_another_domain_is_a_finding(self) -> None:+ kinds = {f.kind for f in analyse_headers(FULL_FAIL).findings}+ assert "reply_to_redirect" in kinds++ def test_a_return_path_mismatch_is_informational_not_a_finding(self) -> None:+ """Routine on mailing lists. Flagging it as a finding trains people to ignore findings."""+ by_kind = {f.kind: f for f in analyse_headers(FULL_FAIL).findings}+ assert by_kind["return_path_mismatch"].severity_hint == "informational"++ def test_an_address_in_the_display_name_that_is_not_the_sender_is_impersonation(self) -> None:+ analysis = analyse_headers({"from": f'"[email protected]" <{PHISH}>'})+ by_kind = {f.kind: f for f in analysis.findings}+ assert "display_name_impersonation" in by_kind+ assert by_kind["display_name_impersonation"].evidence["actual"] == PHISH++ def test_a_display_name_that_is_merely_a_name_is_not_impersonation(self) -> None:+ """The negative control. A matcher that fires on any display name fires on everything."""+ assert "display_name_impersonation" not in {f.kind for f in analyse_headers({"from": f'"Billing Dept" <{PHISH}>'}).findings}++ def test_the_hop_count_comes_from_repeated_received_headers(self) -> None:+ assert analyse_headers(FULL_FAIL).hop_count == 2++ def test_a_clean_message_produces_no_findings_beyond_the_passes(self) -> None:+ """The other negative control: an analyser that flags everything flags nothing."""+ analysis = analyse_headers(CLEAN_PASS)+ assert analysis.failed_methods == ()+ assert analysis.unevaluated_methods == ()+ assert [f.kind for f in analysis.findings] == []++ def test_the_analysis_reaches_no_network(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Header analysis must work on a deployment with no provider and no egress."""+ import socket++ def _boom(*_args, **_kwargs):+ raise AssertionError("header analysis opened a socket")++ monkeypatch.setattr(socket.socket, "connect", _boom)+ monkeypatch.setattr(socket, "getaddrinfo", _boom)+ assert analyse_headers(FULL_FAIL).failed_methods == ("dmarc", "spf")+++class TestTheCountsAreNeverSummed:+ def _analysis(self, *, analysed: int, unanalysed: int) -> MessageAnalysis:+ urls = [+ ArtefactResult(kind="url", value=f"https://a{i}.example.net", outcome="known", detail="", verdict="benign")+ for i in range(analysed)+ ]+ urls += [+ ArtefactResult(kind="url", value=f"https://b{i}.example.net", outcome="no_provider", detail="not analysed")+ for i in range(unanalysed)+ ]+ return MessageAnalysis(headers=analyse_headers(CLEAN_PASS), urls=urls)++ def test_an_artefact_nothing_examined_is_counted_as_unanalysed(self) -> None:+ analysis = self._analysis(analysed=0, unanalysed=5)+ assert analysis.analysed_count == 0+ assert analysis.unanalysed_count == 5++ def test_a_pending_submission_is_not_analysed(self) -> None:+ """A submission accepted is not a result, the same distinction awaiting_completion draws."""+ pending = ArtefactResult(kind="url", value="https://x.example.net", outcome="pending", detail="submitted")+ assert pending.analysed is False++ def test_the_summary_says_how_many_could_not_be_analysed(self) -> None:+ summary = self._analysis(analysed=1, unanalysed=4).summary()+ assert "1 of 5" in summary+ assert "4 could not be" in summary++ def test_a_fully_unanalysed_message_does_not_read_as_zero_findings(self) -> None:+ """The exact rendering this split exists to prevent."""+ summary = self._analysis(analysed=0, unanalysed=5).summary()+ assert "0 of 5" in summary and "5 could not be" in summary+++class TestTheRealAnalysisPathOnADeploymentWithNoProvider:+ """Drives ``analyse_message``, not a hand-built ``MessageAnalysis``.++ Written because the hand-built version missed the defect it was supposed+ to guard. Deleting the "no provider configured" branch from+ ``_analyse_urls`` — so unanalysable URLs are silently skipped — left every+ other test in this file green, because they construct their own+ ``ArtefactResult`` list and never run the code that builds one. A test+ that asserts on a fixture it wrote cannot notice a producer that stopped+ producing.+ """++ @pytest.mark.asyncio+ async def test_a_url_with_no_provider_is_reported_not_skipped(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from app.services.phishing import analysis as analysis_module++ class _Empty:+ def usable_names(self):+ return []++ def get(self, _name): # pragma: no cover - never reached with no names+ return None++ monkeypatch.setattr(analysis_module, "build_registry", lambda: _Empty())+ message = ReportedMessage(+ intake_source="manual",+ sender=PHISH,+ headers=CLEAN_PASS,+ urls=("https://pay.phish.example.net/a", "https://pay.phish.example.net/b"),+ )+ result = await analysis_module.analyse_message(message)++ assert len(result.urls) == 2, "an unanalysable URL must appear in the output, not vanish from it"+ assert result.analysed_count == 0+ assert result.unanalysed_count == 2+ assert all("not a clean verdict" in u.detail for u in result.urls)++ @pytest.mark.asyncio+ async def test_an_unreachable_registry_is_could_not_check_not_an_empty_result(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from app.services.phishing import analysis as analysis_module++ def _boom():+ raise RuntimeError("provider registry unavailable")++ monkeypatch.setattr(analysis_module, "build_registry", _boom)+ message = ReportedMessage(intake_source="manual", sender=PHISH, headers=CLEAN_PASS, urls=("https://x.example.net",))+ result = await analysis_module.analyse_message(message)+ assert result.unanalysed_count == 1+ assert result.urls[0].outcome == "no_provider"++ @pytest.mark.asyncio+ async def test_only_the_first_five_urls_are_submitted(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """A footer with twenty links must not spend a provider's quota."""+ from app.services.phishing import analysis as analysis_module++ class _Empty:+ def usable_names(self):+ return []++ def get(self, _name): # pragma: no cover+ return None++ monkeypatch.setattr(analysis_module, "build_registry", lambda: _Empty())+ message = ReportedMessage(+ intake_source="manual",+ sender=PHISH,+ headers=CLEAN_PASS,+ urls=tuple(f"https://x{i}.example.net" for i in range(20)),+ )+ result = await analysis_module.analyse_message(message)+ assert len(result.urls) == analysis_module.MAX_URLS_ANALYSED++ @pytest.mark.asyncio+ async def test_an_attachment_with_no_provider_is_reported_not_skipped(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """The wording the submit path already shipped, now on the 7.2 path too."""+ from app.services.phishing import analysis as analysis_module++ async def _nothing(_digest):+ return {}++ monkeypatch.setattr(analysis_module, "enrich_file_hash", _nothing)+ message = ReportedMessage(intake_source="manual", sender=PHISH, headers=CLEAN_PASS, attachment_hashes=("a" * 64,))+ result = await analysis_module.analyse_message(message)+ assert result.unanalysed_count == 1+ assert "This is not a clean verdict" in result.attachments[0].detail++ @pytest.mark.asyncio+ async def test_a_sandbox_outage_is_could_not_check_rather_than_a_crash(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from app.services.phishing import analysis as analysis_module++ async def _boom(_digest):+ raise RuntimeError("sandbox down")++ monkeypatch.setattr(analysis_module, "enrich_file_hash", _boom)+ message = ReportedMessage(intake_source="manual", sender=PHISH, headers=CLEAN_PASS, attachment_hashes=("b" * 64,))+ result = await analysis_module.analyse_message(message)+ assert result.attachments[0].outcome == "could_not_check"+ assert result.unanalysed_count == 1+++class TestTheCitationsAreWrittenEvenWhenNothingWasFound:+ def _message(self) -> ReportedMessage:+ return ReportedMessage(intake_source="manual", sender=PHISH, headers=FULL_FAIL)++ def test_a_message_with_no_artefacts_still_writes_a_row_per_component(self) -> None:+ """A ledger with no row for the URL check cannot be told from one where it passed."""+ rows = _citations(self._message(), MessageAnalysis(headers=analyse_headers(FULL_FAIL)))+ components = [payload["component"] for _k, _s, payload in rows]+ assert components == ["headers", "urls", "attachments"]+ assert all(kind == "evidence_cited" for kind, _s, _p in rows)++ def test_the_header_citation_carries_the_unevaluated_list(self) -> None:+ analysis = MessageAnalysis(headers=analyse_headers({"from": f"<{PHISH}>"}))+ _kind, _summary, payload = _citations(self._message(), analysis)[0]+ assert sorted(payload["not_evaluated"]) == ["dkim", "dmarc", "spf"]++ def test_an_unanalysed_artefact_citation_says_it_is_not_a_clean_verdict(self) -> None:+ analysis = MessageAnalysis(+ headers=analyse_headers(CLEAN_PASS),+ urls=[ArtefactResult(kind="url", value="https://x.example.net", outcome="no_provider", detail="not analysed")],+ )+ _kind, summary, payload = _citations(self._message(), analysis)[1]+ assert payload["analysed"] == 0 and payload["unanalysed"] == 1+ assert "not a clean verdict" in summary+++class TestTheVerdictIsOnlyEverRaised:+ """``_merge_analysis_verdict`` follows the same rule the attachment merge did."""++ def _merge(self, verdict: str, analysis: MessageAnalysis):+ from app.api.v1.endpoints.phishing import TriageResult, _merge_analysis_verdict++ base = TriageResult(verdict=verdict, confidence=0.1, indicators=[], mitre_technique=None, summary="Heuristic triage.")+ return _merge_analysis_verdict(base, analysis)++ def test_spf_and_dmarc_both_failing_raises_a_benign_verdict_to_phishing(self) -> None:+ merged = self._merge("benign", MessageAnalysis(headers=analyse_headers(FULL_FAIL)))+ assert merged.verdict == "phishing"+ assert merged.confidence >= 0.75++ def test_spf_alone_failing_does_not(self) -> None:+ """A forwarded message routinely breaks SPF; flagging it alerts on every mailing list."""+ spf_only = analyse_headers({**FULL_FAIL, "authentication-results": "mx; spf=fail; dkim=pass; dmarc=pass"})+ assert self._merge("benign", MessageAnalysis(headers=spf_only)).verdict == "benign"++ def test_unevaluated_authentication_raises_nothing(self) -> None:+ assert self._merge("benign", MessageAnalysis(headers=analyse_headers({"from": f"<{PHISH}>"}))).verdict == "benign"++ def test_a_malicious_artefact_raises_to_malware(self) -> None:+ analysis = MessageAnalysis(+ headers=analyse_headers(CLEAN_PASS),+ urls=[ArtefactResult(kind="url", value="https://x.example.net", outcome="known", detail="bad", verdict="malicious")],+ )+ merged = self._merge("benign", analysis)+ assert merged.verdict == "malware"+ assert merged.confidence >= 0.9++ def test_an_existing_phishing_verdict_is_never_lowered_by_a_clean_analysis(self) -> None:+ merged = self._merge("phishing", MessageAnalysis(headers=analyse_headers(CLEAN_PASS)))+ assert merged.verdict == "phishing"++ def test_every_indicator_survives_the_merge(self) -> None:+ analysis = MessageAnalysis(headers=analyse_headers(FULL_FAIL))+ merged = self._merge("benign", analysis)+ assert len(merged.indicators) == len(analysis.as_indicators())+++class TestTheIntakeAdapterFeedsTheAnalysis:+ def test_a_graph_payloads_headers_reach_the_analyser(self) -> None:+ """The path, not the function: the adapter and the analyser have to agree on casing."""+ payload = {+ "id": "AAMk=",+ "internetMessageId": "<[email protected]>",+ "subject": "Invoice",+ "from": {"emailAddress": {"address": VICTIM}},+ "toRecipients": [{"emailAddress": {"address": "[email protected]"}}],+ "internetMessageHeaders": [+ {"name": "Message-ID", "value": "<[email protected]>"},+ {"name": "From", "value": PHISH},+ {"name": "To", "value": VICTIM},+ {"name": "Authentication-Results", "value": "mx; spf=fail; dkim=none; dmarc=fail"},+ ],+ }+ message = from_graph_message(payload)+ analysis = analyse_headers(message.headers, reported_sender=message.sender)+ assert analysis.failed_methods == ("dmarc", "spf")