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..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 @@ -33,20 +33,36 @@ 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( + await 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( + await resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner }), + ).toEqual({ kind: 'completed', completion }); + await expect( + resolveScreenRecordingStopRecovery({ + ...harness.params, + device: SESSION_DEVICE, + owner: { ...owner, leaseId: 'other-lease' }, + }), + ).rejects.toMatchObject({ code: 'UNAUTHORIZED' }); expect(screenRecordingManifestIsTerminal(harness.params)).toBe(true); }); @@ -70,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 }), + await resolveScreenRecordingStopRecovery({ + ...harness.params, + device: SESSION_DEVICE, + owner: {}, + }), ).toEqual({ kind: 'none' }); } }); @@ -80,9 +100,13 @@ 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( + await resolveScreenRecordingStopRecovery({ + ...harness.params, + device: SESSION_DEVICE, + owner: {}, + }), + ).toEqual({ kind: 'none' }); }); test('a completed manifest owned by another session is refused', async () => { @@ -90,9 +114,9 @@ test('a completed manifest owned by another session is refused', async () => { await completeRecording(harness); writeManifest(harness, undefined, { sessionId: 'other-session' }); - expect(() => - resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE }), - ).toThrowError(expect.objectContaining({ details: { reason: 'runtime-contract-invalid' } })); + await expect( + resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), + ).rejects.toMatchObject({ details: { reason: 'runtime-contract-invalid' } }); }); test('a completed manifest bound to another device is refused', async () => { @@ -102,27 +126,35 @@ test('a completed manifest bound to another device is refused', async () => { device: deviceIdentity({ ...SESSION_DEVICE, id: 'emulator-5556' }), }); - expect(() => - resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE }), - ).toThrowError(expect.objectContaining({ details: { reason: 'runtime-contract-invalid' } })); + await expect( + resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }), + ).rejects.toMatchObject({ details: { reason: 'runtime-contract-invalid' } }); }); 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( + 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 })).toEqual( - { kind: 'none' }, - ); + expect( + 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 4e0383fa745..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 @@ -49,12 +49,25 @@ type ScreenRecordingManifestParams = Readonly<{ sessionStore: Readonly<{ resolveSessionDir(name: string): string }>; }>; -export function resolveScreenRecordingStopRecovery( - params: ScreenRecordingManifestParams & Readonly<{ device: DeviceInfo }>, -): ScreenRecordingStopRecovery { +export async function resolveScreenRecordingStopRecovery( + params: ScreenRecordingManifestParams & + Readonly<{ + device: DeviceInfo; + owner: Readonly<{ tenantId?: string; leaseId?: string }>; + }>, +): Promise { 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 + ) { + 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, + }); + } if (record.envelope.lifecycle !== 'completed') return { kind: 'open', resourcePath }; const completion = readReplayableStoredCompletion(record.envelope.metadata); if (completion === undefined) { 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..637894164e9 --- /dev/null +++ b/packages/command-surface/src/management/artifacts.test.ts @@ -0,0 +1,23 @@ +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', 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 = await artifactsCommandFacet.daemonWriter(input, createTestHostEnvironment()); + assert.equal(request.options.leaseId, 'lease-a'); + assert.equal(request.options.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..01c1ce6a4a1 100644 --- a/packages/command-surface/src/management/artifacts.ts +++ b/packages/command-surface/src/management/artifacts.ts @@ -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/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/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 9c849d8ccfd..99aa29010b5 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -10,9 +10,10 @@ 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'; export const DAEMON_HTTP_PUBLIC_NETWORK_ACCESS = 'public-only'; @@ -120,11 +121,17 @@ 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 // an acknowledged-compatible entry (#1432). -export const DAEMON_RPC_PROTOCOL_VERSION = 3; +export const DAEMON_RPC_PROTOCOL_VERSION = 4; /** * The largest serialized daemon request, in UTF-8 bytes, that any transport reads: the socket diff --git a/packages/contracts/src/lease-scope.ts b/packages/contracts/src/lease-scope.ts index bbf7320904f..e07a60d47a8 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')) || undefined; 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-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/packages/daemon-client/src/__tests__/daemon-client-transport-health-compat.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport-health-compat.test.ts index a961aead4f3..3958109136a 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport-health-compat.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport-health-compat.test.ts @@ -226,20 +226,27 @@ test('a daemon health payload without an upstream link or host arch parses as be ); }); -test.for(['daemon', 'upstream'] as const)( - 'released protocol-2 %s cannot silently omit batch receipt delivery', - async (link, t) => { +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-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/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 new file mode 100644 index 00000000000..59c8a424de5 --- /dev/null +++ b/packages/daemon/src/resources/__tests__/lease-registry-artifact-retention.test.ts @@ -0,0 +1,28 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { LeaseRegistry } from '../lease-registry.ts'; + +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' }); + 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 - 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, + tenantId: 'tenant-a', + runId: 'run-a', + }), + ); +}); diff --git a/packages/daemon/src/resources/__tests__/lease-registry.test.ts b/packages/daemon/src/resources/__tests__/lease-registry.test.ts index 0672a6d71a2..1039fa43a85 100644 --- a/packages/daemon/src/resources/__tests__/lease-registry.test.ts +++ b/packages/daemon/src/resources/__tests__/lease-registry.test.ts @@ -156,6 +156,17 @@ 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 0a06f195f1b..516699b31a6 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,85 @@ 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', () => { + const leaseId = 'ABCDEF0123456789ABCDEF0123456789'; + const root = mkdtempForTestSync('agent-device-upload-lease-'); + const artifactPath = path.join(root, 'payload'); + fs.writeFileSync(artifactPath, 'payload'); + const runtime = createRuntimeStateHandle(); + const id = runtime.run(() => + trackUploadedArtifact({ + artifactPath, + tempDir: root, + tenantId: 'tenant-a', + leaseId, + }), + ); + + 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( + 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'); + const runtime = createRuntimeStateHandle(); + const id = runtime.run(() => + trackDownloadableArtifact({ + artifactPath, + tenantId: 'tenant-a', + leaseId, + artifactType: 'screen-recording', + }), + ); + try { + expect( + await runtime.run(() => + listDownloadableArtifacts('tenant-a', process.env, '1234567890abcdef1234567890abcdef'), + ), + ).toEqual([]); + expect( + await runtime.run(() => + listDownloadableArtifacts('tenant-a', process.env, leaseId.toLowerCase()), + ), + ).toHaveLength(1); + await expect( + runtime.run(() => + openDownloadableArtifact( + id, + 'tenant-a', + process.env, + undefined, + '1234567890abcdef1234567890abcdef', + ), + ), + ).rejects.toMatchObject({ + code: 'UNAUTHORIZED', + details: { reason: 'ARTIFACT_LEASE_MISMATCH' }, + }); + const opened = await runtime.run(() => + openDownloadableArtifact(id, 'tenant-a', process.env, undefined, leaseId.toLowerCase()), + ); + 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..839ca9e7df8 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -3,10 +3,15 @@ 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'; +import { normalizeLeaseId } from '@agent-device/contracts/lease-scope'; import type { PackedGzipTar } from '@agent-device/host-kit/gzip-tar'; import { expiredTenantOwnedEntryError, @@ -19,6 +24,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.`, @@ -53,6 +63,7 @@ type ArtifactDownload = { type ArtifactEntry = { artifactPath: string; tenantId?: string; + leaseId?: string; artifactType: DaemonArtifactType | undefined; fileName?: string; displayRotation?: DeviceRotation; @@ -94,6 +105,7 @@ const pendingUploads = () => artifactTracking().uploads; export type DownloadableArtifactRegistration = { artifactPath: string; tenantId?: string; + leaseId?: string; artifactType: DaemonArtifactType | undefined; fileName?: string; displayRotation?: DeviceRotation; @@ -119,12 +131,13 @@ 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. */ export function trackDownloadableArtifact(params: DownloadableArtifactRegistration): string { - const existingId = findTrackedArtifactId(params.artifactPath, params.tenantId); + 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(); @@ -141,6 +154,7 @@ export function trackDownloadableArtifact(params: DownloadableArtifactRegistrati pendingArtifacts().set(artifactId, { artifactPath: params.artifactPath, tenantId: params.tenantId, + leaseId, artifactType: params.artifactType, fileName: params.fileName, ...(params.displayRotation !== undefined ? { displayRotation: params.displayRotation } : {}), @@ -157,12 +171,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 +197,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 +262,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 +308,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 +319,11 @@ function readDownloadableArtifactEntry( if (entry.cleanupRequested) { throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } + if (entry.leaseId !== (normalizeLeaseId(leaseId) ?? leaseId)) { + throw new AppError('UNAUTHORIZED', 'Artifact belongs to a different lease', { + reason: ARTIFACT_TRACKING_REASONS.leaseMismatch.reason, + }); + } let stat: fs.Stats; try { stat = fs.statSync(entry.artifactPath); @@ -435,8 +459,16 @@ 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 === (normalizeLeaseId(leaseId) ?? leaseId) + ); } function safeArtifactFilename(fileName: string | undefined, fallback: string): string { @@ -510,6 +542,7 @@ type UploadEntry = { artifactPath: string; tempDir: string; tenantId?: string; + leaseId?: string; timer: ReturnType; }; @@ -517,6 +550,7 @@ export function trackUploadedArtifact(params: { artifactPath: string; tempDir: string; tenantId?: string; + leaseId?: string; }): string { const uploadId = crypto.randomUUID(); const timer = setTimeout(() => { @@ -527,18 +561,28 @@ export function trackUploadedArtifact(params: { artifactPath: params.artifactPath, tempDir: params.tempDir, tenantId: params.tenantId, + leaseId: normalizeLeaseId(params.leaseId) ?? params.leaseId, 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 !== (normalizeLeaseId(leaseId) ?? leaseId)) { + 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 fd62615a014..3a2cb88a2de 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -48,11 +48,21 @@ 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 }; 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(); @@ -118,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) { @@ -130,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); @@ -164,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) }; } @@ -187,6 +202,11 @@ 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); } @@ -234,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); @@ -293,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); @@ -313,22 +333,50 @@ 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); } - /** Admit a scoped read without filling an omitted backend with an allocation default. */ - assertLeaseReadAdmission(request: HeartbeatLeaseRequest): void { - this.cleanupExpiredLeases(); + /** Uploads match the active lease's tenant and any supplied run. */ + assertUploadLeaseAdmission(request: { leaseId: string; tenantId: string; runId?: string }): void { + this.consumeExpiredLeases(); const lease = this.getActiveLease(normalizeRequiredLeaseId(request.leaseId)); - assertLeaseOwnerScope(lease, request); - 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. */ + assertArtifactLeaseReadAdmission(request: { + leaseId: string; + tenantId?: string; + runId?: string; + }): void { + const leaseId = normalizeRequiredLeaseId(request.leaseId); + this.consumeExpiredLeases(); + const owner = this.artifactLeaseOwners.get(leaseId); + if ( + !owner || + !request.tenantId || + owner.tenantId !== request.tenantId || + (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', { + reason: LEASE_REGISTRY_REASONS.artifactReadNotOwned.reason, + }); + } } /** Whether this daemon ever allocated `tenantId` a `macos-app` lease, released or not. */ @@ -356,15 +404,15 @@ export class LeaseRegistry { } listActiveLeases(): DeviceLease[] { - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); return Array.from(this.leases.values()).map((entry) => ({ ...entry })); } recordProviderSession( - lease: Pick, + 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)) { @@ -376,13 +424,24 @@ export class LeaseRegistry { provider?: string; providerSessionId?: string; tenantId?: string; + runId?: string; }): ProviderSessionOwnership | undefined { - this.cleanupExpiredLeases(); + this.consumeExpiredLeases(); return this.providerSessionOwnership.resolve(params); } + resolveRetainedProviderLease(params: { + leaseId: string; + provider?: string; + tenantId?: string; + runId?: string; + }): ReturnType { + 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)) @@ -404,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); @@ -473,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); @@ -503,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); @@ -638,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; } @@ -660,10 +724,6 @@ export class LeaseRegistry { return expiredLease; } - private cleanupExpiredLeases(): void { - this.consumeExpiredLeases(); - } - private enforceCapacity(backend: LeaseBackend): void { if (backend !== 'ios-simulator') return; if (this.maxActiveSimulatorLeases <= 0) return; @@ -710,6 +770,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 08a8b2ed7e1..aa5a7d9ffcb 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,38 @@ 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(); + 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) return undefined; + if (!record || record.tenantId !== tenantId || (runId && record.runId !== runId)) { + return undefined; + } return { ...record }; } + resolveLease(params: { + leaseId: string; + provider?: string; + tenantId?: string; + runId?: string; + }): LeaseOwnershipRecord | 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 === provider && record.tenantId === tenantId && record.runId === runId + ? { ...record } + : undefined; + } + private prune(): void { const now = this.now(); for (const [key, record] of this.records) { @@ -84,6 +127,10 @@ 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/__tests__/request-finalization.test.ts b/packages/daemon/src/server/__tests__/request-finalization.test.ts index 94fa4dcc586..c3938dacd56 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,46 @@ 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[] = []; + + const response = 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); + expect(response.ok && response.data?.artifacts?.[0]?.downloadScope).toEqual({ + leaseId: lease.leaseId, + tenantId: lease.tenantId, + }); +}); + 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..3d65f866ada 100644 --- a/packages/daemon/src/server/__tests__/resumable-upload.test.ts +++ b/packages/daemon/src/server/__tests__/resumable-upload.test.ts @@ -35,6 +35,34 @@ 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 5bd12ae641a..75d82ebeef7 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -12,11 +12,19 @@ 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, + 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 // sizes. sizeMismatch: { reason: 'artifact_size_mismatch' }, + // A leased artifact request needs a tenant and lease registry. + leaseAdmissionRequired: { reason: 'ARTIFACT_LEASE_ADMISSION_REQUIRED' }, } as const satisfies ReasonTable<'artifact downloads'>; type DownloadableArtifactHttpRoute = @@ -36,14 +44,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; } @@ -53,7 +63,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': @@ -82,7 +92,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; @@ -101,12 +111,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, + leaseId, ); const { stream } = artifact; const closed = finished(stream, { cleanup: true }).catch(() => {}); @@ -162,7 +174,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({ @@ -174,12 +186,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), + artifacts: await listDownloadableArtifacts(auth.tenantId, options.hostEnv, leaseId), }), ); } catch (error) { @@ -187,6 +200,33 @@ async function handleArtifactInventory( } } +function admitArtifactLease( + req: http.IncomingMessage, + tenantId: string | undefined, + leaseRegistry: LeaseRegistry | undefined, +): string | undefined { + const value = req.headers[DAEMON_HTTP_LEASE_HEADER]; + if (value === undefined) return undefined; + const runId = req.headers[DAEMON_HTTP_RUN_HEADER]; + if ( + typeof value !== 'string' || + !value.trim() || + (runId !== undefined && typeof runId !== 'string') || + !leaseRegistry + ) { + 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 }); + return leaseId; +} + function readArtifactId(pathname: string): string { const encoded = pathname.slice('/artifacts/'.length); if (!encoded || encoded.includes('/')) return ''; 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 36e05c5c7c7..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 @@ -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,19 @@ 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, + }, }); 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, + }, }); expect(ownTenant.status).toBe(200); expect(await ownTenant.text()).toBe('private-recording'); 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..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 @@ -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,109 @@ 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', + 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', + ...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 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 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: { + ...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'), + 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-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/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 3762f2e7d1c..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 @@ -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,28 +302,21 @@ test.each(['marker', 'auth-hook', 'batch'] as const)( expect(runtime.captureScreenshot).toHaveBeenCalledTimes(1); }, env, + leaseRegistry, ); }, ); -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('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'); @@ -337,7 +337,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; @@ -346,13 +347,23 @@ 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'] }); - 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'); - const download = await fetch(`${base}/artifacts/${artifact?.artifactId}`, { - headers: { authorization: 'Bearer test-token' }, + expect(artifact?.downloadScope).toBeUndefined(); + 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 }); expect(download.status).toBe(200); expect(await download.text()).toBe('generated-video'); }, @@ -915,6 +926,27 @@ 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 = scopedHeaders('tenant-a', otherRun.leaseId, '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); @@ -924,8 +956,13 @@ 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: 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' }, + headers: scopedHeaders('tenant-b', leases.get('tenant-b')!.leaseId.toUpperCase()), }); expect(download.status).toBe(200); const archive = gunzipSync(Buffer.from(await download.arrayBuffer())); @@ -937,12 +974,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' }, + 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' }, + headers: scopedHeaders('tenant-a', leases.get('tenant-a')!.leaseId), }); expect(own.status).toBe(200); await own.arrayBuffer(); @@ -953,6 +990,7 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite }); }, env, + leaseRegistry, ); } finally { cwd.mockRestore(); 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/request-finalization.ts b/packages/daemon/src/server/request-finalization.ts index 06b515b4a8b..dd9c7b1f327 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 & { @@ -99,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 @@ -106,9 +112,8 @@ function registerDownloadableArtifacts( ...(artifact.artifactType !== undefined ? { artifactType: artifact.artifactType } : {}), artifactId: trackArtifact({ artifactPath, - tenantId: delivered - ? delivered.tenantId - : (captureOutputTenantId(data) ?? req.meta?.tenantId), + tenantId, + leaseId, artifactType: artifact.artifactType, fileName: artifact.fileName, ...(artifact.deleteAfterDownload === false ? { deleteAfterDownload: false } : {}), @@ -116,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/resumable-upload.ts b/packages/daemon/src/server/resumable-upload.ts index 2ee91d1b54f..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; @@ -71,6 +74,7 @@ export type BeginResumableUploadOptions = { platform?: string; contentType?: string; tenantId?: string; + leaseId?: string; }; type ResumableUploadEntry = { @@ -84,6 +88,7 @@ type ResumableUploadEntry = { artifactType: 'file' | 'app-bundle'; platform?: string; tenantId?: string; + leaseId?: string; timer?: ReturnType; generation: number; tail: Promise; @@ -178,13 +183,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 +240,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 +316,7 @@ function createResumableUploadEntry( artifactType: options.artifactType, platform: options.platform, tenantId: options.tenantId, + leaseId: canonicalLeaseId(options.leaseId), generation: 0, tail: Promise.resolve(), closed: false, @@ -373,7 +381,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 +462,20 @@ 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 !== canonicalLeaseId(leaseId)) { + throw new AppError('UNAUTHORIZED', 'Upload belongs to a different lease', { + reason: UPLOAD_FINALIZE_REASONS.leaseMismatch.reason, + }); + } + return entry; } function validateResumableUploadOptions(options: BeginResumableUploadOptions): void { @@ -480,6 +495,7 @@ function validateResumableUploadOptions(options: BeginResumableUploadOptions): v function buildResumableUploadKey(options: BeginResumableUploadOptions): string { return [ options.tenantId ?? '', + canonicalLeaseId(options.leaseId) ?? '', options.uploadAttemptId, options.sha256.toLowerCase(), String(options.sizeBytes), @@ -488,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 666161a39a3..eb5116a10c0 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 { @@ -13,9 +13,20 @@ 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, + 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/'; +const UPLOAD_LEASE_REASONS = { + // A leased upload needs a tenant and lease registry. + admissionRequired: { reason: 'UPLOAD_LEASE_ADMISSION_REQUIRED' }, +} as const satisfies ReasonTable<'uploads'>; + type UploadHttpRoute = | { kind: 'upload' } | { kind: 'preflight' } @@ -53,12 +64,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 +81,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 +122,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 +144,32 @@ 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; + const runId = req.headers[DAEMON_HTTP_RUN_HEADER]; + if ( + typeof header !== 'string' || + !header.trim() || + (runId !== undefined && typeof runId !== 'string') || + !tenantId || + !leaseRegistry + ) { + throw new AppError( + 'UNAUTHORIZED', + 'Upload lease requires an admitted tenant and lease registry', + { reason: UPLOAD_LEASE_REASONS.admissionRequired.reason }, + ); + } + const leaseId = normalizeRequiredLeaseId(header); + leaseRegistry.assertUploadLeaseAdmission({ leaseId, tenantId, runId }); + return leaseId; +} + /** The upload command and positionals the auth hook sees, under the ingress signal. */ async function authorizeUpload( authorize: AuxiliaryHttpAuthorizer, @@ -145,8 +191,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 +203,7 @@ async function handleUpload( }), auth.tenantId, ingress.commit, + auth.leaseId, ); }); } @@ -166,8 +214,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 +231,7 @@ async function handleUploadPreflight( tokenHeaders: buildUploadTicketAuthHeaders(token), ...preflight, tenantId: auth.tenantId, + leaseId: auth.leaseId, }, (upload) => ingress.commit(() => sendJson(res, { ok: true, ...upload })), ); @@ -193,39 +243,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 +295,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 +327,7 @@ function sendUploadedArtifactResponse( result: { artifactPath: string; tempDir: string }, tenantId: string | undefined, commit: (work: () => T) => T, + leaseId?: string, ): void { let registered = false; try { @@ -269,6 +336,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 5a24b5ff78a..ab40a7e092d 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 } 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,11 +56,12 @@ vi.mock('../../resources/artifact-tracking.ts', async (importOriginal) => { }); const TENANT = 'tenant-a'; +const LEASE_ID = 'abcdef0123456789abcdef0123456789'; 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 }); @@ -90,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', @@ -135,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( @@ -161,7 +172,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,23 +194,40 @@ 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 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 { - const response = await fetch(`http://127.0.0.1:${port}/artifacts/${video!.id}`); + 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 }, + }); 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 +240,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 +258,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 +269,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,12 +278,13 @@ 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({ + const recovery = await resolveScreenRecordingStopRecovery({ 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( @@ -265,7 +294,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 +303,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 +318,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 +330,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); }); @@ -312,7 +341,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'); @@ -330,7 +359,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/__tests__/materialized-path-registry.test.ts b/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts index 04f19cebf1f..d3dad99ba15 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,33 @@ 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 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, + }); + + for (const leaseId of [undefined, '1234567890abcdef1234567890abcdef']) { + await assert.rejects( + () => cleanupRetainedMaterializedPaths(retained.materializationId, 'tenant-a', leaseId), + { code: 'UNAUTHORIZED', details: { reason: 'MATERIALIZED_PATH_LEASE_MISMATCH' } }, + ); + assert.equal(fs.existsSync(retained.installablePath), true); + } + await cleanupRetainedMaterializedPaths( + retained.materializationId, + 'tenant-a', + leaseId.toLowerCase(), + ); + 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/__tests__/request-handler-catalog.test.ts b/packages/daemon/src/sessions/__tests__/request-handler-catalog.test.ts index 91f7ead218d..2e977d17c3d 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', + leaseBackend: '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,11 +614,12 @@ function trackProxyLeaseArtifact(): { artifactId: string; tempDir: string } { artifactType: 'screenshot', fileName: 'proxy-shot.png', tenantId: 'tenant-a', + leaseId, }), }; } -function proxyArtifactsRequest(): DaemonRequest { +function proxyArtifactsRequest(leaseId: string): DaemonRequest { return { command: PUBLIC_COMMANDS.artifacts, token: 'test-token', @@ -618,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 a93f612d656..301f0529fcc 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,11 @@ 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'; +import { + cleanupUploadedArtifact, + trackUploadedArtifact, +} from '../../../resources/artifact-tracking.ts'; type SourceRuntimeOptions = Readonly<{ materializationAvailable?: boolean; @@ -121,6 +126,73 @@ test('install_source materializes and deploys through the admitted ready runtime expect(deploy).toHaveBeenCalledOnce(); }); +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, + }); + 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 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)', 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 15263141a63..adab8709076 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,71 @@ 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'; +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'); + 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.details?.reason === 'ARTIFACT_LEASE_ID_REQUIRED', + ); + 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'); @@ -37,6 +96,48 @@ 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('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'); @@ -74,13 +175,80 @@ 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'); + assert.equal(error.details?.reason, 'ARTIFACT_LEASE_NOT_OWNED'); + 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'); + 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', runId: 'run-a', + leaseId: lease.leaseId.toUpperCase(), providerSessionId: 'session-tenant-a', }); assert.equal(active.ok, true); 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..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 for the named session', 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 for the na 'capture.mp4', ); fs.writeFileSync(outPath, 'mp4'); - await harness.run(['start', outPath]); + 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 }); + const recovered = await harness.run(['stop'], { sessionExplicit: true, ...owner }); expect(recovered).toMatchObject({ ok: true, @@ -105,6 +106,26 @@ test('record stop after a daemon restart replays the completed export for the na ); }); +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 +216,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 +226,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/__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 42632d95f0d..a2b45d9a957 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -67,6 +67,12 @@ 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' }, + // 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. macOsAppHostOwned: { reason: 'MACOS_APP_LEASE_HOST_OWNED' }, // Only the host administrator allocates a `macos-app` lease. @@ -90,31 +96,17 @@ type LeaseHandlerArgs = { export async function handleLeaseCommands(args: LeaseHandlerArgs): Promise { const { req, - sessionName, - sessionStore, leaseRegistry, providerRuntimeIds, failedPlugins, providerCredentials, leaseLifecycleProvider, - cloudArtifactProvider, endSessionsForLease, } = args; const leaseScope = resolveLeaseScope(req); switch (req.command) { - case PUBLIC_COMMANDS.artifacts: { - const artifactScope = resolveRequestOrSessionLeaseScope(req, sessionStore.get(sessionName)); - return { - ok: true, - data: (await listArtifactsForRequest( - req, - artifactScope, - leaseRegistry, - cloudArtifactProvider, - args.host.env, - )) as Record, - }; - } + 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: @@ -509,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, @@ -518,7 +546,13 @@ async function listArtifactsForRequest( ): Promise { const providerSessionId = readFlagString(req.flags, 'providerSessionId'); if (shouldListDaemonArtifacts(leaseScope, providerSessionId)) { - return await listDaemonArtifacts(leaseScope.tenantId, hostEnv); + if (leaseScope.leaseId) { + leaseRegistry.assertArtifactLeaseReadAdmission({ + ...leaseScope, + leaseId: leaseScope.leaseId, + }); + } + return await listDaemonArtifacts(leaseScope.tenantId, leaseScope.leaseId, hostEnv); } return await listCloudArtifactsForRequest( @@ -538,9 +572,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 +603,27 @@ 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', { + reason: LEASE_HANDLER_REASONS.artifactLeaseNotOwned.reason, + }); + } } 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, @@ -591,10 +644,18 @@ function resolveProviderSession( providerSessionId: string | undefined, ): ReturnType { if (!providerSessionId) return undefined; + 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.', + }); + } const providerSession = leaseRegistry.resolveProviderSession({ provider: leaseScope.leaseProvider, providerSessionId, tenantId: leaseScope.tenantId, + 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..6d1510b6227 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 { @@ -42,6 +43,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 { @@ -248,6 +250,7 @@ async function startRecording( if (session.screenRecording) { return { ok: false, error: { code: 'INVALID_ARGS', message: 'recording already in progress' } }; } + const { tenantId, leaseId } = resolveRecordingStartOwner(params.req, session); const draft = ref ? undefined : bindRecordOnlyScreenRecording(params.sessionStore, params.sessionName, session); @@ -276,7 +279,6 @@ async function startRecording( const started = await runtime.operations.screenRecordingStart( screenRecordingStartInput(params, session, prepared, fence, outputPaths), ); - const tenantId = session.lease?.tenantId ?? params.req.meta?.tenantId; await adoptStartedScreenRecording({ admissionLedger: params.admissionLedger, binding, @@ -285,13 +287,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, @@ -506,10 +509,11 @@ async function finishRecovered( session: SessionState, needsReadiness: boolean, ): Promise { - const recovery = resolveScreenRecordingStopRecovery({ + const recovery = await resolveScreenRecordingStopRecovery({ 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 +529,26 @@ async function finishRecovered( return { completion, recordsSessionAction: true }; } +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; +} + +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. diff --git a/packages/daemon/src/sessions/handlers/session-app-deployment.ts b/packages/daemon/src/sessions/handlers/session-app-deployment.ts index b8ef2f0f8e9..469e26fee23 100644 --- a/packages/daemon/src/sessions/handlers/session-app-deployment.ts +++ b/packages/daemon/src/sessions/handlers/session-app-deployment.ts @@ -29,6 +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 { resolveRequestOrSessionLeaseScope } from '../../core/lease-context.ts'; import { requireSessionOrExplicitSelector, resolveCommandDevice, @@ -67,17 +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) + ? prepareUploadedArtifact(uploadedArtifactId, owner.tenantId, owner.leaseId) : expandSessionPath(target.appPathInput, requestCwd(req, params.host)); try { if (!fs.existsSync(appPath)) { @@ -101,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 862a1fd3444..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,6 +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, + type LeaseScope, +} from '../../core/lease-context.ts'; import { resolveCommandDevice } from '../../resources/session-device-resolution.ts'; import { requireRuntimeBinding, @@ -64,12 +69,13 @@ export async function handleInstallFromSourceDeploymentCommand(params: { const { req, sessionName, sessionStore } = params; const ref = sessionStore.lookup(sessionName); const session = ref?.session; + 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); + resolvedSource = resolveInstallSource(req, owner); let device = await resolveInstallDevice( session, req, @@ -114,7 +120,7 @@ export async function handleInstallFromSourceDeploymentCommand(params: { retained = await retainIfRequested({ artifact: materialized, retention, - req, + owner, session, sessionName, }); @@ -132,9 +138,11 @@ 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, + owner.tenantId, + owner.leaseId, + ).catch(() => {}); } return { ok: false, error: normalizeError(error) }; } finally { @@ -152,7 +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); + 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) }; @@ -212,7 +221,7 @@ function resolveRetention(req: DaemonRequest): Retention { async function retainIfRequested(params: { artifact: MaterializedAppSource; retention: Retention; - req: DaemonRequest; + owner: Pick; session: SessionState | undefined; sessionName: string; }): Promise { @@ -220,7 +229,8 @@ async function retainIfRequested(params: { return await retainMaterializedPaths({ archivePath: params.artifact.archivePath, installablePath: params.artifact.installablePath, - tenantId: params.req.meta?.tenantId, + 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 b040b3ce0ec..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; @@ -36,7 +37,10 @@ function requireInstallSource(req: DaemonRequest): DaemonInstallSource { } } -export function resolveInstallSource(req: DaemonRequest): { +export function resolveInstallSource( + req: DaemonRequest, + owner: Pick = { tenantId: req.meta?.tenantId }, +): { source: DaemonInstallSource; cleanup: () => void; } { @@ -48,7 +52,7 @@ export function resolveInstallSource(req: DaemonRequest): { return { source: { kind: 'path', - path: prepareUploadedArtifact(uploadedArtifactId, req.meta?.tenantId), + path: prepareUploadedArtifact(uploadedArtifactId, owner.tenantId, owner.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..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, @@ -25,6 +30,7 @@ type RetainedEntry = { installablePath: string; archivePath?: string; tenantId?: string; + leaseId?: string; sessionName?: string; expiresAt: number; timer: ReturnType; @@ -58,6 +64,7 @@ export async function retainMaterializedPaths(params: { installablePath: string; archivePath?: string; tenantId?: string; + leaseId?: string; sessionName?: string; ttlMs?: number; }): Promise { @@ -71,6 +78,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(() => { @@ -81,6 +89,7 @@ export async function retainMaterializedPaths(params: { installablePath: retainedInstallablePath, archivePath: retainedArchivePath, tenantId: params.tenantId, + leaseId, sessionName: params.sessionName, expiresAt, timer, @@ -117,6 +126,7 @@ export function resolveMaterializedPathRetentionMs( export async function cleanupRetainedMaterializedPaths( materializationId: string, tenantId?: string, + leaseId?: string, ): Promise { const entry = requireTenantOwnedEntry( retainedPaths(), @@ -124,9 +134,20 @@ export async function cleanupRetainedMaterializedPaths( tenantId, MATERIALIZED_PATHS_RESOURCE, ); + if (entry.leaseId !== (await canonicalLeaseId(leaseId))) { + throw new AppError('UNAUTHORIZED', 'Materialized paths belong to a different lease', { + reason: MATERIALIZED_PATH_REASONS.leaseMismatch.reason, + }); + } 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 { 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/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/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/__tests__/upload-client-lease-headers.test.ts b/packages/remote/src/__tests__/upload-client-lease-headers.test.ts new file mode 100644 index 00000000000..bc740addcba --- /dev/null +++ b/packages/remote/src/__tests__/upload-client-lease-headers.test.ts @@ -0,0 +1,85 @@ +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, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +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'; + +const DIRECT_ROUTES = ['POST /upload/preflight', 'PUT /upload/t', 'POST /upload/finalize']; + +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' }, +] as const; + +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()}-`); + 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], + req.headers[DAEMON_HTTP_TENANT_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, + 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); + } + } 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 0b57ce1fdb3..bc3d805bcd5 100644 --- a/packages/remote/src/__tests__/upload-client.test.ts +++ b/packages/remote/src/__tests__/upload-client.test.ts @@ -11,7 +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 } from '@agent-device/contracts/daemon-http'; const TEST_TOKEN = 'agent-device-upload-test-token'; const tempDirs: string[] = []; @@ -897,44 +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]); - 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, - }); - const expected = routes.map((route) => [route, route === unleased ? undefined : leaseId]); - 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/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) => { diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 8d6d546aed8..9c48df82e9a 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, @@ -202,7 +203,7 @@ async function prepareRemoteInstallPackage( baseUrl: info.baseUrl!, token: info.token, platform: req.flags?.platform, - leaseId: leaseScopeFromRequest(req).leaseId, + ...leaseScopeFromRequest(req), onProgress, signal, }); @@ -307,7 +308,7 @@ async function prepareRemoteInstallSource( baseUrl: info.baseUrl!, token: info.token, platform: req.flags?.platform, - leaseId: leaseScopeFromRequest(req).leaseId, + ...leaseScopeFromRequest(req), onProgress, signal, }); @@ -599,11 +600,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/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index fe6801f52ce..6eae6848499 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -4,6 +4,8 @@ import { AppError } from '@agent-device/kernel/errors'; import { buildDaemonHttpAuthHeaders, buildDaemonHttpLeaseHeaders, + buildDaemonHttpRunHeaders, + buildDaemonHttpTenantHeaders, } from '@agent-device/contracts/daemon-http'; import { prepareUploadArtifact, type PreparedUploadArtifact } from './upload-client-artifact.ts'; import { @@ -31,6 +33,8 @@ type UploadArtifactOptions = { env: Readonly; /** The lease this upload is for; every request to the daemon names it in a header. */ leaseId?: string; + runId?: string; + tenantId?: string; onProgress?: UploadProgressSink; /** * Ends the upload when the thing it is uploading for stops being worth finishing — today, a beat @@ -90,6 +94,8 @@ async function uploadArtifactWithinBudget( normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, + tenantId: options.tenantId, artifact: prepared, uploadAttemptId, env: options.env, @@ -104,6 +110,8 @@ async function uploadArtifactWithinBudget( normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, + tenantId: options.tenantId, artifact: prepared, preflight, uploadAttemptId, @@ -122,6 +130,8 @@ async function uploadArtifactWithinBudget( normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, + tenantId: options.tenantId, artifact: prepared, onProgress: options.onProgress, signal: options.signal, @@ -132,6 +142,8 @@ async function uploadArtifactWithinBudget( normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, + tenantId: options.tenantId, artifact: prepared, onProgress: options.onProgress, signal: options.signal, @@ -145,6 +157,8 @@ async function tryDirectUploadWithResume(options: { normalizedBase: string; token: string; leaseId?: string; + runId?: string; + tenantId?: string; artifact: PreparedUploadArtifact; preflight: Extract; uploadAttemptId: string; @@ -160,6 +174,8 @@ async function tryDirectUploadWithResume(options: { normalizedBase: options.normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, + tenantId: options.tenantId, uploadId: preflight.uploadId, signal: options.signal, }); @@ -190,6 +206,8 @@ async function retryDirectUpload( normalizedBase: string; token: string; leaseId?: string; + runId?: string; + tenantId?: string; artifact: PreparedUploadArtifact; uploadAttemptId: string; env: HostEnvironment['env']; @@ -204,6 +222,8 @@ async function retryDirectUpload( normalizedBase: options.normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, + tenantId: options.tenantId, artifact: options.artifact, uploadAttemptId: options.uploadAttemptId, env: options.env, @@ -233,11 +253,13 @@ async function uploadLegacyArtifact(options: { normalizedBase: string; 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 = { @@ -248,7 +270,7 @@ async function uploadLegacyArtifact(options: { 'x-artifact-hash-algorithm': ARTIFACT_HASH_ALGORITHM, 'transfer-encoding': 'chunked', }; - Object.assign(headers, buildDaemonHttpAuthHeaders(token), buildDaemonHttpLeaseHeaders(leaseId)); + Object.assign(headers, buildDaemonHttpAuthHeaders(token), uploadScopeHeaders(options)); const response = await streamFileToHttpRequest({ url: uploadUrl, @@ -277,24 +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), - ); + const headers = uploadControlHeaders(options); const result = await requestUploadControl( preflightUrl, @@ -402,6 +437,8 @@ async function uploadDirectArtifact( options: { normalizedBase: string; leaseId?: string; + runId?: string; + tenantId?: string; artifact: PreparedUploadArtifact; onProgress?: UploadProgressSink; signal: AbortSignal; @@ -417,7 +454,10 @@ 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, + ...uploadScopeHeaders(options), + } : ticket.headers, payloadPath: artifact.payloadPath, errorMessage: 'Failed to upload artifact with direct upload ticket', @@ -442,18 +482,13 @@ async function finalizeDirectUpload(options: { normalizedBase: string; 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), - ); + const headers = uploadControlHeaders(options); const result = await requestUploadControl( finalizeUrl, diff --git a/src/__tests__/cli-run-transport.test.ts b/src/__tests__/cli-run-transport.test.ts index 3f143f05068..ffe281ee83e 100644 --- a/src/__tests__/cli-run-transport.test.ts +++ b/src/__tests__/cli-run-transport.test.ts @@ -19,6 +19,212 @@ afterEach(() => { class ProcessExit extends Error {} +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, + JSON.stringify({ leaseId: 'b'.repeat(32), runId: 'current-run' }), + ); + const now = new Date().toISOString(); + writeRemoteConnectionState({ + stateDir, + state: { + version: 1, + 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', + connectedAt: now, + updatedAt: now, + }, + }); + const sent: Array> = []; + const transportForHost = () => async (request: Omit) => { + sent.push(request); + return { + ok: true, + data: { source: 'daemon', status: 'ready', artifacts: [] }, + } satisfies DaemonResponse; + }; + 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); + 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', + session, + '--tenant', + 'tenant', + '--json', + ]; + 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( + [ + ...owningRunArgs, + '--provider', + 'browserstack', + '--provider-session', + 'historical-provider-session', + ], + deps, + host, + ); + await runCli( + [ + ...owningRunArgs, + 'historical-provider-session', + '--provider', + '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) => ({ + command: request.command, + daemonBaseUrl: request.flags?.daemonBaseUrl, + tenantId: request.meta?.tenantId, + runId: request.meta?.runId, + leaseId: request.meta?.leaseId, + provider: request.meta?.leaseProvider, + 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', + tenantId: 'tenant', + runId: 'owning-run', + leaseId: owningLeaseId, + provider: undefined, + providerSessionId: undefined, + }, + { + 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: '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', + }, + ], + ); +}); + 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/src/cli-command-dispatch.test.ts b/src/cli-command-dispatch.test.ts index 1900a3ad62c..7121accbf5e 100644 --- a/src/cli-command-dispatch.test.ts +++ b/src/cli-command-dispatch.test.ts @@ -5,36 +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(), [ - '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(); diff --git a/src/cli.ts b/src/cli.ts index 5196f84b882..8ca2e765e10 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'; @@ -282,11 +283,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`); @@ -363,6 +364,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 +430,6 @@ async function resolveRunContextOrExit( session: flags.session, remoteConfig: flags.remoteConfig, }); - const effectiveFlags = connectionDefaults - ? mergeConnectionFlags(flags, connectionDefaults.flags, explicitFlagKeys) - : flags; return { ...base, binding, @@ -439,9 +438,12 @@ async function resolveRunContextOrExit( sessionName, connectionDefaults, explicitFlagKeys, - effectiveFlags, - resolvedRuntime: connectionDefaults?.runtime, - connectionMetadata: connectionDefaults?.connection, + ...resolveConnectionRunScope( + parsed.artifactQuery, + flags, + connectionDefaults, + explicitFlagKeys, + ), parsedBatchSteps: undefined, devicePin: parsed.devicePin, }; @@ -494,7 +496,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 @@ -852,18 +858,61 @@ function hasExplicitRemoteScopeFlags(explicitFlagKeys: Set): boolean { ); } -function mergeConnectionFlags( +function resolveConnectionRunScope( + artifactQuery: ReturnType['artifactQuery'], 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 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 (artifactQuery) { + applyArtifactRunScope(artifactQuery, effectiveFlags, defaults, explicitFlagKeys); + } + const sessionDefaults = artifactQuery ? undefined : defaults; + return { + explicitArtifactQuery: Boolean(artifactQuery), + effectiveFlags, + resolvedRuntime: sessionDefaults?.runtime, + connectionMetadata: sessionDefaults?.connection, + }; +} + +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; + } } - return merged; } function hasExplicitMetroRuntimeOverrides(explicitFlagKeys: Set): boolean { 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 dd3ae441c96..627e02964cf 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -635,7 +635,9 @@ 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. + 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. 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/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/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(); } diff --git a/test/wire-compat/closure-policy.ts b/test/wire-compat/closure-policy.ts index adcd87b5439..5e1e069ed8e 100644 --- a/test/wire-compat/closure-policy.ts +++ b/test/wire-compat/closure-policy.ts @@ -35,6 +35,8 @@ const WIRE_EXTERNAL_MODULES: Readonly> = { * 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..97279ea2497 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -1,12 +1,14 @@ { - "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_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", @@ -16,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", @@ -78,8 +80,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 +103,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", @@ -126,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", @@ -139,10 +141,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 +153,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 +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:ca3fa667ab2a60fb8af095bddeacb4875dcd2d12db783585a0fb045db35da212", + "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:3080e4ac4e0d6f46345a3588a88c81152ac74628dd6c03328161188d383a97ff", + "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: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: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", @@ -243,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", @@ -256,7 +258,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 +318,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 +473,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,21 +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/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", - "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", @@ -601,36 +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/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", - "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/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/client-api.md b/website/docs/docs/client-api.md index e007922daf4..92c27ac2adb 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: '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 552560b1298..1d91e75c4f4 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2375,12 +2375,14 @@ 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. - `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. @@ -2760,11 +2762,13 @@ agent-device session list --json List daemon or cloud provider session artifacts. ```bash -agent-device artifacts [provider-session-id] [--provider ] +agent-device artifacts [provider-session-id] [--provider ] [--lease-id ] [--run-id ] ``` | Option | What it does | | --- | --- | +| `--run-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 | @@ -2773,12 +2777,15 @@ 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 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`. ## MCP server diff --git a/website/docs/docs/device-clouds.md b/website/docs/docs/device-clouds.md index 70be22c9cfb..871aca1640c 100644 --- a/website/docs/docs/device-clouds.md +++ b/website/docs/docs/device-clouds.md @@ -60,10 +60,15 @@ 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. 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: ```bash -agent-device artifacts --provider --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. diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index de5c147e0e8..c21bf4be170 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -579,6 +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 tenant and lease registry. | ### Artifact extraction @@ -656,6 +657,8 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `RESOURCE_EXPIRED` | The artifact, upload, or path id expired or never existed; the daemon cannot tell which. | +| `ARTIFACT_LEASE_MISMATCH` | The artifact belongs to another lease of the same tenant. | +| `MATERIALIZED_PATH_LEASE_MISMATCH` | Retained output belongs to another lease of the same tenant. | ### Daemon runtime @@ -821,10 +824,14 @@ These reasons can come from more than one command. | `DEVICE_LEASE_BUSY` | Another lease, or this tenant run, already holds the device; retry after that lease is released or expires. | | `LEASE_ID_IN_USE` | The requested lease id already names a lease that this daemon issued. | | `LEASE_CAPACITY_EXCEEDED` | Every iOS simulator lease slot is taken; retry after another lease is released. | +| `RETAINED_ARTIFACT_LEASE_NOT_OWNED` | The requested retained artifact lease belongs to another tenant or run. | | `MACOS_APP_LEASE_DENIED` | A `macos-app` lease does not cover this request; `details.rule` names the limit. | | `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_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. | | `LEASE_SESSION_MISMATCH` | The lease scope of the request differs from the lease of its session; `details.field` names the field. | @@ -1071,6 +1078,8 @@ These reasons can come from more than one command. | `UPLOAD_ROLLBACK_FAILED` | A failed chunk could not be rolled back, so the upload ticket was invalidated; start a new upload. | | `UPLOAD_FINALIZE_CLEANUP_FAILED` | Finalizing the upload failed, and removing its staged files failed too; `details.originalError` holds the first failure. | | `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 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. |