Skip to content

Commit 367e795

Browse files
authored
fix(remote): let a plain-session client read its own failure record (#2382)
`GET /sessions/<session>/requests/<requestId>/diagnostics` applied the `<tenant>:` prefix rule to every caller carrying a tenant, but `scopeRequestSession` only writes that prefix under tenant isolation — which the daemon forces exactly when the auth hook ATTESTS the tenant. A client whose tenant is only declared (the `x-agent-device-tenant` header on a daemon with no auth hook) therefore ran in a plain session such as `default` or `cwd:<hash>:default` and was then refused 401 reading the record its own failed command wrote, directly and through `agent-device proxy`. The addressability rule now lives beside the naming rule in `session-tenant-scope.ts`, which exists so the two cannot disagree. `isTenantAddressableSessionName` takes the caller's session namespace and applies the prefix rule only where the namespace is actually partitioned; `resolveTrustedTenant` now reports whether the tenant was attested, and `authorizeAuxiliaryHttpRequest` hands that namespace to the route. The attested case is unchanged: an attested tenant is still refused any session outside its own prefix, with the same typed UNAUTHORIZED error.
1 parent a9283fa commit 367e795

9 files changed

Lines changed: 310 additions & 34 deletions

File tree

‎src/daemon/__tests__/http-server-tenant-trust.test.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -401,16 +401,50 @@ test('aux route: no hook configured keeps the header-declared tenant unchanged (
401401
},
402402
});
403403
assert.equal(owner.status, 200);
404+
// Nothing attested either header, so `scopeRequestSession` partitioned no
405+
// session namespace and the `<tenant>:` prefix carries no ownership to check
406+
// — the two RPC regressions above show the same caller may already run any
407+
// command in `tenant-a:default`. The token is the gate in this mode.
404408
const otherTenant = await fetch(diagnosticsUrl(baseUrl, 'tenant-a:default', 'abc123'), {
405409
headers: {
406410
authorization: `Bearer ${DAEMON_TOKEN}`,
407411
[DAEMON_HTTP_TENANT_HEADER]: 'tenant-b',
408412
},
409413
});
410-
assert.equal(otherTenant.status, 401);
414+
assert.equal(otherTenant.status, 200);
411415
});
412416
});
413417

418+
test('aux route: an attested tenant is still refused a record outside its partition', async (t) => {
419+
if (await skipWhenLoopbackUnavailable(t)) return;
420+
const root = mkdtempForTestSync('agent-device-tenant-trust-aux-cross-');
421+
try {
422+
const hookPath = writeAttestingAuthHook(root);
423+
await withDiagnosticsHookServer(hookPath, async ({ baseUrl, sessionsDir }) => {
424+
// The hook attests `tenant-real`, so every session that caller can reach is
425+
// named `tenant-real:...`. Another tenant's record, and the plain sessions
426+
// outside the partition, both stay outside what it may address.
427+
writeDiagnosticsRecord(sessionsDir, 'tenant-other:default', 'abc123');
428+
writeDiagnosticsRecord(sessionsDir, 'cwd:9f1:default', 'abc123');
429+
const auth = { authorization: `Bearer ${DAEMON_TOKEN}` };
430+
for (const session of ['tenant-other:default', 'cwd:9f1:default']) {
431+
const refused = await fetch(diagnosticsUrl(baseUrl, session, 'abc123'), { headers: auth });
432+
assert.equal(refused.status, 401, `expected 401 for session ${session}`);
433+
const body = (await refused.json()) as { error?: string; code?: string };
434+
assert.equal(body.code, 'UNAUTHORIZED');
435+
assert.equal(body.error, 'Session is outside this tenant');
436+
}
437+
writeDiagnosticsRecord(sessionsDir, `${ATTESTED_TENANT_ID}:default`, 'abc123');
438+
const own = await fetch(diagnosticsUrl(baseUrl, `${ATTESTED_TENANT_ID}:default`, 'abc123'), {
439+
headers: auth,
440+
});
441+
assert.equal(own.status, 200);
442+
});
443+
} finally {
444+
fs.rmSync(root, { recursive: true, force: true });
445+
}
446+
});
447+
414448
test('aux route (upload): a hook configured but silent on tenant refuses a client-declared header', async (t) => {
415449
if (await skipWhenLoopbackUnavailable(t)) return;
416450
const root = mkdtempForTestSync('agent-device-tenant-trust-upload-');

‎src/daemon/__tests__/request-diagnostics-http.test.ts‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,15 @@ test('request diagnostics route rejects ids that do not name one record', async
140140
});
141141
});
142142

143-
test('request diagnostics route keeps a tenant inside its own session namespace', async (t) => {
143+
/**
144+
* No auth hook is configured on this server, so every tenant here is a
145+
* client-DECLARED label. `scopeRequestSession` partitions nothing for such a
146+
* caller, and the same caller can already run any command in any session over
147+
* `/rpc` (`http-server-tenant-trust.test.ts`, "no hook configured keeps a
148+
* client-declared flags.tenant unchanged"). The prefix rule that does bite is
149+
* proven against an ATTESTING hook in that file.
150+
*/
151+
test('request diagnostics route reads an unattested tenant as no session partition', async (t) => {
144152
if (await skipWhenLoopbackUnavailable(t)) return;
145153

146154
await withDiagnosticsServer(async ({ baseUrl, sessionsDir }) => {
@@ -153,7 +161,38 @@ test('request diagnostics route keeps a tenant inside its own session namespace'
153161
const otherTenant = await fetch(diagnosticsUrl(baseUrl, 'tenant-a:default', 'abc123'), {
154162
headers: { ...auth, 'x-agent-device-tenant': 'tenant-b' },
155163
});
156-
assert.equal(otherTenant.status, 401);
157-
assert.equal((await otherTenant.text()).includes('request_start'), false);
164+
assert.equal(otherTenant.status, 200);
165+
});
166+
});
167+
168+
test('request diagnostics route serves a plain session to the tenant that ran the command', async (t) => {
169+
if (await skipWhenLoopbackUnavailable(t)) return;
170+
171+
await withDiagnosticsServer(async ({ baseUrl, sessionsDir }) => {
172+
writeRecord(sessionsDir, 'default', 'abc123');
173+
const response = await fetch(diagnosticsUrl(baseUrl, 'default', 'abc123'), {
174+
headers: {
175+
authorization: 'Bearer daemon-secret',
176+
'x-agent-device-tenant': 'tenant-a',
177+
},
178+
});
179+
assert.equal(response.status, 200);
180+
assert.equal(await response.text(), RECORD);
181+
});
182+
});
183+
184+
test('request diagnostics route serves the cwd-scoped session its owner ran in', async (t) => {
185+
if (await skipWhenLoopbackUnavailable(t)) return;
186+
187+
await withDiagnosticsServer(async ({ baseUrl, sessionsDir }) => {
188+
writeRecord(sessionsDir, 'cwd:9f1:default', 'abc123');
189+
const response = await fetch(diagnosticsUrl(baseUrl, 'cwd:9f1:default', 'abc123'), {
190+
headers: {
191+
authorization: 'Bearer daemon-secret',
192+
'x-agent-device-tenant': 'tenant-a',
193+
},
194+
});
195+
assert.equal(response.status, 200);
196+
assert.equal(await response.text(), RECORD);
158197
});
159198
});

‎src/daemon/request-diagnostics-http.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@ import { AppError, normalizeError, type DiagnosticsRecordRef } from '@agent-devi
2020
import type { DaemonRequest } from './daemon-request.ts';
2121
import { isSafeSessionSegment } from './session-paths.ts';
2222
import { decodeUriSegment } from './http-request-target.ts';
23-
import { isTenantOwnedSessionName } from './session-tenant-scope.ts';
23+
import {
24+
isTenantAddressableSessionName,
25+
type TenantSessionNamespace,
26+
} from './session-tenant-scope.ts';
2427
import { failStreamedHttpResponse, sendRestJsonError } from './http-errors.ts';
2528

2629
const REQUEST_DIAGNOSTICS_CONTENT_TYPE = 'application/x-ndjson';
@@ -45,7 +48,7 @@ type RequestDiagnosticsHttpAuthorizer = (params: {
4548
req: http.IncomingMessage;
4649
res: http.ServerResponse;
4750
daemonRequest: Pick<DaemonRequest, 'command' | 'positionals'>;
48-
}) => Promise<{ tenantId?: string } | null>;
51+
}) => Promise<{ tenantId?: string; sessionNamespace?: TenantSessionNamespace } | null>;
4952

5053
export type RequestDiagnosticsHttpOptions = {
5154
req: http.IncomingMessage;
@@ -116,7 +119,10 @@ async function handleRequestDiagnostics(
116119
});
117120
if (!auth) return;
118121

119-
if (auth.tenantId && !isTenantOwnedSessionName(auth.tenantId, ref.session)) {
122+
if (
123+
auth.sessionNamespace &&
124+
!isTenantAddressableSessionName(auth.sessionNamespace, ref.session)
125+
) {
120126
sendRestJsonError(
121127
res,
122128
normalizeError(

‎src/daemon/server/http-server.ts‎

Lines changed: 43 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import { tryHandleUploadHttpRoute } from '../upload-http.ts';
4545
import { tryHandleDownloadableArtifactHttpRoute } from '../downloadable-artifact-http.ts';
4646
import { tryHandleRequestDiagnosticsHttpRoute } from '../request-diagnostics-http.ts';
4747
import { resolveTrustedTenant, tenantTrustRejectionError } from './tenant-trust.ts';
48+
import type { TenantSessionNamespace } from '../session-tenant-scope.ts';
4849
import { tryHandleHumanControlHttpRoute } from '../human-control-http.ts';
4950
import type { LeaseRegistry } from '../lease-registry.ts';
5051

@@ -753,7 +754,11 @@ export async function createDaemonHttpServer(options: {
753754
daemonRequest.meta = {
754755
...daemonRequest.meta,
755756
tenantId: tenantTrust.tenantId,
756-
sessionIsolation: authResult.tenantId
757+
// Attestation is what partitions the session namespace: only an attested
758+
// tenant defaults this request to tenant isolation, so only then does
759+
// `scopeRequestSession` name the session `<tenant>:...`. The diagnostics
760+
// route reads the same distinction back out of `authorizeAuxiliaryHttpRequest`.
761+
sessionIsolation: tenantTrust.attested
757762
? (daemonRequest.meta?.sessionIsolation ??
758763
daemonRequest.flags?.sessionIsolation ??
759764
'tenant')
@@ -870,13 +875,20 @@ function statusCodeForDaemonError(error: {
870875
return statusCodeForNormalizedError(error.code);
871876
}
872877

878+
/**
879+
* The token/auth-hook gate every non-RPC route shares. `sessionNamespace` is the
880+
* naming precondition the session-addressed routes need: present only when the
881+
* caller carries a tenant at all, and `partitioned` exactly when that tenant is
882+
* attested, which is the same condition the `/rpc` handler above turns into
883+
* `sessionIsolation: 'tenant'`.
884+
*/
873885
async function authorizeAuxiliaryHttpRequest(params: {
874886
req: http.IncomingMessage;
875887
res: http.ServerResponse;
876888
authHook: HttpAuthHook | null;
877889
expectedToken?: string;
878890
daemonRequest: Pick<DaemonRequest, 'command' | 'positionals'>;
879-
}): Promise<{ tenantId?: string } | null> {
891+
}): Promise<{ tenantId?: string; sessionNamespace?: TenantSessionNamespace } | null> {
880892
const { req, res, authHook, expectedToken, daemonRequest } = params;
881893
const token = resolveToken({}, req.headers);
882894
const tenantId = normalizeTenantId(readHeaderValue(req.headers, DAEMON_HTTP_TENANT_HEADER));
@@ -903,17 +915,7 @@ async function authorizeAuxiliaryHttpRequest(params: {
903915
},
904916
});
905917
if (!authResult.ok) {
906-
res.statusCode = authResult.statusCode;
907-
res.setHeader('content-type', 'application/json');
908-
res.end(
909-
JSON.stringify({
910-
ok: false,
911-
error:
912-
authResult.response.error?.data?.message ??
913-
authResult.response.error?.message ??
914-
'Unauthorized',
915-
}),
916-
);
918+
sendAuxiliaryAuthHookRejection(res, authResult);
917919
return null;
918920
}
919921

@@ -927,7 +929,34 @@ async function authorizeAuxiliaryHttpRequest(params: {
927929
return null;
928930
}
929931

930-
return { tenantId: tenantTrust.tenantId };
932+
const trustedTenant = tenantTrust.tenantId;
933+
return {
934+
tenantId: trustedTenant,
935+
...(trustedTenant
936+
? { sessionNamespace: { tenant: trustedTenant, partitioned: tenantTrust.attested } }
937+
: {}),
938+
};
939+
}
940+
941+
/**
942+
* An auth hook's own rejection, rendered as the flat REST error these routes
943+
* answer with rather than the JSON-RPC envelope the hook decision carries.
944+
*/
945+
function sendAuxiliaryAuthHookRejection(
946+
res: http.ServerResponse,
947+
decision: Extract<HttpAuthDecision, { ok: false }>,
948+
): void {
949+
res.statusCode = decision.statusCode;
950+
res.setHeader('content-type', 'application/json');
951+
res.end(
952+
JSON.stringify({
953+
ok: false,
954+
error:
955+
decision.response.error?.data?.message ??
956+
decision.response.error?.message ??
957+
'Unauthorized',
958+
}),
959+
);
931960
}
932961

933962
function readHeaderValue(headers: IncomingHttpHeaders, name: string): string | undefined {

‎src/daemon/server/tenant-trust.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
11
import { AppError, normalizeError } from '@agent-device/kernel/errors';
22

3+
/**
4+
* `attested` separates the two ways a request can carry a trusted tenant, because
5+
* the daemon treats them differently everywhere downstream: an ATTESTED tenant
6+
* forces `sessionIsolation: 'tenant'`, so `scopeRequestSession` partitions the
7+
* caller's session namespace beneath `<tenant>:`. A merely DECLARED one (no auth
8+
* hook is configured, so the header is taken at face value) partitions nothing —
9+
* the same caller can already reach any session over `/rpc`.
10+
*/
311
export type TenantTrustDecision =
4-
| { trusted: true; tenantId: string | undefined }
12+
| { trusted: true; tenantId: string | undefined; attested: boolean }
513
| { trusted: false };
614

715
export function resolveTrustedTenant(params: {
@@ -10,8 +18,10 @@ export function resolveTrustedTenant(params: {
1018
clientDeclaredTenant: string | undefined;
1119
}): TenantTrustDecision {
1220
const { hookConfigured, hookAttestedTenant, clientDeclaredTenant } = params;
13-
if (hookAttestedTenant) return { trusted: true, tenantId: hookAttestedTenant };
14-
if (!hookConfigured) return { trusted: true, tenantId: clientDeclaredTenant };
21+
if (hookAttestedTenant) return { trusted: true, tenantId: hookAttestedTenant, attested: true };
22+
if (!hookConfigured) {
23+
return { trusted: true, tenantId: clientDeclaredTenant, attested: false };
24+
}
1525
return { trusted: false };
1626
}
1727

‎src/daemon/session-tenant-scope.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,32 @@
66
* (`request-admission.ts`) names the session, and the request diagnostics route
77
* (`request-diagnostics-http.ts`, #1801) decides from the name alone whether a
88
* caller may read that session's record long after the session itself is gone.
9+
*
10+
* The naming side has a precondition the reading side must honor: it applies the
11+
* prefix ONLY under tenant isolation, which the daemon forces exactly when the
12+
* auth hook ATTESTS the tenant (`http-server.ts`). A tenant the caller merely
13+
* declared — the `x-agent-device-tenant` header on a daemon with no auth hook —
14+
* never scopes anything, so its sessions keep the plain names the client asked
15+
* for (`default`, `cwd:<hash>:default`). Reading the prefix rule onto those names
16+
* made the record read stricter than the write that produced it, and refused a
17+
* caller its own record; `isTenantAddressableSessionName` is the rule with that
18+
* precondition attached, so the two sides cannot disagree again.
19+
*/
20+
21+
/**
22+
* A caller's session namespace as the daemon actually partitions it.
23+
*
24+
* `partitioned` is the naming precondition, not a permission level: true means
25+
* `scopeRequestSession` has put every session this caller can reach beneath
26+
* `<tenant>:`, so a name outside that prefix cannot be the caller's own. False
27+
* means the tenant is an unattested label the daemon never partitioned by — the
28+
* same caller can already run any command in any session over `/rpc` — so the
29+
* prefix carries no ownership to check.
930
*/
31+
export type TenantSessionNamespace = {
32+
tenant: string;
33+
partitioned: boolean;
34+
};
1035

1136
export function tenantScopedSessionName(tenant: string, session: string): string {
1237
return isTenantOwnedSessionName(tenant, session) ? session : `${tenant}:${session}`;
@@ -15,3 +40,16 @@ export function tenantScopedSessionName(tenant: string, session: string): string
1540
export function isTenantOwnedSessionName(tenant: string, sessionName: string): boolean {
1641
return sessionName.startsWith(`${tenant}:`);
1742
}
43+
44+
/**
45+
* Whether a caller in `namespace` may address `sessionName` by name — the read
46+
* counterpart of `scopeRequestSession`'s naming decision, and the only tenant
47+
* rule the diagnostics route applies.
48+
*/
49+
export function isTenantAddressableSessionName(
50+
namespace: TenantSessionNamespace,
51+
sessionName: string,
52+
): boolean {
53+
if (!namespace.partitioned) return true;
54+
return isTenantOwnedSessionName(namespace.tenant, sessionName);
55+
}

0 commit comments

Comments
 (0)