Skip to content

Latest commit

 

History

History
347 lines (277 loc) · 18.1 KB

05-security-model.md

File metadata and controls

347 lines (277 loc) · 18.1 KB

05 · Security model

Part of The engineering behind AgentSwarms.

One sentence carries most of this chapter: the app process holds the service-role key. It can read and write every row belonging to every user, RLS bypassed. Every guard below exists because something untrusted might otherwise reach that process, or borrow its authority.

The second sentence: anything arriving from outside is data, never instruction. A swarm arrives as JSON from a stranger. A tool result is attacker-controllable text. A model can be talked into anything. None of those may become an executed decision without passing a guard written for that case.


Defence in depth, concretely

flowchart TD
    IN["Request"] --> A["Authentication<br/>session · internal secret · embed key · API key"]
    A --> B["Authorization<br/>RLS · IAM roles · model governance"]
    B --> C["Input guardrails<br/>length · injection patterns · PII · topics"]
    C --> D["Capability gating<br/>tool must exist AND be permitted"]
    D --> E["Egress guards<br/>SSRF · allowlisted hosts"]
    E --> F["Execution isolation<br/>Worker · container · never in-process"]
    F --> G["Output guardrails<br/>PII · citations · safety"]
    G --> H["Audit<br/>append-only trail"]
Loading

No single layer is trusted to be sufficient. RLS is the authority even though the app also filters; the SSRF guard resolves addresses even though the URL was validated; the sandbox holds no secrets even though callers are authenticated.


Row Level Security is the authority

Access control lives in Postgres policies, across 233 migrations in supabase/migrations/. The application's own checks are a second layer, not the first — a bug in a handler should fail closed at the database rather than leak rows.

This has one consequence that must be respected everywhere: the moment you reach for supabaseAdmin, RLS is gone and you own the scoping. The convention is to use it only where the system must act as itself rather than as the caller — writing an audit row a user must not be able to forge, reading a key row a user cannot see — and to say why in a comment.

The headless swarm executor is the hardest case: it has no session, so it runs under the service-role client with ctx.scopeUserId set, and every loader filters on that to mirror what RLS would have allowed. The invariant is that a scheduled run can never read more than the owner running it by hand.

Where that invariant had been lost

An audit of the agent tool layer found six reads that honoured RLS and nothing else. On the interactive path they were correct — ctx.sb carries the user's JWT, so a filter would have been redundant. On the headless path the same code ran under the service-role client, and each returned rows belonging to any tenant:

Read Reachable headlessly via What leaked
mcp_servers by name mcp_call_tool the row, including auth_token
mcp_servers connected list mcp_call_tool description other tenants' server names/endpoints
integrations (firecrawl) web_search, web_browse another tenant's Firecrawl key
integrations (n8n) tool offer + handler n8n endpoint and API token
data_warehouse_connections warehouse_query description connection names and providers
user_data_tables sql_query description table names and column schemas

The MCP pair is the serious one, because it composes: the listing supplied another tenant's server names, and the by-name lookup then returned that server's stored credential — so a swarm owned by one tenant could call another tenant's MCP server as them. A server name is a weak secret; github or jira is a guess, not a search.

Two things follow, and both are now enforced by tests:

  • Ownership-only tables (mcp_servers, integrations, data_warehouse_connections) go through one guard, ownedBy(ctx, query), which adds user_id = scopeUserId on the headless path and is a no-op on the RLS path.
  • Shared tables keep their sharing. user_data_tables is visible as own + public samples + IAM-granted, so it uses scopeToVisibleTables — the same predicate the sql_query loader uses, now defined once. Narrowing it to user_id would have been "secure" and would also have hidden sample and shared datasets the agent is entitled to query: a security fix that silently removes a feature is still a regression.

The lesson generalises: these queries were not wrong for the path they were written on. They were wrong for the other one, and nothing in the type system distinguishes the two clients.


SSRF: the guard with two tiers

src/utils/ssrfGuard.server.ts protects every server-side fetch of a URL that a user or a model supplied. The swarm http node takes a URL the user authored; web_browse takes one the model chose, reachable by prompt injection, including through a public embed. All of them run inside the deployment's network.

The policy is deliberately two-tier, and the reasoning is worth reproducing because most SSRF guards get this wrong in one direction or the other:

Always refused, unconditionally. Link-local, cloud-metadata, unspecified and multicast addresses. 169.254.169.254 — the AWS/GCP/Azure/OCI instance metadata endpoint — can hand out the host's IAM credentials and has no legitimate use as a fetch target, so nothing can enable it. The ranges are whole: all of IPv6 link-local fe80::/10 and multicast ff00::/8, and an IPv4 address carried inside IPv6 — IPv4-mapped ::ffff:, IPv4-compatible ::, NAT64 64:ff9b:: and 6to4 2002:: — is judged as that IPv4 address (behind a NAT64 gateway, 64:ff9b::a9fe:a9fe is the metadata endpoint).

Allowed by default. Ordinary private networks: localhost, RFC1918, CGNAT, IPv6 ULA. This is a self-hostable product, and self-hosted model servers (Ollama, vLLM), in-cluster MCP servers and self-hosted n8n all live there. Refusing them by default would break the primary use case to defend against a threat most operators do not have. Those who do — untrusted multi-tenant, public embeds — set BLOCK_PRIVATE_NETWORK_FETCH=true.

Two implementation details do the actual work: the hostname is resolved and every resulting IP is checked, not just the literal in the URL; and redirects are followed manually, so a public URL cannot 302 into a blocked range.

A name that does not resolve is refused, not waved through: a resolver that fails the check's query and answers the connection's with 169.254.169.254 used to walk past the guard. The refusal is a network failure (HostNotResolvedError, the resolver's own code), so it is retried like one and reads "its host name does not resolve". The exception is a hop that leaves through HTTPS_PROXY / HTTP_PROXY, because the proxy resolves the name, not this server.

DNS rebinding is closed for direct connections. safeFetch hands fetch() a dispatcher whose lookup answers with the addresses the check just accepted, so the connection cannot be sent anywhere else; the Host header and TLS name stay the URL's. Residual: a hop through the proxy (the proxy resolves it — filter there), and URLs another program fetches after the check — DuckDB reading an object store or an Iceberg catalog, a scraping service behind web_browse — cannot be pinned from here. Egress rules are the control for those.


HTTP security headers

serverSecurityHeaders.mjs, the outermost middleware in server.mjs, gives every response — static files, pages and API routes — X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin and a Content-Security-Policy, and HSTS when the browser came over HTTPS (directly or per X-Forwarded-Proto). Until R396 it set none, so any site could frame a signed-in page under a decoy.

Framing is decided per page. App pages send frame-ancestors 'self' and X-Frame-Options: SAMEORIGIN. The embed pages (/embed/…) and published dashboards (/share/bi/…) are meant to be framed by other sites, so they send neither, unless EMBED_FRAME_ANCESTORS names the sites; an embed key's domain allow-list still decides what they show. The prefix match keeps its slash: /embeds, the signed-in page that manages keys, is not frameable.

Scripts: the app's own, and nonced ones (R397). The default policy is object-src 'none'; base-uri 'self'; form-action 'self'; script-src 'self' 'nonce-…': no 'unsafe-inline', no 'unsafe-eval', no 'wasm-unsafe-eval'. The middleware makes a 128-bit nonce for each response and runs the request inside an AsyncLocalStorage it parks on globalThis. getRouter() reads the nonce from there (src/lib/cspNonce.ts) into the router's ssr.nonce, so TanStack stamps it on every inline script it renders: hydration, streamed chunks, head scripts, and <meta property="csp-nonce">. The client router reads that meta tag back. So does the consent banner, whose analytics tags carry it. The theme boot script goes through ScriptOnce, which takes the router's nonce. The service-worker registration became an effect, and offline.html lost its inline onclick. In an operator's own policy, {nonce} stands for the nonce.

Two code paths compile code by design, and both are workers. A worker loaded from a URL takes the policy of its own response, so each gets one:

  • DuckDB-WASM's engine (/assets/duckdb-browser-*.worker-<hash>.js): script-src 'self' 'wasm-unsafe-eval' replaces the page's script-src (when the policy restricts scripts at all); every other directive still applies.
  • The swarm function node's sandbox (/sandbox/function-node.js): default-src 'none'; script-src 'unsafe-eval', fixed. It may compile the snippet and reach nothing. It used to be a blob: worker, which takes the PAGE's policy; that would have refused the snippet outright, and with no policy it let a snippet import() a module from anywhere, a way out that deleting fetch never closed.

Nothing else needs eval. Zod 4 probes new Function("") to decide whether to compile its parsers; src/lib/zodNoEval.ts sets jitless first, because Zod reads it when a schema is built, and package.json lists it under sideEffects so the bundler keeps it. pdf.js is called with isEvalSupported: false. The Function("return this") fallbacks in lodash and underscore, the setImmediate string form in exceljs and pptxgen, and regenerator's strict-mode fallback are never reached in a browser.

MEASURED before enforcing: a report-only trial on the live instance walked thirteen pages, among them the Lakehouse, Data Catalog with the in-browser engine, BI, Sheets, Agent Chat, swarms and two embeds. Every report was Zod's probe, one per page load. Then enforced, the same walk ran clean. A blocked inline tag your proxy injects, for example, is fixed in CONTENT_SECURITY_POLICY. Setting it to the three R396 directives removes the script-src again.


Prompt injection, and where the line is

The honest position is that prompt injection is not solved here or anywhere. What the design does is make a successful injection unable to do much:

  • The model never holds a credential. Tools run server-side under the caller's scope. Convincing the model to "use the admin key" fails because there is no key in its context to use.
  • Tool availability is gated on capability. A sql_query tool is not offered when no warehouse connection exists, so it cannot be argued into existence.
  • URLs the model chooses go through the SSRF guard, which is why web_browse cannot be talked into reading cloud metadata.
  • Embeds hard-disable workspace tools. The anonymous surface has the smallest reachable capability set in the product.
  • Input guardrails carry a pattern denylist (src/utils/guardrails.ts) — useful, and explicitly not a boundary.

What a tool allowlist does and does not do

An API key for a hosted MCP server carries a tool_allowlist. It is worth being exact about its scope, because it is easy to over-read.

The check in src/routes/api/mcp.s.$slug.ts is a name check — the requested tool must be in the list. It does not inspect arguments. Once run_query is approved for a key, that key may call run_query with any argument the tool's own schema accepts.

The tool fingerprint is a separate control for a separate attack. Tool names, descriptions and schemas are instructions the calling model reads, so a server that quietly changes them after being trusted is the "rug pull" MCP's security guidance calls out. A redeploy that moves the fingerprint parks the server until a human approves the diff.

Neither is argument-level policy. Between those two and dispatch sit: the IP and origin allowlists, a JSON-RPC method forward list, per-key rate limiting and per-server concurrency, a body-size cap, and then FastMCP/pydantic validating argument types against the declared schema. Past that the model is containment rather than prevention — own container, secrets only in that process, default-deny egress.


Credentials

Provider credentials are stored encrypted and decrypted server-side at call time (src/utils/providers/crypto.server.ts). They never reach the client, and src/utils/providers/credentials.server.ts carries a one-line warning against importing it from client code — enforced by convention, so read it before you add an import.

The internal shared secret used for server→own-API calls is compared in constant time, and the origin those calls target is resolved only from configuration, never from request.url, because that reflects the client's Host header. A spoofed Host: would otherwise make the server POST its own secret to an attacker. See Request lifecycle.

.gitignore covers .env backups — .env.cloud.bak, .env.production.backup, .env.old.copy — because those hold the same service-role and provider keys as .env itself and sat one git add -A from being committed.


The Spark Connect endpoint

A Spark-engine pipeline runs arbitrary code on the driver, and the Compose spark-connect server sits on nb-internal — the same internal network as the notebook kernels. Two properties keep that from being a way in:

  • It authenticates. The server enforces a pre-shared token (SPARK_CONNECT_AUTHENTICATE_TOKEN, wired from SPARK_CONNECT_TOKEN, which setup.sh generates). The app hands the same token to every governed run, so a kernel that reaches the port without it is refused UNAUTHENTICATED. The token is held only server-side and in the run's own environment, scrubbed from logs like any other secret — never in the stored URL unless an operator put it there for a managed cluster.
  • The driver is not root. The container starts as root only long enough to chown the first-boot jar cache, then drops the JVM to the unprivileged spark user (uid 185) via gosu; the per-run Kubernetes driver pods are runAsNonRoot for the same reason. So code running on the driver cannot act as root inside the container.

The client wrinkle worth recording: gRPC refuses to attach a bearer token over an insecure channel unless the host is localhost, and this endpoint is reached by service name over plaintext (gRPC cannot traverse the HTTP egress proxy). The generated program therefore carries a custom Spark Connect channel that adds the token as request metadata on an insecure channel — the one channel it actually has. A managed endpoint reached over TLS uses the stock client's own token path instead. Leaving SPARK_CONNECT_TOKEN empty disables the requirement, for an endpoint that authenticates its callers some other way.


Generated code is an injection surface

The agent and swarm exporters turn a saved graph into a Python or TypeScript file the user is told to run. A swarm can arrive from anyone as a dropped .swarm.json that is one click from the export menu, which makes every interpolated value untrusted.

Three classes were closed there, and they generalise to any code generator:

  1. Numeric fields are coerced, not pasted. A temperature interpolated bare is an expression slot.
  2. Labels are sanitised before reaching docstrings, where a crafted string can close the comment and continue as code.
  3. Tool configs are redacted, not serialised — an export used to carry a plaintext api_key.

Auditing

The audit log's whole purpose is evidence, which makes it the worst possible place for a failed read to render as an empty state. It was: a discarded error produced a page that manufactured evidence of absence. Both findings there were fixed with the injection positively confirmed rather than assumed — see docs/ADVERSARIAL_LOG.md, which records where the audit looked as carefully as what it found.


Known weak points

Stated because an unstated limit is worse than a known one:

  • DNS rebinding where the guard cannot pin the connection: proxied hops and URLs fetched by DuckDB or a scraping service, above.
  • The ADMIN_EMAIL bootstrap under autoconfirm. With email confirmations disabled, Supabase stamps email_confirmed_at for everyone, so the operator and an attacker present identical evidence — possession of a string. The fix is configuration; see Request lifecycle.
  • Egress filtering is instance-wide, not per-sandbox.
  • No argument-level policy in front of MCP dispatch, as above.
  • Approval nodes auto-decide on headless runs, so an approval gate is not a safety gate on the scheduled path.
  • The Spark Connect token is per deployment, not per run. Anyone allowed to run a Spark-engine pipeline can read it inside that run. The per-run Kubernetes drivers carry none: their NetworkPolicy admits any sandbox, and an unguessable service name is the only separation.

Next: 06 · Scale and concurrency.