Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(white-label): brand every surface the doc claims, narrow the two it cannot (#1194)
Beenu Aroraa0cce8860004
diff --git a/GAP_CLOSURE_PROGRESS.md b/GAP_CLOSURE_PROGRESS.mdindex b06292496..ebdaa81cb 100644--- a/GAP_CLOSURE_PROGRESS.md+++ b/GAP_CLOSURE_PROGRESS.md@@ -487,7 +487,7 @@ 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 `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.+- [~] **13.2 MSSP white-label** per organization. Console, digest, case close-out summary, replay report, investigation PDF and email approvals 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/`). ChatOps is the one surface of the five that stays unbranded, as a scope decision with a recorded reason rather than as pending work. 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.@@ -1547,24 +1547,45 @@ a revocation exists, so credentials minted before this change fail closed.Both the access-token path and the refresh path check it. The refresh pathmatters 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+### D29. White-label reaches four of the five surfaces, and the fifth is a scope decision13.2 lists five surfaces: console, PDF reports, digests, email approvals andChatOps. 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.+organization's PDF report and console show its branding", and those two were+implemented and gated end to end first.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.+which is what the PDF contains. The case close-out summary, the replay+evaluation report and the investigation summary PDF followed, each with an+unbranded negative control.++**The record here was wrong, and the way it was wrong is the lesson.** This+entry said email approvals and ChatOps "resolve the same `sender_name` from+the same resolver", missing only an end-to-end test. Neither half was true.+`sender_name` had no reader anywhere outside the resolver that produced it;+`send_approval_email` had no caller at all; and the tokens it would have+minted carried no approver, so the consuming endpoint — which refuses a token+that names nobody — would have rejected every link in a mail that did get+sent. Three dead things in a row, each of which had a passing test, and the+tracker credited the field for resolving. A resolved value is not a rendered+one, and "covered by no end-to-end test" is a much weaker statement than+"read by nothing", so writing the weaker one hid the stronger.++Email approvals are now branded and wired: `POST /api/v1/approvals` is the+producer, one message per recipient with that recipient signed in as the+approver, and `sender_name` is the `From` display name — which is what the+field is for, and the first reader it has ever had.++ChatOps stays unbranded as a **scope decision with a reason**, recorded in+`apps/docs/docs/operations/white-label.md` and in the claim row rather than+left to look pending. The prompt is posted by `services/actions`, and the+bots are `services/slack-bot` and `services/teams-bot`; none can reach the+branding store, which sits behind the API with the tenant session and the+credential vault. The tempting shortcut is a deployment-wide product name in+an environment variable, and it is worse than leaving it alone: branding is+per operator organisation, so one baked-in name is wrong for every+organisation on the deployment except one while reading as configured.**The design decision worth keeping:** asset bytes live in Postgres and areserved from this deployment. A logo referenced by URL is an outbound requestdiff --git a/apps/docs/docs/operations/white-label.md b/apps/docs/docs/operations/white-label.mdindex fb09b182d..b0bd3e4ed 100644--- a/apps/docs/docs/operations/white-label.md+++ b/apps/docs/docs/operations/white-label.md@@ -14,14 +14,57 @@ organisation's portfolio, plus the organisation's own staff console.| Surface | What changes ||---|---|-| Console | Product name, logo, accent colour |-| Executive digest (HTML and PDF) | Product name, logo, accent colour, footer, support link |+| Console sidebar | Product name, logo, primary colour on the wordmark, accent colour on the logo frame |+| Console browser tab | The product name in the page title |+| Executive digest (HTML and PDF) | Product name, logo, primary colour, accent colour, footer, support link |+| Case close-out summary (HTML, print to PDF) | Product name, logo, primary colour, accent colour, footer, support link |+| Replay evaluation report (PDF) | Product name, logo, primary colour, accent colour, footer, support link |+| Investigation summary (PDF) | Product name, primary colour, footer, support contact |+| Email approvals | Product name in the subject and body, `sender_name` as the From display name, primary and accent colours, footer, support contact || Usage CSV export | The organisation named in the header block |Branding resolves field by field. An organisation that sets a product nameand no colours renders its name against the platform palette, rather thanlosing the one field it configured.+Two details are deliberate rather than oversights.++The investigation summary PDF carries no logo. It is drawn by `reportlab`+rather than rendered from HTML, so there is nowhere to place an image without+writing the asset to disk first; the product name, palette, footer and+support contact are all present.++The approve and deny buttons in an approval email stay green and red. Those+two colours say "this one contains a host" and "this one does not", and a+palette that could swap them would be a safety problem rather than a+branding feature.++## Email approvals++The signed email fallback is off until it has somewhere to send to. Set both:++```bash+AISOC_EMAIL_APPROVAL_SECRET=<a long random string>+MAILGUN_API_KEY=<key>+MAILGUN_DOMAIN=mail.acme.example+```++Every address also needs an entry in `AISOC_CHATOPS_APPROVERS` under `email`.+The recipient is signed into the approval token and forwarded as the approver,+so an address that is not mapped is refused when somebody clicks rather than+when the mail is sent.++Each recipient receives their own message with their own pair of links. One+shared link would record every click as the same identity, and separation of+duties cannot be evaluated against a distribution list.++The `From` address stays on your own Mailgun sending domain whatever+`sender_name` says. Only the display name a recipient reads is+white-labelled: a `From` address on a domain the deployment does not control+fails SPF and DKIM, which is how approval mail lands in a spam folder on the+day it matters.+## Setting it```bash@@ -120,10 +163,22 @@ curl -X DELETE https://<your-aisoc-host>/api/v1/branding/assets/logo \Clearing every field on `PUT /api/v1/branding` returns each surface to theplatform 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.+## What is not branded++Two surfaces are not, and both are a limit rather than an omission.++**Slack and Teams messages carry the platform name.** The interactive+approval prompt is posted by `services/actions`, and the bot services are+`services/slack-bot` and `services/teams-bot`. None of the three can read the+branding store, which lives behind the API alongside the tenant session and+the credential vault. Reading it from a deployment-wide environment variable+would be worse than leaving it: branding is set per operator organisation, so+one name baked into the process would be wrong for every organisation on the+deployment except one, while looking configured.++**The sign-in page carries the platform name.** `GET /api/v1/branding`+resolves the organisation from the caller's credential, and on the sign-in+page there is no credential yet. Nothing maps a hostname to an organisation+either — `organizations` has a slug and a name and no domain — so the page+has no way to work out whose product it is about to show. Branding it needs a+hostname-to-organisation mapping first, which does not exist today.diff --git a/apps/web/src/components/layout/AppShell.tsx b/apps/web/src/components/layout/AppShell.tsxindex 2645143f3..37fa6d132 100644--- a/apps/web/src/components/layout/AppShell.tsx+++ b/apps/web/src/components/layout/AppShell.tsx@@ -1,6 +1,7 @@'use client';import { SWRConfig } from 'swr';+import { BrandedDocumentTitle } from './BrandedDocumentTitle';import { Sidebar } from './Sidebar';import { TopBar } from './TopBar';import { CommandPalette } from './CommandPalette';@@ -71,6 +72,9 @@ export function AppShell({ children, demoMode }: AppShellProps) {and cost a frame of layout shift on every demo page load.*/}<DemoBanner demoMode={demo} />+ {/* Renders nothing; it corrects the tab title a build-time+ `metadata` export could not know the tenant for. */}+ <BrandedDocumentTitle /><Sidebar /><div className="md:ml-60"><TopBar demoOffset={demo} />diff --git a/apps/web/src/components/layout/BrandedDocumentTitle.test.tsx b/apps/web/src/components/layout/BrandedDocumentTitle.test.tsxnew file mode 100644index 000000000..e42628d1f--- /dev/null+++ b/apps/web/src/components/layout/BrandedDocumentTitle.test.tsx@@ -0,0 +1,99 @@+/**+ * The browser tab is a surface, and it carried the platform name.+ *+ * Next resolves `metadata` at build time, with no request and therefore no+ * tenant, so an analyst at a white-labelled provider read the platform's+ * product name in every tab and in every bookmark they made. The correction+ * can only happen in the browser.+ *+ * These cases mount the real console shell inside the real theme provider —+ * the same nesting `app/layout.tsx` and `app/(app)/layout.tsx` produce —+ * rather than the title component on its own. A component that works and is+ * mounted nowhere is the failure this repository keeps finding, and rendering+ * it directly could not tell the two apart.+ *+ * Each render gets its own SWR cache. The branding hook keys on the constant+ * string `branding`, so a second render in one file would resolve from the+ * first one's cache and the second case would be testing the cache.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { render, waitFor } from '@testing-library/react';+import { SWRConfig } from 'swr';++vi.mock('next/navigation', () => ({+ usePathname: () => '/dashboard',+ useRouter: () => ({ push: () => {} }),+ useSearchParams: () => new URLSearchParams(),+}));++vi.mock('next/link', () => ({+ default: ({ children, href }: { children: React.ReactNode; href: string }) => <a href={href}>{children}</a>,+}));++const { state } = vi.hoisted(() => ({+ state: {+ response: {+ product_name: 'AiSOC',+ primary_color: '#2563EB',+ accent_color: '#7C3AED',+ support_email: null,+ support_url: null,+ sender_name: 'AiSOC',+ footer_text: 'AiSOC',+ logo_url: null,+ org_id: null,+ is_white_labelled: false,+ },+ },+}));++vi.mock('@/lib/api', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/lib/api')>();+ return { ...actual, brandingApi: { get: async () => state.response, logo: actual.brandingApi.logo } };+});++import { AppShell } from './AppShell';+import { ThemeProvider } from '@/components/theme/ThemeProvider';++function mountConsole() {+ return render(+ <ThemeProvider>+ <SWRConfig value={{ provider: () => new Map() }}>+ <AppShell demoMode={false}>dashboard</AppShell>+ </SWRConfig>+ </ThemeProvider>,+ );+}++beforeEach(() => {+ vi.stubGlobal('fetch', async () => new Response('{}', { status: 200 }));+});++afterEach(() => {+ document.title = '';+ vi.unstubAllGlobals();+});++describe('the console tab title', () => {+ it("replaces the platform name with the organisation's", async () => {+ state.response = { ...state.response, product_name: 'Acme Shield', is_white_labelled: true };+ document.title = 'Honeytokens | AiSOC';++ mountConsole();++ // The section the route named survives; only the product does not. A+ // component that overwrote the whole title would lose the page.+ await waitFor(() => expect(document.title).toBe('Honeytokens | Acme Shield'));+ });++ it('leaves an unbranded deployment alone', async () => {+ state.response = { ...state.response, product_name: 'AiSOC', is_white_labelled: false };+ document.title = 'Honeytokens | AiSOC';++ mountConsole();++ // The negative control. Rewriting unconditionally would be invisible+ // today and a silent corruption the moment the platform default moves.+ await waitFor(() => expect(document.title).toBe('Honeytokens | AiSOC'));+ });+});diff --git a/apps/web/src/components/layout/BrandedDocumentTitle.tsx b/apps/web/src/components/layout/BrandedDocumentTitle.tsxnew file mode 100644index 000000000..223043960--- /dev/null+++ b/apps/web/src/components/layout/BrandedDocumentTitle.tsx@@ -0,0 +1,33 @@+'use client';++import { useEffect } from 'react';+import { usePathname } from 'next/navigation';++import { DEFAULT_BRANDING, useBranding } from '@/hooks/useBranding';++/**+ * Put the organisation's product name in the browser tab.+ *+ * Next resolves the `metadata` export at build time, in a process with no+ * request and therefore no tenant, so the tab title is a compiled literal and+ * the browser is the only place it can be corrected. Rewriting here rather+ * than replacing outright keeps whatever a route contributed — a page that+ * renders `Honeytokens | AiSOC` becomes `Honeytokens | Acme Shield` rather+ * than losing the section it names.+ *+ * Re-runs on navigation because Next sets the title again on each route, and+ * a rewrite that ran once would be undone by the next page the analyst opens.+ */+export function BrandedDocumentTitle() {+ const { branding } = useBranding();+ const pathname = usePathname();++ useEffect(() => {+ if (!branding.is_white_labelled) return;+ const platform = DEFAULT_BRANDING.product_name;+ if (!document.title.includes(platform)) return;+ document.title = document.title.split(platform).join(branding.product_name);+ }, [branding.is_white_labelled, branding.product_name, pathname]);++ return null;+}diff --git a/apps/web/src/components/layout/Sidebar.tsx b/apps/web/src/components/layout/Sidebar.tsxindex a2f375d26..a0bc9194c 100644--- a/apps/web/src/components/layout/Sidebar.tsx+++ b/apps/web/src/components/layout/Sidebar.tsx@@ -6,7 +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';+import { useBrandLogo, useBranding } from '@/hooks/useBranding';import { authApi } from '@/lib/api';const APP_VERSION = packageJson.version;@@ -373,9 +373,18 @@ export function Sidebar() {// 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 logoSrc = useBrandLogo(branding.logo_url);const pathname = usePathname();const [mobileOpen, setMobileOpen] = useState(false);+ // Only a white-labelled organisation overrides the chrome. An unbranded+ // deployment keeps the compiled Tailwind palette, so the platform console+ // is byte-for-byte what it was rather than the same colours restated as+ // inline styles.+ const brandFrameStyle = branding.is_white_labelled+ ? { borderColor: branding.accent_color, backgroundColor: `${branding.accent_color}33` }+ : undefined;+// Users management is admin-only. The nav item is hidden entirely for// viewer/infosec — the server refuses the page's API calls anyway, but// showing a door that only opens for someone else is a lie in chrome.@@ -422,13 +431,16 @@ 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 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.+ <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"+ style={brandFrameStyle}+ >+ {logoSrc ? (+ // An object URL over bytes this deployment served. The raw path+ // cannot go here: the asset route authenticates a bearer token+ // and an `<img>` can only carry a cookie.// eslint-disable-next-line @next/next/no-img-element- <img src={branding.logo_url} alt="" className="w-full h-full object-contain" />+ <img src={logoSrc} alt="" className="w-full h-full object-contain" />) : (<span className="text-brand-400"><ShieldIcon />@@ -437,7 +449,9 @@ export function Sidebar() {</div><div>{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" style={{ color: branding.primary_color }}>+ {branding.product_name}+ </span>) : (<><span className="text-fg-primary font-bold text-base tracking-tight">Ai</span>diff --git a/apps/web/src/components/layout/SidebarBranding.test.tsx b/apps/web/src/components/layout/SidebarBranding.test.tsxindex f22f9db52..12b8d060d 100644--- a/apps/web/src/components/layout/SidebarBranding.test.tsx+++ b/apps/web/src/components/layout/SidebarBranding.test.tsx@@ -10,7 +10,7 @@* 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { render, screen } from '@testing-library/react';vi.mock('next/navigation', () => ({@@ -51,18 +51,48 @@ vi.mock('@/lib/api', async (importOriginal) => {// 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 },+ //+ // `logo` is the real implementation. It is the function that attaches the+ // credential, and stubbing it would move the thing under test outside the+ // test — which is how the sidebar shipped an `<img src>` the API answers+ // 401 to while this file passed.+ brandingApi: { get: async () => brandedResponse, logo: actual.brandingApi.logo },};});import { Sidebar } from './Sidebar';+const LOGO_OBJECT_URL = 'blob:http://localhost/brand-logo';++/** Every request the component made, in order. */+let requests: Array<{ url: string; headers: Record<string, string> }>;++beforeEach(() => {+ requests = [];+ vi.stubGlobal('fetch', async (url: string, init?: RequestInit) => {+ requests.push({ url: String(url), headers: (init?.headers ?? {}) as Record<string, string> });+ return new Response(new Blob(['<svg/>'], { type: 'image/svg+xml' }), { status: 200 });+ });+ // jsdom implements neither half of the object-URL API. Browser plumbing,+ // not ours — stubbed so the component's own code path still runs.+ vi.stubGlobal('URL', Object.assign(URL, {+ createObjectURL: () => LOGO_OBJECT_URL,+ revokeObjectURL: () => undefined,+ }));+ window.localStorage.setItem('aisoc.responder.accessToken', 'a-session-token');+});++afterEach(() => {+ window.localStorage.clear();+ vi.unstubAllGlobals();+});+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 () => {+ it("shows a white-labelled organisation's name, palette and logo, and drops the platform wordmark", async () => {const { container } = render(<Sidebar />);expect(await screen.findByText('Acme Shield')).toBeInTheDocument();@@ -71,12 +101,38 @@ describe('Sidebar branding', () => {// 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);+ // Two chained async hops, not one: branding resolves, and only then does+ // the component fetch the asset with its credential and turn the blob+ // into an object URL. `vi.waitFor` defaults to a second, which is enough+ // here and was not on a loaded CI runner — this timed out on GitHub's+ // runners while passing locally every time. The wait is real rather than+ // a race being papered over, so it gets the headroom explicitly.+ await vi.waitFor(+ () => {+ expect(container.querySelector('img')).not.toBeNull();+ },+ { timeout: 10_000 },+ );+ const logo = container.querySelector('img') as HTMLImageElement;++ // The resolved palette reaches the chrome. `accent_color` was read by+ // nothing in the tree while the documentation listed it as branded.+ expect(screen.getByText('Acme Shield')).toHaveStyle({ color: '#123456' });+ expect(logo.parentElement).toHaveStyle({ borderColor: '#654321' });++ // The defect, stated as an assertion: the raw asset path must never be+ // the `src`. That route authenticates a bearer token, and an `<img>` can+ // only send a cookie — so this is what 401'd on every real deployment.+ const src = logo.getAttribute('src') ?? '';+ expect(src).toBe(LOGO_OBJECT_URL);+ expect(src.startsWith('/api/v1/branding/assets/')).toBe(false);// 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?:\/\//);++ // And the fetch that replaced it carried the credential.+ const assetRequest = requests.find((request) => request.url.includes('/branding/assets/'));+ expect(assetRequest).toBeDefined();+ expect(assetRequest?.headers.Authorization).toBe('Bearer a-session-token');});});diff --git a/apps/web/src/hooks/useBranding.ts b/apps/web/src/hooks/useBranding.tsindex ab0af4dfa..9622e9a82 100644--- a/apps/web/src/hooks/useBranding.ts+++ b/apps/web/src/hooks/useBranding.ts@@ -1,5 +1,6 @@'use client';+import { useEffect, useState } from 'react';import useSWR from 'swr';import { type Branding, brandingApi } from '@/lib/api';@@ -36,3 +37,50 @@ export function useBranding(): { branding: Branding; isLoading: boolean } {return { branding: data ?? DEFAULT_BRANDING, isLoading };}++/**+ * A displayable source for the brand logo, or `null`.+ *+ * `branding.logo_url` is a path on this deployment and the route behind it+ * authenticates a bearer token. An `<img src>` pointing at it sends cookies+ * and nothing else, so the image came back 401 and the sidebar rendered a+ * broken logo on every deployment that was not running the development auth+ * shim. The bytes are fetched with the credential and handed to the DOM as+ * an object URL.+ *+ * `null` on failure, which every renderer already treats as "use the+ * wordmark" — a missing logo is a layout this project ships.+ */+export function useBrandLogo(logoUrl: string | null): string | null {+ const [objectUrl, setObjectUrl] = useState<string | null>(null);++ useEffect(() => {+ if (!logoUrl) {+ setObjectUrl(null);+ return;+ }++ let cancelled = false;+ let created: string | null = null;++ brandingApi+ .logo(logoUrl)+ .then((blob) => {+ if (cancelled) return;+ created = URL.createObjectURL(blob);+ setObjectUrl(created);+ })+ .catch(() => {+ if (!cancelled) setObjectUrl(null);+ });++ return () => {+ cancelled = true;+ // An object URL pins its blob in memory until it is revoked, and the+ // shell remounts on every sign-in.+ if (created) URL.revokeObjectURL(created);+ };+ }, [logoUrl]);++ return objectUrl;+}diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex a25f7c91e..468b251e4 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -661,6 +661,28 @@ export const brandingApi = {async get(): Promise<Branding> {return request<Branding>('/api/v1/branding');},++ /**+ * The logo bytes, fetched with the caller's credential.+ *+ * `logo_url` cannot be handed to an `<img src>`. The route authenticates a+ * bearer token, and the only credential a browser attaches to an image+ * request is a cookie — so the sidebar logo answered 401 on every+ * deployment not running the development auth shim, which is every+ * deployment a customer has. Fetched here and handed to the DOM as an+ * object URL instead.+ */+ async logo(path: string): Promise<Blob> {+ const headers = apiHeaders();+ // A GET for image bytes; the JSON content type `apiHeaders` sets by+ // default describes a body this request does not have.+ delete headers['Content-Type'];+ const response = await fetch(`${API_BASE}${path}`, { headers });+ if (!response.ok) {+ throw new ApiError(`branding logo request failed`, response.status, '');+ }+ return response.blob();+ },};export interface RetroHuntSettings {diff --git a/docs/audit/REPOSITORY_REALITY.md b/docs/audit/REPOSITORY_REALITY.mdindex 9ee4057c8..170d96d54 100644--- a/docs/audit/REPOSITORY_REALITY.md+++ b/docs/audit/REPOSITORY_REALITY.md@@ -208,13 +208,30 @@ 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.+**White-label — WORKING on four of five surfaces, and the fifth is out of+scope rather than pending.** The console, the executive digest in HTML and+PDF, the case close-out summary, the replay evaluation report, the+investigation summary PDF and the signed email approval all carry a+white-labelled organisation's product name, palette and — where the renderer+has somewhere to put one — its logo, each asserted in CI against an unbranded+negative control.++The earlier record here said email approvals and ChatOps "resolve the same+`sender_name` from the same resolver". That was not true of either:+`sender_name` had no reader anywhere in the tree outside the resolver that+produced it, and `send_approval_email` had no caller at all, so the signed+fallback the documentation names for "Slack and Teams are unreachable"+produced nothing. Both are closed; the sentence is recorded because a tracker+that credits a field for resolving is the failure this audit exists to catch,+and it had.++ChatOps stays unbranded on purpose. The prompt is posted by+`services/actions` and by the two bot services, none of which can read the+branding store, and a deployment-wide product name would be wrong for every+organisation on the deployment but one. The sign-in page is unbranded for a+different reason: branding resolves from the caller's credential, and there is+none yet. Both are stated as limits in+`apps/docs/docs/operations/white-label.md` rather than implied to be pending.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 thediff --git a/services/api/app/api/v1/endpoints/approvals.py b/services/api/app/api/v1/endpoints/approvals.pyindex 8f66bb18d..4ca15039c 100644--- a/services/api/app/api/v1/endpoints/approvals.py+++ b/services/api/app/api/v1/endpoints/approvals.py@@ -44,6 +44,7 @@ from app.db.rls import TenantDBSessionfrom app.models.responder import AgentApprovalfrom app.services.actions_client import ActionsServiceError, decide_action, submit_actionfrom app.services.approval_delivery import deliver_approval+from app.services.branding.resolver import resolve_brandinglogger = logging.getLogger(__name__)@@ -214,7 +215,13 @@ async def create_approval(# for somebody to open the console and notice it. The fan-out never# raises: the row is already durable, and a channel that is down must# leave a record saying so rather than take the approval with it.- delivery = await deliver_approval(row)+ # Resolved here because this is the only layer holding both the session+ # and the authenticated tenant. The fan-out took no branding at all when+ # the three channels were unified, so every approval mail rendered the+ # platform palette no matter what the operator had configured --+ # `send_approval_email` has accepted a `branding` argument throughout and+ # nothing passed one.+ delivery = await deliver_approval(row, await resolve_branding(db, user.tenant_id))row.action = {**(row.action or {}), "delivery": delivery.as_dict()}await db.commit()await db.refresh(row)diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.pyindex bfe7aa120..fb57e53c4 100644--- a/services/api/app/api/v1/endpoints/cases.py+++ b/services/api/app/api/v1/endpoints/cases.py@@ -52,6 +52,7 @@ from app.api.v1.deps import AuthUser, DBSession, require_permissionfrom app.core.logging import safe_log_valuefrom app.services import case_orchestration, case_status, evidence_custodyfrom app.services.audit import emit_audit+from app.services.branding.resolver import resolve_brandingfrom app.services.case_fanout import (FanoutResult,fanout_create_case,@@ -1913,7 +1914,11 @@ async def case_auto_summary(raise HTTPException(status_code=404, detail="Case not found.")if format == "html":- rendered = render_case_summary_html(summary)+ # The logo is inlined because this document is saved as a PDF and+ # archived. A referenced asset makes the archived copy depend on the+ # deployment still serving that URL years later.+ branding = await resolve_branding(db, user.tenant_id, inline_logo=True)+ rendered = render_case_summary_html(summary, branding)case_label = summary.case.case_number or str(summary.case.case_id)[:8]filename = _safe_filename_segment(f"case-{case_label}-summary") + ".html"return HTMLResponse(diff --git a/services/api/app/api/v1/endpoints/evaluations.py b/services/api/app/api/v1/endpoints/evaluations.pyindex 20f94460e..4d9303bc5 100644--- a/services/api/app/api/v1/endpoints/evaluations.py+++ b/services/api/app/api/v1/endpoints/evaluations.py@@ -43,6 +43,7 @@ from app._vendor.aisoc_benchmark.replay import MIN_MALICIOUS_FOR_HEADLINEfrom app.api.v1.deps import AuthUser, DBSessionfrom app.db.database import AsyncSessionLocalfrom app.models.connector import Connector+from app.services.branding.resolver import resolve_brandingfrom app.services.replay_evaluation import report as report_exportfrom app.services.replay_evaluation import storefrom app.services.replay_evaluation.job import (@@ -396,7 +397,10 @@ async def export_replay()try:- pdf = report_export.render_pdf(markdown)+ # Inlined, because WeasyPrint renders server-side: a referenced logo+ # would be an outbound request made by this service to an address a+ # customer administrator supplied.+ pdf = report_export.render_pdf(markdown, await resolve_branding(db, user.tenant_id, inline_logo=True))except report_export.PdfUnavailableError as exc:# 503 rather than 500: the report exists and the other two formats# work, so this is a missing capability on this deployment ratherdiff --git a/services/api/app/api/v1/endpoints/investigations.py b/services/api/app/api/v1/endpoints/investigations.pyindex 1e991129a..4f4da2ed1 100644--- a/services/api/app/api/v1/endpoints/investigations.py+++ b/services/api/app/api/v1/endpoints/investigations.py@@ -32,6 +32,7 @@ import ioimport textwrapimport uuidfrom datetime import UTC, datetime+from html import escapefrom typing import Annotatedfrom fastapi import APIRouter, Depends, HTTPException, Query, Response, status@@ -48,6 +49,7 @@ from app.models.investigation import (InvestigationEvent,InvestigationRun,)+from app.services.branding.resolver import DEFAULT_BRANDING, Branding, resolve_brandingfrom app.services.evidence_bundle import build_bundle, bundle_filename, serialize_bundlerouter = APIRouter(prefix="/investigations", tags=["investigations"])@@ -1038,7 +1040,7 @@ async def export_summary_pdf(detail="No summary artifact found. POST /close first to generate one.",)- pdf_bytes = _render_pdf(art.content or "", str(run_id))+ pdf_bytes = _render_pdf(art.content or "", str(run_id), await resolve_branding(db, current_user.tenant_id))filename = f"investigation-{run_id}.pdf"return StreamingResponse(io.BytesIO(pdf_bytes),@@ -1047,13 +1049,21 @@ async def export_summary_pdf()-def _render_pdf(markdown_text: str, run_id: str) -> bytes:+def _render_pdf(markdown_text: str, run_id: str, branding: Branding | None = None) -> bytes:"""Render Markdown text to a minimal PDF using reportlab.Falls back to a plain-text PDF if reportlab is not installed so theendpoint never 500s in environments that haven't installed the optionaldependency.++ The brand lines are drawn rather than referenced: reportlab has no HTML+ model, so there is nowhere to put a logo without an image file on disk.+ A managed customer reading this export sees their provider's name and+ support contact, which is the part of white-label that matters on a+ document forwarded outside the SOC."""+ brand = branding or DEFAULT_BRANDING+ support = brand.support_url or brand.support_emailtry:from reportlab.lib.pagesizes import A4 # type: ignore[import-untyped]from reportlab.lib.styles import getSampleStyleSheet # type: ignore[import-untyped]@@ -1075,6 +1085,16 @@ def _render_pdf(markdown_text: str, run_id: str) -> bytes:)styles = getSampleStyleSheet()story = []+ # reportlab's `Paragraph` parses a mini-markup, so an operator-supplied+ # product name containing `<` would either break the parse or inject+ # into it. Escaped for the same reason every other renderer escapes it.+ story.append(+ Paragraph(+ f"<font size='8' color='{brand.primary_color}'>{escape(brand.product_name).upper()}</font>",+ styles["Normal"],+ )+ )+ story.append(Spacer(1, 0.3 * cm))for line in markdown_text.splitlines():stripped = line.strip()@@ -1096,13 +1116,19 @@ def _render_pdf(markdown_text: str, run_id: str) -> bytes:else:story.append(Spacer(1, 0.2 * cm))+ story.append(Spacer(1, 0.6 * cm))+ footer = escape(brand.footer_text) + (f"<br/>Support: {escape(support)}" if support else "")+ story.append(Paragraph(f"<font size='7' color='#94a3b8'>{footer}</font>", styles["Normal"]))+doc.build(story)return buf.getvalue()except ImportError:- # reportlab not installed — emit a plain-text PDF-like fallback+ # reportlab not installed — emit a plain-text PDF-like fallback. The+ # brand lines are repeated here so the two paths do not disagree about+ # whose document this is.header = b"%PDF-1.4\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"- body = markdown_text.encode("utf-8", errors="replace")+ body = f"{brand.product_name}\n\n{markdown_text}\n\n{brand.footer_text}\n".encode(errors="replace")return header + bodydiff --git a/services/api/app/services/approval_delivery.py b/services/api/app/services/approval_delivery.pyindex 0035825f5..120903319 100644--- a/services/api/app/services/approval_delivery.py+++ b/services/api/app/services/approval_delivery.py@@ -41,6 +41,7 @@ from typing import Anyimport httpximport structlog+from app.services.branding.resolver import Brandingfrom app.services.email_approval import EmailApprovalError, send_approval_emailfrom app.services.smtp_delivery import SmtpApprovalMailer@@ -85,10 +86,33 @@ def _approval_recipients(row: Any) -> list[str]:return [str(r).strip() for r in recipients if str(r).strip()]-async def _deliver_email(row: Any, report: DeliveryReport) -> None:+def _build_mailer() -> Any:+ """The transport this module sends through.++ A named seam rather than a bare constructor in the delivery path, so a+ test can substitute a recorder without an SMTP relay. The indirection+ exists for that reason alone; there is one implementation.+ """+ return SmtpApprovalMailer()+++async def _deliver_email(row: Any, report: DeliveryReport, branding: Branding | None = None) -> None:secret = os.getenv("AISOC_APPROVAL_TOKEN_SECRET", "").strip()recipients = _approval_recipients(row)- mailer = SmtpApprovalMailer()++ # Constructing the transport and asking whether it is configured are+ # both inside the guard, because this function documents that it never+ # raises and neither of those was covered by the try below. A transport+ # that could not answer `configured` therefore propagated out of a+ # best-effort notification and 500'd the approval that had already been+ # persisted -- failing the request for the one reason this path exists+ # to tolerate.+ try:+ mailer = _build_mailer()+ configured = bool(mailer.configured)+ except Exception as exc: # noqa: BLE001 — a transport that cannot be built is a skip, not an outage+ report.record("email", delivered=False, status="failed", detail=f"the mail transport could not be built: {exc}")+ returnif not recipients:report.record("email", delivered=False, status="skipped", detail="the approval names no approver_emails")@@ -99,7 +123,7 @@ async def _deliver_email(row: Any, report: DeliveryReport) -> None:# worse than not sending it.report.record("email", delivered=False, status="skipped", detail="AISOC_APPROVAL_TOKEN_SECRET is unset, so no link could be signed")return- if not mailer.configured:+ if not configured:report.record("email", delivered=False, status="skipped", detail="no SMTP relay is configured (set SMTP_HOST and SMTP_SENDER)")return@@ -118,6 +142,7 @@ async def _deliver_email(row: Any, report: DeliveryReport) -> None:web_base_url=os.getenv("CONSOLE_PUBLIC_BASE_URL", "").rstrip("/"),secret=secret,mailer=mailer,+ branding=branding,)except EmailApprovalError as exc:report.record("email", delivered=False, status="failed", detail=str(exc))@@ -182,16 +207,21 @@ async def _deliver_chat(row: Any, report: DeliveryReport, *, channel: str, url_ereport.record(channel, delivered=posted, status="sent" if posted else "skipped", detail=detail)-async def deliver_approval(row: Any) -> DeliveryReport:+async def deliver_approval(row: Any, branding: Branding | None = None) -> DeliveryReport:"""Offer one approval on every configured channel. Never raises.+ ``branding`` is the operator's appearance, resolved by the caller, which+ is the only layer holding both the session and the tenant. Passing None+ renders the platform default -- `send_approval_email` already treats it+ that way, so an unbranded deployment is unaffected.+Channels run in sequence rather than concurrently on purpose: threechannels is a handful of hundred-millisecond calls, and a gather herewould make the failure of one harder to attribute for no gain a humanwaiting on an approval would notice."""report = DeliveryReport()- await _deliver_email(row, report)+ await _deliver_email(row, report, branding)await _deliver_chat(row, report, channel="slack", url_env="AISOC_SLACK_BOT_URL")await _deliver_chat(row, report, channel="teams", url_env="AISOC_TEAMS_BOT_URL")logger.info(diff --git a/services/api/app/services/case_summary_html.py b/services/api/app/services/case_summary_html.pyindex de56da1d0..61580b99e 100644--- a/services/api/app/services/case_summary_html.py+++ b/services/api/app/services/case_summary_html.py@@ -13,6 +13,10 @@ Design goals* Inline CSS only, so the document is portable when downloaded.* Print-friendly typography and colour-blind-safe palette.* Defensive HTML escaping — every field touches tenant data.+* White-labelled: the product name, palette, logo, footer and support+ contact come from the branding resolver. Severity and recommendation+ colours do not, because those encode how bad something is rather than+ whose product it is."""from __future__ import annotations@@ -20,6 +24,8 @@ from __future__ import annotationsimport htmlfrom datetime import UTC, datetime+from app.services.branding.resolver import DEFAULT_BRANDING, Branding+from .case_summary import (CaseAutoSummary,CaseLifecycleTimings,@@ -88,12 +94,23 @@ def _kpi(label: str, value: str, *, hint: str | None = None) -> str:)-def _header_block(case: CaseSummaryHeader, lifecycle: CaseLifecycleTimings, headline: str) -> str:+def _header_block(case: CaseSummaryHeader, lifecycle: CaseLifecycleTimings, headline: str, brand: Branding) -> str:label = case.case_number or str(case.case_id)[:8]+ # The logo is inlined rather than referenced for the same reason the+ # digest inlines it: a case file is archived and reopened years later, and+ # a referenced asset turns into a broken image the moment somebody tidies+ # up a bucket.+ logo = (+ f'<img src="{_esc(brand.logo_data_uri)}" alt="{_esc(brand.product_name)}" '+ 'style="max-height:36px;max-width:180px;margin-bottom:8px;display:block;">'+ if brand.logo_data_uri+ else ""+ )return ("<header>"- '<div style="font-size:11px;color:#64748b;text-transform:uppercase;'- 'letter-spacing:0.08em;">AiSOC case auto-summary</div>'+ f"{logo}"+ f'<div style="font-size:11px;color:{_esc(brand.primary_color)};text-transform:uppercase;'+ f'letter-spacing:0.08em;">{_esc(brand.product_name)} case auto-summary</div>'f"<h1>{_esc(label)} — {_esc(case.title)}</h1>"f'<div style="margin-top:6px;">{_severity_chip(case.severity)} 'f'<span style="display:inline-block;padding:2px 8px;border-radius:9999px;'@@ -270,13 +287,22 @@ def _recommendation_block(recs: list[CaseRecommendation]) -> str:return "<h2>Post-mortem</h2>" + cards-def render_case_summary_html(summary: CaseAutoSummary) -> str:- """Render a ``CaseAutoSummary`` to a self-contained HTML document."""+def render_case_summary_html(summary: CaseAutoSummary, branding: Branding | None = None) -> str:+ """Render a ``CaseAutoSummary`` to a self-contained HTML document.++ ``branding`` defaults to the platform appearance, so an unbranded+ deployment is unchanged. This is the close-out artifact a managed+ customer receives for their own case file, which makes it one of the two+ documents white-label exists for; it carried the platform name in its+ title, its header and its footer.+ """+ brand = branding or DEFAULT_BRANDING+ support = brand.support_url or brand.support_emailreturn f"""<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">-<title>AiSOC Case Summary — {_esc(summary.case.case_number or summary.case.title)}</title>+<title>{_esc(brand.product_name)} Case Summary — {_esc(summary.case.case_number or summary.case.title)}</title><style>@page {{ margin: 18mm; }}body {{@@ -290,7 +316,7 @@ def render_case_summary_html(summary: CaseAutoSummary) -> str:h1, h2, h3 {{ color: #0f172a; margin-top: 0; }}h1 {{ font-size: 22px; margin-bottom: 4px; }}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; }}+ color: #475569; margin: 20px 0 10px; border-top: 2px solid {_esc(brand.accent_color)}; padding-top: 14px; }}table th, table td {{ border-bottom: 1px solid #f1f5f9; }}@media print {{body {{ padding: 0; }}@@ -299,7 +325,7 @@ def render_case_summary_html(summary: CaseAutoSummary) -> str:</style></head><body>- {_header_block(summary.case, summary.lifecycle, summary.headline)}+ {_header_block(summary.case, summary.lifecycle, summary.headline, brand)}{_description_block(summary.case)}<h2>Lifecycle</h2>@@ -316,8 +342,9 @@ def render_case_summary_html(summary: CaseAutoSummary) -> str:{_recommendation_block(summary.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 case-file archival.+ {_esc(brand.footer_text)}+ {f"<div>Support: {_esc(support)}</div>" if support else ""}+ <div>Print this page (Ctrl/Cmd-P → Save as PDF) for case-file archival.</div></footer></body></html>"""diff --git a/services/api/app/services/digest_html.py b/services/api/app/services/digest_html.pyindex e29c3f7ff..b53d8d1ac 100644--- a/services/api/app/services/digest_html.py+++ b/services/api/app/services/digest_html.py@@ -212,6 +212,7 @@ def render_digest_html(digest: ExecutiveDigest, branding: Branding | None = Noneperiod = digest.periodproduct = _esc(brand.product_name)primary = _esc(brand.primary_color)+ accent = _esc(brand.accent_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;">'@@ -237,9 +238,8 @@ def render_digest_html(digest: ExecutiveDigest, branding: Branding | None = None}}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; }}+ color: #475569; margin: 20px 0 10px; border-top: 2px solid {accent}; padding-top: 14px; }}table th, table td {{ border-bottom: 1px solid #f1f5f9; }}@media print {{body {{ padding: 0; }}diff --git a/services/api/app/services/email_approval.py b/services/api/app/services/email_approval.pyindex 4844e5877..d8900b87f 100644--- a/services/api/app/services/email_approval.py+++ b/services/api/app/services/email_approval.py@@ -40,6 +40,14 @@ The consuming endpoint is ``GET /api/v1/actions/email-decide``. It didnot exist for several releases while ``approval_url`` defaulted to``/v1/actions/email-decide``, a path present nowhere else in the tree,so every rendered approve and deny button linked to a 404.++* **The mail is white-labelled.** A managed-service provider's analyst+ receives this in their own inbox, so the product name, the sender name,+ the footer and the support contact come from+ :mod:`app.services.branding.resolver` rather than from a literal. The+ subject line read ``[AiSOC]`` for every organisation, and the resolved+ ``sender_name`` -- the one field whose whole purpose is naming who mail+ comes from -- was read by nothing in the tree."""from __future__ import annotations@@ -47,6 +55,7 @@ from __future__ import annotationsimport base64import hashlibimport hmac+import htmlimport jsonimport osimport time@@ -57,6 +66,8 @@ from urllib.parse import urlencodeimport httpximport structlog+from app.services.branding.resolver import DEFAULT_BRANDING, Branding+log = structlog.get_logger(__name__)DEFAULT_TTL_SECONDS = 3600 # 1 hour — T3.6 contract@@ -255,6 +266,7 @@ class MailDeliveryClient(Protocol):html: str,text: str,from_addr: str | None = None,+ from_name: str | None = None,) -> dict[str, Any]:# Protocol stub body uses ``pass`` rather than ``...`` to silence# CodeQL ``py/ineffectual-statement``. Semantically identical for@@ -262,6 +274,31 @@ class MailDeliveryClient(Protocol):pass+def _esc(value: str) -> str:+ """HTML-escape one interpolated value, quotes included.++ The attribute values here sit in single quotes, which `html.escape`+ covers along with the double kind.+ """+ return html.escape(str(value), quote=True)+++def _quoted_display_name(name: str) -> str:+ """One RFC 5322 ``quoted-string`` for a ``From`` display name.++ The name is operator-supplied through ``PUT /api/v1/branding``, and it is+ about to be composed into a mail header. A carriage return or newline in+ it is header injection -- the rest of the value becomes additional+ headers, which is how a ``Bcc`` gets added to approval mail nobody else+ was supposed to see. Control characters are removed rather than escaped+ because none of them belong in a product name, and the backslash and+ quote are escaped because a quoted-string is where this lands.+ """+ cleaned = "".join(character for character in name if character.isprintable())+ escaped = cleaned.replace("\\", "\\\\").replace('"', '\\"')+ return f'"{escaped[:80]}"'++def _default_from_addr(domain: str) -> str:"""Sender address when ``AISOC_APPROVAL_FROM_ADDR`` is unset.@@ -306,12 +343,18 @@ class MailgunClient:html: str,text: str,from_addr: str | None = None,+ from_name: str | None = None,) -> dict[str, Any]:if not self._api_key or not self._domain:raise EmailApprovalError("Mailgun is not configured — set MAILGUN_API_KEY and MAILGUN_DOMAIN")url = f"{self._base_url}/{self._domain}/messages"+ # The address stays the operator's own sending domain whatever the+ # display name says, because that is what SPF and DKIM are checked+ # against. Only the name a recipient reads is white-labelled.+ address = from_addr or self._from_addr+ sender = f"{_quoted_display_name(from_name)} <{address}>" if from_name else addressdata: dict[str, Any] = {- "from": from_addr or self._from_addr,+ "from": sender,"to": to,"subject": subject,"text": text,@@ -337,44 +380,62 @@ def render_approval_email(approve_url: str,reject_url: str,web_base_url: str,+ branding: Branding | None = None,) -> tuple[str, str, str]:"""Render a plain-text + HTML approval email for a pending action.Returns ``(subject, text_body, html_body)``.++ ``branding`` defaults to the platform appearance, so an unbranded+ deployment is unchanged. The approve and deny buttons keep their green+ and red: those two colours mean "this one contains, this one does not"+ and an organisation's palette must not be able to swap them."""+ brand = branding or DEFAULT_BRANDINGcase_number = case.get("case_number") or str(case.get("id") or "")[:8] or "(unknown)"action_type = action.get("action_type") or "unknown"target = action.get("target") or "unknown"rationale = (action.get("rationale") or "(no rationale provided)").strip()+ product = brand.product_name+ support = brand.support_url or brand.support_email- subject = f"[AiSOC] Approval needed: {action_type} on {target} — case {case_number}"+ subject = f"[{product}] Approval needed: {action_type} on {target} — case {case_number}"text_body = (- f"AiSOC approval request\n\n"+ f"{product} approval request\n\n"f"Case: {case_number}\n"f"Action: {action_type}\n"f"Target: {target}\n"f"Rationale: {rationale}\n\n"f"Approve: {approve_url}\n"f"Deny: {reject_url}\n\n"- f"Open case in AiSOC: {web_base_url.rstrip('/')}/cases/{case.get('id') or ''}\n\n"+ f"Open case in {product}: {web_base_url.rstrip('/')}/cases/{case.get('id') or ''}\n\n"f"This link expires in 60 minutes. Replies to this email are not monitored.\n"+ + (f"Support: {support}\n" if support else "")+ + f"{brand.footer_text}\n")+ # Everything interpolated below is escaped. The brand fields are+ # operator-supplied free text, and ``rationale`` is the agent's summary of+ # evidence an attacker influenced -- model output written into HTML that an+ # on-call analyst opens in a mail client.html_body = (- f"<p><strong>AiSOC approval request</strong></p>"+ f"<p style='color:{_esc(brand.primary_color)};font-size:11px;text-transform:uppercase;letter-spacing:0.08em;margin-bottom:4px'>{_esc(product)}</p>" # noqa: E501+ f"<p><strong>{_esc(product)} approval request</strong></p>"f"<table style='border-collapse:collapse'>"- f"<tr><td><strong>Case</strong></td><td>{case_number}</td></tr>"- f"<tr><td><strong>Action</strong></td><td><code>{action_type}</code></td></tr>"- f"<tr><td><strong>Target</strong></td><td><code>{target}</code></td></tr>"- f"<tr><td><strong>Rationale</strong></td><td>{rationale}</td></tr>"+ f"<tr><td><strong>Case</strong></td><td>{_esc(case_number)}</td></tr>"+ f"<tr><td><strong>Action</strong></td><td><code>{_esc(action_type)}</code></td></tr>"+ f"<tr><td><strong>Target</strong></td><td><code>{_esc(target)}</code></td></tr>"+ f"<tr><td><strong>Rationale</strong></td><td>{_esc(rationale)}</td></tr>"f"</table>"f"<p style='margin-top:16px'>"- f"<a href='{approve_url}' style='background:#16a34a;color:#fff;padding:8px 14px;border-radius:6px;text-decoration:none;margin-right:8px'>Approve</a>" # noqa: E501- f"<a href='{reject_url}' style='background:#dc2626;color:#fff;padding:8px 14px;border-radius:6px;text-decoration:none'>Deny</a>"+ f"<a href='{_esc(approve_url)}' style='background:#16a34a;color:#fff;padding:8px 14px;border-radius:6px;text-decoration:none;margin-right:8px'>Approve</a>" # noqa: E501+ f"<a href='{_esc(reject_url)}' style='background:#dc2626;color:#fff;padding:8px 14px;border-radius:6px;text-decoration:none'>Deny</a>" # noqa: E501f"</p>"f"<p style='color:#6b7280;font-size:12px'>This link expires in 60 minutes.</p>"+ f"<hr style='border:none;border-top:2px solid {_esc(brand.accent_color)};margin:16px 0 8px'>"+ f"<p style='color:#6b7280;font-size:11px'>{_esc(brand.footer_text)}" + (f"<br>Support: {_esc(support)}" if support else "") + "</p>")return subject, text_body, html_body@@ -388,6 +449,7 @@ async def send_approval_email(web_base_url: str,secret: str,mailer: MailDeliveryClient,+ branding: Branding | None = None,ttl_seconds: int = DEFAULT_TTL_SECONDS,now: float | None = None,) -> dict[str, Any]:@@ -395,48 +457,65 @@ async def send_approval_email(Mint signed approve/deny URLs, render the email body, and dispatchthrough the configured mailer.- Returns the mailer response unchanged so callers can persist the- Mailgun message id for the case timeline.+ Returns ``{"sent": n, "responses": [...]}`` so a caller can persist the+ mailer message ids for the case timeline.++ One message per recipient, each carrying its own pair of tokens, because+ the approver is signed into the token and the consuming endpoint refuses+ a token that names nobody. Minting one pair for the whole list would make+ every click record the same identity, which separation of duties cannot+ be evaluated against -- and minting them with no approver at all, which+ is what this function did while it had no caller, produces links that+ ``/actions/email-decide`` rejects on arrival."""if not recipients:raise EmailApprovalError("no recipients provided")+ brand = branding or DEFAULT_BRANDINGaction_id = str(action.get("id") or action.get("action_id") or "")case_id = str(case.get("id") or "")if not action_id:raise EmailApprovalError("action.id is required")- approve = approval_url(- base_url=api_base_url,- decision="approved",- action_id=action_id,- case_id=case_id,- secret=secret,- ttl_seconds=ttl_seconds,- now=now,- )- reject = approval_url(- base_url=api_base_url,- decision="rejected",- action_id=action_id,- case_id=case_id,- secret=secret,- ttl_seconds=ttl_seconds,- now=now,- )- subject, text_body, html_body = render_approval_email(- case=case,- action=action,- approve_url=approve,- reject_url=reject,- web_base_url=web_base_url,- )- response = await mailer.send(to=recipients, subject=subject, html=html_body, text=text_body)+ responses: list[dict[str, Any]] = []+ for recipient in recipients:+ urls = {+ decision: approval_url(+ base_url=api_base_url,+ decision=decision,+ action_id=action_id,+ case_id=case_id,+ secret=secret,+ approver=recipient,+ ttl_seconds=ttl_seconds,+ now=now,+ )+ for decision in ("approved", "rejected")+ }+ subject, text_body, html_body = render_approval_email(+ case=case,+ action=action,+ approve_url=urls["approved"],+ reject_url=urls["rejected"],+ web_base_url=web_base_url,+ branding=brand,+ )+ responses.append(+ await mailer.send(+ to=[recipient],+ subject=subject,+ html=html_body,+ text=text_body,+ from_name=brand.sender_name,+ )+ )+log.info("email_approval.sent",action_id=action_id,case_id=case_id,recipients=len(recipients),ttl_seconds=ttl_seconds,+ white_labelled=brand.is_white_labelled,)- return response+ return {"sent": len(responses), "responses": responses}diff --git a/services/api/app/services/replay_evaluation/report.py b/services/api/app/services/replay_evaluation/report.pyindex a24887481..db593f4e1 100644--- a/services/api/app/services/replay_evaluation/report.py+++ b/services/api/app/services/replay_evaluation/report.py@@ -37,6 +37,7 @@ import refrom typing import Anyfrom app._vendor.aisoc_benchmark.replay import LATENCY_FIELDS, strip_latency+from app.services.branding.resolver import DEFAULT_BRANDING, Brandinglogger = logging.getLogger(__name__)@@ -194,18 +195,28 @@ def markdown_to_html(markdown: str) -> str:return "\n".join(out)-def _document(body_html: str) -> str:+def _document(body_html: str, brand: Branding) -> str:"""Wrap the fragment in a print-ready page.No generation timestamp and no host name anywhere. A report that prints"generated at" is a report that cannot reproduce byte for byte, which is- this phase's acceptance bar.+ this phase's acceptance bar. Branding does not break that: the same+ organisation's branding renders the same bytes, and a report that+ reproduces only while unbranded is of no use to the operator who has+ configured one."""+ support = brand.support_url or brand.support_email+ logo = (+ f'<img src="{html.escape(brand.logo_data_uri, quote=True)}" alt="{html.escape(brand.product_name)}" '+ 'style="max-height:12mm;max-width:50mm;margin:0 0 3mm;display:block;">'+ if brand.logo_data_uri+ else ""+ )return f"""<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">-<title>AiSOC replay evaluation</title>+<title>{html.escape(brand.product_name)} replay evaluation</title><style>@page {{ margin: 18mm; }}body {{@@ -215,7 +226,7 @@ def _document(body_html: str) -> str:line-height: 1.45;}}h1 {{ font-size: 20pt; margin: 0 0 4mm; }}- h2 {{ font-size: 13pt; margin: 7mm 0 2mm; border-bottom: 1px solid #cbd5e1; padding-bottom: 1mm; }}+ h2 {{ font-size: 13pt; margin: 7mm 0 2mm; border-bottom: 1px solid {html.escape(brand.accent_color, quote=True)}; padding-bottom: 1mm; }}h3 {{ font-size: 11pt; margin: 5mm 0 2mm; }}p {{ margin: 0 0 2mm; }}ul {{ margin: 0 0 3mm 5mm; padding: 0; }}@@ -223,20 +234,28 @@ def _document(body_html: str) -> str:table {{ border-collapse: collapse; width: 100%; margin: 0 0 4mm; font-size: 9pt; }}th, td {{ border: 1px solid #cbd5e1; padding: 1.5mm 2mm; text-align: left; }}th {{ background: #f1f5f9; font-weight: 600; }}+ header.brand {{ color: {html.escape(brand.primary_color, quote=True)}; font-size: 8pt;+ text-transform: uppercase; letter-spacing: 0.08em; margin: 0 0 3mm; }}+ footer.brand {{ color: #94a3b8; font-size: 8pt; margin-top: 8mm; }}</style></head><body>+{logo}<header class="brand">{html.escape(brand.product_name)} replay evaluation</header>{body_html}+<footer class="brand">{html.escape(brand.footer_text)}{f"<br>Support: {html.escape(support)}" if support else ""}</footer></body></html>"""-def render_pdf(markdown: str) -> bytes:+def render_pdf(markdown: str, branding: Branding | None = None) -> bytes:"""Render the stored report as a PDF.Raises :class:`PdfUnavailableError` rather than returning an empty orpartial document, because a zero-byte PDF served with a 200 reads as acorrupt report rather than as a missing library.++ ``branding`` defaults to the platform appearance, so an unbranded+ deployment is unchanged."""# Imported at call time, following ``app.services.digest_pdf``: WeasyPrint# pulls a native stack that is present in the API image and routinely@@ -251,4 +270,4 @@ def render_pdf(markdown: str) -> bytes:logger.warning("replay report PDF export unavailable: %s", exc)raise PdfUnavailableError(PDF_UNAVAILABLE_DETAIL) from exc- return HTML(string=_document(markdown_to_html(markdown))).write_pdf()+ return HTML(string=_document(markdown_to_html(markdown), branding or DEFAULT_BRANDING)).write_pdf()diff --git a/services/api/app/services/smtp_delivery.py b/services/api/app/services/smtp_delivery.pyindex 9115df67c..507f67598 100644--- a/services/api/app/services/smtp_delivery.py+++ b/services/api/app/services/smtp_delivery.py@@ -40,6 +40,7 @@ import sslfrom dataclasses import dataclass, replacefrom email.message import EmailMessagefrom email.utils import formataddr+from typing import Anyimport structlog@@ -223,8 +224,19 @@ class SmtpApprovalMailer:html: str,text: str,from_addr: str | None = None,- ) -> dict[str, object]:- settings = self._settings if from_addr is None else replace(self._settings, sender=from_addr)+ from_name: str | None = None,+ ) -> dict[str, Any]:+ # `from_name` is part of the Protocol and was missing here, so this+ # class did not in fact implement it -- caught as an arg-type finding+ # at the call site rather than at the class, which is the usual way+ # round for a Protocol. A caller setting a display name would have+ # raised TypeError at runtime.+ overrides: dict[str, Any] = {}+ if from_addr is not None:+ overrides["sender"] = from_addr+ if from_name is not None:+ overrides["sender_name"] = from_name+ settings = replace(self._settings, **overrides) if overrides else self._settingsresult = await send_mail(recipients=to,subject=subject,diff --git a/services/api/tests/test_branding.py b/services/api/tests/test_branding.pyindex 54b2cfcdd..f312d53e5 100644--- a/services/api/tests/test_branding.py+++ b/services/api/tests/test_branding.py@@ -315,6 +315,123 @@ class TestTheReport:assert not offenders, f"report references {offenders}"+class TestTheOtherTwoDocuments:+ """The case close-out and the replay evaluation.++ Both are documents an operator forwards outside the SOC, and the doc+ listed "Executive digest" as the only branded report while these two+ carried the platform name in their title, their header and their footer.+ They are covered here rather than in their own suites because this file+ is the gate the white-label claim row names.+ """++ @staticmethod+ def _case_summary():+ from app.services.case_summary import CaseSummaryInputs, SummaryCaseRow, build_summary_from_rows++ opened = datetime(2026, 3, 10, 9, 0, tzinfo=UTC)+ return build_summary_from_rows(+ CaseSummaryInputs(+ case=SummaryCaseRow(+ id=uuid.UUID("c0c0c0c0-0000-0000-0000-00000000000c"),+ case_number="CASE-2026-0042",+ title="Suspected ransomware",+ description=None,+ severity="high",+ status="closed",+ assignee=None,+ created_by=None,+ opened_at=opened,+ triaged_at=None,+ resolved_at=None,+ closed_at=None,+ sla_due_at=None,+ mitre_techniques=[],+ alert_ids=[],+ observable_graph={},+ evidence_chain=[],+ compliance_frameworks=[],+ tags={},+ created_at=opened,+ updated_at=opened,+ )+ ),+ now=opened,+ )++ async def test_the_case_summary_carries_the_organisations_brand(self, session_factory):+ from app.services.case_summary_html import render_case_summary_html++ async with session_factory() as db:+ await _brand(+ db,+ product_name="Acme Shield",+ primary_color="#123456",+ accent_color="#654321",+ support_url="https://support.acme.example",+ )+ branding = await resolver.resolve_branding(db, MANAGED_TENANT)++ html = render_case_summary_html(self._case_summary(), branding)++ assert "Acme Shield case auto-summary" in html+ assert "#123456" in html+ assert "#654321" in html+ assert "support.acme.example" in html+ assert "AiSOC" not in html++ def test_an_unbranded_case_summary_is_unchanged(self):+ """The negative control. A self-hosted install keeps what it had."""+ from app.services.case_summary_html import render_case_summary_html++ html = render_case_summary_html(self._case_summary())+ assert "AiSOC case auto-summary" in html++ async def test_the_replay_report_carries_the_organisations_brand(self, session_factory):+ """Asserted on the HTML the PDF is rendered from.++ Same reasoning as the digest: WeasyPrint turns exactly this document+ into the PDF, so the native stack does not have to be installed to+ know what the PDF says.+ """+ from app.services.replay_evaluation.report import _document, markdown_to_html++ async with session_factory() as db:+ await _brand(db, product_name="Acme Shield", accent_color="#654321", support_email="[email protected]")+ branding = await resolver.resolve_branding(db, MANAGED_TENANT)++ document = _document(markdown_to_html("# Replay\n\nOne paragraph.\n"), branding)++ assert "Acme Shield replay evaluation" in document+ assert "#654321" in document+ assert "[email protected]" in document+ assert "AiSOC" not in document++ def test_an_unbranded_replay_report_is_unchanged(self):+ from app.services.replay_evaluation.report import DEFAULT_BRANDING, _document, markdown_to_html++ document = _document(markdown_to_html("# Replay\n"), DEFAULT_BRANDING)+ assert "AiSOC replay evaluation" in document++ async def test_the_digest_applies_the_accent_colour(self, session_factory):+ """The doc listed "accent colour" for the console and the digest.++ Nothing read ``accent_color`` at all, and the one place the digest+ named ``primary_color`` in its stylesheet was a ``border-top-color``+ rule the very next selector overrode with a literal grey -- so the+ section rules rendered in the platform palette whatever an operator+ configured.+ """+ 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", accent_color="#654321")+ branding = await resolver.resolve_branding(db, MANAGED_TENANT)++ html = render_digest_html(TestTheReport._digest(), branding)+ assert "#654321" in html++class TestSupportUrlIsNotAScriptVector:"""``support_url`` is rendered as a link in email and in a PDF."""diff --git a/services/api/tests/test_white_label_notifications.py b/services/api/tests/test_white_label_notifications.pynew file mode 100644index 000000000..cfef4aeea--- /dev/null+++ b/services/api/tests/test_white_label_notifications.py@@ -0,0 +1,414 @@+"""The signed email approval is wired, and it carries the operator's brand.++Two defects, one path.++``send_approval_email`` had **no caller anywhere in the tree**. The+documentation names it as the fallback for "Slack and Teams are unreachable",+and the function, its signer, its verifier and its consuming endpoint were all+tested — none of which says anything about whether an approval ever produces+one. So these cases drive ``POST /api/v1/approvals`` through the real router+and read what left the mailer, rather than calling the function and asserting+it returns what it was given.++The second is why that matters here: the subject line read ``[AiSOC]`` for+every organisation, and ``sender_name`` — the one resolved field whose entire+purpose is naming who mail comes from — was read by nothing. A managed+customer's on-call analyst is the person this lands on, and they have never+heard of the platform their provider runs.++The link is verified rather than eyeballed. A branded email whose approve+button does not authenticate is worse than an unbranded one, and the+consuming endpoint refuses a token that names no approver — which is exactly+what this function minted while nothing called it.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+import pytest_asyncio+from app.api.v1.deps import CurrentUser, get_current_user+from app.api.v1.endpoints import approvals as endpoint+from app.db.database import Base+from app.db.rls import get_tenant_db+from app.models.branding import OrgBrandAsset, OrgBranding+from app.models.organization import Organization, OrganizationTenant+from app.models.responder import AgentApproval+from app.services import approval_delivery+from app.services.email_approval import EmailApprovalError, _quoted_display_name, verify_token+from fastapi import FastAPI+from fastapi.testclient import TestClient+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++TENANT = uuid.UUID("eeeeeeee-0000-0000-0000-0000000000e1")+ORG = uuid.UUID("0a0a0a0a-0000-0000-0000-00000000000a")+USER = uuid.UUID("0b0b0b0b-0000-0000-0000-00000000000b")+SECRET = "test-approval-signing-secret"+ONCALL = ["[email protected]", "[email protected]"]+++@compiles(JSONB, "sqlite")+def _jsonb_sqlite(_type_, _compiler_, **_kw_):+ return "TEXT"+++@compiles(PgUUID, "sqlite")+def _uuid_sqlite(_type_, _compiler_, **_kw_):+ return "CHAR(36)"+++class _RecordingMailer:+ """Stands in for Mailgun and records the message, not the call.++ Deliberately declares the same keyword-only signature as+ ``MailgunClient.send``. A double that accepts ``**kwargs`` would keep+ passing if the caller stopped sending ``from_name``, which is the field+ this file exists to prove reaches the wire.+ """++ #: The delivery path refuses to send through an unconfigured relay,+ #: so a double has to answer that question too.+ configured = True++ def __init__(self) -> None:+ self.messages: list[dict[str, Any]] = []++ async def send(+ self,+ *,+ to: list[str],+ subject: str,+ html: str,+ text: str,+ from_addr: str | None = None,+ from_name: str | None = None,+ ) -> dict[str, Any]:+ self.messages.append({"to": to, "subject": subject, "html": html, "text": text, "from_addr": from_addr, "from_name": from_name})+ return {"id": f"<{len(self.messages)}@mailgun.test>"}+++@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__,+ # The resolver looks for a logo even when only text fields are+ # set, and it swallows every exception by design. Omitting this+ # table does not fail — it silently resolves the platform+ # default, which is the answer this file is here to disprove.+ OrgBrandAsset.__table__,+ AgentApproval.__table__,+ ],+ )+ yield async_sessionmaker(engine, expire_on_commit=False)+ await engine.dispose()+++def mailer(monkeypatch: pytest.MonkeyPatch) -> _RecordingMailer:+ recorder = _RecordingMailer()+ # The mailer moved out of the endpoint into `approval_delivery` when+ # email, Slack and Teams were given one delivery path, so the seam+ # is patched where it now lives.+ monkeypatch.setattr(approval_delivery, "_build_mailer", lambda: recorder)+ monkeypatch.setenv("AISOC_APPROVAL_TOKEN_SECRET", SECRET)+ # The realtime fan-out is a different notification path with its own+ # tests; leaving it pointed at nothing keeps this one offline.+ monkeypatch.setattr(endpoint.settings, "REALTIME_BASE_URL", "", raising=False)+ return recorder+++def client(session_factory) -> TestClient:+ app = FastAPI()+ app.include_router(endpoint.router, prefix="/api/v1")++ async def _db():+ async with session_factory() as session:+ yield session++ app.dependency_overrides[get_tenant_db] = _db+ app.dependency_overrides[get_current_user] = lambda: CurrentUser(+ user_id=USER,+ tenant_id=TENANT,+ role="admin",+ email="[email protected]",+ resolved_permissions=frozenset({"cases:write"}),+ )+ return TestClient(app, raise_server_exceptions=False)+++async def _brand(session_factory, **overrides) -> None:+ async with session_factory() as db:+ db.add(Organization(id=ORG, slug="acme", name="Acme MSSP", home_tenant_id=uuid.uuid4()))+ db.add(OrganizationTenant(org_id=ORG, tenant_id=TENANT, onboarded_at=datetime.now(UTC)))+ db.add(OrgBranding(org_id=ORG, **overrides))+ await db.commit()+++def _request_approval(client: TestClient, *, approvers: list[str] | None = None) -> dict[str, Any]:+ """Raise an approval, optionally naming nobody.++ Who to notify travels on the approval rather than in process config, so+ the no-recipients case is expressed by the payload the caller sends.+ """+ action: dict[str, Any] = {"action_type": "isolate_host", "target": "WKSTN-01"}+ if approvers is None:+ action["approver_emails"] = ONCALL+ elif approvers:+ action["approver_emails"] = approvers+ response = client.post(+ "/api/v1/approvals",+ json={+ "title": "Isolate WKSTN-01",+ "summary": "Falcon detection with a confirmed C2 beacon.",+ "risk_level": "high",+ "case_id": "CASE-4471",+ "action": action,+ },+ )+ assert response.status_code == 201, response.text+ return response.json()+++def _links(text_body: str) -> list[str]:+ """The approve and deny URLs, read out of the rendered plain-text body."""+ return [line.split(":", 1)[1].strip() for line in text_body.splitlines() if line.startswith(("Approve:", "Deny:"))]+++class TestTheFallbackHasAProducer:+ def test_creating_an_approval_sends_the_signed_email(self, client, mailer) -> None:+ """The defect, stated as a test.++ Nothing in the repository called ``send_approval_email``. Deleting the+ ``_notify_email`` call from ``create_approval`` turns this red, which+ is the only assertion here that could not be satisfied by the function+ existing and being correct.+ """+ _request_approval(client)++ assert mailer.messages, "creating an approval sent no email; the signed fallback has no producer"+ assert [message["to"][0] for message in mailer.messages] == ONCALL++ def test_nothing_is_sent_when_no_recipients_are_configured(self, client, mailer, monkeypatch) -> None:+ """The other direction. Mail to nobody is not a fallback."""+ _request_approval(client, approvers=[])+ assert mailer.messages == []++ def test_a_missing_signing_secret_is_reported_rather_than_silently_skipped(self, client, mailer, monkeypatch, caplog) -> None:+ """An operator who set recipients is expecting mail.++ Returning quietly here is how a wired fallback looks wired and does+ nothing, which is the shape of the defect this file closes.+ """+ monkeypatch.setenv("AISOC_APPROVAL_TOKEN_SECRET", "")+ created = _request_approval(client)++ assert mailer.messages == []+ # Asserted against the delivery report rather than a log line. The+ # report is persisted on the approval and returned to the caller, so+ # it is what an operator can actually see; a warning that scrolls+ # past in a container log is not a channel anyone reads.+ email = (created.get("action") or {}).get("delivery", {}).get("channels", {}).get("email", {})+ assert email.get("delivered") is False+ assert email.get("status") == "skipped"+ assert "AISOC_APPROVAL_TOKEN_SECRET" in email.get("detail", "")++ def test_an_unreachable_mailer_does_not_fail_the_approval(self, client, mailer, monkeypatch) -> None:+ """The approval is already persisted; notification is best effort."""++ class _Broken:+ async def send(self, **_kwargs: Any) -> dict[str, Any]:+ raise EmailApprovalError("Mailgun is not configured")++ monkeypatch.setattr(approval_delivery, "_build_mailer", _Broken)+ assert _request_approval(client)["status"] == "pending"+++class TestTheMailCarriesTheOperatorsBrand:+ @pytest.mark.asyncio+ async def test_the_subject_and_bodies_name_the_organisations_product(self, client, mailer, session_factory) -> None:+ await _brand(session_factory, product_name="Acme Shield")+ _request_approval(client)++ message = mailer.messages[0]+ assert message["subject"].startswith("[Acme Shield]")+ assert "Acme Shield approval request" in message["text"]+ assert "Acme Shield approval request" in message["html"]++ @pytest.mark.asyncio+ async def test_the_platform_name_is_gone_rather_than_sitting_beside_it(self, client, mailer, session_factory) -> None:+ """Mail showing both is not white-labelled, it is co-branded by accident."""+ await _brand(session_factory, product_name="Acme Shield")+ _request_approval(client)++ message = mailer.messages[0]+ assert "AiSOC" not in message["subject"]+ assert "AiSOC" not in message["text"]+ assert "AiSOC" not in message["html"]++ @pytest.mark.asyncio+ async def test_the_sender_name_reaches_the_mailer(self, client, mailer, session_factory) -> None:+ """``sender_name`` had no reader outside the resolver and its own test."""+ await _brand(session_factory, product_name="Acme Shield", sender_name="Acme SOC")+ _request_approval(client)++ assert mailer.messages[0]["from_name"] == "Acme SOC"++ @pytest.mark.asyncio+ async def test_the_sender_name_defaults_to_the_product_name_on_the_wire(self, client, mailer, session_factory) -> None:+ await _brand(session_factory, product_name="Acme Shield")+ _request_approval(client)++ assert mailer.messages[0]["from_name"] == "Acme Shield"++ @pytest.mark.asyncio+ async def test_the_support_contact_and_footer_are_rendered(self, client, mailer, session_factory) -> None:+ await _brand(+ session_factory,+ product_name="Acme Shield",+ support_url="https://support.acme.example",+ footer_text="Acme Shield, operated by Acme MSSP.",+ )+ _request_approval(client)++ message = mailer.messages[0]+ # Counted rather than `in`: exactly one support link per body is the+ # claim, and a containment check against a URL literal is the shape+ # CodeQL reads as an incomplete host check.+ assert message["html"].count("https://support.acme.example") == 1+ assert message["text"].count("https://support.acme.example") == 1+ assert "Acme Shield, operated by Acme MSSP." in message["html"]++ @pytest.mark.asyncio+ async def test_the_palette_is_applied(self, client, mailer, session_factory) -> None:+ await _brand(session_factory, product_name="Acme Shield", primary_color="#123456", accent_color="#654321")+ _request_approval(client)++ html = mailer.messages[0]["html"]+ assert "#123456" in html+ assert "#654321" in html++ @pytest.mark.asyncio+ async def test_the_approve_and_deny_colours_are_not_brandable(self, client, mailer, session_factory) -> None:+ """Green means contains and red means does not.++ An organisation's palette must not be able to swap the two, which is+ why those two are literals while everything else resolves.+ """+ await _brand(session_factory, product_name="Acme Shield", primary_color="#123456", accent_color="#654321")+ _request_approval(client)++ html = mailer.messages[0]["html"]+ assert "#16a34a" in html+ assert "#dc2626" in html++ def test_an_unbranded_deployment_is_unchanged(self, client, mailer) -> None:+ """The negative control for every case above.++ No organisation, so the platform appearance is what renders — and that+ is the default a self-hosted install should keep seeing.+ """+ _request_approval(client)++ message = mailer.messages[0]+ assert message["subject"].startswith("[AiSOC]")+ assert message["from_name"] == "AiSOC"+++class TestTheLinkStillWorks:+ def test_each_recipient_gets_a_token_naming_them_as_the_approver(self, client, mailer) -> None:+ """A shared token records every click as the same identity.++ And a token with *no* approver — which is what this function minted for+ as long as nothing called it — is refused outright by+ ``/actions/email-decide``, so the branded mail would have shipped a+ pair of buttons that do not work.+ """+ _request_approval(client)++ for message in mailer.messages:+ recipient = message["to"][0]+ links = _links(message["text"])+ assert len(links) == 2+ for url in links:+ token = parse_qs(urlparse(url).query)["token"][0]+ assert verify_token(token, secret=SECRET).approver == recipient++ def test_the_two_buttons_carry_opposite_decisions(self, client, mailer) -> None:+ _request_approval(client)++ decisions = {+ verify_token(parse_qs(urlparse(url).query)["token"][0], secret=SECRET).decision for url in _links(mailer.messages[0]["text"])+ }+ assert decisions == {"approved", "rejected"}++ def test_the_link_points_at_the_route_that_serves_it(self, client, mailer) -> None:+ """The console origin, not the API's internal address.++ A recipient clicks from a mail client; the console is the host their+ browser can reach, and it proxies ``/api/v1/*`` through.+ """+ _request_approval(client)++ for url in _links(mailer.messages[0]["text"]):+ assert urlparse(url).path == "/api/v1/actions/email-decide"+++class TestTheSenderNameCannotForgeAHeader:+ """``sender_name`` is operator-supplied and lands in a mail header."""++ @pytest.mark.parametrize("hostile", ["Acme\r\nBcc: [email protected]", "Acme\nX-Priority: 1"])+ def test_a_newline_in_the_display_name_is_removed(self, hostile: str) -> None:+ quoted = _quoted_display_name(hostile)+ assert "\r" not in quoted+ assert "\n" not in quoted++ def test_a_quote_is_escaped_rather_than_closing_the_string(self) -> None:+ assert _quoted_display_name('Acme" <[email protected]> "') == '"Acme\\" <[email protected]> \\""'+++class TestTheMailBodyIsEscaped:+ """Two of the values rendered into this HTML are not ours.++ The brand fields are operator-supplied free text, and the rationale is+ the agent's summary of evidence an attacker influenced — model output+ written into a document an on-call analyst opens in a mail client.+ """++ @pytest.mark.asyncio+ async def test_a_script_tag_in_the_product_name_does_not_survive(self, client, mailer, session_factory) -> None:+ await _brand(session_factory, product_name="<script>alert(1)</script>")+ _request_approval(client)++ html = mailer.messages[0]["html"]+ assert "<script>" not in html+ assert "<script>" in html++ def test_a_script_tag_in_the_agent_rationale_does_not_survive(self, client, mailer) -> None:+ response = client.post(+ "/api/v1/approvals",+ json={+ "title": "Isolate WKSTN-01",+ "summary": "<img src=x onerror=alert(1)>",+ "risk_level": "high",+ "action": {"action_type": "isolate_host", "target": "WKSTN-01", "approver_emails": ONCALL},+ },+ )+ assert response.status_code == 201, response.text++ html = mailer.messages[0]["html"]+ assert "<img src=x" not in html+ assert "<img src=x" in html