# Threat model (V1, private beta)

Scope: the control plane, console, app gateway, outbound Worker, CLI/MCP, deployed apps. Assets: user identities and sessions, workspace membership, app data (per-app D1 and files), release artifacts, agent tokens, external API keys, Cloudflare provisioning credentials.

## Trust boundaries

1. **Browser ↔ console origin** (`console.example.com`): Better Auth session cookie, host-only, `HttpOnly`, `Secure`, `SameSite=Lax` outside development; CSRF defense via strict `Origin` + `Sec-Fetch-Site` checks on every unsafe cookie-authenticated request; console CSP `script-src 'self'`; `frame-ancestors 'none'`.
2. **Agent ↔ API/MCP**: opaque bearer tokens (`ssc_pat_…`, 256-bit), SHA-256 at rest, scoped, expiring (≤ 90 days), revocable, revalidated on each call together with the user's current workspace membership. Cookies are ignored when a bearer token is present; `/mcp` accepts bearer tokens only. Assistants can obtain such a token through OAuth: a signed-in member approves it on the console, for one workspace and chosen scopes.
3. **Browser ↔ app hosts** (`<label>.example-apps.net`, a separate registrable domain): app-host-only session cookie obtained through a single-use launch ticket. App hosts can never receive console cookies (different site) and the console sends no CORS headers, so credentialed cross-origin calls from apps to the control plane fail.
4. **Gateway ↔ user Worker**: internal dispatch only. User code is untrusted.
5. **User Worker ↔ outside** (`packages/runtime/src/egress.ts`, in the Outbound Worker): the only way out. It refuses every host except the virtual ones: external APIs approved by IT, the app's own files, and the platform services (jobs, mail, browser, AI; ADR-005). The app identity comes from a gateway parameter, never from the request. This Worker holds the control D1 binding, the files bucket, the vault key, the job queue producer and the email, browser and AI bindings, so its code is as sensitive as the control plane's.
6. **Platform ↔ user Worker, for jobs**: the gateway consumes the platform queue and calls `POST /__boringcloud/jobs/<name>` on the app's current release. The queue message carries the app id set by the egress layer or the platform cron, never by app code; the app is re-read before each run. Browsers cannot reach this path (only `/api/*` is forwarded) and the job headers are reserved, so they are stripped from browser requests. A job carries no user identity.
7. **Control plane ↔ Cloudflare API**: least-privilege API token held only by the control plane (Workers for Platforms scripts edit on one namespace + D1 edit), never sent to apps, logs or the CLI.

## Controls by category

### Verified provider protections (Cloudflare documentation; confirm in staging)

- User Workers in a dispatch namespace run in **untrusted mode** by default: no `request.cf`, isolated cache, `caches.default` disabled.
- A user Worker only sees bindings attached at upload; we attach exactly `APP_DB` (its own D1).
- With an **Outbound Worker** configured, every `fetch()` from user code is intercepted; user Workers **cannot use `connect()`** (TCP), except via Hyperdrive bindings (never attached).
- **Custom limits** at dispatch: CPU ms and subrequests per invocation; exceeding them throws.
- Requests made through bindings are not intercepted by the outbound Worker — mitigated by attaching no binding other than the app's own database.

### Platform-enforced policies (implemented and tested locally)

- Per-request authorization at the gateway from authoritative D1 state (session, console session, host binding, app status, membership, role). No long-lived signed claims.
- Launch tickets: 256-bit, hashed, 60 s TTL, single use (atomic consume), bound to app/host/user/console session, removed from the URL by redirect, `Referrer-Policy: no-referrer`, never logged.
- Redirect targets restricted to same-origin relative paths (no `//`, backslashes, encoded tricks, `/_boringcloud`).
- Reserved headers (`x-boringcloud-*`, `cf-*`), cookies, `Authorization`, client IPs stripped before dispatch; context headers set from authoritative identity; per-app pseudonymous user id.
- External API keys: write-only; sealed with AES-256-GCM and bound to workspace, API and origin; opened only for a call (Outbound Worker) or an IT test (control plane). Methods, path prefixes, app selection and daily limits are checked before the key is opened. Redirects are not followed, answers containing the key are blocked, only public HTTPS hosts are accepted.
- Assistant sign-in (OAuth): PKCE S256 required, exact registered redirects (only the port of a loopback address may differ), one-time codes of 60 s stored hashed and bound to client, redirect and verifier; a second use revokes the token. Client ids are signed registrations, so anonymous calls write nothing. The consent page identifies the recipient by its address, never by the name it declares. Membership is checked again at the exchange.
- Brand: colors and font names are validated so that they cannot inject CSS; the logo is checked against its type and served with a sandboxed policy, to people who can open the app.
- External sharing (guests): off until IT turns it on per workspace, optionally for listed email domains, with a longest access. Invitations come only from a console session of an app manager or workspace admin (agent tokens refused), never to a workspace member. The link carries a 256-bit secret, stored hashed, sent in request bodies, valid 7 days, accepted once, by the signed-in verified owner of the invited address only, after the policy is checked again. A guest has no membership: launch and the gateway accept only an active, unexpired guest access to that one app, always as `viewer`, whatever grants exist. Disabling sharing, removing a domain, shortening the maximum, ending a guest or disabling the app take effect on the next request; app sessions are revoked too. Guests cannot be emailed by apps and are named `guest` to the app (`x-boringcloud-user-kind`). Every invitation, acceptance, launch, refusal and end is audited, and the gateway records each person's requests, changes and refusals per day.
- IT access: an explicit per-member grant, independent of roles, console sessions only. Only owners grant it; grants and every IT change are audited.
- App files: one R2 prefix per app, computed from the trusted app id; keys are validated after decoding.
- Platform services (`packages/runtime/src/services.ts`): each one checked against the workspace stack (IT switch) and an atomic per-app daily counter before the call. Email goes only to pseudonymous app user ids resolved, at send time, to verified members who can open the app; one message per recipient, platform sender, app name in the subject; the app never learns addresses. Browser rendering of HTML blocks every network request of the page; URLs only when IT allows them, public https only. AI models are chosen by IT, not by the app. Job payloads ≤ 64 KB, delay ≤ 12 h, ≤ 4 attempts; schedules ≤ 10 per app, each at most every 15 minutes.
- Response sanitization: `Set-Cookie`, CSP/CORS/HSTS/Clear-Site-Data overrides dropped; cross-origin redirects blocked; `101` upgrades refused.
- Strict app CSP: `script-src 'self'` (no inline/eval/CDN), `connect-src 'self'`, `frame-src 'none'`, `worker-src 'none'` (no service workers), `frame-ancestors 'none'`, `form-action 'self'`, `base-uri 'none'`.
- Assets: canonical paths derived from validated request paths; content types from an allow-list; `nosniff`; `private, no-cache` so revocation also stops cached assets.
- Artifact validation: strict manifest (unknown fields rejected), per-file SHA-256 recomputed, sizes/counts capped, absolute/traversal/encoded/backslash/dotfile/duplicate/case-ambiguous/reserved paths rejected, content sniffing, no server-side archives or builds, symlinks rejected by the CLI.
- Automatic check of the code (`apps/control-plane/src/services/scan.ts`), on every release from the CLI, the API and MCP. A password or key in a well-known format refuses the release before anything is stored. Risky patterns (HTML or SQL built from text, `eval`) are reported without refusing. Findings give the rule, the file and the line; the value is never returned, stored or logged.
- Release pointer compare-and-swap; failed or partial deployments never become current; rollback only to a `ready`, retained release of the same app.
- IDOR: every read/write re-derives the workspace from the resource and checks membership; non-visible resources return `404`.
- Agent token scopes ∩ user access; tokens cannot create tokens, manage members or change app status.
- Last-owner protection; member removal revokes grants, tokens and app sessions.
- Rate limits (Workers Rate Limiting binding): auth attempts per IP, API calls per user, deploys per user, app requests per app+user. Quotas: apps/workspace, deploys/app/day, retained releases/app, body sizes.
- Logs: structured JSON with request/app/release ids; no tokens, cookies, tickets, payloads.
- Production config fails closed: no dev mail capture, no local runtime, https origins, separate registrable domain for apps, ≥ 32-char auth secret, no open signup.

### Residual risks (accepted for the beta, documented to customers)

- **Data sent to approved APIs.** An app allowed to use an API can send it any data the app can read. IT limits apps, methods and paths, but does not see or filter bodies.
- **Key echoes in unusual encodings.** An answer containing the key as is, URL-encoded, JSON-escaped or as basic credentials is blocked. A provider that returned it transformed in another way would not be detected.
- **Platform services carry app data.** An app can put any data it holds in a job payload (kept in the platform queue until processed), an email to its own users, a page it renders, or a prompt to Workers AI. With URLs allowed in browser rendering, an app can send data out in the query string of the address it renders. Email bodies are written by the app: an app's author could phish its own users within the daily limit; the subject prefix and footer name the app.
- **Prompt injection in app features.** Documents, images and pages that an app sends to AI can contain instructions. The platform gives the model no tools, so injected text can only change the answer, which the app must treat as data.
- **Guests see what the app shows them.** A guest is a `viewer`, which is not read-only: inside the app they can do whatever the code allows viewers to do, and see whatever it shows them. The platform tells the app who is a guest; hiding colleagues' data from guests is the app's job. The invitation goes to an address: whoever controls that mailbox can accept it. No second factor yet.
- **Owners can give themselves IT access.** This is deliberate (no lock-out) and audited.
- **Consent phishing.** Anyone can register an assistant with an https address and send a member its link. The page warns when it does not recognise the address, but a member who approves anyway gives that address their chosen permissions until the token is revoked.
- **The check of the code finds mistakes, not attackers.** It compares text with known patterns. An author who splits or encodes a key, or hides what the code does, passes. It does not see missing permission checks, unknown key formats, images and fonts, or the manifest. Most flaws give no finding, so a release without findings is not a safe release. Releases deployed before the check existed were not checked, and can still be rolled back to. Agents receive security rules, which are instructions and not a control. Isolation protects the platform and other apps; it does not protect an app's users from its own code.
- **Malicious authorized deployers.** Anyone with manager rights on an app controls its code and therefore all of its data. Platform access control limits who can _reach_ the app, not what the app does with data it legitimately holds.
- **Browser-side exfiltration.** CSP limits scripts and connections, but authorized users can always copy data out (screenshots, copy/paste, navigation to external links with data in the URL, downloads). CSP is not DLP. Sensitive/regulated workloads are prohibited in the beta.
- **Denial of wallet / noisy neighbours.** CPU/subrequest limits, rate limits and quotas bound most abuse; D1 storage per app (10 GB D1 cap) and rows read/written are not hard-capped per app in V1. Rate-limit counters are per Cloudflare location and approximate.
- **Data residency.** D1 jurisdiction can be configured per environment (`D1_JURISDICTION`); Workers execute globally. No residency guarantee in V1.
- **Account-level blast radius.** All tenants share one Cloudflare account per environment; compromise of the control plane or its API token is critical. Mitigations: separate staging/production accounts, least-privilege token, no user-controlled API calls.
- **Local development** is not an isolation boundary (only trusted fixtures run there).

### Deferred to V2

SSO/SAML/SCIM, hard per-app D1 storage quotas, Logpush/SIEM export, admin approval policies for sharing/deploys, malware scanning of assets, signed release provenance, customer-managed keys, per-app custom domains, Turnstile on sign-up.

## Abuse cases and where they are tested

The security test matrix is in `docs/testing.md` in the repository.
