skip to content

In Cloudflare's Agents SDK the instance name comes from the request URL; how do you stop one customer from connecting to another customer's support agent?

level: seniorimportance: should knowfreq 22%

answer

  1. addressing is not authorisation
  2. hooks before routing
  3. derive the name server-side
  4. short-lived token in the query
  5. guard state and callables

basics

~10 s

Authenticate before routing with routeAgentRequest()'s onBeforeConnect and onBeforeRequest hooks and check the caller owns the named instance, or derive the name from the session and forward with getAgentByName(). Then guard state and callable methods.

solid answer

~40 s

`routeAgentRequest()` trusts the path, so `/agents/support-agent/customer-7` reaches customer 7's agent for whoever asks. Add `onBeforeConnect` (WebSocket) and `onBeforeRequest` (HTTP) hooks that verify a credential and that the user owns the instance in the path, returning a 401 or 403 `Response` otherwise. Better, let the client connect to a fixed `basePath` and have the Worker derive the name from the session and forward with `getAgentByName(...)` and `agent.fetch(request)`. Browsers cannot set an `Authorization` header on a WebSocket upgrade, so use a same-origin HTTP-only cookie or a short-lived signed token in `useAgent()`'s `query`. Then limit authorised clients: `validateStateChange()` rejects client pushes to server-owned fields, `shouldConnectionBeReadonly()` makes viewers read-only, and every `@callable()` checks its caller.

code

typescript · 23 lines
typescript
import { routeAgentRequest } from "agents";

export default {
  async fetch(request: Request, env: Env) {
    const reject = async (req: Request) => {
      const token = new URL(req.url).searchParams.get("token");
      const user = await verifyShortLivedToken(token, env); // your signed-token check
      if (!user) return new Response("Unauthorized", { status: 401 });
      const instance = new URL(req.url).pathname.split("/")[3];
      if (instance !== `customer-${user.id}`) {
        return new Response("Forbidden", { status: 403 });
      }
      // returning nothing lets the request continue to the agent
    };

    return (
      (await routeAgentRequest(request, env, {
        onBeforeConnect: reject,
        onBeforeRequest: reject,
      })) ?? new Response("Not found", { status: 404 })
    );
  },
} satisfies ExportedHandler<Env>;

go deeper

for a junior

Recall that the instance name in /agents/{class}/{name} is an address that routeAgentRequest() trusts, so access needs its own check.

for a middle

Explain the onBeforeConnect and onBeforeRequest hooks, and why WebSocket clients pass a short-lived token in the query or a same-origin cookie.

for a senior

Show the full defence: ownership check or server-derived names, validateStateChange(), read-only connections and caller checks inside every callable, plus tests that prove each.

for a principal

Decide whether clients may ever name instances, since server-derived naming removes a whole class of access bugs at the cost of custom routing code.

## Why this is a real risk With Cloudflare's Agents SDK, `routeAgentRequest()` takes the instance name straight from the URL: `/agents/support-agent/customer-42`. That name selects a Durable Object with that customer's state, history and schedules. If the Worker routes every `/agents/...` request without checking who sent it, then anyone who can reach the Worker and guess or observe another name can: - open a WebSocket to that agent and receive its **state broadcasts**; - call its **`@callable()` methods**, which any connected client can invoke; - push state with **`setState()`** from the client, which the agent accepts unless you guard it. Customer names are often guessable (sequential IDs, emails), and they appear in URLs and logs. Routing is addressing, not authorisation, so the check has to be added. ## Layer 1: authenticate before routing `routeAgentRequest(request, env, options)` accepts hooks that run before the request reaches any agent: | Hook | Runs before | Return a `Response` to | | --- | --- | --- | | `onBeforeConnect(req, lobby)` | WebSocket connections | reject the upgrade | | `onBeforeRequest(req, lobby)` | plain HTTP requests | reject the request | Returning nothing lets the request continue; returning a `Request` replaces it. Authenticating is only half the job: the hook must also confirm that the authenticated user **owns** the instance named in the path, for example that the path's instance equals `customer-${user.id}`. ## Layer 2: do not let the client choose the name The stronger design takes the name out of the client's hands: 1. The client connects to a fixed path with `useAgent({ agent: "SupportAgent", basePath: "support" })`. 2. The Worker authenticates the session, derives the instance name from it, and forwards with `getAgentByName(env.SupportAgent, name)` followed by `agent.fetch(request)`. 3. There is then no URL a customer can edit to reach someone else's agent. If the names themselves are sensitive, set `static options = { sendIdentityOnConnect: false }` so the agent stops sending its instance name to clients on connect. That hides the name; it does not authenticate anyone. ## Getting a credential onto a WebSocket Browsers cannot attach custom headers, such as an `Authorization` bearer token, to a WebSocket upgrade. The SDK's guidance: - **Same origin**: the browser sends cookies on the handshake, so an HTTP-only session cookie works. - **Cross origin**: pass a **short-lived signed token** through `useAgent()`'s `query` option, ideally as an async function so a fresh token is fetched before each connect; the query cache is invalidated on disconnect, so a reconnect refetches it. - Never put a long-lived secret in the URL, since URLs end up in logs. ## Layer 3: limit what an authorised client can do Even the right customer should not be able to rewrite everything: - **`validateStateChange(next, source)`** runs before a state change is saved or broadcast and can throw, so a client cannot change a ticket's status or another field it does not own. - **`shouldConnectionBeReadonly(connection, ctx)`** marks a connection read-only when it opens, for example a supervisor's view; such a client receives state but cannot change it, directly or through a callable that calls `setState()`. - Treat every **`@callable()`** method as a public endpoint: check the caller inside it with `getCurrentAgent()`, which exposes the current connection. ## How to verify it A defender's checklist for review: 1. Connect as customer A to customer B's path; the upgrade must be refused. 2. Connect without a token, and with an expired one; both must fail. 3. As a legitimate customer, push a state change to a field the server owns; `validateStateChange()` must reject it. 4. Open a read-only connection and call a mutating callable; it must fail. 5. Grep for `routeAgentRequest(request, env)` with no options in front of agents that hold personal data. ## Putting the layers together No single control is enough on its own. The hooks stop strangers, server-side naming stops customers from wandering into each other's agents, and the state and callable guards stop a legitimate customer from changing what only the agent should change. A review that finds one layer missing should ask which attack the remaining layers still stop, and an agent that holds personal data should have all three. The same applies to HTTP endpoints an agent serves through `onRequest()`: they pass through `onBeforeRequest`, and they need the same ownership check as the WebSocket path.

  • Why is checking the token alone, without comparing it to the instance name, not enough?
    A valid token proves who the caller is, not which agent they may open. Customer A with a valid token could still connect to `/agents/support-agent/customer-7`. The hook must compare the authenticated user with the instance in the path, or the Worker must choose the instance from the session itself.
  • What does sendIdentityOnConnect: false protect against, and what does it not?
    It stops the agent from sending its agent and instance name to clients on connect, which matters when names carry user IDs or session IDs. It does not authenticate or authorise anything; a caller who already knows a name can still connect unless the routing hooks or server-side naming stop them.

  • Assuming an unguessable-looking instance name is enough access control.
  • Sending an Authorization header on the WebSocket upgrade from the browser.
  • Verifying the token but never comparing the user with the instance in the path.
  • Believing sendIdentityOnConnect: false blocks unauthorised connections.
  • Treating @callable() methods as internal because only the app's own UI calls them.
  • Putting a long-lived API key in the useAgent() query string.