Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions packages/contracts/src/daemon-http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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);
});
14 changes: 14 additions & 0 deletions packages/contracts/src/daemon-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,20 @@ export function buildDaemonHttpAuthHeaders(token: string | undefined): Record<st
};
}

/** The tenant id every daemon route accepts, trimmed, or `undefined` when it breaks the rule. */
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;
}

/** Whether `sessionName` lies beneath the `<tenant>:` 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<string, string> {
const normalizedTenantId = tenantId?.trim();
if (!normalizedTenantId) return {};
Expand Down
8 changes: 0 additions & 8 deletions packages/daemon/src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
16 changes: 8 additions & 8 deletions packages/daemon/src/core/session-tenant-scope.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { isTenantOwnedSessionName } from '@agent-device/contracts/daemon-http';
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

/**
* The one rule that says which sessions belong to a tenant: under tenant
* isolation every session name lives beneath its own `<tenant>:` prefix.
* isolation every session name lives beneath its own `<tenant>:` 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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/daemon/src/resources/lease-registry-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion packages/daemon/src/server/http/http-authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
5 changes: 3 additions & 2 deletions packages/daemon/src/sessions/request-admission.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down
45 changes: 43 additions & 2 deletions packages/proxy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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. |
Expand Down
Loading
Loading