Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(api): per-organisation white-label and usage metering from real rows (Phases 13.2, 13.3) (#935)

Beenu Aroraa7683368325d
diff --git a/.github/workflows/isolation.yml b/.github/workflows/isolation.yml
index bcd68293e..60c24ce45 100644
--- a/.github/workflows/isolation.yml
+++ b/.github/workflows/isolation.yml
@@ -31,6 +31,7 @@ on:
- "scripts/check_runtime_db_role.py"
- "scripts/check_rls_policy_shape.py"
- "scripts/check_scim_contract.py"
+ - "scripts/check_whitelabel_metering.py"
- "docker-compose.yml"
- "infra/**"
- ".env.example"
@@ -51,6 +52,7 @@ on:
- "scripts/check_runtime_db_role.py"
- "scripts/check_rls_policy_shape.py"
- "scripts/check_scim_contract.py"
+ - "scripts/check_whitelabel_metering.py"
- "docker-compose.yml"
- "infra/**"
- ".env.example"
@@ -206,6 +208,16 @@ jobs:
- name: The SCIM surface matches what it advertises, audits and grants
run: python scripts/check_scim_contract.py
+ # An uploaded logo renders in the console and inside PDF reports other
+ # people open, so the SVG allowlist is a security control under steady
+ # pressure to widen. And a meter added later with its tenant formatted
+ # in would count every tenant's rows while its own test passed.
+ - name: White-label and metering gate self-test (four injected drifts)
+ run: python scripts/check_whitelabel_metering.py --self-test
+
+ - name: The SVG allowlist admits nothing executable and every meter binds its tenant
+ run: python scripts/check_whitelabel_metering.py
+
- name: Start Redis for the two-tenant route replay
run: |
docker run -d --name route-iso-redis -p 6379:6379 redis:7-alpine
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 02c9cb917..69e0f8da1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -95,6 +95,70 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`services/agents` 1390 to 1423 tests, `services/api` 2970 to 3007.
### Added
+- **Per-organisation white-label branding, with uploaded assets treated as a
+ security boundary** (gap-closure Phase 13.2).
+
+ **The gap.** A managed-service provider had no way to present AiSOC as its
+ own product. The name, the palette and the support contacts were the
+ platform's, in every console its customers opened and on every report it
+ forwarded to their board.
+
+ **What ships.** One row per operator organisation sets product name, colours,
+ support contacts and sender name, resolved field by field so an organisation
+ that sets a name and no colours renders its name against the platform
+ palette rather than losing the one field it configured. Applied to the
+ console shell and to the executive digest in HTML and PDF.
+
+ **Why the assets are bytes and not a URL.** The plan says stored locally and
+ never fetched from a third party, and the reason is not convenience. A remote
+ logo is an outbound request made by whatever renders it: by every console
+ that draws it, and for a PDF by the *server*, which turns a customer-supplied
+ address into a server-side request forgery primitive. The test asserts the
+ rendered report contains no external URL at all, rather than asserting one
+ particular attribute is absent.
+
+ **Why an SVG is sanitised against an allowlist.** SVG is XML with a scripting
+ model, and a logo uploaded by a customer administrator is rendered inside
+ consoles and inside reports other people open. A denylist of `<script>`
+ passes while `<foreignObject>` renders arbitrary HTML, so only drawing
+ elements and presentation attributes survive; everything else is dropped with
+ its subtree. Event handlers go by shape rather than enumeration, a paint
+ reference may only point inside the same document, and a file declaring a
+ `DOCTYPE` or an `ENTITY` is refused on a byte scan **before** parsing, which
+ removes both entity-expansion denial-of-service variants rather than bounding
+ them. Detection is on the bytes as well as the declared content type, because
+ the uploader controls that header and skipping the sanitiser is the whole
+ attack. 29 cases, written as attacks; a benign logo is asserted to survive
+ intact, because a sanitiser that removes everything is safe and useless.
+
+- **Usage metering computed from the rows that record the work** (gap-closure
+ Phase 13.3).
+
+ **The gap.** There was no per-tenant record of what a deployment had
+ actually done: alerts, triages by path, investigations, tokens, measured
+ model cost, response actions, connectors and seats.
+
+ **How it is measured, and why that shape.** Ten meters, each a `SELECT`
+ against the table holding the evidence, evaluated when somebody asks. Not a
+ counter table incremented as things happen: a counter drifts from the table
+ it summarises and nothing notices, which is what made `cases_closed_7d` and
+ `mttr_hours` wrong on real data while their tests passed. It is also what
+ makes the acceptance checkable, since a counter can only be tested against
+ itself. Every assertion in the test counts rows independently and compares;
+ the daily series summed must equal one query over the whole window, and the
+ fixture seeds an alert at exactly midnight so a closed interval would
+ double-count it. `GET /api/v1/usage/reconciliation` exposes the same
+ comparison so an operator can run it against their own rows.
+
+ **Honesty.** `events_ingested` lives in the ClickHouse lake, a `full`-profile
+ service, and reads "not measured" with the reason in both the API response
+ and the CSV header. Never `0`: zero is a measurement, and a reader who sees
+ it concludes no events arrived rather than that nothing looked. No pricing
+ logic, gated by `check_whitelabel_metering.py` reading the meter
+ declarations. Linked to the existing entitlement limits, returned alongside
+ the counts, so a usage screen and a quota screen cannot disagree about the
+ same rows.
+
- **SCIM 2.0 provisioning, scoped by its credential and tested against two
identity providers that disagree with each other** (gap-closure Phase 13.1).
diff --git a/GAP_CLOSURE_PROGRESS.md b/GAP_CLOSURE_PROGRESS.md
index 48649a402..682513862 100644
--- a/GAP_CLOSURE_PROGRESS.md
+++ b/GAP_CLOSURE_PROGRESS.md
@@ -460,9 +460,9 @@ suites' job, and anything at all against a live vendor MCP server.
## Phase 13: Enterprise identity and MSSP plumbing
-- [x] **13.1 SCIM 2.0** with Users, Groups, ServiceProviderConfig, ResourceTypes and Schemas, per-organization hashed rotatable tokens, and audited deprovisioning. Migration `071_scim_provisioning.sql`; router at `/scim/v2` (17 routes); `scripts/check_scim_contract.py` wired into `isolation.yml`; Okta-shaped and Entra-shaped sequences pass in `test_scim_provisioning.py` (54 tests). See D28, D29 and D30.
-- [ ] **13.2 MSSP white-label** per organization across console, PDF, digests, email approvals and ChatOps, with SVGs sanitized and assets stored locally.
-- [ ] **13.3 Usage metering** from real rows, exposed through an API and a monthly CSV, with no pricing logic.
+- [x] **13.1 SCIM 2.0** with Users, Groups, ServiceProviderConfig, ResourceTypes and Schemas, per-organization hashed rotatable tokens, and audited deprovisioning. Migration `070_scim_provisioning.sql`; router at `/scim/v2` (17 routes); `scripts/check_scim_contract.py` wired into `isolation.yml`; Okta-shaped and Entra-shaped sequences pass in `test_scim_provisioning.py` (54 tests). See D26, D27 and D28.
+- [~] **13.2 MSSP white-label** per organization. Console and PDF/digest are implemented and gated; assets are held as bytes in `aisoc_org_brand_assets` and SVGs are allowlist-sanitised (migration `072_org_branding.sql`, `app/services/branding/`). Email approvals and ChatOps read the resolved `sender_name` but are **not** covered end to end, and the doc says so. See D29.
+- [x] **13.3 Usage metering** from real rows: `app/services/usage_metering.py`, ten meters each a query against the table holding the evidence, `GET /api/v1/usage`, `/usage/reconciliation` and `/usage/export.csv`. Linked to `entitlements.headroom_for_tenant`. No pricing logic, gated. See D30.
- [ ] **13.4 Console i18n** with a pilot locale, RTL, locale-aware formatting and a missing-keys gate.
---
@@ -1481,3 +1481,56 @@ a revocation exists, so credentials minted before this change fail closed.
Both the access-token path and the refresh path check it. The refresh path
matters more: a refresh token outlives an access token by days.
+
+### D29. White-label reaches the two surfaces the acceptance names, and not the other three
+
+13.2 lists five surfaces: console, PDF reports, digests, email approvals and
+ChatOps. The phase's own "Done when" names two of them, "a white-labelled
+organization's PDF report and console show its branding", and those two are
+implemented and gated end to end.
+
+The digest *is* the PDF path, so it comes with them: `render_digest_pdf` runs
+`render_digest_html` through WeasyPrint, and the test asserts on the HTML,
+which is what the PDF contains.
+
+Email approvals and ChatOps resolve the same `sender_name` from the same
+resolver, and there is no end-to-end test that an outbound message carries it.
+Recorded as `[~]` rather than `[x]`, and
+`apps/docs/docs/operations/white-label.md` says "treat those as unverified
+rather than working" instead of implying coverage that does not exist. The
+alternative, marking the item done because the field resolves, is the shape
+this program exists to prevent.
+
+**The design decision worth keeping:** asset bytes live in Postgres and are
+served from this deployment. A logo referenced by URL is an outbound request
+made by whatever renders it, and for a PDF that renderer is the *server*, so a
+customer-supplied address becomes a server-side request forgery primitive. The
+test asserts the rendered report contains no external URL at all rather than
+asserting the specific attribute is absent.
+
+### D30. Metering is computed, not counted, and that is what makes it testable
+
+The obvious design for 13.3 is a `usage_daily` table incremented as things
+happen. Every meter here is instead a `SELECT` against the table that holds
+the evidence, evaluated when somebody asks.
+
+The reason is the acceptance itself. "Metering matches row counts in a test"
+cannot be demonstrated against a counter table, because the only thing
+available to compare it with is the counter. Against a query, the test counts
+rows independently and compares, which is the arrangement where a
+disagreement can actually surface. It is also the failure this repository has
+already paid for twice: `cases_closed_7d` filtered an intermediate status and
+`mttr_hours` averaged a column ordinary case work never writes, and both
+passed tests that compared a producer against a copy of itself.
+
+The second property a naive implementation gets wrong is day boundaries. The
+windows are half-open, the daily series summed is asserted equal to one query
+over the whole range, and the fixture puts an alert at exactly 00:00 so a
+closed interval would double-count it. `GET /usage/reconciliation` exposes the
+same comparison, so an operator disputing a figure can run it against their
+own rows rather than taking a test's word for it.
+
+`events_ingested` is in the ClickHouse lake, which is a `full`-profile
+service. It reads "not measured" with the reason, in the API response and in
+the CSV header, and a test asserts it is not *also* declared as a meter so it
+can never be reported as a number.
diff --git a/ROADMAP.md b/ROADMAP.md
index f607df5a6..df84b5ba9 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
-The claim-to-gate matrix stands at **209 rows — 201 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
+The claim-to-gate matrix stands at **213 rows — 205 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
## v4.0 — Shipped
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index f63009023..32a007537 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
-The last row is the one worth reading first. It is the honest index: 201 rows
+The last row is the one worth reading first. It is the honest index: 205 rows
`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refuses
to let a row sit at `NO GATE`.
diff --git a/apps/docs/docs/operations/usage-metering.md b/apps/docs/docs/operations/usage-metering.md
new file mode 100644
index 000000000..ee753694f
--- /dev/null
+++ b/apps/docs/docs/operations/usage-metering.md
@@ -0,0 +1,101 @@
+---
+title: Usage metering
+sidebar_label: Usage metering
+description: Per-tenant, per-day usage counted from the rows that record the work, with a monthly CSV export.
+---
+
+# Usage metering
+
+What a tenant did, per day, counted from the rows that record it.
+
+There is no pricing here. These are counts and measured model costs. What
+they are worth is a commercial question and deliberately lives nowhere near
+the code that answers what happened.
+
+## What is metered
+
+| Meter | Source table | Meaning |
+|---|---|---|
+| `alerts` | `alerts` | Alerts created in the window |
+| `triages_model` | `alerts` | Alerts carrying model-generated triage output |
+| `triages_deterministic` | `alerts` | Alerts resolved without model output |
+| `investigations` | `investigation_runs` | Agent investigation runs started |
+| `llm_tokens` | `aisoc_run_costs` | Prompt plus completion tokens |
+| `llm_cost_usd` | `aisoc_run_costs` | Measured model spend |
+| `actions` | `aisoc_action_records` | Response actions recorded |
+| `actions_executed` | `aisoc_action_records` | Of those, the ones that reached a vendor |
+| `active_connectors` | `connectors` | Enabled data sources, right now |
+| `seats` | `users` | Active user accounts, right now |
+
+`triages_model` and `triages_deterministic` partition `alerts` exactly: their
+sum equals the total, so there is no triage unaccounted for and none counted
+twice.
+
+The last two are point-in-time rather than windowed. Counting them per day
+would report today's value against every historical day, which looks like
+data and is not.
+
+## What is not measured
+
+`events_ingested` lives in the ClickHouse event lake, which runs in the
+`full` profile. On a deployment without it, that meter is reported as **not
+measured**, named with the reason, in both the API response and the CSV
+header.
+
+It is never reported as `0`. Zero is a measurement, and a reader who sees it
+concludes no events arrived rather than that nothing looked.
+
+## Reading it
+
+```bash
+curl "https://<your-aisoc-host>/api/v1/usage?start=2026-03-01&end=2026-03-31" \
+ -H "Authorization: Bearer $AISOC_SESSION_TOKEN"
+```
+
+Defaults to the last 30 days. The maximum window in one request is 186 days;
+export a month at a time beyond that.
+
+The response carries the daily series, the totals, the point-in-time figures,
+the meters' own definitions and source tables, whatever was not measured, and
+the entitlement headroom those counts run against. The last of those is
+deliberate: a usage screen and a quota screen that compute their numbers
+separately are two surfaces that will eventually disagree in front of a
+customer.
+
+The tenant comes from your credential. There is no tenant parameter on any of
+these routes, because usage is the input to a commercial conversation and a
+surface that let one customer name another's tenant would publish their
+volume.
+
+## Monthly CSV
+
+```bash
+curl "https://<your-aisoc-host>/api/v1/usage/export.csv?month=2026-03" \
+ -H "Authorization: Bearer $AISOC_SESSION_TOKEN" -o march.csv
+```
+
+Requires `reports:read`. The file carries a header block naming the tenant,
+the operator organisation and the generation time, because a bare grid of
+numbers in a downloads folder cannot answer what it is about.
+
+## Checking the numbers
+
+Metering is computed from the source tables when you ask, rather than kept in
+a counter table that is incremented as things happen. A counter drifts from
+the table it summarises and nothing notices; a query cannot, because the
+number *is* the rows.
+
+You can verify that directly:
+
+```bash
+curl "https://<your-aisoc-host>/api/v1/usage/reconciliation?start=2026-03-01&end=2026-03-31" \
+ -H "Authorization: Bearer $AISOC_SESSION_TOKEN"
+```
+
+This runs each meter twice, once per day and summed, and once as a single
+query over the whole window, and reports both figures with whether they
+agree. Day boundaries are where a row gets dropped or counted twice, and
+neither shows up in a single-day check.
+
+The same comparison runs in CI against a seeded corpus, including an alert
+placed at exactly midnight.
diff --git a/apps/docs/docs/operations/white-label.md b/apps/docs/docs/operations/white-label.md
new file mode 100644
index 000000000..fb09b182d
--- /dev/null
+++ b/apps/docs/docs/operations/white-label.md
@@ -0,0 +1,129 @@
+---
+title: White-label branding
+sidebar_label: White-label branding
+description: Apply your own product name, logo, colours and support contacts across the console and reports.
+---
+
+# White-label branding
+
+A managed-service provider can present AiSOC as its own product. Branding is
+set once per operator organisation and applies to every tenant in that
+organisation's portfolio, plus the organisation's own staff console.
+
+## What is branded
+
+| Surface | What changes |
+|---|---|
+| Console | Product name, logo, accent colour |
+| Executive digest (HTML and PDF) | Product name, logo, accent colour, footer, support link |
+| Usage CSV export | The organisation named in the header block |
+
+Branding resolves field by field. An organisation that sets a product name
+and no colours renders its name against the platform palette, rather than
+losing the one field it configured.
+
+## Setting it
+
+```bash
+curl -X PUT https://<your-aisoc-host>/api/v1/branding \
+ -H "Authorization: Bearer $AISOC_SESSION_TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "product_name": "Acme Shield",
+ "primary_color": "#123456",
+ "accent_color": "#654321",
+ "support_email": "[email protected]",
+ "support_url": "https://support.acme.example",
+ "sender_name": "Acme SOC"
+ }'
+```
+
+Requires `settings:write`, and applies to the organisation your tenant
+belongs to. There is no field for naming a different organisation: that would
+let an authenticated user of one tenant rebrand somebody else's console.
+
+`support_url` must be `https`. It is rendered as a link in email and in PDF
+reports, so a `javascript:` or `data:` value there would be a stored script
+in somebody else's inbox.
+
+If your tenant does not belong to an organisation, this returns 409. Create
+an organisation and add the tenant to its portfolio first.
+
+## Uploading a logo
+
+```bash
+curl -X POST https://<your-aisoc-host>/api/v1/branding/assets/logo \
+ -H "Authorization: Bearer $AISOC_SESSION_TOKEN" \
+```
+
+Accepted types are `image/svg+xml`, `image/png`, `image/jpeg` and
+`image/webp`, up to 256 KB.
+
+Assets are **stored in your deployment**, never referenced by URL. A logo
+fetched from a remote address would be an outbound request made by every
+console that renders it and, for a PDF, by the server itself. Reports also
+stay readable years later, rather than turning into a broken image when
+somebody tidies up a bucket.
+
+### SVG uploads are sanitised
+
+SVG is XML with a scripting model. It can carry `<script>`, event handler
+attributes, `<foreignObject>` containing arbitrary HTML, CSS that fetches
+remote resources, and references to other documents. A logo uploaded by an
+administrator is rendered inside consoles and inside reports that other
+people open, so an unsanitised SVG is a stored cross-site scripting vector
+with a distribution mechanism attached.
+
+Uploads are therefore rewritten against an **allowlist**, not scrubbed
+against a denylist:
+
+- Only drawing elements survive: shapes, paths, text, gradients, clip paths,
+ masks and groups. `<script>`, `<foreignObject>`, `<use>`, `<image>`,
+ `<style>`, `<a>` and every animation element are dropped with their
+ subtrees.
+- Only geometry and presentation attributes survive. Every attribute
+ beginning `on` is dropped by shape, as is anything in the `xlink`
+ namespace.
+- A paint reference may only point inside the same document. `fill="url(#g1)"`
+ survives; `fill="url(https://…)"` does not.
+- A document declaring a `DOCTYPE` or an `ENTITY` is **refused outright**,
+ before parsing. Both entity-expansion denial-of-service variants need one,
+ and a logo has no use for either.
+- The stored file is re-serialised from the parsed document, so anything the
+ parser did not understand cannot survive into it.
+
+The response tells you what was removed:
+
+```json
+{
+ "was_sanitized": true,
+ "removed": { "elements": ["script"], "attributes": ["onload"] }
+}
+```
+
+If your logo renders differently from your graphics program, that field is
+the explanation. Exporting as a plain path-based SVG, or as PNG, usually
+resolves it.
+
+Detection is on the bytes as well as the declared content type. An SVG
+announced as `image/png` still goes through the sanitiser, because the
+uploader controls that header.
+
+## Removing branding
+
+```bash
+curl -X DELETE https://<your-aisoc-host>/api/v1/branding/assets/logo \
+ -H "Authorization: Bearer $AISOC_SESSION_TOKEN"
+```
+
+Clearing every field on `PUT /api/v1/branding` returns each surface to the
+platform appearance.
+
+## What is not branded yet
+
+Email approvals and ChatOps messages resolve the sender name from the same
+place, and the plan lists them alongside the console and reports. The console
+and the report path are implemented and gated; the notification surfaces read
+the resolved `sender_name` but are not yet covered by an end-to-end test, so
+treat those as unverified rather than working.
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index 58936a253..ad676158a 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -187,6 +187,8 @@ const sidebars: SidebarsConfig = {
"operations/credentials",
"operations/secrets",
"operations/scim",
+ "operations/white-label",
+ "operations/usage-metering",
"operations/ingest-authentication",
"operations/airgap",
"operations/air-gapped",
diff --git a/apps/web/src/components/layout/Sidebar.tsx b/apps/web/src/components/layout/Sidebar.tsx
index fc1a15d26..704e0f6a1 100644
--- a/apps/web/src/components/layout/Sidebar.tsx
+++ b/apps/web/src/components/layout/Sidebar.tsx
@@ -6,6 +6,7 @@ import { usePathname } from 'next/navigation';
import { clsx } from 'clsx';
import packageJson from '../../../package.json';
import { LiveQueueBadge } from './LiveQueueBadge';
+import { useBranding } from '@/hooks/useBranding';
const APP_VERSION = packageJson.version;
@@ -353,6 +354,10 @@ const navSections: NavSection[] = [
];
export function Sidebar() {
+ // Resolved server-side from the organisation this tenant belongs to. An
+ // unbranded deployment gets the platform defaults from the same call, so
+ // there is one code path rather than two that drift.
+ const { branding } = useBranding();
const pathname = usePathname();
const [mobileOpen, setMobileOpen] = useState(false);
@@ -392,15 +397,29 @@ export function Sidebar() {
>
{/* Logo */}
<div className="flex items-center gap-3 px-5 h-16 border-b border-surface-border">
- <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-brand-600/20 border border-brand-600/30 flex items-center justify-center">
- <span className="text-brand-400">
- <ShieldIcon />
- </span>
+ <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-brand-600/20 border border-brand-600/30 flex items-center justify-center overflow-hidden">
+ {branding.logo_url ? (
+ // Served from this deployment. The API never returns a
+ // third-party address, so this cannot become a request to
+ // somebody else's host on every page load.
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={branding.logo_url} alt="" className="w-full h-full object-contain" />
+ ) : (
+ <span className="text-brand-400">
+ <ShieldIcon />
+ </span>
+ )}
</div>
<div>
- <span className="text-fg-primary font-bold text-base tracking-tight">Ai</span>
- <span className="text-brand-400 font-bold text-base tracking-tight">SOC</span>
- <p className="text-xs text-fg-subtle -mt-0.5">open-source</p>
+ {branding.is_white_labelled ? (
+ <span className="text-fg-primary font-bold text-base tracking-tight">{branding.product_name}</span>
+ ) : (
+ <>
+ <span className="text-fg-primary font-bold text-base tracking-tight">Ai</span>
+ <span className="text-brand-400 font-bold text-base tracking-tight">SOC</span>
+ <p className="text-xs text-fg-subtle -mt-0.5">open-source</p>
+ </>
+ )}
</div>
{/* Live indicator — decorative, status conveyed by the green dot label */}
<div className="ml-auto flex items-center gap-1" aria-hidden="true">
diff --git a/apps/web/src/components/layout/SidebarBranding.test.tsx b/apps/web/src/components/layout/SidebarBranding.test.tsx
new file mode 100644
index 000000000..f22f9db52
--- /dev/null
+++ b/apps/web/src/components/layout/SidebarBranding.test.tsx
@@ -0,0 +1,82 @@
+/**
+ * The console half of Phase 13.2's acceptance.
+ *
+ * A white-labelled organisation's console has to show its branding, and the
+ * only way to prove that is to render the shell against a branded response
+ * and read what comes out. Asserting that the hook returns the right object
+ * would prove the hook works and say nothing about whether anything renders
+ * it, which is the shape of failure this program keeps finding.
+ *
+ * The API client is mocked rather than the hook, so the wiring between the
+ * two is inside the test rather than stubbed over.
+ */
+import { describe, expect, it, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+
+vi.mock('next/navigation', () => ({
+ usePathname: () => '/dashboard',
+}));
+
+vi.mock('next/link', () => ({
+ default: ({ children, href, className }: { children: React.ReactNode; href: string; className?: string }) => (
+ <a href={href} className={className}>
+ {children}
+ </a>
+ ),
+}));
+
+// `vi.mock` is hoisted above every top-level statement in this file, so a
+// plain `const` referenced from the factory is still in its temporal dead
+// zone when the factory runs. `vi.hoisted` is the supported way to share a
+// value with one.
+const { brandedResponse } = vi.hoisted(() => ({
+ brandedResponse: {
+ product_name: 'Acme Shield',
+ primary_color: '#123456',
+ accent_color: '#654321',
+ support_email: null,
+ support_url: 'https://support.acme.example',
+ sender_name: 'Acme Shield',
+ footer_text: 'Acme Shield',
+ logo_url: '/api/v1/branding/assets/00000000-0000-0000-0000-0000000000aa',
+ org_id: '0a0a0a0a-0000-0000-0000-00000000000a',
+ is_white_labelled: true,
+ },
+}));
+
+vi.mock('@/lib/api', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/lib/api')>();
+ return {
+ ...actual,
+ // A plain async function rather than `vi.fn()`: this suite runs with
+ // mock clearing on, which strips a `vi.fn()` implementation between
+ // tests and would leave the second one resolving `undefined`.
+ brandingApi: { get: async () => brandedResponse },
+ };
+});
+
+import { Sidebar } from './Sidebar';
+
+describe('Sidebar branding', () => {
+ // One render for every assertion, deliberately. SWR keeps a module-level
+ // cache and a deduping window, so a second `render` in this file resolves
+ // from neither the cache nor a fresh request and shows the unbranded
+ // wordmark. Splitting these would test the cache rather than the console.
+ it("shows a white-labelled organisation's name and logo, and drops the platform wordmark", async () => {
+ const { container } = render(<Sidebar />);
+
+ expect(await screen.findByText('Acme Shield')).toBeInTheDocument();
+
+ // The platform wordmark is gone. A console showing both is not
+ // white-labelled, it is co-branded by accident.
+ expect(screen.queryByText('open-source')).not.toBeInTheDocument();
+
+ const logo = container.querySelector('img');
+ expect(logo).not.toBeNull();
+ const src = logo?.getAttribute('src') ?? '';
+ expect(src.startsWith('/api/v1/branding/assets/')).toBe(true);
+ // 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.
+ expect(src).not.toMatch(/^https?:\/\//);
+ });
+});
diff --git a/apps/web/src/hooks/useBranding.ts b/apps/web/src/hooks/useBranding.ts
new file mode 100644
index 000000000..ab0af4dfa
--- /dev/null
+++ b/apps/web/src/hooks/useBranding.ts
@@ -0,0 +1,38 @@
+'use client';
+
+import useSWR from 'swr';
+
+import { type Branding, brandingApi } from '@/lib/api';
+
+/**
+ * The platform appearance, used while the request is in flight and if it fails.
+ *
+ * This is not mock data. It is what an unbranded deployment genuinely looks
+ * like, and it is the same set of values the API returns for a tenant that
+ * belongs to no organisation. Rendering an empty header instead would make
+ * every page load flash a nameless product.
+ */
+export const DEFAULT_BRANDING: Branding = {
+ product_name: 'AiSOC',
+ primary_color: '#2563EB',
+ accent_color: '#7C3AED',
+ support_email: null,
+ support_url: null,
+ sender_name: 'AiSOC',
+ footer_text: 'AiSOC — open-source AI Security Operations Center.',
+ logo_url: null,
+ org_id: null,
+ is_white_labelled: false,
+};
+
+export function useBranding(): { branding: Branding; isLoading: boolean } {
+ const { data, isLoading } = useSWR<Branding>('branding', () => brandingApi.get(), {
+ // Branding moves when an administrator moves it, which is rare.
+ // Revalidating on focus would put a request behind every tab switch for
+ // a value that has not changed.
+ revalidateOnFocus: false,
+ dedupingInterval: 300_000,
+ });
+
+ return { branding: data ?? DEFAULT_BRANDING, isLoading };
+}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index c975bf8fc..6fbda6ac8 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -405,6 +405,35 @@ export interface TenantUser {
created_at: string;
}
+/**
+ * What the product is called and what it looks like, for this tenant.
+ *
+ * Resolved server-side from the organisation the tenant belongs to, so the
+ * console never has to know whether a deployment is white-labelled: an
+ * unbranded one gets the platform defaults from the same endpoint. One code
+ * path rather than a branded one and an unbranded one that drift.
+ */
+export interface Branding {
+ product_name: string;
+ primary_color: string;
+ accent_color: string;
+ support_email: string | null;
+ support_url: string | null;
+ sender_name: string;
+ footer_text: string;
+ /** A path on this deployment, never a third-party address. */
+ logo_url: string | null;
+ org_id: string | null;
+ is_white_labelled: boolean;
+}
+
+export const brandingApi = {
+ /** Readable by any authenticated member; the console calls it per page load. */
+ async get(): Promise<Branding> {
+ return request<Branding>('/api/v1/branding');
+ },
+};
+
export const tenantsApi = {
/**
* Lightweight tenant identity for the SOC console TopBar.
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 7874ea852..329c4595a 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -217,6 +217,10 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| SCIM deprovisioning ends access rather than flagging a row | `plans/aisoc_gap_closure_plan.plan.md` (13.1); `docs/decisions/0008-scim-trust-boundary.md`; `apps/docs/docs/operations/scim.md` (What deprovisioning does) | `ci.yml` api job (`test_scim_provisioning.py::TestDeprovisioning` - a deactivation is asserted to revoke the principal's API keys by **count**, and to stamp `sessions_revoked_at`; `token_is_revoked` is asserted in all four directions including the fail-closed case of a token with no `iat`; minted tokens are asserted to carry `iat`, so the check has something to read; re-activation is asserted **not** to restore revoked API keys; the whole chain is repeated end to end through `DELETE /scim/v2/Users/{id}`) | GATED | DELETE deactivates rather than erasing, which RFC 7644 permits: erasing the row would take the principal's audit attribution and case history with it. A pre-existing fall-through that left a deactivated user's API key working under a generic role is closed in the same change |
| A directory group confers only a role AiSOC enforces, and an unrecognised group confers nothing | `plans/aisoc_gap_closure_plan.plan.md` (13.1); `apps/docs/docs/operations/scim.md` (Mapping groups to roles) | `isolation.yml` (`check_scim_contract.py` compares the group-to-role mapping against `ROLE_PERMISSIONS` in **both** directions, so a role renamed there cannot leave a mapping pointing at a string that grants nothing, and a *new* role must be classified as assignable or recorded as deliberately unreachable; proven able to fail by introducing an unclassified role) + `ci.yml` api job (`test_scim_provisioning.py::TestRoleMapping` - membership is asserted to write `users.role`, which is the column the permission check reads, and removal to take it back; an unmapped group is asserted to confer nothing; no group name resolves to a wildcard role) | GATED | Precedence is a total order, so a principal in several mapped groups holds the same role regardless of the order a provider syncs in |
| 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) | 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" |
+| 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) | 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) | 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 |
+| 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`, 15 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` is asserted to equal `alerts` exactly, so no triage is unaccounted for or double-counted) | 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. `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 in `UNMEASURED` with a reason and is **not** also a meter, so it can never be reported as a number; 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) | 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 |
## Summary
@@ -224,7 +228,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- GATED: 201
+- GATED: 205
- PARTIAL: 8
- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)
diff --git a/docs/audit/REPOSITORY_REALITY.md b/docs/audit/REPOSITORY_REALITY.md
index 1ec63976f..60dfdf9b5 100644
--- a/docs/audit/REPOSITORY_REALITY.md
+++ b/docs/audit/REPOSITORY_REALITY.md
@@ -203,6 +203,28 @@ principal, OIDC or SAML authenticates them.
---
+## White-label and usage metering
+
+**White-label — WORKING on two of five surfaces, and the tracker says which.**
+Console and the executive digest in HTML and PDF carry a white-labelled
+organisation's product name, palette and logo, asserted in CI. Email approvals
+and ChatOps resolve the same `sender_name` from the same resolver and have **no
+end-to-end test**, so they are recorded as unverified rather than working. The
+plan lists five surfaces and its own acceptance names two; marking the item
+done because a field resolves would be the failure this audit exists to catch.
+
+Brand assets are held as bytes in Postgres and served from this deployment.
+Nothing is fetched from a third-party URL, in the console or in the
+server-side PDF renderer. Uploaded SVGs are rewritten against an allowlist and
+a document declaring a DTD or an entity is refused before parsing.
+
+**Usage metering — WORKING, and it equals the rows by construction.** Ten
+meters, each a query against the table holding the evidence, with no counter
+table to drift. `events_ingested` is the one meter with no source on a CORE
+deployment and reports "not measured" with its reason rather than zero.
+
+---
+
## Data integrity
The project's rule is that fabricated security data must never render as a
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index cf0dc69ab..291002521 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -2566,6 +2566,133 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/usage:
+ get:
+ tags:
+ - usage
+ summary: Get Usage
+ description: Daily usage for the caller's tenant, defaulting to the last 30
+ days.
+ operationId: get_usage_api_v1_usage_get
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: start
+ in: query
+ required: false
+ schema:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Start
+ - name: end
+ in: query
+ required: false
+ schema:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: End
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+ title: Response Get Usage Api V1 Usage Get
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/usage/reconciliation:
+ get:
+ tags:
+ - usage
+ summary: Get Reconciliation
+ description: 'Compare the daily sum against one query over the whole window.
+
+
+ Exposed rather than kept in a test so an operator disputing an invoice
+
+ can run the same check the test runs, against their own rows.'
+ operationId: get_reconciliation_api_v1_usage_reconciliation_get
+ parameters:
+ - name: current_user
+ in: query
+ required: true
+ schema:
+ title: Current User
+ - name: start
+ in: query
+ required: false
+ schema:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Start
+ - name: end
+ in: query
+ required: false
+ schema:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: End
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+ title: Response Get Reconciliation Api V1 Usage Reconciliation Get
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/usage/export.csv:
+ get:
+ tags:
+ - usage
+ summary: Export Month
+ description: A month of usage as CSV, labelled with the organisation it belongs
+ to.
+ operationId: export_month_api_v1_usage_export_csv_get
+ parameters:
+ - name: current_user
+ in: query
+ required: true
+ schema:
+ title: Current User
+ - name: month
+ in: query
+ required: false
+ schema:
+ anyOf:
+ - type: string
+ - type: 'null'
+ description: YYYY-MM; defaults to the current month
+ title: Month
+ description: YYYY-MM; defaults to the current month
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema: {}
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
/api/v1/rules:
get:
tags:
@@ -6761,6 +6888,174 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/branding:
+ get:
+ tags:
+ - branding
+ summary: Get Branding
+ description: 'What the product looks like for the caller''s tenant.
+
+
+ Readable by any authenticated member. The console calls it on every page
+
+ load, and gating it behind an administrative permission would leave an
+
+ analyst looking at a differently-branded product from their colleague.'
+ operationId: get_branding_api_v1_branding_get
+ security:
+ - HTTPBearer: []
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+ title: Response Get Branding Api V1 Branding Get
+ put:
+ tags:
+ - branding
+ summary: Put Branding
+ description: Set branding for the organisation the caller's tenant belongs to.
+ operationId: put_branding_api_v1_branding_put
+ parameters:
+ - name: current_user
+ in: query
+ required: true
+ schema:
+ title: Current User
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BrandingIn'
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+ title: Response Put Branding Api V1 Branding Put
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/branding/assets/{kind}:
+ post:
+ tags:
+ - branding
+ summary: Upload Asset
+ description: 'Upload a logo or favicon.
+
+
+ An SVG goes through the sanitiser and what is stored is the sanitised
+
+ output. Nothing re-sanitises at render time, so this handler is the only
+
+ writer and the stored bytes are trusted thereafter.'
+ operationId: upload_asset_api_v1_branding_assets__kind__post
+ parameters:
+ - name: kind
+ in: path
+ required: true
+ schema:
+ type: string
+ title: Kind
+ - name: current_user
+ in: query
+ required: true
+ schema:
+ title: Current User
+ requestBody:
+ required: true
+ content:
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/Body_upload_asset_api_v1_branding_assets__kind__post'
+ responses:
+ '201':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+ title: Response Upload Asset Api V1 Branding Assets Kind Post
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ delete:
+ tags:
+ - branding
+ summary: Delete Asset
+ description: Remove an asset, returning that surface to the wordmark.
+ operationId: delete_asset_api_v1_branding_assets__kind__delete
+ parameters:
+ - name: kind
+ in: path
+ required: true
+ schema:
+ type: string
+ title: Kind
+ - name: current_user
+ in: query
+ required: true
+ schema:
+ title: Current User
+ responses:
+ '204':
+ description: Successful Response
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/branding/assets/{asset_id}:
+ get:
+ tags:
+ - branding
+ summary: Get Asset
+ description: 'Serve a brand asset from this deployment.
+
+
+ Scoped to the caller''s own organisation. The bytes are not secret, but
+
+ an unscoped read would let any authenticated user enumerate every
+
+ operator''s logo, which is a customer list.'
+ operationId: get_asset_api_v1_branding_assets__asset_id__get
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: asset_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ title: Asset Id
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema: {}
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
/api/v1/compliance/frameworks:
get:
tags:
@@ -19013,6 +19308,64 @@ components:
- type_breakdown
- blast_radius_score
title: BlastRadiusResponse
+ Body_upload_asset_api_v1_branding_assets__kind__post:
+ properties:
+ file:
+ type: string
+ contentMediaType: application/octet-stream
+ title: File
+ type: object
+ required:
+ - file
+ title: Body_upload_asset_api_v1_branding_assets__kind__post
+ BrandingIn:
+ properties:
+ product_name:
+ anyOf:
+ - type: string
+ maxLength: 80
+ minLength: 1
+ - type: 'null'
+ title: Product Name
+ primary_color:
+ anyOf:
+ - type: string
+ pattern: ^#[0-9A-Fa-f]{6}$
+ - type: 'null'
+ title: Primary Color
+ accent_color:
+ anyOf:
+ - type: string
+ pattern: ^#[0-9A-Fa-f]{6}$
+ - type: 'null'
+ title: Accent Color
+ support_email:
+ anyOf:
+ - type: string
+ maxLength: 255
+ - type: 'null'
+ title: Support Email
+ support_url:
+ anyOf:
+ - type: string
+ maxLength: 500
+ - type: 'null'
+ title: Support Url
+ sender_name:
+ anyOf:
+ - type: string
+ maxLength: 80
+ minLength: 1
+ - type: 'null'
+ title: Sender Name
+ footer_text:
+ anyOf:
+ - type: string
+ maxLength: 300
+ - type: 'null'
+ title: Footer Text
+ type: object
+ title: BrandingIn
BuildTimelineRequest:
properties:
identity_kind:
diff --git a/scripts/check_whitelabel_metering.py b/scripts/check_whitelabel_metering.py
new file mode 100644
index 000000000..6ca5bea09
--- /dev/null
+++ b/scripts/check_whitelabel_metering.py
@@ -0,0 +1,311 @@
+#!/usr/bin/env python3
+"""Two claims that decay quietly: a sanitiser's allowlist, and a meter's honesty.
+
+Why an allowlist needs a gate
+------------------------------
+`ALLOWED_ELEMENTS` in the SVG sanitiser is one line away from being useless.
+The pressure on it is real and sympathetic: an operator's logo does not render
+the way it did in their graphics program, somebody traces it to a dropped
+element, and the smallest change that fixes the complaint is to add that
+element to the list. If the element is `foreignObject`, `use`, `style` or
+`script`, the sanitiser is now a function that returns its input.
+
+The unit tests cover the payloads somebody thought of. This covers the
+*shape*: no element or attribute that can execute, fetch or reference another
+document may enter the allowlist, whatever the reason.
+
+Why a meter needs a gate
+-------------------------
+Two of this repository's console figures were wrong on real data while their
+tests passed, because each test compared a producer against a copy of itself.
+The metering tests avoid that by counting rows independently. What they cannot
+see is a *new* meter added later with the tenant formatted into its SQL, or a
+meter that quietly starts doing arithmetic on a price.
+
+So this reads the declarations:
+
+* every meter binds the tenant as a parameter and never formats one in;
+* no meter carries pricing vocabulary, because 13.3 says metering and the
+ commercial question belongs elsewhere;
+* a meter that cannot be measured on this deployment is named with a reason
+ and is *not* also declared as a meter, so it can never be reported as zero.
+
+Run: python3 scripts/check_whitelabel_metering.py [--self-test]
+"""
+
+from __future__ import annotations
+
+import ast
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from gate_toolkit import SELF_TEST_FLAG, repo_root, self_test_main # noqa: E402
+
+REPO_ROOT = repo_root()
+
+SANITIZER = REPO_ROOT / "services/api/app/services/branding/svg_sanitizer.py"
+RESOLVER = REPO_ROOT / "services/api/app/services/branding/resolver.py"
+METERING = REPO_ROOT / "services/api/app/services/usage_metering.py"
+
+#: Elements that execute, embed foreign content, or reference another
+#: document. None may ever be allowed, whatever a rendering complaint says.
+FORBIDDEN_ELEMENTS: frozenset[str] = frozenset(
+ {
+ "script",
+ "foreignObject",
+ "foreignobject",
+ "use",
+ "image",
+ "style",
+ "a",
+ "animate",
+ "animateTransform",
+ "animateMotion",
+ "set",
+ "handler",
+ "iframe",
+ "embed",
+ "object",
+ "audio",
+ "video",
+ "feImage",
+ }
+)
+
+#: Attributes that name a URL or carry behaviour. Event handlers are excluded
+#: by shape (anything starting `on`) rather than by enumeration, because the
+#: list of them grows.
+FORBIDDEN_ATTRIBUTES: frozenset[str] = frozenset({"href", "xlink:href", "style", "filter", "from", "to", "values", "begin"})
+
+#: Words that mean somebody started computing what usage is worth.
+PRICING_WORDS: frozenset[str] = frozenset({"price", "rate_card", "invoice", "unit_cost", "plan_cost", "billing_amount"})
+
+
+def _module_constant(tree: ast.Module, name: str) -> object | None:
+ for node in tree.body:
+ targets: list[str] = []
+ value: ast.expr | None = None
+ if isinstance(node, ast.Assign):
+ targets = [t.id for t in node.targets if isinstance(t, ast.Name)]
+ value = node.value
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
+ targets = [node.target.id]
+ value = node.value
+ if name not in targets or value is None:
+ continue
+ # `frozenset({...})` and `tuple(...)` wrap the literal this needs.
+ if isinstance(value, ast.Call) and isinstance(value.func, ast.Name) and value.func.id in {"frozenset", "tuple", "set"}:
+ value = value.args[0] if value.args else value
+ try:
+ return ast.literal_eval(value)
+ except (ValueError, TypeError, SyntaxError):
+ return None
+ return None
+
+
+def _meters(tree: ast.Module, name: str) -> list[dict[str, str]]:
+ """Every ``Meter(...)`` in one module-level tuple, as field dicts."""
+ found: list[dict[str, str]] = []
+ for node in tree.body:
+ target = None
+ value: ast.expr | None = None
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
+ target, value = node.target.id, node.value
+ elif isinstance(node, ast.Assign):
+ names = [t.id for t in node.targets if isinstance(t, ast.Name)]
+ target, value = (names[0] if names else None), node.value
+ if target != name or value is None:
+ continue
+ for call in ast.walk(value):
+ if not isinstance(call, ast.Call) or not isinstance(call.func, ast.Name) or call.func.id != "Meter":
+ continue
+ fields: dict[str, str] = {}
+ for index, arg in enumerate(call.args):
+ key = ("key", "label", "description", "source", "sql")[index] if index < 5 else str(index)
+ # A constant that is not a string goes through `_join` rather
+ # than into a `dict[str, str]`; the fields this reads are
+ # string literals, and a number here means the file changed
+ # shape, not that the gate should carry a non-string.
+ fields[key] = arg.value if isinstance(arg, ast.Constant) and isinstance(arg.value, str) else _join(arg)
+ for kw in call.keywords:
+ if kw.arg:
+ fields[kw.arg] = (
+ kw.value.value if isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str) else _join(kw.value)
+ )
+ found.append(fields)
+ return found
+
+
+def _join(node: ast.expr) -> str:
+ """Flatten an implicitly concatenated string literal."""
+ parts: list[str] = []
+ for inner in ast.walk(node):
+ if isinstance(inner, ast.Constant) and isinstance(inner.value, str):
+ parts.append(inner.value)
+ return " ".join(parts)
+
+
+def audit(root: Path) -> tuple[list[str], dict[str, int]]:
+ problems: list[str] = []
+ counts = {"allowed_elements": 0, "allowed_attributes": 0, "meters": 0}
+
+ sanitizer = root / SANITIZER.relative_to(REPO_ROOT)
+ resolver = root / RESOLVER.relative_to(REPO_ROOT)
+ metering = root / METERING.relative_to(REPO_ROOT)
+
+ missing = [p for p in (sanitizer, resolver, metering) if not p.is_file()]
+ if missing:
+ problems.append("white-label or metering modules are absent: " + ", ".join(str(p.relative_to(root)) for p in missing))
+ return problems, counts
+
+ # --- the SVG allowlist has not been widened -------------------------
+ sanitizer_tree = ast.parse(sanitizer.read_text(encoding="utf-8"))
+ elements = _module_constant(sanitizer_tree, "ALLOWED_ELEMENTS")
+ attributes = _module_constant(sanitizer_tree, "ALLOWED_ATTRIBUTES")
+
+ if not isinstance(elements, (set, frozenset, list, tuple)) or not isinstance(attributes, (set, frozenset, list, tuple)):
+ problems.append("the SVG allowlists are no longer literals this gate can read")
+ else:
+ counts["allowed_elements"] = len(elements)
+ counts["allowed_attributes"] = len(attributes)
+ for element in sorted(set(elements) & FORBIDDEN_ELEMENTS):
+ problems.append(
+ f"ALLOWED_ELEMENTS contains {element!r}, which can execute, embed foreign content or reference "
+ "another document. An uploaded logo renders in the console and inside PDF reports other people open."
+ )
+ for attribute in sorted(set(attributes) & FORBIDDEN_ATTRIBUTES):
+ problems.append(f"ALLOWED_ATTRIBUTES contains {attribute!r}, which names a URL or carries behaviour")
+ for attribute in sorted(a for a in attributes if isinstance(a, str) and a.lower().startswith("on")):
+ problems.append(f"ALLOWED_ATTRIBUTES contains the event handler {attribute!r}")
+
+ # --- a brand asset is never a remote reference ----------------------
+ resolver_source = resolver.read_text(encoding="utf-8")
+ for line_number, line in enumerate(resolver_source.splitlines(), start=1):
+ stripped = line.strip()
+ if stripped.startswith("#") or "logo" not in stripped.lower():
+ continue
+ if "http://" in stripped or "https://" in stripped:
+ problems.append(
+ f"{RESOLVER.name}:{line_number} builds a logo reference containing a remote scheme. "
+ "A remote logo is an outbound request made by the console and by the server-side PDF renderer."
+ )
+
+ # --- the meters stay honest ----------------------------------------
+ metering_tree = ast.parse(metering.read_text(encoding="utf-8"))
+ meters = _meters(metering_tree, "METERS") + _meters(metering_tree, "POINT_IN_TIME_METERS")
+ counts["meters"] = len(meters)
+
+ for meter in meters:
+ key = meter.get("key", "<unnamed>")
+ sql = meter.get("sql", "")
+ if ":tenant_id" not in sql and ":tenant_text" not in sql:
+ problems.append(f"meter {key!r} does not bind a tenant parameter, so it counts every tenant's rows")
+ if "%s" in sql or ".format(" in sql or 'f"' in sql:
+ problems.append(f"meter {key!r} formats a value into its SQL instead of binding it")
+ # Key, label and SQL only. `description` is prose, and the honest
+ # description of `llm_cost_usd` has to be able to say "not a price"
+ # — a gate that forbids the word forbids the disclaimer with it.
+ # Pricing logic would live in a column name or a computation, which
+ # is what these three fields hold.
+ haystack = f"{key} {meter.get('label', '')} {sql}".lower()
+ for word in sorted(PRICING_WORDS):
+ if word in haystack:
+ problems.append(f"meter {key!r} mentions {word!r}; 13.3 is metering, and pricing belongs elsewhere")
+
+ unmeasured = _module_constant(metering_tree, "UNMEASURED")
+ if isinstance(unmeasured, dict):
+ declared = {m.get("key") for m in meters}
+ for key, reason in unmeasured.items():
+ if key in declared:
+ problems.append(
+ f"{key!r} is declared both as a meter and as unmeasured. One of the two will report a number, "
+ "and a reader cannot tell which."
+ )
+ if not reason:
+ problems.append(f"{key!r} is unmeasured with no reason, so a reader cannot tell a gap from a zero")
+ else:
+ problems.append("UNMEASURED is no longer a literal this gate can read")
+
+ return problems, counts
+
+
+def _self_test_cases() -> list[tuple[str, bool]]:
+ import shutil
+ import tempfile
+
+ cases: list[tuple[str, bool]] = []
+ clean, _ = audit(REPO_ROOT)
+ cases.append(("the real tree passes", not clean))
+
+ mutations = [
+ (
+ "widening the allowlist to a script-capable element is reported",
+ SANITIZER,
+ ' "svg",\n',
+ ' "svg",\n "foreignObject",\n',
+ ),
+ ("allowing an event handler attribute is reported", SANITIZER, ' "id",\n', ' "id",\n "onload",\n'),
+ (
+ "a meter with no tenant binding is reported",
+ METERING,
+ '"SELECT count(*) FROM alerts WHERE tenant_id = :tenant_id AND created_at >= :start AND created_at < :end"',
+ '"SELECT count(*) FROM alerts WHERE created_at >= :start AND created_at < :end"',
+ ),
+ (
+ "a remote logo reference is reported",
+ RESOLVER,
+ 'logo_url = f"/api/v1/branding/assets/{asset[0]}" if asset else None',
+ 'logo_url = f"https://cdn.example/logos/{asset[0]}" if asset else None',
+ ),
+ ]
+
+ for description, target, old, new in mutations:
+ with tempfile.TemporaryDirectory() as tmp:
+ tree = Path(tmp) / "tree"
+ for source in {SANITIZER, RESOLVER, METERING}:
+ destination = tree / source.relative_to(REPO_ROOT)
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source, destination)
+ patched = tree / target.relative_to(REPO_ROOT)
+ text = patched.read_text(encoding="utf-8")
+ if old not in text:
+ cases.append((f"{description} (self-test anchor missing; case did not run)", False))
+ continue
+ patched.write_text(text.replace(old, new, 1), encoding="utf-8")
+ problems, _ = audit(tree)
+ cases.append((description, bool(problems)))
+
+ return cases
+
+
+def main() -> int:
+ if SELF_TEST_FLAG in sys.argv[1:]:
+ return self_test_main(Path(__file__).name, extra=_self_test_cases())
+
+ problems, counts = audit(REPO_ROOT)
+ print(
+ f"check_whitelabel_metering: read {counts['allowed_elements']} allowed SVG element(s), "
+ f"{counts['allowed_attributes']} allowed attribute(s) and {counts['meters']} meter(s)"
+ )
+
+ if counts["allowed_elements"] == 0 or counts["meters"] == 0:
+ print(
+ "\nFAIL: the allowlist or the meter set read as empty. A clean result over nothing is indistinguishable from a wrong root.",
+ file=sys.stderr,
+ )
+ return 2
+
+ if problems:
+ print(f"\nFAIL: {len(problems)} finding(s).", file=sys.stderr)
+ for problem in problems:
+ print(f" - {problem}", file=sys.stderr)
+ return 1
+
+ print("OK: the SVG allowlist admits nothing executable, assets stay local, and every meter binds its tenant.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/services/api/app/api/v1/endpoints/branding.py b/services/api/app/api/v1/endpoints/branding.py
new file mode 100644
index 000000000..5c21ac71a
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/branding.py
@@ -0,0 +1,297 @@
+"""Reading and administering white-label branding.
+
+Two audiences on one router:
+
+* ``GET /branding`` and ``GET /branding/assets/{id}`` are read by the console
+ on every page load, by any authenticated member of the tenant. Reading what
+ the product is called is not a privileged act.
+* Everything that writes requires ``settings:write`` and applies to the
+ organisation the caller's tenant belongs to. The organisation is resolved
+ from the credential, never named in the request: a body field would let an
+ authenticated user of one tenant rebrand somebody else's console.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import uuid
+from datetime import UTC, datetime
+from typing import Annotated, Any
+
+from fastapi import APIRouter, File, HTTPException, Request, Response, UploadFile, status
+from pydantic import BaseModel, Field, field_validator
+from sqlalchemy import select
+
+from app.api.v1.deps import AuthUser, DBSession, require_permission
+from app.models.branding import OrgBrandAsset, OrgBranding
+from app.services.audit import emit_audit
+from app.services.branding import resolver, svg_sanitizer
+
+router = APIRouter(prefix="/branding", tags=["branding"])
+
+#: Raster types accepted beside SVG. Deliberately short: each one is a
+#: decoder that will be handed attacker-supplied bytes by a browser, and the
+#: list of formats a logo needs is not long.
+ALLOWED_RASTER_TYPES: dict[str, str] = {
+ "image/png": "png",
+ "image/jpeg": "jpg",
+ "image/webp": "webp",
+}
+
+#: Magic bytes, checked against the declared type. A caller controls the
+#: header; announcing an SVG as `image/png` would otherwise skip the
+#: sanitiser, which is the whole attack.
+_MAGIC: dict[str, tuple[bytes, ...]] = {
+ "image/png": (b"\x89PNG\r\n\x1a\n",),
+ "image/jpeg": (b"\xff\xd8\xff",),
+ "image/webp": (b"RIFF",),
+}
+
+
+class BrandingIn(BaseModel):
+ product_name: str | None = Field(None, min_length=1, max_length=80)
+ primary_color: str | None = Field(None, pattern=r"^#[0-9A-Fa-f]{6}$")
+ accent_color: str | None = Field(None, pattern=r"^#[0-9A-Fa-f]{6}$")
+ support_email: str | None = Field(None, max_length=255)
+ support_url: str | None = Field(None, max_length=500)
+ sender_name: str | None = Field(None, min_length=1, max_length=80)
+ footer_text: str | None = Field(None, max_length=300)
+
+ @field_validator("support_url")
+ @classmethod
+ def _https_only(cls, value: str | None) -> str | None:
+ """Refuse anything but https.
+
+ This string is rendered as a link in an email and in a PDF report, so
+ a `javascript:` value would be a stored script in somebody else's
+ inbox. Checked here as well as by the database constraint, so the
+ caller gets a 422 naming the field rather than a 500.
+ """
+ if value is None or not value.strip():
+ return None
+ candidate = value.strip()
+ if not candidate.startswith("https://"):
+ raise ValueError("support_url must be an https:// address")
+ return candidate
+
+
+async def _require_org(db: Any, tenant_id: uuid.UUID) -> uuid.UUID:
+ org_id = await resolver.owning_org_id(db, tenant_id)
+ if org_id is None:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=(
+ "This tenant does not belong to an operator organisation, so there is nothing to brand. "
+ "Create an organisation and add this tenant to its portfolio first."
+ ),
+ )
+ return org_id
+
+
+async def get_branding(db: DBSession, current_user: AuthUser) -> dict[str, Any]:
+ """What the product looks like for the caller's tenant.
+
+ Readable by any authenticated member. The console calls it on every page
+ load, and gating it behind an administrative permission would leave an
+ analyst looking at a differently-branded product from their colleague.
+ """
+ return (await resolver.resolve_branding(db, current_user.tenant_id)).as_dict()
+
+
+async def put_branding(
+ body: BrandingIn,
+ db: DBSession,
+ request: Request,
+ current_user: Annotated[Any, require_permission("settings:write")],
+) -> dict[str, Any]:
+ """Set branding for the organisation the caller's tenant belongs to."""
+ org_id = await _require_org(db, current_user.tenant_id)
+
+ row = (await db.execute(select(OrgBranding).where(OrgBranding.org_id == org_id))).scalar_one_or_none()
+ if row is None:
+ row = OrgBranding(org_id=org_id)
+ db.add(row)
+
+ for field_name, value in body.model_dump().items():
+ setattr(row, field_name, value)
+ row.updated_by = current_user.user_id
+ row.updated_at = datetime.now(UTC)
+
+ await emit_audit(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.user_id,
+ actor_email=current_user.email,
+ action="branding:update",
+ resource="org_branding",
+ resource_id=str(org_id),
+ changes=body.model_dump(),
+ request=request,
+ )
+ await db.commit()
+ return (await resolver.branding_for_org(db, org_id)).as_dict()
+
+
[email protected]("/assets/{kind}", status_code=status.HTTP_201_CREATED)
+async def upload_asset(
+ kind: str,
+ db: DBSession,
+ request: Request,
+ current_user: Annotated[Any, require_permission("settings:write")],
+ file: Annotated[UploadFile, File()],
+) -> dict[str, Any]:
+ """Upload a logo or favicon.
+
+ An SVG goes through the sanitiser and what is stored is the sanitised
+ output. Nothing re-sanitises at render time, so this handler is the only
+ writer and the stored bytes are trusted thereafter.
+ """
+ if kind not in {"logo", "favicon"}:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="kind must be 'logo' or 'favicon'")
+
+ org_id = await _require_org(db, current_user.tenant_id)
+
+ raw = await file.read(svg_sanitizer.MAX_SVG_BYTES + 1)
+ if not raw:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="the uploaded file is empty")
+ if len(raw) > svg_sanitizer.MAX_SVG_BYTES:
+ raise HTTPException(
+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
+ detail=f"asset exceeds {svg_sanitizer.MAX_SVG_BYTES} bytes",
+ )
+
+ declared = (file.content_type or "").split(";")[0].strip().lower()
+ was_sanitized = False
+
+ # Decided on the bytes as well as the declared type. An SVG announced as
+ # `image/png` would otherwise be stored unsanitised and served back with
+ # a content type a browser may sniff past.
+ if svg_sanitizer.looks_like_svg(declared, raw):
+ try:
+ cleaned = svg_sanitizer.sanitize_svg(raw)
+ except svg_sanitizer.SvgRejected as exc:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc
+ content = cleaned.svg.encode("utf-8")
+ content_type = "image/svg+xml"
+ was_sanitized = cleaned.modified
+ removed = {"elements": sorted(set(cleaned.removed_elements)), "attributes": sorted(set(cleaned.removed_attributes))}
+ elif declared in ALLOWED_RASTER_TYPES:
+ prefixes = _MAGIC.get(declared, ())
+ if prefixes and not any(raw.startswith(prefix) for prefix in prefixes):
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail=f"the file does not begin with {declared} magic bytes",
+ )
+ content, content_type, removed = raw, declared, {"elements": [], "attributes": []}
+ else:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail=f"unsupported content type {declared!r}; accepted: image/svg+xml, {', '.join(sorted(ALLOWED_RASTER_TYPES))}",
+ )
+
+ existing = (
+ await db.execute(select(OrgBrandAsset).where(OrgBrandAsset.org_id == org_id, OrgBrandAsset.kind == kind))
+ ).scalar_one_or_none()
+ digest = hashlib.sha256(content).hexdigest()
+
+ if existing is None:
+ existing = OrgBrandAsset(org_id=org_id, kind=kind)
+ db.add(existing)
+ existing.content_type = content_type
+ existing.content = content
+ existing.byte_size = len(content)
+ existing.sha256 = digest
+ existing.was_sanitized = was_sanitized
+ existing.uploaded_by = current_user.user_id
+ await db.flush()
+
+ await emit_audit(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.user_id,
+ actor_email=current_user.email,
+ action="branding:asset:upload",
+ resource="org_brand_asset",
+ resource_id=str(existing.id),
+ changes={"kind": kind, "content_type": content_type, "bytes": len(content), "sanitized": was_sanitized, "removed": removed},
+ request=request,
+ )
+ await db.commit()
+
+ return {
+ "id": str(existing.id),
+ "kind": kind,
+ "content_type": content_type,
+ "byte_size": len(content),
+ "sha256": digest,
+ "was_sanitized": was_sanitized,
+ "removed": removed,
+ "url": f"/api/v1/branding/assets/{existing.id}",
+ }
+
+
[email protected]("/assets/{asset_id}")
+async def get_asset(asset_id: uuid.UUID, db: DBSession, current_user: AuthUser) -> Response:
+ """Serve a brand asset from this deployment.
+
+ Scoped to the caller's own organisation. The bytes are not secret, but
+ an unscoped read would let any authenticated user enumerate every
+ operator's logo, which is a customer list.
+ """
+ org_id = await resolver.owning_org_id(db, current_user.tenant_id)
+ if org_id is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")
+
+ asset = (
+ await db.execute(select(OrgBrandAsset).where(OrgBrandAsset.id == asset_id, OrgBrandAsset.org_id == org_id))
+ ).scalar_one_or_none()
+ if asset is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")
+
+ return Response(
+ content=asset.content,
+ media_type=asset.content_type,
+ headers={
+ # The bytes are immutable for a given id, and replacing an asset
+ # writes a new sha. Caching privately rather than publicly: a
+ # shared cache would serve one operator's logo from another's
+ # request path.
+ "Cache-Control": "private, max-age=300",
+ "ETag": f'"{asset.sha256}"',
+ # Belt and braces on the SVG path. The content is sanitised, and
+ # a browser that sniffs past the declared type still gets no
+ # script execution from a document served with these headers.
+ "X-Content-Type-Options": "nosniff",
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox",
+ },
+ )
+
+
[email protected]("/assets/{kind}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
+async def delete_asset(
+ kind: str,
+ db: DBSession,
+ request: Request,
+ current_user: Annotated[Any, require_permission("settings:write")],
+) -> None:
+ """Remove an asset, returning that surface to the wordmark."""
+ org_id = await _require_org(db, current_user.tenant_id)
+ asset = (await db.execute(select(OrgBrandAsset).where(OrgBrandAsset.org_id == org_id, OrgBrandAsset.kind == kind))).scalar_one_or_none()
+ if asset is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")
+
+ await db.delete(asset)
+ await emit_audit(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.user_id,
+ actor_email=current_user.email,
+ action="branding:asset:delete",
+ resource="org_brand_asset",
+ resource_id=str(asset.id),
+ changes={"kind": kind},
+ request=request,
+ )
+ await db.commit()
diff --git a/services/api/app/api/v1/endpoints/reports.py b/services/api/app/api/v1/endpoints/reports.py
index 40939c0e7..8c9d547b0 100644
--- a/services/api/app/api/v1/endpoints/reports.py
+++ b/services/api/app/api/v1/endpoints/reports.py
@@ -19,6 +19,7 @@ from app.api.v1.deps import CurrentUser
from app.api.v1.endpoints.auth import get_current_user
from app.db.database import get_db
from app.models.report import ReportArtefact, ReportTemplate
+from app.services.branding.resolver import resolve_branding
from app.services.digest_html import render_digest_html
from app.services.digest_pdf import WeasyPrintUnavailableError, render_digest_pdf
from app.services.executive_digest import ExecutiveDigest, build_weekly_digest
@@ -243,11 +244,18 @@ async def weekly_digest(
)
if fmt == "html":
- return HTMLResponse(content=render_digest_html(digest))
+ # Resolved from the caller's tenant, so a white-labelled
+ # organisation's report carries its own product name, palette and
+ # logo. The logo is inlined because this HTML becomes a PDF rendered
+ # server-side, and a remote reference there is an outbound request
+ # made by the server to a customer-supplied address.
+ branding = await resolve_branding(db, current_user.tenant_id, inline_logo=True)
+ return HTMLResponse(content=render_digest_html(digest, branding))
if fmt == "pdf":
try:
- pdf_bytes = render_digest_pdf(digest)
+ branding = await resolve_branding(db, current_user.tenant_id, inline_logo=True)
+ pdf_bytes = render_digest_pdf(digest, branding)
except WeasyPrintUnavailableError as exc:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
diff --git a/services/api/app/api/v1/endpoints/usage.py b/services/api/app/api/v1/endpoints/usage.py
new file mode 100644
index 000000000..da7140cd1
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/usage.py
@@ -0,0 +1,158 @@
+"""Usage metering: what a tenant did, counted from the rows that record it.
+
+The tenant comes from the credential. There is no tenant parameter on any
+route here, which is deliberate: usage is the input to a commercial
+conversation, and a surface that let an authenticated user name somebody
+else's tenant would publish one customer's volume to another.
+
+No pricing. These are counts and measured model costs. What they are worth
+belongs nowhere near the code that answers what happened.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, date, datetime, timedelta
+from typing import Annotated, Any
+
+from fastapi import APIRouter, HTTPException, Query, Response, status
+from sqlalchemy import select
+
+from app.api.v1.deps import AuthUser, DBSession, require_permission
+from app.models.organization import Organization
+from app.models.tenant import Tenant
+from app.services import usage_metering
+from app.services.branding.resolver import owning_org_id
+from app.services.entitlements import headroom_for_tenant
+
+router = APIRouter(prefix="/usage", tags=["usage"])
+
+#: Longest window a single request may ask for. Each day is a query per
+#: meter, so an unbounded range is a slow request an authenticated caller can
+#: ask for repeatedly.
+MAX_RANGE_DAYS = 186
+
+
+def _parse_day(raw: str | None, *, default: date) -> date:
+ if raw is None:
+ return default
+ try:
+ return date.fromisoformat(raw)
+ except ValueError as exc:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=f"{raw!r} is not an ISO date") from exc
+
+
+async def get_usage(
+ db: DBSession,
+ current_user: AuthUser,
+ start: Annotated[str | None, Query()] = None,
+ end: Annotated[str | None, Query()] = None,
+) -> dict[str, Any]:
+ """Daily usage for the caller's tenant, defaulting to the last 30 days."""
+ today = datetime.now(UTC).date()
+ end_day = _parse_day(end, default=today)
+ start_day = _parse_day(start, default=end_day - timedelta(days=29))
+
+ if end_day < start_day:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="end is before start")
+ if (end_day - start_day).days + 1 > MAX_RANGE_DAYS:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail=f"range exceeds {MAX_RANGE_DAYS} days; export a month at a time",
+ )
+
+ days = await usage_metering.measure_range(db, current_user.tenant_id, start_day, end_day)
+ point_in_time = await usage_metering.measure_point_in_time(db, current_user.tenant_id)
+
+ # The per-tenant override, not the plan default. `limit_for` reads this
+ # first, so omitting it reports plan headroom to a tenant whose limits were
+ # deliberately raised, which is the opposite of what the row says.
+ tenant_limits = await db.scalar(select(Tenant.limits).where(Tenant.id == current_user.tenant_id))
+
+ return {
+ "tenant_id": str(current_user.tenant_id),
+ "start": start_day.isoformat(),
+ "end": end_day.isoformat(),
+ "meters": [
+ {"key": m.key, "label": m.label, "description": m.description, "source": m.source}
+ for m in (*usage_metering.METERS, *usage_metering.POINT_IN_TIME_METERS)
+ ],
+ "daily": [day.as_dict() for day in days],
+ "totals": usage_metering.totals(days),
+ "point_in_time": point_in_time,
+ # Named with the reason rather than omitted. A missing key reads as
+ # zero to anyone charting it, and zero is a measurement.
+ "not_measured": usage_metering.UNMEASURED,
+ # The limits these counts run against, so a usage screen and a quota
+ # screen cannot disagree about the same rows.
+ "entitlements": [h.as_dict() for h in await headroom_for_tenant(db, current_user.tenant_id, tenant_limits)],
+ }
+
+
[email protected]("/reconciliation")
+async def get_reconciliation(
+ db: DBSession,
+ current_user: Annotated[Any, require_permission("settings:read")],
+ start: Annotated[str | None, Query()] = None,
+ end: Annotated[str | None, Query()] = None,
+) -> dict[str, Any]:
+ """Compare the daily sum against one query over the whole window.
+
+ Exposed rather than kept in a test so an operator disputing an invoice
+ can run the same check the test runs, against their own rows.
+ """
+ today = datetime.now(UTC).date()
+ end_day = _parse_day(end, default=today)
+ start_day = _parse_day(start, default=end_day - timedelta(days=29))
+ report = await usage_metering.reconcile(db, current_user.tenant_id, start_day, end_day)
+ return {
+ "start": start_day.isoformat(),
+ "end": end_day.isoformat(),
+ "meters": report,
+ "all_agree": all(entry["agrees"] for entry in report.values()),
+ }
+
+
[email protected]("/export.csv")
+async def export_month(
+ db: DBSession,
+ current_user: Annotated[Any, require_permission("reports:read")],
+ month: Annotated[str | None, Query(description="YYYY-MM; defaults to the current month")] = None,
+) -> Response:
+ """A month of usage as CSV, labelled with the organisation it belongs to."""
+ today = datetime.now(UTC).date()
+ if month is None:
+ year, month_number = today.year, today.month
+ else:
+ try:
+ year, month_number = (int(part) for part in month.split("-", 1))
+ except (ValueError, TypeError) as exc:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="month must be YYYY-MM") from exc
+
+ try:
+ first, last = usage_metering.month_bounds(year, month_number)
+ except ValueError as exc:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc
+
+ days = await usage_metering.measure_range(db, current_user.tenant_id, first, last)
+ point_in_time = await usage_metering.measure_point_in_time(db, current_user.tenant_id)
+ body = usage_metering.to_csv(
+ tenant_id=current_user.tenant_id,
+ org_name=await _org_name(db, current_user.tenant_id),
+ days=days,
+ point_in_time=point_in_time,
+ )
+
+ return Response(
+ content=body,
+ media_type="text/csv",
+ headers={"Content-Disposition": f'attachment; filename="aisoc-usage-{year:04d}-{month_number:02d}.csv"'},
+ )
+
+
+async def _org_name(db: Any, tenant_id: uuid.UUID) -> str | None:
+ org_id = await owning_org_id(db, tenant_id)
+ if org_id is None:
+ return None
+ return (await db.execute(select(Organization.name).where(Organization.id == org_id))).scalar_one_or_none()
diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.py
index 48062bbfc..fd3495b2a 100644
--- a/services/api/app/api/v1/router.py
+++ b/services/api/app/api/v1/router.py
@@ -16,6 +16,7 @@ from app.api.v1.endpoints import (
audit,
auth,
autonomy_policy,
+ branding,
business_context,
cases,
community,
@@ -85,6 +86,7 @@ from app.api.v1.endpoints import (
tenants,
threat_intel,
translation,
+ usage,
waitlist,
)
@@ -114,6 +116,7 @@ api_router.include_router(connectors.router)
# operator back on /onboarding.
api_router.include_router(oauth.router)
api_router.include_router(tenants.router)
+api_router.include_router(usage.router)
api_router.include_router(detection_rules.router)
# Frontend-shape facade: /api/v1/detection/rules + /api/v1/detection/test
api_router.include_router(detection_compat.router)
@@ -149,6 +152,7 @@ api_router.include_router(mcp_servers.router)
api_router.include_router(tenant_skills.router)
api_router.include_router(rbac.router)
api_router.include_router(audit.router)
+api_router.include_router(branding.router)
api_router.include_router(compliance.router)
api_router.include_router(metrics.router)
# Pipeline health snapshot — v1.5 SOC Console parity.
diff --git a/services/api/app/models/__init__.py b/services/api/app/models/__init__.py
index 79813543b..d25d21c84 100644
--- a/services/api/app/models/__init__.py
+++ b/services/api/app/models/__init__.py
@@ -3,6 +3,7 @@
from app.db.database import Base
from app.models.alert import Alert
from app.models.asset import AlertAssetCorrelation, Asset, AssetVulnerability
+from app.models.branding import OrgBrandAsset, OrgBranding
from app.models.case import Case, CaseTask, CaseTimeline
from app.models.connector import Connector
from app.models.detection_proposal import DetectionEvalBaseline, DetectionRuleProposal
@@ -84,6 +85,8 @@ __all__ = [
"MSSPTenantMetrics",
"MSSPTenantNote",
"OAuthAppCredential",
+ "OrgBrandAsset",
+ "OrgBranding",
"Organization",
"ScimGroup",
"ScimGroupMember",
diff --git a/services/api/app/models/branding.py b/services/api/app/models/branding.py
new file mode 100644
index 000000000..ae48f02e3
--- /dev/null
+++ b/services/api/app/models/branding.py
@@ -0,0 +1,60 @@
+"""White-label branding ORM models (migration 072).
+
+The reasoning lives next to the constraints in
+``services/api/migrations/072_org_branding.sql``.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+
+from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, LargeBinary, Text
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.db.database import Base
+
+
+class OrgBrandAsset(Base):
+ """An uploaded logo or favicon, held as bytes rather than as a URL."""
+
+ __tablename__ = "aisoc_org_brand_assets"
+
+ id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
+ org_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False, index=True)
+ kind: Mapped[str] = mapped_column(Text, nullable=False)
+ content_type: Mapped[str] = mapped_column(Text, nullable=False)
+ content: Mapped[bytes] = mapped_column(LargeBinary, nullable=False)
+ byte_size: Mapped[int] = mapped_column(Integer, nullable=False)
+ sha256: Mapped[str] = mapped_column(Text, nullable=False)
+ was_sanitized: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
+ uploaded_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))
+
+
+class OrgBranding(Base):
+ """White-label settings for one operator organisation.
+
+ Every column is nullable. Resolution fills the gaps from the platform
+ default, so a half-configured organisation renders a coherent product
+ rather than a page with holes in it.
+ """
+
+ __tablename__ = "aisoc_org_branding"
+
+ org_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("organizations.id", ondelete="CASCADE"), primary_key=True)
+ product_name: Mapped[str | None] = mapped_column(Text, nullable=True)
+ primary_color: Mapped[str | None] = mapped_column(Text, nullable=True)
+ accent_color: Mapped[str | None] = mapped_column(Text, nullable=True)
+ support_email: Mapped[str | None] = mapped_column(Text, nullable=True)
+ support_url: Mapped[str | None] = mapped_column(Text, nullable=True)
+ sender_name: Mapped[str | None] = mapped_column(Text, nullable=True)
+ footer_text: Mapped[str | None] = mapped_column(Text, nullable=True)
+ updated_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC)
+ )
+
+
+__all__ = ["OrgBrandAsset", "OrgBranding"]
diff --git a/services/api/app/services/branding/__init__.py b/services/api/app/services/branding/__init__.py
new file mode 100644
index 000000000..59a1828ec
--- /dev/null
+++ b/services/api/app/services/branding/__init__.py
@@ -0,0 +1,35 @@
+"""Per-organisation white-label branding.
+
+``svg_sanitizer``
+ Turns an untrusted uploaded SVG into one that is safe to render in a
+ console and inside a PDF, or refuses it.
+``resolver``
+ Answers "what does this tenant's product look like", falling back to the
+ platform default field by field.
+"""
+
+from app.services.branding.resolver import (
+ DEFAULT_BRANDING,
+ Branding,
+ branding_for_org,
+ resolve_branding,
+)
+from app.services.branding.svg_sanitizer import (
+ MAX_SVG_BYTES,
+ SanitizeResult,
+ SvgRejected,
+ looks_like_svg,
+ sanitize_svg,
+)
+
+__all__ = [
+ "DEFAULT_BRANDING",
+ "MAX_SVG_BYTES",
+ "Branding",
+ "SanitizeResult",
+ "SvgRejected",
+ "branding_for_org",
+ "looks_like_svg",
+ "resolve_branding",
+ "sanitize_svg",
+]
diff --git a/services/api/app/services/branding/resolver.py b/services/api/app/services/branding/resolver.py
new file mode 100644
index 000000000..3a3d9d2e5
--- /dev/null
+++ b/services/api/app/services/branding/resolver.py
@@ -0,0 +1,173 @@
+"""Answering "what does this tenant's product look like".
+
+One resolver, called by every surface that renders a product name or a
+colour: the console, the PDF report, the executive digest, email approvals
+and ChatOps. Two resolvers would be two answers, and the one a customer
+notices is whichever renders in the document they forward to their board.
+
+Falls back field by field rather than row by row. An organisation that has
+set a product name and no colours renders its name against the platform
+palette, which is what a half-configured organisation should look like; the
+alternative, falling back to the whole default row, would silently discard
+the one field the operator had bothered to set.
+"""
+
+from __future__ import annotations
+
+import base64
+import uuid
+from dataclasses import dataclass, replace
+from typing import Any, Final
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.branding import OrgBrandAsset, OrgBranding
+from app.models.organization import Organization, OrganizationTenant
+
+
+@dataclass(frozen=True)
+class Branding:
+ """The resolved appearance of the product for one tenant.
+
+ ``logo_url`` is a path on this deployment, never a third-party address.
+ It is ``None`` when no asset has been uploaded, and every renderer treats
+ that as "use the wordmark", so a missing logo is a layout this project
+ ships rather than a broken image.
+ """
+
+ product_name: str
+ primary_color: str
+ accent_color: str
+ support_email: str | None
+ support_url: str | None
+ sender_name: str
+ footer_text: str
+ logo_url: str | None
+ #: The logo inlined as a ``data:`` URI, populated only when a caller asks
+ #: for it. A PDF is rendered server-side by WeasyPrint, so a remote
+ #: ``<img src>`` there would be an outbound request made by the server to
+ #: an address a customer administrator supplied. The console takes
+ #: ``logo_url`` instead and fetches it as an authenticated user.
+ logo_data_uri: str | None
+ org_id: uuid.UUID | None
+ #: False when nothing is configured, so a caller can tell "the default,
+ #: because that is what was chosen" from "the default, because nobody has
+ #: been here yet".
+ is_white_labelled: bool
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "product_name": self.product_name,
+ "primary_color": self.primary_color,
+ "accent_color": self.accent_color,
+ "support_email": self.support_email,
+ "support_url": self.support_url,
+ "sender_name": self.sender_name,
+ "footer_text": self.footer_text,
+ "logo_url": self.logo_url,
+ "org_id": str(self.org_id) if self.org_id else None,
+ "is_white_labelled": self.is_white_labelled,
+ }
+
+
+#: What an unbranded deployment looks like. Referenced by name everywhere
+#: rather than written out, so "the product is called AiSOC" is one fact.
+DEFAULT_BRANDING: Final[Branding] = Branding(
+ product_name="AiSOC",
+ primary_color="#2563EB",
+ accent_color="#7C3AED",
+ support_email=None,
+ support_url=None,
+ sender_name="AiSOC",
+ footer_text="AiSOC — open-source AI Security Operations Center.",
+ logo_url=None,
+ logo_data_uri=None,
+ org_id=None,
+ is_white_labelled=False,
+)
+
+
+def _merge(row: OrgBranding, *, logo_url: str | None, logo_data_uri: str | None) -> Branding:
+ """Overlay one organisation's settings on the platform default."""
+ resolved = replace(
+ DEFAULT_BRANDING,
+ org_id=row.org_id,
+ is_white_labelled=True,
+ logo_url=logo_url,
+ logo_data_uri=logo_data_uri,
+ )
+ if row.product_name:
+ resolved = replace(resolved, product_name=row.product_name)
+ # The sender name defaults to the product name rather than to
+ # "AiSOC". An operator who renames the product and forgets this field
+ # would otherwise send mail from a brand their customer has never
+ # heard of, which reads as a phishing attempt.
+ resolved = replace(resolved, sender_name=row.product_name)
+ resolved = replace(resolved, footer_text=row.product_name)
+ if row.primary_color:
+ resolved = replace(resolved, primary_color=row.primary_color)
+ if row.accent_color:
+ resolved = replace(resolved, accent_color=row.accent_color)
+ if row.support_email:
+ resolved = replace(resolved, support_email=row.support_email)
+ if row.support_url:
+ resolved = replace(resolved, support_url=row.support_url)
+ if row.sender_name:
+ resolved = replace(resolved, sender_name=row.sender_name)
+ if row.footer_text:
+ resolved = replace(resolved, footer_text=row.footer_text)
+ return resolved
+
+
+async def branding_for_org(db: AsyncSession, org_id: uuid.UUID | None, *, inline_logo: bool = False) -> Branding:
+ """Resolve branding for one organisation, or the default for ``None``.
+
+ ``inline_logo`` loads the asset bytes and returns them as a ``data:``
+ URI. Off by default because the console does not need them and every
+ page load would otherwise carry a logo through the JSON.
+ """
+ if org_id is None:
+ return DEFAULT_BRANDING
+
+ row = (await db.execute(select(OrgBranding).where(OrgBranding.org_id == org_id))).scalar_one_or_none()
+ if row is None:
+ return DEFAULT_BRANDING
+
+ columns = (OrgBrandAsset.id, OrgBrandAsset.content_type, OrgBrandAsset.content) if inline_logo else (OrgBrandAsset.id,)
+ asset = (await db.execute(select(*columns).where(OrgBrandAsset.org_id == org_id, OrgBrandAsset.kind == "logo"))).first()
+
+ logo_url = f"/api/v1/branding/assets/{asset[0]}" if asset else None
+ logo_data_uri = None
+ if asset is not None and inline_logo:
+ encoded = base64.b64encode(bytes(asset[2])).decode("ascii")
+ logo_data_uri = f"data:{asset[1]};base64,{encoded}"
+ return _merge(row, logo_url=logo_url, logo_data_uri=logo_data_uri)
+
+
+async def owning_org_id(db: AsyncSession, tenant_id: uuid.UUID) -> uuid.UUID | None:
+ """The organisation whose portfolio holds this tenant, or its home org.
+
+ Two ways a tenant belongs to an organisation and both have to resolve:
+ 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 an operator's own console unbranded, which is the one
+ console they look at every day.
+ """
+ managed = (await db.execute(select(OrganizationTenant.org_id).where(OrganizationTenant.tenant_id == tenant_id))).scalar_one_or_none()
+ if managed is not None:
+ return managed
+ return (await db.execute(select(Organization.id).where(Organization.home_tenant_id == tenant_id))).scalar_one_or_none()
+
+
+async def resolve_branding(db: AsyncSession, tenant_id: uuid.UUID, *, inline_logo: bool = False) -> Branding:
+ """The appearance of the product for one tenant.
+
+ Never raises. A branding lookup that failed would take down whatever it
+ was decorating, and a report that does not render is worse than a report
+ that renders in the platform palette.
+ """
+ try:
+ return await branding_for_org(db, await owning_org_id(db, tenant_id), inline_logo=inline_logo)
+ except Exception: # noqa: BLE001 - see the docstring; appearance must not break content
+ return DEFAULT_BRANDING
diff --git a/services/api/app/services/branding/svg_sanitizer.py b/services/api/app/services/branding/svg_sanitizer.py
new file mode 100644
index 000000000..f2c5af9a9
--- /dev/null
+++ b/services/api/app/services/branding/svg_sanitizer.py
@@ -0,0 +1,299 @@
+"""Sanitising an uploaded SVG, which is a script-carrying format.
+
+Why this is a security boundary and not a theming detail
+---------------------------------------------------------
+PNG and JPEG are pixels. SVG is XML with a scripting model: it can carry
+``<script>``, ``onload`` and every other event attribute, ``<foreignObject>``
+containing arbitrary HTML, CSS that fetches remote resources, and references
+to external documents. An operator logo is uploaded by a customer
+administrator and then rendered inside the console and inside PDF reports
+that other people open. That makes an uploaded SVG a stored cross-site
+scripting vector with a distribution mechanism attached.
+
+Allowlist, never denylist
+--------------------------
+A denylist of ``<script>`` misses ``<foreignObject>``, ``<use href="...">``,
+``<animate attributeName="href">``, ``<set>``, ``<handler>``, and whatever the
+next revision of the specification adds. The list of dangerous constructs
+grows; the list of things a logo needs does not. So only the elements and
+attributes below survive, and everything else is dropped.
+
+Entity expansion is refused before parsing, not handled after
+--------------------------------------------------------------
+``xml.etree.ElementTree`` does not fetch external entities, but it does
+expand internal ones, which is enough for a billion-laughs expansion out of a
+very small upload. Both that and the quadratic-blowup variant need entity
+definitions, and entity definitions need a DTD. So a document declaring a
+DOCTYPE or an ENTITY at all is refused on a byte scan **before** the parser
+sees it, which removes the class rather than bounding it.
+
+This module deliberately uses only the standard library. The alternative was
+a new XML dependency on a path that parses untrusted input, which is a larger
+surface than the one being defended.
+"""
+
+from __future__ import annotations
+
+import re
+import xml.etree.ElementTree as ET # noqa: N817
+from dataclasses import dataclass, field
+from typing import Final
+
+SVG_NAMESPACE: Final[str] = "http://www.w3.org/2000/svg"
+XLINK_NAMESPACE: Final[str] = "http://www.w3.org/1999/xlink"
+
+#: Largest SVG this accepts, before parsing. A logo does not need more, and
+#: an unbounded parse of attacker-supplied XML is a denial of service on the
+#: request path whatever the sanitiser does afterwards.
+MAX_SVG_BYTES: Final[int] = 256 * 1024
+
+#: Elements a logo can be drawn with. Everything absent is dropped with its
+#: subtree. `foreignObject` is absent on purpose: it embeds arbitrary HTML.
+#: `use` is absent because its whole purpose is to reference another document
+#: fragment, and the safe subset of that is not worth the parsing.
+ALLOWED_ELEMENTS: Final[frozenset[str]] = frozenset(
+ {
+ "svg",
+ "g",
+ "defs",
+ "title",
+ "desc",
+ "path",
+ "rect",
+ "circle",
+ "ellipse",
+ "line",
+ "polyline",
+ "polygon",
+ "text",
+ "tspan",
+ "linearGradient",
+ "radialGradient",
+ "stop",
+ "clipPath",
+ "mask",
+ "pattern",
+ "symbol",
+ "marker",
+ }
+)
+
+#: Attributes those elements may carry. Presentation and geometry only.
+#: Nothing here can name a URL except `fill`, `stroke` and `clip-path`, whose
+#: values are checked separately so only same-document `url(#id)` references
+#: survive.
+ALLOWED_ATTRIBUTES: Final[frozenset[str]] = frozenset(
+ {
+ "id",
+ "class",
+ "d",
+ "cx",
+ "cy",
+ "r",
+ "rx",
+ "ry",
+ "x",
+ "y",
+ "x1",
+ "y1",
+ "x2",
+ "y2",
+ "dx",
+ "dy",
+ "width",
+ "height",
+ "points",
+ "transform",
+ "viewBox",
+ "preserveAspectRatio",
+ "fill",
+ "fill-opacity",
+ "fill-rule",
+ "stroke",
+ "stroke-width",
+ "stroke-linecap",
+ "stroke-linejoin",
+ "stroke-dasharray",
+ "stroke-dashoffset",
+ "stroke-opacity",
+ "stroke-miterlimit",
+ "opacity",
+ "offset",
+ "stop-color",
+ "stop-opacity",
+ "gradientUnits",
+ "gradientTransform",
+ "spreadMethod",
+ "clip-path",
+ "clip-rule",
+ "mask",
+ "fr",
+ "fx",
+ "fy",
+ "font-family",
+ "font-size",
+ "font-weight",
+ "font-style",
+ "text-anchor",
+ "dominant-baseline",
+ "letter-spacing",
+ "xmlns",
+ "version",
+ }
+)
+
+#: A `url(...)` that points inside this document. Anything else in a paint
+#: attribute is dropped: `fill="url(https://attacker.example/x)"` is an
+#: outbound request from wherever the logo is rendered, which for a PDF
+#: report is the server.
+_LOCAL_URL_REF = re.compile(r"^url\(\s*['\"]?#[A-Za-z_][\w.:-]*['\"]?\s*\)$")
+
+#: Byte-level refusals, applied before the parser runs.
+_DOCTYPE = re.compile(rb"<!\s*DOCTYPE", re.IGNORECASE)
+_ENTITY = re.compile(rb"<!\s*ENTITY", re.IGNORECASE)
+
+#: A value that executes rather than describes. Checked on every surviving
+#: attribute value, because `style` is not on the allowlist but a future
+#: addition to it would otherwise inherit this hole silently.
+_ACTIVE_VALUE = re.compile(r"(javascript|vbscript|data)\s*:", re.IGNORECASE)
+
+
+class SvgRejected(ValueError):
+ """An upload that cannot be made safe, with the reason.
+
+ Refused rather than repaired. A document declaring a DTD is not a logo
+ somebody drew in a graphics program; repairing it would mean guessing
+ what the author meant, and the author here is untrusted.
+ """
+
+
+@dataclass
+class SanitizeResult:
+ """The cleaned document and what was taken out of it.
+
+ The removals are reported rather than discarded so an administrator whose
+ logo renders wrong can be told why, and so a test can assert on the
+ specific construct rather than on the absence of a string.
+ """
+
+ svg: str
+ removed_elements: list[str] = field(default_factory=list)
+ removed_attributes: list[str] = field(default_factory=list)
+
+ @property
+ def modified(self) -> bool:
+ return bool(self.removed_elements or self.removed_attributes)
+
+
+def _localname(tag: str) -> str:
+ """Strip a namespace from an ElementTree tag.
+
+ Namespace-qualified names are how a hostile document smuggles a
+ disallowed element past a comparison against a bare name:
+ ``{http://www.w3.org/2000/svg}script`` is not the string ``script``.
+ """
+ return tag.rpartition("}")[2] if "}" in tag else tag
+
+
+def _attribute_allowed(name: str, value: str) -> bool:
+ local = _localname(name)
+
+ # Any xlink attribute at all. `xlink:href` is the classic external
+ # reference and there is no member of that namespace a logo needs.
+ if name.startswith(f"{{{XLINK_NAMESPACE}}}") or local.startswith("xlink"):
+ return False
+
+ # Every event handler, by shape rather than by enumeration. `onload`,
+ # `onbegin`, `onmouseover` and whatever is added next all start `on`.
+ if local.lower().startswith("on"):
+ return False
+
+ if local not in ALLOWED_ATTRIBUTES:
+ return False
+
+ if _ACTIVE_VALUE.search(value):
+ return False
+
+ # A paint or clip value may name a reference. Only a same-document one.
+ if "url(" in value.lower() and not _LOCAL_URL_REF.match(value.strip()):
+ return False
+
+ return True
+
+
+def sanitize_svg(raw: bytes) -> SanitizeResult:
+ """Return a safe rendering of ``raw``, or raise :class:`SvgRejected`.
+
+ The output is re-serialised from the parsed tree rather than produced by
+ editing the input, so anything the parser did not understand cannot
+ survive into the result. A sanitiser that returns a modified copy of the
+ original leaves whatever it failed to recognise in place.
+ """
+ if not raw:
+ raise SvgRejected("the uploaded file is empty")
+ if len(raw) > MAX_SVG_BYTES:
+ raise SvgRejected(f"SVG is {len(raw)} bytes; the limit is {MAX_SVG_BYTES}")
+
+ if _DOCTYPE.search(raw) or _ENTITY.search(raw):
+ raise SvgRejected(
+ "SVG declares a DTD or an entity. Both are refused: internal entity expansion is a "
+ "denial of service out of a small upload, and a logo has no use for either."
+ )
+
+ parser = ET.XMLParser()
+ try:
+ root = ET.fromstring(raw, parser=parser) # noqa: S314 - DTD and entities refused above
+ except ET.ParseError as exc:
+ raise SvgRejected(f"not well-formed XML: {exc}") from exc
+
+ if _localname(root.tag) != "svg":
+ raise SvgRejected(f"root element is <{_localname(root.tag)}>, not <svg>")
+
+ result = SanitizeResult(svg="")
+ _scrub(root, result)
+
+ # Namespace declared once on the root, so the serialised document is a
+ # standalone SVG a browser and WeasyPrint both render.
+ root.set("xmlns", SVG_NAMESPACE)
+
+ ET.register_namespace("", SVG_NAMESPACE)
+ body = ET.tostring(root, encoding="unicode")
+ # ElementTree re-emits the namespace as a prefix in some configurations;
+ # collapse the redundant declaration so the output is one canonical shape
+ # rather than two that differ by Python version.
+ body = body.replace(f'xmlns:ns0="{SVG_NAMESPACE}"', "").replace("ns0:", "")
+ result.svg = body.strip()
+ return result
+
+
+def _scrub(element: ET.Element, result: SanitizeResult) -> None:
+ """Drop disallowed children and attributes, depth first."""
+ for attribute in list(element.attrib):
+ if not _attribute_allowed(attribute, element.attrib[attribute]):
+ result.removed_attributes.append(_localname(attribute))
+ del element.attrib[attribute]
+
+ for child in list(element):
+ name = _localname(child.tag)
+ if name not in ALLOWED_ELEMENTS:
+ # The whole subtree goes. A disallowed element's children are not
+ # promoted into its parent: `<script><circle/></script>` is not a
+ # circle somebody wanted.
+ result.removed_elements.append(name)
+ element.remove(child)
+ continue
+ _scrub(child, result)
+
+
+def looks_like_svg(content_type: str | None, raw: bytes) -> bool:
+ """Whether this upload should go through the sanitiser.
+
+ Decided on the bytes as well as the declared type. A caller controls the
+ ``Content-Type`` header, so an SVG announced as ``image/png`` would
+ otherwise skip sanitising entirely, which is the shape of the bug this
+ check exists to prevent.
+ """
+ if content_type and "svg" in content_type.lower():
+ return True
+ head = raw[:1024].lstrip()
+ return head.startswith(b"<?xml") or head.startswith(b"<svg") or b"<svg" in head[:512].lower()
diff --git a/services/api/app/services/digest_html.py b/services/api/app/services/digest_html.py
index 456aa52f6..e29c3f7ff 100644
--- a/services/api/app/services/digest_html.py
+++ b/services/api/app/services/digest_html.py
@@ -20,6 +20,8 @@ from __future__ import annotations
import html
from datetime import UTC, datetime
+from app.services.branding.resolver import DEFAULT_BRANDING, Branding
+
from .executive_digest import (
AutomationSummary,
DigestRecommendation,
@@ -191,16 +193,38 @@ def _recommendation_cards(recs: list[DigestRecommendation]) -> str:
return cards
-def render_digest_html(digest: ExecutiveDigest) -> str:
- """Render an ``ExecutiveDigest`` to a self-contained HTML document."""
+def render_digest_html(digest: ExecutiveDigest, branding: Branding | None = None) -> str:
+ """Render an ``ExecutiveDigest`` to a self-contained HTML document.
+
+ ``branding`` defaults to the platform appearance, so every existing
+ caller keeps working and an unbranded deployment is unchanged. A
+ white-labelled organisation's report carries its product name, its
+ palette and its own logo, which is the document a customer forwards to
+ their board.
+
+ The logo is embedded as a data URI rather than referenced, because this
+ HTML is handed to WeasyPrint: a remote `<img src>` would be an outbound
+ request made by the server, to an address a customer administrator
+ supplied. The bytes are already sanitised at upload.
+ """
+ brand = branding or DEFAULT_BRANDING
headline = _esc(digest.headline)
period = digest.period
+ product = _esc(brand.product_name)
+ primary = _esc(brand.primary_color)
+ logo_block = ""
+ if brand.logo_data_uri:
+ logo_block = f'<img src="{_esc(brand.logo_data_uri)}" alt="{product}" style="max-height:40px;max-width:200px;margin-bottom:10px;">'
+ support_block = ""
+ if brand.support_email or brand.support_url:
+ where = _esc(brand.support_url or brand.support_email or "")
+ support_block = f'<div style="margin-top:4px;">Support: {where}</div>'
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
-<title>AiSOC Executive Digest — {_esc(period.label)}</title>
+<title>{product} Executive Digest — {_esc(period.label)}</title>
<style>
@page {{ margin: 18mm; }}
body {{
@@ -213,6 +237,7 @@ def render_digest_html(digest: ExecutiveDigest) -> str:
}}
h1, h2, h3 {{ color: #0f172a; margin-top: 0; }}
h1 {{ font-size: 22px; margin-bottom: 4px; }}
+ h2 {{ border-top-color: {primary}; }}
h2 {{ font-size: 15px; text-transform: uppercase; letter-spacing: 0.08em;
color: #475569; margin: 20px 0 10px; border-top: 1px solid #e2e8f0; padding-top: 14px; }}
table th, table td {{ border-bottom: 1px solid #f1f5f9; }}
@@ -224,8 +249,9 @@ def render_digest_html(digest: ExecutiveDigest) -> str:
</head>
<body>
<header>
- <div style="font-size:11px;color:#64748b;text-transform:uppercase;letter-spacing:0.08em;">
- AiSOC weekly executive digest
+ {logo_block}
+ <div style="font-size:11px;color:{primary};text-transform:uppercase;letter-spacing:0.08em;">
+ {product} weekly executive digest
</div>
<h1>{_esc(period.label)}</h1>
<div style="color:#334155;font-size:14px;margin-top:6px;">{headline}</div>
@@ -267,8 +293,8 @@ def render_digest_html(digest: ExecutiveDigest) -> str:
{_recommendation_cards(digest.recommendations)}
<footer style="margin-top:32px;color:#94a3b8;font-size:11px;text-align:center;">
- AiSOC — open-source AI Security Operations Center.
- Print this page (Ctrl/Cmd-P → Save as PDF) for board-ready archival.
+ {_esc(brand.footer_text)}
+ {support_block}
</footer>
</body>
</html>"""
diff --git a/services/api/app/services/digest_pdf.py b/services/api/app/services/digest_pdf.py
index 4276875fa..518422e67 100644
--- a/services/api/app/services/digest_pdf.py
+++ b/services/api/app/services/digest_pdf.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import logging
+from app.services.branding.resolver import Branding
from app.services.digest_html import render_digest_html
from app.services.executive_digest import ExecutiveDigest
@@ -27,7 +28,7 @@ class WeasyPrintUnavailableError(RuntimeError):
"""Raised when the WeasyPrint native stack is not installed."""
-def render_digest_pdf(digest: ExecutiveDigest) -> bytes:
+def render_digest_pdf(digest: ExecutiveDigest, branding: Branding | None = None) -> bytes:
"""Render *digest* as a PDF byte string.
Converts the ``ExecutiveDigest`` model to a self-contained, print-ready
@@ -59,7 +60,7 @@ def render_digest_pdf(digest: ExecutiveDigest) -> bytes:
"required apt packages."
) from exc
- html_content = render_digest_html(digest)
+ html_content = render_digest_html(digest, branding)
logger.info(
"rendering executive digest PDF tenant_id=%s period_start=%s",
digest.tenant_id,
diff --git a/services/api/app/services/usage_metering.py b/services/api/app/services/usage_metering.py
new file mode 100644
index 000000000..eeeef7b77
--- /dev/null
+++ b/services/api/app/services/usage_metering.py
@@ -0,0 +1,354 @@
+"""Per-tenant, per-day usage, counted from the rows that record the work.
+
+Why there is no counter table
+------------------------------
+The obvious design is a `usage_daily` table incremented as things happen.
+That design has one failure mode and this repository has already paid for it
+twice: a counter drifts from the table it summarises, nothing notices,
+and two surfaces then disagree about the same rows. `cases_closed_7d` read a
+status that was intermediate; `mttr_hours` averaged a column ordinary case
+work never writes and published emptiness as a confident `0.0`.
+
+So every meter here is a `SELECT` against the table that holds the evidence,
+evaluated when somebody asks. The number cannot drift from the rows because
+it *is* the rows. That is also what makes the acceptance test possible:
+insert a known number of rows, ask the meter, compare. A counter table could
+only be tested against itself.
+
+The cost is that a query runs per request rather than a lookup. Bounded by
+the indexes these tables already carry on `(tenant_id, created_at)`, and a
+usage screen is not on a hot path.
+
+Why a meter can read "not measured"
+------------------------------------
+`events_ingested` lives in the ClickHouse event lake, which is a `full`
+profile service and is absent on CORE. A meter whose source is not deployed
+reports ``None``, and every surface renders that as "not measured". It must
+never render as `0`: zero is a measurement, and a reader who sees it
+concludes no events arrived rather than that nothing looked.
+
+There is no pricing logic here, deliberately. These are counts and measured
+costs. What they are worth is a commercial question and belongs nowhere near
+the code that answers "what happened".
+"""
+
+from __future__ import annotations
+
+import csv
+import io
+import uuid
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Final
+
+from sqlalchemy import DateTime, String, Uuid, bindparam, text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+
+@dataclass(frozen=True)
+class Meter:
+ """One measurable quantity.
+
+ ``sql`` must bind the tenant and the day window as parameters and never
+ format them into the string. It returns exactly one row with one column.
+
+ ``source`` names the table the number comes from, so a reader can check
+ it, and so :func:`reconcile` can state what it compared.
+ """
+
+ key: str
+ label: str
+ description: str
+ source: str
+ sql: str
+ #: A quantity that is summed rather than counted. Only affects how a
+ #: total across days is labelled, never how it is computed.
+ is_sum: bool = False
+
+
+#: Anything a tenant does that this deployment can count from its own rows.
+#:
+#: `alerts` and `triages_*` intentionally mirror the definitions
+#: `app.services.entitlements` uses for the limits they map to, because two
+#: definitions of "a triage" is exactly how a usage screen and a quota screen
+#: end up disagreeing in front of a customer.
+METERS: Final[tuple[Meter, ...]] = (
+ Meter(
+ "alerts",
+ "Alerts",
+ "Alerts created in the window.",
+ "alerts",
+ "SELECT count(*) FROM alerts WHERE tenant_id = :tenant_id AND created_at >= :start AND created_at < :end",
+ ),
+ Meter(
+ # "By path" is the distinction that matters to an operator: how much
+ # of the queue a model touched. An alert carrying AI output is the
+ # row a model triage writes, which is the same evidence
+ # `entitlements.triages_per_month` counts.
+ "triages_model",
+ "AI triages",
+ "Alerts carrying model-generated triage output.",
+ "alerts",
+ (
+ "SELECT count(*) FROM alerts WHERE tenant_id = :tenant_id AND created_at >= :start AND created_at < :end "
+ "AND (ai_summary IS NOT NULL OR ai_score IS NOT NULL)"
+ ),
+ ),
+ Meter(
+ "triages_deterministic",
+ "Deterministic triages",
+ "Alerts resolved without model output: rule verdicts and institutional-memory suppression.",
+ "alerts",
+ (
+ "SELECT count(*) FROM alerts WHERE tenant_id = :tenant_id AND created_at >= :start AND created_at < :end "
+ "AND ai_summary IS NULL AND ai_score IS NULL"
+ ),
+ ),
+ Meter(
+ "investigations",
+ "Investigations",
+ "Agent investigation runs started in the window.",
+ "investigation_runs",
+ "SELECT count(*) FROM investigation_runs WHERE tenant_id = :tenant_id AND created_at >= :start AND created_at < :end",
+ ),
+ Meter(
+ "llm_tokens",
+ "LLM tokens",
+ "Prompt plus completion tokens recorded against this tenant's runs.",
+ "aisoc_run_costs",
+ (
+ "SELECT COALESCE(SUM(total_prompt_tokens + total_completion_tokens), 0) FROM aisoc_run_costs "
+ "WHERE tenant_id = :tenant_text AND recorded_at >= :start AND recorded_at < :end"
+ ),
+ is_sum=True,
+ ),
+ Meter(
+ "llm_cost_usd",
+ "LLM cost (USD)",
+ "Measured model spend. Not a price: what the provider charged for the calls this tenant caused.",
+ "aisoc_run_costs",
+ (
+ "SELECT COALESCE(SUM(total_cost_usd), 0) FROM aisoc_run_costs "
+ "WHERE tenant_id = :tenant_text AND recorded_at >= :start AND recorded_at < :end"
+ ),
+ is_sum=True,
+ ),
+ Meter(
+ "actions",
+ "Response actions",
+ "Response actions recorded in the window, across every approval tier.",
+ "aisoc_action_records",
+ "SELECT count(*) FROM aisoc_action_records WHERE tenant_id = :tenant_text AND created_at >= :start AND created_at < :end",
+ ),
+ Meter(
+ "actions_executed",
+ "Actions executed",
+ "Of those, the ones that reached a vendor. 'executed' is the single status that means a vendor was touched.",
+ "aisoc_action_records",
+ (
+ "SELECT count(*) FROM aisoc_action_records WHERE tenant_id = :tenant_text "
+ "AND created_at >= :start AND created_at < :end AND status = 'executed'"
+ ),
+ ),
+)
+
+#: Meters that describe the current shape of the deployment rather than
+#: activity in a window. Counting them per day would report today's value
+#: against every historical day, which is a plausible-looking lie.
+POINT_IN_TIME_METERS: Final[tuple[Meter, ...]] = (
+ Meter(
+ "active_connectors",
+ "Active connectors",
+ "Enabled data sources right now.",
+ "connectors",
+ "SELECT count(*) FROM connectors WHERE tenant_id = :tenant_id AND is_enabled",
+ ),
+ Meter(
+ "seats",
+ "Seats",
+ "Active user accounts right now.",
+ "users",
+ "SELECT count(*) FROM users WHERE tenant_id = :tenant_id AND is_active",
+ ),
+)
+
+METERS_BY_KEY: Final[dict[str, Meter]] = {m.key: m for m in (*METERS, *POINT_IN_TIME_METERS)}
+
+#: Meters whose source is not in Postgres. Reported as ``None`` rather than
+#: zero, and named here so the API can say *which* meter was not measured and
+#: why, instead of leaving a silent gap in the series.
+UNMEASURED: Final[dict[str, str]] = {
+ "events_ingested": ("counted in the ClickHouse event lake, which runs in the `full` profile. Not measured on a deployment without it."),
+}
+
+
+@dataclass(frozen=True)
+class DailyUsage:
+ """One tenant, one day, every meter."""
+
+ day: date
+ values: dict[str, float | int]
+
+ def as_dict(self) -> dict[str, Any]:
+ return {"day": self.day.isoformat(), **self.values}
+
+
+def _window(day: date) -> tuple[datetime, datetime]:
+ """The half-open UTC day ``[start, end)``.
+
+ Half-open so a row landing exactly at midnight is counted once. Counting
+ it in both days is how a monthly total exceeds the row count it claims to
+ summarise.
+ """
+ start = datetime(day.year, day.month, day.day, tzinfo=UTC)
+ return start, start + timedelta(days=1)
+
+
+#: Bind types for the four parameters the meters use. Declared rather than
+#: inferred because these statements are raw SQL: without a type, the driver
+#: is handed a `uuid.UUID` and a timezone-aware `datetime` and has to guess.
+#: asyncpg guesses correctly and other drivers do not, which would make the
+#: meters work in production and fail in any harness that is not Postgres.
+_BIND_TYPES: Final[dict[str, Any]] = {
+ "tenant_id": Uuid(as_uuid=True),
+ # `aisoc_run_costs` and `aisoc_action_records` store the tenant as TEXT,
+ # so those meters bind a string. Two names rather than one cast, because
+ # a cast in the SQL would defeat the index on those columns.
+ "tenant_text": String(),
+ "start": DateTime(timezone=True),
+ "end": DateTime(timezone=True),
+}
+
+
+def _statement(sql: str) -> Any:
+ """A ``text()`` clause with every parameter it uses explicitly typed."""
+ clause = text(sql)
+ present = [bindparam(name, type_=kind) for name, kind in _BIND_TYPES.items() if f":{name}" in sql]
+ return clause.bindparams(*present) if present else clause
+
+
+async def measure_day(db: AsyncSession, tenant_id: uuid.UUID, day: date) -> DailyUsage:
+ """Every windowed meter for one tenant on one day."""
+ start, end = _window(day)
+ params = {"tenant_id": tenant_id, "tenant_text": str(tenant_id), "start": start, "end": end}
+
+ values: dict[str, float | int] = {}
+ for meter in METERS:
+ raw = await db.scalar(_statement(meter.sql), params)
+ values[meter.key] = float(raw or 0) if meter.key.endswith("_usd") else int(raw or 0)
+ return DailyUsage(day=day, values=values)
+
+
+async def measure_range(db: AsyncSession, tenant_id: uuid.UUID, start: date, end: date) -> list[DailyUsage]:
+ """Daily usage across ``[start, end]`` inclusive."""
+ if end < start:
+ raise ValueError("end is before start")
+ days: list[DailyUsage] = []
+ cursor = start
+ while cursor <= end:
+ days.append(await measure_day(db, tenant_id, cursor))
+ cursor += timedelta(days=1)
+ return days
+
+
+async def measure_point_in_time(db: AsyncSession, tenant_id: uuid.UUID) -> dict[str, int]:
+ """Connectors and seats as they stand now."""
+ values: dict[str, int] = {}
+ for meter in POINT_IN_TIME_METERS:
+ raw = await db.scalar(_statement(meter.sql), {"tenant_id": tenant_id})
+ values[meter.key] = int(raw or 0)
+ return values
+
+
+def totals(days: Sequence[DailyUsage]) -> dict[str, float | int]:
+ """Sum each meter across the range.
+
+ Every meter here is additive over disjoint day windows, which is why the
+ windows are half-open. A meter that was not additive would have to be
+ recomputed over the whole range instead, and none is.
+ """
+ summed: dict[str, float | int] = {}
+ for meter in METERS:
+ values = [day.values.get(meter.key, 0) for day in days]
+ summed[meter.key] = round(sum(float(v) for v in values), 6) if meter.key.endswith("_usd") else sum(int(v) for v in values)
+ return summed
+
+
+async def reconcile(db: AsyncSession, tenant_id: uuid.UUID, start: date, end: date) -> dict[str, dict[str, Any]]:
+ """Compare the daily sum against one query over the whole window.
+
+ This is what makes "metering matches row counts" checkable rather than
+ asserted. The per-day path and the whole-window path are different
+ queries over the same rows; if the day boundaries drop a row or count one
+ twice, these disagree.
+
+ Returns one entry per meter with both figures and whether they agree, so
+ a caller reports every mismatch rather than the first.
+ """
+ days = await measure_range(db, tenant_id, start, end)
+ per_day = totals(days)
+
+ whole_start, _ = _window(start)
+ _, whole_end = _window(end)
+ params = {"tenant_id": tenant_id, "tenant_text": str(tenant_id), "start": whole_start, "end": whole_end}
+
+ report: dict[str, dict[str, Any]] = {}
+ for meter in METERS:
+ raw = await db.scalar(_statement(meter.sql), params)
+ direct = float(raw or 0) if meter.key.endswith("_usd") else int(raw or 0)
+ summed = per_day[meter.key]
+ agrees = abs(float(direct) - float(summed)) < 1e-6
+ report[meter.key] = {"source": meter.source, "per_day_total": summed, "single_query": direct, "agrees": agrees}
+ return report
+
+
+def to_csv(
+ *,
+ tenant_id: uuid.UUID,
+ org_name: str | None,
+ days: Sequence[DailyUsage],
+ point_in_time: dict[str, int],
+) -> str:
+ """The monthly CSV.
+
+ Carries a header block naming the tenant, the organisation and the
+ generation time, because a bare grid of numbers in somebody's downloads
+ folder cannot answer what it is about. Unmeasured meters are listed by
+ name with their reason rather than omitted, so a reader can tell a gap
+ from a zero.
+ """
+ buffer = io.StringIO()
+ writer = csv.writer(buffer, lineterminator="\n")
+
+ writer.writerow(["# AiSOC usage export"])
+ writer.writerow(["# tenant", str(tenant_id)])
+ writer.writerow(["# organisation", org_name or "(none)"])
+ writer.writerow(["# generated", datetime.now(UTC).isoformat()])
+ for key, reason in UNMEASURED.items():
+ writer.writerow([f"# not measured: {key}", reason])
+ writer.writerow([])
+
+ columns = [m.key for m in METERS]
+ writer.writerow(["day", *columns])
+ for day in days:
+ writer.writerow([day.day.isoformat(), *[day.values.get(key, 0) for key in columns]])
+
+ summed = totals(days)
+ writer.writerow(["total", *[summed[key] for key in columns]])
+ writer.writerow([])
+
+ writer.writerow(["# point-in-time, at generation"])
+ for meter in POINT_IN_TIME_METERS:
+ writer.writerow([meter.key, point_in_time.get(meter.key, 0)])
+
+ return buffer.getvalue()
+
+
+def month_bounds(year: int, month: int) -> tuple[date, date]:
+ """First and last day of a calendar month."""
+ if not 1 <= month <= 12:
+ raise ValueError("month must be 1-12")
+ first = date(year, month, 1)
+ last = date(year + (month == 12), 1 if month == 12 else month + 1, 1) - timedelta(days=1)
+ return first, last
diff --git a/services/api/migrations/072_org_branding.sql b/services/api/migrations/072_org_branding.sql
new file mode 100644
index 000000000..ee7b268fb
--- /dev/null
+++ b/services/api/migrations/072_org_branding.sql
@@ -0,0 +1,123 @@
+-- 072: per-organisation white-label branding, with assets held locally.
+--
+-- Gap-closure Phase 13.2.
+--
+-- Why the bytes live in this database
+-- ------------------------------------
+-- The plan is explicit that assets are stored locally and never fetched from
+-- a third-party URL, and the reason is not convenience. A logo referenced by
+-- URL is an outbound request made by whatever renders it: the console (from
+-- the operator's browser, leaking who is looking at what to whoever hosts the
+-- image) and the PDF renderer (from inside the server, which is a
+-- server-side request forgery primitive aimed at a URL a customer
+-- administrator supplied). Holding the bytes removes both, and it removes the
+-- third failure mode too: a logo that renders in a report today and 404s in
+-- the same report opened next quarter.
+--
+-- BYTEA rather than a volume, because a logo is small, the cap is enforced in
+-- the application, and a file on one replica's disk is a file the other
+-- replicas cannot serve.
+--
+-- Why branding hangs off the organisation and not the tenant
+-- -----------------------------------------------------------
+-- A managed-service provider brands what its customers see, across every
+-- tenant in its portfolio. One row per organisation is the whole point: a
+-- per-tenant table would make "our branding" something an operator had to
+-- apply N times and keep in agreement.
+--
+-- Why there is no row-level-security policy here
+-- -----------------------------------------------
+-- These tables carry no `tenant_id`, so the tenant policy shape does not
+-- apply to them. They follow `organizations` and `organization_members` from
+-- migration 058, which are scoped at the query layer by
+-- `app/services/org_scope.py`. `check_rls_policy_shape.py` judges the shape
+-- of tenant policies; adding one keyed on a column that does not exist would
+-- be theatre.
+
+CREATE TABLE IF NOT EXISTS aisoc_org_brand_assets (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ org_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
+
+ -- `logo` renders in the console header and at the top of a PDF report.
+ -- `favicon` is the browser tab. Constrained so a third kind has to be
+ -- added deliberately, with somewhere to render it.
+ kind TEXT NOT NULL CHECK (kind IN ('logo', 'favicon')),
+
+ content_type TEXT NOT NULL,
+ -- The sanitised bytes for an SVG, the original bytes for a raster. What
+ -- is stored is what is served: nothing re-sanitises at render time, so a
+ -- row here is trusted and the sanitiser is the only thing that writes it.
+ content BYTEA NOT NULL,
+ byte_size INTEGER NOT NULL CHECK (byte_size > 0 AND byte_size <= 262144),
+ -- SHA-256 of the stored bytes, so a cache can revalidate and an operator
+ -- can confirm the asset they uploaded is the asset being served.
+ sha256 TEXT NOT NULL,
+ -- TRUE when the uploaded SVG had constructs removed. Surfaced to the
+ -- administrator, because "your logo renders differently than it did in
+ -- your graphics program" needs an explanation and not a mystery.
+ was_sanitized BOOLEAN NOT NULL DEFAULT FALSE,
+
+ uploaded_by UUID REFERENCES users(id) ON DELETE SET NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ -- One current asset per kind per organisation. Replacing is an UPDATE,
+ -- so a stale logo cannot linger beside its replacement.
+ UNIQUE (org_id, kind)
+);
+
+COMMENT ON TABLE aisoc_org_brand_assets IS
+ 'Uploaded brand assets, held as bytes. Never a URL: a remote logo is an '
+ 'outbound request from the console and from the PDF renderer, and the '
+ 'second of those is server-side request forgery against a customer-'
+ 'supplied address.';
+COMMENT ON COLUMN aisoc_org_brand_assets.content IS
+ 'Sanitised bytes for an SVG, original bytes for a raster. Nothing '
+ 're-sanitises at render time, so the sanitiser is the only writer.';
+
+CREATE INDEX IF NOT EXISTS idx_org_brand_assets_org ON aisoc_org_brand_assets (org_id);
+
+
+CREATE TABLE IF NOT EXISTS aisoc_org_branding (
+ org_id UUID PRIMARY KEY REFERENCES organizations(id) ON DELETE CASCADE,
+
+ -- Every field is nullable and every one falls back to the platform
+ -- default at read time. A half-configured organisation therefore renders
+ -- a coherent product rather than a page with holes in it, which is what
+ -- an operator sees during the ten minutes between creating the row and
+ -- finishing it.
+ product_name TEXT CHECK (product_name IS NULL OR length(product_name) BETWEEN 1 AND 80),
+ primary_color TEXT CHECK (primary_color IS NULL OR primary_color ~ '^#[0-9A-Fa-f]{6}$'),
+ accent_color TEXT CHECK (accent_color IS NULL OR accent_color ~ '^#[0-9A-Fa-f]{6}$'),
+
+ support_email TEXT CHECK (support_email IS NULL OR support_email ~ '^[^@[:space:]]+@[^@[:space:]]+\.[^@[:space:]]+$'),
+ -- Constrained to https at the database as well as in the application.
+ -- This string is rendered as a link in an email and in a PDF, so a
+ -- `javascript:` value here would be a stored script in somebody else's
+ -- inbox.
+ support_url TEXT CHECK (support_url IS NULL OR support_url ~ '^https://'),
+
+ -- The display name on outbound mail and ChatOps messages.
+ 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),
+
+ updated_by UUID REFERENCES users(id) ON DELETE SET NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+COMMENT ON TABLE aisoc_org_branding IS
+ 'White-label settings for one operator organisation. Every column is '
+ 'nullable and falls back to the platform default at read time, so a '
+ 'half-configured organisation renders a coherent product.';
+COMMENT ON COLUMN aisoc_org_branding.support_url IS
+ 'https only, enforced here as well as in the application: this string is '
+ 'rendered as a link in email and in PDF reports.';
+
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN
+ GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_org_branding TO aisoc_app;
+ GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_org_brand_assets TO aisoc_app;
+ END IF;
+END
+$$;
diff --git a/services/api/tests/test_branding.py b/services/api/tests/test_branding.py
new file mode 100644
index 000000000..54b2cfcdd
--- /dev/null
+++ b/services/api/tests/test_branding.py
@@ -0,0 +1,335 @@
+"""A white-labelled organisation's console and PDF report carry its branding.
+
+Gap-closure Phase 13.2 gate, and the acceptance is literal: the two surfaces
+named in the plan are exercised here against a configured organisation.
+
+Two properties beyond "the name appears"
+-----------------------------------------
+* **Nothing is fetched from a third party.** The plan says assets are stored
+ locally and never fetched from a remote URL, and the reason is that a
+ remote logo is an outbound request made by whatever renders it. For a PDF
+ that renderer is the server, which makes a customer-supplied address a
+ server-side request forgery primitive. So the report is asserted to embed
+ the bytes and to contain no external scheme at all.
+* **Falling back is field by field.** An organisation that has set a name and
+ no colours renders its name against the platform palette. Falling back to
+ the whole default row would silently discard the one field the operator
+ bothered to set.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+
+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.services.branding import resolver
+from app.services.branding.svg_sanitizer import sanitize_svg
+from sqlalchemy.dialects.postgresql import 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
+
+MANAGED_TENANT = uuid.UUID("eeeeeeee-0000-0000-0000-0000000000e1")
+HOME_TENANT = uuid.UUID("eeeeeeee-0000-0000-0000-0000000000e2")
+UNMANAGED_TENANT = uuid.UUID("ffffffff-0000-0000-0000-0000000000f1")
+ORG = uuid.UUID("0a0a0a0a-0000-0000-0000-00000000000a")
+
+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)"
+
+
+@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__,
+ ],
+ )
+ yield async_sessionmaker(engine, expire_on_commit=False)
+ await engine.dispose()
+
+
+async def _brand(db, **overrides):
+ db.add(Organization(id=ORG, slug="acme", name="Acme MSSP", home_tenant_id=HOME_TENANT))
+ db.add(OrganizationTenant(org_id=ORG, tenant_id=MANAGED_TENANT, onboarded_at=datetime.now(UTC)))
+ db.add(OrgBranding(org_id=ORG, **overrides))
+ await db.commit()
+
+
+class TestResolution:
+ async def test_an_unmanaged_tenant_gets_the_platform_default(self, session_factory):
+ async with session_factory() as db:
+ branding = await resolver.resolve_branding(db, UNMANAGED_TENANT)
+ assert branding.product_name == resolver.DEFAULT_BRANDING.product_name
+ # The flag distinguishes "the default because that was chosen" from
+ # "the default because nobody has been here yet".
+ assert branding.is_white_labelled is False
+
+ async def test_a_managed_tenant_gets_its_operators_branding(self, session_factory):
+ async with session_factory() as db:
+ await _brand(db, product_name="Acme Shield", primary_color="#123456")
+ branding = await resolver.resolve_branding(db, MANAGED_TENANT)
+ assert branding.product_name == "Acme Shield"
+ assert branding.primary_color == "#123456"
+ assert branding.is_white_labelled is True
+
+ async def test_the_operators_own_staff_see_it_too(self, session_factory):
+ """Resolution has to follow ``home_tenant_id`` as well as the portfolio.
+
+ Checking only the portfolio leaves the operator's own console
+ unbranded, which is the one console they look at every day.
+ """
+ async with session_factory() as db:
+ await _brand(db, product_name="Acme Shield")
+ branding = await resolver.resolve_branding(db, HOME_TENANT)
+ assert branding.product_name == "Acme Shield"
+
+ async def test_unset_fields_fall_back_individually(self, session_factory):
+ """A name and no colours renders the name against the platette."""
+ async with session_factory() as db:
+ await _brand(db, product_name="Acme Shield")
+ branding = await resolver.resolve_branding(db, MANAGED_TENANT)
+ assert branding.product_name == "Acme Shield"
+ assert branding.primary_color == resolver.DEFAULT_BRANDING.primary_color
+
+ async def test_the_sender_name_defaults_to_the_product_name(self, session_factory):
+ """Not to the platform name.
+
+ An operator who renames the product and forgets this field would
+ otherwise send mail from a brand their customer has never heard of,
+ which reads as a phishing attempt.
+ """
+ async with session_factory() as db:
+ await _brand(db, product_name="Acme Shield")
+ branding = await resolver.resolve_branding(db, MANAGED_TENANT)
+ assert branding.sender_name == "Acme Shield"
+
+ async def test_an_explicit_sender_name_still_wins(self, session_factory):
+ async with session_factory() as db:
+ await _brand(db, product_name="Acme Shield", sender_name="Acme SOC")
+ branding = await resolver.resolve_branding(db, MANAGED_TENANT)
+ assert branding.sender_name == "Acme SOC"
+
+ async def test_a_broken_lookup_returns_the_default_rather_than_raising(self, session_factory):
+ """Appearance must never take down content.
+
+ A report that renders in the platform palette is better than a report
+ that does not render.
+ """
+
+ class Exploding:
+ async def execute(self, *_args, **_kwargs):
+ raise RuntimeError("database is unavailable")
+
+ branding = await resolver.resolve_branding(Exploding(), MANAGED_TENANT) # type: ignore[arg-type]
+ assert branding == resolver.DEFAULT_BRANDING
+
+
+class TestAssets:
+ async def test_the_logo_is_served_from_this_deployment_not_a_remote_url(self, session_factory):
+ async with session_factory() as db:
+ await _brand(db, product_name="Acme Shield")
+ cleaned = sanitize_svg(LOGO)
+ db.add(
+ OrgBrandAsset(
+ org_id=ORG,
+ kind="logo",
+ content_type="image/svg+xml",
+ content=cleaned.svg.encode(),
+ byte_size=len(cleaned.svg),
+ sha256="x" * 64,
+ )
+ )
+ await db.commit()
+ branding = await resolver.resolve_branding(db, MANAGED_TENANT)
+
+ assert branding.logo_url is not None
+ assert branding.logo_url.startswith("/api/v1/branding/assets/")
+ assert "http://" not in branding.logo_url
+ assert "https://" not in branding.logo_url
+
+ async def test_inlining_produces_a_data_uri_with_no_outbound_reference(self, session_factory):
+ async with session_factory() as db:
+ await _brand(db, product_name="Acme Shield")
+ cleaned = sanitize_svg(LOGO)
+ db.add(
+ OrgBrandAsset(
+ org_id=ORG,
+ kind="logo",
+ content_type="image/svg+xml",
+ content=cleaned.svg.encode(),
+ byte_size=len(cleaned.svg),
+ sha256="x" * 64,
+ )
+ )
+ await db.commit()
+ branding = await resolver.resolve_branding(db, MANAGED_TENANT, inline_logo=True)
+
+ assert branding.logo_data_uri is not None
+ assert branding.logo_data_uri.startswith("data:image/svg+xml;base64,")
+
+ async def test_the_bytes_are_not_loaded_unless_asked_for(self, session_factory):
+ """The console does not need them and every page load would carry one."""
+ async with session_factory() as db:
+ await _brand(db, product_name="Acme Shield")
+ cleaned = sanitize_svg(LOGO)
+ db.add(
+ OrgBrandAsset(
+ org_id=ORG,
+ kind="logo",
+ content_type="image/svg+xml",
+ content=cleaned.svg.encode(),
+ byte_size=len(cleaned.svg),
+ sha256="x" * 64,
+ )
+ )
+ await db.commit()
+ branding = await resolver.resolve_branding(db, MANAGED_TENANT)
+ assert branding.logo_data_uri is None
+
+
+class TestTheReport:
+ """The PDF half of the acceptance.
+
+ A PDF is this HTML run through WeasyPrint, so asserting on the HTML is
+ asserting on what the PDF contains, without requiring the native
+ rendering stack to be installed in CI.
+ """
+
+ @staticmethod
+ def _digest():
+ from app.services.executive_digest import (
+ AlertSummary,
+ AutomationSummary,
+ CaseSummary,
+ DigestPeriod,
+ ExecutiveDigest,
+ MttSummary,
+ SeveritySplit,
+ )
+
+ return ExecutiveDigest(
+ tenant_id=MANAGED_TENANT,
+ period=DigestPeriod(
+ label="10-16 March 2026",
+ start=datetime(2026, 3, 10, tzinfo=UTC),
+ end=datetime(2026, 3, 16, tzinfo=UTC),
+ ),
+ headline="Two incidents, both contained.",
+ alerts=AlertSummary(total=10, new=4, resolved=6, open_at_period_end=4, severity=SeveritySplit()),
+ cases=CaseSummary(opened=2, closed=2, open_at_period_end=0, sla_breached=0),
+ mtt=MttSummary(mttd_hours=1.0, mttr_hours=2.0, mttc_hours=3.0),
+ automation=AutomationSummary(total_decisions=0, auto_executed=0, escalated=0, review_pending=0),
+ top_tactics=[],
+ top_sources=[],
+ high_risk_alerts=[],
+ recommendations=[],
+ )
+
+ def test_an_unbranded_deployment_renders_exactly_as_before(self):
+ from app.services.digest_html import render_digest_html
+
+ html = render_digest_html(self._digest())
+ assert "AiSOC" in html
+
+ async def test_a_white_labelled_report_carries_the_name_palette_and_logo(self, session_factory):
+ from app.services.digest_html import render_digest_html
+
+ async with session_factory() as db:
+ await _brand(db, product_name="Acme Shield", primary_color="#123456", support_url="https://support.acme.example")
+ cleaned = sanitize_svg(LOGO)
+ db.add(
+ OrgBrandAsset(
+ org_id=ORG,
+ kind="logo",
+ content_type="image/svg+xml",
+ content=cleaned.svg.encode(),
+ byte_size=len(cleaned.svg),
+ sha256="x" * 64,
+ )
+ )
+ await db.commit()
+ branding = await resolver.resolve_branding(db, MANAGED_TENANT, inline_logo=True)
+
+ html = render_digest_html(self._digest(), branding)
+
+ assert "Acme Shield" in html
+ assert "#123456" in html
+ assert "data:image/svg+xml;base64," in html
+ assert "support.acme.example" in html
+
+ # And the platform name is gone from the chrome. A report that says
+ # both is not white-labelled, it is co-branded by accident.
+ assert "AiSOC weekly executive digest" not in html
+ assert "AiSOC — open-source" not in html
+
+ async def test_the_report_makes_no_outbound_request_when_rendered(self, session_factory):
+ """WeasyPrint renders this server-side.
+
+ A remote `<img src>` here is an outbound request made by the server,
+ to an address a customer administrator supplied.
+ """
+ from app.services.digest_html import render_digest_html
+
+ async with session_factory() as db:
+ await _brand(db, product_name="Acme Shield")
+ cleaned = sanitize_svg(LOGO)
+ db.add(
+ OrgBrandAsset(
+ org_id=ORG,
+ kind="logo",
+ content_type="image/svg+xml",
+ content=cleaned.svg.encode(),
+ byte_size=len(cleaned.svg),
+ sha256="x" * 64,
+ )
+ )
+ await db.commit()
+ branding = await resolver.resolve_branding(db, MANAGED_TENANT, inline_logo=True)
+
+ html = render_digest_html(self._digest(), branding)
+ for scheme in ("http://", "https://"):
+ offenders = [fragment for fragment in html.split('"') if fragment.startswith(scheme) and "w3.org" not in fragment]
+ assert not offenders, f"report references {offenders}"
+
+
+class TestSupportUrlIsNotAScriptVector:
+ """``support_url`` is rendered as a link in email and in a PDF."""
+
+ @pytest.mark.parametrize(
+ "hostile",
+ ["javascript:alert(1)", "http://insecure.example", "data:text/html,<script>alert(1)</script>", "vbscript:x"],
+ )
+ def test_a_non_https_support_url_is_refused_at_the_boundary(self, hostile):
+ from app.api.v1.endpoints.branding import BrandingIn
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError):
+ BrandingIn(support_url=hostile)
+
+ def test_an_https_url_is_accepted(self):
+ from app.api.v1.endpoints.branding import BrandingIn
+
+ assert BrandingIn(support_url="https://support.acme.example").support_url == "https://support.acme.example"
diff --git a/services/api/tests/test_svg_sanitizer.py b/services/api/tests/test_svg_sanitizer.py
new file mode 100644
index 000000000..a2bd191fe
--- /dev/null
+++ b/services/api/tests/test_svg_sanitizer.py
@@ -0,0 +1,189 @@
+"""An uploaded SVG is a script-carrying document, and this is what stops it.
+
+Gap-closure Phase 13.2 gate.
+
+A logo is uploaded by a customer administrator and rendered inside the
+console and inside PDF reports other people open. That makes it a stored
+cross-site scripting vector with a distribution mechanism attached, so the
+tests below are written as attacks rather than as round trips.
+
+The allowlist is asserted from both sides. A denylist test ("no <script>
+survives") passes against a sanitiser that lets `<foreignObject>` through,
+which is the failure this design exists to prevent, so there is a case here
+for every construct the allowlist excludes and a case proving a legitimate
+logo still renders.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.services.branding.svg_sanitizer import (
+ MAX_SVG_BYTES,
+ SvgRejected,
+ looks_like_svg,
+ sanitize_svg,
+)
+
+#: A logo of the kind a graphics program produces. Must survive intact.
+BENIGN = b"""<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 40" width="120" height="40">
+ <title>Acme Security</title>
+ <defs>
+ <linearGradient id="g1" x1="0" y1="0" x2="1" y2="0">
+ <stop offset="0%" stop-color="#2563EB"/>
+ <stop offset="100%" stop-color="#7C3AED"/>
+ </linearGradient>
+ </defs>
+ <rect x="0" y="0" width="40" height="40" rx="6" fill="url(#g1)"/>
+ <path d="M8 20 L18 30 L32 10" stroke="#ffffff" stroke-width="4" fill="none"/>
+ <text x="48" y="26" font-family="Arial" font-size="16" fill="#0f172a">Acme</text>
+</svg>"""
+
+
+class TestActiveContentIsRemoved:
+ @pytest.mark.parametrize(
+ ("payload", "must_not_contain"),
+ [
+ (b'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>', "alert"),
+ (b'<svg xmlns="http://www.w3.org/2000/svg"><script/><circle r="1"/></svg>', "script"),
+ # The classic: an event handler on a legitimate element.
+ (b'<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"><circle r="1"/></svg>', "onload"),
+ (b'<svg xmlns="http://www.w3.org/2000/svg"><circle r="1" onmouseover="alert(1)"/></svg>', "onmouseover"),
+ # Arbitrary HTML, which a denylist of <script> misses entirely.
+ (
+ # Well-formed XML on purpose: a malformed payload would be
+ # refused by the parser, which would let this case pass
+ # against a sanitiser with no allowlist at all.
+ b'<svg xmlns="http://www.w3.org/2000/svg"><foreignObject><body xmlns="http://www.w3.org/1999/xhtml">'
+ b'<img src="x" onerror="alert(1)"/></body></foreignObject></svg>',
+ "foreignObject",
+ ),
+ # Animation that writes an attribute, reaching the same place.
+ (
+ b'<svg xmlns="http://www.w3.org/2000/svg"><animate attributeName="href" values="javascript:alert(1)"/></svg>',
+ "animate",
+ ),
+ (b'<svg xmlns="http://www.w3.org/2000/svg"><set attributeName="onload" to="alert(1)"/></svg>', "set"),
+ # An external document reference.
+ (
+ b'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">'
+ b'<use xlink:href="https://attacker.example/evil.svg#x"/></svg>',
+ "attacker.example",
+ ),
+ (b'<svg xmlns="http://www.w3.org/2000/svg"><image href="https://attacker.example/p.png"/></svg>', "attacker"),
+ # Inline CSS, which can fetch and can carry expressions.
+ (b'<svg xmlns="http://www.w3.org/2000/svg"><style>@import url(https://attacker.example/x.css);</style></svg>', "import"),
+ (b'<svg xmlns="http://www.w3.org/2000/svg"><circle r="1" style="behavior:url(#x)"/></svg>', "behavior"),
+ # A paint server pointing off-document: an outbound request from
+ # wherever this renders, which for a PDF is the server.
+ (b'<svg xmlns="http://www.w3.org/2000/svg"><rect fill="url(https://attacker.example/x)"/></svg>', "attacker"),
+ (b'<svg xmlns="http://www.w3.org/2000/svg"><a href="javascript:alert(1)"><circle r="1"/></a></svg>', "javascript"),
+ ],
+ )
+ def test_the_dangerous_construct_does_not_survive(self, payload: bytes, must_not_contain: str) -> None:
+ cleaned = sanitize_svg(payload)
+ assert must_not_contain.lower() not in cleaned.svg.lower()
+ assert cleaned.modified, "nothing was reported removed, so the sanitiser did not notice this payload"
+
+ def test_a_namespaced_script_tag_does_not_slip_past_a_name_comparison(self) -> None:
+ """``{http://www.w3.org/2000/svg}script`` is not the string ``script``.
+
+ A sanitiser comparing ElementTree's tag against a bare name lets this
+ through while passing every unqualified test above.
+ """
+ payload = b'<svg xmlns="http://www.w3.org/2000/svg"><svg:script xmlns:svg="http://www.w3.org/2000/svg">alert(1)</svg:script></svg>'
+ cleaned = sanitize_svg(payload)
+ assert "alert" not in cleaned.svg
+ assert "script" not in cleaned.svg.lower()
+
+ def test_a_disallowed_elements_children_are_not_promoted(self) -> None:
+ """``<script><circle/></script>`` is not a circle somebody wanted."""
+ payload = b'<svg xmlns="http://www.w3.org/2000/svg"><script><circle r="5"/></script></svg>'
+ cleaned = sanitize_svg(payload)
+ assert "circle" not in cleaned.svg
+
+
+class TestEntityExpansionIsRefusedNotBounded:
+ def test_a_billion_laughs_document_is_refused_before_parsing(self) -> None:
+ """Refused on a byte scan, so the expansion never runs.
+
+ A size cap alone does not help: the expansion is what turns a small
+ upload into gigabytes, so the input passes the cap.
+ """
+ payload = (
+ b'<?xml version="1.0"?><!DOCTYPE lolz [<!ENTITY lol "lol">'
+ b'<!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">'
+ b'<!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">]>'
+ b'<svg xmlns="http://www.w3.org/2000/svg"><title>&lol3;</title></svg>'
+ )
+ with pytest.raises(SvgRejected, match="DTD or an entity"):
+ sanitize_svg(payload)
+
+ def test_an_external_entity_is_refused(self) -> None:
+ payload = (
+ b'<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>'
+ b'<svg xmlns="http://www.w3.org/2000/svg"><title>&xxe;</title></svg>'
+ )
+ with pytest.raises(SvgRejected, match="DTD or an entity"):
+ sanitize_svg(payload)
+
+ def test_a_bare_doctype_is_refused_even_without_entities(self) -> None:
+ """Refused rather than repaired.
+
+ A document declaring a DTD is not a logo somebody drew, and repairing
+ it would mean guessing what an untrusted author meant.
+ """
+ payload = b'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ""><svg xmlns="http://www.w3.org/2000/svg"/>'
+ with pytest.raises(SvgRejected):
+ sanitize_svg(payload)
+
+
+class TestStructuralRefusals:
+ def test_an_oversized_upload_is_refused(self) -> None:
+ with pytest.raises(SvgRejected, match="limit is"):
+ sanitize_svg(b"<svg xmlns='http://www.w3.org/2000/svg'>" + b"<!-- x -->" * MAX_SVG_BYTES + b"</svg>")
+
+ def test_an_empty_upload_is_refused(self) -> None:
+ with pytest.raises(SvgRejected, match="empty"):
+ sanitize_svg(b"")
+
+ def test_malformed_xml_is_refused(self) -> None:
+ with pytest.raises(SvgRejected, match="well-formed"):
+ sanitize_svg(b"<svg><unclosed>")
+
+ def test_a_non_svg_root_is_refused(self) -> None:
+ with pytest.raises(SvgRejected, match="not <svg>"):
+ sanitize_svg(b'<html xmlns="http://www.w3.org/2000/svg"><body/></html>')
+
+
+class TestLegitimateLogosSurvive:
+ def test_a_real_logo_keeps_its_geometry_and_palette(self) -> None:
+ """A sanitiser that removes everything is safe and useless."""
+ cleaned = sanitize_svg(BENIGN)
+ assert not cleaned.modified, f"removed {cleaned.removed_elements} / {cleaned.removed_attributes}"
+ for fragment in ("<path", "<rect", "<text", "linearGradient", "#2563EB", "M8 20 L18 30 L32 10", "Acme"):
+ assert fragment in cleaned.svg
+
+ def test_a_same_document_paint_reference_survives(self) -> None:
+ """``url(#id)`` is how a gradient is applied, and must still work."""
+ assert 'fill="url(#g1)"' in sanitize_svg(BENIGN).svg
+
+ def test_the_output_declares_its_namespace_so_it_renders_standalone(self) -> None:
+ assert "http://www.w3.org/2000/svg" in sanitize_svg(BENIGN).svg
+
+
+class TestDetection:
+ @pytest.mark.parametrize(
+ ("content_type", "raw", "expected"),
+ [
+ ("image/svg+xml", b"<svg/>", True),
+ # Declared as a raster, actually XML. This is the case that makes
+ # detection-by-header alone a hole: a caller controls the header,
+ # and skipping the sanitiser is the whole attack.
+ ("image/png", b'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>', True),
+ ("image/png", b"\x89PNG\r\n\x1a\n\x00\x00", False),
+ ("image/jpeg", b"\xff\xd8\xff\xe0", False),
+ ],
+ )
+ def test_an_svg_is_recognised_from_its_bytes_not_only_its_header(self, content_type, raw, expected) -> None:
+ assert looks_like_svg(content_type, raw) is expected
diff --git a/services/api/tests/test_usage_metering.py b/services/api/tests/test_usage_metering.py
new file mode 100644
index 000000000..860539773
--- /dev/null
+++ b/services/api/tests/test_usage_metering.py
@@ -0,0 +1,389 @@
+"""Metering has to equal the rows it claims to summarise.
+
+Gap-closure Phase 13.3 gate, and the acceptance is literal: insert a known
+number of rows, ask the meter, compare.
+
+Why the comparison is against rows and not against a fixture
+-------------------------------------------------------------
+Two console figures in this repository's history were wrong on real data
+while passing their tests, because each test compared a producer against a
+copy of itself. `cases_closed_7d` filtered an intermediate status;
+`mttr_hours` averaged a column ordinary case work never writes and published
+emptiness as a confident `0.0`. Both would have survived any test that
+asserted the function returned what the function computed.
+
+So every assertion below counts rows independently of the meter, in the test,
+and compares. The meter and the check are different queries over the same
+table, which is the only arrangement where a disagreement can show up.
+
+The second property, and the one a naive implementation gets wrong: a daily
+series summed over a range must equal one query over the whole range. Day
+boundaries are where a row gets dropped or counted twice, and neither shows
+up in a single-day test.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, date, datetime, timedelta
+
+import pytest
+import pytest_asyncio
+from app.api.v1.endpoints.usage import get_usage
+from app.db.database import Base
+from app.models.alert import Alert
+from app.models.connector import Connector
+from app.models.investigation import InvestigationRun
+from app.models.tenant import Tenant, User
+from app.services import usage_metering
+from sqlalchemy import func, select, text
+from sqlalchemy.dialects.postgresql import ARRAY, INET, 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
+
+TENANT = uuid.UUID("cccccccc-0000-0000-0000-0000000000c1")
+OTHER_TENANT = uuid.UUID("dddddddd-0000-0000-0000-0000000000d1")
+
+
+class _Caller:
+ """The authenticated principal, as the route reads it."""
+
+ def __init__(self, tenant_id: uuid.UUID) -> None:
+ self.tenant_id = tenant_id
+
+
+#: A fixed window, so the assertions do not depend on when the suite runs.
+DAY_ONE = date(2026, 3, 10)
+
+
+@compiles(JSONB, "sqlite")
+def _jsonb_sqlite(_type_, _compiler_, **_kw_):
+ return "TEXT"
+
+
+@compiles(PgUUID, "sqlite")
+def _uuid_sqlite(_type_, _compiler_, **_kw_):
+ return "CHAR(36)"
+
+
+@compiles(INET, "sqlite")
+def _inet_sqlite(_type_, _compiler_, **_kw_):
+ return "TEXT"
+
+
+@compiles(ARRAY, "sqlite")
+def _array_sqlite(_type_, _compiler_, **_kw_):
+ return "TEXT"
+
+
+@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=[Alert.__table__, User.__table__, Connector.__table__, InvestigationRun.__table__, Tenant.__table__],
+ )
+ # The two metered tables with no ORM model in this service. Created
+ # by hand with the columns the meters read, so the real SQL runs.
+ await conn.execute(
+ text(
+ "CREATE TABLE aisoc_run_costs (run_id TEXT, tenant_id TEXT, model TEXT, "
+ "total_prompt_tokens INTEGER DEFAULT 0, total_completion_tokens INTEGER DEFAULT 0, "
+ "total_cost_usd REAL DEFAULT 0, total_latency_ms REAL DEFAULT 0, call_count INTEGER DEFAULT 0, "
+ "recorded_at TIMESTAMP)"
+ )
+ )
+ await conn.execute(
+ text(
+ "CREATE TABLE aisoc_action_records (id TEXT PRIMARY KEY, tenant_id TEXT, status TEXT, "
+ "record TEXT, created_at TIMESTAMP, updated_at TIMESTAMP)"
+ )
+ )
+ yield async_sessionmaker(engine, expire_on_commit=False)
+ await engine.dispose()
+
+
+def _at(day: date, hour: int = 12) -> datetime:
+ return datetime(day.year, day.month, day.day, hour, tzinfo=UTC)
+
+
+async def _alert(db, *, tenant: uuid.UUID, when: datetime, ai: bool) -> None:
+ db.add(
+ Alert(
+ tenant_id=tenant,
+ title="t",
+ description="d",
+ severity="medium",
+ status="new",
+ created_at=when,
+ event_time=when,
+ first_seen=when,
+ last_seen=when,
+ ai_summary="model said so" if ai else None,
+ ai_score=0.5 if ai else None,
+ )
+ )
+
+
+@pytest_asyncio.fixture
+async def seeded(session_factory):
+ """A known, hand-countable corpus spanning three days and two tenants.
+
+ Deliberately includes rows at both edges of a day and rows belonging to
+ another tenant, because those are the two ways a meter over-counts.
+ """
+ async with session_factory() as db:
+ # Day one: 3 alerts, 2 of them model-triaged.
+ await _alert(db, tenant=TENANT, when=_at(DAY_ONE, 0), ai=True) # exactly midnight
+ await _alert(db, tenant=TENANT, when=_at(DAY_ONE, 13), ai=True)
+ await _alert(db, tenant=TENANT, when=_at(DAY_ONE, 23), ai=False)
+ # Day two: 2 alerts, neither model-triaged.
+ await _alert(db, tenant=TENANT, when=_at(DAY_ONE + timedelta(days=1), 9), ai=False)
+ await _alert(db, tenant=TENANT, when=_at(DAY_ONE + timedelta(days=1), 10), ai=False)
+ # Day three: 1 alert, model-triaged.
+ await _alert(db, tenant=TENANT, when=_at(DAY_ONE + timedelta(days=2), 1), ai=True)
+ # Another tenant's rows, inside the same window. Must never be counted.
+ for hour in (2, 3, 4, 5):
+ await _alert(db, tenant=OTHER_TENANT, when=_at(DAY_ONE, hour), ai=True)
+
+ db.add(
+ InvestigationRun(tenant_id=TENANT, case_id="c1", status="completed", created_at=_at(DAY_ONE, 14), started_at=_at(DAY_ONE, 14))
+ )
+ db.add(
+ InvestigationRun(
+ tenant_id=OTHER_TENANT, case_id="c2", status="completed", created_at=_at(DAY_ONE, 15), started_at=_at(DAY_ONE, 15)
+ )
+ )
+
+ for index, (tenant, tokens, cost, when) in enumerate(
+ [
+ (TENANT, 1200, 0.013, _at(DAY_ONE, 14)),
+ (TENANT, 800, 0.007, _at(DAY_ONE + timedelta(days=1), 8)),
+ (OTHER_TENANT, 99999, 9.99, _at(DAY_ONE, 14)),
+ ]
+ ):
+ await db.execute(
+ text(
+ "INSERT INTO aisoc_run_costs (run_id, tenant_id, model, total_prompt_tokens, "
+ "total_completion_tokens, total_cost_usd, recorded_at) "
+ "VALUES (:r, :t, 'm', :p, :c, :usd, :w)"
+ ),
+ {"r": f"run-{index}", "t": str(tenant), "p": tokens // 2, "c": tokens - tokens // 2, "usd": cost, "w": when},
+ )
+
+ for index, (tenant, status_value, when) in enumerate(
+ [
+ (TENANT, "executed", _at(DAY_ONE, 16)),
+ (TENANT, "pending_approval", _at(DAY_ONE, 17)),
+ (TENANT, "executed", _at(DAY_ONE + timedelta(days=2), 3)),
+ (OTHER_TENANT, "executed", _at(DAY_ONE, 16)),
+ ]
+ ):
+ await db.execute(
+ text("INSERT INTO aisoc_action_records (id, tenant_id, status, record, created_at) VALUES (:i, :t, :s, '{}', :w)"),
+ {"i": f"act-{index}", "t": str(tenant), "s": status_value, "w": when},
+ )
+
+ db.add(User(tenant_id=TENANT, email="[email protected]", username="a", hashed_password="!x", is_active=True))
+ db.add(User(tenant_id=TENANT, email="[email protected]", username="b", hashed_password="!x", is_active=False))
+ db.add(User(tenant_id=OTHER_TENANT, email="[email protected]", username="c", hashed_password="!x", is_active=True))
+ await db.commit()
+ return session_factory
+
+
+class TestMetersEqualRowCounts:
+ """Every assertion counts rows in the test, then compares."""
+
+ async def test_alerts_match_the_row_count_for_that_day(self, seeded):
+ async with seeded() as db:
+ for offset, _ in enumerate([0, 1, 2]):
+ day = DAY_ONE + timedelta(days=offset)
+ start, end = (
+ datetime(day.year, day.month, day.day, tzinfo=UTC),
+ datetime(day.year, day.month, day.day, tzinfo=UTC) + timedelta(days=1),
+ )
+ expected = await db.scalar(
+ select(func.count())
+ .select_from(Alert)
+ .where(Alert.tenant_id == TENANT, Alert.created_at >= start, Alert.created_at < end)
+ )
+ measured = await usage_metering.measure_day(db, TENANT, day)
+ assert measured.values["alerts"] == expected, f"day {day} disagreed"
+
+ async def test_triage_paths_partition_the_alerts_exactly(self, seeded):
+ """Model plus deterministic must equal the total.
+
+ A gap between them is a triage nobody is accounting for, and an
+ overlap is one being counted twice.
+ """
+ async with seeded() as db:
+ for offset in range(3):
+ values = (await usage_metering.measure_day(db, TENANT, DAY_ONE + timedelta(days=offset))).values
+ assert values["triages_model"] + values["triages_deterministic"] == values["alerts"]
+
+ async def test_another_tenants_rows_are_never_counted(self, seeded):
+ """The four rows seeded for the other tenant sit inside the window."""
+ async with seeded() as db:
+ days = await usage_metering.measure_range(db, TENANT, DAY_ONE, DAY_ONE + timedelta(days=2))
+ summed = usage_metering.totals(days)
+
+ everything = await db.scalar(select(func.count()).select_from(Alert))
+ ours = await db.scalar(select(func.count()).select_from(Alert).where(Alert.tenant_id == TENANT))
+ assert everything > ours, "the fixture no longer has another tenant's rows, so this proves nothing"
+ assert summed["alerts"] == ours
+
+ async def test_tokens_and_cost_sum_the_rows(self, seeded):
+ async with seeded() as db:
+ summed = usage_metering.totals(await usage_metering.measure_range(db, TENANT, DAY_ONE, DAY_ONE + timedelta(days=2)))
+ expected_tokens = await db.scalar(
+ text("SELECT SUM(total_prompt_tokens + total_completion_tokens) FROM aisoc_run_costs WHERE tenant_id = :t"),
+ {"t": str(TENANT)},
+ )
+ expected_cost = await db.scalar(
+ text("SELECT SUM(total_cost_usd) FROM aisoc_run_costs WHERE tenant_id = :t"), {"t": str(TENANT)}
+ )
+ assert summed["llm_tokens"] == expected_tokens
+ assert summed["llm_cost_usd"] == pytest.approx(expected_cost)
+
+ async def test_actions_split_executed_from_the_rest(self, seeded):
+ async with seeded() as db:
+ summed = usage_metering.totals(await usage_metering.measure_range(db, TENANT, DAY_ONE, DAY_ONE + timedelta(days=2)))
+ total = await db.scalar(text("SELECT count(*) FROM aisoc_action_records WHERE tenant_id = :t"), {"t": str(TENANT)})
+ executed = await db.scalar(
+ text("SELECT count(*) FROM aisoc_action_records WHERE tenant_id = :t AND status = 'executed'"),
+ {"t": str(TENANT)},
+ )
+ assert summed["actions"] == total
+ assert summed["actions_executed"] == executed
+ assert summed["actions_executed"] < summed["actions"], "the fixture no longer distinguishes the two"
+
+ async def test_seats_count_active_users_only(self, seeded):
+ async with seeded() as db:
+ point = await usage_metering.measure_point_in_time(db, TENANT)
+ expected = await db.scalar(select(func.count()).select_from(User).where(User.tenant_id == TENANT, User.is_active.is_(True)))
+ assert point["seats"] == expected
+ assert point["seats"] == 1, "one of the two seeded users is inactive"
+
+
+class TestDayBoundariesDoNotDropOrDoubleCount:
+ async def test_the_daily_series_sums_to_one_query_over_the_whole_range(self, seeded):
+ """The reconciliation the acceptance names, run against real rows."""
+ async with seeded() as db:
+ report = await usage_metering.reconcile(db, TENANT, DAY_ONE, DAY_ONE + timedelta(days=2))
+ disagreements = {key: entry for key, entry in report.items() if not entry["agrees"]}
+ assert not disagreements, f"per-day and whole-window totals disagree: {disagreements}"
+
+ async def test_a_row_at_exactly_midnight_is_counted_once(self, seeded):
+ """The fixture puts an alert at 00:00 on day one.
+
+ A closed interval counts it in both the preceding and the following
+ day, which is invisible in any single-day assertion.
+ """
+ async with seeded() as db:
+ before = (await usage_metering.measure_day(db, TENANT, DAY_ONE - timedelta(days=1))).values["alerts"]
+ on_day = (await usage_metering.measure_day(db, TENANT, DAY_ONE)).values["alerts"]
+ assert before == 0
+ assert on_day == 3
+
+ async def test_an_empty_day_reports_zero_rather_than_being_absent(self, seeded):
+ """A missing day reads as a gap in a chart; zero reads as a fact."""
+ async with seeded() as db:
+ days = await usage_metering.measure_range(db, TENANT, DAY_ONE - timedelta(days=2), DAY_ONE)
+ assert [d.day for d in days] == [DAY_ONE - timedelta(days=2), DAY_ONE - timedelta(days=1), DAY_ONE]
+ assert days[0].values["alerts"] == 0
+
+
+class TestHonesty:
+ def test_an_unmeasurable_meter_is_named_with_a_reason_not_reported_as_zero(self):
+ """Zero is a measurement.
+
+ A reader seeing `events_ingested: 0` concludes no events arrived,
+ rather than that nothing looked.
+ """
+ assert "events_ingested" in usage_metering.UNMEASURED
+ assert usage_metering.UNMEASURED["events_ingested"]
+ assert "events_ingested" not in usage_metering.METERS_BY_KEY
+
+ def test_no_meter_carries_pricing(self):
+ """13.3 says metering, not billing.
+
+ `llm_cost_usd` is what a provider charged, which is a measurement.
+ Anything named for a rate, a plan or a price is a commercial decision
+ and does not belong in the code that answers what happened.
+ """
+ forbidden = ("price", "rate", "invoice", "bill", "tier_cost", "unit_cost", "plan_cost")
+ for meter in (*usage_metering.METERS, *usage_metering.POINT_IN_TIME_METERS):
+ haystack = f"{meter.key} {meter.label} {meter.sql}".lower()
+ for token in forbidden:
+ assert token not in haystack, f"{meter.key} looks like pricing logic"
+
+ def test_every_meter_binds_the_tenant_as_a_parameter(self):
+ """Never formatted into the string.
+
+ The same rule the entitlement limits follow, and the reason the lake
+ rewriter was made to fail closed.
+ """
+ for meter in (*usage_metering.METERS, *usage_metering.POINT_IN_TIME_METERS):
+ assert ":tenant_id" in meter.sql or ":tenant_text" in meter.sql, meter.key
+ assert "format(" not in meter.sql
+ assert "%s" not in meter.sql
+
+
+class TestCsvExport:
+ async def test_the_csv_carries_totals_that_match_the_rows(self, seeded):
+ async with seeded() as db:
+ days = await usage_metering.measure_range(db, TENANT, DAY_ONE, DAY_ONE + timedelta(days=2))
+ point = await usage_metering.measure_point_in_time(db, TENANT)
+ expected = await db.scalar(select(func.count()).select_from(Alert).where(Alert.tenant_id == TENANT))
+
+ body = usage_metering.to_csv(tenant_id=TENANT, org_name="Acme MSSP", days=days, point_in_time=point)
+ lines = [line for line in body.splitlines() if line]
+ total_row = next(line for line in lines if line.startswith("total,"))
+ assert int(total_row.split(",")[1]) == expected
+
+ async def test_the_csv_names_what_was_not_measured(self, seeded):
+ async with seeded() as db:
+ days = await usage_metering.measure_range(db, TENANT, DAY_ONE, DAY_ONE)
+ point = await usage_metering.measure_point_in_time(db, TENANT)
+ body = usage_metering.to_csv(tenant_id=TENANT, org_name=None, days=days, point_in_time=point)
+ assert "not measured: events_ingested" in body
+ # And it says whose numbers these are. A bare grid of figures in a
+ # downloads folder cannot answer that.
+ assert str(TENANT) in body
+
+ def test_month_bounds_cover_the_whole_month_including_february(self):
+ assert usage_metering.month_bounds(2026, 2) == (date(2026, 2, 1), date(2026, 2, 28))
+ assert usage_metering.month_bounds(2024, 2) == (date(2024, 2, 1), date(2024, 2, 29))
+ assert usage_metering.month_bounds(2026, 12) == (date(2026, 12, 1), date(2026, 12, 31))
+ with pytest.raises(ValueError, match="1-12"):
+ usage_metering.month_bounds(2026, 13)
+
+
+class TestTheRouteAnswers:
+ """The route itself, not just the service functions underneath it.
+
+ Every test above this class passed while `GET /usage` raised `TypeError`
+ on every request, because the handler called `headroom_for_tenant` without
+ its `tenant_limits` argument and nothing here had ever called the handler.
+ A service-layer suite cannot see that; only calling the route can.
+ """
+
+ async def test_entitlements_reflect_the_tenant_override_not_the_plan_default(self, seeded):
+ """Asserts the override is *honoured*, not merely that the call returns.
+
+ Passing `None` for `tenant_limits` would satisfy the signature and stop
+ the crash while silently reporting plan headroom to a tenant whose
+ ceiling was deliberately raised, so the assertion is on the number.
+ """
+ raised_ceiling = 4242
+ async with seeded() as db:
+ db.add(Tenant(id=TENANT, name="t", slug="t", limits={"seats": raised_ceiling}))
+ await db.commit()
+
+ async with seeded() as db:
+ body = await get_usage(db, _Caller(TENANT))
+
+ seats = next(row for row in body["entitlements"] if row["key"] == "seats")
+ assert seats["limit"] == raised_ceiling