diff --git a/packages/contracts/src/daemon-http.test.ts b/packages/contracts/src/daemon-http.test.ts index eb54322728..e83f7f8f17 100644 --- a/packages/contracts/src/daemon-http.test.ts +++ b/packages/contracts/src/daemon-http.test.ts @@ -11,6 +11,8 @@ import { buildRemoteTempArtifactPath, DAEMON_RPC_PROTOCOL_VERSION, isRemoteTempArtifactPath, + isTenantOwnedSessionName, + normalizeTenantId, } from './daemon-http.ts'; test('buildDaemonHttpBaseUrl appends the public agent-device base path', () => { @@ -50,6 +52,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('buildDaemonHttpLeaseHeaders names a held lease and omits a blank one', () => { assert.deepEqual(buildDaemonHttpLeaseHeaders(' lease-1 '), { 'x-agent-device-lease-id': 'lease-1', @@ -106,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 ef8c2a5b85..20ea545822 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -33,6 +33,20 @@ export function buildDaemonHttpAuthHeaders(token: string | undefined): Record:` 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/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/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/resources/lease-registry-scope.ts b/packages/daemon/src/resources/lease-registry-scope.ts index 192fb07241..aa643b9a39 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..88bbed63d8 100644 --- a/packages/daemon/src/sessions/request-admission.ts +++ b/packages/daemon/src/sessions/request-admission.ts @@ -1,6 +1,7 @@ import { AppError } from '@agent-device/kernel/errors'; -import { normalizeTenantId, resolveSessionIsolationMode } from '../core/config.ts'; -import { isTenantOwnedSessionName, tenantScopedSessionName } from '../core/session-tenant-scope.ts'; +import { isTenantOwnedSessionName, normalizeTenantId } from '@agent-device/contracts/daemon-http'; +import { resolveSessionIsolationMode } from '../core/config.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 94e2700fdc..40f718fe89 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,53 @@ 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 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. + +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 | 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 762dfdaede..f43a34ca54 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -1,5 +1,10 @@ import { expect, test } from 'vitest'; -import { createDaemonProxy, type DaemonProxyUpstreamFetch } from './daemon-proxy.ts'; +import { buildDaemonHttpAuthHeaders } from '@agent-device/contracts/daemon-http'; +import { + createDaemonProxy, + type DaemonProxyAuthenticatedClient, + type DaemonProxyUpstreamFetch, +} from './daemon-proxy.ts'; const PROXY_ORIGIN = 'https://gateway.example.test'; @@ -247,3 +252,330 @@ 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'); +}); + +const DAEMON_TOKEN = 'daemon-secret'; + +/** 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') + ? Response.json({ + ok: true, + uploadId: 'abc', + upload: { + url: 'http://127.0.0.1:4310/upload/direct/abc', + 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): 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 token === 'alice-key' ? { tenantId: 'alice' } : null; + }, + }); +} + +async function requestTicket( + proxy: ReturnType, + headers: Record, +): Promise> { + const response = await proxy.handle( + new Request(`${PROXY_ORIGIN}/agent-device/upload/preflight`, { + method: 'POST', + headers: { ...headers, 'content-type': 'application/json' }, + body: '{}', + }), + ); + const text = await response.text(); + 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 naming %s upload headers, the ticket carries exactly those', + async (_name, uploadHeaders) => { + const upstream = daemonTicketUpstream(); + const proxy = proxyAuthenticatingByAnyCredential(upstream.fetch); + + const ticketHeaders = await requestTicket(proxy, { + ...uploadHeaders, + authorization: 'Bearer unrelated', + }); + + expect(ticketHeaders).toEqual({ 'content-type': 'application/zip', ...uploadHeaders }); + }, +); + +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 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 ticketHeaders = await requestTicket(proxy, { authorization: 'Bearer client-secret' }); + + expect(ticketHeaders).toEqual({ + 'content-type': 'application/zip', + ...buildDaemonHttpAuthHeaders('client-secret'), + }); +}); + +test('a ticket whose url the proxy cannot rewrite carries no credentials', async () => { + const upstream = recordingUpstream(() => + Response.json({ + ok: true, + 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({ 'content-type': 'application/octet-stream' }); +}); + +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(); +}); + +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 b9a838846c..dae4eccdbe 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -14,6 +14,8 @@ import { DAEMON_HTTP_TENANT_HEADER, buildDaemonHttpAuthHeaders, buildDaemonHttpUrl, + isTenantOwnedSessionName, + normalizeTenantId, } from '@agent-device/contracts/daemon-http'; import { carriesUnbackedHostPathInstallSource, @@ -27,17 +29,49 @@ 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 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 | DaemonProxyAuthenticatedClient | 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 +85,21 @@ 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; uploadHeaders: Record }; + +/** 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; @@ -127,9 +175,19 @@ 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 }, + ); + } + if (caller.tenantId && route === '/rpc' && !isTenantStampedRpcMethod(rpcBody)) { + return tenantRpcMethodRefusedResponse(readJsonRpcId(rpcBody)); + } const staleInstance = refuseStaleProxyInstance( request, @@ -143,7 +201,76 @@ 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) + ? { uploadHeaders: 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 } : {}), + }), + ); + if (!result) return null; + const tenantId = normalizeTenantId( + typeof result.tenantId === 'string' ? result.tenantId : undefined, + ); + if (!tenantId) { + throw new AppError('COMMAND_FAILED', 'Proxy authenticate returned an invalid tenantId', { + hint: 'Return a tenantId of 1-128 letters, digits, ".", "_" or "-".', + }); + } + return { tenantId, uploadHeaders: result.uploadHeaders ?? defaultUploadHeaders(request) }; +} + +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; +} + +/** + * 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 isTenantOwnedSessionName(tenantId, decodeURIComponent(route.split('/')[2] ?? '')); + } catch { + return false; + } +} + +/** 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( @@ -189,13 +316,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 } : {}), }), @@ -207,7 +335,7 @@ async function forwardProxyRequest(params: { request, upstreamResponse, headers, - clientToken: options.clientToken, + uploadHeaders: caller.uploadHeaders, }); } return new Response(upstreamResponse.body, { status: upstreamResponse.status, headers }); @@ -246,12 +374,12 @@ async function rewrittenUploadPreflightResponse(params: { request: Request; upstreamResponse: Response; headers: Headers; - clientToken: string; + uploadHeaders: Record; }): Promise { - const { request, upstreamResponse, headers, clientToken } = 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, clientToken), { + return new Response(rewriteUploadPreflightResponse(text, request, uploadHeaders), { status: upstreamResponse.status, headers, }); @@ -260,7 +388,7 @@ async function rewrittenUploadPreflightResponse(params: { function rewriteUploadPreflightResponse( body: string, request: Request, - clientToken: string, + uploadHeaders: Record, ): string { let parsed: unknown; try { @@ -271,29 +399,36 @@ 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.upload.headers && typeof record.upload.headers === 'object' - ? { ...(record.upload.headers as Record) } - : {}; - Object.assign(headers, buildDaemonHttpAuthHeaders(clientToken)); + 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), + ...(rewrittenUrl ? 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 { @@ -321,11 +456,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)), @@ -416,12 +554,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'); } @@ -444,9 +584,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; } @@ -491,15 +632,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 } }; @@ -509,6 +669,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 { @@ -573,6 +743,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/packages/proxy/src/index.ts b/packages/proxy/src/index.ts index dfccde8ea1..511243f753 100644 --- a/packages/proxy/src/index.ts +++ b/packages/proxy/src/index.ts @@ -3,6 +3,8 @@ export { createDaemonProxyRequestListener, createDaemonProxyServer, type DaemonProxy, + type DaemonProxyAuthenticate, + type DaemonProxyAuthenticatedClient, type DaemonProxyOptions, type DaemonProxyUpstreamFetch, } from './daemon-proxy.ts'; 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); + } +}); 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'), ], }, { diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index c123cd6c62..a1ff57c325 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -196,6 +196,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. 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