From 35993d06fc2773ce9a3b300f988b3ce2069fa786 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 08:43:34 +0100 Subject: [PATCH 01/10] fix(daemon): own artifacts by their producer and bound staged uploads Register every downloadable artifact with a required producer owner (tenant and lease). Capture output from an earlier request carries that producer; finalize no longer mixes in the requesting tenant or lease. Tenant-owned entries serve only their own tenant, so an untenanted upload or artifact is not readable by another tenant. Trace stop, perf stop, and perf report check the full capture owner. Cap staged uploads per tenant with UPLOAD_LIMIT_REACHED, and always run install-source cleanup after materialized cleanup. --- .../__tests__/support/session-factories.ts | 8 +- .../__tests__/support/track-test-artifact.ts | 16 +++ .../core/__tests__/tenant-owned-entry.test.ts | 15 ++- .../src/core/capture-output-ownership.ts | 38 +++---- .../session-script-publication-capability.ts | 13 +-- .../core/session-script-publication-state.ts | 9 +- packages/daemon/src/core/session-state.ts | 3 +- .../daemon/src/core/tenant-owned-entry.ts | 28 +++-- .../src/resources/artifact-tracking.test.ts | 85 ++++++++++----- .../daemon/src/resources/artifact-tracking.ts | 102 ++++++++++++------ .../__tests__/http-server-artifacts.test.ts | 32 +++--- .../http-server-rpc-validation.test.ts | 6 +- .../__tests__/request-finalization.test.ts | 26 ++--- .../request-router-artifacts-web.test.ts | 8 +- .../server/downloadable-artifact-http.test.ts | 8 +- .../http/daemon-runtime-artifacts.test.ts | 8 +- .../http/daemon-runtime-isolation.test.ts | 4 +- .../http-server-capture-publication.test.ts | 6 +- .../http/http-server-perf-report.test.ts | 20 ++-- .../http-server-provider-scenarios.test.ts | 4 +- .../http/http-server-remote-output.test.ts | 11 +- .../daemon/src/server/request-finalization.ts | 16 +-- .../__tests__/request-handler-catalog.test.ts | 8 +- .../record-runtime-stop-recovery.test.ts | 6 +- .../handlers/__tests__/trace-runtime.test.ts | 32 ++++++ .../src/sessions/handlers/record-runtime.ts | 10 +- .../handlers/session-app-source-deployment.ts | 7 +- .../src/sessions/handlers/trace-runtime.ts | 18 ++-- .../internal/session-open-execution.ts | 8 +- .../internal/session-perf-runtime.ts | 73 ++++++------- website/docs/docs/error-reasons.md | 2 + website/docs/docs/remote-proxy.md | 7 +- 32 files changed, 388 insertions(+), 249 deletions(-) create mode 100644 packages/daemon/src/__tests__/support/track-test-artifact.ts diff --git a/packages/daemon/src/__tests__/support/session-factories.ts b/packages/daemon/src/__tests__/support/session-factories.ts index 943f5b6e709..42a67e6efa3 100644 --- a/packages/daemon/src/__tests__/support/session-factories.ts +++ b/packages/daemon/src/__tests__/support/session-factories.ts @@ -35,7 +35,13 @@ export function authoringPublication( ? { kind: 'explicit', path: opts.path, force: opts?.force === true } : { kind: 'default', force: opts?.force === true }, ...(opts?.remote - ? { remoteDelivery: { publicationId: 'publication-0001', revision: 0, tenantId: undefined } } + ? { + remoteDelivery: { + publicationId: 'publication-0001', + revision: 0, + owner: { tenantId: undefined, leaseVerifier: null }, + }, + } : {}), }; } diff --git a/packages/daemon/src/__tests__/support/track-test-artifact.ts b/packages/daemon/src/__tests__/support/track-test-artifact.ts new file mode 100644 index 00000000000..77074fbb7c5 --- /dev/null +++ b/packages/daemon/src/__tests__/support/track-test-artifact.ts @@ -0,0 +1,16 @@ +import { + type DownloadableArtifactRegistration, + trackDownloadableArtifact, +} from '../../resources/artifact-tracking.ts'; + +/** Registers an artifact for a producer named by its tenant and lease verifier; both default to none. */ +export function trackTestArtifact({ + tenantId, + leaseVerifier = null, + ...registration +}: Omit & { + tenantId?: string; + leaseVerifier?: string | null; +}): string { + return trackDownloadableArtifact({ ...registration, owner: { tenantId, leaseVerifier } }); +} diff --git a/packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts b/packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts index fbc7ee2017d..db5e8908fb6 100644 --- a/packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts +++ b/packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts @@ -22,14 +22,21 @@ function captureAppError(fn: () => unknown): AppError { throw new Error('expected an AppError to be thrown'); } -test('requireTenantOwnedEntry returns entries readable by the tenant', () => { +test('requireTenantOwnedEntry returns entries only to their own tenant', () => { const map = new Map([ - ['shared', {}], + ['untenanted', {}], ['owned', { tenantId: 'tenant-a' }], ]); - assert.equal(requireTenantOwnedEntry(map, 'shared', undefined, RESOURCE), map.get('shared')); - assert.equal(requireTenantOwnedEntry(map, 'shared', 'tenant-b', RESOURCE), map.get('shared')); + assert.equal( + requireTenantOwnedEntry(map, 'untenanted', undefined, RESOURCE), + map.get('untenanted'), + ); assert.equal(requireTenantOwnedEntry(map, 'owned', 'tenant-a', RESOURCE), map.get('owned')); + const refused = captureAppError(() => + requireTenantOwnedEntry(map, 'untenanted', 'tenant-b', RESOURCE), + ); + assert.equal(refused.code, 'UNAUTHORIZED'); + assert.equal(refused.details?.reason, 'TENANT_OUTPUT_MISMATCH'); }); test('missing entries surface as expired resources with a recovery hint', () => { diff --git a/packages/daemon/src/core/capture-output-ownership.ts b/packages/daemon/src/core/capture-output-ownership.ts index 01377a1cd2f..53d9c0eb0df 100644 --- a/packages/daemon/src/core/capture-output-ownership.ts +++ b/packages/daemon/src/core/capture-output-ownership.ts @@ -1,25 +1,22 @@ import type { DaemonArtifact, DaemonResponseData } from '@agent-device/kernel/contracts'; +import type { ArtifactOwner } from './tenant-owned-entry.ts'; const CAPTURE_OUTPUT_OWNERSHIP = Symbol('captureOutputOwnership'); type CaptureOutputOwnership = 'daemon' | 'caller'; -type CaptureOutputOwner = Readonly<{ - ownership: CaptureOutputOwnership; - tenantId?: string; - /** Null records an unleased producer. Undefined leaves ownership to the request. */ - leaseVerifier?: string | null; -}>; type CaptureOutputData = DaemonResponseData & { - [CAPTURE_OUTPUT_OWNERSHIP]?: CaptureOutputOwner; + [CAPTURE_OUTPUT_OWNERSHIP]?: Readonly<{ + ownership: CaptureOutputOwnership; + owner: ArtifactOwner; + }>; }; /** Producer-owned capture facts stay private when the response is serialized. */ export function withCaptureOutputOwnership( data: DaemonResponseData, ownership: CaptureOutputOwnership, - tenantId?: string, - leaseVerifier?: string | null, + owner: ArtifactOwner, ): DaemonResponseData { - return { ...data, [CAPTURE_OUTPUT_OWNERSHIP]: { ownership, tenantId, leaseVerifier } }; + return { ...data, [CAPTURE_OUTPUT_OWNERSHIP]: { ownership, owner } }; } export function captureOutputOwnership( @@ -29,39 +26,34 @@ export function captureOutputOwnership( return capture[CAPTURE_OUTPUT_OWNERSHIP]?.ownership; } -export function captureOutputTenantId(data: DaemonResponseData): string | undefined { +export function captureOutputOwner(data: DaemonResponseData): ArtifactOwner | undefined { const capture: CaptureOutputData = data; - return capture[CAPTURE_OUTPUT_OWNERSHIP]?.tenantId; -} - -export function captureOutputLeaseVerifier(data: DaemonResponseData): string | null | undefined { - const capture: CaptureOutputData = data; - return capture[CAPTURE_OUTPUT_OWNERSHIP]?.leaseVerifier; + return capture[CAPTURE_OUTPUT_OWNERSHIP]?.owner; } const DAEMON_DELIVERED_ARTIFACT = Symbol('daemonDeliveredArtifact'); type DeliveredArtifact = DaemonArtifact & { - [DAEMON_DELIVERED_ARTIFACT]?: Readonly<{ tenantId: string | undefined }>; + [DAEMON_DELIVERED_ARTIFACT]?: ArtifactOwner; }; /** * Marks an artifact the daemon produced for the caller itself, such as a remote recording's script - * version. It is registered for download for `tenantId` alone, whatever the request's tenant, + * version. It is registered for download for `owner` alone, whatever the request's tenant, lease, * capture filters, or network marker say. The mark stays private when the response is serialized. */ export function asDaemonDeliveredArtifact( artifact: DaemonArtifact, - tenantId: string | undefined, + owner: ArtifactOwner, ): DaemonArtifact { const delivered: DeliveredArtifact = artifact; - delivered[DAEMON_DELIVERED_ARTIFACT] = { tenantId }; + delivered[DAEMON_DELIVERED_ARTIFACT] = owner; return delivered; } -/** The delivery of a daemon-delivered artifact, or `undefined` for any other artifact. */ +/** The owner of a daemon-delivered artifact, or `undefined` for any other artifact. */ export function daemonDeliveredArtifact( artifact: DaemonArtifact | undefined, -): Readonly<{ tenantId: string | undefined }> | undefined { +): ArtifactOwner | undefined { const delivered: DeliveredArtifact | undefined = artifact; return delivered?.[DAEMON_DELIVERED_ARTIFACT]; } diff --git a/packages/daemon/src/core/session-script-publication-capability.ts b/packages/daemon/src/core/session-script-publication-capability.ts index 7dc5e3dbe91..0b8a0c95944 100644 --- a/packages/daemon/src/core/session-script-publication-capability.ts +++ b/packages/daemon/src/core/session-script-publication-capability.ts @@ -70,18 +70,15 @@ export function armAuthoringOnOpen( ); } -/** - * The remote delivery an `open --save-script` asks for: the publication ID its client minted, when - * well formed, and the tenant that opens it. - */ +/** The publication ID that the client of an `open --save-script` minted, when well formed. */ export function remoteScriptOpen( meta: DaemonRequestMeta | undefined, -): Omit | undefined { +): Pick | undefined { const publicationId = meta?.scriptPublicationId; if (typeof publicationId !== 'string' || !/^[A-Za-z0-9-]{16,64}$/.test(publicationId)) { return undefined; } - return { publicationId, tenantId: meta?.tenantId }; + return { publicationId }; } /** @@ -244,7 +241,7 @@ function stampNextRevision(session: SessionState): RemoteScriptDelivery | undefi /** * Adds one script version of a remote recording to a successful response. The artifact carries the * publication ID and its revision, so the caller writes it only to the destination it recorded and - * keeps the newest version. It registers for the tenant that opened the recording, whoever sent + * keeps the newest version. It registers for the tenant and lease that opened the recording, whoever sent * this request. A failed version keeps the response successful and carries a typed * `scriptDeliveryFailure` with the same publication ID and a warning. */ @@ -280,7 +277,7 @@ function withRemoteScriptVersion( scriptPublicationId: publicationId, scriptRevision: delivery.revision, }, - delivery.tenantId, + delivery.owner, ); const artifacts = Array.isArray(data.artifacts) ? data.artifacts : []; return { ok: true, data: { ...data, artifacts: [...artifacts, artifact] } }; diff --git a/packages/daemon/src/core/session-script-publication-state.ts b/packages/daemon/src/core/session-script-publication-state.ts index 8522b237c1d..734a627c784 100644 --- a/packages/daemon/src/core/session-script-publication-state.ts +++ b/packages/daemon/src/core/session-script-publication-state.ts @@ -13,6 +13,8 @@ * engine can reach any of them. */ +import type { ArtifactOwner } from './tenant-owned-entry.ts'; + /** * Where a script publishes. * @@ -29,14 +31,13 @@ export type SessionScriptTarget = * A remote caller cannot read the daemon target, so each script version is returned as a * `session-script` artifact. `publicationId` is the ID the caller minted for its open, so the caller * writes a version only to the destination it recorded under that ID. `revision` numbers the - * versions, so the caller keeps the newest when downloads finish out of order. Only `tenantId`, the - * tenant that opened the recording, can download a version; an open without a tenant registers its - * versions like every other tenant-less artifact. + * versions, so the caller keeps the newest when downloads finish out of order. Only `owner`, the + * tenant and lease that opened the recording, can download a version. */ export type RemoteScriptDelivery = Readonly<{ publicationId: string; revision: number; - tenantId: string | undefined; + owner: ArtifactOwner; }>; /** diff --git a/packages/daemon/src/core/session-state.ts b/packages/daemon/src/core/session-state.ts index 16e3cd8e0e0..fbed5005f6d 100644 --- a/packages/daemon/src/core/session-state.ts +++ b/packages/daemon/src/core/session-state.ts @@ -17,6 +17,7 @@ import type { PostGesturePreActionBaseline } from '@agent-device/capture-kit/pos import type { SnapshotFreshnessWindow } from '@agent-device/capture-kit/snapshot-freshness'; import type { RefFrame } from './ref-frame-slot.ts'; import type { SessionLease } from './lease-context.ts'; +import type { ArtifactOwner } from './tenant-owned-entry.ts'; import type { SessionScriptPublicationState } from './session-script-publication-state.ts'; /** @@ -259,7 +260,7 @@ export type SessionState = { /** Last stopped CPU-profile coordinates retained for report in the same live session. */ lastPerfProfile?: { profile: PerfProfileHandoff; - leaseVerifier: string | null; + owner: ArtifactOwner; }; /** Native sampler mechanics stay behind the adopted runtime handle. */ audioProbe?: { diff --git a/packages/daemon/src/core/tenant-owned-entry.ts b/packages/daemon/src/core/tenant-owned-entry.ts index ba615e0c965..fa1f0e57764 100644 --- a/packages/daemon/src/core/tenant-owned-entry.ts +++ b/packages/daemon/src/core/tenant-owned-entry.ts @@ -3,18 +3,24 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; export const TENANT_RESOURCE_REASONS = { // The artifact, upload, or path id expired or never existed; the daemon cannot tell which. expired: { reason: 'RESOURCE_EXPIRED' }, + // The artifact, upload, path, or capture belongs to another tenant than the one the request sends. + tenantMismatch: { reason: 'TENANT_OUTPUT_MISMATCH' }, } as const satisfies ReasonTable<'daemon resources'>; -type TenantOwnedEntry = { tenantId?: string | null }; +type TenantOwnedEntry = { tenantId?: string }; -/** An explicit null owner restricts access to the shared, unnamed tenant scope. */ +/** The tenant and lease of the request that produced an output. Null records an unleased producer. */ +export type ArtifactOwner = Readonly<{ + tenantId: string | undefined; + leaseVerifier: string | null; +}>; + +/** An entry serves only its own tenant. An entry without a tenant serves only tenant-less requests. */ export function matchesTenantOwnedEntry( entry: TenantOwnedEntry, tenantId: string | undefined, ): boolean { - return entry.tenantId === null - ? tenantId === undefined - : !entry.tenantId || entry.tenantId === tenantId; + return entry.tenantId === tenantId; } export type TenantOwnedResourceKind = { @@ -46,10 +52,14 @@ export function requireTenantOwnedEntry( throw expiredTenantOwnedEntryError(kind, id); } if (!matchesTenantOwnedEntry(entry, tenantId)) { - throw new AppError( - 'UNAUTHORIZED', - `${kind.label} ${kind.plural ? 'belong' : 'belongs'} to a different tenant`, - ); + throw tenantOutputRefusal(`${kind.label} ${kind.plural ? 'belong' : 'belongs'}`); } return entry; } + +/** `subject` names the resource and its verb, such as "Trace belongs". */ +export function tenantOutputRefusal(subject: string): AppError { + return new AppError('UNAUTHORIZED', `${subject} to a different tenant`, { + reason: TENANT_RESOURCE_REASONS.tenantMismatch.reason, + }); +} diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index bd63521f94f..1e4dfb9540a 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -22,10 +22,12 @@ import { requestTraceDiagnostics, reserveFileOutput, settleCommittedFileOutputs, - trackDownloadableArtifact, trackUploadedArtifact, + prepareUploadedArtifact, + cleanupUploadedArtifact, type OpenedDownloadableArtifact, } from './artifact-tracking.ts'; +import { trackTestArtifact } from '../__tests__/support/track-test-artifact.ts'; test.each(['expiry', 'restart'] as const)( 'reserved outputs are absent from inventory until commit and stop serving after %s', @@ -162,9 +164,7 @@ test.each(['cleanup', 'expiry'] as const)( let id: string; let expire: (() => void) | undefined; try { - id = runtime.run(() => - trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), - ); + id = runtime.run(() => trackTestArtifact({ artifactPath, artifactType: 'trace-log' })); expire = timers.mock.calls.find(([, delay]) => delay === 15 * 60 * 1000)?.[0]; } finally { timers.mockRestore(); @@ -208,9 +208,7 @@ test('a missing cached directory archive is rebuilt from the live source', async const runtime = createRuntimeStateHandle(); const downloads: OpenedDownloadableArtifact[] = []; try { - const id = runtime.run(() => - trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), - ); + const id = runtime.run(() => trackTestArtifact({ artifactPath, artifactType: 'trace-log' })); const first = await runtime.run(() => openDownloadableArtifact(id, {}, process.env)); downloads.push(first); expect(gunzipSync(await buffer(first.stream)).includes(expected)).toBe(true); @@ -257,9 +255,7 @@ test('cancelling the archive builder preserves a second download waiting for its const timers = vi.spyOn(globalThis, 'setTimeout'); const openings: Array> = []; try { - const id = runtime.run(() => - trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), - ); + const id = runtime.run(() => trackTestArtifact({ artifactPath, artifactType: 'trace-log' })); const timerIndex = timers.mock.calls.length; const first = runtime.run(() => openDownloadableArtifact(id, {}, process.env)); openings.push(first); @@ -332,9 +328,7 @@ test.each(['deadline-aborted', 'late-aborted'] as const)( }); const openings: Array> = []; try { - const id = runtime.run(() => - trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), - ); + const id = runtime.run(() => trackTestArtifact({ artifactPath, artifactType: 'trace-log' })); const timers = vi.spyOn(globalThis, 'setTimeout'); const first = runtime.run(() => openDownloadableArtifact(id, {}, process.env)); openings.push(first); @@ -403,9 +397,7 @@ test.each(['before opening', 'while archiving'] as const)( }); let opening: Promise | undefined; try { - const id = runtime.run(() => - trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), - ); + const id = runtime.run(() => trackTestArtifact({ artifactPath, artifactType: 'trace-log' })); if (phase === 'before opening') caller.abort(reason); opening = runtime.run(() => openDownloadableArtifact(id, {}, process.env, caller.signal)); void opening.catch(() => {}); @@ -452,9 +444,7 @@ test('disposing every archive waiter aborts the shared build and removes its tem }); const openings: Array> = []; try { - const id = runtime.run(() => - trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), - ); + const id = runtime.run(() => trackTestArtifact({ artifactPath, artifactType: 'trace-log' })); openings.push(runtime.run(() => openDownloadableArtifact(id, {}, process.env))); await started; openings.push(runtime.run(() => openDownloadableArtifact(id, {}, process.env))); @@ -560,7 +550,7 @@ test.each(['old-first', 'new-first'] as const)( const { spy: removed, removal } = watchRemovals(); const downloads: OpenedDownloadableArtifact[] = []; const track = () => - runtime.run(() => trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' })); + runtime.run(() => trackTestArtifact({ artifactPath, artifactType: 'trace-log' })); try { const firstId = track(); downloads.push(await runtime.run(() => openDownloadableArtifact(firstId, {}, process.env))); @@ -620,9 +610,7 @@ test.each(['expiry-first', 'deadline-first'] as const)( const { spy: removed, removal } = watchRemovals(); let download: OpenedDownloadableArtifact | undefined; try { - const id = runtime.run(() => - trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), - ); + const id = runtime.run(() => trackTestArtifact({ artifactPath, artifactType: 'trace-log' })); const expire = timers.mock.calls.at(-1)![0]; const expiryTimer = timers.mock.results.at(-1)!.value; const timerIndex = timers.mock.calls.length; @@ -681,7 +669,7 @@ test('disposing a runtime removes the temporary files it still tracks', () => { const runtime = createRuntimeStateHandle(); runtime.run(() => { - trackDownloadableArtifact({ + trackTestArtifact({ artifactPath, artifactType: 'runtime-artifact', fileName: 'artifact.txt', @@ -694,6 +682,47 @@ test('disposing a runtime removes the temporary files it still tracks', () => { expect(fs.existsSync(artifactPath)).toBe(false); }); +test('another tenant cannot consume an upload that has no tenant', () => { + const uploadDir = mkdtempForTestSync('agent-device-upload-untenanted-'); + const runtime = createRuntimeStateHandle(); + runtime.run(() => { + const id = trackUploadedArtifact({ + artifactPath: path.join(uploadDir, 'app'), + tempDir: uploadDir, + }); + expect(() => prepareUploadedArtifact(id, 'tenant-b')).toThrow( + expect.objectContaining({ + code: 'UNAUTHORIZED', + details: { reason: 'TENANT_OUTPUT_MISMATCH' }, + }), + ); + expect(prepareUploadedArtifact(id, undefined)).toBe(path.join(uploadDir, 'app')); + }); + runtime.dispose(); +}); + +test('a tenant stages a bounded number of uploads', () => { + const root = mkdtempForTestSync('agent-device-upload-cap-'); + const runtime = createRuntimeStateHandle(); + runtime.run(() => { + const stage = (tenantId: string, index: number) => { + const tempDir = path.join(root, `${tenantId}-${index}`); + fs.mkdirSync(tempDir); + return trackUploadedArtifact({ artifactPath: path.join(tempDir, 'app'), tempDir, tenantId }); + }; + const staged = Array.from({ length: 32 }, (_, index) => stage('tenant-a', index)); + expect(() => stage('tenant-a', 32)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'UPLOAD_LIMIT_REACHED' }), + }), + ); + stage('tenant-b', 0); + cleanupUploadedArtifact(staged[0]!); + stage('tenant-a', 33); + }); + runtime.dispose(); +}); + test('a file tracked twice for one tenant keeps one id, and another tenant gets its own', () => { const root = mkdtempForTestSync('agent-device-artifact-reuse-'); const artifactPath = path.join(root, 'recording.mp4'); @@ -702,7 +731,7 @@ test('a file tracked twice for one tenant keeps one id, and another tenant gets const [first, again, otherTenant] = runtime.run(() => { const track = (tenantId: string) => - trackDownloadableArtifact({ + trackTestArtifact({ artifactPath, tenantId, artifactType: 'screen-recording', @@ -727,7 +756,7 @@ test.each([ const capture = (bytes: string, leaseId: string | undefined) => { fs.writeFileSync(artifactPath, bytes); return runtime.run(() => - trackDownloadableArtifact({ + trackTestArtifact({ artifactPath, tenantId: 'tenant-a', artifactType: 'screenshot', @@ -772,7 +801,7 @@ test.each( const downloads: OpenedDownloadableArtifact[] = []; const track = (deleteAfterDownload = true) => runtime.run(() => - trackDownloadableArtifact({ + trackTestArtifact({ artifactPath, artifactType: 'trace-log', tenantId: 'tenant-a', @@ -833,7 +862,7 @@ test('a file download streams from the descriptor whose identity was checked', a const root = mkdtempForTestSync('artifact-descriptor-'); const source = path.join(root, 'capture.mp4'); fs.writeFileSync(source, 'recorded-video'); - const id = trackDownloadableArtifact({ artifactPath: source, artifactType: 'screen-recording' }); + const id = trackTestArtifact({ artifactPath: source, artifactType: 'screen-recording' }); const checked = vi.spyOn(fs, 'fstatSync'); const streams = vi.spyOn(fs, 'createReadStream'); try { diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 0699d3a6117..4eeb5ef30d3 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -16,9 +16,11 @@ import { normalizeLeaseId } from '@agent-device/contracts/lease-scope'; import type { DaemonArtifactInventoryEntry } from '@agent-device/contracts/observability'; import type { PackedGzipTar } from '@agent-device/host-kit/gzip-tar'; import { + type ArtifactOwner, expiredTenantOwnedEntryError, matchesTenantOwnedEntry, requireTenantOwnedEntry, + tenantOutputRefusal, type TenantOwnedResourceKind, } from '../core/tenant-owned-entry.ts'; import { @@ -30,7 +32,7 @@ import { timingSafeStringEqual } from '@agent-device/host-kit/transport'; import type { DaemonRequest } from '../core/daemon-request.ts'; import type { SessionRef } from '../core/session-state.ts'; import type { SessionStore } from '../core/session-store.ts'; -import { resolveLeaseScope } from '../core/lease-context.ts'; +import { LEASE_FIELD_NORMALIZERS, resolveLeaseScope } from '../core/lease-context.ts'; // --- Leased output ownership --- @@ -51,6 +53,29 @@ export function admittedOutputLeaseVerifier(req: Pick return leaseId === undefined ? null : leaseVerifier(leaseId); } +/** The owner of the output that this request produces. */ +export function requestArtifactOwner( + req: Pick, +): ArtifactOwner { + return { + tenantId: + req.internal?.admittedLease?.tenantId ?? + LEASE_FIELD_NORMALIZERS.tenantId(resolveLeaseScope(req).tenantId), + leaseVerifier: admittedOutputLeaseVerifier(req), + }; +} + +/** Refuses a request that is not the producer of a capture: another tenant or another lease. */ +export function assertRequestOwnsCapture( + owner: ArtifactOwner, + req: Pick, + label: string, +): void { + const reader = requestArtifactOwner(req); + if (owner.leaseVerifier !== reader.leaseVerifier) throw leasedOutputRefusal(label); + if (owner.tenantId !== reader.tenantId) throw tenantOutputRefusal(`${label} belongs`); +} + export function requestTraceDiagnostics( req: DaemonRequest, ref: SessionRef | undefined, @@ -177,7 +202,7 @@ type ArtifactDownload = { type ArtifactEntry = { artifactPath: string; - tenantId?: string | null; + tenantId: string | undefined; leaseVerifier?: string; reservation?: Readonly<{ directory?: string; lifetimeId: string }>; /** The output that was registered. Another output written to `artifactPath` is not this artifact. */ @@ -202,7 +227,7 @@ type ArtifactTrackingState = { uploads: Map; retainedPerformanceSources: Map< string, - { output: string; leaseVerifier: string | null; birthtimeMs: number } + { output: string; owner: ArtifactOwner; birthtimeMs: number } >; }; @@ -247,9 +272,8 @@ export function settleCommittedFileOutputs( /** What a finished request registers for each artifact it hands back to the client. */ export type DownloadableArtifactRegistration = { artifactPath: string; - tenantId?: string; - /** {@link leaseVerifier} of the lease that produced the artifact. Only a request that sends that lease id lists or downloads it. */ - leaseVerifier?: string; + /** The producer. Only its tenant, and for a leased producer only a request that sends its lease id, lists or downloads it. */ + owner: ArtifactOwner; artifactType: DaemonArtifactType | undefined; fileName?: string; displayRotation?: DeviceRotation; @@ -303,8 +327,7 @@ export function reserveFileOutput( { artifactPath, artifactType, - tenantId, - leaseVerifier: leaseVerifier ?? undefined, + owner: { tenantId, leaseVerifier }, fileName: delivery.fileName, displayRotation, }, @@ -358,8 +381,7 @@ export function commitRecordingFileOutputs( artifactPath, artifactType: delivery.artifactType, fileName: delivery.fileName, - tenantId: producer.tenantId ?? null, - leaseVerifier: producer.leaseVerifier ?? undefined, + owner: producer, sessionName, }, sourceIdentity, @@ -413,7 +435,7 @@ export function trackDownloadableArtifact(params: DownloadableArtifactRegistrati function addArtifactEntry( artifacts: Map, artifactId: string, - params: Omit & Pick, + params: DownloadableArtifactRegistration, output: string | undefined, sourceCleanup: ArtifactSourceCleanup, reservation?: ArtifactEntry['reservation'], @@ -429,8 +451,8 @@ function addArtifactEntry( timer.unref(); artifacts.set(artifactId, { artifactPath: params.artifactPath, - tenantId: params.tenantId, - ...(params.leaseVerifier !== undefined ? { leaseVerifier: params.leaseVerifier } : {}), + tenantId: params.owner.tenantId, + ...(params.owner.leaseVerifier !== null ? { leaseVerifier: params.owner.leaseVerifier } : {}), output, reservation, artifactType: params.artifactType, @@ -447,17 +469,17 @@ function addArtifactEntry( } function findTrackedArtifactId( - owner: Pick, + { artifactPath, owner }: Pick, output: string | undefined, ): string | undefined { for (const [artifactId, entry] of pendingArtifacts()) { if ( !entry.cleanupRequested && !entry.reservation && - entry.artifactPath === owner.artifactPath && + entry.artifactPath === artifactPath && entry.output === output && entry.tenantId === owner.tenantId && - entry.leaseVerifier === owner.leaseVerifier + (entry.leaseVerifier ?? null) === owner.leaseVerifier ) return artifactId; } @@ -485,13 +507,13 @@ function readOutputIdentity(artifactPath: string, noFollow = false): string | un } /** Keeps the report source owner independently of the downloadable copy and latest handoff. */ -export function retainPerfReportSource(source: string, leaseVerifier: string | null): void { +export function retainPerfReportSource(source: string, owner: ArtifactOwner): void { const canonical = fs.realpathSync(source); const stat = fs.statSync(canonical); artifactTracking().retainedPerformanceSources.set(canonical, { output: outputFileIdentity(stat), birthtimeMs: stat.birthtimeMs, - leaseVerifier, + owner, }); } @@ -499,28 +521,25 @@ export function retainPerfReportSource(source: string, leaseVerifier: string | n export function assertTrackedPerformanceSourceLease( canonical: string, source: fs.Stats, - caller: string | null, + req: Pick, ): void { const identity = outputFileIdentity(source); const state = artifactTracking(); for (const [retainedPath, entry] of state.retainedPerformanceSources) { if ( - entry.leaseVerifier && - entry.leaseVerifier !== caller && - (canonical === retainedPath || - (identity === entry.output && source.birthtimeMs === entry.birthtimeMs)) + canonical === retainedPath || + (identity === entry.output && source.birthtimeMs === entry.birthtimeMs) ) { - throw leasedOutputRefusal('Performance capture'); + assertRequestOwnsCapture(entry.owner, req, 'Performance capture'); } } for (const entry of state.artifacts.values()) { - if ( - entry.artifactType === 'performance' && - entry.leaseVerifier && - entry.leaseVerifier !== caller && - entry.output === identity - ) { - throw leasedOutputRefusal('Performance capture'); + if (entry.artifactType === 'performance' && entry.output === identity) { + assertRequestOwnsCapture( + { tenantId: entry.tenantId, leaseVerifier: entry.leaseVerifier ?? null }, + req, + 'Performance capture', + ); } } } @@ -907,6 +926,12 @@ function cleanupDirectoryArchive(entry: ArtifactEntry): void { // --- Upload artifact tracking --- const UPLOAD_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes +const MAX_STAGED_UPLOADS_PER_TENANT = 32; + +const STAGED_UPLOAD_REASONS = { + // The tenant already holds the maximum number of uploaded artifacts that no command consumed yet. + limitReached: { reason: 'UPLOAD_LIMIT_REACHED' }, +} as const satisfies ReasonTable<'uploads'>; const UPLOADED_ARTIFACT_RESOURCE: TenantOwnedResourceKind = { label: 'Uploaded artifact', @@ -916,7 +941,7 @@ const UPLOADED_ARTIFACT_RESOURCE: TenantOwnedResourceKind = { type UploadEntry = { artifactPath: string; tempDir: string; - tenantId?: string; + tenantId: string | undefined; timer: ReturnType; }; @@ -925,6 +950,19 @@ export function trackUploadedArtifact(params: { tempDir: string; tenantId?: string; }): string { + const staged = [...pendingUploads().values()].filter( + (entry) => entry.tenantId === params.tenantId, + ).length; + if (staged >= MAX_STAGED_UPLOADS_PER_TENANT) { + throw new AppError( + 'COMMAND_FAILED', + `Too many uploaded artifacts are waiting for a command (limit ${MAX_STAGED_UPLOADS_PER_TENANT}).`, + { + reason: STAGED_UPLOAD_REASONS.limitReached.reason, + hint: `Install the uploaded artifacts, or wait ${UPLOAD_CLEANUP_TIMEOUT_MS / 60_000} minutes for them to expire, then upload again.`, + }, + ); + } const uploadId = crypto.randomUUID(); const timer = setTimeout(() => { cleanupUploadedArtifact(uploadId); diff --git a/packages/daemon/src/server/__tests__/http-server-artifacts.test.ts b/packages/daemon/src/server/__tests__/http-server-artifacts.test.ts index 43ec2227070..f0e10e3e663 100644 --- a/packages/daemon/src/server/__tests__/http-server-artifacts.test.ts +++ b/packages/daemon/src/server/__tests__/http-server-artifacts.test.ts @@ -8,7 +8,6 @@ import { createDaemonHttpServer } from '../http/http-server.ts'; import { cleanupDownloadableArtifact, listDownloadableArtifacts, - trackDownloadableArtifact, } from '../../resources/artifact-tracking.ts'; import { runCmdSync, withCommandExecutorOverride } from '@agent-device/host-kit/command'; import { @@ -17,6 +16,7 @@ import { mkdtempForTestSync, skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; +import { trackTestArtifact } from '../../__tests__/support/track-test-artifact.ts'; type ArtifactInventoryResponse = { artifacts: Array<{ @@ -39,18 +39,18 @@ test('downloadable artifact inventory is filtered by tenant', async () => { fs.writeFileSync(tenantAPath, 'tenant-a'); fs.writeFileSync(tenantBPath, 'tenant-b'); const artifactIds = [ - trackDownloadableArtifact({ + trackTestArtifact({ artifactPath: publicPath, artifactType: 'test-public-file', fileName: 'public.txt', }), - trackDownloadableArtifact({ + trackTestArtifact({ artifactPath: tenantAPath, tenantId: 'tenant-a', artifactType: 'test-tenant-file', fileName: 'tenant-a.txt', }), - trackDownloadableArtifact({ + trackTestArtifact({ artifactPath: tenantBPath, tenantId: 'tenant-b', artifactType: 'test-tenant-file', @@ -67,13 +67,13 @@ test('downloadable artifact inventory is filtered by tenant', async () => { (await listDownloadableArtifacts({ tenantId: 'tenant-a' }, process.env)).map( (artifact) => artifact.filename, ), - ['public.txt', 'tenant-a.txt'], + ['tenant-a.txt'], ); assert.deepEqual( (await listDownloadableArtifacts({ tenantId: 'tenant-b' }, process.env)).map( (artifact) => artifact.filename, ), - ['public.txt', 'tenant-b.txt'], + ['tenant-b.txt'], ); } finally { for (const artifactId of artifactIds) { @@ -91,12 +91,12 @@ test('downloadable artifact inventory skips directory artifacts that fail to arc fs.mkdirSync(tracePath, { recursive: true }); fs.writeFileSync(path.join(tracePath, 'metadata.json'), '{}\n'); const artifactIds = [ - trackDownloadableArtifact({ + trackTestArtifact({ artifactPath: filePath, artifactType: 'test-report', fileName: 'report.json', }), - trackDownloadableArtifact({ + trackTestArtifact({ artifactPath: tracePath, artifactType: 'trace-log', fileName: 'profile.trace', @@ -130,7 +130,7 @@ test('daemon artifact inventory exposes directory artifacts as tar.gz downloads' const tracePath = path.join(tempDir, '--profile.trace'); fs.mkdirSync(tracePath, { recursive: true }); fs.writeFileSync(path.join(tracePath, 'metadata.json'), '{"ok":true}\n'); - const artifactId = trackDownloadableArtifact({ + const artifactId = trackTestArtifact({ artifactPath: tracePath, artifactType: 'trace-log', fileName: 'profile.trace', @@ -195,7 +195,7 @@ test('daemon artifact inventory lists artifacts and downloads consume them', asy const tempDir = mkdtempForTestSync('agent-device-artifacts-http-'); const artifactPath = path.join(tempDir, 'shot.png'); fs.writeFileSync(artifactPath, 'png-body'); - const artifactId = trackDownloadableArtifact({ + const artifactId = trackTestArtifact({ artifactPath, artifactType: 'screenshot', fileName: 'shot.png', @@ -253,7 +253,7 @@ test('daemon artifact downloads can keep the source file while consuming the inv const tempDir = mkdtempForTestSync('agent-device-artifacts-retain-file-'); const artifactPath = path.join(tempDir, 'runner-output.txt'); fs.writeFileSync(artifactPath, 'runner-output'); - const artifactId = trackDownloadableArtifact({ + const artifactId = trackTestArtifact({ artifactPath, artifactType: 'runner-output', fileName: 'runner-output.txt', @@ -304,7 +304,7 @@ test('daemon artifact downloads can be forced retained by server option', async const tempDir = mkdtempForTestSync('agent-device-artifacts-retain-all-'); const artifactPath = path.join(tempDir, 'session-log.txt'); fs.writeFileSync(artifactPath, 'log-body'); - const artifactId = trackDownloadableArtifact({ + const artifactId = trackTestArtifact({ artifactPath, artifactType: 'session-log', fileName: 'session-log.txt', @@ -352,7 +352,7 @@ test('daemon artifact downloads answer 404 for a consumed or unknown artifact id const tempDir = mkdtempForTestSync('agent-device-artifacts-gone-'); const artifactPath = path.join(tempDir, 'shot.png'); fs.writeFileSync(artifactPath, 'png-body'); - const artifactId = trackDownloadableArtifact({ + const artifactId = trackTestArtifact({ artifactPath, artifactType: 'screenshot', fileName: 'shot.png', @@ -415,13 +415,13 @@ test('downloadable artifact inventory reports a screenshot display rotation only const plainPath = path.join(tempDir, 'plain.png'); fs.writeFileSync(rotatedPath, 'png-body'); fs.writeFileSync(plainPath, 'png-body'); - const rotatedId = trackDownloadableArtifact({ + const rotatedId = trackTestArtifact({ artifactPath: rotatedPath, artifactType: 'screenshot', fileName: 'rotated.png', displayRotation: 'landscape-right', }); - const plainId = trackDownloadableArtifact({ + const plainId = trackTestArtifact({ artifactPath: plainPath, artifactType: 'screenshot', fileName: 'plain.png', @@ -444,7 +444,7 @@ test('retiring stale inventory preserves the file now at its path', async () => const root = mkdtempForTestSync('stale-artifact-'); const artifactPath = path.join(root, 'artifact.png'); fs.writeFileSync(artifactPath, 'old'); - const id = trackDownloadableArtifact({ artifactPath, artifactType: 'screenshot' }); + const id = trackTestArtifact({ artifactPath, artifactType: 'screenshot' }); const next = path.join(root, 'replacement.png'); fs.writeFileSync(next, 'replacement'); fs.renameSync(next, artifactPath); diff --git a/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts b/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts index cf04f3028e9..2c462c43bc6 100644 --- a/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts +++ b/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts @@ -271,7 +271,11 @@ test('remote HTTP accepts an uploaded path artifact without resolving the client const root = mkdtempForTestSync('agent-device-http-uploaded-path-'); const artifactPath = path.join(root, 'uploaded.apk'); fs.writeFileSync(artifactPath, 'uploaded'); - const uploadedArtifactId = trackUploadedArtifact({ artifactPath, tempDir: root }); + const uploadedArtifactId = trackUploadedArtifact({ + artifactPath, + tempDir: root, + tenantId: 'tenant-test', + }); const hookPath = writeAllowingAuthHook(root); const received: DaemonRequest[] = []; const server = await createDaemonHttpServer({ diff --git a/packages/daemon/src/server/__tests__/request-finalization.test.ts b/packages/daemon/src/server/__tests__/request-finalization.test.ts index 39cb28cda63..e323796ce95 100644 --- a/packages/daemon/src/server/__tests__/request-finalization.test.ts +++ b/packages/daemon/src/server/__tests__/request-finalization.test.ts @@ -102,7 +102,7 @@ test('finalizeDaemonResponse registers downloadable artifact type', () => { }; const tracked: Array<{ artifactPath: string; - tenantId?: string; + owner: DownloadableArtifactRegistration['owner']; artifactType?: DaemonArtifactType; fileName?: string; }> = []; @@ -142,13 +142,13 @@ test('finalizeDaemonResponse registers downloadable artifact type', () => { expect(tracked).toEqual([ { artifactPath: '/tmp/telemetry.json', - tenantId: 'tenant-a', + owner: { tenantId: 'tenant-a', leaseVerifier: null }, artifactType: 'screen-recording-telemetry', fileName: 'telemetry.json', }, { artifactPath: '/tmp/raw.bin', - tenantId: 'tenant-a', + owner: { tenantId: 'tenant-a', leaseVerifier: null }, artifactType: undefined, fileName: 'raw.bin', }, @@ -259,7 +259,7 @@ test('a committed screenshot keeps its ID alongside a delivered script revision' scriptPublicationId: 'publication', scriptRevision: 2, }, - 'tenant-a', + { tenantId: 'tenant-a', leaseVerifier: null }, ); const tracked: DownloadableArtifactRegistration[] = []; const response = finalizeDaemonResponse( @@ -353,7 +353,7 @@ test.each([ }; const script = asDaemonDeliveredArtifact( { field: 'savedScript', artifactType: 'session-script', path: '/tmp/script.ad' }, - 'tenant-a', + { tenantId: 'tenant-a', leaseVerifier: null }, ); finalizeDaemonResponse(req, { ok: true, data: { artifacts: [script] } }, (registration) => { @@ -361,12 +361,13 @@ test.each([ return 'artifact-id'; }); - expect(registrations.map(({ tenantId }) => tenantId)).toEqual(['tenant-a']); + expect(registrations.map(({ owner }) => owner.tenantId)).toEqual(['tenant-a']); }, ); -test('a delivered script keeps the admitted lease alongside an unleased recording', () => { +test('finalize registers each artifact for its producer, not for the request that returns it', () => { const lease = new LeaseRegistry().allocateLease({ tenantId: 'tenant', runId: 'record' }); + const scriptOwner = { tenantId: 'tenant', leaseVerifier: leaseVerifier('a'.repeat(32)) }; const tracked: DownloadableArtifactRegistration[] = []; finalizeDaemonResponse( { @@ -389,13 +390,12 @@ test('a delivered script keeps the admitted lease alongside an unleased recordin artifactType: 'session-script', path: '/daemon/session.ad', }, - 'tenant', + scriptOwner, ), ], }, 'daemon', - undefined, - null, + { tenantId: 'tenant-a', leaseVerifier: null }, ), }, (entry) => { @@ -403,8 +403,8 @@ test('a delivered script keeps the admitted lease alongside an unleased recordin return 'artifact'; }, ); - expect(tracked.map((artifact) => [artifact.tenantId, artifact.leaseVerifier])).toEqual([ - ['tenant', undefined], - ['tenant', leaseVerifier(lease.leaseId)], + expect(tracked.map((artifact) => artifact.owner)).toEqual([ + { tenantId: 'tenant-a', leaseVerifier: null }, + scriptOwner, ]); }); diff --git a/packages/daemon/src/server/__tests__/request-router-artifacts-web.test.ts b/packages/daemon/src/server/__tests__/request-router-artifacts-web.test.ts index 2173f6cd73e..d1f2ea9ea4c 100644 --- a/packages/daemon/src/server/__tests__/request-router-artifacts-web.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-artifacts-web.test.ts @@ -14,11 +14,9 @@ import { createTestHostEnvironment, } from '@agent-device/test-kit'; -import { - cleanupDownloadableArtifact, - trackDownloadableArtifact, -} from '../../resources/artifact-tracking.ts'; +import { cleanupDownloadableArtifact } from '../../resources/artifact-tracking.ts'; import { fakeCreateCommandSurface } from '../../__tests__/support/command-surface-fake.ts'; +import { trackTestArtifact } from '../../__tests__/support/track-test-artifact.ts'; // #1900: `artifacts` (`handlers/lease.ts`) lists daemon-tracked artifacts by tenant scope with no // device or platform involvement at all — `listArtifactsForRequest` never reads `device.platform`. @@ -30,7 +28,7 @@ test('artifacts lists a daemon-tracked artifact produced during a web session', const artifactDir = mkdtempForTestSync('agent-device-router-artifacts-web-file-'); const artifactPath = path.join(artifactDir, 'web-smoke.png'); fs.writeFileSync(artifactPath, 'fixture-bytes'); - const artifactId = trackDownloadableArtifact({ + const artifactId = trackTestArtifact({ artifactPath, artifactType: 'screenshot', fileName: 'web-smoke.png', diff --git a/packages/daemon/src/server/downloadable-artifact-http.test.ts b/packages/daemon/src/server/downloadable-artifact-http.test.ts index b4453b9c25f..3d74c4896fe 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.test.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.test.ts @@ -12,8 +12,8 @@ import { mkdtempForTestSync, skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; -import * as artifactTracking from '../resources/artifact-tracking.ts'; import { createDaemonHttpServer } from './http/http-server.ts'; +import { trackTestArtifact } from '../__tests__/support/track-test-artifact.ts'; function deferred() { let resolve!: () => void; @@ -72,7 +72,7 @@ async function withDownloadFixture( const timers = vi.spyOn(globalThis, 'setTimeout'); const clearedTimers = vi.spyOn(globalThis, 'clearTimeout'); const id = runtime.run(() => - artifactTracking.trackDownloadableArtifact({ artifactPath: source, artifactType: 'trace-log' }), + trackTestArtifact({ artifactPath: source, artifactType: 'trace-log' }), ); const expire = timers.mock.calls[0]![0]; const expiryTimer = timers.mock.results[0]!.value; @@ -435,7 +435,7 @@ test('a directory artifact expires after download header setup throws', async () const port = await listenOnLoopback(server); const timer = vi.spyOn(globalThis, 'setTimeout'); const artifactId = runtime.run(() => - artifactTracking.trackDownloadableArtifact({ + trackTestArtifact({ artifactPath: source, artifactType: 'trace-log', fileName: 'trace-💥', @@ -500,7 +500,7 @@ test.each(['another download completes', 'expiry fires'] as const)( const headers = { authorization: 'Bearer fu-art-secret' }; const timer = vi.spyOn(globalThis, 'setTimeout'); const artifactId = runtime.run(() => - artifactTracking.trackDownloadableArtifact({ + trackTestArtifact({ artifactPath: source, artifactType: 'trace-log', }), diff --git a/packages/daemon/src/server/http/daemon-runtime-artifacts.test.ts b/packages/daemon/src/server/http/daemon-runtime-artifacts.test.ts index 16560207b97..8470da17d2f 100644 --- a/packages/daemon/src/server/http/daemon-runtime-artifacts.test.ts +++ b/packages/daemon/src/server/http/daemon-runtime-artifacts.test.ts @@ -3,11 +3,9 @@ import path from 'node:path'; import { expect, test } from 'vitest'; import { mkdtempForTestSync, createTestHostEnvironment } from '@agent-device/test-kit'; import { daemonRuntimeDepsFixture } from '../../__tests__/support/daemon-runtime-deps-fixture.ts'; -import { - cleanupDownloadableArtifact, - trackDownloadableArtifact, -} from '../../resources/artifact-tracking.ts'; +import { cleanupDownloadableArtifact } from '../../resources/artifact-tracking.ts'; import { startDaemonRuntime } from './daemon-runtime.ts'; +import { trackTestArtifact } from '../../__tests__/support/track-test-artifact.ts'; async function downloadTrackedArtifact(env: Record, awaitConsumption: boolean) { const stateDir = mkdtempForTestSync('agent-device-daemon-runtime-artifacts-'); @@ -28,7 +26,7 @@ async function downloadTrackedArtifact(env: Record, awaitConsump composeDeps: daemonRuntimeDepsFixture(), }); const artifactId = runtime.run(() => - trackDownloadableArtifact({ + trackTestArtifact({ artifactPath, artifactType: 'runtime-artifact', fileName: 'runtime-artifact.txt', diff --git a/packages/daemon/src/server/http/daemon-runtime-isolation.test.ts b/packages/daemon/src/server/http/daemon-runtime-isolation.test.ts index cb4333b0917..0cae3ea8e46 100644 --- a/packages/daemon/src/server/http/daemon-runtime-isolation.test.ts +++ b/packages/daemon/src/server/http/daemon-runtime-isolation.test.ts @@ -6,8 +6,8 @@ import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/tes import { daemonRuntimeDepsFixture } from '../../__tests__/support/daemon-runtime-deps-fixture.ts'; import { interactorResolution } from '../../core/interactor-resolution.ts'; import { isActiveProviderDevice } from '../../core/provider-device-admission.ts'; -import { trackDownloadableArtifact } from '../../resources/artifact-tracking.ts'; import { startDaemonRuntime } from './daemon-runtime.ts'; +import { trackTestArtifact } from '../../__tests__/support/track-test-artifact.ts'; async function startIsolatedRuntime(label: string, interactorTag: string, providerActive: boolean) { const stateDir = mkdtempForTestSync(`agent-device-daemon-isolation-${label}-`); @@ -77,7 +77,7 @@ test('two runtimes in one process serve, close and keep their state independentl const artifactPath = path.join(a.stateDir, 'artifact.txt'); fs.writeFileSync(artifactPath, 'artifact-a'); const artifactId = a.runtime.run(() => - trackDownloadableArtifact({ + trackTestArtifact({ artifactPath, artifactType: 'runtime-artifact', fileName: 'artifact.txt', diff --git a/packages/daemon/src/server/http/http-server-capture-publication.test.ts b/packages/daemon/src/server/http/http-server-capture-publication.test.ts index cee5470934b..4104275a516 100644 --- a/packages/daemon/src/server/http/http-server-capture-publication.test.ts +++ b/packages/daemon/src/server/http/http-server-capture-publication.test.ts @@ -470,8 +470,12 @@ test.each(['leased at start', 'unleased'])( } else { successfulData(await wait('trace-owner-request', unleased)); successfulData(await wait('trace-other-request', owner)); + expect((await trace('stop', owner)).error?.data?.details).toMatchObject({ + reason: 'LEASE_OUTPUT_MISMATCH', + }); } - const id = successfulData(await trace('stop', owner)).artifacts?.[0]?.artifactId; + const id = successfulData(await trace('stop', leasedAtStart ? owner : unleased)) + .artifacts?.[0]?.artifactId; const url = `${base}/artifacts/${id}`; const headers = { authorization: 'Bearer test-token', diff --git a/packages/daemon/src/server/http/http-server-perf-report.test.ts b/packages/daemon/src/server/http/http-server-perf-report.test.ts index 7b1daa67a74..e6b58a07483 100644 --- a/packages/daemon/src/server/http/http-server-perf-report.test.ts +++ b/packages/daemon/src/server/http/http-server-perf-report.test.ts @@ -28,6 +28,7 @@ import { } from '../../resources/artifact-tracking.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { successfulData, withHttp } from './http-output.fixtures.ts'; +import { trackTestArtifact } from '../../__tests__/support/track-test-artifact.ts'; const tenantId = 'report-tenant'; const positionals = ['cpu', 'profile', 'report', 'xctrace']; @@ -82,7 +83,7 @@ function reportFixture() { }); const profilePath = path.join(root, 'retained.trace'); fs.mkdirSync(profilePath); - const retainProfile = (name: string, leaseId?: string) => { + const retainProfile = (name: string, leaseId?: string, owner?: string) => { sessionStore.publish( name, makeIosAppSession(name, { @@ -96,7 +97,10 @@ function reportFixture() { outPath: profilePath, template: 'Time Profiler', }, - leaseVerifier: leaseId ? leaseVerifier(leaseId) : null, + owner: { + tenantId: leaseId ? tenantId : owner, + leaseVerifier: leaseId ? leaseVerifier(leaseId) : null, + }, }, }), ); @@ -175,17 +179,17 @@ test.each(['xctrace', 'simpleperf'] as const)( 'capture', makeSession('capture', { appBundleId: 'com.example.app' }), ); + const scope = { tenantId, runId: 'producer', leaseBackend: 'android-instance' } as const; + const meta = { ...scope, leaseId: fixture.leaseRegistry.allocateLease(scope).leaseId }; const reporter = fixture.sessionStore.publish('reporter', makeSession('reporter')); if (kind === 'simpleperf') { fixture.sessionStore.update(reporter, { lastPerfProfile: { profile: simpleperfHandoff(path.join(fixture.profilePath, 'local.perf.data')), - leaseVerifier: null, + owner: { tenantId, leaseVerifier: leaseVerifier(meta.leaseId) }, }, }); } - const scope = { tenantId, runId: 'producer', leaseBackend: 'android-instance' } as const; - const meta = { ...scope, leaseId: fixture.leaseRegistry.allocateLease(scope).leaseId }; await withHttp(fixture.handler, async (post) => { const complete = async () => { successfulData(await post(captureRequest('start', meta, kind))); @@ -323,7 +327,7 @@ test('a local Simpleperf report uses the stopped handoff when its export has mov 'capture', makeAndroidSession('capture', { appBundleId: profile.packageName, - lastPerfProfile: { profile, leaseVerifier: null }, + lastPerfProfile: { profile, owner: { tenantId: undefined, leaseVerifier: null } }, }), ); await withHttp(fixture.handler, async (post) => { @@ -351,7 +355,7 @@ test.each(['HTTP request', 'direct daemon request'])( 'an unleased %s perf report is downloadable by the requester tenant', async (origin) => { const fixture = reportFixture(); - fixture.retainProfile('capture'); + fixture.retainProfile('capture', undefined, tenantId); await withHttp(fixture.handler, async (post, base) => { const request = { command: 'perf', session: 'capture', positionals }; const report = successfulData( @@ -399,7 +403,7 @@ test.each(['retained in another session', 'registered as an artifact', 'also ret if (owner === 'also retained locally') fixture.retainProfile('capture'); else fixture.sessionStore.publish('capture', makeIosAppSession('capture')); if (owner === 'registered as an artifact') { - const id = trackDownloadableArtifact({ + const id = trackTestArtifact({ artifactPath: fixture.profilePath, artifactType: 'performance', leaseVerifier: leaseVerifier(lease.leaseId), diff --git a/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts b/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts index 90ca397eef1..eb2b279d408 100644 --- a/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts +++ b/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts @@ -10,7 +10,6 @@ import { AppError } from '@agent-device/kernel/errors'; import { cleanupUploadedArtifact, prepareUploadedArtifact, - trackDownloadableArtifact, } from '../../resources/artifact-tracking.ts'; import { DAEMON_REQUEST_MAX_BYTES, @@ -30,6 +29,7 @@ import { mkdtempForTestSync, skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; +import { trackTestArtifact } from '../../__tests__/support/track-test-artifact.ts'; /** The host facts every scenario server runs with: the live process env and cwd (#3753). */ const scenarioHost = createLiveTestHostEnvironment(); @@ -473,7 +473,7 @@ test('Provider-backed integration daemon HTTP server accepts uploads and streams const root = mkdtempForTestSync('agent-device-http-server-'); const downloadablePath = path.join(root, 'screen.png'); fs.writeFileSync(downloadablePath, 'png-binary'); - const artifactId = trackDownloadableArtifact({ + const artifactId = trackTestArtifact({ artifactPath: downloadablePath, artifactType: 'screenshot', fileName: 'screen.png', diff --git a/packages/daemon/src/server/http/http-server-remote-output.test.ts b/packages/daemon/src/server/http/http-server-remote-output.test.ts index ae567a7b656..8fc36f26711 100644 --- a/packages/daemon/src/server/http/http-server-remote-output.test.ts +++ b/packages/daemon/src/server/http/http-server-remote-output.test.ts @@ -679,6 +679,11 @@ test.each([ positionals: positionals('report'), meta: reporter.meta, }); + if (reporter !== ownership) { + // Another tenant and lease than the capture's producer cannot report its profile. + expect(report.error?.data).toMatchObject({ code: 'UNAUTHORIZED' }); + return; + } const reportData = successfulData(report); await reporter.expectReport( `${baseUrl}/artifacts/${reportData.artifacts?.[0]?.artifactId}`, @@ -844,7 +849,7 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite leaseRegistry, deviceInventoryGateways: createTestDeviceInventoryGateways(), trackDownloadableArtifact: (entry) => { - registrations.push({ path: entry.artifactPath, tenant: entry.tenantId }); + registrations.push({ path: entry.artifactPath, tenant: entry.owner.tenantId }); return trackDownloadableArtifact(entry); }, }); @@ -977,9 +982,9 @@ function nativePerfOwnership(registry: LeaseRegistry, leased: boolean, tenantId? expect(await download.text()).toBe('generated-report'); }, refuseUnowned: async (run: () => Promise<{ error?: { data?: unknown } }>) => { - if (lease) + if (lease || tenantId) expect((await run()).error?.data).toMatchObject({ - details: { reason: 'LEASE_OUTPUT_MISMATCH' }, + details: { reason: lease ? 'LEASE_OUTPUT_MISMATCH' : 'TENANT_OUTPUT_MISMATCH' }, }); }, }; diff --git a/packages/daemon/src/server/request-finalization.ts b/packages/daemon/src/server/request-finalization.ts index 0d54e6fddce..b9c2f5bb82f 100644 --- a/packages/daemon/src/server/request-finalization.ts +++ b/packages/daemon/src/server/request-finalization.ts @@ -29,15 +29,14 @@ import type { import { isDeviceRotation, type DeviceRotation } from '@agent-device/contracts/device'; import { claimRequestDiagnosticsRecord, - leaseVerifier, + requestArtifactOwner, requestDiagnosticsRecordId, type TrackDownloadableArtifact, } from '../resources/artifact-tracking.ts'; import { tenantScopedSessionName } from '../core/session-tenant-scope.ts'; import { - captureOutputLeaseVerifier, + captureOutputOwner, captureOutputOwnership, - captureOutputTenantId, daemonDeliveredArtifact, } from '../core/capture-output-ownership.ts'; @@ -154,14 +153,10 @@ function registerDownloadableArtifacts( trackArtifact: TrackDownloadableArtifact, ): DaemonResponseData | undefined { if (!data) return data; - const admittedLeaseId = req.internal?.admittedLease?.leaseId; - const producer = captureOutputLeaseVerifier(data); - const admittedOwner = admittedLeaseId && leaseVerifier(admittedLeaseId); - const tenantId = captureOutputTenantId(data) ?? req.meta?.tenantId; + // Capture output that an earlier request produced carries that producer; other output is this request's. + const producer = captureOutputOwner(data) ?? requestArtifactOwner(req); const register = (artifact: PendingArtifact): DaemonArtifact => { const artifactPath = artifact.path as string; - const delivered = daemonDeliveredArtifact(artifact); - const owner = delivered || producer === undefined ? admittedOwner : producer; return { field: artifact.field, // Omitted (not null/undefined-valued) when untyped, matching the @@ -169,8 +164,7 @@ function registerDownloadableArtifacts( ...(artifact.artifactType !== undefined ? { artifactType: artifact.artifactType } : {}), artifactId: trackArtifact({ artifactPath, - tenantId: delivered ? delivered.tenantId : tenantId, - ...(owner ? { leaseVerifier: owner } : {}), + owner: daemonDeliveredArtifact(artifact) ?? producer, artifactType: artifact.artifactType, fileName: artifact.fileName, ...(artifact.deleteAfterDownload === false ? { deleteAfterDownload: false } : {}), diff --git a/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts b/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts index 2142a6f2ea7..604a310fa2e 100644 --- a/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts +++ b/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts @@ -13,10 +13,7 @@ import { getDaemonCommandRoute, type DaemonCommandRoute, } from '../../core/daemon-command-registry.ts'; -import { - cleanupDownloadableArtifact, - trackDownloadableArtifact, -} from '../../resources/artifact-tracking.ts'; +import { cleanupDownloadableArtifact } from '../../resources/artifact-tracking.ts'; import { contextFromFlags } from '../../core/context.ts'; import { handleLeaseCommands } from '../handlers/lease.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; @@ -37,6 +34,7 @@ import { createAudioProbeAdmissionLedger } from '@agent-device/capture-kit/audio import { createPerfCaptureAdmissionLedger } from '@agent-device/capture-kit/perf-capture-admission-ledger'; import { createScreenRecordingAdmissionLedger } from '@agent-device/capture-kit/screen-recording-admission-ledger'; import { fakeCreateCommandSurface } from '../../__tests__/support/command-surface-fake.ts'; +import { trackTestArtifact } from '../../__tests__/support/track-test-artifact.ts'; const SPECIALIZED_ROUTES = [ 'humanControl', @@ -661,7 +659,7 @@ function trackProxyLeaseArtifact(): { artifactId: string; tempDir: string } { fs.writeFileSync(artifactPath, 'png-body'); return { tempDir, - artifactId: trackDownloadableArtifact({ + artifactId: trackTestArtifact({ artifactPath, artifactType: 'screenshot', fileName: 'proxy-shot.png', diff --git a/packages/daemon/src/sessions/handlers/__tests__/record-runtime-stop-recovery.test.ts b/packages/daemon/src/sessions/handlers/__tests__/record-runtime-stop-recovery.test.ts index a3796fd4e2d..f25d65dd02a 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/record-runtime-stop-recovery.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/record-runtime-stop-recovery.test.ts @@ -20,7 +20,7 @@ import { screenRecordingDurableResource } from '@agent-device/capture-kit/screen import { screenRecordingRecoveryUse } from '@agent-device/contracts/screen-recording-runtime-plan'; import { LeaseRegistry } from '../../../resources/lease-registry.ts'; import { leaseVerifier } from '../../../resources/artifact-tracking.ts'; -import { captureOutputLeaseVerifier } from '../../../core/capture-output-ownership.ts'; +import { captureOutputOwner } from '../../../core/capture-output-ownership.ts'; import { expectDecodedCompletedRecording, makeRecordRuntimeHarness, @@ -152,7 +152,9 @@ test('a completed leased export replays to the lease id that started it, with no const replayed = await replay(leaseId.toUpperCase()); expect(replayed).toMatchObject({ ok: true, data: { recording: 'stopped', outPath } }); // The export stays with the lease of the manifest when the response is registered. - expect(replayed.ok && captureOutputLeaseVerifier(replayed.data!)).toBe(leaseVerifier(leaseId)); + expect(replayed.ok && captureOutputOwner(replayed.data!)?.leaseVerifier).toBe( + leaseVerifier(leaseId), + ); }); test('a completed remote export whose manifest names no owner is not replayed', async () => { diff --git a/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts b/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts index 95db10173f2..b97ea450c48 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts @@ -198,3 +198,35 @@ test('rejects invalid actions, missing sessions, and incoherent lifecycle transi }), ).toMatchObject({ ok: false, error: { message: 'trace already in progress' } }); }); + +test('only the tenant that started a trace stops it', () => { + const { session, sessionStore } = fixture(); + const asTenant = (positionals: string[], tenantId: string): DaemonRequest => ({ + ...request(positionals), + meta: { tenantId }, + }); + handleTraceCommand({ + host: createTestHostEnvironment(), + req: asTenant(['start'], 'tenant-a'), + sessionName: session.name, + sessionStore, + }); + + expect(() => + handleTraceCommand({ + host: createTestHostEnvironment(), + req: asTenant(['stop'], 'tenant-b'), + sessionName: session.name, + sessionStore, + }), + ).toThrow(expect.objectContaining({ details: { reason: 'TENANT_OUTPUT_MISMATCH' } })); + expect(session.trace).toBeDefined(); + expect( + handleTraceCommand({ + host: createTestHostEnvironment(), + req: asTenant(['stop'], 'tenant-a'), + sessionName: session.name, + sessionStore, + }), + ).toMatchObject({ ok: true, data: { trace: 'stopped' } }); +}); diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index 7b6097742d4..09bc3178415 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -482,12 +482,10 @@ async function stopRecording( return !remote && response.ok && response.data ? { ...response, - data: withCaptureOutputOwnership( - response.data, - 'caller', - undefined, - recordingOutputLeaseVerifier(envelope.metadata), - ), + data: withCaptureOutputOwnership(response.data, 'caller', { + tenantId: normalizeTenantId(envelope.metadata?.remoteCaptureTenantId), + leaseVerifier: recordingOutputLeaseVerifier(envelope.metadata) ?? null, + }), } : response; } diff --git a/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts b/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts index 862a1fd3444..805e803db8f 100644 --- a/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts +++ b/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts @@ -138,8 +138,11 @@ export async function handleInstallFromSourceDeploymentCommand(params: { } return { ok: false, error: normalizeError(error) }; } finally { - await materialized?.cleanup(); - resolvedSource?.cleanup(); + try { + await materialized?.cleanup(); + } finally { + resolvedSource?.cleanup(); + } } } diff --git a/packages/daemon/src/sessions/handlers/trace-runtime.ts b/packages/daemon/src/sessions/handlers/trace-runtime.ts index c1e6abee38c..fd7767cd55c 100644 --- a/packages/daemon/src/sessions/handlers/trace-runtime.ts +++ b/packages/daemon/src/sessions/handlers/trace-runtime.ts @@ -5,8 +5,8 @@ import fs from 'node:fs'; import { randomUUID } from 'node:crypto'; import { updateDiagnosticsScope } from '@agent-device/host-kit/diagnostics'; import { - admittedOutputLeaseVerifier, - leasedOutputRefusal, + assertRequestOwnsCapture, + requestArtifactOwner, } from '../../resources/artifact-tracking.ts'; import path from 'node:path'; import { @@ -54,12 +54,13 @@ function startTrace( ); fs.mkdirSync(path.dirname(outPath), { recursive: true }); fs.appendFileSync(outPath, ''); + const owner = requestArtifactOwner(req); session.trace = { ...(daemonOwned ? { remoteCaptureOutputPath: outPath } : { outPath }), startedAt: Date.now(), clientOutPath: req.meta?.clientArtifactPaths?.outPath, - remoteCaptureTenantId: req.internal?.admittedLease?.tenantId ?? req.meta?.tenantId, - leaseVerifier: admittedOutputLeaseVerifier(req), + remoteCaptureTenantId: owner.tenantId, + leaseVerifier: owner.leaseVerifier, }; recordSessionAction(sessionStore, ref, req, req.command, { action: 'start', outPath }); return { @@ -76,8 +77,11 @@ function stopTrace( ): DaemonResponse { const session = sessionStore.requireCurrent(ref); if (!session.trace) return errorResponse('INVALID_ARGS', 'no active trace'); - const owner = session.trace.leaseVerifier ?? null; - if (owner && owner !== admittedOutputLeaseVerifier(req)) throw leasedOutputRefusal('Trace'); + const owner = { + tenantId: session.trace.remoteCaptureTenantId, + leaseVerifier: session.trace.leaseVerifier ?? null, + }; + assertRequestOwnsCapture(owner, req, 'Trace'); updateDiagnosticsScope({ traceLogPath: undefined }); const outPath = relocateTraceOutput( requestCwd(req, host), @@ -85,7 +89,6 @@ function stopTrace( req.positionals?.[1], ); const daemonOwned = session.trace.remoteCaptureOutputPath === outPath; - const tenantId = session.trace.remoteCaptureTenantId; const clientOutPath = req.meta?.clientArtifactPaths?.outPath ?? session.trace.clientOutPath ?? @@ -109,7 +112,6 @@ function stopTrace( ], } satisfies TraceCommandResult, daemonOwned ? 'daemon' : 'caller', - tenantId, owner, ), }; diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts index d4248dd6416..28fe4b89245 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts @@ -58,7 +58,10 @@ import { markPostOpenStabilization, } from '../../../core/deferred-interaction-outcome.ts'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { requestDiagnosticsRecordId } from '../../../resources/artifact-tracking.ts'; +import { + requestArtifactOwner, + requestDiagnosticsRecordId, +} from '../../../resources/artifact-tracking.ts'; import { prepareOpenCommandDetails, type ReplacedRuntimeHints, @@ -445,11 +448,12 @@ function recordPublishedOpen(params: { } else if (runtimeHints) { bindStoredRuntimeHintsToApp(sessionStore, sessionName, appBundleId); } + const remoteOpen = remoteScriptOpen(req.meta); applyOrdinaryScriptRecordingOpenOutcome({ session, existingSession: params.sessionReused ? session : undefined, saveScriptRequested: Boolean(req.flags?.saveScript), - remoteDelivery: remoteScriptOpen(req.meta), + remoteDelivery: remoteOpen && { ...remoteOpen, owner: requestArtifactOwner(req) }, responseData: result, hostCwd: sessionStore.host.cwd, }); diff --git a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts index 61972a6367c..b569ca04e0e 100644 --- a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts +++ b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts @@ -39,16 +39,16 @@ import type { import type { SessionStore } from '../../../core/session-store.ts'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; import { requestCwd } from '../../../core/context.ts'; -import { LEASE_FIELD_NORMALIZERS, resolveLeaseScope } from '../../../core/lease-context.ts'; import type { SessionRef, SessionState } from '../../../core/session-state.ts'; import { bindSessionPerfCapture } from '../../../core/session-capture-binding.ts'; import { withCaptureOutputOwnership } from '../../../core/capture-output-ownership.ts'; import { - admittedOutputLeaseVerifier, + assertRequestOwnsCapture, assertTrackedPerformanceSourceLease, - leasedOutputRefusal, + requestArtifactOwner, retainPerfReportSource, } from '../../../resources/artifact-tracking.ts'; +import type { ArtifactOwner } from '../../../core/tenant-owned-entry.ts'; import { recordSessionAction } from '../../../core/session-action-recorder.ts'; import { admitRuntimePlan, @@ -171,7 +171,7 @@ async function executeAdmittedPerfPlan( data: withCaptureOutputOwnership( buildMemorySnapshotResponse(session, result), params.req.internal?.publicNetworkOnly ? 'daemon' : 'caller', - session.lease?.tenantId ?? params.req.meta?.tenantId, + requestArtifactOwner(params.req), ), }; } @@ -190,12 +190,12 @@ async function executeAdmittedPerfPlan( const retained = explicit && saved && - !canReadPerfOutput(params.req, saved.leaseVerifier) && + !canReadPerfOutput(params.req, saved.owner) && !samePerfSource(explicit, saved.profile.outPath) ? undefined : saved; const tracePath = requestedPath ?? retained?.profile.outPath; - assertPerfOutputOwner(params.req, retained?.leaseVerifier); + if (retained) assertRequestOwnsCapture(retained.owner, params.req, 'Performance capture'); const last = retained?.profile; if (!tracePath) { throw new AppError( @@ -230,8 +230,7 @@ async function executeAdmittedPerfPlan( data: withCaptureOutputOwnership( { perf: 'reported', ...data }, params.req.internal?.publicNetworkOnly ? 'daemon' : 'caller', - params.req.internal?.admittedLease?.tenantId ?? - LEASE_FIELD_NORMALIZERS.tenantId(resolveLeaseScope(params.req).tenantId), + requestArtifactOwner(params.req), ), }; } @@ -309,7 +308,7 @@ async function startPerfCapture( } throw error; }); - const tenantId = params.req.internal?.admittedLease?.tenantId ?? params.req.meta?.tenantId; + const owner = requestArtifactOwner(params.req); await adoptStartedPerfCapture({ admissionLedger, binding, @@ -322,8 +321,8 @@ async function startPerfCapture( metadata: { ...started.envelope.metadata, ...(params.req.internal?.publicNetworkOnly ? { remoteCaptureOutputPath: outPath } : {}), - ...(tenantId ? { remoteCaptureTenantId: tenantId } : {}), - remoteCaptureLease: admittedOutputLeaseVerifier(params.req), + ...(owner.tenantId ? { remoteCaptureTenantId: owner.tenantId } : {}), + remoteCaptureLease: owner.leaseVerifier, }, }, throwIfCanceled: params.throwIfCanceled, @@ -348,13 +347,8 @@ async function stopPerfCapture( const capture = session.perfCapture; if (!capture) return errorResponse('INVALID_ARGS', 'no active native perf capture'); const metadata = capture.envelope.metadata; - const owner = readString(metadata?.remoteCaptureLease) ?? null; - assertPerfOutputOwner(params.req, owner); - const tenantId = resolveStoppedCaptureTenant( - params.req, - session, - metadata?.remoteCaptureTenantId, - ); + const owner = storedPerfCaptureOwner(metadata); + assertRequestOwnsCapture(owner, params.req, 'Performance capture'); const snapshot = capture.handle.inspect(); const mismatchMessage = perfCaptureStopMismatch(snapshot, request); if (mismatchMessage) return errorResponse('INVALID_ARGS', mismatchMessage); @@ -373,7 +367,7 @@ async function stopPerfCapture( const profile = readProfileHandoff(completion); if (daemonOwned) retainPerfReportSource(profile.outPath, owner); params.sessionStore.update(params.ref, { - lastPerfProfile: { profile, leaseVerifier: owner }, + lastPerfProfile: { profile, owner }, }); } const clientOutPath = params.req.meta?.clientArtifactPaths?.outPath ?? capture.clientOutPath; @@ -390,14 +384,16 @@ async function stopPerfCapture( ...(artifacts ? { artifacts } : {}), }, daemonOwned ? 'daemon' : 'caller', - tenantId, owner, ), }; } -function resolveStoppedCaptureTenant(req: DaemonRequest, session: SessionState, stored: unknown) { - return readString(stored) ?? session.lease?.tenantId ?? req.meta?.tenantId; +function storedPerfCaptureOwner(metadata: Record | undefined): ArtifactOwner { + return { + tenantId: readString(metadata?.remoteCaptureTenantId), + leaseVerifier: readString(metadata?.remoteCaptureLease) ?? null, + }; } function resolveExplicitPerfSource(tracePath: string) { @@ -419,26 +415,22 @@ function samePerfSource(source: PerfReportSource, otherPath: string): boolean { } function assertPerfSourceLease(params: PerfRuntimeHandlerParams, source: PerfReportSource): void { - const owner = admittedOutputLeaseVerifier(params.req); for (const session of params.sessionStore.values()) { const retained = session.lastPerfProfile; - if ( - retained?.leaseVerifier && - retained.leaseVerifier !== owner && - samePerfSource(source, retained.profile.outPath) - ) { - throw leasedOutputRefusal('Performance capture'); + if (retained && samePerfSource(source, retained.profile.outPath)) { + assertRequestOwnsCapture(retained.owner, params.req, 'Performance capture'); } const capture = session.perfCapture; - const captureOwner = readString(capture?.envelope.metadata?.remoteCaptureLease); - if (capture && captureOwner && captureOwner !== owner) { - const capturePath = readString(capture.handle.inspect().outPath); - if (capturePath && samePerfSource(source, capturePath)) { - throw leasedOutputRefusal('Performance capture'); - } + const capturePath = capture && readString(capture.handle.inspect().outPath); + if (capture && capturePath && samePerfSource(source, capturePath)) { + assertRequestOwnsCapture( + storedPerfCaptureOwner(capture.envelope.metadata), + params.req, + 'Performance capture', + ); } } - assertTrackedPerformanceSourceLease(source.path, source.stat, owner); + assertTrackedPerformanceSourceLease(source.path, source.stat, params.req); } function readPerfSource(tracePath: string): PerfReportSource | undefined { @@ -450,12 +442,9 @@ function readPerfSource(tracePath: string): PerfReportSource | undefined { } } -function canReadPerfOutput(req: DaemonRequest, owner: string | null | undefined): boolean { - return !owner || owner === admittedOutputLeaseVerifier(req); -} - -function assertPerfOutputOwner(req: DaemonRequest, owner: string | null | undefined): void { - if (!canReadPerfOutput(req, owner)) throw leasedOutputRefusal('Performance capture'); +function canReadPerfOutput(req: DaemonRequest, owner: ArtifactOwner): boolean { + const reader = requestArtifactOwner(req); + return owner.tenantId === reader.tenantId && owner.leaseVerifier === reader.leaseVerifier; } async function publishXctraceDownload( diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 7d9fa7d9cfc..03754514a03 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -792,6 +792,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `RESOURCE_EXPIRED` | The artifact, upload, or path id expired or never existed; the daemon cannot tell which. | +| `TENANT_OUTPUT_MISMATCH` | The artifact, upload, path, or capture belongs to another tenant than the one the request sends. | ### Daemon runtime @@ -1236,6 +1237,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | +| `UPLOAD_LIMIT_REACHED` | The tenant already holds the maximum number of uploaded artifacts that no command consumed yet. | | `UPLOAD_STATE_CORRUPT` | The staged upload holds more bytes than it declared, so it cannot resume; start a new upload. | | `UPLOAD_ROLLBACK_FAILED` | A failed chunk could not be rolled back, so the upload ticket was invalidated; start a new upload. | | `UPLOAD_FINALIZE_CLEANUP_FAILED` | Finalizing the upload failed, and removing its staged files failed too; `details.originalError` holds the first failure. | diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index bea0453832d..a9daf37b61a 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -106,8 +106,13 @@ send the lease id in the `x-agent-device-lease-id` header: without it, `GET /art list the artifact and the download fails with `UNAUTHORIZED` and reason `LEASE_OUTPUT_MISMATCH`. The same header is required to read the diagnostics record of a request on a leased session. This holds after the session closes, for as long as the daemon keeps the file. -Use the same tenant to capture and download a recording. A recording made without a tenant is +An artifact belongs to the tenant and lease of the request that produced it. For a capture that a +later request stops, such as a trace or a performance capture, that is the request that started it. +Use the same tenant and lease to stop, report, and download a capture. Another tenant gets +`UNAUTHORIZED` and reason `TENANT_OUTPUT_MISMATCH`. An artifact or upload made without a tenant is available only to a request without a tenant. +A tenant can hold at most 32 uploads that no command has used yet. Another upload fails with reason +`UPLOAD_LIMIT_REACHED` until one is used or expires. Stop and download remote recordings before restarting or upgrading the daemon. The download IDs expire when the daemon stops. From ee78a1e5c69e91a3d7091df8308126d175739652 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 09:11:39 +0100 Subject: [PATCH 02/10] fix(daemon): bind trace diagnostics to the full capture owner --- ...osite-resource-admission-lifecycle.test.ts | 7 +- packages/daemon/src/core/session-state.ts | 3 +- .../src/execution/generic-settle.test.ts | 6 +- .../session-selector-dispatch.test.ts | 6 +- .../internal/interaction-settle.test.ts | 8 +- .../src/resources/artifact-tracking.test.ts | 29 +++++- .../daemon/src/resources/artifact-tracking.ts | 12 ++- .../__tests__/request-execution-scope.test.ts | 6 +- .../__tests__/session-idle-expiry.test.ts | 10 +- .../http/http-server-remote-output.test.ts | 98 ++++++++++--------- .../__tests__/session-reinstall.test.ts | 6 +- .../src/sessions/handlers/trace-runtime.ts | 9 +- ...pshot-command-runtime-cancellation.test.ts | 16 ++- 13 files changed, 150 insertions(+), 66 deletions(-) diff --git a/packages/daemon/src/core/composite-resource-admission-lifecycle.test.ts b/packages/daemon/src/core/composite-resource-admission-lifecycle.test.ts index fb5b37f783a..07eec1223b5 100644 --- a/packages/daemon/src/core/composite-resource-admission-lifecycle.test.ts +++ b/packages/daemon/src/core/composite-resource-admission-lifecycle.test.ts @@ -20,7 +20,11 @@ test.each(['perf-capture', 'trace-log'] as const)( const owned = kind === 'perf-capture' ? seedExistingCapture(world, kind) : undefined; if (kind === 'trace-log') { world.sessionStore.update(world.ref, { - trace: { outPath: '/tmp/owned.trace', startedAt: 1 }, + trace: { + outPath: '/tmp/owned.trace', + startedAt: 1, + owner: { tenantId: undefined, leaseVerifier: null }, + }, }); } const before = owned ? fs.readFileSync(owned.resourcePath, 'utf8') : undefined; @@ -42,6 +46,7 @@ test.each(['perf-capture', 'trace-log'] as const)( expect(world.sessionStore.requireCurrent(world.ref).trace).toEqual({ outPath: '/tmp/owned.trace', startedAt: 1, + owner: { tenantId: undefined, leaseVerifier: null }, }); } } finally { diff --git a/packages/daemon/src/core/session-state.ts b/packages/daemon/src/core/session-state.ts index fbed5005f6d..93022338849 100644 --- a/packages/daemon/src/core/session-state.ts +++ b/packages/daemon/src/core/session-state.ts @@ -244,8 +244,7 @@ export type SessionState = { /** Remote traces accept request-scoped diagnostics instead of persistent runner streams. */ trace?: { clientOutPath?: string; - remoteCaptureTenantId?: string; - leaseVerifier?: string | null; + owner: ArtifactOwner; startedAt: number; } & ( | { outPath: string; remoteCaptureOutputPath?: never } diff --git a/packages/daemon/src/execution/generic-settle.test.ts b/packages/daemon/src/execution/generic-settle.test.ts index f301e83e365..cfdd6e08cfa 100644 --- a/packages/daemon/src/execution/generic-settle.test.ts +++ b/packages/daemon/src/execution/generic-settle.test.ts @@ -689,7 +689,11 @@ for (const change of ['rebuild', 'retire'] as const) { }); try { await reached; - const trace = { outPath: 'latest-trace', startedAt: 1 }; + const trace = { + outPath: 'latest-trace', + startedAt: 1, + owner: { tenantId: undefined, leaseVerifier: null }, + }; const successor = makeIosSession(name); if (change === 'rebuild') store.update(ref, { trace }); else { diff --git a/packages/daemon/src/execution/handlers/__tests__/session-selector-dispatch.test.ts b/packages/daemon/src/execution/handlers/__tests__/session-selector-dispatch.test.ts index 38dc57b72c8..26075c9d0cf 100644 --- a/packages/daemon/src/execution/handlers/__tests__/session-selector-dispatch.test.ts +++ b/packages/daemon/src/execution/handlers/__tests__/session-selector-dispatch.test.ts @@ -111,7 +111,11 @@ test.each(['rebuild', 'retire'] as const)( if (transition === 'rebuild') current = sessionStore.update(ref, { actions: [], - trace: { outPath: '/latest.trace', startedAt: 1 }, + trace: { + outPath: '/latest.trace', + startedAt: 1, + owner: { tenantId: undefined, leaseVerifier: null }, + }, }); else { sessionStore.retire(ref); diff --git a/packages/daemon/src/execution/interaction/internal/interaction-settle.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-settle.test.ts index 0cd73501b6c..cdff8f02c85 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-settle.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-settle.test.ts @@ -375,7 +375,13 @@ test('held touch settle publishes refs into the current record of its scoped lif try { await entered; expect(refFrameState(ref.session)).toBe('expired'); - sessionStore.update(ref, { trace: { outPath: 'rebuilt-trace', startedAt: 1 } }); + sessionStore.update(ref, { + trace: { + outPath: 'rebuilt-trace', + startedAt: 1, + owner: { tenantId: undefined, leaseVerifier: null }, + }, + }); release(); const settle = expectOkData(await running).settle as SettlePayload; const current = sessionStore.requireCurrent(ref); diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index 1e4dfb9540a..aef44ce4c97 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -119,7 +119,11 @@ test('an unleased caller-owned trace accepts runner output after the request unt const ref = store.publish( 'default', makeIosSession('default', { - trace: { outPath: tracePath, startedAt: Date.now() }, + trace: { + outPath: tracePath, + startedAt: Date.now(), + owner: { tenantId: undefined, leaseVerifier: null }, + }, }), ); const req = { token: 'test-token', session: 'default', command: 'snapshot', positionals: [] }; @@ -137,6 +141,29 @@ test('an unleased caller-owned trace accepts runner output after the request unt ); }); +test("another tenant's request on a shared unleased session gets no trace writer", () => { + const store = makeSessionStore('agent-device-trace-tenant-scope-'); + const ref = store.publish( + 'default', + makeIosSession('default', { + trace: { + outPath: path.join(store.ensureSessionDir('default'), 'tenant-a.trace'), + startedAt: Date.now(), + owner: { tenantId: 'tenant-a', leaseVerifier: null }, + }, + }), + ); + const request = (tenant: string) => ({ + token: 'test-token', + session: 'default', + command: 'snapshot', + positionals: [], + meta: { tenantId: tenant }, + }); + expect(requestTraceDiagnostics(request('tenant-a'), ref, store).traceLogPath).toBeDefined(); + expect(requestTraceDiagnostics(request('tenant-b'), ref, store).traceLogPath).toBeUndefined(); +}); + test.each(['cleanup', 'expiry'] as const)( '%s aborts an inventory-only archive and removes its source after tar settles', async (trigger) => { diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 4eeb5ef30d3..3862dc0f2ea 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -82,15 +82,21 @@ export function requestTraceDiagnostics( store: Pick, ) { const trace = ref?.session.trace; - const owner = trace?.leaseVerifier ?? null; - if (!ref || !trace || owner !== admittedOutputLeaseVerifier(req)) { + const reader = requestArtifactOwner(req); + if ( + !ref || + !trace || + trace.owner.tenantId !== reader.tenantId || + trace.owner.leaseVerifier !== reader.leaseVerifier + ) { return { traceLogPath: undefined, traceLogWritable: undefined, runnerTraceLogWritable: undefined, }; } - const unleasedCallerTrace = trace.outPath !== undefined && owner === null && !ref.session.lease; + const unleasedCallerTrace = + trace.outPath !== undefined && trace.owner.leaseVerifier === null && !ref.session.lease; const traceLogWritable = () => store.resolveCurrent(ref)?.trace === trace; return { traceLogPath: trace.remoteCaptureOutputPath ?? trace.outPath, diff --git a/packages/daemon/src/server/__tests__/request-execution-scope.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope.test.ts index ba103fa0daf..66e5f84d4e1 100644 --- a/packages/daemon/src/server/__tests__/request-execution-scope.test.ts +++ b/packages/daemon/src/server/__tests__/request-execution-scope.test.ts @@ -764,7 +764,11 @@ test('prepareLockedRequestScope streams ordinary diagnostics into the active tra sessionStore.publish( 'default', makeIosSession('default', { - trace: { outPath: tracePath, startedAt: Date.now() }, + trace: { + outPath: tracePath, + startedAt: Date.now(), + owner: { tenantId: undefined, leaseVerifier: null }, + }, }), ); const scope = await createTestRequestScope({ diff --git a/packages/daemon/src/server/__tests__/session-idle-expiry.test.ts b/packages/daemon/src/server/__tests__/session-idle-expiry.test.ts index 6b4ee9a40ce..0a49c987980 100644 --- a/packages/daemon/src/server/__tests__/session-idle-expiry.test.ts +++ b/packages/daemon/src/server/__tests__/session-idle-expiry.test.ts @@ -170,7 +170,15 @@ test('a session with any capture running is never idle-expired', () => { ['app logs', (s) => (s.appLog = makeTestCaptureResource(s, 'app-log'))], ['audio probe', (s) => (s.audioProbe = makeTestCaptureResource(s, 'audio-probe'))], ['performance capture', (s) => (s.perfCapture = makeTestCaptureResource(s, 'perf-capture'))], - ['trace', (s) => (s.trace = { outPath: '/tmp/trace.trace', startedAt: 1 })], + [ + 'trace', + (s) => + (s.trace = { + outPath: '/tmp/trace.trace', + startedAt: 1, + owner: { tenantId: undefined, leaseVerifier: null }, + }), + ], ]; for (const [name, attach] of running) { const session = claimHoldingSession(); diff --git a/packages/daemon/src/server/http/http-server-remote-output.test.ts b/packages/daemon/src/server/http/http-server-remote-output.test.ts index 8fc36f26711..a70fbbd640b 100644 --- a/packages/daemon/src/server/http/http-server-remote-output.test.ts +++ b/packages/daemon/src/server/http/http-server-remote-output.test.ts @@ -543,13 +543,8 @@ test.each([ output = value; }, finish: async () => { - fs.mkdirSync(kind === 'xctrace' ? output : path.dirname(output), { - recursive: true, - }); - fs.writeFileSync( - kind === 'xctrace' ? path.join(output, 'capture.bin') : output, - 'generated-capture', - ); + fs.mkdirSync(path.dirname(captureFile(kind, output)), { recursive: true }); + fs.writeFileSync(captureFile(kind, output), 'generated-capture'); return { status: 'completed', result: snapshot(true) }; }, forceCleanup: async () => ({ status: 'cleaned' }), @@ -576,12 +571,9 @@ test.each([ expect(profile).toBeUndefined(); expect(template).toBeUndefined(); } - expect( - fs.readFileSync( - kind === 'xctrace' ? path.join(tracePath, 'capture.bin') : tracePath, - 'utf8', - ), - ).toBe(explicit ? 'independent-capture' : 'generated-capture'); + expect(fs.readFileSync(captureFile(kind, tracePath), 'utf8')).toBe( + explicit ? 'independent-capture' : 'generated-capture', + ); fs.writeFileSync(outPath, 'generated-report'); return { outPath }; }, @@ -625,12 +617,7 @@ test.each([ if (origin === 'local' || origin === 'relocated') { expect(artifact?.artifactId).toBeUndefined(); expect(stoppedData.outPath).toBe(callerOutput); - expect( - fs.readFileSync( - kind === 'xctrace' ? path.join(callerOutput, 'capture.bin') : callerOutput, - 'utf8', - ), - ).toBe('generated-capture'); + expect(fs.readFileSync(captureFile(kind, callerOutput), 'utf8')).toBe('generated-capture'); return; } expect(artifact?.artifactId).toBeTypeOf('string'); @@ -641,37 +628,22 @@ test.each([ }); expect(download.status).toBe(200); const payload = Buffer.from(await download.arrayBuffer()); - expect( - kind === 'xctrace' - ? gunzipSync(payload).includes(Buffer.from('generated-capture')) - : payload.toString() === 'generated-capture', - ).toBe(true); + expect(payloadHoldsCapture(kind, payload)).toBe(true); restoreProfile(); if (area === 'cpu') { - expect( - fs.readFileSync(kind === 'xctrace' ? path.join(output, 'capture.bin') : output, 'utf8'), - ).toBe('generated-capture'); + expect(fs.readFileSync(captureFile(kind, output), 'utf8')).toBe('generated-capture'); await ownership.refuseUnowned(() => post({ command: 'perf', session: 'capture', positionals: positionals('report') }), ); if (kind === 'xctrace' && origin === 'leased') { - fs.mkdirSync(explicitTrace); - fs.writeFileSync(path.join(explicitTrace, 'capture.bin'), 'independent-capture'); - const reportPath = path.join(root, 'explicit-report.json'); - const explicitReport = (source: string) => - post( - { - command: 'perf', - session: 'capture', - positionals: [...positionals('report'), '', reportPath, source], - }, - false, - ); - successfulData(await explicitReport(explicitTrace)); - expect(fs.readFileSync(reportPath, 'utf8')).toBe('generated-report'); - const alias = path.join(root, 'retained-alias.trace'); - fs.symlinkSync(output, alias, 'dir'); - await ownership.refuseUnowned(() => explicitReport(alias)); + await expectIndependentXctraceReport({ + post, + ownership, + reportPositionals: positionals('report'), + root, + explicitTrace, + output, + }); } const report = await post({ command: 'perf', @@ -942,6 +914,44 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite } }); +function captureFile(kind: string, output: string): string { + return kind === 'xctrace' ? path.join(output, 'capture.bin') : output; +} + +function payloadHoldsCapture(kind: string, payload: Buffer): boolean { + return kind === 'xctrace' + ? gunzipSync(payload).includes(Buffer.from('generated-capture')) + : payload.toString() === 'generated-capture'; +} + +async function expectIndependentXctraceReport(input: { + post: Parameters[1]>[0]; + ownership: ReturnType; + reportPositionals: string[]; + root: string; + explicitTrace: string; + output: string; +}): Promise { + const { post, ownership, reportPositionals, root, explicitTrace, output } = input; + fs.mkdirSync(explicitTrace); + fs.writeFileSync(path.join(explicitTrace, 'capture.bin'), 'independent-capture'); + const reportPath = path.join(root, 'explicit-report.json'); + const explicitReport = (source: string) => + post( + { + command: 'perf', + session: 'capture', + positionals: [...reportPositionals, '', reportPath, source], + }, + false, + ); + successfulData(await explicitReport(explicitTrace)); + expect(fs.readFileSync(reportPath, 'utf8')).toBe('generated-report'); + const alias = path.join(root, 'retained-alias.trace'); + fs.symlinkSync(output, alias, 'dir'); + await ownership.refuseUnowned(() => explicitReport(alias)); +} + function replaceXctraceProfile(kind: string, area: string, output: string): () => void { if (kind !== 'xctrace' || area !== 'cpu') return () => {}; const profile = path.join(output, 'capture.bin'); diff --git a/packages/daemon/src/sessions/handlers/__tests__/session-reinstall.test.ts b/packages/daemon/src/sessions/handlers/__tests__/session-reinstall.test.ts index d3e2e55957f..2dd0a9a4479 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/session-reinstall.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/session-reinstall.test.ts @@ -442,7 +442,11 @@ test.each(['rebuild', 'retire'] as const)( if (transition === 'rebuild') current = store.update(ref, { actions: [], - trace: { outPath: '/latest.trace', startedAt: 1 }, + trace: { + outPath: '/latest.trace', + startedAt: 1, + owner: { tenantId: undefined, leaseVerifier: null }, + }, }); else { store.retire(ref); diff --git a/packages/daemon/src/sessions/handlers/trace-runtime.ts b/packages/daemon/src/sessions/handlers/trace-runtime.ts index fd7767cd55c..367338bb2ea 100644 --- a/packages/daemon/src/sessions/handlers/trace-runtime.ts +++ b/packages/daemon/src/sessions/handlers/trace-runtime.ts @@ -54,13 +54,11 @@ function startTrace( ); fs.mkdirSync(path.dirname(outPath), { recursive: true }); fs.appendFileSync(outPath, ''); - const owner = requestArtifactOwner(req); session.trace = { ...(daemonOwned ? { remoteCaptureOutputPath: outPath } : { outPath }), startedAt: Date.now(), clientOutPath: req.meta?.clientArtifactPaths?.outPath, - remoteCaptureTenantId: owner.tenantId, - leaseVerifier: owner.leaseVerifier, + owner: requestArtifactOwner(req), }; recordSessionAction(sessionStore, ref, req, req.command, { action: 'start', outPath }); return { @@ -77,10 +75,7 @@ function stopTrace( ): DaemonResponse { const session = sessionStore.requireCurrent(ref); if (!session.trace) return errorResponse('INVALID_ARGS', 'no active trace'); - const owner = { - tenantId: session.trace.remoteCaptureTenantId, - leaseVerifier: session.trace.leaseVerifier ?? null, - }; + const { owner } = session.trace; assertRequestOwnsCapture(owner, req, 'Trace'); updateDiagnosticsScope({ traceLogPath: undefined }); const outPath = relocateTraceOutput( diff --git a/packages/daemon/src/sessions/snapshot-command-runtime-cancellation.test.ts b/packages/daemon/src/sessions/snapshot-command-runtime-cancellation.test.ts index 671d5f40e7a..17cb1cae978 100644 --- a/packages/daemon/src/sessions/snapshot-command-runtime-cancellation.test.ts +++ b/packages/daemon/src/sessions/snapshot-command-runtime-cancellation.test.ts @@ -104,7 +104,13 @@ for (const change of ['unchanged', 'rebuild', 'replace'] as const) { const address = 'cwd:snapshot-completion:default'; const ref = sessionStore.publish( address, - makeAndroidSession('default', { trace: { outPath: 'prior-trace', startedAt: 0 } }), + makeAndroidSession('default', { + trace: { + outPath: 'prior-trace', + startedAt: 0, + owner: { tenantId: undefined, leaseVerifier: null }, + }, + }), ); const entered = deferred(); const release = deferred(); @@ -132,7 +138,13 @@ for (const change of ['unchanged', 'rebuild', 'replace'] as const) { await entered.promise; if (change !== 'replace') { const trace = - change === 'rebuild' ? { outPath: 'intervening-trace', startedAt: 1 } : ref.session.trace; + change === 'rebuild' + ? { + outPath: 'intervening-trace', + startedAt: 1, + owner: { tenantId: undefined, leaseVerifier: null }, + } + : ref.session.trace; if (change === 'rebuild') sessionStore.update(ref, { trace }); const priorRecord = sessionStore.requireCurrent(ref); release.resolve(); From 9c0fe8ce3fcb19eb3f1c34fbbd2caae9cd0c880a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 10:57:06 +0100 Subject: [PATCH 03/10] fix(daemon): keep capture ownership files under the line cap and document the lease reason --- packages/daemon/src/resources/artifact-tracking.ts | 3 --- .../__tests__/request-execution-scope.test.ts | 13 +++---------- .../server/http/http-server-remote-output.test.ts | 1 - website/docs/docs/remote-proxy.md | 5 +++-- 4 files changed, 6 insertions(+), 16 deletions(-) diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 3862dc0f2ea..d27447bc688 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -53,7 +53,6 @@ export function admittedOutputLeaseVerifier(req: Pick return leaseId === undefined ? null : leaseVerifier(leaseId); } -/** The owner of the output that this request produces. */ export function requestArtifactOwner( req: Pick, ): ArtifactOwner { @@ -933,9 +932,7 @@ function cleanupDirectoryArchive(entry: ArtifactEntry): void { const UPLOAD_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes const MAX_STAGED_UPLOADS_PER_TENANT = 32; - const STAGED_UPLOAD_REASONS = { - // The tenant already holds the maximum number of uploaded artifacts that no command consumed yet. limitReached: { reason: 'UPLOAD_LIMIT_REACHED' }, } as const satisfies ReasonTable<'uploads'>; diff --git a/packages/daemon/src/server/__tests__/request-execution-scope.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope.test.ts index 66e5f84d4e1..c8dabcf457a 100644 --- a/packages/daemon/src/server/__tests__/request-execution-scope.test.ts +++ b/packages/daemon/src/server/__tests__/request-execution-scope.test.ts @@ -761,16 +761,9 @@ test('prepareLockedRequestScope passes the session runner log path into handler test('prepareLockedRequestScope streams ordinary diagnostics into the active trace', async () => { const sessionStore = makeSessionStore('agent-device-request-scope-'); const tracePath = path.join(TEST_ROOT, 'active-session.trace'); - sessionStore.publish( - 'default', - makeIosSession('default', { - trace: { - outPath: tracePath, - startedAt: Date.now(), - owner: { tenantId: undefined, leaseVerifier: null }, - }, - }), - ); + const owner = { tenantId: undefined, leaseVerifier: null }; + const trace = { outPath: tracePath, startedAt: Date.now(), owner }; + sessionStore.publish('default', makeIosSession('default', { trace })); const scope = await createTestRequestScope({ req: makeRequest({ command: 'snapshot' }), sessionStore, diff --git a/packages/daemon/src/server/http/http-server-remote-output.test.ts b/packages/daemon/src/server/http/http-server-remote-output.test.ts index a70fbbd640b..025cf566d47 100644 --- a/packages/daemon/src/server/http/http-server-remote-output.test.ts +++ b/packages/daemon/src/server/http/http-server-remote-output.test.ts @@ -652,7 +652,6 @@ test.each([ meta: reporter.meta, }); if (reporter !== ownership) { - // Another tenant and lease than the capture's producer cannot report its profile. expect(report.error?.data).toMatchObject({ code: 'UNAUTHORIZED' }); return; } diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index a9daf37b61a..8727d183e5e 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -108,8 +108,9 @@ The same header is required to read the diagnostics record of a request on a lea This holds after the session closes, for as long as the daemon keeps the file. An artifact belongs to the tenant and lease of the request that produced it. For a capture that a later request stops, such as a trace or a performance capture, that is the request that started it. -Use the same tenant and lease to stop, report, and download a capture. Another tenant gets -`UNAUTHORIZED` and reason `TENANT_OUTPUT_MISMATCH`. An artifact or upload made without a tenant is +Use the same tenant and lease to stop, report, and download a capture. Another lease gets +`UNAUTHORIZED` and reason `LEASE_OUTPUT_MISMATCH`. Another tenant gets `UNAUTHORIZED` and reason +`TENANT_OUTPUT_MISMATCH`. An artifact or upload made without a tenant is available only to a request without a tenant. A tenant can hold at most 32 uploads that no command has used yet. Another upload fails with reason `UPLOAD_LIMIT_REACHED` until one is used or expires. From 69ff56942843e7d8a0554fbc3599dc7e489e1f19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 11:00:34 +0100 Subject: [PATCH 04/10] fix(daemon): restore the staged upload limit reason summary --- packages/daemon/src/resources/artifact-tracking.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index d27447bc688..46a3a6d5edf 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -64,7 +64,6 @@ export function requestArtifactOwner( }; } -/** Refuses a request that is not the producer of a capture: another tenant or another lease. */ export function assertRequestOwnsCapture( owner: ArtifactOwner, req: Pick, @@ -933,6 +932,7 @@ function cleanupDirectoryArchive(entry: ArtifactEntry): void { const UPLOAD_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes const MAX_STAGED_UPLOADS_PER_TENANT = 32; const STAGED_UPLOAD_REASONS = { + // The tenant already holds the maximum number of uploaded artifacts that no command consumed yet. limitReached: { reason: 'UPLOAD_LIMIT_REACHED' }, } as const satisfies ReasonTable<'uploads'>; From 91e72789d689ff2b002efe8a4cd24f31dc8a8752 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 11:18:09 +0100 Subject: [PATCH 05/10] fix(daemon): keep first cleanup error; document tenantless upload limit --- .../sessions/handlers/session-app-source-deployment.ts | 9 ++++++++- website/docs/docs/remote-proxy.md | 5 +++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts b/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts index 805e803db8f..102b481c1ac 100644 --- a/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts +++ b/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts @@ -138,11 +138,18 @@ export async function handleInstallFromSourceDeploymentCommand(params: { } return { ok: false, error: normalizeError(error) }; } finally { + let cleanupError: unknown; try { await materialized?.cleanup(); - } finally { + } catch (error) { + cleanupError = error; + } + try { resolvedSource?.cleanup(); + } catch (error) { + cleanupError ??= error; } + if (cleanupError !== undefined) throw cleanupError; } } diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 8727d183e5e..47bb3c569c0 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -112,8 +112,9 @@ Use the same tenant and lease to stop, report, and download a capture. Another l `UNAUTHORIZED` and reason `LEASE_OUTPUT_MISMATCH`. Another tenant gets `UNAUTHORIZED` and reason `TENANT_OUTPUT_MISMATCH`. An artifact or upload made without a tenant is available only to a request without a tenant. -A tenant can hold at most 32 uploads that no command has used yet. Another upload fails with reason -`UPLOAD_LIMIT_REACHED` until one is used or expires. +Each tenant can hold at most 32 uploads that no command has used yet. All uploads made without a +tenant share one limit of 32. Another upload fails with reason `UPLOAD_LIMIT_REACHED` until one is +used or expires. Stop and download remote recordings before restarting or upgrading the daemon. The download IDs expire when the daemon stops. From 08d8a1100293d35bae60e74a0585b544dc208099 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 11:21:59 +0100 Subject: [PATCH 06/10] fix(daemon): keep install cleanup rethrow out of finally --- .../handlers/session-app-source-deployment.ts | 32 ++++++++++++------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts b/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts index 102b481c1ac..22ac08aa71d 100644 --- a/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts +++ b/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts @@ -138,19 +138,27 @@ export async function handleInstallFromSourceDeploymentCommand(params: { } return { ok: false, error: normalizeError(error) }; } finally { - let cleanupError: unknown; - try { - await materialized?.cleanup(); - } catch (error) { - cleanupError = error; - } - try { - resolvedSource?.cleanup(); - } catch (error) { - cleanupError ??= error; - } - if (cleanupError !== undefined) throw cleanupError; + await cleanupInstallSources(materialized, resolvedSource); + } +} + +/** Runs both cleanups and rethrows the first failure. */ +async function cleanupInstallSources( + materialized: MaterializedAppSource | undefined, + resolvedSource: ReturnType | undefined, +): Promise { + let cleanupError: unknown; + try { + await materialized?.cleanup(); + } catch (error) { + cleanupError = error; + } + try { + resolvedSource?.cleanup(); + } catch (error) { + cleanupError ??= error; } + if (cleanupError !== undefined) throw cleanupError; } export async function handleReleaseMaterializedPathsCommand(params: { From 4016485a373a92fe36d2c3a11264a9b23e21112f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 12:35:45 +0100 Subject: [PATCH 07/10] fix(remote): stage uploads for the request tenant and surface typed upload refusals --- .../__tests__/upload-client-redirect.test.ts | 34 +++++++ .../src/__tests__/upload-client.test.ts | 16 +++- packages/remote/src/daemon-artifacts.ts | 2 + packages/remote/src/upload-client.ts | 88 +++++++++++-------- 4 files changed, 101 insertions(+), 39 deletions(-) diff --git a/packages/remote/src/__tests__/upload-client-redirect.test.ts b/packages/remote/src/__tests__/upload-client-redirect.test.ts index 9c94723a2f7..a04689c3969 100644 --- a/packages/remote/src/__tests__/upload-client-redirect.test.ts +++ b/packages/remote/src/__tests__/upload-client-redirect.test.ts @@ -141,3 +141,37 @@ test.for([ } }, ); + +test('a typed finalize refusal ends the upload with its reason and no legacy fallback', async (t) => { + if (await skipWhenLoopbackUnavailable(t, 'upload refusal coverage')) return; + const daemonRequests: string[] = []; + const daemon = await startServer((req, res) => { + daemonRequests.push(`${req.method} ${req.url}`); + req.resume(); + req.on('end', () => { + if (req.url === '/upload/preflight') { + const url = `${daemon.baseUrl}/upload/direct/t`; + return answerJson(res, { ok: true, uploadId: 't', upload: { url, headers: {} } }); + } + if (req.url === '/upload/direct/t') return res.end('ok'); + res.statusCode = 429; + answerJson(res, { error: 'Limit', code: 'COMMAND_FAILED', reason: 'UPLOAD_LIMIT_REACHED' }); + }); + }); + const localPath = path.join(mkdtempForTestSync('agent-device-upload-refusal-'), 'app.apk'); + fs.writeFileSync(localPath, 'apk-bytes'); + + try { + await assert.rejects( + uploadArtifact({ localPath, baseUrl: daemon.baseUrl, token: 'token', env: process.env }), + { message: 'Limit', details: { reason: 'UPLOAD_LIMIT_REACHED' } }, + ); + assert.deepEqual(daemonRequests, [ + 'POST /upload/preflight', + 'PUT /upload/direct/t', + 'POST /upload/finalize', + ]); + } finally { + await daemon.close(); + } +}); diff --git a/packages/remote/src/__tests__/upload-client.test.ts b/packages/remote/src/__tests__/upload-client.test.ts index 0b57ce1fdb3..0afb5c83064 100644 --- a/packages/remote/src/__tests__/upload-client.test.ts +++ b/packages/remote/src/__tests__/upload-client.test.ts @@ -11,7 +11,10 @@ const uploadArtifact = (options: Omit[0] import type { UploadProgressEvent } from '../upload-progress.ts'; import { runCmdSync, withCommandExecutorOverride } from '@agent-device/host-kit/command'; import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; -import { DAEMON_HTTP_LEASE_HEADER } from '@agent-device/contracts/daemon-http'; +import { + DAEMON_HTTP_LEASE_HEADER, + DAEMON_HTTP_TENANT_HEADER, +} from '@agent-device/contracts/daemon-http'; const TEST_TOKEN = 'agent-device-upload-test-token'; const tempDirs: string[] = []; @@ -905,11 +908,13 @@ test.each([ { flow: 'legacy', host: '', routes: ['POST /upload/preflight', 'POST /upload'], unleased: '' }, { flow: 'direct', host: 'localhost', routes: DIRECT_ROUTES, unleased: 'PUT /upload/t' }, ])( - 'uploadArtifact names a held lease on a $flow upload to ticket host "$host"', + 'uploadArtifact names a held lease and tenant on a $flow upload to ticket host "$host"', async ({ flow, host, routes, unleased }) => { let leases = new Map(); const server = await startServer(async (req, res) => { - leases.set(`${req.method} ${req.url}`, req.headers[DAEMON_HTTP_LEASE_HEADER]); + const { [DAEMON_HTTP_LEASE_HEADER]: lease, [DAEMON_HTTP_TENANT_HEADER]: tenant } = + req.headers; + leases.set(`${req.method} ${req.url}`, lease && `${lease}/${tenant}`); await readRequestBody(req); if (req.url !== '/upload/preflight') return sendJson(res, { ok: true, uploadId: 'done' }); if (flow === 'legacy') return sendJson(res, { ok: true, cacheHit: false }); @@ -920,13 +925,16 @@ test.each([ const localPath = createTempFile('app.apk', `${flow}-payload`); for (const leaseId of ['lease-1', undefined]) { leases = new Map(); + const tenantId = leaseId && 't1'; await uploadArtifact({ localPath, baseUrl: server.baseUrl, token: TEST_TOKEN, leaseId, + tenantId, }); - const expected = routes.map((route) => [route, route === unleased ? undefined : leaseId]); + const scope = leaseId && `${leaseId}/${tenantId}`; + const expected = routes.map((route) => [route, route === unleased ? undefined : scope]); assert.deepEqual([...leases], expected); } } finally { diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 3c2ec3b9f38..1876c7e8b7a 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -210,6 +210,7 @@ async function prepareRemoteInstallPackage( handoff: info.uploadHandoff, platform: req.flags?.platform, leaseId: leaseScopeFromRequest(req).leaseId, + tenantId: leaseScopeFromRequest(req).tenantId, onProgress, signal, }); @@ -316,6 +317,7 @@ async function prepareRemoteInstallSource( handoff: info.uploadHandoff, platform: req.flags?.platform, leaseId: leaseScopeFromRequest(req).leaseId, + tenantId: leaseScopeFromRequest(req).tenantId, onProgress, signal, }); diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index 8c79f0ae602..f5f1598b03d 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -1,9 +1,10 @@ import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import { randomUUID } from 'node:crypto'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, toAppErrorCode } from '@agent-device/kernel/errors'; import { buildDaemonHttpAuthHeaders, buildDaemonHttpLeaseHeaders, + buildDaemonHttpTenantHeaders, } from '@agent-device/contracts/daemon-http'; import { prepareUploadArtifact, type PreparedUploadArtifact } from './upload-client-artifact.ts'; import { @@ -32,6 +33,8 @@ type UploadArtifactOptions = { env: Readonly; /** The lease this upload is for; every request to the daemon names it in a header. */ leaseId?: string; + /** The tenant that the consuming command sends, so the daemon stages the upload for that tenant. */ + tenantId?: string; onProgress?: UploadProgressSink; /** * Ends the upload when the thing it is uploading for stops being worth finishing — today, a beat @@ -86,12 +89,16 @@ async function uploadArtifactWithinBudget( ); const normalizedBase = options.baseUrl.endsWith('/') ? options.baseUrl : `${options.baseUrl}/`; const uploadAttemptId = randomUUID(); + const scopeHeaders = { + ...buildDaemonHttpLeaseHeaders(options.leaseId), + ...buildDaemonHttpTenantHeaders(options.tenantId), + }; try { const preflight = await requestUploadPreflight({ normalizedBase, token: options.token, - leaseId: options.leaseId, + scopeHeaders, artifact: prepared, uploadAttemptId, env: options.env, @@ -106,7 +113,7 @@ async function uploadArtifactWithinBudget( const directUpload = await tryDirectUploadWithResume({ normalizedBase, token: options.token, - leaseId: options.leaseId, + scopeHeaders, artifact: prepared, preflight, uploadAttemptId, @@ -125,7 +132,7 @@ async function uploadArtifactWithinBudget( return await uploadLegacyArtifact({ normalizedBase, token: options.token, - leaseId: options.leaseId, + scopeHeaders, artifact: prepared, onProgress: options.onProgress, signal: options.signal, @@ -136,7 +143,7 @@ async function uploadArtifactWithinBudget( return await uploadLegacyArtifact({ normalizedBase, token: options.token, - leaseId: options.leaseId, + scopeHeaders, artifact: prepared, onProgress: options.onProgress, signal: options.signal, @@ -150,7 +157,7 @@ async function uploadArtifactWithinBudget( async function tryDirectUploadWithResume(options: { normalizedBase: string; token: string; - leaseId?: string; + scopeHeaders: Record; artifact: PreparedUploadArtifact; preflight: Extract; uploadAttemptId: string; @@ -166,7 +173,7 @@ async function tryDirectUploadWithResume(options: { return await finalizeDirectUpload({ normalizedBase: options.normalizedBase, token: options.token, - leaseId: options.leaseId, + scopeHeaders: options.scopeHeaders, uploadId: preflight.uploadId, signal: options.signal, handoff: options.handoff, @@ -180,7 +187,7 @@ async function tryDirectUploadWithResume(options: { // re-preflighting would ask the daemon for a fresh ticket to send bytes nobody is waiting on. if (options.signal.aborted) throw error; // An expired phase is this client's own deadline, never a transport break to retry. - if (isTransferPhaseTimeoutError(error)) throw error; + if (isTransferPhaseTimeoutError(error) || error instanceof UploadRefusal) throw error; if (!shouldRetryDirectUpload(error)) return undefined; return await retryDirectUpload(options, uploadOnce); } @@ -197,7 +204,7 @@ async function retryDirectUpload( options: { normalizedBase: string; token: string; - leaseId?: string; + scopeHeaders: Record; artifact: PreparedUploadArtifact; uploadAttemptId: string; env: HostEnvironment['env']; @@ -212,7 +219,7 @@ async function retryDirectUpload( const retryPreflight = await requestUploadPreflight({ normalizedBase: options.normalizedBase, token: options.token, - leaseId: options.leaseId, + scopeHeaders: options.scopeHeaders, artifact: options.artifact, uploadAttemptId: options.uploadAttemptId, env: options.env, @@ -227,13 +234,26 @@ async function retryDirectUpload( return await uploadOnce(retryPreflight); } catch (error) { options.signal.throwIfAborted(); - if (isTransferPhaseTimeoutError(error)) throw error; + if (isTransferPhaseTimeoutError(error) || error instanceof UploadRefusal) throw error; return undefined; } } return undefined; } +/** A daemon refusal with a typed reason, such as an upload limit. It ends the upload without a fallback. */ +class UploadRefusal extends AppError {} + +function readUploadRefusal(body: unknown): UploadRefusal | undefined { + if (!body || typeof body !== 'object') return undefined; + const { code, error, reason, hint } = body as Record; + if (typeof error !== 'string' || typeof reason !== 'string') return undefined; + return new UploadRefusal(toAppErrorCode(typeof code === 'string' ? code : undefined), error, { + reason, + ...(typeof hint === 'string' ? { hint } : {}), + }); +} + function shouldRetryDirectUpload(error: unknown): boolean { if (!(error instanceof AppError)) return true; return isRetryableUploadStreamError(error); @@ -242,13 +262,13 @@ function shouldRetryDirectUpload(error: unknown): boolean { async function uploadLegacyArtifact(options: { normalizedBase: string; token: string; - leaseId?: string; + scopeHeaders: Record; artifact: PreparedUploadArtifact; onProgress?: UploadProgressSink; signal: AbortSignal; handoff?: UploadHandoff; }): Promise { - const { normalizedBase, token, leaseId, artifact } = options; + const { normalizedBase, token, scopeHeaders, artifact } = options; const uploadUrl = new URL('upload', normalizedBase); const headers: Record = { @@ -259,7 +279,7 @@ async function uploadLegacyArtifact(options: { 'x-artifact-hash-algorithm': ARTIFACT_HASH_ALGORITHM, 'transfer-encoding': 'chunked', }; - Object.assign(headers, buildDaemonHttpAuthHeaders(token), buildDaemonHttpLeaseHeaders(leaseId)); + Object.assign(headers, buildDaemonHttpAuthHeaders(token), scopeHeaders); const response = await streamFileToHttpRequest({ url: uploadUrl, @@ -280,7 +300,10 @@ async function uploadLegacyArtifact(options: { try { const parsed = JSON.parse(response.body) as UploadResponse; if (!parsed.ok || !parsed.uploadId) { - throw new AppError('COMMAND_FAILED', `Upload failed: ${response.body}`); + throw ( + readUploadRefusal(parsed) ?? + new AppError('COMMAND_FAILED', `Upload failed: ${response.body}`) + ); } return parsed.uploadId; } catch (error) { @@ -292,7 +315,7 @@ async function uploadLegacyArtifact(options: { async function requestUploadPreflight(options: { normalizedBase: string; token: string; - leaseId?: string; + scopeHeaders: Record; artifact: PreparedUploadArtifact; uploadAttemptId: string; env: HostEnvironment['env']; @@ -303,11 +326,7 @@ async function requestUploadPreflight(options: { const headers: Record = { 'content-type': 'application/json', }; - Object.assign( - headers, - buildDaemonHttpAuthHeaders(options.token), - buildDaemonHttpLeaseHeaders(options.leaseId), - ); + Object.assign(headers, buildDaemonHttpAuthHeaders(options.token), options.scopeHeaders); const result = await requestUploadControl( preflightUrl, @@ -367,7 +386,7 @@ async function requestUploadControl( }); }; const response = await (handoff?.(start) ?? start()); - const body: unknown = response.ok ? await response.json().catch(() => undefined) : undefined; + const body: unknown = await response.json().catch(() => undefined); watchdog.signal.throwIfAborted(); return { response, body }; } catch (error) { @@ -419,7 +438,7 @@ function isStringRecord(value: unknown): value is Record { async function uploadDirectArtifact( options: { normalizedBase: string; - leaseId?: string; + scopeHeaders: Record; artifact: PreparedUploadArtifact; onProgress?: UploadProgressSink; signal: AbortSignal; @@ -433,10 +452,10 @@ async function uploadDirectArtifact( url, method: 'PUT', // A ticket on the daemon's own origin is routed like any daemon request, so it names the lease - // too; a ticket elsewhere (a signed storage URL) gets only the headers the daemon handed out. + // and tenant too; a ticket elsewhere (a signed storage URL) gets only the daemon's headers. headers: url.origin === new URL(options.normalizedBase).origin - ? { ...ticket.headers, ...buildDaemonHttpLeaseHeaders(options.leaseId) } + ? { ...ticket.headers, ...options.scopeHeaders } : ticket.headers, payloadPath: artifact.payloadPath, errorMessage: 'Failed to upload artifact with direct upload ticket', @@ -461,7 +480,7 @@ async function uploadDirectArtifact( async function finalizeDirectUpload(options: { normalizedBase: string; token: string; - leaseId?: string; + scopeHeaders: Record; uploadId: string; signal?: AbortSignal; handoff?: UploadHandoff; @@ -470,11 +489,7 @@ async function finalizeDirectUpload(options: { const headers: Record = { 'content-type': 'application/json', }; - Object.assign( - headers, - buildDaemonHttpAuthHeaders(options.token), - buildDaemonHttpLeaseHeaders(options.leaseId), - ); + Object.assign(headers, buildDaemonHttpAuthHeaders(options.token), options.scopeHeaders); const result = await requestUploadControl( finalizeUrl, @@ -493,10 +508,13 @@ async function finalizeDirectUpload(options: { }); if (!result.response.ok) { - throw new AppError('COMMAND_FAILED', 'Direct artifact upload finalize failed', { - status: result.response.status, - statusText: result.response.statusText, - }); + throw ( + readUploadRefusal(result.body) ?? + new AppError('COMMAND_FAILED', 'Direct artifact upload finalize failed', { + status: result.response.status, + statusText: result.response.statusText, + }) + ); } const parsed = result.body as UploadResponse | undefined; From 77c84c0d96a7b95c8fdeb9d67a7617503974f421 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 12:43:15 +0100 Subject: [PATCH 08/10] test(wire-compat): record tenant header on upload requests --- test/wire-compat/ledger.json | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index c36004bfe45..67f46e52b4d 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -176,15 +176,15 @@ "packages/remote/src/upload-client.ts#UploadPreflightResponse": "sha256:196a1d9ef41a1aec192589fa7ccb30cf71d971a005349d5d73eed42e6ab21327", "packages/remote/src/upload-client.ts#UploadPreflightResult": "sha256:bd8fc6d617c0630325455fd64d0fe319daaced198ee6745e4673a8ace3df460d", "packages/remote/src/upload-client.ts#UploadResponse": "sha256:499e01466b5e0e03413f8d3f1986f5af6bc120704c50a3747d84de422b3f0314", - "packages/remote/src/upload-client.ts#finalizeDirectUpload": "sha256:a947153dc39b154776b0d2f2ae8bbf184026ec832e41e4ad34280be277ed8724", + "packages/remote/src/upload-client.ts#finalizeDirectUpload": "sha256:b26241013b8c04d5632266a0ed357036ba30ffd087f2f6dda83bc43408e00b67", "packages/remote/src/upload-client.ts#isStringRecord": "sha256:b6d6b571b90baf0976d9c347c4a45a4363a4df5ad184ea1087cb3b9febd4b624", "packages/remote/src/upload-client.ts#parseUploadPreflightResult": "sha256:7ce3f43b45c03df8b7f2690432beedc7a537c1bba540961716862f8a632d5623", - "packages/remote/src/upload-client.ts#requestUploadControl": "sha256:0d6d02e327a0fe791817525cbd9cb72ac4c66d704540f582e2d1aa872e0ed3ff", - "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:e43a2aa251d0881b77a1c29858b5c6007dc38c59971275a0e7472ac8b330dd81", + "packages/remote/src/upload-client.ts#requestUploadControl": "sha256:b7634060cfe7cb9f4f2e1aba6b2e4adc43c3ad30a310f2ddd3276ffb1ec0d992", + "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:e6202ce3dc197853e95387e171c76860127ef148f6a38b62396ed17ef8d31fce", "packages/remote/src/upload-client.ts#shouldRetryDirectUpload": "sha256:29059f076ff7f2b9540ad15408be48792b2d63a601ef2b9fb2d54f5576d49bbd", - "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:cb90256a3d3d85b7f7b2db8d354327c89d2c6477de8155fdf29066d4f8de00f9", - "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:97fb5ccba0a36326fe05e190d14068b68a3bbafa33f5f650f5e5bb0292b99908", - "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:0fe842e708b3ebeb0e252a0b1e650a85335b99c4f8d1a8a519a51dc48821f851", + "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:147c6ae98240ecdb330914840e3c0505161f28b70c31c854cfaa6b96d9b31ab3", + "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:d5aeaefecaf729f962966822acab02cb9385e0a345ee8a94f280dd8c2df18a07", + "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:dc43d41475f612f5f8a027ac5d27d3729d6ab4291df600052b4c74885fac6242", "packages/remote/src/upload-stream.ts#MAX_UPLOAD_REDIRECTS": "sha256:12ff46dfe33a1dce95bdb79c90c17a3ba4f3919e7dc4b3a1b04590fff430f79f", "packages/remote/src/upload-stream.ts#UploadHandoff": "sha256:1e1a07668b0491ceffd178090b493e65dcee74c66cf7e434710861f2148db009", "packages/remote/src/upload-stream.ts#UploadStreamResponse": "sha256:724e284c2a6bd7b4b3a49b1d8c61c8923d6cc24777c3d76224a69d190e56adce", @@ -509,18 +509,18 @@ }, { "declaration": "packages/remote/src/upload-client.ts#uploadDirectArtifact", - "digest": "sha256:97fb5ccba0a36326fe05e190d14068b68a3bbafa33f5f650f5e5bb0292b99908", - "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006). #4441 also stops passing a timeout message and hint that no caller could see, and requires the preparation aggregate's signal. The ticket PUT keeps its route, method, headers and body. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages." + "digest": "sha256:d5aeaefecaf729f962966822acab02cb9385e0a345ee8a94f280dd8c2df18a07", + "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006). #4441 also stops passing a timeout message and hint that no caller could see, and requires the preparation aggregate's signal. The ticket PUT keeps its route, method, headers and body. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#tryDirectUploadWithResume", - "digest": "sha256:cb90256a3d3d85b7f7b2db8d354327c89d2c6477de8155fdf29066d4f8de00f9", - "rationale": "#4441 ends the direct-upload sequence when a transfer phase's own budget expires, instead of re-preflighting for a fresh ticket or falling back, because a second attempt would be permission that budget already refused. Preflight, ticket PUT and finalize requests are unchanged in route, method, headers and body, so a protocol-2 daemon parses everything it parsed before; it just receives no further legs once the caller's aggregate has expired. Its signal is now required, because the preparation aggregate is always the one passed down, and it is read directly; no request changes. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. The client judges a retry ticket URL locally." + "digest": "sha256:147c6ae98240ecdb330914840e3c0505161f28b70c31c854cfaa6b96d9b31ab3", + "rationale": "#4441 ends the direct-upload sequence when a transfer phase's own budget expires, instead of re-preflighting for a fresh ticket or falling back, because a second attempt would be permission that budget already refused. Preflight, ticket PUT and finalize requests are unchanged in route, method, headers and body, so a protocol-2 daemon parses everything it parsed before; it just receives no further legs once the caller's aggregate has expired. Its signal is now required, because the preparation aggregate is always the one passed down, and it is read directly; no request changes. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. The client judges a retry ticket URL locally. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#uploadLegacyArtifact", - "digest": "sha256:0fe842e708b3ebeb0e252a0b1e650a85335b99c4f8d1a8a519a51dc48821f851", - "rationale": "#4441 drops the hint that named the removed 5-minute timeout, and an expired transfer phase is no longer treated as a transport break, so this route is not re-entered by a fallback after the client's own budget ended the attempt. The POST /upload request itself is unchanged: same method, headers, chunked body and response parsing. A protocol-2 daemon sees the identical request in every case that completes, and no further request in a stalled one. The unreachable timeout message and hint are no longer passed, and the aggregate signal is required. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages." + "digest": "sha256:dc43d41475f612f5f8a027ac5d27d3729d6ab4291df600052b4c74885fac6242", + "rationale": "#4441 drops the hint that named the removed 5-minute timeout, and an expired transfer phase is no longer treated as a transport break, so this route is not re-entered by a fallback after the client's own budget ended the attempt. The POST /upload request itself is unchanged: same method, headers, chunked body and response parsing. A protocol-2 daemon sees the identical request in every case that completes, and no further request in a stalled one. The unreachable timeout message and hint are no longer passed, and the aggregate signal is required. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged." }, { "declaration": "packages/daemon-client/src/daemon-client-progress.ts#shouldReadDaemonProgressStream", @@ -579,18 +579,18 @@ }, { "declaration": "packages/remote/src/upload-client.ts#requestUploadControl", - "digest": "sha256:0d6d02e327a0fe791817525cbd9cb72ac4c66d704540f582e2d1aa872e0ed3ff", - "rationale": "Lists the shared control Fetch/JSON owner so changes to method, headers, body or redirect forwarding remain wire-gated. Existing preflight/finalize routes and protocol-2 payloads are preserved; the original 30-second ceiling now retains typed local phase expiry and stops later legs. Non-success status handling is unchanged. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. The client starts the network watchdog at admission and explicitly hands off streamed headers before releasing it. Request headers, route, body framing and response parsing are unchanged." + "digest": "sha256:b7634060cfe7cb9f4f2e1aba6b2e4adc43c3ad30a310f2ddd3276ffb1ec0d992", + "rationale": "Lists the shared control Fetch/JSON owner so changes to method, headers, body or redirect forwarding remain wire-gated. Existing preflight/finalize routes and protocol-2 payloads are preserved; the original 30-second ceiling now retains typed local phase expiry and stops later legs. Non-success status handling is unchanged. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. The client starts the network watchdog at admission and explicitly hands off streamed headers before releasing it. Request headers, route, body framing and response parsing are unchanged. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#requestUploadPreflight", - "digest": "sha256:e43a2aa251d0881b77a1c29858b5c6007dc38c59971275a0e7472ac8b330dd81", - "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. An inadmissible ticket URL is refused locally before sending and the legacy upload route remains available." + "digest": "sha256:e6202ce3dc197853e95387e171c76860127ef148f6a38b62396ed17ef8d31fce", + "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. An inadmissible ticket URL is refused locally before sending and the legacy upload route remains available. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#finalizeDirectUpload", - "digest": "sha256:a947153dc39b154776b0d2f2ae8bbf184026ec832e41e4ad34280be277ed8724", - "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages." + "digest": "sha256:b26241013b8c04d5632266a0ed357036ba30ffd087f2f6dda83bc43408e00b67", + "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged." }, { "declaration": "packages/daemon/src/server/http/http-rpc-methods.ts#toInstallFromSourceDaemonRequest", From daf62a2e3e4a86d26a7a225a56448ae3356064d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 13:20:32 +0100 Subject: [PATCH 09/10] fix(remote): end uploads on a typed preflight or ticket PUT refusal A failed preflight with a typed REST refusal reason, and a refused same-origin ticket PUT, now throw UploadRefusal instead of falling back to the legacy POST. An unsupported preflight route (404, 405, 501) and untyped failures keep the fallback. --- .../__tests__/upload-client-redirect.test.ts | 73 +++++++++++-------- packages/remote/src/upload-client.ts | 34 +++++++-- test/wire-compat/ledger.json | 12 +-- 3 files changed, 74 insertions(+), 45 deletions(-) diff --git a/packages/remote/src/__tests__/upload-client-redirect.test.ts b/packages/remote/src/__tests__/upload-client-redirect.test.ts index a04689c3969..1bda69d5757 100644 --- a/packages/remote/src/__tests__/upload-client-redirect.test.ts +++ b/packages/remote/src/__tests__/upload-client-redirect.test.ts @@ -142,36 +142,47 @@ test.for([ }, ); -test('a typed finalize refusal ends the upload with its reason and no legacy fallback', async (t) => { - if (await skipWhenLoopbackUnavailable(t, 'upload refusal coverage')) return; - const daemonRequests: string[] = []; - const daemon = await startServer((req, res) => { - daemonRequests.push(`${req.method} ${req.url}`); - req.resume(); - req.on('end', () => { - if (req.url === '/upload/preflight') { - const url = `${daemon.baseUrl}/upload/direct/t`; - return answerJson(res, { ok: true, uploadId: 't', upload: { url, headers: {} } }); - } - if (req.url === '/upload/direct/t') return res.end('ok'); - res.statusCode = 429; - answerJson(res, { error: 'Limit', code: 'COMMAND_FAILED', reason: 'UPLOAD_LIMIT_REACHED' }); +const REFUSAL_ROUTES = ['POST /upload/preflight', 'PUT /upload/direct/t', 'POST /upload/finalize']; + +test.for(REFUSAL_ROUTES)( + 'a typed refusal at %s ends the upload with its reason and no legacy fallback', + async (refusedRoute, t) => { + if (await skipWhenLoopbackUnavailable(t, 'upload refusal coverage')) return; + const daemonRequests: string[] = []; + const daemon = await startServer((req, res) => { + const route = `${req.method} ${req.url}`; + daemonRequests.push(route); + req.resume(); + req.on('end', () => { + if (route === refusedRoute) { + res.statusCode = 403; + return answerJson(res, { + ok: false, + error: 'Refused', + code: 'UNAUTHORIZED', + reason: 'LEASE_SESSION_MISMATCH', + }); + } + if (req.url === '/upload/preflight') { + const url = `${daemon.baseUrl}/upload/direct/t`; + return answerJson(res, { ok: true, uploadId: 't', upload: { url, headers: {} } }); + } + if (req.url === '/upload/direct/t') return res.end('ok'); + answerJson(res, { ok: true, uploadId: 'legacy-upload' }); + }); }); - }); - const localPath = path.join(mkdtempForTestSync('agent-device-upload-refusal-'), 'app.apk'); - fs.writeFileSync(localPath, 'apk-bytes'); + const localPath = path.join(mkdtempForTestSync('agent-device-upload-refusal-'), 'app.apk'); + fs.writeFileSync(localPath, 'apk-bytes'); - try { - await assert.rejects( - uploadArtifact({ localPath, baseUrl: daemon.baseUrl, token: 'token', env: process.env }), - { message: 'Limit', details: { reason: 'UPLOAD_LIMIT_REACHED' } }, - ); - assert.deepEqual(daemonRequests, [ - 'POST /upload/preflight', - 'PUT /upload/direct/t', - 'POST /upload/finalize', - ]); - } finally { - await daemon.close(); - } -}); + try { + await assert.rejects( + uploadArtifact({ localPath, baseUrl: daemon.baseUrl, token: 'token', env: process.env }), + { message: 'Refused', code: 'UNAUTHORIZED', details: { reason: 'LEASE_SESSION_MISMATCH' } }, + ); + const refusedAt = REFUSAL_ROUTES.indexOf(refusedRoute); + assert.deepEqual(daemonRequests, REFUSAL_ROUTES.slice(0, refusedAt + 1)); + } finally { + await daemon.close(); + } + }, +); diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index f5f1598b03d..ae285ea857c 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -244,6 +244,9 @@ async function retryDirectUpload( /** A daemon refusal with a typed reason, such as an upload limit. It ends the upload without a fallback. */ class UploadRefusal extends AppError {} +/** Statuses of a daemon without the preflight route; the legacy upload is its only route. */ +const UNSUPPORTED_PREFLIGHT_STATUSES = new Set([404, 405, 501]); + function readUploadRefusal(body: unknown): UploadRefusal | undefined { if (!body || typeof body !== 'object') return undefined; const { code, error, reason, hint } = body as Record; @@ -353,6 +356,13 @@ async function requestUploadPreflight(options: { }); if (!result?.response.ok) { + // A typed refusal, such as a lease or tenant scope or an upload limit, holds for the legacy + // route too. Only an unsupported route or an untyped failure takes the legacy upload. + const refusal = + result && !UNSUPPORTED_PREFLIGHT_STATUSES.has(result.response.status) + ? readUploadRefusal(result.body) + : undefined; + if (refusal) throw refusal; return undefined; } @@ -448,15 +458,13 @@ async function uploadDirectArtifact( ): Promise { const { artifact, onProgress, signal } = options; const url = new URL(ticket.url); + const daemonOrigin = url.origin === new URL(options.normalizedBase).origin; const response = await streamFileToHttpRequest({ url, method: 'PUT', // A ticket on the daemon's own origin is routed like any daemon request, so it names the lease // and tenant too; a ticket elsewhere (a signed storage URL) gets only the daemon's headers. - headers: - url.origin === new URL(options.normalizedBase).origin - ? { ...ticket.headers, ...options.scopeHeaders } - : ticket.headers, + headers: daemonOrigin ? { ...ticket.headers, ...options.scopeHeaders } : ticket.headers, payloadPath: artifact.payloadPath, errorMessage: 'Failed to upload artifact with direct upload ticket', retryable: true, @@ -470,10 +478,20 @@ async function uploadDirectArtifact( }); if (response.statusCode < 200 || response.statusCode >= 300) { - throw new AppError('COMMAND_FAILED', 'Direct artifact upload failed', { - statusCode: response.statusCode, - statusMessage: response.statusMessage, - }); + // The daemon answers a refused PUT with its typed REST body; a signed storage URL does not. + let daemonBody: unknown; + try { + if (daemonOrigin) daemonBody = JSON.parse(response.body); + } catch { + // An untyped failure body: the generic failure below stands. + } + throw ( + readUploadRefusal(daemonBody) ?? + new AppError('COMMAND_FAILED', 'Direct artifact upload failed', { + statusCode: response.statusCode, + statusMessage: response.statusMessage, + }) + ); } } diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 67f46e52b4d..da1ba132901 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -180,10 +180,10 @@ "packages/remote/src/upload-client.ts#isStringRecord": "sha256:b6d6b571b90baf0976d9c347c4a45a4363a4df5ad184ea1087cb3b9febd4b624", "packages/remote/src/upload-client.ts#parseUploadPreflightResult": "sha256:7ce3f43b45c03df8b7f2690432beedc7a537c1bba540961716862f8a632d5623", "packages/remote/src/upload-client.ts#requestUploadControl": "sha256:b7634060cfe7cb9f4f2e1aba6b2e4adc43c3ad30a310f2ddd3276ffb1ec0d992", - "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:e6202ce3dc197853e95387e171c76860127ef148f6a38b62396ed17ef8d31fce", + "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:9bc55c8c107c37c1e1146bee595a41a44a96481ba6403591fe83f7c21fd9f483", "packages/remote/src/upload-client.ts#shouldRetryDirectUpload": "sha256:29059f076ff7f2b9540ad15408be48792b2d63a601ef2b9fb2d54f5576d49bbd", "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:147c6ae98240ecdb330914840e3c0505161f28b70c31c854cfaa6b96d9b31ab3", - "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:d5aeaefecaf729f962966822acab02cb9385e0a345ee8a94f280dd8c2df18a07", + "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:a01f1e725dcb2ded04bc2673f2ef3fe80e9433d88f29d5c779357e6476b3c1fd", "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:dc43d41475f612f5f8a027ac5d27d3729d6ab4291df600052b4c74885fac6242", "packages/remote/src/upload-stream.ts#MAX_UPLOAD_REDIRECTS": "sha256:12ff46dfe33a1dce95bdb79c90c17a3ba4f3919e7dc4b3a1b04590fff430f79f", "packages/remote/src/upload-stream.ts#UploadHandoff": "sha256:1e1a07668b0491ceffd178090b493e65dcee74c66cf7e434710861f2148db009", @@ -509,8 +509,8 @@ }, { "declaration": "packages/remote/src/upload-client.ts#uploadDirectArtifact", - "digest": "sha256:d5aeaefecaf729f962966822acab02cb9385e0a345ee8a94f280dd8c2df18a07", - "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006). #4441 also stops passing a timeout message and hint that no caller could see, and requires the preparation aggregate's signal. The ticket PUT keeps its route, method, headers and body. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged." + "digest": "sha256:a01f1e725dcb2ded04bc2673f2ef3fe80e9433d88f29d5c779357e6476b3c1fd", + "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006). #4441 also stops passing a timeout message and hint that no caller could see, and requires the preparation aggregate's signal. The ticket PUT keeps its route, method, headers and body. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged. A refused same-origin ticket PUT now reads the existing typed REST error body and ends the upload with that reason instead of a generic failure that fell back to the legacy POST; this is client-local, and the request is unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#tryDirectUploadWithResume", @@ -584,8 +584,8 @@ }, { "declaration": "packages/remote/src/upload-client.ts#requestUploadPreflight", - "digest": "sha256:e6202ce3dc197853e95387e171c76860127ef148f6a38b62396ed17ef8d31fce", - "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. An inadmissible ticket URL is refused locally before sending and the legacy upload route remains available. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged." + "digest": "sha256:9bc55c8c107c37c1e1146bee595a41a44a96481ba6403591fe83f7c21fd9f483", + "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. An inadmissible ticket URL is refused locally before sending and the legacy upload route remains available. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged. A failed preflight that carries a typed REST refusal reason (outside 404, 405 and 501) now ends the upload locally instead of retrying through the legacy POST; this is client-local, and the request and accepted response fields are unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#finalizeDirectUpload", From 3cf54074d932a79b8c016a64c8c79b33d846506a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 14:17:40 +0100 Subject: [PATCH 10/10] fix(remote): keep the legacy upload for recoverable typed refusals --- .../__tests__/upload-client-redirect.test.ts | 40 +++++++++++++++++++ packages/remote/src/upload-client.ts | 25 +++++++++--- test/wire-compat/ledger.json | 12 +++--- 3 files changed, 65 insertions(+), 12 deletions(-) diff --git a/packages/remote/src/__tests__/upload-client-redirect.test.ts b/packages/remote/src/__tests__/upload-client-redirect.test.ts index 1bda69d5757..cddce6fa5e3 100644 --- a/packages/remote/src/__tests__/upload-client-redirect.test.ts +++ b/packages/remote/src/__tests__/upload-client-redirect.test.ts @@ -186,3 +186,43 @@ test.for(REFUSAL_ROUTES)( } }, ); + +test('a ticket that expires between preflight and PUT completes through the legacy upload', async (t) => { + if (await skipWhenLoopbackUnavailable(t, 'expired ticket coverage')) return; + const daemonRequests: string[] = []; + const daemon = await startServer((req, res) => { + daemonRequests.push(`${req.method} ${req.url}`); + req.resume(); + req.on('end', () => { + if (req.url === '/upload/preflight') { + const url = `${daemon.baseUrl}/upload/direct/t`; + return answerJson(res, { ok: true, uploadId: 't', upload: { url, headers: {} } }); + } + if (req.url === '/upload/direct/t') { + res.statusCode = 404; + return answerJson(res, { + ok: false, + error: 'Expired', + code: 'NOT_FOUND', + reason: 'RESOURCE_EXPIRED', + }); + } + answerJson(res, { ok: true, uploadId: 'legacy-upload' }); + }); + }); + const localPath = path.join(mkdtempForTestSync('agent-device-upload-expired-'), 'app.apk'); + fs.writeFileSync(localPath, 'apk-bytes'); + + try { + const uploadId = await uploadArtifact({ + localPath, + baseUrl: daemon.baseUrl, + token: 'token', + env: process.env, + }); + assert.equal(uploadId, 'legacy-upload'); + assert.equal(daemonRequests.at(-1), 'POST /upload'); + } finally { + await daemon.close(); + } +}); diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index ae285ea857c..857d48a1c2d 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -187,7 +187,7 @@ async function tryDirectUploadWithResume(options: { // re-preflighting would ask the daemon for a fresh ticket to send bytes nobody is waiting on. if (options.signal.aborted) throw error; // An expired phase is this client's own deadline, never a transport break to retry. - if (isTransferPhaseTimeoutError(error) || error instanceof UploadRefusal) throw error; + if (isTransferPhaseTimeoutError(error) || isDefinitiveRefusal(error)) throw error; if (!shouldRetryDirectUpload(error)) return undefined; return await retryDirectUpload(options, uploadOnce); } @@ -234,16 +234,29 @@ async function retryDirectUpload( return await uploadOnce(retryPreflight); } catch (error) { options.signal.throwIfAborted(); - if (isTransferPhaseTimeoutError(error) || error instanceof UploadRefusal) throw error; + if (isTransferPhaseTimeoutError(error) || isDefinitiveRefusal(error)) throw error; return undefined; } } return undefined; } -/** A daemon refusal with a typed reason, such as an upload limit. It ends the upload without a fallback. */ +/** A daemon refusal with a typed reason, such as an upload limit. */ class UploadRefusal extends AppError {} +/** Authorization, scope, and capacity reasons hold for the legacy route too; any other falls back. */ +const DEFINITIVE_REFUSAL_REASONS: ReadonlySet = new Set([ + 'LEASE_SESSION_MISMATCH', + 'LEASE_SCOPE_MISMATCH', + 'LEASE_OUTPUT_MISMATCH', + 'TENANT_OUTPUT_MISMATCH', + 'UPLOAD_LIMIT_REACHED', +]); + +function isDefinitiveRefusal(error: unknown): error is UploadRefusal { + return error instanceof UploadRefusal && DEFINITIVE_REFUSAL_REASONS.has(error.details?.reason); +} + /** Statuses of a daemon without the preflight route; the legacy upload is its only route. */ const UNSUPPORTED_PREFLIGHT_STATUSES = new Set([404, 405, 501]); @@ -356,13 +369,13 @@ async function requestUploadPreflight(options: { }); if (!result?.response.ok) { - // A typed refusal, such as a lease or tenant scope or an upload limit, holds for the legacy - // route too. Only an unsupported route or an untyped failure takes the legacy upload. + // A definitive refusal, such as a lease or tenant scope or an upload limit, holds for the legacy + // route too. Any other failure takes the legacy upload. const refusal = result && !UNSUPPORTED_PREFLIGHT_STATUSES.has(result.response.status) ? readUploadRefusal(result.body) : undefined; - if (refusal) throw refusal; + if (isDefinitiveRefusal(refusal)) throw refusal; return undefined; } diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index da1ba132901..0660a112fe1 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -180,9 +180,9 @@ "packages/remote/src/upload-client.ts#isStringRecord": "sha256:b6d6b571b90baf0976d9c347c4a45a4363a4df5ad184ea1087cb3b9febd4b624", "packages/remote/src/upload-client.ts#parseUploadPreflightResult": "sha256:7ce3f43b45c03df8b7f2690432beedc7a537c1bba540961716862f8a632d5623", "packages/remote/src/upload-client.ts#requestUploadControl": "sha256:b7634060cfe7cb9f4f2e1aba6b2e4adc43c3ad30a310f2ddd3276ffb1ec0d992", - "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:9bc55c8c107c37c1e1146bee595a41a44a96481ba6403591fe83f7c21fd9f483", + "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:711e92da1332dd30ac75c56f4262cf589d49346be4de77bfbf5636b7438972a9", "packages/remote/src/upload-client.ts#shouldRetryDirectUpload": "sha256:29059f076ff7f2b9540ad15408be48792b2d63a601ef2b9fb2d54f5576d49bbd", - "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:147c6ae98240ecdb330914840e3c0505161f28b70c31c854cfaa6b96d9b31ab3", + "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:183985dfe912398741bb9443e4a2fd74c7cfd044fb0daf00793e720a79781495", "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:a01f1e725dcb2ded04bc2673f2ef3fe80e9433d88f29d5c779357e6476b3c1fd", "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:dc43d41475f612f5f8a027ac5d27d3729d6ab4291df600052b4c74885fac6242", "packages/remote/src/upload-stream.ts#MAX_UPLOAD_REDIRECTS": "sha256:12ff46dfe33a1dce95bdb79c90c17a3ba4f3919e7dc4b3a1b04590fff430f79f", @@ -510,11 +510,11 @@ { "declaration": "packages/remote/src/upload-client.ts#uploadDirectArtifact", "digest": "sha256:a01f1e725dcb2ded04bc2673f2ef3fe80e9433d88f29d5c779357e6476b3c1fd", - "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006). #4441 also stops passing a timeout message and hint that no caller could see, and requires the preparation aggregate's signal. The ticket PUT keeps its route, method, headers and body. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged. A refused same-origin ticket PUT now reads the existing typed REST error body and ends the upload with that reason instead of a generic failure that fell back to the legacy POST; this is client-local, and the request is unchanged." + "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006). #4441 also stops passing a timeout message and hint that no caller could see, and requires the preparation aggregate's signal. The ticket PUT keeps its route, method, headers and body. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged. A same-origin ticket PUT refused with a definitive typed REST reason (authorization, scope or capacity) now ends the upload with that reason instead of falling back to the legacy POST, and any other failure keeps the fallback; this is client-local, and the request is unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#tryDirectUploadWithResume", - "digest": "sha256:147c6ae98240ecdb330914840e3c0505161f28b70c31c854cfaa6b96d9b31ab3", + "digest": "sha256:183985dfe912398741bb9443e4a2fd74c7cfd044fb0daf00793e720a79781495", "rationale": "#4441 ends the direct-upload sequence when a transfer phase's own budget expires, instead of re-preflighting for a fresh ticket or falling back, because a second attempt would be permission that budget already refused. Preflight, ticket PUT and finalize requests are unchanged in route, method, headers and body, so a protocol-2 daemon parses everything it parsed before; it just receives no further legs once the caller's aggregate has expired. Its signal is now required, because the preparation aggregate is always the one passed down, and it is read directly; no request changes. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. The client judges a retry ticket URL locally. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged." }, { @@ -584,8 +584,8 @@ }, { "declaration": "packages/remote/src/upload-client.ts#requestUploadPreflight", - "digest": "sha256:9bc55c8c107c37c1e1146bee595a41a44a96481ba6403591fe83f7c21fd9f483", - "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. An inadmissible ticket URL is refused locally before sending and the legacy upload route remains available. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged. A failed preflight that carries a typed REST refusal reason (outside 404, 405 and 501) now ends the upload locally instead of retrying through the legacy POST; this is client-local, and the request and accepted response fields are unchanged." + "digest": "sha256:711e92da1332dd30ac75c56f4262cf589d49346be4de77bfbf5636b7438972a9", + "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. An inadmissible ticket URL is refused locally before sending and the legacy upload route remains available. #5344 adds the existing tenant header beside the lease header; a daemon that does not read it ignores it, and the route, body and framing are unchanged. A failed preflight that carries a definitive typed REST refusal reason (authorization, scope or capacity) now ends the upload locally instead of retrying through the legacy POST, and any other failure keeps the legacy route; this is client-local, and the request and accepted response fields are unchanged." }, { "declaration": "packages/remote/src/upload-client.ts#finalizeDirectUpload",