From 76af1163723999aa210d56ef54cb051324be458e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 17:16:35 +0100 Subject: [PATCH 01/35] fix: bind retained artifacts and uploads to lease ownership --- .../src/resources/artifact-tracking.test.ts | 49 +++++++++++++++++++ .../daemon/src/resources/artifact-tracking.ts | 44 ++++++++++++++--- .../daemon/src/resources/lease-registry.ts | 14 +++++- .../resources/provider-session-ownership.ts | 48 ++++++++++++++++-- .../src/server/downloadable-artifact-http.ts | 9 +++- .../daemon/src/server/request-finalization.ts | 1 + .../materialized-path-registry.test.ts | 22 +++++++++ .../__tests__/lease-artifacts.test.ts | 43 ++++++++++++++++ .../daemon/src/sessions/handlers/lease.ts | 25 +++++++--- .../handlers/session-app-deployment.ts | 2 +- .../handlers/session-app-source-deployment.ts | 5 +- .../src/sessions/install-source-resolution.ts | 2 +- .../sessions/leased-recording-retention.ts | 1 + .../sessions/materialized-path-registry.ts | 7 +++ 14 files changed, 250 insertions(+), 22 deletions(-) diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index 0a06f195f1b..3a95b874b03 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -10,8 +10,10 @@ import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; import * as command from '@agent-device/host-kit/command'; import { cleanupDownloadableArtifact, + cleanupUploadedArtifact, listDownloadableArtifacts, openDownloadableArtifact, + prepareUploadedArtifact, trackDownloadableArtifact, trackUploadedArtifact, type OpenedDownloadableArtifact, @@ -582,6 +584,53 @@ test('disposing a runtime removes the temporary files it still tracks', () => { expect(fs.existsSync(artifactPath)).toBe(false); }); +test('uploads stay bound to their producing lease and release capacity on cleanup', () => { + const root = mkdtempForTestSync('agent-device-upload-lease-'); + const artifactPath = path.join(root, 'payload'); + fs.writeFileSync(artifactPath, 'payload'); + const releaseReservation = vi.fn(); + const runtime = createRuntimeStateHandle(); + const id = runtime.run(() => trackUploadedArtifact({ + artifactPath, + tempDir: root, + tenantId: 'tenant-a', + leaseId: 'lease-a', + releaseReservation, + })); + + for (const leaseId of [undefined, 'lease-b']) { + expect(() => runtime.run(() => prepareUploadedArtifact(id, 'tenant-a', leaseId))).toThrow(/different lease/); + } + expect(releaseReservation).not.toHaveBeenCalled(); + expect(runtime.run(() => prepareUploadedArtifact(id, 'tenant-a', 'lease-a'))).toBe(artifactPath); + runtime.run(() => cleanupUploadedArtifact(id)); + expect(releaseReservation).toHaveBeenCalledOnce(); + runtime.dispose(); +}); + +test('a retained downloadable artifact requires its producing lease', async () => { + const root = mkdtempForTestSync('agent-device-download-lease-'); + const artifactPath = path.join(root, 'recording.mp4'); + fs.writeFileSync(artifactPath, 'video'); + const runtime = createRuntimeStateHandle(); + const id = runtime.run(() => trackDownloadableArtifact({ + artifactPath, + tenantId: 'tenant-a', + leaseId: 'lease-a', + artifactType: 'screen-recording', + })); + try { + expect(await runtime.run(() => listDownloadableArtifacts('tenant-a', process.env, 'lease-b'))).toEqual([]); + expect(await runtime.run(() => listDownloadableArtifacts('tenant-a', process.env, 'lease-a'))).toHaveLength(1); + await expect(runtime.run(() => openDownloadableArtifact(id, 'tenant-a', process.env, undefined, 'lease-b'))).rejects.toThrow(/different lease/); + const opened = await runtime.run(() => openDownloadableArtifact(id, 'tenant-a', process.env, undefined, 'lease-a')); + expect(await buffer(opened.stream)).toEqual(Buffer.from('video')); + opened.release(); + } finally { + 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'); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index e09ea31c282..b2295ce8431 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -53,6 +53,7 @@ type ArtifactDownload = { type ArtifactEntry = { artifactPath: string; tenantId?: string; + leaseId?: string; artifactType: DaemonArtifactType | undefined; fileName?: string; displayRotation?: DeviceRotation; @@ -83,6 +84,7 @@ const artifactTracking = (): ArtifactTrackingState => } for (const entry of state.uploads.values()) { clearTimeout(entry.timer); + entry.releaseReservation?.(); removeBestEffort(entry.tempDir); } }, @@ -94,6 +96,7 @@ const pendingUploads = () => artifactTracking().uploads; export type DownloadableArtifactRegistration = { artifactPath: string; tenantId?: string; + leaseId?: string; artifactType: DaemonArtifactType | undefined; fileName?: string; displayRotation?: DeviceRotation; @@ -124,7 +127,7 @@ export type OpenedDownloadableArtifact = PreparedDownloadableArtifact & { * download. */ export function trackDownloadableArtifact(params: DownloadableArtifactRegistration): string { - const existingId = findTrackedArtifactId(params.artifactPath, params.tenantId); + const existingId = findTrackedArtifactId(params.artifactPath, params.tenantId, params.leaseId); if (existingId) return existingId; const artifactId = crypto.randomUUID(); const createdAt = Date.now(); @@ -141,6 +144,7 @@ export function trackDownloadableArtifact(params: DownloadableArtifactRegistrati pendingArtifacts().set(artifactId, { artifactPath: params.artifactPath, tenantId: params.tenantId, + leaseId: params.leaseId, artifactType: params.artifactType, fileName: params.fileName, ...(params.displayRotation !== undefined ? { displayRotation: params.displayRotation } : {}), @@ -157,12 +161,14 @@ export function trackDownloadableArtifact(params: DownloadableArtifactRegistrati function findTrackedArtifactId( artifactPath: string, tenantId: string | undefined, + leaseId: string | undefined, ): string | undefined { for (const [artifactId, entry] of pendingArtifacts()) { if ( !entry.cleanupRequested && entry.artifactPath === artifactPath && - entry.tenantId === tenantId + entry.tenantId === tenantId && + entry.leaseId === leaseId ) return artifactId; } @@ -181,10 +187,11 @@ export async function openDownloadableArtifact( tenantId: string | undefined, hostEnv: NodeJS.ProcessEnv, signal?: AbortSignal, + leaseId?: string, ): Promise { if (signal?.aborted) throw createRequestCanceledError(); const artifacts = pendingArtifacts(); - const { entry, stat } = readDownloadableArtifactEntry(artifactId, tenantId); + const { entry, stat } = readDownloadableArtifactEntry(artifactId, tenantId, leaseId); const download: ArtifactDownload = { controller: new AbortController(), release: () => { @@ -245,10 +252,11 @@ function cancelArtifactDownload( export async function listDownloadableArtifacts( tenantId: string | undefined, hostEnv: NodeJS.ProcessEnv, + leaseId?: string, ): Promise { const artifacts: DaemonArtifactInventoryEntry[] = []; for (const [id, entry] of pendingArtifacts()) { - if (!canReadArtifact(entry, tenantId)) continue; + if (!canReadArtifact(entry, tenantId, leaseId)) continue; let stat: fs.Stats; try { stat = fs.statSync(entry.artifactPath); @@ -290,6 +298,7 @@ async function prepareArtifactPayloadForInventory( function readDownloadableArtifactEntry( artifactId: string, tenantId: string | undefined, + leaseId: string | undefined, ): { entry: ArtifactEntry; stat: fs.Stats } { const entry = requireTenantOwnedEntry( pendingArtifacts(), @@ -300,6 +309,9 @@ function readDownloadableArtifactEntry( if (entry.cleanupRequested) { throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } + if (entry.leaseId !== leaseId) { + throw new AppError('UNAUTHORIZED', 'Artifact belongs to a different lease'); + } let stat: fs.Stats; try { stat = fs.statSync(entry.artifactPath); @@ -435,8 +447,12 @@ function archiveFilename(fileName: string): string { return `${fileName}.tar.gz`; } -function canReadArtifact(entry: ArtifactEntry, tenantId: string | undefined): boolean { - return !entry.cleanupRequested && entry.tenantId === tenantId; +function canReadArtifact( + entry: ArtifactEntry, + tenantId: string | undefined, + leaseId?: string, +): boolean { + return !entry.cleanupRequested && entry.tenantId === tenantId && entry.leaseId === leaseId; } function safeArtifactFilename(fileName: string | undefined, fallback: string): string { @@ -510,6 +526,8 @@ type UploadEntry = { artifactPath: string; tempDir: string; tenantId?: string; + leaseId?: string; + releaseReservation?: () => void; timer: ReturnType; }; @@ -517,6 +535,8 @@ export function trackUploadedArtifact(params: { artifactPath: string; tempDir: string; tenantId?: string; + leaseId?: string; + releaseReservation?: () => void; }): string { const uploadId = crypto.randomUUID(); const timer = setTimeout(() => { @@ -527,18 +547,27 @@ export function trackUploadedArtifact(params: { artifactPath: params.artifactPath, tempDir: params.tempDir, tenantId: params.tenantId, + leaseId: params.leaseId, + releaseReservation: params.releaseReservation, timer, }); return uploadId; } -export function prepareUploadedArtifact(uploadId: string, tenantId?: string): string { +export function prepareUploadedArtifact( + uploadId: string, + tenantId?: string, + leaseId?: string, +): string { const entry = requireTenantOwnedEntry( pendingUploads(), uploadId, tenantId, UPLOADED_ARTIFACT_RESOURCE, ); + if (entry.leaseId !== leaseId) { + throw new AppError('UNAUTHORIZED', 'Uploaded artifact belongs to a different lease'); + } clearTimeout(entry.timer); return entry.artifactPath; } @@ -548,5 +577,6 @@ export function cleanupUploadedArtifact(uploadId: string): void { if (!entry) return; clearTimeout(entry.timer); pendingUploads().delete(uploadId); + entry.releaseReservation?.(); fs.rmSync(entry.tempDir, { recursive: true, force: true }); } diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index fd62615a014..6c34df20a0c 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -187,6 +187,7 @@ export class LeaseRegistry { private issueLease(lease: DeviceLease): void { this.issuedLeaseIds.add(lease.leaseId); this.leases.set(lease.leaseId, lease); + this.providerSessionOwnership.recordLease(lease); this.bindLease(lease); this.reportProviderLeases(lease); } @@ -361,7 +362,7 @@ export class LeaseRegistry { } recordProviderSession( - lease: Pick, + lease: Pick, providerSessionId: string, ): void { this.cleanupExpiredLeases(); @@ -376,11 +377,22 @@ export class LeaseRegistry { provider?: string; providerSessionId?: string; tenantId?: string; + runId?: string; }): ProviderSessionOwnership | undefined { this.cleanupExpiredLeases(); return this.providerSessionOwnership.resolve(params); } + resolveRetainedProviderLease(params: { + leaseId: string; + provider?: string; + tenantId?: string; + runId?: string; + }): ReturnType { + this.cleanupExpiredLeases(); + return this.providerSessionOwnership.resolveLease(params); + } + listHumanControlHolds(authority: HumanControlAuthority): HumanControlHold[] { this.cleanupExpiredLeases(); const key = diff --git a/packages/daemon/src/resources/provider-session-ownership.ts b/packages/daemon/src/resources/provider-session-ownership.ts index 08a8b2ed7e1..bd3fc58f84b 100644 --- a/packages/daemon/src/resources/provider-session-ownership.ts +++ b/packages/daemon/src/resources/provider-session-ownership.ts @@ -7,12 +7,15 @@ export type ProviderSessionOwnership = Readonly<{ providerSessionId: string; leaseId: string; tenantId: string; + runId: string; }>; type ProviderSessionRecord = ProviderSessionOwnership & { retainedUntil?: number; }; +type LeaseOwnershipRecord = Omit; + export function providerSessionIdFromData( providerData: Record | undefined, ): string | undefined { @@ -24,6 +27,7 @@ export function providerSessionIdFromData( export class ProviderSessionOwnershipRegistry { private readonly records = new Map(); + private readonly leases = new Map(); private readonly now: () => number; private readonly retentionMs: number; @@ -34,7 +38,10 @@ export class ProviderSessionOwnershipRegistry { : DEFAULT_PROVIDER_SESSION_RETENTION_MS; } - record(lease: Pick, rawId: string): void { + record( + lease: Pick, + rawId: string, + ): void { const provider = lease.leaseProvider?.trim(); const providerSessionId = rawId.trim(); if (!provider || !providerSessionId) return; @@ -44,10 +51,23 @@ export class ProviderSessionOwnershipRegistry { providerSessionId, leaseId: lease.leaseId, tenantId: lease.tenantId, + runId: lease.runId, }; this.records.set(this.key(provider, providerSessionId), ownership); } + recordLease(lease: Pick): void { + const provider = lease.leaseProvider?.trim(); + if (!provider) return; + this.prune(); + this.leases.set(lease.leaseId, { + provider, + leaseId: lease.leaseId, + tenantId: lease.tenantId, + runId: lease.runId, + }); + } + markLeaseReleased( lease: Pick, releasedAt = this.now(), @@ -56,6 +76,8 @@ export class ProviderSessionOwnershipRegistry { if (!provider) return; this.prune(); const retainedUntil = releasedAt + this.retentionMs; + const leaseRecord = this.leases.get(lease.leaseId); + if (leaseRecord) this.leases.set(lease.leaseId, { ...leaseRecord, retainedUntil }); for (const [key, record] of this.records) { if (record.provider !== provider || record.leaseId !== lease.leaseId) continue; this.records.set(key, { ...record, retainedUntil }); @@ -66,17 +88,34 @@ export class ProviderSessionOwnershipRegistry { provider?: string; providerSessionId?: string; tenantId?: string; + runId?: string; }): ProviderSessionOwnership | undefined { const provider = params.provider?.trim(); const providerSessionId = params.providerSessionId?.trim(); const tenantId = params.tenantId?.trim(); - if (!provider || !providerSessionId || !tenantId) return undefined; + if (!provider || !providerSessionId || !tenantId || !params.runId) return undefined; this.prune(); const record = this.records.get(this.key(provider, providerSessionId)); - if (!record || record.tenantId !== tenantId) return undefined; + if (!record || record.tenantId !== tenantId || record.runId !== params.runId) return undefined; return { ...record }; } + resolveLease(params: { + leaseId: string; + provider?: string; + tenantId?: string; + runId?: string; + }): LeaseOwnershipRecord | undefined { + if (!params.provider || !params.tenantId || !params.runId) return undefined; + this.prune(); + const record = this.leases.get(params.leaseId); + return record?.provider === params.provider && + record.tenantId === params.tenantId && + record.runId === params.runId + ? { ...record } + : undefined; + } + private prune(): void { const now = this.now(); for (const [key, record] of this.records) { @@ -84,6 +123,9 @@ export class ProviderSessionOwnershipRegistry { this.records.delete(key); } } + for (const [key, record] of this.leases) { + if (record.retainedUntil !== undefined && record.retainedUntil <= now) this.leases.delete(key); + } } private key(provider: string, providerSessionId: string): string { diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index 5bd12ae641a..b6b5c26693c 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -12,6 +12,7 @@ import { import { failStreamedHttpResponse, sendRestJsonError } from './http-errors.ts'; import { decodeUriSegment } from './http-request-target.ts'; import { responseDisconnectSignal } from './http/response-disconnect-signal.ts'; +import { DAEMON_HTTP_LEASE_HEADER } from '@agent-device/contracts/daemon-http'; const ARTIFACT_DOWNLOAD_REASONS = { // The artifact stream ended at a different size than the daemon recorded; `details` gives both @@ -107,6 +108,7 @@ async function handleArtifactDownload( auth.tenantId, options.hostEnv, signal, + readLeaseId(req), ); const { stream } = artifact; const closed = finished(stream, { cleanup: true }).catch(() => {}); @@ -179,7 +181,7 @@ async function handleArtifactInventory( res.setHeader('content-type', 'application/json'); res.end( JSON.stringify({ - artifacts: await listDownloadableArtifacts(auth.tenantId, options.hostEnv), + artifacts: await listDownloadableArtifacts(auth.tenantId, options.hostEnv, readLeaseId(req)), }), ); } catch (error) { @@ -187,6 +189,11 @@ async function handleArtifactInventory( } } +function readLeaseId(req: http.IncomingMessage): string | undefined { + const value = req.headers[DAEMON_HTTP_LEASE_HEADER]; + return typeof value === 'string' && value.trim() ? value.trim() : undefined; +} + function readArtifactId(pathname: string): string { const encoded = pathname.slice('/artifacts/'.length); if (!encoded || encoded.includes('/')) return ''; diff --git a/packages/daemon/src/server/request-finalization.ts b/packages/daemon/src/server/request-finalization.ts index 06b515b4a8b..cd4c1718da4 100644 --- a/packages/daemon/src/server/request-finalization.ts +++ b/packages/daemon/src/server/request-finalization.ts @@ -109,6 +109,7 @@ function registerDownloadableArtifacts( tenantId: delivered ? delivered.tenantId : (captureOutputTenantId(data) ?? req.meta?.tenantId), + leaseId: req.meta?.leaseId, artifactType: artifact.artifactType, fileName: artifact.fileName, ...(artifact.deleteAfterDownload === false ? { deleteAfterDownload: false } : {}), diff --git a/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts b/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts index 04f19cebf1f..006a48b0f66 100644 --- a/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts +++ b/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts @@ -129,6 +129,28 @@ test('cleanup of tenant-owned materialization rejects other tenants', async () = fs.rmSync(tempRoot, { recursive: true, force: true }); }); +test('same tenant cannot release materialized paths from another lease', async () => { + const tempRoot = mkdtempForTestSync('agent-device-retained-lease-'); + const appPath = path.join(tempRoot, 'Sample.app'); + fs.mkdirSync(appPath, { recursive: true }); + const retained = await retainMaterializedPaths({ + installablePath: appPath, + tenantId: 'tenant-a', + leaseId: 'lease-a', + }); + + for (const leaseId of [undefined, 'lease-b']) { + await assert.rejects( + () => cleanupRetainedMaterializedPaths(retained.materializationId, 'tenant-a', leaseId), + { code: 'UNAUTHORIZED' }, + ); + assert.equal(fs.existsSync(retained.installablePath), true); + } + await cleanupRetainedMaterializedPaths(retained.materializationId, 'tenant-a', 'lease-a'); + assert.equal(fs.existsSync(retained.installablePath), false); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + test('TTL expiry cleans up tenant-owned materializations without a tenant context', async () => { const tempRoot = mkdtempForTestSync('agent-device-retained-ttl-'); const appPath = path.join(tempRoot, 'Sample.app'); diff --git a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts index 15263141a63..9ed033076c0 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts @@ -74,6 +74,49 @@ test('artifacts admits an owned lease ID and refuses a foreign lease ID before c ]); }); +test('artifacts admits a closed lease for its owner until retention expires', async () => { + let now = 1_000; + const world = createWorld({ now: () => now, providerSessionRetentionMs: 100 }); + const lease = await allocateLease(world, 'tenant-a', 'run-a'); + await releaseLease(world, lease); + + const scope = { tenantId: 'tenant-a', runId: 'run-a', leaseId: lease.leaseId }; + assert.equal((await listArtifacts(world, scope)).ok, true); + assert.deepEqual(world.providerCalls, [ + { provider: CLOUD_PROVIDER, leaseId: lease.leaseId, providerSessionId: undefined }, + ]); + world.providerCalls.length = 0; + + for (const denied of [ + { ...scope, tenantId: 'tenant-b' }, + { ...scope, runId: 'run-b' }, + { leaseId: lease.leaseId }, + ]) { + await assert.rejects(() => listArtifacts(world, denied), (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'UNAUTHORIZED'); + return true; + }); + } + assert.deepEqual(world.providerCalls, []); + + now = 1_101; + await assert.rejects(() => listArtifacts(world, scope), { code: 'UNAUTHORIZED' }); + assert.deepEqual(world.providerCalls, []); +}); + +test('artifacts admits a released cloud lease without a provider session ID', async () => { + const world = createWorld(); + world.lifecycle.allocate = async () => ({}); + world.lifecycle.release = async () => ({}); + const lease = await allocateLease(world, 'tenant-a', 'run-a'); + await releaseLease(world, lease); + + assert.equal((await listArtifacts(world, { + tenantId: 'tenant-a', runId: 'run-a', leaseId: lease.leaseId, + })).ok, true); +}); + test('artifacts lists an owned active and recently released provider session', async () => { const world = createWorld(); const lease = await allocateLease(world, 'tenant-a', 'run-a'); diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index 42632d95f0d..de26a6905c6 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -33,7 +33,6 @@ import type { SessionStore } from '../../core/session-store.ts'; import { isProxyLeaseScope, resolveLeaseScope, - resolveRequestOrSessionLeaseScope, } from '../../core/lease-context.ts'; import { isProviderInstanceEndedError, @@ -103,12 +102,11 @@ export async function handleLeaseCommands(args: LeaseHandlerArgs): Promise { const providerSessionId = readFlagString(req.flags, 'providerSessionId'); if (shouldListDaemonArtifacts(leaseScope, providerSessionId)) { - return await listDaemonArtifacts(leaseScope.tenantId, hostEnv); + return await listDaemonArtifacts(leaseScope.tenantId, leaseScope.leaseId, hostEnv); } return await listCloudArtifactsForRequest( @@ -538,9 +536,10 @@ function shouldListDaemonArtifacts( async function listDaemonArtifacts( tenantId: string | undefined, + leaseId: string | undefined, hostEnv: NodeJS.ProcessEnv, ): Promise { - const artifacts = await listDownloadableArtifacts(tenantId, hostEnv); + const artifacts = await listDownloadableArtifacts(tenantId, hostEnv, leaseId); return { source: 'daemon', status: 'ready', @@ -568,9 +567,22 @@ async function listCloudArtifactsForRequest( ); } if (leaseScope.leaseId && !providerSessionId) { - leaseRegistry.assertLeaseReadAdmission({ ...leaseScope, leaseId: leaseScope.leaseId }); + const activeLease = leaseRegistry.getLease({ ...leaseScope, leaseId: leaseScope.leaseId }); + if (!activeLease && !leaseRegistry.resolveRetainedProviderLease({ + leaseId: leaseScope.leaseId, + provider: leaseScope.leaseProvider, + tenantId: leaseScope.tenantId, + runId: leaseScope.runId, + })) { + throw new AppError('UNAUTHORIZED', 'Lease is not owned by the request scope'); + } } const providerSession = resolveProviderSession(leaseRegistry, leaseScope, providerSessionId); + if (providerSession && leaseScope.leaseId && providerSession.leaseId !== leaseScope.leaseId) { + throw new AppError('UNAUTHORIZED', 'Provider session does not belong to the requested lease', { + reason: LEASE_HANDLER_REASONS.providerSessionNotOwned.reason, + }); + } const result = await cloudArtifactProvider?.listCloudArtifacts?.({ provider: leaseScope.leaseProvider, leaseId: providerSession?.leaseId ?? leaseScope.leaseId, @@ -595,6 +607,7 @@ function resolveProviderSession( provider: leaseScope.leaseProvider, providerSessionId, tenantId: leaseScope.tenantId, + runId: leaseScope.runId, }); if (providerSession) return providerSession; throw new AppError('UNAUTHORIZED', 'Provider session is not owned by the request tenant', { diff --git a/packages/daemon/src/sessions/handlers/session-app-deployment.ts b/packages/daemon/src/sessions/handlers/session-app-deployment.ts index b8ef2f0f8e9..1c0a4f0711c 100644 --- a/packages/daemon/src/sessions/handlers/session-app-deployment.ts +++ b/packages/daemon/src/sessions/handlers/session-app-deployment.ts @@ -77,7 +77,7 @@ export async function handleAppDeploymentCommand(params: { const uploadedArtifactId = req.meta?.uploadedArtifactId; // Acquire before the cleanup scope: a rejected foreign upload ID must not delete that upload. const appPath = uploadedArtifactId - ? prepareUploadedArtifact(uploadedArtifactId, req.meta?.tenantId) + ? prepareUploadedArtifact(uploadedArtifactId, req.meta?.tenantId, req.meta?.leaseId) : expandSessionPath(target.appPathInput, requestCwd(req, params.host)); try { if (!fs.existsSync(appPath)) { 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..7c634c2a0b3 100644 --- a/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts +++ b/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts @@ -132,7 +132,7 @@ export async function handleInstallFromSourceDeploymentCommand(params: { return { ok: true, data }; } catch (error) { if (retained) { - await cleanupRetainedMaterializedPaths(retained.materializationId, req.meta?.tenantId).catch( + await cleanupRetainedMaterializedPaths(retained.materializationId, req.meta?.tenantId, req.meta?.leaseId).catch( () => {}, ); } @@ -152,7 +152,7 @@ export async function handleReleaseMaterializedPathsCommand(params: { if (!materializationId) { throw new AppError('INVALID_ARGS', 'release_materialized_paths requires a materializationId'); } - await cleanupRetainedMaterializedPaths(materializationId, req.meta?.tenantId); + await cleanupRetainedMaterializedPaths(materializationId, req.meta?.tenantId, req.meta?.leaseId); return { ok: true, data: { released: true, materializationId } }; } catch (error) { return { ok: false, error: normalizeError(error) }; @@ -221,6 +221,7 @@ async function retainIfRequested(params: { archivePath: params.artifact.archivePath, installablePath: params.artifact.installablePath, tenantId: params.req.meta?.tenantId, + leaseId: params.req.meta?.leaseId, sessionName: params.session ? params.sessionName : undefined, ttlMs: params.retention.ttlMs, }); diff --git a/packages/daemon/src/sessions/install-source-resolution.ts b/packages/daemon/src/sessions/install-source-resolution.ts index b040b3ce0ec..ca37280b5ab 100644 --- a/packages/daemon/src/sessions/install-source-resolution.ts +++ b/packages/daemon/src/sessions/install-source-resolution.ts @@ -48,7 +48,7 @@ export function resolveInstallSource(req: DaemonRequest): { return { source: { kind: 'path', - path: prepareUploadedArtifact(uploadedArtifactId, req.meta?.tenantId), + path: prepareUploadedArtifact(uploadedArtifactId, req.meta?.tenantId, req.meta?.leaseId), }, cleanup: () => { cleanupUploadedArtifact(uploadedArtifactId); diff --git a/packages/daemon/src/sessions/leased-recording-retention.ts b/packages/daemon/src/sessions/leased-recording-retention.ts index e42524f7a42..4c574b7440e 100644 --- a/packages/daemon/src/sessions/leased-recording-retention.ts +++ b/packages/daemon/src/sessions/leased-recording-retention.ts @@ -37,6 +37,7 @@ export function retainLeasedSessionRecording( trackDownloadableArtifact({ artifactPath: artifact.path!, tenantId: lease.tenantId, + leaseId: lease.leaseId, artifactType: artifact.artifactType, fileName: artifact.fileName, sessionName, diff --git a/packages/daemon/src/sessions/materialized-path-registry.ts b/packages/daemon/src/sessions/materialized-path-registry.ts index 1374a31a317..78e2f240686 100644 --- a/packages/daemon/src/sessions/materialized-path-registry.ts +++ b/packages/daemon/src/sessions/materialized-path-registry.ts @@ -25,6 +25,7 @@ type RetainedEntry = { installablePath: string; archivePath?: string; tenantId?: string; + leaseId?: string; sessionName?: string; expiresAt: number; timer: ReturnType; @@ -58,6 +59,7 @@ export async function retainMaterializedPaths(params: { installablePath: string; archivePath?: string; tenantId?: string; + leaseId?: string; sessionName?: string; ttlMs?: number; }): Promise { @@ -81,6 +83,7 @@ export async function retainMaterializedPaths(params: { installablePath: retainedInstallablePath, archivePath: retainedArchivePath, tenantId: params.tenantId, + leaseId: params.leaseId, sessionName: params.sessionName, expiresAt, timer, @@ -117,6 +120,7 @@ export function resolveMaterializedPathRetentionMs( export async function cleanupRetainedMaterializedPaths( materializationId: string, tenantId?: string, + leaseId?: string, ): Promise { const entry = requireTenantOwnedEntry( retainedPaths(), @@ -124,6 +128,9 @@ export async function cleanupRetainedMaterializedPaths( tenantId, MATERIALIZED_PATHS_RESOURCE, ); + if (entry.leaseId !== leaseId) { + throw new AppError('UNAUTHORIZED', 'Materialized paths belong to a different lease'); + } await removeRetainedEntry(materializationId, entry); } From 11218ff5839c475ddb245d8fe96e72be7371d4e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 17:19:12 +0100 Subject: [PATCH 02/35] fix: preserve retained recording ownership checks --- .../daemon/src/resources/artifact-tracking.ts | 4 +-- .../resources/provider-session-ownership.ts | 6 ++-- .../leased-recording-retention.test.ts | 35 ++++++++++--------- .../daemon/src/sessions/handlers/lease.ts | 5 +++ 4 files changed, 30 insertions(+), 20 deletions(-) diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index b2295ce8431..453a36372fd 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -84,8 +84,8 @@ const artifactTracking = (): ArtifactTrackingState => } for (const entry of state.uploads.values()) { clearTimeout(entry.timer); - entry.releaseReservation?.(); removeBestEffort(entry.tempDir); + entry.releaseReservation?.(); } }, ); @@ -577,6 +577,6 @@ export function cleanupUploadedArtifact(uploadId: string): void { if (!entry) return; clearTimeout(entry.timer); pendingUploads().delete(uploadId); - entry.releaseReservation?.(); fs.rmSync(entry.tempDir, { recursive: true, force: true }); + entry.releaseReservation?.(); } diff --git a/packages/daemon/src/resources/provider-session-ownership.ts b/packages/daemon/src/resources/provider-session-ownership.ts index bd3fc58f84b..9fcdbe433ff 100644 --- a/packages/daemon/src/resources/provider-session-ownership.ts +++ b/packages/daemon/src/resources/provider-session-ownership.ts @@ -93,10 +93,12 @@ export class ProviderSessionOwnershipRegistry { const provider = params.provider?.trim(); const providerSessionId = params.providerSessionId?.trim(); const tenantId = params.tenantId?.trim(); - if (!provider || !providerSessionId || !tenantId || !params.runId) return undefined; + if (!provider || !providerSessionId || !tenantId) return undefined; this.prune(); const record = this.records.get(this.key(provider, providerSessionId)); - if (!record || record.tenantId !== tenantId || record.runId !== params.runId) return undefined; + if (!record || record.tenantId !== tenantId || (params.runId && record.runId !== params.runId)) { + return undefined; + } return { ...record }; } diff --git a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts index 5a24b5ff78a..24cfe9a529b 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts @@ -12,7 +12,7 @@ import { import { createDurableResourceEnvelope } from '@agent-device/capture-kit'; import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; import { resolveScreenRecordingStopRecovery } from '@agent-device/capture-kit/screen-recording-stop-recovery'; -import { buildRemoteTempArtifactPath } from '@agent-device/contracts/daemon-http'; +import { buildRemoteTempArtifactPath, DAEMON_HTTP_LEASE_HEADER } from '@agent-device/contracts/daemon-http'; import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime'; import type { ScreenRecordingCompletion, @@ -51,11 +51,12 @@ vi.mock('../../resources/artifact-tracking.ts', async (importOriginal) => { }); const TENANT = 'tenant-a'; +const LEASE_ID = 'lease-1'; const ADDRESS = `${TENANT}:checkout-flow`; const createdPaths: string[] = []; afterEach(async () => { - for (const { id } of await listDownloadableArtifacts(TENANT, process.env)) { + for (const { id } of await listDownloadableArtifacts(TENANT, process.env, LEASE_ID)) { cleanupDownloadableArtifact(id); } for (const filePath of createdPaths.splice(0)) fs.rmSync(filePath, { force: true }); @@ -161,7 +162,7 @@ test('a leased session teardown keeps the remote recording export downloadable b await teardown(sessionStore); - const artifacts = await listDownloadableArtifacts(TENANT, process.env); + const artifacts = await listDownloadableArtifacts(TENANT, process.env, LEASE_ID); expect(artifacts).toEqual([ expect.objectContaining({ artifactType: 'screen-recording', @@ -183,7 +184,7 @@ test('a retained recording is deleted once its tenant downloads it', async (t) = const recordingExport = remoteRecordingExport(); publishRecordingSession(sessionStore, recordingExport); await teardown(sessionStore); - const [video] = await listDownloadableArtifacts(TENANT, process.env); + const [video] = await listDownloadableArtifacts(TENANT, process.env, LEASE_ID); const server = http.createServer((req, res) => { tryHandleDownloadableArtifactHttpRoute({ req, @@ -194,12 +195,14 @@ test('a retained recording is deleted once its tenant downloads it', async (t) = }); const port = await listenOnLoopback(server); try { - const response = await fetch(`http://127.0.0.1:${port}/artifacts/${video!.id}`); + const response = await fetch(`http://127.0.0.1:${port}/artifacts/${video!.id}`, { + headers: { [DAEMON_HTTP_LEASE_HEADER]: LEASE_ID }, + }); expect(await response.text()).toBe('video'); await vi.waitFor(() => expect(fs.existsSync(recordingExport.outPath)).toBe(false)); expect( - (await listDownloadableArtifacts(TENANT, process.env)).map((a) => a.artifactType), + (await listDownloadableArtifacts(TENANT, process.env, LEASE_ID)).map((a) => a.artifactType), ).toEqual(['screen-recording-telemetry']); } finally { await closeLoopbackServer(server); @@ -212,11 +215,11 @@ test('a retained recording nobody downloads is deleted when it expires', async ( const recordingExport = remoteRecordingExport(); publishRecordingSession(sessionStore, recordingExport); await teardown(sessionStore); - expect(await listDownloadableArtifacts(TENANT, process.env)).toHaveLength(2); + expect(await listDownloadableArtifacts(TENANT, process.env, LEASE_ID)).toHaveLength(2); await vi.advanceTimersByTimeAsync(15 * 60 * 1000); - expect(await listDownloadableArtifacts(TENANT, process.env)).toEqual([]); + expect(await listDownloadableArtifacts(TENANT, process.env, LEASE_ID)).toEqual([]); expect(fs.existsSync(recordingExport.outPath)).toBe(false); expect(fs.existsSync(recordingExport.telemetryPath)).toBe(false); }); @@ -230,7 +233,7 @@ test('a failed teardown finish runs forced cleanup and keeps nothing for downloa await expect(teardown(sessionStore)).rejects.toThrow(/recording: .*failed to stop recording/); expect(forceCleanup).toHaveBeenCalledOnce(); - expect(await listDownloadableArtifacts(TENANT, process.env)).toEqual([]); + expect(await listDownloadableArtifacts(TENANT, process.env, LEASE_ID)).toEqual([]); }); test('a leased teardown that cannot register the export deletes it instead of leaking it', async () => { @@ -241,7 +244,7 @@ test('a leased teardown that cannot register the export deletes it instead of le await teardown(sessionStore); - expect(await listDownloadableArtifacts(TENANT, process.env)).toEqual([]); + expect(await listDownloadableArtifacts(TENANT, process.env, LEASE_ID)).toEqual([]); expect(fs.existsSync(recordingExport.outPath)).toBe(false); expect(fs.existsSync(recordingExport.telemetryPath)).toBe(false); }); @@ -250,7 +253,7 @@ test('a record stop replay after a leased teardown serves the artifacts teardown const sessionStore = makeSessionStore('agent-device-leased-recording-replay-'); publishRecordingSession(sessionStore, remoteRecordingExport()); await teardown(sessionStore); - const retained = await listDownloadableArtifacts(TENANT, process.env); + const retained = await listDownloadableArtifacts(TENANT, process.env, LEASE_ID); const recovery = resolveScreenRecordingStopRecovery({ sessionName: ADDRESS, @@ -265,7 +268,7 @@ test('a record stop replay after a leased teardown serves the artifacts teardown command: 'record', positionals: ['stop'], flags: {}, - meta: { tenantId: TENANT }, + meta: { tenantId: TENANT, leaseId: LEASE_ID }, }, buildRecordingStopResponse(recovery.completion), trackDownloadableArtifact, @@ -274,7 +277,7 @@ test('a record stop replay after a leased teardown serves the artifacts teardown expect(replayed.ok && replayed.data?.artifacts?.map((a) => a.artifactId)).toEqual( retained.map((a) => a.id), ); - expect(await listDownloadableArtifacts(TENANT, process.env)).toEqual([ + expect(await listDownloadableArtifacts(TENANT, process.env, LEASE_ID)).toEqual([ expect.objectContaining({ id: retained[0]!.id, sessionName: 'checkout-flow' }), expect.objectContaining({ id: retained[1]!.id, sessionName: 'checkout-flow' }), ]); @@ -289,7 +292,7 @@ test.each([undefined, '/client/local-copy.mp4'])( await teardown(sessionStore); - expect(await listDownloadableArtifacts(TENANT, process.env)).toEqual([]); + expect(await listDownloadableArtifacts(TENANT, process.env, LEASE_ID)).toEqual([]); expect(fs.readFileSync(recordingExport.outPath, 'utf8')).toBe('video'); }, ); @@ -301,7 +304,7 @@ test('an unleased session teardown registers nothing for a remote export', async await teardown(sessionStore); - expect(await listDownloadableArtifacts(TENANT, process.env)).toEqual([]); + expect(await listDownloadableArtifacts(TENANT, process.env, LEASE_ID)).toEqual([]); expect(await listDownloadableArtifacts(undefined, process.env)).toEqual([]); expect(fs.existsSync(recordingExport.outPath)).toBe(true); }); @@ -330,7 +333,7 @@ test.each([undefined, '/client/downloads/checkout.mp4'])( await teardown(harness.sessionStore); - const artifacts = await listDownloadableArtifacts(TENANT, process.env); + const artifacts = await listDownloadableArtifacts(TENANT, process.env, LEASE_ID); expect(artifacts).toEqual([ expect.objectContaining({ artifactType: 'screen-recording', diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index de26a6905c6..e1c4e4531fd 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -603,6 +603,11 @@ function resolveProviderSession( providerSessionId: string | undefined, ): ReturnType { if (!providerSessionId) return undefined; + if (!leaseScope.runId) { + throw new AppError('UNAUTHORIZED', 'Provider session requires the request run', { + reason: LEASE_HANDLER_REASONS.providerSessionNotOwned.reason, + }); + } const providerSession = leaseRegistry.resolveProviderSession({ provider: leaseScope.leaseProvider, providerSessionId, From 5ed6cfa3d2459cfc34105e90325034051095ddde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 17:30:20 +0100 Subject: [PATCH 03/35] fix: admit upload and artifact reads through lease ownership --- packages/contracts/src/daemon-http.ts | 7 + .../src/resources/artifact-tracking.test.ts | 52 ++++--- .../daemon/src/resources/lease-registry.ts | 36 +++++ .../resources/provider-session-ownership.ts | 9 +- .../src/server/downloadable-artifact-http.ts | 44 ++++-- .../http-server-install-retention.test.ts | 78 +++++++++++ .../daemon/src/server/http/http-server.ts | 2 + .../daemon/src/server/resumable-upload.ts | 19 ++- packages/daemon/src/server/upload-http.ts | 129 ++++++++++++------ .../leased-recording-retention.test.ts | 35 ++++- .../__tests__/lease-artifacts.test.ts | 26 ++-- .../daemon/src/sessions/handlers/lease.ts | 22 ++- .../handlers/session-app-source-deployment.ts | 14 +- packages/remote/src/artifact-download.ts | 2 + 14 files changed, 374 insertions(+), 101 deletions(-) diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 9c849d8ccfd..981a03caad8 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -13,6 +13,7 @@ export const DAEMON_HTTP_TENANT_HEADER = 'x-agent-device-tenant'; // as RPC calls name it in their body. Neither the daemon nor the proxy reads it; it lets a gateway // in front of many daemons route those requests to the one holding the lease. export const DAEMON_HTTP_LEASE_HEADER = 'x-agent-device-lease-id'; +export const DAEMON_HTTP_RUN_HEADER = 'x-agent-device-run-id'; export const DAEMON_HTTP_NETWORK_ACCESS_HEADER = 'x-agent-device-network-access'; export const DAEMON_HTTP_PUBLIC_NETWORK_ACCESS = 'public-only'; @@ -120,6 +121,12 @@ export function buildDaemonHttpLeaseHeaders(leaseId: string | undefined): Record return { [DAEMON_HTTP_LEASE_HEADER]: normalizedLeaseId }; } +export function buildDaemonHttpRunHeaders(runId: string | undefined): Record { + const normalizedRunId = runId?.trim(); + if (!normalizedRunId) return {}; + return { [DAEMON_HTTP_RUN_HEADER]: normalizedRunId }; +} + // See docs/adr/0006-daemon-rpc-protocol-version.md before changing this value. // Enforced, not just documented: `test/wire-compat/` digests the declarations // that cross this boundary and fails when one changes shape without a bump or diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index 3a95b874b03..d76866f6940 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -590,16 +590,20 @@ test('uploads stay bound to their producing lease and release capacity on cleanu fs.writeFileSync(artifactPath, 'payload'); const releaseReservation = vi.fn(); const runtime = createRuntimeStateHandle(); - const id = runtime.run(() => trackUploadedArtifact({ - artifactPath, - tempDir: root, - tenantId: 'tenant-a', - leaseId: 'lease-a', - releaseReservation, - })); + const id = runtime.run(() => + trackUploadedArtifact({ + artifactPath, + tempDir: root, + tenantId: 'tenant-a', + leaseId: 'lease-a', + releaseReservation, + }), + ); for (const leaseId of [undefined, 'lease-b']) { - expect(() => runtime.run(() => prepareUploadedArtifact(id, 'tenant-a', leaseId))).toThrow(/different lease/); + expect(() => runtime.run(() => prepareUploadedArtifact(id, 'tenant-a', leaseId))).toThrow( + /different lease/, + ); } expect(releaseReservation).not.toHaveBeenCalled(); expect(runtime.run(() => prepareUploadedArtifact(id, 'tenant-a', 'lease-a'))).toBe(artifactPath); @@ -613,17 +617,29 @@ test('a retained downloadable artifact requires its producing lease', async () = const artifactPath = path.join(root, 'recording.mp4'); fs.writeFileSync(artifactPath, 'video'); const runtime = createRuntimeStateHandle(); - const id = runtime.run(() => trackDownloadableArtifact({ - artifactPath, - tenantId: 'tenant-a', - leaseId: 'lease-a', - artifactType: 'screen-recording', - })); + const id = runtime.run(() => + trackDownloadableArtifact({ + artifactPath, + tenantId: 'tenant-a', + leaseId: 'lease-a', + artifactType: 'screen-recording', + }), + ); try { - expect(await runtime.run(() => listDownloadableArtifacts('tenant-a', process.env, 'lease-b'))).toEqual([]); - expect(await runtime.run(() => listDownloadableArtifacts('tenant-a', process.env, 'lease-a'))).toHaveLength(1); - await expect(runtime.run(() => openDownloadableArtifact(id, 'tenant-a', process.env, undefined, 'lease-b'))).rejects.toThrow(/different lease/); - const opened = await runtime.run(() => openDownloadableArtifact(id, 'tenant-a', process.env, undefined, 'lease-a')); + expect( + await runtime.run(() => listDownloadableArtifacts('tenant-a', process.env, 'lease-b')), + ).toEqual([]); + expect( + await runtime.run(() => listDownloadableArtifacts('tenant-a', process.env, 'lease-a')), + ).toHaveLength(1); + await expect( + runtime.run(() => + openDownloadableArtifact(id, 'tenant-a', process.env, undefined, 'lease-b'), + ), + ).rejects.toThrow(/different lease/); + const opened = await runtime.run(() => + openDownloadableArtifact(id, 'tenant-a', process.env, undefined, 'lease-a'), + ); expect(await buffer(opened.stream)).toEqual(Buffer.from('video')); opened.release(); } finally { diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index 6c34df20a0c..7631aa05ad0 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -53,6 +53,14 @@ const LEASE_REGISTRY_REASONS = { type OwnedHumanControlHold = { hold: HumanControlHold; ownerLeaseId?: string }; export class LeaseRegistry { + private readonly artifactLeaseOwners = new Map< + string, + { + tenantId: string; + runId: string; + retainedUntil?: number; + } + >(); private readonly holdsByDevice = new Map>(); private readonly mutations = new DeviceMutationDrain(); private readonly inFlightWork = new LeaseInFlightWorkRegistry(); @@ -187,6 +195,10 @@ export class LeaseRegistry { private issueLease(lease: DeviceLease): void { this.issuedLeaseIds.add(lease.leaseId); this.leases.set(lease.leaseId, lease); + this.artifactLeaseOwners.set(lease.leaseId, { + tenantId: lease.tenantId, + runId: lease.runId, + }); this.providerSessionOwnership.recordLease(lease); this.bindLease(lease); this.reportProviderLeases(lease); @@ -332,6 +344,23 @@ export class LeaseRegistry { assertLeaseScopeMatch(lease, request); } + /** Retained artifacts can be read by their original owner after lease release. */ + assertArtifactLeaseReadAdmission(request: HeartbeatLeaseRequest): void { + const leaseId = normalizeRequiredLeaseId(request.leaseId); + this.cleanupExpiredLeases(); + const owner = this.artifactLeaseOwners.get(leaseId); + if ( + !owner || + !request.tenantId || + !request.runId || + owner.tenantId !== request.tenantId || + owner.runId !== request.runId || + (owner.retainedUntil !== undefined && owner.retainedUntil <= this.now()) + ) { + throw new AppError('UNAUTHORIZED', 'Lease is not owned by the artifact request'); + } + } + /** Whether this daemon ever allocated `tenantId` a `macos-app` lease, released or not. */ hasHeldMacOsAppLease(tenantId: string): boolean { return this.macOsAppTenantIds.has(tenantId); @@ -722,6 +751,13 @@ export class LeaseRegistry { } private unbindLease(lease: DeviceLease, releasedAt = this.now()): void { + const artifactOwner = this.artifactLeaseOwners.get(lease.leaseId); + if (artifactOwner) { + this.artifactLeaseOwners.set(lease.leaseId, { + ...artifactOwner, + retainedUntil: releasedAt + 15 * 60_000, + }); + } this.hostTtlMsByLeaseId.delete(lease.leaseId); this.runBindings.delete(leaseRunBindingKey(lease)); const deviceBindingKey = leaseDeviceBindingKey(lease); diff --git a/packages/daemon/src/resources/provider-session-ownership.ts b/packages/daemon/src/resources/provider-session-ownership.ts index 9fcdbe433ff..ae2f9b0e73a 100644 --- a/packages/daemon/src/resources/provider-session-ownership.ts +++ b/packages/daemon/src/resources/provider-session-ownership.ts @@ -96,7 +96,11 @@ export class ProviderSessionOwnershipRegistry { if (!provider || !providerSessionId || !tenantId) return undefined; this.prune(); const record = this.records.get(this.key(provider, providerSessionId)); - if (!record || record.tenantId !== tenantId || (params.runId && record.runId !== params.runId)) { + if ( + !record || + record.tenantId !== tenantId || + (params.runId && record.runId !== params.runId) + ) { return undefined; } return { ...record }; @@ -126,7 +130,8 @@ export class ProviderSessionOwnershipRegistry { } } for (const [key, record] of this.leases) { - if (record.retainedUntil !== undefined && record.retainedUntil <= now) this.leases.delete(key); + if (record.retainedUntil !== undefined && record.retainedUntil <= now) + this.leases.delete(key); } } diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index b6b5c26693c..eb42f275514 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -12,7 +12,11 @@ import { import { failStreamedHttpResponse, sendRestJsonError } from './http-errors.ts'; import { decodeUriSegment } from './http-request-target.ts'; import { responseDisconnectSignal } from './http/response-disconnect-signal.ts'; -import { DAEMON_HTTP_LEASE_HEADER } from '@agent-device/contracts/daemon-http'; +import { + DAEMON_HTTP_LEASE_HEADER, + DAEMON_HTTP_RUN_HEADER, +} from '@agent-device/contracts/daemon-http'; +import type { LeaseRegistry } from '../resources/lease-registry.ts'; const ARTIFACT_DOWNLOAD_REASONS = { // The artifact stream ended at a different size than the daemon recorded; `details` gives both @@ -37,14 +41,16 @@ export function tryHandleDownloadableArtifactHttpRoute(params: { retainArtifacts?: boolean; /** The runtime host's environment, handed to the directory-archive spawn. */ hostEnv: NodeJS.ProcessEnv; + leaseRegistry?: LeaseRegistry; }): boolean { - const { req, res, authorize, retainArtifacts, hostEnv } = params; + const { req, res, authorize, retainArtifacts, hostEnv, leaseRegistry } = params; const route = resolveDownloadableArtifactHttpRoute(req); if (route === null) return false; void handleDownloadableArtifactHttpRoute(route, req, res, authorize, { retainArtifacts, hostEnv, + leaseRegistry, }); return true; } @@ -54,7 +60,7 @@ async function handleDownloadableArtifactHttpRoute( req: http.IncomingMessage, res: http.ServerResponse, authorize: DownloadableArtifactHttpAuthorizer, - options: { retainArtifacts?: boolean; hostEnv: NodeJS.ProcessEnv }, + options: { retainArtifacts?: boolean; hostEnv: NodeJS.ProcessEnv; leaseRegistry?: LeaseRegistry }, ): Promise { switch (route.kind) { case 'inventory': @@ -83,7 +89,7 @@ async function handleArtifactDownload( req: http.IncomingMessage, res: http.ServerResponse, authorize: DownloadableArtifactHttpAuthorizer, - options: { retainArtifacts?: boolean; hostEnv: NodeJS.ProcessEnv }, + options: { retainArtifacts?: boolean; hostEnv: NodeJS.ProcessEnv; leaseRegistry?: LeaseRegistry }, ): Promise { if (!artifactId) { res.statusCode = 400; @@ -102,13 +108,14 @@ async function handleArtifactDownload( }, }); if (!auth) return; + const leaseId = admitArtifactLease(req, auth.tenantId, options.leaseRegistry); const artifact = await openDownloadableArtifact( artifactId, auth.tenantId, options.hostEnv, signal, - readLeaseId(req), + leaseId, ); const { stream } = artifact; const closed = finished(stream, { cleanup: true }).catch(() => {}); @@ -164,7 +171,7 @@ async function handleArtifactInventory( req: http.IncomingMessage, res: http.ServerResponse, authorize: DownloadableArtifactHttpAuthorizer, - options: { hostEnv: NodeJS.ProcessEnv }, + options: { hostEnv: NodeJS.ProcessEnv; leaseRegistry?: LeaseRegistry }, ): Promise { try { const auth = await authorize({ @@ -176,12 +183,13 @@ async function handleArtifactInventory( }, }); if (!auth) return; + const leaseId = admitArtifactLease(req, auth.tenantId, options.leaseRegistry); res.statusCode = 200; res.setHeader('content-type', 'application/json'); res.end( JSON.stringify({ - artifacts: await listDownloadableArtifacts(auth.tenantId, options.hostEnv, readLeaseId(req)), + artifacts: await listDownloadableArtifacts(auth.tenantId, options.hostEnv, leaseId), }), ); } catch (error) { @@ -189,9 +197,27 @@ async function handleArtifactInventory( } } -function readLeaseId(req: http.IncomingMessage): string | undefined { +function admitArtifactLease( + req: http.IncomingMessage, + tenantId: string | undefined, + leaseRegistry: LeaseRegistry | undefined, +): string | undefined { const value = req.headers[DAEMON_HTTP_LEASE_HEADER]; - return typeof value === 'string' && value.trim() ? value.trim() : undefined; + if (value === undefined) return undefined; + const runId = req.headers[DAEMON_HTTP_RUN_HEADER]; + if ( + typeof value !== 'string' || + !value.trim() || + typeof runId !== 'string' || + !runId.trim() || + !tenantId || + !leaseRegistry + ) { + throw new AppError('UNAUTHORIZED', 'Artifact lease requires an admitted tenant and run'); + } + const leaseId = value.trim(); + leaseRegistry.assertArtifactLeaseReadAdmission({ leaseId, tenantId, runId: runId.trim() }); + return leaseId; } function readArtifactId(pathname: string): string { diff --git a/packages/daemon/src/server/http/http-server-install-retention.test.ts b/packages/daemon/src/server/http/http-server-install-retention.test.ts index d08bd992db4..0567a4a8a38 100644 --- a/packages/daemon/src/server/http/http-server-install-retention.test.ts +++ b/packages/daemon/src/server/http/http-server-install-retention.test.ts @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import { createHash, randomUUID } from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { test } from 'vitest'; @@ -11,6 +12,7 @@ import { } from '@agent-device/test-kit'; import { daemonPlatformServicesFixture } from '../../__tests__/support/platform-services-fixture.ts'; import { SessionStore } from '../../core/session-store.ts'; +import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { cleanupUploadedArtifact, prepareUploadedArtifact, @@ -112,3 +114,79 @@ test('HTTP install rejection leaves an uploaded artifact available', async (t) = await closeLoopbackServer(server); } }); + +test('HTTP leased resumable upload remains readable by install dispatch', async (t) => { + if (await skipWhenLoopbackUnavailable(t, 'leased resumable upload')) return; + const host = createLiveTestHostEnvironment(); + const env = { ...host.env }; + delete env.AGENT_DEVICE_HTTP_AUTH_HOOK; + const leaseRegistry = new LeaseRegistry(); + const lease = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-a' }); + let uploadedId: string | undefined; + const server = await createDaemonHttpServer({ + token: 'test-token', + ...host, + env, + leaseRegistry, + handleRequest: async (req) => { + assert.equal(req.command, 'install'); + const artifactPath = prepareUploadedArtifact( + uploadedId!, + req.meta?.tenantId, + req.meta?.leaseId, + ); + assert.equal(fs.readFileSync(artifactPath, 'utf8'), 'leased-apk'); + return { ok: true, data: { installed: true } }; + }, + }); + try { + const port = await listenOnLoopback(server); + const base = `http://127.0.0.1:${port}`; + const headers = { + authorization: 'Bearer test-token', + 'x-agent-device-tenant': 'tenant-a', + 'x-agent-device-lease-id': lease.leaseId, + }; + const preflight = await fetch(`${base}/upload/preflight`, { + method: 'POST', + headers: { ...headers, 'content-type': 'application/json' }, + body: JSON.stringify({ + uploadAttemptId: randomUUID(), + sha256: createHash('sha256').update('leased-apk').digest('hex'), + fileName: 'app.apk', + sizeBytes: Buffer.byteLength('leased-apk'), + artifactType: 'file', + }), + }); + assert.equal(preflight.status, 200); + const ticket = (await preflight.json()) as { uploadId: string; upload: { url: string } }; + const chunk = await fetch(ticket.upload.url, { + method: 'PUT', + headers, + body: 'leased-apk', + }); + assert.equal(chunk.status, 200); + const finalize = await fetch(`${base}/upload/finalize`, { + method: 'POST', + headers: { ...headers, 'content-type': 'application/json' }, + body: JSON.stringify({ uploadId: ticket.uploadId }), + }); + assert.equal(finalize.status, 200); + uploadedId = ((await finalize.json()) as { uploadId: string }).uploadId; + const install = await callRpc(port, 'agent_device.command', { + command: 'install', + positionals: ['app.apk'], + meta: { + tenantId: 'tenant-a', + runId: 'run-a', + leaseId: lease.leaseId, + uploadedArtifactId: uploadedId, + }, + }); + assert.equal(install.status, 200); + assert.equal(((await install.json()) as { result?: { ok: boolean } }).result?.ok, true); + } finally { + if (uploadedId) cleanupUploadedArtifact(uploadedId); + await closeLoopbackServer(server); + } +}); diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 09e51e0f0ff..82cc6551f6e 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -199,6 +199,7 @@ export async function createDaemonHttpServer(options: { tryHandleUploadHttpRoute({ req, res, + leaseRegistry: options.leaseRegistry, token: resolveToken({}, req.headers), origin: publicOrigin ?? ingressUrl.origin, authorize: async (request) => @@ -220,6 +221,7 @@ export async function createDaemonHttpServer(options: { tryHandleDownloadableArtifactHttpRoute({ req, res, + leaseRegistry: options.leaseRegistry, retainArtifacts, hostEnv: environment, authorize: async (request) => diff --git a/packages/daemon/src/server/resumable-upload.ts b/packages/daemon/src/server/resumable-upload.ts index 2ee91d1b54f..724310ad3d5 100644 --- a/packages/daemon/src/server/resumable-upload.ts +++ b/packages/daemon/src/server/resumable-upload.ts @@ -71,6 +71,7 @@ export type BeginResumableUploadOptions = { platform?: string; contentType?: string; tenantId?: string; + leaseId?: string; }; type ResumableUploadEntry = { @@ -84,6 +85,7 @@ type ResumableUploadEntry = { artifactType: 'file' | 'app-bundle'; platform?: string; tenantId?: string; + leaseId?: string; timer?: ReturnType; generation: number; tail: Promise; @@ -178,13 +180,14 @@ export async function receiveResumableUploadChunk(params: { uploadId: string; req: IncomingMessage; tenantId?: string; + leaseId?: string; signal?: AbortSignal; /** The request owner's commit gate; the chunk offset commits through it. */ commit?: (work: () => T) => T; onAcceptedBytes?: (bytes: number) => void; onBodyComplete?: () => void; }): Promise<{ complete: boolean; offset: number }> { - const entry = requireResumableUpload(params.uploadId, params.tenantId); + const entry = requireResumableUpload(params.uploadId, params.tenantId, params.leaseId); // The ticket's own expiry reaches the receive through this controller, never by // destroying the request: the request owner ends the exchange in response order. const ticketExpiry = new AbortController(); @@ -234,8 +237,9 @@ export async function finalizeResumableUpload( uploadId: string, tenantId?: string, ingress?: FinalizeUploadIngressLink, + leaseId?: string, ): Promise<{ artifactPath: string; tempDir: string }> { - const entry = requireResumableUpload(uploadId, tenantId); + const entry = requireResumableUpload(uploadId, tenantId, leaseId); const signal = ingress?.signal; // The owner's typed expiry, including a recorded deadline whose timer has not run yet. const ensureActive = () => { @@ -309,6 +313,7 @@ function createResumableUploadEntry( artifactType: options.artifactType, platform: options.platform, tenantId: options.tenantId, + leaseId: options.leaseId, generation: 0, tail: Promise.resolve(), closed: false, @@ -373,7 +378,7 @@ async function runExclusive( throwIfIngressAborted(signal); }, ); - if (entry.closed) requireResumableUpload(entry.id, entry.tenantId); + if (entry.closed) requireResumableUpload(entry.id, entry.tenantId, entry.leaseId); // The close check above runs first, so a close/cancel race keeps the close side's // typed expiry error, and the entry's ownership is untouched either way (#4441). throwIfIngressAborted(signal); @@ -454,13 +459,18 @@ function closeEntry(entry: ResumableUploadEntry): void { function requireResumableUpload( uploadId: string, tenantId: string | undefined, + leaseId?: string, ): ResumableUploadEntry { - return requireTenantOwnedEntry( + const entry = requireTenantOwnedEntry( RESUMABLE_UPLOADS_BY_ID(), uploadId, tenantId, RESUMABLE_UPLOAD_RESOURCE, ); + if (entry.leaseId !== leaseId) { + throw new AppError('UNAUTHORIZED', 'Upload belongs to a different lease'); + } + return entry; } function validateResumableUploadOptions(options: BeginResumableUploadOptions): void { @@ -480,6 +490,7 @@ function validateResumableUploadOptions(options: BeginResumableUploadOptions): v function buildResumableUploadKey(options: BeginResumableUploadOptions): string { return [ options.tenantId ?? '', + options.leaseId ?? '', options.uploadAttemptId, options.sha256.toLowerCase(), String(options.sizeBytes), diff --git a/packages/daemon/src/server/upload-http.ts b/packages/daemon/src/server/upload-http.ts index 666161a39a3..5da3959bbfd 100644 --- a/packages/daemon/src/server/upload-http.ts +++ b/packages/daemon/src/server/upload-http.ts @@ -13,6 +13,8 @@ import { receiveUpload } from './upload.ts'; import { sendRestJsonError } from './http-errors.ts'; import { beginUploadTransferIngress, type UploadTransferIngress } from './upload-ingress.ts'; import { readNodeHttpRequestBody } from '@agent-device/host-kit/transport'; +import { DAEMON_HTTP_LEASE_HEADER } from '@agent-device/contracts/daemon-http'; +import type { LeaseRegistry } from '../resources/lease-registry.ts'; const DIRECT_UPLOAD_PATH_PREFIX = '/upload/direct/'; @@ -53,12 +55,13 @@ export function tryHandleUploadHttpRoute(params: { authorize: AuxiliaryHttpAuthorizer; token: string; origin: string; + leaseRegistry?: LeaseRegistry; }): boolean { - const { req, res, authorize, token, origin } = params; + const { req, res, authorize, token, origin, leaseRegistry } = params; const route = resolveUploadHttpRoute(req); if (route === null) return false; - void handleUploadHttpRoute(route, req, res, authorize, token, origin); + void handleUploadHttpRoute(route, req, res, authorize, token, origin, leaseRegistry); return true; } @@ -69,19 +72,20 @@ async function handleUploadHttpRoute( authorize: AuxiliaryHttpAuthorizer, token: string, origin: string, + leaseRegistry?: LeaseRegistry, ): Promise { switch (route.kind) { case 'preflight': - await handleUploadPreflight(req, res, authorize, token, origin); + await handleUploadPreflight(req, res, authorize, token, origin, leaseRegistry); return; case 'direct': - await handleResumableUpload(route.uploadId, req, res, authorize); + await handleResumableUpload(route.uploadId, req, res, authorize, leaseRegistry); return; case 'finalize': - await handleUploadFinalize(req, res, authorize); + await handleUploadFinalize(req, res, authorize, leaseRegistry); return; case 'upload': - await handleUpload(req, res, authorize); + await handleUpload(req, res, authorize, leaseRegistry); return; } } @@ -109,14 +113,21 @@ async function runUploadRoute( req: http.IncomingMessage, res: http.ServerResponse, authorize: AuxiliaryHttpAuthorizer, + leaseRegistry: LeaseRegistry | undefined, positionals: string[], - handle: (auth: { tenantId?: string }, ingress: UploadTransferIngress) => Promise, + handle: ( + auth: { tenantId?: string; leaseId?: string }, + ingress: UploadTransferIngress, + ) => Promise, ): Promise { const ingress = beginUploadTransferIngress({ req, res }); try { const auth = await authorizeUpload(authorize, req, res, ingress, positionals); if (!auth) return; - await handle(auth, ingress); + await handle( + { ...auth, leaseId: admitUploadLease(req, auth.tenantId, leaseRegistry) }, + ingress, + ); } catch (error) { answerUploadFailure(res, error, ingress.commit); } finally { @@ -124,6 +135,24 @@ async function runUploadRoute( } } +function admitUploadLease( + req: http.IncomingMessage, + tenantId: string | undefined, + leaseRegistry: LeaseRegistry | undefined, +): string | undefined { + const header = req.headers[DAEMON_HTTP_LEASE_HEADER]; + if (header === undefined) return undefined; + if (typeof header !== 'string' || !header.trim() || !tenantId || !leaseRegistry) { + throw new AppError( + 'UNAUTHORIZED', + 'Upload lease requires an admitted tenant and lease registry', + ); + } + const leaseId = header.trim(); + leaseRegistry.assertLeaseReadAdmission({ leaseId, tenantId }); + return leaseId; +} + /** The upload command and positionals the auth hook sees, under the ingress signal. */ async function authorizeUpload( authorize: AuxiliaryHttpAuthorizer, @@ -145,8 +174,9 @@ async function handleUpload( req: http.IncomingMessage, res: http.ServerResponse, authorize: AuxiliaryHttpAuthorizer, + leaseRegistry?: LeaseRegistry, ): Promise { - await runUploadRoute(req, res, authorize, [], async (auth, ingress) => { + await runUploadRoute(req, res, authorize, leaseRegistry, [], async (auth, ingress) => { sendUploadedArtifactResponse( res, await receiveUpload(req, { @@ -156,6 +186,7 @@ async function handleUpload( }), auth.tenantId, ingress.commit, + auth.leaseId, ); }); } @@ -166,8 +197,9 @@ async function handleUploadPreflight( authorize: AuxiliaryHttpAuthorizer, token: string, origin: string, + leaseRegistry?: LeaseRegistry, ): Promise { - await runUploadRoute(req, res, authorize, ['preflight'], async (auth, ingress) => { + await runUploadRoute(req, res, authorize, leaseRegistry, ['preflight'], async (auth, ingress) => { const body = await readRestJsonBody(req, 64 * 1024, ingress.onAcceptedBodyBytes); // The JSON body is fully received: inactivity stops here and the remaining work // observes only the aggregate (#4441). @@ -182,6 +214,7 @@ async function handleUploadPreflight( tokenHeaders: buildUploadTicketAuthHeaders(token), ...preflight, tenantId: auth.tenantId, + leaseId: auth.leaseId, }, (upload) => ingress.commit(() => sendJson(res, { ok: true, ...upload })), ); @@ -193,39 +226,49 @@ async function handleResumableUpload( req: http.IncomingMessage, res: http.ServerResponse, authorize: AuxiliaryHttpAuthorizer, + leaseRegistry?: LeaseRegistry, ): Promise { - await runUploadRoute(req, res, authorize, ['direct', uploadId], async (auth, ingress) => { - const result = await receiveResumableUploadChunk({ - uploadId, - req, - tenantId: auth.tenantId, - signal: ingress.signal, - commit: ingress.commit, - onAcceptedBytes: (bytes) => ingress.onAcceptedBodyBytes(bytes), - onBodyComplete: () => ingress.bodyComplete(), - }); - ingress.commit(() => { - if (result.complete) { - res.statusCode = 200; - res.end('ok'); - return; - } - res.statusCode = 308; - if (result.offset > 0) { - res.setHeader('range', `bytes=0-${result.offset - 1}`); - } - res.setHeader('x-upload-offset', String(result.offset)); - res.end(); - }); - }); + await runUploadRoute( + req, + res, + authorize, + leaseRegistry, + ['direct', uploadId], + async (auth, ingress) => { + const result = await receiveResumableUploadChunk({ + uploadId, + req, + tenantId: auth.tenantId, + leaseId: auth.leaseId, + signal: ingress.signal, + commit: ingress.commit, + onAcceptedBytes: (bytes) => ingress.onAcceptedBodyBytes(bytes), + onBodyComplete: () => ingress.bodyComplete(), + }); + ingress.commit(() => { + if (result.complete) { + res.statusCode = 200; + res.end('ok'); + return; + } + res.statusCode = 308; + if (result.offset > 0) { + res.setHeader('range', `bytes=0-${result.offset - 1}`); + } + res.setHeader('x-upload-offset', String(result.offset)); + res.end(); + }); + }, + ); } async function handleUploadFinalize( req: http.IncomingMessage, res: http.ServerResponse, authorize: AuxiliaryHttpAuthorizer, + leaseRegistry?: LeaseRegistry, ): Promise { - await runUploadRoute(req, res, authorize, ['finalize'], async (auth, ingress) => { + await runUploadRoute(req, res, authorize, leaseRegistry, ['finalize'], async (auth, ingress) => { const body = await readRestJsonBody(req, 64 * 1024, ingress.onAcceptedBodyBytes); // The JSON body is fully received: inactivity stops here, so the post-body hash, // extraction and registration observe only the aggregate (#4441). @@ -235,12 +278,18 @@ async function handleUploadFinalize( res, // The request's ingress signal is threaded through the serialized admission into // the post-body hash, the owned extraction stream and artifact materialization. - await finalizeResumableUpload(finalize.uploadId, auth.tenantId, { - signal: ingress.signal, - commit: ingress.commit, - }), + await finalizeResumableUpload( + finalize.uploadId, + auth.tenantId, + { + signal: ingress.signal, + commit: ingress.commit, + }, + auth.leaseId, + ), auth.tenantId, ingress.commit, + auth.leaseId, ); }); } @@ -261,6 +310,7 @@ function sendUploadedArtifactResponse( result: { artifactPath: string; tempDir: string }, tenantId: string | undefined, commit: (work: () => T) => T, + leaseId?: string, ): void { let registered = false; try { @@ -269,6 +319,7 @@ function sendUploadedArtifactResponse( artifactPath: result.artifactPath, tempDir: result.tempDir, tenantId, + leaseId, }); registered = true; sendJson(res, { ok: true, uploadId }); diff --git a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts index 24cfe9a529b..52f29b86c49 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts @@ -12,13 +12,18 @@ import { import { createDurableResourceEnvelope } from '@agent-device/capture-kit'; import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; import { resolveScreenRecordingStopRecovery } from '@agent-device/capture-kit/screen-recording-stop-recovery'; -import { buildRemoteTempArtifactPath, DAEMON_HTTP_LEASE_HEADER } from '@agent-device/contracts/daemon-http'; +import { + buildRemoteTempArtifactPath, + DAEMON_HTTP_LEASE_HEADER, + DAEMON_HTTP_RUN_HEADER, +} from '@agent-device/contracts/daemon-http'; import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime'; import type { ScreenRecordingCompletion, ScreenRecordingLiveHandle, } from '@agent-device/contracts/screen-recording-runtime'; import { deriveRecordingTelemetryPath } from '@agent-device/capture-kit/recording-telemetry'; +import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { makeIosSession } from '../../__tests__/support/session-factories.ts'; import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; import { platformResourceCleanupFixture } from '../../__tests__/support/platform-resource-cleanup-fixture.ts'; @@ -51,7 +56,7 @@ vi.mock('../../resources/artifact-tracking.ts', async (importOriginal) => { }); const TENANT = 'tenant-a'; -const LEASE_ID = 'lease-1'; +const LEASE_ID = 'abcdef0123456789abcdef0123456789'; const ADDRESS = `${TENANT}:checkout-flow`; const createdPaths: string[] = []; @@ -91,7 +96,7 @@ function publishRecordingSession( appBundleId: 'com.example.app', ...(options.leased === false ? {} - : { lease: { leaseId: 'lease-1', tenantId: TENANT, runId: 'run-1' } }), + : { lease: { leaseId: LEASE_ID, tenantId: TENANT, runId: 'run-1' } }), }); const completion: ScreenRecordingCompletion = { backend: 'simctl recordVideo', @@ -185,18 +190,38 @@ test('a retained recording is deleted once its tenant downloads it', async (t) = publishRecordingSession(sessionStore, recordingExport); await teardown(sessionStore); const [video] = await listDownloadableArtifacts(TENANT, process.env, LEASE_ID); + const leaseRegistry = new LeaseRegistry(); + const lease = leaseRegistry.allocateLease({ + leaseId: LEASE_ID, + tenantId: TENANT, + runId: 'run-1', + }); + leaseRegistry.releaseLease({ leaseId: lease.leaseId, tenantId: TENANT, runId: 'run-1' }); const server = http.createServer((req, res) => { tryHandleDownloadableArtifactHttpRoute({ req, res, authorize: async () => ({ tenantId: TENANT }), hostEnv: process.env, + leaseRegistry, }); }); const port = await listenOnLoopback(server); try { + for (const runId of [undefined, 'run-2']) { + for (const route of ['/artifacts', `/artifacts/${video!.id}`]) { + const denied = await fetch(`http://127.0.0.1:${port}${route}`, { + headers: { + [DAEMON_HTTP_LEASE_HEADER]: LEASE_ID, + ...(runId ? { [DAEMON_HTTP_RUN_HEADER]: runId } : {}), + }, + }); + expect(denied.status).not.toBe(200); + expect(fs.existsSync(recordingExport.outPath)).toBe(true); + } + } const response = await fetch(`http://127.0.0.1:${port}/artifacts/${video!.id}`, { - headers: { [DAEMON_HTTP_LEASE_HEADER]: LEASE_ID }, + headers: { [DAEMON_HTTP_LEASE_HEADER]: LEASE_ID, [DAEMON_HTTP_RUN_HEADER]: 'run-1' }, }); expect(await response.text()).toBe('video'); @@ -315,7 +340,7 @@ test.each([undefined, '/client/downloads/checkout.mp4'])( const harness = makeRecordRuntimeHarness('leased-remote-session-recording-', { sessionName: ADDRESS, }); - harness.session.lease = { leaseId: 'lease-1', tenantId: TENANT, runId: 'run-1' }; + harness.session.lease = { leaseId: LEASE_ID, tenantId: TENANT, runId: 'run-1' }; const start = harness.runtime.start.getMockImplementation()!; harness.runtime.start.mockImplementation(async (input) => { fs.writeFileSync(input.outputPath, 'session-owned-video'); diff --git a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts index 9ed033076c0..f55c1d857d1 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts @@ -92,11 +92,14 @@ test('artifacts admits a closed lease for its owner until retention expires', as { ...scope, runId: 'run-b' }, { leaseId: lease.leaseId }, ]) { - await assert.rejects(() => listArtifacts(world, denied), (error: unknown) => { - assert.ok(error instanceof AppError); - assert.equal(error.code, 'UNAUTHORIZED'); - return true; - }); + await assert.rejects( + () => listArtifacts(world, denied), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'UNAUTHORIZED'); + return true; + }, + ); } assert.deepEqual(world.providerCalls, []); @@ -112,9 +115,16 @@ test('artifacts admits a released cloud lease without a provider session ID', as const lease = await allocateLease(world, 'tenant-a', 'run-a'); await releaseLease(world, lease); - assert.equal((await listArtifacts(world, { - tenantId: 'tenant-a', runId: 'run-a', leaseId: lease.leaseId, - })).ok, true); + assert.equal( + ( + await listArtifacts(world, { + tenantId: 'tenant-a', + runId: 'run-a', + leaseId: lease.leaseId, + }) + ).ok, + true, + ); }); test('artifacts lists an owned active and recently released provider session', async () => { diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index e1c4e4531fd..d21134de740 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -30,10 +30,7 @@ import { normalizeRequiredLeaseId, } from '../../resources/lease-registry-scope.ts'; import type { SessionStore } from '../../core/session-store.ts'; -import { - isProxyLeaseScope, - resolveLeaseScope, -} from '../../core/lease-context.ts'; +import { isProxyLeaseScope, resolveLeaseScope } from '../../core/lease-context.ts'; import { isProviderInstanceEndedError, leaseDeviceKey, @@ -89,8 +86,6 @@ type LeaseHandlerArgs = { export async function handleLeaseCommands(args: LeaseHandlerArgs): Promise { const { req, - sessionName, - sessionStore, leaseRegistry, providerRuntimeIds, failedPlugins, @@ -568,12 +563,15 @@ async function listCloudArtifactsForRequest( } if (leaseScope.leaseId && !providerSessionId) { const activeLease = leaseRegistry.getLease({ ...leaseScope, leaseId: leaseScope.leaseId }); - if (!activeLease && !leaseRegistry.resolveRetainedProviderLease({ - leaseId: leaseScope.leaseId, - provider: leaseScope.leaseProvider, - tenantId: leaseScope.tenantId, - runId: leaseScope.runId, - })) { + if ( + !activeLease && + !leaseRegistry.resolveRetainedProviderLease({ + leaseId: leaseScope.leaseId, + provider: leaseScope.leaseProvider, + tenantId: leaseScope.tenantId, + runId: leaseScope.runId, + }) + ) { throw new AppError('UNAUTHORIZED', 'Lease is not owned by the request scope'); } } 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 7c634c2a0b3..ee2f8a60211 100644 --- a/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts +++ b/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts @@ -132,9 +132,11 @@ export async function handleInstallFromSourceDeploymentCommand(params: { return { ok: true, data }; } catch (error) { if (retained) { - await cleanupRetainedMaterializedPaths(retained.materializationId, req.meta?.tenantId, req.meta?.leaseId).catch( - () => {}, - ); + await cleanupRetainedMaterializedPaths( + retained.materializationId, + req.meta?.tenantId, + req.meta?.leaseId, + ).catch(() => {}); } return { ok: false, error: normalizeError(error) }; } finally { @@ -152,7 +154,11 @@ export async function handleReleaseMaterializedPathsCommand(params: { if (!materializationId) { throw new AppError('INVALID_ARGS', 'release_materialized_paths requires a materializationId'); } - await cleanupRetainedMaterializedPaths(materializationId, req.meta?.tenantId, req.meta?.leaseId); + await cleanupRetainedMaterializedPaths( + materializationId, + req.meta?.tenantId, + req.meta?.leaseId, + ); return { ok: true, data: { released: true, materializationId } }; } catch (error) { return { ok: false, error: normalizeError(error) }; diff --git a/packages/remote/src/artifact-download.ts b/packages/remote/src/artifact-download.ts index 9d33ac57e12..4f08ae41e25 100644 --- a/packages/remote/src/artifact-download.ts +++ b/packages/remote/src/artifact-download.ts @@ -12,6 +12,7 @@ import type { DaemonRequestMeta } from '@agent-device/kernel/contracts'; import { buildDaemonHttpAuthHeaders, buildDaemonHttpLeaseHeaders, + buildDaemonHttpRunHeaders, buildDaemonHttpTenantHeaders, } from '@agent-device/contracts/daemon-http'; @@ -201,6 +202,7 @@ async function requestRemoteArtifact( ...buildDaemonHttpAuthHeaders(params.token), ...buildDaemonHttpTenantHeaders(params.requestScope?.tenantId), ...buildDaemonHttpLeaseHeaders(params.requestScope?.leaseId), + ...buildDaemonHttpRunHeaders(params.requestScope?.runId), }, }, (res) => { From 2a473b8d24c0e28fef2f8e8978f1ff7822d137f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 17:35:02 +0100 Subject: [PATCH 04/35] fix: forward lease scope for retained artifact reads --- .../http/http-server-remote-output.test.ts | 32 ++++++++++++++++--- .../__tests__/request-handler-catalog.test.ts | 1 + packages/proxy/src/daemon-proxy.ts | 4 +++ .../cloud-webdriver-runtime.test.ts | 18 +++++++++-- .../provider-scenarios/harness-proxy.ts | 4 +++ .../remote-proxy-artifact-tenant.test.ts | 2 ++ 6 files changed, 55 insertions(+), 6 deletions(-) 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 3762f2e7d1c..4d4ba93daf0 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 @@ -73,11 +73,13 @@ async function withHttp( base: string, ) => Promise, env = localEnv(), + leaseRegistry?: LeaseRegistry, ): Promise { const server = await createDaemonHttpServer({ token: 'test-token', handleRequest, env, + leaseRegistry, cwd: process.cwd(), }); try { @@ -287,7 +289,12 @@ test.each(['marker', 'auth-hook', 'batch'] as const)( const artifact = data?.artifacts?.[0]; expect(artifact?.artifactId).toBeTypeOf('string'); const download = await fetch(`${base}/artifacts/${artifact?.artifactId}`, { - headers: { authorization: 'Bearer test-token' }, + headers: { + authorization: 'Bearer test-token', + ...(lease + ? { 'x-agent-device-lease-id': lease.leaseId, 'x-agent-device-run-id': 'run-a' } + : {}), + }, }); expect(download.status).toBe(200); const bytes = Buffer.from(await download.arrayBuffer()); @@ -295,6 +302,7 @@ test.each(['marker', 'auth-hook', 'batch'] as const)( expect(runtime.captureScreenshot).toHaveBeenCalledTimes(1); }, env, + leaseRegistry, ); }, ); @@ -925,7 +933,12 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite path.join(sessionStore.resolveSessionDir('tenant-b:capture'), 'test-artifacts'), ); const download = await fetch(`${baseUrl}/artifacts/${second.artifactId}`, { - headers: { authorization: 'Bearer test-token', 'x-tenant': 'tenant-b' }, + headers: { + authorization: 'Bearer test-token', + 'x-tenant': 'tenant-b', + 'x-agent-device-lease-id': leases.get('tenant-b')!.leaseId, + 'x-agent-device-run-id': 'tenant-b', + }, }); expect(download.status).toBe(200); const archive = gunzipSync(Buffer.from(await download.arrayBuffer())); @@ -937,12 +950,22 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite const third = await runSuite('tenant-a'); expect(registrations[2]!.path).not.toBe(firstPath); const forbidden = await fetch(`${baseUrl}/artifacts/${first.artifactId}`, { - headers: { authorization: 'Bearer test-token', 'x-tenant': 'tenant-b' }, + headers: { + authorization: 'Bearer test-token', + 'x-tenant': 'tenant-b', + 'x-agent-device-lease-id': leases.get('tenant-a')!.leaseId, + 'x-agent-device-run-id': 'tenant-a', + }, }); expect(forbidden.status).toBe(401); for (const artifact of [first, third]) { const own = await fetch(`${baseUrl}/artifacts/${artifact.artifactId}`, { - headers: { authorization: 'Bearer test-token', 'x-tenant': 'tenant-a' }, + headers: { + authorization: 'Bearer test-token', + 'x-tenant': 'tenant-a', + 'x-agent-device-lease-id': leases.get('tenant-a')!.leaseId, + 'x-agent-device-run-id': 'tenant-a', + }, }); expect(own.status).toBe(200); await own.arrayBuffer(); @@ -953,6 +976,7 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite }); }, env, + leaseRegistry, ); } finally { cwd.mockRestore(); 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 91f7ead218d..890037618bb 100644 --- a/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts +++ b/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts @@ -606,6 +606,7 @@ function trackProxyLeaseArtifact(): { artifactId: string; tempDir: string } { artifactType: 'screenshot', fileName: 'proxy-shot.png', tenantId: 'tenant-a', + leaseId: 'lease-a', }), }; } diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 173ee717a6d..9268ace2675 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -12,6 +12,8 @@ import { DAEMON_HTTP_NETWORK_ACCESS_HEADER, DAEMON_HTTP_PUBLIC_NETWORK_ACCESS, DAEMON_HTTP_TENANT_HEADER, + DAEMON_HTTP_LEASE_HEADER, + DAEMON_HTTP_RUN_HEADER, buildDaemonHttpAuthHeaders, buildDaemonHttpUrl, isTenantOwnedSessionName, @@ -144,6 +146,8 @@ const FORWARDED_REQUEST_HEADERS = [ 'x-artifact-hash', 'x-artifact-hash-algorithm', DAEMON_HTTP_TENANT_HEADER, + DAEMON_HTTP_LEASE_HEADER, + DAEMON_HTTP_RUN_HEADER, ]; const FORWARDED_RESPONSE_HEADERS = [ 'content-type', diff --git a/test/integration/provider-scenarios/cloud-webdriver-runtime.test.ts b/test/integration/provider-scenarios/cloud-webdriver-runtime.test.ts index 942133fef52..973d02f181c 100644 --- a/test/integration/provider-scenarios/cloud-webdriver-runtime.test.ts +++ b/test/integration/provider-scenarios/cloud-webdriver-runtime.test.ts @@ -46,7 +46,14 @@ test('packaged Cloud WebDriver facade drives provider devices through daemon com meta: leaseMeta(lease.leaseId), }); - const inferredArtifacts = await daemon.callCommand('artifacts'); + const inferredArtifacts = await daemon.callCommand( + 'artifacts', + [], + leaseFlags(lease.leaseId), + { + meta: leaseMeta(lease.leaseId), + }, + ); const inferredData = assertRpcOk<{ provider?: string; status?: string; @@ -57,7 +64,14 @@ test('packaged Cloud WebDriver facade drives provider devices through daemon com assert.equal(inferredData.providerSessionId, 'wd-1'); server.artifactFailuresRemaining = 1; - const unavailableArtifacts = await daemon.callCommand('artifacts'); + const unavailableArtifacts = await daemon.callCommand( + 'artifacts', + [], + leaseFlags(lease.leaseId), + { + meta: leaseMeta(lease.leaseId), + }, + ); const unavailableData = assertRpcOk<{ provider?: string; status?: string; diff --git a/test/integration/provider-scenarios/harness-proxy.ts b/test/integration/provider-scenarios/harness-proxy.ts index 986768e9792..f0c7be6642d 100644 --- a/test/integration/provider-scenarios/harness-proxy.ts +++ b/test/integration/provider-scenarios/harness-proxy.ts @@ -24,6 +24,8 @@ export type ProviderScenarioForwardedRequest = { responseBody: string; authorization: string | undefined; tenantId: string | undefined; + leaseId: string | undefined; + runId: string | undefined; statusCode: number; upstreamErrorCode?: string; }; @@ -245,6 +247,8 @@ function recordForwardedRequest( responseBody: '', authorization: request.headers.authorization, tenantId: Array.isArray(tenantHeader) ? tenantHeader.join(', ') : tenantHeader, + leaseId: request.headers['x-agent-device-lease-id'] as string | undefined, + runId: request.headers['x-agent-device-run-id'] as string | undefined, statusCode: 0, }; forwarded.push(entry); diff --git a/test/integration/provider-scenarios/remote-proxy-artifact-tenant.test.ts b/test/integration/provider-scenarios/remote-proxy-artifact-tenant.test.ts index 45778445a16..8edd360e6e2 100644 --- a/test/integration/provider-scenarios/remote-proxy-artifact-tenant.test.ts +++ b/test/integration/provider-scenarios/remote-proxy-artifact-tenant.test.ts @@ -181,6 +181,8 @@ test('Provider-backed integration proxy materializes tenant-owned test artifacts [`Bearer ${daemon.token}`, TENANT, 200], ], ); + assert.equal(downloads[1]?.leaseId, leaseId); + assert.equal(downloads[1]?.runId, 'artifact-run'); } finally { await proxy.close(); } From c066be484e1445e06d41729f2b38fdce8323c354 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 18:17:53 +0100 Subject: [PATCH 05/35] fix: prune retained lease owners and guide artifact scope --- .../src/management/artifacts.test.ts | 18 +++++++++++++++++ .../src/management/artifacts.ts | 8 +++++--- packages/contracts/src/daemon-http.ts | 4 ++-- .../__tests__/lease-registry.test.ts | 20 +++++++++++++++++++ .../daemon/src/resources/lease-registry.ts | 6 ++++++ .../daemon/src/sessions/handlers/lease.ts | 6 ++++++ website/docs/docs/commands.md | 11 ++++++---- website/docs/docs/device-clouds.md | 3 ++- 8 files changed, 66 insertions(+), 10 deletions(-) create mode 100644 packages/command-surface/src/management/artifacts.test.ts diff --git a/packages/command-surface/src/management/artifacts.test.ts b/packages/command-surface/src/management/artifacts.test.ts new file mode 100644 index 00000000000..602df8933e4 --- /dev/null +++ b/packages/command-surface/src/management/artifacts.test.ts @@ -0,0 +1,18 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { artifactsCommandFacet } from './artifacts.ts'; + +test('artifacts CLI passes an explicit lease and run through to the daemon command', () => { + const input = artifactsCommandFacet.cliReader([], { + leaseId: 'lease-a', + runId: 'run-a', + }); + assert.equal(input.leaseId, 'lease-a'); + assert.equal(input.runId, 'run-a'); + assert.deepEqual(artifactsCommandFacet.cliSchema.allowedFlags, [ + 'provider', + 'providerSessionId', + 'leaseId', + 'runId', + ]); +}); diff --git a/packages/command-surface/src/management/artifacts.ts b/packages/command-surface/src/management/artifacts.ts index 52844a60b05..77045e6b9e4 100644 --- a/packages/command-surface/src/management/artifacts.ts +++ b/packages/command-surface/src/management/artifacts.ts @@ -8,7 +8,7 @@ import { defineFieldCommandMetadata } from '../field-command-contract.ts'; const artifactsCommandMetadata = defineFieldCommandMetadata( 'artifacts', - 'List daemon or cloud provider artifacts for an active or completed session.', + 'List daemon or cloud provider artifacts for an active or completed session. For leased artifacts, pass the producing --lease-id and --run-id.', { provider: stringField( 'Cloud provider name, for example browserstack, aws-device-farm, or testmu.', @@ -19,13 +19,15 @@ const artifactsCommandMetadata = defineFieldCommandMetadata( const artifactsCliSchema = { usageOverride: 'artifacts [provider-session-id]', - usageFlags: ['provider'], + usageFlags: ['provider', 'leaseId', 'runId'], positionalArgs: ['provider-session-id?'], - allowedFlags: ['provider', 'providerSessionId'], + allowedFlags: ['provider', 'providerSessionId', 'leaseId', 'runId'], } as const satisfies CommandSchemaOverride; const artifactsCliReader: CliReader = (positionals, flags) => ({ ...commonInputFromFlags(flags), + runId: flags.runId, + leaseId: flags.leaseId, provider: flags.provider, providerSessionId: positionals[0] ?? flags.providerSessionId, }); diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 981a03caad8..511a0c434f3 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -10,8 +10,8 @@ import type { ReasonTable } from '@agent-device/kernel/errors'; export const DAEMON_HTTP_BASE_PATH = '/agent-device'; export const DAEMON_HTTP_TENANT_HEADER = 'x-agent-device-tenant'; // Names the lease a non-RPC request (upload, artifact download, request diagnostics) belongs to, -// as RPC calls name it in their body. Neither the daemon nor the proxy reads it; it lets a gateway -// in front of many daemons route those requests to the one holding the lease. +// as RPC calls name it in their body. The daemon reads it for lease admission and a gateway +// can route the request to the daemon holding the lease. The header is caller-declared. export const DAEMON_HTTP_LEASE_HEADER = 'x-agent-device-lease-id'; export const DAEMON_HTTP_RUN_HEADER = 'x-agent-device-run-id'; export const DAEMON_HTTP_NETWORK_ACCESS_HEADER = 'x-agent-device-network-access'; diff --git a/packages/daemon/src/resources/__tests__/lease-registry.test.ts b/packages/daemon/src/resources/__tests__/lease-registry.test.ts index 0672a6d71a2..1a9c39fd18e 100644 --- a/packages/daemon/src/resources/__tests__/lease-registry.test.ts +++ b/packages/daemon/src/resources/__tests__/lease-registry.test.ts @@ -30,6 +30,26 @@ test('allocateLease creates lease and enforces tenant/run validation', () => { ); }); +test('released artifact lease owners are removed after retention', () => { + let now = 0; + const registry = new LeaseRegistry({ now: () => now }); + const lease = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-a' }); + registry.releaseLease({ leaseId: lease.leaseId }); + const owners = (registry as unknown as { artifactLeaseOwners: Map }) + .artifactLeaseOwners; + assert.equal(owners.has(lease.leaseId), true); + + now = 15 * 60_000; + assert.throws(() => + registry.assertArtifactLeaseReadAdmission({ + leaseId: lease.leaseId, + tenantId: 'tenant-a', + runId: 'run-a', + }), + ); + assert.equal(owners.has(lease.leaseId), false); +}); + function isLeaseIdInUse(error: unknown): boolean { return ( error instanceof AppError && diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index 7631aa05ad0..6ea1e963207 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -703,6 +703,12 @@ export class LeaseRegistry { private cleanupExpiredLeases(): void { this.consumeExpiredLeases(); + const now = this.now(); + for (const [leaseId, owner] of this.artifactLeaseOwners) { + if (owner.retainedUntil !== undefined && owner.retainedUntil <= now) { + this.artifactLeaseOwners.delete(leaseId); + } + } } private enforceCapacity(backend: LeaseBackend): void { diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index d21134de740..fe8ecc3d406 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -97,6 +97,11 @@ export async function handleLeaseCommands(args: LeaseHandlerArgs): Promise] +agent-device artifacts [provider-session-id] [--provider ] [--lease-id ] [--run-id ] ``` | Option | What it does | | --- | --- | | `--provider ` | Cloud provider name for provider-scoped commands | | `--provider-session ` | Cloud provider session id or ARN | +| `--lease-id ` | Lease that produced the artifacts | +| `--run-id ` | Run that owns the lease or provider session | Exact behavior: `agent-device help artifacts`. ```bash -agent-device artifacts --provider browserstack --provider-session --json -agent-device artifacts --provider aws-device-farm --provider-session --json +agent-device artifacts --provider browserstack --provider-session --run-id --json +agent-device artifacts --provider aws-device-farm --provider-session --run-id --json ``` - `artifacts` lists the provider-hosted videos, logs, and dashboard links as `cloudArtifacts`. See [Device clouds](/docs/device-clouds#compare-providers) for what each provider returns. -- To look up a past session, pass `--provider ` and `--provider-session `. +- To look up a past session, pass `--provider `, `--provider-session `, and the owning `--run-id `. +- For leased artifacts, pass the producing `--lease-id ` and `--run-id `; a session name alone does not grant access. - Providers can finish their URLs only after the session stops, so retry `artifacts` if the first response is `pending`. ## MCP server diff --git a/website/docs/docs/device-clouds.md b/website/docs/docs/device-clouds.md index 70be22c9cfb..18bb7a54842 100644 --- a/website/docs/docs/device-clouds.md +++ b/website/docs/docs/device-clouds.md @@ -63,10 +63,11 @@ Use `snapshot -i` to confirm the target. If the driver does not support the `/el After `close`, run `agent-device artifacts --json` to check for the artifacts your provider makes available (see [Compare providers](#compare-providers)). To look up an earlier session, pass its provider session ID: ```bash -agent-device artifacts --provider --json +agent-device artifacts --provider --run-id --json ``` Providers finalize video and log URLs after the session ends. If the lookup reports artifacts as pending right after `close`, retry it a little later. +For artifacts produced by a lease, pass that lease's `--lease-id` and `--run-id` explicitly. A session name alone does not grant access to its artifacts. ## NoMac From 1f2dc7a2e7a6e8b580fb0960d3ce3fe618778050 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 19:27:05 +0100 Subject: [PATCH 06/35] fix: require run scope for leased uploads --- .../http-server-install-retention.test.ts | 7 +++++ packages/daemon/src/server/upload-http.ts | 19 +++++++++--- .../__tests__/lease-artifacts.test.ts | 27 +++++++++++++++++ .../src/__tests__/upload-client.test.ts | 19 ++++++++++-- packages/remote/src/daemon-artifacts.ts | 2 ++ packages/remote/src/upload-client.ts | 29 +++++++++++++++++-- 6 files changed, 94 insertions(+), 9 deletions(-) diff --git a/packages/daemon/src/server/http/http-server-install-retention.test.ts b/packages/daemon/src/server/http/http-server-install-retention.test.ts index 0567a4a8a38..d73197e1d7e 100644 --- a/packages/daemon/src/server/http/http-server-install-retention.test.ts +++ b/packages/daemon/src/server/http/http-server-install-retention.test.ts @@ -146,7 +146,14 @@ test('HTTP leased resumable upload remains readable by install dispatch', async authorization: 'Bearer test-token', 'x-agent-device-tenant': 'tenant-a', 'x-agent-device-lease-id': lease.leaseId, + 'x-agent-device-run-id': 'run-a', }; + const wrongRun = await fetch(`${base}/upload/preflight`, { + method: 'POST', + headers: { ...headers, 'x-agent-device-run-id': 'run-b', 'content-type': 'application/json' }, + body: '{}', + }); + assert.equal(wrongRun.status, 401); const preflight = await fetch(`${base}/upload/preflight`, { method: 'POST', headers: { ...headers, 'content-type': 'application/json' }, diff --git a/packages/daemon/src/server/upload-http.ts b/packages/daemon/src/server/upload-http.ts index 5da3959bbfd..b31bc44370f 100644 --- a/packages/daemon/src/server/upload-http.ts +++ b/packages/daemon/src/server/upload-http.ts @@ -13,7 +13,10 @@ import { receiveUpload } from './upload.ts'; import { sendRestJsonError } from './http-errors.ts'; import { beginUploadTransferIngress, type UploadTransferIngress } from './upload-ingress.ts'; import { readNodeHttpRequestBody } from '@agent-device/host-kit/transport'; -import { DAEMON_HTTP_LEASE_HEADER } from '@agent-device/contracts/daemon-http'; +import { + DAEMON_HTTP_LEASE_HEADER, + DAEMON_HTTP_RUN_HEADER, +} from '@agent-device/contracts/daemon-http'; import type { LeaseRegistry } from '../resources/lease-registry.ts'; const DIRECT_UPLOAD_PATH_PREFIX = '/upload/direct/'; @@ -142,14 +145,22 @@ function admitUploadLease( ): string | undefined { const header = req.headers[DAEMON_HTTP_LEASE_HEADER]; if (header === undefined) return undefined; - if (typeof header !== 'string' || !header.trim() || !tenantId || !leaseRegistry) { + const runId = req.headers[DAEMON_HTTP_RUN_HEADER]; + if ( + typeof header !== 'string' || + !header.trim() || + typeof runId !== 'string' || + !runId.trim() || + !tenantId || + !leaseRegistry + ) { throw new AppError( 'UNAUTHORIZED', - 'Upload lease requires an admitted tenant and lease registry', + 'Upload lease requires an admitted tenant, run and lease registry', ); } const leaseId = header.trim(); - leaseRegistry.assertLeaseReadAdmission({ leaseId, tenantId }); + leaseRegistry.assertLeaseReadAdmission({ leaseId, tenantId, runId: runId.trim() }); return leaseId; } diff --git a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts index f55c1d857d1..c8baa20cc2d 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts @@ -7,12 +7,39 @@ import type { DeviceLease } from '@agent-device/contracts/device'; import { AppError, isRequestCanceledError } from '@agent-device/kernel/errors'; import { clearRequestCanceled, markRequestCanceled } from '@agent-device/host-kit/request'; import { makeSessionStore } from '../../../__tests__/support/store-factory.ts'; +import { makeAndroidSession } from '../../../__tests__/support/session-factories.ts'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; import { handleLeaseCommands } from '../lease.ts'; import { LeaseRegistry } from '../../../resources/lease-registry.ts'; const CLOUD_PROVIDER = 'fake-cloud'; +test('session name alone gives a typed error for leased artifact inventory', async () => { + const world = createWorld(); + const lease = await allocateLease(world, 'tenant-a', 'run-a'); + world.sessionStore.publish( + 'artifact-test', + makeAndroidSession('artifact-test', { + lease: { + leaseId: lease.leaseId, + tenantId: lease.tenantId, + runId: lease.runId, + leaseBackend: lease.backend, + leaseProvider: lease.leaseProvider, + }, + }), + ); + + await assert.rejects( + () => listArtifacts(world, { tenantId: 'tenant-a', runId: 'run-a' }), + (error: unknown) => + error instanceof AppError && + error.code === 'INVALID_ARGS' && + error.message.includes('--lease-id'), + ); + assert.deepEqual(world.providerCalls, []); +}); + test('artifacts refuses foreign and unknown provider session ids before cloud dispatch', async () => { const world = createWorld(); await allocateLease(world, 'tenant-a', 'run-a'); diff --git a/packages/remote/src/__tests__/upload-client.test.ts b/packages/remote/src/__tests__/upload-client.test.ts index 0b57ce1fdb3..3dde267974d 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_RUN_HEADER, +} from '@agent-device/contracts/daemon-http'; const TEST_TOKEN = 'agent-device-upload-test-token'; const tempDirs: string[] = []; @@ -909,7 +912,10 @@ test.each([ 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]); + leases.set(`${req.method} ${req.url}`, [ + req.headers[DAEMON_HTTP_LEASE_HEADER], + req.headers[DAEMON_HTTP_RUN_HEADER], + ]); 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 }); @@ -925,8 +931,15 @@ test.each([ baseUrl: server.baseUrl, token: TEST_TOKEN, leaseId, + runId: leaseId ? 'run-a' : undefined, }); - const expected = routes.map((route) => [route, route === unleased ? undefined : leaseId]); + const expected = routes.map((route) => [ + route, + [ + route === unleased ? undefined : leaseId, + route === unleased ? undefined : leaseId ? 'run-a' : undefined, + ], + ]); assert.deepEqual([...leases], expected); } } finally { diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 8d6d546aed8..ce1aea15714 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -203,6 +203,7 @@ async function prepareRemoteInstallPackage( token: info.token, platform: req.flags?.platform, leaseId: leaseScopeFromRequest(req).leaseId, + runId: leaseScopeFromRequest(req).runId, onProgress, signal, }); @@ -308,6 +309,7 @@ async function prepareRemoteInstallSource( token: info.token, platform: req.flags?.platform, leaseId: leaseScopeFromRequest(req).leaseId, + runId: leaseScopeFromRequest(req).runId, onProgress, signal, }); diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index fe6801f52ce..a4857c05bd9 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -4,6 +4,7 @@ import { AppError } from '@agent-device/kernel/errors'; import { buildDaemonHttpAuthHeaders, buildDaemonHttpLeaseHeaders, + buildDaemonHttpRunHeaders, } from '@agent-device/contracts/daemon-http'; import { prepareUploadArtifact, type PreparedUploadArtifact } from './upload-client-artifact.ts'; import { @@ -31,6 +32,7 @@ type UploadArtifactOptions = { env: Readonly; /** The lease this upload is for; every request to the daemon names it in a header. */ leaseId?: string; + runId?: string; onProgress?: UploadProgressSink; /** * Ends the upload when the thing it is uploading for stops being worth finishing — today, a beat @@ -90,6 +92,7 @@ async function uploadArtifactWithinBudget( normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, artifact: prepared, uploadAttemptId, env: options.env, @@ -104,6 +107,7 @@ async function uploadArtifactWithinBudget( normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, artifact: prepared, preflight, uploadAttemptId, @@ -122,6 +126,7 @@ async function uploadArtifactWithinBudget( normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, artifact: prepared, onProgress: options.onProgress, signal: options.signal, @@ -132,6 +137,7 @@ async function uploadArtifactWithinBudget( normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, artifact: prepared, onProgress: options.onProgress, signal: options.signal, @@ -145,6 +151,7 @@ async function tryDirectUploadWithResume(options: { normalizedBase: string; token: string; leaseId?: string; + runId?: string; artifact: PreparedUploadArtifact; preflight: Extract; uploadAttemptId: string; @@ -160,6 +167,7 @@ async function tryDirectUploadWithResume(options: { normalizedBase: options.normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, uploadId: preflight.uploadId, signal: options.signal, }); @@ -190,6 +198,7 @@ async function retryDirectUpload( normalizedBase: string; token: string; leaseId?: string; + runId?: string; artifact: PreparedUploadArtifact; uploadAttemptId: string; env: HostEnvironment['env']; @@ -204,6 +213,7 @@ async function retryDirectUpload( normalizedBase: options.normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, artifact: options.artifact, uploadAttemptId: options.uploadAttemptId, env: options.env, @@ -233,6 +243,7 @@ async function uploadLegacyArtifact(options: { normalizedBase: string; token: string; leaseId?: string; + runId?: string; artifact: PreparedUploadArtifact; onProgress?: UploadProgressSink; signal: AbortSignal; @@ -248,7 +259,12 @@ 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), + buildDaemonHttpLeaseHeaders(leaseId), + buildDaemonHttpRunHeaders(options.runId), + ); const response = await streamFileToHttpRequest({ url: uploadUrl, @@ -281,6 +297,7 @@ async function requestUploadPreflight(options: { normalizedBase: string; token: string; leaseId?: string; + runId?: string; artifact: PreparedUploadArtifact; uploadAttemptId: string; env: HostEnvironment['env']; @@ -294,6 +311,7 @@ async function requestUploadPreflight(options: { headers, buildDaemonHttpAuthHeaders(options.token), buildDaemonHttpLeaseHeaders(options.leaseId), + buildDaemonHttpRunHeaders(options.runId), ); const result = await requestUploadControl( @@ -402,6 +420,7 @@ async function uploadDirectArtifact( options: { normalizedBase: string; leaseId?: string; + runId?: string; artifact: PreparedUploadArtifact; onProgress?: UploadProgressSink; signal: AbortSignal; @@ -417,7 +436,11 @@ async function uploadDirectArtifact( // too; a ticket elsewhere (a signed storage URL) gets only the headers the daemon handed out. headers: url.origin === new URL(options.normalizedBase).origin - ? { ...ticket.headers, ...buildDaemonHttpLeaseHeaders(options.leaseId) } + ? { + ...ticket.headers, + ...buildDaemonHttpLeaseHeaders(options.leaseId), + ...buildDaemonHttpRunHeaders(options.runId), + } : ticket.headers, payloadPath: artifact.payloadPath, errorMessage: 'Failed to upload artifact with direct upload ticket', @@ -442,6 +465,7 @@ async function finalizeDirectUpload(options: { normalizedBase: string; token: string; leaseId?: string; + runId?: string; uploadId: string; signal?: AbortSignal; }): Promise { @@ -453,6 +477,7 @@ async function finalizeDirectUpload(options: { headers, buildDaemonHttpAuthHeaders(options.token), buildDaemonHttpLeaseHeaders(options.leaseId), + buildDaemonHttpRunHeaders(options.runId), ); const result = await requestUploadControl( From a85d6aa2e36922b8206449d94712c1d0dac82816 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 19:43:56 +0100 Subject: [PATCH 07/35] fix: align artifact docs and focused tests with repo guards --- .../src/management/artifacts.test.ts | 3 +- .../src/management/artifacts.ts | 2 +- .../lease-registry-artifact-retention.test.ts | 23 ++++++ .../__tests__/lease-registry.test.ts | 20 ----- .../upload-client-lease-headers.test.ts | 74 +++++++++++++++++++ .../src/__tests__/upload-client.test.ts | 52 ------------- website/docs/docs/commands.md | 4 +- 7 files changed, 102 insertions(+), 76 deletions(-) create mode 100644 packages/daemon/src/resources/__tests__/lease-registry-artifact-retention.test.ts create mode 100644 packages/remote/src/__tests__/upload-client-lease-headers.test.ts diff --git a/packages/command-surface/src/management/artifacts.test.ts b/packages/command-surface/src/management/artifacts.test.ts index 602df8933e4..c5a2a879dce 100644 --- a/packages/command-surface/src/management/artifacts.test.ts +++ b/packages/command-surface/src/management/artifacts.test.ts @@ -1,12 +1,13 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; import { artifactsCommandFacet } from './artifacts.ts'; +import type { CliFlags } from '@agent-device/contracts/command'; test('artifacts CLI passes an explicit lease and run through to the daemon command', () => { const input = artifactsCommandFacet.cliReader([], { leaseId: 'lease-a', runId: 'run-a', - }); + } as CliFlags); assert.equal(input.leaseId, 'lease-a'); assert.equal(input.runId, 'run-a'); assert.deepEqual(artifactsCommandFacet.cliSchema.allowedFlags, [ diff --git a/packages/command-surface/src/management/artifacts.ts b/packages/command-surface/src/management/artifacts.ts index 77045e6b9e4..01c1ce6a4a1 100644 --- a/packages/command-surface/src/management/artifacts.ts +++ b/packages/command-surface/src/management/artifacts.ts @@ -8,7 +8,7 @@ import { defineFieldCommandMetadata } from '../field-command-contract.ts'; const artifactsCommandMetadata = defineFieldCommandMetadata( 'artifacts', - 'List daemon or cloud provider artifacts for an active or completed session. For leased artifacts, pass the producing --lease-id and --run-id.', + 'List daemon or cloud provider artifacts for an active or completed session.', { provider: stringField( 'Cloud provider name, for example browserstack, aws-device-farm, or testmu.', diff --git a/packages/daemon/src/resources/__tests__/lease-registry-artifact-retention.test.ts b/packages/daemon/src/resources/__tests__/lease-registry-artifact-retention.test.ts new file mode 100644 index 00000000000..b5fdc9cead9 --- /dev/null +++ b/packages/daemon/src/resources/__tests__/lease-registry-artifact-retention.test.ts @@ -0,0 +1,23 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { LeaseRegistry } from '../lease-registry.ts'; + +test('released artifact lease owners are removed after retention', () => { + let now = 0; + const registry = new LeaseRegistry({ now: () => now }); + const lease = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-a' }); + registry.releaseLease({ leaseId: lease.leaseId }); + const owners = (registry as unknown as { artifactLeaseOwners: Map }) + .artifactLeaseOwners; + assert.equal(owners.has(lease.leaseId), true); + + now = 15 * 60_000; + assert.throws(() => + registry.assertArtifactLeaseReadAdmission({ + leaseId: lease.leaseId, + tenantId: 'tenant-a', + runId: 'run-a', + }), + ); + assert.equal(owners.has(lease.leaseId), false); +}); diff --git a/packages/daemon/src/resources/__tests__/lease-registry.test.ts b/packages/daemon/src/resources/__tests__/lease-registry.test.ts index 1a9c39fd18e..0672a6d71a2 100644 --- a/packages/daemon/src/resources/__tests__/lease-registry.test.ts +++ b/packages/daemon/src/resources/__tests__/lease-registry.test.ts @@ -30,26 +30,6 @@ test('allocateLease creates lease and enforces tenant/run validation', () => { ); }); -test('released artifact lease owners are removed after retention', () => { - let now = 0; - const registry = new LeaseRegistry({ now: () => now }); - const lease = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-a' }); - registry.releaseLease({ leaseId: lease.leaseId }); - const owners = (registry as unknown as { artifactLeaseOwners: Map }) - .artifactLeaseOwners; - assert.equal(owners.has(lease.leaseId), true); - - now = 15 * 60_000; - assert.throws(() => - registry.assertArtifactLeaseReadAdmission({ - leaseId: lease.leaseId, - tenantId: 'tenant-a', - runId: 'run-a', - }), - ); - assert.equal(owners.has(lease.leaseId), false); -}); - function isLeaseIdInUse(error: unknown): boolean { return ( error instanceof AppError && diff --git a/packages/remote/src/__tests__/upload-client-lease-headers.test.ts b/packages/remote/src/__tests__/upload-client-lease-headers.test.ts new file mode 100644 index 00000000000..b4463486ce4 --- /dev/null +++ b/packages/remote/src/__tests__/upload-client-lease-headers.test.ts @@ -0,0 +1,74 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import http from 'node:http'; +import path from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { test } from 'vitest'; +import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import { + DAEMON_HTTP_LEASE_HEADER, + DAEMON_HTTP_RUN_HEADER, +} from '@agent-device/contracts/daemon-http'; +import { uploadArtifact } from '../upload-client.ts'; + +const DIRECT_ROUTES = ['POST /upload/preflight', 'PUT /upload/t', 'POST /upload/finalize']; + +test.each([ + { flow: 'direct', host: '127.0.0.1', routes: DIRECT_ROUTES, unleased: '' }, + { flow: 'legacy', host: '', routes: ['POST /upload/preflight', 'POST /upload'], unleased: '' }, + { flow: 'direct', host: 'localhost', routes: DIRECT_ROUTES, unleased: 'PUT /upload/t' }, +])( + 'upload forwards lease and run only to daemon-bound $flow routes for $host', + async ({ flow, host, routes, unleased }) => { + const directory = mkdtempForTestSync(`agent-device-upload-lease-${randomUUID()}-`); + const localPath = path.join(directory, 'app.apk'); + fs.writeFileSync(localPath, `${flow}-payload`); + let headers = new Map(); + let baseUrl = ''; + const server = http.createServer((req, res) => { + void (async () => { + headers.set(`${req.method} ${req.url}`, [ + req.headers[DAEMON_HTTP_LEASE_HEADER], + req.headers[DAEMON_HTTP_RUN_HEADER], + ]); + for await (const chunk of req) void chunk; + res.setHeader('content-type', 'application/json'); + if (req.url !== '/upload/preflight') + return res.end(JSON.stringify({ ok: true, uploadId: 'done' })); + if (flow === 'legacy') return res.end(JSON.stringify({ ok: true, cacheHit: false })); + const url = `${baseUrl.replace('127.0.0.1', host)}/upload/t`; + res.end(JSON.stringify({ ok: true, uploadId: 't', upload: { url, headers: {} } })); + })().catch((error) => { + res.statusCode = 500; + res.end(String(error)); + }); + }); + server.unref(); + try { + const port = await listenOnLoopback(server); + baseUrl = `http://127.0.0.1:${port}`; + for (const leaseId of ['lease-1', undefined]) { + headers = new Map(); + await uploadArtifact({ + localPath, + baseUrl, + token: 'test-token', + env: process.env, + leaseId, + runId: leaseId ? 'run-a' : undefined, + }); + const expected = routes.map((route) => [ + route, + [ + route === unleased ? undefined : leaseId, + route === unleased ? undefined : leaseId ? 'run-a' : undefined, + ], + ]); + assert.deepEqual([...headers], expected); + } + } finally { + await closeLoopbackServer(server); + fs.rmSync(directory, { recursive: true, force: true }); + } + }, +); diff --git a/packages/remote/src/__tests__/upload-client.test.ts b/packages/remote/src/__tests__/upload-client.test.ts index 3dde267974d..bc3d805bcd5 100644 --- a/packages/remote/src/__tests__/upload-client.test.ts +++ b/packages/remote/src/__tests__/upload-client.test.ts @@ -11,10 +11,6 @@ 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, - DAEMON_HTTP_RUN_HEADER, -} from '@agent-device/contracts/daemon-http'; const TEST_TOKEN = 'agent-device-upload-test-token'; const tempDirs: string[] = []; @@ -900,54 +896,6 @@ test('uploadArtifact uploads APK, AAB, and IPA files without wrapping them', asy } }); -const DIRECT_ROUTES = ['POST /upload/preflight', 'PUT /upload/t', 'POST /upload/finalize']; - -// A `localhost` ticket reaches this fake but is another origin, as a signed storage URL is. -test.each([ - { flow: 'direct', host: '127.0.0.1', routes: DIRECT_ROUTES, unleased: '' }, - { 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"', - 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], - req.headers[DAEMON_HTTP_RUN_HEADER], - ]); - 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 }); - const url = `${server.baseUrl.replace('127.0.0.1', host)}/upload/t`; - sendJson(res, { ok: true, uploadId: 't', upload: { url, headers: {} } }); - }); - try { - const localPath = createTempFile('app.apk', `${flow}-payload`); - for (const leaseId of ['lease-1', undefined]) { - leases = new Map(); - await uploadArtifact({ - localPath, - baseUrl: server.baseUrl, - token: TEST_TOKEN, - leaseId, - runId: leaseId ? 'run-a' : undefined, - }); - const expected = routes.map((route) => [ - route, - [ - route === unleased ? undefined : leaseId, - route === unleased ? undefined : leaseId ? 'run-a' : undefined, - ], - ]); - assert.deepEqual([...leases], expected); - } - } finally { - await server.close(); - } - }, -); - function createTempDir(): string { const dir = mkdtempForTestSync(`agent-device-upload-client-${randomUUID()}-`); tempDirs.push(dir); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 324e833109b..a8cb253b167 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2765,10 +2765,10 @@ agent-device artifacts [provider-session-id] [--provider ] [--lease-id ` | Run identifier used for tenant lease admission checks | +| `--lease-id ` | Lease identifier bound to tenant/run admission scope | | `--provider ` | Cloud provider name for provider-scoped commands | | `--provider-session ` | Cloud provider session id or ARN | -| `--lease-id ` | Lease that produced the artifacts | -| `--run-id ` | Run that owns the lease or provider session | Exact behavior: `agent-device help artifacts`. From 16637a3f71254c8d4ced238c49ddf9d278234782 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 19:47:04 +0100 Subject: [PATCH 08/35] fix: distinguish missing artifact run from ownership refusal --- .../handlers/__tests__/lease-artifacts.test.ts | 17 +++++++++++++++++ packages/daemon/src/sessions/handlers/lease.ts | 10 +++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts index c8baa20cc2d..8967dc51968 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts @@ -64,6 +64,22 @@ test('artifacts refuses foreign and unknown provider session ids before cloud di assert.deepEqual(world.providerCalls, []); }); +test('provider session lookup reports a missing run as invalid scope', async () => { + const world = createWorld(); + await allocateLease(world, 'tenant-a', 'run-a'); + + await assert.rejects( + () => listArtifacts(world, { tenantId: 'tenant-a', providerSessionId: 'session-tenant-a' }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + assert.equal(error.details?.reason, 'PROVIDER_SESSION_RUN_REQUIRED'); + return true; + }, + ); + assert.deepEqual(world.providerCalls, []); +}); + test('artifacts admits an owned lease ID and refuses a foreign lease ID before cloud dispatch', async () => { const world = createWorld(); const lease = await allocateLease(world, 'tenant-a', 'run-a'); @@ -124,6 +140,7 @@ test('artifacts admits a closed lease for its owner until retention expires', as (error: unknown) => { assert.ok(error instanceof AppError); assert.equal(error.code, 'UNAUTHORIZED'); + assert.equal(error.details?.reason, 'ARTIFACT_LEASE_NOT_OWNED'); return true; }, ); diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index fe8ecc3d406..708353956ae 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -63,6 +63,8 @@ const LEASE_HANDLER_REASONS = { providerCredentialsChanged: { reason: 'provider-credentials-changed' }, // The provider session belongs to another tenant. providerSessionNotOwned: { reason: 'PROVIDER_SESSION_NOT_OWNED' }, + providerSessionRunRequired: { reason: 'PROVIDER_SESSION_RUN_REQUIRED' }, + artifactLeaseNotOwned: { reason: 'ARTIFACT_LEASE_NOT_OWNED' }, // Only the host administrator releases a `macos-app` lease. macOsAppHostOwned: { reason: 'MACOS_APP_LEASE_HOST_OWNED' }, // Only the host administrator allocates a `macos-app` lease. @@ -577,7 +579,9 @@ async function listCloudArtifactsForRequest( runId: leaseScope.runId, }) ) { - throw new AppError('UNAUTHORIZED', 'Lease is not owned by the request scope'); + throw new AppError('UNAUTHORIZED', 'Lease is not owned by the request scope', { + reason: LEASE_HANDLER_REASONS.artifactLeaseNotOwned.reason, + }); } } const providerSession = resolveProviderSession(leaseRegistry, leaseScope, providerSessionId); @@ -607,8 +611,8 @@ function resolveProviderSession( ): ReturnType { if (!providerSessionId) return undefined; if (!leaseScope.runId) { - throw new AppError('UNAUTHORIZED', 'Provider session requires the request run', { - reason: LEASE_HANDLER_REASONS.providerSessionNotOwned.reason, + throw new AppError('INVALID_ARGS', 'Provider session requires the request run', { + reason: LEASE_HANDLER_REASONS.providerSessionRunRequired.reason, hint: 'Pass --run-id for the run that owns this provider session.', }); } From 8215e4f636c8c3040c0364ab4d2877d46c7f7e43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 19:58:24 +0100 Subject: [PATCH 09/35] fix: document artifact reasons and expect missing-run refusal --- packages/daemon/src/sessions/handlers/lease.ts | 2 ++ src/daemon-entrypoint.test.ts | 8 ++++---- website/docs/docs/error-reasons.md | 2 ++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index 708353956ae..03d70db4ef8 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -63,7 +63,9 @@ const LEASE_HANDLER_REASONS = { providerCredentialsChanged: { reason: 'provider-credentials-changed' }, // The provider session belongs to another tenant. providerSessionNotOwned: { reason: 'PROVIDER_SESSION_NOT_OWNED' }, + // Provider-session artifact lookup needs the run that owns the session. providerSessionRunRequired: { reason: 'PROVIDER_SESSION_RUN_REQUIRED' }, + // The requested cloud artifact lease is outside the caller's ownership scope. artifactLeaseNotOwned: { reason: 'ARTIFACT_LEASE_NOT_OWNED' }, // Only the host administrator releases a `macos-app` lease. macOsAppHostOwned: { reason: 'MACOS_APP_LEASE_HOST_OWNED' }, diff --git a/src/daemon-entrypoint.test.ts b/src/daemon-entrypoint.test.ts index 7682b398e06..8d68a3c7847 100644 --- a/src/daemon-entrypoint.test.ts +++ b/src/daemon-entrypoint.test.ts @@ -154,7 +154,7 @@ test('daemon runtime publishes dual transport metadata', async () => { } }); -test('daemon rejects unowned cloud artifacts over RPC', async () => { +test('daemon reports missing run for cloud artifacts over RPC', async () => { const stateDir = mkdtempForTestSync('agent-device-daemon-provider-'); const providerRequests: string[] = []; const providerServer = http.createServer((_req, res) => { @@ -206,10 +206,10 @@ test('daemon rejects unowned cloud artifacts over RPC', async () => { error?: { code?: number; message?: string; data?: { code?: string; details?: unknown } }; }; - assert.equal(response.status, 401); + assert.equal(response.status, 400); assert.equal(body.error?.code, -32000); - assert.equal(body.error?.data?.code, 'UNAUTHORIZED'); - assert.deepEqual(body.error?.data?.details, { reason: 'PROVIDER_SESSION_NOT_OWNED' }); + assert.equal(body.error?.data?.code, 'INVALID_ARGS'); + assert.deepEqual(body.error?.data?.details, { reason: 'PROVIDER_SESSION_RUN_REQUIRED' }); assert.deepEqual(providerRequests, []); } finally { await runtime?.close(); diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index de5c147e0e8..ca6603ab076 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -825,6 +825,8 @@ These reasons can come from more than one command. | `provider-not-registered` | The lease names a provider this daemon has not registered; `details.failedPlugins` lists plugins that failed to load. | | `provider-credentials-changed` | The running daemon holds different provider credentials than this shell; stop the daemon and rerun. | | `PROVIDER_SESSION_NOT_OWNED` | The provider session belongs to another tenant. | +| `PROVIDER_SESSION_RUN_REQUIRED` | Provider-session artifact lookup needs the run that owns the session. | +| `ARTIFACT_LEASE_NOT_OWNED` | The requested cloud artifact lease is outside the caller's ownership scope. | | `MACOS_APP_LEASE_HOST_OWNED` | Only the host administrator releases a `macos-app` lease. | | `MACOS_APP_LEASE_HOST_ALLOCATED` | Only the host administrator allocates a `macos-app` lease. | | `LEASE_SESSION_MISMATCH` | The lease scope of the request differs from the lease of its session; `details.field` names the field. | From ee1821971b3fe22d69a7087f87badac26e766918 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 12:00:51 +0100 Subject: [PATCH 10/35] fix: align artifact lease admission and protocol boundary --- packages/contracts/src/daemon-http.ts | 2 +- ...mon-client-transport-health-compat.test.ts | 17 ++-- .../src/resources/artifact-tracking.test.ts | 6 +- .../daemon/src/resources/artifact-tracking.ts | 5 -- .../daemon/src/resources/lease-registry.ts | 6 +- .../src/server/downloadable-artifact-http.ts | 3 +- .../http-server-install-retention.test.ts | 6 +- .../http/http-server-remote-output.test.ts | 12 ++- packages/daemon/src/server/upload-http.ts | 3 +- .../__tests__/lease-artifacts.test.ts | 14 ++- .../daemon/src/sessions/handlers/lease.ts | 9 +- test/wire-compat/closure-policy.ts | 2 + test/wire-compat/ledger.json | 90 ++++--------------- website/docs/docs/error-reasons.md | 1 + 14 files changed, 78 insertions(+), 98 deletions(-) diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 511a0c434f3..99aa29010b5 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -131,7 +131,7 @@ export function buildDaemonHttpRunHeaders(runId: string | undefined): Record { +test.for([ + ['daemon', 2], + ['upstream', 2], + ['daemon', 3], + ['upstream', 3], +] as const)( + 'released protocol-%s %s is refused before command RPC', + async ([link, releasedProtocol], t) => { if (await skipWhenLoopbackUnavailable(t)) return; const payload = - link === 'upstream' ? proxyHealth(2) : { ...DAEMON_LINK, rpcProtocolVersion: 2 }; + link === 'upstream' + ? proxyHealth(releasedProtocol) + : { ...DAEMON_LINK, rpcProtocolVersion: releasedProtocol }; await withHealthServer(payload, async (baseUrl) => { await assert.rejects( readRemoteDaemonHealth({ baseUrl, token: 't', pid: 0 }), (error: unknown) => { const failure = error as { code?: string; details?: Record }; assert.equal(failure.code, 'COMMAND_FAILED'); - assert.equal(failure.details?.remoteRpcProtocolVersion, 2); + assert.equal(failure.details?.remoteRpcProtocolVersion, releasedProtocol); assert.equal(failure.details?.supportedRpcProtocolVersion, DAEMON_RPC_PROTOCOL_VERSION); return true; }, diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index d76866f6940..6b897e9bd60 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -584,11 +584,10 @@ test('disposing a runtime removes the temporary files it still tracks', () => { expect(fs.existsSync(artifactPath)).toBe(false); }); -test('uploads stay bound to their producing lease and release capacity on cleanup', () => { +test('uploads stay bound to their producing lease', () => { const root = mkdtempForTestSync('agent-device-upload-lease-'); const artifactPath = path.join(root, 'payload'); fs.writeFileSync(artifactPath, 'payload'); - const releaseReservation = vi.fn(); const runtime = createRuntimeStateHandle(); const id = runtime.run(() => trackUploadedArtifact({ @@ -596,7 +595,6 @@ test('uploads stay bound to their producing lease and release capacity on cleanu tempDir: root, tenantId: 'tenant-a', leaseId: 'lease-a', - releaseReservation, }), ); @@ -605,10 +603,8 @@ test('uploads stay bound to their producing lease and release capacity on cleanu /different lease/, ); } - expect(releaseReservation).not.toHaveBeenCalled(); expect(runtime.run(() => prepareUploadedArtifact(id, 'tenant-a', 'lease-a'))).toBe(artifactPath); runtime.run(() => cleanupUploadedArtifact(id)); - expect(releaseReservation).toHaveBeenCalledOnce(); runtime.dispose(); }); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 453a36372fd..8b275c11582 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -85,7 +85,6 @@ const artifactTracking = (): ArtifactTrackingState => for (const entry of state.uploads.values()) { clearTimeout(entry.timer); removeBestEffort(entry.tempDir); - entry.releaseReservation?.(); } }, ); @@ -527,7 +526,6 @@ type UploadEntry = { tempDir: string; tenantId?: string; leaseId?: string; - releaseReservation?: () => void; timer: ReturnType; }; @@ -536,7 +534,6 @@ export function trackUploadedArtifact(params: { tempDir: string; tenantId?: string; leaseId?: string; - releaseReservation?: () => void; }): string { const uploadId = crypto.randomUUID(); const timer = setTimeout(() => { @@ -548,7 +545,6 @@ export function trackUploadedArtifact(params: { tempDir: params.tempDir, tenantId: params.tenantId, leaseId: params.leaseId, - releaseReservation: params.releaseReservation, timer, }); return uploadId; @@ -578,5 +574,4 @@ export function cleanupUploadedArtifact(uploadId: string): void { clearTimeout(entry.timer); pendingUploads().delete(uploadId); fs.rmSync(entry.tempDir, { recursive: true, force: true }); - entry.releaseReservation?.(); } diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index 6ea1e963207..6568a1a65ae 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -345,7 +345,11 @@ export class LeaseRegistry { } /** Retained artifacts can be read by their original owner after lease release. */ - assertArtifactLeaseReadAdmission(request: HeartbeatLeaseRequest): void { + assertArtifactLeaseReadAdmission(request: { + leaseId: string; + tenantId?: string; + runId?: string; + }): void { const leaseId = normalizeRequiredLeaseId(request.leaseId); this.cleanupExpiredLeases(); const owner = this.artifactLeaseOwners.get(leaseId); diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index eb42f275514..ff9b4b8be04 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -17,6 +17,7 @@ import { DAEMON_HTTP_RUN_HEADER, } from '@agent-device/contracts/daemon-http'; import type { LeaseRegistry } from '../resources/lease-registry.ts'; +import { normalizeRequiredLeaseId } from '../resources/lease-registry-scope.ts'; const ARTIFACT_DOWNLOAD_REASONS = { // The artifact stream ended at a different size than the daemon recorded; `details` gives both @@ -215,7 +216,7 @@ function admitArtifactLease( ) { throw new AppError('UNAUTHORIZED', 'Artifact lease requires an admitted tenant and run'); } - const leaseId = value.trim(); + const leaseId = normalizeRequiredLeaseId(value); leaseRegistry.assertArtifactLeaseReadAdmission({ leaseId, tenantId, runId: runId.trim() }); return leaseId; } diff --git a/packages/daemon/src/server/http/http-server-install-retention.test.ts b/packages/daemon/src/server/http/http-server-install-retention.test.ts index d73197e1d7e..a9b6234d1fe 100644 --- a/packages/daemon/src/server/http/http-server-install-retention.test.ts +++ b/packages/daemon/src/server/http/http-server-install-retention.test.ts @@ -156,7 +156,11 @@ test('HTTP leased resumable upload remains readable by install dispatch', async assert.equal(wrongRun.status, 401); const preflight = await fetch(`${base}/upload/preflight`, { method: 'POST', - headers: { ...headers, 'content-type': 'application/json' }, + headers: { + ...headers, + 'x-agent-device-lease-id': lease.leaseId.toUpperCase(), + 'content-type': 'application/json', + }, body: JSON.stringify({ uploadAttemptId: randomUUID(), sha256: createHash('sha256').update('leased-apk').digest('hex'), 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 4d4ba93daf0..ee22c7cd5df 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 @@ -932,11 +932,21 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite expect(path.dirname(secondPath)).toBe( path.join(sessionStore.resolveSessionDir('tenant-b:capture'), 'test-artifacts'), ); + const inventory = await fetch(`${baseUrl}/artifacts`, { + headers: { + authorization: 'Bearer test-token', + 'x-tenant': 'tenant-b', + 'x-agent-device-lease-id': leases.get('tenant-b')!.leaseId.toUpperCase(), + 'x-agent-device-run-id': 'tenant-b', + }, + }); + expect(inventory.status).toBe(200); + expect(JSON.stringify(await inventory.json())).toContain(second.artifactId); const download = await fetch(`${baseUrl}/artifacts/${second.artifactId}`, { headers: { authorization: 'Bearer test-token', 'x-tenant': 'tenant-b', - 'x-agent-device-lease-id': leases.get('tenant-b')!.leaseId, + 'x-agent-device-lease-id': leases.get('tenant-b')!.leaseId.toUpperCase(), 'x-agent-device-run-id': 'tenant-b', }, }); diff --git a/packages/daemon/src/server/upload-http.ts b/packages/daemon/src/server/upload-http.ts index b31bc44370f..382a6f41d05 100644 --- a/packages/daemon/src/server/upload-http.ts +++ b/packages/daemon/src/server/upload-http.ts @@ -18,6 +18,7 @@ import { DAEMON_HTTP_RUN_HEADER, } from '@agent-device/contracts/daemon-http'; import type { LeaseRegistry } from '../resources/lease-registry.ts'; +import { normalizeRequiredLeaseId } from '../resources/lease-registry-scope.ts'; const DIRECT_UPLOAD_PATH_PREFIX = '/upload/direct/'; @@ -159,7 +160,7 @@ function admitUploadLease( 'Upload lease requires an admitted tenant, run and lease registry', ); } - const leaseId = header.trim(); + const leaseId = normalizeRequiredLeaseId(header); leaseRegistry.assertLeaseReadAdmission({ leaseId, tenantId, runId: runId.trim() }); return leaseId; } diff --git a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts index 8967dc51968..aa392f54918 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts @@ -35,7 +35,7 @@ test('session name alone gives a typed error for leased artifact inventory', asy (error: unknown) => error instanceof AppError && error.code === 'INVALID_ARGS' && - error.message.includes('--lease-id'), + error.details?.reason === 'ARTIFACT_LEASE_ID_REQUIRED', ); assert.deepEqual(world.providerCalls, []); }); @@ -174,6 +174,18 @@ test('artifacts admits a released cloud lease without a provider session ID', as test('artifacts lists an owned active and recently released provider session', async () => { const world = createWorld(); const lease = await allocateLease(world, 'tenant-a', 'run-a'); + world.sessionStore.publish( + 'artifact-test', + makeAndroidSession('artifact-test', { + lease: { + leaseId: lease.leaseId, + tenantId: lease.tenantId, + runId: lease.runId, + leaseBackend: lease.backend, + leaseProvider: lease.leaseProvider, + }, + }), + ); const active = await listArtifacts(world, { tenantId: 'tenant-a', diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index 03d70db4ef8..e067021724d 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -65,6 +65,8 @@ const LEASE_HANDLER_REASONS = { providerSessionNotOwned: { reason: 'PROVIDER_SESSION_NOT_OWNED' }, // Provider-session artifact lookup needs the run that owns the session. providerSessionRunRequired: { reason: 'PROVIDER_SESSION_RUN_REQUIRED' }, + // A leased daemon artifact lookup must name the lease that produced it. + artifactLeaseIdRequired: { reason: 'ARTIFACT_LEASE_ID_REQUIRED' }, // The requested cloud artifact lease is outside the caller's ownership scope. artifactLeaseNotOwned: { reason: 'ARTIFACT_LEASE_NOT_OWNED' }, // Only the host administrator releases a `macos-app` lease. @@ -101,8 +103,13 @@ export async function handleLeaseCommands(args: LeaseHandlerArgs): Promise> = { * cannot change what a skewed peer parses. */ export const WIRE_CLOSURE_WAIVERS: Readonly> = { + 'packages/daemon/src/resources/lease-registry.ts#LeaseRegistry': + 'Server-local lease authority injected into HTTP handlers. The registry object never crosses the wire; the handlers listed in the ledger own admission and response behavior.', 'packages/kernel/src/source-value.ts#HostEnvironment': "The client process's own environment and working directory, read to resolve local paths. It never crosses the wire; only the paths it helps resolve do, and those are digested through the declarations that use them.", 'packages/kernel/src/errors.ts#AppError': diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index f33634a6690..5f924eedded 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -1,5 +1,5 @@ { - "protocolVersion": 3, + "protocolVersion": 4, "declarations": { "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_BASE_PATH": "sha256:a1ada25c6f90d9c69c8c836538e8882547bf239559f7c1accacd0654355802dd", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_TENANT_HEADER": "sha256:ed49119d232500885f014ac73f6123d298d404c6c176abdae59cf324825927e5", @@ -78,8 +78,8 @@ "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:bf9ca0ecb9dc00f18d0bf4acab30d544d680246b8cdacbc50f684db182b6f23b", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpAuthorizer": "sha256:1b2702a929ca9170db2ca97c08e3ab67e17edb3ee75325a576c4c1b9cdbebb44", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpRoute": "sha256:e63c4581ccde668913914149c9092d16ecf8a5cbd7ab33c6eb8617e77fc1015e", - "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:9f72097ae602ee8040c7a42104d682e4ea6b4c5999aa653a72b3cf47d4f5b81d", - "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory": "sha256:651806eabbd78d51d4bb21dab0b8a28847fb6087941f73dee735c24d9c2a79fa", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:aa76d3381f7ccb1ea5326e2beda2e97492375ab051513f7365acbc0fb91e306c", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory": "sha256:da4b9a6c2e84bef48aaeac74e8e8d87c0bb19ee4c7ac11f34029e178ef9c1caf", "packages/daemon/src/server/downloadable-artifact-http.ts#readArtifactId": "sha256:3472ee52d951fdf7ef00ee500298602c68f0e1e3b8c44ff51b09981efabf348c", "packages/daemon/src/server/downloadable-artifact-http.ts#readRequestPathname": "sha256:6b3a49c72365cf7da4552abef59862c073461f746025e28d409048815dd586f2", "packages/daemon/src/server/downloadable-artifact-http.ts#resolveDownloadableArtifactHttpRoute": "sha256:9fcdc9619e8d378e8f04ef7b3584863af446e855702ddce83a16ec194a6d98af", @@ -101,7 +101,7 @@ "packages/daemon-contracts/src/request-progress-protocol.ts#serializeDaemonResponseEnvelope": "sha256:bc2b651df28446c51d8b92b7fd47a3bced9fade9ae50e2cd73e453ba89fd33b5", "packages/daemon-contracts/src/request-progress-protocol.ts#serializeDaemonRpcResponseEnvelope": "sha256:e244291bef44cedfb59ad07c45337bb8e5fdde00b712ebdf5ca9627f6355f111", "packages/daemon-contracts/src/request-progress-protocol.ts#shouldStreamRequestProgress": "sha256:cf7b26ccea9cd5c33c93477f783a3bdb9a1b0ce629da8b77fef0d49d6c6f4112", - "packages/daemon/src/server/resumable-upload.ts#BeginResumableUploadOptions": "sha256:ef804e321b8cd1f23a51566919fc0cda79c1b0ef82aeceed54ce3f2a398d8457", + "packages/daemon/src/server/resumable-upload.ts#BeginResumableUploadOptions": "sha256:2c5c469051fa97c7d6d6931b27a5c18dc4288718383516c66cd3879b1564b05b", "packages/daemon/src/server/http/http-rpc-methods.ts#COMMAND_RPC_METHODS": "sha256:4b675a84ef475c2fe0e864457c254c2e888de942e4ae428d5b3e1fa72101e97b", "packages/daemon/src/server/http/http-authorization.ts#HttpAuthDecision": "sha256:a7fc2a91f998ce62b107b14dd9b6fcf1f4ca5abe2e30d4df5a0896d56a0a52f8", "packages/daemon/src/server/http/http-authorization.ts#HttpAuthHook": "sha256:1ed0ba84708f040787d81d7f546c8b6e0cb8c319625d6c654ece3819be2de8e6", @@ -139,10 +139,10 @@ "packages/daemon/src/server/upload-http.ts#UploadHttpRoute": "sha256:3fee66976292bedc9587e266f7f584ff27574e939329bb3ecb98f100c4c54b2e", "packages/daemon/src/server/upload-http.ts#UploadPreflightBody": "sha256:05b5e8bd75887f821c44cd54b027f09de1ea08c6e41c44d4dc9ec7cf09fc1ea5", "packages/daemon/src/server/upload-http.ts#buildUploadTicketAuthHeaders": "sha256:04d65207c440424257ea04a86fa50fd27f5e6b62e8cede884d9af1db4fb86475", - "packages/daemon/src/server/upload-http.ts#handleResumableUpload": "sha256:294c54016839b3a98ad9a01b2201dcad662af7a4caf581ae3976fa646d435b35", - "packages/daemon/src/server/upload-http.ts#handleUpload": "sha256:9d89e442631e057467c2543be81150caa39f389bc582c6d69628a9dad52af75b", - "packages/daemon/src/server/upload-http.ts#handleUploadFinalize": "sha256:2fc9137a076fba30139ed2eb8109560552e57a9efa81f6478fc87506c66dffef", - "packages/daemon/src/server/upload-http.ts#handleUploadPreflight": "sha256:c17b3a0576819308720d55e8b6b14507fa6f70cb884dc7e1f3bac4e6151c8f74", + "packages/daemon/src/server/upload-http.ts#handleResumableUpload": "sha256:d187993ad77280476bd3cbec2269a995f35e5f4284c5c1bec384ecf1012fedb2", + "packages/daemon/src/server/upload-http.ts#handleUpload": "sha256:0f9e4ee9fad26c471393584da829fabdb0a88a697202379b9318fc3fa3eaeb71", + "packages/daemon/src/server/upload-http.ts#handleUploadFinalize": "sha256:8f801ed381173e9ddd4cf16b6d889feb3a11aef565374e0ee2fdb0dc300092a4", + "packages/daemon/src/server/upload-http.ts#handleUploadPreflight": "sha256:f5203a0767ac6f0387c7138c7d61bf98fb1c3f1cf9994cb950ce7f6380e480a2", "packages/daemon/src/server/upload-http.ts#readUploadFinalizeBody": "sha256:076298afa73d7e498a964b6c48d823de1cc8b15e9e971d0a22b7e6c3fd98d685", "packages/daemon/src/server/upload-http.ts#readUploadPreflightBody": "sha256:2e56302178b75d9a6f5424f01dfc46551dca2056ba06a43e48ae09ec528956b6", "packages/contracts/src/daemon-http.ts#resolveHttpRequestBaseUrl": "sha256:6ef76a849a7c61c7ae035cbf162dd1dfac3631f6a2df421560f19f798853e50f", @@ -151,7 +151,7 @@ "packages/contracts/src/daemon-http.ts#containsInvalidHttpUrlCharacter": "sha256:008c59ed9aa9338f7259877253783446762e603dad6dd91948a8aafc5eee37e0", "packages/daemon/src/server/upload-http.ts#resolveUploadHttpRoute": "sha256:d744044d036a46221c3b8220179cc30e1e66b8619a4e5cd3f7dd5f8582817aba", "packages/daemon/src/server/upload-http.ts#sendJson": "sha256:c2317b4b14a10731684c9160038005965856150f05f8923765a3fa833d2ecae9", - "packages/daemon/src/server/upload-http.ts#sendUploadedArtifactResponse": "sha256:8a8873eb6437a32f7045c87a7b16226a48ff7fc4d61c5de459809e2558758768", + "packages/daemon/src/server/upload-http.ts#sendUploadedArtifactResponse": "sha256:02d2e73fac5cf94cf5d7a019f2e507a550b82d2378bb71195fcb222d459b8a81", "packages/remote/src/artifact-download.ts#RemoteArtifactDownload": "sha256:d3eeaf9a072123004d868a0261067456793a7121836d6f6b354fcd65aa0826bd", "packages/remote/src/artifact-download.ts#downloadRemoteArtifactFromUrl": "sha256:4772ec65900be31f0ac6fb889967a9f35a4a565f6bb87e72458e3ab6e54cc941", "packages/remote/src/daemon-artifacts.ts#DaemonArtifactEndpoint": "sha256:45226717ac52c0af2a62f74e91549582d95f4a4abc49be87989e026291a88c82", @@ -172,15 +172,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:ca3fa667ab2a60fb8af095bddeacb4875dcd2d12db783585a0fb045db35da212", + "packages/remote/src/upload-client.ts#finalizeDirectUpload": "sha256:e3a005b87fc51f74187a761ebdcccacc316e8de1a9fcd23e25529bb5312dade3", "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:5689da0c0cd18d0293e5bb05ddc0d8a07d1bca9ab1d94f8ca185b03bc5b8d758", - "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:3080e4ac4e0d6f46345a3588a88c81152ac74628dd6c03328161188d383a97ff", + "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:4b35726208b30b16d9cbcf268aae8d6d48b4afecfbb9c5ea25ec950f85e559a8", "packages/remote/src/upload-client.ts#shouldRetryDirectUpload": "sha256:29059f076ff7f2b9540ad15408be48792b2d63a601ef2b9fb2d54f5576d49bbd", - "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:405c614f566f1385ac8ef7eebdc064fe93914241aefd46ca5b855f889c4eca83", - "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:93a36a9d3dea88064569517f3cdc34f27b33df6bf5f0c0ecc9efc29b47f24b77", - "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:1546c696134b47bfaaaffcf95deb176cccdce243818b658ae0494dafb57fafb6", + "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:54401ef57b2f6aaa3f904867278936affc47d056dfdfad48bbb93fb3eb852ac7", + "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:5d3f1677bbe8689c5572f1af40fd7fd401bc8f0c7dd191a6b7e21e6a9906cbd2", + "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:5ca45f3ed66b3457354f6e510ae4d22cd8132de37ae9792b0c9dabfb4f7ab635", "packages/remote/src/upload-stream.ts#MAX_UPLOAD_REDIRECTS": "sha256:12ff46dfe33a1dce95bdb79c90c17a3ba4f3919e7dc4b3a1b04590fff430f79f", "packages/remote/src/upload-stream.ts#UploadStreamResponse": "sha256:724e284c2a6bd7b4b3a49b1d8c61c8923d6cc24777c3d76224a69d190e56adce", "packages/remote/src/upload-stream.ts#buildUploadRequestHeaders": "sha256:827576b13a9f3e6cea445119a6a29b2ac5eaa23b66436cf810b2d09765c82a4c", @@ -256,7 +256,7 @@ "packages/remote/src/artifact-download.ts#RemoteArtifactRequest": "sha256:6cce66499f34bb18139917df592e554395936964025089024d6c6f67e4fa4b98", "packages/remote/src/artifact-download.ts#RemoteArtifactFetch": "sha256:e83939ec48a66917df9ec84becf53b6ca3c8115cfdada10731046381ac9e32c1", "packages/remote/src/artifact-download.ts#fetchRemoteArtifactFromUrl": "sha256:de6e71abdc758f760beffba0dc260473f88a8c60b13540b9c14d39f1a3d5e3a1", - "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:cafb5fd5838819719b2fac62c5e108276dd800a58b4614462d138cf1ed2f7d6e", + "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:720fa8c81aa6a91caf545b8c67ea97e79cc1562e6c8a810723c79040cc8413a3", "packages/daemon-client/src/daemon-client-checked-rpc.ts#isCheckedRpcOutcomeResponse": "sha256:75fb9f3444a3f8f4a762811ba7cbe02d92a39ed4e55483ea0cf7f029e5720a3e", "packages/daemon-client/src/daemon-client-checked-rpc.ts#CheckedRpcOutcome": "sha256:8aa7e58307417460bb54938f6bbbd340254e14ffbbaf2093272996909592f7be", "packages/daemon-client/src/daemon-client-checked-rpc.ts#ReadHealthLink": "sha256:86a9e6f1ebdaecca3ddaa16081c221321c01c684b70197961ecd71a3f54a464f", @@ -316,16 +316,6 @@ "digest": "sha256:3472ee52d951fdf7ef00ee500298602c68f0e1e3b8c44ff51b09981efabf348c", "rationale": "Inlined `decodeURIComponent`+catch replaced by the shared `decodeUriSegment` (packages/daemon/src/server/http-request-target.ts), which is listed and byte-identical in behaviour: the same artifact ids decode, and an undecodable id still resolves to the empty id the route rejects." }, - { - "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", - "digest": "sha256:9f72097ae602ee8040c7a42104d682e4ea6b4c5999aa653a72b3cf47d4f5b81d", - "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. The handler waits for file readiness before setting headers and starting the pipeline, so open errors use the existing JSON error response. Setup errors clear artifact-only headers first. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete streaming reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field. Implementation-only follow-up to #4165 under ADR 0006: response close cancels artifact preparation and streaming through an internal AbortSignal. Shared builds continue for other downloads. The existing streamed failure helper now owns the same pre-header JSON error and post-header connection destruction. Successful status, headers, bytes, routes and authorization retain their existing contracts; disconnected clients receive no new payload. A response that has finished writing is not cancelled by its normal close event, so successful pipeline completion keeps its existing success semantics. Caller cancellation is normalized to the existing request_canceled error instead of forwarding caller-supplied reasons. Artifact expiry and download deadlines keep their existing reasons. The shared HTTP disconnect helper preserves typed cancellation on aborted requests and unfinished response closes. Directory preparation counts inventory and download callers together, so one disconnected download cannot abort an inventory caller's build; successful response fields and authorization stay unchanged. The size-mismatch failure reads artifact_size_mismatch from a ReasonTable row; the published reason value is unchanged." - }, - { - "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", - "digest": "sha256:651806eabbd78d51d4bb21dab0b8a28847fb6087941f73dee735c24d9c2a79fa", - "rationale": "#3753 threads the daemon runtime's host environment into the same archive spawn from the inventory route. The JSON body it writes and the error path are unchanged; no peer-visible field moves." - }, { "declaration": "packages/kernel/src/errors.ts#normalizeError", "digest": "sha256:5d9f906fd326676b4c3095cd6bd675c784cb26f36f4b8344a108cf5f7628f9dc", @@ -481,21 +471,6 @@ "digest": "sha256:6f68c317e4c0fe5de008ec1fe5e7e030a9d298ad4a7dfd561db933d22e12ae9e", "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)." }, - { - "declaration": "packages/remote/src/upload-client.ts#uploadDirectArtifact", - "digest": "sha256:93a36a9d3dea88064569517f3cdc34f27b33df6bf5f0c0ecc9efc29b47f24b77", - "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." - }, - { - "declaration": "packages/remote/src/upload-client.ts#tryDirectUploadWithResume", - "digest": "sha256:405c614f566f1385ac8ef7eebdc064fe93914241aefd46ca5b855f889c4eca83", - "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 client environment is now passed through to the retry preflight, which judges the ticket URL locally; no request changes." - }, - { - "declaration": "packages/remote/src/upload-client.ts#uploadLegacyArtifact", - "digest": "sha256:1546c696134b47bfaaaffcf95deb176cccdce243818b658ae0494dafb57fafb6", - "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." - }, { "declaration": "packages/daemon-client/src/daemon-client-progress.ts#shouldReadDaemonProgressStream", "digest": "sha256:27ac0a5299324aab39fa2c4fe0e0d32b1eb1515df47c7f4aa75a75d66b8b5a3e", @@ -556,16 +531,6 @@ "digest": "sha256:5689da0c0cd18d0293e5bb05ddc0d8a07d1bca9ab1d94f8ca185b03bc5b8d758", "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." }, - { - "declaration": "packages/remote/src/upload-client.ts#requestUploadPreflight", - "digest": "sha256:3080e4ac4e0d6f46345a3588a88c81152ac74628dd6c03328161188d383a97ff", - "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 client now also drops a direct-upload ticket whose URL is plain http to a host that is not loopback, unless the operator's environment overrides it, and takes the legacy upload route a released daemon already serves when it hands out no usable ticket. The preflight request and response shapes are unchanged." - }, - { - "declaration": "packages/remote/src/upload-client.ts#finalizeDirectUpload", - "digest": "sha256:ca3fa667ab2a60fb8af095bddeacb4875dcd2d12db783585a0fb045db35da212", - "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." - }, { "declaration": "packages/daemon/src/server/http/http-rpc-methods.ts#toInstallFromSourceDaemonRequest", "digest": "sha256:071c53e7bd8e553cb9df820961294ed4d1e2e385053485364d895cb1777e9429", @@ -601,31 +566,6 @@ "digest": "sha256:d744044d036a46221c3b8220179cc30e1e66b8619a4e5cd3f7dd5f8582817aba", "rationale": "#4434 accepts optional query components on the existing POST upload, preflight and finalize routes. Existing query-free paths and methods resolve identically; direct-upload IDs still exclude the query. This broadens accepted request targets without removing a route or changing any response framing under ADR 0006." }, - { - "declaration": "packages/daemon/src/server/upload-http.ts#handleUploadPreflight", - "digest": "sha256:c17b3a0576819308720d55e8b6b14507fa6f70cb884dc7e1f3bac4e6151c8f74", - "rationale": "#4441 adds finite server-side ingress budgets to the existing upload routes: a 600-second aggregate and a 120-second body-inactivity ceiling admitted per request, renewed only after body bytes pass the bounded JSON reader or file writer, and stopped at body completion so post-body work observes just the aggregate, plus explicit daemon listener ceilings: a 30 s header ceiling and a request ceiling derived from the header ceiling, the connections-checking interval, the upload aggregate and a margin. Routes, methods, request fields, response fields, status codes (including the 308 resume framing) and ticket/artifact payloads are unchanged, so a released peer parses and answers exactly as before. The route also passes its ingress signal to the authorizer, so a held auth hook stops at the same deadline or disconnect; the request, response and status framing are unchanged. Expiry is also checked on the monotonic clock before a ticket is created, a chunk offset is committed and an artifact is registered, and an expired exchange ends with the same typed error answer; status codes and body shapes are unchanged. Every answer, ticket publish and registration now commits through the request's single commit gate; a newly created preflight ticket is removed when its answer is refused. Status codes, headers and bodies are unchanged." - }, - { - "declaration": "packages/daemon/src/server/upload-http.ts#handleUpload", - "digest": "sha256:9d89e442631e057467c2543be81150caa39f389bc582c6d69628a9dad52af75b", - "rationale": "#4441 bounds the single-shot upload with the same finite ingress budgets and threads the request's ingress signal into the owned post-body hash and extraction; the route, headers, response artifact framing and status codes are unchanged, so a released peer interoperates as before. The route also passes its ingress signal to the authorizer, so a held auth hook stops at the same deadline or disconnect; the request, response and status framing are unchanged. Expiry is also checked on the monotonic clock before a ticket is created, a chunk offset is committed and an artifact is registered, and an expired exchange ends with the same typed error answer; status codes and body shapes are unchanged. Every answer, ticket publish and registration now commits through the request's single commit gate; a newly created preflight ticket is removed when its answer is refused. Status codes, headers and bodies are unchanged." - }, - { - "declaration": "packages/daemon/src/server/upload-http.ts#handleResumableUpload", - "digest": "sha256:294c54016839b3a98ad9a01b2201dcad662af7a4caf581ae3976fa646d435b35", - "rationale": "#4441 bounds the direct chunk receive with the same finite ingress budgets and renews the ticket idle timer on accepted bytes; the 308 range/x-upload-offset framing and completion status are unchanged, so a released client resumes exactly as before. The route also passes its ingress signal to the authorizer, so a held auth hook stops at the same deadline or disconnect; the request, response and status framing are unchanged. Expiry is also checked on the monotonic clock before a ticket is created, a chunk offset is committed and an artifact is registered, and an expired exchange ends with the same typed error answer; status codes and body shapes are unchanged. Every answer, ticket publish and registration now commits through the request's single commit gate; a newly created preflight ticket is removed when its answer is refused. Status codes, headers and bodies are unchanged." - }, - { - "declaration": "packages/daemon/src/server/upload-http.ts#handleUploadFinalize", - "digest": "sha256:2fc9137a076fba30139ed2eb8109560552e57a9efa81f6478fc87506c66dffef", - "rationale": "#4441 bounds the finalize request with the same finite ingress budgets, renews inactivity on JSON bytes accepted by the bounded reader, and passes the request's ingress signal through the serialized admission into the post-body hash, the owned extraction stream and the artifact registration boundary; the request body, response artifact framing and status codes are unchanged, so a released peer interoperates as before. The route also passes its ingress signal to the authorizer, so a held auth hook stops at the same deadline or disconnect; the request, response and status framing are unchanged. Expiry is also checked on the monotonic clock before a ticket is created, a chunk offset is committed and an artifact is registered, and an expired exchange ends with the same typed error answer; status codes and body shapes are unchanged. Every answer, ticket publish and registration now commits through the request's single commit gate; a newly created preflight ticket is removed when its answer is refused. Status codes, headers and bodies are unchanged." - }, - { - "declaration": "packages/daemon/src/server/upload-http.ts#sendUploadedArtifactResponse", - "digest": "sha256:8a8873eb6437a32f7045c87a7b16226a48ff7fc4d61c5de459809e2558758768", - "rationale": "#4441 removes an unregistered upload directory if ingress is canceled before the registry takes ownership. Successful responses retain the same status and uploadId envelope. Expiry is also checked on the monotonic clock before a ticket is created, a chunk offset is committed and an artifact is registered, and an expired exchange ends with the same typed error answer; status codes and body shapes are unchanged. Every answer, ticket publish and registration now commits through the request's single commit gate; a newly created preflight ticket is removed when its answer is refused. Status codes, headers and bodies are unchanged." - }, { "declaration": "packages/kernel/src/contracts.ts#DaemonArtifact", "digest": "sha256:77dee23e48dc77febb33efadc85377cbbcd137389ae7b33e93ba31670565fdf6", diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index ca6603ab076..fe200bd3a61 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -826,6 +826,7 @@ These reasons can come from more than one command. | `provider-credentials-changed` | The running daemon holds different provider credentials than this shell; stop the daemon and rerun. | | `PROVIDER_SESSION_NOT_OWNED` | The provider session belongs to another tenant. | | `PROVIDER_SESSION_RUN_REQUIRED` | Provider-session artifact lookup needs the run that owns the session. | +| `ARTIFACT_LEASE_ID_REQUIRED` | Leased daemon artifact lookup needs the lease that produced the artifacts. | | `ARTIFACT_LEASE_NOT_OWNED` | The requested cloud artifact lease is outside the caller's ownership scope. | | `MACOS_APP_LEASE_HOST_OWNED` | Only the host administrator releases a `macos-app` lease. | | `MACOS_APP_LEASE_HOST_ALLOCATED` | Only the host administrator allocates a `macos-app` lease. | From afbd8e226e522a0de105fbf13d6453fc37f332b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 12:08:49 +0100 Subject: [PATCH 11/35] fix: align protocol fixtures and generated reasons --- .../daemon-client-checked-rpc-connect-recovery.test.ts | 6 +++++- .../src/__tests__/daemon-client-checked-rpc.test.ts | 4 ++-- website/docs/docs/error-reasons.md | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts index ff5455d08d8..a313fa8c68b 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts @@ -7,6 +7,7 @@ import http from 'node:http'; import { EventEmitter } from 'node:events'; import { afterEach, test, vi } from 'vitest'; import { isRequestCanceledError } from '@agent-device/kernel/errors'; +import { DAEMON_RPC_PROTOCOL_VERSION } from '@agent-device/contracts/daemon-http'; import { sendToDaemon } from '../index.ts'; type Call = { method: string; path: string; at: number }; @@ -24,7 +25,10 @@ function fakeResponse(): EventEmitter { * The first checked POST hangs before its socket connects. `/health` answers with `healthStatus` * (and an instance ID, so a usable answer is cached); every other request answers. */ -function firstCheckedConnectHangs(healthStatus = 200, healthProtocol = 3): Call[] { +function firstCheckedConnectHangs( + healthStatus = 200, + healthProtocol = DAEMON_RPC_PROTOCOL_VERSION, +): Call[] { const calls: Call[] = []; vi.spyOn(http, 'request').mockImplementation((( options: { method?: string; path?: string }, diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts index 11d760bf211..56c90ca850b 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts @@ -48,7 +48,7 @@ async function remoteDaemon(answer: Answer = OK_ANSWER, pinned = false) { JSON.stringify({ ok: true, service: 'agent-device-daemon', - rpcProtocolVersion: 3, + rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, ...(pinned ? { instanceId: 'daemon-1' } : {}), }), ); @@ -467,7 +467,7 @@ test('after a stale-instance retry onto a daemon with no instance ID, the next o JSON.stringify({ ok: true, service: 'agent-device-daemon', - rpcProtocolVersion: 3, + rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, ...(replaced ? {} : { instanceId: 'old' }), }), ); diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index fe200bd3a61..85afeb92362 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -826,7 +826,7 @@ These reasons can come from more than one command. | `provider-credentials-changed` | The running daemon holds different provider credentials than this shell; stop the daemon and rerun. | | `PROVIDER_SESSION_NOT_OWNED` | The provider session belongs to another tenant. | | `PROVIDER_SESSION_RUN_REQUIRED` | Provider-session artifact lookup needs the run that owns the session. | -| `ARTIFACT_LEASE_ID_REQUIRED` | Leased daemon artifact lookup needs the lease that produced the artifacts. | +| `ARTIFACT_LEASE_ID_REQUIRED` | A leased daemon artifact lookup must name the lease that produced it. | | `ARTIFACT_LEASE_NOT_OWNED` | The requested cloud artifact lease is outside the caller's ownership scope. | | `MACOS_APP_LEASE_HOST_OWNED` | Only the host administrator releases a `macos-app` lease. | | `MACOS_APP_LEASE_HOST_ALLOCATED` | Only the host administrator allocates a `macos-app` lease. | From 6b702ac0594d3670f2ef35d9d36517b909c9ec57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 12:56:43 +0100 Subject: [PATCH 12/35] fix: canonicalize lease IDs across artifact owners --- packages/contracts/src/lease-scope.ts | 3 ++- .../src/resources/artifact-tracking.test.ts | 16 +++++++++++----- .../daemon/src/resources/artifact-tracking.ts | 18 ++++++++++++------ .../materialized-path-registry.test.ts | 9 +++++++-- .../handlers/__tests__/lease-artifacts.test.ts | 1 + .../src/sessions/materialized-path-registry.ts | 5 +++-- 6 files changed, 36 insertions(+), 16 deletions(-) diff --git a/packages/contracts/src/lease-scope.ts b/packages/contracts/src/lease-scope.ts index bbf7320904f..14a43a6b372 100644 --- a/packages/contracts/src/lease-scope.ts +++ b/packages/contracts/src/lease-scope.ts @@ -95,10 +95,11 @@ type LeaseOptionsLike = { }; export function leaseScopeFromRequest(req: LeaseRequestLike): LeaseScope { + const leaseId = req.meta?.leaseId ?? readFlagString(req.flags, 'leaseId'); return stripUndefined({ tenantId: req.meta?.tenantId ?? readFlagString(req.flags, 'tenant'), runId: req.meta?.runId ?? readFlagString(req.flags, 'runId'), - leaseId: req.meta?.leaseId ?? readFlagString(req.flags, 'leaseId'), + leaseId: normalizeLeaseId(leaseId) ?? leaseId, leaseTtlMs: req.meta?.leaseTtlMs, leaseRetainOnClose: req.meta?.leaseRetainOnClose, leaseBackend: req.meta?.leaseBackend, diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index 6b897e9bd60..549a6e27117 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -585,6 +585,7 @@ test('disposing a runtime removes the temporary files it still tracks', () => { }); test('uploads stay bound to their producing lease', () => { + const leaseId = 'ABCDEF0123456789ABCDEF0123456789'; const root = mkdtempForTestSync('agent-device-upload-lease-'); const artifactPath = path.join(root, 'payload'); fs.writeFileSync(artifactPath, 'payload'); @@ -594,7 +595,7 @@ test('uploads stay bound to their producing lease', () => { artifactPath, tempDir: root, tenantId: 'tenant-a', - leaseId: 'lease-a', + leaseId, }), ); @@ -603,12 +604,15 @@ test('uploads stay bound to their producing lease', () => { /different lease/, ); } - expect(runtime.run(() => prepareUploadedArtifact(id, 'tenant-a', 'lease-a'))).toBe(artifactPath); + expect(runtime.run(() => prepareUploadedArtifact(id, 'tenant-a', leaseId.toLowerCase()))).toBe( + artifactPath, + ); runtime.run(() => cleanupUploadedArtifact(id)); runtime.dispose(); }); test('a retained downloadable artifact requires its producing lease', async () => { + const leaseId = 'ABCDEF0123456789ABCDEF0123456789'; const root = mkdtempForTestSync('agent-device-download-lease-'); const artifactPath = path.join(root, 'recording.mp4'); fs.writeFileSync(artifactPath, 'video'); @@ -617,7 +621,7 @@ test('a retained downloadable artifact requires its producing lease', async () = trackDownloadableArtifact({ artifactPath, tenantId: 'tenant-a', - leaseId: 'lease-a', + leaseId, artifactType: 'screen-recording', }), ); @@ -626,7 +630,9 @@ test('a retained downloadable artifact requires its producing lease', async () = await runtime.run(() => listDownloadableArtifacts('tenant-a', process.env, 'lease-b')), ).toEqual([]); expect( - await runtime.run(() => listDownloadableArtifacts('tenant-a', process.env, 'lease-a')), + await runtime.run(() => + listDownloadableArtifacts('tenant-a', process.env, leaseId.toLowerCase()), + ), ).toHaveLength(1); await expect( runtime.run(() => @@ -634,7 +640,7 @@ test('a retained downloadable artifact requires its producing lease', async () = ), ).rejects.toThrow(/different lease/); const opened = await runtime.run(() => - openDownloadableArtifact(id, 'tenant-a', process.env, undefined, 'lease-a'), + openDownloadableArtifact(id, 'tenant-a', process.env, undefined, leaseId.toLowerCase()), ); expect(await buffer(opened.stream)).toEqual(Buffer.from('video')); opened.release(); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 8b275c11582..79981f8df27 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -7,6 +7,7 @@ import { AppError, createRequestCanceledError } from '@agent-device/kernel/error import type { DaemonArtifactType } from '@agent-device/kernel/contracts'; import type { DeviceRotation } from '@agent-device/contracts/device'; import type { DaemonArtifactInventoryEntry } from '@agent-device/contracts/observability'; +import { normalizeLeaseId } from '@agent-device/contracts/lease-scope'; import type { PackedGzipTar } from '@agent-device/host-kit/gzip-tar'; import { expiredTenantOwnedEntryError, @@ -126,7 +127,8 @@ export type OpenedDownloadableArtifact = PreparedDownloadableArtifact & { * download. */ export function trackDownloadableArtifact(params: DownloadableArtifactRegistration): string { - const existingId = findTrackedArtifactId(params.artifactPath, params.tenantId, params.leaseId); + const leaseId = normalizeLeaseId(params.leaseId) ?? params.leaseId; + const existingId = findTrackedArtifactId(params.artifactPath, params.tenantId, leaseId); if (existingId) return existingId; const artifactId = crypto.randomUUID(); const createdAt = Date.now(); @@ -143,7 +145,7 @@ export function trackDownloadableArtifact(params: DownloadableArtifactRegistrati pendingArtifacts().set(artifactId, { artifactPath: params.artifactPath, tenantId: params.tenantId, - leaseId: params.leaseId, + leaseId, artifactType: params.artifactType, fileName: params.fileName, ...(params.displayRotation !== undefined ? { displayRotation: params.displayRotation } : {}), @@ -308,7 +310,7 @@ function readDownloadableArtifactEntry( if (entry.cleanupRequested) { throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } - if (entry.leaseId !== leaseId) { + if (entry.leaseId !== (normalizeLeaseId(leaseId) ?? leaseId)) { throw new AppError('UNAUTHORIZED', 'Artifact belongs to a different lease'); } let stat: fs.Stats; @@ -451,7 +453,11 @@ function canReadArtifact( tenantId: string | undefined, leaseId?: string, ): boolean { - return !entry.cleanupRequested && entry.tenantId === tenantId && entry.leaseId === leaseId; + return ( + !entry.cleanupRequested && + entry.tenantId === tenantId && + entry.leaseId === (normalizeLeaseId(leaseId) ?? leaseId) + ); } function safeArtifactFilename(fileName: string | undefined, fallback: string): string { @@ -544,7 +550,7 @@ export function trackUploadedArtifact(params: { artifactPath: params.artifactPath, tempDir: params.tempDir, tenantId: params.tenantId, - leaseId: params.leaseId, + leaseId: normalizeLeaseId(params.leaseId) ?? params.leaseId, timer, }); return uploadId; @@ -561,7 +567,7 @@ export function prepareUploadedArtifact( tenantId, UPLOADED_ARTIFACT_RESOURCE, ); - if (entry.leaseId !== leaseId) { + if (entry.leaseId !== (normalizeLeaseId(leaseId) ?? leaseId)) { throw new AppError('UNAUTHORIZED', 'Uploaded artifact belongs to a different lease'); } clearTimeout(entry.timer); diff --git a/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts b/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts index 006a48b0f66..2452a3260bb 100644 --- a/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts +++ b/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts @@ -130,13 +130,14 @@ test('cleanup of tenant-owned materialization rejects other tenants', async () = }); test('same tenant cannot release materialized paths from another lease', async () => { + const leaseId = 'ABCDEF0123456789ABCDEF0123456789'; const tempRoot = mkdtempForTestSync('agent-device-retained-lease-'); const appPath = path.join(tempRoot, 'Sample.app'); fs.mkdirSync(appPath, { recursive: true }); const retained = await retainMaterializedPaths({ installablePath: appPath, tenantId: 'tenant-a', - leaseId: 'lease-a', + leaseId, }); for (const leaseId of [undefined, 'lease-b']) { @@ -146,7 +147,11 @@ test('same tenant cannot release materialized paths from another lease', async ( ); assert.equal(fs.existsSync(retained.installablePath), true); } - await cleanupRetainedMaterializedPaths(retained.materializationId, 'tenant-a', 'lease-a'); + await cleanupRetainedMaterializedPaths( + retained.materializationId, + 'tenant-a', + leaseId.toLowerCase(), + ); assert.equal(fs.existsSync(retained.installablePath), false); fs.rmSync(tempRoot, { recursive: true, force: true }); }); diff --git a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts index aa392f54918..af44bff0762 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts @@ -190,6 +190,7 @@ test('artifacts lists an owned active and recently released provider session', a const active = await listArtifacts(world, { tenantId: 'tenant-a', runId: 'run-a', + leaseId: lease.leaseId.toUpperCase(), providerSessionId: 'session-tenant-a', }); assert.equal(active.ok, true); diff --git a/packages/daemon/src/sessions/materialized-path-registry.ts b/packages/daemon/src/sessions/materialized-path-registry.ts index 78e2f240686..b44352b081a 100644 --- a/packages/daemon/src/sessions/materialized-path-registry.ts +++ b/packages/daemon/src/sessions/materialized-path-registry.ts @@ -1,5 +1,6 @@ import { runtimeSlot } from '@agent-device/host-kit/runtime-slots'; import { AppError } from '@agent-device/kernel/errors'; +import { normalizeLeaseId } from '@agent-device/contracts/lease-scope'; import crypto from 'node:crypto'; import { rmSync } from 'node:fs'; import fs from 'node:fs/promises'; @@ -83,7 +84,7 @@ export async function retainMaterializedPaths(params: { installablePath: retainedInstallablePath, archivePath: retainedArchivePath, tenantId: params.tenantId, - leaseId: params.leaseId, + leaseId: normalizeLeaseId(params.leaseId) ?? params.leaseId, sessionName: params.sessionName, expiresAt, timer, @@ -128,7 +129,7 @@ export async function cleanupRetainedMaterializedPaths( tenantId, MATERIALIZED_PATHS_RESOURCE, ); - if (entry.leaseId !== leaseId) { + if (entry.leaseId !== (normalizeLeaseId(leaseId) ?? leaseId)) { throw new AppError('UNAUTHORIZED', 'Materialized paths belong to a different lease'); } await removeRetainedEntry(materializationId, entry); From d132b4af02895239feeeda62cd78427ca453044f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 12:59:12 +0100 Subject: [PATCH 13/35] fix: admit artifact uploads for scoped proxy leases --- .../daemon/src/resources/lease-registry.ts | 5 ++--- .../http-server-install-retention.test.ts | 22 ++++++++++++++++++- packages/daemon/src/server/upload-http.ts | 2 +- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index 6568a1a65ae..31992ba8f74 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -336,11 +336,10 @@ export class LeaseRegistry { assertLeaseScopeMatch(this.getActiveLease(scope.leaseId), scope); } - /** Admit a scoped read without filling an omitted backend with an allocation default. */ - assertLeaseReadAdmission(request: HeartbeatLeaseRequest): void { + /** Uploads prove the active lease's tenant and run; provider/device details stay on lease RPCs. */ + assertUploadLeaseAdmission(request: { leaseId: string; tenantId: string; runId: string }): void { this.cleanupExpiredLeases(); const lease = this.getActiveLease(normalizeRequiredLeaseId(request.leaseId)); - assertLeaseOwnerScope(lease, request); assertLeaseScopeMatch(lease, request); } diff --git a/packages/daemon/src/server/http/http-server-install-retention.test.ts b/packages/daemon/src/server/http/http-server-install-retention.test.ts index a9b6234d1fe..3bed1fa94ea 100644 --- a/packages/daemon/src/server/http/http-server-install-retention.test.ts +++ b/packages/daemon/src/server/http/http-server-install-retention.test.ts @@ -121,7 +121,17 @@ test('HTTP leased resumable upload remains readable by install dispatch', async const env = { ...host.env }; delete env.AGENT_DEVICE_HTTP_AUTH_HOOK; const leaseRegistry = new LeaseRegistry(); - const lease = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-a' }); + const lease = leaseRegistry.allocateLease({ + tenantId: 'tenant-a', + runId: 'run-a', + leaseProvider: 'proxy', + deviceKey: 'android:emulator:example', + clientId: 'client-a', + }); + assert.throws( + () => leaseRegistry.getLease({ leaseId: lease.leaseId, tenantId: 'tenant-a', runId: 'run-a' }), + { code: 'UNAUTHORIZED', details: { reason: 'LEASE_SCOPE_REQUIRED' } }, + ); let uploadedId: string | undefined; const server = await createDaemonHttpServer({ token: 'test-token', @@ -154,6 +164,16 @@ test('HTTP leased resumable upload remains readable by install dispatch', async body: '{}', }); assert.equal(wrongRun.status, 401); + const wrongTenant = await fetch(`${base}/upload/preflight`, { + method: 'POST', + headers: { + ...headers, + 'x-agent-device-tenant': 'tenant-b', + 'content-type': 'application/json', + }, + body: '{}', + }); + assert.equal(wrongTenant.status, 401); const preflight = await fetch(`${base}/upload/preflight`, { method: 'POST', headers: { diff --git a/packages/daemon/src/server/upload-http.ts b/packages/daemon/src/server/upload-http.ts index 382a6f41d05..4060cfae0ef 100644 --- a/packages/daemon/src/server/upload-http.ts +++ b/packages/daemon/src/server/upload-http.ts @@ -161,7 +161,7 @@ function admitUploadLease( ); } const leaseId = normalizeRequiredLeaseId(header); - leaseRegistry.assertLeaseReadAdmission({ leaseId, tenantId, runId: runId.trim() }); + leaseRegistry.assertUploadLeaseAdmission({ leaseId, tenantId, runId: runId.trim() }); return leaseId; } From 73e4c1b999656d4c1e703889976ffef3ed1934af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 13:06:42 +0100 Subject: [PATCH 14/35] fix: load lease normalization only for materialized paths --- .../src/sessions/materialized-path-registry.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/daemon/src/sessions/materialized-path-registry.ts b/packages/daemon/src/sessions/materialized-path-registry.ts index b44352b081a..8d7b06962ae 100644 --- a/packages/daemon/src/sessions/materialized-path-registry.ts +++ b/packages/daemon/src/sessions/materialized-path-registry.ts @@ -1,6 +1,5 @@ import { runtimeSlot } from '@agent-device/host-kit/runtime-slots'; import { AppError } from '@agent-device/kernel/errors'; -import { normalizeLeaseId } from '@agent-device/contracts/lease-scope'; import crypto from 'node:crypto'; import { rmSync } from 'node:fs'; import fs from 'node:fs/promises'; @@ -74,6 +73,7 @@ export async function retainMaterializedPaths(params: { const retainedArchivePath = params.archivePath ? await copyPathInto(params.archivePath, path.join(rootPath, 'archive')) : undefined; + const leaseId = await canonicalLeaseId(params.leaseId); const materializationId = crypto.randomUUID(); const expiresAt = Date.now() + ttlMs; const timer = setTimeout(() => { @@ -84,7 +84,7 @@ export async function retainMaterializedPaths(params: { installablePath: retainedInstallablePath, archivePath: retainedArchivePath, tenantId: params.tenantId, - leaseId: normalizeLeaseId(params.leaseId) ?? params.leaseId, + leaseId, sessionName: params.sessionName, expiresAt, timer, @@ -129,12 +129,18 @@ export async function cleanupRetainedMaterializedPaths( tenantId, MATERIALIZED_PATHS_RESOURCE, ); - if (entry.leaseId !== (normalizeLeaseId(leaseId) ?? leaseId)) { + if (entry.leaseId !== (await canonicalLeaseId(leaseId))) { throw new AppError('UNAUTHORIZED', 'Materialized paths belong to a different lease'); } await removeRetainedEntry(materializationId, entry); } +async function canonicalLeaseId(leaseId: string | undefined): Promise { + if (!leaseId) return leaseId; + const { normalizeLeaseId } = await import('@agent-device/contracts/lease-scope'); + return normalizeLeaseId(leaseId) ?? leaseId; +} + export async function cleanupRetainedMaterializedPathsForSession( sessionName: string, ): Promise { From 66838f974a37a16d3b8bc0b553c734f032239e56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 13:50:48 +0100 Subject: [PATCH 15/35] fix: close lease artifact ownership review gaps --- .../src/management/artifacts.test.ts | 3 + .../__tests__/lease-registry.test.ts | 12 ++++ .../src/resources/artifact-tracking.test.ts | 26 +++++++-- .../daemon/src/resources/artifact-tracking.ts | 17 ++++-- .../daemon/src/resources/lease-registry.ts | 11 +++- .../resources/provider-session-ownership.ts | 12 ++-- .../__tests__/request-finalization.test.ts | 37 ++++++++++++ .../server/__tests__/resumable-upload.test.ts | 25 ++++++++ .../src/server/downloadable-artifact-http.ts | 7 ++- .../http/http-server-remote-output.test.ts | 20 +++++++ .../daemon/src/server/request-finalization.ts | 3 +- .../daemon/src/server/resumable-upload.ts | 17 ++++-- packages/daemon/src/server/upload-http.ts | 8 ++- .../materialized-path-registry.test.ts | 4 +- .../handlers/__tests__/install-source.test.ts | 46 ++++++++++++++- .../__tests__/lease-artifacts.test.ts | 58 +++++++++++++++++++ .../__tests__/session-reinstall.test.ts | 12 +++- .../daemon/src/sessions/handlers/lease.ts | 13 ++++- .../handlers/session-app-deployment.ts | 7 ++- .../handlers/session-app-source-deployment.ts | 11 +++- .../sessions/materialized-path-registry.ts | 11 +++- .../upload-client-lease-headers.test.ts | 10 +++- test/wire-compat/ledger.json | 2 + test/wire-compat/surface.ts | 2 + website/docs/docs/device-clouds.md | 2 +- website/docs/docs/error-reasons.md | 6 ++ 26 files changed, 340 insertions(+), 42 deletions(-) diff --git a/packages/command-surface/src/management/artifacts.test.ts b/packages/command-surface/src/management/artifacts.test.ts index c5a2a879dce..3f73ce9dd57 100644 --- a/packages/command-surface/src/management/artifacts.test.ts +++ b/packages/command-surface/src/management/artifacts.test.ts @@ -10,6 +10,9 @@ test('artifacts CLI passes an explicit lease and run through to the daemon comma } as CliFlags); assert.equal(input.leaseId, 'lease-a'); assert.equal(input.runId, 'run-a'); + const request = artifactsCommandFacet.daemonWriter(input); + assert.equal(request.options.leaseId, 'lease-a'); + assert.equal(request.options.runId, 'run-a'); assert.deepEqual(artifactsCommandFacet.cliSchema.allowedFlags, [ 'provider', 'providerSessionId', diff --git a/packages/daemon/src/resources/__tests__/lease-registry.test.ts b/packages/daemon/src/resources/__tests__/lease-registry.test.ts index 0672a6d71a2..5acdf17db4d 100644 --- a/packages/daemon/src/resources/__tests__/lease-registry.test.ts +++ b/packages/daemon/src/resources/__tests__/lease-registry.test.ts @@ -156,6 +156,18 @@ test('a retried allocation of a host-pinned lease never outlives the host window assert.equal(retried.expiresAt, 15_000); }); +test('a host cannot reissue a released lease id to another artifact owner', () => { + const registry = new LeaseRegistry(); + const leaseId = 'cccccccccccccccccccccccccccccccc'; + registry.putHostLease(leaseId, { tenantId: 'tenant-a', runId: 'run-1' }); + registry.releaseLease({ leaseId }); + + assert.throws( + () => registry.putHostLease(leaseId, { tenantId: 'tenant-b', runId: 'run-2' }), + isLeaseIdInUse, + ); +}); + test('an expired provider lease keeps its id and provider session from a caller-chosen reuse', () => { let now = 1_000; const registry = new LeaseRegistry({ now: () => now, defaultLeaseTtlMs: 10_000 }); diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index 549a6e27117..516699b31a6 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -599,9 +599,12 @@ test('uploads stay bound to their producing lease', () => { }), ); - for (const leaseId of [undefined, 'lease-b']) { - expect(() => runtime.run(() => prepareUploadedArtifact(id, 'tenant-a', leaseId))).toThrow( - /different lease/, + for (const leaseId of [undefined, '1234567890abcdef1234567890abcdef']) { + expect(() => runtime.run(() => prepareUploadedArtifact(id, 'tenant-a', leaseId))).toThrowError( + expect.objectContaining({ + code: 'UNAUTHORIZED', + details: expect.objectContaining({ reason: 'ARTIFACT_LEASE_MISMATCH' }), + }), ); } expect(runtime.run(() => prepareUploadedArtifact(id, 'tenant-a', leaseId.toLowerCase()))).toBe( @@ -627,7 +630,9 @@ test('a retained downloadable artifact requires its producing lease', async () = ); try { expect( - await runtime.run(() => listDownloadableArtifacts('tenant-a', process.env, 'lease-b')), + await runtime.run(() => + listDownloadableArtifacts('tenant-a', process.env, '1234567890abcdef1234567890abcdef'), + ), ).toEqual([]); expect( await runtime.run(() => @@ -636,9 +641,18 @@ test('a retained downloadable artifact requires its producing lease', async () = ).toHaveLength(1); await expect( runtime.run(() => - openDownloadableArtifact(id, 'tenant-a', process.env, undefined, 'lease-b'), + openDownloadableArtifact( + id, + 'tenant-a', + process.env, + undefined, + '1234567890abcdef1234567890abcdef', + ), ), - ).rejects.toThrow(/different lease/); + ).rejects.toMatchObject({ + code: 'UNAUTHORIZED', + details: { reason: 'ARTIFACT_LEASE_MISMATCH' }, + }); const opened = await runtime.run(() => openDownloadableArtifact(id, 'tenant-a', process.env, undefined, leaseId.toLowerCase()), ); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 79981f8df27..30203f171c2 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -3,7 +3,7 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { finished } from 'node:stream/promises'; -import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; +import { AppError, createRequestCanceledError, type ReasonTable } from '@agent-device/kernel/errors'; import type { DaemonArtifactType } from '@agent-device/kernel/contracts'; import type { DeviceRotation } from '@agent-device/contracts/device'; import type { DaemonArtifactInventoryEntry } from '@agent-device/contracts/observability'; @@ -20,6 +20,11 @@ import { const ARTIFACT_CLEANUP_TIMEOUT_MS = 15 * 60 * 1000; const ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS = 15 * 60 * 1000; +const ARTIFACT_TRACKING_REASONS = { + // The artifact belongs to another lease of the same tenant. + leaseMismatch: { reason: 'ARTIFACT_LEASE_MISMATCH' }, +} as const satisfies ReasonTable<'daemon resources'>; + const DOWNLOADABLE_ARTIFACT_RESOURCE: TenantOwnedResourceKind = { label: 'Artifact', expiredHint: `Downloadable artifacts are removed after download or after ${ARTIFACT_CLEANUP_TIMEOUT_MS / 60_000} minutes. Re-run the command that produced the artifact and download it again.`, @@ -122,7 +127,7 @@ export type OpenedDownloadableArtifact = PreparedDownloadableArtifact & { }; /** - * Registers one file for download and returns its id. A file the same tenant can already download + * Registers one file for download and returns its id. A file the same tenant and lease can already download * returns its existing entry unchanged: two ids for one file would each delete it after their own * download. */ @@ -311,7 +316,9 @@ function readDownloadableArtifactEntry( throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } if (entry.leaseId !== (normalizeLeaseId(leaseId) ?? leaseId)) { - throw new AppError('UNAUTHORIZED', 'Artifact belongs to a different lease'); + throw new AppError('UNAUTHORIZED', 'Artifact belongs to a different lease', { + reason: ARTIFACT_TRACKING_REASONS.leaseMismatch.reason, + }); } let stat: fs.Stats; try { @@ -568,7 +575,9 @@ export function prepareUploadedArtifact( UPLOADED_ARTIFACT_RESOURCE, ); if (entry.leaseId !== (normalizeLeaseId(leaseId) ?? leaseId)) { - throw new AppError('UNAUTHORIZED', 'Uploaded artifact belongs to a different lease'); + throw new AppError('UNAUTHORIZED', 'Uploaded artifact belongs to a different lease', { + reason: ARTIFACT_TRACKING_REASONS.leaseMismatch.reason, + }); } clearTimeout(entry.timer); return entry.artifactPath; diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index 31992ba8f74..5aa3d88a8c1 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -48,6 +48,8 @@ const LEASE_REGISTRY_REASONS = { idInUse: { reason: 'LEASE_ID_IN_USE' }, // Every iOS simulator lease slot is taken; retry after another lease is released. capacityExceeded: { reason: 'LEASE_CAPACITY_EXCEEDED' }, + // The requested retained artifact lease belongs to another tenant or run. + artifactReadNotOwned: { reason: 'RETAINED_ARTIFACT_LEASE_NOT_OWNED' }, } as const satisfies ReasonTable<'leases'>; type OwnedHumanControlHold = { hold: HumanControlHold; ownerLeaseId?: string }; @@ -138,6 +140,11 @@ export class LeaseRegistry { this.hostTtlMsByLeaseId.set(id, leaseTtlMs); return this.refreshLease(existing, leaseTtlMs); } + if (this.issuedLeaseIds.has(id)) { + throw new AppError('INVALID_ARGS', 'Lease id already names a lease this daemon issued.', { + reason: LEASE_REGISTRY_REASONS.idInUse.reason, + }); + } this.assertHumanControlAdmission(normalized); this.assertDeviceAvailable(normalized); if (normalized.backend === 'macos-app') this.macOsAppTenantIds.add(normalized.tenantId); @@ -360,7 +367,9 @@ export class LeaseRegistry { owner.runId !== request.runId || (owner.retainedUntil !== undefined && owner.retainedUntil <= this.now()) ) { - throw new AppError('UNAUTHORIZED', 'Lease is not owned by the artifact request'); + throw new AppError('UNAUTHORIZED', 'Lease is not owned by the artifact request', { + reason: LEASE_REGISTRY_REASONS.artifactReadNotOwned.reason, + }); } } diff --git a/packages/daemon/src/resources/provider-session-ownership.ts b/packages/daemon/src/resources/provider-session-ownership.ts index ae2f9b0e73a..4a454a8e924 100644 --- a/packages/daemon/src/resources/provider-session-ownership.ts +++ b/packages/daemon/src/resources/provider-session-ownership.ts @@ -93,13 +93,14 @@ export class ProviderSessionOwnershipRegistry { const provider = params.provider?.trim(); const providerSessionId = params.providerSessionId?.trim(); const tenantId = params.tenantId?.trim(); + const runId = params.runId?.trim(); if (!provider || !providerSessionId || !tenantId) return undefined; this.prune(); const record = this.records.get(this.key(provider, providerSessionId)); if ( !record || record.tenantId !== tenantId || - (params.runId && record.runId !== params.runId) + (runId && record.runId !== runId) ) { return undefined; } @@ -112,12 +113,13 @@ export class ProviderSessionOwnershipRegistry { tenantId?: string; runId?: string; }): LeaseOwnershipRecord | undefined { - if (!params.provider || !params.tenantId || !params.runId) return undefined; + const provider = params.provider?.trim(); + const tenantId = params.tenantId?.trim(); + const runId = params.runId?.trim(); + if (!provider || !tenantId || !runId) return undefined; this.prune(); const record = this.leases.get(params.leaseId); - return record?.provider === params.provider && - record.tenantId === params.tenantId && - record.runId === params.runId + return record?.provider === provider && record.tenantId === tenantId && record.runId === runId ? { ...record } : undefined; } diff --git a/packages/daemon/src/server/__tests__/request-finalization.test.ts b/packages/daemon/src/server/__tests__/request-finalization.test.ts index 94fa4dcc586..f8e772a0dbd 100644 --- a/packages/daemon/src/server/__tests__/request-finalization.test.ts +++ b/packages/daemon/src/server/__tests__/request-finalization.test.ts @@ -5,6 +5,7 @@ import type { DaemonRequest } from '../../core/daemon-request.ts'; import type { DaemonArtifactType, DaemonResponse } from '@agent-device/kernel/contracts'; import type { DownloadableArtifactRegistration } from '../../resources/artifact-tracking.ts'; import { asDaemonDeliveredArtifact } from '../../core/capture-output-ownership.ts'; +import { LeaseRegistry } from '../../resources/lease-registry.ts'; test('finalizeDaemonResponse preserves handler error hints from details', () => { const req: DaemonRequest = { @@ -192,6 +193,42 @@ test('finalizeDaemonResponse registers an unexpected output artifact without a c }); }); +test('finalizeDaemonResponse binds session output to the admitted lease', () => { + const lease = new LeaseRegistry().allocateLease({ + tenantId: 'tenant-a', + runId: 'run-a', + leaseBackend: 'android-instance', + }); + const req: DaemonRequest = { + token: 'token', + session: 'leased', + command: 'snapshot', + positionals: [], + meta: { tenantId: 'tenant-a' }, + internal: { admittedLease: lease }, + }; + const tracked: DownloadableArtifactRegistration[] = []; + + finalizeDaemonResponse( + req, + { + ok: true, + data: { + fallbackScreenshotPath: '/tmp/leased.png', + artifacts: [ + { field: 'fallbackScreenshotPath', path: '/tmp/leased.png', artifactType: 'screenshot' }, + ], + }, + }, + (registration) => { + tracked.push(registration); + return 'artifact-id'; + }, + ); + + expect(tracked[0]?.leaseId).toBe(lease.leaseId); +}); + test('finalizeDaemonResponse leaves unrelated local-path artifacts unregistered', () => { const req: DaemonRequest = { token: 'token', diff --git a/packages/daemon/src/server/__tests__/resumable-upload.test.ts b/packages/daemon/src/server/__tests__/resumable-upload.test.ts index 4aa2e3c114f..ff33e11c08a 100644 --- a/packages/daemon/src/server/__tests__/resumable-upload.test.ts +++ b/packages/daemon/src/server/__tests__/resumable-upload.test.ts @@ -35,6 +35,31 @@ test('finalizing an unknown upload reports expiry with a recovery hint', async ( assert.equal(typeof appError.details?.hint, 'string'); }); +test('resumable upload uses one lease identity across mixed-case retries', async () => { + const bytes = Buffer.from('leased-upload'); + const leaseId = 'ABCDEF0123456789ABCDEF0123456789'; + const options = { ...uploadOptions(bytes), tenantId: 'tenant-a', leaseId }; + const uploadId = beginResumableUpload(options).uploadId; + assert.equal(beginResumableUpload({ ...options, leaseId: leaseId.toLowerCase() }).uploadId, uploadId); + await receiveResumableUploadChunk({ + uploadId, + tenantId: 'tenant-a', + leaseId: leaseId.toLowerCase(), + req: request(bytes), + }); + const finalized = await finalizeResumableUpload( + uploadId, + 'tenant-a', + undefined, + leaseId.toLowerCase(), + ); + try { + assert.equal(fs.readFileSync(finalized.artifactPath, 'utf8'), 'leased-upload'); + } finally { + fs.rmSync(finalized.tempDir, { recursive: true, force: true }); + } +}); + test('oversized ranged chunks roll back atomically and can be retried and finalized', async () => { const bytes = Buffer.from('ABCDE'); const uploadId = beginUpload(bytes).uploadId; diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index ff9b4b8be04..e0685d5d407 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -23,6 +23,8 @@ const ARTIFACT_DOWNLOAD_REASONS = { // The artifact stream ended at a different size than the daemon recorded; `details` gives both // sizes. sizeMismatch: { reason: 'artifact_size_mismatch' }, + // A leased artifact request needs a named run and lease registry. + leaseAdmissionRequired: { reason: 'ARTIFACT_LEASE_ADMISSION_REQUIRED' }, } as const satisfies ReasonTable<'artifact downloads'>; type DownloadableArtifactHttpRoute = @@ -211,10 +213,11 @@ function admitArtifactLease( !value.trim() || typeof runId !== 'string' || !runId.trim() || - !tenantId || !leaseRegistry ) { - throw new AppError('UNAUTHORIZED', 'Artifact lease requires an admitted tenant and run'); + throw new AppError('UNAUTHORIZED', 'Artifact lease requires an admitted tenant and run', { + reason: ARTIFACT_DOWNLOAD_REASONS.leaseAdmissionRequired.reason, + }); } const leaseId = normalizeRequiredLeaseId(value); leaseRegistry.assertArtifactLeaseReadAdmission({ leaseId, tenantId, runId: runId.trim() }); 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 ee22c7cd5df..9cee4a2590c 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 @@ -923,6 +923,26 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite const first = await runSuite('tenant-a'); const firstPath = registrations[0]!.path; fs.writeFileSync(path.join(firstPath, 'private-a.txt'), 'tenant-a-private-marker'); + const otherRun = leaseRegistry.allocateLease({ + tenantId: 'tenant-a', + runId: 'other-run', + leaseBackend: 'android-instance', + }); + const otherRunHeaders = { + authorization: 'Bearer test-token', + 'x-tenant': 'tenant-a', + 'x-agent-device-lease-id': otherRun.leaseId, + 'x-agent-device-run-id': 'other-run', + }; + const otherRunInventory = await fetch(`${baseUrl}/artifacts`, { + headers: otherRunHeaders, + }); + expect(otherRunInventory.status).toBe(200); + expect(JSON.stringify(await otherRunInventory.json())).not.toContain(first.artifactId); + const otherRunDownload = await fetch(`${baseUrl}/artifacts/${first.artifactId}`, { + headers: otherRunHeaders, + }); + expect(otherRunDownload.status).toBe(401); const second = await runSuite('tenant-b'); const secondPath = registrations[1]!.path; expect(secondPath).not.toBe(firstPath); diff --git a/packages/daemon/src/server/request-finalization.ts b/packages/daemon/src/server/request-finalization.ts index cd4c1718da4..55d470f7f28 100644 --- a/packages/daemon/src/server/request-finalization.ts +++ b/packages/daemon/src/server/request-finalization.ts @@ -19,6 +19,7 @@ import { captureOutputTenantId, daemonDeliveredArtifact, } from '../core/capture-output-ownership.ts'; +import { resolveLeaseScope } from '../core/lease-context.ts'; /** A response artifact plus the capture facts the inventory reports beside it. */ type PendingArtifact = DaemonArtifact & { @@ -109,7 +110,7 @@ function registerDownloadableArtifacts( tenantId: delivered ? delivered.tenantId : (captureOutputTenantId(data) ?? req.meta?.tenantId), - leaseId: req.meta?.leaseId, + leaseId: req.internal?.admittedLease?.leaseId ?? resolveLeaseScope(req).leaseId, artifactType: artifact.artifactType, fileName: artifact.fileName, ...(artifact.deleteAfterDownload === false ? { deleteAfterDownload: false } : {}), diff --git a/packages/daemon/src/server/resumable-upload.ts b/packages/daemon/src/server/resumable-upload.ts index 724310ad3d5..da12e0d1f19 100644 --- a/packages/daemon/src/server/resumable-upload.ts +++ b/packages/daemon/src/server/resumable-upload.ts @@ -18,6 +18,7 @@ import { } from './artifact-download.ts'; import { computeUploadHash, receiveResumableTransfer } from './resumable-upload-transfer.ts'; import { resolveIngressFailure, throwIfIngressAborted } from './upload-ingress.ts'; +import { normalizeLeaseId } from '@agent-device/contracts/lease-scope'; const UPLOAD_FINALIZE_REASONS = { // Finalizing the upload failed, and removing its staged files failed too; `details.originalError` @@ -25,6 +26,8 @@ const UPLOAD_FINALIZE_REASONS = { cleanupFailed: { reason: 'UPLOAD_FINALIZE_CLEANUP_FAILED' }, // A new upload would exceed the active upload count or reserved byte budget. capacityExceeded: { reason: 'UPLOAD_CAPACITY_EXCEEDED' }, + // A staged upload belongs to another lease of the same tenant. + leaseMismatch: { reason: 'RESUMABLE_UPLOAD_LEASE_MISMATCH' }, } as const satisfies ReasonTable<'uploads'>; const RESUMABLE_UPLOAD_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000; @@ -313,7 +316,7 @@ function createResumableUploadEntry( artifactType: options.artifactType, platform: options.platform, tenantId: options.tenantId, - leaseId: options.leaseId, + leaseId: canonicalLeaseId(options.leaseId), generation: 0, tail: Promise.resolve(), closed: false, @@ -467,8 +470,10 @@ function requireResumableUpload( tenantId, RESUMABLE_UPLOAD_RESOURCE, ); - if (entry.leaseId !== leaseId) { - throw new AppError('UNAUTHORIZED', 'Upload belongs to a different lease'); + if (entry.leaseId !== canonicalLeaseId(leaseId)) { + throw new AppError('UNAUTHORIZED', 'Upload belongs to a different lease', { + reason: UPLOAD_FINALIZE_REASONS.leaseMismatch.reason, + }); } return entry; } @@ -490,7 +495,7 @@ function validateResumableUploadOptions(options: BeginResumableUploadOptions): v function buildResumableUploadKey(options: BeginResumableUploadOptions): string { return [ options.tenantId ?? '', - options.leaseId ?? '', + canonicalLeaseId(options.leaseId) ?? '', options.uploadAttemptId, options.sha256.toLowerCase(), String(options.sizeBytes), @@ -499,3 +504,7 @@ function buildResumableUploadKey(options: BeginResumableUploadOptions): string { options.platform ?? '', ].join('\0'); } + +function canonicalLeaseId(leaseId: string | undefined): string | undefined { + return leaseId === undefined ? undefined : (normalizeLeaseId(leaseId) ?? leaseId); +} diff --git a/packages/daemon/src/server/upload-http.ts b/packages/daemon/src/server/upload-http.ts index 4060cfae0ef..f017e45bc07 100644 --- a/packages/daemon/src/server/upload-http.ts +++ b/packages/daemon/src/server/upload-http.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import http from 'node:http'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError, type ReasonTable } from '@agent-device/kernel/errors'; import type { DaemonRequest } from '../core/daemon-request.ts'; import { trackUploadedArtifact } from '../resources/artifact-tracking.ts'; import { @@ -22,6 +22,11 @@ import { normalizeRequiredLeaseId } from '../resources/lease-registry-scope.ts'; const DIRECT_UPLOAD_PATH_PREFIX = '/upload/direct/'; +const UPLOAD_LEASE_REASONS = { + // A leased upload needs an authenticated tenant and a named run and lease registry. + admissionRequired: { reason: 'UPLOAD_LEASE_ADMISSION_REQUIRED' }, +} as const satisfies ReasonTable<'uploads'>; + type UploadHttpRoute = | { kind: 'upload' } | { kind: 'preflight' } @@ -158,6 +163,7 @@ function admitUploadLease( throw new AppError( 'UNAUTHORIZED', 'Upload lease requires an admitted tenant, run and lease registry', + { reason: UPLOAD_LEASE_REASONS.admissionRequired.reason }, ); } const leaseId = normalizeRequiredLeaseId(header); diff --git a/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts b/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts index 2452a3260bb..d3dad99ba15 100644 --- a/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts +++ b/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts @@ -140,10 +140,10 @@ test('same tenant cannot release materialized paths from another lease', async ( leaseId, }); - for (const leaseId of [undefined, 'lease-b']) { + for (const leaseId of [undefined, '1234567890abcdef1234567890abcdef']) { await assert.rejects( () => cleanupRetainedMaterializedPaths(retained.materializationId, 'tenant-a', leaseId), - { code: 'UNAUTHORIZED' }, + { code: 'UNAUTHORIZED', details: { reason: 'MATERIALIZED_PATH_LEASE_MISMATCH' } }, ); assert.equal(fs.existsSync(retained.installablePath), true); } diff --git a/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts b/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts index a93f612d656..b85a08154d1 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts @@ -1,5 +1,5 @@ import { daemonPlatformServicesFixture } from '../../../__tests__/support/platform-services-fixture.ts'; -import { readFileSync } from 'node:fs'; +import { readFileSync, rmSync, writeFileSync } from 'node:fs'; import path from 'node:path'; import { expect, test, vi } from 'vitest'; import type { @@ -39,6 +39,7 @@ import { SessionStore } from '../../../core/session-store.ts'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; import type { SessionState } from '../../../core/session-state.ts'; import { handleInstallFromSourceDeploymentCommand } from '../session-app-source-deployment.ts'; +import { cleanupRetainedMaterializedPaths } from '../../materialized-path-registry.ts'; type SourceRuntimeOptions = Readonly<{ materializationAvailable?: boolean; @@ -121,6 +122,49 @@ test('install_source materializes and deploys through the admitted ready runtime expect(deploy).toHaveBeenCalledOnce(); }); +test('install_source retains output under an existing session lease', async () => { + const root = mkdtempForTestSync('agent-device-leased-source-'); + const appPath = path.join(root, 'app.apk'); + writeFileSync(appPath, 'app'); + const store = makeStore(); + const session = makeSession({ + platform: 'android', + id: 'emulator-5554', + name: 'Pixel', + kind: 'emulator', + booted: true, + }); + const leaseId = 'abcdef0123456789abcdef0123456789'; + session.lease = { leaseId, tenantId: 'tenant-a', runId: 'run-a' }; + store.publish(session.name, session); + const runtime = createSourceRuntime( + session.device, + async () => ({ installablePath: appPath, cleanup: async () => {} }), + async () => ({ packageName: 'com.example.app' }), + ); + const req = makeRequest({ kind: 'url', url: 'https://example.com/app.zip', headers: {} }); + req.meta = { ...req.meta, tenantId: 'tenant-a', retainMaterializedPaths: true }; + try { + const response = await handleInstallFromSourceDeploymentCommand({ + platformServices: daemonPlatformServicesFixture(), + req, + sessionName: session.name, + sessionStore: store, + inspectFacts: runtime.inspectFacts, + bindDevice: runtime.bindDevice, + }); + expect(response.ok).toBe(true); + if (!response.ok) return; + const materializationId = response.data?.materializationId as string; + await expect(cleanupRetainedMaterializedPaths(materializationId, 'tenant-a')).rejects.toMatchObject({ + code: 'UNAUTHORIZED', + }); + await cleanupRetainedMaterializedPaths(materializationId, 'tenant-a', leaseId); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + test.each(['emulator-5554', 'emulator-5556'])( 'install_source adopts readiness metadata before materialization and deployment (%s)', async (readyId) => { diff --git a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts index af44bff0762..adab8709076 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts @@ -11,9 +11,41 @@ import { makeAndroidSession } from '../../../__tests__/support/session-factories import type { DaemonRequest } from '../../../core/daemon-request.ts'; import { handleLeaseCommands } from '../lease.ts'; import { LeaseRegistry } from '../../../resources/lease-registry.ts'; +import { ProviderSessionOwnershipRegistry } from '../../../resources/provider-session-ownership.ts'; const CLOUD_PROVIDER = 'fake-cloud'; +test('provider ownership resolves normalized scope fields', () => { + const registry = new ProviderSessionOwnershipRegistry(); + const lease = { + leaseId: '0123456789abcdef0123456789abcdef', + leaseProvider: CLOUD_PROVIDER, + tenantId: 'tenant-a', + runId: 'run-a', + }; + registry.recordLease(lease); + registry.record(lease, 'session-a'); + + assert.equal( + registry.resolve({ + provider: ` ${CLOUD_PROVIDER} `, + providerSessionId: ' session-a ', + tenantId: ' tenant-a ', + runId: ' run-a ', + })?.leaseId, + lease.leaseId, + ); + assert.equal( + registry.resolveLease({ + leaseId: lease.leaseId, + provider: ` ${CLOUD_PROVIDER} `, + tenantId: ' tenant-a ', + runId: ' run-a ', + })?.leaseId, + lease.leaseId, + ); +}); + test('session name alone gives a typed error for leased artifact inventory', async () => { const world = createWorld(); const lease = await allocateLease(world, 'tenant-a', 'run-a'); @@ -80,6 +112,32 @@ test('provider session lookup reports a missing run as invalid scope', async () assert.deepEqual(world.providerCalls, []); }); +test('provider session lookup uses the matching local session lease', async () => { + const world = createWorld(); + const lease = await allocateLease(world, 'tenant-a', 'run-a'); + world.sessionStore.publish( + 'artifact-test', + makeAndroidSession('artifact-test', { + lease: { + leaseId: lease.leaseId, + tenantId: lease.tenantId, + runId: lease.runId, + leaseBackend: lease.backend, + leaseProvider: lease.leaseProvider, + }, + }), + ); + + const response = await listArtifacts(world, { + tenantId: 'tenant-a', + providerSessionId: 'session-tenant-a', + }); + assert.equal(response.ok, true); + assert.deepEqual(world.providerCalls, [ + { provider: CLOUD_PROVIDER, leaseId: lease.leaseId, providerSessionId: 'session-tenant-a' }, + ]); +}); + test('artifacts admits an owned lease ID and refuses a foreign lease ID before cloud dispatch', async () => { const world = createWorld(); const lease = await allocateLease(world, 'tenant-a', 'run-a'); 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..08d067f8ad3 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/session-reinstall.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/session-reinstall.test.ts @@ -285,7 +285,13 @@ test('reinstall cleans an uploaded artifact after the request-scoped operation', const root = mkdtempForTestSync('agent-device-uploaded-artifact-'); const appPath = path.join(root, 'Sample.app'); fs.writeFileSync(appPath, 'placeholder'); - const uploadedArtifactId = trackUploadedArtifact({ artifactPath: appPath, tempDir: root }); + const leaseId = 'abcdef0123456789abcdef0123456789'; + const uploadedArtifactId = trackUploadedArtifact({ + artifactPath: appPath, + tempDir: root, + tenantId: 'tenant-a', + leaseId, + }); mockDeployAppRuntime.mockResolvedValue({ bundleId: 'com.example.app' }); vi.mocked(resolveTargetDevice).mockResolvedValue(session.device); @@ -298,8 +304,8 @@ test('reinstall cleans an uploaded artifact after the request-scoped operation', session: session.name, command: 'reinstall', positionals: ['com.example.app', '/Users/dev/Downloads/Sample.app'], - flags: {}, - meta: { uploadedArtifactId }, + flags: { leaseId }, + meta: { uploadedArtifactId, tenantId: 'tenant-a' }, }, sessionName: session.name, logPath: '/tmp/daemon.log', diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index e067021724d..8fb95d6809c 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -30,7 +30,11 @@ import { normalizeRequiredLeaseId, } from '../../resources/lease-registry-scope.ts'; import type { SessionStore } from '../../core/session-store.ts'; -import { isProxyLeaseScope, resolveLeaseScope } from '../../core/lease-context.ts'; +import { + isProxyLeaseScope, + resolveLeaseScope, + resolveRequestOrSessionLeaseScope, +} from '../../core/lease-context.ts'; import { isProviderInstanceEndedError, leaseDeviceKey, @@ -103,9 +107,10 @@ export async function handleLeaseCommands(args: LeaseHandlerArgs): Promise | undefined; let materialized: MaterializedAppSource | undefined; let retained: RetainedMaterializedPaths | undefined; @@ -115,6 +118,7 @@ export async function handleInstallFromSourceDeploymentCommand(params: { artifact: materialized, retention, req, + leaseId, session, sessionName, }); @@ -135,7 +139,7 @@ export async function handleInstallFromSourceDeploymentCommand(params: { await cleanupRetainedMaterializedPaths( retained.materializationId, req.meta?.tenantId, - req.meta?.leaseId, + leaseId, ).catch(() => {}); } return { ok: false, error: normalizeError(error) }; @@ -157,7 +161,7 @@ export async function handleReleaseMaterializedPathsCommand(params: { await cleanupRetainedMaterializedPaths( materializationId, req.meta?.tenantId, - req.meta?.leaseId, + req.internal?.admittedLease?.leaseId ?? resolveLeaseScope(req).leaseId, ); return { ok: true, data: { released: true, materializationId } }; } catch (error) { @@ -219,6 +223,7 @@ async function retainIfRequested(params: { artifact: MaterializedAppSource; retention: Retention; req: DaemonRequest; + leaseId: string | undefined; session: SessionState | undefined; sessionName: string; }): Promise { @@ -227,7 +232,7 @@ async function retainIfRequested(params: { archivePath: params.artifact.archivePath, installablePath: params.artifact.installablePath, tenantId: params.req.meta?.tenantId, - leaseId: params.req.meta?.leaseId, + leaseId: params.leaseId, sessionName: params.session ? params.sessionName : undefined, ttlMs: params.retention.ttlMs, }); diff --git a/packages/daemon/src/sessions/materialized-path-registry.ts b/packages/daemon/src/sessions/materialized-path-registry.ts index 8d7b06962ae..999bfa335a5 100644 --- a/packages/daemon/src/sessions/materialized-path-registry.ts +++ b/packages/daemon/src/sessions/materialized-path-registry.ts @@ -1,5 +1,5 @@ import { runtimeSlot } from '@agent-device/host-kit/runtime-slots'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import crypto from 'node:crypto'; import { rmSync } from 'node:fs'; import fs from 'node:fs/promises'; @@ -13,6 +13,11 @@ import { const DEFAULT_MATERIALIZED_PATH_TTL_MS = 15 * 60 * 1000; const MAX_MATERIALIZED_PATH_TTL_MS = 2_147_483_647; +const MATERIALIZED_PATH_REASONS = { + // Retained output belongs to another lease of the same tenant. + leaseMismatch: { reason: 'MATERIALIZED_PATH_LEASE_MISMATCH' }, +} as const satisfies ReasonTable<'daemon resources'>; + const MATERIALIZED_PATHS_RESOURCE: TenantOwnedResourceKind = { label: 'Materialized paths', plural: true, @@ -130,7 +135,9 @@ export async function cleanupRetainedMaterializedPaths( MATERIALIZED_PATHS_RESOURCE, ); if (entry.leaseId !== (await canonicalLeaseId(leaseId))) { - throw new AppError('UNAUTHORIZED', 'Materialized paths belong to a different lease'); + throw new AppError('UNAUTHORIZED', 'Materialized paths belong to a different lease', { + reason: MATERIALIZED_PATH_REASONS.leaseMismatch.reason, + }); } await removeRetainedEntry(materializationId, entry); } diff --git a/packages/remote/src/__tests__/upload-client-lease-headers.test.ts b/packages/remote/src/__tests__/upload-client-lease-headers.test.ts index b4463486ce4..a8aa659affc 100644 --- a/packages/remote/src/__tests__/upload-client-lease-headers.test.ts +++ b/packages/remote/src/__tests__/upload-client-lease-headers.test.ts @@ -4,7 +4,12 @@ import http from 'node:http'; import path from 'node:path'; import { randomUUID } from 'node:crypto'; import { test } from 'vitest'; -import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import { + closeLoopbackServer, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; import { DAEMON_HTTP_LEASE_HEADER, DAEMON_HTTP_RUN_HEADER, @@ -19,7 +24,8 @@ test.each([ { flow: 'direct', host: 'localhost', routes: DIRECT_ROUTES, unleased: 'PUT /upload/t' }, ])( 'upload forwards lease and run only to daemon-bound $flow routes for $host', - async ({ flow, host, routes, unleased }) => { + async ({ flow, host, routes, unleased }, t) => { + if (await skipWhenLoopbackUnavailable(t)) return; const directory = mkdtempForTestSync(`agent-device-upload-lease-${randomUUID()}-`); const localPath = path.join(directory, 'app.apk'); fs.writeFileSync(localPath, `${flow}-payload`); diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 5f924eedded..e07eb36af41 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -2,11 +2,13 @@ "protocolVersion": 4, "declarations": { "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_BASE_PATH": "sha256:a1ada25c6f90d9c69c8c836538e8882547bf239559f7c1accacd0654355802dd", + "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_RUN_HEADER": "sha256:66a6ad6d4388872490417e4210dc5eae1581a7531695ca002e9b2ecf3ebc6700", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_TENANT_HEADER": "sha256:ed49119d232500885f014ac73f6123d298d404c6c176abdae59cf324825927e5", "packages/contracts/src/daemon-http.ts#DaemonHealthPayload": "sha256:466c1c0bb01d3b61ef67695c835bac2ac20e10f4c7d11a5d0f54963e5e4f792c", "packages/contracts/src/daemon-http.ts#buildDaemonHealthPayload": "sha256:807a09e96c57595a5d903c07d35443e1e166496405ffd4787ff8450c15e3a890", "packages/contracts/src/daemon-http.ts#buildDaemonHttpAuthHeaders": "sha256:5548a44d6248ed858d19a0b2985ec4ae8a7181bae8294b85edf3c1b3b58e80d4", "packages/contracts/src/daemon-http.ts#buildDaemonHttpBaseUrl": "sha256:f92697208d9f42ec0dcfb006b6f2dce761bd5307db27ce2e52927fd7742e3a9a", + "packages/contracts/src/daemon-http.ts#buildDaemonHttpRunHeaders": "sha256:a635b2e3c2086e53f2e99c5b4d7bd143b9872dc95829029b3bace4b579b084f5", "packages/contracts/src/daemon-http.ts#buildDaemonHttpTenantHeaders": "sha256:e38a5f0b5ab07ee3a5fe3db229d0de750888660c55bf31692e100002be96de1d", "packages/contracts/src/daemon-http.ts#buildDaemonHttpUrl": "sha256:d38f1f8877588fbcb1fea8c52a5cb7dc205043e3fc698b3d78fdcf821fa80471", "packages/contracts/src/daemon-http.ts#isTenantOwnedSessionName": "sha256:c3cff883507d462548846554b89779cb815ceb265714575e57bee022b57c4bd1", diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index 2718281938f..5f32b9e16b3 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -240,6 +240,8 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'buildDaemonHttpAuthHeaders', 'DAEMON_HTTP_TENANT_HEADER', 'buildDaemonHttpTenantHeaders', + 'DAEMON_HTTP_RUN_HEADER', + 'buildDaemonHttpRunHeaders', 'isTenantOwnedSessionName', ), ...from( diff --git a/website/docs/docs/device-clouds.md b/website/docs/docs/device-clouds.md index 18bb7a54842..b1db7200493 100644 --- a/website/docs/docs/device-clouds.md +++ b/website/docs/docs/device-clouds.md @@ -67,7 +67,7 @@ agent-device artifacts --provider --run-id Date: Tue, 1 Dec 2026 13:55:45 +0100 Subject: [PATCH 16/35] fix: keep lease regressions within test gates --- .../src/management/artifacts.test.ts | 5 ++- .../__tests__/lease-registry.test.ts | 5 +-- .../http/http-server-remote-output.test.ts | 41 +++++-------------- .../upload-client-lease-headers.test.ts | 15 +++---- 4 files changed, 23 insertions(+), 43 deletions(-) diff --git a/packages/command-surface/src/management/artifacts.test.ts b/packages/command-surface/src/management/artifacts.test.ts index 3f73ce9dd57..637894164e9 100644 --- a/packages/command-surface/src/management/artifacts.test.ts +++ b/packages/command-surface/src/management/artifacts.test.ts @@ -2,15 +2,16 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; import { artifactsCommandFacet } from './artifacts.ts'; import type { CliFlags } from '@agent-device/contracts/command'; +import { createTestHostEnvironment } from '@agent-device/test-kit'; -test('artifacts CLI passes an explicit lease and run through to the daemon command', () => { +test('artifacts CLI passes an explicit lease and run through to the daemon command', async () => { const input = artifactsCommandFacet.cliReader([], { leaseId: 'lease-a', runId: 'run-a', } as CliFlags); assert.equal(input.leaseId, 'lease-a'); assert.equal(input.runId, 'run-a'); - const request = artifactsCommandFacet.daemonWriter(input); + const request = await artifactsCommandFacet.daemonWriter(input, createTestHostEnvironment()); assert.equal(request.options.leaseId, 'lease-a'); assert.equal(request.options.runId, 'run-a'); assert.deepEqual(artifactsCommandFacet.cliSchema.allowedFlags, [ diff --git a/packages/daemon/src/resources/__tests__/lease-registry.test.ts b/packages/daemon/src/resources/__tests__/lease-registry.test.ts index 5acdf17db4d..620a62f4884 100644 --- a/packages/daemon/src/resources/__tests__/lease-registry.test.ts +++ b/packages/daemon/src/resources/__tests__/lease-registry.test.ts @@ -162,10 +162,7 @@ test('a host cannot reissue a released lease id to another artifact owner', () = registry.putHostLease(leaseId, { tenantId: 'tenant-a', runId: 'run-1' }); registry.releaseLease({ leaseId }); - assert.throws( - () => registry.putHostLease(leaseId, { tenantId: 'tenant-b', runId: 'run-2' }), - isLeaseIdInUse, - ); + assert.throws(() => registry.putHostLease(leaseId, { tenantId: 'tenant-b', runId: 'run-2' }), isLeaseIdInUse); }); test('an expired provider lease keeps its id and provider session from a caller-chosen reuse', () => { 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 9cee4a2590c..4d306a98d64 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 @@ -923,17 +923,18 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite const first = await runSuite('tenant-a'); const firstPath = registrations[0]!.path; fs.writeFileSync(path.join(firstPath, 'private-a.txt'), 'tenant-a-private-marker'); + const scopedHeaders = (tenant: string, leaseId: string, runId = tenant) => ({ + authorization: 'Bearer test-token', + 'x-tenant': tenant, + 'x-agent-device-lease-id': leaseId, + 'x-agent-device-run-id': runId, + }); const otherRun = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'other-run', leaseBackend: 'android-instance', }); - const otherRunHeaders = { - authorization: 'Bearer test-token', - 'x-tenant': 'tenant-a', - 'x-agent-device-lease-id': otherRun.leaseId, - 'x-agent-device-run-id': 'other-run', - }; + const otherRunHeaders = scopedHeaders('tenant-a', otherRun.leaseId, 'other-run'); const otherRunInventory = await fetch(`${baseUrl}/artifacts`, { headers: otherRunHeaders, }); @@ -953,22 +954,12 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite path.join(sessionStore.resolveSessionDir('tenant-b:capture'), 'test-artifacts'), ); const inventory = await fetch(`${baseUrl}/artifacts`, { - headers: { - authorization: 'Bearer test-token', - 'x-tenant': 'tenant-b', - 'x-agent-device-lease-id': leases.get('tenant-b')!.leaseId.toUpperCase(), - 'x-agent-device-run-id': 'tenant-b', - }, + headers: scopedHeaders('tenant-b', leases.get('tenant-b')!.leaseId.toUpperCase()), }); expect(inventory.status).toBe(200); expect(JSON.stringify(await inventory.json())).toContain(second.artifactId); const download = await fetch(`${baseUrl}/artifacts/${second.artifactId}`, { - headers: { - authorization: 'Bearer test-token', - 'x-tenant': 'tenant-b', - 'x-agent-device-lease-id': leases.get('tenant-b')!.leaseId.toUpperCase(), - 'x-agent-device-run-id': 'tenant-b', - }, + headers: scopedHeaders('tenant-b', leases.get('tenant-b')!.leaseId.toUpperCase()), }); expect(download.status).toBe(200); const archive = gunzipSync(Buffer.from(await download.arrayBuffer())); @@ -980,22 +971,12 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite const third = await runSuite('tenant-a'); expect(registrations[2]!.path).not.toBe(firstPath); const forbidden = await fetch(`${baseUrl}/artifacts/${first.artifactId}`, { - headers: { - authorization: 'Bearer test-token', - 'x-tenant': 'tenant-b', - 'x-agent-device-lease-id': leases.get('tenant-a')!.leaseId, - 'x-agent-device-run-id': 'tenant-a', - }, + headers: scopedHeaders('tenant-b', leases.get('tenant-a')!.leaseId, 'tenant-a'), }); expect(forbidden.status).toBe(401); for (const artifact of [first, third]) { const own = await fetch(`${baseUrl}/artifacts/${artifact.artifactId}`, { - headers: { - authorization: 'Bearer test-token', - 'x-tenant': 'tenant-a', - 'x-agent-device-lease-id': leases.get('tenant-a')!.leaseId, - 'x-agent-device-run-id': 'tenant-a', - }, + headers: scopedHeaders('tenant-a', leases.get('tenant-a')!.leaseId), }); expect(own.status).toBe(200); await own.arrayBuffer(); diff --git a/packages/remote/src/__tests__/upload-client-lease-headers.test.ts b/packages/remote/src/__tests__/upload-client-lease-headers.test.ts index a8aa659affc..364190fc21e 100644 --- a/packages/remote/src/__tests__/upload-client-lease-headers.test.ts +++ b/packages/remote/src/__tests__/upload-client-lease-headers.test.ts @@ -18,14 +18,15 @@ import { uploadArtifact } from '../upload-client.ts'; const DIRECT_ROUTES = ['POST /upload/preflight', 'PUT /upload/t', 'POST /upload/finalize']; -test.each([ +const cases = [ { flow: 'direct', host: '127.0.0.1', routes: DIRECT_ROUTES, unleased: '' }, { flow: 'legacy', host: '', routes: ['POST /upload/preflight', 'POST /upload'], unleased: '' }, { flow: 'direct', host: 'localhost', routes: DIRECT_ROUTES, unleased: 'PUT /upload/t' }, -])( - 'upload forwards lease and run only to daemon-bound $flow routes for $host', - async ({ flow, host, routes, unleased }, t) => { - if (await skipWhenLoopbackUnavailable(t)) return; +] as const; + +test('upload forwards lease and run only to daemon-bound routes', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + for (const { flow, host, routes, unleased } of cases) { const directory = mkdtempForTestSync(`agent-device-upload-lease-${randomUUID()}-`); const localPath = path.join(directory, 'app.apk'); fs.writeFileSync(localPath, `${flow}-payload`); @@ -76,5 +77,5 @@ test.each([ await closeLoopbackServer(server); fs.rmSync(directory, { recursive: true, force: true }); } - }, -); + } +}); From f8b5b230d469c9f0f943e71c4efd6972e4d2359c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 13:58:57 +0100 Subject: [PATCH 17/35] style: format lease artifact review fixes --- .../daemon/src/resources/__tests__/lease-registry.test.ts | 6 ++++-- packages/daemon/src/resources/artifact-tracking.ts | 6 +++++- packages/daemon/src/resources/provider-session-ownership.ts | 6 +----- .../daemon/src/server/__tests__/resumable-upload.test.ts | 5 ++++- .../src/sessions/handlers/__tests__/install-source.test.ts | 4 +++- 5 files changed, 17 insertions(+), 10 deletions(-) diff --git a/packages/daemon/src/resources/__tests__/lease-registry.test.ts b/packages/daemon/src/resources/__tests__/lease-registry.test.ts index 620a62f4884..1039fa43a85 100644 --- a/packages/daemon/src/resources/__tests__/lease-registry.test.ts +++ b/packages/daemon/src/resources/__tests__/lease-registry.test.ts @@ -161,8 +161,10 @@ test('a host cannot reissue a released lease id to another artifact owner', () = const leaseId = 'cccccccccccccccccccccccccccccccc'; registry.putHostLease(leaseId, { tenantId: 'tenant-a', runId: 'run-1' }); registry.releaseLease({ leaseId }); - - assert.throws(() => registry.putHostLease(leaseId, { tenantId: 'tenant-b', runId: 'run-2' }), isLeaseIdInUse); + assert.throws( + () => registry.putHostLease(leaseId, { tenantId: 'tenant-b', runId: 'run-2' }), + isLeaseIdInUse, + ); }); test('an expired provider lease keeps its id and provider session from a caller-chosen reuse', () => { diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 30203f171c2..839ca9e7df8 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -3,7 +3,11 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { finished } from 'node:stream/promises'; -import { AppError, createRequestCanceledError, type ReasonTable } from '@agent-device/kernel/errors'; +import { + AppError, + createRequestCanceledError, + type ReasonTable, +} from '@agent-device/kernel/errors'; import type { DaemonArtifactType } from '@agent-device/kernel/contracts'; import type { DeviceRotation } from '@agent-device/contracts/device'; import type { DaemonArtifactInventoryEntry } from '@agent-device/contracts/observability'; diff --git a/packages/daemon/src/resources/provider-session-ownership.ts b/packages/daemon/src/resources/provider-session-ownership.ts index 4a454a8e924..aa5a7d9ffcb 100644 --- a/packages/daemon/src/resources/provider-session-ownership.ts +++ b/packages/daemon/src/resources/provider-session-ownership.ts @@ -97,11 +97,7 @@ export class ProviderSessionOwnershipRegistry { if (!provider || !providerSessionId || !tenantId) return undefined; this.prune(); const record = this.records.get(this.key(provider, providerSessionId)); - if ( - !record || - record.tenantId !== tenantId || - (runId && record.runId !== runId) - ) { + if (!record || record.tenantId !== tenantId || (runId && record.runId !== runId)) { return undefined; } return { ...record }; diff --git a/packages/daemon/src/server/__tests__/resumable-upload.test.ts b/packages/daemon/src/server/__tests__/resumable-upload.test.ts index ff33e11c08a..3d65f866ada 100644 --- a/packages/daemon/src/server/__tests__/resumable-upload.test.ts +++ b/packages/daemon/src/server/__tests__/resumable-upload.test.ts @@ -40,7 +40,10 @@ test('resumable upload uses one lease identity across mixed-case retries', async const leaseId = 'ABCDEF0123456789ABCDEF0123456789'; const options = { ...uploadOptions(bytes), tenantId: 'tenant-a', leaseId }; const uploadId = beginResumableUpload(options).uploadId; - assert.equal(beginResumableUpload({ ...options, leaseId: leaseId.toLowerCase() }).uploadId, uploadId); + assert.equal( + beginResumableUpload({ ...options, leaseId: leaseId.toLowerCase() }).uploadId, + uploadId, + ); await receiveResumableUploadChunk({ uploadId, tenantId: 'tenant-a', diff --git a/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts b/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts index b85a08154d1..69990eba859 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts @@ -156,7 +156,9 @@ test('install_source retains output under an existing session lease', async () = expect(response.ok).toBe(true); if (!response.ok) return; const materializationId = response.data?.materializationId as string; - await expect(cleanupRetainedMaterializedPaths(materializationId, 'tenant-a')).rejects.toMatchObject({ + await expect( + cleanupRetainedMaterializedPaths(materializationId, 'tenant-a'), + ).rejects.toMatchObject({ code: 'UNAUTHORIZED', }); await cleanupRetainedMaterializedPaths(materializationId, 'tenant-a', leaseId); From 81c9003b11d2eda02f00b55193ecc54ceda158bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 14:04:35 +0100 Subject: [PATCH 18/35] test: assert leased recording access in tenant capture fixture --- .../http/http-server-capture-tenant.test.ts | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/daemon/src/server/http/http-server-capture-tenant.test.ts b/packages/daemon/src/server/http/http-server-capture-tenant.test.ts index 36e05c5c7c7..4f939fa2d88 100644 --- a/packages/daemon/src/server/http/http-server-capture-tenant.test.ts +++ b/packages/daemon/src/server/http/http-server-capture-tenant.test.ts @@ -80,6 +80,7 @@ test.each([false, true])( const server = await createDaemonHttpServer({ token: 'capture-token', handleRequest, + leaseRegistry, env: { AGENT_DEVICE_HTTP_AUTH_HOOK: hookPath }, cwd: root, }); @@ -122,8 +123,11 @@ test.each([false, true])( const artifactId = stopped.data?.artifacts?.[0]?.artifactId; expect(artifactId).toBeTypeOf('string'); expect(await listDownloadableArtifacts('tenant-b', {})).toEqual([]); + expect(await listDownloadableArtifacts(tenantId, {})).toEqual([]); expect( - (await listDownloadableArtifacts(tenantId, {})).some(({ id }) => id === artifactId), + (await listDownloadableArtifacts(tenantId, {}, lease.leaseId)).some( + ({ id }) => id === artifactId, + ), ).toBe(true); const recovered = await stop(); @@ -131,11 +135,21 @@ test.each([false, true])( if (recovered.ok) expect(recovered.data?.artifacts?.[0]?.artifactId).toBe(artifactId); const otherTenant = await fetch(`${base}/artifacts/${artifactId}`, { - headers: { authorization: 'Bearer capture-token', 'x-tenant': 'tenant-b' }, + headers: { + authorization: 'Bearer capture-token', + 'x-tenant': 'tenant-b', + 'x-agent-device-lease-id': lease.leaseId, + 'x-agent-device-run-id': lease.runId, + }, }); expect(otherTenant.status).toBe(401); const ownTenant = await fetch(`${base}/artifacts/${artifactId}`, { - headers: { authorization: 'Bearer capture-token', 'x-tenant': tenantId }, + headers: { + authorization: 'Bearer capture-token', + 'x-tenant': tenantId, + 'x-agent-device-lease-id': lease.leaseId, + 'x-agent-device-run-id': lease.runId, + }, }); expect(ownTenant.status).toBe(200); expect(await ownTenant.text()).toBe('private-recording'); From 4c1a01a6a77b8898910e7a5abbe7491a47114a47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 14:30:31 +0100 Subject: [PATCH 19/35] fix(daemon): reuse the effective lease for source installs --- .../handlers/__tests__/install-source.test.ts | 37 +++++++++++++++---- .../handlers/session-app-source-deployment.ts | 2 +- .../src/sessions/install-source-resolution.ts | 7 +++- website/docs/docs/device-clouds.md | 2 +- 4 files changed, 36 insertions(+), 12 deletions(-) diff --git a/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts b/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts index 69990eba859..99854aa6cc3 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts @@ -40,6 +40,10 @@ import type { DaemonRequest } from '../../../core/daemon-request.ts'; import type { SessionState } from '../../../core/session-state.ts'; import { handleInstallFromSourceDeploymentCommand } from '../session-app-source-deployment.ts'; import { cleanupRetainedMaterializedPaths } from '../../materialized-path-registry.ts'; +import { + cleanupUploadedArtifact, + trackUploadedArtifact, +} from '../../../resources/artifact-tracking.ts'; type SourceRuntimeOptions = Readonly<{ materializationAvailable?: boolean; @@ -122,10 +126,13 @@ test('install_source materializes and deploys through the admitted ready runtime expect(deploy).toHaveBeenCalledOnce(); }); -test('install_source retains output under an existing session lease', async () => { +test('install_source consumes a leased upload and retains output under the same lease', async () => { const root = mkdtempForTestSync('agent-device-leased-source-'); const appPath = path.join(root, 'app.apk'); + const uploadDir = mkdtempForTestSync('agent-device-leased-upload-'); + const uploadPath = path.join(uploadDir, 'uploaded.apk'); writeFileSync(appPath, 'app'); + writeFileSync(uploadPath, 'uploaded app'); const store = makeStore(); const session = makeSession({ platform: 'android', @@ -137,13 +144,23 @@ test('install_source retains output under an existing session lease', async () = const leaseId = 'abcdef0123456789abcdef0123456789'; session.lease = { leaseId, tenantId: 'tenant-a', runId: 'run-a' }; store.publish(session.name, session); - const runtime = createSourceRuntime( - session.device, - async () => ({ installablePath: appPath, cleanup: async () => {} }), - async () => ({ packageName: 'com.example.app' }), - ); - const req = makeRequest({ kind: 'url', url: 'https://example.com/app.zip', headers: {} }); - req.meta = { ...req.meta, tenantId: 'tenant-a', retainMaterializedPaths: true }; + const uploadedArtifactId = trackUploadedArtifact({ + artifactPath: uploadPath, + tempDir: uploadDir, + tenantId: 'tenant-a', + leaseId, + }); + const materialize = vi.fn(async () => ({ installablePath: appPath, cleanup: async () => {} })); + const runtime = createSourceRuntime(session.device, materialize, async () => ({ + packageName: 'com.example.app', + })); + const req = makeRequest({ kind: 'path', path: 'app.apk' }, { leaseId }); + req.meta = { + ...req.meta, + tenantId: 'tenant-a', + retainMaterializedPaths: true, + uploadedArtifactId, + }; try { const response = await handleInstallFromSourceDeploymentCommand({ platformServices: daemonPlatformServicesFixture(), @@ -155,6 +172,9 @@ test('install_source retains output under an existing session lease', async () = }); expect(response.ok).toBe(true); if (!response.ok) return; + expect(materialize).toHaveBeenCalledWith( + expect.objectContaining({ source: { kind: 'path', path: uploadPath } }), + ); const materializationId = response.data?.materializationId as string; await expect( cleanupRetainedMaterializedPaths(materializationId, 'tenant-a'), @@ -163,6 +183,7 @@ test('install_source retains output under an existing session lease', async () = }); await cleanupRetainedMaterializedPaths(materializationId, 'tenant-a', leaseId); } finally { + cleanupUploadedArtifact(uploadedArtifactId); rmSync(root, { recursive: true, force: true }); } }); 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 303b91a31cf..bd330fe7405 100644 --- a/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts +++ b/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts @@ -72,7 +72,7 @@ export async function handleInstallFromSourceDeploymentCommand(params: { let retained: RetainedMaterializedPaths | undefined; try { const retention = resolveRetention(req); - resolvedSource = resolveInstallSource(req); + resolvedSource = resolveInstallSource(req, leaseId); let device = await resolveInstallDevice( session, req, diff --git a/packages/daemon/src/sessions/install-source-resolution.ts b/packages/daemon/src/sessions/install-source-resolution.ts index ca37280b5ab..e77d525cdbc 100644 --- a/packages/daemon/src/sessions/install-source-resolution.ts +++ b/packages/daemon/src/sessions/install-source-resolution.ts @@ -36,7 +36,10 @@ function requireInstallSource(req: DaemonRequest): DaemonInstallSource { } } -export function resolveInstallSource(req: DaemonRequest): { +export function resolveInstallSource( + req: DaemonRequest, + leaseId?: string, +): { source: DaemonInstallSource; cleanup: () => void; } { @@ -48,7 +51,7 @@ export function resolveInstallSource(req: DaemonRequest): { return { source: { kind: 'path', - path: prepareUploadedArtifact(uploadedArtifactId, req.meta?.tenantId, req.meta?.leaseId), + path: prepareUploadedArtifact(uploadedArtifactId, req.meta?.tenantId, leaseId), }, cleanup: () => { cleanupUploadedArtifact(uploadedArtifactId); diff --git a/website/docs/docs/device-clouds.md b/website/docs/docs/device-clouds.md index b1db7200493..c829f40ee83 100644 --- a/website/docs/docs/device-clouds.md +++ b/website/docs/docs/device-clouds.md @@ -67,7 +67,7 @@ agent-device artifacts --provider --run-id Date: Tue, 1 Dec 2026 16:22:31 +0100 Subject: [PATCH 20/35] fix(daemon): preserve lease scope through artifact delivery and release --- .../screen-recording-stop-recovery.test.ts | 50 ++++++++++++------- .../screen-recording-stop-recovery.ts | 15 +++++- .../daemon/src/resources/lease-registry.ts | 16 ++++-- .../__tests__/request-finalization.test.ts | 6 ++- .../src/server/downloadable-artifact-http.ts | 17 ++++--- .../src/server/http/http-rpc-methods.ts | 14 ++++++ .../http/http-server-capture-tenant.test.ts | 2 - .../http-server-install-retention.test.ts | 1 - .../http-server-provider-scenarios.test.ts | 6 +++ .../daemon/src/server/request-finalization.ts | 12 +++-- packages/daemon/src/server/upload-http.ts | 9 ++-- .../leased-recording-retention.test.ts | 27 +++++----- .../daemon/src/sessions/handlers/lease.ts | 33 ++++++++---- .../src/sessions/handlers/record-runtime.ts | 11 +++- packages/kernel/src/contracts.ts | 1 + .../daemon-artifacts-record-download.test.ts | 13 ++++- packages/remote/src/daemon-artifacts.ts | 20 +++++++- src/commands/schema/cli-help.ts | 2 +- test/wire-compat/ledger.json | 8 +-- website/docs/docs/client-api.md | 5 +- website/docs/docs/device-clouds.md | 4 +- website/docs/docs/error-reasons.md | 4 +- 22 files changed, 191 insertions(+), 85 deletions(-) diff --git a/packages/capture-kit/src/capture-admission/__tests__/screen-recording-stop-recovery.test.ts b/packages/capture-kit/src/capture-admission/__tests__/screen-recording-stop-recovery.test.ts index b6fb6cf0d83..5b578a3320c 100644 --- a/packages/capture-kit/src/capture-admission/__tests__/screen-recording-stop-recovery.test.ts +++ b/packages/capture-kit/src/capture-admission/__tests__/screen-recording-stop-recovery.test.ts @@ -33,20 +33,32 @@ test('a completed manifest with no surviving video serves nothing', async () => await completeRecording(harness); fs.rmSync(harness.videoPath); - expect(resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE })).toEqual( - { kind: 'none' }, - ); + expect( + resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), + ).toEqual({ kind: 'none' }); }); test('a completed manifest hands back the whole stop response it stored', async () => { const harness = makeHarness(); const completion = fullCompletion(harness.videoPath); fs.writeFileSync(harness.videoPath, 'mp4'); - writeManifest(harness, encodeScreenRecordingCompletionMetadata(completion)); + const owner = { tenantId: 'tenant', leaseId: 'producing-lease' }; + writeManifest(harness, { + ...encodeScreenRecordingCompletionMetadata(completion), + remoteCaptureTenantId: owner.tenantId, + remoteCaptureLeaseId: owner.leaseId, + }); - expect(resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE })).toEqual( - { kind: 'completed', completion }, - ); + expect( + resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner }), + ).toEqual({ kind: 'completed', completion }); + expect(() => + resolveScreenRecordingStopRecovery({ + ...harness.params, + device: SESSION_DEVICE, + owner: { ...owner, leaseId: 'other-lease' }, + }), + ).toThrowError(expect.objectContaining({ code: 'UNAUTHORIZED' })); expect(screenRecordingManifestIsTerminal(harness.params)).toBe(true); }); @@ -70,7 +82,7 @@ test('a completed manifest whose stored response is damaged serves nothing', asy for (const damaged of damages) { writeManifest(harness, withStoredCompletion(stored, damaged)); expect( - resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE }), + resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), ).toEqual({ kind: 'none' }); } }); @@ -80,9 +92,9 @@ test('a completed manifest with no completion metadata serves nothing', async () await completeRecording(harness); writeManifest(harness, { phase: 'completed' }); - expect(resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE })).toEqual( - { kind: 'none' }, - ); + expect( + resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), + ).toEqual({ kind: 'none' }); }); test('a completed manifest owned by another session is refused', async () => { @@ -91,7 +103,7 @@ test('a completed manifest owned by another session is refused', async () => { writeManifest(harness, undefined, { sessionId: 'other-session' }); expect(() => - resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE }), + resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), ).toThrowError(expect.objectContaining({ details: { reason: 'runtime-contract-invalid' } })); }); @@ -103,7 +115,7 @@ test('a completed manifest bound to another device is refused', async () => { }); expect(() => - resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE }), + resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), ).toThrowError(expect.objectContaining({ details: { reason: 'runtime-contract-invalid' } })); }); @@ -111,18 +123,18 @@ test('an open manifest stays available for exact-owner recovery', async () => { const harness = makeHarness(); writeManifest(harness, { phase: 'active' }, { lifecycle: 'open' }); - expect(resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE })).toEqual( - { kind: 'open', resourcePath: manifestPath(harness.sessionStore) }, - ); + expect( + resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), + ).toEqual({ kind: 'open', resourcePath: manifestPath(harness.sessionStore) }); expect(screenRecordingManifestIsTerminal(harness.params)).toBe(false); }); test('a session with no recording manifest has nothing to recover', () => { const harness = makeHarness(); - expect(resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE })).toEqual( - { kind: 'none' }, - ); + expect( + resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), + ).toEqual({ kind: 'none' }); expect(screenRecordingManifestIsTerminal(harness.params)).toBe(false); }); diff --git a/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts b/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts index 4e0383fa745..5dbeb0399d6 100644 --- a/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts +++ b/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import { LEASE_REASONS } from '@agent-device/contracts/lease-scope'; import type { JsonObject } from '@agent-device/contracts/client'; import { isRecordingScope, type RecordingAppIdentity } from '@agent-device/contracts/recording'; import { isNativePathDisposition } from '@agent-device/contracts/recording-native-path'; @@ -50,11 +51,23 @@ type ScreenRecordingManifestParams = Readonly<{ }>; export function resolveScreenRecordingStopRecovery( - params: ScreenRecordingManifestParams & Readonly<{ device: DeviceInfo }>, + params: ScreenRecordingManifestParams & + Readonly<{ + device: DeviceInfo; + owner: Readonly<{ tenantId?: string; leaseId?: string }>; + }>, ): ScreenRecordingStopRecovery { const { resourcePath, record } = readSessionManifest(params); if (record.status !== 'decoded') return { kind: 'none' }; assertManifestBelongsToRequest(params, record.envelope); + if ( + record.envelope.metadata?.remoteCaptureTenantId !== params.owner.tenantId || + record.envelope.metadata?.remoteCaptureLeaseId !== params.owner.leaseId + ) { + throw new AppError('UNAUTHORIZED', 'Screen recording belongs to a different tenant or lease', { + reason: LEASE_REASONS.scopeMismatch.reason, + }); + } if (record.envelope.lifecycle !== 'completed') return { kind: 'open', resourcePath }; const completion = readReplayableStoredCompletion(record.envelope.metadata); if (completion === undefined) { diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index 5aa3d88a8c1..dcf6256cc23 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -343,11 +343,18 @@ export class LeaseRegistry { assertLeaseScopeMatch(this.getActiveLease(scope.leaseId), scope); } - /** Uploads prove the active lease's tenant and run; provider/device details stay on lease RPCs. */ - assertUploadLeaseAdmission(request: { leaseId: string; tenantId: string; runId: string }): void { + /** Uploads match the active lease's tenant and any supplied run. */ + assertUploadLeaseAdmission(request: { leaseId: string; tenantId: string; runId?: string }): void { this.cleanupExpiredLeases(); const lease = this.getActiveLease(normalizeRequiredLeaseId(request.leaseId)); - assertLeaseScopeMatch(lease, request); + if ( + lease.tenantId !== request.tenantId || + (request.runId !== undefined && lease.runId !== request.runId.trim()) + ) { + throw new AppError('UNAUTHORIZED', 'Lease does not match tenant/run scope', { + reason: LEASE_REASONS.scopeMismatch.reason, + }); + } } /** Retained artifacts can be read by their original owner after lease release. */ @@ -362,9 +369,8 @@ export class LeaseRegistry { if ( !owner || !request.tenantId || - !request.runId || owner.tenantId !== request.tenantId || - owner.runId !== request.runId || + (request.runId !== undefined && owner.runId !== request.runId.trim()) || (owner.retainedUntil !== undefined && owner.retainedUntil <= this.now()) ) { throw new AppError('UNAUTHORIZED', 'Lease is not owned by the artifact request', { diff --git a/packages/daemon/src/server/__tests__/request-finalization.test.ts b/packages/daemon/src/server/__tests__/request-finalization.test.ts index f8e772a0dbd..c3938dacd56 100644 --- a/packages/daemon/src/server/__tests__/request-finalization.test.ts +++ b/packages/daemon/src/server/__tests__/request-finalization.test.ts @@ -209,7 +209,7 @@ test('finalizeDaemonResponse binds session output to the admitted lease', () => }; const tracked: DownloadableArtifactRegistration[] = []; - finalizeDaemonResponse( + const response = finalizeDaemonResponse( req, { ok: true, @@ -227,6 +227,10 @@ test('finalizeDaemonResponse binds session output to the admitted lease', () => ); expect(tracked[0]?.leaseId).toBe(lease.leaseId); + expect(response.ok && response.data?.artifacts?.[0]?.downloadScope).toEqual({ + leaseId: lease.leaseId, + tenantId: lease.tenantId, + }); }); test('finalizeDaemonResponse leaves unrelated local-path artifacts unregistered', () => { diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index e0685d5d407..75d82ebeef7 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -23,7 +23,7 @@ const ARTIFACT_DOWNLOAD_REASONS = { // The artifact stream ended at a different size than the daemon recorded; `details` gives both // sizes. sizeMismatch: { reason: 'artifact_size_mismatch' }, - // A leased artifact request needs a named run and lease registry. + // A leased artifact request needs a tenant and lease registry. leaseAdmissionRequired: { reason: 'ARTIFACT_LEASE_ADMISSION_REQUIRED' }, } as const satisfies ReasonTable<'artifact downloads'>; @@ -211,16 +211,19 @@ function admitArtifactLease( if ( typeof value !== 'string' || !value.trim() || - typeof runId !== 'string' || - !runId.trim() || + (runId !== undefined && typeof runId !== 'string') || !leaseRegistry ) { - throw new AppError('UNAUTHORIZED', 'Artifact lease requires an admitted tenant and run', { - reason: ARTIFACT_DOWNLOAD_REASONS.leaseAdmissionRequired.reason, - }); + throw new AppError( + 'UNAUTHORIZED', + 'Artifact lease requires an admitted tenant and lease registry', + { + reason: ARTIFACT_DOWNLOAD_REASONS.leaseAdmissionRequired.reason, + }, + ); } const leaseId = normalizeRequiredLeaseId(value); - leaseRegistry.assertArtifactLeaseReadAdmission({ leaseId, tenantId, runId: runId.trim() }); + leaseRegistry.assertArtifactLeaseReadAdmission({ leaseId, tenantId, runId }); return leaseId; } diff --git a/packages/daemon/src/server/http/http-rpc-methods.ts b/packages/daemon/src/server/http/http-rpc-methods.ts index 84646aa9c55..1e423e3130e 100644 --- a/packages/daemon/src/server/http/http-rpc-methods.ts +++ b/packages/daemon/src/server/http/http-rpc-methods.ts @@ -165,6 +165,7 @@ function toInstallFromSourceDaemonRequest( flags: { platform }, meta: { requestId: readStringParam(params, 'requestId'), + ...readDeploymentLeaseScope(params), installSource: parseInstallSource(params), retainMaterializedPaths: readBooleanParam(params, 'retainPaths'), materializedPathRetentionMs: @@ -190,11 +191,24 @@ function toReleaseMaterializedPathsDaemonRequest( positionals: [], meta: { requestId: readStringParam(params, 'requestId'), + ...readDeploymentLeaseScope(params), materializationId, }, }; } +function readDeploymentLeaseScope(params: Record): DaemonRequest['meta'] { + return { + tenantId: readStringParam(params, 'tenantId'), + runId: readStringParam(params, 'runId'), + leaseId: readStringParam(params, 'leaseId'), + leaseBackend: readStringParam(params, 'leaseBackend') as LeaseBackend | undefined, + leaseProvider: readStringParam(params, 'leaseProvider'), + deviceKey: readStringParam(params, 'deviceKey'), + clientId: readStringParam(params, 'clientId'), + }; +} + // The runtime schema reports failures with an internal JSON-path prefix // (e.g. `$.positionals: Expected an array`). Strip the `$` sigil so the wire message // stays user-facing without leaking the schema's internal path representation. diff --git a/packages/daemon/src/server/http/http-server-capture-tenant.test.ts b/packages/daemon/src/server/http/http-server-capture-tenant.test.ts index 4f939fa2d88..f6a5f77c1d0 100644 --- a/packages/daemon/src/server/http/http-server-capture-tenant.test.ts +++ b/packages/daemon/src/server/http/http-server-capture-tenant.test.ts @@ -139,7 +139,6 @@ test.each([false, true])( authorization: 'Bearer capture-token', 'x-tenant': 'tenant-b', 'x-agent-device-lease-id': lease.leaseId, - 'x-agent-device-run-id': lease.runId, }, }); expect(otherTenant.status).toBe(401); @@ -148,7 +147,6 @@ test.each([false, true])( authorization: 'Bearer capture-token', 'x-tenant': tenantId, 'x-agent-device-lease-id': lease.leaseId, - 'x-agent-device-run-id': lease.runId, }, }); expect(ownTenant.status).toBe(200); diff --git a/packages/daemon/src/server/http/http-server-install-retention.test.ts b/packages/daemon/src/server/http/http-server-install-retention.test.ts index 3bed1fa94ea..e2219518ab4 100644 --- a/packages/daemon/src/server/http/http-server-install-retention.test.ts +++ b/packages/daemon/src/server/http/http-server-install-retention.test.ts @@ -156,7 +156,6 @@ test('HTTP leased resumable upload remains readable by install dispatch', async authorization: 'Bearer test-token', 'x-agent-device-tenant': 'tenant-a', 'x-agent-device-lease-id': lease.leaseId, - 'x-agent-device-run-id': 'run-a', }; const wrongRun = await fetch(`${base}/upload/preflight`, { method: 'POST', 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 b13a17dcf04..49cffc0164c 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 @@ -176,6 +176,9 @@ test('Provider-backed integration daemon HTTP server maps RPC methods, auth, and session: 'bootstrap', requestId: 'req-release', materializationId: 'materialized-1', + tenantId: 'Tenant A', + leaseId: '0123456789abcdef0123456789abcdef', + runId: 'run-1', }, }); assert.equal(release.status, 200); @@ -228,6 +231,9 @@ test('Provider-backed integration daemon HTTP server maps RPC methods, auth, and (req) => req.command === 'release_materialized_paths', ); assert.equal(releaseRequest?.meta?.materializationId, 'materialized-1'); + assert.equal(releaseRequest?.meta?.tenantId, 'Tenant A'); + assert.equal(releaseRequest?.meta?.leaseId, '0123456789abcdef0123456789abcdef'); + assert.equal(releaseRequest?.meta?.runId, 'run-1'); } finally { await closeLoopbackServer(server); } diff --git a/packages/daemon/src/server/request-finalization.ts b/packages/daemon/src/server/request-finalization.ts index 55d470f7f28..dd9c7b1f327 100644 --- a/packages/daemon/src/server/request-finalization.ts +++ b/packages/daemon/src/server/request-finalization.ts @@ -100,6 +100,11 @@ function registerDownloadableArtifacts( const register = (artifact: PendingArtifact): DaemonArtifact => { const artifactPath = artifact.path as string; const delivered = daemonDeliveredArtifact(artifact); + const admittedLease = req.internal?.admittedLease; + const leaseId = admittedLease?.leaseId ?? resolveLeaseScope(req).leaseId; + const tenantId = delivered + ? delivered.tenantId + : (captureOutputTenantId(data) ?? admittedLease?.tenantId ?? req.meta?.tenantId); return { field: artifact.field, // Omitted (not null/undefined-valued) when untyped, matching the @@ -107,10 +112,8 @@ function registerDownloadableArtifacts( ...(artifact.artifactType !== undefined ? { artifactType: artifact.artifactType } : {}), artifactId: trackArtifact({ artifactPath, - tenantId: delivered - ? delivered.tenantId - : (captureOutputTenantId(data) ?? req.meta?.tenantId), - leaseId: req.internal?.admittedLease?.leaseId ?? resolveLeaseScope(req).leaseId, + tenantId, + leaseId, artifactType: artifact.artifactType, fileName: artifact.fileName, ...(artifact.deleteAfterDownload === false ? { deleteAfterDownload: false } : {}), @@ -118,6 +121,7 @@ function registerDownloadableArtifacts( ? { displayRotation: artifact.displayRotation } : {}), }), + ...(leaseId ? { downloadScope: { leaseId, tenantId } } : {}), fileName: artifact.fileName, localPath: artifact.localPath, scriptPublicationId: artifact.scriptPublicationId, diff --git a/packages/daemon/src/server/upload-http.ts b/packages/daemon/src/server/upload-http.ts index f017e45bc07..eb5116a10c0 100644 --- a/packages/daemon/src/server/upload-http.ts +++ b/packages/daemon/src/server/upload-http.ts @@ -23,7 +23,7 @@ import { normalizeRequiredLeaseId } from '../resources/lease-registry-scope.ts'; const DIRECT_UPLOAD_PATH_PREFIX = '/upload/direct/'; const UPLOAD_LEASE_REASONS = { - // A leased upload needs an authenticated tenant and a named run and lease registry. + // A leased upload needs a tenant and lease registry. admissionRequired: { reason: 'UPLOAD_LEASE_ADMISSION_REQUIRED' }, } as const satisfies ReasonTable<'uploads'>; @@ -155,19 +155,18 @@ function admitUploadLease( if ( typeof header !== 'string' || !header.trim() || - typeof runId !== 'string' || - !runId.trim() || + (runId !== undefined && typeof runId !== 'string') || !tenantId || !leaseRegistry ) { throw new AppError( 'UNAUTHORIZED', - 'Upload lease requires an admitted tenant, run and lease registry', + 'Upload lease requires an admitted tenant and lease registry', { reason: UPLOAD_LEASE_REASONS.admissionRequired.reason }, ); } const leaseId = normalizeRequiredLeaseId(header); - leaseRegistry.assertUploadLeaseAdmission({ leaseId, tenantId, runId: runId.trim() }); + leaseRegistry.assertUploadLeaseAdmission({ leaseId, tenantId, runId }); return leaseId; } diff --git a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts index 52f29b86c49..3bccb234fdb 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts @@ -141,7 +141,12 @@ function publishRecordingSession( fence: { token: 'recording-fence', generation: 1 }, lifecycle: 'open', descriptor: { version: 1, body: { recordingId: 'checkout-flow' } }, - metadata: { phase: 'active' }, + metadata: { + phase: 'active', + ...(options.leased !== false + ? { remoteCaptureTenantId: TENANT, remoteCaptureLeaseId: LEASE_ID } + : {}), + }, }); session.screenRecording = { handle, envelope }; screenRecordingResourceStore.write( @@ -208,20 +213,15 @@ test('a retained recording is deleted once its tenant downloads it', async (t) = }); const port = await listenOnLoopback(server); try { - for (const runId of [undefined, 'run-2']) { - for (const route of ['/artifacts', `/artifacts/${video!.id}`]) { - const denied = await fetch(`http://127.0.0.1:${port}${route}`, { - headers: { - [DAEMON_HTTP_LEASE_HEADER]: LEASE_ID, - ...(runId ? { [DAEMON_HTTP_RUN_HEADER]: runId } : {}), - }, - }); - expect(denied.status).not.toBe(200); - expect(fs.existsSync(recordingExport.outPath)).toBe(true); - } + for (const route of ['/artifacts', `/artifacts/${video!.id}`]) { + const denied = await fetch(`http://127.0.0.1:${port}${route}`, { + headers: { [DAEMON_HTTP_LEASE_HEADER]: LEASE_ID, [DAEMON_HTTP_RUN_HEADER]: 'run-2' }, + }); + expect(denied.status).toBe(401); + expect(fs.existsSync(recordingExport.outPath)).toBe(true); } const response = await fetch(`http://127.0.0.1:${port}/artifacts/${video!.id}`, { - headers: { [DAEMON_HTTP_LEASE_HEADER]: LEASE_ID, [DAEMON_HTTP_RUN_HEADER]: 'run-1' }, + headers: { [DAEMON_HTTP_LEASE_HEADER]: LEASE_ID }, }); expect(await response.text()).toBe('video'); @@ -284,6 +284,7 @@ test('a record stop replay after a leased teardown serves the artifacts teardown sessionName: ADDRESS, sessionStore, device: IOS_SIMULATOR, + owner: { tenantId: TENANT, leaseId: LEASE_ID }, }); if (recovery.kind !== 'completed') throw new Error(`expected a replay, got ${recovery.kind}`); const replayed = finalizeDaemonResponse( diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index 8fb95d6809c..0779ee9179e 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -108,23 +108,29 @@ export async function handleLeaseCommands(args: LeaseHandlerArgs): Promise { const providerSessionId = readFlagString(req.flags, 'providerSessionId'); if (shouldListDaemonArtifacts(leaseScope, providerSessionId)) { + if (leaseScope.leaseId) { + leaseRegistry.assertArtifactLeaseReadAdmission({ + ...leaseScope, + leaseId: leaseScope.leaseId, + }); + } return await listDaemonArtifacts(leaseScope.tenantId, leaseScope.leaseId, hostEnv); } @@ -626,7 +638,8 @@ function resolveProviderSession( providerSessionId: string | undefined, ): ReturnType { if (!providerSessionId) return undefined; - if (!leaseScope.runId) { + const runId = leaseScope.runId?.trim(); + if (!runId) { throw new AppError('INVALID_ARGS', 'Provider session requires the request run', { reason: LEASE_HANDLER_REASONS.providerSessionRunRequired.reason, hint: 'Pass --run-id for the run that owns this provider session.', @@ -636,7 +649,7 @@ function resolveProviderSession( provider: leaseScope.leaseProvider, providerSessionId, tenantId: leaseScope.tenantId, - runId: leaseScope.runId, + runId, }); if (providerSession) return providerSession; throw new AppError('UNAUTHORIZED', 'Provider session is not owned by the request tenant', { diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index 4f64bf262d9..c944521e463 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -42,6 +42,7 @@ import { screenRecordingManifestDevice, screenRecordingManifestIsTerminal, } from '@agent-device/capture-kit/screen-recording-stop-recovery'; +import { resolveRequestOrSessionLeaseScope } from '../../core/lease-context.ts'; import { resolveSessionScope } from '../session-routing.ts'; import type { SessionStore } from '../../core/session-store.ts'; import type { @@ -276,7 +277,7 @@ async function startRecording( const started = await runtime.operations.screenRecordingStart( screenRecordingStartInput(params, session, prepared, fence, outputPaths), ); - const tenantId = session.lease?.tenantId ?? params.req.meta?.tenantId; + const { tenantId, leaseId } = resolveRecordingOwner(params.req, session); await adoptStartedScreenRecording({ admissionLedger: params.admissionLedger, binding, @@ -285,13 +286,14 @@ async function startRecording( fence, ...started, envelope: - params.req.internal?.publicNetworkOnly || tenantId + params.req.internal?.publicNetworkOnly || tenantId || leaseId ? { ...started.envelope, metadata: { ...started.envelope.metadata, ...(params.req.internal?.publicNetworkOnly ? { remoteCaptureOutput: true } : {}), ...(tenantId ? { remoteCaptureTenantId: tenantId } : {}), + ...(leaseId ? { remoteCaptureLeaseId: leaseId } : {}), }, } : started.envelope, @@ -510,6 +512,7 @@ async function finishRecovered( sessionName: params.sessionName, sessionStore: params.sessionStore, device: session.device, + owner: resolveRecordingOwner(params.req, session), }); if (recovery.kind === 'completed') { return { completion: recovery.completion, recordsSessionAction: false }; @@ -525,6 +528,10 @@ async function finishRecovered( return { completion, recordsSessionAction: true }; } +function resolveRecordingOwner(req: DaemonRequest, session: SessionState) { + return req.internal?.admittedLease ?? resolveRequestOrSessionLeaseScope(req, session); +} + /** * Recovery control bound to a record's own owner and fence, for a recording whose live handle this * daemon no longer holds. A recovered stop and the start-time settle share it. diff --git a/packages/kernel/src/contracts.ts b/packages/kernel/src/contracts.ts index 10e0790444f..0699869d014 100644 --- a/packages/kernel/src/contracts.ts +++ b/packages/kernel/src/contracts.ts @@ -224,6 +224,7 @@ export type DaemonArtifact = { // `DaemonArtifactType | undefined` form so artifact owners must decide. artifactType?: DaemonArtifactType; artifactId?: string; + downloadScope?: { leaseId: string; tenantId?: string }; fileName?: string; localPath?: string; path?: string; diff --git a/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts b/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts index f0304edc06a..ba0498ffe70 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts @@ -18,6 +18,7 @@ async function withRecordingServer( cwd: string, stop: ReturnType, artifactRequests: string[], + requestHeaders: http.IncomingHttpHeaders[], ) => Promise, ): Promise { if (await skipWhenLoopbackUnavailable(t, 'remote recording download')) return; @@ -25,9 +26,11 @@ async function withRecordingServer( const cwd = path.join(root, 'cwd'); fs.mkdirSync(cwd); const artifactRequests: string[] = []; + const requestHeaders: http.IncomingHttpHeaders[] = []; // Each artifact's bytes are its own id, served as binary so the body is never read as HTML. const server = http.createServer((req, res) => { artifactRequests.push(req.url ?? ''); + requestHeaders.push(req.headers); res.writeHead(200, { 'content-type': 'application/octet-stream' }); res.end(path.basename(req.url ?? '')); }); @@ -37,6 +40,7 @@ async function withRecordingServer( cwd, recordStop(`http://127.0.0.1:${port}`, cwd, path.join(root, 'state')), artifactRequests, + requestHeaders, ); } finally { await closeLoopbackServer(server); @@ -72,9 +76,14 @@ const video = { } satisfies DaemonArtifact; test('record stop ignores the daemon localPath and warns about the cwd download', async (t) => { - await withRecordingServer(t, async (cwd, stop) => { + await withRecordingServer(t, async (cwd, stop, _requests, requestHeaders) => { const hostile = path.resolve(cwd, '../hostile.mp4'); - const data = await stop([{ ...video, localPath: hostile }]); + const downloadScope = { leaseId: '0123456789abcdef0123456789abcdef', tenantId: 'tenant-a' }; + const data = await stop([{ ...video, localPath: hostile, downloadScope }]); + expect(requestHeaders[0]).toMatchObject({ + 'x-agent-device-lease-id': downloadScope.leaseId, + 'x-agent-device-tenant': downloadScope.tenantId, + }); const fallback = path.join(cwd, 'clip.mp4'); expect(fs.existsSync(hostile)).toBe(false); expect(fs.readFileSync(fallback, 'utf8')).toBe('video'); diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index ce1aea15714..717933d5538 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -11,10 +11,11 @@ import path from 'node:path'; import { buildRemoteTempArtifactDirPath, buildRemoteTempArtifactPath, + normalizeTenantId, } from '@agent-device/contracts/daemon-http'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { assertScriptTargetVacant, resolveScriptDestination } from '@agent-device/host-kit/file'; -import { leaseScopeFromRequest } from '@agent-device/contracts/lease-scope'; +import { leaseScopeFromRequest, normalizeLeaseId } from '@agent-device/contracts/lease-scope'; import { appendRecordingExtensionWhenMissing, recordingExtensionForPlatform, @@ -601,11 +602,26 @@ async function downloadOneArtifact( dropped.push({ field: artifact.field, reason: 'artifact_name_invalid' }); return; } + const scope = leaseScopeFromRequest(req); + const downloadScope = artifact.downloadScope; + const leaseId = + typeof downloadScope?.leaseId === 'string' + ? normalizeLeaseId(downloadScope.leaseId) + : undefined; + const tenantId = + leaseId && typeof downloadScope?.tenantId === 'string' + ? normalizeTenantId(downloadScope.tenantId) + : undefined; const materializedPath = await downloadRemoteArtifact({ ...endpoint, artifactId: artifact.artifactId, destinationPath: destination.path, - requestScope: req.meta, + requestScope: { + ...req.meta, + tenantId: tenantId ?? scope.tenantId, + leaseId: leaseId ?? scope.leaseId, + runId: scope.runId, + }, // #2246: `test-artifacts` is the one directory-shaped artifact type today — known from the // response, before any bytes arrive, so cleanup-on-error can be decided up front instead of // racing the response headers (a directory destination must never be `rm`'d wholesale; see diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index dd3ae441c96..0ad88c5af2c 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -635,7 +635,7 @@ Rules: To replace an existing connection, pass its returned session explicitly with --session --force. --force without --session creates another fresh session and does not release or overwrite an unrelated active connection. Prefer short-lived AWS role credentials in CI. Generated connection profiles store app/device selectors and ARNs, not Limrun API keys or instance tokens, BrowserStack or TestMu AI access keys, or AWS credentials. Limrun Android supports direct ADB port reverse for local Metro. Limrun iOS requires a public Metro URL because it cannot reach local host ports directly. - After closing a device cloud session, run agent-device artifacts --json to retrieve provider video/log/dashboard URLs when the provider has made them available. + Before closing a device cloud session, save its lease and run IDs. After close, list provider artifacts with agent-device artifacts --provider --lease-id --run-id --json. connect proxy stores the connection profile and client identity. Proxy device leases are acquired on open and expire after five minutes without commands; when a lease expires or is released, the daemon ends the session opened under it and frees its device; devices may inspect proxy inventory without allocating. Multiple agents can share one proxy when each uses connect proxy, open, commands, close, and disconnect. disconnect releases local connection state; close releases the active session and device lease. diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index e07eb36af41..aa2c1808ae0 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -18,7 +18,7 @@ "packages/contracts/src/request-progress.ts#RequestProgressEvent": "sha256:2516c4d0a4e831f779d68e692158b863f6b42c78a7eaac6607ebbffe2d4b6ce5", "packages/kernel/src/contracts.ts#CommandRpcParams": "sha256:3a400b0d815920d9cf4c6236531931f6ba6f9debf7ac26915e0116b493f1c97a", "packages/kernel/src/contracts.ts#DAEMON_LOCK_POLICIES": "sha256:625cc33bb574aa6119add45878a0f6adc445244edc2957737da975f91605c786", - "packages/kernel/src/contracts.ts#DaemonArtifact": "sha256:77dee23e48dc77febb33efadc85377cbbcd137389ae7b33e93ba31670565fdf6", + "packages/kernel/src/contracts.ts#DaemonArtifact": "sha256:d1b8a9a699edc80a581090d5005d57c18f156d503e861f490e77427551141601", "packages/kernel/src/contracts.ts#DaemonArtifactKnownType": "sha256:4a55e654d15d4719a579df4aa1929dda1d52a4acf4c71e9ff78814ad09d6d233", "packages/kernel/src/contracts.ts#ScriptDeliveryFailure": "sha256:186881f8b2e6a0227a6d1a2c802d8f7356fee39d4137800a0c9fa65401aa2765", "packages/kernel/src/contracts.ts#DaemonArtifactType": "sha256:5e5017276fefe880b8ab32001888011d2e02a8670f0978afdb9b56a77ab37f09", @@ -128,9 +128,9 @@ "packages/daemon/src/server/http/http-authorization.ts#resolveToken": "sha256:3abcb019e1325317618045b7138e41845990af10953dd937571997cd6ec35981", "packages/daemon/src/server/http/http-rpc-envelope.ts#sendJson": "sha256:a1de00da3f1db8c98e69a85dfe2e11b626a4d2ce472840e3b8f519aa8a207a8f", "packages/daemon/src/server/http/http-rpc-methods.ts#toDaemonRequest": "sha256:d6afa5f8f1219e519e72bbd6fddd7de7763818f1ed7ae2a1e2a12001bd66bd52", - "packages/daemon/src/server/http/http-rpc-methods.ts#toInstallFromSourceDaemonRequest": "sha256:071c53e7bd8e553cb9df820961294ed4d1e2e385053485364d895cb1777e9429", + "packages/daemon/src/server/http/http-rpc-methods.ts#toInstallFromSourceDaemonRequest": "sha256:c77a325fbfaaf95c788acff442d7cb418321b5671914feea6d546980d9dc6e3a", "packages/daemon/src/server/http/http-rpc-methods.ts#toLeaseDaemonRequest": "sha256:e017795c86534feb8a7e6e53ffbd614db893aad20c5406b2bc53c771ee646948", - "packages/daemon/src/server/http/http-rpc-methods.ts#toReleaseMaterializedPathsDaemonRequest": "sha256:708736ca03d6a3fc449bb408382dbd509e490de1f84ecc8771fd77d4adda0154", + "packages/daemon/src/server/http/http-rpc-methods.ts#toReleaseMaterializedPathsDaemonRequest": "sha256:52cd65da4141f3a7138b3925d28a667cca0af751c37070052d922b4d4c85b82e", "packages/daemon/src/server/http/http-rpc-envelope.ts#writeProgressEnvelope": "sha256:7be778b3902c72d7aa6282c16dc7106fdd64e99c0b5daf9f413ff5dd3fb044f1", "packages/daemon/src/server/http/http-rpc-envelope.ts#writeRpcResponseEnvelope": "sha256:7a8155e9fcbb53485489728250a85109b5dab0d96cdd4aa8b7e7eb87a4898ddb", "packages/daemon/src/core/session-tenant-scope.ts#TenantSessionNamespace": "sha256:a6613d22933caa053e479f05b7f016664f6be8d0afdbbf81e578ff497fc1b13d", @@ -245,7 +245,7 @@ "packages/daemon-contracts/src/daemon-resolution.ts#DaemonCapability": "sha256:2a5acf280a72e3d54c5ad7b52aece3ced37a30e4e721ef106a98e3bbd18ddbc3", "packages/daemon-contracts/src/daemon-resolution.ts#readDaemonCapabilities": "sha256:e410d36be74d307f7e5d8ddae63af5aae77f8eef77951ce9eeb7724f2fefae88", "packages/remote/src/daemon-artifacts.ts#downloadResponseArtifacts": "sha256:ba600575e06995bc903c107477b23f7853e920751452a50a9734fab6677326bf", - "packages/remote/src/daemon-artifacts.ts#downloadOneArtifact": "sha256:dd8726c99d2e5a4c63ad5f66392732d0116496af50251d7d03007d605b29012d", + "packages/remote/src/daemon-artifacts.ts#downloadOneArtifact": "sha256:2025b8848795a8703e373ab9d4497a2028b6f88d5fcde8ce2630c178a2fa388b", "packages/remote/src/daemon-artifacts.ts#DroppedArtifact": "sha256:c340f0a9a4b99d0664f8c32ac78b3a054c95e7f171cf3531331f7cdc143e0cfb", "packages/remote/src/session-script-destination.ts#SessionScriptDelivery": "sha256:741fafbb8e2b43e2e967b2f4206f1d60017a636f63e3cde68b6258fd4efefa18", "packages/remote/src/script-version-publisher.ts#publishScriptVersion": "sha256:b37b9391d20f535ca9c0858f92ed37943297c7acbf1fb10f8cad5cd5b53423eb", diff --git a/website/docs/docs/client-api.md b/website/docs/docs/client-api.md index e007922daf4..d82b9e097b9 100644 --- a/website/docs/docs/client-api.md +++ b/website/docs/docs/client-api.md @@ -94,12 +94,13 @@ stdout/stderr. The option mirrors `open --launch-console` and is not valid for U `client.sessions.stateDir()` mirrors `session state-dir` and returns the resolved daemon state directory without starting or contacting the daemon. Pass `{ stateDir }` to resolve an explicit override the same way the CLI resolves `--state-dir`. -`client.sessions.artifacts({ provider, providerSessionId })` mirrors `artifacts --provider ... --provider-session ...` and returns provider-hosted `cloudArtifacts`. -Use it for BrowserStack, AWS Device Farm, or TestMu AI session videos/logs after a cloud session has stopped; `client.sessions.close()` returns the ID as `closed.provider?.providerSessionId`. Omit `providerSessionId` when an embedding host has registered a provider runtime that can infer the active lease. Limrun does not expose provider artifacts through this command. +`client.sessions.artifacts({ provider, providerSessionId, runId })` mirrors `artifacts --provider ... --provider-session ...` and returns provider-hosted `cloudArtifacts`. +Use it for BrowserStack, AWS Device Farm, or TestMu AI session videos/logs after a cloud session has stopped; `client.sessions.close()` returns the ID as `closed.provider?.providerSessionId`. Pass the run ID from the original connection. Omit `providerSessionId` when an embedding host has registered a provider runtime that can infer the active lease. Limrun does not expose provider artifacts through this command. ```ts const result = await client.sessions.artifacts({ provider: 'aws-device-farm', + runId: producingRunId, providerSessionId: 'arn:aws:devicefarm:us-west-2:123:session/project/session/00000', }); diff --git a/website/docs/docs/device-clouds.md b/website/docs/docs/device-clouds.md index c829f40ee83..27d8f6e1188 100644 --- a/website/docs/docs/device-clouds.md +++ b/website/docs/docs/device-clouds.md @@ -60,14 +60,14 @@ Use `snapshot -i` to confirm the target. If the driver does not support the `/el ## Retrieve artifacts after close -After `close`, run `agent-device artifacts --json` to check for the artifacts your provider makes available (see [Compare providers](#compare-providers)). To look up an earlier session, pass its provider session ID: +Before `close`, save the lease ID and run ID from the connection you used. After `close`, pass both IDs to `agent-device artifacts --json` to list retained daemon artifacts. For provider-hosted artifacts, also pass `--provider ` (see [Compare providers](#compare-providers)). If `close --json` returns a provider session ID, you can look it up directly: ```bash agent-device artifacts --provider --run-id --json ``` Providers finalize video and log URLs after the session ends. If the lookup reports artifacts as pending right after `close`, retry it a little later. -To list daemon or provider artifacts for a lease without a provider session ID, pass that lease's `--lease-id` and `--run-id`. To look up a provider session directly, pass its provider session ID and run ID as shown above. +Use the tenant that owned the producing lease and the run ID from the original connection. ## NoMac diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 6077b20d107..c21bf4be170 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -579,7 +579,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `artifact_size_mismatch` | The artifact stream ended at a different size than the daemon recorded; `details` gives both sizes. | -| `ARTIFACT_LEASE_ADMISSION_REQUIRED` | A leased artifact request needs a named run and lease registry. | +| `ARTIFACT_LEASE_ADMISSION_REQUIRED` | A leased artifact request needs a tenant and lease registry. | ### Artifact extraction @@ -1079,7 +1079,7 @@ These reasons can come from more than one command. | `UPLOAD_FINALIZE_CLEANUP_FAILED` | Finalizing the upload failed, and removing its staged files failed too; `details.originalError` holds the first failure. | | `UPLOAD_CAPACITY_EXCEEDED` | A new upload would exceed the active upload count or reserved byte budget. | | `RESUMABLE_UPLOAD_LEASE_MISMATCH` | A staged upload belongs to another lease of the same tenant. | -| `UPLOAD_LEASE_ADMISSION_REQUIRED` | A leased upload needs an authenticated tenant and a named run and lease registry. | +| `UPLOAD_LEASE_ADMISSION_REQUIRED` | A leased upload needs a tenant and lease registry. | | `transfer_ingress_deadline_exceeded` | The upload request exceeded its aggregate deadline (`details.timeoutMs`), which also covers processing after the body arrived. | | `upload_canceled` | The client disconnected or canceled before the upload finished. | From f9e6d8f8300960b3cd71a26db9d2d8e9f75ed39b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 16:46:27 +0100 Subject: [PATCH 21/35] fix: align lease artifact admission and upload scope --- .../screen-recording-stop-recovery.test.ts | 46 +++++-- .../screen-recording-stop-recovery.ts | 6 +- .../src/__tests__/index-lease-header.test.ts | 28 +++- .../__tests__/request-handler-catalog.test.ts | 20 ++- .../handlers/__tests__/install-source.test.ts | 123 +++++++++--------- .../daemon/src/sessions/handlers/lease.ts | 70 +++++----- .../src/sessions/handlers/record-runtime.ts | 2 +- .../handlers/session-app-deployment.ts | 16 +-- .../handlers/session-app-source-deployment.ts | 32 +++-- .../src/sessions/install-source-resolution.ts | 5 +- .../upload-client-lease-headers.test.ts | 6 +- packages/remote/src/daemon-artifacts.ts | 6 +- packages/remote/src/upload-client.ts | 64 +++++---- test/wire-compat/ledger.json | 20 +-- website/docs/docs/client-api.md | 2 +- website/docs/docs/commands.md | 1 + 16 files changed, 254 insertions(+), 193 deletions(-) diff --git a/packages/capture-kit/src/capture-admission/__tests__/screen-recording-stop-recovery.test.ts b/packages/capture-kit/src/capture-admission/__tests__/screen-recording-stop-recovery.test.ts index 5b578a3320c..74b3eeb5851 100644 --- a/packages/capture-kit/src/capture-admission/__tests__/screen-recording-stop-recovery.test.ts +++ b/packages/capture-kit/src/capture-admission/__tests__/screen-recording-stop-recovery.test.ts @@ -34,7 +34,11 @@ test('a completed manifest with no surviving video serves nothing', async () => fs.rmSync(harness.videoPath); expect( - resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), + await resolveScreenRecordingStopRecovery({ + ...harness.params, + device: SESSION_DEVICE, + owner: {}, + }), ).toEqual({ kind: 'none' }); }); @@ -50,15 +54,15 @@ test('a completed manifest hands back the whole stop response it stored', async }); expect( - resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner }), + await resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner }), ).toEqual({ kind: 'completed', completion }); - expect(() => + await expect( resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: { ...owner, leaseId: 'other-lease' }, }), - ).toThrowError(expect.objectContaining({ code: 'UNAUTHORIZED' })); + ).rejects.toMatchObject({ code: 'UNAUTHORIZED' }); expect(screenRecordingManifestIsTerminal(harness.params)).toBe(true); }); @@ -82,7 +86,11 @@ test('a completed manifest whose stored response is damaged serves nothing', asy for (const damaged of damages) { writeManifest(harness, withStoredCompletion(stored, damaged)); expect( - resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), + await resolveScreenRecordingStopRecovery({ + ...harness.params, + device: SESSION_DEVICE, + owner: {}, + }), ).toEqual({ kind: 'none' }); } }); @@ -93,7 +101,11 @@ test('a completed manifest with no completion metadata serves nothing', async () writeManifest(harness, { phase: 'completed' }); expect( - resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), + await resolveScreenRecordingStopRecovery({ + ...harness.params, + device: SESSION_DEVICE, + owner: {}, + }), ).toEqual({ kind: 'none' }); }); @@ -102,9 +114,9 @@ test('a completed manifest owned by another session is refused', async () => { await completeRecording(harness); writeManifest(harness, undefined, { sessionId: 'other-session' }); - expect(() => + await expect( resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), - ).toThrowError(expect.objectContaining({ details: { reason: 'runtime-contract-invalid' } })); + ).rejects.toMatchObject({ details: { reason: 'runtime-contract-invalid' } }); }); test('a completed manifest bound to another device is refused', async () => { @@ -114,9 +126,9 @@ test('a completed manifest bound to another device is refused', async () => { device: deviceIdentity({ ...SESSION_DEVICE, id: 'emulator-5556' }), }); - expect(() => + await expect( resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), - ).toThrowError(expect.objectContaining({ details: { reason: 'runtime-contract-invalid' } })); + ).rejects.toMatchObject({ details: { reason: 'runtime-contract-invalid' } }); }); test('an open manifest stays available for exact-owner recovery', async () => { @@ -124,16 +136,24 @@ test('an open manifest stays available for exact-owner recovery', async () => { writeManifest(harness, { phase: 'active' }, { lifecycle: 'open' }); expect( - resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), + await resolveScreenRecordingStopRecovery({ + ...harness.params, + device: SESSION_DEVICE, + owner: {}, + }), ).toEqual({ kind: 'open', resourcePath: manifestPath(harness.sessionStore) }); expect(screenRecordingManifestIsTerminal(harness.params)).toBe(false); }); -test('a session with no recording manifest has nothing to recover', () => { +test('a session with no recording manifest has nothing to recover', async () => { const harness = makeHarness(); expect( - resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), + await resolveScreenRecordingStopRecovery({ + ...harness.params, + device: SESSION_DEVICE, + owner: {}, + }), ).toEqual({ kind: 'none' }); expect(screenRecordingManifestIsTerminal(harness.params)).toBe(false); }); diff --git a/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts b/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts index 5dbeb0399d6..de5f1327e62 100644 --- a/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts +++ b/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts @@ -1,5 +1,4 @@ import fs from 'node:fs'; -import { LEASE_REASONS } from '@agent-device/contracts/lease-scope'; import type { JsonObject } from '@agent-device/contracts/client'; import { isRecordingScope, type RecordingAppIdentity } from '@agent-device/contracts/recording'; import { isNativePathDisposition } from '@agent-device/contracts/recording-native-path'; @@ -50,13 +49,13 @@ type ScreenRecordingManifestParams = Readonly<{ sessionStore: Readonly<{ resolveSessionDir(name: string): string }>; }>; -export function resolveScreenRecordingStopRecovery( +export async function resolveScreenRecordingStopRecovery( params: ScreenRecordingManifestParams & Readonly<{ device: DeviceInfo; owner: Readonly<{ tenantId?: string; leaseId?: string }>; }>, -): ScreenRecordingStopRecovery { +): Promise { const { resourcePath, record } = readSessionManifest(params); if (record.status !== 'decoded') return { kind: 'none' }; assertManifestBelongsToRequest(params, record.envelope); @@ -64,6 +63,7 @@ export function resolveScreenRecordingStopRecovery( record.envelope.metadata?.remoteCaptureTenantId !== params.owner.tenantId || record.envelope.metadata?.remoteCaptureLeaseId !== params.owner.leaseId ) { + const { LEASE_REASONS } = await import('@agent-device/contracts/lease-scope'); throw new AppError('UNAUTHORIZED', 'Screen recording belongs to a different tenant or lease', { reason: LEASE_REASONS.scopeMismatch.reason, }); diff --git a/packages/daemon-client/src/__tests__/index-lease-header.test.ts b/packages/daemon-client/src/__tests__/index-lease-header.test.ts index 05f1a92ab1e..9404afcca9e 100644 --- a/packages/daemon-client/src/__tests__/index-lease-header.test.ts +++ b/packages/daemon-client/src/__tests__/index-lease-header.test.ts @@ -17,11 +17,14 @@ import { skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; import { sendToDaemon } from '../index.ts'; -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 DAEMON_TOKEN = 'remote-secret'; -type SeenRequest = { route: string; leaseHeader: string | undefined }; +type SeenRequest = { route: string; leaseHeader: string | undefined; tenantHeader?: string }; const tempDirs: string[] = []; @@ -57,8 +60,10 @@ async function withRemoteDaemon( } if (req.url !== '/rpc') { const leaseHeader = req.headers[DAEMON_HTTP_LEASE_HEADER]; + const tenantHeader = req.headers[DAEMON_HTTP_TENANT_HEADER]; seen.push({ route, + ...(typeof tenantHeader === 'string' ? { tenantHeader } : {}), leaseHeader: typeof leaseHeader === 'string' ? leaseHeader : undefined, }); } @@ -198,3 +203,22 @@ test('a remote upload, artifact download and diagnostics fetch send no lease hea }, ]); }); + +test('a remote local-file install stages with the tenant carried in command flags', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + + await withRemoteDaemon(async (baseUrl, seen) => { + const apkPath = path.join(tempDir('agent-device-install-tenant-'), 'app.apk'); + fs.writeFileSync(apkPath, 'apk-bytes'); + const leaseId = 'a'.repeat(32); + await sendRemote( + baseUrl, + { command: 'install', positionals: [apkPath], flags: { tenant: 'tenant-a' } }, + leaseId, + ); + assert.deepEqual(seen, [ + { route: 'POST /upload/preflight', leaseHeader: leaseId, tenantHeader: 'tenant-a' }, + { route: 'POST /upload', leaseHeader: leaseId, tenantHeader: 'tenant-a' }, + ]); + }); +}); 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 890037618bb..496eea6b67e 100644 --- a/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts +++ b/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts @@ -200,12 +200,20 @@ test('lease handler preserves device-aware lease fields', async () => { test('lease artifacts lists daemon inventory for proxy lease scopes', async () => { const leaseRegistry = new LeaseRegistry(); const sessionStore = makeSessionStore('agent-device-lease-artifacts-'); - const tracked = trackProxyLeaseArtifact(); + const lease = leaseRegistry.allocateLease({ + tenantId: 'tenant-a', + runId: 'run-a', + backend: 'ios-instance', + leaseProvider: 'proxy', + deviceKey: 'device-1', + clientId: 'client-a', + }); + const tracked = trackProxyLeaseArtifact(lease.leaseId); try { const response = await handleLeaseCommands({ host: createTestHostEnvironment(), - req: proxyArtifactsRequest(), + req: proxyArtifactsRequest(lease.leaseId), sessionName: 'catalog-test', sessionStore, leaseRegistry, @@ -595,7 +603,7 @@ function catalogRouteRequest(command: string): DaemonRequest { }; } -function trackProxyLeaseArtifact(): { artifactId: string; tempDir: string } { +function trackProxyLeaseArtifact(leaseId: string): { artifactId: string; tempDir: string } { const tempDir = mkdtempForTestSync('agent-device-lease-artifacts-'); const artifactPath = path.join(tempDir, 'proxy-shot.png'); fs.writeFileSync(artifactPath, 'png-body'); @@ -606,12 +614,12 @@ function trackProxyLeaseArtifact(): { artifactId: string; tempDir: string } { artifactType: 'screenshot', fileName: 'proxy-shot.png', tenantId: 'tenant-a', - leaseId: 'lease-a', + leaseId, }), }; } -function proxyArtifactsRequest(): DaemonRequest { +function proxyArtifactsRequest(leaseId: string): DaemonRequest { return { command: PUBLIC_COMMANDS.artifacts, token: 'test-token', @@ -619,7 +627,7 @@ function proxyArtifactsRequest(): DaemonRequest { meta: { tenantId: 'tenant-a', runId: 'run-a', - leaseId: 'lease-a', + leaseId, leaseProvider: 'proxy', deviceKey: 'device-1', clientId: 'client-a', diff --git a/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts b/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts index 99854aa6cc3..301f0529fcc 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/install-source.test.ts @@ -126,67 +126,72 @@ test('install_source materializes and deploys through the admitted ready runtime expect(deploy).toHaveBeenCalledOnce(); }); -test('install_source consumes a leased upload and retains output under the same lease', async () => { - const root = mkdtempForTestSync('agent-device-leased-source-'); - const appPath = path.join(root, 'app.apk'); - const uploadDir = mkdtempForTestSync('agent-device-leased-upload-'); - const uploadPath = path.join(uploadDir, 'uploaded.apk'); - writeFileSync(appPath, 'app'); - writeFileSync(uploadPath, 'uploaded app'); - const store = makeStore(); - const session = makeSession({ - platform: 'android', - id: 'emulator-5554', - name: 'Pixel', - kind: 'emulator', - booted: true, - }); - const leaseId = 'abcdef0123456789abcdef0123456789'; - session.lease = { leaseId, tenantId: 'tenant-a', runId: 'run-a' }; - store.publish(session.name, session); - const uploadedArtifactId = trackUploadedArtifact({ - artifactPath: uploadPath, - tempDir: uploadDir, - tenantId: 'tenant-a', - leaseId, - }); - const materialize = vi.fn(async () => ({ installablePath: appPath, cleanup: async () => {} })); - const runtime = createSourceRuntime(session.device, materialize, async () => ({ - packageName: 'com.example.app', - })); - const req = makeRequest({ kind: 'path', path: 'app.apk' }, { leaseId }); - req.meta = { - ...req.meta, - tenantId: 'tenant-a', - retainMaterializedPaths: true, - uploadedArtifactId, - }; - try { - const response = await handleInstallFromSourceDeploymentCommand({ - platformServices: daemonPlatformServicesFixture(), - req, - sessionName: session.name, - sessionStore: store, - inspectFacts: runtime.inspectFacts, - bindDevice: runtime.bindDevice, +test.each(['explicit request', 'implicit session'])( + 'install_source consumes a leased upload and retains output under the %s lease', + async (scope) => { + const root = mkdtempForTestSync('agent-device-leased-source-'); + const appPath = path.join(root, 'app.apk'); + const uploadDir = mkdtempForTestSync('agent-device-leased-upload-'); + const uploadPath = path.join(uploadDir, 'uploaded.apk'); + writeFileSync(appPath, 'app'); + writeFileSync(uploadPath, 'uploaded app'); + const store = makeStore(); + const session = makeSession({ + platform: 'android', + id: 'emulator-5554', + name: 'Pixel', + kind: 'emulator', + booted: true, }); - expect(response.ok).toBe(true); - if (!response.ok) return; - expect(materialize).toHaveBeenCalledWith( - expect.objectContaining({ source: { kind: 'path', path: uploadPath } }), - ); - const materializationId = response.data?.materializationId as string; - await expect( - cleanupRetainedMaterializedPaths(materializationId, 'tenant-a'), - ).rejects.toMatchObject({ - code: 'UNAUTHORIZED', + const leaseId = 'abcdef0123456789abcdef0123456789'; + session.lease = { leaseId, tenantId: 'tenant-a', runId: 'run-a' }; + store.publish(session.name, session); + const uploadedArtifactId = trackUploadedArtifact({ + artifactPath: uploadPath, + tempDir: uploadDir, + tenantId: 'tenant-a', + leaseId, }); - await cleanupRetainedMaterializedPaths(materializationId, 'tenant-a', leaseId); - } finally { - cleanupUploadedArtifact(uploadedArtifactId); - rmSync(root, { recursive: true, force: true }); - } -}); + const materialize = vi.fn(async () => ({ installablePath: appPath, cleanup: async () => {} })); + const runtime = createSourceRuntime(session.device, materialize, async () => ({ + packageName: 'com.example.app', + })); + const explicitScope = scope === 'explicit request'; + const req = makeRequest({ kind: 'path', path: 'app.apk' }, explicitScope ? { leaseId } : {}); + + req.meta = { + ...req.meta, + ...(explicitScope ? { tenantId: 'tenant-a' } : {}), + retainMaterializedPaths: true, + uploadedArtifactId, + }; + try { + const response = await handleInstallFromSourceDeploymentCommand({ + platformServices: daemonPlatformServicesFixture(), + req, + sessionName: session.name, + sessionStore: store, + inspectFacts: runtime.inspectFacts, + bindDevice: runtime.bindDevice, + }); + expect(response.ok).toBe(true); + if (!response.ok) return; + expect(materialize).toHaveBeenCalledWith( + expect.objectContaining({ source: { kind: 'path', path: uploadPath } }), + ); + const materializationId = response.data?.materializationId as string; + await expect( + cleanupRetainedMaterializedPaths(materializationId, 'tenant-a'), + ).rejects.toMatchObject({ + code: 'UNAUTHORIZED', + }); + await cleanupRetainedMaterializedPaths(materializationId, 'tenant-a', leaseId); + } finally { + cleanupUploadedArtifact(uploadedArtifactId); + rmSync(root, { recursive: true, force: true }); + } + }, +); test.each(['emulator-5554', 'emulator-5556'])( 'install_source adopts readiness metadata before materialization and deployment (%s)', diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index 0779ee9179e..a2b45d9a957 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -101,42 +101,12 @@ export async function handleLeaseCommands(args: LeaseHandlerArgs): Promise, - }; - } + case PUBLIC_COMMANDS.artifacts: + return await handleArtifactInventory(args, leaseScope); case 'lease_allocate': { assertTenantMayAllocate(leaseScope.leaseBackend); // The registry stores the trimmed, validated id, so every admission check reads that id: @@ -531,6 +501,42 @@ function assertProviderCredentialsUnchanged( ); } +async function handleArtifactInventory( + args: LeaseHandlerArgs, + leaseScope: ReturnType, +): Promise { + const { req, leaseRegistry, cloudArtifactProvider } = args; + const providerSessionId = readFlagString(req.flags, 'providerSessionId'); + const session = args.sessionStore.get(args.sessionName); + if (!leaseScope.leaseId && !providerSessionId && session?.lease) { + throw new AppError('INVALID_ARGS', 'Leased session artifacts require --lease-id', { + reason: LEASE_HANDLER_REASONS.artifactLeaseIdRequired.reason, + hint: 'Pass --lease-id and --run-id for the lease that produced the artifacts.', + }); + } + const sessionScope = resolveRequestOrSessionLeaseScope(req, session); + const sessionLease = session?.lease; + const matchingProviderSession = + providerSessionId && + sessionLease && + leaseRegistry.resolveProviderSession({ + provider: sessionScope.leaseProvider, + providerSessionId, + tenantId: leaseScope.tenantId, + runId: leaseScope.runId, + })?.leaseId === sessionLease.leaseId; + return { + ok: true, + data: (await listArtifactsForRequest( + req, + matchingProviderSession ? sessionScope : leaseScope, + leaseRegistry, + cloudArtifactProvider, + args.host.env, + )) as Record, + }; +} + async function listArtifactsForRequest( req: DaemonRequest, leaseScope: ReturnType, diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index c944521e463..234b79eb928 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -508,7 +508,7 @@ async function finishRecovered( session: SessionState, needsReadiness: boolean, ): Promise { - const recovery = resolveScreenRecordingStopRecovery({ + const recovery = await resolveScreenRecordingStopRecovery({ sessionName: params.sessionName, sessionStore: params.sessionStore, device: session.device, diff --git a/packages/daemon/src/sessions/handlers/session-app-deployment.ts b/packages/daemon/src/sessions/handlers/session-app-deployment.ts index 2b0accdabfb..469e26fee23 100644 --- a/packages/daemon/src/sessions/handlers/session-app-deployment.ts +++ b/packages/daemon/src/sessions/handlers/session-app-deployment.ts @@ -29,7 +29,7 @@ import type { SessionRef, SessionState } from '../../core/session-state.ts'; import { resolveDeployResultTarget } from '@agent-device/contracts/deploy-result-target'; import { withSuccessText } from '@agent-device/kernel/success-text'; import { recordSessionAction } from '../../core/session-action-recorder.ts'; -import { resolveLeaseScope } from '../../core/lease-context.ts'; +import { resolveRequestOrSessionLeaseScope } from '../../core/lease-context.ts'; import { requireSessionOrExplicitSelector, resolveCommandDevice, @@ -68,21 +68,17 @@ export async function handleAppDeploymentCommand(params: { }): Promise { const { req, command, sessionName, sessionStore } = params; const ref = sessionStore.lookup(sessionName); - const session = ref?.session; - const flags = req.flags ?? {}; - const guard = requireSessionOrExplicitSelector(command, session, flags); + const guard = requireSessionOrExplicitSelector(command, ref?.session, req.flags); if (guard) return guard; const target = resolveDeployTarget(command, req.positionals ?? []); if (!target.ok) return target.response; + const session = ref?.session; const uploadedArtifactId = req.meta?.uploadedArtifactId; // Acquire before the cleanup scope: a rejected foreign upload ID must not delete that upload. + const owner = req.internal?.admittedLease ?? resolveRequestOrSessionLeaseScope(req, session); const appPath = uploadedArtifactId - ? prepareUploadedArtifact( - uploadedArtifactId, - req.meta?.tenantId, - req.internal?.admittedLease?.leaseId ?? resolveLeaseScope(req).leaseId, - ) + ? prepareUploadedArtifact(uploadedArtifactId, owner.tenantId, owner.leaseId) : expandSessionPath(target.appPathInput, requestCwd(req, params.host)); try { if (!fs.existsSync(appPath)) { @@ -106,7 +102,7 @@ export async function handleAppDeploymentCommand(params: { device, owner: runtime.owner, bindDevice, - flags, + flags: req.flags ?? {}, env: sessionStore.host.env, deadlineAtMs: undefined, }); 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 bd330fe7405..2bb2b3ca1ba 100644 --- a/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts +++ b/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts @@ -34,7 +34,11 @@ import type { SessionState } from '../../core/session-state.ts'; import { resolveInstallFromSourceResultTarget } from '@agent-device/contracts/deploy-result-target'; import { withSuccessText } from '@agent-device/kernel/success-text'; import { recordSessionAction } from '../../core/session-action-recorder.ts'; -import { resolveLeaseScope, resolveRequestOrSessionLeaseScope } from '../../core/lease-context.ts'; +import { + resolveLeaseScope, + resolveRequestOrSessionLeaseScope, + type LeaseScope, +} from '../../core/lease-context.ts'; import { resolveCommandDevice } from '../../resources/session-device-resolution.ts'; import { requireRuntimeBinding, @@ -65,14 +69,13 @@ export async function handleInstallFromSourceDeploymentCommand(params: { const { req, sessionName, sessionStore } = params; const ref = sessionStore.lookup(sessionName); const session = ref?.session; - const leaseId = - req.internal?.admittedLease?.leaseId ?? resolveRequestOrSessionLeaseScope(req, session).leaseId; + const owner = req.internal?.admittedLease ?? resolveRequestOrSessionLeaseScope(req, session); let resolvedSource: ReturnType | undefined; let materialized: MaterializedAppSource | undefined; let retained: RetainedMaterializedPaths | undefined; try { const retention = resolveRetention(req); - resolvedSource = resolveInstallSource(req, leaseId); + resolvedSource = resolveInstallSource(req, owner); let device = await resolveInstallDevice( session, req, @@ -117,8 +120,7 @@ export async function handleInstallFromSourceDeploymentCommand(params: { retained = await retainIfRequested({ artifact: materialized, retention, - req, - leaseId, + owner, session, sessionName, }); @@ -138,8 +140,8 @@ export async function handleInstallFromSourceDeploymentCommand(params: { if (retained) { await cleanupRetainedMaterializedPaths( retained.materializationId, - req.meta?.tenantId, - leaseId, + owner.tenantId, + owner.leaseId, ).catch(() => {}); } return { ok: false, error: normalizeError(error) }; @@ -158,11 +160,8 @@ export async function handleReleaseMaterializedPathsCommand(params: { if (!materializationId) { throw new AppError('INVALID_ARGS', 'release_materialized_paths requires a materializationId'); } - await cleanupRetainedMaterializedPaths( - materializationId, - req.meta?.tenantId, - req.internal?.admittedLease?.leaseId ?? resolveLeaseScope(req).leaseId, - ); + const owner = req.internal?.admittedLease ?? resolveLeaseScope(req); + await cleanupRetainedMaterializedPaths(materializationId, owner.tenantId, owner.leaseId); return { ok: true, data: { released: true, materializationId } }; } catch (error) { return { ok: false, error: normalizeError(error) }; @@ -222,8 +221,7 @@ function resolveRetention(req: DaemonRequest): Retention { async function retainIfRequested(params: { artifact: MaterializedAppSource; retention: Retention; - req: DaemonRequest; - leaseId: string | undefined; + owner: Pick; session: SessionState | undefined; sessionName: string; }): Promise { @@ -231,8 +229,8 @@ async function retainIfRequested(params: { return await retainMaterializedPaths({ archivePath: params.artifact.archivePath, installablePath: params.artifact.installablePath, - tenantId: params.req.meta?.tenantId, - leaseId: params.leaseId, + tenantId: params.owner.tenantId, + leaseId: params.owner.leaseId, sessionName: params.session ? params.sessionName : undefined, ttlMs: params.retention.ttlMs, }); diff --git a/packages/daemon/src/sessions/install-source-resolution.ts b/packages/daemon/src/sessions/install-source-resolution.ts index e77d525cdbc..4e06a8c5d67 100644 --- a/packages/daemon/src/sessions/install-source-resolution.ts +++ b/packages/daemon/src/sessions/install-source-resolution.ts @@ -5,6 +5,7 @@ import { prepareUploadedArtifact, } from '../resources/artifact-tracking.ts'; import type { DaemonRequest } from '../core/daemon-request.ts'; +import type { LeaseScope } from '../core/lease-context.ts'; function requireInstallSource(req: DaemonRequest): DaemonInstallSource { const source = req.meta?.installSource; @@ -38,7 +39,7 @@ function requireInstallSource(req: DaemonRequest): DaemonInstallSource { export function resolveInstallSource( req: DaemonRequest, - leaseId?: string, + owner: Pick = { tenantId: req.meta?.tenantId }, ): { source: DaemonInstallSource; cleanup: () => void; @@ -51,7 +52,7 @@ export function resolveInstallSource( return { source: { kind: 'path', - path: prepareUploadedArtifact(uploadedArtifactId, req.meta?.tenantId, leaseId), + path: prepareUploadedArtifact(uploadedArtifactId, owner.tenantId, owner.leaseId), }, cleanup: () => { cleanupUploadedArtifact(uploadedArtifactId); diff --git a/packages/remote/src/__tests__/upload-client-lease-headers.test.ts b/packages/remote/src/__tests__/upload-client-lease-headers.test.ts index 364190fc21e..bc740addcba 100644 --- a/packages/remote/src/__tests__/upload-client-lease-headers.test.ts +++ b/packages/remote/src/__tests__/upload-client-lease-headers.test.ts @@ -13,6 +13,7 @@ import { import { DAEMON_HTTP_LEASE_HEADER, DAEMON_HTTP_RUN_HEADER, + DAEMON_HTTP_TENANT_HEADER, } from '@agent-device/contracts/daemon-http'; import { uploadArtifact } from '../upload-client.ts'; @@ -24,7 +25,7 @@ const cases = [ { flow: 'direct', host: 'localhost', routes: DIRECT_ROUTES, unleased: 'PUT /upload/t' }, ] as const; -test('upload forwards lease and run only to daemon-bound routes', async (t) => { +test('upload forwards tenant, lease and run only to daemon-bound routes', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; for (const { flow, host, routes, unleased } of cases) { const directory = mkdtempForTestSync(`agent-device-upload-lease-${randomUUID()}-`); @@ -37,6 +38,7 @@ test('upload forwards lease and run only to daemon-bound routes', async (t) => { headers.set(`${req.method} ${req.url}`, [ req.headers[DAEMON_HTTP_LEASE_HEADER], req.headers[DAEMON_HTTP_RUN_HEADER], + req.headers[DAEMON_HTTP_TENANT_HEADER], ]); for await (const chunk of req) void chunk; res.setHeader('content-type', 'application/json'); @@ -63,12 +65,14 @@ test('upload forwards lease and run only to daemon-bound routes', async (t) => { env: process.env, leaseId, runId: leaseId ? 'run-a' : undefined, + tenantId: 'tenant-a', }); const expected = routes.map((route) => [ route, [ route === unleased ? undefined : leaseId, route === unleased ? undefined : leaseId ? 'run-a' : undefined, + route === unleased ? undefined : 'tenant-a', ], ]); assert.deepEqual([...headers], expected); diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 717933d5538..9c48df82e9a 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -203,8 +203,7 @@ async function prepareRemoteInstallPackage( baseUrl: info.baseUrl!, token: info.token, platform: req.flags?.platform, - leaseId: leaseScopeFromRequest(req).leaseId, - runId: leaseScopeFromRequest(req).runId, + ...leaseScopeFromRequest(req), onProgress, signal, }); @@ -309,8 +308,7 @@ async function prepareRemoteInstallSource( baseUrl: info.baseUrl!, token: info.token, platform: req.flags?.platform, - leaseId: leaseScopeFromRequest(req).leaseId, - runId: leaseScopeFromRequest(req).runId, + ...leaseScopeFromRequest(req), onProgress, signal, }); diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index a4857c05bd9..6eae6848499 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -5,6 +5,7 @@ import { buildDaemonHttpAuthHeaders, buildDaemonHttpLeaseHeaders, buildDaemonHttpRunHeaders, + buildDaemonHttpTenantHeaders, } from '@agent-device/contracts/daemon-http'; import { prepareUploadArtifact, type PreparedUploadArtifact } from './upload-client-artifact.ts'; import { @@ -33,6 +34,7 @@ type UploadArtifactOptions = { /** The lease this upload is for; every request to the daemon names it in a header. */ leaseId?: string; runId?: string; + tenantId?: string; onProgress?: UploadProgressSink; /** * Ends the upload when the thing it is uploading for stops being worth finishing — today, a beat @@ -93,6 +95,7 @@ async function uploadArtifactWithinBudget( token: options.token, leaseId: options.leaseId, runId: options.runId, + tenantId: options.tenantId, artifact: prepared, uploadAttemptId, env: options.env, @@ -108,6 +111,7 @@ async function uploadArtifactWithinBudget( token: options.token, leaseId: options.leaseId, runId: options.runId, + tenantId: options.tenantId, artifact: prepared, preflight, uploadAttemptId, @@ -127,6 +131,7 @@ async function uploadArtifactWithinBudget( token: options.token, leaseId: options.leaseId, runId: options.runId, + tenantId: options.tenantId, artifact: prepared, onProgress: options.onProgress, signal: options.signal, @@ -138,6 +143,7 @@ async function uploadArtifactWithinBudget( token: options.token, leaseId: options.leaseId, runId: options.runId, + tenantId: options.tenantId, artifact: prepared, onProgress: options.onProgress, signal: options.signal, @@ -152,6 +158,7 @@ async function tryDirectUploadWithResume(options: { token: string; leaseId?: string; runId?: string; + tenantId?: string; artifact: PreparedUploadArtifact; preflight: Extract; uploadAttemptId: string; @@ -168,6 +175,7 @@ async function tryDirectUploadWithResume(options: { token: options.token, leaseId: options.leaseId, runId: options.runId, + tenantId: options.tenantId, uploadId: preflight.uploadId, signal: options.signal, }); @@ -199,6 +207,7 @@ async function retryDirectUpload( token: string; leaseId?: string; runId?: string; + tenantId?: string; artifact: PreparedUploadArtifact; uploadAttemptId: string; env: HostEnvironment['env']; @@ -214,6 +223,7 @@ async function retryDirectUpload( token: options.token, leaseId: options.leaseId, runId: options.runId, + tenantId: options.tenantId, artifact: options.artifact, uploadAttemptId: options.uploadAttemptId, env: options.env, @@ -244,11 +254,12 @@ async function uploadLegacyArtifact(options: { token: string; leaseId?: string; runId?: string; + tenantId?: string; artifact: PreparedUploadArtifact; onProgress?: UploadProgressSink; signal: AbortSignal; }): Promise { - const { normalizedBase, token, leaseId, artifact } = options; + const { normalizedBase, token, artifact } = options; const uploadUrl = new URL('upload', normalizedBase); const headers: Record = { @@ -259,12 +270,7 @@ async function uploadLegacyArtifact(options: { 'x-artifact-hash-algorithm': ARTIFACT_HASH_ALGORITHM, 'transfer-encoding': 'chunked', }; - Object.assign( - headers, - buildDaemonHttpAuthHeaders(token), - buildDaemonHttpLeaseHeaders(leaseId), - buildDaemonHttpRunHeaders(options.runId), - ); + Object.assign(headers, buildDaemonHttpAuthHeaders(token), uploadScopeHeaders(options)); const response = await streamFileToHttpRequest({ url: uploadUrl, @@ -293,26 +299,37 @@ async function uploadLegacyArtifact(options: { } } +function uploadScopeHeaders(scope: Pick) { + return { + ...buildDaemonHttpTenantHeaders(scope.tenantId), + ...buildDaemonHttpLeaseHeaders(scope.leaseId), + ...buildDaemonHttpRunHeaders(scope.runId), + }; +} + +function uploadControlHeaders( + scope: Pick, +) { + return { + 'content-type': 'application/json', + ...buildDaemonHttpAuthHeaders(scope.token), + ...uploadScopeHeaders(scope), + }; +} + async function requestUploadPreflight(options: { normalizedBase: string; token: string; leaseId?: string; runId?: string; + tenantId?: string; artifact: PreparedUploadArtifact; uploadAttemptId: string; env: HostEnvironment['env']; signal?: AbortSignal; }): Promise { const preflightUrl = new URL('upload/preflight', options.normalizedBase); - const headers: Record = { - 'content-type': 'application/json', - }; - Object.assign( - headers, - buildDaemonHttpAuthHeaders(options.token), - buildDaemonHttpLeaseHeaders(options.leaseId), - buildDaemonHttpRunHeaders(options.runId), - ); + const headers = uploadControlHeaders(options); const result = await requestUploadControl( preflightUrl, @@ -421,6 +438,7 @@ async function uploadDirectArtifact( normalizedBase: string; leaseId?: string; runId?: string; + tenantId?: string; artifact: PreparedUploadArtifact; onProgress?: UploadProgressSink; signal: AbortSignal; @@ -438,8 +456,7 @@ async function uploadDirectArtifact( url.origin === new URL(options.normalizedBase).origin ? { ...ticket.headers, - ...buildDaemonHttpLeaseHeaders(options.leaseId), - ...buildDaemonHttpRunHeaders(options.runId), + ...uploadScopeHeaders(options), } : ticket.headers, payloadPath: artifact.payloadPath, @@ -466,19 +483,12 @@ async function finalizeDirectUpload(options: { token: string; leaseId?: string; runId?: string; + tenantId?: string; uploadId: string; signal?: AbortSignal; }): Promise { const finalizeUrl = new URL('upload/finalize', options.normalizedBase); - const headers: Record = { - 'content-type': 'application/json', - }; - Object.assign( - headers, - buildDaemonHttpAuthHeaders(options.token), - buildDaemonHttpLeaseHeaders(options.leaseId), - buildDaemonHttpRunHeaders(options.runId), - ); + const headers = uploadControlHeaders(options); const result = await requestUploadControl( finalizeUrl, diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index aa2c1808ae0..97279ea2497 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -174,15 +174,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:e3a005b87fc51f74187a761ebdcccacc316e8de1a9fcd23e25529bb5312dade3", + "packages/remote/src/upload-client.ts#finalizeDirectUpload": "sha256:dc86827543249852132213585db86b47fab482ecf5df01eaad93110d234e8625", "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:5689da0c0cd18d0293e5bb05ddc0d8a07d1bca9ab1d94f8ca185b03bc5b8d758", - "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:4b35726208b30b16d9cbcf268aae8d6d48b4afecfbb9c5ea25ec950f85e559a8", + "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:73831aa50b752300836e1e5d6c0bd3fa0e31d5535f45f0b708973b4d62bb81d0", "packages/remote/src/upload-client.ts#shouldRetryDirectUpload": "sha256:29059f076ff7f2b9540ad15408be48792b2d63a601ef2b9fb2d54f5576d49bbd", - "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:54401ef57b2f6aaa3f904867278936affc47d056dfdfad48bbb93fb3eb852ac7", - "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:5d3f1677bbe8689c5572f1af40fd7fd401bc8f0c7dd191a6b7e21e6a9906cbd2", - "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:5ca45f3ed66b3457354f6e510ae4d22cd8132de37ae9792b0c9dabfb4f7ab635", + "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:1922f3de72d9b24f5d02df0a6d4d911e40086763bace3fe0e22facf8b9f7b47b", + "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:da21e40e125d8f8a45f3c1ba184e7e034e50d5f4f997cd0dc0f5ce21db36771b", + "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:9c4e373fc0eb2684a78faf1d8f3321a149e944d94c2be2fad0a66c7932d31a18", "packages/remote/src/upload-stream.ts#MAX_UPLOAD_REDIRECTS": "sha256:12ff46dfe33a1dce95bdb79c90c17a3ba4f3919e7dc4b3a1b04590fff430f79f", "packages/remote/src/upload-stream.ts#UploadStreamResponse": "sha256:724e284c2a6bd7b4b3a49b1d8c61c8923d6cc24777c3d76224a69d190e56adce", "packages/remote/src/upload-stream.ts#buildUploadRequestHeaders": "sha256:827576b13a9f3e6cea445119a6a29b2ac5eaa23b66436cf810b2d09765c82a4c", @@ -533,11 +533,6 @@ "digest": "sha256:5689da0c0cd18d0293e5bb05ddc0d8a07d1bca9ab1d94f8ca185b03bc5b8d758", "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." }, - { - "declaration": "packages/daemon/src/server/http/http-rpc-methods.ts#toInstallFromSourceDaemonRequest", - "digest": "sha256:071c53e7bd8e553cb9df820961294ed4d1e2e385053485364d895cb1777e9429", - "rationale": "Implementation-only validation repair: a supplied retentionMs is validated before request projection instead of silently dropping fractions or malformed values. Existing integer values in the supported 1..2147483647 range and omitted values keep their request projection, defaults, payload fields and response framing. Unsupported durations now fail clearly with the existing INVALID_ARGS envelope; released clients can parse that normal command error. No route, authentication, method or wire field changes; no protocol bump under ADR 0006." - }, { "declaration": "packages/contracts/src/lease-scope.ts#buildDaemonRpcRequest", "digest": "sha256:b3d03bb08f8f332b04dea6d2ea30abca2faf83a10f11cb874df2344b3f54c2b6", @@ -568,11 +563,6 @@ "digest": "sha256:d744044d036a46221c3b8220179cc30e1e66b8619a4e5cd3f7dd5f8582817aba", "rationale": "#4434 accepts optional query components on the existing POST upload, preflight and finalize routes. Existing query-free paths and methods resolve identically; direct-upload IDs still exclude the query. This broadens accepted request targets without removing a route or changing any response framing under ADR 0006." }, - { - "declaration": "packages/kernel/src/contracts.ts#DaemonArtifact", - "digest": "sha256:77dee23e48dc77febb33efadc85377cbbcd137389ae7b33e93ba31670565fdf6", - "rationale": "#4511 adds the optional scriptPublicationId string and scriptRevision number, which a daemon sets only on a session-script artifact for a remote recording. A released client ignores the unknown fields and downloads the artifact like any other file named by its field; every existing field keeps its meaning." - }, { "declaration": "packages/daemon/src/server/http/http-authorization.ts#HttpAuthHookContext", "digest": "sha256:f6b0b0ff2db474168b53af51994c81d32459b5010f643c965eba66f3ca89b737", diff --git a/website/docs/docs/client-api.md b/website/docs/docs/client-api.md index d82b9e097b9..92c27ac2adb 100644 --- a/website/docs/docs/client-api.md +++ b/website/docs/docs/client-api.md @@ -100,7 +100,7 @@ Use it for BrowserStack, AWS Device Farm, or TestMu AI session videos/logs after ```ts const result = await client.sessions.artifacts({ provider: 'aws-device-farm', - runId: producingRunId, + runId: 'original-connection-run-id', providerSessionId: 'arn:aws:devicefarm:us-west-2:123:session/project/session/00000', }); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index a8cb253b167..6e0ff922eb2 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2381,6 +2381,7 @@ Exact behavior: `agent-device help record`. - `android_screenrecord_startup_failed` means the device refused to record, and `details.stderr` holds the device's message. agent-device has no other Android recording backend. - Limrun sessions always record the whole screen. - `apple_simulator_recording_busy` means another recording holds the simulator. Run `record stop` in the session that owns it. +- Stop active leased recordings before upgrading to daemon protocol 4. To recover a recording started on protocol 3, use the daemon version that started it. - `record stop` is safe to repeat. If it returns `video_validator_compile_timeout`, or the request ends during export, run `record stop` again; the recording is kept. `video_validator_unavailable` names a host failure to repair before you retry. - On HarmonyOS, if the export goes missing or becomes unreadable while cleanup is pending, retry `record stop` in the same session to recover it from the device. If stop reports `manual-recovery-required`, recover the recording before retrying. - `record start --scope device` without a session creates one, and `record stop` ends it, unless something else started using the session meanwhile. From 93251c20ec1d55fe007d06045ecebe47c1f61bd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 16:49:44 +0100 Subject: [PATCH 22/35] test(daemon): align lease and recording fixtures with their contracts --- .../src/sessions/__tests__/leased-recording-retention.test.ts | 2 +- .../src/sessions/__tests__/request-handler-catalog.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts index 3bccb234fdb..ab40a7e092d 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts @@ -280,7 +280,7 @@ test('a record stop replay after a leased teardown serves the artifacts teardown await teardown(sessionStore); const retained = await listDownloadableArtifacts(TENANT, process.env, LEASE_ID); - const recovery = resolveScreenRecordingStopRecovery({ + const recovery = await resolveScreenRecordingStopRecovery({ sessionName: ADDRESS, sessionStore, device: IOS_SIMULATOR, 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 496eea6b67e..2e977d17c3d 100644 --- a/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts +++ b/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts @@ -203,7 +203,7 @@ test('lease artifacts lists daemon inventory for proxy lease scopes', async () = const lease = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-a', - backend: 'ios-instance', + leaseBackend: 'ios-instance', leaseProvider: 'proxy', deviceKey: 'device-1', clientId: 'client-a', From 9ddbd0992d57a9d41d84b98f4efff3a2e122d7eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 08:15:47 +0100 Subject: [PATCH 23/35] fix(daemon): normalize empty tenant for unleased recording recovery --- .../__tests__/record-runtime-stop-recovery.test.ts | 6 +++--- packages/daemon/src/sessions/handlers/record-runtime.ts | 9 +++++++-- 2 files changed, 10 insertions(+), 5 deletions(-) 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 4958c2e1203..7780404b52b 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 @@ -74,7 +74,7 @@ vi.mock('@agent-device/device-selection/dispatch-resolve', () => ({ resolveTargetDeviceMock(...(args as Parameters)), })); -test('record stop after a daemon restart replays the completed export for the named session', async () => { +test('record stop after a daemon restart replays the completed export with an empty tenant', async () => { // The #3674 state itself: sessions are memory-only, so a restart drops `recording`, while the // on-disk manifest survives. The caller still names the session (the only address that finds // the manifest at all), and `help record` promises the completed recording on that stop — even @@ -85,14 +85,14 @@ test('record stop after a daemon restart replays the completed export for the na 'capture.mp4', ); fs.writeFileSync(outPath, 'mp4'); - await harness.run(['start', outPath]); + await harness.run(['start', outPath], { tenantId: '' }); await harness.run(['stop']); const ref = harness.sessionStore.lookup(harness.sessionName); if (!ref) throw new Error('Expected the stopped recording session'); harness.sessionStore.retire(ref); resolveTargetDeviceMock.mockClear(); - const recovered = await harness.run(['stop'], { sessionExplicit: true }); + const recovered = await harness.run(['stop'], { sessionExplicit: true, tenantId: '' }); expect(recovered).toMatchObject({ ok: true, diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index 234b79eb928..e63d2fa3f13 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -528,8 +528,13 @@ async function finishRecovered( return { completion, recordsSessionAction: true }; } -function resolveRecordingOwner(req: DaemonRequest, session: SessionState) { - return req.internal?.admittedLease ?? resolveRequestOrSessionLeaseScope(req, session); +function resolveRecordingOwner( + req: DaemonRequest, + session: SessionState, +): { tenantId?: string; leaseId?: string } { + const owner = req.internal?.admittedLease ?? resolveRequestOrSessionLeaseScope(req, session); + if (owner.tenantId === '' && owner.leaseId === undefined) return {}; + return owner; } /** From b2f9ffe623e02e6c83c33bc391bcfd2690bca4e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 08:30:03 +0100 Subject: [PATCH 24/35] fix(daemon): require a tenant owner before leased recording --- .../command-surface/src/recording/index.ts | 1 + .../record-runtime-stop-recovery.test.ts | 26 +++++++++++++++++-- .../src/sessions/handlers/record-runtime.ts | 9 ++++++- website/docs/docs/commands.md | 1 + 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/packages/command-surface/src/recording/index.ts b/packages/command-surface/src/recording/index.ts index c0fe40c0b3f..f889854b77a 100644 --- a/packages/command-surface/src/recording/index.ts +++ b/packages/command-surface/src/recording/index.ts @@ -129,6 +129,7 @@ export const recordCommandFacet = defineCommandFacet({ summary: 'Start or stop screen recording', searchHint: 'mp4', cliDetail: + 'A leased recording requires a tenant owner before it can start. ' + 'MP4 verification setup starts in the background before recording output preparation, without delaying capture. If setup exceeds the stop budget, details.reason is video_validator_compile_timeout (retriable); run record stop again while setup continues. Hosts without xcrun keep container-only MP4 completion. Other compilation failures, or an unavailable validator executable or AVFoundation during verification, return video_validator_unavailable. A Swift helper cache that is not private to this user returns swift_cache_untrusted. When details.ancestor is the configured cache root or a directory above it that the group or other users can write, remove that write access (chmod g-w,o-w) from that directory. When it is v3 or a directory inside it (bin, home or module-cache), do not chmod it: that clears the refusal but keeps whatever was written while it was open. Set AGENT_DEVICE_SWIFT_CACHE_DIR to a new directory only you can write, or remove that directory yourself; agent-device never deletes it. When details.exposure is untrusted_developer_dir, the DEVELOPER_DIR selection is refused; it is checked only when a Swift helper compiles, and a cached helper is reused without checking it: restart the daemon with DEVELOPER_DIR unset, or set DEVELOPER_DIR to an empty value for one local command to select the system default, or point it at an Xcode Contents/Developer directory, given as an absolute path, that root or you own along with every directory above it. Repair the reported failure and retry record stop; a failed compile is retried on the next start or stop. The default --scope app requires an active app session from open ; use --scope device/system to explicitly request whole-screen recording where the selected backend supports it. Android record start publishes a durable device manifest, recordings longer than the 180s adb screenrecord limit are returned as multiple MP4 chunks while the daemon stays alive, and daemon-restart recovery uses only manifest-owned chunks. An Android recorder the device refuses at startup returns COMMAND_FAILED with reason android_screenrecord_startup_failed, and details.stderr carries the message the native recorder printed. That message is the verdict of the device policy, so report it to the device manufacturer; agent-device has no alternative Android recording backend. Android screenrecord encodes a frame only when the screen changes, so a clip can end at the last frame the recorder encoded instead of at record stop; durationMs is host wall clock from record start until the export finished, and capturedDurationMs reports the video timeline when it can be measured, with a warning naming how much of the window that video covers. An Android manifest left by an unreachable recording is retired on the next start once its recorders are proven gone; one still owned refuses with non-retriable DEVICE_IN_USE and reason native_recovery_evidence_open naming the session to run record stop for, and a recorder that is still writing an artifact refuses with DEVICE_IN_USE and reason native_recording_artifact_claimed, which clears itself once that recorder ends at the 180s limit. HarmonyOS supports whole-screen recording on physical devices only: use --scope device/system; --fps, --quality, and --hide-touches are unsupported. If a HarmonyOS export goes missing or becomes unreadable while cleanup is pending, retry record stop in the same session to recover it from the device. If stop reports manual-recovery-required, recover the recording before retrying. Use --quality to choose medium or high export quality on supported backends. The touch overlay renders at most 30 frames a second, or at --fps when lower; a lower --fps makes record stop faster on a long recording, and an overlay export that runs past its budget returns the raw video with an overlayWarning. A watchOS simulator records the same way an iOS simulator does: the host runs simctl recordVideo, so the watch needs no runner recorder and the export keeps the resolution of the watch. An iOS simulator host recording lock returns non-retriable DEVICE_IN_USE with reason apple_simulator_recording_busy. Stop the recording in its owning session; if a dead recorder left the host locked, ask the host operator to restart the CoreSimulator stream service. A physical iPhone or iPad on a USB cable of this Mac records the USB screen-capture source of the device near 60 fps when both recording transports belong to this host; otherwise it records runner screenshots (help physical-device). A USB capture recording learns the capture source of a device when every other device with its name has a learned source and the store in ~/.agent-device can be written, and later recordings of that device open that source while it has the device name, and otherwise match by name; only a newer exact match replaces what was learned. When USB capture cannot record, before its first frame, the runner records instead and recorderFallbackReason names why: ios_usb_capture_camera_access_not_authorized (agent-device never asks for camera access), ios_usb_capture_device_name_shared (no capture source is learned for the device, and another Apple device in the inventory of the daemon, cabled or wireless, that has no learned source, or another USB capture source on this Mac that is not learned for another device, has the name, or the inventory could not be read), ios_usb_capture_source_of_another_device (no capture source is learned for the device, and another device learned the capture source that matched its name while it started), ios_usb_capture_device_not_found (neither the source learned for the device nor a source with the device name appeared; the learned source is kept), ios_usb_capture_no_frames (screen asleep or locked), or ios_usb_capture_start_busy (another USB capture recording on this Mac, of any user, held the host-wide start lock). USB capture fails the start with ios_usb_capture_start_lock_unusable (another account owns the start lock file and does not let this user read it). On any backend, record start first settles the open recording records on its device that it would refuse on and whose session this daemon no longer holds: it finishes each one as its own record stop would, so the export lands at the output path of that recording and a later record stop in that session returns it, and runs the exact-owner recovery a daemon restart runs, which discards what that recording left, only for a record that cannot finish. A record it cannot confirm cleaned, or one whose session is still held, refuses the start with reason cleanup-unconfirmed and names that session: stop or close it, then retry. A record that another device left under the same session name is never settled from this device: the start refuses and names that device, so stop it in that session or record under another session name. A record stop that cannot produce its export keeps what a retry reads back — on Android the device-side artifact and the native manifest — leaves the recording manifest of that session open, and returns its own error, so retry record stop in that session; while this daemon holds that session, only closing it disposes them, and once it does not, the next record start on that device settles them as described above. Every stopped recording also reports what became of its recorder and of the file that recorder writes to: recorder is confirmed, or lost when the session holding it died, and nativePathDisposition is retirable while that file still owes a removal or retired once its removal was verified. Both are optional disclosures, not failures; ADR 0024 declares further states (unconfirmed, pending) for the steps that gain those probes, and no stop reports them yet. record contact-sheet [--out ] is a local report over a file you already exported: it decodes frames out of that MP4 and writes one PNG holding the cells where the screen visibly changed, each labeled with its elapsed time on the clip timeline. It needs no session and no device, rebuilds any past recording, and works for every backend that exports MP4; a WebM recording is refused with reason contact_sheet_container_unsupported. The sample grid is bounded and spread across the whole clip, so it reports coverage rather than a review: a flash that opens and closes entirely between two sample times is not in the sheet, which is why the result also reports how many times it sampled and how many frames came back. Frame decoding is Apple AVFoundation tooling, so the command runs only on macOS hosts and refuses elsewhere with reason contact_sheet_unsupported_host.', }, metadata: recordCommandMetadata, 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 7780404b52b..13211ed21cb 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 @@ -105,6 +105,26 @@ test('record stop after a daemon restart replays the completed export with an em ); }); +test.each([undefined, ''])( + 'record start requires a tenant for lease metadata (%s)', + async (tenantId) => { + const harness = makeRecordRuntimeHarness('record-runtime-lease-owner-', { + appBundleId: 'com.example.app', + }); + + const response = await harness.run(['start'], { tenantId, leaseId: 'a'.repeat(32) }); + + expect(response).toMatchObject({ + ok: false, + error: { + code: 'UNAUTHORIZED', + details: { reason: 'LEASE_SCOPE_REQUIRED', field: 'tenantId' }, + }, + }); + expect(harness.runtime.start).not.toHaveBeenCalled(); + }, +); + test('record stop recovery after a daemon restart keeps the request host-scoping selectors', async () => { // --android-device-allowlist says WHERE to look, not which device. A recovery that dropped it // would resolve (or fail) outside the allowlist the recording was started under. @@ -195,7 +215,9 @@ test('record stop recovery carries the request lease and discovery context', asy ); fs.writeFileSync(outPath, 'mp4'); const leaseFlags = { - leaseId: 'lease-1', + tenant: 'tenant-1', + runId: 'run-1', + leaseId: 'b'.repeat(32), leaseProvider: 'proxy', deviceKey: 'android:mobile:emulator-5554', clientId: 'client-1', @@ -203,7 +225,7 @@ test('record stop recovery carries the request lease and discovery context', asy expect(await harness.run(['start', outPath], undefined, { ...leaseFlags })).toMatchObject({ ok: true, }); - expect(await harness.run(['stop'])).toMatchObject({ ok: true }); + expect(await harness.run(['stop'], undefined, { ...leaseFlags })).toMatchObject({ ok: true }); expectDecodedCompletedRecording(harness.sessionStore, harness.sessionName); const ref = harness.sessionStore.lookup(harness.sessionName); if (!ref) throw new Error('Expected the stopped recording session'); diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index e63d2fa3f13..3027154a142 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -18,6 +18,7 @@ import { screenRecordingStartUse, } from '@agent-device/contracts/screen-recording-runtime-plan'; import { isWholeScreenRecordingScope } from '@agent-device/contracts/recording'; +import { LEASE_REASONS } from '@agent-device/contracts/lease-scope'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { namesSessionExplicitly } from '@agent-device/kernel/contracts'; import { @@ -249,6 +250,13 @@ async function startRecording( if (session.screenRecording) { return { ok: false, error: { code: 'INVALID_ARGS', message: 'recording already in progress' } }; } + const { tenantId, leaseId } = resolveRecordingOwner(params.req, session); + if (leaseId !== undefined && !tenantId) { + throw new AppError('UNAUTHORIZED', 'Leased recording requires a tenant owner', { + reason: LEASE_REASONS.scopeRequired.reason, + field: 'tenantId', + }); + } const draft = ref ? undefined : bindRecordOnlyScreenRecording(params.sessionStore, params.sessionName, session); @@ -277,7 +285,6 @@ async function startRecording( const started = await runtime.operations.screenRecordingStart( screenRecordingStartInput(params, session, prepared, fence, outputPaths), ); - const { tenantId, leaseId } = resolveRecordingOwner(params.req, session); await adoptStartedScreenRecording({ admissionLedger: params.admissionLedger, binding, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 6e0ff922eb2..4f084a60e54 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2375,6 +2375,7 @@ Exact behavior: `agent-device help record`. - `record start` defaults to app scope, which needs an active app session from `open `; the backend decides what is captured. A local iOS simulator recording always captures the whole display, even at app scope. Use `--scope device` or `--scope system` for whole-screen capture (several apps, settings, the home screen) where the backend supports it. +- A leased recording requires a tenant owner before it can start. - On physical iOS devices, a recording is a series of runner screenshots: no audio, about 15 FPS by default, and dropped frames are expected. - Burned-in touch overlays export only on macOS hosts. Elsewhere, or when the export takes too long, `record stop` returns the raw video with `overlayWarning`. - Android splits long recordings into MP4 chunks. A clip can end early when the screen stops changing; `capturedDurationMs` and a warning report how much the video covers. From b0206197d2316e2304c6d4ad93b80b264b0a79cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 08:35:02 +0100 Subject: [PATCH 25/35] fix(daemon): validate recording ownership at start admission --- .../src/sessions/handlers/record-runtime.ts | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index 3027154a142..6d1510b6227 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -250,13 +250,7 @@ async function startRecording( if (session.screenRecording) { return { ok: false, error: { code: 'INVALID_ARGS', message: 'recording already in progress' } }; } - const { tenantId, leaseId } = resolveRecordingOwner(params.req, session); - if (leaseId !== undefined && !tenantId) { - throw new AppError('UNAUTHORIZED', 'Leased recording requires a tenant owner', { - reason: LEASE_REASONS.scopeRequired.reason, - field: 'tenantId', - }); - } + const { tenantId, leaseId } = resolveRecordingStartOwner(params.req, session); const draft = ref ? undefined : bindRecordOnlyScreenRecording(params.sessionStore, params.sessionName, session); @@ -544,6 +538,17 @@ function resolveRecordingOwner( return owner; } +function resolveRecordingStartOwner(req: DaemonRequest, session: SessionState) { + const owner = resolveRecordingOwner(req, session); + if (owner.leaseId !== undefined && !owner.tenantId) { + throw new AppError('UNAUTHORIZED', 'Leased recording requires a tenant owner', { + reason: LEASE_REASONS.scopeRequired.reason, + field: 'tenantId', + }); + } + return owner; +} + /** * Recovery control bound to a record's own owner and fence, for a recording whose live handle this * daemon no longer holds. A recovered stop and the start-time settle share it. From 1d909122a04f9ff1aa17bf3d09d77dad3af3f9e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 10:44:41 +0100 Subject: [PATCH 26/35] fix(artifacts): normalize recording owner and document historical lookup --- .../record-runtime-stop-recovery.test.ts | 7 +- .../src/sessions/handlers/record-runtime.ts | 4 +- src/__tests__/cli-run-transport.test.ts | 84 +++++++++++++++++++ website/docs/docs/commands.md | 1 + website/docs/docs/device-clouds.md | 8 +- 5 files changed, 97 insertions(+), 7 deletions(-) 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 13211ed21cb..562ebe263d6 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 @@ -74,7 +74,7 @@ vi.mock('@agent-device/device-selection/dispatch-resolve', () => ({ resolveTargetDeviceMock(...(args as Parameters)), })); -test('record stop after a daemon restart replays the completed export with an empty tenant', async () => { +test('record stop after a daemon restart replays the completed export with empty owner metadata', async () => { // The #3674 state itself: sessions are memory-only, so a restart drops `recording`, while the // on-disk manifest survives. The caller still names the session (the only address that finds // the manifest at all), and `help record` promises the completed recording on that stop — even @@ -85,14 +85,15 @@ test('record stop after a daemon restart replays the completed export with an em 'capture.mp4', ); fs.writeFileSync(outPath, 'mp4'); - await harness.run(['start', outPath], { tenantId: '' }); + const owner = { tenantId: '', leaseId: '' }; + expect(await harness.run(['start', outPath], owner)).toMatchObject({ ok: true }); await harness.run(['stop']); const ref = harness.sessionStore.lookup(harness.sessionName); if (!ref) throw new Error('Expected the stopped recording session'); harness.sessionStore.retire(ref); resolveTargetDeviceMock.mockClear(); - const recovered = await harness.run(['stop'], { sessionExplicit: true, tenantId: '' }); + const recovered = await harness.run(['stop'], { sessionExplicit: true, ...owner }); expect(recovered).toMatchObject({ ok: true, diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index 6d1510b6227..bea9f992c9e 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -533,7 +533,9 @@ function resolveRecordingOwner( req: DaemonRequest, session: SessionState, ): { tenantId?: string; leaseId?: string } { - const owner = req.internal?.admittedLease ?? resolveRequestOrSessionLeaseScope(req, session); + const request = + req.meta?.leaseId === '' ? { ...req, meta: { ...req.meta, leaseId: undefined } } : req; + const owner = req.internal?.admittedLease ?? resolveRequestOrSessionLeaseScope(request, session); if (owner.tenantId === '' && owner.leaseId === undefined) return {}; return owner; } diff --git a/src/__tests__/cli-run-transport.test.ts b/src/__tests__/cli-run-transport.test.ts index 3f143f05068..e0759fc9f7e 100644 --- a/src/__tests__/cli-run-transport.test.ts +++ b/src/__tests__/cli-run-transport.test.ts @@ -19,6 +19,90 @@ afterEach(() => { class ProcessExit extends Error {} +test('historical artifact lookups can use an unused session with explicit scope', async () => { + const { root, home, project } = makeTempWorkspace(); + const stateDir = path.join(root, 'state'); + const remoteConfigPath = path.join(project, 'remote.json'); + fs.writeFileSync(remoteConfigPath, '{}'); + const now = new Date().toISOString(); + writeRemoteConnectionState({ + stateDir, + state: { + version: 1, + session: 'default', + remoteConfigPath, + remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), + tenant: 'tenant', + runId: 'current-run', + leaseId: 'b'.repeat(32), + leaseProvider: 'browserstack', + connectedAt: now, + updatedAt: now, + }, + }); + const sent: Array> = []; + const transportForHost = () => async (request: Omit) => { + sent.push(request); + return { ok: true, data: { source: 'daemon', status: 'ready', artifacts: [] } } as const; + }; + const host = { env: { HOME: home, PATH: process.env.PATH }, cwd: project }; + vi.spyOn(process, 'exit').mockImplementation((() => { + throw new ProcessExit(); + }) as never); + vi.spyOn(process.stdout, 'write').mockReturnValue(true); + vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const owningLeaseId = 'a'.repeat(32); + const args = [ + 'artifacts', + '--state-dir', + stateDir, + '--session', + 'artifact-lookup', + '--tenant', + 'tenant', + '--run-id', + 'owning-run', + '--json', + ]; + const deps = { sendToDaemon: vi.fn(), transportForHost }; + + await runCli([...args, '--lease-id', owningLeaseId], deps, host); + await runCli( + [...args, '--provider', 'browserstack', '--provider-session', 'historical-provider-session'], + deps, + host, + ); + + assert.deepEqual( + sent.map((request) => ({ + command: request.command, + tenantId: request.meta?.tenantId, + runId: request.meta?.runId, + leaseId: request.meta?.leaseId, + provider: request.meta?.leaseProvider, + providerSessionId: request.flags?.providerSessionId, + })), + [ + { + command: 'artifacts', + tenantId: 'tenant', + runId: 'owning-run', + leaseId: owningLeaseId, + provider: undefined, + providerSessionId: undefined, + }, + { + command: 'artifacts', + tenantId: 'tenant', + runId: 'owning-run', + leaseId: undefined, + provider: 'browserstack', + providerSessionId: 'historical-provider-session', + }, + ], + ); +}); + test('a CLI run builds one transport, shared by the remote-materialization client and the command client', async () => { const { root, home, project } = makeTempWorkspace(); const stateDir = path.join(root, 'state'); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 4f084a60e54..584dd590a75 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2784,6 +2784,7 @@ agent-device artifacts --provider aws-device-farm --provider-session `, `--provider-session `, and the owning `--run-id `. - For leased artifacts, pass the producing `--lease-id ` and `--run-id `; a session name alone does not grant access. +- When a saved connection uses a different lease, follow [Retrieve artifacts after close](/docs/device-clouds#retrieve-artifacts-after-close) to query the producing lease directly. - Providers can finish their URLs only after the session stops, so retry `artifacts` if the first response is `pending`. ## MCP server diff --git a/website/docs/docs/device-clouds.md b/website/docs/docs/device-clouds.md index 27d8f6e1188..a088f69f188 100644 --- a/website/docs/docs/device-clouds.md +++ b/website/docs/docs/device-clouds.md @@ -60,14 +60,16 @@ Use `snapshot -i` to confirm the target. If the driver does not support the `/el ## Retrieve artifacts after close -Before `close`, save the lease ID and run ID from the connection you used. After `close`, pass both IDs to `agent-device artifacts --json` to list retained daemon artifacts. For provider-hosted artifacts, also pass `--provider ` (see [Compare providers](#compare-providers)). If `close --json` returns a provider session ID, you can look it up directly: +Before `close`, save the lease ID and run ID from the connection you used. For a lookup after `close`, choose an unused `--session` name and omit `--remote-config` so the CLI sends the lookup without a saved connection's lease. Use the same daemon and tenant that produced the artifacts. For a remote daemon, set `AGENT_DEVICE_DAEMON_BASE_URL` and `AGENT_DEVICE_DAEMON_AUTH_TOKEN` for that daemon. + +Pass the producing lease and run IDs to list retained daemon artifacts. For provider-hosted artifacts by lease, also pass `--provider ` (see [Compare providers](#compare-providers)). If `close --json` returns a provider session ID, use that ID with the provider and original run: ```bash -agent-device artifacts --provider --run-id --json +agent-device artifacts --session artifact-lookup --tenant "$PRODUCING_TENANT" --lease-id "$PRODUCING_LEASE_ID" --run-id "$PRODUCING_RUN_ID" --json +agent-device artifacts --session artifact-lookup --tenant "$PRODUCING_TENANT" --provider "$PRODUCING_PROVIDER" --provider-session "$PROVIDER_SESSION_ID" --run-id "$PRODUCING_RUN_ID" --json ``` Providers finalize video and log URLs after the session ends. If the lookup reports artifacts as pending right after `close`, retry it a little later. -Use the tenant that owned the producing lease and the run ID from the original connection. ## NoMac From d29aea59fcc9917d3275656b8a4d7f9525c1c6cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 10:47:23 +0100 Subject: [PATCH 27/35] test(artifacts): use a mutable daemon response fixture --- src/__tests__/cli-run-transport.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/__tests__/cli-run-transport.test.ts b/src/__tests__/cli-run-transport.test.ts index e0759fc9f7e..116c7ead434 100644 --- a/src/__tests__/cli-run-transport.test.ts +++ b/src/__tests__/cli-run-transport.test.ts @@ -43,7 +43,10 @@ test('historical artifact lookups can use an unused session with explicit scope' const sent: Array> = []; const transportForHost = () => async (request: Omit) => { sent.push(request); - return { ok: true, data: { source: 'daemon', status: 'ready', artifacts: [] } } as const; + return { + ok: true, + data: { source: 'daemon', status: 'ready', artifacts: [] }, + } satisfies DaemonResponse; }; const host = { env: { HOME: home, PATH: process.env.PATH }, cwd: project }; vi.spyOn(process, 'exit').mockImplementation((() => { From 6a00dd955a427f9ec19a1c0793be308994997eda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 11:18:26 +0100 Subject: [PATCH 28/35] fix(leases): prune retained artifact owners during expiry sweeps --- .../docs/remote-device-lease-contracts.md | 6 ++- .../lease-registry-artifact-retention.test.ts | 9 +++- .../daemon/src/resources/lease-registry.ts | 47 +++++++++---------- 3 files changed, 32 insertions(+), 30 deletions(-) diff --git a/packages/daemon/docs/remote-device-lease-contracts.md b/packages/daemon/docs/remote-device-lease-contracts.md index ffa9926173d..f5ccd53273f 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -178,8 +178,10 @@ If a tenant could name the scope, the scope would be self-chosen. Thus, only a host administrator allocates a `macos-app` lease, over the loopback `/admin/leases` route that uses the daemon token like host holds. Tenant `lease_allocate` refuses the backend. The host picks the lease id. -A repeated PUT renews the lease. -A PUT that names another scope for an existing id is refused, not rewritten. +A repeated PUT with the same scope renews an active lease. +A PUT that names another scope for an active id is refused. +After a lease ends, use a fresh id. +The daemon refuses to reissue an ended lease's id with `INVALID_ARGS` and reason `LEASE_ID_IN_USE`. Heartbeat, expiry, and the loss on daemon restart are those of any lease, with two exceptions: diff --git a/packages/daemon/src/resources/__tests__/lease-registry-artifact-retention.test.ts b/packages/daemon/src/resources/__tests__/lease-registry-artifact-retention.test.ts index b5fdc9cead9..59c8a424de5 100644 --- a/packages/daemon/src/resources/__tests__/lease-registry-artifact-retention.test.ts +++ b/packages/daemon/src/resources/__tests__/lease-registry-artifact-retention.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; import { LeaseRegistry } from '../lease-registry.ts'; -test('released artifact lease owners are removed after retention', () => { +test('the periodic lease sweep removes artifact owners after retention', () => { let now = 0; const registry = new LeaseRegistry({ now: () => now }); const lease = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-a' }); @@ -11,7 +11,13 @@ test('released artifact lease owners are removed after retention', () => { .artifactLeaseOwners; assert.equal(owners.has(lease.leaseId), true); + now = 15 * 60_000 - 1; + registry.consumeExpiredLeases(); + assert.equal(owners.has(lease.leaseId), true); + now = 15 * 60_000; + registry.consumeExpiredLeases(); + assert.equal(owners.has(lease.leaseId), false); assert.throws(() => registry.assertArtifactLeaseReadAdmission({ leaseId: lease.leaseId, @@ -19,5 +25,4 @@ test('released artifact lease owners are removed after retention', () => { runId: 'run-a', }), ); - assert.equal(owners.has(lease.leaseId), false); }); diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index dcf6256cc23..3a2cb88a2de 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -128,7 +128,7 @@ export class LeaseRegistry { putHostLease(leaseId: string, request: AllocateLeaseRequest): DeviceLease { const id = normalizeRequiredLeaseId(leaseId); const normalized = normalizeAllocateLeaseRequest(request); - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); const leaseTtlMs = this.resolveLeaseTtlMs(normalized.ttlMs); const existing = this.leases.get(id); if (existing) { @@ -179,7 +179,7 @@ export class LeaseRegistry { const chosenLeaseId = request.leaseId === undefined ? undefined : normalizeRequiredLeaseId(request.leaseId); const normalized = normalizeAllocateLeaseRequest(request); - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); return { chosenLeaseId, normalized, leaseTtlMs: this.resolveLeaseTtlMs(normalized.ttlMs) }; } @@ -254,7 +254,7 @@ export class LeaseRegistry { */ heartbeatLease(request: HeartbeatLeaseRequest): DeviceLease { const leaseId = normalizeRequiredLeaseId(request.leaseId); - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); const lease = this.getActiveLease(leaseId); assertLeaseOwnerScope(lease, request); assertLeaseScopeMatch(lease, request); @@ -313,7 +313,7 @@ export class LeaseRegistry { */ getLease(request: ReleaseLeaseRequest): DeviceLease | undefined { const leaseId = normalizeRequiredLeaseId(request.leaseId); - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); const lease = this.leases.get(leaseId); if (!lease) return undefined; assertLeaseOwnerScope(lease, request); @@ -333,19 +333,19 @@ export class LeaseRegistry { /** Refuses a lease the registry does not hold, whatever its scope. */ assertLeaseActive(leaseId: string): void { - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); this.getActiveLease(normalizeLeaseId(leaseId) ?? leaseId); } assertLeaseAdmission(request: AdmissionRequest): void { const scope = normalizeLeaseAdmissionRequest(request); - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); assertLeaseScopeMatch(this.getActiveLease(scope.leaseId), scope); } /** Uploads match the active lease's tenant and any supplied run. */ assertUploadLeaseAdmission(request: { leaseId: string; tenantId: string; runId?: string }): void { - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); const lease = this.getActiveLease(normalizeRequiredLeaseId(request.leaseId)); if ( lease.tenantId !== request.tenantId || @@ -364,7 +364,7 @@ export class LeaseRegistry { runId?: string; }): void { const leaseId = normalizeRequiredLeaseId(request.leaseId); - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); const owner = this.artifactLeaseOwners.get(leaseId); if ( !owner || @@ -404,7 +404,7 @@ export class LeaseRegistry { } listActiveLeases(): DeviceLease[] { - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); return Array.from(this.leases.values()).map((entry) => ({ ...entry })); } @@ -412,7 +412,7 @@ export class LeaseRegistry { lease: Pick, providerSessionId: string, ): void { - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); const releasedAt = lease.expiresAt <= this.now() ? lease.expiresAt : undefined; this.providerSessionOwnership.record(lease, providerSessionId); if (!this.leases.has(lease.leaseId)) { @@ -426,7 +426,7 @@ export class LeaseRegistry { tenantId?: string; runId?: string; }): ProviderSessionOwnership | undefined { - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); return this.providerSessionOwnership.resolve(params); } @@ -436,12 +436,12 @@ export class LeaseRegistry { tenantId?: string; runId?: string; }): ReturnType { - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); return this.providerSessionOwnership.resolveLease(params); } listHumanControlHolds(authority: HumanControlAuthority): HumanControlHold[] { - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); const key = authority.kind === 'lease' ? leaseDeviceBindingKey(this.requireHumanControlLease(authority.leaseId)) @@ -463,7 +463,7 @@ export class LeaseRegistry { signal?.throwIfAborted(); const id = normalizeHumanControlHoldId(rawId); const input = parseHumanControlHoldInput(rawInput); - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); const scope = this.resolveHumanControlScope(authority, input); const key = leaseDeviceBindingKey(scope)!; const existing = this.findHumanControlHold(id); @@ -532,7 +532,7 @@ export class LeaseRegistry { rawId: string, ): HumanControlHold | undefined { const id = normalizeHumanControlHoldId(rawId); - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); const existing = this.findHumanControlHold(id); if (!existing) return undefined; this.assertHoldAuthority(authority, existing); @@ -562,7 +562,7 @@ export class LeaseRegistry { async runDeviceMutation(lease: DeviceLease | undefined, task: () => Promise): Promise { if (!lease) return await task(); - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); const activeLease = this.getActiveLease(lease.leaseId); this.assertHumanControlAdmission(activeLease); const key = leaseDeviceBindingKey(activeLease); @@ -697,6 +697,11 @@ export class LeaseRegistry { this.onLeaseExpired?.(expiredLease); this.reportProviderLeases(expiredLease); } + for (const [leaseId, owner] of this.artifactLeaseOwners) { + if (owner.retainedUntil !== undefined && owner.retainedUntil <= now) { + this.artifactLeaseOwners.delete(leaseId); + } + } return expired; } @@ -719,16 +724,6 @@ export class LeaseRegistry { return expiredLease; } - private cleanupExpiredLeases(): void { - this.consumeExpiredLeases(); - const now = this.now(); - for (const [leaseId, owner] of this.artifactLeaseOwners) { - if (owner.retainedUntil !== undefined && owner.retainedUntil <= now) { - this.artifactLeaseOwners.delete(leaseId); - } - } - } - private enforceCapacity(backend: LeaseBackend): void { if (backend !== 'ios-simulator') return; if (this.maxActiveSimulatorLeases <= 0) return; From 71aede7644140f5470362a1f393e83664f1a4feb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 15:52:36 +0100 Subject: [PATCH 29/35] fix(artifacts): preserve explicit lookup scope and empty lease absence --- packages/contracts/src/lease-scope.ts | 2 +- .../http/http-server-remote-output.test.ts | 28 +++++++++-- .../src/sessions/handlers/record-runtime.ts | 4 +- src/__tests__/cli-run-transport.test.ts | 47 +++++++++++++++++-- src/cli.ts | 25 ++++++++-- src/commands/schema/cli-help.ts | 3 +- website/docs/docs/commands.md | 4 +- website/docs/docs/device-clouds.md | 2 +- 8 files changed, 95 insertions(+), 20 deletions(-) diff --git a/packages/contracts/src/lease-scope.ts b/packages/contracts/src/lease-scope.ts index 14a43a6b372..e07a60d47a8 100644 --- a/packages/contracts/src/lease-scope.ts +++ b/packages/contracts/src/lease-scope.ts @@ -95,7 +95,7 @@ type LeaseOptionsLike = { }; export function leaseScopeFromRequest(req: LeaseRequestLike): LeaseScope { - const leaseId = req.meta?.leaseId ?? readFlagString(req.flags, 'leaseId'); + const leaseId = (req.meta?.leaseId ?? readFlagString(req.flags, 'leaseId')) || undefined; return stripUndefined({ tenantId: req.meta?.tenantId ?? readFlagString(req.flags, 'tenant'), runId: req.meta?.runId ?? readFlagString(req.flags, 'runId'), 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 4d306a98d64..190af61e982 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 @@ -324,7 +324,16 @@ test('local HTTP still honors capture destinations and cwd', async () => { ); }); -test('remote recording without client metadata stays in its session and downloads by ID', async () => { +test.each([ + { scope: 'omitted lease', meta: {}, flags: {} }, + { scope: 'empty lease metadata', meta: { leaseId: '' }, flags: {} }, + { scope: 'empty legacy lease flag', meta: {}, flags: { leaseId: '' } }, + { + scope: 'empty lease metadata taking precedence over the legacy flag', + meta: { leaseId: '' }, + flags: { leaseId: 'a'.repeat(32) }, + }, +])('remote recording with $scope stays in its session and downloads by ID', async (input) => { const harness = makeRecordRuntimeHarness('remote-record-output-'); const root = mkdtempForTestSync('remote-record-victim-'); const victim = path.join(root, 'protected.mp4'); @@ -345,7 +354,8 @@ test('remote recording without client metadata stays in its session and download const started = await post({ command: 'record', positionals: ['start', victim], - meta: { cwd: root }, + meta: { cwd: root, ...input.meta }, + flags: input.flags, }); expect(started.result?.ok).toBe(true); const output = started.result?.data?.outPath as string; @@ -354,10 +364,22 @@ test('remote recording without client metadata stays in its session and download ); expect(output).toMatch(/recording-[0-9a-f-]+\.mp4$/); expect(fs.readFileSync(victim, 'utf8')).toBe('protected-content'); - const stopped = await post({ command: 'record', positionals: ['stop'] }); + const stopped = await post({ + command: 'record', + positionals: ['stop'], + meta: input.meta, + flags: input.flags, + }); expect(stopped.result?.ok).toBe(true); const artifact = stopped.result?.data?.artifacts?.[0]; expect(artifact?.artifactId).toBeTypeOf('string'); + expect(artifact?.downloadScope).toBeUndefined(); + const inventory = await fetch(`${base}/artifacts`, { + headers: { authorization: 'Bearer test-token' }, + }); + expect(await inventory.json()).toMatchObject({ + artifacts: expect.arrayContaining([expect.objectContaining({ id: artifact?.artifactId })]), + }); const download = await fetch(`${base}/artifacts/${artifact?.artifactId}`, { headers: { authorization: 'Bearer test-token' }, }); diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index bea9f992c9e..6d1510b6227 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -533,9 +533,7 @@ function resolveRecordingOwner( req: DaemonRequest, session: SessionState, ): { tenantId?: string; leaseId?: string } { - const request = - req.meta?.leaseId === '' ? { ...req, meta: { ...req.meta, leaseId: undefined } } : req; - const owner = req.internal?.admittedLease ?? resolveRequestOrSessionLeaseScope(request, session); + const owner = req.internal?.admittedLease ?? resolveRequestOrSessionLeaseScope(req, session); if (owner.tenantId === '' && owner.leaseId === undefined) return {}; return owner; } diff --git a/src/__tests__/cli-run-transport.test.ts b/src/__tests__/cli-run-transport.test.ts index 116c7ead434..2e4b94bd76b 100644 --- a/src/__tests__/cli-run-transport.test.ts +++ b/src/__tests__/cli-run-transport.test.ts @@ -19,11 +19,14 @@ afterEach(() => { class ProcessExit extends Error {} -test('historical artifact lookups can use an unused session with explicit scope', async () => { +test.each(['artifact-lookup', 'default'])('artifact query scope in %s', async (session) => { const { root, home, project } = makeTempWorkspace(); const stateDir = path.join(root, 'state'); const remoteConfigPath = path.join(project, 'remote.json'); - fs.writeFileSync(remoteConfigPath, '{}'); + fs.writeFileSync( + remoteConfigPath, + JSON.stringify({ leaseId: 'b'.repeat(32), runId: 'current-run' }), + ); const now = new Date().toISOString(); writeRemoteConnectionState({ stateDir, @@ -32,10 +35,11 @@ test('historical artifact lookups can use an unused session with explicit scope' session: 'default', remoteConfigPath, remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), + daemon: { baseUrl: 'http://127.0.0.1:7001', transport: 'http' }, tenant: 'tenant', runId: 'current-run', leaseId: 'b'.repeat(32), - leaseProvider: 'browserstack', + leaseProvider: 'proxy', connectedAt: now, updatedAt: now, }, @@ -48,7 +52,16 @@ test('historical artifact lookups can use an unused session with explicit scope' data: { source: 'daemon', status: 'ready', artifacts: [] }, } satisfies DaemonResponse; }; - const host = { env: { HOME: home, PATH: process.env.PATH }, cwd: project }; + const host = { + env: { + HOME: home, + PATH: process.env.PATH, + ...(session === 'artifact-lookup' + ? { AGENT_DEVICE_DAEMON_BASE_URL: 'http://127.0.0.1:7001' } + : {}), + }, + cwd: project, + }; vi.spyOn(process, 'exit').mockImplementation((() => { throw new ProcessExit(); }) as never); @@ -60,7 +73,7 @@ test('historical artifact lookups can use an unused session with explicit scope' '--state-dir', stateDir, '--session', - 'artifact-lookup', + session, '--tenant', 'tenant', '--run-id', @@ -75,10 +88,23 @@ test('historical artifact lookups can use an unused session with explicit scope' deps, host, ); + await runCli( + [ + ...args, + 'historical-provider-session', + '--provider', + 'browserstack', + '--lease-id', + owningLeaseId, + ], + deps, + host, + ); assert.deepEqual( sent.map((request) => ({ command: request.command, + daemonBaseUrl: request.flags?.daemonBaseUrl, tenantId: request.meta?.tenantId, runId: request.meta?.runId, leaseId: request.meta?.leaseId, @@ -88,6 +114,7 @@ test('historical artifact lookups can use an unused session with explicit scope' [ { command: 'artifacts', + daemonBaseUrl: 'http://127.0.0.1:7001', tenantId: 'tenant', runId: 'owning-run', leaseId: owningLeaseId, @@ -96,12 +123,22 @@ test('historical artifact lookups can use an unused session with explicit scope' }, { command: 'artifacts', + daemonBaseUrl: 'http://127.0.0.1:7001', tenantId: 'tenant', runId: 'owning-run', leaseId: undefined, provider: 'browserstack', providerSessionId: 'historical-provider-session', }, + { + command: 'artifacts', + daemonBaseUrl: 'http://127.0.0.1:7001', + tenantId: 'tenant', + runId: 'owning-run', + leaseId: owningLeaseId, + provider: 'browserstack', + providerSessionId: 'historical-provider-session', + }, ], ); }); diff --git a/src/cli.ts b/src/cli.ts index 5196f84b882..98230934c2d 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -363,6 +363,7 @@ type CliRunContext = { daemonPaths: ReturnType; sessionName: string; connectionDefaults: ReturnType; + explicitArtifactQuery: boolean; explicitFlagKeys: Set; // Mutated in place by resolveRemoteContext (auth, materialization) so the // failure handler always sees the same state the throwing phase saw. @@ -428,9 +429,20 @@ async function resolveRunContextOrExit( session: flags.session, remoteConfig: flags.remoteConfig, }); - const effectiveFlags = connectionDefaults + const explicitArtifactQuery = + base.command === 'artifacts' && + (explicitFlagKeys.has('leaseId') || Boolean(base.positionals[0] ?? flags.providerSessionId)); + const connectionFlags = connectionDefaults ? mergeConnectionFlags(flags, connectionDefaults.flags, explicitFlagKeys) : flags; + const effectiveFlags = explicitArtifactQuery + ? { + ...connectionFlags, + leaseId: explicitFlagKeys.has('leaseId') ? flags.leaseId : undefined, + runId: explicitFlagKeys.has('runId') ? flags.runId : undefined, + leaseBackend: undefined, + } + : connectionFlags; return { ...base, binding, @@ -438,10 +450,11 @@ async function resolveRunContextOrExit( daemonPaths, sessionName, connectionDefaults, + explicitArtifactQuery, explicitFlagKeys, effectiveFlags, - resolvedRuntime: connectionDefaults?.runtime, - connectionMetadata: connectionDefaults?.connection, + resolvedRuntime: explicitArtifactQuery ? undefined : connectionDefaults?.runtime, + connectionMetadata: explicitArtifactQuery ? undefined : connectionDefaults?.connection, parsedBatchSteps: undefined, devicePin: parsed.devicePin, }; @@ -494,7 +507,11 @@ async function resolveRemoteContext( ctx.effectiveFlags = authResolution.flags; } - if (ctx.effectiveFlags.remoteConfig && shouldMaterializeRemoteConnection(ctx.command)) { + if ( + ctx.effectiveFlags.remoteConfig && + !ctx.explicitArtifactQuery && + shouldMaterializeRemoteConnection(ctx.command) + ) { ctx.effectiveFlags = (ctx.leaseAdmission ??= { flagsBefore: ctx.effectiveFlags }).flagsBefore; const { createClientDaemonTransport } = await import('./cli/cli-daemon-transport.ts'); // Lease allocate and heartbeat calls act on the remote before the command, so they go diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 0ad88c5af2c..842748d96e1 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -635,7 +635,8 @@ Rules: To replace an existing connection, pass its returned session explicitly with --session --force. --force without --session creates another fresh session and does not release or overwrite an unrelated active connection. Prefer short-lived AWS role credentials in CI. Generated connection profiles store app/device selectors and ARNs, not Limrun API keys or instance tokens, BrowserStack or TestMu AI access keys, or AWS credentials. Limrun Android supports direct ADB port reverse for local Metro. Limrun iOS requires a public Metro URL because it cannot reach local host ports directly. - Before closing a device cloud session, save its lease and run IDs. After close, list provider artifacts with agent-device artifacts --provider --lease-id --run-id --json. + Before closing a device cloud session, save its lease and run IDs. Set AGENT_DEVICE_DAEMON_BASE_URL and AGENT_DEVICE_DAEMON_AUTH_TOKEN for the same remote daemon. After close, query from an unused session. + agent-device artifacts --session artifact-lookup --tenant --provider --lease-id --run-id --json connect proxy stores the connection profile and client identity. Proxy device leases are acquired on open and expire after five minutes without commands; when a lease expires or is released, the daemon ends the session opened under it and frees its device; devices may inspect proxy inventory without allocating. Multiple agents can share one proxy when each uses connect proxy, open, commands, close, and disconnect. disconnect releases local connection state; close releases the active session and device lease. diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 584dd590a75..cb6845fdd40 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2783,8 +2783,8 @@ agent-device artifacts --provider aws-device-farm --provider-session `, `--provider-session `, and the owning `--run-id `. -- For leased artifacts, pass the producing `--lease-id ` and `--run-id `; a session name alone does not grant access. -- When a saved connection uses a different lease, follow [Retrieve artifacts after close](/docs/device-clouds#retrieve-artifacts-after-close) to query the producing lease directly. +- To look up artifacts by lease, pass the producing `--lease-id ` and `--run-id `. For a provider session ID, pass the provider and producing run. If you also pass a lease ID, it must match the provider session's lease. +- To query after close, use the saved connection's session for its endpoint or follow the standalone workflow in [Retrieve artifacts after close](/docs/device-clouds#retrieve-artifacts-after-close). - Providers can finish their URLs only after the session stops, so retry `artifacts` if the first response is `pending`. ## MCP server diff --git a/website/docs/docs/device-clouds.md b/website/docs/docs/device-clouds.md index a088f69f188..c8ce75ef27e 100644 --- a/website/docs/docs/device-clouds.md +++ b/website/docs/docs/device-clouds.md @@ -60,7 +60,7 @@ Use `snapshot -i` to confirm the target. If the driver does not support the `/el ## Retrieve artifacts after close -Before `close`, save the lease ID and run ID from the connection you used. For a lookup after `close`, choose an unused `--session` name and omit `--remote-config` so the CLI sends the lookup without a saved connection's lease. Use the same daemon and tenant that produced the artifacts. For a remote daemon, set `AGENT_DEVICE_DAEMON_BASE_URL` and `AGENT_DEVICE_DAEMON_AUTH_TOKEN` for that daemon. +Before `close`, save the lease ID and run ID from the connection you used. Use the same daemon and tenant that produced the artifacts. An explicit `--lease-id` or provider session ID uses the saved connection's endpoint when you name its session. Pass the producing `--run-id` with either selector. For a standalone lookup, choose an unused `--session` name and set `AGENT_DEVICE_DAEMON_BASE_URL` and `AGENT_DEVICE_DAEMON_AUTH_TOKEN` for the producing daemon. Pass the producing lease and run IDs to list retained daemon artifacts. For provider-hosted artifacts by lease, also pass `--provider ` (see [Compare providers](#compare-providers)). If `close --json` returns a provider session ID, use that ID with the provider and original run: From 422c80707249bce8c7aca85f89d06ae7768ce00b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 16:01:01 +0100 Subject: [PATCH 30/35] fix: keep artifact scope within CLI and test limits --- .../http-server-remote-host-arguments.test.ts | 20 ++++++- .../http/http-server-remote-output.test.ts | 43 ++++--------- src/cli.ts | 60 +++++++++---------- 3 files changed, 60 insertions(+), 63 deletions(-) diff --git a/packages/daemon/src/server/http/http-server-remote-host-arguments.test.ts b/packages/daemon/src/server/http/http-server-remote-host-arguments.test.ts index 7d146ce4253..fe3ccfd9f21 100644 --- a/packages/daemon/src/server/http/http-server-remote-host-arguments.test.ts +++ b/packages/daemon/src/server/http/http-server-remote-host-arguments.test.ts @@ -9,7 +9,7 @@ import type { DaemonRequest } from '../../core/daemon-request.ts'; import { createDaemonHttpServer } from './http-server.ts'; type RpcBody = { - result?: { ok: boolean; data?: { positionals?: string[] } }; + result?: { ok: boolean; data?: { positionals?: string[]; request?: DaemonRequest } }; error?: { data?: { code?: string; details?: { reason?: string; field?: string } } }; }; @@ -20,6 +20,7 @@ async function withHttp( ): Promise { const env = { ...process.env }; delete env.AGENT_DEVICE_HTTP_AUTH_HOOK; + delete env.AGENT_DEVICE_HTTP_AUTH_EXPORT; const server = await createDaemonHttpServer({ token: 'test-token', handleRequest, @@ -177,6 +178,23 @@ test('local admission keeps file URLs available to the host operator', async () ); }); +test('local HTTP still honors capture destinations and cwd', async () => { + const params = { + command: 'screenshot', + positionals: ['local.png'], + flags: { out: 'flag.png' }, + meta: { cwd: '/local/project' }, + }; + await withHttp( + async (request) => ({ ok: true, data: { request } }), + async (post) => { + const body = await post(params); + expect(body.result?.data?.request).toMatchObject(params); + }, + false, + ); +}); + test.each([ { command: 'open', positionals: ['https://example.com/file:///tmp/probe.txt'] }, { command: 'open', positionals: ['http://example.com'] }, 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 190af61e982..36c7de82784 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 @@ -307,23 +307,6 @@ test.each(['marker', 'auth-hook', 'batch'] as const)( }, ); -test('local HTTP still honors capture destinations and cwd', async () => { - const meta = { cwd: '/local/project' }; - await withHttp( - async (request) => ({ ok: true, data: { request } }), - async (post) => { - const params = { - command: 'screenshot', - positionals: ['local.png'], - flags: { out: 'flag.png' }, - meta, - }; - const body = await post(params, false); - expect(body.result?.data?.request).toMatchObject(params); - }, - ); -}); - test.each([ { scope: 'omitted lease', meta: {}, flags: {} }, { scope: 'empty lease metadata', meta: { leaseId: '' }, flags: {} }, @@ -364,25 +347,23 @@ test.each([ ); expect(output).toMatch(/recording-[0-9a-f-]+\.mp4$/); expect(fs.readFileSync(victim, 'utf8')).toBe('protected-content'); - const stopped = await post({ - command: 'record', - positionals: ['stop'], - meta: input.meta, - flags: input.flags, - }); - expect(stopped.result?.ok).toBe(true); - const artifact = stopped.result?.data?.artifacts?.[0]; + const { artifacts } = successfulData( + await post({ + command: 'record', + positionals: ['stop'], + meta: input.meta, + flags: input.flags, + }), + ); + const artifact = artifacts?.[0]; expect(artifact?.artifactId).toBeTypeOf('string'); expect(artifact?.downloadScope).toBeUndefined(); - const inventory = await fetch(`${base}/artifacts`, { - headers: { authorization: 'Bearer test-token' }, - }); + const headers = { authorization: 'Bearer test-token' }; + const inventory = await fetch(`${base}/artifacts`, { headers }); expect(await inventory.json()).toMatchObject({ artifacts: expect.arrayContaining([expect.objectContaining({ id: artifact?.artifactId })]), }); - const download = await fetch(`${base}/artifacts/${artifact?.artifactId}`, { - headers: { authorization: 'Bearer test-token' }, - }); + const download = await fetch(`${base}/artifacts/${artifact?.artifactId}`, { headers }); expect(download.status).toBe(200); expect(await download.text()).toBe('generated-video'); }, diff --git a/src/cli.ts b/src/cli.ts index 98230934c2d..f12d7c07d60 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -282,11 +282,11 @@ async function parseCliInputOrExit( } const isHelpAlias = parsed.command === 'help'; + if (isHelpAlias && parsed.positionals.length > 1) { + await printHumanError(new AppError('INVALID_ARGS', 'help accepts at most one command.')); + return exitAfterFlush(1); + } if (isHelpAlias || parsed.flags.help) { - if (isHelpAlias && parsed.positionals.length > 1) { - await printHumanError(new AppError('INVALID_ARGS', 'help accepts at most one command.')); - return exitAfterFlush(1); - } const helpTarget = isHelpAlias ? parsed.positionals[0] : parsed.command; if (!helpTarget) { writeStdout(`${await usage()}\n`); @@ -429,20 +429,6 @@ async function resolveRunContextOrExit( session: flags.session, remoteConfig: flags.remoteConfig, }); - const explicitArtifactQuery = - base.command === 'artifacts' && - (explicitFlagKeys.has('leaseId') || Boolean(base.positionals[0] ?? flags.providerSessionId)); - const connectionFlags = connectionDefaults - ? mergeConnectionFlags(flags, connectionDefaults.flags, explicitFlagKeys) - : flags; - const effectiveFlags = explicitArtifactQuery - ? { - ...connectionFlags, - leaseId: explicitFlagKeys.has('leaseId') ? flags.leaseId : undefined, - runId: explicitFlagKeys.has('runId') ? flags.runId : undefined, - leaseBackend: undefined, - } - : connectionFlags; return { ...base, binding, @@ -450,11 +436,8 @@ async function resolveRunContextOrExit( daemonPaths, sessionName, connectionDefaults, - explicitArtifactQuery, explicitFlagKeys, - effectiveFlags, - resolvedRuntime: explicitArtifactQuery ? undefined : connectionDefaults?.runtime, - connectionMetadata: explicitArtifactQuery ? undefined : connectionDefaults?.connection, + ...resolveConnectionRunScope(base, flags, connectionDefaults, explicitFlagKeys), parsedBatchSteps: undefined, devicePin: parsed.devicePin, }; @@ -869,18 +852,33 @@ function hasExplicitRemoteScopeFlags(explicitFlagKeys: Set): boolean { ); } -function mergeConnectionFlags( +function resolveConnectionRunScope( + { command, positionals }: Pick, flags: CliFlags, - defaults: Partial, + defaults: CliRunContext['connectionDefaults'], explicitFlagKeys: Set, -): CliFlags { - const merged = { ...flags }; - for (const [key, value] of Object.entries(defaults) as Array<[FlagKey, unknown]>) { - if (value === undefined) continue; - if (explicitFlagKeys.has(key)) continue; - (merged as Record)[key] = value; +) { + const explicitArtifactQuery = + command === 'artifacts' && + (explicitFlagKeys.has('leaseId') || Boolean(positionals[0] ?? flags.providerSessionId)); + const effectiveFlags = { ...flags }; + for (const [key, value] of Object.entries(defaults?.flags ?? {}) as Array<[FlagKey, unknown]>) { + if (value !== undefined && !explicitFlagKeys.has(key)) { + (effectiveFlags as Record)[key] = value; + } + } + if (explicitArtifactQuery) { + effectiveFlags.leaseId = explicitFlagKeys.has('leaseId') ? flags.leaseId : undefined; + effectiveFlags.runId = explicitFlagKeys.has('runId') ? flags.runId : undefined; + effectiveFlags.leaseBackend = undefined; } - return merged; + const sessionDefaults = explicitArtifactQuery ? undefined : defaults; + return { + explicitArtifactQuery, + effectiveFlags, + resolvedRuntime: sessionDefaults?.runtime, + connectionMetadata: sessionDefaults?.connection, + }; } function hasExplicitMetroRuntimeOverrides(explicitFlagKeys: Set): boolean { From f8a376b49a2d5f010744ed3f34966d4e38a4a45e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 16:01:52 +0100 Subject: [PATCH 31/35] test(cli): expect artifacts in command dispatch checks --- src/cli-command-dispatch.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cli-command-dispatch.test.ts b/src/cli-command-dispatch.test.ts index 1900a3ad62c..c9a93a85ae4 100644 --- a/src/cli-command-dispatch.test.ts +++ b/src/cli-command-dispatch.test.ts @@ -10,6 +10,7 @@ test('cli.ts command dispatch checks are recognized by parser-level unknown-comm // The exact set, so a reader that collects nothing, or stops collecting, fails here instead // of passing over an empty loop. assert.deepEqual([...commands].sort(), [ + 'artifacts', 'batch', 'cdp', 'close', From dba25f7a22bc4ba926cffc686e168508cf5dcd35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 17:08:33 +0100 Subject: [PATCH 32/35] fix(cli): preserve operator scope for historical artifacts --- src/__tests__/cli-run-transport.test.ts | 63 ++++++++++++++++++++++--- src/cli.ts | 26 ++++++---- src/cli/resolve-cli-options.ts | 10 +++- src/commands/schema/cli-help.ts | 2 +- website/docs/docs/device-clouds.md | 4 +- 5 files changed, 85 insertions(+), 20 deletions(-) diff --git a/src/__tests__/cli-run-transport.test.ts b/src/__tests__/cli-run-transport.test.ts index 2e4b94bd76b..0eb214b13ae 100644 --- a/src/__tests__/cli-run-transport.test.ts +++ b/src/__tests__/cli-run-transport.test.ts @@ -39,7 +39,7 @@ test.each(['artifact-lookup', 'default'])('artifact query scope in %s', async (s tenant: 'tenant', runId: 'current-run', leaseId: 'b'.repeat(32), - leaseProvider: 'proxy', + leaseProvider: 'browserstack', connectedAt: now, updatedAt: now, }, @@ -76,30 +76,52 @@ test.each(['artifact-lookup', 'default'])('artifact query scope in %s', async (s session, '--tenant', 'tenant', - '--run-id', - 'owning-run', '--json', ]; + const owningRunArgs = [...args, '--run-id', 'owning-run']; const deps = { sendToDaemon: vi.fn(), transportForHost }; - await runCli([...args, '--lease-id', owningLeaseId], deps, host); + await runCli([...owningRunArgs, '--lease-id', owningLeaseId], deps, host); await runCli( - [...args, '--provider', 'browserstack', '--provider-session', 'historical-provider-session'], + [ + ...owningRunArgs, + '--provider', + 'browserstack', + '--provider-session', + 'historical-provider-session', + ], deps, host, ); await runCli( [ - ...args, + ...owningRunArgs, 'historical-provider-session', '--provider', - 'browserstack', + 'testmu', '--lease-id', owningLeaseId, ], deps, host, ); + const configPath = path.join(project, 'operator.json'); + fs.writeFileSync(configPath, JSON.stringify({ leaseId: owningLeaseId, runId: 'config-run' })); + await runCli( + [...args, '--config', configPath, '--provider', 'browserstack', 'historical-provider-session'], + deps, + host, + ); + await runCli([...args, '--config', configPath], deps, host); + await runCli( + [ + ...args, + ...(session === 'artifact-lookup' ? ['--provider', 'browserstack'] : []), + 'historical-provider-session', + ], + deps, + { ...host, env: { ...host.env, AGENT_DEVICE_RUN_ID: 'env-run' } }, + ); assert.deepEqual( sent.map((request) => ({ @@ -136,6 +158,33 @@ test.each(['artifact-lookup', 'default'])('artifact query scope in %s', async (s tenantId: 'tenant', runId: 'owning-run', leaseId: owningLeaseId, + provider: 'testmu', + providerSessionId: 'historical-provider-session', + }, + { + command: 'artifacts', + daemonBaseUrl: 'http://127.0.0.1:7001', + tenantId: 'tenant', + runId: 'config-run', + leaseId: owningLeaseId, + provider: 'browserstack', + providerSessionId: 'historical-provider-session', + }, + { + command: 'artifacts', + daemonBaseUrl: 'http://127.0.0.1:7001', + tenantId: 'tenant', + runId: 'config-run', + leaseId: owningLeaseId, + provider: undefined, + providerSessionId: undefined, + }, + { + command: 'artifacts', + daemonBaseUrl: 'http://127.0.0.1:7001', + tenantId: 'tenant', + runId: 'env-run', + leaseId: undefined, provider: 'browserstack', providerSessionId: 'historical-provider-session', }, diff --git a/src/cli.ts b/src/cli.ts index f12d7c07d60..fda93c76a93 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -60,6 +60,7 @@ import { import { resolveRemoteAuthForCli } from './cli/auth-session.ts'; import type { FlagKey } from '@agent-device/command-registry/flag-types'; import type { CliFlags } from '@agent-device/contracts/command'; +import { leaseProviderRequiringRuntime } from '@agent-device/contracts/lease-scope'; import type { SessionRuntimeHints } from '@agent-device/kernel/contracts'; import { isKnownCliCommandName } from '@agent-device/command-registry/catalog'; import type * as LeaseAdmission from './cli/commands/connection-lease-admission.ts'; @@ -437,7 +438,12 @@ async function resolveRunContextOrExit( sessionName, connectionDefaults, explicitFlagKeys, - ...resolveConnectionRunScope(base, flags, connectionDefaults, explicitFlagKeys), + ...resolveConnectionRunScope( + parsed.artifactQuery, + flags, + connectionDefaults, + explicitFlagKeys, + ), parsedBatchSteps: undefined, devicePin: parsed.devicePin, }; @@ -853,28 +859,28 @@ function hasExplicitRemoteScopeFlags(explicitFlagKeys: Set): boolean { } function resolveConnectionRunScope( - { command, positionals }: Pick, + artifactQuery: ReturnType['artifactQuery'], flags: CliFlags, defaults: CliRunContext['connectionDefaults'], explicitFlagKeys: Set, ) { - const explicitArtifactQuery = - command === 'artifacts' && - (explicitFlagKeys.has('leaseId') || Boolean(positionals[0] ?? flags.providerSessionId)); const effectiveFlags = { ...flags }; for (const [key, value] of Object.entries(defaults?.flags ?? {}) as Array<[FlagKey, unknown]>) { if (value !== undefined && !explicitFlagKeys.has(key)) { (effectiveFlags as Record)[key] = value; } } - if (explicitArtifactQuery) { - effectiveFlags.leaseId = explicitFlagKeys.has('leaseId') ? flags.leaseId : undefined; - effectiveFlags.runId = explicitFlagKeys.has('runId') ? flags.runId : undefined; + if (artifactQuery) { + effectiveFlags.leaseId = artifactQuery.leaseId; + effectiveFlags.runId = artifactQuery.runId; effectiveFlags.leaseBackend = undefined; + if (artifactQuery.providerSessionId && defaults?.connection) { + effectiveFlags.provider ??= leaseProviderRequiringRuntime(defaults.connection); + } } - const sessionDefaults = explicitArtifactQuery ? undefined : defaults; + const sessionDefaults = artifactQuery ? undefined : defaults; return { - explicitArtifactQuery, + explicitArtifactQuery: Boolean(artifactQuery), effectiveFlags, resolvedRuntime: sessionDefaults?.runtime, connectionMetadata: sessionDefaults?.connection, diff --git a/src/cli/resolve-cli-options.ts b/src/cli/resolve-cli-options.ts index aab362a8a86..9cf645cc36e 100644 --- a/src/cli/resolve-cli-options.ts +++ b/src/cli/resolve-cli-options.ts @@ -11,6 +11,7 @@ import { type EnvMap } from '@agent-device/kernel/source-value'; export type ResolvedCliOptions = ReturnType & { providedFlags: ReturnType['providedFlags']; remoteConfigLeaseProvider: ReturnType['leaseProvider']; + artifactQuery?: { leaseId?: string; runId?: string; providerSessionId?: string }; /** Enforced on every finished daemon request by the client (`assertRequestHonorsDevicePin`). */ devicePin: DevicePin | undefined; }; @@ -39,16 +40,23 @@ export function resolveCliOptions( env, }); const devicePin = configDefaults.devicePin; - const defaultFlags = mergeDefinedFlags(configDefaults.flags, remoteConfig.flags); + const defaultFlags = mergeDefinedFlags({ ...configDefaults.flags }, remoteConfig.flags); const finalized = finalizeParsedArgs(rawParsed, { strictFlags: options?.strictFlags, defaultFlags, }); + const leaseId = rawParsed.flags.leaseId ?? configDefaults.flags.leaseId; + const runId = rawParsed.flags.runId ?? configDefaults.flags.runId; + const providerSessionId = finalized.positionals[0] ?? finalized.flags.providerSessionId; // The flags drop the profile's lease provider, which decides whether a session is required (#3931). return { ...finalized, providedFlags: rawParsed.providedFlags, remoteConfigLeaseProvider: remoteConfig.leaseProvider, + artifactQuery: + finalized.command === 'artifacts' && (leaseId || providerSessionId) + ? { leaseId, runId, providerSessionId } + : undefined, devicePin, }; } diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 842748d96e1..875c7984e09 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -635,7 +635,7 @@ Rules: To replace an existing connection, pass its returned session explicitly with --session --force. --force without --session creates another fresh session and does not release or overwrite an unrelated active connection. Prefer short-lived AWS role credentials in CI. Generated connection profiles store app/device selectors and ARNs, not Limrun API keys or instance tokens, BrowserStack or TestMu AI access keys, or AWS credentials. Limrun Android supports direct ADB port reverse for local Metro. Limrun iOS requires a public Metro URL because it cannot reach local host ports directly. - Before closing a device cloud session, save its lease and run IDs. Set AGENT_DEVICE_DAEMON_BASE_URL and AGENT_DEVICE_DAEMON_AUTH_TOKEN for the same remote daemon. After close, query from an unused session. + Before closing a device cloud session, save its lease and run IDs. For a remote daemon, set AGENT_DEVICE_DAEMON_BASE_URL and AGENT_DEVICE_DAEMON_AUTH_TOKEN for the producing daemon. For a local provider profile, use the producing daemon's state directory. After close, query from an unused session. agent-device artifacts --session artifact-lookup --tenant --provider --lease-id --run-id --json connect proxy stores the connection profile and client identity. Proxy device leases are acquired on open and expire after five minutes without commands; when a lease expires or is released, the daemon ends the session opened under it and frees its device; devices may inspect proxy inventory without allocating. Multiple agents can share one proxy when each uses connect proxy, open, commands, close, and disconnect. diff --git a/website/docs/docs/device-clouds.md b/website/docs/docs/device-clouds.md index c8ce75ef27e..871aca1640c 100644 --- a/website/docs/docs/device-clouds.md +++ b/website/docs/docs/device-clouds.md @@ -60,7 +60,9 @@ Use `snapshot -i` to confirm the target. If the driver does not support the `/el ## Retrieve artifacts after close -Before `close`, save the lease ID and run ID from the connection you used. Use the same daemon and tenant that produced the artifacts. An explicit `--lease-id` or provider session ID uses the saved connection's endpoint when you name its session. Pass the producing `--run-id` with either selector. For a standalone lookup, choose an unused `--session` name and set `AGENT_DEVICE_DAEMON_BASE_URL` and `AGENT_DEVICE_DAEMON_AUTH_TOKEN` for the producing daemon. +Before `close`, save the lease ID and run ID from the connection you used. Use the same daemon and tenant that produced the artifacts. An explicit `--lease-id` or provider session ID uses the saved connection's endpoint when you name its session. A provider-session lookup uses the named cloud connection's provider unless you pass `--provider`. Pass the producing `--run-id` with either selector. + +For a standalone lookup, choose an unused `--session` name. For a remote daemon, set `AGENT_DEVICE_DAEMON_BASE_URL` and `AGENT_DEVICE_DAEMON_AUTH_TOKEN` for the producing daemon. For a local provider profile, use the producing daemon's state directory. If you used `--state-dir` to select it, pass the same value again. Pass the producing lease and run IDs to list retained daemon artifacts. For provider-hosted artifacts by lease, also pass `--provider ` (see [Compare providers](#compare-providers)). If `close --json` returns a provider session ID, use that ID with the provider and original run: From bfdf5ce50920e87148d07c70bc74b1b674f18780 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 17:20:48 +0100 Subject: [PATCH 33/35] test(cli): follow artifact command check into option resolution --- src/cli-command-dispatch.test.ts | 51 ++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/src/cli-command-dispatch.test.ts b/src/cli-command-dispatch.test.ts index c9a93a85ae4..7121accbf5e 100644 --- a/src/cli-command-dispatch.test.ts +++ b/src/cli-command-dispatch.test.ts @@ -5,37 +5,42 @@ import { fileURLToPath } from 'node:url'; import { parseSync } from 'oxc-parser'; import { isKnownCliCommandName } from '@agent-device/command-registry/catalog'; -test('cli.ts command dispatch checks are recognized by parser-level unknown-command handling', () => { - const commands = collectCliDispatchCommandLiterals(); - // The exact set, so a reader that collects nothing, or stops collecting, fails here instead - // of passing over an empty loop. - assert.deepEqual([...commands].sort(), [ - 'artifacts', - 'batch', - 'cdp', - 'close', - 'connect', - 'connection', - 'disconnect', - 'help', - 'mcp', - 'open', - 'react-devtools', - 'runtime', - 'test', - 'web', - ]); +test.each([ + { + source: './cli.ts', + expected: [ + 'batch', + 'cdp', + 'close', + 'connect', + 'connection', + 'disconnect', + 'help', + 'mcp', + 'open', + 'react-devtools', + 'runtime', + 'test', + 'web', + ], + }, + { source: './cli/resolve-cli-options.ts', expected: ['artifacts'] }, +])('$source command checks are recognized by parser-level unknown-command handling', (fixture) => { + const { source, expected } = fixture; + const commands = collectCliCommandLiterals(source); + // The exact set catches a reader that stops collecting checks from this source. + assert.deepEqual([...commands].sort(), expected); for (const command of commands) { assert.equal( isKnownCliCommandName(command), true, - `cli.ts checks command "${command}" but the parser does not recognize it`, + `${source} checks command "${command}" but the parser does not recognize it`, ); } }); -function collectCliDispatchCommandLiterals(): Set { - const cliPath = fileURLToPath(new URL('./cli.ts', import.meta.url)); +function collectCliCommandLiterals(source: string): Set { + const cliPath = fileURLToPath(new URL(source, import.meta.url)); const sourceText = fs.readFileSync(cliPath, 'utf8'); const parsed = parseSync(cliPath, sourceText); const commands = new Set(); From 8d5cf141a1d37881602c38fc154af4c46e416bc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 17:48:28 +0100 Subject: [PATCH 34/35] fix(cli): restore provider artifact scope for named connections --- src/__tests__/cli-run-transport.test.ts | 33 +++++++++++++++++++++++++ src/cli.ts | 23 +++++++++++++++-- src/commands/schema/cli-help.ts | 1 + website/docs/docs/commands.md | 3 ++- 4 files changed, 57 insertions(+), 3 deletions(-) diff --git a/src/__tests__/cli-run-transport.test.ts b/src/__tests__/cli-run-transport.test.ts index 0eb214b13ae..ffe281ee83e 100644 --- a/src/__tests__/cli-run-transport.test.ts +++ b/src/__tests__/cli-run-transport.test.ts @@ -81,6 +81,21 @@ test.each(['artifact-lookup', 'default'])('artifact query scope in %s', async (s const owningRunArgs = [...args, '--run-id', 'owning-run']; const deps = { sendToDaemon: vi.fn(), transportForHost }; + await runCli( + [ + ...args, + ...(session === 'artifact-lookup' ? ['--provider', 'browserstack'] : []), + '--provider-session', + 'current-provider-session', + ], + deps, + host, + ); + await runCli( + [...args, '--provider', 'testmu', '--provider-session', 'different-provider-session'], + deps, + host, + ); await runCli([...owningRunArgs, '--lease-id', owningLeaseId], deps, host); await runCli( [ @@ -134,6 +149,24 @@ test.each(['artifact-lookup', 'default'])('artifact query scope in %s', async (s providerSessionId: request.flags?.providerSessionId, })), [ + { + command: 'artifacts', + daemonBaseUrl: 'http://127.0.0.1:7001', + tenantId: 'tenant', + runId: session === 'default' ? 'current-run' : undefined, + leaseId: session === 'default' ? 'b'.repeat(32) : undefined, + provider: 'browserstack', + providerSessionId: 'current-provider-session', + }, + { + command: 'artifacts', + daemonBaseUrl: 'http://127.0.0.1:7001', + tenantId: 'tenant', + runId: undefined, + leaseId: undefined, + provider: 'testmu', + providerSessionId: 'different-provider-session', + }, { command: 'artifacts', daemonBaseUrl: 'http://127.0.0.1:7001', diff --git a/src/cli.ts b/src/cli.ts index fda93c76a93..b60ce3a6d90 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -871,11 +871,30 @@ function resolveConnectionRunScope( } } if (artifactQuery) { + const connection = defaults?.flags; + const connectionProvider = defaults?.connection + ? leaseProviderRequiringRuntime(defaults.connection) + : undefined; effectiveFlags.leaseId = artifactQuery.leaseId; effectiveFlags.runId = artifactQuery.runId; effectiveFlags.leaseBackend = undefined; - if (artifactQuery.providerSessionId && defaults?.connection) { - effectiveFlags.provider ??= leaseProviderRequiringRuntime(defaults.connection); + if (artifactQuery.providerSessionId) { + effectiveFlags.provider ??= connectionProvider; + if ( + artifactQuery.leaseId === undefined && + artifactQuery.runId === undefined && + explicitFlagKeys.has('session') && + connection?.leaseId && + connection.runId && + connectionProvider && + effectiveFlags.provider === connectionProvider && + effectiveFlags.tenant === connection.tenant && + effectiveFlags.daemonBaseUrl === connection.daemonBaseUrl && + effectiveFlags.daemonTransport === connection.daemonTransport + ) { + effectiveFlags.leaseId = connection.leaseId; + effectiveFlags.runId = connection.runId; + } } } const sessionDefaults = artifactQuery ? undefined : defaults; diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 875c7984e09..627e02964cf 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -635,6 +635,7 @@ Rules: To replace an existing connection, pass its returned session explicitly with --session --force. --force without --session creates another fresh session and does not release or overwrite an unrelated active connection. Prefer short-lived AWS role credentials in CI. Generated connection profiles store app/device selectors and ARNs, not Limrun API keys or instance tokens, BrowserStack or TestMu AI access keys, or AWS credentials. Limrun Android supports direct ADB port reverse for local Metro. Limrun iOS requires a public Metro URL because it cannot reach local host ports directly. + To look up artifacts for a provider session on the current cloud connection, run agent-device artifacts --session --provider-session . The provider session must belong to that connection's lease. Before closing a device cloud session, save its lease and run IDs. For a remote daemon, set AGENT_DEVICE_DAEMON_BASE_URL and AGENT_DEVICE_DAEMON_AUTH_TOKEN for the producing daemon. For a local provider profile, use the producing daemon's state directory. After close, query from an unused session. agent-device artifacts --session artifact-lookup --tenant --provider --lease-id --run-id --json connect proxy stores the connection profile and client identity. Proxy device leases are acquired on open and expire after five minutes without commands; when a lease expires or is released, the daemon ends the session opened under it and frees its device; devices may inspect proxy inventory without allocating. diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index cb6845fdd40..1d91e75c4f4 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2783,7 +2783,8 @@ agent-device artifacts --provider aws-device-farm --provider-session `, `--provider-session `, and the owning `--run-id `. -- To look up artifacts by lease, pass the producing `--lease-id ` and `--run-id `. For a provider session ID, pass the provider and producing run. If you also pass a lease ID, it must match the provider session's lease. +- For a provider session on your current cloud connection, pass `--session ` and `--provider-session `. The lookup uses that connection's provider, lease, and run when you omit `--lease-id` and `--run-id`. The provider session must belong to that lease. +- To look up artifacts by lease, pass the producing `--lease-id ` and `--run-id `. If you also pass a provider session ID, it must belong to the lease. - To query after close, use the saved connection's session for its endpoint or follow the standalone workflow in [Retrieve artifacts after close](/docs/device-clouds#retrieve-artifacts-after-close). - Providers can finish their URLs only after the session stops, so retry `artifacts` if the first response is `pending`. From 46a98d5310ea6a4730f871a3a2a903ff03f0bd86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 18:05:29 +0100 Subject: [PATCH 35/35] refactor(cli): separate artifact run scope resolution --- src/cli.ts | 59 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 25 deletions(-) diff --git a/src/cli.ts b/src/cli.ts index b60ce3a6d90..8ca2e765e10 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -871,31 +871,7 @@ function resolveConnectionRunScope( } } if (artifactQuery) { - const connection = defaults?.flags; - const connectionProvider = defaults?.connection - ? leaseProviderRequiringRuntime(defaults.connection) - : undefined; - effectiveFlags.leaseId = artifactQuery.leaseId; - effectiveFlags.runId = artifactQuery.runId; - effectiveFlags.leaseBackend = undefined; - if (artifactQuery.providerSessionId) { - effectiveFlags.provider ??= connectionProvider; - if ( - artifactQuery.leaseId === undefined && - artifactQuery.runId === undefined && - explicitFlagKeys.has('session') && - connection?.leaseId && - connection.runId && - connectionProvider && - effectiveFlags.provider === connectionProvider && - effectiveFlags.tenant === connection.tenant && - effectiveFlags.daemonBaseUrl === connection.daemonBaseUrl && - effectiveFlags.daemonTransport === connection.daemonTransport - ) { - effectiveFlags.leaseId = connection.leaseId; - effectiveFlags.runId = connection.runId; - } - } + applyArtifactRunScope(artifactQuery, effectiveFlags, defaults, explicitFlagKeys); } const sessionDefaults = artifactQuery ? undefined : defaults; return { @@ -906,6 +882,39 @@ function resolveConnectionRunScope( }; } +function applyArtifactRunScope( + artifactQuery: NonNullable['artifactQuery']>, + effectiveFlags: CliFlags, + defaults: CliRunContext['connectionDefaults'], + explicitFlagKeys: Set, +): void { + const connection = defaults?.flags; + const connectionProvider = defaults?.connection + ? leaseProviderRequiringRuntime(defaults.connection) + : undefined; + effectiveFlags.leaseId = artifactQuery.leaseId; + effectiveFlags.runId = artifactQuery.runId; + effectiveFlags.leaseBackend = undefined; + if (artifactQuery.providerSessionId) { + effectiveFlags.provider ??= connectionProvider; + if ( + artifactQuery.leaseId === undefined && + artifactQuery.runId === undefined && + explicitFlagKeys.has('session') && + connection?.leaseId && + connection.runId && + connectionProvider && + effectiveFlags.provider === connectionProvider && + effectiveFlags.tenant === connection.tenant && + effectiveFlags.daemonBaseUrl === connection.daemonBaseUrl && + effectiveFlags.daemonTransport === connection.daemonTransport + ) { + effectiveFlags.leaseId = connection.leaseId; + effectiveFlags.runId = connection.runId; + } + } +} + function hasExplicitMetroRuntimeOverrides(explicitFlagKeys: Set): boolean { for (const key of METRO_RUNTIME_OVERRIDE_FLAG_KEYS) { if (explicitFlagKeys.has(key)) {