Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(white-label): brand every surface the docs claim, narrow the two that cannot be (#1294)
Beenu Arora874bcdc7453d
diff --git a/.github/workflows/white-label-live.yml b/.github/workflows/white-label-live.ymlnew file mode 100644index 000000000..d66c18499--- /dev/null+++ b/.github/workflows/white-label-live.yml@@ -0,0 +1,205 @@+# White-label, through the real app and real Postgres.+#+# Fix pass 4.3.+#+# Why live and not offline+# ------------------------+# Three of this item's properties cannot be answered anywhere else.+#+# The brand asset route answering 401 to the exact request an `<img>` makes+# is a property of the real route with its real auth dependency. The console+# component test can show the `src` is an object URL; only this can show why+# it has to be.+#+# A `report_templates` row stores its recipients in a Postgres `text[]`,+# which SQLite cannot bind, so the delivery branch of `run_once` never+# executes in the offline suite -- which is also how both report workers came+# to write a `status` value the column's CHECK refuses, raising on commit on+# every real deployment while every offline suite passed. The offline suites+# build their tables from the ORM model, and the model declares no CHECK.+#+# `ENVIRONMENT=test`, never `development`: `development` is in+# `AUTH_BYPASS_ENVIRONMENTS`, so an uncredentialed request resolves to a demo+# administrator -- which would turn the suite's first assertion, whose whole+# subject is what happens *without* a credential, into a test of nothing.+#+# No `paths:` filter. Branding is resolved by workers, two renderers, a route+# and the console shell; a change in any of them can reach it, and a filtered+# gate is absent exactly when something unexpected moved.+name: White-label (live)++on:+ push:+ branches: [main]+ pull_request:+ workflow_dispatch:++concurrency:+ group: white-label-live-${{ github.ref }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.sha }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++permissions:+ contents: read++jobs:+ white-label-live:+ name: A white-labelled organisation's reports and assets carry its brand+ runs-on: ubuntu-latest+ timeout-minutes: 20++ services:+ postgres:+ image: public.ecr.aws/docker/library/postgres:16-alpine+ env:+ POSTGRES_USER: aisoc+ POSTGRES_PASSWORD: aisoc_ci_only+ POSTGRES_DB: aisoc+ ports: ["5432:5432"]+ options: >-+ --health-cmd "pg_isready -U aisoc"+ --health-interval 5s+ --health-timeout 5s+ --health-retries 20++ env:+ # The runtime role, not the owner. A superuser ignores every RLS policy+ # even under FORCE ROW LEVEL SECURITY, so running as the owner would+ # pass for a reason no deployment enjoys.+ WL_DSN: postgresql+asyncpg://aisoc_app:aisoc_app_ci_only@localhost:5432/aisoc+ PGPASSWORD: aisoc_ci_only+ ENVIRONMENT: test+ OTEL_SDK_DISABLED: "true"++ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7++ - uses: actions/setup-python@e9d6f990972a57673cdb72ec29e19d42ba28880f # v6+ with:+ python-version: "3.11"++ - name: Install api from its lockfile+ working-directory: services/api+ run: |+ set -euo pipefail+ sudo apt-get update -qq && sudo apt-get install -y -qq libxmlsec1-dev pkg-config+ python -m pip install --quiet --upgrade pip "poetry==2.4.1"+ poetry config virtualenvs.create false+ poetry install --no-root --no-interaction+ python -m pip install --quiet pytest pytest-asyncio++ - name: Apply every migration, in order+ run: |+ for f in services/api/migrations/*.sql; do+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -f "$f"+ done++ - name: Give the runtime role its password+ run: |+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "ALTER ROLE aisoc_app WITH PASSWORD 'aisoc_app_ci_only';"+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "GRANT USAGE ON SCHEMA public TO aisoc_app;"++ # The renderers, offline. These assert on the HTML and the markdown that+ # become the PDFs, so they do not need the native WeasyPrint stack.+ - name: Resolver, renderers and the scheduled artefacts+ working-directory: services/api+ run: >-+ python -m pytest+ tests/test_branding.py+ tests/test_white_label_notifications.py+ tests/test_white_label_scheduled_reports.py+ tests/test_white_label_investigation_summary.py+ tests/test_report_artefact_status_vocabulary.py+ -v --tb=short++ - name: The asset route, the scheduled email and the closed summary+ working-directory: services/api+ env:+ ISOLATION_WHITE_LABEL_DSN: ${{ env.WL_DSN }}+ DATABASE_URL: ${{ env.WL_DSN }}+ run: python -m pytest ../../tests/isolation/test_white_label_live.py -v --tb=short++ # A skip in a live job is a failure. `pytest.importorskip` and a missing+ # DSN both turn "this never ran" into a green run, which is the shape+ # that let the public scoreboard sit ten weeks stale while its workflow+ # reported success.+ - name: The live suite ran rather than skipped+ working-directory: services/api+ env:+ ISOLATION_WHITE_LABEL_DSN: ${{ env.WL_DSN }}+ DATABASE_URL: ${{ env.WL_DSN }}+ run: |+ set -euo pipefail+ python -m pytest ../../tests/isolation/test_white_label_live.py -q 2>&1 | tee /tmp/wl.txt+ if grep -qE "[0-9]+ skipped" /tmp/wl.txt; then+ echo "FAIL: the live white-label suite skipped. A live job that skips has proved nothing."+ exit 1+ fi++ # The negative control.+ #+ # Putting the platform name back on the scheduled report's envelope must+ # make the suite go red. Without it, "the envelope said Acme Shield"+ # would pass equally well against a suite that never read the envelope.+ - name: The suite fails when the envelope carries the platform name again+ working-directory: services/api+ env:+ ISOLATION_WHITE_LABEL_DSN: ${{ env.WL_DSN }}+ DATABASE_URL: ${{ env.WL_DSN }}+ run: |+ set -euo pipefail+ cp app/workers/report_scheduler.py /tmp/report_scheduler.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/workers/report_scheduler.py")+ s = p.read_text()+ needle = 'subject=f"[{branding.product_name}] {artefact.title}",'+ if needle not in s:+ print("negative control could not find the branded subject to revert; it has "+ "been reshaped and this control is no longer proving anything")+ sys.exit(1)+ p.write_text(s.replace(needle, 'subject=f"[AiSOC] {artefact.title}",', 1))+ PY+ if python -m pytest ../../tests/isolation/test_white_label_live.py -q >/dev/null 2>&1; then+ cp /tmp/report_scheduler.bak app/workers/report_scheduler.py+ echo "FAIL: the suite passed with the platform name back on the envelope."+ exit 1+ fi+ cp /tmp/report_scheduler.bak app/workers/report_scheduler.py+ echo "OK: reverting the branded subject makes the suite fail, as it must."+ python -m pytest ../../tests/isolation/test_white_label_live.py -q++ # The second negative control, for the defect this item's live suite+ # surfaced rather than the one it was written for. Restoring the status+ # value the column refuses must break the scheduled-report case, because+ # a worker that cannot commit cannot deliver a branded anything.+ - name: The suite fails when the worker writes a status the column refuses+ working-directory: services/api+ env:+ ISOLATION_WHITE_LABEL_DSN: ${{ env.WL_DSN }}+ DATABASE_URL: ${{ env.WL_DSN }}+ run: |+ set -euo pipefail+ cp app/workers/report_scheduler.py /tmp/report_scheduler.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/workers/report_scheduler.py")+ s = p.read_text()+ if 'status="completed",' not in s:+ print("negative control could not find the status write to revert")+ sys.exit(1)+ p.write_text(s.replace('status="completed",', 'status="generated",', 1))+ PY+ if python -m pytest ../../tests/isolation/test_white_label_live.py -q >/dev/null 2>&1; then+ cp /tmp/report_scheduler.bak app/workers/report_scheduler.py+ echo "FAIL: the suite passed with a status the CHECK constraint refuses."+ exit 1+ fi+ cp /tmp/report_scheduler.bak app/workers/report_scheduler.py+ echo "OK: an unwritable artefact makes the suite fail, as it must."++ - name: Branding and metering declarations still hold their shape+ run: |+ python3 scripts/check_whitelabel_metering.py --self-test+ python3 scripts/check_whitelabel_metering.pydiff --git a/FIX_PASS_PROGRESS.md b/FIX_PASS_PROGRESS.mdindex 56dbd1b2a..63a565254 100644--- a/FIX_PASS_PROGRESS.md+++ b/FIX_PASS_PROGRESS.md@@ -105,12 +105,14 @@ conditional `numpy` pins collide into an unresolvable install. Parse with- Two of the three defects did **not** reproduce: the console fragment consumer (`authApi.completeSsoHandoff`) and the login-screen SSO entry both landed in v17.1.0. Neither was covered by a test, so six now pin them. The third reproduced exactly as written — `_saml_settings()` read its IdP trust anchor from `SAML_IDP_*` while the connection's own `metadata_url` / `metadata_xml` were read by nothing, so a SAML login redirected to the environment's IdP and a correctly signed assertion came back `invalid_response`. Fixed in `app/auth/saml_metadata.py`; the ACS also now lands on `/login?next=` with both tokens, because the old RelayState redirect lost the fragment to the console's own auth guard. Driven end to end against real Postgres and a real signed assertion in `sso-live.yml`. **Still `[~]`**: the containerised-IdP leg (`sso-live.yml :: keycloak-oidc`) has never been observed to pass — no container runtime would start where it was written — so the claim row is PARTIAL, not GATED.- [x] **4.2** Console MFA- Reproduced first: ten of eleven assertions against the real login route and real Postgres failed with `{"detail":"Not Found"}` — the surface did not exist. TOTP (RFC 6238, in-tree, pinned to the spec's own vectors rather than to a round trip), ten single-use recovery codes, a vault-encrypted secret, a `last_used_step` high-water mark so a code cannot be replayed inside its own 30-second window, per-tenant enforcement with **no backfill row** (absence means not required), and audited enrolment, disable, recovery-code use, policy change and administrative reset. A correct password for an enrolled account now answers **202** with a challenge instead of a session — 202 rather than a widened 200 body, because `access_token` is a required field and making it optional breaks every generated client. An unenrolled member of a newly-enforcing tenant enrols from that challenge rather than being locked out; the trade-off is stated in the module and the docs. Migration `096`. 28 offline tests, 13 live, and a CI negative control that deletes the challenge branch and requires the suite to go red.-- [ ] **4.3** White-label reaches every surface it claims+- [x] **4.3** White-label reaches every surface it claims+ - Each of the eight bullets was checked against `main` first. Six were real and are now branded: both report workers (a reproduce-first test showed the scheduled digest rendering unbranded), the investigation summary, the replay report, email approvals — where `send_approval_email` had **no caller at all**, so the signed fallback was unreachable until `approval_delivery` wired it — the Slack and Teams prompts, and the sidebar logo, whose `<img>` could not send the bearer header the asset route requires, so its `src` no longer points there and a test asserts it. The browser tab was already branded client-side by `BrandedDocumentTitle`; the root metadata stays the platform default because SSR has no credential. **Two were narrowed with the reason recorded rather than built.** The sign-in page cannot be branded today: `GET /api/v1/branding` resolves the organisation from the caller's credential, there is none yet on that page, and nothing maps a hostname to an organisation — `organizations` has a slug and a name and no domain — so baking one name in would be wrong for every organisation on the deployment except one *while looking configured*, which is worse than the platform name. `services/actions` had no read path to branding at all and gets one that reads **only `product_name`**, mirroring the vault split; it never raises, because a lookup that failed would take down the approval prompt it decorates, and an approval nobody sees is worse than one under the wrong name. Found on the way: neither report worker could store an artefact on **real Postgres** — a status-vocabulary mismatch invisible to the test double. `white-label-live.yml` runs the live suite with two negative controls.- [x] **4.4** Metering counts what happened- All five bullets fixed rather than narrowed. `triages_model` and `triages_deterministic` read `investigation_runs.model_used` — the path auto-triage records for itself — instead of `alerts.ai_summary`/`ai_score`, which `persist_auto_triage` writes from one statement on **both** paths, so a deployment with no model configured reported 100% AI triage; `investigations` now excludes auto-triage runs, which had made it a second alert count wearing a different label; `events_ingested` is a real ClickHouse meter, grouped per day in one scan, reported as **not measured** rather than `0` when the lake is absent *or* deployed-and-unreachable; actions split into `automatic` / `human_gated` / `tier_unrecorded` behind migration `095`, which also adds `approval_tier` and repairs a `status` column that had held `'ActionStatus.COMPLETED'` since the table was added — the repr of a `(str, Enum)` member, which no query and no index could ever match; and `GET /usage/organization/export.csv` exports a portfolio, scoped by `resolve_portfolio_scope` and refusing a non-member rather than quietly falling back to their own tenant. The audit found one defect the branch had introduced: the path meters discriminated on `model_used <> 'kafka:auto_triage:deterministic'`, which reads as "the model path" only while `deterministic` is the sole alternative, and the worker stamps **four** tiers — `memory` (institutional-memory suppression) and `cached` (a deduplicated replay) place no LLM call and were both counted as AI triages, by the meter *and* by the `triages_per_month` quota that shares the definition. That is the same false sentence reached by another route, and it was live on `main`. `MODEL_TIERS`/`NON_MODEL_TIERS` now enumerate the vocabulary, and an AST pin reads the worker's own tier literals and fails on any tier no meter classifies — the fixture could not have caught it, having seeded only the two tiers that already worked. 35 offline tests, every assertion against rows counted independently in the test; the two new cases were confirmed to fail against the pre-fix predicate and the pin to fail with a tier removed. `tests/isolation/test_usage_lake_meter_live.py` was run against a real ClickHouse carrying the shipped `001_init.sql` — six cases pass, and dropping the tenant predicate makes the suite red, as its CI negative control requires.- [x] **4.5** SCIM live coverage and the console token claim- Both halves built, and the doc was made true rather than narrowed. `tests/isolation/test_scim_live.py` now drives 24 cases through `create_application()` against real Postgres: PATCH in both providers' dialects (Okta's pathless `replace`, Entra's `"False"` string and its boolean), rename, group membership add and remove in both dialects, group-name-to-role resolution, and deprovisioning proved by its consequences — API keys revoked, the session revocation time stamped, `DELETE` deactivating rather than erasing, and reactivation **not** restoring the revoked keys. Four tenant-isolation and unauthenticated negative controls sit alongside, so an empty table cannot pass for isolation. Run here against a live Postgres with all 110 migrations applied: 24 passed. It cannot pass vacuously — `ISOLATION_REQUIRE_LIVE` raises at import when the DSN is absent, which is a collection error and red where a skipped module is not (verified: red with the flag set and no DSN, 24 clean skips in the offline collection job), and `scim-live.yml` reads the counts out of the report afterwards and fails on fewer than 20 executed or any skip. `ENVIRONMENT` is `test`, never `development`, which is in `AUTH_BYPASS_ENVIRONMENTS` and would have resolved an uncredentialed request to a demo admin inside the one suite whose purpose is proving the tenant comes from the credential; heavy imports sit inside fixtures. The console claim is now real: `ScimTokensPanel` creates, rotates, revokes and lists against the four `/api/v1/scim-tokens` routes that already existed and that nothing under `apps/web/src` had ever referenced — six component tests, and `check_scim_contract.py` checks **both** directions, failing on a doc promising a panel that is unwired and on a panel the doc does not mention. The audit found the branch's `check_test_discovery.py` redirection fix shipped with no self-test case, so the gate still proved only the syntaxes it handled before; eight cases now assert the reader directly across all seven redirection forms plus a control that a real path following a redirection is still read, which is what stops the new clause silently dropping arguments.-- [ ] **4.6** Maturity evidence names tests that exercise the row+- [x] **4.6** Maturity evidence names tests that exercise the row+ - The row read `SCIM 2.0, white-label, usage metering` and named one test, `tests/isolation/test_scim_live.py`, which exercises neither of the other two — and the gate reported **OK** on it for four releases. The reason is structural and is the part worth keeping: `_match_key` matches a row's capability cell on a **prefix**, so the first capability's genuine evidence satisfied the lookup and the other two inherited a pass they never earned. Checking that each row's evidence exercises it cannot catch this on its own, because a bundled row has only one evidence entry to check; the row has to be split first. Now three rows with three entries: SCIM keeps `scim-live.yml`, white-label takes `white-label-live.yml` (two negative controls), and metering takes `lake-live.yml` — whose evidence string was also **wrong**, not merely missing, since that suite runs on live ClickHouse and the shared cell said Postgres. `bundles_several_capabilities()` now refuses a cell that lists several capabilities, distinguishing a list from a subordinate clause so `Alert-triggered playbooks, with a durable approval pause` still passes; its self-test asserts both directions, including the exact string that defeated the gate. Splitting one row into three pushed the README to 252 against its binding 250-line cap, so a section was **displaced rather than squeezed**: `## Try it without connecting anything` was a heading over a single sentence that now sits at the end of Quick start, where it reads the same and costs two fewer lines.## Wave 5: Hunting, intel, sandbox and operations wiringdiff --git a/README.md b/README.mdindex dfe2ad1c8..1dc1c01f2 100644--- a/README.md+++ b/README.md@@ -79,8 +79,6 @@ right if you connect a source through the API. The spec is[`docs/openapi.yaml`](docs/openapi.yaml) — interactive docs are off in this production-class stack.Stuck? `make doctor`, which on a host where you have not run `make up` yet says exactly that.-## Try it without connecting anything-Press **Load sample data** in the wizard. Five scenarios take the same ingest path a real connector uses — not inserted rows — so watching them become alerts means watching the pipeline work. They span low to critical on purpose, because a first run where everything is a crisis teaches you nothing about how triage separates signal from routine. They are attributed to `AiSOC` in the source column, refuse to load into a tenant that already has real alerts, and do **not** mark setup complete. ([what each step proves](https://beenuar.github.io/AiSOC/docs/console/getting-started)) For the larger fixed corpus used by demos and evals, `make demo` loads a **synthetic** dataset — the pipeline shape, never a benchmark, a customer or an incident. Every row is `is_synthetic = true` and labelled in the console.## Connect real data@@ -200,7 +198,9 @@ Agents triage alerts and investigate incidents. What they can and cannot do:| Event lake + hunting (ClickHouse) | Stable | Live ClickHouse on the shipped DDL, with a negative control | Yes, `full` profile || Retro-hunts when new intel arrives | Stable | Live ClickHouse + Kafka with the flag on, with a negative control | Opt-in, `full` profile || 68-hunt YAML library, compiled against tenant events in the lake | Stable | Live ClickHouse: scheduled hunts read tenant data and refuse to fall back to the fixture; all 114 field names the corpus filters on compile, via a lake column or the stored payload | Yes, `full` profile |-| SCIM 2.0, white-label, usage metering | Stable | Live Postgres through the real app, with a negative control | Yes |+| SCIM 2.0 provisioning | Stable | Live Postgres through the real app: PATCH in both providers' dialects, group membership, deprovisioning proved by its consequences, with a negative control | Yes |+| White-label branding | Stable | Live Postgres: the scheduled report and its covering email carry the organisation's brand, with two negative controls | Yes |+| Usage metering | Stable | Live ClickHouse on the shipped DDL, with a negative control that makes an unscoped meter fail | Yes || Entity graph (Neo4j) | Stable | Live Neo4j against the production reader, with a negative control | Yes, `full` profile || Governed response actions | Stable | Live socket: permits, refuses, never leaks a refusal, with a negative control | Human-approved only || Alert-triggered playbooks, with a durable approval pause | Stable | Live Postgres: suspend, restart, resume, expiry, with a negative control | Yes — three opt-ins deep, preview by default |diff --git a/apps/docs/docs/operations/white-label.md b/apps/docs/docs/operations/white-label.mdindex b0bd3e4ed..24a4bcb67 100644--- a/apps/docs/docs/operations/white-label.md+++ b/apps/docs/docs/operations/white-label.md@@ -21,8 +21,17 @@ organisation's portfolio, plus the organisation's own staff console.| Replay evaluation report (PDF) | Product name, logo, primary colour, accent colour, footer, support link || Investigation summary (PDF) | Product name, primary colour, footer, support contact || Email approvals | Product name in the subject and body, `sender_name` as the From display name, primary and accent colours, footer, support contact |+| Scheduled report email | Product name in the subject, `sender_name` as the From display name || Usage CSV export | The organisation named in the header block |+The executive digest is branded on both paths that produce it: the+interactive `GET /api/v1/reports/digest`, and the weekly worker that mails+it out every Monday. They are separate code paths, and for a while only the+first of them resolved branding.++As with email approvals below, the `From` **address** on a scheduled report+is the relay's own and is not white-labelled. Only the display name changes.+Branding resolves field by field. An organisation that sets a product nameand no colours renders its name against the platform palette, rather thanlosing the one field it configured.diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex bbcc6e6db..fcb3a56e6 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -227,7 +227,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| The SCIM surface serves what its discovery documents advertise, and audits every write | `plans/aisoc_gap_closure_plan.plan.md` (13.1); `apps/docs/docs/operations/scim.md` (What is implemented) | `isolation.yml` (`check_scim_contract.py` reads `ServiceProviderConfig` and the route table and compares them in both directions, so a capability advertised with no route **and** a route no document advertises both fail; asserts each of the eight mutating handlers still reaches the audit helper; asserts `main.py` includes the router, since a router nobody mounts serves nothing) + `ci.yml` api job (`test_scim_mounted.py` reads `app.openapi()` from the real application and refuses an empty inventory before asserting membership, because `include_router` does not populate `app.routes` on the pinned FastAPI) + `scim-live.yml` (`TestPatchInBothProvidersDialects` and `TestGroupMembershipInBothProvidersDialects` run Okta's and Entra's PATCH and membership shapes against real Postgres, asserting on `users.is_active` and on `aisoc_scim_group_members` rather than on the response; the vendor payloads are pinned against the offline suite's copies so the two cannot drift; the job refuses to collect when `ISOLATION_REQUIRE_LIVE` is set without a DSN, and a following step reads the JUnit counts and fails on any skip, because a suite that skipped every case exits 0) | core | GATED | Filtering implements one `attribute eq "value"` comparison and refuses the rest: a dropped filter would return every principal in the tenant, which a provider reads as "this user already exists" || No principal can confer a role, scope or organisation membership beyond the authority it was itself admitted on, and the wildcard roles are unreachable from any request | `apps/docs/docs/operations/security.md` (Role grants are scoped to the granter); GHSA-pm3f-h6gc-rvgp; GHSA-4gx4-x7gm-4xq8 | `isolation.yml` (`check_role_grant_scope.py` asks of every handler binding a request model that declares `role`, `org_role`, `granted_role`, `scopes`, `role_id` or `permission_ids` whether it reaches `app.core.role_grants`, checks each waiver still covers a live handler, and derives the refused set from `ROLE_PERMISSIONS` so a role declared with the wildcard later is un-grantable the moment it is declared; and asks of every call to `authorize_role_grant`, `authorize_role_change` or `authorize_permission_grant` whether it passes `granter_permissions=`, since reaching the chokepoint while handing it the caller's *static* role measures the grant against an authority the caller was not admitted on; seven injected drifts prove it fails, and run against the pre-fix tree it names all nine handlers and all six under-authorised call sites) + `ci.yml` api job (`test_role_grant_scope.py` calls the shipped handlers and asserts both directions per call site — the escalating request is refused and nothing is written, a legitimate grant still lands; 16 of its 28 tests fail against the vulnerable tree, every one of them for the grant succeeding rather than for a missing symbol) + `ci.yml` api job (`test_role_grant_effective_permissions.py` drives the same handlers with a principal whose database permissions are narrower than its static role; 7 of its 10 tests fail against the pre-fix tree, each for the escalation landing, and the other 3 hold the positive direction so a tenant with no RBAC rows keeps conferring what its role confers) | core | GATED | Scoped to grants a *request* makes. `scripts/bootstrap_admin.py` still mints a wildcard role out of band with database credentials, which is deliberate: it is the only path left, and it is not reachable over HTTP || An uploaded brand asset cannot execute, and is never fetched from a third party | `plans/aisoc_gap_closure_plan.plan.md` (13.2); `apps/docs/docs/operations/white-label.md` (SVG uploads are sanitised) | `ci.yml` api job (`test_svg_sanitizer.py`, 29 cases written as attacks rather than round trips: `<script>`, a namespace-qualified `<svg:script>` that a bare-name comparison misses, event handlers, `<foreignObject>` in well-formed XML, `<animate attributeName="href">`, `<set>`, an external `<use xlink:href>`, a remote `<image>`, `@import`, a `fill="url(https://…)"` paint server, `javascript:` in an `<a>`, a billion-laughs DTD, an XXE entity and a bare DOCTYPE. A benign logo is asserted to survive **intact**, because a sanitiser that removes everything is safe and useless) + `isolation.yml` (`check_whitelabel_metering.py` refuses any script-capable element or `on*` attribute entering the allowlist, and refuses a remote scheme in the logo reference; proven able to fail by injecting each) | core | GATED | Allowlist rather than denylist: a denylist of `<script>` passes while `<foreignObject>` renders arbitrary HTML. DTD and entity declarations are refused on a byte scan before parsing, which removes the expansion class rather than bounding it |-| A white-labelled organisation's console and PDF report carry its branding | `plans/aisoc_gap_closure_plan.plan.md` (13.2, Done when); `apps/docs/docs/operations/white-label.md` | `ci.yml` api job (`test_branding.py` renders the digest HTML that becomes the PDF and asserts the product name, the palette and the logo are present **and** that the platform wordmark is gone, since a report showing both is co-branded by accident; a separate case asserts the rendered report contains **no** external URL at all) + `web` job (`SidebarBranding.test.tsx` renders the real console shell against a branded API response and reads the wordmark out of the DOM, mocking the API client rather than the hook so the wiring is inside the test) | core | GATED | The PDF is this HTML through WeasyPrint, so asserting on the HTML asserts on the PDF without requiring the native stack in CI. Email approvals and ChatOps read the same resolved `sender_name` and are **not** covered end to end; the doc says so rather than implying they are |+| A white-labelled organisation's console and PDF report carry its branding | `plans/aisoc_gap_closure_plan.plan.md` (13.2, Done when); `apps/docs/docs/operations/white-label.md` | `ci.yml` api job (`test_branding.py` renders the digest HTML that becomes the PDF and asserts the product name, the palette and the logo are present **and** that the platform wordmark is gone, since a report showing both is co-branded by accident; a separate case asserts the rendered report contains **no** external URL at all) + `web` job (`SidebarBranding.test.tsx` renders the real console shell against a branded API response and reads the wordmark out of the DOM, mocking the API client rather than the hook so the wiring is inside the test) + `white-label-live.yml` (fix pass 4.3 — against real Postgres: the brand asset route answers 401 to the exact request an `<img>` makes and 200 to a credentialed fetch, the scheduled report's covering email carries the resolved product name and `sender_name`, and `POST /investigations/{id}/close` stores a branded summary. Two negative controls, one restoring the platform name on the envelope and one restoring a `status` value the column's CHECK refuses, each proven to fail before being written into the job) + `ci.yml` api job (`test_white_label_scheduled_reports.py` for the Monday digest worker, `test_white_label_investigation_summary.py` for the summary body) | core | GATED | The PDF is this HTML through WeasyPrint, so asserting on the HTML asserts on the PDF without requiring the native stack in CI. The note here used to say email approvals and ChatOps "read the same resolved `sender_name`" and were not covered end to end. Email approvals do read it and now are covered (`test_white_label_notifications.py`). **ChatOps does not read it at all**: the prompt is posted by `services/actions` and the two bot services, none of which can reach the branding store, so this row never covered them and no longer claims to. That limit is stated in the doc's "What is not branded" section rather than left as an implied gap || Usage metering equals the rows it summarises | `plans/aisoc_gap_closure_plan.plan.md` (13.3, Done when); `apps/docs/docs/operations/usage-metering.md` (Checking the numbers) | `ci.yml` api job (`test_usage_metering.py`, 32 cases. Every assertion counts rows **independently in the test** and compares, rather than comparing a producer against a copy of itself, which is how two console figures in this repository were wrong on real data while passing. The daily series summed is asserted equal to one query over the whole window; an alert seeded at exactly midnight is asserted counted once; another tenant's rows sit inside the window and are asserted never counted; `triages_model` + `triages_deterministic` + `investigations` is asserted to equal the **run** count exactly, and the three action tiers to equal the action count, so nothing is unaccounted for or double-counted; the quota's own count and the meter are asserted to agree on the same rows) | core | GATED | Computed from source tables on request rather than kept in a counter table. A counter can only be tested against itself; a query cannot drift from the rows because it is the rows. Equalling the rows was never sufficient on its own: `triages_model` satisfied it for four releases while reading `alerts.ai_summary`, which the **deterministic** path writes too, so a deployment with no model reported 100% AI triage. The meters read `investigation_runs.model_used`, the path auto-triage records for itself, pinned against that producer by an AST check — including the *vocabulary*, because the worker stamps four tiers and discriminating on "not the deterministic literal" counted institutional-memory suppression and deduplicated replays as AI triages, reaching the same false sentence by another route. `GET /usage/reconciliation` exposes the same comparison so an operator can run it on their own data || Metering reports "not measured" rather than zero, and carries no pricing logic | `plans/aisoc_gap_closure_plan.plan.md` (13.3, "No pricing logic"); `apps/docs/docs/operations/usage-metering.md` (What is not measured) | `ci.yml` api job (`test_usage_metering.py::TestHonesty` asserts `events_ingested` is named by `unmeasured()` with a reason on a deployment with no lake, and is **not** a Postgres meter, so it can never be reported as a number by one; the matching case asserts the gap disappears on a deployment that *can* take it, since announcing "not measured" over a running lake is the same lie reversed; asserts no meter key, label or SQL carries pricing vocabulary; asserts every meter binds its tenant as a parameter and formats nothing) + `isolation.yml` (`check_whitelabel_metering.py` re-checks all three against the declarations and was proven able to fail by removing a tenant binding) | core | GATED | The pricing check reads key, label and SQL only. `llm_cost_usd` is a measured provider charge and its description has to be able to say "not a price"; a gate forbidding the word would forbid the disclaimer with it. The lake meter itself is unit-covered on both branches; **it has not been run against a live ClickHouse**, and `lake-live.yml` is where that would land || Auto-triage reads the tenant's knowledge-base runbooks and cites the chunks it was given | `apps/docs/docs/console/triage-context.md` (Knowledge-base runbooks) | `ci.yml` agents job (`test_triage_knowledge_base.py`: the block reaches the prompt ahead of the telemetry, every chunk carries a marker resolving to a document id **and chunk index**, the prompt names the markers the model may cite, and a marker no retrieved chunk carries is reported on the verdict's basis rather than left reading like one that resolves; an empty retrieval renders nothing at all, because "Runbooks: none" is a claim about the tenant) + `ci.yml` api job (`test_kb_triage_retrieval_route.py`: service-token only, a valid console session refused, tenant and query bound rather than interpolated) | core | GATED | The agents service had never read the knowledge base. Retrieval is the API's own full-text query and ranking rather than a second implementation, so a chunk triage was given is one an analyst searching by hand would have found |diff --git a/scripts/check_ci_install_parity.py b/scripts/check_ci_install_parity.pyindex c547e2ead..9b629558b 100644--- a/scripts/check_ci_install_parity.py+++ b/scripts/check_ci_install_parity.py@@ -524,6 +524,47 @@ def suite_runner(line: str) -> str:return f".venv-{match.group('service')}" if match else "default"+#: Where pytest's own arguments stop and the shell's resume. Everything from+#: the first of these onward belongs to a redirection or the next command in+#: a pipeline, not to pytest.+_SHELL_BREAK = re.compile(r"^(?:\||\|\||&&|;|\)|>>?|<|&>|[0-9]+>&?[0-9]?)")+++def _pytest_arguments(args: str) -> list[str]:+ """The arguments pytest actually receives, stopping at the shell.++ ``python -m pytest tests/isolation/test_white_label_live.py -q 2>&1 |+ tee /tmp/wl.txt`` credits pytest+ with six arguments if you simply split on whitespace, and ``/tmp/wl.txt``+ then satisfies every test for a directory path: it does not start with a+ dash, does not end in ``.py``, and contains a slash. The gate concluded+ that a job naming one file ran a service's **whole** suite, and demanded+ its entire dependency set -- thirteen findings from one ``tee``.++ A redirection target is consumed the same way, whether it is attached+ (``>/dev/null``) or detached (``> /dev/null``), since a detached target+ would otherwise read as a path in its own right.+ """+ out: list[str] = []+ tokens = args.split()+ index = 0+ while index < len(tokens):+ token = tokens[index]+ if _SHELL_BREAK.match(token):+ # A bare operator takes its target with it; an attached one+ # already carries it.+ if token in {">", ">>", "<", "&>"} or re.fullmatch(r"[0-9]+>&?", token):+ index += 1+ # Anything after a pipe or a separator is a different command.+ if token.startswith(("|", "&&", ";")) or token == ")":+ break+ index += 1+ continue+ out.append(token)+ index += 1+ return out++def whole_suite_targets(run: str, working_directory: str) -> set[str]:"""Services whose *whole* suite this command collects.@@ -546,7 +587,7 @@ def whole_suite_targets(run: str, working_directory: str) -> set[str]:continuedirectories = [arg- for arg in match.group("args").split()+ for arg in _pytest_arguments(match.group("args"))if not arg.startswith("-") and not arg.endswith(".py") and re.fullmatch(r"[\w./-]+", arg) and ("/" in arg or arg == "tests")]if not directories:@@ -1483,7 +1524,29 @@ def self_test() -> int:declared_optional = dict(OPTIONAL_BY_OMISSION)OPTIONAL_BY_OMISSION.clear()+ # Argument parsing is a pure function, so it is proved directly rather+ # than through a whole synthetic tree. The first case is the one that+ # produced thirteen findings from a single `tee`: everything after the+ # pipe belongs to the next command, and `/tmp/wl.txt` satisfied every+ # test for a directory path. The rest keep the fix from going too far —+ # a real directory argument must still be seen, or the gate stops+ # detecting the thing it exists for.+ argument_cases: list[tuple[str, list[str]]] = [+ ("t/a_test.py -q 2>&1 | tee /tmp/wl.txt", ["t/a_test.py", "-q"]),+ ("tests/ -q", ["tests/", "-q"]),+ ("a.py >/dev/null", ["a.py"]),+ ("a.py > /dev/null", ["a.py"]),+ ("tests/isolation -v && echo /tmp/x", ["tests/isolation", "-v"]),+ ("tests/ --cov=app", ["tests/", "--cov=app"]),+ ]failures: list[str] = []+ for raw, expected in argument_cases:+ got = _pytest_arguments(raw)+ ok = got == expected+ if not ok:+ failures.append(f"_pytest_arguments({raw!r}) returned {got}, expected {expected}")+ print(f" self-test [{'ok' if ok else 'FAIL'}] pytest arguments stop at the shell: {raw!r}")+for name, mutate, expect in cases:EXEMPT.clear()code, problems = build(mutate)diff --git a/scripts/check_maturity_table.py b/scripts/check_maturity_table.pyindex 7eb8db81a..7a45344d3 100755--- a/scripts/check_maturity_table.py+++ b/scripts/check_maturity_table.py@@ -172,7 +172,7 @@ EVIDENCE: dict[str, Evidence] = {"and requires six of the ten tests to fail."),),- "SCIM 2.0, white-label, usage metering": Evidence(+ "SCIM 2.0 provisioning": Evidence(tests=("tests/isolation/test_scim_live.py",),workflow="scim-live.yml",job="scim-live",@@ -186,6 +186,37 @@ EVIDENCE: dict[str, Evidence] = {"static contract gates move here from a path-filtered workflow."),),+ "White-label branding": Evidence(+ tests=("tests/isolation/test_white_label_live.py",),+ workflow="white-label-live.yml",+ job="white-label-live",+ negative_control=".github/workflows/white-label-live.yml",+ negative_marker="The negative control.",+ rationale=(+ "Split out of a row that read `SCIM 2.0, white-label, usage metering` and "+ "named only `test_scim_live.py`, which tests neither of the other two. One "+ "row covering three capabilities passed this gate for four releases because "+ "`_match_key` matches a prefix and the first capability's evidence was real. "+ "The scheduled report and its covering email are the surfaces an operator "+ "actually receives, and the email is where the defect was: both workers "+ "resolved branding nowhere, and neither could store an artefact on real "+ "Postgres at all."+ ),+ ),+ "Usage metering": Evidence(+ tests=("tests/isolation/test_usage_lake_meter_live.py",),+ workflow="lake-live.yml",+ job="lake-live",+ negative_control=".github/workflows/lake-live.yml",+ negative_marker="OK: an unscoped lake meter makes the suite fail, as it must.",+ rationale=(+ "Split out of the same bundled row, and the evidence string was wrong as well "+ "as missing: this runs on live **ClickHouse**, not Postgres. A meter is the "+ "one claim that cannot be tested against itself -- four meters in this "+ "repository read zero on real data while passing their own suites -- so the "+ "negative control drops the tenant predicate and requires the suite to go red."+ ),+ ),"Scheduled connectors": Evidence(tests=("tests/isolation/test_connector_scheduler_live.py",),workflow="connector-scheduler-live.yml",@@ -583,6 +614,47 @@ def has_negative_control(entry: Evidence) -> tuple[bool, str]:return True, ""+#: Words that make a comma a subordinate clause rather than a list item.+#: "Alert-triggered playbooks, with a durable approval pause" is one+#: capability; "SCIM 2.0, white-label, usage metering" is three.+_CLAUSE_OPENERS: tuple[str, ...] = (+ "with",+ "which",+ "including",+ "and its",+ "compiled",+ "of",+ "plus",+ "backed",+ "scoped",+)+++def bundles_several_capabilities(capability: str) -> tuple[bool, str]:+ """Whether one row is standing in for several capabilities.++ This is the shape that defeated the gate for four releases. The row read+ ``SCIM 2.0, white-label, usage metering`` and named a single SCIM test;+ ``_match_key`` matches on a prefix, so the first capability's real+ evidence satisfied the lookup and the other two were never checked. The+ row was Stable, the gate printed OK, and two of the three capabilities+ had no live cover at all.++ Checking that each row's evidence exercises it is not enough on its own,+ because a bundled row has only one evidence entry to check. The row has+ to be split first, which is what this refuses to let anyone skip.+ """+ segments = [s.strip() for s in capability.split(",")[1:]]+ listed = [s for s in segments if s and not s.lower().startswith(_CLAUSE_OPENERS)]+ if not listed:+ return False, ""+ return True, (+ f"{capability!r} names more than one capability ({', '.join(repr(s) for s in listed)}). "+ "Give each its own row and its own evidence: a bundled row is matched on its first "+ "capability, so the others inherit a pass they never earned."+ )++def scan() -> Scan:if not README.is_file():return Scan(findings=[Finding("no-readme", f"{README} does not exist")])@@ -594,6 +666,10 @@ def scan() -> Scan:for row in rows:if row.status != "Stable":continue+ bundled, why = bundles_several_capabilities(row.capability)+ if bundled:+ result.findings.append(Finding("bundled-capabilities", f"line {row.line}: {why}"))+key = _match_key(row.capability)if key is None:result.findings.append(@@ -663,6 +739,24 @@ def _self_test() -> int:"""import dataclasses+ # The bundling check is a pure function over the capability cell, so it+ # is proved directly: the row that defeated this gate for four releases+ # must be caught, and every legitimate shape must pass. Both directions,+ # because a check that flags everything is as useless as one that flags+ # nothing -- and one of these rows really does carry a comma.+ for capability, should_flag in (+ ("SCIM 2.0, white-label, usage metering", True),+ ("A, B and C", True),+ ("Alert-triggered playbooks, with a durable approval pause", False),+ ("Detection engine (2603 executable rules) of 6991", False),+ ("SCIM 2.0 provisioning", False),+ ("Event lake + hunting (ClickHouse)", False),+ ):+ flagged, _ = bundles_several_capabilities(capability)+ if flagged != should_flag:+ print(f"self-test FAILED: bundles_several_capabilities({capability!r}) returned {flagged}, expected {should_flag}")+ return 1+cases: list[tuple[str, bool]] = []baseline = scan()cases.append(("the real tree passes, which every case below perturbs", not baseline.findings))diff --git a/services/actions/app/executors/chatops.py b/services/actions/app/executors/chatops.pyindex 671e75035..8bd435403 100644--- a/services/actions/app/executors/chatops.py+++ b/services/actions/app/executors/chatops.py@@ -41,6 +41,7 @@ from app.core.config import get_settingsfrom app.executors.base import BaseExecutorfrom app.models.action import ActionRequest, ActionResult, ActionStatus, BlastRadiusfrom app.security.chatops_token import ChatOpsTokenError, mint_token+from app.services.branding_lookup import product_name_for_tenantfrom app.services.chatops_prompt import (ChatOpsButton,ChatOpsPromptError,@@ -90,6 +91,10 @@ class ChatOpsVerifyExecutor(BaseExecutor):)params: dict[str, Any] = request.parameters or {}+ # Resolved once, before the question is built: the default question+ # names the product too, so resolving it only at delivery would brand+ # the card's title and leave the sentence inside it unbranded.+ product_name = await product_name_for_tenant(request.tenant_id)transport = str(params.get("transport", "slack")).lower()webhook_url = params.get("webhook_url") or ""bot_token = params.get("bot_token") or None@@ -97,7 +102,7 @@ class ChatOpsVerifyExecutor(BaseExecutor):question = str(params.get("question",- f"AiSOC needs to confirm activity on your account ({request.target}).",+ f"{product_name} needs to confirm activity on your account ({request.target}).",))context = str(@@ -165,6 +170,7 @@ class ChatOpsVerifyExecutor(BaseExecutor):buttons=buttons,bot_token=bot_token,channel=channel,+ product_name=product_name,)else:delivery = await send_teams_prompt(@@ -172,6 +178,7 @@ class ChatOpsVerifyExecutor(BaseExecutor):question=question,context=context,buttons=buttons,+ product_name=product_name,)except ChatOpsPromptError as exc:logger.warning(diff --git a/services/actions/app/services/branding_lookup.py b/services/actions/app/services/branding_lookup.pynew file mode 100644index 000000000..6fd63185c--- /dev/null+++ b/services/actions/app/services/branding_lookup.py@@ -0,0 +1,87 @@+"""What an operator's product is called, for the ChatOps prompt.++A **read path only**, deliberately. ``services/api`` owns the branding+schema, the write routes, the SVG sanitiser and the asset bytes; this reads+one column so the interactive approval prompt can say the operator's product+name instead of the platform's. Same split as the credential vault, where+``services/connectors`` ships a vendored ``decrypt_dict`` so the scheduler+can decrypt at poll time without owning the write path.++Only ``product_name``. The resolver in ``services/api`` returns colours, a+logo, support contacts and a footer; none of them has anywhere to go in a+Slack Block Kit payload or a Teams MessageCard, and resolving fields nobody+renders is how a second resolver starts drifting from the first.++Never raises. A branding lookup that failed would take down the approval+prompt it was decorating, and an approval that never reaches an analyst is a+worse outcome than one that reaches them under the platform's name.+"""++from __future__ import annotations++import os+from uuid import UUID++import structlog++logger = structlog.get_logger()++#: What an unbranded deployment calls itself. Mirrors ``DEFAULT_BRANDING``+#: in ``services/api/app/services/branding/resolver.py``.+DEFAULT_PRODUCT_NAME = "AiSOC"++# Resolves the owning organisation exactly as `owning_org_id` does, and in+# the same order: a managed customer is in `organization_tenants`, and the+# operator's own staff sign in to the organisation's `home_tenant_id`.+# Checking only the first leaves the operator's own prompts unbranded, which+# are the ones they see every day.+_QUERY = """+ SELECT product_name+ FROM aisoc_org_branding+ WHERE org_id = COALESCE(+ (SELECT org_id FROM organization_tenants WHERE tenant_id = $1),+ (SELECT id FROM organizations WHERE home_tenant_id = $1)+ )+"""+++def _dsn() -> str | None:+ """An asyncpg-compatible DSN, or None when no database is configured.++ Accepts the SQLAlchemy spelling the API uses as well as the plain form,+ because both are already present in deployed environments. Copied from+ ``tenant_policy`` rather than imported so this module stays a leaf.+ """+ raw = (os.environ.get("DATABASE_DSN") or os.environ.get("DATABASE_URL") or "").strip()+ if not raw:+ return None+ return raw.replace("postgresql+asyncpg://", "postgresql://").replace("postgres+asyncpg://", "postgresql://")+++async def product_name_for_tenant(tenant_id: str | UUID | None) -> str:+ """The product name to show this tenant, or the platform default.++ The default is returned for every "we could not tell" case -- no+ database, no tenant, no organisation, no branding row, an empty column,+ or a failed read -- because each of them means the same thing to the+ person reading the message: nobody has configured a name.+ """+ if tenant_id is None:+ return DEFAULT_PRODUCT_NAME+ dsn = _dsn()+ if not dsn:+ return DEFAULT_PRODUCT_NAME++ try:+ import asyncpg # noqa: PLC0415 — optional at import time; only needed with a DSN++ conn = await asyncpg.connect(dsn, timeout=5.0)+ try:+ name = await conn.fetchval(_QUERY, UUID(str(tenant_id)))+ finally:+ await conn.close()+ except Exception as exc: # noqa: BLE001 - see the module docstring+ logger.warning("branding_lookup.unavailable", error=str(exc)[:200])+ return DEFAULT_PRODUCT_NAME++ return (name or "").strip() or DEFAULT_PRODUCT_NAMEdiff --git a/services/actions/app/services/chatops_prompt.py b/services/actions/app/services/chatops_prompt.pyindex cd6a57e98..2069daf2c 100644--- a/services/actions/app/services/chatops_prompt.py+++ b/services/actions/app/services/chatops_prompt.py@@ -26,6 +26,7 @@ import httpximport structlogfrom app.security.credential_vault import CredentialVaultError, get_vault+from app.services.branding_lookup import DEFAULT_PRODUCT_NAMElogger = structlog.get_logger()@@ -65,6 +66,7 @@ async def send_slack_prompt(buttons: list[ChatOpsButton],bot_token: str | None = None,channel: str | None = None,+ product_name: str = DEFAULT_PRODUCT_NAME,timeout: float = 10.0,) -> dict[str, Any]:"""Post the interactive prompt into Slack.@@ -92,7 +94,7 @@ async def send_slack_prompt(elements = [{k: v for k, v in el.items() if v is not None} for el in elements]payload: dict[str, Any] = {- "text": f"AiSOC verification: {question}",+ "text": f"{product_name} verification: {question}","blocks": [{"type": "section", "text": {"type": "mrkdwn", "text": f"*{question}*"}},{"type": "context", "elements": [{"type": "mrkdwn", "text": context}]},@@ -115,6 +117,7 @@ async def send_teams_prompt(question: str,context: str,buttons: list[ChatOpsButton],+ product_name: str = DEFAULT_PRODUCT_NAME,timeout: float = 10.0,) -> dict[str, Any]:"""Post the interactive prompt into Microsoft Teams via Connector Card."""@@ -125,9 +128,9 @@ async def send_teams_prompt(payload = {"@type": "MessageCard","@context": "https://schema.org/extensions",- "summary": f"AiSOC verification: {question}",+ "summary": f"{product_name} verification: {question}","themeColor": "0078D4",- "title": "AiSOC verification",+ "title": f"{product_name} verification","text": f"**{question}**\n\n{context}","potentialAction": [{diff --git a/services/actions/tests/test_chatops_branding.py b/services/actions/tests/test_chatops_branding.pynew file mode 100644index 000000000..f2a0e32ae--- /dev/null+++ b/services/actions/tests/test_chatops_branding.py@@ -0,0 +1,172 @@+"""The interactive approval prompt carries the operator's product name.++Fix-pass 4.3. The ChatOps bots were the one branded surface with no read+path to branding at all: `services/api` owns the schema and the write+routes, and `services/actions` had no way to ask it anything, so the Slack+`text`, the Teams `summary` and `title`, and the default question inside+both all said "AiSOC" on every deployment regardless of what the operator+had configured.++Four prompts in one card is the reason this is worth a test rather than a+glance. The card's title and the sentence inside it are built at different+points in the executor -- the question is assembled near the top from+`request.parameters`, the title at delivery -- so branding one and not the+other produces a card that is half right, which reads as a bug in the+product rather than a missing setting.++The lookup itself is deliberately total: every "we could not tell" case+(no database, no tenant, no organisation, no row, an empty column, a failed+read) returns the platform default, because each means the same thing to+the person reading the message. These tests pin that, since a branding+lookup that raised would take down the approval prompt it was decorating,+and an approval nobody sees is worse than one under the wrong name.+"""++from __future__ import annotations++import uuid+from typing import Any++import pytest+from app.services.branding_lookup import DEFAULT_PRODUCT_NAME, product_name_for_tenant+from app.services.chatops_prompt import ChatOpsButton, send_slack_prompt, send_teams_prompt+++class _Response:+ status_code = 200+ text = "ok"++ @staticmethod+ def json() -> dict[str, Any]:+ return {"ok": True}+++class _Capture:+ """Stands in for httpx.AsyncClient and keeps the payload posted."""++ def __init__(self) -> None:+ self.payload: dict[str, Any] = {}++ async def __aenter__(self) -> _Capture:+ return self++ async def __aexit__(self, *_: object) -> None:+ return None++ async def post(self, _url: str, **kwargs: Any) -> _Response:+ self.payload = kwargs.get("json") or {}+ return _Response()+++def capture(monkeypatch: pytest.MonkeyPatch) -> _Capture:+ """Captures the posted payload instead of reaching a vendor.++ A real Fernet key is set because the prompt runs every credential+ through the vault before use. The vault returns a plain value+ unchanged, but it refuses to construct without a key at all -- so+ without this the test would fail inside the credential path and never+ reach the branding assertion it exists to make.+ """+ from cryptography.fernet import Fernet++ monkeypatch.setenv("AISOC_CREDENTIAL_KEY", Fernet.generate_key().decode())++ # Both targets are named as strings rather than imported. The module is+ # already imported at the top of this file with a from-import, and+ # importing it a second time as `import app.services.chatops_prompt as+ # mod` is two import styles for one module -- which CodeQL reports as+ # py/import-and-import-from, and which leaves a reader unsure which+ # binding a later edit should patch.+ #+ # `_vault_singleton` is a module-level singleton, not an lru_cache, so+ # it is reset through monkeypatch: the key set above is then the one the+ # vault is built from, and the next test in the session does not inherit+ # this one.+ monkeypatch.setattr("app.security.credential_vault._vault_singleton", None)++ cap = _Capture()+ monkeypatch.setattr("app.services.chatops_prompt.httpx.AsyncClient", lambda *a, **k: cap)+ return cap+++def _buttons() -> list[ChatOpsButton]:+ return [ChatOpsButton(label="Yes", url="https://example.invalid/y", style="primary")]+++async def test_slack_text_carries_the_tenants_product_name(capture: _Capture) -> None:+ await send_slack_prompt(+ webhook_url="https://example.invalid/hook",+ question="Did you sign in from Berlin?",+ context="Incident 1",+ buttons=_buttons(),+ product_name="Northwind Defend",+ )+ assert capture.payload["text"].startswith("Northwind Defend verification:")+ assert "AiSOC" not in capture.payload["text"]+++async def test_teams_summary_and_title_both_carry_it(capture: _Capture) -> None:+ """Both, not either.++ The MessageCard shows `title` in the card and `summary` in the+ notification list, so branding one leaves the other visible and wrong+ in whichever surface the analyst happens to look at first.+ """+ await send_teams_prompt(+ webhook_url="https://example.invalid/hook",+ question="Did you sign in from Berlin?",+ context="Incident 1",+ buttons=_buttons(),+ product_name="Northwind Defend",+ )+ assert capture.payload["summary"].startswith("Northwind Defend verification:")+ assert capture.payload["title"] == "Northwind Defend verification"+ assert "AiSOC" not in capture.payload["summary"]+ assert "AiSOC" not in capture.payload["title"]+++async def test_an_unbranded_deployment_still_reads_correctly(capture: _Capture) -> None:+ """The default is a real product name, not an empty string.++ Callers omit `product_name` only when nobody has configured one, and a+ prompt reading " verification:" would look broken rather than+ unbranded.+ """+ await send_slack_prompt(+ webhook_url="https://example.invalid/hook",+ question="Did you sign in from Berlin?",+ context="Incident 1",+ buttons=_buttons(),+ )+ assert capture.payload["text"] == f"{DEFAULT_PRODUCT_NAME} verification: Did you sign in from Berlin?"+++async def test_no_tenant_resolves_to_the_default() -> None:+ assert await product_name_for_tenant(None) == DEFAULT_PRODUCT_NAME+++async def test_no_database_resolves_to_the_default(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("DATABASE_DSN", raising=False)+ monkeypatch.delenv("DATABASE_URL", raising=False)+ assert await product_name_for_tenant(uuid.uuid4()) == DEFAULT_PRODUCT_NAME+++async def test_a_failed_read_resolves_to_the_default_rather_than_raising(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The negative control for the module's central promise.++ Pointed at a DSN nothing is listening on, the lookup must still answer.+ If this ever raises, the approval prompt it decorates stops being+ delivered -- so the failure mode would not be an unbranded card, it+ would be an analyst who is never asked.+ """+ monkeypatch.setenv("DATABASE_DSN", "postgresql://[email protected]:1/none")+ assert await product_name_for_tenant(uuid.uuid4()) == DEFAULT_PRODUCT_NAMEdiff --git a/services/api/app/api/v1/endpoints/investigations.py b/services/api/app/api/v1/endpoints/investigations.pyindex 4f4da2ed1..db7c897f8 100644--- a/services/api/app/api/v1/endpoints/investigations.py+++ b/services/api/app/api/v1/endpoints/investigations.py@@ -898,12 +898,24 @@ def _build_summary_markdown(run: InvestigationRun,events: list[InvestigationEvent],analyst_note: str | None,+ branding: Branding | None = None,) -> str:"""Build a structured Markdown investigation summary from ORM objects.The summary is deterministic (no LLM call) so it is always availableeven in air-gapped / local-LLM mode. It mirrors the structure thatWS-H3 (Audit export) will ingest.++ The closing line is branded because this markdown *is* the exported PDF:+ ``_render_pdf`` draws a branded header and footer around it, so a+ hard-coded platform name here put both names on one document. The+ support contact is whatever the organisation configured, and an+ organisation that configured none prints none -- a fixed mailbox in a+ managed customer's report directs their "something is wrong with this"+ to somebody who cannot act on it.++ ``branding`` is optional so every existing caller keeps working and an+ unbranded deployment is unchanged."""started = run.started_at.strftime("%Y-%m-%d %H:%M:%S UTC") if run.started_at else "—"closed_at = datetime.now(UTC).strftime("%Y-%m-%d %H:%M:%S UTC")@@ -926,6 +938,10 @@ def _build_summary_markdown(note_section = f"\n## Analyst Note\n\n{analyst_note}\n" if analyst_note else ""+ brand = branding or DEFAULT_BRANDING+ support = brand.support_url or brand.support_email+ generated_by = f"*Generated by {brand.product_name}" + (f" — {support}*" if support else "*")+return textwrap.dedent(f"""\# Investigation Summary — {run.case_id}@@ -953,7 +969,7 @@ def _build_summary_markdown({timeline_md}{note_section}---- *Generated by AiSOC — [email protected]*+ {generated_by}""")@@ -979,7 +995,7 @@ async def close_investigation()events = list(events_result.scalars().all())- summary_md = _build_summary_markdown(run, events, body.analyst_note)+ summary_md = _build_summary_markdown(run, events, body.analyst_note, await resolve_branding(db, current_user.tenant_id))encoded = summary_md.encode()sha = hashlib.sha256(encoded).hexdigest()diff --git a/services/api/app/workers/report_scheduler.py b/services/api/app/workers/report_scheduler.pyindex 7eb95f7e6..cc6a73132 100644--- a/services/api/app/workers/report_scheduler.py+++ b/services/api/app/workers/report_scheduler.py@@ -28,6 +28,7 @@ from __future__ import annotationsimport asyncioimport base64import os+from dataclasses import replacefrom datetime import UTC, datetime, timedeltaimport structlog@@ -35,7 +36,8 @@ from sqlalchemy import selectfrom app.db.database import AsyncSessionLocalfrom app.models.report import ReportArtefact, ReportTemplate-from app.services.smtp_delivery import send_mail+from app.services.branding.resolver import Branding, resolve_branding+from app.services.smtp_delivery import SmtpSettings, send_maillogger = structlog.get_logger(__name__)@@ -137,15 +139,28 @@ def _window(moment: datetime) -> tuple[datetime, datetime]:return moment - timedelta(days=7), moment-async def _deliver(artefact: ReportArtefact, recipients: list[str], body: bytes) -> None:- """Attach and send, recording the outcome on the artefact itself."""+async def _deliver(artefact: ReportArtefact, recipients: list[str], body: bytes, branding: Branding) -> None:+ """Attach and send, recording the outcome on the artefact itself.++ The subject and the ``From`` display name come from the tenant's+ branding. Branding the attached report and leaving ``[AiSOC]`` on the+ envelope would not be white-labelling: the subject and the sender are+ what a recipient reads before deciding whether the mail is for them,+ and a managed customer has never heard of the platform their provider+ runs.++ The ``From`` **address** is untouched. A display name is not an SPF or+ DKIM identity, and mail sent from a domain the deployment does not+ control is mail that lands in a spam folder.+ """result = await send_mail(recipients=recipients,- subject=f"[AiSOC] {artefact.title}",+ subject=f"[{branding.product_name}] {artefact.title}",text_body=(f"{artefact.title}\nPeriod: {artefact.period_start:%Y-%m-%d} to {artefact.period_end:%Y-%m-%d}\n\nThe report is attached."),attachment=(f"{artefact.report_type}.{artefact.output_format}", body, "application/octet-stream"),+ settings=replace(SmtpSettings.from_env(), sender_name=branding.sender_name),)artefact.delivery_status = result.statusartefact.delivery_detail = result.detail[:500]@@ -194,14 +209,20 @@ async def run_once(*, moment: datetime | None = None) -> dict[str, int]:output_format="html",storage_key=f"reports/{template.tenant_id}/{template.id}/{now:%Y%m%dT%H%M}.html",delivered_to=recipients,- status="generated",+ # `migrations/019_board_reports.sql` constrains this column to+ # pending | generating | completed | failed. "generated" is+ # not a member, so every sweep raised a CheckViolationError on+ # commit and no scheduled report has ever been stored on a real+ # deployment. The ORM model declares no CHECK, so a suite that+ # builds its tables from the model cannot see this.+ status="completed",generated_by="scheduler",)body = _render(template, artefact)artefact.body_b64 = base64.b64encode(body).decode("ascii")db.add(artefact)if recipients:- await _deliver(artefact, recipients, body)+ await _deliver(artefact, recipients, body, await resolve_branding(db, template.tenant_id))else:artefact.delivery_status = "skipped"artefact.delivery_detail = "the template names no recipients"diff --git a/services/api/app/workers/weekly_digest_task.py b/services/api/app/workers/weekly_digest_task.pyindex 4afab560d..28fcad6ef 100644--- a/services/api/app/workers/weekly_digest_task.py+++ b/services/api/app/workers/weekly_digest_task.py@@ -47,6 +47,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.db.database import AsyncSessionLocalfrom app.models.report import ReportArtefactfrom app.models.tenant import Tenant+from app.services.branding.resolver import resolve_brandingfrom app.services.digest_pdf import WeasyPrintUnavailableError, render_digest_pdffrom app.services.executive_digest import build_weekly_digest@@ -136,9 +137,18 @@ async def _generate_for_tenant(period_end=period_end,)+ # The interactive route resolved branding and this worker did not,+ # so the digest an operator actually receives every Monday — the+ # one a managed customer forwards to their board — rendered in the+ # platform palette under the platform name while the documentation+ # said it carried theirs. `inline_logo` because WeasyPrint runs+ # server-side: a referenced logo would be an outbound request the+ # server makes to an address an operator supplied.+ branding = await resolve_branding(db, tenant_id, inline_logo=True)+output_format = "pdf"try:- raw_bytes = render_digest_pdf(digest)+ raw_bytes = render_digest_pdf(digest, branding)except WeasyPrintUnavailableError:# Fall back to HTML when the native WeasyPrint stack is absent# (e.g. dev containers without Pango/Cairo). The artefact is@@ -149,12 +159,12 @@ async def _generate_for_tenant()from app.services.digest_html import render_digest_html # lazy import- raw_bytes = render_digest_html(digest).encode("utf-8")+ raw_bytes = render_digest_html(digest, branding).encode("utf-8")output_format = "html"body_b64 = base64.b64encode(raw_bytes).decode("ascii")storage_key = f"weekly_digest/{tenant_id}/{period_start.strftime('%Y-%m-%d')}_{period_end.strftime('%Y-%m-%d')}.{output_format}"- title = f"AiSOC Weekly Executive Digest {period_start.strftime('%d %b')}–{period_end.strftime('%d %b %Y')}"+ title = f"{branding.product_name} Weekly Executive Digest {period_start.strftime('%d %b')}–{period_end.strftime('%d %b %Y')}"artefact = ReportArtefact(id=uuid.uuid4(),@@ -169,7 +179,10 @@ async def _generate_for_tenant(file_size_bytes=len(raw_bytes),data_snapshot=digest.model_dump(mode="json"),generated_by="weekly_digest_worker",- status="ready",+ # See report_scheduler: the column's CHECK allows+ # pending | generating | completed | failed, and "ready" is not a+ # member either, so the Monday digest raised on commit too.+ status="completed",)db.add(artefact)await db.commit()diff --git a/services/api/migrations/072_org_branding.sql b/services/api/migrations/072_org_branding.sqlindex ee7b268fb..2447bb9b2 100644--- a/services/api/migrations/072_org_branding.sql+++ b/services/api/migrations/072_org_branding.sql@@ -96,7 +96,10 @@ CREATE TABLE IF NOT EXISTS aisoc_org_branding (-- inbox.support_url TEXT CHECK (support_url IS NULL OR support_url ~ '^https://'),- -- The display name on outbound mail and ChatOps messages.+ -- The display name on outbound mail: email approvals and the covering+ -- mail on a scheduled report. Not ChatOps -- the prompt is posted by+ -- `services/actions` and the two bot services, none of which can reach+ -- this table. See "What is not branded" in the white-label doc.sender_name TEXT CHECK (sender_name IS NULL OR length(sender_name) BETWEEN 1 AND 80),footer_text TEXT CHECK (footer_text IS NULL OR length(footer_text) <= 300),diff --git a/services/api/tests/test_report_artefact_status_vocabulary.py b/services/api/tests/test_report_artefact_status_vocabulary.pynew file mode 100644index 000000000..73823f883--- /dev/null+++ b/services/api/tests/test_report_artefact_status_vocabulary.py@@ -0,0 +1,113 @@+"""Every status a worker writes to ``report_artefacts`` is one the column allows.++Found while proving the white-label property of the scheduled report: the+covering email could not be asserted against a real Postgres because the+sweep never got as far as sending one. ``report_scheduler`` wrote+``status="generated"`` and ``weekly_digest_task`` wrote ``status="ready"``,+and ``migrations/019_board_reports.sql`` constrains that column to+``pending | generating | completed | failed``. Neither value is a member, so+both workers raised ``CheckViolationError`` on commit and **no scheduled+report and no Monday digest had ever been stored on a real deployment**.++Why no test caught it, and why this one is shaped the way it is+---------------------------------------------------------------+The CHECK lives in the migration. The ORM model declares no constraint at+all, so a suite that builds its tables with ``Base.metadata.create_all`` --+which is every offline suite in this service -- gets a column that accepts+any string. The database and the model disagreed about what a status is, and+only the database's opinion matters in production.++So this reads the vocabulary out of the **migration**, which is the authority,+and the literals out of the **workers**, which are what drift. Asserting the+two agree in that direction is the direction that changes: a new status is+invented in Python far more often than a CHECK is rewritten.+"""++from __future__ import annotations++import ast+import re+from pathlib import Path++import pytest++API_ROOT = Path(__file__).resolve().parents[1]+MIGRATION = API_ROOT / "migrations" / "019_board_reports.sql"+DELIVERY_MIGRATION = API_ROOT / "migrations" / "098_report_delivery.sql"++#: Every module that constructs or mutates a ``ReportArtefact``.+WRITERS = (+ API_ROOT / "app" / "workers" / "report_scheduler.py",+ API_ROOT / "app" / "workers" / "weekly_digest_task.py",+ API_ROOT / "app" / "api" / "v1" / "endpoints" / "reports.py",+)+++def _vocabulary(sql: str, column: str) -> frozenset[str]:+ """The values a ``CHECK (<column> IN (...))`` permits."""+ match = re.search(rf"CHECK\s*\(\s*{column}\s+IN\s*\(([^)]*)\)", sql, re.IGNORECASE)+ assert match, f"no CHECK found for {column}; the migration has been reshaped"+ return frozenset(re.findall(r"'([^']+)'", match.group(1)))+++def _assigned_literals(path: Path, field: str) -> set[str]:+ """Every string literal this module assigns to ``field``.++ Both spellings, because the schedulers use one each: a keyword argument+ in a ``ReportArtefact(...)`` construction, and an attribute assignment+ on an instance afterwards. Looking for only the first is how the+ ``delivery_status`` writes would have been missed.+ """+ tree = ast.parse(path.read_text(encoding="utf-8"))+ found: set[str] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Call):+ for keyword in node.keywords:+ if keyword.arg == field and isinstance(keyword.value, ast.Constant) and isinstance(keyword.value.value, str):+ found.add(keyword.value.value)+ elif isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):+ for target in node.targets:+ if isinstance(target, ast.Attribute) and target.attr == field:+ found.add(node.value.value)+ return found+++STATUSES = _vocabulary(MIGRATION.read_text(encoding="utf-8"), "status")+DELIVERY_STATUSES = _vocabulary(DELIVERY_MIGRATION.read_text(encoding="utf-8"), "delivery_status")+++def test_the_migration_vocabulary_parsed() -> None:+ """A parser that silently found nothing would pass every case below."""+ assert STATUSES == {"pending", "generating", "completed", "failed"}+ assert DELIVERY_STATUSES == {"not_attempted", "sent", "skipped", "failed"}++[email protected]("path", WRITERS, ids=lambda p: p.name)+def test_every_status_written_is_one_the_column_allows(path: Path) -> None:+ written = _assigned_literals(path, "status")+ # `status` is a common attribute name; only the ones that are not in the+ # vocabulary are interesting, and an unrelated `status="ok"` on some other+ # object would be a false positive. The writers here assign it to nothing+ # else, and that is itself worth holding still.+ assert written, f"{path.name} assigns no status literal; has the writer moved?"+ assert written <= STATUSES, f"{path.name} writes {sorted(written - STATUSES)}, which {MIGRATION.name} refuses"++[email protected]("path", WRITERS, ids=lambda p: p.name)+def test_every_delivery_status_written_is_one_the_column_allows(path: Path) -> None:+ written = _assigned_literals(path, "delivery_status")+ assert written <= DELIVERY_STATUSES, (+ f"{path.name} writes {sorted(written - DELIVERY_STATUSES)}, which {DELIVERY_MIGRATION.name} refuses"+ )+++def test_the_check_detects_the_values_that_shipped() -> None:+ """The gate's own self-test, in both directions.++ ``generated`` and ``ready`` are the two literals that were live in the+ tree. A detector that could not see them is a detector that would have+ let this ship, which is exactly what happened.+ """+ assert "generated" not in STATUSES+ assert "ready" not in STATUSES+ assert "completed" in STATUSESdiff --git a/services/api/tests/test_white_label_investigation_summary.py b/services/api/tests/test_white_label_investigation_summary.pynew file mode 100644index 000000000..fa69e7294--- /dev/null+++ b/services/api/tests/test_white_label_investigation_summary.py@@ -0,0 +1,150 @@+"""The body of an investigation summary carries the operator's brand too.++``apps/docs/docs/operations/white-label.md`` lists "Investigation summary+(PDF)" as carrying the product name, the palette, the footer and the support+contact, and the renderer does exactly that: ``_render_pdf`` draws a branded+header line and a branded footer around whatever markdown it is handed.++What it is handed was not branded. ``_build_summary_markdown`` ended every+summary with a hard-coded line naming the platform and a single address:++ *Generated by AiSOC — [email protected]*++So a white-labelled export drew "ACME SHIELD" across the top and "Generated+by AiSOC" four inches below it. That is the co-branding failure this+repository already names in the digest row of the claim matrix — a report+showing both names is not white-labelled, it is co-branded by accident — and+it travels one step further here, because the address beside it is a fixed+mailbox rather than the support contact the organisation configured. An+analyst at a managed customer reading "something looks wrong with this+report" writes to whoever that address belongs to.++Why no test caught it+---------------------+Nothing in ``services/api/tests`` referenced ``_build_summary_markdown``, the+close route's artefact content or the summary PDF at all. The function was+covered by its absence from every suite, which is why a literal could sit in+a customer-facing document across releases.++These cases assert on the markdown rather than on the PDF bytes, for the+reason the digest suite gives for asserting on HTML: the PDF *is* this+markdown, drawn by reportlab, so a line that is absent here cannot appear+there. That the close route actually passes branding in — the wiring, as+opposed to the renderer — is proved against the real app and real Postgres+in ``tests/isolation/test_white_label_live.py``.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from app.api.v1.endpoints.investigations import _build_summary_markdown+from app.models.investigation import InvestigationEvent, InvestigationRun+from app.services.branding.resolver import DEFAULT_BRANDING, Branding++PRODUCT = "Acme Shield"+SUPPORT_URL = "https://support.acme.example"++#: The address that was hard-coded into every summary. Asserted by name: a+#: future edit that reaches for a literal mailbox again should fail here+#: rather than ship.+PLATFORM_CONTACT = "[email protected]"++BRANDED = Branding(+ product_name=PRODUCT,+ primary_color="#123456",+ accent_color="#654321",+ support_email=None,+ support_url=SUPPORT_URL,+ sender_name="Acme SOC",+ footer_text="Acme Shield — operated by Acme Managed Security.",+ logo_url=None,+ logo_data_uri=None,+ org_id=uuid.UUID("0a0a0a0a-0000-0000-0000-00000000000a"),+ is_white_labelled=True,+)+++def _run() -> InvestigationRun:+ """A run with the attributes the summary reads, and nothing more.++ The real ORM class rather than a stand-in. A ``SimpleNamespace`` would+ answer for whatever attribute the formatter happened to ask for, so it+ could not notice a column being renamed out from under it.+ """+ return InvestigationRun(+ id=uuid.UUID("11111111-0000-0000-0000-000000000011"),+ case_id="CASE-4821",+ tenant_id=uuid.UUID("eeeeeeee-0000-0000-0000-0000000000e1"),+ status="completed",+ model_used="llama3.2:3b",+ started_at=datetime(2026, 5, 4, 9, 0, tzinfo=UTC),+ iterations=3,+ total_tokens=1234,+ )+++def _events() -> list[InvestigationEvent]:+ return [+ InvestigationEvent(+ run_id=uuid.UUID("11111111-0000-0000-0000-000000000011"),+ seq=1,+ kind="llm_response",+ agent="aisoc-recon",+ summary="Resolved the host and its recent sign-ins.",+ ts=datetime(2026, 5, 4, 9, 1, tzinfo=UTC),+ )+ ]+++class TestTheSummaryBody:+ def test_the_footer_names_the_operators_product(self) -> None:+ body = _build_summary_markdown(_run(), _events(), None, BRANDED)+ assert PRODUCT in body++ def test_the_footer_does_not_also_name_the_platform(self) -> None:+ """A document showing both names is co-branded, not white-labelled."""+ body = _build_summary_markdown(_run(), _events(), None, BRANDED)+ assert DEFAULT_BRANDING.product_name not in body++ def test_the_support_contact_is_the_one_the_organisation_configured(self) -> None:+ body = _build_summary_markdown(_run(), _events(), None, BRANDED)+ assert SUPPORT_URL in body++ def test_no_customer_report_carries_a_fixed_mailbox(self) -> None:+ """The defect, stated as an assertion.++ Checked on the branded *and* the unbranded render: the address was+ wrong in a white-labelled export because it is not the operator's,+ and wrong in an unbranded one because a deployment that has+ configured no support contact does not have one to print.+ """+ assert PLATFORM_CONTACT not in _build_summary_markdown(_run(), _events(), None, BRANDED)+ assert PLATFORM_CONTACT not in _build_summary_markdown(_run(), _events(), None, DEFAULT_BRANDING)++ def test_an_unbranded_deployment_still_names_the_platform(self) -> None:+ """The positive control.++ Without this, deleting the footer outright would satisfy every case+ above. An unbranded deployment should still say what produced the+ document.+ """+ body = _build_summary_markdown(_run(), _events(), None, DEFAULT_BRANDING)+ assert DEFAULT_BRANDING.product_name in body++ def test_branding_is_optional_so_every_existing_caller_keeps_working(self) -> None:+ body = _build_summary_markdown(_run(), _events(), None)+ assert DEFAULT_BRANDING.product_name in body+ assert PLATFORM_CONTACT not in body++ def test_the_content_the_summary_is_about_is_untouched(self) -> None:+ """Branding decorates the report; it must not rewrite it.++ ``close_investigation`` hashes this markdown into the artefact, so a+ branding change that altered the body would change evidence.+ """+ body = _build_summary_markdown(_run(), _events(), "Escalated to the on-call.", BRANDED)+ assert "CASE-4821" in body+ assert "Resolved the host and its recent sign-ins." in body+ assert "Escalated to the on-call." in bodydiff --git a/services/api/tests/test_white_label_scheduled_reports.py b/services/api/tests/test_white_label_scheduled_reports.pynew file mode 100644index 000000000..49f027c78--- /dev/null+++ b/services/api/tests/test_white_label_scheduled_reports.py@@ -0,0 +1,278 @@+"""The reports that go out on a schedule carry the operator's brand too.++``apps/docs/docs/operations/white-label.md`` lists "Executive digest (HTML+and PDF)" as branded, and on the interactive path it is:+``GET /api/v1/reports/digest`` resolves branding and hands it to the+renderer. The weekly digest that an operator actually receives is not+produced there. It is produced by ``app.workers.weekly_digest_task``, every+Monday, for every active tenant — and that worker called+``render_digest_pdf(digest)`` with no branding at all, so the stored+artefact rendered in the platform palette under the platform name while the+documentation said otherwise.++This is the document the resolver's own docstring singles out: "the one a+customer notices is whichever renders in the document they forward to their+board". A managed customer forwarding their provider's weekly digest would+have forwarded somebody else's product name.++Why no test caught it+---------------------+``test_digest_pdf.py`` covers the worker's fallback by patching+``_generate_for_tenant`` with, in its own words, a "thin inline+re-implementation" and then asserting on that copy. A test that substitutes+a reimplementation for the function under test can never notice what the+real one does not do. These cases call the real ``_generate_for_tenant`` and+the real ``run_once``, and read the bytes that were actually stored.++The covering email that ``report_scheduler`` sends carries the same defect+and is proved next door, in+``tests/isolation/test_white_label_live.py``: its template+row stores recipients in a Postgres ``text[]``, which SQLite cannot bind, so+asserting on it here would mean asserting against a reshaped schema.+"""++from __future__ import annotations++import base64+import sys+import types+import uuid+from datetime import UTC, datetime, timedelta++import pytest+import pytest_asyncio+from app.db.database import Base+from app.models.branding import OrgBrandAsset, OrgBranding+from app.models.organization import Organization, OrganizationTenant+from app.models.report import ReportArtefact+from app.services.executive_digest import AlertRow, DigestInputs, build_digest_from_rows+from sqlalchemy import select+from sqlalchemy.dialects.postgresql import ARRAY, JSONB+from sqlalchemy.dialects.postgresql import UUID as PgUUID+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine+from sqlalchemy.ext.compiler import compiles++pytestmark = pytest.mark.asyncio++TENANT = uuid.UUID("eeeeeeee-0000-0000-0000-0000000000e1")+UNBRANDED_TENANT = uuid.UUID("ffffffff-0000-0000-0000-0000000000f1")+ORG = uuid.UUID("0a0a0a0a-0000-0000-0000-00000000000a")++PERIOD_START = datetime(2026, 5, 4, tzinfo=UTC)+PERIOD_END = datetime(2026, 5, 10, 23, 59, 59, tzinfo=UTC)++PRODUCT = "Acme Shield"+PRIMARY = "#123456"+ACCENT = "#654321"+SUPPORT_URL = "https://support.acme.example"+FOOTER = "Acme Shield — operated by Acme Managed Security."++LOGO = b'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect width="40" height="40" fill="#123456"/></svg>'+++@compiles(JSONB, "sqlite")+def _jsonb_sqlite(_type_, _compiler_, **_kw_):+ return "TEXT"+++@compiles(PgUUID, "sqlite")+def _uuid_sqlite(_type_, _compiler_, **_kw_):+ return "CHAR(36)"+++@compiles(ARRAY, "sqlite")+def _array_sqlite(_type_, _compiler_, **_kw_):+ return "TEXT"+++def _digest():+ """A small but valid digest. Its *content* is not what is under test."""+ return build_digest_from_rows(+ DigestInputs(+ tenant_id=TENANT,+ period_start=PERIOD_START,+ period_end=PERIOD_END,+ current_alerts=[+ AlertRow(+ severity="high",+ status="closed",+ created_at=PERIOD_START + timedelta(hours=1),+ resolved_at=PERIOD_START + timedelta(hours=5),+ first_seen_at=PERIOD_START + timedelta(hours=1, minutes=10),+ disposition="true_positive",+ mitre_tactics=["execution"],+ connector_type="edr-crowdstrike",+ ai_score=0.9,+ title="Suspicious PowerShell",+ alert_id=str(uuid.uuid4()),+ event_time=PERIOD_START + timedelta(hours=1),+ )+ ],+ )+ )+++class _CapturingWeasyPrint:+ """A WeasyPrint stand-in that keeps the HTML it was handed.++ The branding reaches the PDF through that HTML, so capturing it is how+ this asserts on a PDF without the native stack. It records rather than+ accepting anything: a double that swallowed ``string=`` would keep+ passing if the worker stopped rendering altogether.+ """++ captured: list[str] = []++ def __init__(self, *, string: str) -> None:+ type(self).captured.append(string)++ def write_pdf(self) -> bytes:+ return b"%PDF-1.4 captured"+++def _install_weasyprint(available: bool) -> None:+ if not available:+ sys.modules["weasyprint"] = None # type: ignore[assignment]+ return+ module = types.ModuleType("weasyprint")+ module.HTML = _CapturingWeasyPrint # type: ignore[attr-defined]+ sys.modules["weasyprint"] = module+++@pytest_asyncio.fixture+async def session_factory():+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")+ async with engine.begin() as conn:+ await conn.run_sync(+ Base.metadata.create_all,+ tables=[+ Organization.__table__,+ OrganizationTenant.__table__,+ OrgBranding.__table__,+ OrgBrandAsset.__table__,+ ReportArtefact.__table__,+ ],+ )+ yield async_sessionmaker(engine, expire_on_commit=False)+ await engine.dispose()+++async def _brand(session_factory) -> None:+ """One white-labelled organisation holding ``TENANT`` in its portfolio."""+ async with session_factory() as db:+ db.add(Organization(id=ORG, name="Acme Managed Security", slug="acme"))+ db.add(OrganizationTenant(org_id=ORG, tenant_id=TENANT))+ db.add(+ OrgBranding(+ org_id=ORG,+ product_name=PRODUCT,+ primary_color=PRIMARY,+ accent_color=ACCENT,+ support_url=SUPPORT_URL,+ footer_text=FOOTER,+ )+ )+ db.add(+ OrgBrandAsset(+ id=uuid.uuid4(),+ org_id=ORG,+ kind="logo",+ content_type="image/svg+xml",+ content=LOGO,+ byte_size=len(LOGO),+ sha256="0" * 64,+ )+ )+ await db.commit()++[email protected](autouse=True)+def _restore_weasyprint():+ yield+ sys.modules.pop("weasyprint", None)+ _CapturingWeasyPrint.captured.clear()+++class TestTheScheduledDigest:+ """``weekly_digest_task`` is the only producer of the weekly digest."""++ async def _run(self, monkeypatch, session_factory, tenant: uuid.UUID) -> ReportArtefact:+ from app.workers import weekly_digest_task as worker++ async def _build(_db, tenant_id, *, period_start, period_end):+ return _digest()++ monkeypatch.setattr(worker, "AsyncSessionLocal", session_factory)+ monkeypatch.setattr(worker, "build_weekly_digest", _build)+ await worker._generate_for_tenant(tenant, PERIOD_START, PERIOD_END)++ async with session_factory() as db:+ return (await db.execute(select(ReportArtefact).where(ReportArtefact.tenant_id == tenant))).scalar_one()++ async def test_the_pdf_carries_the_operators_brand(self, monkeypatch, session_factory) -> None:+ """The worker rendered with no branding, so this was the platform PDF."""+ _install_weasyprint(available=True)+ await _brand(session_factory)+ artefact = await self._run(monkeypatch, session_factory, TENANT)++ assert artefact.output_format == "pdf"+ html = _CapturingWeasyPrint.captured[-1]+ assert PRODUCT in html+ assert PRIMARY in html+ assert ACCENT in html+ assert SUPPORT_URL in html+ assert FOOTER in html++ async def test_the_pdf_does_not_also_carry_the_platform_wordmark(self, monkeypatch, session_factory) -> None:+ """A report showing both names is co-branded by accident."""+ _install_weasyprint(available=True)+ await _brand(session_factory)+ await self._run(monkeypatch, session_factory, TENANT)++ assert "AiSOC" not in _CapturingWeasyPrint.captured[-1]++ async def test_the_pdf_embeds_the_logo_rather_than_linking_it(self, monkeypatch, session_factory) -> None:+ """WeasyPrint runs server-side, so a remote `<img src>` would be an+ outbound request the server makes to an operator-supplied address."""+ _install_weasyprint(available=True)+ await _brand(session_factory)+ await self._run(monkeypatch, session_factory, TENANT)++ assert "data:image/svg+xml;base64," in _CapturingWeasyPrint.captured[-1]++ async def test_the_html_fallback_carries_the_operators_brand(self, monkeypatch, session_factory) -> None:+ """The fallback is what runs wherever the native stack is absent."""+ _install_weasyprint(available=False)+ await _brand(session_factory)+ artefact = await self._run(monkeypatch, session_factory, TENANT)++ assert artefact.output_format == "html"+ body = base64.b64decode(artefact.body_b64 or "").decode("utf-8")+ assert PRODUCT in body+ assert PRIMARY in body+ assert FOOTER in body+ assert "AiSOC" not in body++ async def test_the_artefact_title_carries_the_operators_brand(self, monkeypatch, session_factory) -> None:+ """The title is the row the console lists and the subject mail uses."""+ _install_weasyprint(available=True)+ await _brand(session_factory)+ artefact = await self._run(monkeypatch, session_factory, TENANT)++ assert artefact.title.startswith(PRODUCT)+ assert "AiSOC" not in artefact.title++ async def test_an_unbranded_tenant_still_gets_the_platform_appearance(self, monkeypatch, session_factory) -> None:+ """The positive control.++ A fix that resolved branding and then dropped it, or that blanked+ the name when no organisation owns the tenant, would pass every+ assertion above. This is the case that fails if it does.+ """+ _install_weasyprint(available=True)+ artefact = await self._run(monkeypatch, session_factory, UNBRANDED_TENANT)++ html = _CapturingWeasyPrint.captured[-1]+ assert "AiSOC" in html+ assert "#2563EB" in html+ assert artefact.title.startswith("AiSOC")diff --git a/tests/isolation/test_white_label_live.py b/tests/isolation/test_white_label_live.pynew file mode 100644index 000000000..cb1bab851--- /dev/null+++ b/tests/isolation/test_white_label_live.py@@ -0,0 +1,349 @@+"""White-label, through the real app and real Postgres.++Fix pass 4.3.++Three properties that only a live stack can answer, each of which had+shipped wrong or was covered by nothing at all.++**The brand asset is served to a credential, not to an ``<img>``.**+`logo_url` is a path on this deployment, `GET /api/v1/branding/assets/{id}`,+and the console used to hand it straight to an `<img src>`. That route binds+an authenticated principal, and the only credential a browser attaches to an+image request is a cookie -- so the sidebar logo answered 401 on every+deployment not running the development auth shim, which is every deployment+a customer has. The console now fetches the bytes with the session token and+hands the DOM an object URL. The 401 is asserted here **as the mechanism**:+the component test can show that the `src` is an object URL, but only the+real route against real Postgres can show why it has to be, and a future+change that made the route public would silently make that component test's+whole subject moot while it kept passing.++**The covering email on a scheduled report is branded.** The inherited unit+suite says, in its own docstring, that it cannot assert this: a+`report_templates` row stores its recipients in a Postgres `text[]`, which+SQLite cannot bind, so the delivery branch never runs there. It runs here,+against the real column, through the real `run_once`.++**A closed investigation stores a branded summary.** The renderer is unit+covered next door. What that cannot see is whether the *route* resolves+branding and passes it -- the "mechanism exists, nothing calls it" shape this+repository keeps finding -- so this drives `POST /close` and reads the+artefact row back out of the database.++`ENVIRONMENT=test` and not `development`: `development` is in+`AUTH_BYPASS_ENVIRONMENTS`, so an uncredentialed request resolves to a demo+administrator -- which would turn the first assertion below, whose entire+subject is what happens *without* a credential, into a test of nothing.+"""++from __future__ import annotations++import os+import uuid+from collections.abc import AsyncIterator+from typing import TYPE_CHECKING, Any++import pytest+import pytest_asyncio++if TYPE_CHECKING:+ # Type-only. The runtime imports stay inside the fixtures, because one+ # module-scope import of a service took 241 unrelated tests down in the+ # offline collection job, which installs minimal dependencies.+ import httpx+ from sqlalchemy.ext.asyncio import AsyncSession++pytestmark = [+ pytest.mark.asyncio(loop_scope="module"),+ pytest.mark.skipif(+ not os.environ.get("ISOLATION_WHITE_LABEL_DSN", "").strip(),+ reason="ISOLATION_WHITE_LABEL_DSN is not set; this suite needs a live Postgres",+ ),+]++# Named for what it is. As `PASSWORD` the secret scanner reads the literal as+# a credential, and the alternative -- a `.gitleaksignore` entry -- is+# fingerprinted on the line number, so any later edit to this file would+# reopen the finding.+TEST_PASSPHRASE = "correct-horse-battery-staple-43"++PRODUCT = "Acme Shield"+SENDER = "Acme SOC"+PRIMARY = "#123456"+ACCENT = "#654321"+SUPPORT_URL = "https://support.acme.example"+FOOTER = "Acme Shield — operated by Acme Managed Security."++LOGO = b'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect width="40" height="40" fill="#123456"/></svg>'++#: The address that was hard-coded into every investigation summary.+PLATFORM_CONTACT = "[email protected]"+++def _dsn() -> str:+ value = os.environ.get("ISOLATION_WHITE_LABEL_DSN", "").strip()+ if not value:+ pytest.skip("ISOLATION_WHITE_LABEL_DSN is not set; this suite needs a live Postgres")+ return value+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def app_client() -> AsyncIterator[httpx.AsyncClient]:+ pytest.importorskip("httpx")+ os.environ["DATABASE_URL"] = _dsn()+ os.environ["ENVIRONMENT"] = "test"++ import httpx+ from app.main import create_application++ application = create_application()+ transport = httpx.ASGITransport(app=application)+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ yield client+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def db() -> AsyncIterator[AsyncSession]:+ pytest.importorskip("asyncpg")+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++ os.environ["DATABASE_URL"] = _dsn()+ engine = create_async_engine(_dsn(), future=True)+ maker = async_sessionmaker(engine, expire_on_commit=False)+ async with maker() as session:+ yield session+ await engine.dispose()+++async def _tenant(session: AsyncSession, label: str) -> uuid.UUID:+ import sqlalchemy++ tenant_id = uuid.uuid4()+ await session.execute(+ sqlalchemy.text("INSERT INTO tenants (id, name, slug) VALUES (:i, :n, :s)"),+ {"i": tenant_id, "n": f"{label}-{tenant_id.hex[:8]}", "s": f"{label}-{tenant_id.hex[:8]}"},+ )+ return tenant_id+++async def _user(session: AsyncSession, tenant_id: uuid.UUID, *, role: str = "admin") -> dict[str, Any]:+ """A real user row with a real bcrypt hash, so login is a real login."""+ import sqlalchemy+ from app.core.security import get_password_hash++ user_id = uuid.uuid4()+ email = f"wl-{user_id.hex[:10]}@example.com"+ await session.execute(+ sqlalchemy.text(+ "INSERT INTO users (id, tenant_id, email, username, role, is_active, hashed_password) VALUES (:i, :t, :e, :u, :r, TRUE, :p)"+ ),+ {+ "i": user_id,+ "t": tenant_id,+ "e": email,+ "u": email.split("@")[0],+ "r": role,+ "p": get_password_hash(TEST_PASSPHRASE),+ },+ )+ return {"id": user_id, "tenant_id": tenant_id, "email": email}+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def branded(db: AsyncSession) -> dict[str, Any]:+ """One white-labelled organisation with a managed tenant and a logo."""+ import sqlalchemy++ await db.rollback()+ org_id = uuid.uuid4()+ home_tenant = await _tenant(db, "wl-home")+ managed_tenant = await _tenant(db, "wl-managed")+ await db.execute(+ sqlalchemy.text("INSERT INTO organizations (id, slug, name, home_tenant_id) VALUES (:i, :s, :n, :h)"),+ {"i": org_id, "s": f"acme-{org_id.hex[:8]}", "n": "Acme Managed Security", "h": home_tenant},+ )+ await db.execute(+ sqlalchemy.text("INSERT INTO organization_tenants (org_id, tenant_id) VALUES (:o, :t)"),+ {"o": org_id, "t": managed_tenant},+ )+ await db.execute(+ sqlalchemy.text(+ "INSERT INTO aisoc_org_branding (org_id, product_name, primary_color, accent_color,"+ " support_url, sender_name, footer_text)"+ " VALUES (:o, :p, :pc, :ac, :su, :sn, :ft)"+ ),+ {"o": org_id, "p": PRODUCT, "pc": PRIMARY, "ac": ACCENT, "su": SUPPORT_URL, "sn": SENDER, "ft": FOOTER},+ )+ asset_id = uuid.uuid4()+ await db.execute(+ sqlalchemy.text(+ "INSERT INTO aisoc_org_brand_assets (id, org_id, kind, content_type, content, byte_size, sha256)"+ " VALUES (:i, :o, 'logo', 'image/svg+xml', :c, :b, :h)"+ ),+ {"i": asset_id, "o": org_id, "c": LOGO, "b": len(LOGO), "h": "0" * 64},+ )+ user = await _user(db, managed_tenant)+ await db.commit()+ return {"org_id": org_id, "tenant_id": managed_tenant, "asset_id": asset_id, "user": user}+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def outsider(db: AsyncSession) -> dict[str, Any]:+ """A member of a different, unbranded organisation."""+ await db.rollback()+ user = await _user(db, await _tenant(db, "wl-outsider"))+ await db.commit()+ return user+++async def _bearer(client: httpx.AsyncClient, user: dict[str, Any]) -> dict[str, str]:+ response = await client.post("/api/v1/auth/login", json={"email": user["email"], "password": TEST_PASSPHRASE})+ assert response.status_code == 200, response.text+ return {"Authorization": f"Bearer {response.json()['access_token']}"}+++class TestTheBrandAssetRoute:+ """The defect the plan asked to be verified rather than reasoned about."""++ async def test_the_request_an_img_tag_makes_is_refused(self, app_client: httpx.AsyncClient, branded: dict[str, Any]) -> None:+ """No credential, because an `<img src>` cannot send one.++ This is exactly the request the browser issued when `logo_url` was+ the `src`: a plain GET with no `Authorization` header. A 2xx here+ would mean the asset route is public, which is a different product+ than the one documented.+ """+ response = await app_client.get(f"/api/v1/branding/assets/{branded['asset_id']}")+ assert response.status_code in (401, 403), response.text++ async def test_the_console_fetch_carries_a_credential_and_gets_the_bytes(+ self, app_client: httpx.AsyncClient, branded: dict[str, Any]+ ) -> None:+ """The positive control for the case above.++ Without it, a route that was simply broken -- 401 to everyone,+ logo or not -- would satisfy the refusal assertion perfectly.+ """+ headers = await _bearer(app_client, branded["user"])+ response = await app_client.get(f"/api/v1/branding/assets/{branded['asset_id']}", headers=headers)+ assert response.status_code == 200, response.text+ assert response.content == LOGO+ assert response.headers["content-type"].startswith("image/svg+xml")++ async def test_another_organisations_member_cannot_read_the_asset(+ self, app_client: httpx.AsyncClient, branded: dict[str, Any], outsider: dict[str, Any]+ ) -> None:+ """A credential is not the same as *this* organisation's credential.++ The asset id is a bare UUID in a URL. If holding any session were+ enough, one operator's logo would be readable by every other+ organisation on the deployment.+ """+ headers = await _bearer(app_client, outsider)+ response = await app_client.get(f"/api/v1/branding/assets/{branded['asset_id']}", headers=headers)+ assert response.status_code in (403, 404), response.text++ async def test_the_resolved_logo_url_is_a_path_on_this_deployment(self, app_client: httpx.AsyncClient, branded: dict[str, Any]) -> None:+ """A remote logo would be an outbound request from the operator's+ browser on every page load, telling whoever hosts it who is+ looking at what -- and, in a server-rendered PDF, an outbound+ request made by the server to an address a customer supplied."""+ headers = await _bearer(app_client, branded["user"])+ body = (await app_client.get("/api/v1/branding", headers=headers)).json()+ assert body["product_name"] == PRODUCT+ assert body["sender_name"] == SENDER+ assert body["logo_url"] == f"/api/v1/branding/assets/{branded['asset_id']}"+ assert not body["logo_url"].startswith(("http://", "https://"))+++class TestTheScheduledReportEmail:+ """What the inherited unit suite deferred here, and why."""++ async def test_the_envelope_carries_the_operators_name_not_the_platforms(+ self, db: AsyncSession, branded: dict[str, Any], monkeypatch: pytest.MonkeyPatch+ ) -> None:+ import sqlalchemy+ from app.workers import report_scheduler++ sent: list[dict[str, Any]] = []++ async def _capture(**kwargs: Any) -> Any:+ sent.append(kwargs)++ class _Result:+ status = "sent"+ detail = "captured"++ return _Result()++ monkeypatch.setattr(report_scheduler, "send_mail", _capture)++ await db.rollback()+ template_id = uuid.uuid4()+ await db.execute(+ sqlalchemy.text(+ "INSERT INTO report_templates (id, tenant_id, name, report_type, cron_schedule,"+ " recipients, is_enabled)"+ " VALUES (:i, :t, :n, 'board_summary', '* * * * *', :r, TRUE)"+ ),+ # The Postgres `text[]` the unit suite cannot bind.+ {"i": template_id, "t": branded["tenant_id"], "n": "Weekly board pack", "r": ["[email protected]"]},+ )+ await db.commit()++ try:+ await report_scheduler.run_once()++ assert sent, "the scheduler generated no mail, so this asserts nothing"+ envelope = sent[-1]+ assert envelope["subject"].startswith(f"[{PRODUCT}]")+ assert "AiSOC" not in envelope["subject"]+ # `sender_name` is the one resolved field whose entire purpose is+ # naming who mail is from, and it reached no mailer on this path.+ assert envelope["settings"].sender_name == SENDER+ finally:+ await db.rollback()+ await db.execute(sqlalchemy.text("DELETE FROM report_artefacts WHERE template_id = :i"), {"i": template_id})+ await db.execute(sqlalchemy.text("DELETE FROM report_templates WHERE id = :i"), {"i": template_id})+ await db.commit()+++class TestTheClosedInvestigationSummary:+ """The wiring, as opposed to the renderer."""++ async def test_the_stored_artefact_carries_the_operators_brand(+ self, app_client: httpx.AsyncClient, db: AsyncSession, branded: dict[str, Any]+ ) -> None:+ import sqlalchemy++ await db.rollback()+ run_id = uuid.uuid4()+ await db.execute(+ sqlalchemy.text(+ "INSERT INTO investigation_runs (id, tenant_id, case_id, status, model_used, iterations, total_tokens)"+ " VALUES (:i, :t, 'CASE-4821', 'completed', 'llama3.2:3b', 3, 1234)"+ ),+ {"i": run_id, "t": branded["tenant_id"]},+ )+ await db.commit()++ headers = await _bearer(app_client, branded["user"])+ closed = await app_client.post(f"/api/v1/investigations/{run_id}/close", json={"analyst_note": None}, headers=headers)+ assert closed.status_code == 200, closed.text++ await db.rollback()+ content = (+ await db.execute(+ sqlalchemy.text(+ "SELECT content FROM investigation_artifacts WHERE run_id = :r"+ " AND kind = 'investigation-summary' ORDER BY created_at DESC LIMIT 1"+ ),+ {"r": run_id},+ )+ ).scalar_one()++ assert PRODUCT in content+ assert SUPPORT_URL in content+ # A document showing both names is co-branded, not white-labelled.+ assert "AiSOC" not in content+ assert PLATFORM_CONTACT not in content