From b342c0b22279a3c7d25798b55bb11a55794f8136 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 12 Oct 2026 11:33:54 +0200 Subject: [PATCH 1/7] feat(proxy): authenticate option sets each caller's tenant createDaemonProxy accepts authenticate(request) in place of clientToken. The proxy sends every forwarded request as the returned tenant with tenant session isolation, confines request diagnostics to that tenant's sessions, and puts the caller's own credential on upload tickets. --- packages/proxy/README.md | 28 ++++- packages/proxy/src/daemon-proxy.test.ts | 160 ++++++++++++++++++++++++ packages/proxy/src/daemon-proxy.ts | 149 +++++++++++++++++++--- packages/proxy/src/index.ts | 1 + website/docs/docs/remote-proxy.md | 2 + 5 files changed, 320 insertions(+), 20 deletions(-) diff --git a/packages/proxy/README.md b/packages/proxy/README.md index 94e2700fdc..1542567b9d 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -5,7 +5,8 @@ The proxy behind `agent-device proxy`, as a library. Embed it in your own gatewa The proxy: -- authenticates clients with a token you choose, and never exposes the daemon's own token; +- authenticates clients with a token you choose, or with your own check, and never exposes the + daemon's own token; - forwards only the routes a remote client needs: `/health`, `/rpc`, uploads, artifacts, and request diagnostics; - refuses install sources that name a file on the daemon host; @@ -89,13 +90,36 @@ const proxy = createDaemonProxy({ `upstreamFetch` receives a `Request` addressed to `upstreamBaseUrl` and must resolve with the daemon's `Response`. Abort the exchange when `request.signal` aborts. +### Authenticate each client yourself + +One `clientToken` is shared by every client. To give each client its own credential, pass +`authenticate` instead. It receives each client request (with its JSON body on `/rpc`) and returns +the tenant the client acts as, or `null` to refuse it with a 401: + +```ts +const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://127.0.0.1:4310', + upstreamToken: daemonToken, + authenticate: async (request) => { + const account = await accounts.findByApiKey(request.headers.get('authorization')); + return account ? { tenantId: account.id } : null; + }, +}); +``` + +The proxy then sends every request to the daemon as that tenant, whatever tenant the client named, +and isolates its sessions from other tenants' sessions. A tenant id is 1-128 letters, numbers, dots, +underscores or hyphens. Upload tickets carry the client's own `authorization` or +`x-agent-device-token` header, so the upload is authenticated the same way. + ## Options | Option | Default | Meaning | | --- | --- | --- | | `upstreamBaseUrl` | required | Base URL of the daemon's HTTP server. | | `upstreamToken` | required | The daemon's auth token. | -| `clientToken` | required | Token clients must send as their daemon auth token. | +| `clientToken` | required without `authenticate` | Token clients must send as their daemon auth token. | +| `authenticate` | none | Authenticates each client and names its tenant; replaces `clientToken`. | | `upstreamFetch` | global `fetch` | Sends one request to the daemon. | | `maxRpcBodyBytes` | 1 MiB | Larger `/rpc` bodies get a 400 response. | | `upstreamTimeoutMs` | 5 minutes | Longest time one daemon request may take, including its body. | diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index 72178e8484..2073495f0a 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -177,3 +177,163 @@ test('an unsupported route answers a bare 404 without reaching the daemon', asyn expect(response.headers.get('content-type')).toBeNull(); expect(upstream.requests).toHaveLength(0); }); + +function proxyAuthenticatingWith(upstreamFetch: DaemonProxyUpstreamFetch) { + const seen: Request[] = []; + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch, + authenticate: async (request) => { + seen.push(request); + const token = request.headers.get('authorization'); + if (token === 'Bearer alice-key') return { tenantId: 'alice' }; + if (token === 'Bearer bob-key') return { tenantId: 'bob' }; + return null; + }, + }); + return { proxy, seen }; +} + +function forwardedParams(request: Request | undefined): Promise> { + return request!.json().then((body) => (body as { params: Record }).params); +} + +test('authenticate refuses a caller it returns null for with the unauthorized rpc envelope', async () => { + const upstream = recordingUpstream(() => Response.json({})); + const { proxy } = proxyAuthenticatingWith(upstream.fetch); + + const response = await proxy.handle( + rpcRequest( + { jsonrpc: '2.0', id: 9, method: 'agent-device.command' }, + { + headers: { authorization: 'Bearer client-secret' }, + }, + ), + ); + + expect(response.status).toBe(401); + expect(await response.json()).toMatchObject({ + id: 9, + error: { code: -32001, data: { code: 'UNAUTHORIZED' } }, + }); + expect(upstream.requests).toHaveLength(0); +}); + +test('authenticate sees the rpc body and its tenant overwrites the tenant a command declares', async () => { + const upstream = recordingUpstream(() => Response.json({ jsonrpc: '2.0', id: 1, result: {} })); + const { proxy, seen } = proxyAuthenticatingWith(upstream.fetch); + + const response = await proxy.handle( + rpcRequest( + { + jsonrpc: '2.0', + id: 1, + method: 'agent-device.command', + params: { + command: 'devices', + flags: { tenant: 'bob', sessionIsolation: 'none' }, + meta: { tenantId: 'bob', sessionIsolation: 'none', requestId: 'r1' }, + }, + }, + { headers: { authorization: 'Bearer alice-key' } }, + ), + ); + + expect(response.status).toBe(200); + expect((await forwardedParams(seen[0])).command).toBe('devices'); + const params = await forwardedParams(upstream.requests[0]); + expect(params.meta).toEqual({ tenantId: 'alice', sessionIsolation: 'tenant', requestId: 'r1' }); + expect(params.flags).toEqual({ tenant: 'alice', sessionIsolation: 'tenant' }); + expect(params.token).toBe('daemon-secret'); +}); + +test('authenticate tenant overwrites the tenant a lease call declares', async () => { + const upstream = recordingUpstream(() => Response.json({ jsonrpc: '2.0', id: 1, result: {} })); + const { proxy } = proxyAuthenticatingWith(upstream.fetch); + + await proxy.handle( + rpcRequest( + { + jsonrpc: '2.0', + id: 1, + method: 'agent_device.lease.allocate', + params: { tenantId: 'bob', runId: 'run-1' }, + }, + { headers: { authorization: 'Bearer alice-key' } }, + ), + ); + + expect((await forwardedParams(upstream.requests[0])).tenantId).toBe('alice'); +}); + +test('authenticate tenant replaces the tenant header a client sends on artifact routes', async () => { + const upstream = recordingUpstream(() => Response.json({ artifacts: [] })); + const { proxy } = proxyAuthenticatingWith(upstream.fetch); + + await proxy.handle( + new Request(`${PROXY_ORIGIN}/agent-device/artifacts`, { + headers: { authorization: 'Bearer alice-key', 'x-agent-device-tenant': 'bob' }, + }), + ); + + expect(upstream.requests[0]?.headers.get('x-agent-device-tenant')).toBe('alice'); +}); + +test('with authenticate, upload tickets carry the caller credential', async () => { + const upstream = recordingUpstream(() => + Response.json({ + ok: true, + upload: { url: 'http://127.0.0.1:4310/upload/direct/abc', headers: { 'x-extra': '1' } }, + }), + ); + const { proxy } = proxyAuthenticatingWith(upstream.fetch); + + const response = await proxy.handle( + new Request(`${PROXY_ORIGIN}/agent-device/upload/preflight`, { + method: 'POST', + headers: { authorization: 'Bearer bob-key' }, + body: '{}', + }), + ); + + const payload = (await response.json()) as { upload: { headers: Record } }; + expect(payload.upload.headers).toEqual({ 'x-extra': '1', authorization: 'Bearer bob-key' }); +}); + +test('with authenticate, request diagnostics are served only for the caller tenant sessions', async () => { + const upstream = recordingUpstream(() => Response.json({ ok: true })); + const { proxy } = proxyAuthenticatingWith(upstream.fetch); + const diagnostics = (session: string) => + proxy.handle( + new Request( + `${PROXY_ORIGIN}/agent-device/sessions/${encodeURIComponent(session)}/requests/r1/diagnostics`, + { headers: { authorization: 'Bearer alice-key' } }, + ), + ); + + const other = await diagnostics('bob:default'); + const own = await diagnostics('alice:default'); + + expect(other.status).toBe(401); + expect(own.status).toBe(200); + expect(upstream.requests).toHaveLength(1); +}); + +test('without authenticate, the tenant a client declares is forwarded unchanged', async () => { + const upstream = recordingUpstream(() => Response.json({ jsonrpc: '2.0', id: 1, result: {} })); + const proxy = proxyWith(upstream.fetch); + + await proxy.handle( + rpcRequest({ + jsonrpc: '2.0', + id: 1, + method: 'agent-device.command', + params: { command: 'devices', meta: { tenantId: 'bob' } }, + }), + ); + + const params = await forwardedParams(upstream.requests[0]); + expect(params.meta).toEqual({ tenantId: 'bob' }); + expect(params.tenantId).toBeUndefined(); +}); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 5314c08e75..7fcdff3689 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -27,17 +27,37 @@ import { */ export type DaemonProxyUpstreamFetch = (request: Request) => Promise; +/** + * Authenticates one client request and names the tenant it acts as, or returns `null` to refuse + * it. The request carries the client's headers and, for `/rpc`, its JSON body. + */ +export type DaemonProxyAuthenticate = ( + request: Request, +) => Promise<{ tenantId: string } | null> | { tenantId: string } | null; + export type DaemonProxyOptions = { /** Base URL of the upstream agent-device daemon HTTP server. */ upstreamBaseUrl: string; /** Auth token of the upstream daemon. Never leaves the proxy. */ upstreamToken: string; - /** Token proxy clients must present as their daemon auth token. */ - clientToken: string; maxRpcBodyBytes?: number; upstreamTimeoutMs?: number; upstreamFetch?: DaemonProxyUpstreamFetch; -}; +} & ( + | { + /** Token proxy clients must present as their daemon auth token. */ + clientToken: string; + authenticate?: undefined; + } + | { + clientToken?: undefined; + /** + * Replaces the `clientToken` check. Every forwarded request acts as the returned tenant, + * with its sessions isolated from other tenants. + */ + authenticate: DaemonProxyAuthenticate; + } +); export type DaemonProxy = { /** Identifies this proxy instance in its health payload, so clients notice a restart. */ @@ -51,7 +71,18 @@ export type DaemonProxy = { handle(request: Request): Promise; }; -type NormalizedProxyOptions = Required; +type NormalizedProxyOptions = { + upstreamBaseUrl: string; + upstreamToken: string; + clientToken: string | undefined; + authenticate: DaemonProxyAuthenticate | undefined; + maxRpcBodyBytes: number; + upstreamTimeoutMs: number; + upstreamFetch: DaemonProxyUpstreamFetch; +}; + +/** The client a request was authenticated as; `tenantId` is set only by `authenticate`. */ +type ProxyCaller = { tenantId?: string }; const DEFAULT_MAX_RPC_BODY_BYTES = 1024 * 1024; const DEFAULT_UPSTREAM_TIMEOUT_MS = 5 * 60 * 1000; @@ -125,9 +156,16 @@ async function handleProxyRequest( ); } - if (!isAuthorized(request, options.clientToken, rpcBody)) { + const caller = await authenticateCaller(request, options, rpcBody); + if (!caller) { return unauthorizedResponse(route, readJsonRpcId(rpcBody)); } + if (caller.tenantId && !isRouteWithinTenant(route, caller.tenantId)) { + return Response.json( + { ok: false, error: 'Session is outside this tenant', code: 'UNAUTHORIZED' }, + { status: 401 }, + ); + } const staleInstance = refuseStaleProxyInstance( request, @@ -141,7 +179,44 @@ async function handleProxyRequest( return hostPathInstallSourceRefusedResponse(readJsonRpcId(rpcBody)); } - return await forwardProxyRequest({ request, route, options, rpcBody }); + return await forwardProxyRequest({ request, route, options, rpcBody, caller }); +} + +async function authenticateCaller( + request: Request, + options: NormalizedProxyOptions, + rpcBody: string | undefined, +): Promise { + if (!options.authenticate) { + return isAuthorized(request, options.clientToken ?? '', rpcBody) ? {} : null; + } + const result = await options.authenticate( + new Request(request.url, { + method: request.method, + headers: request.headers, + signal: request.signal, + ...(rpcBody !== undefined ? { body: rpcBody } : {}), + }), + ); + if (!result) return null; + const tenantId = typeof result.tenantId === 'string' ? result.tenantId.trim() : ''; + if (!tenantId) { + throw new AppError('COMMAND_FAILED', 'Proxy authenticate returned no tenantId'); + } + return { tenantId }; +} + +/** + * The daemon does not partition a tenant it did not attest itself, so the proxy confines the + * diagnostics route to the sessions the daemon named beneath `:`. Other routes pass. + */ +function isRouteWithinTenant(route: string, tenantId: string): boolean { + if (!isRequestDiagnosticsRoute(route)) return true; + try { + return decodeURIComponent(route.split('/')[2] ?? '').startsWith(`${tenantId}:`); + } catch { + return false; + } } async function proxyHealthResponse( @@ -187,13 +262,14 @@ async function forwardProxyRequest(params: { route: string; options: NormalizedProxyOptions; rpcBody?: string; + caller: ProxyCaller; }): Promise { - const { request, route, options, rpcBody } = params; - const body = resolveUpstreamBody(request, route, rpcBody, options.upstreamToken); + const { request, route, options, rpcBody, caller } = params; + const body = resolveUpstreamBody(request, route, rpcBody, options.upstreamToken, caller.tenantId); const upstreamResponse = await options.upstreamFetch( new Request(buildUpstreamUrl(options.upstreamBaseUrl, route, request.url), { method: request.method, - headers: buildUpstreamHeaders(request.headers, options.upstreamToken, route), + headers: buildUpstreamHeaders(request.headers, options.upstreamToken, route, caller.tenantId), signal: upstreamSignal(request, options), ...(body ? { body, duplex: 'half' as const } : {}), }), @@ -205,7 +281,9 @@ async function forwardProxyRequest(params: { request, upstreamResponse, headers, - clientToken: options.clientToken, + ticketAuthHeaders: options.authenticate + ? readClientAuthHeaders(request.headers) + : buildDaemonHttpAuthHeaders(options.clientToken), }); } return new Response(upstreamResponse.body, { status: upstreamResponse.status, headers }); @@ -233,12 +311,12 @@ async function rewrittenUploadPreflightResponse(params: { request: Request; upstreamResponse: Response; headers: Headers; - clientToken: string; + ticketAuthHeaders: Record; }): Promise { - const { request, upstreamResponse, headers, clientToken } = params; + const { request, upstreamResponse, headers, ticketAuthHeaders } = params; const text = await upstreamResponse.text(); headers.set('content-type', upstreamResponse.headers.get('content-type') ?? 'application/json'); - return new Response(rewriteUploadPreflightResponse(text, request, clientToken), { + return new Response(rewriteUploadPreflightResponse(text, request, ticketAuthHeaders), { status: upstreamResponse.status, headers, }); @@ -247,7 +325,7 @@ async function rewrittenUploadPreflightResponse(params: { function rewriteUploadPreflightResponse( body: string, request: Request, - clientToken: string, + ticketAuthHeaders: Record, ): string { let parsed: unknown; try { @@ -269,7 +347,7 @@ function rewriteUploadPreflightResponse( record.upload.headers && typeof record.upload.headers === 'object' ? { ...(record.upload.headers as Record) } : {}; - Object.assign(headers, buildDaemonHttpAuthHeaders(clientToken)); + Object.assign(headers, ticketAuthHeaders); return JSON.stringify({ ...(parsed as Record), @@ -281,6 +359,16 @@ function rewriteUploadPreflightResponse( }); } +/** The client's own credential, so its upload ticket authenticates as the client did. */ +function readClientAuthHeaders(requestHeaders: Headers): Record { + const headers: Record = {}; + for (const name of ['authorization', 'x-agent-device-token']) { + const value = requestHeaders.get(name); + if (value !== null) headers[name] = value; + } + return headers; +} + function rewriteUploadDirectUrl(upstreamUrl: string, request: Request): string | null { let parsed: URL; try { @@ -308,11 +396,14 @@ function rewriteUploadDirectUrl(upstreamUrl: string, request: Request): string | function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOptions { const upstreamBaseUrl = normalizeBaseUrl(options.upstreamBaseUrl, 'upstreamBaseUrl'); const upstreamToken = normalizeToken(options.upstreamToken, 'upstreamToken'); - const clientToken = normalizeToken(options.clientToken, 'clientToken'); + const clientToken = options.authenticate + ? undefined + : normalizeToken(options.clientToken ?? '', 'clientToken'); return { upstreamBaseUrl, upstreamToken, clientToken, + authenticate: options.authenticate, maxRpcBodyBytes: options.maxRpcBodyBytes ?? DEFAULT_MAX_RPC_BODY_BYTES, upstreamTimeoutMs: options.upstreamTimeoutMs ?? DEFAULT_UPSTREAM_TIMEOUT_MS, upstreamFetch: options.upstreamFetch ?? ((request) => fetch(request)), @@ -403,12 +494,14 @@ function buildUpstreamHeaders( requestHeaders: Headers, upstreamToken: string, route: string, + tenantId?: string, ): Headers { const headers = new Headers(); for (const name of FORWARDED_REQUEST_HEADERS) { const value = requestHeaders.get(name); if (value?.trim()) headers.set(name, value); } + if (tenantId) headers.set(DAEMON_HTTP_TENANT_HEADER, tenantId); if (route === '/rpc' && !headers.has('content-type')) { headers.set('content-type', 'application/json'); } @@ -431,9 +524,10 @@ function resolveUpstreamBody( route: string, rpcBody: string | undefined, upstreamToken: string, + tenantId: string | undefined, ): BodyInit | null { if (request.method === 'GET' || request.method === 'HEAD') return null; - if (route === '/rpc') return rewriteRpcToken(rpcBody ?? '', upstreamToken); + if (route === '/rpc') return rewriteRpcParams(rpcBody ?? '', upstreamToken, tenantId); return request.body; } @@ -478,15 +572,34 @@ function resolveRequestToken(request: Request, rpcBody: string | undefined): str return ''; } -function rewriteRpcToken(body: string, upstreamToken: string): string { +function rewriteRpcParams(body: string, upstreamToken: string, tenantId?: string): string { const parsed = JSON.parse(body) as { params?: Record }; parsed.params = { ...(parsed.params ?? {}), token: upstreamToken, }; + if (tenantId) stampRpcTenant(parsed.params, tenantId); return JSON.stringify(parsed); } +/** + * Sets the tenant everywhere the daemon reads it — `meta` for commands, `tenantId` for lease + * calls — with tenant session isolation, overwriting whatever the client sent. + */ +function stampRpcTenant(params: Record, tenantId: string): void { + params.tenantId = tenantId; + params.meta = { ...asRecord(params.meta), tenantId, sessionIsolation: 'tenant' }; + const flags = asRecord(params.flags); + if (flags.tenant !== undefined) flags.tenant = tenantId; + if (flags.sessionIsolation !== undefined) flags.sessionIsolation = 'tenant'; +} + +function asRecord(value: unknown): Record { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : {}; +} + function readJsonRpcToken(body: string): string { try { const parsed = JSON.parse(body) as { params?: { token?: unknown } }; diff --git a/packages/proxy/src/index.ts b/packages/proxy/src/index.ts index dfccde8ea1..d8d88d3d95 100644 --- a/packages/proxy/src/index.ts +++ b/packages/proxy/src/index.ts @@ -3,6 +3,7 @@ export { createDaemonProxyRequestListener, createDaemonProxyServer, type DaemonProxy, + type DaemonProxyAuthenticate, type DaemonProxyOptions, type DaemonProxyUpstreamFetch, } from './daemon-proxy.ts'; diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 0ba410b89c..36cf32692c 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -194,6 +194,8 @@ These rules apply to requests made under the lease. To refuse requests that name start the daemon with a policy that requires one (`leases.require`, below). The proxy token is shared by every client of the proxy, so a host serving several clients through one proxy authenticates each client itself and sets each request's tenant, session isolation, and lease before forwarding it. +Embedding `@agent-device/proxy` with its `authenticate` option does the tenant and session +isolation part: the proxy sends each client's requests as the tenant `authenticate` returns. ## Restrict what clients can do From 0697f4e52c1cd76bee135804c3328de6a918589d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 14 Oct 2026 12:49:50 +0200 Subject: [PATCH 2/7] refactor(contracts): own the tenant id rule in daemon-http Move normalizeTenantId from the daemon config into @agent-device/contracts/daemon-http so the proxy and the daemon apply one tenant id rule. --- packages/contracts/src/daemon-http.test.ts | 10 ++++++++++ packages/contracts/src/daemon-http.ts | 9 +++++++++ packages/daemon/src/core/config.ts | 8 -------- packages/daemon/src/resources/lease-registry-scope.ts | 2 +- packages/daemon/src/server/http/http-authorization.ts | 2 +- packages/daemon/src/sessions/request-admission.ts | 3 ++- 6 files changed, 23 insertions(+), 11 deletions(-) diff --git a/packages/contracts/src/daemon-http.test.ts b/packages/contracts/src/daemon-http.test.ts index 9f3b25b214..63ea664d83 100644 --- a/packages/contracts/src/daemon-http.test.ts +++ b/packages/contracts/src/daemon-http.test.ts @@ -10,6 +10,7 @@ import { buildRemoteTempArtifactPath, DAEMON_RPC_PROTOCOL_VERSION, isRemoteTempArtifactPath, + normalizeTenantId, } from './daemon-http.ts'; test('buildDaemonHttpBaseUrl appends the public agent-device base path', () => { @@ -49,6 +50,15 @@ test('buildDaemonHttpTenantHeaders omits blank tenant identities', () => { assert.deepEqual(buildDaemonHttpTenantHeaders(''), {}); }); +test('normalizeTenantId trims an id and refuses blank, oversized, or out-of-alphabet ids', () => { + assert.equal(normalizeTenantId(' team-a.prod_1 '), 'team-a.prod_1'); + assert.equal(normalizeTenantId('x'.repeat(128)), 'x'.repeat(128)); + assert.equal(normalizeTenantId('x'.repeat(129)), undefined); + assert.equal(normalizeTenantId('alice@example.com'), undefined); + assert.equal(normalizeTenantId(' '), undefined); + assert.equal(normalizeTenantId(undefined), undefined); +}); + test('buildDaemonHealthPayload takes the version from its caller and keeps the payload shape', () => { assert.deepEqual(buildDaemonHealthPayload('agent-device-daemon', '0.20.9'), { ok: true, diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 86772a61ad..5e4a719660 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -29,6 +29,15 @@ export function buildDaemonHttpAuthHeaders(token: string | undefined): Record { const normalizedTenantId = tenantId?.trim(); if (!normalizedTenantId) return {}; diff --git a/packages/daemon/src/core/config.ts b/packages/daemon/src/core/config.ts index d815dc24ea..8d48f0630e 100644 --- a/packages/daemon/src/core/config.ts +++ b/packages/daemon/src/core/config.ts @@ -13,11 +13,3 @@ export function resolveSessionIsolationMode(raw: string | undefined): SessionIso if (normalized === 'tenant') return 'tenant'; return 'none'; } - -export function normalizeTenantId(raw: string | undefined): string | undefined { - if (!raw) return undefined; - const value = raw.trim(); - if (!value) return undefined; - if (!/^[a-zA-Z0-9._-]{1,128}$/.test(value)) return undefined; - return value; -} diff --git a/packages/daemon/src/resources/lease-registry-scope.ts b/packages/daemon/src/resources/lease-registry-scope.ts index 434443523f..c86770feb5 100644 --- a/packages/daemon/src/resources/lease-registry-scope.ts +++ b/packages/daemon/src/resources/lease-registry-scope.ts @@ -6,7 +6,7 @@ import { } from '@agent-device/contracts/lease-scope'; import { LEASE_BACKENDS, type LeaseBackend } from '@agent-device/kernel/contracts'; import { AppError } from '@agent-device/kernel/errors'; -import { normalizeTenantId } from '../core/config.ts'; +import { normalizeTenantId } from '@agent-device/contracts/daemon-http'; export type LeaseRegistryOptions = { maxActiveSimulatorLeases?: number; diff --git a/packages/daemon/src/server/http/http-authorization.ts b/packages/daemon/src/server/http/http-authorization.ts index d5877e217b..ee7a50daee 100644 --- a/packages/daemon/src/server/http/http-authorization.ts +++ b/packages/daemon/src/server/http/http-authorization.ts @@ -8,10 +8,10 @@ import { pathToFileURL } from 'node:url'; import { AppError, normalizeError, toAppErrorCode } from '@agent-device/kernel/errors'; import { timingSafeStringEqual } from '@agent-device/host-kit/transport'; import type { DaemonRequest } from '../../core/daemon-request.ts'; -import { normalizeTenantId } from '../../core/config.ts'; import { DAEMON_HTTP_PUBLIC_NETWORK_ACCESS, DAEMON_HTTP_TENANT_HEADER, + normalizeTenantId, } from '@agent-device/contracts/daemon-http'; import { sendRestJsonError } from '../http-errors.ts'; import { resolveTrustedTenant, tenantTrustRejectionError } from './tenant-trust.ts'; diff --git a/packages/daemon/src/sessions/request-admission.ts b/packages/daemon/src/sessions/request-admission.ts index f704da4cbc..2fed3ccd28 100644 --- a/packages/daemon/src/sessions/request-admission.ts +++ b/packages/daemon/src/sessions/request-admission.ts @@ -1,5 +1,6 @@ import { AppError } from '@agent-device/kernel/errors'; -import { normalizeTenantId, resolveSessionIsolationMode } from '../core/config.ts'; +import { normalizeTenantId } from '@agent-device/contracts/daemon-http'; +import { resolveSessionIsolationMode } from '../core/config.ts'; import { isTenantOwnedSessionName, tenantScopedSessionName } from '../core/session-tenant-scope.ts'; import { isAppLeaseAllowed, From 26229f8afe79a21053bbd4ec4e375a6be8fcc837 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 14 Oct 2026 12:49:55 +0200 Subject: [PATCH 3/7] fix(proxy): refuse unstamped rpc methods and invalid tenant ids under authenticate With authenticate set, /rpc accepts only the command and lease methods, whose tenant fields the proxy stamps; install_from_source and release_materialized_paths are refused because the daemon builds their requests without those fields. A tenantId outside the daemon's rule now fails the request instead of reaching upload and artifact routes untenanted. --- packages/proxy/README.md | 6 +- packages/proxy/src/daemon-proxy.test.ts | 18 +++++ packages/proxy/src/daemon-proxy.ts | 55 +++++++++++++++- .../remote-proxy-artifact-tenant.test.ts | 65 +++++++++++++++++++ 4 files changed, 140 insertions(+), 4 deletions(-) diff --git a/packages/proxy/README.md b/packages/proxy/README.md index 1542567b9d..c20d6c0fde 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -109,8 +109,10 @@ const proxy = createDaemonProxy({ The proxy then sends every request to the daemon as that tenant, whatever tenant the client named, and isolates its sessions from other tenants' sessions. A tenant id is 1-128 letters, numbers, dots, -underscores or hyphens. Upload tickets carry the client's own `authorization` or -`x-agent-device-token` header, so the upload is authenticated the same way. +underscores or hyphens; any other id fails the request with a 500. On `/rpc` the proxy accepts only +`agent_device.command` and the `agent_device.lease.*` methods, and refuses others with a 401. Upload +tickets carry the client's own `authorization` or `x-agent-device-token` header, so the upload is +authenticated the same way. ## Options diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index ef0e5e2d34..3feb349970 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -407,3 +407,21 @@ test('without authenticate, the tenant a client declares is forwarded unchanged' expect(params.meta).toEqual({ tenantId: 'bob' }); expect(params.tenantId).toBeUndefined(); }); + +test('authenticate returning a tenantId the daemon rejects refuses the request before the daemon', async () => { + const upstream = recordingUpstream(() => Response.json({ ok: true })); + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch: upstream.fetch, + authenticate: () => ({ tenantId: 'alice@example.com' }), + }); + + const response = await proxy.handle( + new Request(`${PROXY_ORIGIN}/agent-device/upload/preflight`, { method: 'POST', body: '{}' }), + ); + + expect(response.status).toBe(500); + expect(await response.json()).toMatchObject({ ok: false, code: 'COMMAND_FAILED' }); + expect(upstream.requests).toHaveLength(0); +}); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index c50a0df31a..f7e1a379fb 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -14,6 +14,7 @@ import { DAEMON_HTTP_TENANT_HEADER, buildDaemonHttpAuthHeaders, buildDaemonHttpUrl, + normalizeTenantId, } from '@agent-device/contracts/daemon-http'; import { carriesUnbackedHostPathInstallSource, @@ -168,6 +169,9 @@ async function handleProxyRequest( { status: 401 }, ); } + if (caller.tenantId && route === '/rpc' && !isTenantStampedRpcMethod(rpcBody)) { + return tenantRpcMethodRefusedResponse(readJsonRpcId(rpcBody)); + } const staleInstance = refuseStaleProxyInstance( request, @@ -201,9 +205,13 @@ async function authenticateCaller( }), ); if (!result) return null; - const tenantId = typeof result.tenantId === 'string' ? result.tenantId.trim() : ''; + const tenantId = normalizeTenantId( + typeof result.tenantId === 'string' ? result.tenantId : undefined, + ); if (!tenantId) { - throw new AppError('COMMAND_FAILED', 'Proxy authenticate returned no tenantId'); + throw new AppError('COMMAND_FAILED', 'Proxy authenticate returned an invalid tenantId', { + hint: 'Return a tenantId of 1-128 letters, digits, ".", "_" or "-".', + }); } return { tenantId }; } @@ -221,6 +229,23 @@ function isRouteWithinTenant(route: string, tenantId: string): boolean { } } +/** The RPC methods whose every tenant field `stampRpcTenant` sets. */ +const TENANT_STAMPED_RPC_METHODS = new Set([ + 'agent_device.command', + 'agent-device.command', + 'agent_device.lease.allocate', + 'agent-device.lease.allocate', + 'agent_device.lease.heartbeat', + 'agent-device.lease.heartbeat', + 'agent_device.lease.release', + 'agent-device.lease.release', +]); + +function isTenantStampedRpcMethod(rpcBody: string | undefined): boolean { + const method = readJsonRpcMethod(rpcBody); + return method !== undefined && TENANT_STAMPED_RPC_METHODS.has(method); +} + async function proxyHealthResponse( request: Request, options: NormalizedProxyOptions, @@ -622,6 +647,16 @@ function readJsonRpcToken(body: string): string { } } +function readJsonRpcMethod(body: string | undefined): string | undefined { + if (!body) return undefined; + try { + const { method } = JSON.parse(body) as { method?: unknown }; + return typeof method === 'string' ? method : undefined; + } catch { + return undefined; + } +} + function readJsonRpcId(body: string | undefined): unknown { if (!body) return null; try { @@ -686,6 +721,22 @@ function unauthorizedResponse(route: string, rpcId: unknown): Response { ); } +function tenantRpcMethodRefusedResponse(rpcId: unknown): Response { + const error = new AppError( + 'UNAUTHORIZED', + 'This RPC method cannot act as an authenticated tenant through the proxy', + { hint: 'Use agent_device.command or the agent_device.lease methods.' }, + ); + return Response.json( + { + jsonrpc: '2.0', + id: rpcId, + error: { code: -32001, message: error.message, data: normalizeError(error) }, + }, + { status: 401 }, + ); +} + function proxyErrorResponse(error: unknown): Response { const normalized = normalizeError(error); return Response.json( diff --git a/test/integration/provider-scenarios/remote-proxy-artifact-tenant.test.ts b/test/integration/provider-scenarios/remote-proxy-artifact-tenant.test.ts index ed58ea6a56..9f50230440 100644 --- a/test/integration/provider-scenarios/remote-proxy-artifact-tenant.test.ts +++ b/test/integration/provider-scenarios/remote-proxy-artifact-tenant.test.ts @@ -10,6 +10,7 @@ import { } from '@agent-device/daemon/testing/artifact-tracking'; import { finalizeDaemonResponse } from '@agent-device/daemon/testing/request-finalization'; import { createDaemonHttpServer } from '@agent-device/daemon/testing/server/http-server'; +import type { DaemonRequest, DaemonResponse } from '@agent-device/daemon/daemon-request'; import { normalizeAgentDeviceError } from '@agent-device/kernel/errors'; import { downloadRemoteArtifact } from '../../../src/remote/daemon-artifacts.ts'; import { createDaemonProxyServer } from '@agent-device/proxy'; @@ -103,3 +104,67 @@ test('Provider-backed integration local proxy materializes tenant-scoped screens fs.rmSync(tempDir, { recursive: true, force: true }); } }); + +test('Provider-backed integration authenticated proxy sends every admitted RPC method as the caller tenant', async (t) => { + if (await skipWhenLoopbackUnavailable(t, 'authenticated proxy rpc tenant coverage')) return; + + const observed: DaemonRequest[] = []; + const upstream = await createDaemonHttpServer({ + token: 'upstream-token', + handleRequest: async (req): Promise => { + observed.push(req); + return { ok: true, data: {} }; + }, + }); + const proxy = createDaemonProxyServer({ + upstreamBaseUrl: `http://127.0.0.1:${await listenOnLoopback(upstream)}`, + upstreamToken: 'upstream-token', + authenticate: (request) => + request.headers.get('authorization') === 'Bearer alice-key' ? { tenantId: 'alice' } : null, + }); + const otherTenantParams = { session: 'bob:default', tenantId: 'bob', runId: 'run-1' }; + const admitted: Array<[string, Record]> = [ + ['agent_device.command', { command: 'devices', meta: { tenantId: 'bob' } }], + ['agent_device.lease.allocate', { backend: 'ios-simulator' }], + ['agent_device.lease.heartbeat', { leaseId: 'lease-1' }], + ['agent_device.lease.release', { leaseId: 'lease-1' }], + ]; + const refused: Array<[string, Record]> = [ + [ + 'agent_device.install_from_source', + { platform: 'ios', source: { kind: 'url', url: 'https://example.test/app.ipa' } }, + ], + ['agent_device.release_materialized_paths', { materializationId: 'materialization-1' }], + ]; + + try { + const rpcUrl = `http://127.0.0.1:${await listenOnLoopback(proxy)}/agent-device/rpc`; + const call = async (method: string, params: Record) => + await fetch(rpcUrl, { + method: 'POST', + headers: { 'content-type': 'application/json', authorization: 'Bearer alice-key' }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: method, + method, + params: { ...otherTenantParams, ...params }, + }), + }); + + for (const [method, params] of admitted) { + const response = await call(method, params); + assert.equal(response.status, 200, method); + assert.equal(observed.at(-1)?.meta?.tenantId, 'alice', method); + } + assert.equal(observed[0]?.meta?.sessionIsolation, 'tenant'); + + for (const [method, params] of refused) { + const response = await call(method, params); + assert.equal(response.status, 401, method); + } + assert.equal(observed.length, admitted.length); + } finally { + await closeLoopbackServer(proxy); + await closeLoopbackServer(upstream); + } +}); From c52ab8232538ce1eb21fd1f9b279846d9b24eda2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 14 Oct 2026 17:25:42 +0200 Subject: [PATCH 4/7] fix(proxy): never return the daemon token in upload tickets Strip every daemon auth header from the upstream ticket in all modes, then add the caller's own credential. In authenticate mode the ticket carries the client headers authenticate read, so cookie or API-key callers pass the direct upload. Share isTenantOwnedSessionName through contracts/daemon-http, and build the daemon's ticket headers with buildDaemonHttpAuthHeaders. --- packages/contracts/src/daemon-http.test.ts | 8 ++ packages/contracts/src/daemon-http.ts | 5 + .../daemon/src/core/session-tenant-scope.ts | 16 +-- packages/daemon/src/server/upload-http.ts | 10 +- .../daemon/src/sessions/request-admission.ts | 4 +- packages/proxy/README.md | 14 ++- packages/proxy/src/daemon-proxy.test.ts | 104 ++++++++++++++++-- packages/proxy/src/daemon-proxy.ts | 99 +++++++++++------ 8 files changed, 195 insertions(+), 65 deletions(-) diff --git a/packages/contracts/src/daemon-http.test.ts b/packages/contracts/src/daemon-http.test.ts index fc720d01c6..e83f7f8f17 100644 --- a/packages/contracts/src/daemon-http.test.ts +++ b/packages/contracts/src/daemon-http.test.ts @@ -11,6 +11,7 @@ import { buildRemoteTempArtifactPath, DAEMON_RPC_PROTOCOL_VERSION, isRemoteTempArtifactPath, + isTenantOwnedSessionName, normalizeTenantId, } from './daemon-http.ts'; @@ -116,3 +117,10 @@ test('a temp path of another prefix, a directory, or an escape is not a remote t false, ); }); + +test('isTenantOwnedSessionName accepts only names beneath the tenant prefix', () => { + assert.equal(isTenantOwnedSessionName('alice', 'alice:default'), true); + assert.equal(isTenantOwnedSessionName('alice', 'alice'), false); + assert.equal(isTenantOwnedSessionName('alice', 'alice-2:default'), false); + assert.equal(isTenantOwnedSessionName('alice', 'bob:alice:default'), false); +}); diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index d821f9fb86..20ea545822 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -42,6 +42,11 @@ export function normalizeTenantId(raw: string | undefined): string | undefined { return value; } +/** Whether `sessionName` lies beneath the `:` prefix tenant isolation names sessions with. */ +export function isTenantOwnedSessionName(tenant: string, sessionName: string): boolean { + return sessionName.startsWith(`${tenant}:`); +} + export function buildDaemonHttpTenantHeaders(tenantId: string | undefined): Record { const normalizedTenantId = tenantId?.trim(); if (!normalizedTenantId) return {}; diff --git a/packages/daemon/src/core/session-tenant-scope.ts b/packages/daemon/src/core/session-tenant-scope.ts index a5fc7bef26..849686432d 100644 --- a/packages/daemon/src/core/session-tenant-scope.ts +++ b/packages/daemon/src/core/session-tenant-scope.ts @@ -1,11 +1,15 @@ +import { isTenantOwnedSessionName } from '@agent-device/contracts/daemon-http'; + /** * The one rule that says which sessions belong to a tenant: under tenant - * isolation every session name lives beneath its own `:` prefix. + * isolation every session name lives beneath its own `:` prefix + * (`isTenantOwnedSessionName` in `@agent-device/contracts/daemon-http`). * - * It is written once because two sides depend on it agreeing — `scopeRequestSession` + * It is written once because several sides depend on it agreeing — `scopeRequestSession` * (`request-admission.ts`) names the session, and the request diagnostics route - * (`request-diagnostics-http.ts`, #1801) decides from the name alone whether a - * caller may read that session's record long after the session itself is gone. + * (`request-diagnostics-http.ts`, #1801) and `@agent-device/proxy` decide from the + * name alone whether a caller may read that session's record long after the session + * itself is gone. * * The naming side has a precondition the reading side must honor: it applies the * prefix ONLY under tenant isolation, which the daemon forces exactly when the @@ -37,10 +41,6 @@ export function tenantScopedSessionName(tenant: string, session: string): string return isTenantOwnedSessionName(tenant, session) ? session : `${tenant}:${session}`; } -export function isTenantOwnedSessionName(tenant: string, sessionName: string): boolean { - return sessionName.startsWith(`${tenant}:`); -} - /** * Whether a caller in `namespace` may address `sessionName` by name — the read * counterpart of `scopeRequestSession`'s naming decision, and the only tenant diff --git a/packages/daemon/src/server/upload-http.ts b/packages/daemon/src/server/upload-http.ts index bd503a6e91..e186ebf927 100644 --- a/packages/daemon/src/server/upload-http.ts +++ b/packages/daemon/src/server/upload-http.ts @@ -1,5 +1,6 @@ import http from 'node:http'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { buildDaemonHttpAuthHeaders } from '@agent-device/contracts/daemon-http'; import type { DaemonRequest } from '../core/daemon-request.ts'; import { trackUploadedArtifact } from '../resources/artifact-tracking.ts'; import { @@ -134,7 +135,7 @@ async function handleUploadPreflight( const preflight = readUploadPreflightBody(body); const upload = beginResumableUpload({ baseUrl: resolveHttpRequestBaseUrl(req), - tokenHeaders: buildUploadTicketAuthHeaders(token), + tokenHeaders: buildDaemonHttpAuthHeaders(token), ...preflight, tenantId: auth.tenantId, }); @@ -288,13 +289,6 @@ function readRequiredArtifactType(record: Record): 'file' | 'ap throw new AppError('INVALID_ARGS', 'artifactType must be "file" or "app-bundle"'); } -function buildUploadTicketAuthHeaders(token: string): Record { - return { - authorization: `Bearer ${token}`, - 'x-agent-device-token': token, - }; -} - function resolveHttpRequestBaseUrl(req: http.IncomingMessage): string { const host = typeof req.headers.host === 'string' ? req.headers.host : ''; if (!host) throw new AppError('INVALID_ARGS', 'Missing host header'); diff --git a/packages/daemon/src/sessions/request-admission.ts b/packages/daemon/src/sessions/request-admission.ts index 2fed3ccd28..88bbed63d8 100644 --- a/packages/daemon/src/sessions/request-admission.ts +++ b/packages/daemon/src/sessions/request-admission.ts @@ -1,7 +1,7 @@ import { AppError } from '@agent-device/kernel/errors'; -import { normalizeTenantId } from '@agent-device/contracts/daemon-http'; +import { isTenantOwnedSessionName, normalizeTenantId } from '@agent-device/contracts/daemon-http'; import { resolveSessionIsolationMode } from '../core/config.ts'; -import { isTenantOwnedSessionName, tenantScopedSessionName } from '../core/session-tenant-scope.ts'; +import { tenantScopedSessionName } from '../core/session-tenant-scope.ts'; import { isAppLeaseAllowed, isLeaseAdmissionExempt, diff --git a/packages/proxy/README.md b/packages/proxy/README.md index c20d6c0fde..150819ff5e 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -107,12 +107,14 @@ const proxy = createDaemonProxy({ }); ``` -The proxy then sends every request to the daemon as that tenant, whatever tenant the client named, -and isolates its sessions from other tenants' sessions. A tenant id is 1-128 letters, numbers, dots, -underscores or hyphens; any other id fails the request with a 500. On `/rpc` the proxy accepts only -`agent_device.command` and the `agent_device.lease.*` methods, and refuses others with a 401. Upload -tickets carry the client's own `authorization` or `x-agent-device-token` header, so the upload is -authenticated the same way. +The proxy then sends every authenticated request to the daemon as that tenant, whatever tenant the +client named, and isolates its sessions from other tenants' sessions. `GET /health` is not +authenticated and carries no tenant. A tenant id is 1-128 letters, numbers, dots, underscores or +hyphens; any other id fails the request with a 500. On `/rpc` the proxy accepts only +`agent_device.command` and the `agent_device.lease.*` methods (or the same names spelled +`agent-device.command` and `agent-device.lease.*`), and refuses others with a 401. Upload tickets +carry the client request headers that `authenticate` read by name, such as `authorization` or an API +key header, so the upload is authenticated the same way. They never carry the daemon's token. ## Options diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index 3feb349970..2e14f4ffec 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -1,4 +1,5 @@ import { expect, test } from 'vitest'; +import { buildDaemonHttpAuthHeaders } from '@agent-device/contracts/daemon-http'; import { createDaemonProxy, type DaemonProxyUpstreamFetch } from './daemon-proxy.ts'; const PROXY_ORIGIN = 'https://gateway.example.test'; @@ -350,25 +351,108 @@ test('authenticate tenant replaces the tenant header a client sends on artifact expect(upstream.requests[0]?.headers.get('x-agent-device-tenant')).toBe('alice'); }); -test('with authenticate, upload tickets carry the caller credential', async () => { - const upstream = recordingUpstream(() => - Response.json({ - ok: true, - upload: { url: 'http://127.0.0.1:4310/upload/direct/abc', headers: { 'x-extra': '1' } }, - }), +const DAEMON_TOKEN = 'daemon-secret'; + +/** Answers a preflight with the ticket the daemon issues: both daemon credentials plus extras. */ +function daemonTicketUpstream() { + return recordingUpstream((request) => + new URL(request.url).pathname.endsWith('/upload/preflight') + ? Response.json({ + ok: true, + uploadId: 'abc', + upload: { + url: 'http://127.0.0.1:4310/upload/direct/abc', + headers: { ...buildDaemonHttpAuthHeaders(DAEMON_TOKEN), 'x-extra': '1' }, + }, + }) + : new Response(null, { status: 200 }), ); - const { proxy } = proxyAuthenticatingWith(upstream.fetch); +} +function proxyAuthenticatingByAnyCredential(upstreamFetch: DaemonProxyUpstreamFetch) { + return createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: DAEMON_TOKEN, + upstreamFetch, + authenticate: (request) => { + const key = + request.headers.get('x-api-key') ?? + request.headers.get('cookie')?.replace(/^session=/, '') ?? + request.headers.get('x-agent-device-token') ?? + request.headers.get('authorization')?.replace(/^Bearer /, ''); + return key === 'alice-key' ? { tenantId: 'alice' } : null; + }, + }); +} + +async function requestTicket( + proxy: ReturnType, + headers: Record, +): Promise<{ text: string; ticketHeaders: Record }> { const response = await proxy.handle( new Request(`${PROXY_ORIGIN}/agent-device/upload/preflight`, { method: 'POST', - headers: { authorization: 'Bearer bob-key' }, + headers: { ...headers, 'content-type': 'application/json' }, body: '{}', }), ); + const text = await response.text(); + return { + text, + ticketHeaders: (JSON.parse(text) as { upload: { headers: Record } }).upload + .headers, + }; +} + +test.each([ + ['authorization', { authorization: 'Bearer alice-key' }], + ['x-agent-device-token', { 'x-agent-device-token': 'alice-key' }], + ['cookie', { cookie: 'session=alice-key' }], + ['x-api-key', { 'x-api-key': 'alice-key' }], +])( + 'with authenticate, a %s caller gets a ticket with only its own credential', + async (_name, clientHeaders) => { + const upstream = daemonTicketUpstream(); + const proxy = proxyAuthenticatingByAnyCredential(upstream.fetch); + + const { text, ticketHeaders } = await requestTicket(proxy, clientHeaders); + + expect(text).not.toContain(DAEMON_TOKEN); + expect(ticketHeaders).toEqual({ 'x-extra': '1', ...clientHeaders }); + }, +); + +test('with authenticate, the ticket credential passes authenticate on the direct upload', async () => { + const upstream = daemonTicketUpstream(); + const proxy = proxyAuthenticatingByAnyCredential(upstream.fetch); + const { ticketHeaders } = await requestTicket(proxy, { 'x-api-key': 'alice-key' }); + + const upload = await proxy.handle( + new Request(`${PROXY_ORIGIN}/agent-device/upload/direct/abc`, { + method: 'PUT', + headers: ticketHeaders, + body: 'bytes', + duplex: 'half', + } as RequestInit), + ); - const payload = (await response.json()) as { upload: { headers: Record } }; - expect(payload.upload.headers).toEqual({ 'x-extra': '1', authorization: 'Bearer bob-key' }); + expect(upload.status).toBe(200); + expect(upstream.requests[1]?.headers.get('x-agent-device-tenant')).toBe('alice'); +}); + +test('with a client token, the ticket carries the client token, never the daemon token', async () => { + const upstream = daemonTicketUpstream(); + const proxy = proxyWith(upstream.fetch); + + const { text, ticketHeaders } = await requestTicket(proxy, { + authorization: 'Bearer client-secret', + }); + + expect(text).not.toContain(DAEMON_TOKEN); + expect(ticketHeaders).toEqual({ + 'x-extra': '1', + ...buildDaemonHttpAuthHeaders('client-secret'), + }); }); test('with authenticate, request diagnostics are served only for the caller tenant sessions', async () => { diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index f7e1a379fb..a4ae463bc0 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -14,6 +14,7 @@ import { DAEMON_HTTP_TENANT_HEADER, buildDaemonHttpAuthHeaders, buildDaemonHttpUrl, + isTenantOwnedSessionName, normalizeTenantId, } from '@agent-device/contracts/daemon-http'; import { @@ -30,7 +31,9 @@ export type DaemonProxyUpstreamFetch = (request: Request) => Promise; /** * Authenticates one client request and names the tenant it acts as, or returns `null` to refuse - * it. The request carries the client's headers and, for `/rpc`, its JSON body. + * it. The request carries the client's headers and, for `/rpc`, its JSON body. Read credentials + * with `request.headers.get` or `has`: an upload ticket carries the client headers read that way, + * so the direct upload passes the same check. */ export type DaemonProxyAuthenticate = ( request: Request, @@ -82,8 +85,24 @@ type NormalizedProxyOptions = { upstreamFetch: DaemonProxyUpstreamFetch; }; -/** The client a request was authenticated as; `tenantId` is set only by `authenticate`. */ -type ProxyCaller = { tenantId?: string }; +/** + * The client a request was authenticated as; `tenantId` is set only by `authenticate`. + * `credentialHeaders` are the client's own headers its upload ticket must carry to pass the same + * check on the direct upload. + */ +type ProxyCaller = { tenantId?: string; credentialHeaders: Record }; + +/** Headers that frame the request they arrive on, so a ticket never repeats them. */ +const NON_CREDENTIAL_REQUEST_HEADERS = new Set([ + 'connection', + 'content-length', + 'content-type', + 'host', + 'transfer-encoding', +]); + +/** Upstream daemon credential header names; a ticket the proxy returns never carries them. */ +const DAEMON_AUTH_HEADER_NAMES = Object.keys(buildDaemonHttpAuthHeaders('daemon')); const DEFAULT_MAX_RPC_BODY_BYTES = 1024 * 1024; const DEFAULT_UPSTREAM_TIMEOUT_MS = 5 * 60 * 1000; @@ -194,16 +213,19 @@ async function authenticateCaller( rpcBody: string | undefined, ): Promise { if (!options.authenticate) { - return isAuthorized(request, options.clientToken ?? '', rpcBody) ? {} : null; + return isAuthorized(request, options.clientToken ?? '', rpcBody) + ? { credentialHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } + : null; } - const result = await options.authenticate( - new Request(request.url, { - method: request.method, - headers: request.headers, - signal: request.signal, - ...(rpcBody !== undefined ? { body: rpcBody } : {}), - }), - ); + const headers = new ReadRecordingHeaders(request.headers); + const authenticateRequest = new Request(request.url, { + method: request.method, + headers, + signal: request.signal, + ...(rpcBody !== undefined ? { body: rpcBody } : {}), + }); + Object.defineProperty(authenticateRequest, 'headers', { value: headers }); + const result = await options.authenticate(authenticateRequest); if (!result) return null; const tenantId = normalizeTenantId( typeof result.tenantId === 'string' ? result.tenantId : undefined, @@ -213,7 +235,32 @@ async function authenticateCaller( hint: 'Return a tenantId of 1-128 letters, digits, ".", "_" or "-".', }); } - return { tenantId }; + return { tenantId, credentialHeaders: headers.readHeaders() }; +} + +/** Records which headers `authenticate` reads by name, so an upload ticket can carry them. */ +class ReadRecordingHeaders extends Headers { + readonly #readNames = new Set(); + + override get(name: string): string | null { + this.#readNames.add(name.toLowerCase()); + return super.get(name); + } + + override has(name: string): boolean { + this.#readNames.add(name.toLowerCase()); + return super.has(name); + } + + readHeaders(): Record { + const headers: Record = {}; + for (const name of this.#readNames) { + if (NON_CREDENTIAL_REQUEST_HEADERS.has(name)) continue; + const value = super.get(name); + if (value !== null) headers[name] = value; + } + return headers; + } } /** @@ -223,7 +270,7 @@ async function authenticateCaller( function isRouteWithinTenant(route: string, tenantId: string): boolean { if (!isRequestDiagnosticsRoute(route)) return true; try { - return decodeURIComponent(route.split('/')[2] ?? '').startsWith(`${tenantId}:`); + return isTenantOwnedSessionName(tenantId, decodeURIComponent(route.split('/')[2] ?? '')); } catch { return false; } @@ -308,9 +355,7 @@ async function forwardProxyRequest(params: { request, upstreamResponse, headers, - ticketAuthHeaders: options.authenticate - ? readClientAuthHeaders(request.headers) - : buildDaemonHttpAuthHeaders(options.clientToken), + ticketAuthHeaders: caller.credentialHeaders, }); } return new Response(upstreamResponse.body, { status: upstreamResponse.status, headers }); @@ -381,10 +426,12 @@ function rewriteUploadPreflightResponse( const rewrittenUrl = rewriteUploadDirectUrl(record.upload.url, request); if (!rewrittenUrl) return body; - const headers = - record.upload.headers && typeof record.upload.headers === 'object' - ? { ...(record.upload.headers as Record) } - : {}; + const headers: Record = {}; + if (record.upload.headers && typeof record.upload.headers === 'object') { + for (const [name, value] of Object.entries(record.upload.headers)) { + if (!DAEMON_AUTH_HEADER_NAMES.includes(name.toLowerCase())) headers[name] = value; + } + } Object.assign(headers, ticketAuthHeaders); return JSON.stringify({ @@ -397,16 +444,6 @@ function rewriteUploadPreflightResponse( }); } -/** The client's own credential, so its upload ticket authenticates as the client did. */ -function readClientAuthHeaders(requestHeaders: Headers): Record { - const headers: Record = {}; - for (const name of ['authorization', 'x-agent-device-token']) { - const value = requestHeaders.get(name); - if (value !== null) headers[name] = value; - } - return headers; -} - function rewriteUploadDirectUrl(upstreamUrl: string, request: Request): string | null { let parsed: URL; try { From 5528c82f57cc605eeaac9e060aaa3eb183dd3b00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 14 Oct 2026 17:49:19 +0200 Subject: [PATCH 5/7] fix(wire-compat): keep the released upload ticket declaration and track the moved tenant rule buildUploadTicketAuthHeaders is listed daemon RPC wire surface released in v0.21.27. Replacing it with buildDaemonHttpAuthHeaders removed that declaration, and the released-surface gate treats any removal as bump-only. The wire output did not change, so restore the released declaration rather than bump the protocol. isTenantOwnedSessionName moved unchanged into contracts/daemon-http. Point the manifest and its ledger key at the new path; the gate records it as a move. --- packages/daemon/src/server/upload-http.ts | 10 ++++++++-- test/wire-compat/ledger.json | 2 +- test/wire-compat/surface.ts | 8 ++------ 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/packages/daemon/src/server/upload-http.ts b/packages/daemon/src/server/upload-http.ts index e186ebf927..bd503a6e91 100644 --- a/packages/daemon/src/server/upload-http.ts +++ b/packages/daemon/src/server/upload-http.ts @@ -1,6 +1,5 @@ import http from 'node:http'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; -import { buildDaemonHttpAuthHeaders } from '@agent-device/contracts/daemon-http'; import type { DaemonRequest } from '../core/daemon-request.ts'; import { trackUploadedArtifact } from '../resources/artifact-tracking.ts'; import { @@ -135,7 +134,7 @@ async function handleUploadPreflight( const preflight = readUploadPreflightBody(body); const upload = beginResumableUpload({ baseUrl: resolveHttpRequestBaseUrl(req), - tokenHeaders: buildDaemonHttpAuthHeaders(token), + tokenHeaders: buildUploadTicketAuthHeaders(token), ...preflight, tenantId: auth.tenantId, }); @@ -289,6 +288,13 @@ function readRequiredArtifactType(record: Record): 'file' | 'ap throw new AppError('INVALID_ARGS', 'artifactType must be "file" or "app-bundle"'); } +function buildUploadTicketAuthHeaders(token: string): Record { + return { + authorization: `Bearer ${token}`, + 'x-agent-device-token': token, + }; +} + function resolveHttpRequestBaseUrl(req: http.IncomingMessage): string { const host = typeof req.headers.host === 'string' ? req.headers.host : ''; if (!host) throw new AppError('INVALID_ARGS', 'Missing host header'); diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index c4fabb747b..16846f6193 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -9,6 +9,7 @@ "packages/contracts/src/daemon-http.ts#buildDaemonHttpBaseUrl": "sha256:f92697208d9f42ec0dcfb006b6f2dce761bd5307db27ce2e52927fd7742e3a9a", "packages/contracts/src/daemon-http.ts#buildDaemonHttpTenantHeaders": "sha256:e38a5f0b5ab07ee3a5fe3db229d0de750888660c55bf31692e100002be96de1d", "packages/contracts/src/daemon-http.ts#buildDaemonHttpUrl": "sha256:d38f1f8877588fbcb1fea8c52a5cb7dc205043e3fc698b3d78fdcf821fa80471", + "packages/contracts/src/daemon-http.ts#isTenantOwnedSessionName": "sha256:c3cff883507d462548846554b89779cb815ceb265714575e57bee022b57c4bd1", "packages/contracts/src/request-progress.ts#CommandProgressEvent": "sha256:2dc6ff7f3b619d9b917210d47ebf9eee8095563389c8956b4e9f2bd994e1942d", "packages/contracts/src/request-progress.ts#ReplayTestProgressEvent": "sha256:61df00308d0e21f2acfc4f73cb2c07cd0c251e827f1c87628e2d08338e1b5c84", "packages/contracts/src/request-progress.ts#ReplayTestSuiteProgressEvent": "sha256:2d6599bfcf1e94596c61f85a8a986874b59b8c05e82e5e00dd31e381a5b0fe84", @@ -127,7 +128,6 @@ "packages/daemon/src/server/http/http-rpc-envelope.ts#writeRpcResponseEnvelope": "sha256:7a8155e9fcbb53485489728250a85109b5dab0d96cdd4aa8b7e7eb87a4898ddb", "packages/daemon/src/core/session-tenant-scope.ts#TenantSessionNamespace": "sha256:a6613d22933caa053e479f05b7f016664f6be8d0afdbbf81e578ff497fc1b13d", "packages/daemon/src/core/session-tenant-scope.ts#isTenantAddressableSessionName": "sha256:cc8ae18094b7f57d4bb694678f84ba767637b1087fd28058ffd6a3c92c79f05d", - "packages/daemon/src/core/session-tenant-scope.ts#isTenantOwnedSessionName": "sha256:c3cff883507d462548846554b89779cb815ceb265714575e57bee022b57c4bd1", "packages/daemon/src/server/upload-http.ts#AuxiliaryHttpAuthorizer": "sha256:6521ffa355c57af97bfc8095699f2a2b38745a6ef8d61a34c8cfc80ee690b6b5", "packages/daemon/src/server/upload-http.ts#DIRECT_UPLOAD_PATH_PREFIX": "sha256:6fe7d42a65baceb595d96b6aa83fe9aa84527d9aa2e448d7ef47882d31a03276", "packages/daemon/src/server/upload-http.ts#UploadFinalizeBody": "sha256:c358aea9b3c341f51f3fa263032dfda8a3fbbf729396fcf7f2d8aa051b231b8b", diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index e0193b5226..1381795218 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -166,6 +166,7 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'buildDaemonHttpAuthHeaders', 'DAEMON_HTTP_TENANT_HEADER', 'buildDaemonHttpTenantHeaders', + 'isTenantOwnedSessionName', ), ...from( HTTP_AUTHORIZATION, @@ -186,12 +187,7 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ // is that rule; the namespace it takes says whether the caller's sessions // were partitioned at all, which is what the naming side keys off. ...from(REQUEST_DIAGNOSTICS_HTTP, 'RequestDiagnosticsHttpAuthorizer'), - ...from( - SESSION_TENANT_SCOPE, - 'TenantSessionNamespace', - 'isTenantOwnedSessionName', - 'isTenantAddressableSessionName', - ), + ...from(SESSION_TENANT_SCOPE, 'TenantSessionNamespace', 'isTenantAddressableSessionName'), ], }, { From bea3137924aa39efbab7eae9cb654fb6bef8161f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 14 Oct 2026 17:58:22 +0200 Subject: [PATCH 6/7] fix(proxy): build upload tickets from declared upload headers authenticate now returns { tenantId, uploadHeaders? }. uploadHeaders default to the client's own authorization and x-agent-device-token headers. The ticket the proxy returns is the upstream content-type plus those headers, so no daemon credential can reach a client whatever the daemon's ticket holds. This replaces the header-read recording and the name-based strip list. --- packages/proxy/README.md | 19 +++- packages/proxy/src/daemon-proxy.test.ts | 132 +++++++++++++++++------ packages/proxy/src/daemon-proxy.ts | 134 ++++++++++-------------- packages/proxy/src/index.ts | 1 + website/docs/docs/remote-proxy.md | 2 +- 5 files changed, 174 insertions(+), 114 deletions(-) diff --git a/packages/proxy/README.md b/packages/proxy/README.md index 150819ff5e..40f718fe89 100644 --- a/packages/proxy/README.md +++ b/packages/proxy/README.md @@ -112,9 +112,22 @@ client named, and isolates its sessions from other tenants' sessions. `GET /heal authenticated and carries no tenant. A tenant id is 1-128 letters, numbers, dots, underscores or hyphens; any other id fails the request with a 500. On `/rpc` the proxy accepts only `agent_device.command` and the `agent_device.lease.*` methods (or the same names spelled -`agent-device.command` and `agent-device.lease.*`), and refuses others with a 401. Upload tickets -carry the client request headers that `authenticate` read by name, such as `authorization` or an API -key header, so the upload is authenticated the same way. They never carry the daemon's token. +`agent-device.command` and `agent-device.lease.*`), and refuses others with a 401. + +Clients upload files with a ticket that names the headers to send. The proxy builds that ticket +from the daemon ticket's `content-type` and the client's own credential, so it never carries the +daemon's token. By default the credential is the client's `authorization` and +`x-agent-device-token` headers. If your clients use another header, such as a cookie or an API key +header, return it as `uploadHeaders` so the upload passes `authenticate` too: + +```ts +authenticate: async (request) => { + const apiKey = request.headers.get('x-api-key'); + if (!apiKey) return null; + const account = await accounts.findByApiKey(apiKey); + return account ? { tenantId: account.id, uploadHeaders: { 'x-api-key': apiKey } } : null; +}, +``` ## Options diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index 2e14f4ffec..8a25119a72 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -1,6 +1,10 @@ import { expect, test } from 'vitest'; import { buildDaemonHttpAuthHeaders } from '@agent-device/contracts/daemon-http'; -import { createDaemonProxy, type DaemonProxyUpstreamFetch } from './daemon-proxy.ts'; +import { + createDaemonProxy, + type DaemonProxyAuthenticatedClient, + type DaemonProxyUpstreamFetch, +} from './daemon-proxy.ts'; const PROXY_ORIGIN = 'https://gateway.example.test'; @@ -353,7 +357,7 @@ test('authenticate tenant replaces the tenant header a client sends on artifact const DAEMON_TOKEN = 'daemon-secret'; -/** Answers a preflight with the ticket the daemon issues: both daemon credentials plus extras. */ +/** Answers a preflight with a ticket carrying daemon credentials under several header names. */ function daemonTicketUpstream() { return recordingUpstream((request) => new URL(request.url).pathname.endsWith('/upload/preflight') @@ -362,25 +366,35 @@ function daemonTicketUpstream() { uploadId: 'abc', upload: { url: 'http://127.0.0.1:4310/upload/direct/abc', - headers: { ...buildDaemonHttpAuthHeaders(DAEMON_TOKEN), 'x-extra': '1' }, + headers: { + ...buildDaemonHttpAuthHeaders(DAEMON_TOKEN), + cookie: `daemon=${DAEMON_TOKEN}`, + 'x-extra': '1', + 'content-type': 'application/zip', + }, }, }) : new Response(null, { status: 200 }), ); } +/** Admits `alice-key` from any of four credential headers, naming its own upload headers. */ function proxyAuthenticatingByAnyCredential(upstreamFetch: DaemonProxyUpstreamFetch) { return createDaemonProxy({ upstreamBaseUrl: 'http://daemon.internal:4310', upstreamToken: DAEMON_TOKEN, upstreamFetch, - authenticate: (request) => { - const key = - request.headers.get('x-api-key') ?? - request.headers.get('cookie')?.replace(/^session=/, '') ?? + authenticate: (request): DaemonProxyAuthenticatedClient | null => { + if (request.headers.get('x-api-key') === 'alice-key') { + return { tenantId: 'alice', uploadHeaders: { 'x-api-key': 'alice-key' } }; + } + if (request.headers.get('cookie') === 'session=alice-key') { + return { tenantId: 'alice', uploadHeaders: { cookie: 'session=alice-key' } }; + } + const token = request.headers.get('x-agent-device-token') ?? request.headers.get('authorization')?.replace(/^Bearer /, ''); - return key === 'alice-key' ? { tenantId: 'alice' } : null; + return token === 'alice-key' ? { tenantId: 'alice' } : null; }, }); } @@ -388,7 +402,7 @@ function proxyAuthenticatingByAnyCredential(upstreamFetch: DaemonProxyUpstreamFe async function requestTicket( proxy: ReturnType, headers: Record, -): Promise<{ text: string; ticketHeaders: Record }> { +): Promise> { const response = await proxy.handle( new Request(`${PROXY_ORIGIN}/agent-device/upload/preflight`, { method: 'POST', @@ -397,64 +411,114 @@ async function requestTicket( }), ); const text = await response.text(); - return { - text, - ticketHeaders: (JSON.parse(text) as { upload: { headers: Record } }).upload - .headers, - }; + expect(text).not.toContain(DAEMON_TOKEN); + const ticketHeaders = (JSON.parse(text) as { upload: { headers: Record } }).upload + .headers; + for (const value of Object.values(ticketHeaders)) expect(value).not.toContain(DAEMON_TOKEN); + return ticketHeaders; +} + +function uploadChunk(proxy: ReturnType, headers: Record) { + return proxy.handle( + new Request(`${PROXY_ORIGIN}/agent-device/upload/direct/abc`, { + method: 'PUT', + headers, + body: 'bytes', + duplex: 'half', + } as RequestInit), + ); } test.each([ ['authorization', { authorization: 'Bearer alice-key' }], ['x-agent-device-token', { 'x-agent-device-token': 'alice-key' }], +])( + 'with authenticate naming no upload headers, a %s caller gets a ticket with its own credential', + async (_name, clientHeaders) => { + const upstream = daemonTicketUpstream(); + const proxy = proxyAuthenticatingByAnyCredential(upstream.fetch); + + const ticketHeaders = await requestTicket(proxy, clientHeaders); + + expect(ticketHeaders).toEqual({ 'content-type': 'application/zip', ...clientHeaders }); + }, +); + +test.each([ ['cookie', { cookie: 'session=alice-key' }], ['x-api-key', { 'x-api-key': 'alice-key' }], ])( - 'with authenticate, a %s caller gets a ticket with only its own credential', - async (_name, clientHeaders) => { + 'with authenticate naming %s upload headers, the ticket carries exactly those', + async (_name, uploadHeaders) => { const upstream = daemonTicketUpstream(); const proxy = proxyAuthenticatingByAnyCredential(upstream.fetch); - const { text, ticketHeaders } = await requestTicket(proxy, clientHeaders); + const ticketHeaders = await requestTicket(proxy, { + ...uploadHeaders, + authorization: 'Bearer unrelated', + }); - expect(text).not.toContain(DAEMON_TOKEN); - expect(ticketHeaders).toEqual({ 'x-extra': '1', ...clientHeaders }); + expect(ticketHeaders).toEqual({ 'content-type': 'application/zip', ...uploadHeaders }); }, ); -test('with authenticate, the ticket credential passes authenticate on the direct upload', async () => { +test('with authenticate, a custom upload header passes authenticate on the direct upload', async () => { const upstream = daemonTicketUpstream(); const proxy = proxyAuthenticatingByAnyCredential(upstream.fetch); - const { ticketHeaders } = await requestTicket(proxy, { 'x-api-key': 'alice-key' }); + const ticketHeaders = await requestTicket(proxy, { 'x-api-key': 'alice-key' }); - const upload = await proxy.handle( - new Request(`${PROXY_ORIGIN}/agent-device/upload/direct/abc`, { - method: 'PUT', - headers: ticketHeaders, - body: 'bytes', - duplex: 'half', - } as RequestInit), - ); + const upload = await uploadChunk(proxy, ticketHeaders); expect(upload.status).toBe(200); expect(upstream.requests[1]?.headers.get('x-agent-device-tenant')).toBe('alice'); }); +test('an authenticate that never reads headers still yields a working ticket', async () => { + const upstream = daemonTicketUpstream(); + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: DAEMON_TOKEN, + upstreamFetch: upstream.fetch, + authenticate: () => ({ tenantId: 'alice' }), + }); + const ticketHeaders = await requestTicket(proxy, { authorization: 'Bearer alice-key' }); + + const upload = await uploadChunk(proxy, ticketHeaders); + + expect(ticketHeaders).toEqual({ + 'content-type': 'application/zip', + authorization: 'Bearer alice-key', + }); + expect(upload.status).toBe(200); + expect(upstream.requests[1]?.headers.get('x-agent-device-tenant')).toBe('alice'); +}); + test('with a client token, the ticket carries the client token, never the daemon token', async () => { const upstream = daemonTicketUpstream(); const proxy = proxyWith(upstream.fetch); - const { text, ticketHeaders } = await requestTicket(proxy, { - authorization: 'Bearer client-secret', - }); + const ticketHeaders = await requestTicket(proxy, { authorization: 'Bearer client-secret' }); - expect(text).not.toContain(DAEMON_TOKEN); expect(ticketHeaders).toEqual({ - 'x-extra': '1', + 'content-type': 'application/zip', ...buildDaemonHttpAuthHeaders('client-secret'), }); }); +test('a ticket whose url the proxy cannot rewrite still drops the daemon credentials', async () => { + const upstream = recordingUpstream(() => + Response.json({ + ok: true, + upload: { url: 'not a url', headers: buildDaemonHttpAuthHeaders(DAEMON_TOKEN) }, + }), + ); + const proxy = proxyWith(upstream.fetch); + + const ticketHeaders = await requestTicket(proxy, { authorization: 'Bearer client-secret' }); + + expect(ticketHeaders).toEqual(buildDaemonHttpAuthHeaders('client-secret')); +}); + test('with authenticate, request diagnostics are served only for the caller tenant sessions', async () => { const upstream = recordingUpstream(() => Response.json({ ok: true })); const { proxy } = proxyAuthenticatingWith(upstream.fetch); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index a4ae463bc0..db6a198d5f 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -29,15 +29,25 @@ import { */ export type DaemonProxyUpstreamFetch = (request: Request) => Promise; +/** The client an `authenticate` call admitted. */ +export type DaemonProxyAuthenticatedClient = { + /** The tenant every request from this client acts as. */ + tenantId: string; + /** + * The credential headers an upload ticket gives this client, so its direct upload passes + * `authenticate` again. Defaults to the client's own `authorization` and + * `x-agent-device-token` request headers, when it sent them. + */ + uploadHeaders?: Record; +}; + /** - * Authenticates one client request and names the tenant it acts as, or returns `null` to refuse - * it. The request carries the client's headers and, for `/rpc`, its JSON body. Read credentials - * with `request.headers.get` or `has`: an upload ticket carries the client headers read that way, - * so the direct upload passes the same check. + * Authenticates one client request and names the client it admits, or returns `null` to refuse + * it. The request carries the client's headers and, for `/rpc`, its JSON body. */ export type DaemonProxyAuthenticate = ( request: Request, -) => Promise<{ tenantId: string } | null> | { tenantId: string } | null; +) => Promise | DaemonProxyAuthenticatedClient | null; export type DaemonProxyOptions = { /** Base URL of the upstream agent-device daemon HTTP server. */ @@ -85,24 +95,11 @@ type NormalizedProxyOptions = { upstreamFetch: DaemonProxyUpstreamFetch; }; -/** - * The client a request was authenticated as; `tenantId` is set only by `authenticate`. - * `credentialHeaders` are the client's own headers its upload ticket must carry to pass the same - * check on the direct upload. - */ -type ProxyCaller = { tenantId?: string; credentialHeaders: Record }; - -/** Headers that frame the request they arrive on, so a ticket never repeats them. */ -const NON_CREDENTIAL_REQUEST_HEADERS = new Set([ - 'connection', - 'content-length', - 'content-type', - 'host', - 'transfer-encoding', -]); +/** The client a request was authenticated as; `tenantId` is set only by `authenticate`. */ +type ProxyCaller = { tenantId?: string; uploadHeaders: Record }; -/** Upstream daemon credential header names; a ticket the proxy returns never carries them. */ -const DAEMON_AUTH_HEADER_NAMES = Object.keys(buildDaemonHttpAuthHeaders('daemon')); +/** The client request headers an upload ticket repeats when `authenticate` names none. */ +const DEFAULT_UPLOAD_CREDENTIAL_HEADERS = Object.keys(buildDaemonHttpAuthHeaders('client')); const DEFAULT_MAX_RPC_BODY_BYTES = 1024 * 1024; const DEFAULT_UPSTREAM_TIMEOUT_MS = 5 * 60 * 1000; @@ -214,18 +211,17 @@ async function authenticateCaller( ): Promise { if (!options.authenticate) { return isAuthorized(request, options.clientToken ?? '', rpcBody) - ? { credentialHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } + ? { uploadHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } : null; } - const headers = new ReadRecordingHeaders(request.headers); - const authenticateRequest = new Request(request.url, { - method: request.method, - headers, - signal: request.signal, - ...(rpcBody !== undefined ? { body: rpcBody } : {}), - }); - Object.defineProperty(authenticateRequest, 'headers', { value: headers }); - const result = await options.authenticate(authenticateRequest); + const result = await options.authenticate( + new Request(request.url, { + method: request.method, + headers: request.headers, + signal: request.signal, + ...(rpcBody !== undefined ? { body: rpcBody } : {}), + }), + ); if (!result) return null; const tenantId = normalizeTenantId( typeof result.tenantId === 'string' ? result.tenantId : undefined, @@ -235,32 +231,16 @@ async function authenticateCaller( hint: 'Return a tenantId of 1-128 letters, digits, ".", "_" or "-".', }); } - return { tenantId, credentialHeaders: headers.readHeaders() }; + return { tenantId, uploadHeaders: result.uploadHeaders ?? defaultUploadHeaders(request) }; } -/** Records which headers `authenticate` reads by name, so an upload ticket can carry them. */ -class ReadRecordingHeaders extends Headers { - readonly #readNames = new Set(); - - override get(name: string): string | null { - this.#readNames.add(name.toLowerCase()); - return super.get(name); - } - - override has(name: string): boolean { - this.#readNames.add(name.toLowerCase()); - return super.has(name); - } - - readHeaders(): Record { - const headers: Record = {}; - for (const name of this.#readNames) { - if (NON_CREDENTIAL_REQUEST_HEADERS.has(name)) continue; - const value = super.get(name); - if (value !== null) headers[name] = value; - } - return headers; +function defaultUploadHeaders(request: Request): Record { + const headers: Record = {}; + for (const name of DEFAULT_UPLOAD_CREDENTIAL_HEADERS) { + const value = request.headers.get(name); + if (value !== null) headers[name] = value; } + return headers; } /** @@ -355,7 +335,7 @@ async function forwardProxyRequest(params: { request, upstreamResponse, headers, - ticketAuthHeaders: caller.credentialHeaders, + uploadHeaders: caller.uploadHeaders, }); } return new Response(upstreamResponse.body, { status: upstreamResponse.status, headers }); @@ -394,12 +374,12 @@ async function rewrittenUploadPreflightResponse(params: { request: Request; upstreamResponse: Response; headers: Headers; - ticketAuthHeaders: Record; + uploadHeaders: Record; }): Promise { - const { request, upstreamResponse, headers, ticketAuthHeaders } = params; + const { request, upstreamResponse, headers, uploadHeaders } = params; const text = await upstreamResponse.text(); headers.set('content-type', upstreamResponse.headers.get('content-type') ?? 'application/json'); - return new Response(rewriteUploadPreflightResponse(text, request, ticketAuthHeaders), { + return new Response(rewriteUploadPreflightResponse(text, request, uploadHeaders), { status: upstreamResponse.status, headers, }); @@ -408,7 +388,7 @@ async function rewrittenUploadPreflightResponse(params: { function rewriteUploadPreflightResponse( body: string, request: Request, - ticketAuthHeaders: Record, + uploadHeaders: Record, ): string { let parsed: unknown; try { @@ -419,31 +399,33 @@ function rewriteUploadPreflightResponse( if (!parsed || typeof parsed !== 'object') return body; const record = parsed as { upload?: { url?: unknown; headers?: unknown } }; - if (!record.upload || typeof record.upload.url !== 'string') { - return body; - } - - const rewrittenUrl = rewriteUploadDirectUrl(record.upload.url, request); - if (!rewrittenUrl) return body; - - const headers: Record = {}; - if (record.upload.headers && typeof record.upload.headers === 'object') { - for (const [name, value] of Object.entries(record.upload.headers)) { - if (!DAEMON_AUTH_HEADER_NAMES.includes(name.toLowerCase())) headers[name] = value; - } - } - Object.assign(headers, ticketAuthHeaders); + if (!record.upload || typeof record.upload !== 'object') return body; + const rewrittenUrl = + typeof record.upload.url === 'string' + ? rewriteUploadDirectUrl(record.upload.url, request) + : null; return JSON.stringify({ ...(parsed as Record), upload: { ...record.upload, - url: rewrittenUrl, - headers, + ...(rewrittenUrl ? { url: rewrittenUrl } : {}), + headers: { ...upstreamTicketContentType(record.upload.headers), ...uploadHeaders }, }, }); } +/** The only upstream ticket header a client ticket repeats; daemon credentials never pass. */ +function upstreamTicketContentType(headers: unknown): Record { + if (!headers || typeof headers !== 'object') return {}; + for (const [name, value] of Object.entries(headers)) { + if (name.toLowerCase() === 'content-type' && typeof value === 'string') { + return { 'content-type': value }; + } + } + return {}; +} + function rewriteUploadDirectUrl(upstreamUrl: string, request: Request): string | null { let parsed: URL; try { diff --git a/packages/proxy/src/index.ts b/packages/proxy/src/index.ts index d8d88d3d95..511243f753 100644 --- a/packages/proxy/src/index.ts +++ b/packages/proxy/src/index.ts @@ -4,6 +4,7 @@ export { createDaemonProxyServer, type DaemonProxy, type DaemonProxyAuthenticate, + type DaemonProxyAuthenticatedClient, type DaemonProxyOptions, type DaemonProxyUpstreamFetch, } from './daemon-proxy.ts'; diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index e513a0a290..a1ff57c325 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -197,7 +197,7 @@ start the daemon with a policy that requires one (`leases.require`, below). The by every client of the proxy, so a host serving several clients through one proxy authenticates each client itself and sets each request's tenant, session isolation, and lease before forwarding it. Embedding `@agent-device/proxy` with its `authenticate` option does the tenant and session -isolation part: the proxy sends each client's requests as the tenant `authenticate` returns. A tenant id is 1-128 letters, numbers, dots, underscores or hyphens; any other id fails the request with a 500. On `/rpc` the proxy accepts only `agent_device.command` and the `agent_device.lease.*` methods, and refuses others with a 401. +isolation part: the proxy sends each client's requests as the tenant `authenticate` returns. A tenant id is 1-128 letters, numbers, dots, underscores or hyphens; any other id fails the request with a 500. On `/rpc` the proxy accepts only `agent_device.command` and the `agent_device.lease.*` methods, and refuses others with a 401. Upload tickets carry the client's own `authorization` and `x-agent-device-token` headers, or the `uploadHeaders` that `authenticate` returns, and never the daemon's token. ## Restrict what clients can do From 54523d581f3af918585d649eef4265592f8685fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 14 Oct 2026 18:04:14 +0200 Subject: [PATCH 7/7] fix(proxy): attach the caller credential only to tickets that name the proxy --- packages/proxy/src/daemon-proxy.test.ts | 12 +++++++++--- packages/proxy/src/daemon-proxy.ts | 5 ++++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index 8a25119a72..f43a34ca54 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -505,18 +505,24 @@ test('with a client token, the ticket carries the client token, never the daemon }); }); -test('a ticket whose url the proxy cannot rewrite still drops the daemon credentials', async () => { +test('a ticket whose url the proxy cannot rewrite carries no credentials', async () => { const upstream = recordingUpstream(() => Response.json({ ok: true, - upload: { url: 'not a url', headers: buildDaemonHttpAuthHeaders(DAEMON_TOKEN) }, + upload: { + url: 'https://elsewhere.example/put/abc', + headers: { + ...buildDaemonHttpAuthHeaders(DAEMON_TOKEN), + 'content-type': 'application/octet-stream', + }, + }, }), ); const proxy = proxyWith(upstream.fetch); const ticketHeaders = await requestTicket(proxy, { authorization: 'Bearer client-secret' }); - expect(ticketHeaders).toEqual(buildDaemonHttpAuthHeaders('client-secret')); + expect(ticketHeaders).toEqual({ 'content-type': 'application/octet-stream' }); }); test('with authenticate, request diagnostics are served only for the caller tenant sessions', async () => { diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index db6a198d5f..dae4eccdbe 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -410,7 +410,10 @@ function rewriteUploadPreflightResponse( upload: { ...record.upload, ...(rewrittenUrl ? { url: rewrittenUrl } : {}), - headers: { ...upstreamTicketContentType(record.upload.headers), ...uploadHeaders }, + headers: { + ...upstreamTicketContentType(record.upload.headers), + ...(rewrittenUrl ? uploadHeaders : {}), + }, }, }); }