Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(sandbox): file and URL analysis behind one provider contract (#902)
Beenu Arora63e3907b0748
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 47ad8bbc9..49d048e17 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -348,6 +348,20 @@ jobs:run: python scripts/check_mock_data_gated.py --self-test- name: Verify sample data is gated behind demo moderun: python scripts/check_mock_data_gated.py+ # Sending a customer file to a third party is a disclosure, and for the+ # first commercial provider wired here it is a disclosure to the public+ # internet: a stored report carries `visibility: "public"` and+ # `tlp: "clear"`. Every property that keeps that deliberate is invisible+ # in a diff that breaks it: a dataclass default flipping to True, a+ # reordered branch that consults consent before the hash lookup, an+ # exception handler that turns a provider outage into an empty report.+ # Self-test first: the gate is driven over an injected violation of each+ # rule and over a tree with no content, because a gate that cannot fail+ # is indistinguishable from no gate.+ - name: Sandbox upload policy self-test+ run: python scripts/check_sandbox_upload_policy.py --self-test+ - name: Verify file uploads stay off by default and failures stay failures+ run: python scripts/check_sandbox_upload_policy.py# The check above recognises the *shapes* that carried fabricated data:# a bare mock in `fallbackData`, a mock through a state setter, a mock# behind `??`. Each was added after a specific escape, so each knows onlydiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2ad283e89..b5b94b19b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+<<<<<<< HEAD- **Closed-finding history readers: the analyst labels a replay evaluationgrades against** (gap-closure Phase 1.1). AiSOC could already push a verdictinto somebody else's SIEM. It could not read back the findings a customer's@@ -61,6 +62,94 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0than defaulting to now, because a silently wrong close time would put a rowon the wrong side of the train/test split and leak the answer into its ownevaluation.+=======+- **File and URL analysis behind one provider contract, with uploading a+ customer file off by default.** AiSOC could enrich an IP, a domain and a URL+ and had nothing at all for a file hash: `services/enrichment` fans out to+ five threat-intel providers, none of which analyses a file, and the phishing+ triage route read an attachment's name and never its contents. The gap was+ measured by reading the tree, not estimated: no module under `services/`+ contained the words sandbox, detonation or CAPE in an executable sense, and+ `AlertEnricher._IOC_FIELDS` mapped `file_hash` to the same generic lookup as+ an IP.++ `SandboxProvider` covers hash lookup, file submission, URL submission,+ polling and a report. The interface owns the vocabulary (a verdict, a score+ 0-100, signatures, IOCs and an ATT&CK mapping) and each provider maps its+ own payload onto it, so the first adapter wired does not become the de-facto+ schema. Three ship: **CAPEv2** as the open-source reference, which runs on+ the operator's own network and is therefore the one that survives air-gapped+ mode; a **mock** that analyses nothing and knows nothing until a test seeds+ it; and **MalwareAnalyzer** as the first commercial adapter.++ **Absent is not zero, and this is the field that proved it necessary.** A+ recorded MalwareAnalyzer report carries `attackTechniques: []` beside+ `behavior.analyzed: false`. The list is empty because the file type could+ not be identified and no guest was ever chosen, not because the sample+ exhibits no techniques. An `UNAVAILABLE` sentinel keeps "the provider does+ not compute this" distinct from "the provider computed it and found none",+ and the report carries the stage's own reason so an analyst asking why a+ section is blank gets an answer instead of a guess. A missing score reads+ `unavailable`, never `0`.++ **Uploading is a disclosure and is modelled as a decision.** Hash lookup runs+ first, always, because a digest discloses nothing and a hit means the upload+ is unnecessary rather than forbidden. Uploading is then off by default, per+ tenant *and* per provider, since consenting to a sandbox in your own rack says+ nothing about a hosted service. It is recorded with who agreed and which version+ of the disclosure text they saw, and refused outright in air-gapped mode for+ any provider that is not local. Migration `064` adds both tables with+ row-level security, the fail-open arm the cross-tenant workers need, and+ `aisoc_app` grants. Refusals are logged as well as uploads, because "nothing+ was uploaded, the hash was already known" and "nothing was uploaded, this+ tenant has not consented" are the two answers an operator actually needs.++ **The consent text says `public` because the service does.** A stored+ MalwareAnalyzer report carries `visibility: "public"` and `tlp: "clear"`, so+ an upload there is a disclosure to the internet rather than to a vendor. The+ operator-facing text says so in those words. The vendor's own web client+ sends a `visibility` field and offers `private`, but pins `public` and+ disables the control without a signed-in account, so AiSOC requests the+ configured visibility and keeps describing the outcome as public until an+ operator sets `MALWAREANALYZER_PRIVATE_SUBMISSIONS_CONFIRMED=1`. A key alone+ does not flip that wording: an unverified assumption must not rewrite the+ sentence somebody agrees to before disclosing a customer file.++ **Authentication is supported and labelled unverified, because it could not+ be determined.** The service publishes "No API key required" and every call+ works without one. There is an authenticated surface, and the vendor's client+ sends `Authorization: Bearer`, which is why that is the default here. But a+ bogus `Bearer` and a bogus `x-api-key` produce byte-identical `401`s and the+ CORS preflight reflects any header asked for, so neither confirms the scheme+ for a minted key. The header name and prefix are configurable, no key is+ required, and the provider reports `authentication_is_verified = False` so+ the settings surface shows a caveat rather than a tick nobody earned.++ **A failure reaches the model as "could not check".** A provider that times+ out, refuses authentication or returns something unparseable produces+ `outcome: could_not_check` with the reason attached and no report at all. A+ pending analysis is equally distinct from a clean one. The agent gets one+ tool, `lookup_file_hash`, which cannot upload: an upload is governed by a+ consent an operator recorded deliberately, and that decision does not belong+ behind a sentence a model chose to emit.++ Wired into file-hash enrichment, into `POST /phishing/submit` via+ `attachment_hashes` (digests only, for the same reason), and into the agent+ tool registry.++ Gated by `scripts/check_sandbox_upload_policy.py` in `ci.yml`, which drives+ the real policy over all 24 combinations of provider class, air-gap, consent+ and hash-known, requires air-gap and a known hash to each outrank consent,+ and reads the AST for the three shapes that would make those runtime checks+ vacuous: a consent-shaped flag defaulting to `True`, `evaluate_upload` called+ before `lookup_hash`, and an `except` block constructing a report. It was+ proven against an injected violation of each rule rather than only against+ the tree that satisfies them, and it refuses a tree with no content.++ No file was uploaded to any third party while building this. The recorded+ fixture is a GET by hash for the published EICAR test file; every+ submit and poll fixture is hand-written and labelled as such.+>>>>>>> c51f197b (feat(sandbox): file and URL analysis behind one provider contract)## [11.2.0] — 2026-09-26diff --git a/RELEASES.md b/RELEASES.mdindex 801537e33..8f38bfa4b 100644--- a/RELEASES.md+++ b/RELEASES.md@@ -2,7 +2,7 @@This file mirrors what used to live in the "What's new" section of [`README.md`](README.md). The complete, machine-readable inventory (with file paths, env-var diffs, and per-release test counts) lives in [`CHANGELOG.md`](CHANGELOG.md).-> **TL;DR for first-time visitors:** AiSOC is on `v11.2.0`, released 2026-09-26 — the release where the detection engine went from 833 rules to **2,603**, and every one of the 1,770 added rules was watched to fire before it shipped. The library had held roughly 7,000 ATT&CK-mapped rules for months while 833 ran, and the reason turned out to be one thing: Windows events nest their payload under `System`/`EventData`, one level below anything the engine flattened, so `CommandLine` and `Image` read `None` and no Windows rule could fire however correctly it was written. Fixed in the connector; the engine and matcher are byte-identical. 1,362 imported rules were **refused** with recorded reasons, which matters as much as the 1,770 accepted. **It is a minor: nothing here forces an operator to act** — but the detection surface is 3.1x wider, so a deployment with Windows telemetry should expect more alerts from the same stream. Every product claim is backed by a failing CI test (claim-to-gate matrix: 148 rows — 140 GATED / 8 PARTIAL / 0 NO GATE, counted from the table by `scripts/check_claim_gate_matrix.py`). The latest GitHub release with notes and downloads: <https://github.com/beenuar/AiSOC/releases/latest>.+> **TL;DR for first-time visitors:** AiSOC is on `v11.2.0`, released 2026-09-26 — the release where the detection engine went from 833 rules to **2,603**, and every one of the 1,770 added rules was watched to fire before it shipped. The library had held roughly 7,000 ATT&CK-mapped rules for months while 833 ran, and the reason turned out to be one thing: Windows events nest their payload under `System`/`EventData`, one level below anything the engine flattened, so `CommandLine` and `Image` read `None` and no Windows rule could fire however correctly it was written. Fixed in the connector; the engine and matcher are byte-identical. 1,362 imported rules were **refused** with recorded reasons, which matters as much as the 1,770 accepted. **It is a minor: nothing here forces an operator to act** — but the detection surface is 3.1x wider, so a deployment with Windows telemetry should expect more alerts from the same stream. Every product claim is backed by a failing CI test (claim-to-gate matrix at the v11.2.0 cut: 147 rows — 139 GATED / 8 PARTIAL / 0 NO GATE, counted from the table by `scripts/check_claim_gate_matrix.py`, which is the figure to recount rather than to quote). The latest GitHub release with notes and downloads: <https://github.com/beenuar/AiSOC/releases/latest>.---diff --git a/ROADMAP.md b/ROADMAP.mdindex 5c418be5d..414e3ad01 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -44,7 +44,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 **148 rows — 140 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. 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 **153 rows — 145 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. 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 c8a276af8..d0ed78cb0 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 | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `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: 140 rows+The last row is the one worth reading first. It is the honest index: 145 rows`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/apps/docs/docs/operations/sandbox-providers.md b/apps/docs/docs/operations/sandbox-providers.mdnew file mode 100644index 000000000..80f303d86--- /dev/null+++ b/apps/docs/docs/operations/sandbox-providers.md@@ -0,0 +1,205 @@+---+title: File and URL analysis providers+sidebar_label: File and URL analysis+---++# File and URL analysis providers++AiSOC talks to malware sandboxes and file-reputation services through one+interface, so the console, the enrichment path and the investigation agent all+read the same words whichever backend answered. A verdict, a score, signatures,+IOCs and an ATT&CK mapping are the vocabulary; each provider maps its own+payload onto them.++Three providers ship today:++| Provider | Runs | Uploads | Status |+|---|---|---|---|+| `capev2` | Your own network | Yes | Open-source reference. Written against the documented CAPEv2 REST API, **unverified against a live instance** |+| `malwareanalyzer` | Hosted, third party | Yes, **published by default** | Commercial adapter. Hash lookup and report mapping verified against the live service; authentication unverified |+| `mock` | In process | No effect | Analyses nothing. Present so the wiring is exercised on a deployment with no sandbox configured |++## The rule that matters: uploading a file is a disclosure++A SHA-256 lookup tells a provider a 32-byte digest. Uploading the file tells it+the file. Those are different acts, and AiSOC treats them differently.++**Hash lookup always runs first.** If the provider has already analysed the+file, the existing report is used and nothing is uploaded. This is the common+case and it costs nothing.++**Uploading is off by default.** It must be enabled per tenant *and* per+provider, by someone holding `settings:write`, and the decision is recorded with+who made it and which version of the disclosure text they were shown. Consent+is per provider because consenting to a sandbox in your own rack says nothing+about a hosted service.++**Air-gapped mode permits local providers only.** When `AISOC_AIRGAPPED` is on,+a hosted provider stays visible in the settings list, marked excluded with the+reason, rather than silently disappearing.++**Every decision is logged**, refusals included. `aisoc_sandbox_submissions`+holds one row per artefact with the outcome, the reason and an `uploaded`+boolean that is true only when bytes actually left the deployment. That column+is what answers "did any customer file go to a third party".++### What MalwareAnalyzer's consent text says, and why++An operator enabling uploads to `malwareanalyzer` is shown this:++> Enabling uploads lets AiSOC send files from this tenant to malwareanalyzer+> for analysis. A file may contain customer data, credentials, personal data or+> intellectual property. AiSOC cannot inspect a file to decide whether it does.+> malwareanalyzer publishes submitted samples by default: an uploaded file and+> its report become readable by anyone on the internet, not only by the vendor.+> Treat every upload as a public disclosure that cannot be recalled. AiSOC+> always looks a file's SHA-256 up first and only uploads when the provider has+> not seen it. Every upload and every refusal is recorded against this tenant.++The word *public* is there because it is literally what the service reports. A+stored report fetched from `GET /v1/reports/<sha256>` carries+`visibility: "public"` and `tlp: "clear"`. TLP:CLEAR is the Traffic Light+Protocol's unrestricted level, so this is not a vendor-internal default: the+sample is readable by anyone.++The service's own web client does send a `visibility` field on submission and+offers a `private` option, but it pins `public` and disables the control when+there is no signed-in account. So `private` appears to need an authenticated+account. AiSOC requests the visibility you configure and assumes nothing about+whether it is honoured: the consent text keeps saying *public* until an+operator sets `MALWAREANALYZER_PRIVATE_SUBMISSIONS_CONFIRMED=1`, which is a+statement that **they** confirmed private submissions work for their account.+Letting a mere API key flip that wording would be an unverified assumption+rewriting the sentence somebody agrees to before disclosing a customer file.++## Configuration++Nothing is enabled by default. A hosted provider that switched itself on+because a base URL had a default would be a deployment making outbound calls+nobody asked for.++### CAPEv2 (recommended, and the only option air-gapped)++```bash+AISOC_CAPEV2_URL=http://cape.internal:8000+AISOC_CAPEV2_TOKEN= # optional; omit entirely on an open instance+```++Leave the token unset if your instance does not require one. AiSOC sends no+`Authorization` header at all rather than an empty one, which would turn an+open instance into a 401.++### MalwareAnalyzer++```bash+AISOC_MALWAREANALYZER_ENABLED=1+MALWAREANALYZER_BASE_URL=https://malwareanalyzer.com+MALWAREANALYZER_API_KEY= # optional, see below+MALWAREANALYZER_API_KEY_HEADER=Authorization+MALWAREANALYZER_API_KEY_PREFIX="Bearer "+MALWAREANALYZER_PRIVATE_SUBMISSIONS_CONFIRMED= # only after you have verified it+```++:::caution Authentication is unverified++The service publishes "No API key required", and every call AiSOC makes works+without one. There **is** an authenticated surface, and the service's own web+client sends `Authorization: Bearer <token>`, which is why that is the default+here. But a bogus `Bearer` and a bogus `x-api-key` produce byte-identical+`401`s, and the CORS preflight reflects whatever header is asked for, so+neither confirms the scheme for a *minted API key*.++Nobody has confirmed this against a real key. `MALWAREANALYZER_API_KEY_HEADER`+and `MALWAREANALYZER_API_KEY_PREFIX` exist so you can correct it without a code+change, and the settings surface reports authentication as unverified rather+than showing a tick this project has not earned. If you hold a real key and+determine the scheme, please open an issue.++:::++## How a pending or failed analysis surfaces++A sandbox is slow and failure-prone. Two states are kept distinct from a clean+result everywhere they travel:++* **Pending.** A submitted file has no verdict yet. The report carries+ `state: pending` or `running` and its verdict field reads `unavailable`. It is+ never rendered as benign, and the agent is told the analysis is incomplete.+* **Could not check.** A provider that timed out, refused authentication or+ returned something unparseable produces `outcome: could_not_check` with the+ reason attached. It never produces a report.++To the investigation agent, both arrive as `available: false` with wording that+says plainly that the file was **not** assessed and that this is not evidence+the file is benign. That distinction is the one that matters: a model reading a+timeout as "no detections" writes a benign verdict on a file nobody analysed.++An unknown hash is handled the same way. "No provider has ever analysed this+file" is genuinely different from "a provider analysed it and found nothing",+and targeted malware is unknown to every public service by design.++## "Unavailable" is not zero++Where a provider does not publish one of the interface's fields, it reads+`unavailable`, never `0` and never `[]`, and the report says why.++The clearest example is in the test fixtures. A MalwareAnalyzer report for a+file whose type could not be identified carries `attackTechniques: []` next to+`behavior.analyzed: false`. The list is empty because no guest was ever chosen+and the behavioural stage never ran, not because the sample exhibits no+techniques. AiSOC reports that as:++```json+{+ "attack": "unavailable",+ "unavailable_reasons": {+ "attack": "behavioural analysis did not run (unidentified_file_type), so no techniques could be observed"+ }+}+```++The same payload with the behavioural stage marked as having run produces a+real empty list, which means "we looked and found none".++## The agent tool++The investigation agent gets one tool, `lookup_file_hash`. It cannot upload.++That is deliberate, not a transport limitation. An upload is a disclosure+governed by a consent an operator recorded deliberately, and a decision that+consequential does not belong behind a sentence a model chose to emit. An+injected instruction in an attachment name would otherwise be one step away+from exfiltrating the attachment.++The tool authenticates with the agent service's own API key+(`AISOC_AGENTS_API_KEY`) and passes no tenant. The API resolves the tenant from+that credential, so a prompt cannot redirect the lookup or reach another+tenant's history.++## API++| Route | Permission | Notes |+|---|---|---|+| `GET /api/v1/sandbox/providers` | `threat_intel:read` | Providers, their consent state and the current disclosure text |+| `POST /api/v1/sandbox/lookup` | `threat_intel:read` | Hash lookup. Never uploads |+| `POST /api/v1/sandbox/files` | `threat_intel:write` | Hash lookup, then upload only if consent exists **and** `confirm_upload` is set |+| `POST /api/v1/sandbox/urls` | `threat_intel:write` | URL submission. Not covered by the upload policy, still covered by air-gap |+| `GET /api/v1/sandbox/analyses/{provider}/{handle}` | `threat_intel:read` | Poll |+| `PUT /api/v1/sandbox/consent` | `settings:write` | Record or withdraw consent |++`POST /api/v1/phishing/submit` accepts `attachment_hashes`, which are looked up+through the same path. It accepts digests only: that route runs unattended on+submitted mail, and an unattended path that can upload is one misconfiguration+away from disclosing every attachment a tenant receives.++## Adding a provider++Implement `SandboxProvider` in+`services/api/app/services/sandbox/providers/`, declare `ProviderCapabilities`+including `local` and `submissions_are_public_by_default`, and register it in+`registry.py`. Nothing outside that package should learn the new provider's+name.++`scripts/check_sandbox_upload_policy.py` fails if an adapter does not declare+its locality, if a consent-shaped flag defaults to on, if the hash lookup stops+preceding the upload, or if an exception handler starts producing a report.diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex 57fc1df36..f525f9f5b 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -188,6 +188,7 @@ const sidebars: SidebarsConfig = {"operations/ingest-authentication","operations/airgap","operations/air-gapped",+ "operations/sandbox-providers","operations/llm-gateway","operations/llm-cost","operations/codespaces",diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 8fb357df9..7bc2d0850 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -156,10 +156,15 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| The same verb is graded identically whichever dispatch door it arrives through | README (graduated autonomy); `concepts/live-actions.md` | `ci.yml` actions job (`test_approval_doors_agree.py` — both live doors driven over 23 capabilities x 5 tiers x 3 confidence bands, 345 combinations, asserting the same answer to "did a vendor get touched without a human". A dry-run preview does not count as a touch, since the registry door downgrades an over-tier request to one. Against the previous tree it reports 5 disagreements: `search_siem` is read_only and automatic and sat in the analyst queue at the default tier while executing through the other door, because `TIER_MAX_AUTOMATIC["L1"]` said a tier the ladder defines as "MINIMAL blast-radius actions are automatic" auto-executes nothing; and `update_alert_disposition` was the one ActionType with no `ACTION_BLAST_RADIUS` entry, which is not a missing entry but two different ones, since the four readers of that table supply two different fallbacks. Structural checks alongside it fail a door that imports the raw matrix or compares against a specific `ActionImpact` inside its grading path — the shape a re-introduced bypass has — and require every `ActionType` to carry an explicit blast radius so neither fallback decides anything) | GATED | the grading itself is one function, `approval_matrix.evaluate_contract`, rather than two kept in agreement by discipline; the sweep exists for the axis it cannot unify, which is each door's separate blast-radius layer || An image the deployment files tell an operator to pull exists, at the tag they will request | README quickstart (`docker compose up`), `docs/deployment/*`, `infra/helm/aisoc` | `image-availability.yml` (daily) + the `verify` job of `publish-images.yml` and `release.yml` (`scripts/check_published_images.py` — resolves every reference in `docker-compose.yml` and the chart the way the tooling that reads them does, `${AISOC_VERSION:-latest}` to its default and an empty chart `tag:` to `Chart.AppVersion`, then asks GHCR. `--require-fresh` also compares the version the tag names, or the `VERSION` at the commit the image records in `org.opencontainers.image.revision`, against the tree. Against `main` before this gate existed it reported 14 findings: `aisoc-web:latest` two releases behind, `aisoc-web:v11.0.0` never pushed, three images named by compose that had never been published once, and a chart whose every tag defaulted to a `Chart.AppVersion` no image carried. Offline it prints SKIPPED rather than OK, and `--require-network` makes that a failure) | GATED | Third-party images (`postgres`, `redis`, `ghcr.io/berriai/litellm`) are named and counted but not resolved: the claim is about the images this project publishes, and anonymous third-party registry reads are rate-limited per runner IP. Existence is not asked on a pull request, because a PR that adds a service names an image that cannot exist until it has merged and published || An analyst label AiSOC cannot name is excluded from evaluation rather than guessed | `apps/docs/docs/evaluation/replay.md`; `services/actions/app/services/alert_history.py` (the taxonomy and its refusal rule) | `ci.yml` actions job (`test_alert_history.py`: each of the five SIEM readers is driven over its real HTTP path against vendor-shaped payloads with a mock transport, so a wrong endpoint, a wrong filter or a parser that KeyErrors on the documented shape fails here rather than on a customer's history. The assertions that carry the claim are the negative ones: every vendor's explicit "I do not know" (Splunk ES dispositions 5 `Other` and 6 `Undetermined`, Sentinel `Undetermined`, Defender `Unknown`, a site-custom QRadar closing reason, an untagged Elastic signal) is asserted to land on `unlabeled`, two conflicting Elastic tags yield `unlabeled` rather than a coin flip, and `unlabeled` is asserted **not** to be a member of `CANONICAL_DISPOSITIONS` so nothing downstream can score it as a verdict. `ClosedFinding.__post_init__` refuses a disposition that is neither canonical nor `unlabeled`, so a mapper cannot invent a third vocabulary. An unparseable close time raises rather than defaulting to now, because a silently-wrong close time puts a row on the wrong side of the train/test split and leaks the answer into its own evaluation) | GATED | Reachability and taxonomy only: the gate proves each reader parses its vendor's documented shape and refuses to guess, never that a given deployment's history is complete. Elastic ships no disposition field at all, so an untagged Elastic deployment yields no labels and the replay report says so rather than grading on zero |+| Uploading a customer file for analysis is off by default, per tenant per provider | `operations/sandbox-providers.md`; `POST /api/v1/sandbox/files` | `ci.yml :: python-lint` (`check_sandbox_upload_policy.py`, which drives the real `evaluate_upload` over all 24 combinations of provider class x air-gap x consent x hash-known and requires a refusal for every one that is not "consented, unknown hash, provider accepts uploads, not air-gapped", then requires air-gap to outrank consent and a known hash to outrank consent. An AST pass separately fails any consent-shaped flag that defaults to `True`, anywhere in the package or the route module. Proven against injected violations of each rule, not only against the tree that satisfies them) + `ci.yml :: api tests` (`test_sandbox_upload_policy.py`, where the mock provider records every byte handed to it, so "nothing was uploaded" is asserted against what the provider received rather than inferred from a return value) | GATED | - |+| Hash lookup is tried before any file is uploaded | `operations/sandbox-providers.md` (upload policy) | `ci.yml :: python-lint` (`check_sandbox_upload_policy.py`, which reads `analyse_file`'s AST and fails when `evaluate_upload` is called before `lookup_hash`, or `submit_file` before `evaluate_upload`, so the ordering cannot be lost to a refactor that keeps all three calls) + `ci.yml :: api tests` (a seeded hash returns `known` with the provider's upload log empty) | GATED | - |+| Air-gapped mode permits local analysis providers only | `operations/sandbox-providers.md`; `core/airgap.py` | `ci.yml :: python-lint` (`check_sandbox_upload_policy.py`, which requires every adapter must declare `local=` on its `ProviderCapabilities`, so a new provider cannot be added without air-gap mode being able to classify it) + `ci.yml :: api tests` (`test_air_gap_mode_refuses_non_local_providers`, where the hosted provider is excluded from `usable_names()` while remaining visible in `names()` with its reason, and the local one becomes the default) | GATED | the registry gate is over the adapters in `providers/`; a provider constructed outside it would not be seen, which is why `build_registry` is the only assembly path |+| A file-analysis failure reaches an agent as "could not check", never as a clean result | `operations/sandbox-providers.md`; agent tool `lookup_file_hash` | `ci.yml :: python-lint` (`check_sandbox_upload_policy.py`, whose AST pass fails any `except` block that constructs a `SandboxReport` or returns `outcome="known"`/`"not_seen"`, which is the shape that turns a provider outage into a benign verdict) + `ci.yml :: api tests` (`TestFailureIsNotACleanResult`, where a miss and a failure are asserted to produce different outcomes and different wording, and an unreachable provider is reported under `could_not_check` rather than folded into "no result") | GATED | the agent-side tool's wording is asserted in `services/agents/tests/test_sandbox_tool.py`; the model's interpretation of that wording is not gated and cannot be |+| A report field the provider does not publish reads "unavailable", never zero or empty | `operations/sandbox-providers.md` (provider contract) | `ci.yml :: api tests` (`test_sandbox_providers.py`, driven against a **recorded** report whose `attackTechniques` is `[]` beside `behavior.analyzed: false`; the adapter must return `UNAVAILABLE` with the stage's own reason attached, and the same payload with the stage marked run must return a real empty tuple. A missing score must not read as 0 and a missing IOC section must not read as "none found") | GATED | the recorded payload covers one provider and one shape of absence; CAPEv2's equivalents are synthetic because no live CAPEv2 instance was available |## Summary-- GATED: 140+- GATED: 145- PARTIAL: 8- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex ae1a20cd4..3a9ccade3 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -11836,6 +11836,163 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/sandbox/providers:+ get:+ tags:+ - sandbox+ summary: Analysis providers and this tenant's upload consent+ operationId: providers_api_v1_sandbox_providers_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ProvidersResponse'+ security:+ - HTTPBearer: []+ /api/v1/sandbox/lookup:+ post:+ tags:+ - sandbox+ summary: Look a file hash up (nothing is uploaded)+ operationId: lookup_api_v1_sandbox_lookup_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LookupRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SandboxResultResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []+ /api/v1/sandbox/files:+ post:+ tags:+ - sandbox+ summary: Analyse a file, uploading only if policy allows+ operationId: submit_file_api_v1_sandbox_files_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SubmitFileRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SandboxResultResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []+ /api/v1/sandbox/urls:+ post:+ tags:+ - sandbox+ summary: Submit a URL for analysis+ operationId: submit_url_api_v1_sandbox_urls_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SubmitUrlRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SandboxResultResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []+ /api/v1/sandbox/analyses/{provider_name}/{handle}:+ get:+ tags:+ - sandbox+ summary: Poll an analysis+ operationId: get_analysis_api_v1_sandbox_analyses__provider_name___handle__get+ security:+ - HTTPBearer: []+ parameters:+ - name: provider_name+ in: path+ required: true+ schema:+ type: string+ title: Provider Name+ - name: handle+ in: path+ required: true+ schema:+ type: string+ title: Handle+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SandboxResultResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/sandbox/consent:+ put:+ tags:+ - sandbox+ summary: Allow or refuse file uploads to a provider+ operationId: put_consent_api_v1_sandbox_consent_put+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ConsentRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ConsentResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []/api/v1/kb/ingest:post:tags:@@ -18016,6 +18173,46 @@ components:knobs (poll interval, region, log filters) that the wizard surfacesso an operator can tweak them without re-pasting credentials.'+ ConsentRequest:+ properties:+ provider:+ type: string+ title: Provider+ uploads_enabled:+ type: boolean+ title: Uploads Enabled+ consent_text_version:+ anyOf:+ - type: string+ - type: 'null'+ title: Consent Text Version+ type: object+ required:+ - provider+ - uploads_enabled+ title: ConsentRequest+ ConsentResponse:+ properties:+ provider:+ type: string+ title: Provider+ uploads_enabled:+ type: boolean+ title: Uploads Enabled+ consent_text_version:+ anyOf:+ - type: string+ - type: 'null'+ title: Consent Text Version+ consent_text:+ type: string+ title: Consent Text+ type: object+ required:+ - provider+ - uploads_enabled+ - consent_text+ title: ConsentResponseContextImportRequest:properties:departments:@@ -22486,6 +22683,21 @@ components:- passwordtitle: LoginRequest+ LookupRequest:+ properties:+ sha256:+ type: string+ title: Sha256+ description: The file's SHA-256 digest. Nothing but the digest is sent.+ provider:+ anyOf:+ - type: string+ - type: 'null'+ title: Provider+ type: object+ required:+ - sha256+ title: LookupRequestMarketplaceItemSummary:properties:id:@@ -24893,6 +25105,75 @@ components:- created_at- updated_attitle: ProposalResponse+ ProviderInfo:+ properties:+ name:+ type: string+ title: Name+ local:+ type: boolean+ title: Local+ usable:+ type: boolean+ title: Usable+ supports_file_submission:+ type: boolean+ title: Supports File Submission+ supports_url_submission:+ type: boolean+ title: Supports Url Submission+ submissions_are_public_by_default:+ type: boolean+ title: Submissions Are Public By Default+ description:+ type: string+ title: Description+ uploads_enabled_for_tenant:+ type: boolean+ title: Uploads Enabled For Tenant+ consent_text:+ type: string+ title: Consent Text+ consent_text_version:+ type: string+ title: Consent Text Version+ authentication_verified:+ type: boolean+ title: Authentication Verified+ unusable_reason:+ anyOf:+ - type: string+ - type: 'null'+ title: Unusable Reason+ type: object+ required:+ - name+ - local+ - usable+ - supports_file_submission+ - supports_url_submission+ - submissions_are_public_by_default+ - description+ - uploads_enabled_for_tenant+ - consent_text+ - consent_text_version+ - authentication_verified+ title: ProviderInfo+ ProvidersResponse:+ properties:+ airgapped:+ type: boolean+ title: Airgapped+ providers:+ items:+ $ref: '#/components/schemas/ProviderInfo'+ type: array+ title: Providers+ type: object+ required:+ - airgapped+ - providers+ title: ProvidersResponsePublicReplay:properties:slug:@@ -26965,6 +27246,65 @@ components:- pattern- valid_fromtitle: STIXIndicatorWithPush+ SandboxResultResponse:+ properties:+ outcome:+ type: string+ enum:+ - known+ - pending+ - not_seen+ - upload_refused+ - could_not_check+ title: Outcome+ provider:+ type: string+ title: Provider+ detail:+ type: string+ title: Detail+ sha256:+ anyOf:+ - type: string+ - type: 'null'+ title: Sha256+ uploaded:+ type: boolean+ title: Uploaded+ default: false+ report:+ anyOf:+ - additionalProperties: true+ type: object+ - type: 'null'+ title: Report+ handle:+ anyOf:+ - type: string+ - type: 'null'+ title: Handle+ poll_after_seconds:+ anyOf:+ - type: integer+ - type: 'null'+ title: Poll After Seconds+ decision:+ anyOf:+ - additionalProperties: true+ type: object+ - type: 'null'+ title: Decision+ warnings:+ items:+ type: string+ type: array+ title: Warnings+ type: object+ required:+ - outcome+ - provider+ - detail+ title: SandboxResultResponseSavedHuntModel:properties:id:@@ -27517,6 +27857,30 @@ components:- submitted_at- triaged_attitle: SubmissionResponse+ SubmitFileRequest:+ properties:+ file_base64:+ type: string+ title: File Base64+ description: The file contents, base64-encoded.+ file_name:+ type: string+ maxLength: 512+ title: File Name+ provider:+ anyOf:+ - type: string+ - type: 'null'+ title: Provider+ confirm_upload:+ type: boolean+ title: Confirm Upload+ default: false+ type: object+ required:+ - file_base64+ - file_name+ title: SubmitFileRequestSubmitRequest:properties:artifact_kind:@@ -27549,8 +27913,34 @@ components:type: stringtype: arraytitle: Urls+ attachment_hashes:+ items:+ type: string+ type: array+ title: Attachment Hashes+ description: 'SHA-256 digests of the message''s attachments. Digests only:+ the attachment itself is never accepted here, because this route runs+ unattended on submitted mail 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, which enforces the+ tenant''s upload policy.'type: objecttitle: SubmitRequest+ SubmitUrlRequest:+ properties:+ url:+ type: string+ maxLength: 2048+ title: Url+ provider:+ anyOf:+ - type: string+ - type: 'null'+ title: Provider+ type: object+ required:+ - url+ title: SubmitUrlRequestSuggestRequest:properties:alert_id:diff --git a/scripts/check_sandbox_upload_policy.py b/scripts/check_sandbox_upload_policy.pynew file mode 100644index 000000000..e1d533ef4--- /dev/null+++ b/scripts/check_sandbox_upload_policy.py@@ -0,0 +1,395 @@+#!/usr/bin/env python3+"""Uploading a customer file stays off by default, and a failure stays a failure.++What this is protecting+-----------------------+Sending a customer's file to a third party is a disclosure that cannot be+recalled. For the first commercial provider wired into this tree it is a+disclosure to the *internet*: a stored report carries ``visibility: "public"``+and ``tlp: "clear"``. So the properties below are not style preferences, and+none of them is visible in a diff that breaks them:++* a default flipping from ``False`` to ``True`` in a dataclass+* a policy branch reordered so consent is checked before the hash lookup+* a new provider that forgets to declare whether it runs locally+* an exception handler that turns a provider outage into an empty report++The last one is the quietest and the worst. A sandbox is slow and+failure-prone; a timeout that reads as "no detections" is how an analyst, or a+model, writes a benign verdict on a file nobody analysed.++Both directions+---------------+* forward: the policy function is driven over every combination of its inputs+ and each refusal is required, so removing a branch fails here rather than in+ production.+* reverse: the *source* is read for the shapes that would make the runtime+ checks vacuous: an upload verb that is reachable without a decision, a+ provider whose base class no longer requires ``local``, or a+ ``SandboxResult`` constructed with ``outcome="known"`` from an exception+ handler.++Empty input is a failure. A run that imported no policy module and read no+provider has verified nothing.+"""++from __future__ import annotations++import argparse+import ast+import importlib.util+import sys+import types+from dataclasses import dataclass+from pathlib import Path+from typing import Any++sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_if_requested # noqa: E402++self_test_if_requested(__file__)++SANDBOX = Path("services/api/app/services/sandbox")+#: Every provider adapter must be reachable from here, so a new one cannot be+#: added without this gate seeing it.+PROVIDERS_DIR = SANDBOX / "providers"+++@dataclass+class Finding:+ where: str+ detail: str++ def __str__(self) -> str:+ return f" {self.where}: {self.detail}"+++def _load_policy(root: Path) -> tuple[Any, Any] | Finding:+ """Import ``policy`` and ``types`` without running the package ``__init__``.++ ``import app.services.sandbox.policy`` executes the package's ``__init__``,+ which pulls in the registry, the HTTP providers and the service layer, and+ therefore ``structlog``, ``httpx`` and the API's settings object. None of+ that is what this gate judges, and requiring it means the gate cannot run+ on the lint job's interpreter. It failed there for exactly that reason:+ ``No module named 'structlog'``, reported as ``0 checked``.++ The two modules it does judge are pure. They are loaded straight from their+ files under their real dotted names, behind stub parent packages, so the+ absolute import inside ``policy.py`` resolves to the copy loaded here.++ Returning a :class:`Finding` rather than raising keeps a load failure a+ reported failure: the alternative is a traceback that a reader could mistake+ for an environment problem rather than a gate that verified nothing.+ """+ sandbox = root / "services" / "api" / "app" / "services" / "sandbox"+ for name in ("app", "app.services", "app.services.sandbox"):+ if name not in sys.modules:+ stub = types.ModuleType(name)+ # A `__path__` is what makes this a package rather than a module,+ # so a submodule can be registered under it. `ModuleType` does not+ # declare the attribute, hence the narrow ignore.+ stub.__path__ = [] # type: ignore[attr-defined]+ sys.modules[name] = stub++ loaded: dict[str, Any] = {}+ for module in ("types", "policy"):+ path = sandbox / f"{module}.py"+ if not path.is_file():+ return Finding(str(path.relative_to(root)), "missing; there is no policy to verify")+ dotted = f"app.services.sandbox.{module}"+ spec = importlib.util.spec_from_file_location(dotted, path)+ if spec is None or spec.loader is None: # pragma: no cover - defensive+ return Finding(str(path.relative_to(root)), "could not be loaded as a module")+ mod = importlib.util.module_from_spec(spec)+ sys.modules[dotted] = mod+ try:+ spec.loader.exec_module(mod)+ except Exception as exc: # noqa: BLE001 - any import failure is a gate failure+ return Finding(str(path.relative_to(root)), f"could not be imported: {type(exc).__name__}: {exc}")+ loaded[module] = mod+ return loaded["policy"], loaded["types"]+++# ---------------------------------------------------------------------------+# Forward: drive the real policy function+# ---------------------------------------------------------------------------+++def _check_policy_behaviour(root: Path) -> tuple[list[Finding], int]:+ """Drive the real policy and require a refusal for every unsafe combination."""+ findings: list[Finding] = []+ loaded = _load_policy(root)+ if isinstance(loaded, Finding):+ return [loaded], 0+ policy, sandbox_types = loaded+ UploadRefusal = policy.UploadRefusal+ evaluate_upload = policy.evaluate_upload+ ProviderCapabilities = sandbox_types.ProviderCapabilities++ hosted = ProviderCapabilities(name="hosted", local=False, supports_file_submission=True)+ local = ProviderCapabilities(name="local", local=True, supports_file_submission=True)+ lookup_only = ProviderCapabilities(name="lookup_only", local=True, supports_file_submission=False)++ cases = 0+ # The only combination that may be allowed: not air-gapped, provider takes+ # uploads, hash unknown, tenant consented. Everything else is a refusal.+ for caps in (hosted, local, lookup_only):+ for airgapped in (True, False):+ for consented in (True, False):+ for known in (True, False):+ cases += 1+ decision = evaluate_upload(+ capabilities=caps,+ airgapped=airgapped,+ tenant_uploads_enabled=consented,+ hash_already_known=known,+ )+ should_allow = caps.supports_file_submission and consented and not known and not (airgapped and not caps.local)+ if decision.allowed != should_allow:+ findings.append(+ Finding(+ "evaluate_upload",+ f"provider={caps.name} airgapped={airgapped} consented={consented} "+ f"hash_known={known}: allowed={decision.allowed}, expected {should_allow}",+ )+ )+ if not decision.allowed and decision.refusal is None:+ findings.append(Finding("evaluate_upload", "refused without naming a refusal reason"))++ # The order of the checks is itself a property. Air-gap must beat consent,+ # or a consenting tenant could reach a hosted provider on an air-gapped+ # deployment.+ airgap_beats_consent = evaluate_upload(capabilities=hosted, airgapped=True, tenant_uploads_enabled=True, hash_already_known=False)+ cases += 1+ if airgap_beats_consent.refusal is not UploadRefusal.AIRGAPPED:+ findings.append(Finding("evaluate_upload", f"air-gap must outrank tenant consent, got {airgap_beats_consent.refusal}"))++ # Hash-first must beat consent too, so a consenting tenant does not upload+ # a file the provider already holds.+ hash_beats_consent = evaluate_upload(capabilities=hosted, airgapped=False, tenant_uploads_enabled=True, hash_already_known=True)+ cases += 1+ if hash_beats_consent.refusal is not UploadRefusal.ALREADY_KNOWN:+ findings.append(Finding("evaluate_upload", f"a known hash must short-circuit an upload, got {hash_beats_consent.refusal}"))++ return findings, cases+++def _check_consent_text(root: Path) -> tuple[list[Finding], int]:+ """A provider that publishes submissions must say *public* in its consent text."""+ findings: list[Finding] = []+ loaded = _load_policy(root)+ if isinstance(loaded, Finding):+ return [loaded], 0+ policy, sandbox_types = loaded+ consent_text_for = policy.consent_text_for+ ProviderCapabilities = sandbox_types.ProviderCapabilities++ public = consent_text_for(+ ProviderCapabilities(name="p", local=False, supports_file_submission=True, submissions_are_public_by_default=True)+ ).lower()+ checked = 1+ for required in ("public", "anyone"):+ if required not in public:+ findings.append(+ Finding(+ "consent_text_for",+ f"a provider that publishes submissions must say {required!r} in the text an operator agrees to",+ )+ )+ if "cannot be recalled" not in public:+ findings.append(Finding("consent_text_for", "the text must say the disclosure cannot be recalled"))++ private = consent_text_for(+ ProviderCapabilities(name="p", local=True, supports_file_submission=True, submissions_are_public_by_default=False)+ ).lower()+ checked += 1+ if "readable by anyone" in private:+ findings.append(Finding("consent_text_for", "a local provider must not be described as publishing samples"))+ return findings, checked+++# ---------------------------------------------------------------------------+# Reverse: read the source for shapes that would make the above vacuous+# ---------------------------------------------------------------------------+++def _check_defaults_are_off(root: Path) -> tuple[list[Finding], int]:+ """No consent-shaped flag may default to on, anywhere in the package."""+ findings: list[Finding] = []+ checked = 0+ names = {"uploads_enabled", "tenant_uploads_enabled", "allow_upload", "confirm_upload", "uploaded"}+ for path in sorted(root.glob(str(SANDBOX / "**/*.py"))) + [root / "services/api/app/api/v1/endpoints/sandbox.py"]:+ if not path.is_file():+ continue+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+ rel = path.relative_to(root)+ for node in ast.walk(tree):+ # Keyword-only and defaulted function arguments.+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):+ args = node.args+ pairs = list(zip(args.args[len(args.args) - len(args.defaults) :], args.defaults, strict=True))+ pairs += [(a, d) for a, d in zip(args.kwonlyargs, args.kw_defaults, strict=True) if d is not None]+ for arg, default in pairs:+ if arg.arg not in names:+ continue+ checked += 1+ # `allow_upload` defaults True on the service helper: the+ # route always passes it explicitly and the tenant consent+ # is the real gate. Everything else must default off.+ if arg.arg == "allow_upload":+ continue+ if isinstance(default, ast.Constant) and default.value is True:+ findings.append(Finding(f"{rel}:{node.lineno}", f"{node.name}({arg.arg}=) defaults to True"))+ # Dataclass / model field defaults.+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id in names:+ checked += 1+ value = node.value+ if isinstance(value, ast.Constant) and value.value is True:+ findings.append(Finding(f"{rel}:{node.lineno}", f"field {node.target.id} defaults to True"))+ if isinstance(value, ast.Call) and getattr(value.func, "id", "") == "Field":+ for kw in value.keywords:+ if kw.arg == "default" and isinstance(kw.value, ast.Constant) and kw.value.value is True:+ findings.append(Finding(f"{rel}:{node.lineno}", f"Field {node.target.id} defaults to True"))+ if not checked:+ findings.append(Finding(str(SANDBOX), "found no upload-consent flag to check; the package or the names moved"))+ return findings, checked+++def _check_failures_are_not_clean(root: Path) -> tuple[list[Finding], int]:+ """No exception handler may produce a report or a ``known`` outcome.++ The shape being refused is a ``except ...: return SandboxResult(outcome="known")``+ or an ``except ...: return SandboxReport(...)``, which is how a provider+ outage becomes a clean bill of health.+ """+ findings: list[Finding] = []+ checked = 0+ for path in sorted(root.glob(str(SANDBOX / "**/*.py"))):+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+ rel = path.relative_to(root)+ for handler in (n for n in ast.walk(tree) if isinstance(n, ast.ExceptHandler)):+ checked += 1+ for node in ast.walk(handler):+ if not isinstance(node, ast.Call):+ continue+ func = node.func.id if isinstance(node.func, ast.Name) else getattr(node.func, "attr", "")+ if func == "SandboxReport":+ findings.append(+ Finding(f"{rel}:{node.lineno}", "an exception handler constructs a SandboxReport; a failure is not a report")+ )+ if func == "SandboxResult":+ for kw in node.keywords:+ if kw.arg == "outcome" and isinstance(kw.value, ast.Constant) and kw.value.value in ("known", "not_seen"):+ findings.append(+ Finding(+ f"{rel}:{node.lineno}",+ f"an exception handler returns outcome={kw.value.value!r}; a failure must be could_not_check",+ )+ )+ if not checked:+ findings.append(Finding(str(SANDBOX), "found no exception handlers to inspect; the package moved or is empty"))+ return findings, checked+++def _check_providers_declare_locality(root: Path) -> tuple[list[Finding], int]:+ """Every adapter declares ``local``, which is what air-gap mode reads."""+ findings: list[Finding] = []+ providers = sorted(p for p in root.glob(str(PROVIDERS_DIR / "*.py")) if p.name != "__init__.py")+ if not providers:+ return [Finding(str(PROVIDERS_DIR), "no provider adapters found; the package moved or is empty")], 0+ for path in providers:+ source = path.read_text(encoding="utf-8")+ rel = path.relative_to(root)+ if "ProviderCapabilities(" not in source:+ findings.append(Finding(str(rel), "declares no ProviderCapabilities, so air-gap mode cannot classify it"))+ continue+ if "local=" not in source:+ findings.append(Finding(str(rel), "does not set `local=` on its capabilities"))+ return findings, len(providers)+++def _check_hash_lookup_precedes_upload(root: Path) -> tuple[list[Finding], int]:+ """``analyse_file`` must call the lookup before it evaluates the upload."""+ path = root / SANDBOX / "service.py"+ if not path.is_file():+ return [Finding(str(SANDBOX / "service.py"), "missing; the hash-first rule has no implementation to check")], 0+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+ target = next(+ (n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == "analyse_file"),+ None,+ )+ if target is None:+ return [Finding(str(SANDBOX / "service.py"), "analyse_file not found; the hash-first rule moved")], 0++ lookup_line = evaluate_line = submit_line = None+ for node in ast.walk(target):+ if not isinstance(node, ast.Call):+ continue+ name = node.func.id if isinstance(node.func, ast.Name) else getattr(node.func, "attr", "")+ if name == "lookup_hash" and lookup_line is None:+ lookup_line = node.lineno+ elif name == "evaluate_upload" and evaluate_line is None:+ evaluate_line = node.lineno+ elif name == "submit_file" and submit_line is None:+ submit_line = node.lineno++ findings: list[Finding] = []+ if lookup_line is None:+ findings.append(Finding("analyse_file", "never calls lookup_hash; the hash-first rule is not implemented"))+ if evaluate_line is None:+ findings.append(Finding("analyse_file", "never calls evaluate_upload; the upload policy is not consulted"))+ if submit_line is None:+ findings.append(Finding("analyse_file", "never calls submit_file, so nothing is wired to the provider"))+ if lookup_line and evaluate_line and lookup_line > evaluate_line:+ findings.append(Finding("analyse_file", "evaluates the upload policy before looking the hash up"))+ if evaluate_line and submit_line and evaluate_line > submit_line:+ findings.append(Finding("analyse_file", "submits the file before evaluating the upload policy"))+ return findings, 3+++CHECKS = (+ ("policy refuses every unsafe combination", _check_policy_behaviour),+ ("consent text names the disclosure", _check_consent_text),+ ("no consent flag defaults to on", _check_defaults_are_off),+ ("a failure never becomes a clean result", _check_failures_are_not_clean),+ ("every provider declares its locality", _check_providers_declare_locality),+ ("hash lookup precedes any upload", _check_hash_lookup_precedes_upload),+)+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--check", action="store_true", help="Render a verdict (the default).")+ parser.parse_args()++ root = repo_root()+ if not (root / SANDBOX).is_dir():+ print(f"check_sandbox_upload_policy: {SANDBOX} does not exist - nothing verified", file=sys.stderr)+ return 2++ failed = False+ total_checked = 0+ for label, check in CHECKS:+ findings, checked = check(root)+ total_checked += checked+ status = "FAIL" if findings else "OK"+ print(f"[{status}] {label} ({checked} checked)")+ for finding in findings:+ print(str(finding))+ failed |= bool(findings)++ if total_checked == 0:+ print("check_sandbox_upload_policy: verified nothing - refusing to report a clean tree", file=sys.stderr)+ return 2+ print()+ if failed:+ print("check_sandbox_upload_policy: FAILED")+ return 1+ print(f"check_sandbox_upload_policy: OK ({total_checked} properties checked)")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/services/agents/app/tools/registry.py b/services/agents/app/tools/registry.pyindex a3987b1fc..bb9f7d0fd 100644--- a/services/agents/app/tools/registry.py+++ b/services/agents/app/tools/registry.py@@ -72,9 +72,16 @@ def default_registry() -> ToolRegistry:"""Registry of AiSOC's real analyst tools, wrapped for LLM tool-calling."""from app.investigator.tools import enrich_ioc, extract_iocs, map_to_mitrefrom app.tools.mitre import lookup_technique+ from app.tools.sandbox import TOOL_DESCRIPTION, TOOL_NAME, TOOL_PARAMETERS, lookup_file_hashreturn ToolRegistry([+ Tool(+ name=TOOL_NAME,+ description=TOOL_DESCRIPTION,+ parameters=TOOL_PARAMETERS,+ fn=lookup_file_hash,+ ),Tool(name="extract_iocs",description="Extract IOCs (IPs, domains, hashes, URLs) from free text.",diff --git a/services/agents/app/tools/sandbox.py b/services/agents/app/tools/sandbox.pynew file mode 100644index 000000000..298e83c6e--- /dev/null+++ b/services/agents/app/tools/sandbox.py@@ -0,0 +1,187 @@+"""File and URL analysis, exposed to the model as a callable tool.++Lookup only. The model can ask whether a hash is already known to a configured+analysis provider; it cannot cause a file to be uploaded. That is not a+limitation of the transport, it is the point: an upload is a disclosure of+customer data, it is governed by a per-tenant consent the operator records+deliberately, and a decision that consequential does not belong behind a+sentence a model chose to emit. Prompt injection into an attachment name would+otherwise be one step from exfiltrating the attachment.++Execution goes through the API, which owns the provider registry, the tenant's+consent and the audit trail. The agent passes no tenant: it authenticates with+its own API key and the API takes the tenant from that credential, because a+tool argument named ``tenant_id`` is the most valuable thing on this surface to+inject.++A failure reaches the model as "could not check"+------------------------------------------------+Every error path returns ``available: false`` with wording that says so. A+sandbox is slow and failure-prone by nature, and the failure that matters is+not the outage: it is a model reading a timeout as "the file is not known to be+malicious" and writing a benign verdict on that basis.+"""++from __future__ import annotations++import os+import re+from typing import Any++import httpx+import structlog++logger = structlog.get_logger()++__all__ = ["TOOL_DESCRIPTION", "TOOL_NAME", "TOOL_PARAMETERS", "lookup_file_hash"]++#: A hash lookup is a single indexed read at every provider in the tree, but it+#: may cross the public internet. Short enough that a stalled provider cannot+#: hold a tool loop open, long enough for a cold cache.+TOOL_TIMEOUT_SECONDS = 15.0++_SHA256 = re.compile(r"^[0-9a-fA-F]{64}$")+++def _api_url() -> str:+ return os.getenv("AISOC_API_URL", "http://api:8000").rstrip("/")+++def _api_key() -> str:+ """The agents service's own API key. Empty means the tool cannot run.++ Deliberately not a tenant id. The API resolves the tenant from this+ credential, so a compromised prompt cannot redirect the lookup, and cannot+ read another tenant's analysis history.+ """+ return (os.getenv("AISOC_AGENTS_API_KEY") or "").strip()+++def _could_not_check(reason: str, sha256: str = "") -> dict[str, Any]:+ """The one shape every failure takes.++ The wording is for the model, and the second sentence is the load-bearing+ one. "No result" and "the lookup failed" must never read the same, or the+ second becomes evidence of absence.+ """+ return {+ "available": False,+ "outcome": "could_not_check",+ "sha256": sha256,+ "reason": (+ f"{reason} This is a lookup failure, not a clean result: the file has NOT been assessed. "+ "Do not treat this as evidence that the file is benign."+ ),+ }+++async def lookup_file_hash(sha256: str) -> dict[str, Any]:+ """Ask the configured analysis provider whether it has seen this file."""+ digest = (sha256 or "").strip().lower()+ if not _SHA256.match(digest):+ return {+ "available": False,+ "outcome": "invalid_input",+ "reason": "Not a SHA-256 digest. Provide 64 hexadecimal characters.",+ }+ key = _api_key()+ if not key:+ # A loud skip. Without the credential the API refuses by design, so+ # this would be a guaranteed 401 on every lookup; an operator needs to+ # see why rather than find an empty result.+ logger.warning("sandbox_tool.no_api_key", reason="AISOC_AGENTS_API_KEY is unset")+ return _could_not_check("No file-analysis credential is configured for the agent service.", digest)++ try:+ async with httpx.AsyncClient(timeout=TOOL_TIMEOUT_SECONDS) as client:+ response = await client.post(+ f"{_api_url()}/api/v1/sandbox/lookup",+ json={"sha256": digest},+ headers={"Authorization": f"Bearer {key}"},+ )+ except Exception as exc: # noqa: BLE001 - every failure becomes data for the model+ logger.warning("sandbox_tool.unreachable", error=type(exc).__name__)+ return _could_not_check(f"Could not reach the file-analysis service ({type(exc).__name__}).", digest)++ if response.status_code == 404:+ return _could_not_check("No file-analysis provider is configured for this deployment.", digest)+ if response.status_code == 403:+ return _could_not_check("Air-gapped mode permits local analysis providers only, and none is configured.", digest)+ if response.status_code >= 400:+ logger.warning("sandbox_tool.refused", status_code=response.status_code)+ return _could_not_check(f"The file-analysis service returned HTTP {response.status_code}.", digest)++ try:+ body = response.json()+ except ValueError:+ return _could_not_check("The file-analysis service returned an unreadable response.", digest)++ outcome = body.get("outcome")+ if outcome == "could_not_check":+ return _could_not_check(str(body.get("detail") or "The provider could not be reached."), digest)+ if outcome == "known":+ return {+ "available": True,+ "outcome": "known",+ "sha256": digest,+ "provider": body.get("provider"),+ # Passed through whole: fields the provider does not publish read+ # "unavailable" here rather than being absent, so the model is+ # never invited to infer one.+ "report": body.get("report"),+ "detail": body.get("detail"),+ }+ if outcome == "pending":+ return {+ "available": False,+ "outcome": "pending",+ "sha256": digest,+ "provider": body.get("provider"),+ "reason": (+ "An analysis of this file is still running, so there is no verdict yet. "+ "This is not a clean result. Continue the investigation on other evidence and "+ "say the file analysis was incomplete."+ ),+ }+ # not_seen and upload_refused both mean no provider holds a report. Said+ # plainly, because "no provider has analysed this file" is genuinely+ # different from "a provider analysed it and found nothing".+ return {+ "available": True,+ "outcome": "not_seen",+ "sha256": digest,+ "provider": body.get("provider"),+ "reason": (+ "No configured analysis provider has ever analysed this file. That is an absence of prior "+ "analysis, not a verdict: an unknown hash is common for targeted malware and says nothing "+ "either way. Uploading the file is a disclosure and is not available to this tool."+ ),+ "detail": body.get("detail"),+ }+++# The registry wraps these into its own ``Tool`` rather than this module+# importing that dataclass. The import would run tool module -> registry while+# ``default_registry`` already runs registry -> tool module, and a cycle that+# happens to work because one side defers its import is still a cycle. Keeping+# the schema here as plain data also means a tool module knows nothing about+# how tools are registered.+TOOL_NAME = "lookup_file_hash"++TOOL_DESCRIPTION = (+ "Check whether a configured malware-analysis provider has already analysed a file, by its "+ "SHA-256 hash. Returns a verdict, score, signatures and any ATT&CK techniques when a report "+ "exists. Never uploads the file. An unknown hash is not a clean verdict, and a failed lookup "+ "is not a clean verdict either: check the 'outcome' field."+)++TOOL_PARAMETERS: dict[str, Any] = {+ "type": "object",+ "properties": {+ "sha256": {+ "type": "string",+ "description": "The file's SHA-256 digest, 64 hexadecimal characters.",+ }+ },+ "required": ["sha256"],+}diff --git a/services/agents/tests/test_sandbox_tool.py b/services/agents/tests/test_sandbox_tool.pynew file mode 100644index 000000000..d35b1b0c5--- /dev/null+++ b/services/agents/tests/test_sandbox_tool.py@@ -0,0 +1,128 @@+"""The file-analysis tool cannot upload, and never hands the model a clean negative.++The wording assertions look fussy and are the point. A model that reads a+timeout as "no detections" writes a benign verdict on a file nobody analysed,+and the only thing standing between those two outcomes is the sentence this+tool returns.+"""++from __future__ import annotations++import httpx+import pytest+from app.tools.registry import default_registry+from app.tools.sandbox import TOOL_DESCRIPTION, TOOL_PARAMETERS, lookup_file_hash++DIGEST = "275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f"++pytestmark = pytest.mark.asyncio++[email protected](autouse=True)+def _credential(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("AISOC_AGENTS_API_KEY", "aisoc_test_key")+ monkeypatch.setenv("AISOC_API_URL", "http://api:8000")+++def _api(status: int, body: dict | None = None) -> httpx.MockTransport:+ return httpx.MockTransport(lambda request: httpx.Response(status, json=body or {}))+++def _patch_client(monkeypatch: pytest.MonkeyPatch, transport: httpx.MockTransport) -> None:+ real = httpx.AsyncClient++ def factory(*args: object, **kwargs: object) -> httpx.AsyncClient:+ kwargs.pop("transport", None)+ return real(transport=transport, **kwargs) # type: ignore[arg-type]++ monkeypatch.setattr(httpx, "AsyncClient", factory)+++class TestFailuresNeverReadAsClean:+ async def test_an_unreachable_api_is_could_not_check(self, monkeypatch: pytest.MonkeyPatch) -> None:+ def boom(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("refused")++ _patch_client(monkeypatch, httpx.MockTransport(boom))+ result = await lookup_file_hash(DIGEST)+ assert result["available"] is False+ assert result["outcome"] == "could_not_check"+ assert "NOT been assessed" in result["reason"]+ assert "do not treat this as evidence that the file is benign" in result["reason"].lower()++ async def test_a_server_error_is_could_not_check(self, monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_client(monkeypatch, _api(503))+ result = await lookup_file_hash(DIGEST)+ assert result["outcome"] == "could_not_check"++ async def test_air_gap_refusal_is_could_not_check_not_a_miss(self, monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_client(monkeypatch, _api(403))+ result = await lookup_file_hash(DIGEST)+ assert result["outcome"] == "could_not_check"+ assert "air-gapped" in result["reason"].lower()++ async def test_a_missing_credential_is_a_loud_skip(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("AISOC_AGENTS_API_KEY", raising=False)+ result = await lookup_file_hash(DIGEST)+ assert result["outcome"] == "could_not_check"+ assert "credential" in result["reason"]++ async def test_the_providers_own_failure_is_passed_through_as_a_failure(self, monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_client(monkeypatch, _api(200, {"outcome": "could_not_check", "provider": "capev2", "detail": "timed out"}))+ result = await lookup_file_hash(DIGEST)+ assert result["outcome"] == "could_not_check"+ assert "timed out" in result["reason"]+++class TestOrdinaryAnswers:+ async def test_a_known_hash_returns_the_report_whole(self, monkeypatch: pytest.MonkeyPatch) -> None:+ report = {"verdict": "malicious", "score": 100, "attack": "unavailable"}+ _patch_client(monkeypatch, _api(200, {"outcome": "known", "provider": "mock", "report": report, "detail": "ok"}))+ result = await lookup_file_hash(DIGEST)+ assert result["available"] is True+ assert result["outcome"] == "known"+ # Unavailable fields survive the trip rather than being stripped, so+ # the model is never invited to infer one.+ assert result["report"]["attack"] == "unavailable"++ async def test_an_unknown_hash_is_not_presented_as_a_clean_verdict(self, monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_client(monkeypatch, _api(200, {"outcome": "not_seen", "provider": "mock", "detail": "no analysis"}))+ result = await lookup_file_hash(DIGEST)+ assert result["outcome"] == "not_seen"+ assert "not a verdict" in result["reason"]+ assert "targeted malware" in result["reason"]++ async def test_a_pending_analysis_is_not_available(self, monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_client(monkeypatch, _api(200, {"outcome": "pending", "provider": "capev2"}))+ result = await lookup_file_hash(DIGEST)+ assert result["available"] is False+ assert result["outcome"] == "pending"+ assert "not a clean result" in result["reason"]++ async def test_a_non_hash_is_rejected_before_any_call(self, monkeypatch: pytest.MonkeyPatch) -> None:+ def unexpected(request: httpx.Request) -> httpx.Response:+ raise AssertionError("the tool must not call out for a malformed digest")++ _patch_client(monkeypatch, httpx.MockTransport(unexpected))+ result = await lookup_file_hash("not-a-hash")+ assert result["outcome"] == "invalid_input"+++class TestToolSurface:+ async def test_the_tool_is_registered_for_the_model(self) -> None:+ assert "lookup_file_hash" in default_registry().names()++ async def test_the_registry_advertises_no_upload_verb(self) -> None:+ """The model must have no way to cause a file to leave the deployment."""+ names = default_registry().names()+ for forbidden in ("submit_file", "upload_file", "detonate_file", "analyse_file"):+ assert forbidden not in names++ async def test_the_tool_takes_a_hash_and_nothing_else(self) -> None:+ assert list(TOOL_PARAMETERS["properties"]) == ["sha256"]+ assert TOOL_PARAMETERS["required"] == ["sha256"]++ async def test_the_description_warns_the_model_about_both_negatives(self) -> None:+ description = TOOL_DESCRIPTION.lower()+ assert "never uploads" in description+ assert "unknown hash is not a clean verdict" in descriptiondiff --git a/services/api/app/api/v1/endpoints/phishing.py b/services/api/app/api/v1/endpoints/phishing.pyindex 92606da71..1724a9377 100644--- a/services/api/app/api/v1/endpoints/phishing.py+++ b/services/api/app/api/v1/endpoints/phishing.py@@ -29,6 +29,7 @@ from app.api.v1.deps import AuthUser, DBSessionfrom app.core.airgap import AirgapViolation, enforce_airgap_for_urlfrom 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.sandbox.enrichment import enrich_file_hashlogger = logging.getLogger(__name__)@@ -48,6 +49,15 @@ class SubmitRequest(BaseModel):sender: str | None = Nonesubject: str | None = Noneurls: list[str] = Field(default_factory=list)+ attachment_hashes: list[str] = Field(+ default_factory=list,+ description=(+ "SHA-256 digests of the message's attachments. Digests only: the attachment itself is never "+ "accepted here, because this route runs unattended on submitted mail 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, which enforces the tenant's upload policy."+ ),+ )class TriageResult(BaseModel):@@ -168,6 +178,76 @@ def _heuristic_triage(content: str | None, urls: list[str]) -> TriageResult:)+async def _attachment_indicators(hashes: list[str]) -> list[dict[str, Any]]:+ """Look each attachment digest up through the sandbox provider contract.++ Hash lookup only, and never an upload: see ``attachment_hashes`` above.++ A provider that could not be reached produces an indicator saying so rather+ than nothing. The distinction matters most here, because an analyst reading+ a phishing verdict with no attachment indicator would otherwise conclude+ the attachments were checked and found clean.+ """+ indicators: list[dict[str, Any]] = []+ for digest in hashes[:10]:+ try:+ block = (await enrich_file_hash(digest)).get("file_analysis") or {}+ except Exception: # noqa: BLE001 - a sandbox outage must not fail triage+ logger.warning("phishing.attachment_lookup_failed hash=%s", str(digest)[:64].replace("\n", " "))+ indicators.append({"kind": "hash", "value": digest, "note": "attachment could not be checked: analysis provider unavailable"})+ continue+ if not block:+ continue+ for unchecked in block.get("could_not_check") or []:+ indicators.append(+ {+ "kind": "hash",+ "value": digest,+ "note": f"could not be checked by {unchecked.get('provider')}: not a clean result",+ }+ )+ for finding in block.get("findings") or []:+ indicators.append(+ {+ "kind": "hash",+ "value": digest,+ "note": f"{finding.get('provider')} verdict: {finding.get('verdict')}",+ "score": finding.get("score"),+ "attack_techniques": finding.get("attack_techniques"),+ }+ )+ return indicators+++def _merge_attachment_verdict(result: TriageResult, indicators: list[dict[str, Any]]) -> TriageResult:+ """Fold attachment findings into the triage result.++ A malicious attachment raises the verdict to ``malware`` and the confidence+ floor, because a sandbox verdict on the file itself is stronger evidence+ than any amount of keyword matching on the body. A verdict is never lowered+ here: an attachment nothing recognised says nothing about the message.+ """+ if not indicators:+ return result+ merged = [*result.indicators, *indicators]+ malicious = any("verdict: malicious" in str(i.get("note", "")) for i in indicators)+ if malicious:+ return TriageResult(+ verdict="malware",+ confidence=max(result.confidence, 0.9),+ indicators=merged,+ mitre_technique=result.mitre_technique or "T1566.001",+ summary=f"{result.summary} An attachment was identified as malicious by file analysis.".strip(),+ )+ return TriageResult(+ verdict=result.verdict,+ confidence=result.confidence,+ indicators=merged,+ mitre_technique=result.mitre_technique,+ summary=result.summary,+ )++def _row_to_submission(row: Any) -> SubmissionResponse:return SubmissionResponse(id=row.id,@@ -204,6 +284,7 @@ async def submit(body: SubmitRequest, db: DBSession, user: AuthUser) -> Submissiresult = Noneif not result:result = _heuristic_triage(body.raw_content, body.urls)+ result = _merge_attachment_verdict(result, await _attachment_indicators(body.attachment_hashes))now = datetime.now(UTC)sub_id = uuid.uuid4()@@ -298,6 +379,12 @@ async def retriage(submission_id: uuid.UUID, db: DBSession, user: AuthUser) -> Sresult = 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.+ 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))))now = datetime.now(UTC)q = text("""diff --git a/services/api/app/api/v1/endpoints/sandbox.py b/services/api/app/api/v1/endpoints/sandbox.pynew file mode 100644index 000000000..d9c92a994--- /dev/null+++ b/services/api/app/api/v1/endpoints/sandbox.py@@ -0,0 +1,290 @@+"""File and URL analysis: hash lookup, submission, polling, and the upload consent.++Every route authenticates and takes its tenant from the credential. The+provider is named in the request because a deployment may have several; the+tenant never is, because a request that could name a tenant is a request that+could name somebody else's.++Permissions follow what the action discloses rather than what it reads:++* a hash lookup and a poll need ``threat_intel:read``, which analysts hold+* enabling uploads needs ``settings:write``, which only a tenant administrator+ holds, because it is a standing agreement to disclose customer files+* submitting needs ``threat_intel:write``, and is refused anyway unless the+ standing agreement exists+"""++from __future__ import annotations++import base64+import binascii+import logging+import re+from typing import Any, Literal++from fastapi import APIRouter, HTTPException, status+from pydantic import BaseModel, Field++from app.api.v1.deps import AuthUser, DBSession+from app.services.sandbox import (+ CONSENT_TEXT_VERSION,+ SandboxResult,+ analyse_file,+ analyse_url,+ build_registry,+ consent_text_for,+ lookup_hash,+ poll,+)+from app.services.sandbox.store import list_consent, read_consent, record_decision, set_consent++logger = logging.getLogger(__name__)++router = APIRouter(prefix="/sandbox", tags=["sandbox"])++_SHA256 = re.compile(r"^[0-9a-fA-F]{64}$")+#: Matches the ingest path's own attachment ceiling. A sandbox is not a file+#: store, and an unbounded base64 body is a denial-of-service surface before it+#: is anything else.+_MAX_UPLOAD_BYTES = 32 * 1024 * 1024+++# ────────────────────────────────────────────────────────────────────────────+# Schemas+# ────────────────────────────────────────────────────────────────────────────+++class ProviderInfo(BaseModel):+ name: str+ local: bool+ usable: bool+ supports_file_submission: bool+ supports_url_submission: bool+ submissions_are_public_by_default: bool+ description: str+ uploads_enabled_for_tenant: bool+ consent_text: str+ consent_text_version: str+ #: False for every hosted provider whose authentication this repository has+ #: not confirmed against a real key. Rendered as a caveat, never as a tick.+ authentication_verified: bool+ unusable_reason: str | None = None+++class ProvidersResponse(BaseModel):+ airgapped: bool+ providers: list[ProviderInfo]+++class LookupRequest(BaseModel):+ sha256: str = Field(..., description="The file's SHA-256 digest. Nothing but the digest is sent.")+ provider: str | None = None+++class SubmitFileRequest(BaseModel):+ file_base64: str = Field(..., description="The file contents, base64-encoded.")+ file_name: str = Field(..., max_length=512)+ provider: str | None = None+ #: The caller's acknowledgement that this specific upload is intended.+ #: Tenant consent is the standing agreement; this is the per-action one,+ #: and both are required so a standing agreement cannot turn every future+ #: call into a silent upload.+ confirm_upload: bool = False+++class SubmitUrlRequest(BaseModel):+ url: str = Field(..., max_length=2048)+ provider: str | None = None+++class SandboxResultResponse(BaseModel):+ outcome: Literal["known", "pending", "not_seen", "upload_refused", "could_not_check"]+ provider: str+ detail: str+ sha256: str | None = None+ uploaded: bool = False+ report: dict[str, Any] | None = None+ handle: str | None = None+ poll_after_seconds: int | None = None+ decision: dict[str, Any] | None = None+ warnings: list[str] = Field(default_factory=list)+++class ConsentRequest(BaseModel):+ provider: str+ uploads_enabled: bool+ #: Must be the version the caller was shown. A stale console tab agreeing+ #: to superseded wording is refused rather than recorded as agreement to+ #: the current text.+ consent_text_version: str | None = None+++class ConsentResponse(BaseModel):+ provider: str+ uploads_enabled: bool+ consent_text_version: str | None = None+ consent_text: str+++# ────────────────────────────────────────────────────────────────────────────+# Helpers+# ────────────────────────────────────────────────────────────────────────────+++def _to_response(result: SandboxResult) -> SandboxResultResponse:+ return SandboxResultResponse(**result.as_dict())+++def _resolve(provider_name: str | None) -> tuple[Any, Any]:+ """Return ``(registry, provider)``, raising 4xx when the provider is unusable.++ Air-gap mode produces a 403 rather than a 404: the provider exists and is+ configured, and telling an operator it is missing would send them to add+ configuration that is already there.+ """+ registry = build_registry()+ provider = registry.get(provider_name) if provider_name else registry.default()+ if provider is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=(+ f"No analysis provider named {provider_name!r}."+ if provider_name+ else "No analysis provider is configured for this deployment."+ ),+ )+ if not registry.is_usable(provider):+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=(+ f"Air-gapped mode is on and {provider.name} runs outside this deployment. Only local analysis providers are permitted."+ ),+ )+ return registry, provider+++# ────────────────────────────────────────────────────────────────────────────+# Endpoints+# ────────────────────────────────────────────────────────────────────────────++[email protected]("/providers", response_model=ProvidersResponse, summary="Analysis providers and this tenant's upload consent")+async def providers(db: DBSession, user: AuthUser) -> ProvidersResponse:+ user.require_permission("threat_intel:read")+ registry = build_registry()+ consent = {c.provider: c.uploads_enabled for c in await list_consent(db, tenant_id=user.tenant_id)}+ out: list[ProviderInfo] = []+ for name in registry.names():+ provider = registry.get(name)+ if provider is None: # pragma: no cover - names() is derived from the same map+ continue+ caps = provider.capabilities+ usable = registry.is_usable(provider)+ out.append(+ ProviderInfo(+ name=caps.name,+ local=caps.local,+ usable=usable,+ supports_file_submission=caps.supports_file_submission,+ supports_url_submission=caps.supports_url_submission,+ submissions_are_public_by_default=caps.submissions_are_public_by_default,+ description=caps.description,+ uploads_enabled_for_tenant=consent.get(caps.name, False),+ consent_text=consent_text_for(caps),+ consent_text_version=CONSENT_TEXT_VERSION,+ authentication_verified=bool(getattr(provider, "authentication_is_verified", True)),+ unusable_reason=(None if usable else "Air-gapped mode permits local providers only."),+ )+ )+ return ProvidersResponse(airgapped=registry.airgapped, providers=out)++[email protected]("/lookup", response_model=SandboxResultResponse, summary="Look a file hash up (nothing is uploaded)")+async def lookup(body: LookupRequest, db: DBSession, user: AuthUser) -> SandboxResultResponse:+ user.require_permission("threat_intel:read")+ if not _SHA256.match(body.sha256.strip()):+ raise HTTPException(status_code=422, detail="sha256 must be a 64-character hexadecimal digest.")+ _, provider = _resolve(body.provider)+ result = await lookup_hash(provider, body.sha256.strip().lower())+ await record_decision(db, tenant_id=user.tenant_id, result=result, artifact_kind="hash", actor_id=user.user_id)+ return _to_response(result)++[email protected]("/files", response_model=SandboxResultResponse, summary="Analyse a file, uploading only if policy allows")+async def submit_file(body: SubmitFileRequest, db: DBSession, user: AuthUser) -> SandboxResultResponse:+ user.require_permission("threat_intel:write")+ try:+ content = base64.b64decode(body.file_base64, validate=True)+ except (binascii.Error, ValueError) as exc:+ raise HTTPException(status_code=422, detail="file_base64 is not valid base64.") from exc+ if not content:+ raise HTTPException(status_code=422, detail="file_base64 decoded to zero bytes.")+ if len(content) > _MAX_UPLOAD_BYTES:+ raise HTTPException(status_code=413, detail=f"File exceeds the {_MAX_UPLOAD_BYTES // (1024 * 1024)} MB analysis limit.")++ registry, provider = _resolve(body.provider)+ result = await analyse_file(+ provider,+ content=content,+ file_name=body.file_name,+ registry=registry,+ tenant_uploads_enabled=await read_consent(db, tenant_id=user.tenant_id, provider=provider.name),+ # The hash lookup always runs; only the upload half is gated on the+ # caller confirming this specific transfer.+ allow_upload=body.confirm_upload,+ )+ await record_decision(+ db,+ tenant_id=user.tenant_id,+ result=result,+ artifact_kind="file",+ file_name=body.file_name,+ actor_id=user.user_id,+ )+ return _to_response(result)++[email protected]("/urls", response_model=SandboxResultResponse, summary="Submit a URL for analysis")+async def submit_url(body: SubmitUrlRequest, db: DBSession, user: AuthUser) -> SandboxResultResponse:+ user.require_permission("threat_intel:write")+ registry, provider = _resolve(body.provider)+ result = await analyse_url(provider, body.url.strip(), registry=registry)+ await record_decision(db, tenant_id=user.tenant_id, result=result, artifact_kind="url", actor_id=user.user_id)+ return _to_response(result)++[email protected]("/analyses/{provider_name}/{handle}", response_model=SandboxResultResponse, summary="Poll an analysis")+async def get_analysis(provider_name: str, handle: str, user: AuthUser) -> SandboxResultResponse:+ user.require_permission("threat_intel:read")+ _, provider = _resolve(provider_name)+ return _to_response(await poll(provider, handle))++[email protected]("/consent", response_model=ConsentResponse, summary="Allow or refuse file uploads to a provider")+async def put_consent(body: ConsentRequest, db: DBSession, user: AuthUser) -> ConsentResponse:+ # settings:write, not threat_intel:write. This is a standing agreement to+ # disclose customer files, which is an administrator's decision rather than+ # an analyst's.+ user.require_permission("settings:write")+ _, provider = _resolve(body.provider)+ if body.uploads_enabled and body.consent_text_version not in (None, CONSENT_TEXT_VERSION):+ raise HTTPException(+ status_code=409,+ detail=(+ f"The disclosure text has changed since this page was loaded (shown {body.consent_text_version}, "+ f"current {CONSENT_TEXT_VERSION}). Reload and read the current text before enabling uploads."+ ),+ )+ record = await set_consent(+ db,+ tenant_id=user.tenant_id,+ provider=provider.name,+ enabled=body.uploads_enabled,+ actor_id=user.user_id,+ )+ return ConsentResponse(+ provider=record.provider,+ uploads_enabled=record.uploads_enabled,+ consent_text_version=record.consent_text_version,+ consent_text=consent_text_for(provider.capabilities),+ )diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex e059a3646..abc1b2d39 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -70,6 +70,7 @@ from app.api.v1.endpoints import (report_builder,reports,rule_tuning,+ sandbox,saved_hunts,saved_views,shifts,@@ -240,6 +241,11 @@ api_router.include_router(saved_hunts.router)# Email-security + phishing-triage workflow (Tier 3)api_router.include_router(phishing.router)+# File + URL analysis behind one provider contract. Hash lookup is always+# allowed; uploading a customer file is off by default, per tenant per+# provider, and air-gapped mode permits local providers only.+api_router.include_router(sandbox.router)+# Knowledge-base + RAG over org docs/runbooks (Tier 3)api_router.include_router(knowledge_base.router)diff --git a/services/api/app/services/sandbox/__init__.py b/services/api/app/services/sandbox/__init__.pynew file mode 100644index 000000000..b0511c731--- /dev/null+++ b/services/api/app/services/sandbox/__init__.py@@ -0,0 +1,72 @@+"""File and URL analysis behind one provider contract.++``types`` owns the vocabulary, ``base`` the contract, ``policy`` the decision+about whether a customer file may leave, ``service`` the hash-first sequencing+and the "could not check" rule, and ``providers/`` the adapters.+"""++from app.services.sandbox.base import SandboxProvider, guard_outbound_url+from app.services.sandbox.policy import (+ CONSENT_TEXT_VERSION,+ UploadDecision,+ UploadRefusal,+ consent_text_for,+ evaluate_upload,+)+from app.services.sandbox.registry import SandboxRegistry, build_registry+from app.services.sandbox.service import (+ SandboxOutcome,+ SandboxResult,+ analyse_file,+ analyse_url,+ lookup_hash,+ poll,+ sha256_of,+)+from app.services.sandbox.types import (+ UNAVAILABLE,+ AnalysisState,+ AttackTechnique,+ ProviderCapabilities,+ SandboxError,+ SandboxIocs,+ SandboxReport,+ SandboxUnavailable,+ SandboxVerdict,+ Signature,+ SubmissionReceipt,+ Unavailable,+ is_available,+)++__all__ = [+ "CONSENT_TEXT_VERSION",+ "UNAVAILABLE",+ "AnalysisState",+ "AttackTechnique",+ "ProviderCapabilities",+ "SandboxError",+ "SandboxIocs",+ "SandboxOutcome",+ "SandboxProvider",+ "SandboxRegistry",+ "SandboxReport",+ "SandboxResult",+ "SandboxUnavailable",+ "SandboxVerdict",+ "Signature",+ "SubmissionReceipt",+ "Unavailable",+ "UploadDecision",+ "UploadRefusal",+ "analyse_file",+ "analyse_url",+ "build_registry",+ "consent_text_for",+ "evaluate_upload",+ "guard_outbound_url",+ "is_available",+ "lookup_hash",+ "poll",+ "sha256_of",+]diff --git a/services/api/app/services/sandbox/base.py b/services/api/app/services/sandbox/base.pynew file mode 100644index 000000000..89312ed11--- /dev/null+++ b/services/api/app/services/sandbox/base.py@@ -0,0 +1,216 @@+"""The provider contract, and the outbound rules every provider obeys.++Five verbs, because five is what the callers need: look a hash up, submit a+file, submit a URL, poll, and describe yourself. Everything a provider knows+that is not one of those is its own business, and the interface never learns+it.++The asymmetry between :meth:`SandboxProvider.lookup_hash` and the two submit+verbs is the point rather than an accident. A hash lookup discloses a 32-byte+digest; a file submission discloses the file. They are separated so the upload+policy has something to sit between, and so a provider that can only do the+first is a complete implementation rather than a partial one.+"""++from __future__ import annotations++import abc+import ipaddress+import socket+from typing import Any, TypeAlias+from urllib.parse import urlsplit++from app.core.airgap import AirgapViolation, enforce_airgap_for_url+from app.services.sandbox.types import (+ AnalysisState,+ ProviderCapabilities,+ SandboxReport,+ SandboxUnavailable,+ SubmissionReceipt,+)++__all__ = ["SandboxProvider", "as_mapping", "guard_outbound_url"]+++def as_mapping(value: object) -> dict[str, Any]:+ """``value`` if it is a JSON object, otherwise an empty one.++ Every adapter reads vendor JSON, where any key may be absent or the wrong+ shape, and the obvious inline spelling+ ``payload.get(k) if isinstance(payload.get(k), dict) else {}`` calls+ ``get`` twice, so a type checker cannot narrow the first result from the+ second's test. Doing it once here narrows properly and stops seven+ near-identical expressions drifting apart.+ """+ return value if isinstance(value, dict) else {}+++#: Hosts that must never be reached whatever DNS says, matching the blocklist+#: in ``services/agents/app/playbook/ssrf_guard.py``. A sandbox provider is+#: operator-configured, and an operator who can set a base URL can point it at+#: the instance metadata service.+_METADATA_HOSTS: frozenset[str] = frozenset(+ {+ "169.254.169.254",+ "metadata.google.internal",+ "metadata",+ "metadata.azure.com",+ "100.100.100.200",+ }+)+++#: The two concrete address types, rather than ``ipaddress._BaseAddress``:+#: the private base declares none of the ``is_*`` properties this function+#: reads, so annotating with it type-checks every one of them as an error.+_IPAddress: TypeAlias = ipaddress.IPv4Address | ipaddress.IPv6Address+++def _refuse_address(ip: _IPAddress, *, allow_private: bool) -> str:+ """Empty string when ``ip`` may be contacted, otherwise the reason it may not."""+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ return _refuse_address(ip.ipv4_mapped, allow_private=allow_private)+ if ip.is_loopback and not allow_private:+ return "loopback address"+ if ip.is_link_local:+ # Never relaxed. 169.254.0.0/16 is the cloud metadata range, which is+ # the one address a local sandbox has no reason to live on.+ return "link-local address (cloud metadata range)"+ if ip.is_unspecified:+ return "unspecified address"+ if ip.is_multicast:+ return "multicast address"+ if ip.is_reserved:+ return "reserved address"+ if ip.is_private and not allow_private:+ return "private address"+ return ""+++def guard_outbound_url(url: str, *, provider: str, allow_private: bool = False) -> str:+ """Run a provider's outbound URL past the air-gap policy and an SSRF check.++ The two refuse different things, and both have to run: air-gap refuses a+ URL that leaves the deployment, and the SSRF check refuses one that points+ back into it. A self-hosted sandbox is the case where the second would fire+ and must not, so ``allow_private`` is set from the provider's own ``local``+ declaration rather than from an environment variable. Link-local stays+ refused either way, because relaxing "private" to reach a sandbox on+ ``10.0.0.0/8`` must not also open the metadata service.++ Returns the URL so a call site reads ``client.get(guard_outbound_url(...))``+ and cannot accidentally use the unchecked string.+ """+ try:+ enforce_airgap_for_url(url)+ except AirgapViolation as exc:+ raise SandboxUnavailable(provider, str(exc), kind="network") from exc++ parts = urlsplit(url.strip())+ if parts.scheme not in ("http", "https"):+ raise SandboxUnavailable(provider, f"scheme {parts.scheme or '(none)'!r} is not allowed", kind="network")+ if parts.username or parts.password:+ raise SandboxUnavailable(provider, "URL must not carry userinfo", kind="network")+ host = (parts.hostname or "").strip().lower()+ if not host:+ raise SandboxUnavailable(provider, "URL has no hostname", kind="network")+ if host in _METADATA_HOSTS:+ raise SandboxUnavailable(provider, f"host {host!r} is on the metadata blocklist", kind="network")++ try:+ literal = ipaddress.ip_address(host)+ except ValueError:+ literal = None+ if literal is not None:+ if reason := _refuse_address(literal, allow_private=allow_private):+ raise SandboxUnavailable(provider, f"host {host!r} is blocked: {reason}", kind="network")+ return url++ try:+ infos = socket.getaddrinfo(host, None, type=socket.SOCK_STREAM)+ except OSError as exc:+ raise SandboxUnavailable(provider, f"could not resolve {host!r}: {exc}", kind="network") from exc+ seen: set[str] = set()+ for info in infos:+ addr = str(info[4][0]).split("%", 1)[0]+ if not addr or addr in seen:+ continue+ seen.add(addr)+ # Every answer, not just the first: a record that mixes one public and+ # one private address would otherwise pass on whichever came back+ # first.+ if reason := _refuse_address(ipaddress.ip_address(addr), allow_private=allow_private):+ raise SandboxUnavailable(provider, f"{host!r} resolves to {addr} ({reason})", kind="network")+ if not seen:+ raise SandboxUnavailable(provider, f"{host!r} resolved to no usable address", kind="network")+ return url+++class SandboxProvider(abc.ABC):+ """A file and URL analysis backend.++ Implementations must not raise for an ordinary negative answer. A hash the+ provider has never seen is ``None`` from :meth:`lookup_hash`, and an+ analysis that has not finished is a report whose state is+ :attr:`~app.services.sandbox.types.AnalysisState.PENDING`. Raising is+ reserved for "the question could not be asked", which is+ :class:`~app.services.sandbox.types.SandboxUnavailable`, so that a caller+ can tell a negative result from a failure without reading the message.+ """++ @property+ @abc.abstractmethod+ def capabilities(self) -> ProviderCapabilities:+ """What this provider can do and where it runs."""++ @property+ def name(self) -> str:+ return self.capabilities.name++ @property+ def local(self) -> bool:+ return self.capabilities.local++ @abc.abstractmethod+ async def lookup_hash(self, sha256: str) -> SandboxReport | None:+ """Report for a file the provider has already analysed, or ``None``.++ Discloses only the digest. This is the verb the upload policy makes+ callers try first, and the only one a tenant never has to consent to.+ """++ async def submit_file(self, content: bytes, file_name: str, *, visibility: str | None = None) -> SubmissionReceipt:+ """Send a file for analysis.++ Never called without an allowed+ :class:`~app.services.sandbox.policy.UploadDecision`. A provider that+ cannot accept files leaves this alone and declares+ ``supports_file_submission=False``.+ """+ raise SandboxUnavailable(self.name, "this provider does not accept file submissions", kind="bad_response")++ async def submit_url(self, url: str) -> SubmissionReceipt:+ """Send a URL for analysis."""+ raise SandboxUnavailable(self.name, "this provider does not accept URL submissions", kind="bad_response")++ @abc.abstractmethod+ async def poll(self, handle: str) -> SandboxReport:+ """Current state of a submission, by its :class:`SubmissionReceipt` handle."""++ async def aclose(self) -> None:+ """Release any transport the provider holds. Safe to call twice.++ Concrete rather than abstract: a provider that holds no transport has+ nothing to close, and forcing every adapter to write an empty override+ would make the one that *should* have closed a client harder to spot.+ """+ return None++ @staticmethod+ def _pending(provider: str, handle: str, state: AnalysisState = AnalysisState.PENDING) -> SandboxReport:+ """A report that carries no verdict, for an analysis still in flight."""+ return SandboxReport(+ provider=provider,+ state=state,+ unavailable_reasons={"verdict": f"analysis {handle} has not finished ({state.value})"},+ )diff --git a/services/api/app/services/sandbox/enrichment.py b/services/api/app/services/sandbox/enrichment.pynew file mode 100644index 000000000..1a5fbff9d--- /dev/null+++ b/services/api/app/services/sandbox/enrichment.py@@ -0,0 +1,107 @@+"""File-hash enrichment: what a sandbox adds to an alert or a submission.++This is the hash-lookup half of the provider contract, shaped for the callers+that have a digest and want to know whether it is worth caring about. It never+uploads: enrichment runs unattended on whatever arrives, and an unattended path+that could upload is one misconfiguration away from disclosing every attachment+a tenant receives.++The output shape mirrors the enrichment service's, so a caller merging this+into an alert's ``enrichments`` does not learn a second schema. The key is+``file_analysis`` rather than a provider name, for the same reason the+interface owns the vocabulary: the reader should not have to know which sandbox+answered.+"""++from __future__ import annotations++import re+from typing import Any++from app.services.sandbox.registry import SandboxRegistry, build_registry+from app.services.sandbox.service import lookup_hash+from app.services.sandbox.types import SandboxVerdict, Unavailable, is_available++__all__ = ["enrich_file_hash", "enrich_file_hashes"]++_SHA256 = re.compile(r"^[0-9a-fA-F]{64}$")++#: Verdicts that should raise an analyst's attention. ``UNKNOWN`` is not one:+#: a provider saying "I looked and cannot tell" is not a signal.+_NOTABLE = {SandboxVerdict.MALICIOUS, SandboxVerdict.SUSPICIOUS}+++async def enrich_file_hash(sha256: str, *, registry: SandboxRegistry | None = None) -> dict[str, Any]:+ """Look one digest up across every usable provider.++ Returns ``{}`` when nothing is known, so a caller merging this into an+ alert adds nothing rather than adding an empty section. A provider that+ could not be reached is reported under ``could_not_check`` and is+ deliberately *not* folded into "no result": an alert whose file could not+ be checked and one whose file is clean must not render the same.+ """+ digest = (sha256 or "").strip().lower()+ if not _SHA256.match(digest):+ return {}+ registry = registry or build_registry()++ findings: list[dict[str, Any]] = []+ unchecked: list[dict[str, str]] = []+ for name in registry.usable_names():+ provider = registry.get(name)+ if provider is None: # pragma: no cover+ continue+ result = await lookup_hash(provider, digest)+ if result.outcome == "could_not_check":+ unchecked.append({"provider": name, "reason": result.detail})+ continue+ if result.outcome != "known" or result.report is None:+ continue+ report = result.report+ findings.append(+ {+ "provider": name,+ "verdict": report.verdict.value if is_available(report.verdict) else "unavailable",+ "score": report.score if is_available(report.score) else None,+ "signature_count": 0 if isinstance(report.signatures, Unavailable) else len(report.signatures),+ "attack_techniques": (None if isinstance(report.attack, Unavailable) else [t.technique_id for t in report.attack]),+ "report_url": report.report_url,+ "analyzed_at": report.analyzed_at.isoformat() if report.analyzed_at else None,+ "unavailable": dict(report.unavailable_reasons),+ }+ )++ if not findings and not unchecked:+ return {}++ malicious = [f for f in findings if f["verdict"] in {v.value for v in _NOTABLE}]+ scores = [f["score"] for f in findings if isinstance(f["score"], int)]+ return {+ "file_analysis": {+ "sha256": digest,+ "hit": bool(malicious),+ "findings": findings,+ # Named so it cannot be read as a zero. A caller that only checks+ # `max_score` gets None, not 0, when nothing published one.+ "max_score": max(scores) if scores else None,+ "could_not_check": unchecked,+ }+ }+++async def enrich_file_hashes(hashes: list[str], *, registry: SandboxRegistry | None = None, limit: int = 10) -> dict[str, Any]:+ """Enrich several digests, capped so one alert cannot fan out unboundedly."""+ registry = registry or build_registry()+ seen: list[str] = []+ for value in hashes:+ digest = (value or "").strip().lower()+ if _SHA256.match(digest) and digest not in seen:+ seen.append(digest)+ if len(seen) >= limit:+ break+ merged: list[dict[str, Any]] = []+ for digest in seen:+ block = (await enrich_file_hash(digest, registry=registry)).get("file_analysis")+ if block:+ merged.append(block)+ return {"file_analysis": merged} if merged else {}diff --git a/services/api/app/services/sandbox/policy.py b/services/api/app/services/sandbox/policy.pynew file mode 100644index 000000000..f9e1e21d9--- /dev/null+++ b/services/api/app/services/sandbox/policy.py@@ -0,0 +1,187 @@+"""When a customer file may leave the deployment, and what the operator agreed to.++Uploading a customer file to a third party is a disclosure. Not a lookup with a+side effect, not a cache miss: the file leaves, and for at least one provider+in this tree it then becomes readable by anyone. So the decision is modelled as+a decision, with four refusals that are checked in a fixed order and an audit+row written whichever way it goes.++The order is load-bearing:++1. **Air-gap.** A deployment that declares itself air-gapped may use local+ providers only. Checked first because no amount of tenant consent overrides+ it, and because the answer does not depend on the tenant.+2. **Can the provider even take it.** A provider that accepts no uploads is a+ refusal with a different meaning from a policy refusal, and conflating them+ would have an operator hunting for a consent screen that would not help.+3. **Hash first.** A digest discloses nothing, so it is always tried, and a hit+ means the upload is unnecessary rather than forbidden. This is the case the+ plan puts first and it is also the common one.+4. **Tenant consent.** Off by default, per tenant *and* per provider, recorded+ with who agreed and to what text.++Per tenant per provider, not per tenant+---------------------------------------+Consent is about where the file goes. An operator who is content to send a+sample to a sandbox they run in their own rack has agreed to nothing about a+hosted service, and a single per-tenant flag would treat those as the same+question. The pair ``(tenant, provider)`` is the key for that reason.++Consent text is versioned+-------------------------+:data:`CONSENT_TEXT_VERSION` travels onto the row. If the disclosure changes,+what a tenant previously agreed to did not, and a stored boolean with no record+of the sentence behind it cannot tell anyone which one it was.+"""++from __future__ import annotations++import enum+from dataclasses import dataclass++from app.services.sandbox.types import ProviderCapabilities++__all__ = [+ "CONSENT_TEXT_VERSION",+ "UploadDecision",+ "UploadRefusal",+ "consent_text_for",+ "evaluate_upload",+]++#: Bump when any wording in :func:`consent_text_for` changes. Stored on every+#: consent row so an audit can say which text was agreed to.+CONSENT_TEXT_VERSION = "2026-09-26.1"+++class UploadRefusal(str, enum.Enum):+ """Why an upload was refused. The console renders a different remedy for each."""++ AIRGAPPED = "airgapped"+ PROVIDER_CANNOT_UPLOAD = "provider_cannot_upload"+ ALREADY_KNOWN = "already_known"+ TENANT_NOT_CONSENTED = "tenant_not_consented"+++@dataclass(frozen=True, slots=True)+class UploadDecision:+ """The answer, and enough of the reasoning to log and to render.++ ``allowed`` is never ``True`` by omission: every construction site sets it+ explicitly, and the only place it becomes ``True`` is :func:`evaluate_upload`+ after all four checks have passed.+ """++ allowed: bool+ reason: str+ refusal: UploadRefusal | None = None+ provider: str = ""+ #: Set when the decision was reached because a hash lookup already+ #: answered the question. Carries the disclosure count to zero.+ satisfied_by_hash_lookup: bool = False++ def as_dict(self) -> dict[str, object]:+ return {+ "allowed": self.allowed,+ "reason": self.reason,+ "refusal": self.refusal.value if self.refusal else None,+ "provider": self.provider,+ "satisfied_by_hash_lookup": self.satisfied_by_hash_lookup,+ }+++def consent_text_for(capabilities: ProviderCapabilities) -> str:+ """The sentence an operator has to agree to before files go to this provider.++ Written to be read by the person clicking it, which means saying what+ happens rather than naming a policy. The first commercial adapter in this+ tree returns ``visibility: "public"`` and ``tlp: "clear"`` on a stored+ report, so for a provider that declares+ ``submissions_are_public_by_default`` the text says *public* in those+ words. "Shared with the vendor" would be true and would also be the wrong+ impression.+ """+ lines = [+ f"Enabling uploads lets AiSOC send files from this tenant to {capabilities.name} for analysis.",+ "A file may contain customer data, credentials, personal data or intellectual property. "+ "AiSOC cannot inspect a file to decide whether it does.",+ ]+ if capabilities.submissions_are_public_by_default:+ lines.append(+ f"{capabilities.name} publishes submitted samples by default: an uploaded file and its report become "+ "readable by anyone on the internet, not only by the vendor. Treat every upload as a public disclosure "+ "that cannot be recalled."+ )+ elif not capabilities.local:+ lines.append(+ f"{capabilities.name} runs outside this deployment. An uploaded file leaves your infrastructure and is "+ "retained under that vendor's terms."+ )+ else:+ lines.append(+ f"{capabilities.name} runs inside your own network, so an uploaded file does not leave your "+ "infrastructure. It is still written to that system's storage."+ )+ lines.append(+ "AiSOC always looks a file's SHA-256 up first and only uploads when the provider has not seen it. "+ "Every upload and every refusal is recorded against this tenant."+ )+ return " ".join(lines)+++def evaluate_upload(+ *,+ capabilities: ProviderCapabilities,+ airgapped: bool,+ tenant_uploads_enabled: bool,+ hash_already_known: bool,+) -> UploadDecision:+ """Decide whether one file may be sent to one provider for one tenant.++ Pure, and takes the tenant's setting as an argument rather than reading it,+ so the gate and the tests can drive every combination without a database.+ The caller is responsible for having *done* the hash lookup: passing+ ``hash_already_known=False`` without having looked is how the hash-first+ rule would get skipped, which is why the route helper in+ :mod:`app.services.sandbox.service` owns both steps rather than exposing+ them separately.+ """+ provider = capabilities.name++ if airgapped and not capabilities.local:+ return UploadDecision(+ allowed=False,+ reason=(f"Air-gapped mode is on and {provider} runs outside this deployment. Only local analysis providers are permitted."),+ refusal=UploadRefusal.AIRGAPPED,+ provider=provider,+ )++ if not capabilities.supports_file_submission:+ return UploadDecision(+ allowed=False,+ reason=f"{provider} does not accept file submissions; it can only answer hash lookups.",+ refusal=UploadRefusal.PROVIDER_CANNOT_UPLOAD,+ provider=provider,+ )++ if hash_already_known:+ return UploadDecision(+ allowed=False,+ reason=f"{provider} has already analysed this file. The existing report was used and nothing was uploaded.",+ refusal=UploadRefusal.ALREADY_KNOWN,+ provider=provider,+ satisfied_by_hash_lookup=True,+ )++ if not tenant_uploads_enabled:+ return UploadDecision(+ allowed=False,+ reason=(+ f"Uploading files to {provider} is disabled for this tenant. An administrator must enable it in "+ "Settings, which records who agreed to the disclosure."+ ),+ refusal=UploadRefusal.TENANT_NOT_CONSENTED,+ provider=provider,+ )++ return UploadDecision(allowed=True, reason=f"Tenant policy permits uploads to {provider}.", provider=provider)diff --git a/services/api/app/services/sandbox/providers/__init__.py b/services/api/app/services/sandbox/providers/__init__.pynew file mode 100644index 000000000..14247c64e--- /dev/null+++ b/services/api/app/services/sandbox/providers/__init__.py@@ -0,0 +1,13 @@+"""Adapters. One open-source reference, one mock, one commercial.++Adding a fourth means implementing+:class:`~app.services.sandbox.base.SandboxProvider` and registering it in+:mod:`app.services.sandbox.registry`. Nothing outside this package should+learn the new provider's name.+"""++from app.services.sandbox.providers.capev2 import CapeV2Provider+from app.services.sandbox.providers.malwareanalyzer import MalwareAnalyzerProvider+from app.services.sandbox.providers.mock import MockSandboxProvider++__all__ = ["CapeV2Provider", "MalwareAnalyzerProvider", "MockSandboxProvider"]diff --git a/services/api/app/services/sandbox/providers/capev2.py b/services/api/app/services/sandbox/providers/capev2.pynew file mode 100644index 000000000..9009b0f73--- /dev/null+++ b/services/api/app/services/sandbox/providers/capev2.py@@ -0,0 +1,336 @@+"""CAPEv2, the open-source reference provider.++Why this one is the reference+-----------------------------+It is open source, it is the sandbox an operator can actually stand up next to+AiSOC, and because it runs on the operator's own network it is the provider+that stays usable in air-gapped mode. It is also the useful shape to write the+interface against first: CAPE publishes a ``malscore`` on a 0-10 scale and no+verdict string at all, which forces the interface to own both the range and the+word rather than adopting whichever provider was wired first.++What is mapped, and what is derived+-----------------------------------+``malscore`` is multiplied by 10 into the interface's 0-100 score. The verdict+is *derived*, because CAPE does not publish one: at or above 7.0 malicious, at+or above 3.0 suspicious, above 0 unknown, and exactly 0 benign. Those numbers+are a judgement this adapter makes and they are stated here, on the API+response and in the operator documentation, rather than presented as CAPE's+own opinion.++Verification status+-------------------+Written against the documented CAPEv2 REST API and exercised in CI against+recorded, synthetic payloads. **Not verified against a live CAPEv2 instance**+by anyone in this repository. The docs page says the same thing. An operator+who runs it against a real deployment and finds a mismatch is fixing a real+defect, not a hypothetical one.+"""++from __future__ import annotations++from datetime import UTC, datetime+from typing import Any++import httpx++from app.services.sandbox.base import SandboxProvider, as_mapping, guard_outbound_url+from app.services.sandbox.types import (+ UNAVAILABLE,+ AnalysisState,+ AttackTechnique,+ ProviderCapabilities,+ SandboxIocs,+ SandboxReport,+ SandboxUnavailable,+ SandboxVerdict,+ Signature,+ SubmissionReceipt,+)++__all__ = ["CapeV2Provider"]++#: CAPE task states that mean the analysis is finished and a report exists.+_DONE = frozenset({"reported"})+#: States that mean it is still going. Anything unrecognised is treated as+#: running rather than failed: a new CAPE release adding a state must not turn+#: a healthy analysis into a reported failure.+_FAILED = frozenset({"failed_analysis", "failed_processing", "failed_reporting", "banned"})++_MALICIOUS_AT = 7.0+_SUSPICIOUS_AT = 3.0+++class CapeV2Provider(SandboxProvider):+ """Adapter for a self-hosted CAPEv2 instance."""++ def __init__(+ self,+ base_url: str,+ *,+ api_token: str | None = None,+ timeout_seconds: float = 20.0,+ client: httpx.AsyncClient | None = None,+ ) -> None:+ self._base = base_url.rstrip("/")+ self._token = (api_token or "").strip()+ self._timeout = timeout_seconds+ self._client = client+ self._owns_client = client is None++ @property+ def capabilities(self) -> ProviderCapabilities:+ return ProviderCapabilities(+ name="capev2",+ local=True,+ supports_hash_lookup=True,+ supports_file_submission=True,+ supports_url_submission=True,+ submissions_are_public_by_default=False,+ description="Self-hosted CAPEv2 sandbox. Runs on the operator's own network, so it stays usable air-gapped.",+ )++ # ---------------------------------------------------------------- transport++ def _headers(self) -> dict[str, str]:+ # CAPEv2 documents `Authorization: Token <apitoken>` when token auth is+ # enabled, and no header at all when it is not. Sending an empty token+ # would turn an open instance into a 401, so the header is omitted+ # rather than sent blank.+ return {"Authorization": f"Token {self._token}"} if self._token else {}++ async def _get_client(self) -> httpx.AsyncClient:+ if self._client is None:+ self._client = httpx.AsyncClient(timeout=self._timeout)+ return self._client++ async def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:+ url = guard_outbound_url(f"{self._base}{path}", provider="capev2", allow_private=True)+ client = await self._get_client()+ try:+ return await client.request(method, url, headers=self._headers(), **kwargs)+ except httpx.HTTPError as exc:+ raise SandboxUnavailable("capev2", f"{method} {path} failed: {exc}", kind="network") from exc++ async def aclose(self) -> None:+ if self._client is not None and self._owns_client:+ await self._client.aclose()+ self._client = None++ # ------------------------------------------------------------------- verbs++ async def lookup_hash(self, sha256: str) -> SandboxReport | None:+ digest = (sha256 or "").strip().lower()+ resp = await self._request("GET", f"/apiv2/tasks/search/sha256/{digest}/")+ if resp.status_code == 404:+ return None+ if resp.status_code == 401 or resp.status_code == 403:+ raise SandboxUnavailable("capev2", f"authentication refused (HTTP {resp.status_code})", kind="auth")+ if resp.status_code >= 400:+ raise SandboxUnavailable("capev2", f"hash search returned HTTP {resp.status_code}", kind="bad_response")+ body = _json(resp, "hash search")+ # CAPE answers a miss with `error: true` and a 200, so the status code+ # alone does not separate hit from miss.+ if body.get("error"):+ return None+ tasks = body.get("data") or []+ if not isinstance(tasks, list) or not tasks:+ return None+ task_id = tasks[0].get("id") if isinstance(tasks[0], dict) else None+ if task_id is None:+ return None+ return await self.poll(str(task_id))++ async def submit_file(self, content: bytes, file_name: str, *, visibility: str | None = None) -> SubmissionReceipt:+ resp = await self._request(+ "POST",+ "/apiv2/tasks/create/file/",+ files={"file": (file_name, content, "application/octet-stream")},+ )+ return self._receipt(resp, "file submission")++ async def submit_url(self, url: str) -> SubmissionReceipt:+ resp = await self._request("POST", "/apiv2/tasks/create/url/", data={"url": url})+ return self._receipt(resp, "URL submission")++ def _receipt(self, resp: httpx.Response, what: str) -> SubmissionReceipt:+ if resp.status_code >= 400:+ raise SandboxUnavailable("capev2", f"{what} returned HTTP {resp.status_code}", kind="bad_response")+ body = _json(resp, what)+ data = body.get("data") or {}+ task_id = data.get("task_ids", [None])[0] if isinstance(data.get("task_ids"), list) else data.get("task_id")+ if task_id is None:+ raise SandboxUnavailable("capev2", f"{what} returned no task id", kind="bad_response")+ return SubmissionReceipt(+ provider="capev2",+ handle=str(task_id),+ state=AnalysisState.PENDING,+ visibility="private",+ poll_after_seconds=30,+ submitted_at=datetime.now(UTC),+ )++ async def poll(self, handle: str) -> SandboxReport:+ resp = await self._request("GET", f"/apiv2/tasks/view/{handle}/")+ if resp.status_code == 404:+ return SandboxReport(+ provider="capev2",+ state=AnalysisState.NOT_FOUND,+ unavailable_reasons={"verdict": f"CAPEv2 has no task {handle}"},+ )+ if resp.status_code >= 400:+ raise SandboxUnavailable("capev2", f"task view returned HTTP {resp.status_code}", kind="bad_response")+ task = (_json(resp, "task view").get("data") or {}).get("task") or {}+ status = str(task.get("status") or "").lower()+ if status in _FAILED:+ return SandboxReport(+ provider="capev2",+ state=AnalysisState.FAILED,+ unavailable_reasons={"verdict": f"CAPEv2 analysis {handle} ended in state {status!r}"},+ )+ if status not in _DONE:+ return self._pending("capev2", handle, AnalysisState.RUNNING if status else AnalysisState.PENDING)++ report_resp = await self._request("GET", f"/apiv2/tasks/get/report/{handle}/json/")+ if report_resp.status_code >= 400:+ raise SandboxUnavailable("capev2", f"report fetch returned HTTP {report_resp.status_code}", kind="bad_response")+ return self.to_report(_json(report_resp, "report"), handle=handle)++ # ------------------------------------------------------------------ mapping++ @staticmethod+ def to_report(payload: dict[str, Any], *, handle: str = "") -> SandboxReport:+ """Map a CAPEv2 JSON report onto the interface. Pure, so tests can drive it."""+ info = as_mapping(payload.get("info"))+ target_file = as_mapping(as_mapping(payload.get("target")).get("file"))++ malscore = payload.get("malscore")+ score: Any = UNAVAILABLE+ verdict: Any = UNAVAILABLE+ reasons: dict[str, str] = {}+ if isinstance(malscore, (int, float)):+ value = float(malscore)+ score = max(0, min(100, round(value * 10)))+ if value >= _MALICIOUS_AT:+ verdict = SandboxVerdict.MALICIOUS+ elif value >= _SUSPICIOUS_AT:+ verdict = SandboxVerdict.SUSPICIOUS+ elif value > 0:+ verdict = SandboxVerdict.UNKNOWN+ else:+ verdict = SandboxVerdict.BENIGN+ else:+ reasons["score"] = "CAPEv2 report carried no malscore"+ reasons["verdict"] = "CAPEv2 publishes no verdict and this report carried no malscore to derive one from"++ signatures: list[Signature] = []+ techniques: dict[str, AttackTechnique] = {}+ raw_signatures = payload.get("signatures")+ if isinstance(raw_signatures, list):+ for sig in raw_signatures:+ if not isinstance(sig, dict):+ continue+ signatures.append(+ Signature(+ identifier=str(sig.get("name") or "").strip() or "unnamed",+ source="capev2",+ description=str(sig.get("description") or "").strip(),+ severity=str(sig.get("severity")) if sig.get("severity") is not None else None,+ confidence=_confidence(sig.get("confidence")),+ )+ )+ for tid in _technique_ids(sig):+ techniques.setdefault(tid, AttackTechnique(technique_id=tid))+ else:+ reasons["signatures"] = "CAPEv2 report carried no signatures array"++ for tid in _technique_ids(payload):+ techniques.setdefault(tid, AttackTechnique(technique_id=tid))++ network = payload.get("network") if isinstance(payload.get("network"), dict) else None+ if network is None:+ iocs = SandboxIocs()+ reasons["iocs"] = "CAPEv2 report carried no network section"+ else:+ iocs = SandboxIocs(+ urls=tuple(_strings(network.get("http"), "uri")),+ domains=tuple(_strings(network.get("domains"), "domain")),+ ipv4=tuple(_strings(network.get("hosts"), "ip")),+ )++ analyzed_at = _parse_time(info.get("ended") or info.get("started"))+ return SandboxReport(+ provider="capev2",+ state=AnalysisState.COMPLETED,+ verdict=verdict,+ score=score,+ signatures=tuple(signatures) if isinstance(raw_signatures, list) else UNAVAILABLE,+ iocs=iocs,+ # An empty tuple here is a real answer: CAPE ran the behavioural+ # stage and mapped no techniques. That differs from the commercial+ # adapter, where an absent behavioural stage makes it unavailable.+ attack=tuple(techniques.values()),+ sha256=str(target_file.get("sha256") or "") or None,+ file_name=str(target_file.get("name") or "") or None,+ file_type=str(target_file.get("type") or "") or None,+ report_url=None,+ visibility="private",+ analyzed_at=analyzed_at,+ unavailable_reasons=reasons,+ )+++def _json(resp: httpx.Response, what: str) -> dict[str, Any]:+ try:+ body = resp.json()+ except ValueError as exc:+ raise SandboxUnavailable("capev2", f"{what} returned a non-JSON body", kind="bad_response") from exc+ return body if isinstance(body, dict) else {}+++def _confidence(value: Any) -> float | None:+ """CAPE reports confidence as a percentage; the interface uses 0-1."""+ if not isinstance(value, (int, float)):+ return None+ return round(float(value) / 100.0, 3) if value > 1 else float(value)+++def _technique_ids(container: Any) -> list[str]:+ """Pull ATT&CK ids out of the several shapes CAPE has used for them."""+ found: list[str] = []+ if not isinstance(container, dict):+ return found+ for key in ("ttp", "ttps", "attack_id", "attack"):+ raw = container.get(key)+ if isinstance(raw, str):+ found.append(raw)+ elif isinstance(raw, list):+ for item in raw:+ if isinstance(item, str):+ found.append(item)+ elif isinstance(item, dict):+ found.extend(str(v) for v in (item.get("ttp"), item.get("id")) if isinstance(v, str))+ elif isinstance(raw, dict):+ found.extend(str(k) for k in raw)+ return [t.strip().upper() for t in found if t and t.strip().upper().startswith("T")]+++def _strings(container: Any, key: str) -> list[str]:+ if not isinstance(container, list):+ return []+ out: list[str] = []+ for item in container:+ value = item.get(key) if isinstance(item, dict) else item+ if isinstance(value, str) and value.strip():+ out.append(value.strip())+ return sorted(set(out))+++def _parse_time(value: Any) -> datetime | None:+ if not isinstance(value, str) or not value.strip():+ return None+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)diff --git a/services/api/app/services/sandbox/providers/malwareanalyzer.py b/services/api/app/services/sandbox/providers/malwareanalyzer.pynew file mode 100644index 000000000..7dea0c260--- /dev/null+++ b/services/api/app/services/sandbox/providers/malwareanalyzer.py@@ -0,0 +1,478 @@+"""MalwareAnalyzer, the first commercial adapter behind the provider contract.++What was characterised, and how+-------------------------------+Against the live service at ``https://malwareanalyzer.com``, using hash lookups+and unauthenticated GETs only. **No file was uploaded to build this adapter.**+The EICAR test file's SHA-256 was used because it is published for exactly this+purpose and the service already holds it.++Confirmed by request:++``POST /v1/submit``+ JSON, exactly one of ``fileBase64`` (with ``fileName``), ``url``, ``hash``+ or ``uploadKey``. An empty body is ``400 bad_request`` naming those four.+ A known hash is ``200`` with ``{state: "completed", contentHash, existing:+ true, reportUrl}``; an unknown one is ``404 not_found``. Unknown JSON+ properties are ignored silently rather than rejected.+``GET /v1/reports/<sha256>``+ ``200`` with the full JSON report, ``404 not_found`` otherwise. This is+ the richest read and the one this adapter uses for a hash lookup, because+ ``/v1/submit`` returns only a stub plus an HTML ``reportUrl``.+``GET /v1/reputation/<indicator>``+ ``200`` ``{known: true, verdict, score, family, tags, firstSeen, lastSeen,+ prevalence}`` or ``404`` ``{known: false, verdict: "unknown"}``. Cheaper+ than the full report and used when only a judgement is wanted.+``GET /v1/result/<scanUuid>``+ The poll. **The progress state is at ``data.status``**; the submit+ response's ``state`` field does not appear here, and a poll loop reading+ ``state`` reports nothing while the scan runs normally. There is also a+ ``data.partial`` boolean. A content hash is not accepted here: that is+ ``404 Scan not found``.++Errors are ``{"error": {"code", "message"}}``. There is no OpenAPI document:+``/openapi.json``, ``/swagger.json`` and ``/docs/json`` all return the+single-page app's HTML.++Visibility, which drives the upload policy+------------------------------------------+The stored report for a sample submitted anonymously carries ``visibility:+"public"``, ``tlp: "clear"`` and ``submitter: "anonymous"``. TLP:CLEAR is the+Traffic Light Protocol's unrestricted level, so this is not a vendor-internal+default: a submitted sample is readable by anyone.++The service's own web client sends ``visibility`` on ``/v1/submit`` and offers+``public`` / ``private``, but it pins ``visibility: "public"`` and disables the+control whenever there is no access token. So the best available reading is+that ``private`` needs an authenticated account, and this adapter therefore+**requests** the operator's chosen visibility while assuming nothing about+whether it is honoured. :attr:`capabilities.submissions_are_public_by_default`+stays ``True`` unless an operator has both configured a key and recorded that+they confirmed private submissions work, because the consent text an operator+reads must describe the outcome they will actually get.++Authentication, which is undetermined+-------------------------------------+The service's published copy says "No API key required", and every call this+adapter makes works without one. There is an authenticated surface+(``GET /v1/vault/samples`` answers ``401 unauthorized``), and the web client+sends ``authorization: Bearer <token>``, but a bogus ``Bearer`` and a bogus+``x-api-key`` produce byte-identical ``401``s, and the CORS preflight reflects+any header asked for, so neither confirms the scheme for a *minted API key*.++So: the header name is configurable, it defaults to ``Authorization`` with a+``Bearer`` prefix because that is what the vendor's own client sends, and the+whole auth path is marked unverified in the docs. No key is required and none+is invented.+"""++from __future__ import annotations++import base64+import os+from datetime import UTC, datetime+from typing import Any++import httpx++from app.services.sandbox.base import SandboxProvider, as_mapping, guard_outbound_url+from app.services.sandbox.types import (+ UNAVAILABLE,+ AnalysisState,+ AttackTechnique,+ ProviderCapabilities,+ SandboxIocs,+ SandboxReport,+ SandboxUnavailable,+ SandboxVerdict,+ Signature,+ SubmissionReceipt,+)++__all__ = ["DEFAULT_BASE_URL", "MalwareAnalyzerProvider"]++DEFAULT_BASE_URL = "https://malwareanalyzer.com"++#: ``data.status`` values that mean the analysis is finished.+_DONE = frozenset({"completed", "complete", "done", "finished", "reported"})+_FAILED = frozenset({"failed", "error", "cancelled", "canceled", "rejected"})++_VERDICTS = {+ "malicious": SandboxVerdict.MALICIOUS,+ "suspicious": SandboxVerdict.SUSPICIOUS,+ "benign": SandboxVerdict.BENIGN,+ "clean": SandboxVerdict.BENIGN,+ "harmless": SandboxVerdict.BENIGN,+ "unknown": SandboxVerdict.UNKNOWN,+ "undetected": SandboxVerdict.UNKNOWN,+}++#: The service's IOC bucket names, mapped onto the interface's.+_IOC_KEYS: tuple[tuple[str, str], ...] = (+ ("urls", "urls"),+ ("domains", "domains"),+ ("ipv4", "ipv4"),+ ("ipv6", "ipv6"),+ ("emails", "emails"),+ ("filePaths", "file_paths"),+ ("registryKeys", "registry_keys"),+ ("mutexes", "mutexes"),+ ("cve", "cves"),+)+++class MalwareAnalyzerProvider(SandboxProvider):+ """Adapter for the hosted MalwareAnalyzer service.++ ``api_key`` and ``api_key_header`` are both optional and both default from+ the environment. Supplying a key is supported because the maintainer asked+ for it; nothing requires one, and no call is withheld when there is none.+ """++ def __init__(+ self,+ *,+ base_url: str | None = None,+ api_key: str | None = None,+ api_key_header: str | None = None,+ api_key_prefix: str | None = None,+ private_submissions_confirmed: bool | None = None,+ timeout_seconds: float = 30.0,+ client: httpx.AsyncClient | None = None,+ ) -> None:+ self._base = (base_url or os.getenv("MALWAREANALYZER_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")+ self._key = (api_key if api_key is not None else os.getenv("MALWAREANALYZER_API_KEY") or "").strip()+ self._key_header = (api_key_header or os.getenv("MALWAREANALYZER_API_KEY_HEADER") or "Authorization").strip()+ # Separate from the header name because the two vary independently: a+ # key sent as `X-Api-Key` carries no prefix, one sent as+ # `Authorization` carries `Bearer `. An operator who learns the real+ # scheme configures both without a code change.+ prefix = api_key_prefix if api_key_prefix is not None else os.getenv("MALWAREANALYZER_API_KEY_PREFIX")+ self._key_prefix = ("Bearer " if self._key_header.lower() == "authorization" else "") if prefix is None else prefix+ self._private_confirmed = (+ private_submissions_confirmed+ if private_submissions_confirmed is not None+ else _env_flag("MALWAREANALYZER_PRIVATE_SUBMISSIONS_CONFIRMED")+ )+ self._timeout = timeout_seconds+ self._client = client+ self._owns_client = client is None++ @property+ def capabilities(self) -> ProviderCapabilities:+ return ProviderCapabilities(+ name="malwareanalyzer",+ local=False,+ supports_hash_lookup=True,+ supports_file_submission=True,+ supports_url_submission=True,+ # Public unless an operator has *confirmed* private submissions+ # work for their account. Reading this as "private because a key+ # is set" would let an unverified assumption rewrite the consent+ # text an operator agrees to before disclosing a customer file.+ submissions_are_public_by_default=not (bool(self._key) and self._private_confirmed),+ description=(+ "Hosted file and URL analysis service. Submitted samples are published by default (visibility: public, TLP:CLEAR)."+ ),+ )++ @property+ def authentication_is_verified(self) -> bool:+ """False always, today.++ Exposed rather than hidden so the settings surface can say "unverified"+ instead of showing an operator a green tick this repository cannot+ earn. It flips when someone confirms a real key against the service and+ changes this, not when a key is merely present.+ """+ return False++ # ---------------------------------------------------------------- transport++ def _headers(self) -> dict[str, str]:+ headers = {"accept": "application/json"}+ if self._key:+ headers[self._key_header] = f"{self._key_prefix}{self._key}"+ return headers++ async def _get_client(self) -> httpx.AsyncClient:+ if self._client is None:+ self._client = httpx.AsyncClient(timeout=self._timeout)+ return self._client++ async def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:+ url = guard_outbound_url(f"{self._base}{path}", provider="malwareanalyzer")+ client = await self._get_client()+ try:+ return await client.request(method, url, headers=self._headers(), **kwargs)+ except httpx.HTTPError as exc:+ raise SandboxUnavailable("malwareanalyzer", f"{method} {path} failed: {exc}", kind="network") from exc++ async def aclose(self) -> None:+ if self._client is not None and self._owns_client:+ await self._client.aclose()+ self._client = None++ def _raise_for_error(self, resp: httpx.Response, what: str) -> dict[str, Any]:+ try:+ body = resp.json()+ except ValueError as exc:+ raise SandboxUnavailable("malwareanalyzer", f"{what} returned a non-JSON body", kind="bad_response") from exc+ if not isinstance(body, dict):+ raise SandboxUnavailable("malwareanalyzer", f"{what} returned {type(body).__name__}, expected an object", kind="bad_response")+ if resp.status_code in (401, 403):+ raise SandboxUnavailable("malwareanalyzer", f"{what}: authentication refused (HTTP {resp.status_code})", kind="auth")+ if resp.status_code == 429:+ raise SandboxUnavailable("malwareanalyzer", f"{what}: rate limited", kind="rate_limit")+ if resp.status_code >= 400:+ message = as_mapping(body.get("error")).get("message")+ raise SandboxUnavailable("malwareanalyzer", f"{what}: HTTP {resp.status_code} {message or ''}".strip(), kind="bad_response")+ return body++ # ------------------------------------------------------------------- verbs++ async def lookup_hash(self, sha256: str) -> SandboxReport | None:+ digest = (sha256 or "").strip().lower()+ if not digest:+ return None+ resp = await self._request("GET", f"/v1/reports/{digest}")+ if resp.status_code == 404:+ # `not_found` here means the service has never analysed this file.+ # A normal answer, not a failure, so None rather than an exception.+ return None+ return self.to_report(self._raise_for_error(resp, "report lookup"))++ async def submit_file(self, content: bytes, file_name: str, *, visibility: str | None = None) -> SubmissionReceipt:+ # Base64 in JSON, not multipart: the service documents that shape and+ # rejects a body carrying none of its four accepted keys.+ payload: dict[str, Any] = {+ "fileBase64": base64.b64encode(content).decode("ascii"),+ "fileName": file_name,+ }+ if visibility:+ payload["visibility"] = visibility+ return self._receipt(await self._request("POST", "/v1/submit", json=payload), "file submission", visibility)++ async def submit_url(self, url: str) -> SubmissionReceipt:+ return self._receipt(await self._request("POST", "/v1/submit", json={"url": url}), "URL submission", None)++ def _receipt(self, resp: httpx.Response, what: str, visibility: str | None) -> SubmissionReceipt:+ body = self._raise_for_error(resp, what)+ handle = body.get("scanUuid") or body.get("taskId")+ if not handle:+ raise SandboxUnavailable("malwareanalyzer", f"{what} returned neither scanUuid nor taskId", kind="bad_response")+ return SubmissionReceipt(+ provider="malwareanalyzer",+ handle=str(handle),+ state=_state(body.get("state")),+ # What was *asked for*, recorded so the audit row says what the+ # operator requested even if the service silently publishes it.+ visibility=visibility or "public",+ poll_after_seconds=15,+ submitted_at=datetime.now(UTC),+ )++ async def poll(self, handle: str) -> SandboxReport:+ resp = await self._request("GET", f"/v1/result/{handle}")+ if resp.status_code == 404:+ return SandboxReport(+ provider="malwareanalyzer",+ state=AnalysisState.NOT_FOUND,+ unavailable_reasons={"verdict": f"no analysis with handle {handle}"},+ )+ body = self._raise_for_error(resp, "poll")+ data = as_mapping(body.get("data")) or body+ # The progress state is `data.status`. The submit response's `state`+ # does not appear on this route, and reading it here reports nothing+ # while a scan runs normally.+ state = _state(data.get("status"))+ if data.get("partial") is True:+ # `partial` outranks the status. A response that says `completed`+ # while still flagged partial is a report that will keep changing,+ # and publishing its verdict now means publishing a verdict that+ # may be revised.+ return self._pending("malwareanalyzer", handle, AnalysisState.RUNNING)+ if not state.terminal:+ return self._pending("malwareanalyzer", handle, state)+ if state is AnalysisState.FAILED:+ return SandboxReport(+ provider="malwareanalyzer",+ state=AnalysisState.FAILED,+ unavailable_reasons={"verdict": f"analysis {handle} reported status {data.get('status')!r}"},+ )+ return self.to_report(data)++ # ------------------------------------------------------------------ mapping++ @staticmethod+ def to_report(payload: dict[str, Any]) -> SandboxReport:+ """Map a MalwareAnalyzer report onto the interface. Pure, so tests can drive it."""+ verdict_block = as_mapping(payload.get("verdict"))+ reasons: dict[str, str] = {}++ raw_verdict = str(verdict_block.get("verdict") or "").strip().lower()+ verdict: Any = _VERDICTS.get(raw_verdict, UNAVAILABLE)+ if not raw_verdict:+ reasons["verdict"] = "report carried no verdict"+ elif verdict is UNAVAILABLE:+ reasons["verdict"] = f"report carried an unrecognised verdict {raw_verdict!r}"++ raw_score = verdict_block.get("score")+ if isinstance(raw_score, (int, float)):+ score: Any = max(0, min(100, round(float(raw_score))))+ else:+ score = UNAVAILABLE+ reasons["score"] = "report carried no score"++ signatures = _signatures(verdict_block.get("signals"), payload.get("yara"))+ if signatures is UNAVAILABLE:+ reasons["signatures"] = "report carried neither a signals array nor YARA matches"++ # The honesty case this whole interface exists for. The service reports+ # `attackTechniques: []` alongside `behavior.analyzed: false`, which is+ # an empty list because the behavioural stage never ran, not because+ # the sample exhibited no techniques. Publishing that as "no ATT&CK+ # techniques" would be an invented negative about a sample nobody+ # detonated.+ behavior = as_mapping(payload.get("behavior"))+ raw_attack = verdict_block.get("attackTechniques")+ if not isinstance(raw_attack, list):+ raw_attack = payload.get("attack") if isinstance(payload.get("attack"), list) else None+ if raw_attack is None:+ attack: Any = UNAVAILABLE+ reasons["attack"] = "report carried no ATT&CK section"+ elif not raw_attack and behavior.get("analyzed") is False:+ attack = UNAVAILABLE+ detail = str(behavior.get("reason") or "").strip() or "unspecified"+ reasons["attack"] = f"behavioural analysis did not run ({detail}), so no techniques could be observed"+ else:+ attack = tuple(_technique(item) for item in raw_attack if _technique(item) is not None)+ attack = tuple(t for t in attack if t is not None)++ return SandboxReport(+ provider="malwareanalyzer",+ state=AnalysisState.COMPLETED,+ verdict=verdict,+ score=score,+ signatures=signatures,+ iocs=_iocs(payload.get("iocs"), reasons),+ attack=attack,+ sha256=_sha256(payload),+ file_name=str(payload.get("fileName") or "") or None,+ file_type=str(payload.get("fileType") or "") or None,+ report_url=f"/report/{_sha256(payload)}" if _sha256(payload) else None,+ visibility=str(payload.get("visibility") or "") or None,+ analyzed_at=_parse_time(payload.get("analyzedAt")),+ unavailable_reasons=reasons,+ )+++def _env_flag(name: str) -> bool:+ return (os.getenv(name) or "").strip().lower() in {"1", "true", "yes", "on"}+++def _sha256(payload: dict[str, Any]) -> str | None:+ hashes = as_mapping(payload.get("hashes"))+ value = payload.get("contentHash") or hashes.get("sha256")+ return str(value).lower() if isinstance(value, str) and value.strip() else None+++def _state(raw: Any) -> AnalysisState:+ value = str(raw or "").strip().lower()+ if value in _DONE:+ return AnalysisState.COMPLETED+ if value in _FAILED:+ return AnalysisState.FAILED+ if value in {"queued", "pending", "accepted"}:+ return AnalysisState.PENDING+ # `partial`, `running`, `analyzing` and anything unrecognised: still going.+ # Treating an unknown status as failed would turn a new service state into+ # a fabricated failure.+ return AnalysisState.RUNNING+++def _signatures(signals: Any, yara: Any) -> Any:+ out: list[Signature] = []+ saw_section = False+ if isinstance(signals, list):+ saw_section = True+ for item in signals:+ if not isinstance(item, dict):+ continue+ confidence = item.get("confidence")+ out.append(+ Signature(+ identifier=str(item.get("id") or item.get("rule") or "").strip() or "unnamed",+ source=str(item.get("source") or "malwareanalyzer").strip(),+ description=str(item.get("description") or "").strip(),+ confidence=float(confidence) if isinstance(confidence, (int, float)) else None,+ )+ )+ if isinstance(yara, list):+ saw_section = True+ known = {s.identifier for s in out}+ for item in yara:+ if not isinstance(item, dict):+ continue+ rule = str(item.get("rule") or "").strip()+ meta = as_mapping(item.get("meta"))+ # The signals array already names YARA hits as `yara:<rule>`, so+ # only rules it did not carry are added.+ if not rule or rule in known or f"yara:{rule}" in known:+ continue+ out.append(+ Signature(+ identifier=rule,+ source="yara",+ description=str(meta.get("description") or "").strip(),+ severity=str(meta.get("severity")) if meta.get("severity") is not None else None,+ )+ )+ return tuple(out) if saw_section else UNAVAILABLE+++def _technique(item: Any) -> AttackTechnique | None:+ if isinstance(item, str) and item.strip().upper().startswith("T"):+ return AttackTechnique(technique_id=item.strip().upper())+ if isinstance(item, dict):+ tid = item.get("id") or item.get("technique") or item.get("techniqueId")+ if isinstance(tid, str) and tid.strip():+ return AttackTechnique(+ technique_id=tid.strip().upper(),+ name=str(item.get("name") or "") or None,+ tactic=str(item.get("tactic") or "") or None,+ )+ return None+++def _iocs(raw: Any, reasons: dict[str, str]) -> SandboxIocs:+ if not isinstance(raw, dict):+ reasons["iocs"] = "report carried no IOC section"+ return SandboxIocs()+ values: dict[str, Any] = {}+ for vendor_key, field_name in _IOC_KEYS:+ bucket = raw.get(vendor_key)+ # A present-but-empty bucket is a real "none found" and stays a tuple;+ # a missing bucket stays UNAVAILABLE.+ if isinstance(bucket, list):+ values[field_name] = tuple(str(v) for v in bucket if isinstance(v, str) and v.strip())+ hashes: list[str] = []+ saw_hash_bucket = False+ for key in ("sha256", "sha1", "md5"):+ bucket = raw.get(key)+ if isinstance(bucket, list):+ saw_hash_bucket = True+ hashes.extend(str(v) for v in bucket if isinstance(v, str) and v.strip())+ if saw_hash_bucket:+ values["file_hashes"] = tuple(dict.fromkeys(hashes))+ return SandboxIocs(**values)+++def _parse_time(value: Any) -> datetime | None:+ if not isinstance(value, str) or not value.strip():+ return None+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)diff --git a/services/api/app/services/sandbox/providers/mock.py b/services/api/app/services/sandbox/providers/mock.pynew file mode 100644index 000000000..0418f0d49--- /dev/null+++ b/services/api/app/services/sandbox/providers/mock.py@@ -0,0 +1,142 @@+"""An in-memory provider, for tests and for a deployment with no sandbox wired.++Two jobs. It is what the test suite drives so no test needs a network, and it+is the provider a CORE deployment gets by default so the wiring is exercised on+a first run rather than lying dormant until someone configures CAPEv2.++Everything it returns is labelled synthetic. ``is_synthetic`` rides on the+report's :attr:`~app.services.sandbox.types.SandboxReport.unavailable_reasons`+and on every API response built from it, so a fabricated verdict can never be+mistaken for a measured one, and the corpus is empty unless a caller seeds it.+An empty corpus means a first run reports "not seen" rather than inventing a+clean bill of health for a file nobody analysed.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from app.services.sandbox.base import SandboxProvider+from app.services.sandbox.types import (+ AnalysisState,+ AttackTechnique,+ ProviderCapabilities,+ SandboxIocs,+ SandboxReport,+ SandboxUnavailable,+ SandboxVerdict,+ Signature,+ SubmissionReceipt,+)++__all__ = ["MockSandboxProvider"]++#: Marks every report this provider produces. Read by+#: ``check_mock_data_gated.py``'s sibling rule in the API layer and asserted by+#: the tests: a synthetic verdict that reaches a surface without this key is+#: the failure the flag exists to make impossible.+SYNTHETIC_MARKER = "is_synthetic"+++class MockSandboxProvider(SandboxProvider):+ """A sandbox that analyses nothing and says so.++ ``seed`` is how a test gives it something to find. Nothing is seeded by+ default, deliberately: a provider that answers "malicious" for an+ unseeded hash would make every test that forgets to seed pass for the+ wrong reason.+ """++ def __init__(self, *, accepts_uploads: bool = True) -> None:+ self._known: dict[str, SandboxReport] = {}+ self._submissions: dict[str, SandboxReport] = {}+ self._accepts_uploads = accepts_uploads+ #: Every file handed to :meth:`submit_file`, so a test can assert that+ #: a refused upload really did not transfer any bytes.+ self.uploaded: list[tuple[str, int]] = []++ @property+ def capabilities(self) -> ProviderCapabilities:+ return ProviderCapabilities(+ name="mock",+ local=True,+ supports_hash_lookup=True,+ supports_file_submission=self._accepts_uploads,+ supports_url_submission=True,+ submissions_are_public_by_default=False,+ description="In-process provider for tests and unconfigured deployments. Analyses nothing.",+ )++ def seed(+ self,+ sha256: str,+ *,+ verdict: SandboxVerdict = SandboxVerdict.MALICIOUS,+ score: int = 90,+ signatures: tuple[Signature, ...] = (),+ attack: tuple[AttackTechnique, ...] = (),+ file_name: str | None = None,+ ) -> SandboxReport:+ """Register a hash so :meth:`lookup_hash` finds it."""+ report = SandboxReport(+ provider="mock",+ state=AnalysisState.COMPLETED,+ verdict=verdict,+ score=score,+ signatures=signatures,+ attack=attack,+ iocs=SandboxIocs(),+ sha256=sha256.lower(),+ file_name=file_name,+ visibility="private",+ analyzed_at=datetime.now(UTC),+ unavailable_reasons={SYNTHETIC_MARKER: "synthetic fixture from the mock provider, not a real analysis"},+ )+ self._known[sha256.lower()] = report+ return report++ async def lookup_hash(self, sha256: str) -> SandboxReport | None:+ return self._known.get((sha256 or "").strip().lower())++ async def submit_file(self, content: bytes, file_name: str, *, visibility: str | None = None) -> SubmissionReceipt:+ if not self._accepts_uploads:+ raise SandboxUnavailable("mock", "this provider does not accept file submissions", kind="bad_response")+ self.uploaded.append((file_name, len(content)))+ return self._accept(kind="file")++ async def submit_url(self, url: str) -> SubmissionReceipt:+ return self._accept(kind="url")++ def _accept(self, *, kind: str) -> SubmissionReceipt:+ handle = f"mock_{kind}_{uuid.uuid4().hex[:12]}"+ self._submissions[handle] = SandboxReport(+ provider="mock",+ state=AnalysisState.PENDING,+ unavailable_reasons={+ "verdict": "analysis has not finished",+ SYNTHETIC_MARKER: "synthetic fixture from the mock provider, not a real analysis",+ },+ )+ return SubmissionReceipt(+ provider="mock",+ handle=handle,+ state=AnalysisState.PENDING,+ visibility="private",+ poll_after_seconds=1,+ submitted_at=datetime.now(UTC),+ )++ def complete(self, handle: str, report: SandboxReport) -> None:+ """Move a pending submission to a finished report, for a test's timeline."""+ self._submissions[handle] = report++ async def poll(self, handle: str) -> SandboxReport:+ report = self._submissions.get(handle)+ if report is None:+ return SandboxReport(+ provider="mock",+ state=AnalysisState.NOT_FOUND,+ unavailable_reasons={"verdict": f"no submission with handle {handle}"},+ )+ return reportdiff --git a/services/api/app/services/sandbox/registry.py b/services/api/app/services/sandbox/registry.pynew file mode 100644index 000000000..2c46d2d9b--- /dev/null+++ b/services/api/app/services/sandbox/registry.py@@ -0,0 +1,108 @@+"""Which providers a deployment has, and which of them it may use right now.++Configuration is by environment variable because a sandbox is a deployment+fact, not a tenant one: the tenant decides whether its *files* may go to a+provider, the operator decides whether the provider exists at all. Keeping the+two apart is what makes the consent question answerable, because a tenant+cannot consent to a provider nobody configured.++The mock is always present. A deployment with no sandbox configured still has+the wiring exercised on every path, and the mock knows nothing, so the honest+answer on a first run is "not seen by any provider" rather than silence.+"""++from __future__ import annotations++import os++import structlog++from app.core.config import settings+from app.services.sandbox.base import SandboxProvider+from app.services.sandbox.providers.capev2 import CapeV2Provider+from app.services.sandbox.providers.malwareanalyzer import MalwareAnalyzerProvider+from app.services.sandbox.providers.mock import MockSandboxProvider++log = structlog.get_logger(__name__)++__all__ = ["SandboxRegistry", "build_registry"]+++class SandboxRegistry:+ """The configured providers, and the air-gap rule over them."""++ def __init__(self, providers: list[SandboxProvider], *, airgapped: bool | None = None) -> None:+ self._providers = {p.name: p for p in providers}+ self._airgapped = settings.AISOC_AIRGAPPED if airgapped is None else airgapped++ @property+ def airgapped(self) -> bool:+ return self._airgapped++ def names(self) -> list[str]:+ """Every configured provider, including ones air-gap mode forbids.++ Forbidden is not absent: an operator whose provider has been excluded+ needs to see it excluded, with the reason, rather than watch it vanish+ from the settings page.+ """+ return sorted(self._providers)++ def usable_names(self) -> list[str]:+ return sorted(name for name, p in self._providers.items() if self.is_usable(p))++ def is_usable(self, provider: SandboxProvider) -> bool:+ return provider.local or not self._airgapped++ def get(self, name: str) -> SandboxProvider | None:+ return self._providers.get((name or "").strip().lower())++ def default(self) -> SandboxProvider | None:+ """The provider a caller that named none should get.++ A local provider wins over a hosted one at equal configuration, because+ the local one discloses nothing. Within that, configuration order is+ preserved, so an operator running CAPEv2 gets CAPEv2 and not the mock.+ """+ usable = [p for p in self._providers.values() if self.is_usable(p)]+ if not usable:+ return None+ real = [p for p in usable if p.name != "mock"]+ pool = real or usable+ return next((p for p in pool if p.local), pool[0])++ async def aclose(self) -> None:+ for provider in self._providers.values():+ await provider.aclose()+++def build_registry(*, airgapped: bool | None = None) -> SandboxRegistry:+ """Assemble the providers this deployment has configured."""+ providers: list[SandboxProvider] = []++ cape_url = (os.getenv("AISOC_CAPEV2_URL") or "").strip()+ if cape_url:+ providers.append(CapeV2Provider(cape_url, api_token=os.getenv("AISOC_CAPEV2_TOKEN")))++ if _enabled("AISOC_MALWAREANALYZER_ENABLED"):+ providers.append(MalwareAnalyzerProvider())++ providers.append(MockSandboxProvider())+ registry = SandboxRegistry(providers, airgapped=airgapped)+ log.info(+ "sandbox.registry",+ providers=registry.names(),+ usable=registry.usable_names(),+ airgapped=registry.airgapped,+ )+ return registry+++def _enabled(name: str) -> bool:+ """Default off.++ A hosted analysis provider that switched itself on because a base URL had a+ default would be a deployment making outbound calls nobody asked for, which+ is the shape the upload policy exists to prevent one level down.+ """+ return (os.getenv(name) or "").strip().lower() in {"1", "true", "yes", "on"}diff --git a/services/api/app/services/sandbox/service.py b/services/api/app/services/sandbox/service.pynew file mode 100644index 000000000..e61335af8--- /dev/null+++ b/services/api/app/services/sandbox/service.py@@ -0,0 +1,269 @@+"""The one place hash-first is enforced and a failure becomes "could not check".++Two rules live here rather than in the routes, because there is more than one+caller (enrichment, phishing, the agent tool, the console) and a rule+re-implemented per caller is a rule that holds in three places and not the+fourth.++**Hash first.** :func:`analyse_file` looks the digest up before it will even+evaluate whether an upload is permitted, so the sequence cannot be skipped by a+caller passing the wrong argument. The policy function takes+``hash_already_known`` as data, and this is the only code that computes it.++**A failure is not a negative.** A provider that times out, refuses+authentication or returns something unparseable produces+``outcome="could_not_check"`` with the reason attached. It never produces a+report, and never an absent verdict that reads like a clean one. This is the+same rule the plan states for read tools generally, and a sandbox is the read+tool most likely to be slow or down.+"""++from __future__ import annotations++import hashlib+from dataclasses import dataclass, field+from typing import Any, Literal++import structlog++from app.services.sandbox.base import SandboxProvider+from app.services.sandbox.policy import UploadDecision, UploadRefusal, evaluate_upload+from app.services.sandbox.registry import SandboxRegistry+from app.services.sandbox.types import (+ AnalysisState,+ SandboxReport,+ SandboxUnavailable,+ SubmissionReceipt,+)++log = structlog.get_logger(__name__)++__all__ = ["SandboxOutcome", "SandboxResult", "analyse_file", "analyse_url", "lookup_hash", "poll", "sha256_of"]++#: What happened, as one word a caller can branch on.+#:+#: ``known`` a report exists and is attached.+#: ``pending`` an analysis is running; come back with ``handle``.+#: ``not_seen`` no provider has analysed this, and nothing was uploaded.+#: ``upload_refused`` an upload would have been needed and policy said no.+#: ``could_not_check`` the provider could not be asked. Not a verdict.+SandboxOutcome = Literal["known", "pending", "not_seen", "upload_refused", "could_not_check"]+++@dataclass(frozen=True, slots=True)+class SandboxResult:+ """What a caller gets back, whatever happened.++ One type for all five outcomes on purpose: a caller that forgets to handle+ ``could_not_check`` gets a result whose ``report`` is ``None``, rather than+ an exception it can swallow into a clean answer.+ """++ outcome: SandboxOutcome+ provider: str+ #: Present only when ``outcome == "known"``.+ report: SandboxReport | None = None+ #: Present when ``outcome == "pending"``.+ receipt: SubmissionReceipt | None = None+ #: Present when ``outcome == "upload_refused"``.+ decision: UploadDecision | None = None+ #: Human-readable, and safe to show an analyst or send to a model.+ detail: str = ""+ sha256: str | None = None+ #: True when bytes left this deployment as part of producing this result.+ uploaded: bool = False+ warnings: list[str] = field(default_factory=list)++ def as_dict(self) -> dict[str, Any]:+ return {+ "outcome": self.outcome,+ "provider": self.provider,+ "detail": self.detail,+ "sha256": self.sha256,+ "uploaded": self.uploaded,+ "report": self.report.summary() if self.report else None,+ "handle": self.receipt.handle if self.receipt else None,+ "poll_after_seconds": self.receipt.poll_after_seconds if self.receipt else None,+ "decision": self.decision.as_dict() if self.decision else None,+ "warnings": list(self.warnings),+ }+++def sha256_of(content: bytes) -> str:+ return hashlib.sha256(content).hexdigest()+++async def lookup_hash(provider: SandboxProvider, sha256: str) -> SandboxResult:+ """Ask one provider whether it has already analysed this digest.++ The only verb that is always allowed: a SHA-256 discloses nothing about the+ file it names, so no tenant has to consent to it and air-gap mode only+ restricts which providers exist to ask.+ """+ digest = (sha256 or "").strip().lower()+ try:+ report = await provider.lookup_hash(digest)+ except SandboxUnavailable as exc:+ log.warning("sandbox.lookup_failed", provider=provider.name, kind=exc.kind, reason=exc.reason)+ return SandboxResult(+ outcome="could_not_check",+ provider=provider.name,+ sha256=digest,+ detail=f"Could not check {provider.name}: {exc.reason}. This is not a verdict; the file was not assessed.",+ )+ if report is None:+ return SandboxResult(+ outcome="not_seen",+ provider=provider.name,+ sha256=digest,+ detail=f"{provider.name} has no analysis on file for this hash.",+ )+ if not report.state.terminal:+ return SandboxResult(+ outcome="pending",+ provider=provider.name,+ report=None,+ sha256=digest,+ detail=f"{provider.name} is still analysing this file.",+ )+ return SandboxResult(+ outcome="known",+ provider=provider.name,+ report=report,+ sha256=digest,+ detail=f"{provider.name} has an existing report for this hash. Nothing was uploaded.",+ )+++async def analyse_file(+ provider: SandboxProvider,+ *,+ content: bytes,+ file_name: str,+ registry: SandboxRegistry,+ tenant_uploads_enabled: bool,+ allow_upload: bool = True,+ requested_visibility: str | None = None,+) -> SandboxResult:+ """Hash-lookup first, then upload only if policy allows it.++ ``allow_upload=False`` is how a caller that only wants a lookup says so+ without pretending the tenant has not consented: the refusal it produces+ names the caller, not the tenant's setting.+ """+ digest = sha256_of(content)+ looked_up = await lookup_hash(provider, digest)+ if looked_up.outcome in ("known", "pending", "could_not_check"):+ # A provider that could not be reached for the lookup will not be+ # reached for an upload either, and trying anyway would disclose the+ # file to find that out.+ return looked_up++ decision = evaluate_upload(+ capabilities=provider.capabilities,+ airgapped=registry.airgapped,+ tenant_uploads_enabled=tenant_uploads_enabled and allow_upload,+ hash_already_known=False,+ )+ if not decision.allowed:+ detail = decision.reason+ if not allow_upload and decision.refusal is UploadRefusal.TENANT_NOT_CONSENTED:+ detail = f"{provider.name} has not seen this file. This caller performs hash lookups only and did not upload it."+ return SandboxResult(+ outcome="upload_refused",+ provider=provider.name,+ decision=decision,+ sha256=digest,+ detail=detail,+ )++ visibility = requested_visibility or ("private" if provider.capabilities.local else "private")+ try:+ receipt = await provider.submit_file(content, file_name, visibility=visibility)+ except SandboxUnavailable as exc:+ log.warning("sandbox.submit_failed", provider=provider.name, kind=exc.kind, reason=exc.reason)+ return SandboxResult(+ outcome="could_not_check",+ provider=provider.name,+ sha256=digest,+ detail=f"Could not submit to {provider.name}: {exc.reason}. This is not a verdict.",+ )++ warnings: list[str] = []+ if provider.capabilities.submissions_are_public_by_default:+ warnings.append(f"{provider.name} publishes submitted samples: this file and its report are now readable by anyone.")+ return SandboxResult(+ outcome="pending",+ provider=provider.name,+ receipt=receipt,+ sha256=digest,+ uploaded=True,+ detail=f"Uploaded to {provider.name} for analysis. Poll {receipt.handle} for the result.",+ warnings=warnings,+ )+++async def analyse_url(provider: SandboxProvider, url: str, *, registry: SandboxRegistry) -> SandboxResult:+ """Submit a URL.++ Not governed by the upload policy, which is about customer *files*. It is+ still governed by air-gap mode, because a hosted provider is unreachable+ there whatever the artefact.+ """+ if not registry.is_usable(provider):+ decision = evaluate_upload(+ capabilities=provider.capabilities,+ airgapped=True,+ tenant_uploads_enabled=True,+ hash_already_known=False,+ )+ return SandboxResult(outcome="upload_refused", provider=provider.name, decision=decision, detail=decision.reason)+ if not provider.capabilities.supports_url_submission:+ return SandboxResult(+ outcome="could_not_check",+ provider=provider.name,+ detail=f"{provider.name} does not accept URL submissions.",+ )+ try:+ receipt = await provider.submit_url(url)+ except SandboxUnavailable as exc:+ return SandboxResult(+ outcome="could_not_check",+ provider=provider.name,+ detail=f"Could not submit to {provider.name}: {exc.reason}. This is not a verdict.",+ )+ return SandboxResult(+ outcome="pending",+ provider=provider.name,+ receipt=receipt,+ detail=f"Submitted to {provider.name}. Poll {receipt.handle} for the result.",+ )+++async def poll(provider: SandboxProvider, handle: str) -> SandboxResult:+ """Check on a submission."""+ try:+ report = await provider.poll(handle)+ except SandboxUnavailable as exc:+ return SandboxResult(+ outcome="could_not_check",+ provider=provider.name,+ detail=f"Could not reach {provider.name}: {exc.reason}. This is not a verdict.",+ )+ if report.state is AnalysisState.NOT_FOUND:+ return SandboxResult(outcome="not_seen", provider=provider.name, detail=f"{provider.name} has no analysis {handle}.")+ if report.state is AnalysisState.FAILED:+ return SandboxResult(+ outcome="could_not_check",+ provider=provider.name,+ detail=f"{provider.name} failed to analyse {handle}. No verdict was reached.",+ )+ if not report.state.terminal:+ return SandboxResult(outcome="pending", provider=provider.name, detail=f"{provider.name} is still analysing {handle}.")+ return SandboxResult(+ outcome="known",+ provider=provider.name,+ report=report,+ sha256=report.sha256,+ detail=f"{provider.name} finished analysing {handle}.",+ )diff --git a/services/api/app/services/sandbox/store.py b/services/api/app/services/sandbox/store.pynew file mode 100644index 000000000..9c7561160--- /dev/null+++ b/services/api/app/services/sandbox/store.py@@ -0,0 +1,179 @@+"""Reading the consent and writing the audit row.++Kept apart from :mod:`app.services.sandbox.policy`, which is pure and knows+nothing about a database, so every combination of the policy can be driven in a+test without one. This module is the only thing that turns a row into the+``tenant_uploads_enabled`` boolean the policy takes.++The tenant is always an argument, never a request field: every caller here+receives it from the authenticated principal, and every statement binds it.+"""++from __future__ import annotations++import uuid+from dataclasses import dataclass++import structlog+from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession++from app.services.sandbox.policy import CONSENT_TEXT_VERSION+from app.services.sandbox.service import SandboxResult++log = structlog.get_logger(__name__)++__all__ = ["UploadConsent", "list_consent", "read_consent", "record_decision", "set_consent"]+++@dataclass(frozen=True, slots=True)+class UploadConsent:+ provider: str+ uploads_enabled: bool+ consent_text_version: str | None = None+ consented_by: uuid.UUID | None = None+ consented_at: str | None = None+++async def read_consent(db: AsyncSession, *, tenant_id: uuid.UUID, provider: str) -> bool:+ """Whether this tenant has consented to uploads to this provider.++ A missing row is a ``False``, not an error. Consent is the presence of an+ affirmative record, so "no row" and "row saying no" mean the same thing and+ neither needs to be created before the first refusal can be logged.+ """+ row = (+ await db.execute(+ text(+ "SELECT uploads_enabled FROM aisoc_sandbox_upload_policy WHERE tenant_id = :tenant_id AND provider = :provider"+ ).bindparams(tenant_id=tenant_id, provider=provider)+ )+ ).fetchone()+ return bool(row.uploads_enabled) if row else False+++async def list_consent(db: AsyncSession, *, tenant_id: uuid.UUID) -> list[UploadConsent]:+ rows = (+ await db.execute(+ text(+ "SELECT provider, uploads_enabled, consent_text_version, consented_by, consented_at "+ "FROM aisoc_sandbox_upload_policy WHERE tenant_id = :tenant_id ORDER BY provider"+ ).bindparams(tenant_id=tenant_id)+ )+ ).fetchall()+ return [+ UploadConsent(+ provider=r.provider,+ uploads_enabled=bool(r.uploads_enabled),+ consent_text_version=r.consent_text_version,+ consented_by=r.consented_by,+ consented_at=r.consented_at.isoformat() if r.consented_at else None,+ )+ for r in rows+ ]+++async def set_consent(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ provider: str,+ enabled: bool,+ actor_id: uuid.UUID | None,+) -> UploadConsent:+ """Record a consent decision, with who made it and which text they saw.++ Turning consent *off* clears the attribution, because the recorded agreement+ no longer describes the state of the row and leaving it there would suggest+ somebody agreed to the current setting.+ """+ await db.execute(+ text("""+ INSERT INTO aisoc_sandbox_upload_policy+ (tenant_id, provider, uploads_enabled, consent_text_version, consented_by, consented_at, updated_at)+ VALUES+ (:tenant_id, :provider, :enabled,+ CASE WHEN :enabled THEN :version ELSE NULL END,+ CASE WHEN :enabled THEN :actor ELSE NULL END,+ CASE WHEN :enabled THEN NOW() ELSE NULL END,+ NOW())+ ON CONFLICT (tenant_id, provider) DO UPDATE SET+ uploads_enabled = EXCLUDED.uploads_enabled,+ consent_text_version = EXCLUDED.consent_text_version,+ consented_by = EXCLUDED.consented_by,+ consented_at = EXCLUDED.consented_at,+ updated_at = NOW()+ """).bindparams(+ tenant_id=tenant_id,+ provider=provider,+ enabled=enabled,+ version=CONSENT_TEXT_VERSION,+ actor=actor_id,+ )+ )+ await db.commit()+ log.info(+ "sandbox.consent_changed",+ tenant_id=str(tenant_id),+ provider=provider,+ uploads_enabled=enabled,+ consent_text_version=CONSENT_TEXT_VERSION if enabled else None,+ )+ return UploadConsent(+ provider=provider,+ uploads_enabled=enabled,+ consent_text_version=CONSENT_TEXT_VERSION if enabled else None,+ consented_by=actor_id if enabled else None,+ )+++async def record_decision(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ result: SandboxResult,+ artifact_kind: str,+ file_name: str | None = None,+ actor_id: uuid.UUID | None = None,+) -> None:+ """Append the audit row for one decision, allowed or refused.++ Fail-soft on purpose: a sandbox lookup must not 500 because the audit+ insert failed. It logs at ``warning`` with the outcome it could not store,+ so a missing row is visible in the log pipeline rather than silent.+ """+ try:+ await db.execute(+ text("""+ INSERT INTO aisoc_sandbox_submissions+ (tenant_id, provider, artifact_kind, sha256, file_name, outcome,+ refusal, reason, uploaded, visibility, provider_handle, requested_by)+ VALUES+ (:tenant_id, :provider, :kind, :sha256, :file_name, :outcome,+ :refusal, :reason, :uploaded, :visibility, :handle, :actor)+ """).bindparams(+ tenant_id=tenant_id,+ provider=result.provider,+ kind=artifact_kind,+ sha256=result.sha256,+ file_name=file_name,+ outcome=result.outcome,+ refusal=result.decision.refusal.value if result.decision and result.decision.refusal else None,+ reason=result.detail[:2000],+ uploaded=result.uploaded,+ visibility=(result.receipt.visibility if result.receipt else None) or (result.report.visibility if result.report else None),+ handle=result.receipt.handle if result.receipt else None,+ actor=actor_id,+ )+ )+ await db.commit()+ except Exception as exc: # noqa: BLE001 - never fail a lookup over its audit row+ await db.rollback()+ log.warning(+ "sandbox.audit_write_failed",+ tenant_id=str(tenant_id),+ provider=result.provider,+ outcome=result.outcome,+ uploaded=result.uploaded,+ error=str(exc),+ )diff --git a/services/api/app/services/sandbox/types.py b/services/api/app/services/sandbox/types.pynew file mode 100644index 000000000..7d1fe08b0--- /dev/null+++ b/services/api/app/services/sandbox/types.py@@ -0,0 +1,335 @@+"""The vocabulary every file and URL analysis provider is translated into.++Why a vocabulary and not a payload+----------------------------------+A sandbox report is the most vendor-shaped object in this product. One vendor+calls its judgement ``verdict``, another ``score``, another ``malscore``; one+returns ATT&CK under ``ttps``, another under ``attackTechniques``, another not+at all. Passing any one of those through to the console and to the agent makes+the first provider wired the de-facto interface, and the second adapter then+gets written to imitate it.++So the interface owns the words. A verdict, a score, signatures, IOCs and an+ATT&CK mapping are what a caller may ask for, and each provider maps its own+payload onto them. Nothing here is named after a vendor, and nothing here+exists because one vendor happened to return it.++Absent is not zero+------------------+The rule that makes this usable is :data:`UNAVAILABLE`. Three states have to+stay distinguishable and two of them look identical if the type is a list:++``[]`` / ``0``+ The provider computed this and the answer is none. The sample contacted no+ domains.+:data:`UNAVAILABLE`+ The provider does not compute this, or the stage that would have computed+ it did not run. Nothing is known either way.+``None`` on an optional field+ Reserved for "this provider has no such concept at all".++Collapsing the middle one into the first is how a sandbox report turns into a+clean bill of health for a sample nobody detonated. A concrete instance is in+the tree: the first commercial adapter returns an empty ATT&CK list alongside+``behavior.analyzed = false``, because the file type could not be identified+and no guest was ever chosen. The techniques are absent because the stage did+not run, and reporting that as "no techniques" would be an invented negative.+"""++from __future__ import annotations++import enum+from dataclasses import dataclass, field+from datetime import datetime+from typing import Any, Final, Literal, TypeAlias, TypeGuard, TypeVar++__all__ = [+ "UNAVAILABLE",+ "AnalysisState",+ "AttackTechnique",+ "Maybe",+ "ProviderCapabilities",+ "SandboxError",+ "SandboxIocs",+ "SandboxReport",+ "SandboxUnavailable",+ "SandboxVerdict",+ "Signature",+ "SubmissionReceipt",+ "Unavailable",+ "is_available",+]+++class Unavailable:+ """Singleton for "not known", distinct from an empty result.++ Falsy on purpose, so ``if report.attack:`` is never accidentally true, but+ never equal to ``[]``, ``0`` or ``None``, so a caller that cares about the+ difference can ask for it.+ """++ _instance: Unavailable | None = None++ def __new__(cls) -> Unavailable:+ if cls._instance is None:+ cls._instance = super().__new__(cls)+ return cls._instance++ def __bool__(self) -> bool:+ return False++ def __repr__(self) -> str:+ return "UNAVAILABLE"++ def __reduce__(self) -> tuple[type[Unavailable], tuple[()]]:+ return (Unavailable, ())+++UNAVAILABLE: Final[Unavailable] = Unavailable()++_T = TypeVar("_T")+#: A value the provider supplied, or :data:`UNAVAILABLE`.+#:+#: The ``: TypeAlias`` annotation is load-bearing, not decoration. Without it+#: a bare type variable is not a valid alias target, so this reads as an+#: ordinary variable and every annotation spelled ``Maybe[X]`` is silently+#: untyped, which is the opposite of the point of this module.+Maybe: TypeAlias = _T | Unavailable+++def is_available(value: Maybe[_T]) -> TypeGuard[_T]:+ """True when ``value`` came from the provider rather than standing in for it.++ A ``TypeGuard`` rather than a ``bool`` so the type checker narrows the+ positive branch. Without it, ``report.verdict.value`` behind this call is+ an error at every call site, and the call sites would then be written to+ avoid the helper instead of using it.+ """+ return not isinstance(value, Unavailable)+++class SandboxVerdict(str, enum.Enum):+ """The judgement, normalised across providers.++ ``UNKNOWN`` is a judgement the provider reached; a provider that reached no+ judgement returns :data:`UNAVAILABLE` for the field instead.+ """++ MALICIOUS = "malicious"+ SUSPICIOUS = "suspicious"+ BENIGN = "benign"+ UNKNOWN = "unknown"+++class AnalysisState(str, enum.Enum):+ """Where an analysis has got to.++ ``PENDING`` and ``RUNNING`` both mean "ask again later"; they are separate+ because a caller that has not yet been scheduled and one that is executing+ deserve different wording in front of an analyst. ``NOT_FOUND`` is the+ hash-lookup miss, which is a normal answer and not an error.+ """++ PENDING = "pending"+ RUNNING = "running"+ COMPLETED = "completed"+ FAILED = "failed"+ NOT_FOUND = "not_found"++ @property+ def terminal(self) -> bool:+ return self in (AnalysisState.COMPLETED, AnalysisState.FAILED, AnalysisState.NOT_FOUND)+++@dataclass(frozen=True, slots=True)+class Signature:+ """One named thing a provider observed or matched.++ Deliberately flat. A YARA hit, a behavioural signature and an engine+ detection are the same shape to a reader deciding whether to care, and+ keeping them one type is what stops the console growing a section per+ provider. ``source`` carries the provenance ("yara", "capa", "behaviour",+ an engine name) so nothing is lost by the flattening.+ """++ identifier: str+ source: str+ description: str = ""+ severity: str | None = None+ confidence: float | None = None+++@dataclass(frozen=True, slots=True)+class AttackTechnique:+ technique_id: str+ name: str | None = None+ tactic: str | None = None+++@dataclass(frozen=True, slots=True)+class SandboxIocs:+ """Indicators the analysis extracted.++ Every list is independently :data:`UNAVAILABLE`-able: a static-only pass+ can produce embedded URLs while knowing nothing about mutexes, and saying+ "no mutexes" there would be a claim it never made.+ """++ urls: Maybe[tuple[str, ...]] = UNAVAILABLE+ domains: Maybe[tuple[str, ...]] = UNAVAILABLE+ ipv4: Maybe[tuple[str, ...]] = UNAVAILABLE+ ipv6: Maybe[tuple[str, ...]] = UNAVAILABLE+ emails: Maybe[tuple[str, ...]] = UNAVAILABLE+ file_hashes: Maybe[tuple[str, ...]] = UNAVAILABLE+ file_paths: Maybe[tuple[str, ...]] = UNAVAILABLE+ registry_keys: Maybe[tuple[str, ...]] = UNAVAILABLE+ mutexes: Maybe[tuple[str, ...]] = UNAVAILABLE+ cves: Maybe[tuple[str, ...]] = UNAVAILABLE+++@dataclass(frozen=True, slots=True)+class ProviderCapabilities:+ """What a provider can do, so a caller never offers what it cannot.++ ``local`` is the air-gap predicate and is a property of where the analysis+ runs, not of who wrote the adapter: a self-hosted open-source sandbox on+ the operator's own network is local, and a hosted service is not, however+ the credential is configured.+ """++ name: str+ local: bool+ supports_hash_lookup: bool = True+ supports_file_submission: bool = False+ supports_url_submission: bool = False+ #: True when a submitted sample is visible beyond the operator and the+ #: vendor. Drives the consent text, so it is a declared fact about the+ #: provider rather than something the upload path infers.+ submissions_are_public_by_default: bool = False+ description: str = ""+++@dataclass(frozen=True, slots=True)+class SubmissionReceipt:+ """What a caller needs to come back for a result.++ ``handle`` is opaque and provider-scoped. It is deliberately not called a+ task id, a scan uuid or a job id, because it is all three depending on who+ answered, and giving it one vendor's name is how the next adapter ends up+ fabricating one.+ """++ provider: str+ handle: str+ state: AnalysisState+ #: What the analysis will be visible to once it completes, when the+ #: provider says. Recorded on the audit row, so an operator can answer+ #: "where did this file go" later.+ visibility: str | None = None+ poll_after_seconds: int = 15+ submitted_at: datetime | None = None+++@dataclass(frozen=True, slots=True)+class SandboxReport:+ """A provider's answer, in the interface's words.++ ``state`` leads because it is what a caller must branch on. A report whose+ state is ``PENDING`` carries no verdict and is not a benign one.+ """++ provider: str+ state: AnalysisState+ verdict: Maybe[SandboxVerdict] = UNAVAILABLE+ #: 0-100, higher is worse. ``UNAVAILABLE`` when the provider publishes no+ #: score; a provider with a different range normalises here rather than+ #: leaking its own.+ score: Maybe[int] = UNAVAILABLE+ signatures: Maybe[tuple[Signature, ...]] = UNAVAILABLE+ iocs: SandboxIocs = field(default_factory=SandboxIocs)+ attack: Maybe[tuple[AttackTechnique, ...]] = UNAVAILABLE+ sha256: str | None = None+ file_name: str | None = None+ file_type: str | None = None+ #: Where a human can read the full report, when there is such a place.+ report_url: str | None = None+ #: Who the completed analysis is visible to, in the provider's own words.+ visibility: str | None = None+ analyzed_at: datetime | None = None+ #: Why a section is missing, keyed by field name, e.g.+ #: ``{"attack": "behavioural stage did not run: unidentified_file_type"}``.+ #: An analyst asking "why is this blank" gets an answer instead of a guess.+ unavailable_reasons: dict[str, str] = field(default_factory=dict)++ def summary(self) -> dict[str, Any]:+ """A compact, JSON-safe projection for a prompt or an API response.++ Unavailable fields are rendered as the string ``"unavailable"`` rather+ than dropped, because a key that is simply missing reads to a model as+ a field it may infer.+ """++ def render(value: Maybe[Any]) -> Any:+ if isinstance(value, Unavailable):+ return "unavailable"+ if isinstance(value, enum.Enum):+ return value.value+ return value++ return {+ "provider": self.provider,+ "state": self.state.value,+ "verdict": render(self.verdict),+ "score": render(self.score),+ "signatures": (+ "unavailable"+ if isinstance(self.signatures, Unavailable)+ else [{"id": s.identifier, "source": s.source, "description": s.description} for s in self.signatures[:25]]+ ),+ "attack": (+ "unavailable"+ if isinstance(self.attack, Unavailable)+ else [{"technique_id": t.technique_id, "name": t.name} for t in self.attack]+ ),+ "iocs": {+ name: ("unavailable" if isinstance(value, Unavailable) else list(value[:50]))+ for name, value in (+ ("urls", self.iocs.urls),+ ("domains", self.iocs.domains),+ ("ipv4", self.iocs.ipv4),+ ("ipv6", self.iocs.ipv6),+ ("emails", self.iocs.emails),+ ("file_hashes", self.iocs.file_hashes),+ ("file_paths", self.iocs.file_paths),+ ("registry_keys", self.iocs.registry_keys),+ ("mutexes", self.iocs.mutexes),+ ("cves", self.iocs.cves),+ )+ },+ "sha256": self.sha256,+ "file_name": self.file_name,+ "report_url": self.report_url,+ "visibility": self.visibility,+ "unavailable_reasons": dict(self.unavailable_reasons),+ }+++class SandboxError(RuntimeError):+ """Base class for every failure a provider can raise."""+++class SandboxUnavailable(SandboxError):+ """The provider could not be reached, or refused to answer.++ Raised rather than returning a report, so no call site can mistake a+ failed check for a clean one. Callers that face a model or an analyst+ catch it and say "could not check"; see+ :mod:`app.services.sandbox.service`.+ """++ def __init__(self, provider: str, reason: str, *, kind: Literal["network", "auth", "rate_limit", "bad_response"] = "network") -> None:+ super().__init__(f"{provider}: {reason}")+ self.provider = provider+ self.reason = reason+ self.kind = kinddiff --git a/services/api/migrations/064_sandbox_upload_policy.sql b/services/api/migrations/064_sandbox_upload_policy.sqlnew file mode 100644index 000000000..4a625eb01--- /dev/null+++ b/services/api/migrations/064_sandbox_upload_policy.sql@@ -0,0 +1,121 @@+-- 064: who agreed that this tenant's files may leave, and what left.+--+-- Two tables, because two different questions get asked later and neither+-- answers the other.+--+-- aisoc_sandbox_upload_policy may files from tenant T go to provider P,+-- who agreed, and to which words+-- aisoc_sandbox_submissions what was actually decided, per artefact+--+-- Why the consent is per (tenant, provider) and not per tenant+-- ------------------------------------------------------------+-- Consent is about where the file goes. An operator content to send a sample+-- to a sandbox running in their own rack has agreed to nothing about a hosted+-- service, and one flag would treat those as the same question. The primary+-- key is the pair for that reason.+--+-- Why the consent text version is stored+-- --------------------------------------+-- The first commercial provider wired here publishes submitted samples: a+-- stored report carries `visibility: "public"` and `tlp: "clear"`, so an+-- upload is a disclosure to the internet rather than to a vendor. The consent+-- text says that in those words. If the wording ever changes, what a tenant+-- previously agreed to did not, and a bare boolean cannot say which sentence+-- it was. `consent_text_version` travels onto the row so an audit can.+--+-- Why refusals are recorded and not only uploads+-- ----------------------------------------------+-- The common row here is a refusal, and it is the more useful one. "Nothing+-- was uploaded because the hash was already known" and "nothing was uploaded+-- because this tenant has not consented" are the two answers an operator+-- needs when asked what happened to an attachment, and a table holding only+-- successful uploads answers neither. `uploaded` is the single boolean that+-- means bytes left the deployment.++CREATE TABLE IF NOT EXISTS aisoc_sandbox_upload_policy (+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ provider TEXT NOT NULL,+ -- Off. Not defaulted on for any provider, local ones included: a local+ -- sandbox still writes the file to a system with its own retention.+ uploads_enabled BOOLEAN NOT NULL DEFAULT FALSE,+ consent_text_version TEXT,+ consented_by UUID REFERENCES users(id) ON DELETE SET NULL,+ consented_at TIMESTAMPTZ,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ PRIMARY KEY (tenant_id, provider)+);++COMMENT ON TABLE aisoc_sandbox_upload_policy IS+ 'Per-tenant, per-provider consent to upload customer files for analysis. '+ 'Absence of a row means no consent, which is why every read defaults to false '+ 'rather than requiring a row to exist.';+COMMENT ON COLUMN aisoc_sandbox_upload_policy.consent_text_version IS+ 'Which version of the disclosure text was shown when this was enabled. '+ 'A boolean with no record of the sentence behind it cannot be audited.';++CREATE TABLE IF NOT EXISTS aisoc_sandbox_submissions (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ provider TEXT NOT NULL,+ -- 'file' | 'url' | 'hash'+ artifact_kind TEXT NOT NULL,+ sha256 TEXT,+ file_name TEXT,+ -- The service.SandboxOutcome word: known | pending | not_seen |+ -- upload_refused | could_not_check.+ outcome TEXT NOT NULL,+ -- The policy.UploadRefusal word when the outcome was a refusal.+ refusal TEXT,+ reason TEXT NOT NULL DEFAULT '',+ -- TRUE only when bytes left this deployment. The column the question+ -- "did any customer file go to a third party" is answered from.+ uploaded BOOLEAN NOT NULL DEFAULT FALSE,+ -- What the analysis is visible to, in the provider's own words.+ visibility TEXT,+ provider_handle TEXT,+ requested_by UUID REFERENCES users(id) ON DELETE SET NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);++COMMENT ON TABLE aisoc_sandbox_submissions IS+ 'Every file/URL analysis decision, allowed or refused. Refusals are the '+ 'common row and the more useful one: it is what answers "what happened to '+ 'this attachment" when nothing was uploaded.';+COMMENT ON COLUMN aisoc_sandbox_submissions.uploaded IS+ 'TRUE only when file bytes were transmitted to the provider.';++CREATE INDEX IF NOT EXISTS idx_sandbox_submissions_tenant_created+ ON aisoc_sandbox_submissions (tenant_id, created_at DESC);+CREATE INDEX IF NOT EXISTS idx_sandbox_submissions_sha256+ ON aisoc_sandbox_submissions (tenant_id, sha256) WHERE sha256 IS NOT NULL;+CREATE INDEX IF NOT EXISTS idx_sandbox_submissions_uploaded+ ON aisoc_sandbox_submissions (tenant_id, created_at DESC) WHERE uploaded;++-- Row-level security. The `OR current_tenant_id() IS NULL` arm is the one that+-- lets the cross-tenant workers (retention purge, tenant deletion) read these+-- tables on a connection that binds no tenant; dropping it makes those+-- silently see nothing. FORCE so the owner does not walk past.+ALTER TABLE aisoc_sandbox_upload_policy ENABLE ROW LEVEL SECURITY;+ALTER TABLE aisoc_sandbox_upload_policy FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS aisoc_sandbox_upload_policy_tenant ON aisoc_sandbox_upload_policy;+CREATE POLICY aisoc_sandbox_upload_policy_tenant ON aisoc_sandbox_upload_policy+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++ALTER TABLE aisoc_sandbox_submissions ENABLE ROW LEVEL SECURITY;+ALTER TABLE aisoc_sandbox_submissions FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS aisoc_sandbox_submissions_tenant ON aisoc_sandbox_submissions;+CREATE POLICY aisoc_sandbox_submissions_tenant ON aisoc_sandbox_submissions+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++-- 061 set ALTER DEFAULT PRIVILEGES so new tables pick these up, but only for+-- tables created by the role that ran it. Granting explicitly means a chain+-- replayed by a different owner still leaves the runtime role able to work.+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_sandbox_upload_policy TO aisoc_app;+ GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_sandbox_submissions TO aisoc_app;+ END IF;+END+$$;diff --git a/services/api/tests/fixtures/sandbox/README.md b/services/api/tests/fixtures/sandbox/README.mdnew file mode 100644index 000000000..d832d5927--- /dev/null+++ b/services/api/tests/fixtures/sandbox/README.md@@ -0,0 +1,43 @@+# Sandbox provider fixtures++Two kinds of payload live here and they are not equally trustworthy, so they+are labelled rather than mixed.++## Recorded++`malwareanalyzer_report_eicar.json`++Captured from `GET https://malwareanalyzer.com/v1/reports/<sha256>` on+2026-09-26, for the **EICAR anti-malware test file**, whose SHA-256 is+`275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f`. EICAR is+published by EICAR for exactly this purpose, contains no code and no customer+data, and the service already held an analysis of it.++**No file was uploaded to obtain this.** It is the response to a GET by hash.+Bulky sections that the adapter does not map (`strings`, `featureVector`,+`entropyMap`, the 51-entry `engines` array, `packer`) were removed; every field+the adapter reads is present, byte for byte as returned.++It is kept because it carries three facts no invented payload would:+`visibility: "public"`, `tlp: "clear"`, and an empty `attack` array sitting+next to `behavior.analyzed: false`. That last pairing is the case the+`UNAVAILABLE` sentinel exists for, and a hand-written fixture would have got it+wrong by writing an empty list and meaning "none".++## Synthetic++`malwareanalyzer_submit_*.json`, `malwareanalyzer_poll_*.json`,+`capev2_*.json`++Hand-written, vendor-shaped, and **not recorded**. They exist because+recording them would have required submitting a file or a URL, and no file was+uploaded to a third party at any point in this work.++The MalwareAnalyzer submit and poll shapes follow a characterisation supplied+by the maintainer, who performed one URL submission of `https://example.com/`.+They are therefore second-hand and are labelled here so nobody later mistakes+them for a capture. The CAPEv2 payloads follow the documented CAPEv2 REST API+and have not been verified against a live instance.++No fixture here contains customer data, a credential, or a real malicious+sample.diff --git a/services/api/tests/fixtures/sandbox/capev2_report_completed.json b/services/api/tests/fixtures/sandbox/capev2_report_completed.jsonnew file mode 100644index 000000000..ec8db2206--- /dev/null+++ b/services/api/tests/fixtures/sandbox/capev2_report_completed.json@@ -0,0 +1,54 @@+{+ "_synthetic": "Hand-written from the documented CAPEv2 report schema. Unverified against a live instance.",+ "info": {+ "id": 4211,+ "started": "2026-09-20T11:04:08",+ "ended": "2026-09-20T11:09:55"+ },+ "target": {+ "file": {+ "name": "invoice.doc",+ "type": "Composite Document File V2",+ "sha256": "9f2c1b7e4a6d8053f1e2c3b4a5968770d1e2f3a4b5c6d7e8f90a1b2c3d4e5f60"+ }+ },+ "malscore": 8.4,+ "signatures": [+ {+ "name": "office_macro_autoexec",+ "description": "Document runs a macro on open",+ "severity": 3,+ "confidence": 90,+ "ttp": [+ "T1204.002"+ ]+ },+ {+ "name": "injection_createremotethread",+ "description": "Injects into a remote process",+ "severity": 3,+ "confidence": 80,+ "ttp": [+ "T1055"+ ]+ }+ ],+ "network": {+ "domains": [+ {+ "domain": "payload.example.net",+ "ip": "203.0.113.24"+ }+ ],+ "hosts": [+ {+ "ip": "203.0.113.24"+ }+ ],+ "http": [+ {+ "uri": "http://payload.example.net/stage2.bin"+ }+ ]+ }+}diff --git a/services/api/tests/fixtures/sandbox/capev2_search_hit.json b/services/api/tests/fixtures/sandbox/capev2_search_hit.jsonnew file mode 100644index 000000000..6ef311405--- /dev/null+++ b/services/api/tests/fixtures/sandbox/capev2_search_hit.json@@ -0,0 +1,9 @@+{+ "_synthetic": "Hand-written from the documented CAPEv2 hash-search schema.",+ "error": false,+ "data": [+ {+ "id": 4211+ }+ ]+}diff --git a/services/api/tests/fixtures/sandbox/capev2_search_miss.json b/services/api/tests/fixtures/sandbox/capev2_search_miss.jsonnew file mode 100644index 000000000..3eadab7dd--- /dev/null+++ b/services/api/tests/fixtures/sandbox/capev2_search_miss.json@@ -0,0 +1,5 @@+{+ "_synthetic": "Hand-written. CAPE answers a miss with error:true and HTTP 200.",+ "error": true,+ "data": []+}diff --git a/services/api/tests/fixtures/sandbox/capev2_task_running.json b/services/api/tests/fixtures/sandbox/capev2_task_running.jsonnew file mode 100644index 000000000..f00218b20--- /dev/null+++ b/services/api/tests/fixtures/sandbox/capev2_task_running.json@@ -0,0 +1,10 @@+{+ "_synthetic": "Hand-written from the documented CAPEv2 task-view schema.",+ "error": false,+ "data": {+ "task": {+ "id": 4212,+ "status": "running"+ }+ }+}diff --git a/services/api/tests/fixtures/sandbox/malwareanalyzer_error_not_found.json b/services/api/tests/fixtures/sandbox/malwareanalyzer_error_not_found.jsonnew file mode 100644index 000000000..4097a30da--- /dev/null+++ b/services/api/tests/fixtures/sandbox/malwareanalyzer_error_not_found.json@@ -0,0 +1,6 @@+{+ "error": {+ "code": "not_found",+ "message": "Report not found"+ }+}diff --git a/services/api/tests/fixtures/sandbox/malwareanalyzer_poll_partial.json b/services/api/tests/fixtures/sandbox/malwareanalyzer_poll_partial.jsonnew file mode 100644index 000000000..a20e29900--- /dev/null+++ b/services/api/tests/fixtures/sandbox/malwareanalyzer_poll_partial.json@@ -0,0 +1,14 @@+{+ "_synthetic": "Hand-written. Pins that the poll response nests status under `data`.",+ "data": {+ "schemaVersion": 1,+ "uuid": "scan_0f1e2d3c4b5a6978",+ "status": "partial",+ "partial": true,+ "task": {+ "visibility": "public",+ "tier": "standard"+ },+ "page": {}+ }+}diff --git a/services/api/tests/fixtures/sandbox/malwareanalyzer_report_eicar.json b/services/api/tests/fixtures/sandbox/malwareanalyzer_report_eicar.jsonnew file mode 100644index 000000000..49299f0fd--- /dev/null+++ b/services/api/tests/fixtures/sandbox/malwareanalyzer_report_eicar.json@@ -0,0 +1,158 @@+{+ "contentHash": "275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f",+ "fileName": "eicar.com",+ "fileType": "unknown",+ "sizeBytes": 68,+ "hashes": {+ "md5": "44d88612fea8a8f36de82e1278abb02f",+ "sha1": "3395856ce81f2b7382dee72602f798b642f14140",+ "sha256": "275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f"+ },+ "visibility": "public",+ "tlp": "clear",+ "verdict": {+ "verdict": "malicious",+ "score": 100,+ "signals": [+ {+ "id": "yara:EICAR_Test_File",+ "source": "yara",+ "description": "EICAR antivirus test string",+ "weight": 0.95,+ "confidence": 0.9,+ "rule": "EICAR_Test_File"+ },+ {+ "id": "engine:clamav-daily",+ "source": "engine",+ "description": "ClamAV (daily) flagged {HEX}test.test.eicar.1040.UNOFFICIAL",+ "weight": 0.9,+ "confidence": 0.95,+ "engine": "clamav-daily",+ "rule": "{HEX}test.test.eicar.1040.UNOFFICIAL"+ },+ {+ "id": "engine:hash-threatlens",+ "source": "engine",+ "description": "Hash: MalwareAnalyser reputation flagged known-malicious-hash",+ "weight": 0.9,+ "confidence": 0.95,+ "engine": "hash-threatlens",+ "rule": "known-malicious-hash"+ },+ {+ "id": "engine:cyble-vision",+ "source": "engine",+ "description": "Cyble Vision flagged Cyble Vision: Monero Miner",+ "weight": 0.9,+ "confidence": 0.95,+ "engine": "cyble-vision",+ "rule": "Cyble Vision: Monero Miner"+ },+ {+ "id": "engine:microsoft-defender",+ "source": "engine",+ "description": "Microsoft Defender flagged Virus:DOS/EICAR_Test_File",+ "weight": 0.55,+ "confidence": 0.85,+ "engine": "microsoft-defender",+ "rule": "Virus:DOS/EICAR_Test_File"+ },+ {+ "id": "engine:emsisoft",+ "source": "engine",+ "description": "Emsisoft (Emergency Kit) flagged EICAR-Test-File",+ "weight": 0.55,+ "confidence": 0.85,+ "engine": "emsisoft",+ "rule": "EICAR-Test-File"+ },+ {+ "id": "engine:trellix-stinger",+ "source": "engine",+ "description": "Trellix Stinger (McAfee) flagged EICAR test file",+ "weight": 0.55,+ "confidence": 0.85,+ "engine": "trellix-stinger",+ "rule": "EICAR test file"+ },+ {+ "id": "engine:kaspersky-kvrt",+ "source": "engine",+ "description": "Kaspersky (KVRT) flagged EICAR-Test-File",+ "weight": 0.55,+ "confidence": 0.85,+ "engine": "kaspersky-kvrt",+ "rule": "EICAR-Test-File"+ },+ {+ "id": "engine:threatlens-community",+ "source": "engine",+ "description": "YARA: MalwareAnalyser community pack flagged TL_EICAR_Test_File",+ "weight": 0.35,+ "confidence": 0.7,+ "engine": "threatlens-community",+ "rule": "TL_EICAR_Test_File"+ }+ ],+ "attackTechniques": [],+ "fusionVersion": "3",+ "weightsVersion": "2026-07-15",+ "rulePackHash": "82ab8ba57c81cda9",+ "coverage": 0.75+ },+ "characteristics": {+ "magic": "EICAR virus test files",+ "mimeType": "text/plain",+ "metadata": {+ "FileType": "TXT",+ "FileTypeExtension": "txt",+ "MIMEType": "text/plain"+ }+ },+ "yara": [+ {+ "rule": "EICAR_Test_File",+ "tags": [+ "test"+ ],+ "meta": {+ "description": "EICAR antivirus test string",+ "severity": "info"+ },+ "matchedStrings": [+ "eicar"+ ]+ }+ ],+ "capa": [],+ "iocs": {+ "urls": [],+ "domains": [],+ "ipv4": [],+ "emails": [],+ "registryKeys": [],+ "filePaths": [],+ "bitcoin": [],+ "sha256": [],+ "sha1": [],+ "md5": [],+ "cve": [],+ "ipv6": [],+ "mutexes": []+ },+ "engineStats": {+ "total": 51,+ "flagged": 9+ },+ "behavior": {+ "analyzed": false,+ "reason": "unidentified_file_type",+ "detail": "The file type could not be identified, so no interpreter or guest could be chosen for it. Obfuscated scripts can land here; if you know what this is, resubmitting it with its original extension will route it correctly."+ },+ "attack": [],+ "dynamicDegraded": false,+ "staticDegraded": false,+ "analyzedAt": "2026-07-31T16:01:36.190Z",+ "submitter": "anonymous"+}diff --git a/services/api/tests/fixtures/sandbox/malwareanalyzer_submit_hash_hit.json b/services/api/tests/fixtures/sandbox/malwareanalyzer_submit_hash_hit.jsonnew file mode 100644index 000000000..9c777d3b5--- /dev/null+++ b/services/api/tests/fixtures/sandbox/malwareanalyzer_submit_hash_hit.json@@ -0,0 +1,8 @@+{+ "_synthetic": "Shape recorded from a live hash lookup; wrapper key added for labelling.",+ "taskId": null,+ "state": "completed",+ "contentHash": "275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f",+ "existing": true,+ "reportUrl": "/report/275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f"+}diff --git a/services/api/tests/fixtures/sandbox/malwareanalyzer_submit_url.json b/services/api/tests/fixtures/sandbox/malwareanalyzer_submit_url.jsonnew file mode 100644index 000000000..9dd712eb3--- /dev/null+++ b/services/api/tests/fixtures/sandbox/malwareanalyzer_submit_url.json@@ -0,0 +1,10 @@+{+ "_synthetic": "Hand-written from a supplied characterisation. Not a recorded capture.",+ "taskId": null,+ "kind": "url",+ "scanUuid": "scan_0f1e2d3c4b5a6978",+ "state": "queued",+ "pollUrl": "/v1/result/scan_0f1e2d3c4b5a6978",+ "resultUrl": "/v1/result/scan_0f1e2d3c4b5a6978",+ "streamUrl": "/v1/result/scan_0f1e2d3c4b5a6978/stream"+}diff --git a/services/api/tests/test_sandbox_providers.py b/services/api/tests/test_sandbox_providers.pynew file mode 100644index 000000000..2e61b19a9--- /dev/null+++ b/services/api/tests/test_sandbox_providers.py@@ -0,0 +1,288 @@+"""Each adapter maps its own payload onto the interface, and says so honestly.++Driven against recorded and synthetic vendor payloads through+``httpx.MockTransport``. Nothing here makes a network call, and nothing here+uploads a file: the recorded fixture was obtained by a GET on the EICAR test+file's hash. See ``tests/fixtures/sandbox/README.md`` for which payloads are+captures and which are hand-written.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++import httpx+import pytest+from app.services.sandbox.providers.capev2 import CapeV2Provider+from app.services.sandbox.providers.malwareanalyzer import MalwareAnalyzerProvider+from app.services.sandbox.types import UNAVAILABLE, AnalysisState, SandboxUnavailable, SandboxVerdict, Unavailable++FIXTURES = Path(__file__).parent / "fixtures" / "sandbox"+++def load(name: str) -> dict[str, Any]:+ return json.loads((FIXTURES / name).read_text())+++def transport(routes: dict[str, tuple[int, Any]]) -> httpx.MockTransport:+ """Answer by path suffix, so a changed base URL does not silently miss."""++ def handler(request: httpx.Request) -> httpx.Response:+ for suffix, (status, body) in routes.items():+ if request.url.path.endswith(suffix) or suffix in str(request.url):+ return httpx.Response(status, json=body)+ return httpx.Response(404, json={"error": {"code": "not_found", "message": "no route"}})++ return httpx.MockTransport(handler)+++def client_for(routes: dict[str, tuple[int, Any]]) -> httpx.AsyncClient:+ return httpx.AsyncClient(transport=transport(routes))+++# ---------------------------------------------------------------------------+# MalwareAnalyzer+# ---------------------------------------------------------------------------+++class TestMalwareAnalyzerMapping:+ """The pure mapping, driven on the recorded EICAR report."""++ def test_verdict_score_and_signatures_come_across(self) -> None:+ report = MalwareAnalyzerProvider.to_report(load("malwareanalyzer_report_eicar.json"))+ assert report.state is AnalysisState.COMPLETED+ assert report.verdict is SandboxVerdict.MALICIOUS+ assert report.score == 100+ assert not isinstance(report.signatures, Unavailable)+ assert len(report.signatures) == 9+ assert any(s.identifier == "yara:EICAR_Test_File" for s in report.signatures)+ assert report.sha256 == "275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f"++ def test_absent_behavioural_stage_makes_attack_unavailable_not_empty(self) -> None:+ """The case the whole sentinel exists for.++ The recorded report carries ``attackTechniques: []`` beside+ ``behavior.analyzed: false``. The techniques are missing because the+ stage never ran, so reporting "no ATT&CK techniques" would invent a+ negative about a sample nobody detonated.+ """+ payload = load("malwareanalyzer_report_eicar.json")+ assert payload["verdict"]["attackTechniques"] == []+ assert payload["behavior"]["analyzed"] is False++ report = MalwareAnalyzerProvider.to_report(payload)+ assert report.attack is UNAVAILABLE+ assert report.attack != []+ assert "behavioural analysis did not run" in report.unavailable_reasons["attack"]+ assert "unidentified_file_type" in report.unavailable_reasons["attack"]+ assert report.summary()["attack"] == "unavailable"++ def test_a_run_behavioural_stage_yields_a_real_empty_list(self) -> None:+ """Same empty array, opposite meaning, when the stage did run."""+ payload = load("malwareanalyzer_report_eicar.json")+ payload["behavior"] = {"analyzed": True}+ report = MalwareAnalyzerProvider.to_report(payload)+ assert report.attack == ()+ assert "attack" not in report.unavailable_reasons++ def test_present_but_empty_ioc_buckets_are_not_unavailable(self) -> None:+ report = MalwareAnalyzerProvider.to_report(load("malwareanalyzer_report_eicar.json"))+ # Every bucket is present in the payload and empty: the analysis looked+ # and found none, which is a result.+ assert report.iocs.urls == ()+ assert report.iocs.domains == ()++ def test_a_missing_ioc_section_is_unavailable(self) -> None:+ payload = load("malwareanalyzer_report_eicar.json")+ payload.pop("iocs")+ report = MalwareAnalyzerProvider.to_report(payload)+ assert report.iocs.urls is UNAVAILABLE+ assert "iocs" in report.unavailable_reasons++ def test_public_visibility_is_carried_through(self) -> None:+ """The fact the upload policy turns on, taken from the payload not a constant."""+ report = MalwareAnalyzerProvider.to_report(load("malwareanalyzer_report_eicar.json"))+ assert report.visibility == "public"++ def test_a_missing_score_reads_unavailable_never_zero(self) -> None:+ payload = load("malwareanalyzer_report_eicar.json")+ payload["verdict"].pop("score")+ report = MalwareAnalyzerProvider.to_report(payload)+ assert report.score is UNAVAILABLE+ assert report.score != 0+ assert report.summary()["score"] == "unavailable"+++class TestMalwareAnalyzerTransport:+ async def test_hash_hit_returns_a_report(self) -> None:+ provider = MalwareAnalyzerProvider(client=client_for({"/v1/reports/": (200, load("malwareanalyzer_report_eicar.json"))}))+ report = await provider.lookup_hash("275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f")+ assert report is not None+ assert report.verdict is SandboxVerdict.MALICIOUS++ async def test_hash_miss_is_none_not_an_exception(self) -> None:+ """A miss is an ordinary answer, so it must not look like a failure."""+ provider = MalwareAnalyzerProvider(client=client_for({"/v1/reports/": (404, load("malwareanalyzer_error_not_found.json"))}))+ assert await provider.lookup_hash("0" * 64) is None++ async def test_poll_reads_status_from_data_not_from_state(self) -> None:+ """The trap. The submit response uses ``state``; the poll response does not.++ A loop reading ``state`` here finds nothing and reports no progress+ while the scan runs perfectly normally.+ """+ payload = load("malwareanalyzer_poll_partial.json")+ assert "state" not in payload["data"]+ assert payload["data"]["status"] == "partial"++ provider = MalwareAnalyzerProvider(client=client_for({"/v1/result/": (200, payload)}))+ report = await provider.poll("scan_0f1e2d3c4b5a6978")+ assert report.state is AnalysisState.RUNNING+ assert not report.state.terminal+ assert report.verdict is UNAVAILABLE++ async def test_a_partial_flag_holds_back_a_completed_status(self) -> None:+ payload = load("malwareanalyzer_poll_partial.json")+ payload["data"]["status"] = "completed"+ payload["data"]["partial"] = True+ provider = MalwareAnalyzerProvider(client=client_for({"/v1/result/": (200, payload)}))+ assert not (await provider.poll("scan_x")).state.terminal++ async def test_url_submission_returns_the_scan_uuid_as_the_handle(self) -> None:+ provider = MalwareAnalyzerProvider(client=client_for({"/v1/submit": (202, load("malwareanalyzer_submit_url.json"))}))+ receipt = await provider.submit_url("https://example.com/")+ assert receipt.handle == "scan_0f1e2d3c4b5a6978"+ assert receipt.state is AnalysisState.PENDING++ async def test_an_unreachable_service_raises_rather_than_returning_a_report(self) -> None:+ def boom(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("connection refused")++ provider = MalwareAnalyzerProvider(client=httpx.AsyncClient(transport=httpx.MockTransport(boom)))+ with pytest.raises(SandboxUnavailable) as caught:+ await provider.lookup_hash("a" * 64)+ assert caught.value.kind == "network"++ async def test_a_401_is_reported_as_auth_not_as_a_miss(self) -> None:+ provider = MalwareAnalyzerProvider(client=client_for({"/v1/reports/": (401, {"error": {"code": "unauthorized"}})}))+ with pytest.raises(SandboxUnavailable) as caught:+ await provider.lookup_hash("a" * 64)+ assert caught.value.kind == "auth"+++class TestMalwareAnalyzerAuthentication:+ """The header is undetermined, so it is configurable and never invented."""++ def test_no_key_configured_sends_no_auth_header(self) -> None:+ provider = MalwareAnalyzerProvider(api_key="")+ assert "Authorization" not in provider._headers()++ def test_the_default_scheme_is_the_one_the_vendor_client_uses(self) -> None:+ provider = MalwareAnalyzerProvider(api_key="k-123")+ assert provider._headers()["Authorization"] == "Bearer k-123"++ def test_an_operator_can_name_a_different_header_without_a_code_change(self) -> None:+ provider = MalwareAnalyzerProvider(api_key="k-123", api_key_header="X-Api-Key")+ headers = provider._headers()+ assert headers["X-Api-Key"] == "k-123"+ assert "Authorization" not in headers++ def test_authentication_is_never_reported_as_verified(self) -> None:+ """Nobody in this repository has confirmed the scheme against a real key."""+ assert MalwareAnalyzerProvider(api_key="k-123").authentication_is_verified is False++ def test_a_key_alone_does_not_make_submissions_private(self) -> None:+ """Presence of a key is not evidence that `visibility: private` is honoured.++ Letting a key silently flip this would rewrite the sentence an+ operator agrees to before disclosing a customer file.+ """+ assert MalwareAnalyzerProvider(api_key="k").capabilities.submissions_are_public_by_default is True+ confirmed = MalwareAnalyzerProvider(api_key="k", private_submissions_confirmed=True)+ assert confirmed.capabilities.submissions_are_public_by_default is False++ def test_the_provider_is_never_local(self) -> None:+ assert MalwareAnalyzerProvider().capabilities.local is False+++# ---------------------------------------------------------------------------+# CAPEv2+# ---------------------------------------------------------------------------+++class TestCapeV2Mapping:+ """The pure mapping, on a documented CAPEv2 report schema."""++ def test_malscore_is_normalised_into_the_interface_range(self) -> None:+ """CAPE publishes 0-10. The interface publishes 0-100 and owns the range."""+ report = CapeV2Provider.to_report(load("capev2_report_completed.json"))+ assert report.score == 84+ assert report.verdict is SandboxVerdict.MALICIOUS++ def test_techniques_are_lifted_out_of_the_signatures(self) -> None:+ report = CapeV2Provider.to_report(load("capev2_report_completed.json"))+ assert not isinstance(report.attack, Unavailable)+ assert {t.technique_id for t in report.attack} == {"T1204.002", "T1055"}++ def test_a_report_with_no_malscore_has_no_derived_verdict(self) -> None:+ payload = load("capev2_report_completed.json")+ payload.pop("malscore")+ report = CapeV2Provider.to_report(payload)+ assert report.score is UNAVAILABLE+ assert report.verdict is UNAVAILABLE+ assert "publishes no verdict" in report.unavailable_reasons["verdict"]++ def test_iocs_are_mapped_from_the_network_section(self) -> None:+ report = CapeV2Provider.to_report(load("capev2_report_completed.json"))+ assert report.iocs.domains == ("payload.example.net",)+ assert report.iocs.urls == ("http://payload.example.net/stage2.bin",)+++class TestCapeV2Transport:+ async def test_a_hash_miss_is_none(self) -> None:+ """CAPE answers a miss with HTTP 200 and ``error: true``."""+ provider = CapeV2Provider("http://127.0.0.1:8090", client=client_for({"/search/": (200, load("capev2_search_miss.json"))}))+ assert await provider.lookup_hash("b" * 64) is None++ async def test_a_hash_hit_resolves_through_to_the_report(self) -> None:+ provider = CapeV2Provider(+ "http://127.0.0.1:8090",+ client=client_for(+ {+ "/search/": (200, load("capev2_search_hit.json")),+ "/view/": (200, {"error": False, "data": {"task": {"id": 4211, "status": "reported"}}}),+ "/report/": (200, load("capev2_report_completed.json")),+ }+ ),+ )+ report = await provider.lookup_hash("9" * 64)+ assert report is not None+ assert report.state is AnalysisState.COMPLETED+ assert report.verdict is SandboxVerdict.MALICIOUS++ async def test_a_running_task_carries_no_verdict(self) -> None:+ provider = CapeV2Provider("http://127.0.0.1:8090", client=client_for({"/view/": (200, load("capev2_task_running.json"))}))+ report = await provider.poll("4212")+ assert report.state is AnalysisState.RUNNING+ assert report.verdict is UNAVAILABLE++ async def test_an_unrecognised_state_is_running_not_failed(self) -> None:+ """A new CAPE release adding a state must not become a fabricated failure."""+ provider = CapeV2Provider(+ "http://127.0.0.1:8090",+ client=client_for({"/view/": (200, {"error": False, "data": {"task": {"status": "distributed"}}})}),+ )+ assert (await provider.poll("1")).state is AnalysisState.RUNNING++ async def test_a_failed_analysis_is_failed_and_still_carries_no_verdict(self) -> None:+ provider = CapeV2Provider(+ "http://127.0.0.1:8090",+ client=client_for({"/view/": (200, {"error": False, "data": {"task": {"status": "failed_analysis"}}})}),+ )+ report = await provider.poll("1")+ assert report.state is AnalysisState.FAILED+ assert report.verdict is UNAVAILABLEdiff --git a/services/api/tests/test_sandbox_upload_policy.py b/services/api/tests/test_sandbox_upload_policy.pynew file mode 100644index 000000000..1159d75a5--- /dev/null+++ b/services/api/tests/test_sandbox_upload_policy.py@@ -0,0 +1,358 @@+"""The upload policy, the hash-first sequencing, and what a failure reaches a caller as.++The three properties the plan's definition of done names are asserted by name+at the bottom of this file:++* a phishing attachment hash is looked up through the mock provider+* an upload is refused unless tenant policy allows it+* air-gap mode refuses non-local providers++Nothing here makes a network call, and nothing here uploads a file. The mock+provider records every byte handed to it, so "no upload happened" is asserted+against what the provider received rather than inferred from a return value.+"""++from __future__ import annotations++import pytest+from app.services.sandbox import (+ CONSENT_TEXT_VERSION,+ SandboxRegistry,+ analyse_file,+ analyse_url,+ consent_text_for,+ evaluate_upload,+ lookup_hash,+ sha256_of,+)+from app.services.sandbox.enrichment import enrich_file_hash+from app.services.sandbox.policy import UploadRefusal+from app.services.sandbox.providers.capev2 import CapeV2Provider+from app.services.sandbox.providers.malwareanalyzer import MalwareAnalyzerProvider+from app.services.sandbox.providers.mock import MockSandboxProvider+from app.services.sandbox.types import (+ AnalysisState,+ ProviderCapabilities,+ SandboxReport,+ SandboxUnavailable,+ SandboxVerdict,+)++SAMPLE = b"not a real sample, just bytes for a digest"+SAMPLE_SHA256 = sha256_of(SAMPLE)++HOSTED = ProviderCapabilities(name="hosted", local=False, supports_file_submission=True, submissions_are_public_by_default=True)+LOCAL = ProviderCapabilities(name="local", local=True, supports_file_submission=True)+++def registry(*providers, airgapped: bool = False) -> SandboxRegistry:+ return SandboxRegistry(list(providers), airgapped=airgapped)+++class ExplodingProvider(MockSandboxProvider):+ """A provider that is reachable for nothing, to drive the failure paths."""++ async def lookup_hash(self, sha256: str) -> SandboxReport | None:+ raise SandboxUnavailable("mock", "connection timed out", kind="network")+++# ---------------------------------------------------------------------------+# The decision+# ---------------------------------------------------------------------------+++class TestUploadDecision:+ def test_uploads_are_off_until_a_tenant_consents(self) -> None:+ decision = evaluate_upload(capabilities=HOSTED, airgapped=False, tenant_uploads_enabled=False, hash_already_known=False)+ assert decision.allowed is False+ assert decision.refusal is UploadRefusal.TENANT_NOT_CONSENTED++ def test_consent_alone_is_enough_once_given(self) -> None:+ decision = evaluate_upload(capabilities=HOSTED, airgapped=False, tenant_uploads_enabled=True, hash_already_known=False)+ assert decision.allowed is True++ def test_consent_is_per_provider_not_per_tenant(self) -> None:+ """Agreeing to a sandbox in your own rack is not agreeing to a hosted one.++ Driven here as two independent evaluations, which is the shape the+ store's ``(tenant, provider)`` primary key enforces.+ """+ local_ok = evaluate_upload(capabilities=LOCAL, airgapped=False, tenant_uploads_enabled=True, hash_already_known=False)+ hosted_not = evaluate_upload(capabilities=HOSTED, airgapped=False, tenant_uploads_enabled=False, hash_already_known=False)+ assert local_ok.allowed is True+ assert hosted_not.allowed is False++ def test_air_gap_outranks_tenant_consent(self) -> None:+ decision = evaluate_upload(capabilities=HOSTED, airgapped=True, tenant_uploads_enabled=True, hash_already_known=False)+ assert decision.allowed is False+ assert decision.refusal is UploadRefusal.AIRGAPPED++ def test_air_gap_leaves_a_local_provider_usable(self) -> None:+ decision = evaluate_upload(capabilities=LOCAL, airgapped=True, tenant_uploads_enabled=True, hash_already_known=False)+ assert decision.allowed is True++ def test_a_known_hash_short_circuits_even_a_consenting_tenant(self) -> None:+ decision = evaluate_upload(capabilities=HOSTED, airgapped=False, tenant_uploads_enabled=True, hash_already_known=True)+ assert decision.allowed is False+ assert decision.refusal is UploadRefusal.ALREADY_KNOWN+ assert decision.satisfied_by_hash_lookup is True++ def test_every_refusal_names_its_reason(self) -> None:+ for airgapped, consented, known in ((True, True, False), (False, False, False), (False, True, True)):+ decision = evaluate_upload(capabilities=HOSTED, airgapped=airgapped, tenant_uploads_enabled=consented, hash_already_known=known)+ assert decision.refusal is not None+ assert decision.reason+++class TestConsentText:+ def test_a_publishing_provider_says_public_and_says_anyone(self) -> None:+ """The operator-facing sentence, for the provider that publishes samples."""+ text = consent_text_for(HOSTED)+ assert "public disclosure" in text+ assert "readable by anyone on the internet" in text+ assert "cannot be recalled" in text++ def test_the_live_provider_declares_itself_publishing(self) -> None:+ """Not a constant in the text: read off the adapter's own capabilities.++ The recorded report from that service carries ``visibility: "public"``+ and ``tlp: "clear"``.+ """+ caps = MalwareAnalyzerProvider().capabilities+ assert caps.submissions_are_public_by_default is True+ assert "readable by anyone on the internet" in consent_text_for(caps)++ def test_a_local_provider_is_not_described_as_publishing(self) -> None:+ text = consent_text_for(CapeV2Provider("http://127.0.0.1:8090").capabilities)+ assert "readable by anyone" not in text+ assert "does not leave your infrastructure" in text++ def test_every_text_says_the_hash_is_tried_first(self) -> None:+ for caps in (HOSTED, LOCAL):+ assert "looks a file's SHA-256 up first" in consent_text_for(caps)++ def test_the_version_is_a_constant_the_store_can_record(self) -> None:+ assert CONSENT_TEXT_VERSION+++# ---------------------------------------------------------------------------+# Sequencing+# ---------------------------------------------------------------------------+++class TestHashFirst:+ async def test_a_known_hash_is_answered_without_uploading(self) -> None:+ provider = MockSandboxProvider()+ provider.seed(SAMPLE_SHA256, verdict=SandboxVerdict.MALICIOUS, score=95)+ result = await analyse_file(+ provider,+ content=SAMPLE,+ file_name="sample.bin",+ registry=registry(provider),+ tenant_uploads_enabled=True,+ )+ assert result.outcome == "known"+ assert result.uploaded is False+ assert provider.uploaded == []++ async def test_an_unknown_hash_without_consent_refuses_and_uploads_nothing(self) -> None:+ provider = MockSandboxProvider()+ result = await analyse_file(+ provider,+ content=SAMPLE,+ file_name="sample.bin",+ registry=registry(provider),+ tenant_uploads_enabled=False,+ )+ assert result.outcome == "upload_refused"+ assert result.decision is not None+ assert result.decision.refusal is UploadRefusal.TENANT_NOT_CONSENTED+ assert result.uploaded is False+ assert provider.uploaded == []++ async def test_an_unknown_hash_with_consent_uploads_once(self) -> None:+ provider = MockSandboxProvider()+ result = await analyse_file(+ provider,+ content=SAMPLE,+ file_name="sample.bin",+ registry=registry(provider),+ tenant_uploads_enabled=True,+ )+ assert result.outcome == "pending"+ assert result.uploaded is True+ assert provider.uploaded == [("sample.bin", len(SAMPLE))]++ async def test_a_caller_may_decline_to_upload_without_blaming_the_tenant(self) -> None:+ """``allow_upload=False`` is the enrichment path: lookup only."""+ provider = MockSandboxProvider()+ result = await analyse_file(+ provider,+ content=SAMPLE,+ file_name="sample.bin",+ registry=registry(provider),+ tenant_uploads_enabled=True,+ allow_upload=False,+ )+ assert result.outcome == "upload_refused"+ assert "hash lookups only" in result.detail+ assert provider.uploaded == []++ async def test_an_upload_to_a_publishing_provider_carries_a_warning(self) -> None:+ class Publishing(MockSandboxProvider):+ @property+ def capabilities(self) -> ProviderCapabilities:+ return ProviderCapabilities(name="mock", local=False, supports_file_submission=True, submissions_are_public_by_default=True)++ provider = Publishing()+ result = await analyse_file(+ provider,+ content=SAMPLE,+ file_name="sample.bin",+ registry=registry(provider),+ tenant_uploads_enabled=True,+ )+ assert result.uploaded is True+ assert any("readable by anyone" in w for w in result.warnings)+++class TestFailureIsNotACleanResult:+ async def test_a_lookup_failure_is_could_not_check_not_not_seen(self) -> None:+ result = await lookup_hash(ExplodingProvider(), SAMPLE_SHA256)+ assert result.outcome == "could_not_check"+ assert result.report is None+ assert "not a verdict" in result.detail++ async def test_a_lookup_failure_never_becomes_an_upload(self) -> None:+ """A provider that could not answer a lookup must not then receive the file."""+ provider = ExplodingProvider()+ result = await analyse_file(+ provider,+ content=SAMPLE,+ file_name="sample.bin",+ registry=registry(provider),+ tenant_uploads_enabled=True,+ )+ assert result.outcome == "could_not_check"+ assert provider.uploaded == []++ async def test_a_miss_and_a_failure_do_not_read_the_same(self) -> None:+ miss = await lookup_hash(MockSandboxProvider(), SAMPLE_SHA256)+ failure = await lookup_hash(ExplodingProvider(), SAMPLE_SHA256)+ assert miss.outcome == "not_seen"+ assert failure.outcome == "could_not_check"+ assert miss.detail != failure.detail++ async def test_enrichment_reports_an_unreachable_provider_separately(self) -> None:+ """An alert whose file could not be checked must not render as clean."""+ block = (await enrich_file_hash(SAMPLE_SHA256, registry=registry(ExplodingProvider())))["file_analysis"]+ assert block["hit"] is False+ assert block["findings"] == []+ assert block["could_not_check"]+ assert block["max_score"] is None++ async def test_enrichment_publishes_no_score_rather_than_a_zero(self) -> None:+ provider = MockSandboxProvider()+ provider.seed(SAMPLE_SHA256, verdict=SandboxVerdict.BENIGN, score=0)+ block = (await enrich_file_hash(SAMPLE_SHA256, registry=registry(provider)))["file_analysis"]+ # A measured zero is a fact and survives; an absent one would be None.+ assert block["max_score"] == 0+ assert block["hit"] is False+++# ---------------------------------------------------------------------------+# The plan's definition of done+# ---------------------------------------------------------------------------+++class TestPhaseElevenDoneWhen:+ async def test_a_phishing_attachment_hash_is_looked_up_through_the_mock_provider(self) -> None:+ provider = MockSandboxProvider()+ attachment = b"attachment bytes"+ digest = sha256_of(attachment)+ provider.seed(digest, verdict=SandboxVerdict.MALICIOUS, score=88, file_name="invoice.doc")++ block = (await enrich_file_hash(digest, registry=registry(provider)))["file_analysis"]+ assert block["hit"] is True+ assert block["findings"][0]["provider"] == "mock"+ assert block["findings"][0]["verdict"] == "malicious"+ # The whole point of the lookup: the attachment itself never moved.+ assert provider.uploaded == []++ async def test_an_upload_is_refused_unless_tenant_policy_allows_it(self) -> None:+ provider = MockSandboxProvider()+ refused = await analyse_file(+ provider,+ content=SAMPLE,+ file_name="sample.bin",+ registry=registry(provider),+ tenant_uploads_enabled=False,+ )+ assert refused.outcome == "upload_refused"+ assert provider.uploaded == []++ allowed = await analyse_file(+ provider,+ content=SAMPLE,+ file_name="sample.bin",+ registry=registry(provider),+ tenant_uploads_enabled=True,+ )+ assert allowed.outcome == "pending"+ assert provider.uploaded == [("sample.bin", len(SAMPLE))]++ async def test_air_gap_mode_refuses_non_local_providers(self) -> None:+ hosted = MalwareAnalyzerProvider()+ local = CapeV2Provider("http://127.0.0.1:8090")+ airgapped = registry(hosted, local, airgapped=True)++ assert airgapped.is_usable(hosted) is False+ assert airgapped.is_usable(local) is True+ assert airgapped.usable_names() == ["capev2"]+ # Present but excluded, with the reason, rather than silently absent.+ assert "malwareanalyzer" in airgapped.names()+ assert airgapped.default() is local++ result = await analyse_url(hosted, "https://example.com/", registry=airgapped)+ assert result.outcome == "upload_refused"+ assert result.decision is not None+ assert result.decision.refusal is UploadRefusal.AIRGAPPED++ async def test_air_gap_refuses_a_hosted_upload_even_with_consent(self) -> None:+ hosted = MalwareAnalyzerProvider()+ result = await analyse_file(+ hosted,+ content=SAMPLE,+ file_name="sample.bin",+ registry=registry(hosted, airgapped=True),+ tenant_uploads_enabled=True,+ )+ # The lookup itself is refused first, because the outbound guard+ # enforces air-gap at the transport. Either way no file moves.+ assert result.outcome in ("could_not_check", "upload_refused")+ assert result.uploaded is False+++class TestRegistryDefaults:+ def test_a_local_provider_wins_the_default_over_a_hosted_one(self) -> None:+ hosted = MalwareAnalyzerProvider()+ local = CapeV2Provider("http://127.0.0.1:8090")+ assert SandboxRegistry([hosted, local]).default() is local++ def test_the_mock_is_only_the_default_when_nothing_else_is_configured(self) -> None:+ mock = MockSandboxProvider()+ assert SandboxRegistry([mock]).default() is mock+ cape = CapeV2Provider("http://127.0.0.1:8090")+ assert SandboxRegistry([mock, cape]).default() is cape++ def test_the_mock_knows_nothing_until_a_test_seeds_it(self) -> None:+ """A first run must report "not seen", never a fabricated clean verdict."""+ assert MockSandboxProvider()._known == {}++ def test_a_mock_report_is_labelled_synthetic(self) -> None:+ report = MockSandboxProvider().seed(SAMPLE_SHA256)+ assert report.unavailable_reasons["is_synthetic"]+ assert report.state is AnalysisState.COMPLETED