From 2581250813e80c5ff080d31fb74e14366c405442 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 18:59:51 +0100 Subject: [PATCH 1/3] fix(daemon): unify admitted output and transfer ownership --- .../src/management/artifacts.ts | 6 +- packages/contracts/src/daemon-http.ts | 24 +- ...lient-checked-rpc-connect-recovery.test.ts | 6 +- .../daemon-client-checked-rpc.test.ts | 4 +- ...mon-client-transport-health-compat.test.ts | 17 +- .../support/human-control-router-fixture.ts | 1 - .../src/core/__tests__/daemon-policy.test.ts | 2 +- .../__tests__/request-ended-leases.test.ts | 1 - .../request-runtime-binding-router.test.ts | 1 - .../core/__tests__/tenant-owned-entry.test.ts | 5 +- .../src/core/capture-output-ownership.ts | 66 --- packages/daemon/src/core/daemon-request.ts | 3 + .../session-script-publication-capability.ts | 66 ++- packages/daemon/src/core/session-state.ts | 3 +- packages/daemon/src/core/session-store.ts | 1 + .../daemon/src/core/tenant-owned-entry.ts | 4 +- .../execution/__tests__/back-runtime.test.ts | 1 - .../execution/__tests__/focus-runtime.test.ts | 1 - .../__tests__/orientation-runtime.test.ts | 1 - .../__tests__/system-button-runtime.test.ts | 1 - .../__tests__/tv-remote-runtime.test.ts | 1 - .../__tests__/viewport-runtime.test.ts | 1 - .../request-dispatch-disclosure.test.ts | 2 +- .../sparse-fallback-screenshot.test.ts | 34 +- .../execution/sparse-fallback-screenshot.ts | 28 +- .../src/resources/artifact-tracking.test.ts | 6 +- .../daemon/src/resources/artifact-tracking.ts | 137 ++++++- .../daemon/src/resources/lease-registry.ts | 7 +- .../resources/provider-session-ownership.ts | 29 +- .../http-server-rpc-validation.test.ts | 19 +- ...equest-execution-scope-observation.test.ts | 2 - .../__tests__/request-execution-scope.test.ts | 4 - .../__tests__/request-finalization.test.ts | 382 +----------------- ...router-android-foreground-evidence.test.ts | 1 - .../request-router-android-modal.test.ts | 2 +- ...est-router-android-snapshot-helper.test.ts | 1 - .../request-router-app-device-batches.test.ts | 1 - .../request-router-apps-admission.test.ts | 1 - .../request-router-artifacts-web.test.ts | 1 - ...uest-router-bounded-claim-recovery.test.ts | 1 - .../request-router-coordinate-unit.test.ts | 2 +- .../__tests__/request-router-cost.test.ts | 2 +- ...request-router-custom-action-flags.test.ts | 1 - .../request-router-developer-dir.test.ts | 1 - .../request-router-device-spec-gate.test.ts | 2 +- .../request-router-error-redaction.test.ts | 2 +- .../__tests__/request-router-events.test.ts | 7 - .../request-router-fill-text-stdin.test.ts | 1 - .../request-router-idle-expired.test.ts | 1 - ...est-router-install-source-deadline.test.ts | 2 +- .../request-router-lock-policy.test.ts | 9 - .../request-router-macos-app-lease.test.ts | 2 - .../request-router-named-session.test.ts | 1 - ...equest-router-nested-session-lease.test.ts | 1 - ...request-router-open-claim-recovery.test.ts | 1 - .../request-router-open-claim.test.ts | 1 - .../__tests__/request-router-open.test.ts | 2 +- ...equest-router-provider-credentials.test.ts | 1 - .../request-router-record-flags.test.ts | 1 - ...uest-router-record-only-retirement.test.ts | 1 - ...request-router-record-runtime-lock.test.ts | 1 - .../request-router-recording-health.test.ts | 6 +- ...uest-router-remote-maestro-capture.test.ts | 1 - .../request-router-repair-expired.test.ts | 1 - .../request-router-replay-env.test.ts | 1 - .../request-router-replay-plugin.test.ts | 1 - .../request-router-replay-scope.test.ts | 6 - .../request-router-response-level.test.ts | 2 +- .../request-router-screenshot.test.ts | 3 - .../request-router-selection.test.ts | 1 - .../request-router-session-address.test.ts | 1 - .../request-router-typed-error.test.ts | 1 - .../request-router-web-sessions.test.ts | 78 +++- .../request-save-script-policy.test.ts | 1 - .../request-save-script-transports.test.ts | 1 - .../server/__tests__/resumable-upload.test.ts | 335 +++++++++++++-- .../__tests__/upload-http-capacity.test.ts | 190 +++++++++ .../daemon/src/server/artifact-archive.ts | 4 + .../daemon/src/server/artifact-download.ts | 5 +- packages/daemon/src/server/http-errors.ts | 4 +- .../daemon/src/server/http/daemon-runtime.ts | 11 +- .../src/server/http/http-rpc-methods.ts | 29 +- .../http-server-batch-maestro-trust.test.ts | 1 - .../http-server-capture-publication.test.ts | 7 - .../http/http-server-capture-tenant.test.ts | 3 - .../http-server-install-retention.test.ts | 11 +- .../http/http-server-perf-report.test.ts | 1 - .../http-server-provider-scenarios.test.ts | 21 +- .../http-server-proxy-leased-output.test.ts | 2 - ...http-server-proxy-reply-visibility.test.ts | 1 - .../http/http-server-proxy-rollback.test.ts | 6 +- .../http-server-proxy-session-lease.test.ts | 1 - .../http/http-server-remote-output.test.ts | 36 +- .../http/http-server-remote-suite.test.ts | 6 +- .../http/http-server-resumable-upload.test.ts | 7 +- .../http-server-rpc-ingress-budget.test.ts | 280 +++++++++++++ ...ttp-server-session-lease-touch.fixtures.ts | 2 +- .../daemon/src/server/http/http-server.ts | 221 ++++++++-- .../src/server/remote-host-input-policy.ts | 20 + .../src/server/request-execution-scope.ts | 16 +- .../daemon/src/server/request-finalization.ts | 140 +------ packages/daemon/src/server/request-router.ts | 14 +- .../daemon/src/server/resumable-upload.ts | 151 +++---- .../src/server/upload-authority.test.ts | 165 ++++++++ .../daemon/src/server/upload-authority.ts | 120 ++++++ packages/daemon/src/server/upload-capacity.ts | 83 ++++ packages/daemon/src/server/upload-http.ts | 77 ++-- packages/daemon/src/server/upload.ts | 51 ++- .../install-source-resolution.test.ts | 16 +- .../__tests__/lease-lifecycle.test.ts | 17 + .../materialized-path-registry.test.ts | 35 +- .../replay-runtime/application.test.ts | 1 + .../session-test-command-trust.test.ts | 1 + .../session-test-suite-command-video.test.ts | 1 + .../request-recording-health.test.ts | 1 - ...shot-custom-actions-platform-guard.test.ts | 1 - .../__tests__/lease-artifacts.test.ts | 13 + .../__tests__/session-reinstall.test.ts | 24 +- .../__tests__/session-replay-command.test.ts | 20 +- .../daemon/src/sessions/handlers/lease.ts | 13 +- .../src/sessions/handlers/record-runtime.ts | 14 +- .../handlers/session-app-deployment.ts | 3 +- .../handlers/session-app-source-deployment.ts | 14 +- .../handlers/session-replay-command.ts | 8 + .../src/sessions/handlers/trace-runtime.ts | 68 ++-- .../src/sessions/install-source-resolution.ts | 8 +- .../daemon/src/sessions/lease-lifecycle.ts | 21 +- .../sessions/materialized-path-registry.ts | 20 +- .../session-devices-batch-runtime.test.ts | 7 +- .../internal/session-perf-runtime.ts | 230 ++++++++--- packages/host-kit/src/archive.ts | 5 +- .../src/internal/byte-limit-stream.ts | 7 + .../src/daemon-proxy-cancellation.test.ts | 199 +++++++++ packages/proxy/src/daemon-proxy.ts | 192 +++++---- packages/proxy/src/node-http.test.ts | 67 +++ packages/proxy/src/node-http.ts | 11 +- packages/proxy/src/rpc-body-budget.ts | 68 ++++ packages/proxy/src/rpc-refusals.ts | 60 +++ .../__tests__/upload-client-capacity.test.ts | 237 +++++++++++ .../upload-client-lease-headers.test.ts | 85 ++++ packages/remote/src/daemon-artifacts.ts | 6 + packages/remote/src/upload-client.ts | 201 ++++++--- .../__tests__/script-source.test.ts | 99 ++++- .../test-command-remote-artifacts.test.ts | 11 +- .../src/daemon-port/command-types.ts | 3 +- .../src/daemon-port/script-source.ts | 94 ++++- .../test-command-flag-policy.test.ts | 1 + .../src/daemon-port/test-command.ts | 6 +- src/__tests__/cli-run-transport.test.ts | 206 ++++++++++ src/cli.ts | 18 +- src/cli/connection/command-connection.ts | 31 ++ src/cli/resolve-cli-options.ts | 10 +- src/commands/schema/cli-help.ts | 2 +- src/daemon-entrypoint.test.ts | 4 +- test/wire-compat/ledger.json | 119 ++---- test/wire-compat/surface.ts | 8 + test/wire-compat/wire-mutations.test.ts | 2 +- website/docs/docs/error-reasons.md | 17 + website/docs/docs/remote-proxy.md | 12 +- 159 files changed, 3922 insertions(+), 1436 deletions(-) create mode 100644 packages/daemon/src/server/__tests__/upload-http-capacity.test.ts create mode 100644 packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts create mode 100644 packages/daemon/src/server/upload-authority.test.ts create mode 100644 packages/daemon/src/server/upload-authority.ts create mode 100644 packages/daemon/src/server/upload-capacity.ts create mode 100644 packages/proxy/src/rpc-body-budget.ts create mode 100644 packages/proxy/src/rpc-refusals.ts create mode 100644 packages/remote/src/__tests__/upload-client-capacity.test.ts create mode 100644 packages/remote/src/__tests__/upload-client-lease-headers.test.ts diff --git a/packages/command-surface/src/management/artifacts.ts b/packages/command-surface/src/management/artifacts.ts index 52844a60b05..eb287ccedcc 100644 --- a/packages/command-surface/src/management/artifacts.ts +++ b/packages/command-surface/src/management/artifacts.ts @@ -8,12 +8,14 @@ import { defineFieldCommandMetadata } from '../field-command-contract.ts'; const artifactsCommandMetadata = defineFieldCommandMetadata( 'artifacts', - 'List daemon or cloud provider artifacts for an active or completed session.', + 'List artifacts for the authenticated tenant and producing lease, including retained output after close.', { provider: stringField( 'Cloud provider name, for example browserstack, aws-device-farm, or testmu.', ), - providerSessionId: stringField('Cloud provider session id or ARN.'), + providerSessionId: stringField( + 'Cloud provider session id or ARN. Send the original producing lease scope.', + ), }, ); diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index a1eb9a90ac9..bbfe84b71da 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -10,9 +10,15 @@ 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'; +/** Why an upload is refused before its staging directory is created. */ +export const UPLOAD_CAPACITY_REASONS = { + // A new upload would exceed the active upload count or reserved byte budget. + exceeded: { reason: 'UPLOAD_CAPACITY_EXCEEDED' }, +} as const satisfies ReasonTable<'uploads'>; +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 +126,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 @@ -134,6 +146,10 @@ export const DAEMON_RPC_PROTOCOL_VERSION = 3; * worst-case escaping. It also bounds the memory one unauthenticated connection can hold. */ export const DAEMON_REQUEST_MAX_BYTES = 64 * 1024 * 1024; +/** Time for receiving and authenticating an RPC before command execution begins. */ +export const DAEMON_RPC_PREAUTH_TIMEOUT_MS = 5_000; +/** Maximum string ID length echoed in an RPC preauthorization timeout. */ +export const DAEMON_RPC_PREAUTH_MAX_ID_LENGTH = 128; export const DAEMON_HTTP_INSTANCE_HEADER = 'x-agent-device-instance'; export const DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER = 'x-agent-device-upstream-instance'; @@ -352,3 +368,5 @@ function dottedExtension(extension: string): string { function remoteTempArtifactStem(prefix: string): string { return `agent-device-${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; } + +export const DAEMON_HTTP_UPLOAD_SESSION_HEADER = 'x-agent-device-session'; 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 528b95f3a67..d227f4f0e40 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 391883524ca..e9a1dd29df6 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' } : {}), }), ); @@ -536,7 +536,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/src/__tests__/support/human-control-router-fixture.ts b/packages/daemon/src/__tests__/support/human-control-router-fixture.ts index 499a22d42f3..63bde3485e4 100644 --- a/packages/daemon/src/__tests__/support/human-control-router-fixture.ts +++ b/packages/daemon/src/__tests__/support/human-control-router-fixture.ts @@ -43,7 +43,6 @@ export function createHumanControlHarness() { deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, androidObservation: clearAndroidObservationFixture, platformResourceCleanup: platformResourceCleanupFixture(), - trackDownloadableArtifact: () => 'artifact-1', }); return { registry, lease, sessionStore, sessionName, handleRequest }; } diff --git a/packages/daemon/src/core/__tests__/daemon-policy.test.ts b/packages/daemon/src/core/__tests__/daemon-policy.test.ts index b081de86440..4f5acf0c1d7 100644 --- a/packages/daemon/src/core/__tests__/daemon-policy.test.ts +++ b/packages/daemon/src/core/__tests__/daemon-policy.test.ts @@ -88,7 +88,7 @@ function makeHandler( } : undefined, }), - trackDownloadableArtifact: () => 'artifact-id', + hostDiagnostics: hostDiagnosticsFixture(), daemonPolicy, }); diff --git a/packages/daemon/src/core/__tests__/request-ended-leases.test.ts b/packages/daemon/src/core/__tests__/request-ended-leases.test.ts index 98962073deb..6cdd78ad27d 100644 --- a/packages/daemon/src/core/__tests__/request-ended-leases.test.ts +++ b/packages/daemon/src/core/__tests__/request-ended-leases.test.ts @@ -58,7 +58,6 @@ function leasedDaemon() { leaseRegistry, deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, - trackDownloadableArtifact: () => 'artifact-id', }); return { root, diff --git a/packages/daemon/src/core/__tests__/request-runtime-binding-router.test.ts b/packages/daemon/src/core/__tests__/request-runtime-binding-router.test.ts index d281803aac7..ea5e7977b34 100644 --- a/packages/daemon/src/core/__tests__/request-runtime-binding-router.test.ts +++ b/packages/daemon/src/core/__tests__/request-runtime-binding-router.test.ts @@ -153,7 +153,6 @@ function makeHandler(gateway: DeviceRuntimeGateway) { leaseRegistry, deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: gateway, - trackDownloadableArtifact: () => 'artifact', }), }; } diff --git a/packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts b/packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts index fbc7ee2017d..d8b3082050a 100644 --- a/packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts +++ b/packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts @@ -28,7 +28,10 @@ test('requireTenantOwnedEntry returns entries readable by the tenant', () => { ['owned', { tenantId: 'tenant-a' }], ]); assert.equal(requireTenantOwnedEntry(map, 'shared', undefined, RESOURCE), map.get('shared')); - assert.equal(requireTenantOwnedEntry(map, 'shared', 'tenant-b', RESOURCE), map.get('shared')); + assert.throws( + () => requireTenantOwnedEntry(map, 'shared', 'tenant-b', RESOURCE), + /different tenant/, + ); assert.equal(requireTenantOwnedEntry(map, 'owned', 'tenant-a', RESOURCE), map.get('owned')); }); diff --git a/packages/daemon/src/core/capture-output-ownership.ts b/packages/daemon/src/core/capture-output-ownership.ts index 01377a1cd2f..1f57cc972b6 100644 --- a/packages/daemon/src/core/capture-output-ownership.ts +++ b/packages/daemon/src/core/capture-output-ownership.ts @@ -1,71 +1,5 @@ import type { DaemonArtifact, DaemonResponseData } from '@agent-device/kernel/contracts'; -const CAPTURE_OUTPUT_OWNERSHIP = Symbol('captureOutputOwnership'); -type CaptureOutputOwnership = 'daemon' | 'caller'; -type CaptureOutputOwner = Readonly<{ - ownership: CaptureOutputOwnership; - tenantId?: string; - /** Null records an unleased producer. Undefined leaves ownership to the request. */ - leaseVerifier?: string | null; -}>; -type CaptureOutputData = DaemonResponseData & { - [CAPTURE_OUTPUT_OWNERSHIP]?: CaptureOutputOwner; -}; - -/** Producer-owned capture facts stay private when the response is serialized. */ -export function withCaptureOutputOwnership( - data: DaemonResponseData, - ownership: CaptureOutputOwnership, - tenantId?: string, - leaseVerifier?: string | null, -): DaemonResponseData { - return { ...data, [CAPTURE_OUTPUT_OWNERSHIP]: { ownership, tenantId, leaseVerifier } }; -} - -export function captureOutputOwnership( - data: DaemonResponseData, -): CaptureOutputOwnership | undefined { - const capture: CaptureOutputData = data; - return capture[CAPTURE_OUTPUT_OWNERSHIP]?.ownership; -} - -export function captureOutputTenantId(data: DaemonResponseData): string | undefined { - const capture: CaptureOutputData = data; - return capture[CAPTURE_OUTPUT_OWNERSHIP]?.tenantId; -} - -export function captureOutputLeaseVerifier(data: DaemonResponseData): string | null | undefined { - const capture: CaptureOutputData = data; - return capture[CAPTURE_OUTPUT_OWNERSHIP]?.leaseVerifier; -} - -const DAEMON_DELIVERED_ARTIFACT = Symbol('daemonDeliveredArtifact'); -type DeliveredArtifact = DaemonArtifact & { - [DAEMON_DELIVERED_ARTIFACT]?: Readonly<{ tenantId: string | undefined }>; -}; - -/** - * Marks an artifact the daemon produced for the caller itself, such as a remote recording's script - * version. It is registered for download for `tenantId` alone, whatever the request's tenant, - * capture filters, or network marker say. The mark stays private when the response is serialized. - */ -export function asDaemonDeliveredArtifact( - artifact: DaemonArtifact, - tenantId: string | undefined, -): DaemonArtifact { - const delivered: DeliveredArtifact = artifact; - delivered[DAEMON_DELIVERED_ARTIFACT] = { tenantId }; - return delivered; -} - -/** The delivery of a daemon-delivered artifact, or `undefined` for any other artifact. */ -export function daemonDeliveredArtifact( - artifact: DaemonArtifact | undefined, -): Readonly<{ tenantId: string | undefined }> | undefined { - const delivered: DeliveredArtifact | undefined = artifact; - return delivered?.[DAEMON_DELIVERED_ARTIFACT]; -} - const screenshotDeliveryPaths = new WeakMap(); /** Keep delivery metadata on the artifact that response views carry to the HTTP reply. */ diff --git a/packages/daemon/src/core/daemon-request.ts b/packages/daemon/src/core/daemon-request.ts index ae5e34f4608..7b816b3b629 100644 --- a/packages/daemon/src/core/daemon-request.ts +++ b/packages/daemon/src/core/daemon-request.ts @@ -1,3 +1,4 @@ +import type { ArtifactOwner } from '../resources/artifact-tracking.ts'; import type { ExecutionPlan } from './execution-plan.ts'; import type { PreresolvedInteractionTarget } from '@agent-device/contracts/interaction'; import type { DeviceLease } from '@agent-device/contracts/device'; @@ -50,6 +51,8 @@ type DaemonRequestInternal = ReplayDispatchOptions & { */ retainDeviceExecutionLock?: (deviceId: string) => Promise; admittedLease?: DeviceLease; + admittedArtifactScope?: { principal: 'local' | 'declared' | 'attested'; owner: ArtifactOwner }; + principal?: 'local' | 'declared' | 'attested'; sessionAuthorityActive?: () => boolean; snapshotObservation?: Readonly<{ device: DeviceInfo; diff --git a/packages/daemon/src/core/session-script-publication-capability.ts b/packages/daemon/src/core/session-script-publication-capability.ts index 7dc5e3dbe91..6f8346abee6 100644 --- a/packages/daemon/src/core/session-script-publication-capability.ts +++ b/packages/daemon/src/core/session-script-publication-capability.ts @@ -7,7 +7,11 @@ import type { } from '@agent-device/kernel/contracts'; import { readResponseWarnings } from '@agent-device/kernel/success-text'; import type { AuthorizedSession } from './session-store.ts'; -import { asDaemonDeliveredArtifact } from './capture-output-ownership.ts'; +import { + leaseVerifier, + commitProducedOutput, + type ArtifactOwner, +} from '../resources/artifact-tracking.ts'; import type { SessionState } from './session-state.ts'; import { NO_SCRIPT_PUBLICATION, @@ -230,6 +234,7 @@ type RemoteScriptVersion = export type RemoteCloseScript = Readonly<{ delivery: RemoteScriptDelivery; version?: RemoteScriptVersion; + owner: ArtifactOwner; }>; /** Numbers the next version of a remote recording, so the caller keeps the newest one. */ @@ -252,6 +257,7 @@ function withRemoteScriptVersion( response: DaemonResponse, delivery: RemoteScriptDelivery, version: RemoteScriptVersion, + owner: ArtifactOwner, ): DaemonResponse { if (!response.ok) return response; const { publicationId } = delivery; @@ -271,16 +277,19 @@ function withRemoteScriptVersion( }, }; } - const artifact = asDaemonDeliveredArtifact( + const artifact = commitProducedOutput( { - field: 'savedScript', + artifactPath: version.path, artifactType: 'session-script', - path: version.path, + fileName: path.basename(version.path), + }, + owner, + { + field: 'savedScript', fileName: path.basename(version.path), scriptPublicationId: publicationId, scriptRevision: delivery.revision, }, - delivery.tenantId, ); const artifacts = Array.isArray(data.artifacts) ? data.artifacts : []; return { ok: true, data: { ...data, artifacts: [...artifacts, artifact] } }; @@ -305,16 +314,26 @@ export function remoteScriptVersionDelivery( const result = authorized.writeScriptVersion(); if (result.written) { const stamped = stampNextRevision(ref.session) ?? delivery; - return withRemoteScriptVersion(response, stamped, { path: result.path }); + return withRemoteScriptVersion( + response, + stamped, + { path: result.path }, + scriptProducer(ref.session, delivery), + ); } if (!result.error) return response; // The daemon diagnostic keeps the cause; its daemon-host path stays out of the response. - return withRemoteScriptVersion(response, delivery, { - failure: { - message: 'The action succeeded, but the daemon could not write the remote recording.', - hint: 'The --save-script file keeps the previous version. The next recorded action or close delivers the full recording again.', + return withRemoteScriptVersion( + response, + delivery, + { + failure: { + message: 'The action succeeded, but the daemon could not write the remote recording.', + hint: 'The --save-script file keeps the previous version. The next recorded action or close delivers the full recording again.', + }, }, - }); + scriptProducer(ref.session, delivery), + ); }; } @@ -333,11 +352,19 @@ export function remoteCloseScript( if (writeFailed) { const message = 'The session was closed, but the daemon could not write its final script.'; const hint = 'The --save-script file keeps the version from the last recorded action.'; - return { delivery, version: { failure: { message, hint } } }; + return { + delivery, + owner: scriptProducer(session, delivery), + version: { failure: { message, hint } }, + }; } const writtenPath = state.status === 'published' ? scriptTargetPath(state) : undefined; - if (!writtenPath) return { delivery }; - return { delivery: stampNextRevision(session) ?? delivery, version: { path: writtenPath } }; + if (!writtenPath) return { delivery, owner: scriptProducer(session, delivery) }; + return { + delivery: stampNextRevision(session) ?? delivery, + owner: scriptProducer(session, delivery), + version: { path: writtenPath }, + }; } /** @@ -354,5 +381,14 @@ export function remoteCloseScriptDelivery( ok: true, data: { ...response.data, scriptPublicationId: close.delivery.publicationId }, }; - return close.version ? withRemoteScriptVersion(named, close.delivery, close.version) : named; + return close.version + ? withRemoteScriptVersion(named, close.delivery, close.version, close.owner) + : named; +} + +function scriptProducer(session: SessionState, delivery: RemoteScriptDelivery): ArtifactOwner { + return { + tenantId: delivery.tenantId, + leaseVerifier: session.lease ? leaseVerifier(session.lease.leaseId) : null, + }; } diff --git a/packages/daemon/src/core/session-state.ts b/packages/daemon/src/core/session-state.ts index 16e3cd8e0e0..c7b4ae79469 100644 --- a/packages/daemon/src/core/session-state.ts +++ b/packages/daemon/src/core/session-state.ts @@ -1,3 +1,4 @@ +import type { reserveFileOutput } from '../resources/artifact-tracking.ts'; import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; import type { SnapshotDiagnosticsState } from '@agent-device/contracts/capture'; import type { AppLogFailure, AppLogLiveHandle } from '@agent-device/contracts/app-log-runtime'; @@ -242,8 +243,8 @@ export type SessionState = { snapshotDiagnostics?: SnapshotDiagnosticsState; /** Remote traces accept request-scoped diagnostics instead of persistent runner streams. */ trace?: { + outputReservation?: ReturnType; clientOutPath?: string; - remoteCaptureTenantId?: string; leaseVerifier?: string | null; startedAt: number; } & ( diff --git a/packages/daemon/src/core/session-store.ts b/packages/daemon/src/core/session-store.ts index 75e67a17177..97374c12237 100644 --- a/packages/daemon/src/core/session-store.ts +++ b/packages/daemon/src/core/session-store.ts @@ -208,6 +208,7 @@ export class SessionStore { lease: { ...session.lease }, }); } + session.trace?.outputReservation?.discard(); this.runtimeHints.delete(ref.address); if (isSafeSessionSegment(ref.address)) { removeEmptySessionDirectory(this.resolveSessionDir(ref.address)); diff --git a/packages/daemon/src/core/tenant-owned-entry.ts b/packages/daemon/src/core/tenant-owned-entry.ts index ba615e0c965..f6d3ff4ab70 100644 --- a/packages/daemon/src/core/tenant-owned-entry.ts +++ b/packages/daemon/src/core/tenant-owned-entry.ts @@ -12,9 +12,7 @@ export function matchesTenantOwnedEntry( entry: TenantOwnedEntry, tenantId: string | undefined, ): boolean { - return entry.tenantId === null - ? tenantId === undefined - : !entry.tenantId || entry.tenantId === tenantId; + return (entry.tenantId ?? undefined) === tenantId; } export type TenantOwnedResourceKind = { diff --git a/packages/daemon/src/execution/__tests__/back-runtime.test.ts b/packages/daemon/src/execution/__tests__/back-runtime.test.ts index c8d43fb3550..67d63aa3eaa 100644 --- a/packages/daemon/src/execution/__tests__/back-runtime.test.ts +++ b/packages/daemon/src/execution/__tests__/back-runtime.test.ts @@ -156,7 +156,6 @@ test('request router joins back admission to execution, recording, and ref inval leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: harness.gateway, - trackDownloadableArtifact: () => 'artifact', }); const response = await handler({ diff --git a/packages/daemon/src/execution/__tests__/focus-runtime.test.ts b/packages/daemon/src/execution/__tests__/focus-runtime.test.ts index ee9cf85419f..d20be400db1 100644 --- a/packages/daemon/src/execution/__tests__/focus-runtime.test.ts +++ b/packages/daemon/src/execution/__tests__/focus-runtime.test.ts @@ -208,7 +208,6 @@ test('request router joins focus admission to execution, recording, and ref inva leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: harness.gateway, - trackDownloadableArtifact: () => 'artifact', }); const response = await handler({ diff --git a/packages/daemon/src/execution/__tests__/orientation-runtime.test.ts b/packages/daemon/src/execution/__tests__/orientation-runtime.test.ts index 269882eddaa..084dbeb7ce0 100644 --- a/packages/daemon/src/execution/__tests__/orientation-runtime.test.ts +++ b/packages/daemon/src/execution/__tests__/orientation-runtime.test.ts @@ -272,7 +272,6 @@ test('request router joins orientation admission to execution and ref invalidati deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: harness.gateway, androidObservation: androidObservationFixture, - trackDownloadableArtifact: () => 'artifact', }); const response = await handler({ diff --git a/packages/daemon/src/execution/__tests__/system-button-runtime.test.ts b/packages/daemon/src/execution/__tests__/system-button-runtime.test.ts index d4343d7bfe3..1139b1d86f0 100644 --- a/packages/daemon/src/execution/__tests__/system-button-runtime.test.ts +++ b/packages/daemon/src/execution/__tests__/system-button-runtime.test.ts @@ -238,7 +238,6 @@ test('request router joins home admission to execution, recording, and ref inval leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: harness.gateway, - trackDownloadableArtifact: () => 'artifact', }); const response = await handler({ diff --git a/packages/daemon/src/execution/__tests__/tv-remote-runtime.test.ts b/packages/daemon/src/execution/__tests__/tv-remote-runtime.test.ts index fd4e9f20af2..c792c1c7aae 100644 --- a/packages/daemon/src/execution/__tests__/tv-remote-runtime.test.ts +++ b/packages/daemon/src/execution/__tests__/tv-remote-runtime.test.ts @@ -234,7 +234,6 @@ test('request router joins tv-remote admission to execution and ref invalidation leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: harness.gateway, - trackDownloadableArtifact: () => 'artifact', }); const response = await handler({ diff --git a/packages/daemon/src/execution/__tests__/viewport-runtime.test.ts b/packages/daemon/src/execution/__tests__/viewport-runtime.test.ts index d92192b6b51..3a0692af8a6 100644 --- a/packages/daemon/src/execution/__tests__/viewport-runtime.test.ts +++ b/packages/daemon/src/execution/__tests__/viewport-runtime.test.ts @@ -183,7 +183,6 @@ test('request router joins viewport admission to execution, recording, and ref i leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: harness.gateway, - trackDownloadableArtifact: () => 'artifact', }); const response = await handler({ diff --git a/packages/daemon/src/execution/request-dispatch-disclosure.test.ts b/packages/daemon/src/execution/request-dispatch-disclosure.test.ts index 6f98bd9980f..0108c66fc07 100644 --- a/packages/daemon/src/execution/request-dispatch-disclosure.test.ts +++ b/packages/daemon/src/execution/request-dispatch-disclosure.test.ts @@ -158,7 +158,7 @@ async function route( sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', + deviceRuntimeGateway: routeDeviceRuntimeGateway, androidObservation, }); diff --git a/packages/daemon/src/execution/sparse-fallback-screenshot.test.ts b/packages/daemon/src/execution/sparse-fallback-screenshot.test.ts index f26d5a82ebb..f7c7b927bfb 100644 --- a/packages/daemon/src/execution/sparse-fallback-screenshot.test.ts +++ b/packages/daemon/src/execution/sparse-fallback-screenshot.test.ts @@ -6,8 +6,10 @@ import { makeIosSession } from '../__tests__/support/session-factories.ts'; import { createLiveTestHostEnvironment, mkdtempForTest } from '@agent-device/test-kit'; import { SessionStore } from '../core/session-store.ts'; import { dispatchSnapshotViaRuntime } from '../sessions/snapshot-runtime.ts'; -import type { DownloadableArtifactRegistration } from '../resources/artifact-tracking.ts'; -import { finalizeDaemonResponse } from '../server/request-finalization.ts'; +import { + settleCommittedFileOutputs, + listDownloadableArtifacts, +} from '../resources/artifact-tracking.ts'; import { screenshotRuntimeFixture, writeSolidPng, @@ -68,7 +70,13 @@ async function dispatch( positionals: [], token: 't', session: input.sessionName, - ...(internalObservation ? { internal: { observationOnly: true } } : {}), + internal: { + admittedArtifactScope: { + principal: 'local', + owner: { tenantId: undefined, leaseVerifier: null }, + }, + ...(internalObservation ? { observationOnly: true } : {}), + }, }, sessionName: input.sessionName, logPath: input.logPath, @@ -91,7 +99,7 @@ test('a sparse snapshot captures the screenshot its own remedy asks for and link { field: 'fallbackScreenshotPath', artifactType: 'screenshot', - path: data.fallbackScreenshotPath, + artifactId: expect.any(String), fileName: 'snapshot-fallback.png', }, ]); @@ -139,21 +147,13 @@ test('the fallback screenshot reaches the artifact inventory with its display ro }); const data = await dispatch(input, runtime); - const tracked: DownloadableArtifactRegistration[] = []; - finalizeDaemonResponse( - { command: 'snapshot', positionals: [], token: 't', session: input.sessionName }, - { ok: true, data }, - (registration) => { - tracked.push(registration); - return 'artifact-id'; - }, - ); - - expect(tracked).toEqual([ + settleCommittedFileOutputs(data.artifacts, true); + const tracked = await listDownloadableArtifacts({}, process.env); + expect(tracked).toContainEqual( expect.objectContaining({ + id: data.artifacts?.[0]?.artifactId, artifactType: 'screenshot', - fileName: 'snapshot-fallback.png', displayRotation: 'landscape-left', }), - ]); + ); }); diff --git a/packages/daemon/src/execution/sparse-fallback-screenshot.ts b/packages/daemon/src/execution/sparse-fallback-screenshot.ts index 5574857df2f..8aad118a07a 100644 --- a/packages/daemon/src/execution/sparse-fallback-screenshot.ts +++ b/packages/daemon/src/execution/sparse-fallback-screenshot.ts @@ -1,3 +1,5 @@ +import { admittedArtifactOwner, commitProducedOutput } from '../resources/artifact-tracking.ts'; +import type { DaemonArtifact } from '@agent-device/kernel/contracts'; import type { DeviceRotation } from '@agent-device/contracts/device'; import type { CreateDaemonCommandSurface } from '@agent-device/contracts/daemon-command-surface'; import type { SnapshotQualityVerdict } from '@agent-device/kernel/snapshot'; @@ -13,13 +15,7 @@ import type { SessionState } from '../core/session-state.ts'; export type SparseFallbackScreenshot = { path: string; - artifact: { - field: 'fallbackScreenshotPath'; - artifactType: 'screenshot'; - path: string; - fileName: string; - displayRotation?: DeviceRotation; - }; + artifact: DaemonArtifact; }; /** @@ -52,15 +48,19 @@ export async function captureSparseFallbackScreenshot( const captured = await captureFallbackScreenshot({ ...params, session }); if (captured === undefined) return undefined; const { path, displayRotation } = captured; + const owner = admittedArtifactOwner(params.req); return { path, - artifact: { - field: 'fallbackScreenshotPath', - artifactType: 'screenshot', - path, - fileName: 'snapshot-fallback.png', - ...(displayRotation ? { displayRotation } : {}), - }, + artifact: commitProducedOutput( + { + artifactPath: path, + artifactType: 'screenshot', + fileName: 'snapshot-fallback.png', + displayRotation, + }, + owner, + { field: 'fallbackScreenshotPath', fileName: 'snapshot-fallback.png' }, + ), }; } diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index bd63521f94f..5245381cf3d 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -686,7 +686,11 @@ test('disposing a runtime removes the temporary files it still tracks', () => { artifactType: 'runtime-artifact', fileName: 'artifact.txt', }); - trackUploadedArtifact({ artifactPath: path.join(uploadDir, 'payload'), tempDir: uploadDir }); + trackUploadedArtifact({ + owner: { tenantId: undefined, leaseVerifier: null }, + artifactPath: path.join(uploadDir, 'payload'), + tempDir: uploadDir, + }); }); runtime.dispose(); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 0699d3a6117..46de891eb7f 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -83,7 +83,7 @@ export function requestHoldsOutputLease( ownerVerifier: string | undefined, presentedLeaseId: string | undefined, ): boolean { - if (ownerVerifier === undefined) return true; + if (ownerVerifier === undefined) return presentedLeaseId === undefined; return ( presentedLeaseId !== undefined && timingSafeStringEqual(leaseVerifier(presentedLeaseId), ownerVerifier) @@ -200,6 +200,7 @@ type ArtifactTrackingState = { artifacts: Map; reservations: Set<() => void>; uploads: Map; + onStagedUploadCleanupDeferred?: (tempDir: string, error: unknown, retryDelayMs: number) => void; retainedPerformanceSources: Map< string, { output: string; leaseVerifier: string | null; birthtimeMs: number } @@ -224,7 +225,7 @@ const artifactTracking = (): ArtifactTrackingState => } for (const entry of state.uploads.values()) { clearTimeout(entry.timer); - removeBestEffort(entry.tempDir); + removeStagedUpload(entry.tempDir, entry.releaseReservation); } }, ); @@ -313,18 +314,43 @@ export function reserveFileOutput( { directory, lifetimeId }, ); reservations.delete(discard); - const artifact = { ...delivery, artifactType, artifactId: id }; - committedFileOutputDeliveries.set(artifact, (delivered) => { - const entry = artifacts.get(id); - if (!entry) return; - if (delivered) entry.awaitingDelivery = false; - else requestArtifactCleanup(artifacts, id, entry); - }); - return artifact; + return commitOutputDelivery(id, { ...delivery, artifactType, artifactId: id }); }, }; } +export function commitProducedOutput( + registration: Omit, + owner: ArtifactOwner, + delivery: Omit, +): DaemonArtifact { + const artifactId = trackDownloadableArtifact({ + ...registration, + tenantId: owner.tenantId, + leaseVerifier: owner.leaseVerifier ?? undefined, + }); + return commitOutputDelivery(artifactId, { + ...delivery, + artifactType: registration.artifactType, + artifactId, + }); +} + +function commitOutputDelivery( + id: string, + artifact: DaemonArtifact & { artifactId: string }, +): DaemonArtifact & { artifactId: string } { + const artifacts = pendingArtifacts(); + artifacts.get(id)!.awaitingDelivery = true; + committedFileOutputDeliveries.set(artifact, (delivered) => { + const entry = artifacts.get(id); + if (!entry) return; + if (delivered) entry.awaitingDelivery = false; + else requestArtifactCleanup(artifacts, id, entry); + }); + return artifact; +} + type RecordingFile = DaemonArtifact & { path: string; artifactId: string; sourceIdentity: string }; /** Registers the producer's identities. A replay can only reference entries this daemon retains. */ @@ -904,8 +930,27 @@ function cleanupDirectoryArchive(entry: ArtifactEntry): void { entry.directoryArchive = undefined; } +export type ArtifactOwner = Readonly<{ + tenantId: string | undefined; + leaseVerifier: string | null; +}>; + +export function admittedArtifactOwner(req: DaemonRequest): ArtifactOwner { + const owner = req.internal?.admittedArtifactScope?.owner; + if (!owner) + throw new AppError('COMMAND_FAILED', 'Artifact operation has no admitted producer scope.'); + return owner; +} + +export function assertArtifactOwner(owner: ArtifactOwner, reader: ArtifactOwner): void { + if (owner.tenantId !== reader.tenantId || owner.leaseVerifier !== reader.leaseVerifier) { + throw leasedOutputRefusal('Artifact'); + } +} + // --- Upload artifact tracking --- +const STAGED_UPLOAD_RETRY_DELAY_MS = 30_000; const UPLOAD_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes const UPLOADED_ARTIFACT_RESOURCE: TenantOwnedResourceKind = { @@ -916,14 +961,16 @@ const UPLOADED_ARTIFACT_RESOURCE: TenantOwnedResourceKind = { type UploadEntry = { artifactPath: string; tempDir: string; - tenantId?: string; + owner: ArtifactOwner; + releaseReservation?: () => void; timer: ReturnType; }; export function trackUploadedArtifact(params: { artifactPath: string; tempDir: string; - tenantId?: string; + owner: ArtifactOwner; + releaseReservation?: () => void; }): string { const uploadId = crypto.randomUUID(); const timer = setTimeout(() => { @@ -933,19 +980,17 @@ export function trackUploadedArtifact(params: { pendingUploads().set(uploadId, { artifactPath: params.artifactPath, tempDir: params.tempDir, - tenantId: params.tenantId, + owner: params.owner, + releaseReservation: params.releaseReservation, timer, }); return uploadId; } -export function prepareUploadedArtifact(uploadId: string, tenantId?: string): string { - const entry = requireTenantOwnedEntry( - pendingUploads(), - uploadId, - tenantId, - UPLOADED_ARTIFACT_RESOURCE, - ); +export function prepareUploadedArtifact(uploadId: string, owner: ArtifactOwner): string { + const entry = pendingUploads().get(uploadId); + if (!entry) throw expiredTenantOwnedEntryError(UPLOADED_ARTIFACT_RESOURCE, uploadId); + assertArtifactOwner(entry.owner, owner); clearTimeout(entry.timer); return entry.artifactPath; } @@ -955,5 +1000,55 @@ export function cleanupUploadedArtifact(uploadId: string): void { if (!entry) return; clearTimeout(entry.timer); pendingUploads().delete(uploadId); - fs.rmSync(entry.tempDir, { recursive: true, force: true }); + removeStagedUpload(entry.tempDir, entry.releaseReservation); +} + +export function removeStagedUpload(tempDir: string, releaseReservation?: () => void): void { + removeStagedUploadSync(tempDir, releaseReservation, true); +} + +function removeStagedUploadSync( + tempDir: string, + releaseReservation: (() => void) | undefined, + firstAttempt: boolean, +): void { + try { + fs.rmSync(tempDir, { recursive: true, force: true }); + } catch (error) { + retryRemoval(tempDir, releaseReservation); + if (firstAttempt) reportStagedUploadCleanupDeferred(tempDir, error); + return; + } + releaseReservation?.(); +} + +export async function removeStagedUploadAsync( + tempDir: string, + releaseReservation: () => void, +): Promise { + try { + await fs.promises.rm(tempDir, { recursive: true, force: true }); + } catch (error) { + retryRemoval(tempDir, releaseReservation); + reportStagedUploadCleanupDeferred(tempDir, error); + throw error; + } + releaseReservation(); +} + +function retryRemoval(tempDir: string, releaseReservation?: () => void): void { + setTimeout( + () => removeStagedUploadSync(tempDir, releaseReservation, false), + STAGED_UPLOAD_RETRY_DELAY_MS, + ).unref(); +} + +function reportStagedUploadCleanupDeferred(tempDir: string, error: unknown): void { + artifactTracking().onStagedUploadCleanupDeferred?.(tempDir, error, STAGED_UPLOAD_RETRY_DELAY_MS); +} + +export function setStagedUploadCleanupDiagnostic( + emit: NonNullable, +): void { + artifactTracking().onStagedUploadCleanupDeferred = emit; } diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index 33cc6927e1e..fccae3f17d6 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -515,10 +515,7 @@ export class LeaseRegistry { return Array.from(this.leases.values()).map((entry) => ({ ...entry })); } - recordProviderSession( - lease: Pick, - providerSessionId: string, - ): void { + recordProviderSession(lease: DeviceLease, providerSessionId: string): void { this.cleanupExpiredLeases(); const releasedAt = lease.expiresAt <= this.now() ? lease.expiresAt : undefined; this.providerSessionOwnership.record(lease, providerSessionId); @@ -531,6 +528,8 @@ export class LeaseRegistry { provider?: string; providerSessionId?: string; tenantId?: string; + leaseId?: string; + runId?: string; }): ProviderSessionOwnership | undefined { this.cleanupExpiredLeases(); return this.providerSessionOwnership.resolve(params); diff --git a/packages/daemon/src/resources/provider-session-ownership.ts b/packages/daemon/src/resources/provider-session-ownership.ts index 08a8b2ed7e1..25fd63fb10a 100644 --- a/packages/daemon/src/resources/provider-session-ownership.ts +++ b/packages/daemon/src/resources/provider-session-ownership.ts @@ -1,13 +1,16 @@ +import type { SessionLease } from '../core/lease-context.ts'; import type { DeviceLease } from '@agent-device/contracts/device'; const DEFAULT_PROVIDER_SESSION_RETENTION_MS = 5 * 60_000; -export type ProviderSessionOwnership = Readonly<{ - provider: string; - providerSessionId: string; - leaseId: string; - tenantId: string; -}>; +export type ProviderSessionOwnership = SessionLease & + Readonly<{ + provider: string; + providerSessionId: string; + leaseId: string; + tenantId: string; + runId?: string; + }>; type ProviderSessionRecord = ProviderSessionOwnership & { retainedUntil?: number; @@ -34,16 +37,18 @@ export class ProviderSessionOwnershipRegistry { : DEFAULT_PROVIDER_SESSION_RETENTION_MS; } - record(lease: Pick, rawId: string): void { + record(lease: SessionLease, rawId: string): void { const provider = lease.leaseProvider?.trim(); const providerSessionId = rawId.trim(); if (!provider || !providerSessionId) return; this.prune(); const ownership: ProviderSessionOwnership = { + ...lease, provider, providerSessionId, leaseId: lease.leaseId, tenantId: lease.tenantId, + runId: lease.runId, }; this.records.set(this.key(provider, providerSessionId), ownership); } @@ -66,13 +71,19 @@ export class ProviderSessionOwnershipRegistry { provider?: string; providerSessionId?: string; tenantId?: string; + leaseId?: string; + runId?: string; }): ProviderSessionOwnership | undefined { const provider = params.provider?.trim(); const providerSessionId = params.providerSessionId?.trim(); const tenantId = params.tenantId?.trim(); - if (!provider || !providerSessionId || !tenantId) return undefined; + if (!provider || (!providerSessionId && !params.leaseId) || !tenantId) return undefined; this.prune(); - const record = this.records.get(this.key(provider, providerSessionId)); + const record = providerSessionId + ? this.records.get(this.key(provider, providerSessionId)) + : [...this.records.values()].find( + (entry) => entry.provider === provider && entry.leaseId === params.leaseId, + ); if (!record || record.tenantId !== tenantId) return undefined; return { ...record }; } diff --git a/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts b/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts index cf04f3028e9..5d161563b2d 100644 --- a/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts +++ b/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts @@ -130,6 +130,11 @@ test('the rpc boundary never accepts internal request fields from the wire', asy command: 'snapshot', positionals: [], internal: { + principal: 'attested', + admittedArtifactScope: { + principal: 'attested', + owner: { tenantId: 'forged', leaseVerifier: 'forged' }, + }, observationOnly: true, replayPlanStep: true, replayTargetGuard: { ref: '@e1' }, @@ -140,9 +145,9 @@ test('the rpc boundary never accepts internal request fields from the wire', asy assert.equal(response.status, 200); assert.equal(received.length, 1); - assert.equal( + assert.deepEqual( received[0]?.internal, - undefined, + { principal: 'local' }, 'a wire-supplied `internal` must never reach the daemon request', ); } finally { @@ -271,14 +276,18 @@ test('remote HTTP accepts an uploaded path artifact without resolving the client const root = mkdtempForTestSync('agent-device-http-uploaded-path-'); const artifactPath = path.join(root, 'uploaded.apk'); fs.writeFileSync(artifactPath, 'uploaded'); - const uploadedArtifactId = trackUploadedArtifact({ artifactPath, tempDir: root }); + const uploadedArtifactId = trackUploadedArtifact({ + owner: { tenantId: undefined, leaseVerifier: null }, + artifactPath, + tempDir: root, + }); const hookPath = writeAllowingAuthHook(root); const received: DaemonRequest[] = []; const server = await createDaemonHttpServer({ env: remoteHttpEnvironment(hookPath), handleRequest: async (request): Promise => { received.push(request); - const resolved = resolveInstallSource(request); + const resolved = resolveInstallSource(request, { tenantId: undefined, leaseVerifier: null }); try { assert.equal(resolved.source.kind, 'path'); assert.equal(resolved.source.path, artifactPath); @@ -336,7 +345,7 @@ test('local command RPC keeps host paths unrestricted', async (t) => { kind: 'path', path: '/tmp/local.apk', }); - assert.equal(received[0]?.internal, undefined); + assert.deepEqual(received[0]?.internal, { principal: 'local' }); } finally { await closeLoopbackServer(server); } diff --git a/packages/daemon/src/server/__tests__/request-execution-scope-observation.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope-observation.test.ts index 299f24e1031..d24fa504cb0 100644 --- a/packages/daemon/src/server/__tests__/request-execution-scope-observation.test.ts +++ b/packages/daemon/src/server/__tests__/request-execution-scope-observation.test.ts @@ -69,7 +69,6 @@ async function observe(req: DaemonRequest, sessionStore: ReturnType 'artifact-id', }); const response = await handler({ diff --git a/packages/daemon/src/server/__tests__/request-execution-scope.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope.test.ts index ba103fa0daf..4698384f6ec 100644 --- a/packages/daemon/src/server/__tests__/request-execution-scope.test.ts +++ b/packages/daemon/src/server/__tests__/request-execution-scope.test.ts @@ -690,7 +690,6 @@ test('prepareLockedRequestScope preserves existing-session selector validation', prepareLockedRequestScope({ scope, sessionStore, - trackDownloadableArtifact: () => 'artifact-id', }), ), ).rejects.toThrow(/already bound to android device "Pixel" \(emulator-5554\).*--platform=ios/i); @@ -720,7 +719,6 @@ test('prepareLockedRequestScope blocks commands for invalidated recordings befor prepareLockedRequestScope({ scope, sessionStore, - trackDownloadableArtifact: () => 'artifact-id', }), ), ); @@ -747,7 +745,6 @@ test('prepareLockedRequestScope passes the session runner log path into handler prepareLockedRequestScope({ scope, sessionStore, - trackDownloadableArtifact: () => 'artifact-id', }), ); @@ -778,7 +775,6 @@ test('prepareLockedRequestScope streams ordinary diagnostics into the active tra const result = await prepareLockedRequestScope({ scope, sessionStore, - trackDownloadableArtifact: () => 'artifact-id', }); expect(result.type).toBe('scope'); emitDiagnostic({ phase: 'trace_regression_canary' }); diff --git a/packages/daemon/src/server/__tests__/request-finalization.test.ts b/packages/daemon/src/server/__tests__/request-finalization.test.ts index 39cb28cda63..8d4a32554f1 100644 --- a/packages/daemon/src/server/__tests__/request-finalization.test.ts +++ b/packages/daemon/src/server/__tests__/request-finalization.test.ts @@ -1,24 +1,8 @@ import { test, expect } from 'vitest'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { finalizeDaemonResponse } from '../request-finalization.ts'; -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 { LeaseRegistry } from '../../resources/lease-registry.ts'; -import { leaseVerifier } from '../../resources/artifact-tracking.ts'; -import { - asDaemonDeliveredArtifact, - withCaptureOutputOwnership, -} from '../../core/capture-output-ownership.ts'; - test('finalizeDaemonResponse preserves handler error hints from details', () => { - const req: DaemonRequest = { - token: 'token', - session: 'default', - command: 'open', - positionals: [], - flags: {}, - }; const response: DaemonResponse = { ok: false, error: { @@ -31,7 +15,7 @@ test('finalizeDaemonResponse preserves handler error hints from details', () => }, }; - const finalized = finalizeDaemonResponse(req, response, () => 'artifact-id'); + const finalized = finalizeDaemonResponse(response); expect(finalized.ok).toBe(false); if (!finalized.ok) { @@ -40,13 +24,6 @@ test('finalizeDaemonResponse preserves handler error hints from details', () => }); test('finalizeDaemonResponse keeps a network error code without the cause message', () => { - const req: DaemonRequest = { - token: 'token', - session: 'default', - command: 'install-from-source', - positionals: ['https://example.com/app.apk'], - flags: {}, - }; const response: DaemonResponse = { ok: false, error: normalizeError( @@ -59,7 +36,7 @@ test('finalizeDaemonResponse keeps a network error code without the cause messag ), }; - const finalized = finalizeDaemonResponse(req, response, () => 'artifact-id'); + const finalized = finalizeDaemonResponse(response); expect(finalized.ok).toBe(false); if (!finalized.ok) { @@ -71,340 +48,23 @@ test('finalizeDaemonResponse keeps a network error code without the cause messag } }); -test('finalizeDaemonResponse registers downloadable artifact type', () => { - const req: DaemonRequest = { - token: 'token', - session: 'default', - command: 'record', - positionals: ['stop'], - meta: { tenantId: 'tenant-a' }, - }; - const response: DaemonResponse = { - ok: true, - data: { - artifacts: [ - { - field: 'telemetryPath', - artifactType: 'screen-recording-telemetry', - path: '/tmp/telemetry.json', - localPath: '/client/telemetry.json', - fileName: 'telemetry.json', - }, - { - field: 'rawPath', - artifactType: undefined, - path: '/tmp/raw.bin', - localPath: '/client/raw.bin', - fileName: 'raw.bin', - }, - ], - }, - }; - const tracked: Array<{ - artifactPath: string; - tenantId?: string; - artifactType?: DaemonArtifactType; - fileName?: string; - }> = []; - - const finalized = finalizeDaemonResponse(req, response, (opts) => { - tracked.push(opts); - return `artifact-id-${tracked.length}`; - }); - - expect(finalized).toEqual({ - ok: true, - data: { - artifacts: [ - { - field: 'telemetryPath', - artifactType: 'screen-recording-telemetry', - artifactId: 'artifact-id-1', - fileName: 'telemetry.json', - localPath: '/client/telemetry.json', - }, - { - field: 'rawPath', - artifactId: 'artifact-id-2', - fileName: 'raw.bin', - localPath: '/client/raw.bin', - }, - ], - }, - }); - // The untyped artifact must omit the key entirely (optional wire contract), - // not carry an explicit undefined — toEqual alone cannot tell these apart. - const finalizedArtifacts = - finalized.ok === true - ? (finalized.data?.artifacts as Array>) - : undefined; - expect(finalizedArtifacts?.[1]).not.toHaveProperty('artifactType'); - expect(tracked).toEqual([ - { - artifactPath: '/tmp/telemetry.json', - tenantId: 'tenant-a', - artifactType: 'screen-recording-telemetry', - fileName: 'telemetry.json', - }, - { - artifactPath: '/tmp/raw.bin', - tenantId: 'tenant-a', - artifactType: undefined, - fileName: 'raw.bin', - }, - ]); -}); - -test('finalizeDaemonResponse registers an unexpected output artifact without a client path', () => { - const req: DaemonRequest = { - token: 'token', - session: 'default', - command: 'snapshot', - positionals: [], - meta: { tenantId: 'tenant-a' }, - }; - const response: DaemonResponse = { - ok: true, - data: { - fallbackScreenshotPath: '/tmp/snapshot-fallback.png', - artifacts: [ - { - field: 'fallbackScreenshotPath', - artifactType: 'screenshot', - path: '/tmp/snapshot-fallback.png', - fileName: 'snapshot-fallback.png', - }, - ], - }, - }; - - const finalized = finalizeDaemonResponse(req, response, () => 'artifact-id'); - - expect(finalized).toEqual({ - ok: true, - data: { - fallbackScreenshotPath: '/tmp/snapshot-fallback.png', - artifacts: [ - { - field: 'fallbackScreenshotPath', - artifactType: 'screenshot', - artifactId: 'artifact-id', - fileName: 'snapshot-fallback.png', - localPath: undefined, - }, - ], - }, - }); -}); - -test('finalizeDaemonResponse leaves unrelated local-path artifacts unregistered', () => { - const req: DaemonRequest = { - token: 'token', - session: 'default', - command: 'record', - positionals: ['stop'], - }; - const response: DaemonResponse = { - ok: true, - data: { - artifacts: [ - { - field: 'recordingPath', - artifactType: 'screen-recording', - path: '/tmp/recording.mp4', - fileName: 'recording.mp4', - }, - ], - }, - }; - - const finalized = finalizeDaemonResponse(req, response, () => { - throw new Error('local-only artifact must not be registered'); - }); - - expect(finalized).toEqual(response); -}); - -test('a screenshot response path alone does not register an artifact', () => { - const req: DaemonRequest = { - token: 'token', - session: 'default', - command: 'screenshot', - positionals: [], - internal: { publicNetworkOnly: true }, - meta: { clientArtifactPaths: { path: '/client/screenshot.png' } }, - }; - const response: DaemonResponse = { ok: true, data: { path: '/tmp/screenshot.png' } }; - - expect( - finalizeDaemonResponse(req, response, () => { - throw new Error('A screenshot needs a producer-committed artifact'); - }), - ).toEqual(response); -}); - -test('a committed screenshot keeps its ID alongside a delivered script revision', () => { - const screenshot = { - field: 'path', - artifactType: 'screenshot' as const, - artifactId: 'producer-id', - fileName: 'screenshot.png', - localPath: '/client/screenshot.png', - }; - const script = asDaemonDeliveredArtifact( - { - field: 'savedScript', - artifactType: 'session-script', - path: '/daemon/session.ad', - scriptPublicationId: 'publication', - scriptRevision: 2, - }, - 'tenant-a', - ); - const tracked: DownloadableArtifactRegistration[] = []; - const response = finalizeDaemonResponse( - { token: 'token', session: 'default', command: 'screenshot', positionals: [] }, - { ok: true, data: { artifacts: [screenshot, script] } }, - (entry) => { - tracked.push(entry); - return 'script-id'; - }, - ); - - expect(response).toMatchObject({ - ok: true, - data: { - artifacts: [screenshot, { artifactId: 'script-id', scriptRevision: 2 }], - }, - }); - expect(tracked.map(({ artifactPath }) => artifactPath)).toEqual(['/daemon/session.ad']); -}); - -test('finalizeDaemonResponse registers the display rotation a handler put on its own artifact', () => { - const req: DaemonRequest = { - token: 'token', - session: 'default', - command: 'snapshot', - positionals: [], - }; - const tracked: DownloadableArtifactRegistration[] = []; - const fallbackArtifact = { - field: 'fallbackScreenshotPath', - artifactType: 'screenshot' as const, - path: '/tmp/snapshot-fallback.png', - fileName: 'snapshot-fallback.png', - displayRotation: 'landscape-right' as const, - }; - - finalizeDaemonResponse( - req, - { ok: true, data: { artifacts: [fallbackArtifact] } }, - (registration) => { - tracked.push(registration); - return 'artifact-id'; - }, - ); - - expect(tracked[0]?.displayRotation).toBe('landscape-right'); -}); - -test('finalizeDaemonResponse registers no display rotation outside the vocabulary on a handler artifact', () => { - const req: DaemonRequest = { - token: 'token', - session: 'default', - command: 'snapshot', - positionals: [], - }; - const tracked: DownloadableArtifactRegistration[] = []; - const fallbackArtifact = { - field: 'fallbackScreenshotPath', - artifactType: 'screenshot' as const, - path: '/tmp/snapshot-fallback.png', - fileName: 'snapshot-fallback.png', - displayRotation: 'sideways', +test('finalization preserves committed IDs and does not infer registrations from response paths', () => { + const data = { + outPath: '/untrusted/reply-path', + artifacts: [ + { + field: 'outPath', + artifactType: 'performance' as const, + artifactId: 'producer-committed-id', + localPath: 'agent-device-capture-token', + }, + { + field: 'savedScript', + artifactType: 'session-script' as const, + path: '/another/reply-path', + }, + ], }; - - finalizeDaemonResponse( - req, - { ok: true, data: { artifacts: [fallbackArtifact] } }, - (registration) => { - tracked.push(registration); - return 'artifact-id'; - }, - ); - - expect(tracked).toHaveLength(1); - expect(tracked[0]).not.toHaveProperty('displayRotation'); -}); - -test.each([ - { name: 'no tenant', requestTenant: undefined }, - { name: 'another tenant', requestTenant: 'tenant-b' }, -])( - 'a daemon-delivered artifact registers for its recording tenant on a request with $name', - ({ requestTenant }) => { - const registrations: DownloadableArtifactRegistration[] = []; - const req: DaemonRequest = { - token: 'token', - session: 'journey', - command: 'wait', - positionals: [], - meta: requestTenant ? { tenantId: requestTenant } : {}, - }; - const script = asDaemonDeliveredArtifact( - { field: 'savedScript', artifactType: 'session-script', path: '/tmp/script.ad' }, - 'tenant-a', - ); - - finalizeDaemonResponse(req, { ok: true, data: { artifacts: [script] } }, (registration) => { - registrations.push(registration); - return 'artifact-id'; - }); - - expect(registrations.map(({ tenantId }) => tenantId)).toEqual(['tenant-a']); - }, -); - -test('a delivered script keeps the admitted lease alongside an unleased recording', () => { - const lease = new LeaseRegistry().allocateLease({ tenantId: 'tenant', runId: 'record' }); - const tracked: DownloadableArtifactRegistration[] = []; - finalizeDaemonResponse( - { - token: 'token', - session: 'default', - command: 'record', - positionals: ['stop'], - internal: { admittedLease: lease }, - meta: { tenantId: 'tenant' }, - }, - { - ok: true, - data: withCaptureOutputOwnership( - { - artifacts: [ - { field: 'outPath', artifactType: 'screen-recording', path: '/daemon/video.mp4' }, - asDaemonDeliveredArtifact( - { - field: 'savedScript', - artifactType: 'session-script', - path: '/daemon/session.ad', - }, - 'tenant', - ), - ], - }, - 'daemon', - undefined, - null, - ), - }, - (entry) => { - tracked.push(entry); - return 'artifact'; - }, - ); - expect(tracked.map((artifact) => [artifact.tenantId, artifact.leaseVerifier])).toEqual([ - ['tenant', undefined], - ['tenant', leaseVerifier(lease.leaseId)], - ]); + const response = finalizeDaemonResponse({ ok: true, data }); + expect(response.ok && response.data).toBe(data); }); diff --git a/packages/daemon/src/server/__tests__/request-router-android-foreground-evidence.test.ts b/packages/daemon/src/server/__tests__/request-router-android-foreground-evidence.test.ts index 2af777853dc..aa7ba67752f 100644 --- a/packages/daemon/src/server/__tests__/request-router-android-foreground-evidence.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-android-foreground-evidence.test.ts @@ -30,7 +30,6 @@ function createOpenHandler(sessionStore: ReturnType) { leaseRegistry: new LeaseRegistry(), deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); } diff --git a/packages/daemon/src/server/__tests__/request-router-android-modal.test.ts b/packages/daemon/src/server/__tests__/request-router-android-modal.test.ts index 8c6c077c729..bbc7a6e2403 100644 --- a/packages/daemon/src/server/__tests__/request-router-android-modal.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-android-modal.test.ts @@ -69,7 +69,7 @@ async function scrollWhileRecording(params: { sessionStore: params.sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', + deviceRuntimeGateway: gestureDeviceRuntimeGateway, androidObservation: params.observation, }); diff --git a/packages/daemon/src/server/__tests__/request-router-android-snapshot-helper.test.ts b/packages/daemon/src/server/__tests__/request-router-android-snapshot-helper.test.ts index dc60866004d..9966d67d3b4 100644 --- a/packages/daemon/src/server/__tests__/request-router-android-snapshot-helper.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-android-snapshot-helper.test.ts @@ -51,7 +51,6 @@ function snapshotHandler( local: async () => [ANDROID_EMULATOR], }), deviceRuntimeGateway: runtime.gateway, - trackDownloadableArtifact: () => 'artifact-id', }); return { handler, sessionStore, leaseRegistry, runtime }; } diff --git a/packages/daemon/src/server/__tests__/request-router-app-device-batches.test.ts b/packages/daemon/src/server/__tests__/request-router-app-device-batches.test.ts index 3d07541c40a..1e77354c6b6 100644 --- a/packages/daemon/src/server/__tests__/request-router-app-device-batches.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-app-device-batches.test.ts @@ -68,7 +68,6 @@ test('batches in two app sessions that each open the other app finish instead of deviceInventoryGateways: createTestDeviceInventoryGateways({ local: async () => [MACOS_DEVICE], }), - trackDownloadableArtifact: () => 'artifact-id', }); // Each batch holds its own app device's lock for its whole run, so each step that opens the diff --git a/packages/daemon/src/server/__tests__/request-router-apps-admission.test.ts b/packages/daemon/src/server/__tests__/request-router-apps-admission.test.ts index d01f7cbf865..f93ab108789 100644 --- a/packages/daemon/src/server/__tests__/request-router-apps-admission.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-apps-admission.test.ts @@ -60,7 +60,6 @@ function createAppsAdmissionHarness(apps: readonly string[] = []) { credentials: { variables: [], byBackend: {} }, }, ], - trackDownloadableArtifact: () => 'artifact-id', }); return { handler, listProviderApps, inspectFacts, bind }; } diff --git a/packages/daemon/src/server/__tests__/request-router-artifacts-web.test.ts b/packages/daemon/src/server/__tests__/request-router-artifacts-web.test.ts index 2173f6cd73e..d83690338d7 100644 --- a/packages/daemon/src/server/__tests__/request-router-artifacts-web.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-artifacts-web.test.ts @@ -45,7 +45,6 @@ test('artifacts lists a daemon-tracked artifact produced during a web session', sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'unused-artifact-id', }); const response = await handler({ diff --git a/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts b/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts index b5440b72fcd..bc3f32a42b7 100644 --- a/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts @@ -176,7 +176,6 @@ function route( ? options.inventory(request) : (options.inventory ?? [device]), }), - trackDownloadableArtifact: () => 'artifact-id', }); return { handler, runtime, recovery, sessionStore }; } diff --git a/packages/daemon/src/server/__tests__/request-router-coordinate-unit.test.ts b/packages/daemon/src/server/__tests__/request-router-coordinate-unit.test.ts index 868b6cb5d61..dc459ba4c64 100644 --- a/packages/daemon/src/server/__tests__/request-router-coordinate-unit.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-coordinate-unit.test.ts @@ -189,7 +189,7 @@ function makeHandler(device: DeviceInfo | null = ANDROID_EMULATOR) { deviceInventoryGateways: createTestDeviceInventoryGateways({ local: async () => [ANDROID_EMULATOR, IOS_SIMULATOR], }), - trackDownloadableArtifact: () => 'artifact-id', + deviceRuntimeGateway: gateway, androidObservation: clearAndroidObservationFixture, }); diff --git a/packages/daemon/src/server/__tests__/request-router-cost.test.ts b/packages/daemon/src/server/__tests__/request-router-cost.test.ts index 04d73c3893f..9d45dc42854 100644 --- a/packages/daemon/src/server/__tests__/request-router-cost.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-cost.test.ts @@ -62,7 +62,7 @@ function makeHandler(sessionStore = makeSessionStore('agent-device-router-cost-' sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', + deviceRuntimeGateway: gestureDeviceRuntimeGateway, }), }; diff --git a/packages/daemon/src/server/__tests__/request-router-custom-action-flags.test.ts b/packages/daemon/src/server/__tests__/request-router-custom-action-flags.test.ts index 5b3b0a464d6..90357933722 100644 --- a/packages/daemon/src/server/__tests__/request-router-custom-action-flags.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-custom-action-flags.test.ts @@ -24,7 +24,6 @@ function createHandler() { sessionStore: makeSessionStore('agent-device-router-custom-action-flags-'), leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); } diff --git a/packages/daemon/src/server/__tests__/request-router-developer-dir.test.ts b/packages/daemon/src/server/__tests__/request-router-developer-dir.test.ts index 8d5d99896e4..5a287ee69a1 100644 --- a/packages/daemon/src/server/__tests__/request-router-developer-dir.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-developer-dir.test.ts @@ -29,7 +29,6 @@ test('a request spawns its commands with its own DEVELOPER_DIR, else the daemon return []; }, }), - trackDownloadableArtifact: () => 'artifact-id', }); const devices = (developerDir?: string) => handler({ diff --git a/packages/daemon/src/server/__tests__/request-router-device-spec-gate.test.ts b/packages/daemon/src/server/__tests__/request-router-device-spec-gate.test.ts index 657f5934616..2c8fbfa6e4c 100644 --- a/packages/daemon/src/server/__tests__/request-router-device-spec-gate.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-device-spec-gate.test.ts @@ -39,7 +39,7 @@ function makeHandler() { leaseRegistry: new LeaseRegistry(), deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways({ local: async () => [] }), - trackDownloadableArtifact: () => 'artifact-id', + hostDiagnostics: hostDiagnosticsFixture(), }); } diff --git a/packages/daemon/src/server/__tests__/request-router-error-redaction.test.ts b/packages/daemon/src/server/__tests__/request-router-error-redaction.test.ts index fac6db1c6c2..ffbc2469dc1 100644 --- a/packages/daemon/src/server/__tests__/request-router-error-redaction.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-error-redaction.test.ts @@ -69,7 +69,7 @@ test('a Maestro replay error comes back unchanged after its inputText registered sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', + deviceRuntimeGateway: typingDeviceRuntimeGateway, }); diff --git a/packages/daemon/src/server/__tests__/request-router-events.test.ts b/packages/daemon/src/server/__tests__/request-router-events.test.ts index 499a907d12a..8dba269cca6 100644 --- a/packages/daemon/src/server/__tests__/request-router-events.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-events.test.ts @@ -33,7 +33,6 @@ test('events reads the daemon-owned session timeline without appending poll nois sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ @@ -80,7 +79,6 @@ test('events accepts a blank limit placeholder for cursor-only reads', async () sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ @@ -122,7 +120,6 @@ test('events returns structured errors for invalid limit and cursor', async () = sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const invalidLimit = await handler({ @@ -172,7 +169,6 @@ test('events flushes pending event writes before reading', async () => { sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ @@ -214,7 +210,6 @@ test('events reads the daemon-owned session timeline for a web-backed session', sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ @@ -249,7 +244,6 @@ test('request timeline records thrown request failures after scope creation', as sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ @@ -293,7 +287,6 @@ test.each([ sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ diff --git a/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts b/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts index 7b0fba9ebd9..0c05d1186d9 100644 --- a/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts @@ -93,7 +93,6 @@ function sendToWebSession( leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway, - trackDownloadableArtifact: () => 'artifact-id', }); const response = handler({ token: 'test-token', diff --git a/packages/daemon/src/server/__tests__/request-router-idle-expired.test.ts b/packages/daemon/src/server/__tests__/request-router-idle-expired.test.ts index 637b657c5ec..1c60ffc4136 100644 --- a/packages/daemon/src/server/__tests__/request-router-idle-expired.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-idle-expired.test.ts @@ -27,7 +27,6 @@ function makeHandler(prefix: string) { sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); return { sessionStore, handler }; } diff --git a/packages/daemon/src/server/__tests__/request-router-install-source-deadline.test.ts b/packages/daemon/src/server/__tests__/request-router-install-source-deadline.test.ts index ee4986b6188..c4d0c32e1d5 100644 --- a/packages/daemon/src/server/__tests__/request-router-install-source-deadline.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-install-source-deadline.test.ts @@ -295,7 +295,7 @@ function makeRouterHarness(gateway: DeviceRuntimeGateway 'artifact-id', + deviceRuntimeGateway: gateway, }); return { sessionStore, handler }; diff --git a/packages/daemon/src/server/__tests__/request-router-lock-policy.test.ts b/packages/daemon/src/server/__tests__/request-router-lock-policy.test.ts index b6f16ebd96d..cef63ae91e8 100644 --- a/packages/daemon/src/server/__tests__/request-router-lock-policy.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-lock-policy.test.ts @@ -135,7 +135,6 @@ test('direct daemon requests cannot bypass reject lock policy for existing sessi sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ @@ -176,7 +175,6 @@ test('a fresh named session with a matching explicit serial waits for the holder makeAndroidSession('inventory').device, ]), deviceRuntimeGateway: snapshotDeviceRuntimeGateway(), - trackDownloadableArtifact: () => 'artifact-id', }); const first = handler({ @@ -256,7 +254,6 @@ test('fresh named sessions with the same name serialize first binding before rej secondDevice, ]), deviceRuntimeGateway: snapshotDeviceRuntimeGateway(), - trackDownloadableArtifact: () => 'artifact-id', }); const first = handler({ @@ -330,7 +327,6 @@ test('a fresh named session with only a lock platform default waits for the hold makeAndroidSession('inventory').device, ]), deviceRuntimeGateway: snapshotDeviceRuntimeGateway(), - trackDownloadableArtifact: () => 'artifact-id', }); const first = handler({ @@ -438,7 +434,6 @@ test('fresh named sessions reject incompatible selector combinations before bind deviceInventoryGateways: createTestDeviceInventoryGatewaysFromProvider(async () => [ makeIosSession('inventory').device, ]), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ @@ -476,7 +471,6 @@ test('batch steps cannot bypass reject lock policy on nested direct requests', a sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ @@ -524,7 +518,6 @@ test('direct daemon requests apply strip lock policy for existing sessions befor leaseRegistry: new LeaseRegistry(), deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ @@ -568,7 +561,6 @@ test('strip lock policy still refuses a request naming a different device, befor sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ @@ -609,7 +601,6 @@ test('batch preserves tenant-scoped session names across nested requests', async leaseRegistry, deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ diff --git a/packages/daemon/src/server/__tests__/request-router-macos-app-lease.test.ts b/packages/daemon/src/server/__tests__/request-router-macos-app-lease.test.ts index 25997b2a43f..bfd6c76793f 100644 --- a/packages/daemon/src/server/__tests__/request-router-macos-app-lease.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-macos-app-lease.test.ts @@ -65,7 +65,6 @@ function leasedRouter() { leaseRegistry, deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: runtime.gateway, - trackDownloadableArtifact: () => 'artifact-id', }); return { handler, sessionStore }; } @@ -137,7 +136,6 @@ test('a request without a macos-app lease keeps its log locators', async () => { leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: screenshotRuntimeFixture().gateway, - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ diff --git a/packages/daemon/src/server/__tests__/request-router-named-session.test.ts b/packages/daemon/src/server/__tests__/request-router-named-session.test.ts index 1d3915bf350..8efaf6c4875 100644 --- a/packages/daemon/src/server/__tests__/request-router-named-session.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-named-session.test.ts @@ -57,7 +57,6 @@ function makeHandler( return BOOTED_SIMULATORS; }, }), - trackDownloadableArtifact: () => 'artifact-id', }); return { handler, sessionStore }; } diff --git a/packages/daemon/src/server/__tests__/request-router-nested-session-lease.test.ts b/packages/daemon/src/server/__tests__/request-router-nested-session-lease.test.ts index 64c2199ddff..622e96ef95f 100644 --- a/packages/daemon/src/server/__tests__/request-router-nested-session-lease.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-nested-session-lease.test.ts @@ -97,7 +97,6 @@ function leasedRouter(options: { leased?: boolean } = {}) { leaseRegistry, deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: gateway, - trackDownloadableArtifact: () => 'artifact-id', }); return { handler, leaseId: lease.leaseId, root }; } diff --git a/packages/daemon/src/server/__tests__/request-router-open-claim-recovery.test.ts b/packages/daemon/src/server/__tests__/request-router-open-claim-recovery.test.ts index 833033d6ec2..e7a38ba212a 100644 --- a/packages/daemon/src/server/__tests__/request-router-open-claim-recovery.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-open-claim-recovery.test.ts @@ -56,7 +56,6 @@ test('open composes claim recovery from the foreign owner state directory', asyn deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, claimRecoveryGateway: composeClaimRecovery, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler( diff --git a/packages/daemon/src/server/__tests__/request-router-open-claim.test.ts b/packages/daemon/src/server/__tests__/request-router-open-claim.test.ts index 72ee3cf2c05..f9a8a94671e 100644 --- a/packages/daemon/src/server/__tests__/request-router-open-claim.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-open-claim.test.ts @@ -79,7 +79,6 @@ function createOpenHandler( leaseRegistry, deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); } diff --git a/packages/daemon/src/server/__tests__/request-router-open.test.ts b/packages/daemon/src/server/__tests__/request-router-open.test.ts index 1af33d21ad2..89b448013ee 100644 --- a/packages/daemon/src/server/__tests__/request-router-open.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-open.test.ts @@ -111,7 +111,7 @@ function createOpenHandler( leaseRegistry, deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', + ...capabilities, }); } diff --git a/packages/daemon/src/server/__tests__/request-router-provider-credentials.test.ts b/packages/daemon/src/server/__tests__/request-router-provider-credentials.test.ts index 332a2f6608d..9a8953fdf8c 100644 --- a/packages/daemon/src/server/__tests__/request-router-provider-credentials.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-provider-credentials.test.ts @@ -34,7 +34,6 @@ test.for([ return {}; }, }, - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ diff --git a/packages/daemon/src/server/__tests__/request-router-record-flags.test.ts b/packages/daemon/src/server/__tests__/request-router-record-flags.test.ts index 4f5a85d4330..cdc82f116ef 100644 --- a/packages/daemon/src/server/__tests__/request-router-record-flags.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-record-flags.test.ts @@ -24,7 +24,6 @@ function createHandler() { sessionStore: makeSessionStore('agent-device-router-record-flags-'), leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); } diff --git a/packages/daemon/src/server/__tests__/request-router-record-only-retirement.test.ts b/packages/daemon/src/server/__tests__/request-router-record-only-retirement.test.ts index 7343ecdd7f1..f3d84eca769 100644 --- a/packages/daemon/src/server/__tests__/request-router-record-only-retirement.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-record-only-retirement.test.ts @@ -308,7 +308,6 @@ function createHandler( deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway, platformServices: daemonPlatformServicesFixture(platformServiceOverrides), - trackDownloadableArtifact: () => 'artifact-id', }); } diff --git a/packages/daemon/src/server/__tests__/request-router-record-runtime-lock.test.ts b/packages/daemon/src/server/__tests__/request-router-record-runtime-lock.test.ts index 432d0e19c4b..fc6e2d7718c 100644 --- a/packages/daemon/src/server/__tests__/request-router-record-runtime-lock.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-record-runtime-lock.test.ts @@ -53,7 +53,6 @@ test('a fresh session record start waits for the holder, then is refused before leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: runtime.gateway, - trackDownloadableArtifact: () => 'artifact', }); const first = handler(recordStartRequest('session-a', 'record-start-a')); diff --git a/packages/daemon/src/server/__tests__/request-router-recording-health.test.ts b/packages/daemon/src/server/__tests__/request-router-recording-health.test.ts index f5212c15f13..fa3a9271ebe 100644 --- a/packages/daemon/src/server/__tests__/request-router-recording-health.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-recording-health.test.ts @@ -97,7 +97,7 @@ test('router blocks non-record commands when recording was invalidated', async ( sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', + platformServices, }); @@ -150,7 +150,7 @@ test('bounded record refusal does not let the outer request invalidate recording sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', + platformServices, }); @@ -211,7 +211,7 @@ test('router allows canonical iOS simulator gestures during overlay recording af sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', + deviceRuntimeGateway: gestureDeviceRuntimeGateway, platformServices, }); diff --git a/packages/daemon/src/server/__tests__/request-router-remote-maestro-capture.test.ts b/packages/daemon/src/server/__tests__/request-router-remote-maestro-capture.test.ts index 45b0a9ad29a..d76d9909069 100644 --- a/packages/daemon/src/server/__tests__/request-router-remote-maestro-capture.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-remote-maestro-capture.test.ts @@ -41,7 +41,6 @@ function harness(simulatorSetPath?: string) { leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: runtime.gateway, - trackDownloadableArtifact: () => 'artifact-id', }); const run = async (steps: string) => { const flowPath = path.join(root, 'flow.yaml'); diff --git a/packages/daemon/src/server/__tests__/request-router-repair-expired.test.ts b/packages/daemon/src/server/__tests__/request-router-repair-expired.test.ts index 2511216b138..13db7edb3cc 100644 --- a/packages/daemon/src/server/__tests__/request-router-repair-expired.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-repair-expired.test.ts @@ -38,7 +38,6 @@ function makeHandler(prefix: string) { sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); return { sessionStore, handler }; } diff --git a/packages/daemon/src/server/__tests__/request-router-replay-env.test.ts b/packages/daemon/src/server/__tests__/request-router-replay-env.test.ts index ee3fbaa1a41..5420ee32e53 100644 --- a/packages/daemon/src/server/__tests__/request-router-replay-env.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-replay-env.test.ts @@ -21,7 +21,6 @@ function createHarness() { sessionStore: makeSessionStore('agent-device-router-replay-env-store-'), leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }), }; } diff --git a/packages/daemon/src/server/__tests__/request-router-replay-plugin.test.ts b/packages/daemon/src/server/__tests__/request-router-replay-plugin.test.ts index 4eb868f99f5..1855bebec19 100644 --- a/packages/daemon/src/server/__tests__/request-router-replay-plugin.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-replay-plugin.test.ts @@ -34,7 +34,6 @@ async function fixture(storeEnv?: NodeJS.ProcessEnv) { sessionStore: store, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways({ local: discover }), - trackDownloadableArtifact: () => 'artifact-id', }); return { registry, discover, handler, store }; } diff --git a/packages/daemon/src/server/__tests__/request-router-replay-scope.test.ts b/packages/daemon/src/server/__tests__/request-router-replay-scope.test.ts index 53a778bb0d1..e8421aa4414 100644 --- a/packages/daemon/src/server/__tests__/request-router-replay-scope.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-replay-scope.test.ts @@ -105,7 +105,6 @@ test.each([false, true])( { version: 1, capabilities: { deny: ['device-shutdown'] } }, path.join(root, 'policy.json'), ), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ token: 'test-token', @@ -145,7 +144,6 @@ test('replay runs active-session actions inside the parent request provider scop deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), requestPlatformProviders: providerScopes.providers, - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ @@ -187,7 +185,6 @@ test('replay routes session-changing actions through the full request path', asy deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), requestPlatformProviders: providerScopes.providers, - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ @@ -224,7 +221,6 @@ test('session list includes a cwd-scoped session opened by replay', async () => leaseRegistry: new LeaseRegistry(), deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const replayResponse = await handler({ @@ -288,7 +284,6 @@ test('fresh replay retains a dynamically selected device through finalization', leaseRegistry, deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const replayResponse = handler({ token: 'test-token', @@ -339,7 +334,6 @@ test('test runs a one-case suite whose script leaves a session open, passes, and leaseRegistry: new LeaseRegistry(), deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler({ diff --git a/packages/daemon/src/server/__tests__/request-router-response-level.test.ts b/packages/daemon/src/server/__tests__/request-router-response-level.test.ts index 0e3d6cc4df5..d3a0c4dae91 100644 --- a/packages/daemon/src/server/__tests__/request-router-response-level.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-response-level.test.ts @@ -76,7 +76,7 @@ function makeHandler() { sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', + // Both subjects reach bound runtimes now — `app-switcher` through R56 and `scroll` through // R53 — so the handler needs an owner admitting `appSwitcher` and `scrollDirection` alike. deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, diff --git a/packages/daemon/src/server/__tests__/request-router-screenshot.test.ts b/packages/daemon/src/server/__tests__/request-router-screenshot.test.ts index 192e341f11f..b1364edbfb5 100644 --- a/packages/daemon/src/server/__tests__/request-router-screenshot.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-screenshot.test.ts @@ -95,7 +95,6 @@ function screenshotRouter( leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: runtime.gateway, - trackDownloadableArtifact: () => 'artifact-id', }); return { handler, sessionStore, runtime }; } @@ -253,7 +252,6 @@ test('router serializes concurrent commands for the same device across sessions' leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: runtime.gateway, - trackDownloadableArtifact: () => 'artifact-id', }); const screenshotRequest = handler({ @@ -685,7 +683,6 @@ function sessionlessScreenshotHandler(prefix: string) { local: async () => [ANDROID_EMULATOR], }), deviceRuntimeGateway: runtime.gateway, - trackDownloadableArtifact: () => 'artifact-id', }); return { handler, runtime }; } diff --git a/packages/daemon/src/server/__tests__/request-router-selection.test.ts b/packages/daemon/src/server/__tests__/request-router-selection.test.ts index 9f790b0f469..374989d5862 100644 --- a/packages/daemon/src/server/__tests__/request-router-selection.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-selection.test.ts @@ -65,7 +65,6 @@ function selectionHandler( }), }, }), - trackDownloadableArtifact: () => 'artifact-id', }); return { handler, sessionStore, inspectFacts }; } diff --git a/packages/daemon/src/server/__tests__/request-router-session-address.test.ts b/packages/daemon/src/server/__tests__/request-router-session-address.test.ts index 6a893614633..b88b1d15756 100644 --- a/packages/daemon/src/server/__tests__/request-router-session-address.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-session-address.test.ts @@ -71,7 +71,6 @@ function createHandler(sessionStore: ReturnType) { leaseRegistry: new LeaseRegistry(), deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); } diff --git a/packages/daemon/src/server/__tests__/request-router-typed-error.test.ts b/packages/daemon/src/server/__tests__/request-router-typed-error.test.ts index 8d33a8909ab..64e19fcf19e 100644 --- a/packages/daemon/src/server/__tests__/request-router-typed-error.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-typed-error.test.ts @@ -73,7 +73,6 @@ function makeHandler(sessionStore = makeSessionStore('agent-device-router-typed- leaseRegistry: new LeaseRegistry(), deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }), }; } diff --git a/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts b/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts index 4d79e2c4ade..61d3480f211 100644 --- a/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts @@ -119,7 +119,6 @@ test.each(['batch', 'replay'] as const)( }, }, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const pending = names.map((name) => handler(freshWebRequest(command, name, replayPath))); // A request that ends before it binds releases the other one's wait, so its failure reaches @@ -152,7 +151,6 @@ function createOpenHandler( leaseRegistry, deviceRuntimeGateway, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); } @@ -167,6 +165,81 @@ function openWebRequest(session: string): DaemonRequest { }; } +test('remote web open is refused before a browser runtime binds', async () => { + mockResolveTargetDevice.mockImplementation(webSessionResolution); + const store = makeSessionStore('agent-device-remote-web-denied-'); + let binds = 0; + const handler = createOpenHandler(store, new LeaseRegistry(), { + ...lifecycleDeviceRuntimeGateway, + bind: async (request) => { + binds += 1; + return await lifecycleDeviceRuntimeGateway.bind(request); + }, + }); + + const result = await handler({ + ...openWebRequest('remote-web'), + internal: { publicNetworkOnly: true }, + }); + expect(result).toMatchObject({ + ok: false, + error: { + code: 'UNSUPPORTED_OPERATION', + details: { reason: 'remote_web_browser_unconfined' }, + }, + }); + expect(binds).toBe(0); + expect(store.toArray()).toEqual([]); +}); + +test('remote requests cannot use an existing web session without a platform flag', async () => { + mockResolveTargetDevice.mockImplementation(webSessionResolution); + const store = makeSessionStore('agent-device-remote-web-existing-'); + store.publish('existing-web', makeSession('existing-web', { device: WEB_DESKTOP_DEVICE })); + let binds = 0; + const handler = createOpenHandler(store, new LeaseRegistry(), { + ...lifecycleDeviceRuntimeGateway, + bind: async (request) => { + binds += 1; + return await lifecycleDeviceRuntimeGateway.bind(request); + }, + }); + + const result = await handler({ + token: 'test-token', + session: 'existing-web', + command: 'snapshot', + positionals: [], + flags: {}, + meta: { requestId: 'remote-existing-web', sessionExplicit: true }, + internal: { publicNetworkOnly: true }, + }); + expect(result).toMatchObject({ + ok: false, + error: { details: { reason: 'remote_web_browser_unconfined' } }, + }); + expect(binds).toBe(0); +}); + +test('remote close can release an existing web session', async () => { + mockResolveTargetDevice.mockImplementation(webSessionResolution); + const store = makeSessionStore('agent-device-remote-web-close-'); + store.publish('existing-web', makeSession('existing-web', { device: WEB_DESKTOP_DEVICE })); + const handler = createOpenHandler(store); + + const result = await handler({ + token: 'test-token', + session: 'existing-web', + command: 'close', + positionals: [], + flags: {}, + meta: { requestId: 'remote-close-web', sessionExplicit: true }, + internal: { publicNetworkOnly: true }, + }); + expect(result).toMatchObject({ ok: true }); + expect(store.get('existing-web')).toBeUndefined(); +}); + test('implicit web sessions isolate workspaces and retain their device on follow-up requests', async () => { mockResolveTargetDevice.mockImplementation(webSessionResolution); const claimsDir = mkdtempForTestSync('agent-device-web-workspace-claims-'); @@ -295,7 +368,6 @@ test.each(['batch', 'replay'] as const)( }, }, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const response = await handler(freshWebRequest(command, '', replayPath)); diff --git a/packages/daemon/src/server/__tests__/request-save-script-policy.test.ts b/packages/daemon/src/server/__tests__/request-save-script-policy.test.ts index 10d75bcb46c..7245745fe7a 100644 --- a/packages/daemon/src/server/__tests__/request-save-script-policy.test.ts +++ b/packages/daemon/src/server/__tests__/request-save-script-policy.test.ts @@ -142,7 +142,6 @@ test.each([ deviceInventoryGateways: createTestDeviceInventoryGateways({ local: async () => [ANDROID_EMULATOR], }), - trackDownloadableArtifact: () => 'artifact-id', }); const platform = Object.getOwnPropertyDescriptor(process, 'platform')!; Object.defineProperty(process, 'platform', { value: 'win32' }); diff --git a/packages/daemon/src/server/__tests__/request-save-script-transports.test.ts b/packages/daemon/src/server/__tests__/request-save-script-transports.test.ts index 04c519add14..5f083ac1494 100644 --- a/packages/daemon/src/server/__tests__/request-save-script-transports.test.ts +++ b/packages/daemon/src/server/__tests__/request-save-script-transports.test.ts @@ -87,7 +87,6 @@ function setup(): Harness { sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); return { root, sessionStore, session, handleRequest }; } diff --git a/packages/daemon/src/server/__tests__/resumable-upload.test.ts b/packages/daemon/src/server/__tests__/resumable-upload.test.ts index b6e8c44e8b6..554158bf416 100644 --- a/packages/daemon/src/server/__tests__/resumable-upload.test.ts +++ b/packages/daemon/src/server/__tests__/resumable-upload.test.ts @@ -23,7 +23,10 @@ function acceptedWrite(): { promise: Promise; resolve: () => void } { } test('finalizing an unknown upload reports expiry with a recovery hint', async () => { - const error = await finalizeResumableUpload('missing-upload-id').then( + const error = await finalizeResumableUpload('missing-upload-id', { + tenantId: undefined, + leaseVerifier: null, + }).then( () => null, (error: unknown) => error, ); @@ -35,11 +38,34 @@ test('finalizing an unknown upload reports expiry with a recovery hint', async ( assert.equal(typeof appError.details?.hint, 'string'); }); +test('resumable upload refuses another producer without consuming the ticket', async () => { + const bytes = Buffer.from('leased-upload'); + const owner = { tenantId: 'tenant-a', leaseVerifier: 'producing-lease' }; + const uploadId = beginResumableUpload({ ...uploadOptions(bytes), owner }).uploadId; + await assert.rejects( + receiveResumableUploadChunk({ + uploadId, + owner: { ...owner, leaseVerifier: null }, + req: request(bytes), + }), + /belongs to a device lease/, + ); + await receiveResumableUploadChunk({ uploadId, owner, req: request(bytes) }); + await assert.rejects( + finalizeResumableUpload(uploadId, { ...owner, tenantId: 'tenant-b' }), + /belongs to a device lease/, + ); + const finalized = await finalizeResumableUpload(uploadId, owner); + assert.equal(fs.readFileSync(finalized.artifactPath, 'utf8'), 'leased-upload'); + 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; await assert.rejects( receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: request(Buffer.from('ABC'), { 'content-range': 'bytes 0-1/5' }), }), @@ -47,16 +73,21 @@ test('oversized ranged chunks roll back atomically and can be retried and finali ); assert.deepEqual( await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: request(Buffer.from('AB'), { 'content-range': 'bytes 0-1/5' }), }), { complete: false, offset: 2 }, ); await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: request(Buffer.from('CDE'), { 'content-range': 'bytes 2-4/5' }), }); - const finalized = await finalizeResumableUpload(uploadId); + const finalized = await finalizeResumableUpload(uploadId, { + tenantId: undefined, + leaseVerifier: null, + }); try { assert.equal(fs.readFileSync(finalized.artifactPath, 'utf8'), 'ABCDE'); } finally { @@ -82,9 +113,16 @@ test('finalize extracts a gzip-compressed app bundle upload', async () => { platform: 'ios', contentType: 'application/gzip', }).uploadId; - await receiveResumableUploadChunk({ uploadId, req: request(archive) }); + await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, + uploadId, + req: request(archive), + }); - const finalized = await finalizeResumableUpload(uploadId); + const finalized = await finalizeResumableUpload(uploadId, { + tenantId: undefined, + leaseVerifier: null, + }); try { assert.equal( fs.readFileSync(path.join(finalized.artifactPath, 'payload.txt'), 'utf8'), @@ -101,9 +139,19 @@ test('finalize extracts a gzip-compressed app bundle upload', async () => { test('an early finalize keeps the upload resumable', async () => { const bytes = Buffer.from('resume'); const uploadId = beginUpload(bytes).uploadId; - await assert.rejects(finalizeResumableUpload(uploadId), /incomplete/i); - await receiveResumableUploadChunk({ uploadId, req: request(bytes) }); - const finalized = await finalizeResumableUpload(uploadId); + await assert.rejects( + finalizeResumableUpload(uploadId, { tenantId: undefined, leaseVerifier: null }), + /incomplete/i, + ); + await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, + uploadId, + req: request(bytes), + }); + const finalized = await finalizeResumableUpload(uploadId, { + tenantId: undefined, + leaseVerifier: null, + }); fs.rmSync(finalized.tempDir, { recursive: true, force: true }); }); @@ -112,8 +160,16 @@ test('per-ticket operations serialize while an earlier chunk is paused', async ( const uploadId = beginUpload(bytes).uploadId; const first = requestStream({ 'content-range': 'bytes 0-1/4' }); const second = requestStream({ 'content-range': 'bytes 2-3/4' }); - const firstResult = receiveResumableUploadChunk({ uploadId, req: first }); - const secondResult = receiveResumableUploadChunk({ uploadId, req: second }); + const firstResult = receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, + uploadId, + req: first, + }); + const secondResult = receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, + uploadId, + req: second, + }); second.end('CD'); let secondSettled = false; void secondResult.finally(() => { @@ -124,7 +180,10 @@ test('per-ticket operations serialize while an earlier chunk is paused', async ( first.end('AB'); assert.deepEqual(await firstResult, { complete: false, offset: 2 }); assert.deepEqual(await secondResult, { complete: true, offset: 4 }); - const finalized = await finalizeResumableUpload(uploadId); + const finalized = await finalizeResumableUpload(uploadId, { + tenantId: undefined, + leaseVerifier: null, + }); fs.rmSync(finalized.tempDir, { recursive: true, force: true }); }); @@ -134,12 +193,57 @@ test('expiry aborts an active receive and invalidates the ticket after rollback' const bytes = Buffer.from('AB'); const uploadId = beginUpload(bytes).uploadId; const body = requestStream(); - const receiving = receiveResumableUploadChunk({ uploadId, req: body }); + const receiving = receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, + uploadId, + req: body, + }); body.write('A'); await vi.advanceTimersByTimeAsync(5 * 60 * 1000); await assert.rejects(receiving, /expired/i); - await assert.rejects(finalizeResumableUpload(uploadId), /not found or expired/i); + await assert.rejects( + finalizeResumableUpload(uploadId, { tenantId: undefined, leaseVerifier: null }), + /not found or expired/i, + ); + } finally { + vi.useRealTimers(); + } +}); + +test('expiry owns staged removal when active receive rollback fails', async () => { + vi.useFakeTimers(); + const accepted = acceptedWrite(); + const truncate = vi.spyOn(fs.promises, 'truncate').mockRejectedValueOnce(new Error('busy')); + const remove = vi.spyOn(fs.promises, 'rm').mockRejectedValueOnce(new Error('busy')); + const retry = vi.spyOn(fs, 'rmSync'); + const uploadId = beginUpload(Buffer.from('AB')).uploadId; + const body = requestStream(); + const receiving = receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, + uploadId, + req: body, + onAcceptedBytes: accepted.resolve, + }); + const rolledBack = assert.rejects( + receiving, + (error: unknown) => + error instanceof AppError && error.details?.reason === 'UPLOAD_ROLLBACK_FAILED', + ); + try { + body.write('A'); + await accepted.promise; + await vi.advanceTimersByTimeAsync(5 * 60 * 1000); + await rolledBack; + await vi.advanceTimersByTimeAsync(0); + assert.equal(truncate.mock.calls.length, 1); + assert.equal(remove.mock.calls.length, 1); + assert.equal(retry.mock.calls.length, 0); + await vi.advanceTimersByTimeAsync(30_000); + assert.equal(retry.mock.calls.length, 1); } finally { + body.destroy(); + await vi.advanceTimersByTimeAsync(30_000); + vi.restoreAllMocks(); vi.useRealTimers(); } }); @@ -153,6 +257,7 @@ test('an ignored out-of-order chunk does not extend upload expiry', async () => assert.deepEqual( await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: request(Buffer.from('B'), { 'content-range': 'bytes 1-1/2' }), }), @@ -160,7 +265,10 @@ test('an ignored out-of-order chunk does not extend upload expiry', async () => ); await vi.advanceTimersByTimeAsync(60 * 1000); - await assert.rejects(finalizeResumableUpload(uploadId), /not found or expired/i); + await assert.rejects( + finalizeResumableUpload(uploadId, { tenantId: undefined, leaseVerifier: null }), + /not found or expired/i, + ); } finally { await vi.advanceTimersByTimeAsync(5 * 60 * 1000); vi.useRealTimers(); @@ -173,18 +281,26 @@ test('an ignored un-ranged retry does not extend upload expiry', async () => { const bytes = Buffer.from('ABC'); const uploadId = beginUpload(bytes).uploadId; await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: request(Buffer.from('A'), { 'content-range': 'bytes 0-0/3' }), }); await vi.advanceTimersByTimeAsync(4 * 60 * 1000); assert.deepEqual( - await receiveResumableUploadChunk({ uploadId, req: request(Buffer.from('A')) }), + await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, + uploadId, + req: request(Buffer.from('A')), + }), { complete: false, offset: 1 }, ); await vi.advanceTimersByTimeAsync(60 * 1000); - await assert.rejects(finalizeResumableUpload(uploadId), /not found or expired/i); + await assert.rejects( + finalizeResumableUpload(uploadId, { tenantId: undefined, leaseVerifier: null }), + /not found or expired/i, + ); } finally { await vi.advanceTimersByTimeAsync(5 * 60 * 1000); vi.useRealTimers(); @@ -201,6 +317,7 @@ test('accepted body progress renews the ticket idle lifetime mid-chunk', async ( const uploadId = beginResumableUpload(options).uploadId; let accepted = acceptedWrite(); const receiving = receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: body, onAcceptedBytes: () => accepted.resolve(), @@ -224,7 +341,10 @@ test('accepted body progress renews the ticket idle lifetime mid-chunk', async ( } // Idle after the last accepted byte: the ticket expires on schedule. await vi.advanceTimersByTimeAsync(5 * 60 * 1000 + 1); - await assert.rejects(finalizeResumableUpload(uploadId), /not found or expired/i); + await assert.rejects( + finalizeResumableUpload(uploadId, { tenantId: undefined, leaseVerifier: null }), + /not found or expired/i, + ); } finally { vi.useRealTimers(); } @@ -236,8 +356,15 @@ test('finalize is not expired by the idle timer during its post-write checks', a const bytes = Buffer.from('AB'); const options = uploadOptions(bytes); const uploadId = beginResumableUpload(options).uploadId; - await receiveResumableUploadChunk({ uploadId, req: request(bytes) }); - const finalizing = finalizeResumableUpload(uploadId); + await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, + uploadId, + req: request(bytes), + }); + const finalizing = finalizeResumableUpload(uploadId, { + tenantId: undefined, + leaseVerifier: null, + }); // The idle timer armed at the last accepted chunk must not fire mid-finalize: // past the deadline the ticket still resolves to the finalizing entry. await vi.advanceTimersByTimeAsync(5 * 60 * 1000 + 1); @@ -248,7 +375,10 @@ test('finalize is not expired by the idle timer during its post-write checks', a } finally { fs.rmSync(finalized.tempDir, { recursive: true, force: true }); } - await assert.rejects(finalizeResumableUpload(uploadId), /not found or expired/i); + await assert.rejects( + finalizeResumableUpload(uploadId, { tenantId: undefined, leaseVerifier: null }), + /not found or expired/i, + ); } finally { vi.useRealTimers(); } @@ -262,9 +392,15 @@ test('an incomplete finalize leaves the original idle lifetime intact', async () await vi.advanceTimersByTimeAsync(4 * 60 * 1000); // The incomplete finalize is not terminal and must not disarm the idle timer: // the ticket still expires at the original deadline, 5 minutes after creation. - await assert.rejects(finalizeResumableUpload(uploadId), /incomplete/i); + await assert.rejects( + finalizeResumableUpload(uploadId, { tenantId: undefined, leaseVerifier: null }), + /incomplete/i, + ); await vi.advanceTimersByTimeAsync(60 * 1000 + 1); - await assert.rejects(finalizeResumableUpload(uploadId), /not found or expired/i); + await assert.rejects( + finalizeResumableUpload(uploadId, { tenantId: undefined, leaseVerifier: null }), + /not found or expired/i, + ); } finally { vi.useRealTimers(); } @@ -281,6 +417,7 @@ test('an aborted ingress signal maps to its owned typed reason and rolls back th const controller = new AbortController(); const body = requestStream({ 'content-range': 'bytes 0-3/4' }); const receiving = receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: body, signal: controller.signal, @@ -305,12 +442,16 @@ test('an aborted ingress signal maps to its owned typed reason and rolls back th // a full retry completes the upload. assert.deepEqual( await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: request(bytes, { 'content-range': 'bytes 0-3/4' }), }), { complete: true, offset: 4 }, ); - const finalized = await finalizeResumableUpload(uploadId); + const finalized = await finalizeResumableUpload(uploadId, { + tenantId: undefined, + leaseVerifier: null, + }); try { assert.equal(fs.readFileSync(finalized.artifactPath, 'utf8'), 'ABCD'); } finally { @@ -328,6 +469,7 @@ test('an earlier classified pipeline failure survives a later abort of the same const body = requestStream({ 'content-range': 'bytes 0-0/2' }); const accepted = acceptedWrite(); const receiving = receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: body, signal: controller.signal, @@ -364,13 +506,21 @@ test('an ingress owner aborted while finalize waits in the admission queue owns const uploadId = beginUpload(bytes).uploadId; // Occupy the serialized admission queue with a receive that stays open. const blocker = requestStream({ 'content-range': 'bytes 0-1/2' }); - const receiving = receiveResumableUploadChunk({ uploadId, req: blocker }); + const receiving = receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, + uploadId, + req: blocker, + }); blocker.write('A'); await flushIO(); const controller = new AbortController(); - const finalizing = finalizeResumableUpload(uploadId, undefined, { - signal: controller.signal, - }).then( + const finalizing = finalizeResumableUpload( + uploadId, + { tenantId: undefined, leaseVerifier: null }, + { + signal: controller.signal, + }, + ).then( () => null, (error: unknown) => error, ); @@ -390,7 +540,10 @@ test('an ingress owner aborted while finalize waits in the admission queue owns assert.equal(error?.details?.reason, 'transfer_ingress_deadline_exceeded'); // Ownership is preserved: the aborted admission did not close the ticket, so a // fresh finalize without the owner still succeeds (recovery). - const finalized = await finalizeResumableUpload(uploadId); + const finalized = await finalizeResumableUpload(uploadId, { + tenantId: undefined, + leaseVerifier: null, + }); try { assert.equal(fs.readFileSync(finalized.artifactPath, 'utf8'), 'AB'); } finally { @@ -405,11 +558,16 @@ test('an aborted queued PUT releases at once while later work still waits for th const bytes = Buffer.from('AB'); const uploadId = beginUpload(bytes).uploadId; const blocker = requestStream({ 'content-range': 'bytes 0-1/2' }); - const receiving = receiveResumableUploadChunk({ uploadId, req: blocker }); + const receiving = receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, + uploadId, + req: blocker, + }); blocker.write('A'); await flushIO(); const controller = new AbortController(); const queued = receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: requestStream({ 'content-range': 'bytes 0-1/2' }), signal: controller.signal, @@ -417,7 +575,10 @@ test('an aborted queued PUT releases at once while later work still waits for th () => null, (error: unknown) => error, ); - const finalizing = finalizeResumableUpload(uploadId); + const finalizing = finalizeResumableUpload(uploadId, { + tenantId: undefined, + leaseVerifier: null, + }); let finalizeSettled = false; void finalizing.then( () => { @@ -472,6 +633,7 @@ test('a chunk cancelled during its final offset check rolls back and never advan }) as typeof fs.promises.stat); try { const error = (await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: request(bytes, { 'content-range': 'bytes 0-3/4' }), signal: controller.signal, @@ -488,12 +650,16 @@ test('a chunk cancelled during its final offset check rolls back and never advan // The cancelled chunk rolled back: a full retry from offset zero completes. assert.deepEqual( await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: request(bytes, { 'content-range': 'bytes 0-3/4' }), }), { complete: true, offset: 4 }, ); - const finalized = await finalizeResumableUpload(uploadId); + const finalized = await finalizeResumableUpload(uploadId, { + tenantId: undefined, + leaseVerifier: null, + }); fs.rmSync(finalized.tempDir, { recursive: true, force: true }); }); @@ -506,9 +672,17 @@ test('an ingress owner aborted mid-hash cancels the finalize with its typed reas // synthetic owner can fire mid-hash. const bytes = Buffer.alloc(64 * 1024 * 1024, 0x61); const uploadId = beginUpload(bytes).uploadId; - await receiveResumableUploadChunk({ uploadId, req: request(bytes) }); + await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, + uploadId, + req: request(bytes), + }); const controller = new AbortController(); - const finalizing = finalizeResumableUpload(uploadId, undefined, { signal: controller.signal }); + const finalizing = finalizeResumableUpload( + uploadId, + { tenantId: undefined, leaseVerifier: null }, + { signal: controller.signal }, + ); await new Promise((resolve) => setTimeout(resolve, 5)); controller.abort( new AppError('COMMAND_FAILED', 'Upload transfer deadline exceeded', { @@ -525,7 +699,10 @@ test('an ingress owner aborted mid-hash cancels the finalize with its typed reas assert.equal(error?.details?.reason, 'transfer_ingress_deadline_exceeded'); // Semantic cleanup: the terminal failure closed the ticket and removed its temp // dir, so a retry reports expiry and the temp root is empty. - await assert.rejects(finalizeResumableUpload(uploadId), /not found or expired/i); + await assert.rejects( + finalizeResumableUpload(uploadId, { tenantId: undefined, leaseVerifier: null }), + /not found or expired/i, + ); assert.deepEqual(fs.readdirSync(tempRoot), []); } finally { if (previousTmpDir === undefined) delete process.env.TMPDIR; @@ -537,11 +714,19 @@ test('an ingress owner aborted mid-hash cancels the finalize with its typed reas test('finalize with a live ingress signal succeeds through the owned post-body phases', async () => { const bytes = Buffer.from('OWNED'); const uploadId = beginUpload(bytes).uploadId; - await receiveResumableUploadChunk({ uploadId, req: request(bytes) }); - const controller = new AbortController(); - const finalized = await finalizeResumableUpload(uploadId, undefined, { - signal: controller.signal, + await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, + uploadId, + req: request(bytes), }); + const controller = new AbortController(); + const finalized = await finalizeResumableUpload( + uploadId, + { tenantId: undefined, leaseVerifier: null }, + { + signal: controller.signal, + }, + ); try { assert.equal(controller.signal.aborted, false); assert.equal(fs.readFileSync(finalized.artifactPath, 'utf8'), 'OWNED'); @@ -557,6 +742,7 @@ test('idempotent preflight does not extend upload expiry', async () => { const options = uploadOptions(bytes); const uploadId = beginResumableUpload(options).uploadId; await receiveResumableUploadChunk({ + owner: { tenantId: undefined, leaseVerifier: null }, uploadId, req: request(Buffer.from('A'), { 'content-range': 'bytes 0-0/2' }), }); @@ -565,8 +751,80 @@ test('idempotent preflight does not extend upload expiry', async () => { assert.equal(beginResumableUpload(options).uploadId, uploadId); await vi.advanceTimersByTimeAsync(60 * 1000); - await assert.rejects(finalizeResumableUpload(uploadId), /not found or expired/i); + await assert.rejects( + finalizeResumableUpload(uploadId, { tenantId: undefined, leaseVerifier: null }), + /not found or expired/i, + ); + } finally { + await vi.advanceTimersByTimeAsync(5 * 60 * 1000); + vi.useRealTimers(); + } +}); + +test('upload preflights reserve tenant capacity and preserve idempotent tickets', async () => { + vi.useFakeTimers(); + try { + const options = { + ...uploadOptions(Buffer.alloc(0)), + owner: { tenantId: 'quota-tenant', leaseVerifier: null }, + sizeBytes: 2 * 1024 * 1024 * 1024, + }; + const first = beginResumableUpload(options); + beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() }); + beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() }); + assert.equal(beginResumableUpload(options).uploadId, first.uploadId); + assert.throws( + () => beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() }), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'UPLOAD_CAPACITY_EXCEEDED', + ); + } finally { + await vi.advanceTimersByTimeAsync(5 * 60 * 1000); + vi.useRealTimers(); + } +}); + +test('expired upload keeps staged capacity through a failed removal and retry', async () => { + vi.useFakeTimers(); + const cleanupStarted = acceptedWrite(); + const cleanupAllowed = acceptedWrite(); + const cleanupFinished = acceptedWrite(); + vi.spyOn(fs.promises, 'rm').mockImplementationOnce(async () => { + cleanupStarted.resolve(); + await cleanupAllowed.promise; + cleanupFinished.resolve(); + throw Object.assign(new Error('staging directory is busy'), { code: 'EBUSY' }); + }); + try { + const options = { + ...uploadOptions(Buffer.alloc(0)), + owner: { tenantId: 'expiry-capacity-tenant', leaseVerifier: null }, + sizeBytes: 2 * 1024 * 1024 * 1024, + }; + beginResumableUpload(options); + await vi.advanceTimersByTimeAsync(60 * 1000); + beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() }); + beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() }); + await vi.advanceTimersByTimeAsync(4 * 60 * 1000); + await cleanupStarted.promise; + const beginNext = () => + beginResumableUpload({ ...options, uploadAttemptId: crypto.randomUUID() }); + const assertCapacityHeld = () => + assert.throws( + beginNext, + (error: unknown) => + error instanceof AppError && error.details?.reason === 'UPLOAD_CAPACITY_EXCEEDED', + ); + assertCapacityHeld(); + cleanupAllowed.resolve(); + await cleanupFinished.promise; + await vi.advanceTimersByTimeAsync(0); + assertCapacityHeld(); + await vi.advanceTimersByTimeAsync(30_000); + beginNext(); } finally { + cleanupAllowed.resolve(); + vi.restoreAllMocks(); await vi.advanceTimersByTimeAsync(5 * 60 * 1000); vi.useRealTimers(); } @@ -578,6 +836,7 @@ function beginUpload(bytes: Buffer): ReturnType { function uploadOptions(bytes: Buffer): Parameters[0] { return { + owner: { tenantId: undefined, leaseVerifier: null }, baseUrl: 'http://127.0.0.1:1234', tokenHeaders: {}, uploadAttemptId: crypto.randomUUID(), diff --git a/packages/daemon/src/server/__tests__/upload-http-capacity.test.ts b/packages/daemon/src/server/__tests__/upload-http-capacity.test.ts new file mode 100644 index 00000000000..a90fd43643d --- /dev/null +++ b/packages/daemon/src/server/__tests__/upload-http-capacity.test.ts @@ -0,0 +1,190 @@ +import assert from 'node:assert/strict'; +import { createHash, randomUUID } from 'node:crypto'; +import { test } from 'vitest'; +import { + MAX_ARCHIVE_EXPANDED_BYTES, + MAX_ARTIFACT_COMPRESSED_BYTES, +} from '@agent-device/host-kit/archive'; +import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; +import { createDaemonProxyServer } from '@agent-device/proxy'; +import { + closeLoopbackServer, + listenOnLoopback, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { cleanupUploadedArtifact } from '../../resources/artifact-tracking.ts'; +import { createDaemonHttpServer } from '../http/http-server.ts'; +import { reserveUploadCapacity } from '../upload-capacity.ts'; + +test('the staging budget admits one maximum-size archive and its expanded contents', () => { + const reservation = reserveUploadCapacity('archive-tenant', MAX_ARTIFACT_COMPRESSED_BYTES); + try { + assert.doesNotThrow(() => reservation.addBytes(MAX_ARCHIVE_EXPANDED_BYTES)); + } finally { + reservation.release(); + } +}); + +test('legacy uploads use the same staged capacity over direct and proxied HTTP', async (t) => { + if (await skipWhenLoopbackUnavailable(t, 'upload capacity')) return; + const env = { ...process.env }; + delete env.AGENT_DEVICE_HTTP_AUTH_HOOK; + const runtime = createRuntimeStateHandle(); + const server = await runtime.run(() => + createDaemonHttpServer({ + token: 'test-token', + env, + cwd: process.cwd(), + handleRequest: async () => ({ ok: true, data: {} }), + }), + ); + try { + const port = await listenOnLoopback(server); + const base = `http://127.0.0.1:${port}`; + const auth = { authorization: 'Bearer test-token', 'x-agent-device-tenant': 'tenant-a' }; + const emptyHash = createHash('sha256').update('').digest('hex'); + const declaredBytes = Buffer.byteLength('new-app'); + for (const [index, sizeBytes] of [ + MAX_ARTIFACT_COMPRESSED_BYTES, + MAX_ARTIFACT_COMPRESSED_BYTES, + MAX_ARTIFACT_COMPRESSED_BYTES - declaredBytes, + ].entries()) { + const preflight = await fetch(`${base}/upload/preflight`, { + method: 'POST', + headers: { ...auth, 'content-type': 'application/json' }, + body: JSON.stringify({ + sha256: emptyHash, + uploadAttemptId: randomUUID(), + fileName: `empty-${index}.apk`, + sizeBytes, + artifactType: 'file', + }), + }); + assert.equal(preflight.status, 200); + await preflight.json(); + } + + const uploadLegacy = (origin: string, token: string) => + fetch(`${origin}/upload`, { + method: 'POST', + headers: { + ...auth, + authorization: `Bearer ${token}`, + 'x-artifact-type': 'file', + 'x-artifact-filename': 'new.apk', + 'content-length': String(declaredBytes), + }, + body: 'new-app', + }); + const admittedWithDeclaredLength = await uploadLegacy(base, 'test-token'); + assert.equal(admittedWithDeclaredLength.status, 200); + const retainedId = ((await admittedWithDeclaredLength.json()) as { uploadId: string }).uploadId; + + const full = await uploadLegacy(base, 'test-token'); + assert.equal(full.status, 503); + const refusal = (await full.json()) as { reason?: string }; + assert.equal(refusal.reason, 'UPLOAD_CAPACITY_EXCEEDED'); + + runtime.run(() => cleanupUploadedArtifact(retainedId)); + const proxy = createDaemonProxyServer({ + upstreamBaseUrl: base, + upstreamToken: 'test-token', + clientToken: 'proxy-token', + }); + try { + const proxyPort = await listenOnLoopback(proxy); + const admittedThroughProxy = await uploadLegacy( + `http://127.0.0.1:${proxyPort}`, + 'proxy-token', + ); + assert.equal(admittedThroughProxy.status, 200); + const uploaded = (await admittedThroughProxy.json()) as { uploadId: string }; + assert.ok(uploaded.uploadId); + } finally { + await closeLoopbackServer(proxy); + } + } finally { + try { + await closeLoopbackServer(server); + } finally { + runtime.dispose(); + } + } +}); + +test('capacity refusals disclose the exhausted dimension and limit without utilization', () => { + const runtime = createRuntimeStateHandle(); + try { + runtime.run(() => { + assert.throws( + () => reserveUploadCapacity('tenant-a', 7 * 1024 ** 3), + (error: unknown) => { + assert.deepEqual((error as { details: unknown }).details, { + reason: 'UPLOAD_CAPACITY_EXCEEDED', + resource: 'staged-upload', + scope: 'tenant', + dimension: 'bytes', + limit: 6 * 1024 ** 3, + retriable: true, + }); + return true; + }, + ); + for (let i = 0; i < 32; i++) reserveUploadCapacity('tenant-a', 0); + assert.throws( + () => reserveUploadCapacity('tenant-a', 0), + (error: unknown) => { + assert.equal((error as { details: { dimension: string } }).details.dimension, 'count'); + return true; + }, + ); + }); + } finally { + runtime.dispose(); + } +}); + +test('chunked uploads charge shared bytes before the chunk reaches staging', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const runtime = createRuntimeStateHandle(); + const occupied = runtime.run(() => reserveUploadCapacity('tenant-a', 6 * 1024 ** 3 - 2)); + const env = { ...process.env }; + delete env.AGENT_DEVICE_HTTP_AUTH_HOOK; + const server = await runtime.run(() => + createDaemonHttpServer({ + token: 'test-token', + env, + cwd: process.cwd(), + handleRequest: async () => ({ ok: true }), + }), + ); + try { + const port = await listenOnLoopback(server); + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('abc')); + controller.close(); + }, + }); + const response = await fetch(`http://127.0.0.1:${port}/upload`, { + method: 'POST', + headers: { + authorization: 'Bearer test-token', + 'x-agent-device-tenant': 'tenant-a', + 'x-artifact-type': 'file', + 'x-artifact-filename': 'app.apk', + }, + body, + duplex: 'half', + } as RequestInit); + assert.equal(response.status, 503); + assert.equal( + ((await response.json()) as { reason: string }).reason, + 'UPLOAD_CAPACITY_EXCEEDED', + ); + } finally { + occupied.release(); + await closeLoopbackServer(server); + runtime.dispose(); + } +}); diff --git a/packages/daemon/src/server/artifact-archive.ts b/packages/daemon/src/server/artifact-archive.ts index 00eb3d6e9f5..b3e43c4a6d8 100644 --- a/packages/daemon/src/server/artifact-archive.ts +++ b/packages/daemon/src/server/artifact-archive.ts @@ -9,6 +9,7 @@ export async function extractTarInstallableArtifact(params: { platform: 'ios' | 'android'; expectedRootName?: string; signal?: AbortSignal; + reserveExpandedBytes?: (bytes: number) => void; }): Promise { params.signal?.throwIfAborted(); const outputRoot = path.join(params.tempDir, 'extracted'); @@ -23,6 +24,9 @@ export async function extractTarInstallableArtifact(params: { signal: params.signal, validateManifest: (manifest) => { rootName = resolveArchiveRootName(manifest, params.platform, params.expectedRootName); + params.reserveExpandedBytes?.( + manifest.reduce((bytes, entry) => bytes + (entry.kind === 'file' ? entry.size : 0), 0), + ); }, }); params.signal?.throwIfAborted(); diff --git a/packages/daemon/src/server/artifact-download.ts b/packages/daemon/src/server/artifact-download.ts index 2e34548d588..4f45df0eb57 100644 --- a/packages/daemon/src/server/artifact-download.ts +++ b/packages/daemon/src/server/artifact-download.ts @@ -20,7 +20,9 @@ export function createArtifactTempDir(requestId?: string): string { return fs.mkdtempSync(path.join(os.tmpdir(), `${TEMP_PREFIX}${scope}-`)); } -export function validateArtifactContentLength(rawLength: string | number | undefined): void { +export function validateArtifactContentLength( + rawLength: string | number | undefined, +): number | undefined { if (rawLength === undefined) return; const raw = String(rawLength); if (!/^\d+$/.test(raw)) { @@ -36,6 +38,7 @@ export function validateArtifactContentLength(rawLength: string | number | undef `Upload exceeds maximum size of ${MAX_ARTIFACT_COMPRESSED_BYTES} bytes`, ); } + return parsed; } function sanitizeRequestId(raw: string | undefined): string { diff --git a/packages/daemon/src/server/http-errors.ts b/packages/daemon/src/server/http-errors.ts index 72837fd8752..6d7d8434a7d 100644 --- a/packages/daemon/src/server/http-errors.ts +++ b/packages/daemon/src/server/http-errors.ts @@ -23,7 +23,9 @@ export function statusCodeForNormalizedError(error: { case 'COMMAND_FAILED': // A TTL registry cannot tell an expired id from one that never existed, // so a gone resource is 404 rather than 410. - return error.details?.reason === 'RESOURCE_EXPIRED' ? 404 : 500; + if (error.details?.reason === 'RESOURCE_EXPIRED') return 404; + if (error.details?.reason === 'UPLOAD_CAPACITY_EXCEEDED') return 503; + return 500; default: return 500; } diff --git a/packages/daemon/src/server/http/daemon-runtime.ts b/packages/daemon/src/server/http/daemon-runtime.ts index 3f57213f0ec..dcedca73431 100644 --- a/packages/daemon/src/server/http/daemon-runtime.ts +++ b/packages/daemon/src/server/http/daemon-runtime.ts @@ -1,3 +1,4 @@ +import { setStagedUploadCleanupDiagnostic } from '../../resources/artifact-tracking.ts'; import type { ExpiryProviderSettlement } from '../lease-session-end.ts'; import type { ComposeDaemonRuntimeDeps } from './daemon-runtime-deps.ts'; import { recoverAppLogResourcesAfterDaemonLock } from '@agent-device/capture-kit/app-log-resource-recovery'; @@ -18,7 +19,6 @@ import { resolveDaemonServerMode, type DaemonRuntimeOwnership, } from '@agent-device/daemon-contracts/daemon-resolution'; -import { trackDownloadableArtifact } from '../../resources/artifact-tracking.ts'; import { installProviderDeviceAdmission } from '../../core/provider-device-admission.ts'; import { loadDaemonPolicy, @@ -265,6 +265,13 @@ async function startDaemonRuntimeOnHost( : undefined; const sessionStore = new SessionStore(sessionsDir, host); + setStagedUploadCleanupDiagnostic((tempDir, error, retryDelayMs) => { + void emitDaemonDiagnostic(logPath, 'staged_upload_cleanup_deferred', { + tempDir, + error: String(error), + retryDelayMs, + }).catch(() => {}); + }); const deps = await options.composeDeps({ host, hostedAttachment: attachment?.hostedAttachment, @@ -415,7 +422,6 @@ async function startDaemonRuntimeOnHost( hostDiagnostics: deps.hostDiagnostics, screenRecordingAdmissionLedger, daemonPolicy, - trackDownloadableArtifact, // The facts the deps declare at the top level, offered to the router from that one place. deviceRuntimeGateway, claimRecoveryGateway: deps.claimRecoveryGateway, @@ -715,6 +721,7 @@ async function startDaemonRuntimeOnHost( startupRecovered, hostAdminEnabled: !attachment, admitAuxiliary, + sessionStore, leaseLifecycleProvider: deps.leaseLifecycleProvider, leaseRegistry, endSessionsForLease: async (leaseId) => await endSessionsForLease(leaseId, 'LEASE_RELEASED'), diff --git a/packages/daemon/src/server/http/http-rpc-methods.ts b/packages/daemon/src/server/http/http-rpc-methods.ts index 35b8f48eb4e..9cbc00ca816 100644 --- a/packages/daemon/src/server/http/http-rpc-methods.ts +++ b/packages/daemon/src/server/http/http-rpc-methods.ts @@ -190,22 +190,21 @@ function toReleaseMaterializedPathsDaemonRequest( if (!materializationId) { throw new AppError('INVALID_ARGS', 'Invalid params: materializationId is required'); } - return { - token: resolveToken(params, headers), - ...resolveRequestSessionAtIntake({ session: readStringParam(params, 'session') }), - command: 'release_materialized_paths', - positionals: [], - meta: { - requestId: readStringParam(params, 'requestId'), - // The install that retained the paths recorded this tenant as their owner. - tenantId: readTenantParam(params), - materializationId, + const leaseLabels = readLeaseLabelParams(params); + return withDisplacedLeaseClaims( + { + token: resolveToken(params, headers), + ...resolveRequestSessionAtIntake({ session: readStringParam(params, 'session') }), + command: 'release_materialized_paths', + positionals: [], + meta: { + requestId: readStringParam(params, 'requestId'), + ...leaseLabels.meta, + materializationId, + }, }, - }; -} - -function readTenantParam(params: Record): string | undefined { - return readStringParam(params, 'tenantId') ?? readStringParam(params, 'tenant'); + leaseLabels.displaced, + ); } const LEASE_LABEL_PARAMS = { diff --git a/packages/daemon/src/server/http/http-server-batch-maestro-trust.test.ts b/packages/daemon/src/server/http/http-server-batch-maestro-trust.test.ts index 14a21234a9d..e7fed3dcb58 100644 --- a/packages/daemon/src/server/http/http-server-batch-maestro-trust.test.ts +++ b/packages/daemon/src/server/http/http-server-batch-maestro-trust.test.ts @@ -99,7 +99,6 @@ test.for(remoteCases)( sessionStore: new SessionStore(path.join(root, 'sessions'), host), leaseRegistry, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: () => 'artifact-id', }); const hookPath = path.join(root, 'auth-hook.mjs'); if (origin === 'auth-hook') { diff --git a/packages/daemon/src/server/http/http-server-capture-publication.test.ts b/packages/daemon/src/server/http/http-server-capture-publication.test.ts index cee5470934b..47924310e61 100644 --- a/packages/daemon/src/server/http/http-server-capture-publication.test.ts +++ b/packages/daemon/src/server/http/http-server-capture-publication.test.ts @@ -21,7 +21,6 @@ import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { cleanupDownloadableArtifact, settleCommittedFileOutputs, - trackDownloadableArtifact, } from '../../resources/artifact-tracking.ts'; import { makeRecordRuntimeHarness } from '../../sessions/handlers/__tests__/record-runtime.fixtures.ts'; import { runBatchCommands } from '../../sessions/handlers/session-batch.ts'; @@ -53,7 +52,6 @@ test.each(['caller destination', 'remote placeholder', 'public remote', 'public return { displayRotation: 'landscape-left' }; }, }); - const legacyRegistration = vi.fn(trackDownloadableArtifact); const handler = createRequestHandler({ host: createTestHostEnvironment(), createCommandSurface: screenshotCommandSurface, @@ -63,7 +61,6 @@ test.each(['caller destination', 'remote placeholder', 'public remote', 'public leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: runtime.gateway, - trackDownloadableArtifact: legacyRegistration, }); await withHttp(handler, async (post, base) => { const capture = { command: 'screenshot', session: 'capture', positionals: [destination] }; @@ -104,7 +101,6 @@ test.each(['caller destination', 'remote placeholder', 'public remote', 'public localPath: '/client/first.png', }); expect(first.artifacts?.[0]).not.toHaveProperty('path'); - expect(legacyRegistration).not.toHaveBeenCalled(); const inventory = await fetch(`${base}/artifacts`, { headers: { authorization: 'Bearer test-token' }, }); @@ -170,7 +166,6 @@ test.each(['failure', 'cancellation'] as const)( }; }, }, - trackDownloadableArtifact, }); await withHttp(handler, async (post, base) => { const reply = post({ @@ -224,7 +219,6 @@ test('a leased screenshot uses the admitted tenant when the capture omits the te leaseRegistry, deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: screenshotRuntimeFixture().gateway, - trackDownloadableArtifact, }); await withHttp(handler, async (post, base) => { const shot = successfulData( @@ -425,7 +419,6 @@ test.each(['leased at start', 'unleased'])( sessionStore, leaseRegistry, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact, }); await withHttp(handler, async (post, base) => { const trace = (action: string, meta = {}) => 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 d71687d495a..a28899c0bef 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 @@ -101,9 +101,6 @@ test.each([ bind: async ({ device }) => await recordingBinding(device), shutdown: async () => {}, }, - trackDownloadableArtifact: () => { - throw new Error('Recording must be committed before request finalization'); - }, }); const hookPath = path.join(root, 'auth-hook.mjs'); fs.writeFileSync( 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..6b52cc323a7 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 @@ -77,7 +77,11 @@ test('HTTP install rejection leaves an uploaded artifact available', async (t) = fs.mkdirSync(tempDir); const artifactPath = path.join(tempDir, 'app.apk'); fs.writeFileSync(artifactPath, 'uploaded-apk'); - const uploadId = trackUploadedArtifact({ artifactPath, tempDir }); + const uploadId = trackUploadedArtifact({ + owner: { tenantId: undefined, leaseVerifier: null }, + artifactPath, + tempDir, + }); const sessionStore = new SessionStore(path.join(root, 'sessions'), host); const server = await createDaemonHttpServer({ token: 'test-token', @@ -105,7 +109,10 @@ test('HTTP install rejection leaves an uploaded artifact available', async (t) = assert.equal(response.status, 400); const body = (await response.json()) as { error?: { data?: { code?: string } } }; assert.equal(body.error?.data?.code, 'INVALID_ARGS'); - assert.equal(prepareUploadedArtifact(uploadId), artifactPath); + assert.equal( + prepareUploadedArtifact(uploadId, { tenantId: undefined, leaseVerifier: null }), + artifactPath, + ); assert.equal(fs.readFileSync(artifactPath, 'utf8'), 'uploaded-apk'); } finally { cleanupUploadedArtifact(uploadId); diff --git a/packages/daemon/src/server/http/http-server-perf-report.test.ts b/packages/daemon/src/server/http/http-server-perf-report.test.ts index 7b1daa67a74..45da715b97e 100644 --- a/packages/daemon/src/server/http/http-server-perf-report.test.ts +++ b/packages/daemon/src/server/http/http-server-perf-report.test.ts @@ -78,7 +78,6 @@ function reportFixture() { }; }, }, - trackDownloadableArtifact, }); const profilePath = path.join(root, 'retained.trace'); fs.mkdirSync(profilePath); diff --git a/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts b/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts index 90ca397eef1..0ac1181d076 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 @@ -596,7 +596,12 @@ test('Provider-backed integration daemon HTTP server resumes direct uploads befo const finalizeBody = (await finalize.json()) as { uploadId?: string }; trackedUploadId = finalizeBody.uploadId ?? ''; assert.equal(typeof trackedUploadId, 'string'); - assert.deepEqual(fs.readFileSync(prepareUploadedArtifact(trackedUploadId)), content); + assert.deepEqual( + fs.readFileSync( + prepareUploadedArtifact(trackedUploadId, { tenantId: undefined, leaseVerifier: null }), + ), + content, + ); } finally { if (trackedUploadId) cleanupUploadedArtifact(trackedUploadId); await closeLoopbackServer(server); @@ -668,7 +673,12 @@ test('Provider-backed integration daemon HTTP server isolates same-artifact uplo const secondFinalize = await finalizeUpload(port, second.uploadId); trackedUploadIds.push(secondFinalize); - assert.deepEqual(fs.readFileSync(prepareUploadedArtifact(secondFinalize)), content); + assert.deepEqual( + fs.readFileSync( + prepareUploadedArtifact(secondFinalize, { tenantId: undefined, leaseVerifier: null }), + ), + content, + ); const firstComplete = await fetch(first.uploadUrl, { method: 'PUT', @@ -682,7 +692,12 @@ test('Provider-backed integration daemon HTTP server isolates same-artifact uplo const firstFinalize = await finalizeUpload(port, first.uploadId); trackedUploadIds.push(firstFinalize); - assert.deepEqual(fs.readFileSync(prepareUploadedArtifact(firstFinalize)), content); + assert.deepEqual( + fs.readFileSync( + prepareUploadedArtifact(firstFinalize, { tenantId: undefined, leaseVerifier: null }), + ), + content, + ); } finally { for (const uploadId of trackedUploadIds) cleanupUploadedArtifact(uploadId); await closeLoopbackServer(server); diff --git a/packages/daemon/src/server/http/http-server-proxy-leased-output.test.ts b/packages/daemon/src/server/http/http-server-proxy-leased-output.test.ts index 4919428a94d..c8e4afde453 100644 --- a/packages/daemon/src/server/http/http-server-proxy-leased-output.test.ts +++ b/packages/daemon/src/server/http/http-server-proxy-leased-output.test.ts @@ -29,7 +29,6 @@ import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { cleanupDownloadableArtifact, listDownloadableArtifacts, - trackDownloadableArtifact, } from '../../resources/artifact-tracking.ts'; // One proxy token and one tenant label for every client, as a host with many sandboxes has. @@ -84,7 +83,6 @@ async function startProxiedDaemon() { leaseRegistry, deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: screenshotRuntimeFixture().gateway, - trackDownloadableArtifact, }); const daemon = await createDaemonHttpServer({ token: 'daemon-token', diff --git a/packages/daemon/src/server/http/http-server-proxy-reply-visibility.test.ts b/packages/daemon/src/server/http/http-server-proxy-reply-visibility.test.ts index b9761a67fa2..c592d255777 100644 --- a/packages/daemon/src/server/http/http-server-proxy-reply-visibility.test.ts +++ b/packages/daemon/src/server/http/http-server-proxy-reply-visibility.test.ts @@ -176,7 +176,6 @@ async function startProxiedDaemon() { }; }, }, - trackDownloadableArtifact: () => 'artifact-id', }); const daemon = await createDaemonHttpServer({ token: 'daemon-token', diff --git a/packages/daemon/src/server/http/http-server-proxy-rollback.test.ts b/packages/daemon/src/server/http/http-server-proxy-rollback.test.ts index f37811a93f9..f1d0fa978f1 100644 --- a/packages/daemon/src/server/http/http-server-proxy-rollback.test.ts +++ b/packages/daemon/src/server/http/http-server-proxy-rollback.test.ts @@ -152,7 +152,11 @@ test.for(['disconnect and resume', 'uninterrupted'] as const)( }); expect(finalize.status).toBe(200); tracked = ((await finalize.json()) as { uploadId: string }).uploadId; - expect(fs.readFileSync(prepareUploadedArtifact(tracked))).toEqual(content); + expect( + fs.readFileSync( + prepareUploadedArtifact(tracked, { tenantId: undefined, leaseVerifier: null }), + ), + ).toEqual(content); } finally { if (tracked) cleanupUploadedArtifact(tracked); await closeLoopbackServer(proxy); diff --git a/packages/daemon/src/server/http/http-server-proxy-session-lease.test.ts b/packages/daemon/src/server/http/http-server-proxy-session-lease.test.ts index 43b1229e8db..6e2a19222ac 100644 --- a/packages/daemon/src/server/http/http-server-proxy-session-lease.test.ts +++ b/packages/daemon/src/server/http/http-server-proxy-session-lease.test.ts @@ -106,7 +106,6 @@ async function startProxiedDaemon( local: async () => [IOS_SIMULATOR], }), deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, - trackDownloadableArtifact: () => 'artifact-id', }); const daemon = await createDaemonHttpServer({ token: 'daemon-token', diff --git a/packages/daemon/src/server/http/http-server-remote-output.test.ts b/packages/daemon/src/server/http/http-server-remote-output.test.ts index ae567a7b656..22b1b2b0486 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 @@ -33,7 +33,6 @@ import { cleanupDownloadableArtifact, listDownloadableArtifacts, settleCommittedFileOutputs, - trackDownloadableArtifact, } from '../../resources/artifact-tracking.ts'; import { makeRecordRuntimeHarness } from '../../sessions/handlers/__tests__/record-runtime.fixtures.ts'; import { localEnv, successfulData, withHttp } from './http-output.fixtures.ts'; @@ -174,7 +173,6 @@ test.each(['marker', 'auth-hook', 'batch'] as const)( leaseRegistry, deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: runtime.gateway, - trackDownloadableArtifact, }); const env = localEnv(); if (route === 'auth-hook') { @@ -387,7 +385,6 @@ test.each(['local', 'remote'] as const)( sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact, }); await withHttp(handler, async (post, base) => { const started = await post( @@ -434,7 +431,6 @@ test('nested remote dispatch normalizes host outputs again below HTTP', async () leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: runtime.gateway, - trackDownloadableArtifact, }); const response = await handler({ token: 'test-token', @@ -589,7 +585,6 @@ test.each([ }; }, }, - trackDownloadableArtifact, }); await withHttp(handler, async (post, baseUrl) => { const positionals = (action: string) => @@ -730,7 +725,6 @@ test('remote perf memory output reaches the runtime only as a session artifact a }; }, }, - trackDownloadableArtifact, }); await withHttp(handler, async (post, baseUrl) => { const body = await post({ @@ -744,8 +738,8 @@ test('remote perf memory output reaches the runtime only as a session artifact a expect(body.result?.ok).toBe(true); expect(fs.readFileSync(victim, 'utf8')).toBe('protected-content'); const data = body.result?.data; - expect((data!.artifact as { path: string }).path).toBe( - path.join(sessionStore.resolveSessionDir('capture'), 'artifacts', 'memory.hprof'), + expect((data!.artifact as { path: string }).path).toMatch( + /agent-device-output-[^/]+\/memory\.hprof$/, ); const download = await fetch(`${baseUrl}/artifacts/${data?.artifacts?.[0]?.artifactId}`, { headers: { authorization: 'Bearer test-token' }, @@ -770,7 +764,6 @@ test.each(['./capture.log', undefined])( sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact, }); await withHttp(handler, async (post, baseUrl) => { const req = { @@ -834,7 +827,6 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite }), ]), ); - const registrations: Array<{ path: string; tenant?: string }> = []; const handler = createRequestHandler({ host: createTestHostEnvironment({ cwd: root }), createCommandSurface: screenshotCommandSurface, @@ -843,10 +835,6 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite sessionStore, leaseRegistry, deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact: (entry) => { - registrations.push({ path: entry.artifactPath, tenant: entry.tenantId }); - return trackDownloadableArtifact(entry); - }, }); const hook = path.join(root, 'hook.mjs'); fs.writeFileSync(hook, "export default ({ headers }) => ({ tenantId: headers['x-tenant'] });"); @@ -856,6 +844,11 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite async (post, baseUrl) => { const runSuite = async (tenant: string) => { const lease = leases.get(tenant)!; + const artifactsRoot = path.join( + sessionStore.resolveSessionDir(`${tenant}:capture`), + 'test-artifacts', + ); + const before = new Set(fs.existsSync(artifactsRoot) ? fs.readdirSync(artifactsRoot) : []); const body = await post( { command: 'test', @@ -880,13 +873,18 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite expect(body.result?.ok, JSON.stringify(body)).toBe(true); expect(body.result?.data?.executed).toBe(1); expect(body.result?.data?.artifacts?.[0]?.artifactId).toBeTypeOf('string'); - return body.result!.data!.artifacts![0]!; + const created = fs.readdirSync(artifactsRoot).filter((entry) => !before.has(entry)); + expect(created).toHaveLength(1); + return { + ...body.result!.data!.artifacts![0]!, + storagePath: path.join(artifactsRoot, created[0]!), + }; }; const first = await runSuite('tenant-a'); - const firstPath = registrations[0]!.path; + const firstPath = first.storagePath; fs.writeFileSync(path.join(firstPath, 'private-a.txt'), 'tenant-a-private-marker'); const second = await runSuite('tenant-b'); - const secondPath = registrations[1]!.path; + const secondPath = second.storagePath; expect(secondPath).not.toBe(firstPath); expect(path.dirname(firstPath)).toBe( path.join(sessionStore.resolveSessionDir('tenant-a:capture'), 'test-artifacts'), @@ -909,7 +907,7 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite 'tenant-a-private-marker', ); const third = await runSuite('tenant-a'); - expect(registrations[2]!.path).not.toBe(firstPath); + expect(third.storagePath).not.toBe(firstPath); const forbidden = await fetch(`${baseUrl}/artifacts/${first.artifactId}`, { headers: { authorization: 'Bearer test-token', 'x-tenant': 'tenant-b' }, }); @@ -927,7 +925,7 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite } await vi.waitFor(() => { expect(fs.existsSync(firstPath)).toBe(false); - expect(fs.existsSync(registrations[2]!.path)).toBe(false); + expect(fs.existsSync(third.storagePath)).toBe(false); }); }, env, diff --git a/packages/daemon/src/server/http/http-server-remote-suite.test.ts b/packages/daemon/src/server/http/http-server-remote-suite.test.ts index 464c873cc5c..7e7bb097fe5 100644 --- a/packages/daemon/src/server/http/http-server-remote-suite.test.ts +++ b/packages/daemon/src/server/http/http-server-remote-suite.test.ts @@ -7,10 +7,7 @@ import { createRequestHandler } from '../../__tests__/support/test-device-runtim import { screenshotCommandSurface } from '../../__tests__/support/screenshot-command-surface-fake.ts'; import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; -import { - cleanupDownloadableArtifact, - trackDownloadableArtifact, -} from '../../resources/artifact-tracking.ts'; +import { cleanupDownloadableArtifact } from '../../resources/artifact-tracking.ts'; import { successfulData, withHttp } from './http-output.fixtures.ts'; test('trusted remote suites with a repeated request ID download distinct archives', async () => { @@ -25,7 +22,6 @@ test('trusted remote suites with a repeated request ID download distinct archive sessionStore, leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), - trackDownloadableArtifact, }); await withHttp(handler, async (post, base) => { const run = async (marker: string) => { diff --git a/packages/daemon/src/server/http/http-server-resumable-upload.test.ts b/packages/daemon/src/server/http/http-server-resumable-upload.test.ts index fd29bf2b049..73a4cfcdb4c 100644 --- a/packages/daemon/src/server/http/http-server-resumable-upload.test.ts +++ b/packages/daemon/src/server/http/http-server-resumable-upload.test.ts @@ -79,7 +79,12 @@ test('chunked ranged overflow rolls back before an exact retry and finalize', as assert.equal(finalized.status, 200); const body = (await finalized.json()) as { uploadId?: string }; trackedUploadId = body.uploadId ?? ''; - assert.deepEqual(fs.readFileSync(prepareUploadedArtifact(trackedUploadId)), content); + assert.deepEqual( + fs.readFileSync( + prepareUploadedArtifact(trackedUploadId, { tenantId: undefined, leaseVerifier: null }), + ), + content, + ); } finally { if (trackedUploadId) cleanupUploadedArtifact(trackedUploadId); await closeLoopbackServer(server); diff --git a/packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts b/packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts new file mode 100644 index 00000000000..0eef8deebab --- /dev/null +++ b/packages/daemon/src/server/http/http-server-rpc-ingress-budget.test.ts @@ -0,0 +1,280 @@ +import http from 'node:http'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { test, vi } from 'vitest'; +import { createDaemonProxyServer } from '@agent-device/proxy'; +import { + closeLoopbackServer, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { createDaemonHttpServer } from './http-server.ts'; +import { + postRpcCommand, + startRpcServer, + type RpcErrorBody, +} from '../__tests__/http-server-rpc.fixtures.ts'; + +test('preauthorization body deadline answers with a typed reason before dispatch', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let dispatched = 0; + const { port, server } = await startRpcServer('budget-token', async () => { + dispatched += 1; + return { ok: true, data: {} }; + }); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const reached = new Promise((resolve) => server.once('request', () => resolve())); + let request!: http.ClientRequest; + const response = new Promise<{ status: number; body: string }>((resolve, reject) => { + request = http.request({ + host: '127.0.0.1', + port, + method: 'POST', + path: '/rpc', + headers: { 'content-type': 'application/json' }, + }); + request.on('response', (res) => { + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('end', () => + resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') }), + ); + }); + request.on('error', reject); + request.flushHeaders(); + }); + try { + await reached; + await vi.advanceTimersByTimeAsync(5_000); + const answered = await response; + const body = JSON.parse(answered.body) as { + error?: { data?: { details?: { reason?: string; dispatched?: string } } }; + }; + assert.equal(answered.status, 408); + assert.equal(body.error?.data?.details?.reason, 'RPC_PREAUTH_DEADLINE_EXCEEDED'); + assert.equal(body.error?.data?.details?.dispatched, 'no'); + assert.equal(dispatched, 0); + } finally { + vi.useRealTimers(); + request.destroy(); + await closeLoopbackServer(server); + } +}); + +test.for([ + ['proxy', 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', 0], + ['daemon', 'RPC_PREAUTH_DEADLINE_EXCEEDED', 1], +] as const)( + 'the %s auth deadline answers through the proxy and allows a fresh call', + async ([origin, reason, expectedDaemonCalls], t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const root = mkdtempForTestSync('rpc-preauth-id-'); + const hookPath = path.join(root, 'auth-hook.mjs'); + fs.writeFileSync( + hookPath, + `const entered = Promise.withResolvers(); +const held = Promise.withResolvers(); +export const authEntered = entered.promise; +export const releaseAuth = () => held.resolve({ tenantId: 'budget-tenant' }); +export function holdAuth() { + entered.resolve(); + return held.promise; +} +export default function authHook({ rpcRequest }) { + return rpcRequest.id === 'daemon-timeout' ? holdAuth() : { tenantId: 'budget-tenant' }; +} +`, + ); + const auth = (await import(pathToFileURL(hookPath).href)) as { + authEntered: Promise; + holdAuth: () => Promise<{ tenantId: string }>; + releaseAuth: () => void; + }; + let daemonCalls = 0; + let dispatched = 0; + const daemon = await createDaemonHttpServer({ + token: 'budget-token', + env: { AGENT_DEVICE_HTTP_AUTH_HOOK: hookPath }, + cwd: process.cwd(), + handleRequest: async () => { + dispatched += 1; + return { ok: true, data: { reached: 'daemon-handler' } }; + }, + }); + t.onTestFinished(() => closeLoopbackServer(daemon)); + daemon.on('request', () => { + daemonCalls += 1; + }); + const daemonPort = await listenOnLoopback(daemon); + const proxy = createDaemonProxyServer({ + upstreamBaseUrl: `http://127.0.0.1:${daemonPort}`, + upstreamToken: 'budget-token', + authenticate: (request) => + request.headers.get('x-request-id') === 'proxy-timeout' + ? auth.holdAuth() + : { tenantId: 'budget-tenant' }, + }); + t.onTestFinished(() => closeLoopbackServer(proxy)); + const proxyPort = await listenOnLoopback(proxy); + const post = (id: string) => + fetch(`http://127.0.0.1:${proxyPort}/agent-device/rpc`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-request-id': id }, + body: JSON.stringify({ + jsonrpc: '2.0', + id, + method: 'agent_device.command', + params: { command: 'session_list' }, + }), + signal: AbortSignal.timeout(2_000), + }); + + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + t.onTestFinished(() => { + vi.useRealTimers(); + auth.releaseAuth(); + }); + const id = `${origin}-timeout`; + const pending = post(id); + await Promise.race([ + auth.authEntered, + pending.then((response) => + assert.fail(`HTTP ${response.status} before entering ${origin} auth`), + ), + ]); + await vi.advanceTimersByTimeAsync(5_000); + const response = await pending; + assert.equal(response.status, 408); + const body = (await response.json()) as RpcErrorBody; + assert.equal(body.id, id); + assert.equal(body.error?.data?.details?.reason, reason); + assert.equal(body.error?.data?.details?.dispatched, 'no'); + assert.equal(body.error?.data?.retriable, true); + assert.equal(daemonCalls, expectedDaemonCalls); + assert.equal(dispatched, 0); + + vi.useRealTimers(); + auth.releaseAuth(); + const fresh = await post(`${origin}-fresh`); + assert.equal(fresh.status, 200); + assert.deepEqual(await fresh.json(), { + jsonrpc: '2.0', + id: `${origin}-fresh`, + result: { ok: true, data: { reached: 'daemon-handler' } }, + }); + assert.equal(daemonCalls, expectedDaemonCalls + 1); + assert.equal(dispatched, 1); + }, +); + +test('unfinished unauthenticated RPC bodies do not block authenticated dispatch', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let dispatched = 0; + const { port, server } = await startRpcServer('budget-token', async () => { + dispatched += 1; + return { ok: true, data: {} }; + }); + const held: http.ClientRequest[] = []; + let received = 0; + let allReceived!: () => void; + const ready = new Promise((resolve) => { + allReceived = resolve; + }); + server.on('request', (req) => { + if (req.url === '/rpc' && ++received === 32) allReceived(); + }); + try { + for (let index = 0; index < 32; index += 1) { + const request = http.request({ + host: '127.0.0.1', + port, + method: 'POST', + path: '/rpc', + headers: { 'content-type': 'application/json' }, + }); + request.on('error', () => {}); + request.flushHeaders(); + held.push(request); + } + await ready; + const admitted = await postRpcCommand(port, 'budget-token', 'admitted'); + assert.equal(admitted.status, 200); + assert.equal(dispatched, 1); + for (const request of held) request.destroy(); + const afterDisconnect = await postRpcCommand(port, 'budget-token', 'after-disconnect'); + assert.equal(afterDisconnect.status, 200); + } finally { + for (const request of held) request.destroy(); + await closeLoopbackServer(server); + } +}); + +test('preauth capacity accepts duplicate unadmitted IDs, refuses the next caller and releases on disconnect', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const root = mkdtempForTestSync('rpc-preauth-capacity-'); + const hookPath = path.join(root, 'hook.mjs'); + fs.writeFileSync( + hookPath, + ` +const admitted = Promise.withResolvers(); +const ended = Promise.withResolvers(); +let count = 0; +let aborted = 0; +export const entered = admitted.promise; +export const allAborted = ended.promise; +export default ({ rpcRequest, signal }) => { + if (!String(rpcRequest.id).startsWith('stall-')) return { tenantId: 'budget-tenant' }; + count++; + if (count === 128) admitted.resolve(); + signal.addEventListener('abort', () => { if (++aborted === 128) ended.resolve(); }, { once: true }); + return new Promise(() => {}); +};`, + ); + const hook = (await import(pathToFileURL(hookPath).href)) as { + entered: Promise; + allAborted: Promise; + }; + let dispatched = 0; + const server = await createDaemonHttpServer({ + token: 'budget-token', + cwd: root, + env: { ...process.env, AGENT_DEVICE_HTTP_AUTH_HOOK: hookPath }, + handleRequest: async () => { + dispatched++; + return { ok: true }; + }, + }); + const port = await listenOnLoopback(server); + const controllers = Array.from({ length: 128 }, () => new AbortController()); + const pending = controllers.map((controller, index) => + fetch(`http://127.0.0.1:${port}/rpc`, { + method: 'POST', + headers: { authorization: 'Bearer budget-token', 'content-type': 'application/json' }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: `stall-${index}`, + method: 'agent_device.command', + params: { command: 'session_list', meta: { requestId: 'shared-unadmitted-id' } }, + }), + signal: controller.signal, + }).catch(() => undefined), + ); + try { + await hook.entered; + const refused = await postRpcCommand(port, 'budget-token', 'capacity'); + assert.equal(refused.status, 503); + assert.equal(refused.body.error?.data?.details?.reason, 'RPC_PREAUTH_CAPACITY_EXCEEDED'); + assert.equal(dispatched, 0); + controllers.forEach((controller) => controller.abort()); + await hook.allAborted; + assert.equal((await postRpcCommand(port, 'budget-token', 'fresh')).status, 200); + assert.equal(dispatched, 1); + } finally { + controllers.forEach((controller) => controller.abort()); + await Promise.all(pending); + await closeLoopbackServer(server); + } +}); diff --git a/packages/daemon/src/server/http/http-server-session-lease-touch.fixtures.ts b/packages/daemon/src/server/http/http-server-session-lease-touch.fixtures.ts index cde569fc305..d82afec351c 100644 --- a/packages/daemon/src/server/http/http-server-session-lease-touch.fixtures.ts +++ b/packages/daemon/src/server/http/http-server-session-lease-touch.fixtures.ts @@ -139,7 +139,7 @@ export async function startDaemon(daemonPolicy?: DaemonPolicy) { }, }), deviceRuntimeGateway: runtime.gateway, - trackDownloadableArtifact: () => 'artifact-id', + hostDiagnostics, daemonPolicy, platformResourceCleanup: requestTeardown, diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index daae7f1eef0..ce7243a1804 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -12,8 +12,12 @@ import { AsyncResource } from 'node:async_hooks'; import http from 'node:http'; import { TLSSocket } from 'node:tls'; import { randomUUID } from 'node:crypto'; -import type { DiagnosticsRecordRef, NormalizedError } from '@agent-device/kernel/errors'; -import { normalizeError } from '@agent-device/kernel/errors'; +import type { + DiagnosticsRecordRef, + NormalizedError, + ReasonTable, +} from '@agent-device/kernel/errors'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { LEASE_BACKENDS } from '@agent-device/kernel/contracts'; import { isRecord } from '@agent-device/kernel/record'; import type { DaemonInvokeFn, DaemonRequest } from '../../core/daemon-request.ts'; @@ -40,6 +44,8 @@ import { DAEMON_HTTP_NETWORK_ACCESS_HEADER, type CheckedRpcProtocolRefusal, DAEMON_REQUEST_MAX_BYTES, + DAEMON_RPC_PREAUTH_MAX_ID_LENGTH, + DAEMON_RPC_PREAUTH_TIMEOUT_MS, } from '@agent-device/contracts/daemon-http'; import { readVersion } from '@agent-device/host-kit/version'; import { readHostCpuArch } from '@agent-device/host-kit/process'; @@ -57,6 +63,7 @@ import { import { tryHandleDownloadableArtifactHttpRoute } from '../downloadable-artifact-http.ts'; import { tryHandleRequestDiagnosticsHttpRoute } from '../request-diagnostics-http.ts'; import { tryHandleHostAdminHttpRoute } from '../host-lease-http.ts'; +import type { SessionStore } from '../../core/session-store.ts'; import type { LeaseRegistry } from '../../resources/lease-registry.ts'; import { createAuxiliaryHttpAuthorizer, @@ -96,6 +103,15 @@ import { import type { HostedAuxiliaryAdmission } from '../hosted-attachment-admission.ts'; const MAX_HTTP_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; +const MAX_IN_FLIGHT_RPC_BODY_BYTES = 128 * 1024 * 1024; +const MAX_RPC_PREAUTH_REQUESTS = 128; +const DAEMON_RPC_INGRESS_REASONS = { + // The daemon has no free slot to receive and authenticate another RPC request. + preauthCapacityExceeded: { reason: 'RPC_PREAUTH_CAPACITY_EXCEEDED' }, + // The RPC body or authentication did not finish before its preauthorization deadline, so nothing was dispatched. + preauthDeadlineExceeded: { reason: 'RPC_PREAUTH_DEADLINE_EXCEEDED' }, +} as const satisfies ReasonTable<'RPC ingress'>; +type RpcIngressBudget = { bytes: number; preauthRequests: number }; /** What this daemon serves over HTTP beyond the base RPC contract, as `/health` advertises it. */ const DAEMON_HTTP_CAPABILITIES: readonly DaemonCapability[] = [ 'script-artifacts', @@ -110,6 +126,7 @@ export async function createDaemonHttpServer(options: { leaseRegistry?: LeaseRegistry; hostAdminEnabled?: boolean; admitAuxiliary?: HostedAuxiliaryAdmission; + sessionStore?: SessionStore; startupRecovered?: Promise; leaseLifecycleProvider?: LeaseLifecycleProvider; endSessionsForLease?: (leaseId: string) => Promise; @@ -162,6 +179,7 @@ export async function createDaemonHttpServer(options: { resolveRequestDiagnosticsPath, onUnownedRequestFailure, } = options; + const rpcIngressBudget: RpcIngressBudget = { bytes: 0, preauthRequests: 0 }; const onRequest = AsyncResource.bind((req: http.IncomingMessage, res: http.ServerResponse) => { const ingressUrl = nodeHttpRequestUrl(req.url, req.rawHeaders, req.socket instanceof TLSSocket); if (!ingressUrl) { @@ -206,8 +224,11 @@ export async function createDaemonHttpServer(options: { tryHandleUploadHttpRoute({ req, res, + leaseRegistry: options.leaseRegistry, token: resolveToken({}, req.headers), origin: publicOrigin ?? ingressUrl.origin, + leaseRegistry: options.leaseRegistry, + sessionStore: options.sessionStore, authorize: authorizeAuxiliary, }) ) { @@ -218,6 +239,7 @@ export async function createDaemonHttpServer(options: { tryHandleDownloadableArtifactHttpRoute({ req, res, + leaseRegistry: options.leaseRegistry, retainArtifacts, hostEnv: environment, authorize: authorizeAuxiliary, @@ -245,24 +267,33 @@ export async function createDaemonHttpServer(options: { return; } - readRpcRequestBody(req, res, (body) => { - // The flow owns this request's lifetime, so this call site must neither hold lifetime state - // nor re-run it; the `catch` reports the failure to the daemon-level sink and answers. That - // answer is load-bearing: the daemon exits on an `unhandledRejection`, so a rejection dropped - // here would let any process that reaches the port stop the daemon with one request body. - void handleRpcRequest({ - req, - res, - body, - authHook, - expectedToken: token, - instanceId, - handleRequest, - checked, - }).catch((error: unknown) => { - sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); - }); - }); + readRpcRequestBody( + req, + res, + rpcIngressBudget, + (body, release, preauthSignal, finishPreauth) => { + // The flow owns this request's lifetime, so this call site must neither hold lifetime state + // nor re-run it; the `catch` reports the failure to the daemon-level sink and answers. That + // answer is load-bearing: the daemon exits on an `unhandledRejection`, so a rejection dropped + // here would let any process that reaches the port stop the daemon with one request body. + void handleRpcRequest({ + req, + res, + body, + authHook, + expectedToken: token, + instanceId, + handleRequest, + checked, + preauthSignal, + finishPreauth, + }) + .catch((error: unknown) => { + sendUnownedRpcRequestFailure(res, onUnownedRequestFailure, error); + }) + .finally(release); + }, + ); }); // Socket ingress ceilings from one owner (ingress-budget.ts). They bound socket ingress // only; RPC execution keeps its own deadlines. The header ceiling acts before admission @@ -289,33 +320,120 @@ export async function createDaemonHttpServer(options: { function readRpcRequestBody( req: http.IncomingMessage, res: http.ServerResponse, - onBody: (body: string) => void, + budget: RpcIngressBudget, + onBody: ( + body: string, + release: () => void, + preauthSignal: AbortSignal, + finishPreauth: () => void, + ) => void, ): void { + if (budget.preauthRequests >= MAX_RPC_PREAUTH_REQUESTS) { + res.setHeader('connection', 'close'); + sendRpcPreauthRefusal( + res, + null, + 503, + 'RPC preauthorization capacity exceeded', + DAEMON_RPC_INGRESS_REASONS.preauthCapacityExceeded.reason, + ); + return; + } + budget.preauthRequests += 1; + const preauth = new AbortController(); + let deadline: ReturnType | undefined = setTimeout(() => { + preauth.abort(new Error('RPC ingress deadline exceeded')); + release(); + if (!res.headersSent && !res.writableEnded) { + res.once('finish', () => req.destroy()); + sendRpcPreauthRefusal( + res, + bodyComplete ? readCompletedRpcId(body) : null, + 408, + 'RPC ingress deadline exceeded', + DAEMON_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason, + ); + } else { + req.destroy(); + } + }, DAEMON_RPC_PREAUTH_TIMEOUT_MS); + const finishPreauth = () => { + if (deadline === undefined) return; + clearTimeout(deadline); + deadline = undefined; + budget.preauthRequests -= 1; + res.off('close', release); + }; let body = ''; let bodyBytes = 0; + let released = false; + let bodyComplete = false; + const release = () => { + if (released) return; + released = true; + finishPreauth(); + budget.bytes -= bodyBytes; + }; req.setEncoding('utf8'); req.on('data', (chunk: string) => { - body += chunk; - bodyBytes += Buffer.byteLength(chunk, 'utf8'); - if (bodyBytes > MAX_HTTP_RPC_BODY_BYTES) { + if (released) return; + const bytes = Buffer.byteLength(chunk, 'utf8'); + if ( + bodyBytes + bytes > MAX_HTTP_RPC_BODY_BYTES || + budget.bytes + bytes > MAX_IN_FLIGHT_RPC_BODY_BYTES + ) { req.destroy(new Error('request too large')); + return; } + bodyBytes += bytes; + budget.bytes += bytes; + body += chunk; }); req.on('error', () => { - if (!res.headersSent) { + if (!bodyComplete) release(); + if (!res.headersSent && !res.writableEnded) { sendRpcRefusal(res, rpcParseErrorRefusal()); } }); + res.once('close', release); req.on( 'end', AsyncResource.bind(() => { - onBody(body); + if (released) return; + bodyComplete = true; + onBody(body, release, preauth.signal, finishPreauth); }), ); } +function sendRpcPreauthRefusal( + res: http.ServerResponse, + id: string | number | null, + status: number, + message: string, + reason: string, +): void { + const error = normalizeError( + new AppError('COMMAND_FAILED', message, { reason, dispatched: 'no', retriable: true }), + ); + sendRpcRefusal(res, rpcRefusal(id, -32000, error.message, status, error)); +} + +function readCompletedRpcId(body: string): string | number | null { + try { + const parsed: unknown = JSON.parse(body); + if (!isRecord(parsed)) return null; + const id = parsed.id; + if (typeof id === 'string') return id.length <= DAEMON_RPC_PREAUTH_MAX_ID_LENGTH ? id : null; + if (typeof id === 'number') return Number.isFinite(id) ? id : null; + } catch { + // An incomplete or malformed body has no request id to preserve. + } + return null; +} + // The `/rpc` flow, in the order it runs: the envelope decides whether this body is a // call at all; admission decides whether its caller may run it; the lifetime owns the // tracking id and cancellation from that moment to cleanup; invocation runs the @@ -332,8 +450,21 @@ async function handleRpcRequest(params: { handleRequest: DaemonInvokeFn; /** The call came on the checked route, so its protocol is checked before dispatch. */ checked: boolean; + preauthSignal: AbortSignal; + finishPreauth: () => void; }): Promise { - const { req, res, body, authHook, expectedToken, instanceId, handleRequest, checked } = params; + const { + req, + res, + body, + authHook, + expectedToken, + instanceId, + handleRequest, + checked, + preauthSignal, + finishPreauth, + } = params; // A checked call proves its credential before anything reads its protocol or method. One on // another protocol then takes the `/rpc` flow and is refused only once every auth gate passed. if (checked && refuseCheckedRpcCredential(req, res, body, expectedToken)) return; @@ -361,7 +492,9 @@ async function handleRpcRequest(params: { params: validated.params, lifetime, protocolRefusal, + preauthSignal, }); + finishPreauth(); if (admission.outcome !== 'admitted') { if (admission.outcome === 'rejected') { sendRpcRefusal(res, admission.refusal); @@ -369,6 +502,8 @@ async function handleRpcRequest(params: { return; } + preauthSignal.throwIfAborted(); + lifetime.watchForClientDisconnect(); await invokeAdmittedRpcRequest({ res, @@ -382,7 +517,8 @@ async function handleRpcRequest(params: { // or a duplicate tracking id. The failure answer is on its way, so a socket closing // after it is not a client walking out on work still in flight. lifetime.markHandlerCompleted(); - sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error)); + if (!res.writableEnded) + sendRpcRequestFailure(res, validated.rpcRequest.id, normalizeError(error)); } finally { lifetime.release(); } @@ -494,6 +630,7 @@ function sendRpcRefusal(res: http.ServerResponse, refusal: RpcRefusal): void { * before `admit`, so a call that was never admitted still cleans up from one place. */ type RpcRequestLifetime = { + signal: AbortSignal; /** * Stamps the daemon's request tracking id into `meta` and registers the request's AbortSignal * under it. An id already in flight throws `duplicate_request_id` from here, so the caller @@ -527,7 +664,7 @@ function beginRpcRequestLifetime(params: { let abortRegistration: ReturnType; let handlerCompleted = false; let canceledInFlight = false; - let disconnectSignal: AbortSignal | undefined; + const disconnectSignal = responseDisconnectSignal(req, res); let onClientGone: (() => void) | undefined; const markCanceledIfResponseIncomplete = () => { @@ -544,6 +681,7 @@ function beginRpcRequestLifetime(params: { }; return { + signal: disconnectSignal, admit(daemonRequest) { requestId = resolveRequestTrackingId(daemonRequest.meta?.requestId, rpcId); abortRegistration = registerRequestAbort(requestId, undefined, { @@ -557,7 +695,6 @@ function beginRpcRequestLifetime(params: { }, watchForClientDisconnect() { onClientGone = AsyncResource.bind(markCanceledIfResponseIncomplete); - disconnectSignal = responseDisconnectSignal(req, res); disconnectSignal.addEventListener('abort', onClientGone, { once: true }); if (disconnectSignal.aborted) { markCanceledIfResponseIncomplete(); @@ -567,7 +704,7 @@ function beginRpcRequestLifetime(params: { handlerCompleted = true; }, release() { - if (onClientGone) disconnectSignal?.removeEventListener('abort', onClientGone); + if (onClientGone) disconnectSignal.removeEventListener('abort', onClientGone); clearRequestAbortRegistration(abortRegistration); }, }; @@ -607,8 +744,19 @@ async function admitRpcRequest(params: { lifetime: RpcRequestLifetime; /** A checked call's protocol refusal, answered once the caller passes the auth gates. */ protocolRefusal: CheckedRpcProtocolRefusal | undefined; + preauthSignal: AbortSignal; }): Promise { - const { req, res, authHook, expectedToken, instanceId, rpcRequest, method, lifetime } = params; + const { + req, + res, + authHook, + expectedToken, + instanceId, + rpcRequest, + method, + lifetime, + preauthSignal, + } = params; const { protocolRefusal } = params; const wireRequest = methodToDaemonRequest(method, params.params, req.headers); // A command call naming no command is params the router cannot route. @@ -626,7 +774,7 @@ async function admitRpcRequest(params: { // A call that will be refused never reserves its tracking id: only a call that can run registers. const daemonRequest = protocolRefusal ? withUnregisteredTrackingId(wireRequest, rpcRequest.id) - : lifetime.admit(wireRequest); + : wireRequest; // Captured before the hook runs: what the caller claimed is an input to the trust // decision, never an identity. @@ -636,6 +784,7 @@ async function admitRpcRequest(params: { headers: req.headers, rpcRequest, daemonRequest, + signal: AbortSignal.any([lifetime.signal, preauthSignal]), }); if (!authResult.ok) { return { @@ -665,7 +814,7 @@ async function admitRpcRequest(params: { return { outcome: 'admitted', - daemonRequest: stampAdmittedIdentity(daemonRequest, tenantTrust, authHook, req), + daemonRequest: lifetime.admit(stampAdmittedIdentity(daemonRequest, tenantTrust, authHook, req)), }; } @@ -703,6 +852,10 @@ function stampAdmittedIdentity( ): DaemonRequest { let admitted: DaemonRequest = { ...daemonRequest, + internal: { + ...daemonRequest.internal, + principal: tenantTrust.attested ? 'attested' : tenantTrust.tenantId ? 'declared' : 'local', + }, meta: { ...daemonRequest.meta, tenantId: tenantTrust.tenantId, diff --git a/packages/daemon/src/server/remote-host-input-policy.ts b/packages/daemon/src/server/remote-host-input-policy.ts index 623de0ff2ba..1f241e9fbe3 100644 --- a/packages/daemon/src/server/remote-host-input-policy.ts +++ b/packages/daemon/src/server/remote-host-input-policy.ts @@ -1,3 +1,5 @@ +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { assertReplayScriptSourcesWithinLimit } from '@agent-device/replay-port/script-source'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { INTERNAL_COMMANDS } from '@agent-device/command-registry/catalog'; import { validateAndNormalizeBatchSteps } from '@agent-device/command-registry/batch'; @@ -9,6 +11,8 @@ const REMOTE_HOST_INPUT_REASONS = { // A remote request supplied a host path or other host input (`details.field`), which a remote // daemon refuses. denied: { reason: 'REMOTE_HOST_INPUT_DENIED' }, + // The managed browser cannot confine a remote tenant's network traffic. + webBrowserUnconfined: { reason: 'remote_web_browser_unconfined' }, } as const satisfies ReasonTable<'remote daemon'>; const HOST_PATH_FIELDS = [ @@ -27,6 +31,8 @@ const HOST_PATH_FIELDS = [ /** Remote callers choose client destinations; only the daemon chooses host output paths. */ export function restrictRemoteHostInputs(request: DaemonRequest): DaemonRequest { + if (request.command === 'replay' || request.command === 'test') + assertReplayScriptSourcesWithinLimit(request.flags as Record | undefined); if (!request.internal?.publicNetworkOnly) return request; const { cwd: _cwd, ...meta } = request.meta ?? {}; const command = request.command; @@ -215,3 +221,17 @@ function remoteHostInputDenied(field: string, hint = REMOTE_HOST_INPUT_HINT): Ap hint, }); } + +export function assertRemoteWebDeviceAdmitted(request: DaemonRequest, device: DeviceInfo): void { + if ( + !request.internal?.publicNetworkOnly || + device.platform !== 'web' || + request.command === 'close' + ) + return; + throw new AppError( + 'UNSUPPORTED_OPERATION', + 'Remote web sessions require a browser that confines public-network traffic.', + { reason: REMOTE_HOST_INPUT_REASONS.webBrowserUnconfined.reason, retriable: false }, + ); +} diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index 5df273517d2..d1fc5a086fd 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -1,6 +1,9 @@ import { LEASE_REASONS } from '@agent-device/contracts/lease-scope'; import { thrownBeforeDispatch } from '../execution/request-dispatch-disclosure.ts'; -import { restrictRemoteHostInputs } from './remote-host-input-policy.ts'; +import { + assertRemoteWebDeviceAdmitted, + restrictRemoteHostInputs, +} from './remote-host-input-policy.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { heldKeyedLockKeys } from '@agent-device/kernel/keyed-lock'; @@ -811,8 +814,12 @@ function createRequestDeviceAccess(params: { dispatchLedger: params.dispatchLedger, admitDeviceClaim: claimAdmission.admit, admitDevice: - params.admitDevicePin || daemonPolicy || claimPolicy === 'require-owner' + params.admitDevicePin || + daemonPolicy || + claimPolicy === 'require-owner' || + params.req.internal?.publicNetworkOnly ? (device) => { + assertRemoteWebDeviceAdmitted(params.req, device); params.admitDevicePin?.(device); if (daemonPolicy) { assertDaemonPolicyAdmitsDevice(daemonPolicy, device); @@ -863,9 +870,8 @@ function preparedSessionRef( export async function prepareLockedRequestScope(params: { scope: RequestExecutionScope; sessionStore: SessionStore; - trackDownloadableArtifact: output.TrackDownloadableArtifact; }): Promise { - const { scope, sessionStore, trackDownloadableArtifact } = params; + const { scope, sessionStore } = params; const logPath = scope.runnerLogPath; scope.throwIfCanceled(); const ref = scope.admittedRef; @@ -891,7 +897,7 @@ export async function prepareLockedRequestScope(params: { const existingSession = existingRef?.session; updateDiagnosticsScope(output.requestTraceDiagnostics(lockedReq, existingRef, sessionStore)); const finalize = (handled: DaemonResponse): DaemonResponse => { - const finalized = finalizeDaemonResponse(lockedReq, handled, trackDownloadableArtifact); + const finalized = finalizeDaemonResponse(handled); scope.recordFinished(lockedReq, finalized); return finalized; }; diff --git a/packages/daemon/src/server/request-finalization.ts b/packages/daemon/src/server/request-finalization.ts index 0d54e6fddce..0429417177e 100644 --- a/packages/daemon/src/server/request-finalization.ts +++ b/packages/daemon/src/server/request-finalization.ts @@ -1,5 +1,3 @@ -import path from 'node:path'; -import { isRecord } from '@agent-device/kernel/record'; import { AppError, normalizeError, @@ -21,32 +19,12 @@ import { scopeRequestSession } from '../sessions/request-admission.ts'; import { resolveEffectiveSessionName } from '../sessions/session-routing.ts'; import { sessionIdleExpiredError } from './session-idle-expiry.ts'; import type { IdleSessionTombstone } from '../core/session-idle-tombstone.ts'; -import type { - DaemonArtifact, - DaemonResponse, - DaemonResponseData, -} from '@agent-device/kernel/contracts'; -import { isDeviceRotation, type DeviceRotation } from '@agent-device/contracts/device'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { claimRequestDiagnosticsRecord, - leaseVerifier, requestDiagnosticsRecordId, - type TrackDownloadableArtifact, } from '../resources/artifact-tracking.ts'; import { tenantScopedSessionName } from '../core/session-tenant-scope.ts'; -import { - captureOutputLeaseVerifier, - captureOutputOwnership, - captureOutputTenantId, - daemonDeliveredArtifact, -} from '../core/capture-output-ownership.ts'; - -/** A response artifact plus the capture facts the inventory reports beside it. */ -type PendingArtifact = DaemonArtifact & { - displayRotation?: DeviceRotation; - deleteAfterDownload?: boolean; -}; - export function installDetachedRequestDiagnostics( req: DaemonRequest, store: Pick, @@ -84,11 +62,7 @@ export function finalizeThrownRequestError(error: unknown): DaemonResponse { }; } -export function finalizeDaemonResponse( - req: DaemonRequest, - response: DaemonResponse, - trackArtifact: TrackDownloadableArtifact, -): DaemonResponse { +export function finalizeDaemonResponse(response: DaemonResponse): DaemonResponse { const details = getDiagnosticsMeta(); if (!response.ok) { emitDiagnostic({ @@ -144,116 +118,8 @@ export function finalizeDaemonResponse( flushDiagnosticsToSessionFile(); return { ok: true, - data: registerDownloadableArtifacts(req, response.data, trackArtifact), - }; -} - -function registerDownloadableArtifacts( - req: DaemonRequest, - data: DaemonResponseData | undefined, - trackArtifact: TrackDownloadableArtifact, -): DaemonResponseData | undefined { - if (!data) return data; - const admittedLeaseId = req.internal?.admittedLease?.leaseId; - const producer = captureOutputLeaseVerifier(data); - const admittedOwner = admittedLeaseId && leaseVerifier(admittedLeaseId); - const tenantId = captureOutputTenantId(data) ?? req.meta?.tenantId; - const register = (artifact: PendingArtifact): DaemonArtifact => { - const artifactPath = artifact.path as string; - const delivered = daemonDeliveredArtifact(artifact); - const owner = delivered || producer === undefined ? admittedOwner : producer; - return { - field: artifact.field, - // Omitted (not null/undefined-valued) when untyped, matching the - // optional wire contract on DaemonArtifact. - ...(artifact.artifactType !== undefined ? { artifactType: artifact.artifactType } : {}), - artifactId: trackArtifact({ - artifactPath, - tenantId: delivered ? delivered.tenantId : tenantId, - ...(owner ? { leaseVerifier: owner } : {}), - artifactType: artifact.artifactType, - fileName: artifact.fileName, - ...(artifact.deleteAfterDownload === false ? { deleteAfterDownload: false } : {}), - ...(isDeviceRotation(artifact.displayRotation) - ? { displayRotation: artifact.displayRotation } - : {}), - }), - fileName: artifact.fileName, - localPath: artifact.localPath, - scriptPublicationId: artifact.scriptPublicationId, - scriptRevision: artifact.scriptRevision, - }; + data: response.data, }; - if (captureOutputOwnership(data) === 'caller') { - // Caller-owned capture output stays at the caller path; a daemon-delivered artifact still registers. - if (!data.artifacts?.some(daemonDeliveredArtifact)) return data; - return { - ...data, - artifacts: data.artifacts.map((item) => - daemonDeliveredArtifact(item) ? register(item) : item, - ), - }; - } - const pendingArtifacts = collectPendingArtifacts(req, data); - if (pendingArtifacts.length === 0) return data; - const committed = Array.isArray(data.artifacts) - ? data.artifacts.filter((artifact) => artifact?.artifactId && !artifact.path) - : []; - return { ...data, artifacts: [...committed, ...pendingArtifacts.map(register)] }; -} - -function collectPendingArtifacts(req: DaemonRequest, data: DaemonResponseData): PendingArtifact[] { - const ownership = captureOutputOwnership(data); - const artifacts: PendingArtifact[] = Array.isArray(data.artifacts) ? [...data.artifacts] : []; - const hasField = (field: string): boolean => - artifacts.some((artifact) => artifact?.field === field); - if (!hasField('outPath')) { - const performance = pendingPerformanceArtifact(req, data); - if (performance) artifacts.push(performance); - } - return artifacts.filter((artifact): artifact is PendingArtifact => - Boolean( - artifact && - typeof artifact.field === 'string' && - typeof artifact.path === 'string' && - (ownership === 'daemon' || - daemonDeliveredArtifact(artifact) !== undefined || - (req.internal?.publicNetworkOnly && !['record', 'perf', 'trace'].includes(req.command)) || - (typeof artifact.localPath === 'string' && artifact.localPath.length > 0) || - (artifact.field === 'fallbackScreenshotPath' && artifact.artifactType === 'screenshot')), - ), - ); -} - -function pendingPerformanceArtifact( - req: DaemonRequest, - data: DaemonResponseData, -): PendingArtifact | undefined { - if (captureOutputOwnership(data) !== 'daemon' || req.command !== 'perf') return undefined; - const capture = isRecord(data.artifact) ? data.artifact : undefined; - const artifactPath = - typeof capture?.path === 'string' ? capture.path : performanceResponseOutputPath(req, data); - if (typeof artifactPath !== 'string') return undefined; - return { - field: 'outPath', - artifactType: 'performance', - path: artifactPath, - localPath: - req.meta?.clientArtifactPaths?.outPath ?? - (typeof data.clientOutPath === 'string' ? data.clientOutPath : undefined), - fileName: path.basename(artifactPath), - ...(req.positionals?.[0]?.toLowerCase() === 'cpu' && - req.positionals?.[2]?.toLowerCase() === 'stop' - ? { deleteAfterDownload: false } - : {}), - }; -} - -function performanceResponseOutputPath(req: DaemonRequest, data: DaemonResponseData): unknown { - const [area, operation, action] = (req.positionals ?? []).map((value) => value.toLowerCase()); - if (action === 'report' || action === 'stop') return data.outPath; - if (area === 'trace' && operation === 'stop') return data.outPath; - return undefined; } /** diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index df898520cc3..8562d7747e4 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -30,10 +30,7 @@ import { } from '@agent-device/kernel/contracts'; import { namesSessionExplicitly } from '@agent-device/kernel/record'; import type { CloudArtifactProvider } from '@agent-device/contracts/observability'; -import { - settleCommittedFileOutputs, - type TrackDownloadableArtifact, -} from '../resources/artifact-tracking.ts'; +import { settleCommittedFileOutputs } from '../resources/artifact-tracking.ts'; import type { RequestPlatformProviderScope, RequestPlatformProviders, @@ -179,7 +176,6 @@ export type RequestRouterDeps = { /** ADR 0029: the daemon policy every admitted request, including nested steps, obeys. */ daemonPolicy?: DaemonPolicy; admitAttachment?: (req: DaemonRequest) => DaemonRequest; - trackDownloadableArtifact: TrackDownloadableArtifact; }; export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { @@ -209,7 +205,6 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { platformResourceCleanup, leaseSessionEnd, providerDeviceRuntimeScope, - trackDownloadableArtifact, daemonPolicy, admitAttachment, } = deps; @@ -323,11 +318,7 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { saveScriptFlagResponse(req, sessionStore.host.cwd) ?? deviceSpecFlagsResponse(req); if (refusal) { - return redactForMacOsAppLease( - req, - undefined, - finalizeDaemonResponse(req, refusal, trackDownloadableArtifact), - ); + return redactForMacOsAppLease(req, undefined, finalizeDaemonResponse(refusal)); } if (req.command === 'replay' || req.command === 'test') { @@ -391,7 +382,6 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { const locked = await prepareLockedRequestScope({ scope, sessionStore, - trackDownloadableArtifact, }); if (locked.type === 'response') return locked.response; const lockedScope = locked.scope; diff --git a/packages/daemon/src/server/resumable-upload.ts b/packages/daemon/src/server/resumable-upload.ts index af3536a0f5a..71c46ce2d70 100644 --- a/packages/daemon/src/server/resumable-upload.ts +++ b/packages/daemon/src/server/resumable-upload.ts @@ -1,3 +1,9 @@ +import { + assertArtifactOwner, + type ArtifactOwner, + removeStagedUpload, + removeStagedUploadAsync, +} from '../resources/artifact-tracking.ts'; import { runtimeSlot } from '@agent-device/host-kit/runtime-slots'; import crypto from 'node:crypto'; import fs from 'node:fs'; @@ -7,7 +13,7 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import { extractTarInstallableArtifact } from './artifact-archive.ts'; import { - requireTenantOwnedEntry, + expiredTenantOwnedEntryError, TENANT_RESOURCE_REASONS, type TenantOwnedResourceKind, } from '../core/tenant-owned-entry.ts'; @@ -18,11 +24,14 @@ import { } from './artifact-download.ts'; import { computeUploadHash, receiveResumableTransfer } from './resumable-upload-transfer.ts'; import { resolveIngressFailure, throwIfIngressAborted } from './upload-ingress.ts'; +import { reserveUploadCapacity, type UploadCapacityReservation } from './upload-capacity.ts'; const UPLOAD_FINALIZE_REASONS = { // Finalizing the upload failed, and removing its staged files failed too; `details.originalError` // holds the first failure. cleanupFailed: { reason: 'UPLOAD_FINALIZE_CLEANUP_FAILED' }, + // 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; @@ -43,11 +52,7 @@ const resumableUploads = (): ResumableUploadState => (state) => { for (const entry of state.byId.values()) { clearTimeout(entry.timer); - try { - fs.rmSync(entry.tempDir, { recursive: true, force: true }); - } catch { - // best-effort cleanup only - } + removeStagedUpload(entry.tempDir, entry.reservation.release); } }, ); @@ -64,7 +69,7 @@ export type BeginResumableUploadOptions = { artifactType: 'file' | 'app-bundle'; platform?: string; contentType?: string; - tenantId?: string; + owner: ArtifactOwner; }; type ResumableUploadEntry = { @@ -77,14 +82,14 @@ type ResumableUploadEntry = { sha256: string; artifactType: 'file' | 'app-bundle'; platform?: string; - tenantId?: string; + owner: ArtifactOwner; timer?: ReturnType; generation: number; tail: Promise; /** Aborts the active receive with the ticket's typed expiry. */ activeReceive?: AbortController; closed: boolean; - finalized: boolean; + reservation: UploadCapacityReservation; }; type ResumableUploadTicket = { @@ -113,9 +118,8 @@ export function beginResumableUpload( try { publish(ticket); } catch (error) { - if (!existing) { - closeEntry(entry); - fs.rmSync(entry.tempDir, { recursive: true, force: true }); + if (!existing && closeEntry(entry)) { + removeStagedUpload(entry.tempDir, entry.reservation.release); } throw error; } @@ -145,14 +149,14 @@ function describeResumableUploadTicket( export async function receiveResumableUploadChunk(params: { uploadId: string; req: IncomingMessage; - tenantId?: string; + owner: ArtifactOwner; 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.owner); // 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(); @@ -200,10 +204,10 @@ export type FinalizeUploadIngressLink = { export async function finalizeResumableUpload( uploadId: string, - tenantId?: string, + owner: ArtifactOwner, ingress?: FinalizeUploadIngressLink, -): Promise<{ artifactPath: string; tempDir: string }> { - const entry = requireResumableUpload(uploadId, tenantId); +): Promise<{ artifactPath: string; tempDir: string; releaseReservation: () => void }> { + const entry = requireResumableUpload(uploadId, owner); const signal = ingress?.signal; // The owner's typed expiry, including a recorded deadline whose timer has not run yet. const ensureActive = () => { @@ -231,7 +235,8 @@ export async function finalizeResumableUpload( } // A complete finalize is active work that owns the entry: disarm the idle timer so // expiry cannot fire during the post-write checks (hash, extraction, rename). Both - // terminal outcomes close the entry and clean up through closeEntry (#4441). + // terminal outcomes close the entry; failed finalize removes staged bytes before + // releasing capacity (#4441). disarmResumableUploadTimer(entry); try { ensureActive(); @@ -246,8 +251,12 @@ export async function finalizeResumableUpload( ensureActive(); const artifactPath = await materializeFinalArtifact(entry, signal); ensureActive(); - markFinalized(entry); - return { artifactPath, tempDir: entry.tempDir }; + closeEntry(entry); + return { + artifactPath, + tempDir: entry.tempDir, + releaseReservation: entry.reservation.release, + }; } catch (error) { // Joined cleanup runs on every terminal failure; the typed first failure — // including an abort-owned one mapped back to the owner's reason — is rethrown. @@ -263,29 +272,37 @@ function createResumableUploadEntry( key: string, ): ResumableUploadEntry { const id = crypto.randomUUID(); - const tempDir = createArtifactTempDir('upload'); - const payloadPath = path.join(tempDir, 'payload'); - fs.writeFileSync(payloadPath, ''); - const entry: ResumableUploadEntry = { - id, - key, - tempDir, - payloadPath, - fileName: sanitizeArtifactFilename(options.fileName), - sizeBytes: options.sizeBytes, - sha256: options.sha256.toLowerCase(), - artifactType: options.artifactType, - platform: options.platform, - tenantId: options.tenantId, - generation: 0, - tail: Promise.resolve(), - closed: false, - finalized: false, - }; - RESUMABLE_UPLOADS_BY_ID().set(id, entry); - RESUMABLE_UPLOADS_BY_KEY().set(key, id); - refreshResumableUploadTimer(entry); - return entry; + const reservation = reserveUploadCapacity(options.owner.tenantId, options.sizeBytes); + let tempDir: string | undefined; + try { + tempDir = createArtifactTempDir('upload'); + const payloadPath = path.join(tempDir, 'payload'); + fs.writeFileSync(payloadPath, ''); + const entry: ResumableUploadEntry = { + id, + key, + tempDir, + payloadPath, + fileName: sanitizeArtifactFilename(options.fileName), + sizeBytes: options.sizeBytes, + sha256: options.sha256.toLowerCase(), + artifactType: options.artifactType, + platform: options.platform, + owner: options.owner, + generation: 0, + tail: Promise.resolve(), + closed: false, + reservation, + }; + RESUMABLE_UPLOADS_BY_ID().set(id, entry); + RESUMABLE_UPLOADS_BY_KEY().set(key, id); + refreshResumableUploadTimer(entry); + return entry; + } catch (error) { + if (tempDir) removeStagedUpload(tempDir, reservation.release); + else reservation.release(); + throw error; + } } function refreshResumableUploadTimer(entry: ResumableUploadEntry): void { @@ -310,15 +327,14 @@ function disarmResumableUploadTimer(entry: ResumableUploadEntry): void { } function expireEntry(entry: ResumableUploadEntry, generation: number): void { - if (entry.generation !== generation || entry.closed) return; - closeEntry(entry); + if (entry.generation !== generation || !closeEntry(entry)) return; entry.activeReceive?.abort( new AppError('COMMAND_FAILED', 'Upload expired while receiving data', { reason: TENANT_RESOURCE_REASONS.expired.reason, }), ); const cleanup = entry.tail.then(async () => { - if (!entry.finalized) await fs.promises.rm(entry.tempDir, { recursive: true, force: true }); + await removeStagedUploadAsync(entry.tempDir, entry.reservation.release); }); entry.tail = cleanup.catch(() => {}); } @@ -341,7 +357,7 @@ async function runExclusive( throwIfIngressAborted(signal); }, ); - if (entry.closed) requireResumableUpload(entry.id, entry.tenantId); + if (entry.closed) requireResumableUpload(entry.id, entry.owner); // 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); @@ -370,29 +386,30 @@ async function materializeFinalArtifact( await fs.promises.rename(entry.payloadPath, artifactPath); return artifactPath; } + let expandedBytes = 0; const artifactPath = await extractTarInstallableArtifact({ archivePath: entry.payloadPath, tempDir: entry.tempDir, platform: entry.platform === 'android' ? 'android' : 'ios', expectedRootName: entry.fileName, signal, + reserveExpandedBytes: (bytes) => { + expandedBytes = bytes; + entry.reservation.addBytes(bytes); + }, }); await fs.promises.rm(entry.payloadPath, { force: true }); + entry.reservation.setBytes(expandedBytes); return artifactPath; } -function markFinalized(entry: ResumableUploadEntry): void { - entry.finalized = true; - closeEntry(entry); -} - async function cleanupTerminalFinalizeFailure( entry: ResumableUploadEntry, originalError: unknown, ): Promise { - closeEntry(entry); + if (!closeEntry(entry)) return originalError; try { - await fs.promises.rm(entry.tempDir, { recursive: true, force: true }); + await removeStagedUploadAsync(entry.tempDir, entry.reservation.release); return originalError; } catch (cleanupError) { return new AppError( @@ -408,27 +425,24 @@ async function cleanupTerminalFinalizeFailure( } async function terminateEntry(entry: ResumableUploadEntry): Promise { - closeEntry(entry); - await fs.promises.rm(entry.tempDir, { recursive: true, force: true }).catch(() => {}); + if (!closeEntry(entry)) return; + await removeStagedUploadAsync(entry.tempDir, entry.reservation.release).catch(() => {}); } -function closeEntry(entry: ResumableUploadEntry): void { +function closeEntry(entry: ResumableUploadEntry): boolean { + if (entry.closed) return false; entry.closed = true; if (entry.timer) clearTimeout(entry.timer); RESUMABLE_UPLOADS_BY_ID().delete(entry.id); RESUMABLE_UPLOADS_BY_KEY().delete(entry.key); + return true; } -function requireResumableUpload( - uploadId: string, - tenantId: string | undefined, -): ResumableUploadEntry { - return requireTenantOwnedEntry( - RESUMABLE_UPLOADS_BY_ID(), - uploadId, - tenantId, - RESUMABLE_UPLOAD_RESOURCE, - ); +function requireResumableUpload(uploadId: string, owner: ArtifactOwner): ResumableUploadEntry { + const entry = RESUMABLE_UPLOADS_BY_ID().get(uploadId); + if (!entry) throw expiredTenantOwnedEntryError(RESUMABLE_UPLOAD_RESOURCE, uploadId); + assertArtifactOwner(entry.owner, owner); + return entry; } function validateResumableUploadOptions(options: BeginResumableUploadOptions): void { @@ -447,7 +461,8 @@ function validateResumableUploadOptions(options: BeginResumableUploadOptions): v function buildResumableUploadKey(options: BeginResumableUploadOptions): string { return [ - options.tenantId ?? '', + options.owner.tenantId ?? '', + options.owner.leaseVerifier ?? '', options.uploadAttemptId, options.sha256.toLowerCase(), String(options.sizeBytes), diff --git a/packages/daemon/src/server/upload-authority.test.ts b/packages/daemon/src/server/upload-authority.test.ts new file mode 100644 index 00000000000..1ada58e1938 --- /dev/null +++ b/packages/daemon/src/server/upload-authority.test.ts @@ -0,0 +1,165 @@ +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { test } from 'vitest'; +import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; +import { + closeLoopbackServer, + listenOnLoopback, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { makeSession } from '../__tests__/support/session-factories.ts'; +import { makeSessionStore } from '../__tests__/support/store-factory.ts'; +import { LeaseRegistry } from '../resources/lease-registry.ts'; +import { + cleanupUploadedArtifact, + leaseVerifier, + prepareUploadedArtifact, +} from '../resources/artifact-tracking.ts'; +import { createDaemonHttpServer } from './http/http-server.ts'; +import { admitUploadAuthority } from './upload-authority.ts'; + +function fixture() { + const registry = new LeaseRegistry(); + const lease = registry.allocateLease({ + tenantId: 'tenant-a', + runId: 'run-a', + retainOnClose: true, + }); + const store = makeSessionStore(); + const ref = store.publish('default', makeSession('default', { lease })); + return { registry, lease, store, ref }; +} + +test('upload admission pins canonical producer, checks supplied claims and session lifetime', () => { + const { registry, lease, store, ref } = fixture(); + const controller = new AbortController(); + const admit = (headers: http.IncomingHttpHeaders, tenantId = 'tenant-a') => + admitUploadAuthority({ + req: { headers } as http.IncomingMessage, + auth: { tenantId }, + leaseRegistry: registry, + sessionStore: store, + signal: controller.signal, + }); + assert.throws(() => admit({ 'x-agent-device-session': 'default' }), /Send its lease id/); + assert.throws(() => admit({ 'x-agent-device-lease-id': lease.leaseId }, 'tenant-b'), /tenant/); + assert.throws( + () => admit({ 'x-agent-device-lease-id': lease.leaseId, 'x-agent-device-run-id': 'wrong' }), + /runId/, + ); + const admitted = admit({ + 'x-agent-device-lease-id': lease.leaseId.toUpperCase(), + 'x-agent-device-session': 'default', + }); + assert.deepEqual(admitted.owner, { + tenantId: 'tenant-a', + leaseVerifier: leaseVerifier(lease.leaseId), + }); + admitted.assertCurrent(); + store.retire(ref); + store.publish('default', makeSession('default', { lease })); + assert.throws( + () => admitted.assertCurrent(), + (error: unknown) => + (error as { details?: { reason: string } }).details?.reason === 'session_lifetime_ended', + ); + admitted.release(); + admitted.release(); +}); + +test('an upload lease pass protects work only while the transfer is wanted', () => { + let now = Date.now(); + const registry = new LeaseRegistry({ now: () => now, minLeaseTtlMs: 1, defaultLeaseTtlMs: 10 }); + const lease = registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-a' }); + const canceled = new AbortController(); + const authority = admitUploadAuthority({ + req: { headers: { 'x-agent-device-lease-id': lease.leaseId } } as http.IncomingMessage, + auth: { tenantId: 'tenant-a' }, + leaseRegistry: registry, + signal: canceled.signal, + }); + now += 11; + authority.assertCurrent(); + assert.ok(registry.inspectActiveLease(lease.leaseId)); + canceled.abort(); + assert.equal(registry.inspectActiveLease(lease.leaseId), undefined); + authority.release(); +}); + +test('hookless HTTP refuses a leased session before file bytes, then stages and consumes the admitted scope', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { registry, lease, store } = fixture(); + const runtime = createRuntimeStateHandle(); + const env = { ...process.env }; + delete env.AGENT_DEVICE_HTTP_AUTH_HOOK; + const server = await runtime.run(() => + createDaemonHttpServer({ + token: 'test-token', + cwd: process.cwd(), + env, + leaseRegistry: registry, + sessionStore: store, + handleRequest: async () => ({ ok: true }), + }), + ); + const port = await listenOnLoopback(server); + let request: http.ClientRequest | undefined; + try { + const refused = await new Promise((resolve, reject) => { + request = http.request( + { + host: '127.0.0.1', + port, + path: '/upload', + method: 'POST', + headers: { + authorization: 'Bearer test-token', + 'x-agent-device-tenant': 'tenant-a', + 'x-agent-device-session': 'default', + 'x-artifact-type': 'file', + 'x-artifact-filename': 'app.apk', + 'content-length': '1000000', + }, + }, + (res) => { + res.resume(); + res.on('end', () => resolve(res.statusCode!)); + }, + ); + request.on('error', reject); + request.flushHeaders(); + }); + assert.equal(refused, 401); + request.destroy(); + const response = await fetch(`http://127.0.0.1:${port}/upload`, { + method: 'POST', + headers: { + authorization: 'Bearer test-token', + 'x-agent-device-tenant': 'tenant-a', + 'x-agent-device-session': 'default', + 'x-agent-device-lease-id': lease.leaseId, + 'x-artifact-type': 'file', + 'x-artifact-filename': 'app.apk', + }, + body: 'app-bytes', + }); + assert.equal(response.status, 200); + const { uploadId } = (await response.json()) as { uploadId: string }; + runtime.run(() => { + assert.throws( + () => prepareUploadedArtifact(uploadId, { tenantId: 'tenant-a', leaseVerifier: null }), + /belongs to a device lease/, + ); + const artifact = prepareUploadedArtifact(uploadId, { + tenantId: 'tenant-a', + leaseVerifier: leaseVerifier(lease.leaseId), + }); + assert.ok(artifact.endsWith('app.apk')); + cleanupUploadedArtifact(uploadId); + }); + } finally { + request?.destroy(); + await closeLoopbackServer(server); + runtime.dispose(); + } +}); diff --git a/packages/daemon/src/server/upload-authority.ts b/packages/daemon/src/server/upload-authority.ts new file mode 100644 index 00000000000..8e12df1d86d --- /dev/null +++ b/packages/daemon/src/server/upload-authority.ts @@ -0,0 +1,120 @@ +import type { IncomingMessage } from 'node:http'; +import { AppError } from '@agent-device/kernel/errors'; +import { + DAEMON_HTTP_LEASE_HEADER, + DAEMON_HTTP_RUN_HEADER, + normalizeTenantId, + DAEMON_HTTP_TENANT_HEADER, + DAEMON_HTTP_UPLOAD_SESSION_HEADER, +} from '@agent-device/contracts/daemon-http'; +import { LEASE_REASONS, normalizeLeaseId } from '@agent-device/contracts/lease-scope'; +import { assertRequestPresentsLease, withDisplacedLeaseClaims } from '../core/lease-context.ts'; +import type { SessionStore } from '../core/session-store.ts'; +import type { LeaseRegistry } from '../resources/lease-registry.ts'; +import { leaseVerifier, type ArtifactOwner } from '../resources/artifact-tracking.ts'; +import { + resolveRequestSessionName, + resolveRequestSessionRef, + scopeRequestSession, +} from '../sessions/request-admission.ts'; +import type { DaemonRequest } from '../core/daemon-request.ts'; +import type { TenantSessionNamespace } from '../core/session-tenant-scope.ts'; + +export type UploadAuthority = { + principal: 'local' | 'declared' | 'attested'; + owner: ArtifactOwner; + assertCurrent(): void; + release(): void; +}; + +/** Admits staging before file bytes arrive. A session never confers its lease credential. */ +export function admitUploadAuthority(params: { + req: IncomingMessage; + auth: { tenantId?: string; sessionNamespace?: TenantSessionNamespace }; + leaseRegistry?: LeaseRegistry; + sessionStore?: SessionStore; + signal: AbortSignal; +}): UploadAuthority { + const { req, auth, leaseRegistry, sessionStore, signal } = params; + const header = (name: string): string | undefined => { + const value = req.headers[name]; + if (value === undefined) return undefined; + if (typeof value !== 'string') throw new AppError('INVALID_ARGS', `Invalid ${name}`); + return value; + }; + const rawLease = header(DAEMON_HTTP_LEASE_HEADER); + const leaseId = normalizeLeaseId(rawLease); + if (rawLease?.trim() && !leaseId) throw new AppError('INVALID_ARGS', 'Invalid lease id.'); + const runId = header(DAEMON_HTTP_RUN_HEADER); + const tenantId = normalizeTenantId(auth.tenantId); + const session = header(DAEMON_HTTP_UPLOAD_SESSION_HEADER); + const request: DaemonRequest = withDisplacedLeaseClaims( + scopeRequestSession({ + token: '', + session: session ?? 'default', + command: 'install', + positionals: [], + meta: { + tenantId, + leaseId, + runId, + ...(auth.sessionNamespace?.partitioned ? { sessionIsolation: 'tenant' } : {}), + }, + }), + { + tenantId: [header(DAEMON_HTTP_TENANT_HEADER)].filter( + (value) => value !== undefined && value !== tenantId, + ), + }, + ); + if (session !== undefined && !sessionStore) { + throw new AppError('UNAUTHORIZED', 'This daemon cannot admit the addressed upload session.', { + reason: LEASE_REASONS.scopeMismatch.reason, + field: 'session', + }); + } + const ref = + sessionStore && leaseRegistry + ? resolveRequestSessionRef( + request, + sessionStore.lookup( + resolveRequestSessionName({ + scopedReq: request, + unscopedReq: request, + sessionStore, + leaseRegistry, + }), + ), + leaseRegistry, + ) + : undefined; + const lease = leaseId ? leaseRegistry?.inspectActiveLease(leaseId) : undefined; + if (leaseId) { + if (!tenantId || !lease || lease.tenantId !== tenantId) { + throw new AppError( + 'UNAUTHORIZED', + 'Upload requires an active lease owned by the authenticated tenant.', + { reason: LEASE_REASONS.scopeMismatch.reason }, + ); + } + assertRequestPresentsLease(request, lease); + } + const leaseIsCurrent = lease && leaseRegistry!.pinActiveLease(lease.leaseId); + const work = lease && leaseRegistry!.retainLeaseWork(lease, () => !signal.aborted); + return { + principal: auth.sessionNamespace?.partitioned ? 'attested' : tenantId ? 'declared' : 'local', + owner: { tenantId, leaseVerifier: lease ? leaseVerifier(lease.leaseId) : null }, + assertCurrent() { + signal.throwIfAborted(); + if (ref) sessionStore!.requireCurrent(ref); + if (lease && !leaseIsCurrent!()) { + throw new AppError('UNAUTHORIZED', 'Upload lease ended during transfer.', { + reason: LEASE_REASONS.notFound.reason, + }); + } + }, + release() { + work?.release(); + }, + }; +} diff --git a/packages/daemon/src/server/upload-capacity.ts b/packages/daemon/src/server/upload-capacity.ts new file mode 100644 index 00000000000..102e7f753a3 --- /dev/null +++ b/packages/daemon/src/server/upload-capacity.ts @@ -0,0 +1,83 @@ +import { runtimeSlot } from '@agent-device/host-kit/runtime-slots'; +import { AppError } from '@agent-device/kernel/errors'; +import { UPLOAD_CAPACITY_REASONS } from '@agent-device/contracts/daemon-http'; +import { + MAX_ARCHIVE_EXPANDED_BYTES, + MAX_ARTIFACT_COMPRESSED_BYTES, +} from '@agent-device/host-kit/archive'; + +const MAX_UPLOADS_PER_TENANT = 32; +const MAX_UPLOADS_TOTAL = 256; +const MAX_BYTES_PER_TENANT = MAX_ARTIFACT_COMPRESSED_BYTES + MAX_ARCHIVE_EXPANDED_BYTES; +const MAX_BYTES_TOTAL = 16 * 1024 * 1024 * 1024; + +type Reservation = { tenantId?: string; bytes: number }; +export type UploadCapacityReservation = { + release: () => void; + addBytes: (bytes: number) => void; + setBytes: (bytes: number) => void; +}; +const UPLOAD_CAPACITY_SLOT = Symbol('uploadCapacity'); +const reservations = () => runtimeSlot(UPLOAD_CAPACITY_SLOT, () => new Set()); + +/** Reserve staged bytes before creating a staging directory; release after consumption or expiry. */ +export function reserveUploadCapacity( + tenantId: string | undefined, + bytes: number, +): UploadCapacityReservation { + const active = reservations(); + const reservation = { tenantId, bytes: 0 }; + let released = false; + const setBytes = (nextBytes: number) => { + if (released) throw new AppError('COMMAND_FAILED', 'Upload reservation is released'); + if (!Number.isSafeInteger(nextBytes) || nextBytes < 0) { + throw new AppError('INVALID_ARGS', 'Invalid staged upload size'); + } + let tenantCount = 1; + let totalCount = 1; + let occupiedTenantBytes = nextBytes; + let occupiedTotalBytes = nextBytes; + for (const current of active) { + if (current === reservation) continue; + totalCount += 1; + occupiedTotalBytes += current.bytes; + if (current.tenantId === tenantId) { + tenantCount += 1; + occupiedTenantBytes += current.bytes; + } + } + const refusal = [ + { scope: 'tenant', dimension: 'count', value: tenantCount, limit: MAX_UPLOADS_PER_TENANT }, + { scope: 'daemon', dimension: 'count', value: totalCount, limit: MAX_UPLOADS_TOTAL }, + { + scope: 'tenant', + dimension: 'bytes', + value: occupiedTenantBytes, + limit: MAX_BYTES_PER_TENANT, + }, + { scope: 'daemon', dimension: 'bytes', value: occupiedTotalBytes, limit: MAX_BYTES_TOTAL }, + ].find(({ value, limit }) => value > limit); + if (refusal) { + throw new AppError('COMMAND_FAILED', 'Upload capacity exceeded', { + reason: UPLOAD_CAPACITY_REASONS.exceeded.reason, + resource: 'staged-upload', + scope: refusal.scope, + dimension: refusal.dimension, + limit: refusal.limit, + retriable: true, + }); + } + reservation.bytes = nextBytes; + }; + setBytes(bytes); + active.add(reservation); + return { + release: () => { + if (released) return; + released = true; + active.delete(reservation); + }, + addBytes: (additionalBytes) => setBytes(reservation.bytes + additionalBytes), + setBytes, + }; +} diff --git a/packages/daemon/src/server/upload-http.ts b/packages/daemon/src/server/upload-http.ts index 666161a39a3..a31f1a8816b 100644 --- a/packages/daemon/src/server/upload-http.ts +++ b/packages/daemon/src/server/upload-http.ts @@ -1,8 +1,16 @@ -import fs from 'node:fs'; +import type { SessionStore } from '../core/session-store.ts'; +import type { LeaseRegistry } from '../resources/lease-registry.ts'; +import type { TenantSessionNamespace } from '../core/session-tenant-scope.ts'; +import { admitUploadAuthority, type UploadAuthority } from './upload-authority.ts'; +import { reserveUploadCapacity } from './upload-capacity.ts'; import http from 'node:http'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; import type { DaemonRequest } from '../core/daemon-request.ts'; -import { trackUploadedArtifact } from '../resources/artifact-tracking.ts'; +import { + trackUploadedArtifact, + removeStagedUpload, + type ArtifactOwner, +} from '../resources/artifact-tracking.ts'; import { type BeginResumableUploadOptions, beginResumableUpload, @@ -45,7 +53,10 @@ type AuxiliaryHttpAuthorizer = (params: { signal: AbortSignal; /** The upload ingress commit gate: a refusal after the hook answers through it. */ commit: (work: () => T) => T; -}) => Promise<{ tenantId?: string } | null>; +}) => Promise<{ tenantId?: string; sessionNamespace?: TenantSessionNamespace } | null>; +type AdmittedUploadAuthorizer = ( + request: Parameters[0], +) => Promise; export function tryHandleUploadHttpRoute(params: { req: http.IncomingMessage; @@ -53,12 +64,18 @@ export function tryHandleUploadHttpRoute(params: { authorize: AuxiliaryHttpAuthorizer; token: string; origin: string; + leaseRegistry?: LeaseRegistry; + sessionStore?: SessionStore; }): boolean { const { req, res, authorize, token, origin } = params; const route = resolveUploadHttpRoute(req); if (route === null) return false; - void handleUploadHttpRoute(route, req, res, authorize, token, origin); + const admit: AdmittedUploadAuthorizer = async (request) => { + const auth = await authorize(request); + return auth ? admitUploadAuthority({ ...params, req, auth, signal: request.signal }) : null; + }; + void handleUploadHttpRoute(route, req, res, admit, token, origin); return true; } @@ -66,7 +83,7 @@ async function handleUploadHttpRoute( route: UploadHttpRoute, req: http.IncomingMessage, res: http.ServerResponse, - authorize: AuxiliaryHttpAuthorizer, + authorize: AdmittedUploadAuthorizer, token: string, origin: string, ): Promise { @@ -108,30 +125,40 @@ function resolveUploadHttpRoute(req: http.IncomingMessage): UploadHttpRoute | nu async function runUploadRoute( req: http.IncomingMessage, res: http.ServerResponse, - authorize: AuxiliaryHttpAuthorizer, + authorize: AdmittedUploadAuthorizer, positionals: string[], - handle: (auth: { tenantId?: string }, ingress: UploadTransferIngress) => Promise, + handle: (auth: UploadAuthority, ingress: UploadTransferIngress) => Promise, ): Promise { const ingress = beginUploadTransferIngress({ req, res }); + let auth: UploadAuthority | null = null; try { - const auth = await authorizeUpload(authorize, req, res, ingress, positionals); + auth = await authorizeUpload(authorize, req, res, ingress, positionals); if (!auth) return; - await handle(auth, ingress); + const admitted = auth; + await handle(admitted, { + ...ingress, + commit: (work) => + ingress.commit(() => { + admitted.assertCurrent(); + return work(); + }), + }); } catch (error) { answerUploadFailure(res, error, ingress.commit); } finally { + auth?.release(); ingress.dispose(); } } /** The upload command and positionals the auth hook sees, under the ingress signal. */ async function authorizeUpload( - authorize: AuxiliaryHttpAuthorizer, + authorize: AdmittedUploadAuthorizer, req: http.IncomingMessage, res: http.ServerResponse, ingress: { signal: AbortSignal; commit: (work: () => T) => T }, positionals: string[], -): Promise<{ tenantId?: string } | null> { +): Promise { return await authorize({ req, res, @@ -144,17 +171,18 @@ async function authorizeUpload( async function handleUpload( req: http.IncomingMessage, res: http.ServerResponse, - authorize: AuxiliaryHttpAuthorizer, + authorize: AdmittedUploadAuthorizer, ): Promise { await runUploadRoute(req, res, authorize, [], async (auth, ingress) => { sendUploadedArtifactResponse( res, await receiveUpload(req, { + reserveCapacity: (bytes) => reserveUploadCapacity(auth.owner.tenantId, bytes), signal: ingress.signal, onBodyBytes: (bytes) => ingress.onAcceptedBodyBytes(bytes), onBodyComplete: () => ingress.bodyComplete(), }), - auth.tenantId, + auth.owner, ingress.commit, ); }); @@ -163,7 +191,7 @@ async function handleUpload( async function handleUploadPreflight( req: http.IncomingMessage, res: http.ServerResponse, - authorize: AuxiliaryHttpAuthorizer, + authorize: AdmittedUploadAuthorizer, token: string, origin: string, ): Promise { @@ -181,7 +209,7 @@ async function handleUploadPreflight( baseUrl: origin, tokenHeaders: buildUploadTicketAuthHeaders(token), ...preflight, - tenantId: auth.tenantId, + owner: auth.owner, }, (upload) => ingress.commit(() => sendJson(res, { ok: true, ...upload })), ); @@ -192,13 +220,13 @@ async function handleResumableUpload( uploadId: string, req: http.IncomingMessage, res: http.ServerResponse, - authorize: AuxiliaryHttpAuthorizer, + authorize: AdmittedUploadAuthorizer, ): Promise { await runUploadRoute(req, res, authorize, ['direct', uploadId], async (auth, ingress) => { const result = await receiveResumableUploadChunk({ uploadId, req, - tenantId: auth.tenantId, + owner: auth.owner, signal: ingress.signal, commit: ingress.commit, onAcceptedBytes: (bytes) => ingress.onAcceptedBodyBytes(bytes), @@ -223,7 +251,7 @@ async function handleResumableUpload( async function handleUploadFinalize( req: http.IncomingMessage, res: http.ServerResponse, - authorize: AuxiliaryHttpAuthorizer, + authorize: AdmittedUploadAuthorizer, ): Promise { await runUploadRoute(req, res, authorize, ['finalize'], async (auth, ingress) => { const body = await readRestJsonBody(req, 64 * 1024, ingress.onAcceptedBodyBytes); @@ -235,11 +263,11 @@ 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, { + await finalizeResumableUpload(finalize.uploadId, auth.owner, { signal: ingress.signal, commit: ingress.commit, }), - auth.tenantId, + auth.owner, ingress.commit, ); }); @@ -258,8 +286,8 @@ function sendJson(res: http.ServerResponse, body: Record): void */ function sendUploadedArtifactResponse( res: http.ServerResponse, - result: { artifactPath: string; tempDir: string }, - tenantId: string | undefined, + result: { artifactPath: string; tempDir: string; releaseReservation?: () => void }, + owner: ArtifactOwner, commit: (work: () => T) => T, ): void { let registered = false; @@ -268,13 +296,14 @@ function sendUploadedArtifactResponse( const uploadId = trackUploadedArtifact({ artifactPath: result.artifactPath, tempDir: result.tempDir, - tenantId, + owner, + releaseReservation: result.releaseReservation, }); registered = true; sendJson(res, { ok: true, uploadId }); }); } catch (error) { - if (!registered) fs.rmSync(result.tempDir, { recursive: true, force: true }); + if (!registered) removeStagedUpload(result.tempDir, result.releaseReservation); throw error; } } diff --git a/packages/daemon/src/server/upload.ts b/packages/daemon/src/server/upload.ts index ab1532ee554..03a0aaa6a65 100644 --- a/packages/daemon/src/server/upload.ts +++ b/packages/daemon/src/server/upload.ts @@ -1,3 +1,4 @@ +import { removeStagedUpload } from '../resources/artifact-tracking.ts'; import fs from 'node:fs'; import path from 'node:path'; import type { IncomingMessage } from 'node:http'; @@ -18,6 +19,7 @@ import { pipeRequestBody, } from './resumable-upload-transfer.ts'; import { resolveIngressFailure, throwIfIngressAborted } from './upload-ingress.ts'; +import type { UploadCapacityReservation } from './upload-capacity.ts'; /** * The ingress owner a single-shot upload runs under (#4441): its signal aborts the joined @@ -28,12 +30,13 @@ export type UploadIngressLink = { signal?: AbortSignal; onBodyBytes?: (bytes: number) => void; onBodyComplete?: () => void; + reserveCapacity?: (bytes: number) => UploadCapacityReservation; }; export async function receiveUpload( req: IncomingMessage, ingress?: UploadIngressLink, -): Promise<{ artifactPath: string; tempDir: string }> { +): Promise<{ artifactPath: string; tempDir: string; releaseReservation?: () => void }> { const artifactType = req.headers['x-artifact-type'] as string | undefined; const rawFilename = req.headers['x-artifact-filename'] as string | undefined; if (!artifactType || !rawFilename) { @@ -49,41 +52,47 @@ export async function receiveUpload( ); } - validateArtifactContentLength(req.headers['content-length']); + const declaredBytes = validateArtifactContentLength(req.headers['content-length']); const expectedSha256 = readExpectedUploadSha256(req); const artifactFilename = sanitizeArtifactFilename(rawFilename); - const tempDir = createArtifactTempDir('upload'); + const reservation = ingress?.reserveCapacity?.(declaredBytes ?? 0); + let tempDir: string | undefined; try { + tempDir = createArtifactTempDir('upload'); + const releaseReservation = reservation?.release; + const reserveBodyBytes = declaredBytes === undefined ? reservation?.addBytes : undefined; + const payloadPath = path.join( + tempDir, + artifactType === 'file' ? artifactFilename : 'artifact.tar', + ); + await receiveUploadBody(req, payloadPath, ingress, reserveBodyBytes); + throwIfIngressAborted(ingress?.signal); + await verifyUploadSha256(payloadPath, expectedSha256, ingress?.signal); if (artifactType === 'file') { - const artifactPath = path.join(tempDir, artifactFilename); - await receiveUploadBody(req, artifactPath, ingress); - // Hashing reads only the bounded file just received under the ingress owner's - // signal; the check keeps an already-fired owner authoritative even when no - // hash header was sent. - throwIfIngressAborted(ingress?.signal); - await verifyUploadSha256(artifactPath, expectedSha256, ingress?.signal); - return { artifactPath, tempDir }; + return { artifactPath: payloadPath, tempDir, releaseReservation }; } - - const archivePath = path.join(tempDir, 'artifact.tar'); - await receiveUploadBody(req, archivePath, ingress); - throwIfIngressAborted(ingress?.signal); - await verifyUploadSha256(archivePath, expectedSha256, ingress?.signal); throwIfIngressAborted(ingress?.signal); // Extraction reads only the archive just received, which the body pipeline capped // at MAX_ARTIFACT_COMPRESSED_BYTES; the owner's signal destroys the extraction // stream mid-phase instead of admitting unbounded work behind the byte cap. + let expandedBytes = 0; const artifactPath = await extractTarInstallableArtifact({ - archivePath, + archivePath: payloadPath, tempDir, platform: 'ios', expectedRootName: artifactFilename, signal: ingress?.signal, + reserveExpandedBytes: (bytes) => { + reservation?.addBytes(bytes); + expandedBytes = bytes; + }, }); - fs.rmSync(archivePath, { force: true }); - return { artifactPath, tempDir }; + fs.rmSync(payloadPath, { force: true }); + reservation?.setBytes(expandedBytes); + return { artifactPath, tempDir, releaseReservation }; } catch (error) { - fs.rmSync(tempDir, { recursive: true, force: true }); + if (tempDir) removeStagedUpload(tempDir, reservation?.release); + else reservation?.release(); throw resolveIngressFailure(ingress?.signal, error); } } @@ -100,9 +109,11 @@ async function receiveUploadBody( req: IncomingMessage, destPath: string, ingress?: UploadIngressLink, + reserveBodyBytes?: (bytes: number) => void, ): Promise { const byteLimit = createByteLimitStream({ maxBytes: MAX_ARTIFACT_COMPRESSED_BYTES, + acceptBytes: reserveBodyBytes, createLimitError: () => new AppError( 'INVALID_ARGS', diff --git a/packages/daemon/src/sessions/__tests__/install-source-resolution.test.ts b/packages/daemon/src/sessions/__tests__/install-source-resolution.test.ts index d1697117525..587003a401a 100644 --- a/packages/daemon/src/sessions/__tests__/install-source-resolution.test.ts +++ b/packages/daemon/src/sessions/__tests__/install-source-resolution.test.ts @@ -13,6 +13,12 @@ function makeRequest(meta?: DaemonRequest['meta']): DaemonRequest { command: 'install_source', positionals: [], flags: { platform: 'android' }, + internal: { + admittedArtifactScope: { + principal: 'local', + owner: { tenantId: undefined, leaseVerifier: null }, + }, + }, meta, }; } @@ -21,7 +27,11 @@ test('resolveInstallSource uses uploaded artifact path for uploaded path sources const tempRoot = mkdtempForTestSync('agent-device-install-source-upload-'); const artifactPath = path.join(tempRoot, 'Sample.apk'); fs.writeFileSync(artifactPath, 'apk-binary'); - const uploadedArtifactId = trackUploadedArtifact({ artifactPath, tempDir: tempRoot }); + const uploadedArtifactId = trackUploadedArtifact({ + owner: { tenantId: undefined, leaseVerifier: null }, + artifactPath, + tempDir: tempRoot, + }); const resolved = resolveInstallSource( makeRequest({ @@ -31,6 +41,7 @@ test('resolveInstallSource uses uploaded artifact path for uploaded path sources path: '/Users/dev/Downloads/Sample.apk', }, }), + { tenantId: undefined, leaseVerifier: null }, ); expect(resolved.source.kind).toBe('path'); @@ -52,6 +63,7 @@ test('resolveInstallSource leaves URL sources unchanged even when upload metadat headers: {}, }, }), + { tenantId: undefined, leaseVerifier: null }, ); expect(resolved.source).toEqual({ @@ -73,6 +85,7 @@ test('resolveInstallSource rejects a source kind it cannot materialize', () => { artifactId: 1234567890, } as never, }), + { tenantId: undefined, leaseVerifier: null }, ), ).toThrow(/must be "url" or "path"/); }); @@ -84,6 +97,7 @@ test('resolveInstallSource refuses an unknown upload id rather than reading the uploadedArtifactId: 'not-a-real-upload', installSource: { kind: 'path', path: '/etc/passwd' }, }), + { tenantId: undefined, leaseVerifier: null }, ), ).toThrow(); }); diff --git a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts index b56cf6e149c..dbb6f162512 100644 --- a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts +++ b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts @@ -275,3 +275,20 @@ function makeRequest(overrides: Partial = {}): DaemonRequest { ...overrides, }; } + +test('detached output release keeps presented proof after the producing lease ends', () => { + const req = admitRequestLeaseForLockedScope({ + env: process.env, + leaseRegistry: new LeaseRegistry(), + session: undefined, + req: makeRequest({ + command: 'release_materialized_paths', + meta: { tenantId: 'tenant-a', leaseId: 'a'.repeat(32) }, + }), + }); + expect(req.internal?.admittedLease).toBeUndefined(); + expect(req.internal?.admittedArtifactScope).toMatchObject({ + principal: 'declared', + owner: { tenantId: 'tenant-a', leaseVerifier: expect.any(String) }, + }); +}); 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..6bdba7af0d9 100644 --- a/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts +++ b/packages/daemon/src/sessions/__tests__/materialized-path-registry.test.ts @@ -13,7 +13,11 @@ import { mkdtempForTestSync } from '@agent-device/test-kit'; test.each([1.5, Number.NaN, Number.POSITIVE_INFINITY, 0, -1, 2_147_483_648])( 'retainMaterializedPaths rejects unsupported TTL %s', async (ttlMs) => { - const failure = await retainMaterializedPaths({ installablePath: '/missing', ttlMs }).then( + const failure = await retainMaterializedPaths({ + owner: { tenantId: undefined, leaseVerifier: null }, + installablePath: '/missing', + ttlMs, + }).then( () => null, (error: unknown) => error, ); @@ -31,6 +35,7 @@ test('maximum TTL schedules the supported delay and reports matching expiry', as fs.mkdirSync(appPath); try { const retained = await retainMaterializedPaths({ + owner: { tenantId: undefined, leaseVerifier: null }, installablePath: appPath, ttlMs: 2_147_483_647, }); @@ -54,6 +59,7 @@ test('retainMaterializedPaths copies file and directory artifacts into managed s fs.writeFileSync(path.join(appPath, 'Info.plist'), 'plist'); const retained = await retainMaterializedPaths({ + owner: { tenantId: undefined, leaseVerifier: null }, archivePath, installablePath: appPath, ttlMs: 60_000, @@ -66,7 +72,10 @@ test('retainMaterializedPaths copies file and directory artifacts into managed s assert.equal(fs.readFileSync(retained.archivePath ?? '', 'utf8'), 'archive-bytes'); assert.equal(fs.readFileSync(path.join(retained.installablePath, 'Info.plist'), 'utf8'), 'plist'); - await cleanupRetainedMaterializedPaths(retained.materializationId); + await cleanupRetainedMaterializedPaths(retained.materializationId, { + tenantId: undefined, + leaseVerifier: null, + }); assert.equal(fs.existsSync(retained.archivePath ?? ''), false); assert.equal(fs.existsSync(retained.installablePath), false); @@ -80,6 +89,7 @@ test('cleanupRetainedMaterializedPathsForSession removes retained paths bound to fs.writeFileSync(path.join(appPath, 'Info.plist'), 'plist'); const retained = await retainMaterializedPaths({ + owner: { tenantId: undefined, leaseVerifier: null }, installablePath: appPath, sessionName: 'session-one', ttlMs: 60_000, @@ -93,7 +103,10 @@ test('cleanupRetainedMaterializedPathsForSession removes retained paths bound to }); test('cleanup of unknown materialization reports expiry with a recovery hint', async () => { - const error = await cleanupRetainedMaterializedPaths('missing-id').then( + const error = await cleanupRetainedMaterializedPaths('missing-id', { + tenantId: undefined, + leaseVerifier: null, + }).then( () => null, (error: unknown) => error, ); @@ -111,12 +124,16 @@ test('cleanup of tenant-owned materialization rejects other tenants', async () = fs.mkdirSync(appPath, { recursive: true }); const retained = await retainMaterializedPaths({ + owner: { tenantId: 'tenant-a', leaseVerifier: null }, installablePath: appPath, - tenantId: 'tenant-a', + ttlMs: 60_000, }); - const error = await cleanupRetainedMaterializedPaths(retained.materializationId, 'tenant-b').then( + const error = await cleanupRetainedMaterializedPaths(retained.materializationId, { + tenantId: 'tenant-b', + leaseVerifier: null, + }).then( () => null, (error: unknown) => error, ); @@ -124,7 +141,10 @@ test('cleanup of tenant-owned materialization rejects other tenants', async () = assert.equal((error as AppError).code, 'UNAUTHORIZED'); assert.equal(fs.existsSync(retained.installablePath), true); - await cleanupRetainedMaterializedPaths(retained.materializationId, 'tenant-a'); + await cleanupRetainedMaterializedPaths(retained.materializationId, { + tenantId: 'tenant-a', + leaseVerifier: null, + }); assert.equal(fs.existsSync(retained.installablePath), false); fs.rmSync(tempRoot, { recursive: true, force: true }); }); @@ -135,8 +155,9 @@ test('TTL expiry cleans up tenant-owned materializations without a tenant contex fs.mkdirSync(appPath, { recursive: true }); const retained = await retainMaterializedPaths({ + owner: { tenantId: 'tenant-a', leaseVerifier: null }, installablePath: appPath, - tenantId: 'tenant-a', + ttlMs: 20, }); diff --git a/packages/daemon/src/sessions/__tests__/replay-runtime/application.test.ts b/packages/daemon/src/sessions/__tests__/replay-runtime/application.test.ts index 7a3f2a44ff7..c782941ec63 100644 --- a/packages/daemon/src/sessions/__tests__/replay-runtime/application.test.ts +++ b/packages/daemon/src/sessions/__tests__/replay-runtime/application.test.ts @@ -64,6 +64,7 @@ function testCommand( invoke: (request: DaemonRequest) => Promise, ): ReplayTestCommand { return { + commitArtifact: (artifact) => artifact, ...replayCommand(req, root, sessionStore, invoke), createSession: (sessionName, logPath) => createReplaySession(sessionName, logPath, sessionStore), diff --git a/packages/daemon/src/sessions/__tests__/replay-suite/session-test-command-trust.test.ts b/packages/daemon/src/sessions/__tests__/replay-suite/session-test-command-trust.test.ts index 6e9b26b9329..49bf71f06ca 100644 --- a/packages/daemon/src/sessions/__tests__/replay-suite/session-test-command-trust.test.ts +++ b/packages/daemon/src/sessions/__tests__/replay-suite/session-test-command-trust.test.ts @@ -49,6 +49,7 @@ async function forwardedCommands(publicNetworkOnly?: true): Promise artifact, request: req, host: sessionStore.host, session: createReplaySession('default', path.join(root, 'daemon.log'), sessionStore), diff --git a/packages/daemon/src/sessions/__tests__/replay-suite/session-test-suite-command-video.test.ts b/packages/daemon/src/sessions/__tests__/replay-suite/session-test-suite-command-video.test.ts index 2c4de105e26..83f960e4394 100644 --- a/packages/daemon/src/sessions/__tests__/replay-suite/session-test-suite-command-video.test.ts +++ b/packages/daemon/src/sessions/__tests__/replay-suite/session-test-suite-command-video.test.ts @@ -298,6 +298,7 @@ test('test finalizes replay video exactly once when cancellation arrives after s if (!video) throw new Error('Expected replay video owner'); const responsePromise = runReplayTestCommand({ + commitArtifact: (artifact) => artifact, ...splitReplayCommandRequest(request), host: sessionStore.host, session: createReplaySession('default', path.join(root, 'daemon.log'), sessionStore), diff --git a/packages/daemon/src/sessions/__tests__/request-recording-health.test.ts b/packages/daemon/src/sessions/__tests__/request-recording-health.test.ts index 9242bef4b69..6d2d2699033 100644 --- a/packages/daemon/src/sessions/__tests__/request-recording-health.test.ts +++ b/packages/daemon/src/sessions/__tests__/request-recording-health.test.ts @@ -220,7 +220,6 @@ test.each(['rebuild', 'retire'] as const)( prepareLockedRequestScope({ scope, sessionStore: store, - trackDownloadableArtifact: () => 'artifact', }), ); const outcome = prepared.then( diff --git a/packages/daemon/src/sessions/__tests__/snapshot-custom-actions-platform-guard.test.ts b/packages/daemon/src/sessions/__tests__/snapshot-custom-actions-platform-guard.test.ts index 8f2cc0e3890..4ceedab8937 100644 --- a/packages/daemon/src/sessions/__tests__/snapshot-custom-actions-platform-guard.test.ts +++ b/packages/daemon/src/sessions/__tests__/snapshot-custom-actions-platform-guard.test.ts @@ -60,7 +60,6 @@ function handlerForDevice(device: DeviceInfo) { leaseRegistry: new LeaseRegistry(), deviceInventoryGateways: createTestDeviceInventoryGateways(), deviceRuntimeGateway: snapshotDeviceRuntimeGateway(), - trackDownloadableArtifact: () => 'artifact-id', }); } 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 d87bbe87104..e79c3d4b6aa 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/lease-artifacts.test.ts @@ -73,11 +73,23 @@ test('artifacts lists an owned active and recently released provider session', a await releaseLease(world, lease); world.providerCalls.length = 0; + await assert.rejects( + () => + listArtifacts(world, { + tenantId: 'tenant-a', + runId: 'run-a', + providerSessionId: 'session-tenant-a', + leaseId: 'f'.repeat(32), + }), + /Lease does not match session owner/, + ); + assert.deepEqual(world.providerCalls, []); const released = await listArtifacts(world, { tenantId: 'tenant-a', runId: 'run-a', providerSessionId: 'session-tenant-a', + leaseId: lease.leaseId, }); assert.equal(released.ok, true); assert.deepEqual(world.providerCalls, [ @@ -206,6 +218,7 @@ test('artifacts refuses a released provider session after the retention window', tenantId: 'tenant-a', runId: 'run-a', providerSessionId: 'session-tenant-a', + leaseId: lease.leaseId, }); assert.equal(retained.ok, true); 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..43c8685614f 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,11 @@ 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 uploadedArtifactId = trackUploadedArtifact({ + owner: { tenantId: undefined, leaseVerifier: null }, + artifactPath: appPath, + tempDir: root, + }); mockDeployAppRuntime.mockResolvedValue({ bundleId: 'com.example.app' }); vi.mocked(resolveTargetDevice).mockResolvedValue(session.device); @@ -299,6 +303,12 @@ test('reinstall cleans an uploaded artifact after the request-scoped operation', command: 'reinstall', positionals: ['com.example.app', '/Users/dev/Downloads/Sample.app'], flags: {}, + internal: { + admittedArtifactScope: { + principal: 'local', + owner: { tenantId: undefined, leaseVerifier: null }, + }, + }, meta: { uploadedArtifactId }, }, sessionName: session.name, @@ -325,9 +335,9 @@ test('install with another tenant upload ID leaves that upload in place', async const appPath = path.join(root, 'Sample.apk'); fs.writeFileSync(appPath, 'placeholder'); const uploadedArtifactId = trackUploadedArtifact({ + owner: { tenantId: 'tenant-a', leaseVerifier: null }, artifactPath: appPath, tempDir: root, - tenantId: 'tenant-a', }); await expect( @@ -341,6 +351,12 @@ test('install with another tenant upload ID leaves that upload in place', async command: 'install', positionals: ['/client/Sample.apk'], flags: {}, + internal: { + admittedArtifactScope: { + principal: 'local', + owner: { tenantId: 'tenant-b', leaseVerifier: null }, + }, + }, meta: { uploadedArtifactId, tenantId: 'tenant-b' }, }, sessionName: session.name, @@ -350,7 +366,9 @@ test('install with another tenant upload ID leaves that upload in place', async }), ).rejects.toMatchObject({ code: 'UNAUTHORIZED' }); expect(fs.existsSync(appPath)).toBe(true); - expect(prepareUploadedArtifact(uploadedArtifactId, 'tenant-a')).toBe(appPath); + expect( + prepareUploadedArtifact(uploadedArtifactId, { tenantId: 'tenant-a', leaseVerifier: null }), + ).toBe(appPath); expect(mockDeployAppRuntime).not.toHaveBeenCalled(); }); diff --git a/packages/daemon/src/sessions/handlers/__tests__/session-replay-command.test.ts b/packages/daemon/src/sessions/handlers/__tests__/session-replay-command.test.ts index 5073ad648fb..855cb844de1 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/session-replay-command.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/session-replay-command.test.ts @@ -34,6 +34,12 @@ test('replay test handler threads the complete video owner into the application token: 'token', session: 'default', command: 'test', + internal: { + admittedArtifactScope: { + principal: 'local', + owner: { tenantId: undefined, leaseVerifier: null }, + }, + }, positionals: [path.join(root, 'suite.ad')], flags: { recordVideo: true }, meta: { cwd: root, requestId: 'replay-handler-video' }, @@ -87,6 +93,12 @@ test.each([false, true])( token: 'token', session: 'default', command: 'test', + internal: { + admittedArtifactScope: { + principal: 'local', + owner: { tenantId: undefined, leaseVerifier: null }, + }, + }, positionals: [scriptPath], flags: {}, meta: { cwd: root, requestId: 'replay-handler-ended-lease', leaseId: lease.leaseId }, @@ -96,7 +108,13 @@ test.each([false, true])( createCommandSurface: fakeCreateCommandSurface, req: { ...wireReq, - internal: { endedLeases }, + internal: { + endedLeases, + admittedArtifactScope: { + principal: 'declared', + owner: { tenantId: lease.tenantId, leaseVerifier: null }, + }, + }, }, deviceShutdownDenied: shutdownDenied, sessionName: 'default', diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index 4e950033cf7..4330362ef46 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -570,11 +570,14 @@ async function listCloudArtifactsForRequest( const activeLeaseId = leaseScope.leaseId ? assertRequestHoldsActiveProviderLease(leaseRegistry, req, leaseScope.leaseId) : undefined; - const providerSession = resolveProviderSession(req, leaseRegistry, leaseScope, providerSessionId); + const providerSession = + !activeLeaseId || providerSessionId + ? resolveProviderSession(req, leaseRegistry, leaseScope, providerSessionId) + : undefined; const result = await cloudArtifactProvider?.listCloudArtifacts?.({ provider: leaseScope.leaseProvider, leaseId: providerSession?.leaseId ?? activeLeaseId ?? leaseScope.leaseId, - providerSessionId, + providerSessionId: providerSessionId ?? providerSession?.providerSessionId, }); if (!result) { throw new AppError( @@ -591,14 +594,16 @@ function resolveProviderSession( leaseScope: ReturnType, providerSessionId: string | undefined, ): ReturnType { - if (!providerSessionId) return undefined; + if (!providerSessionId && !leaseScope.leaseId) return undefined; const providerSession = leaseRegistry.resolveProviderSession({ provider: leaseScope.leaseProvider, providerSessionId, tenantId: leaseScope.tenantId, + leaseId: leaseScope.leaseId, + runId: leaseScope.runId, }); if (providerSession) { - assertRequestHoldsActiveProviderLease(leaseRegistry, req, providerSession.leaseId); + assertRequestPresentsLease(req, 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 511fda1db69..124fdd25390 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -50,7 +50,6 @@ import type { DaemonRequest } from '../../core/daemon-request.ts'; import { requestCwd } from '../../core/context.ts'; import type { SessionRef, SessionState } from '../../core/session-state.ts'; import { sessionHasOwnersBeyondRecording } from '../../core/session-state.ts'; -import { withCaptureOutputOwnership } from '../../core/capture-output-ownership.ts'; import { resolveLeaseScope } from '../../core/lease-context.ts'; import { leasedOutputRefusal, @@ -474,18 +473,7 @@ async function stopRecording( kind === 'stop-live', ) : undefined; - const response = buildRecordingStopResponse(completion, artifacts, remote); - return !remote && response.ok && response.data - ? { - ...response, - data: withCaptureOutputOwnership( - response.data, - 'caller', - undefined, - recordingOutputLeaseVerifier(envelope.metadata), - ), - } - : response; + return buildRecordingStopResponse(completion, artifacts, remote); } /** diff --git a/packages/daemon/src/sessions/handlers/session-app-deployment.ts b/packages/daemon/src/sessions/handlers/session-app-deployment.ts index b8ef2f0f8e9..1edd152ac39 100644 --- a/packages/daemon/src/sessions/handlers/session-app-deployment.ts +++ b/packages/daemon/src/sessions/handlers/session-app-deployment.ts @@ -16,6 +16,7 @@ import { parseInlineNotificationPayload, readNotificationPayload } from '../disp import { cleanupUploadedArtifact, prepareUploadedArtifact, + admittedArtifactOwner, } from '../../resources/artifact-tracking.ts'; import { expireRefFrame } from '../../core/ref-frame.ts'; import type { @@ -77,7 +78,7 @@ export async function handleAppDeploymentCommand(params: { const uploadedArtifactId = req.meta?.uploadedArtifactId; // Acquire before the cleanup scope: a rejected foreign upload ID must not delete that upload. const appPath = uploadedArtifactId - ? prepareUploadedArtifact(uploadedArtifactId, req.meta?.tenantId) + ? prepareUploadedArtifact(uploadedArtifactId, admittedArtifactOwner(req)) : expandSessionPath(target.appPathInput, requestCwd(req, params.host)); try { if (!fs.existsSync(appPath)) { diff --git a/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts b/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts index 862a1fd3444..c9293dcb98a 100644 --- a/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts +++ b/packages/daemon/src/sessions/handlers/session-app-source-deployment.ts @@ -1,3 +1,4 @@ +import { admittedArtifactOwner } from '../../resources/artifact-tracking.ts'; import { resolveCommandAndroidAvdSelection } from '../../core/daemon-command-registry.ts'; import { INSTALL_SOURCE_DEPLOY_LEDGER_RESERVE_MS } from '@agent-device/command-registry/timeout-policy'; import { getRequestDeadlineMs } from '@agent-device/host-kit/request'; @@ -69,7 +70,7 @@ export async function handleInstallFromSourceDeploymentCommand(params: { let retained: RetainedMaterializedPaths | undefined; try { const retention = resolveRetention(req); - resolvedSource = resolveInstallSource(req); + resolvedSource = resolveInstallSource(req, admittedArtifactOwner(req)); let device = await resolveInstallDevice( session, req, @@ -132,9 +133,10 @@ 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, + admittedArtifactOwner(req), + ).catch(() => {}); } return { ok: false, error: normalizeError(error) }; } finally { @@ -152,7 +154,7 @@ export async function handleReleaseMaterializedPathsCommand(params: { if (!materializationId) { throw new AppError('INVALID_ARGS', 'release_materialized_paths requires a materializationId'); } - await cleanupRetainedMaterializedPaths(materializationId, req.meta?.tenantId); + await cleanupRetainedMaterializedPaths(materializationId, admittedArtifactOwner(req)); return { ok: true, data: { released: true, materializationId } }; } catch (error) { return { ok: false, error: normalizeError(error) }; @@ -220,7 +222,7 @@ async function retainIfRequested(params: { return await retainMaterializedPaths({ archivePath: params.artifact.archivePath, installablePath: params.artifact.installablePath, - tenantId: params.req.meta?.tenantId, + owner: admittedArtifactOwner(params.req), sessionName: params.session ? params.sessionName : undefined, ttlMs: params.retention.ttlMs, }); diff --git a/packages/daemon/src/sessions/handlers/session-replay-command.ts b/packages/daemon/src/sessions/handlers/session-replay-command.ts index 789d2fa0b5b..03e7a3c1f70 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command.ts @@ -1,3 +1,4 @@ +import { admittedArtifactOwner, commitProducedOutput } from '../../resources/artifact-tracking.ts'; import { getRequestDeadlineMs, getRequestSignal, @@ -168,7 +169,14 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ }, } : req; + const outputOwner = admittedArtifactOwner(req); return await runReplayTestCommand({ + commitArtifact: ({ path: artifactPath, ...delivery }) => + commitProducedOutput( + { artifactPath, artifactType: delivery.artifactType, fileName: delivery.fileName }, + outputOwner, + delivery, + ), ...splitReplayCommandRequest(suiteRequest), host, session: createReplaySession(sessionName, logPath, sessionStore, capture), diff --git a/packages/daemon/src/sessions/handlers/trace-runtime.ts b/packages/daemon/src/sessions/handlers/trace-runtime.ts index c1e6abee38c..747f6a25140 100644 --- a/packages/daemon/src/sessions/handlers/trace-runtime.ts +++ b/packages/daemon/src/sessions/handlers/trace-runtime.ts @@ -2,10 +2,11 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { expandSessionPath } from '@agent-device/host-kit/session-paths'; import fs from 'node:fs'; -import { randomUUID } from 'node:crypto'; import { updateDiagnosticsScope } from '@agent-device/host-kit/diagnostics'; import { admittedOutputLeaseVerifier, + admittedArtifactOwner, + reserveFileOutput, leasedOutputRefusal, } from '../../resources/artifact-tracking.ts'; import path from 'node:path'; @@ -20,7 +21,6 @@ import { requestCwd } from '../../core/context.ts'; import type { SessionRef } from '../../core/session-state.ts'; import { recordSessionAction } from '../../core/session-action-recorder.ts'; import { errorResponse } from '@agent-device/kernel/contracts'; -import { withCaptureOutputOwnership } from '../../core/capture-output-ownership.ts'; export function handleTraceCommand(params: { host: HostEnvironment; @@ -46,8 +46,14 @@ function startTrace( const session = sessionStore.requireCurrent(ref); if (session.trace) return errorResponse('INVALID_ARGS', 'trace already in progress'); const daemonOwned = req.internal?.publicNetworkOnly === true; - const outPath = daemonOwned - ? path.join(sessionStore.ensureSessionDir(ref.address), `trace-${randomUUID()}.log`) + const reservation = daemonOwned + ? reserveFileOutput('trace-log', 'trace.log', { + ...admittedArtifactOwner(req), + lifetimeId: ref.lifetime.journalId, + }) + : undefined; + const outPath = reservation + ? reservation.path : expandSessionPath( req.positionals?.[1] ?? sessionStore.defaultTracePath(session), requestCwd(req, host), @@ -56,9 +62,9 @@ function startTrace( fs.appendFileSync(outPath, ''); session.trace = { ...(daemonOwned ? { remoteCaptureOutputPath: outPath } : { outPath }), + outputReservation: reservation, startedAt: Date.now(), clientOutPath: req.meta?.clientArtifactPaths?.outPath, - remoteCaptureTenantId: req.internal?.admittedLease?.tenantId ?? req.meta?.tenantId, leaseVerifier: admittedOutputLeaseVerifier(req), }; recordSessionAction(sessionStore, ref, req, req.command, { action: 'start', outPath }); @@ -79,39 +85,33 @@ function stopTrace( const owner = session.trace.leaseVerifier ?? null; if (owner && owner !== admittedOutputLeaseVerifier(req)) throw leasedOutputRefusal('Trace'); updateDiagnosticsScope({ traceLogPath: undefined }); - const outPath = relocateTraceOutput( - requestCwd(req, host), - session.trace.remoteCaptureOutputPath ?? session.trace.outPath, - req.positionals?.[1], - ); - const daemonOwned = session.trace.remoteCaptureOutputPath === outPath; - const tenantId = session.trace.remoteCaptureTenantId; - const clientOutPath = - req.meta?.clientArtifactPaths?.outPath ?? - session.trace.clientOutPath ?? - (req.internal?.publicNetworkOnly ? undefined : outPath); + const outPath = + session.trace.remoteCaptureOutputPath ?? + relocateTraceOutput( + requestCwd(req, host), + session.trace.remoteCaptureOutputPath ?? session.trace.outPath, + req.positionals?.[1], + ); + const trace = session.trace; + const clientOutPath = req.meta?.clientArtifactPaths?.outPath ?? trace.clientOutPath; + const artifact = trace.outputReservation + ? trace.outputReservation.commit({ + field: 'outPath', + localPath: clientOutPath, + fileName: path.basename(clientOutPath ?? outPath), + }) + : { + field: 'outPath', + artifactType: 'trace-log' as const, + path: outPath, + localPath: clientOutPath, + fileName: path.basename(clientOutPath ?? outPath), + }; session.trace = undefined; recordSessionAction(sessionStore, ref, req, req.command, { action: 'stop', outPath }); return { ok: true, - data: withCaptureOutputOwnership( - { - trace: 'stopped', - outPath, - artifacts: [ - { - field: 'outPath', - artifactType: 'trace-log', - path: outPath, - localPath: clientOutPath, - fileName: path.basename(clientOutPath ?? outPath), - }, - ], - } satisfies TraceCommandResult, - daemonOwned ? 'daemon' : 'caller', - tenantId, - owner, - ), + data: { trace: 'stopped', outPath, artifacts: [artifact] } satisfies TraceCommandResult, }; } diff --git a/packages/daemon/src/sessions/install-source-resolution.ts b/packages/daemon/src/sessions/install-source-resolution.ts index b040b3ce0ec..fa7472d64ce 100644 --- a/packages/daemon/src/sessions/install-source-resolution.ts +++ b/packages/daemon/src/sessions/install-source-resolution.ts @@ -3,6 +3,7 @@ import type { DaemonInstallSource } from '@agent-device/kernel/contracts'; import { cleanupUploadedArtifact, prepareUploadedArtifact, + type ArtifactOwner, } from '../resources/artifact-tracking.ts'; import type { DaemonRequest } from '../core/daemon-request.ts'; @@ -36,7 +37,10 @@ function requireInstallSource(req: DaemonRequest): DaemonInstallSource { } } -export function resolveInstallSource(req: DaemonRequest): { +export function resolveInstallSource( + req: DaemonRequest, + owner: ArtifactOwner, +): { 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), }, cleanup: () => { cleanupUploadedArtifact(uploadedArtifactId); diff --git a/packages/daemon/src/sessions/lease-lifecycle.ts b/packages/daemon/src/sessions/lease-lifecycle.ts index 2d1aecc836b..93fdd9f349f 100644 --- a/packages/daemon/src/sessions/lease-lifecycle.ts +++ b/packages/daemon/src/sessions/lease-lifecycle.ts @@ -1,3 +1,6 @@ +import { ignoresSessionLease } from '../core/daemon-command-registry.ts'; +import { resolveLeaseScope } from '../core/lease-context.ts'; +import { leaseVerifier } from '../resources/artifact-tracking.ts'; import type { PluginInventoryEntry } from '@agent-device/contracts/plugin-inventory'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; @@ -90,8 +93,22 @@ export function admitRequestLeaseForLockedScope(params: { daemonPolicy: params.daemonPolicy, }, ); - if (!activeLease) return params.req; - return { ...params.req, internal: { ...params.req.internal, admittedLease: activeLease } }; + const presented = resolveLeaseScope(params.req); + const tenantId = activeLease?.tenantId ?? presented.tenantId; + const outputLeaseId = + activeLease?.leaseId ?? + (ignoresSessionLease(params.req.command) ? presented.leaseId : undefined); + return { + ...params.req, + internal: { + ...params.req.internal, + admittedLease: activeLease, + admittedArtifactScope: { + principal: params.req.internal?.principal ?? (tenantId ? 'declared' : 'local'), + owner: { tenantId, leaseVerifier: outputLeaseId ? leaseVerifier(outputLeaseId) : null }, + }, + }, + }; } function closeLeaseDecision( diff --git a/packages/daemon/src/sessions/materialized-path-registry.ts b/packages/daemon/src/sessions/materialized-path-registry.ts index 1374a31a317..434d567c7c1 100644 --- a/packages/daemon/src/sessions/materialized-path-registry.ts +++ b/packages/daemon/src/sessions/materialized-path-registry.ts @@ -1,3 +1,4 @@ +import { assertArtifactOwner, type ArtifactOwner } from '../resources/artifact-tracking.ts'; import { runtimeSlot } from '@agent-device/host-kit/runtime-slots'; import { AppError } from '@agent-device/kernel/errors'; import crypto from 'node:crypto'; @@ -6,7 +7,7 @@ import fs from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { - requireTenantOwnedEntry, + expiredTenantOwnedEntryError, type TenantOwnedResourceKind, } from '../core/tenant-owned-entry.ts'; @@ -24,7 +25,7 @@ type RetainedEntry = { rootPath: string; installablePath: string; archivePath?: string; - tenantId?: string; + owner: ArtifactOwner; sessionName?: string; expiresAt: number; timer: ReturnType; @@ -57,7 +58,7 @@ const retainedPaths = (): Map => export async function retainMaterializedPaths(params: { installablePath: string; archivePath?: string; - tenantId?: string; + owner: ArtifactOwner; sessionName?: string; ttlMs?: number; }): Promise { @@ -80,7 +81,7 @@ export async function retainMaterializedPaths(params: { rootPath, installablePath: retainedInstallablePath, archivePath: retainedArchivePath, - tenantId: params.tenantId, + owner: params.owner, sessionName: params.sessionName, expiresAt, timer, @@ -116,14 +117,11 @@ export function resolveMaterializedPathRetentionMs( export async function cleanupRetainedMaterializedPaths( materializationId: string, - tenantId?: string, + owner: ArtifactOwner, ): Promise { - const entry = requireTenantOwnedEntry( - retainedPaths(), - materializationId, - tenantId, - MATERIALIZED_PATHS_RESOURCE, - ); + const entry = retainedPaths().get(materializationId); + if (!entry) throw expiredTenantOwnedEntryError(MATERIALIZED_PATHS_RESOURCE, materializationId); + assertArtifactOwner(entry.owner, owner); await removeRetainedEntry(materializationId, entry); } diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-devices-batch-runtime.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-devices-batch-runtime.test.ts index 0899b114165..028a3c2b625 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-devices-batch-runtime.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-devices-batch-runtime.test.ts @@ -389,6 +389,7 @@ test('close clears retained materialized install paths bound to the session', as fs.mkdirSync(appPath, { recursive: true }); fs.writeFileSync(path.join(appPath, 'Info.plist'), 'plist'); const retained = await retainMaterializedPaths({ + owner: { tenantId: undefined, leaseVerifier: null }, installablePath: appPath, sessionName, ttlMs: 60_000, @@ -422,7 +423,11 @@ test('release_materialized_paths removes retained install artifacts', async () = const appPath = path.join(tempRoot, 'Sample.app'); fs.mkdirSync(appPath, { recursive: true }); fs.writeFileSync(path.join(appPath, 'Info.plist'), 'plist'); - const retained = await retainMaterializedPaths({ installablePath: appPath, ttlMs: 60_000 }); + const retained = await retainMaterializedPaths({ + owner: { tenantId: undefined, leaseVerifier: null }, + installablePath: appPath, + ttlMs: 60_000, + }); const response = await handleReleaseMaterializedPathsCommand({ req: { diff --git a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts index 61972a6367c..f00f5f5a237 100644 --- a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts +++ b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts @@ -39,12 +39,14 @@ import type { import type { SessionStore } from '../../../core/session-store.ts'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; import { requestCwd } from '../../../core/context.ts'; -import { LEASE_FIELD_NORMALIZERS, resolveLeaseScope } from '../../../core/lease-context.ts'; import type { SessionRef, SessionState } from '../../../core/session-state.ts'; import { bindSessionPerfCapture } from '../../../core/session-capture-binding.ts'; -import { withCaptureOutputOwnership } from '../../../core/capture-output-ownership.ts'; import { admittedOutputLeaseVerifier, + admittedArtifactOwner, + reserveFileOutput, + commitProducedOutput, + type ArtifactOwner, assertTrackedPerformanceSourceLease, leasedOutputRefusal, retainPerfReportSource, @@ -155,25 +157,40 @@ async function executeAdmittedPerfPlan( } case 'memory-snapshot': { const runtime = await bindDevice(device, plan.use); - const result = await runtime.operations.perfMemorySnapshot({ - appId: session.appBundleId, - kind: plan.request.kind, - outPath: plan.request.outPath - ? expandSessionPath(plan.request.outPath, requestCwd(params.req, params.host)) - : undefined, - artifactsDir: path.join( - params.sessionStore.ensureSessionDir(params.sessionName), - 'artifacts', - ), - }); - return { - ok: true, - data: withCaptureOutputOwnership( - buildMemorySnapshotResponse(session, result), - params.req.internal?.publicNetworkOnly ? 'daemon' : 'caller', - session.lease?.tenantId ?? params.req.meta?.tenantId, - ), - }; + const reservation = reservePerfFile( + params, + plan.request.kind === 'android-hprof' || session.device.platform === 'android' + ? 'memory.hprof' + : 'memory.memgraph', + ); + try { + const result = await runtime.operations.perfMemorySnapshot({ + appId: session.appBundleId, + kind: plan.request.kind, + outPath: + reservation?.path ?? + (plan.request.outPath + ? expandSessionPath(plan.request.outPath, requestCwd(params.req, params.host)) + : undefined), + artifactsDir: path.join( + params.sessionStore.ensureSessionDir(params.sessionName), + 'artifacts', + ), + }); + return { + ok: true, + data: { + ...buildMemorySnapshotResponse(session, result), + ...commitPerfFile( + params, + reservation, + isRecord(result.artifact) ? result.artifact.path : undefined, + ), + }, + }; + } finally { + reservation?.discard(); + } } case 'capture-start': { const runtime = await bindDevice(device, plan.use); @@ -216,24 +233,25 @@ async function executeAdmittedPerfPlan( isXctrace || requestedPath ? (explicit ?? readPerfSource(tracePath)) : undefined; if (source) assertPerfSourceLease(params, source); const runtime = await bindDevice(device, plan.use); - const outPath = resolveNativeOutPath(params, plan.request.outPath, 'cpu-report.json'); - const data = await runtime.operations.perfProfileReport({ - appId: session.appBundleId, - kind: plan.request.kind, - tracePath: isXctrace ? (source?.path ?? tracePath) : tracePath, - outPath, - template: plan.request.template ?? (last?.kind === 'xctrace' ? last.template : undefined), - profile: last, - }); - return { - ok: true, - data: withCaptureOutputOwnership( - { perf: 'reported', ...data }, - params.req.internal?.publicNetworkOnly ? 'daemon' : 'caller', - params.req.internal?.admittedLease?.tenantId ?? - LEASE_FIELD_NORMALIZERS.tenantId(resolveLeaseScope(params.req).tenantId), - ), - }; + const reservation = reservePerfFile(params, 'cpu-report.json'); + const outPath = + reservation?.path ?? resolveNativeOutPath(params, plan.request.outPath, 'cpu-report.json'); + try { + const data = await runtime.operations.perfProfileReport({ + appId: session.appBundleId, + kind: plan.request.kind, + tracePath: isXctrace ? (source?.path ?? tracePath) : tracePath, + outPath, + template: plan.request.template ?? (last?.kind === 'xctrace' ? last.template : undefined), + profile: last, + }); + return { + ok: true, + data: { perf: 'reported', ...data, ...commitPerfFile(params, reservation, data.outPath) }, + }; + } finally { + reservation?.discard(); + } } } } @@ -255,6 +273,9 @@ async function startPerfCapture( hint: 'Run open first so perf can resolve the app process identity.', }); } + const producer = params.req.internal?.publicNetworkOnly + ? admittedArtifactOwner(params.req) + : undefined; const fallback = request.kind === 'xctrace' ? `perf-${request.area === 'cpu' ? 'cpu-profile' : 'trace'}.trace` @@ -309,7 +330,7 @@ async function startPerfCapture( } throw error; }); - const tenantId = params.req.internal?.admittedLease?.tenantId ?? params.req.meta?.tenantId; + await adoptStartedPerfCapture({ admissionLedger, binding, @@ -322,8 +343,13 @@ async function startPerfCapture( metadata: { ...started.envelope.metadata, ...(params.req.internal?.publicNetworkOnly ? { remoteCaptureOutputPath: outPath } : {}), - ...(tenantId ? { remoteCaptureTenantId: tenantId } : {}), - remoteCaptureLease: admittedOutputLeaseVerifier(params.req), + ...(producer + ? { + remoteCaptureOwner: { ...producer, tenantId: producer.tenantId ?? null }, + remoteCaptureLifetime: params.ref.lifetime.journalId, + } + : {}), + ...(!producer ? { remoteCaptureLease: admittedOutputLeaseVerifier(params.req) } : {}), }, }, throwIfCanceled: params.throwIfCanceled, @@ -348,17 +374,18 @@ async function stopPerfCapture( const capture = session.perfCapture; if (!capture) return errorResponse('INVALID_ARGS', 'no active native perf capture'); const metadata = capture.envelope.metadata; - const owner = readString(metadata?.remoteCaptureLease) ?? null; + const producer = + metadata?.remoteCaptureOutputPath !== undefined + ? readPerfProducer(metadata, params.ref) + : undefined; + const owner = producer + ? producer.leaseVerifier + : (readString(metadata?.remoteCaptureLease) ?? null); assertPerfOutputOwner(params.req, owner); - const tenantId = resolveStoppedCaptureTenant( - params.req, - session, - metadata?.remoteCaptureTenantId, - ); const snapshot = capture.handle.inspect(); const mismatchMessage = perfCaptureStopMismatch(snapshot, request); if (mismatchMessage) return errorResponse('INVALID_ARGS', mismatchMessage); - if (request.outPath) { + if (request.outPath && !params.req.internal?.publicNetworkOnly) { capture.handle.setOutputPath( expandSessionPath(request.outPath, requestCwd(params.req, params.host)), ); @@ -377,27 +404,92 @@ async function stopPerfCapture( }); } const clientOutPath = params.req.meta?.clientArtifactPaths?.outPath ?? capture.clientOutPath; - const artifacts = - daemonOwned && completion.kind === 'xctrace' - ? [await publishXctraceDownload(outPath, clientOutPath, request.area === 'cpu')] - : undefined; + let artifacts: DaemonArtifact[] | undefined; + if (daemonOwned) { + const artifact = + completion.kind === 'xctrace' + ? await publishXctraceDownload(outPath, clientOutPath, request.area === 'cpu') + : { + field: 'outPath', + artifactType: 'performance' as const, + path: outPath, + localPath: clientOutPath, + fileName: path.basename(outPath), + ...(request.area === 'cpu' ? { deleteAfterDownload: false } : {}), + }; + artifacts = [commitPerfArtifact(artifact, producer!)]; + } return { ok: true, - data: withCaptureOutputOwnership( - { - ...completion, - ...(clientOutPath ? { clientOutPath } : {}), - ...(artifacts ? { artifacts } : {}), - }, - daemonOwned ? 'daemon' : 'caller', - tenantId, - owner, - ), + data: { + ...completion, + ...(clientOutPath ? { clientOutPath } : {}), + ...(artifacts ? { artifacts } : {}), + }, }; } -function resolveStoppedCaptureTenant(req: DaemonRequest, session: SessionState, stored: unknown) { - return readString(stored) ?? session.lease?.tenantId ?? req.meta?.tenantId; +function readPerfProducer( + metadata: Record | undefined, + ref: SessionRef, +): ArtifactOwner { + const owner = metadata?.remoteCaptureOwner; + if ( + metadata?.remoteCaptureLifetime !== ref.lifetime.journalId || + !isRecord(owner) || + !(owner.tenantId === null || typeof owner.tenantId === 'string') || + !(owner.leaseVerifier === null || typeof owner.leaseVerifier === 'string') + ) + throw leasedOutputRefusal('Performance capture'); + return { + tenantId: owner.tenantId === null ? undefined : owner.tenantId, + leaseVerifier: owner.leaseVerifier, + }; +} + +function reservePerfFile(params: PerfRuntimeHandlerParams & { ref: SessionRef }, filename: string) { + return params.req.internal?.publicNetworkOnly + ? reserveFileOutput('performance', filename, { + ...admittedArtifactOwner(params.req), + lifetimeId: params.ref.lifetime.journalId, + }) + : undefined; +} + +function commitPerfFile( + params: PerfRuntimeHandlerParams, + reservation: ReturnType | undefined, + producedPath: unknown, +) { + if (!reservation || producedPath === undefined) return {}; + if (producedPath !== reservation.path) throw leasedOutputRefusal('Performance output'); + return { + artifacts: [ + reservation.commit({ + field: 'outPath', + fileName: path.basename(reservation.path), + localPath: params.req.meta?.clientArtifactPaths?.outPath, + }), + ], + }; +} + +function commitPerfArtifact( + artifact: DaemonArtifact & { deleteAfterDownload?: boolean }, + owner: ArtifactOwner, +): DaemonArtifact { + const { path: artifactPath, deleteAfterDownload, ...delivery } = artifact; + if (!artifactPath) throw leasedOutputRefusal('Performance capture'); + return commitProducedOutput( + { + artifactPath, + artifactType: artifact.artifactType, + fileName: artifact.fileName, + deleteAfterDownload, + }, + owner, + delivery, + ); } function resolveExplicitPerfSource(tracePath: string) { @@ -430,7 +522,13 @@ function assertPerfSourceLease(params: PerfRuntimeHandlerParams, source: PerfRep throw leasedOutputRefusal('Performance capture'); } const capture = session.perfCapture; - const captureOwner = readString(capture?.envelope.metadata?.remoteCaptureLease); + const capturedProducer = capture?.envelope.metadata?.remoteCaptureOwner; + const captureOwner = + capture?.envelope.metadata?.remoteCaptureOutputPath !== undefined + ? isRecord(capturedProducer) + ? readString(capturedProducer.leaseVerifier) + : undefined + : readString(capture?.envelope.metadata?.remoteCaptureLease); if (capture && captureOwner && captureOwner !== owner) { const capturePath = readString(capture.handle.inspect().outPath); if (capturePath && samePerfSource(source, capturePath)) { diff --git a/packages/host-kit/src/archive.ts b/packages/host-kit/src/archive.ts index 3300b1f413b..b938aac530a 100644 --- a/packages/host-kit/src/archive.ts +++ b/packages/host-kit/src/archive.ts @@ -1,4 +1,7 @@ export { archiveTypeFromPath, extractArchiveSafely } from './internal/archive-extraction.ts'; export { ArchiveBudget, type ArchiveManifestEntry } from './internal/archive-safety.ts'; -export { MAX_ARTIFACT_COMPRESSED_BYTES } from './internal/artifact-limits.ts'; +export { + MAX_ARCHIVE_EXPANDED_BYTES, + MAX_ARTIFACT_COMPRESSED_BYTES, +} from './internal/artifact-limits.ts'; export { createByteLimitStream } from './internal/byte-limit-stream.ts'; diff --git a/packages/host-kit/src/internal/byte-limit-stream.ts b/packages/host-kit/src/internal/byte-limit-stream.ts index 21cbfd75d47..9ef997633f6 100644 --- a/packages/host-kit/src/internal/byte-limit-stream.ts +++ b/packages/host-kit/src/internal/byte-limit-stream.ts @@ -7,6 +7,7 @@ export type ByteLimitStream = Transform & { export function createByteLimitStream(options: { maxBytes: number; createLimitError: () => Error; + acceptBytes?: (bytes: number) => void; }): ByteLimitStream { if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 0) { throw new RangeError('maxBytes must be a non-negative safe integer'); @@ -20,6 +21,12 @@ export function createByteLimitStream(options: { callback(options.createLimitError()); return; } + try { + options.acceptBytes?.(chunk.byteLength); + } catch (error) { + callback(error as Error); + return; + } bytesSeen = nextBytesSeen; callback(null, chunk); }, diff --git a/packages/proxy/src/daemon-proxy-cancellation.test.ts b/packages/proxy/src/daemon-proxy-cancellation.test.ts index ac3e609b69d..e7ac09253ef 100644 --- a/packages/proxy/src/daemon-proxy-cancellation.test.ts +++ b/packages/proxy/src/daemon-proxy-cancellation.test.ts @@ -3,6 +3,8 @@ import type { AddressInfo } from 'node:net'; import { setFlagsFromString } from 'node:v8'; import { runInNewContext } from 'node:vm'; import { expect, onTestFinished, test, vi } from 'vitest'; +import { DAEMON_RPC_PREAUTH_MAX_ID_LENGTH } from '@agent-device/contracts/daemon-http'; +import { AppError } from '@agent-device/kernel/errors'; import { createDaemonProxy, createDaemonProxyServer, @@ -69,6 +71,168 @@ function rpcRequest(body: unknown, init: RequestInit = {}): Request { }); } +test('a pending RPC authentication does not block another caller', async () => { + let authenticating = 0; + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch: async () => Response.json({ ok: true }), + authenticate: () => { + authenticating += 1; + return authenticating <= 32 ? new Promise(() => {}) : { tenantId: 'tenant-a' }; + }, + }); + const controllers = Array.from({ length: 32 }, () => new AbortController()); + const pending = controllers.map((controller) => + proxy.handle( + rpcRequest( + { jsonrpc: '2.0', id: 1, method: 'agent-device.command' }, + { signal: controller.signal }, + ), + ), + ); + await vi.waitFor(() => expect(authenticating).toBe(32)); + const admitted = await proxy.handle( + rpcRequest({ jsonrpc: '2.0', id: 33, method: 'agent-device.command' }), + ); + expect(admitted.status).toBe(200); + + controllers[0]!.abort(); + await pending[0]; + const afterDisconnect = await proxy.handle( + rpcRequest({ jsonrpc: '2.0', id: 34, method: 'agent-device.command' }), + ); + expect(afterDisconnect.status).toBe(200); + for (const controller of controllers.slice(1)) controller.abort(); + await Promise.all(pending); +}); + +test('RPC authentication that completes after the ingress deadline cannot dispatch', async () => { + vi.useFakeTimers(); + try { + const entered = signalled(); + const auth = Promise.withResolvers<{ tenantId: string }>(); + const upstreamFetch = vi.fn(async () => Response.json({ ok: true })); + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch, + authenticate: () => { + entered.resolve(); + return auth.promise; + }, + }); + const pending = proxy.handle( + rpcRequest({ jsonrpc: '2.0', id: 1, method: 'agent-device.command' }), + ); + await entered.promise; + await vi.advanceTimersByTimeAsync(5_001); + const response = await pending; + const body = (await response.json()) as { + id?: unknown; + error?: { data?: { details?: { reason?: string; dispatched?: string } } }; + }; + expect(response.status).toBe(408); + expect(body.id).toBe(1); + expect(body.error?.data?.details).toMatchObject({ + reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', + dispatched: 'no', + }); + auth.resolve({ tenantId: 'tenant-a' }); + await vi.advanceTimersByTimeAsync(0); + expect(upstreamFetch).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } +}); + +test.each([ + ['object', { nested: 'untrusted' }], + ['oversized string', 'x'.repeat(DAEMON_RPC_PREAUTH_MAX_ID_LENGTH + 1)], +])('RPC authentication timeout drops an %s request id', async (_label, id) => { + vi.useFakeTimers(); + try { + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch: async () => Response.json({ ok: true }), + authenticate: () => new Promise(() => {}), + }); + const pending = proxy.handle( + rpcRequest({ jsonrpc: '2.0', id, method: 'agent-device.command' }), + ); + await vi.advanceTimersByTimeAsync(5_001); + const response = await pending; + const body = (await response.json()) as { id?: unknown }; + expect(response.status).toBe(408); + expect(body.id).toBeNull(); + } finally { + vi.useRealTimers(); + } +}); + +test('an unfinished RPC body receives the same typed preauth deadline refusal', async () => { + vi.useFakeTimers(); + try { + const upstreamFetch = vi.fn(async () => Response.json({ ok: true })); + const proxy = proxyWith(upstreamFetch); + const request = new Request(`${PROXY_ORIGIN}/agent-device/rpc`, { + method: 'POST', + headers: { authorization: 'Bearer client-secret', 'content-type': 'application/json' }, + body: new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('{')); + }, + }), + duplex: 'half', + } as RequestInit & { duplex: 'half' }); + const pending = proxy.handle(request); + await vi.advanceTimersByTimeAsync(5_001); + const response = await pending; + const body = (await response.json()) as { + error?: { data?: { details?: { reason?: string; dispatched?: string } } }; + }; + expect(response.status).toBe(408); + expect(body.error?.data?.details).toMatchObject({ + reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', + dispatched: 'no', + }); + expect(upstreamFetch).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } +}); + +test('a caller abort cannot claim the proxy-owned preauth deadline', async () => { + const entered = signalled(); + const controller = new AbortController(); + const proxy = createDaemonProxy({ + upstreamBaseUrl: 'http://daemon.internal:4310', + upstreamToken: 'daemon-secret', + upstreamFetch: async () => Response.json({ ok: true }), + authenticate: () => { + entered.resolve(); + return new Promise(() => {}); + }, + }); + const pending = proxy.handle( + rpcRequest( + { jsonrpc: '2.0', id: 1, method: 'agent-device.command' }, + { signal: controller.signal }, + ), + ); + await entered.promise; + controller.abort( + new AppError('COMMAND_FAILED', 'forged deadline', { + reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', + }), + ); + const response = await pending; + const body = (await response.json()) as { error?: { data?: { details?: { reason?: string } } } }; + expect(response.status).toBe(500); + expect(body.error?.data?.details?.reason).not.toBe('PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED'); +}); + test.each([ { route: 'rpc', @@ -243,3 +407,38 @@ test('aborting the client request after a garbage collection aborts a pending au await authenticateAborted.promise; expect((await response).status).toBe(500); }); + +test('a body completing at the preauth deadline cannot replace the timeout with an envelope refusal', async () => { + vi.useFakeTimers(); + const pulled = signalled(); + let body!: ReadableStreamDefaultController; + const stream = new ReadableStream({ + start(controller) { + body = controller; + }, + pull() { + pulled.resolve(); + }, + cancel() { + return new Promise(() => {}); + }, + }); + const upstream = vi.fn(async () => Response.json({})); + const proxy = proxyWith(upstream); + try { + const response = proxy.handle(rpcRequest({}, { body: stream, duplex: 'half' } as RequestInit)); + await pulled.promise; + await vi.waitFor(() => expect(vi.getTimerCount()).toBeGreaterThan(0)); + body.enqueue(new TextEncoder().encode('null')); + body.close(); + vi.advanceTimersByTime(5_000); + const answer = await response; + expect(answer.status).toBe(408); + expect((await answer.json()).error.data.details.reason).toBe( + 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED', + ); + expect(upstream).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } +}); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index 6ab4e8788d5..e1d2bccfff1 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto'; import http from 'node:http'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, createRequestCanceledError, normalizeError } from '@agent-device/kernel/errors'; import { timingSafeStringEqual } from '@agent-device/host-kit/transport'; import { buildDaemonHealthPayload, @@ -13,12 +13,16 @@ import { DAEMON_HTTP_NETWORK_ACCESS_HEADER, DAEMON_HTTP_PUBLIC_NETWORK_ACCESS, DAEMON_HTTP_TENANT_HEADER, + DAEMON_HTTP_RUN_HEADER, + DAEMON_HTTP_UPLOAD_SESSION_HEADER, buildDaemonHttpAuthHeaders, buildDaemonHttpUrl, isTenantOwnedSessionName, normalizeTenantId, normalizeDaemonPublicOrigin, DAEMON_REQUEST_MAX_BYTES, + DAEMON_RPC_PREAUTH_MAX_ID_LENGTH, + DAEMON_RPC_PREAUTH_TIMEOUT_MS, DAEMON_INSTANCE_REASONS, DAEMON_HTTP_CHECKED_RPC_CAPABILITY, DAEMON_HTTP_CHECKED_RPC_ROUTE, @@ -29,6 +33,7 @@ import { carriesUnbackedHostPathInstallSource, hostPathInstallSourceRefusedResponse, } from './install-source-admission.ts'; +import type { createRpcBodyBudget } from './rpc-body-budget.ts'; /** * Carries one request to the upstream daemon and resolves with its response. Without `upstreamFetch` @@ -120,6 +125,7 @@ type NormalizedProxyOptions = { clientToken: string | undefined; authenticate: DaemonProxyAuthenticate | undefined; maxRpcBodyBytes: number; + getRpcBodyBudget: () => Promise>; upstreamTimeoutMs: number | undefined; upstreamAdmission: Promise | undefined; upstreamFetch: DaemonProxyUpstreamFetch; @@ -131,7 +137,6 @@ type ProxyCaller = { tenantId?: string; uploadHeaders: Record }; /** The client request headers an upload ticket repeats when `authenticate` names none. */ const DEFAULT_UPLOAD_CREDENTIAL_HEADERS = Object.keys(buildDaemonHttpAuthHeaders('client')); - const DEFAULT_MAX_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; /** `/health` answers quickly or not at all; its probe never waits on `upstreamTimeoutMs`. */ const UPSTREAM_HEALTH_TIMEOUT_MS = 5_000; @@ -145,7 +150,8 @@ const FORWARDED_REQUEST_HEADERS = [ 'x-artifact-hash', 'x-artifact-hash-algorithm', DAEMON_HTTP_TENANT_HEADER, - DAEMON_HTTP_LEASE_HEADER, + DAEMON_HTTP_RUN_HEADER, + DAEMON_HTTP_UPLOAD_SESSION_HEADER, ]; const FORWARDED_RESPONSE_HEADERS = [ 'content-type', @@ -204,27 +210,60 @@ async function handleProxyRequest( return new Response(new TextEncoder().encode('Not found'), { status: 404 }); } - if (!isRpcRoute(route)) return await handleDaemonRoute(request, route, options, instanceId); + return isRpcRoute(route) + ? await handleRpcRoute(request, route, options, instanceId) + : await handleDaemonRoute(request, route, options, instanceId); +} - let rpcBody: string; - try { - rpcBody = await readRequestText( - request, - options.maxRpcBodyBytes, - 'Proxy request body is too large.', - ); - } catch (error) { - return rpcErrorResponse(null, error); - } - // The checked route checks its envelope after authentication and the protocol: a caller on - // another protocol is told so before the proxy reads what its own protocol defines. - const envelopeRefusal = - route === DAEMON_HTTP_CHECKED_RPC_ROUTE ? null : refuseInvalidRpcEnvelope(rpcBody); - if (envelopeRefusal) return envelopeRefusal; +async function handleRpcRoute( + request: Request, + route: string, + options: NormalizedProxyOptions, + instanceId: string, +): Promise { + const { refuseInvalidRpcEnvelope, rpcErrorResponse, rpcPreauthDeadlineError } = + await import('./rpc-refusals.ts'); + const preauth = new AbortController(); + const signal = AbortSignal.any([request.signal, preauth.signal]); + let deadline: ReturnType | undefined = setTimeout( + () => preauth.abort(rpcPreauthDeadlineError()), + DAEMON_RPC_PREAUTH_TIMEOUT_MS, + ); + let ingress: { body: string; release: () => void } | undefined; try { - return await handleDaemonRoute(request, route, options, instanceId, rpcBody); + ingress = await ( + await options.getRpcBodyBudget() + ).read(request, options.maxRpcBodyBytes, signal); + const rpcBody = ingress.body; + // The checked route checks its envelope after authentication and the protocol: a caller on + // another protocol is told so before the proxy reads what its own protocol defines. + const envelopeRefusal = + route === DAEMON_HTTP_CHECKED_RPC_ROUTE ? null : refuseInvalidRpcEnvelope(rpcBody); + signal.throwIfAborted(); + if (envelopeRefusal) return envelopeRefusal; + const caller = await authenticateCaller(request, options, rpcBody, signal); + signal.throwIfAborted(); + clearTimeout(deadline); + deadline = undefined; + return await handleDaemonRoute(request, route, options, instanceId, rpcBody, caller); } catch (error) { - return rpcErrorResponse(readJsonRpcId(rpcBody), error); + let refusal = error; + if (deadline !== undefined && signal.aborted) { + refusal = + preauth.signal.aborted && signal.reason === preauth.signal.reason + ? preauth.signal.reason + : createRequestCanceledError(undefined, signal.reason); + } + const id = readJsonRpcId(ingress?.body); + const oversizedTimeoutId = + preauth.signal.aborted && + refusal === preauth.signal.reason && + typeof id === 'string' && + id.length > DAEMON_RPC_PREAUTH_MAX_ID_LENGTH; + return rpcErrorResponse(oversizedTimeoutId ? null : id, refusal); + } finally { + clearTimeout(deadline); + ingress?.release(); } } @@ -234,14 +273,19 @@ async function handleDaemonRoute( options: NormalizedProxyOptions, instanceId: string, rpcBody?: string, + admittedCaller?: ProxyCaller | null, ): Promise { - const caller = await authenticateCaller(request, options, rpcBody); + const caller = + admittedCaller === undefined + ? await authenticateCaller(request, options, rpcBody) + : admittedCaller; if (!caller) { return unauthorizedResponse(route, readJsonRpcId(rpcBody)); } if (route === DAEMON_HTTP_CHECKED_RPC_ROUTE) { // Loaded only on the checked route: authentication, then the protocol, then the envelope. const { refuseCheckedRpcProtocol } = await import('./checked-rpc-admission.ts'); + const { refuseInvalidRpcEnvelope } = await import('./rpc-refusals.ts'); const refusal = (await refuseCheckedRpcProtocol(request, readJsonRpcId(rpcBody))) ?? refuseInvalidRpcEnvelope(rpcBody ?? ''); @@ -276,19 +320,26 @@ async function authenticateCaller( request: Request, options: NormalizedProxyOptions, rpcBody: string | undefined, + signal: AbortSignal = request.signal, ): Promise { if (!options.authenticate) { return isAuthorized(request, options.clientToken ?? '', rpcBody) ? { uploadHeaders: buildDaemonHttpAuthHeaders(options.clientToken) } : null; } - const result = await options.authenticate( - forwardedRequest(request, request.url, { - method: request.method, - headers: request.headers, - signal: request.signal, - ...(rpcBody !== undefined ? { body: rpcBody } : {}), - }), + const { awaitWithSignal } = await import('@agent-device/kernel/await-with-signal'); + const result = await awaitWithSignal( + Promise.resolve( + options.authenticate( + forwardedRequest(request, request.url, { + method: request.method, + headers: request.headers, + signal, + ...(rpcBody !== undefined ? { body: rpcBody } : {}), + }), + ), + ), + signal, ); if (!result) return null; const tenantId = normalizeTenantId( @@ -594,6 +645,7 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti // A refusal reaches every request that waits for the verdict. upstreamAdmission?.catch(() => {}); const upstreamFetch = customUpstreamFetch ?? ((request: Request) => fetch(request)); + let rpcBodyBudget: Promise> | undefined; return { upstreamBaseUrl, publicOrigin: @@ -604,6 +656,10 @@ function normalizeProxyOptions(options: DaemonProxyOptions): NormalizedProxyOpti clientToken, authenticate: options.authenticate, maxRpcBodyBytes: options.maxRpcBodyBytes ?? DEFAULT_MAX_RPC_BODY_BYTES, + getRpcBodyBudget: () => + (rpcBodyBudget ??= import('./rpc-body-budget.ts').then((module) => + module.createRpcBodyBudget(), + )), upstreamTimeoutMs: options.upstreamTimeoutMs, upstreamAdmission, upstreamFetch, @@ -757,28 +813,6 @@ function resolveUpstreamBody( return request.body; } -async function readRequestText( - request: Request, - maxBodyBytes: number, - tooLargeMessage: string, -): Promise { - if (!request.body) return ''; - const reader = request.body.getReader(); - const chunks: Uint8Array[] = []; - let bodyBytes = 0; - for (;;) { - const { done, value } = await reader.read(); - if (done) break; - bodyBytes += value.byteLength; - if (bodyBytes > maxBodyBytes) { - await reader.cancel(); - throw new AppError('INVALID_ARGS', tooLargeMessage); - } - chunks.push(value); - } - return Buffer.concat(chunks).toString('utf8'); -} - function isAuthorized(request: Request, expectedToken: string, rpcBody: string | undefined) { const requestToken = resolveRequestToken(request, rpcBody); return requestToken.length > 0 && timingSafeStringEqual(requestToken, expectedToken); @@ -845,14 +879,18 @@ function readJsonRpcMethod(body: string | undefined): string | undefined { } } -function readJsonRpcId(body: string | undefined): unknown { +function readJsonRpcId(body: string | undefined): string | number | null { if (!body) return null; try { - const parsed = JSON.parse(body) as { id?: unknown }; - return parsed.id ?? null; + const parsed: unknown = JSON.parse(body); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null; + const id = (parsed as { id?: unknown }).id; + if (typeof id === 'string') return id; + if (typeof id === 'number') return Number.isFinite(id) ? id : null; } catch { - return null; + // A malformed body has no request id to preserve. } + return null; } function resolveRequestId(request: Request): string { @@ -925,50 +963,6 @@ function tenantRpcMethodRefusedResponse(rpcId: unknown): Response { ); } -const JSON_RPC_PARSE_ERROR = -32700; -const JSON_RPC_INVALID_REQUEST = -32600; - -/** Refuses an `/rpc` body that is not JSON, or not one object, as the daemon itself does. */ -function refuseInvalidRpcEnvelope(body: string): Response | null { - let parsed: unknown; - try { - parsed = JSON.parse(body); - } catch { - return rpcRefusalResponse(JSON_RPC_PARSE_ERROR, 'Parse error'); - } - if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return null; - return rpcRefusalResponse(JSON_RPC_INVALID_REQUEST, 'Invalid Request'); -} - -function rpcRefusalResponse(code: number, message: string): Response { - return Response.json( - { - jsonrpc: '2.0', - id: null, - error: { - code, - message, - data: normalizeError(new AppError('INVALID_ARGS', message)), - }, - }, - { status: 400 }, - ); -} - -/** An `/rpc` failure in the JSON-RPC envelope the client reads its error code and message from. */ -function rpcErrorResponse(rpcId: unknown, error: unknown): Response { - const normalized = publicProxyError(error); - const invalidArgs = normalized.code === 'INVALID_ARGS'; - return Response.json( - { - jsonrpc: '2.0', - id: rpcId, - error: { code: invalidArgs ? -32602 : -32000, message: normalized.message, data: normalized }, - }, - { status: invalidArgs ? 400 : 500 }, - ); -} - async function proxyErrorResponse(error: unknown, request: Request): Promise { const details = isTransferRoute(resolveProxyRoute(request.url), request.method) ? (await import('./transfer-transport.ts')).transferWireDetails(error) diff --git a/packages/proxy/src/node-http.test.ts b/packages/proxy/src/node-http.test.ts index 351ccc955e3..de38829986d 100644 --- a/packages/proxy/src/node-http.test.ts +++ b/packages/proxy/src/node-http.test.ts @@ -99,6 +99,73 @@ test('a method Fetch refuses is answered with 404 instead of a dropped socket', } }); +test('a handler can cancel an unread body and still answer the request', async () => { + const proxy: DaemonProxy = { + instanceId: 'test', + handle: async (request) => { + await request.body?.cancel(); + return new Response('body declined', { status: 400 }); + }, + }; + const server = http.createServer((req, res) => void serveProxyRequest(proxy, req, res)); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const response = await new Promise((resolve, reject) => { + const request = http.request( + { port, host: '127.0.0.1', method: 'POST', headers: { 'content-length': '4' } }, + resolve, + ); + request.on('error', reject); + request.setTimeout(1_000, () => request.destroy(new Error('No HTTP response'))); + request.flushHeaders(); + }); + expect(response.statusCode).toBe(400); + expect(response.headers.connection).toBe('close'); + let body = ''; + for await (const chunk of response) body += String(chunk); + expect(body).toBe('body declined'); + } finally { + await new Promise((resolve) => server.close(resolve)); + } +}); + +test('cancelling an unfinished body still writes a capacity refusal', async () => { + const proxy: DaemonProxy = { + instanceId: 'test', + handle: async (request) => { + await request.body?.cancel(); + return new Response(null, { status: 503 }); + }, + }; + const server = http.createServer((req, res) => void serveProxyRequest(proxy, req, res)); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const { port } = server.address() as AddressInfo; + const status = await new Promise((resolve, reject) => { + const client = http.request( + { + port, + host: '127.0.0.1', + method: 'POST', + path: '/agent-device/rpc', + headers: { 'content-length': '100' }, + }, + (response) => { + response.resume(); + resolve(response.statusCode); + }, + ); + client.on('error', reject); + client.write('partial'); + }); + expect(status).toBe(503); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + } +}); + test('real HTTP ingress refuses invalid targets and Host before forwarding', async () => { let calls = 0; const server = http.createServer( diff --git a/packages/proxy/src/node-http.ts b/packages/proxy/src/node-http.ts index b5b8ed60866..a2fb3f3bd82 100644 --- a/packages/proxy/src/node-http.ts +++ b/packages/proxy/src/node-http.ts @@ -23,6 +23,7 @@ export async function serveProxyRequest( const response = await proxy.handle(toWebRequest(url, req, res)); res.statusCode = response.status; for (const [name, value] of response.headers) res.setHeader(name, value); + if (!req.complete) res.setHeader('connection', 'close'); if (!response.body) { res.end(); return; @@ -43,13 +44,17 @@ function requestUrl(req: IncomingMessage): URL | null { function toWebRequest(url: URL, req: IncomingMessage, res: ServerResponse): Request { const method = req.method ?? 'GET'; const hasBody = method !== 'GET' && method !== 'HEAD'; + // The HTTP response owns the socket. Canceling a body read must leave it open to answer. + const body = hasBody + ? ( + Readable.toWeb(req, { strategy: { highWaterMark: 0 } }) as ReadableStream + ).pipeThrough(new TransformStream(), { preventCancel: true }) + : undefined; return new Request(url, { method, headers: toWebHeaders(req), signal: clientGoneSignal(req, res), - ...(hasBody - ? { body: Readable.toWeb(req) as ReadableStream, duplex: 'half' as const } - : {}), + ...(body ? { body, duplex: 'half' as const } : {}), }); } diff --git a/packages/proxy/src/rpc-body-budget.ts b/packages/proxy/src/rpc-body-budget.ts new file mode 100644 index 00000000000..c18299cd3be --- /dev/null +++ b/packages/proxy/src/rpc-body-budget.ts @@ -0,0 +1,68 @@ +import { + AppError, + createRequestCanceledError, + type ReasonTable, +} from '@agent-device/kernel/errors'; +import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; + +const MAX_IN_FLIGHT_RPC_BODY_BYTES = 128 * 1024 * 1024; +const RPC_INGRESS_REASONS = { + // Proxy RPC request bodies exceed the aggregate buffered-byte limit. + capacityExceeded: { reason: 'PROXY_RPC_BODY_CAPACITY_EXCEEDED' }, +} as const satisfies ReasonTable<'proxy RPC ingress'>; + +function capacityError(): AppError { + return new AppError('COMMAND_FAILED', 'Proxy RPC ingress capacity exceeded', { + reason: RPC_INGRESS_REASONS.capacityExceeded.reason, + retriable: true, + }); +} + +/** Holds the body bytes until the caller finishes authentication and dispatch. */ +export function createRpcBodyBudget(): { + read( + request: Request, + maxBodyBytes: number, + signal: AbortSignal, + ): Promise<{ body: string; release: () => void }>; +} { + let totalBytes = 0; + return { + async read(request, maxBodyBytes, signal) { + let ownedBytes = 0; + let released = false; + const release = () => { + if (released) return; + released = true; + totalBytes -= ownedBytes; + }; + try { + if (!request.body) return { body: '', release }; + const reader = request.body.getReader(); + const chunks: Uint8Array[] = []; + for (;;) { + const { done, value } = await awaitWithSignal(reader.read(), signal, () => { + void reader.cancel().catch(() => {}); + return createRequestCanceledError(undefined, signal.reason); + }); + if (done) break; + if (ownedBytes + value.byteLength > maxBodyBytes) { + void reader.cancel().catch(() => {}); + throw new AppError('INVALID_ARGS', 'Proxy request body is too large.'); + } + if (totalBytes + value.byteLength > MAX_IN_FLIGHT_RPC_BODY_BYTES) { + void reader.cancel().catch(() => {}); + throw capacityError(); + } + ownedBytes += value.byteLength; + totalBytes += value.byteLength; + chunks.push(value); + } + return { body: Buffer.concat(chunks).toString('utf8'), release }; + } catch (error) { + release(); + throw error; + } + }, + }; +} diff --git a/packages/proxy/src/rpc-refusals.ts b/packages/proxy/src/rpc-refusals.ts new file mode 100644 index 00000000000..a9f48d27aad --- /dev/null +++ b/packages/proxy/src/rpc-refusals.ts @@ -0,0 +1,60 @@ +import { AppError, normalizeError, type ReasonTable } from '@agent-device/kernel/errors'; + +const JSON_RPC_PARSE_ERROR = -32700; +const JSON_RPC_INVALID_REQUEST = -32600; +const PROXY_RPC_INGRESS_REASONS = { + // Proxy RPC body or authentication did not finish before its deadline, so nothing was dispatched. + preauthDeadlineExceeded: { reason: 'PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED' }, +} as const satisfies ReasonTable<'proxy RPC ingress'>; + +export function rpcPreauthDeadlineError(): AppError { + return new AppError('COMMAND_FAILED', 'Proxy RPC ingress deadline exceeded', { + reason: PROXY_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason, + dispatched: 'no', + retriable: true, + }); +} + +/** Refuses an `/rpc` body that is not JSON, or not one object, as the daemon itself does. */ +export function refuseInvalidRpcEnvelope(body: string): Response | null { + let parsed: unknown; + try { + parsed = JSON.parse(body); + } catch { + return rpcRefusalResponse(JSON_RPC_PARSE_ERROR, 'Parse error'); + } + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return null; + return rpcRefusalResponse(JSON_RPC_INVALID_REQUEST, 'Invalid Request'); +} + +function rpcRefusalResponse(code: number, message: string): Response { + return Response.json( + { + jsonrpc: '2.0', + id: null, + error: { + code, + message, + data: normalizeError(new AppError('INVALID_ARGS', message)), + }, + }, + { status: 400 }, + ); +} + +/** An `/rpc` failure in the JSON-RPC envelope the client reads its error code and message from. */ +export function rpcErrorResponse(rpcId: string | number | null, error: unknown): Response { + const normalized = normalizeError(error); + const invalidArgs = normalized.code === 'INVALID_ARGS'; + const capacityExceeded = normalized.details?.reason === 'PROXY_RPC_BODY_CAPACITY_EXCEEDED'; + const preauthDeadline = + normalized.details?.reason === PROXY_RPC_INGRESS_REASONS.preauthDeadlineExceeded.reason; + return Response.json( + { + jsonrpc: '2.0', + id: rpcId, + error: { code: invalidArgs ? -32602 : -32000, message: normalized.message, data: normalized }, + }, + { status: invalidArgs ? 400 : capacityExceeded ? 503 : preauthDeadline ? 408 : 500 }, + ); +} diff --git a/packages/remote/src/__tests__/upload-client-capacity.test.ts b/packages/remote/src/__tests__/upload-client-capacity.test.ts new file mode 100644 index 00000000000..a3167753670 --- /dev/null +++ b/packages/remote/src/__tests__/upload-client-capacity.test.ts @@ -0,0 +1,237 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import http from 'node:http'; +import path from 'node:path'; +import { test, vi } from 'vitest'; +import { + closeLoopbackServer, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { uploadArtifact } from '../upload-client.ts'; + +test('a typed preflight capacity refusal never falls back to the legacy route', async () => { + const dir = mkdtempForTestSync('upload-capacity-client-'); + const file = path.join(dir, 'app.apk'); + fs.writeFileSync(file, 'capacity-payload'); + const requests: string[] = []; + const server = http.createServer((req, res) => { + requests.push(`${req.method} ${req.url}`); + req.resume(); + req.on('end', () => { + res.statusCode = 503; + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ ok: false, reason: 'UPLOAD_CAPACITY_EXCEEDED' })); + }); + }); + try { + const port = await listenOnLoopback(server); + await assert.rejects( + uploadArtifact({ + localPath: file, + baseUrl: `http://127.0.0.1:${port}`, + token: 'test-token', + env: process.env, + }), + (error: unknown) => + error instanceof Error && + 'details' in error && + (error.details as { reason?: string }).reason === 'UPLOAD_CAPACITY_EXCEEDED', + ); + assert.deepEqual(requests, ['POST /upload/preflight']); + } finally { + await closeLoopbackServer(server); + } +}); + +test('a typed finalize capacity refusal never retries or falls back to legacy', async () => { + const dir = mkdtempForTestSync('upload-finalize-capacity-client-'); + const file = path.join(dir, 'app.apk'); + fs.writeFileSync(file, 'capacity-payload'); + const requests: string[] = []; + const runHeaders: Array = []; + const server = http.createServer((req, res) => { + requests.push(`${req.method} ${req.url}`); + runHeaders.push(req.headers['x-agent-device-run-id'] as string | undefined); + req.resume(); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + if (req.url === '/upload/preflight') { + res.end( + JSON.stringify({ + ok: true, + uploadId: 'ticket-1', + upload: { + url: `http://127.0.0.1:${(server.address() as { port: number }).port}/upload/direct/ticket-1`, + headers: {}, + }, + }), + ); + } else if (req.url === '/upload/finalize') { + res.statusCode = 503; + res.end(JSON.stringify({ ok: false, reason: 'UPLOAD_CAPACITY_EXCEEDED' })); + } else { + res.end(JSON.stringify({ ok: true, uploadId: 'ticket-1' })); + } + }); + }); + try { + const port = await listenOnLoopback(server); + await assert.rejects( + uploadArtifact({ + localPath: file, + baseUrl: `http://127.0.0.1:${port}`, + token: 'test-token', + leaseId: 'lease-1', + runId: 'run-1', + tenantId: 'tenant-1', + env: process.env, + }), + (error: unknown) => + error instanceof Error && + 'details' in error && + (error.details as { reason?: string }).reason === 'UPLOAD_CAPACITY_EXCEEDED', + ); + assert.deepEqual(requests, [ + 'POST /upload/preflight', + 'PUT /upload/direct/ticket-1', + 'POST /upload/finalize', + ]); + assert.deepEqual(runHeaders, ['run-1', 'run-1', 'run-1']); + } finally { + await closeLoopbackServer(server); + } +}); + +test('legacy fallback streams a file replaced between sizing and hashing', async () => { + const dir = mkdtempForTestSync('upload-legacy-run-client-'); + const file = path.join(dir, 'app.apk'); + fs.writeFileSync(file, 'legacy-payload'); + const replacement = 'a different-sized payload'; + const statSync = fs.statSync.bind(fs); + let stats = 0; + const stat = vi + .spyOn(fs, 'statSync') + .mockImplementation((...args: Parameters) => { + const result = statSync(...args); + if (args[0] === file && ++stats === 2) fs.writeFileSync(file, replacement); + return result; + }); + const requests: string[] = []; + const runHeaders: Array = []; + const lengths: Array = []; + const encodings: Array = []; + const server = http.createServer((req, res) => { + requests.push(`${req.method} ${req.url}`); + runHeaders.push(req.headers['x-agent-device-run-id'] as string | undefined); + lengths.push(req.headers['content-length']); + encodings.push(req.headers['transfer-encoding']); + const chunks: Buffer[] = []; + req.on('data', (chunk: Buffer) => chunks.push(chunk)); + req.on('end', () => { + if (req.url === '/upload/preflight') { + res.statusCode = 404; + res.end(); + } else { + if (Buffer.concat(chunks).toString() !== replacement) { + res.statusCode = 400; + res.end('unexpected artifact bytes'); + return; + } + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ ok: true, uploadId: 'legacy-1' })); + } + }); + }); + try { + const port = await listenOnLoopback(server); + const uploadId = await uploadArtifact({ + localPath: file, + baseUrl: `http://127.0.0.1:${port}`, + token: 'test-token', + leaseId: 'lease-1', + runId: 'run-1', + tenantId: 'tenant-1', + env: process.env, + }); + assert.equal(uploadId, 'legacy-1'); + assert.deepEqual(requests, ['POST /upload/preflight', 'POST /upload']); + assert.deepEqual(runHeaders, ['run-1', 'run-1']); + assert.equal(lengths[1], undefined); + assert.equal(encodings[1], 'chunked'); + } finally { + stat.mockRestore(); + await closeLoopbackServer(server); + } +}); + +test('legacy capacity refusal retains its typed reason', async () => { + const dir = mkdtempForTestSync('upload-legacy-capacity-client-'); + const file = path.join(dir, 'app.apk'); + fs.writeFileSync(file, 'capacity-payload'); + const server = http.createServer((req, res) => { + req.resume(); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + if (req.url === '/upload/preflight') { + res.statusCode = 404; + res.end(); + } else { + res.statusCode = 503; + res.end(JSON.stringify({ ok: false, reason: 'UPLOAD_CAPACITY_EXCEEDED' })); + } + }); + }); + try { + const port = await listenOnLoopback(server); + await assert.rejects( + uploadArtifact({ + localPath: file, + baseUrl: `http://127.0.0.1:${port}`, + token: 'test-token', + env: process.env, + }), + (error: unknown) => + error instanceof Error && + 'details' in error && + (error.details as { reason?: string }).reason === 'UPLOAD_CAPACITY_EXCEEDED', + ); + } finally { + await closeLoopbackServer(server); + } +}); + +test.for([400, 401, 403, 413])( + 'preflight refusal %i sends no file bytes or legacy request', + async (status, t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const root = mkdtempForTestSync('upload-refused-owner-'); + const file = path.join(root, 'app.apk'); + fs.writeFileSync(file, 'never-transfer-this-payload'); + const requests: string[] = []; + const server = http.createServer((req, res) => { + requests.push(`${req.method} ${req.url}`); + req.resume(); + res.writeHead(status, { 'content-type': 'application/json' }); + res.end( + JSON.stringify({ ok: false, code: 'UNAUTHORIZED', reason: 'LEASE_SESSION_MISMATCH' }), + ); + }); + try { + const port = await listenOnLoopback(server); + await assert.rejects( + uploadArtifact({ + localPath: file, + baseUrl: `http://127.0.0.1:${port}`, + token: 'test-token', + env: process.env, + }), + /before transfer/, + ); + assert.deepEqual(requests, ['POST /upload/preflight']); + } finally { + await closeLoopbackServer(server); + } + }, +); 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/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 3c2ec3b9f38..6494c2153dd 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -210,6 +210,9 @@ async function prepareRemoteInstallPackage( handoff: info.uploadHandoff, platform: req.flags?.platform, leaseId: leaseScopeFromRequest(req).leaseId, + runId: leaseScopeFromRequest(req).runId, + tenantId: leaseScopeFromRequest(req).tenantId, + session: req.session, onProgress, signal, }); @@ -316,6 +319,9 @@ async function prepareRemoteInstallSource( handoff: info.uploadHandoff, platform: req.flags?.platform, leaseId: leaseScopeFromRequest(req).leaseId, + runId: leaseScopeFromRequest(req).runId, + tenantId: leaseScopeFromRequest(req).tenantId, + session: req.session, onProgress, signal, }); diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index 8c79f0ae602..db3567b22d3 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -2,8 +2,12 @@ import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value' import { randomUUID } from 'node:crypto'; import { AppError } from '@agent-device/kernel/errors'; import { + DAEMON_HTTP_UPLOAD_SESSION_HEADER, buildDaemonHttpAuthHeaders, buildDaemonHttpLeaseHeaders, + buildDaemonHttpRunHeaders, + buildDaemonHttpTenantHeaders, + UPLOAD_CAPACITY_REASONS, } from '@agent-device/contracts/daemon-http'; import { prepareUploadArtifact, type PreparedUploadArtifact } from './upload-client-artifact.ts'; import { @@ -32,6 +36,9 @@ 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; + session?: string; onProgress?: UploadProgressSink; /** * Ends the upload when the thing it is uploading for stops being worth finishing — today, a beat @@ -92,6 +99,9 @@ async function uploadArtifactWithinBudget( normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, + tenantId: options.tenantId, + session: options.session, artifact: prepared, uploadAttemptId, env: options.env, @@ -107,6 +117,9 @@ async function uploadArtifactWithinBudget( normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, + tenantId: options.tenantId, + session: options.session, artifact: prepared, preflight, uploadAttemptId, @@ -126,6 +139,9 @@ async function uploadArtifactWithinBudget( normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, + tenantId: options.tenantId, + session: options.session, artifact: prepared, onProgress: options.onProgress, signal: options.signal, @@ -137,6 +153,9 @@ async function uploadArtifactWithinBudget( normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, + tenantId: options.tenantId, + session: options.session, artifact: prepared, onProgress: options.onProgress, signal: options.signal, @@ -151,6 +170,9 @@ async function tryDirectUploadWithResume(options: { normalizedBase: string; token: string; leaseId?: string; + runId?: string; + tenantId?: string; + session?: string; artifact: PreparedUploadArtifact; preflight: Extract; uploadAttemptId: string; @@ -167,6 +189,9 @@ async function tryDirectUploadWithResume(options: { normalizedBase: options.normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, + tenantId: options.tenantId, + session: options.session, uploadId: preflight.uploadId, signal: options.signal, handoff: options.handoff, @@ -181,6 +206,11 @@ async function tryDirectUploadWithResume(options: { if (options.signal.aborted) throw error; // An expired phase is this client's own deadline, never a transport break to retry. if (isTransferPhaseTimeoutError(error)) throw error; + if ( + error instanceof AppError && + error.details?.reason === UPLOAD_CAPACITY_REASONS.exceeded.reason + ) + throw error; if (!shouldRetryDirectUpload(error)) return undefined; return await retryDirectUpload(options, uploadOnce); } @@ -198,6 +228,9 @@ async function retryDirectUpload( normalizedBase: string; token: string; leaseId?: string; + runId?: string; + tenantId?: string; + session?: string; artifact: PreparedUploadArtifact; uploadAttemptId: string; env: HostEnvironment['env']; @@ -213,6 +246,9 @@ async function retryDirectUpload( normalizedBase: options.normalizedBase, token: options.token, leaseId: options.leaseId, + runId: options.runId, + tenantId: options.tenantId, + session: options.session, artifact: options.artifact, uploadAttemptId: options.uploadAttemptId, env: options.env, @@ -228,6 +264,11 @@ async function retryDirectUpload( } catch (error) { options.signal.throwIfAborted(); if (isTransferPhaseTimeoutError(error)) throw error; + if ( + error instanceof AppError && + error.details?.reason === UPLOAD_CAPACITY_REASONS.exceeded.reason + ) + throw error; return undefined; } } @@ -243,12 +284,15 @@ async function uploadLegacyArtifact(options: { normalizedBase: string; token: string; leaseId?: string; + runId?: string; + tenantId?: string; + session?: string; artifact: PreparedUploadArtifact; onProgress?: UploadProgressSink; signal: AbortSignal; handoff?: UploadHandoff; }): Promise { - const { normalizedBase, token, leaseId, artifact } = options; + const { normalizedBase, token, artifact } = options; const uploadUrl = new URL('upload', normalizedBase); const headers: Record = { @@ -257,9 +301,11 @@ async function uploadLegacyArtifact(options: { 'x-artifact-filename': artifact.fileName, 'x-artifact-hash': artifact.sha256, 'x-artifact-hash-algorithm': ARTIFACT_HASH_ALGORITHM, - 'transfer-encoding': 'chunked', + ...(artifact.artifactType === 'file' + ? { 'transfer-encoding': 'chunked' } + : { 'content-length': String(artifact.sizeBytes) }), }; - Object.assign(headers, buildDaemonHttpAuthHeaders(token), buildDaemonHttpLeaseHeaders(leaseId)); + Object.assign(headers, buildDaemonHttpAuthHeaders(token), uploadScopeHeaders(options)); const response = await streamFileToHttpRequest({ url: uploadUrl, @@ -278,7 +324,13 @@ async function uploadLegacyArtifact(options: { }); try { - const parsed = JSON.parse(response.body) as UploadResponse; + const parsed = JSON.parse(response.body) as Partial & { reason?: unknown }; + if (response.statusCode === 503 && parsed.reason === UPLOAD_CAPACITY_REASONS.exceeded.reason) { + throw new AppError('COMMAND_FAILED', 'Upload capacity exceeded', { + reason: UPLOAD_CAPACITY_REASONS.exceeded.reason, + retriable: true, + }); + } if (!parsed.ok || !parsed.uploadId) { throw new AppError('COMMAND_FAILED', `Upload failed: ${response.body}`); } @@ -289,40 +341,59 @@ async function uploadLegacyArtifact(options: { } } +function uploadScopeHeaders(scope: { + tenantId?: string; + leaseId?: string; + runId?: string; + session?: string; +}) { + return { + ...(scope.session ? { [DAEMON_HTTP_UPLOAD_SESSION_HEADER]: scope.session } : {}), + ...buildDaemonHttpTenantHeaders(scope.tenantId), + ...buildDaemonHttpLeaseHeaders(scope.leaseId), + ...buildDaemonHttpRunHeaders(scope.runId), + }; +} + +function uploadControlHeaders(scope: { + token: string; + tenantId?: string; + session?: string; + leaseId?: string; + runId?: string; +}) { + return { + 'content-type': 'application/json', + ...buildDaemonHttpAuthHeaders(scope.token), + ...uploadScopeHeaders(scope), + }; +} + async function requestUploadPreflight(options: { normalizedBase: string; token: string; leaseId?: string; + runId?: string; + tenantId?: string; + session?: string; artifact: PreparedUploadArtifact; uploadAttemptId: string; env: HostEnvironment['env']; signal?: AbortSignal; handoff?: UploadHandoff; }): 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 result = await requestUploadControl( - preflightUrl, - { - headers, - body: JSON.stringify({ - uploadAttemptId: options.uploadAttemptId, - sha256: options.artifact.sha256, - fileName: options.artifact.fileName, - sizeBytes: options.artifact.sizeBytes, - artifactType: options.artifact.artifactType, - ...(options.artifact.platform ? { platform: options.artifact.platform } : {}), - contentType: options.artifact.contentType, - }), - }, + new URL('upload/preflight', options.normalizedBase), + options, + JSON.stringify({ + uploadAttemptId: options.uploadAttemptId, + sha256: options.artifact.sha256, + fileName: options.artifact.fileName, + sizeBytes: options.artifact.sizeBytes, + artifactType: options.artifact.artifactType, + ...(options.artifact.platform ? { platform: options.artifact.platform } : {}), + contentType: options.artifact.contentType, + }), 'preflight', options.signal, options.handoff, @@ -333,6 +404,21 @@ async function requestUploadPreflight(options: { return undefined; }); + throwIfUploadCapacityRefused(result); + if ( + result && + result.response.status >= 400 && + result.response.status < 500 && + result.response.status !== 404 + ) { + throw new AppError( + result.response.status === 401 || result.response.status === 403 + ? 'UNAUTHORIZED' + : 'INVALID_ARGS', + 'Upload preflight was refused before transfer', + result.body as Record, + ); + } if (!result?.response.ok) { return undefined; } @@ -348,7 +434,15 @@ async function requestUploadPreflight(options: { async function requestUploadControl( url: URL, - init: { headers: Record; body: string }, + options: { + token: string; + leaseId?: string; + runId?: string; + tenantId?: string; + session?: string; + signal?: AbortSignal; + }, + requestBody: string, phase: 'preflight' | 'finalize', callerSignal?: AbortSignal, handoff?: UploadHandoff, @@ -360,14 +454,15 @@ async function requestUploadControl( watchdog.signal.throwIfAborted(); watchdog.arm(phase, UPLOAD_CONTROL_PLANE_TIMEOUT_MS); return fetch(url, { - ...init, + headers: uploadControlHeaders(options), + body: requestBody, method: 'POST', redirect: 'error', signal: watchdog.signal, }); }; const response = await (handoff?.(start) ?? start()); - const body: unknown = response.ok ? await response.json().catch(() => undefined) : undefined; + const body: unknown = await response.json().catch(() => undefined); watchdog.signal.throwIfAborted(); return { response, body }; } catch (error) { @@ -378,6 +473,21 @@ async function requestUploadControl( } } +function throwIfUploadCapacityRefused( + result: { response: Response; body: unknown } | undefined, +): void { + if ( + result?.response.status === 503 && + (result.body as { reason?: unknown } | undefined)?.reason === + UPLOAD_CAPACITY_REASONS.exceeded.reason + ) { + throw new AppError('COMMAND_FAILED', 'Upload capacity exceeded', { + reason: UPLOAD_CAPACITY_REASONS.exceeded.reason, + retriable: true, + }); + } +} + function parseUploadPreflightResult(value: unknown): UploadPreflightResult | undefined { if (!value || typeof value !== 'object') { return undefined; @@ -420,6 +530,9 @@ async function uploadDirectArtifact( options: { normalizedBase: string; leaseId?: string; + runId?: string; + tenantId?: string; + session?: string; artifact: PreparedUploadArtifact; onProgress?: UploadProgressSink; signal: AbortSignal; @@ -436,7 +549,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', @@ -462,26 +578,17 @@ async function finalizeDirectUpload(options: { normalizedBase: string; token: string; leaseId?: string; + runId?: string; + tenantId?: string; + session?: string; uploadId: string; signal?: AbortSignal; handoff?: UploadHandoff; }): 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 result = await requestUploadControl( - finalizeUrl, - { - headers, - body: JSON.stringify({ uploadId: options.uploadId }), - }, + new URL('upload/finalize', options.normalizedBase), + options, + JSON.stringify({ uploadId: options.uploadId }), 'finalize', options.signal, options.handoff, @@ -492,6 +599,8 @@ async function finalizeDirectUpload(options: { throw new AppError('COMMAND_FAILED', 'Failed to finalize direct artifact upload', {}, error); }); + throwIfUploadCapacityRefused(result); + if (!result.response.ok) { throw new AppError('COMMAND_FAILED', 'Direct artifact upload finalize failed', { status: result.response.status, diff --git a/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts b/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts index e7d35f20840..51efd11c9b0 100644 --- a/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts +++ b/packages/replay-port/src/daemon-port/__tests__/script-source.test.ts @@ -1,6 +1,15 @@ import { expect, test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; -import { readReplayScriptSourceFile } from '../script-source.ts'; +import { REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES as CLIENT_SOURCE_MAX_BYTES } from '../../script-source-bundle.ts'; +import { + assertReplayScriptSourcesWithinLimit, + readReplayScriptSourceFile, + REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, +} from '../script-source.ts'; + +test('client and daemon enforce the same replay source byte ceiling', () => { + expect(REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES).toBe(CLIENT_SOURCE_MAX_BYTES); +}); test('reading a file the bundle does not carry names the file and the entry', () => { const bundle = { entry: '/flows/login.yaml', files: { '/flows/login.yaml': '---\n- back\n' } }; @@ -15,3 +24,91 @@ test('reading a file the bundle does not carry names the file and the entry', () expect((error as AppError).details).toMatchObject({ entry: '/flows/login.yaml' }); } }); + +test('a remote test request cannot hide oversized sources across bundles', () => { + const half = 'x'.repeat(REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES / 2); + const source = { entry: 'flow.ad', files: { 'flow.ad': half } }; + expect(() => + assertReplayScriptSourcesWithinLimit({ replayScriptSources: [source, source] }), + ).not.toThrow(); + expect(() => + assertReplayScriptSourcesWithinLimit({ + replayScriptSources: [source, { entry: 'extra.ad', files: { 'extra.ad': 'x' } }, source], + }), + ).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ + limitBytes: REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, + totalBytes: REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES + 1, + }), + }), + ); +}); + +test('an oversized replay source path reports the path byte limit', () => { + const entry = 'flow.ad'; + const longPath = 'x'.repeat(64 * 1024); + expect(() => + assertReplayScriptSourcesWithinLimit({ + replayScriptSource: { entry, files: { [entry]: 'x', [longPath]: 'x' } }, + }), + ).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ + limitBytes: 64 * 1024, + totalBytes: 64 * 1024 + 2 * entry.length, + }), + }), + ); +}); + +test('empty replay source names are refused before suite discovery', () => { + expect(() => + assertReplayScriptSourcesWithinLimit({ replayScriptSource: { entry: '', files: { '': '' } } }), + ).toThrow(expect.objectContaining({ code: 'INVALID_ARGS' })); + expect(() => + assertReplayScriptSourcesWithinLimit({ + replayScriptSource: { entry: 'flow.ad', files: { '': '', 'flow.ad': '' } }, + }), + ).toThrow(expect.objectContaining({ code: 'INVALID_ARGS' })); +}); + +test('an empty source list passes source admission', () => { + expect(() => assertReplayScriptSourcesWithinLimit({ replayScriptSources: [] })).not.toThrow(); +}); + +test('empty replay source text cannot evade bundle or file counts', () => { + const source = { entry: 'flow.ad', files: { 'flow.ad': '' } }; + expect(() => + assertReplayScriptSourcesWithinLimit({ replayScriptSources: Array(256).fill(source) }), + ).not.toThrow(); + expect(() => + assertReplayScriptSourcesWithinLimit({ replayScriptSources: Array(257).fill(source) }), + ).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ + limitCount: 256, + totalCount: 257, + hint: expect.stringContaining('Split the suite'), + }), + }), + ); + const files = Object.fromEntries( + Array.from({ length: 2_049 }, (_, index) => [`file-${index}`, '']), + ); + expect(() => + assertReplayScriptSourcesWithinLimit({ replayScriptSource: { entry: 'file-0', files } }), + ).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ + limitCount: 2_048, + totalCount: 2_049, + hint: expect.stringContaining('Split the suite'), + }), + }), + ); +}); diff --git a/packages/replay-port/src/daemon-port/__tests__/test-command-remote-artifacts.test.ts b/packages/replay-port/src/daemon-port/__tests__/test-command-remote-artifacts.test.ts index b4f77a5e240..c6496ea17a1 100644 --- a/packages/replay-port/src/daemon-port/__tests__/test-command-remote-artifacts.test.ts +++ b/packages/replay-port/src/daemon-port/__tests__/test-command-remote-artifacts.test.ts @@ -90,7 +90,11 @@ test('rewrites the suite, every test, and every failure to the caller-local root const clientRoot = '/Users/ci/work/installer-app/remote-device-artifacts/ad-test'; const clientSuiteRoot = path.join(clientRoot, SUITE_INVOCATION_ID); - const data = attachRemoteReplayTestArtifacts(suiteResult(daemonRoot), req(clientRoot)); + const data = attachRemoteReplayTestArtifacts( + suiteResult(daemonRoot), + req(clientRoot), + (artifact) => artifact, + ); assert.equal(data.artifactsDir, clientSuiteRoot); const tests = data.tests as ReplaySuiteResult['tests']; @@ -133,7 +137,7 @@ test('a local daemon (no clientArtifactPaths hint) returns the suite result unch fs.mkdirSync(path.join(daemonRoot, 'qa-flows__open.ad', 'attempt-1'), { recursive: true }); const result = suiteResult(daemonRoot); - const data = attachRemoteReplayTestArtifacts(result, req(undefined)); + const data = attachRemoteReplayTestArtifacts(result, req(undefined), (artifact) => artifact); assert.equal(data, result); }); @@ -149,6 +153,7 @@ test('a public suite without a client destination returns relative paths and sta const data = attachRemoteReplayTestArtifacts( suiteResult(daemonRoot), req(undefined), + (artifact) => artifact, [{ ...recording, path: path.join(daemonRoot, 'recording.mp4') }], true, ); @@ -187,7 +192,7 @@ test('a suite directory that was never created (all sources skipped) still repor ], }; - const data = attachRemoteReplayTestArtifacts(result, req(clientRoot)); + const data = attachRemoteReplayTestArtifacts(result, req(clientRoot), (artifact) => artifact); // Nothing to download, but the reported root is still the caller-local one the suite WOULD // have used — not the unreachable daemon-local temp path. diff --git a/packages/replay-port/src/daemon-port/command-types.ts b/packages/replay-port/src/daemon-port/command-types.ts index 60981495d44..51b388576d6 100644 --- a/packages/replay-port/src/daemon-port/command-types.ts +++ b/packages/replay-port/src/daemon-port/command-types.ts @@ -7,7 +7,7 @@ import type { ReplayBackendSession, } from '@agent-device/contracts/replay-backend'; import type { SessionAction, SessionScope } from '@agent-device/contracts/session'; -import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import type { DaemonArtifact, DaemonResponse } from '@agent-device/kernel/contracts'; /** Immutable read projection of the repair-transaction fields the coordinator's writers touch. */ export type ReplaySessionView = Readonly<{ @@ -101,6 +101,7 @@ export type ReplayTestVideoOwner = Readonly<{ export type ReplayTestCommand = ReplayCommand & Readonly<{ + commitArtifact: (artifact: DaemonArtifact & { path: string }) => DaemonArtifact; createSession: ReplayTestSessionFactory; runAttempt: ( sessionName: string, diff --git a/packages/replay-port/src/daemon-port/script-source.ts b/packages/replay-port/src/daemon-port/script-source.ts index 717008434cb..97fe20dd05b 100644 --- a/packages/replay-port/src/daemon-port/script-source.ts +++ b/packages/replay-port/src/daemon-port/script-source.ts @@ -1,5 +1,97 @@ import { AppError } from '@agent-device/kernel/errors'; import type { ReplayScriptSourceBundle } from '@agent-device/contracts/replay'; +export const REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES = 2 * 1024 * 1024; +const REPLAY_SCRIPT_SOURCE_PATH_MAX_BYTES = 64 * 1024; +const REPLAY_SCRIPT_SOURCE_MAX_BUNDLES = 256; +const REPLAY_SCRIPT_SOURCE_MAX_FILES = 2_048; + +/** Admit client-supplied replay sources before any engine reads or splits their text. */ +export function assertReplayScriptSourcesWithinLimit( + flags: Record | undefined, +): void { + if (!flags) return; + const sources = replaySourcesFromFlags(flags); + if (!sources) return; + if (sources.length === 0) return; + if (sources.length > REPLAY_SCRIPT_SOURCE_MAX_BUNDLES) { + throw new AppError('INVALID_ARGS', 'Replay request carries too many source bundles.', { + limitCount: REPLAY_SCRIPT_SOURCE_MAX_BUNDLES, + totalCount: sources.length, + hint: 'Split the suite or shard it into smaller invocations.', + }); + } + const size = { text: 0, paths: 0, files: 0 }; + for (const source of sources) validateReplaySource(source, size); +} + +function replaySourcesFromFlags(flags: Record): unknown[] | undefined { + const single = flags.replayScriptSource; + const multiple = flags.replayScriptSources; + if (single === undefined && multiple === undefined) return undefined; + if (single !== undefined && multiple !== undefined) invalidReplaySources(); + const sources = multiple === undefined ? [single] : multiple; + if (!Array.isArray(sources)) invalidReplaySources(); + return sources; +} + +function validateReplaySource( + source: unknown, + size: { text: number; paths: number; files: number }, +): void { + if ( + !isRecord(source) || + typeof source.entry !== 'string' || + source.entry.length === 0 || + !isRecord(source.files) + ) { + invalidReplaySources(); + } + if (!Object.hasOwn(source.files, source.entry) || typeof source.files[source.entry] !== 'string') + invalidReplaySources(); + size.paths += Buffer.byteLength(source.entry, 'utf8'); + for (const [filePath, text] of Object.entries(source.files)) { + if ( + ['__proto__', 'prototype', 'constructor'].includes(filePath) || + filePath.length === 0 || + typeof text !== 'string' + ) + invalidReplaySources(); + size.files += 1; + if (size.files > REPLAY_SCRIPT_SOURCE_MAX_FILES) { + throw new AppError('INVALID_ARGS', 'Replay request carries too many source files.', { + limitCount: REPLAY_SCRIPT_SOURCE_MAX_FILES, + totalCount: size.files, + hint: 'Split the suite or shard it into smaller invocations.', + }); + } + size.paths += Buffer.byteLength(filePath, 'utf8'); + size.text += Buffer.byteLength(text, 'utf8'); + if (size.text > REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES) { + throw new AppError('INVALID_ARGS', 'Replay script sources exceed the request byte limit.', { + limitBytes: REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES, + totalBytes: size.text, + }); + } + if (size.paths > REPLAY_SCRIPT_SOURCE_PATH_MAX_BYTES) { + throw new AppError( + 'INVALID_ARGS', + 'Replay script source paths exceed the request byte limit.', + { + limitBytes: REPLAY_SCRIPT_SOURCE_PATH_MAX_BYTES, + totalBytes: size.paths, + }, + ); + } + } +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function invalidReplaySources(): never { + throw new AppError('INVALID_ARGS', 'Replay script sources must contain an entry and text files.'); +} export const REPLAY_SCRIPT_SOURCE_REQUIRED_MESSAGE = 'This replay request carries no script sources. Replay scripts are read by the client and sent with the request; upgrade the agent-device client that issued it to a version that sends script sources.'; @@ -8,7 +100,7 @@ export function readReplayScriptSourceFile( bundle: ReplayScriptSourceBundle, resolvedPath: string, ): string { - const script = bundle.files[resolvedPath]; + const script = Object.hasOwn(bundle.files, resolvedPath) ? bundle.files[resolvedPath] : undefined; if (script === undefined) { throw new AppError( 'INVALID_ARGS', diff --git a/packages/replay-port/src/daemon-port/test-command-flag-policy.test.ts b/packages/replay-port/src/daemon-port/test-command-flag-policy.test.ts index 3605c4b68a3..bf574c86ba3 100644 --- a/packages/replay-port/src/daemon-port/test-command-flag-policy.test.ts +++ b/packages/replay-port/src/daemon-port/test-command-flag-policy.test.ts @@ -9,6 +9,7 @@ function rejectedTestCommand(flags: CommandFlags) { throw new Error('test must not start a suite attempt when a replay-only flag is rejected'); }); const command: ReplayTestCommand = { + commitArtifact: (artifact) => artifact, request: { token: 'token', session: 'default', diff --git a/packages/replay-port/src/daemon-port/test-command.ts b/packages/replay-port/src/daemon-port/test-command.ts index 689254a3612..5740796327f 100644 --- a/packages/replay-port/src/daemon-port/test-command.ts +++ b/packages/replay-port/src/daemon-port/test-command.ts @@ -310,6 +310,7 @@ export async function runReplayTestCommand(command: ReplayTestCommand): Promise< data: attachRemoteReplayTestArtifacts( outcome.data, req, + command.commitArtifact, command.recordingOutputs?.(), command.publicNetworkOnly, ), @@ -371,6 +372,7 @@ function withOriginalTestRefusalGuidance( export function attachRemoteReplayTestArtifacts( data: ReplaySuiteResult, req: DaemonWireRequest, + commitArtifact: ReplayTestCommand['commitArtifact'], recordings: readonly ReplaySuiteRecordingArtifact[] = [], publicNetworkOnly = false, ): DaemonResponseData { @@ -434,7 +436,7 @@ export function attachRemoteReplayTestArtifacts( return { ...rewritten, artifacts: [ - { + commitArtifact({ field: 'artifactsDir', artifactType: 'test-artifacts', path: daemonRoot, @@ -442,7 +444,7 @@ export function attachRemoteReplayTestArtifacts( // top-level entry already supplies the invocation-id segment on extraction. localPath: clientRoot, fileName: path.basename(daemonRoot), - }, + }), ], }; } diff --git a/src/__tests__/cli-run-transport.test.ts b/src/__tests__/cli-run-transport.test.ts index 39e5b18f80b..31dc187acc9 100644 --- a/src/__tests__/cli-run-transport.test.ts +++ b/src/__tests__/cli-run-transport.test.ts @@ -25,6 +25,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.ts b/src/cli.ts index 63b5c750678..167b1359659 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -366,6 +366,7 @@ type CliRunContext = { daemonPaths: ReturnType; sessionName: string; hadConnectionDefaults: boolean; + explicitArtifactQuery: boolean; claimedConnection?: RemoteConnectionState | null; commandConnection: CommandConnection | null; cloudSession?: CloudSessionBinding; @@ -418,7 +419,11 @@ async function resolveRunContextOrExit( const leasedRemoteConfig = parsed.remoteConfigLeaseProvider && runsOnRemoteConnection(base.command); const leasedConnect = base.command === 'connect' && !flags.remoteConfig; - if (flags.session === undefined && (leasedRemoteConfig || leasedConnect)) { + if ( + !parsed.artifactQuery && + flags.session === undefined && + (leasedRemoteConfig || leasedConnect) + ) { throw remoteSessionRequiredError(parsed.remoteConfigLeaseProvider); } const { resolveCommandConnection } = await import('./cli/connection/command-connection.ts'); @@ -431,17 +436,18 @@ async function resolveRunContextOrExit( base.command !== 'connection' && runsOnRemoteConnection(base.command), materializes: shouldMaterializeRemoteConnection(base.command), + artifactQuery: parsed.artifactQuery, command: base.command, }); const { resolveCloudAdmission } = await import('./cli/connection/active-connection.ts'); - const cloudSession = defaults?.cloudSession; + const cloudSession = parsed.artifactQuery ? undefined : defaults?.cloudSession; const admitConnection = await resolveCloudAdmission({ releaseProxyFrontLease: (state, attachment) => import('./cli/connection/proxy-front-release.ts').then((module) => module.releaseExpiredProxyFrontLease(base.host, state, attachment), ), command: base.command, - usesSessions: runsOnRemoteConnection(base.command), + usesSessions: !parsed.artifactQuery && runsOnRemoteConnection(base.command), forget: effectiveFlags.forget, stateDir: daemonPaths.baseDir, host: base.host, @@ -463,12 +469,13 @@ async function resolveRunContextOrExit( daemonPaths, sessionName: flags.session ?? 'default', hadConnectionDefaults: defaults !== null, + explicitArtifactQuery: parsed.artifactQuery !== undefined, claimedConnection: defaults?.claimed, commandConnection: connection, explicitFlagKeys, effectiveFlags, - resolvedRuntime: defaults?.runtime, - connectionMetadata: defaults?.connection, + resolvedRuntime: parsed.artifactQuery ? undefined : defaults?.runtime, + connectionMetadata: parsed.artifactQuery ? undefined : defaults?.connection, parsedBatchSteps: undefined, devicePin: parsed.devicePin, }; @@ -890,6 +897,7 @@ function shouldWarnOpenMayMissRemoteRuntime(options: { runtime?: SessionRuntimeHints; explicitFlagKeys: Set; hadConnectionDefaults: boolean; + explicitArtifactQuery: boolean; claimedConnection?: RemoteConnectionState | null; }): boolean { if (options.command !== 'open') return false; diff --git a/src/cli/connection/command-connection.ts b/src/cli/connection/command-connection.ts index 3bdea595f76..ef80bcc58de 100644 --- a/src/cli/connection/command-connection.ts +++ b/src/cli/connection/command-connection.ts @@ -1,3 +1,5 @@ +import { leaseProviderRequiringRuntime } from '@agent-device/contracts/lease-scope'; +import type { ResolvedCliOptions } from '../resolve-cli-options.ts'; import fs from 'node:fs'; import { admitDaemonStateRoot, @@ -35,6 +37,7 @@ type CommandConnectionOptions = { readDefaults: boolean; materializes: boolean; command?: string; + artifactQuery?: ResolvedCliOptions['artifactQuery']; }; type CommandConnectionContext = { @@ -80,6 +83,34 @@ export function resolveCommandConnection( state: storedState, }); const merged = defaults ? mergeConnectionFlags(flags, defaults.flags, explicitFlagKeys) : flags; + if (options.artifactQuery) { + const query = options.artifactQuery; + const connectionProvider = + defaults?.connection && leaseProviderRequiringRuntime(defaults.connection); + const inheritsNamedOwner = + query.leaseId === undefined && + query.runId === undefined && + explicitFlagKeys.has('session') && + connectionProvider && + (merged.provider ?? connectionProvider) === connectionProvider && + merged.tenant === defaults?.flags.tenant && + merged.daemonBaseUrl === defaults?.flags.daemonBaseUrl && + merged.daemonTransport === defaults?.flags.daemonTransport; + return { + daemonPaths: paths, + defaults, + connection: null, + effectiveFlags: { + ...merged, + provider: query.providerSessionId + ? (merged.provider ?? connectionProvider) + : merged.provider, + leaseId: inheritsNamedOwner ? defaults?.flags.leaseId : query.leaseId, + runId: inheritsNamedOwner ? defaults?.flags.runId : query.runId, + leaseBackend: undefined, + }, + }; + } if (!options.materializes || !merged.remoteConfig) { return { daemonPaths: paths, effectiveFlags: merged, defaults, connection: null }; } diff --git a/src/cli/resolve-cli-options.ts b/src/cli/resolve-cli-options.ts index daa1bec2608..dceb61263c8 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 2682f271ce9..d6305682681 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -682,7 +682,7 @@ Rules: To replace a hosted connection, pass --session --force with the existing session name. 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. + After closing a device cloud session, keep the same cloud connection and producing lease scope when you run agent-device artifacts --json. A provider session ID alone does not grant access. Without lease scope, daemon inventory lists only unleased output. 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. Use disconnect to end a hosted session. For direct proxy connections, close also releases the device lease. diff --git a/src/daemon-entrypoint.test.ts b/src/daemon-entrypoint.test.ts index 4ec90a82210..f2f3f6b22b3 100644 --- a/src/daemon-entrypoint.test.ts +++ b/src/daemon-entrypoint.test.ts @@ -151,7 +151,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-'); let runtime: DaemonRuntimeController | null = null; @@ -190,7 +190,7 @@ 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' }); diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index c36004bfe45..551830a11ac 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -1,5 +1,5 @@ { - "protocolVersion": 3, + "protocolVersion": 4, "declarations": { "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_BASE_PATH": "sha256:a1ada25c6f90d9c69c8c836538e8882547bf239559f7c1accacd0654355802dd", "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_TENANT_HEADER": "sha256:ed49119d232500885f014ac73f6123d298d404c6c176abdae59cf324825927e5", @@ -88,7 +88,7 @@ "packages/daemon/src/server/http-errors.ts#NormalizedHttpError": "sha256:2c2111802fe5f193acbeacc454de9cfab82bc8e4274b896f485e19a14f5518cf", "packages/daemon/src/server/http-errors.ts#failStreamedHttpResponse": "sha256:3e6b642cb41b88ab1e6f3269ebd14918f912cbecf09f40e9b591fdd28a2ba489", "packages/daemon/src/server/http-errors.ts#sendRestJsonError": "sha256:226399f1ecfc9024c44198568d39970c7b9fb7ef2f6ab58afe57ed8b0d8edd27", - "packages/daemon/src/server/http-errors.ts#statusCodeForNormalizedError": "sha256:39aa61eed8459527d7077e31e23be4fe0275021ed99c70ad692538091db91125", + "packages/daemon/src/server/http-errors.ts#statusCodeForNormalizedError": "sha256:2d13b89473a83112ed98c53c885e62d852d0ee7cda858ff979c5b294a3bac2a1", "packages/daemon/src/server/http-request-target.ts#decodeUriSegment": "sha256:b37622771ea4e61d1a9820169dbdc5809b5c38889bfad79277d7b22f3c3f1ef1", "packages/daemon/src/server/request-diagnostics-http.ts#REQUEST_DIAGNOSTICS_CONTENT_TYPE": "sha256:16bbd9ae7eaeaaa8c8cbd6e65c4ce786a6c5230c5351288228bbf1a6f11bdcdc", "packages/daemon/src/server/request-diagnostics-http.ts#RequestDiagnosticsHttpAuthorizer": "sha256:24b0fa6b1d965e5cf6503a4665148dc6360c56bf5a0ae710eeaa76a73a62c52a", @@ -103,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:9a2b0abb4b1a208763952e7deec3c492bfb9fb6603e6e108839ec4dcc9d24700", "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", @@ -130,21 +130,21 @@ "packages/daemon/src/server/http/http-rpc-methods.ts#toDaemonRequest": "sha256:14743424656a7a4097eb184d2be2c6272d0b1ff645591e4f4f9430d030789013", "packages/daemon/src/server/http/http-rpc-methods.ts#toInstallFromSourceDaemonRequest": "sha256:5110ccd2e370ec4f85b64a692cbeaf6ecab44b745e31d2c11e7559aab45d5238", "packages/daemon/src/server/http/http-rpc-methods.ts#toLeaseDaemonRequest": "sha256:a7bcfa4e8e09378b71dbcffc0566ea6ca82eeeb309e910182f4797cd626736e2", - "packages/daemon/src/server/http/http-rpc-methods.ts#toReleaseMaterializedPathsDaemonRequest": "sha256:d1b91e9abe8d1527c5dfbc855b0b31eee61766020a940acfe2310e7d3eb69e9d", + "packages/daemon/src/server/http/http-rpc-methods.ts#toReleaseMaterializedPathsDaemonRequest": "sha256:1f87659a0a677ba745ffdd50b52ac09af62e4978a0e35e276f4240eb6bd644fb", "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", "packages/daemon/src/core/session-tenant-scope.ts#isTenantAddressableSessionName": "sha256:cc8ae18094b7f57d4bb694678f84ba767637b1087fd28058ffd6a3c92c79f05d", - "packages/daemon/src/server/upload-http.ts#AuxiliaryHttpAuthorizer": "sha256:939b227d303574f90d59f01dd1bcb99eec7c5831b8e40dc5a6412be62c673e7e", + "packages/daemon/src/server/upload-http.ts#AuxiliaryHttpAuthorizer": "sha256:2a6f1630c34fbb438fdef81a4a15eb31d3a38e090722f6b7c7c37a2d00fbe95f", "packages/daemon/src/server/upload-http.ts#DIRECT_UPLOAD_PATH_PREFIX": "sha256:6fe7d42a65baceb595d96b6aa83fe9aa84527d9aa2e448d7ef47882d31a03276", "packages/daemon/src/server/upload-http.ts#UploadFinalizeBody": "sha256:c358aea9b3c341f51f3fa263032dfda8a3fbbf729396fcf7f2d8aa051b231b8b", "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:964a482a4bd711f988ce3876d6f7eb79199cad2fb5bdbbaabf1063f418539036", + "packages/daemon/src/server/upload-http.ts#handleUpload": "sha256:225cc7b3d93570e3099c9c109d5b795d140c34051ec63a721f4a86718c7280a9", + "packages/daemon/src/server/upload-http.ts#handleUploadFinalize": "sha256:a89514f940a315b3ffdb312ec3376a8f567dc3b4cbda686a3a6b1cf1a532369f", + "packages/daemon/src/server/upload-http.ts#handleUploadPreflight": "sha256:d1e7dbe52534de94b32c6e1cccedbf704442d877d5c33707f7f9adaca060229e", "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", @@ -153,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:2154c087dc223db5b9a03929f5495c0972cbeb2f842b6654210c9afa5dc76fd3", "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:ad45f46b76540332bf71e28b58fc45a0267f9d1e67faecc17bd2b884073191df", @@ -176,15 +176,15 @@ "packages/remote/src/upload-client.ts#UploadPreflightResponse": "sha256:196a1d9ef41a1aec192589fa7ccb30cf71d971a005349d5d73eed42e6ab21327", "packages/remote/src/upload-client.ts#UploadPreflightResult": "sha256:bd8fc6d617c0630325455fd64d0fe319daaced198ee6745e4673a8ace3df460d", "packages/remote/src/upload-client.ts#UploadResponse": "sha256:499e01466b5e0e03413f8d3f1986f5af6bc120704c50a3747d84de422b3f0314", - "packages/remote/src/upload-client.ts#finalizeDirectUpload": "sha256:a947153dc39b154776b0d2f2ae8bbf184026ec832e41e4ad34280be277ed8724", + "packages/remote/src/upload-client.ts#finalizeDirectUpload": "sha256:1525f39f44cb1808136a31005a5dfa821cab114a2e5be70cd757130402c88ec8", "packages/remote/src/upload-client.ts#isStringRecord": "sha256:b6d6b571b90baf0976d9c347c4a45a4363a4df5ad184ea1087cb3b9febd4b624", "packages/remote/src/upload-client.ts#parseUploadPreflightResult": "sha256:7ce3f43b45c03df8b7f2690432beedc7a537c1bba540961716862f8a632d5623", - "packages/remote/src/upload-client.ts#requestUploadControl": "sha256:0d6d02e327a0fe791817525cbd9cb72ac4c66d704540f582e2d1aa872e0ed3ff", - "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:e43a2aa251d0881b77a1c29858b5c6007dc38c59971275a0e7472ac8b330dd81", + "packages/remote/src/upload-client.ts#requestUploadControl": "sha256:b1668523b92513cab6368f690c6c741ae8d618637b0df94afbbdd5c58dc67f53", + "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:298305e3c098bb2cd2d3fa47e1a15a74c5b07bee926fc33de955ac80c0f82915", "packages/remote/src/upload-client.ts#shouldRetryDirectUpload": "sha256:29059f076ff7f2b9540ad15408be48792b2d63a601ef2b9fb2d54f5576d49bbd", - "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:cb90256a3d3d85b7f7b2db8d354327c89d2c6477de8155fdf29066d4f8de00f9", - "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:97fb5ccba0a36326fe05e190d14068b68a3bbafa33f5f650f5e5bb0292b99908", - "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:0fe842e708b3ebeb0e252a0b1e650a85335b99c4f8d1a8a519a51dc48821f851", + "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:10edf334a3c9ab77e2819d9536e84975b2afe9fe2b6ee4f1a35b05da9da005a9", + "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:be8b1cff13ee98ef1f73c6dc74c1f921b0765c4480532c007763adf79782230a", + "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:acebf052734058c701b71762d1dae8b2294c6d48a1a641d4ffcaae8a7212ab53", "packages/remote/src/upload-stream.ts#MAX_UPLOAD_REDIRECTS": "sha256:12ff46dfe33a1dce95bdb79c90c17a3ba4f3919e7dc4b3a1b04590fff430f79f", "packages/remote/src/upload-stream.ts#UploadHandoff": "sha256:1e1a07668b0491ceffd178090b493e65dcee74c66cf7e434710861f2148db009", "packages/remote/src/upload-stream.ts#UploadStreamResponse": "sha256:724e284c2a6bd7b4b3a49b1d8c61c8923d6cc24777c3d76224a69d190e56adce", @@ -255,7 +255,7 @@ "packages/remote/src/script-version-publisher.ts#PublishOutcome": "sha256:a4ae6fc3298d3c560719591372edddbfa83ce749f4cf3f3e2ed1d8369313bd2d", "packages/remote/src/session-script-destination.ts#sendRemoteScriptOpen": "sha256:7cdb0d65cdc72e12c88a05a837f20097fa76034fd00e82fa4a10da78be4fb7f4", "packages/remote/src/session-script-destination.ts#RemoteEndpoint": "sha256:2fbcaa03bc0675fef8d19fd0a163d5d01a2162031745a41ff5c1db8a982cc2b6", - "packages/daemon/src/server/upload-http.ts#authorizeUpload": "sha256:69ee5039c7eadbe0f96cdf57bcd947b16cdc815671ba4c966ace93ad353cc740", + "packages/daemon/src/server/upload-http.ts#authorizeUpload": "sha256:33416e8fb30c31c175524c866aeb2dda811f56fa9a1f33bde4dd6414f581ab6f", "packages/remote/src/daemon-artifacts.ts#FetchRemoteArtifactParams": "sha256:dc5f36ded3e34bc45b4dc806b4e953767dfe705c122ec03f7e794b3053d78852", "packages/remote/src/daemon-artifacts.ts#fetchRemoteArtifact": "sha256:871f675d744dfa2bbf50237ac14b7f8957f973b126b774f4011da65573c8548f", "packages/remote/src/artifact-download.ts#RemoteArtifactRequest": "sha256:8e4ef9a2751e5ce2bd4ec8c9ade2f3616933386f1d284dcba38f96bfb4a005dc", @@ -274,7 +274,15 @@ "packages/kernel/src/contracts.ts#CoordinateUnit": "sha256:f4d20c9b4bbe0822e59d47f79678de7c75ffbcf8457c0bc2025f9da3d11faad8", "packages/kernel/src/contracts.ts#ResponseCoordinates": "sha256:9fb9e4defb36120b2d8d3ce658be2aeba9980ef541fe72c03744d7eefd172e1d", "packages/kernel/src/contracts.ts#readResponseCoordinates": "sha256:7ec3ce8ce888c5ab832628b49c31a6b714e0052312d2a27480ddad558acb88c2", - "packages/daemon/src/core/request-session-intake.ts#resolveRequestSessionAtIntake": "sha256:d620b6ee56a8c2f74d2c161016fa19974cbc833e3b87fa522411e35b381d9bc9" + "packages/daemon/src/core/request-session-intake.ts#resolveRequestSessionAtIntake": "sha256:d620b6ee56a8c2f74d2c161016fa19974cbc833e3b87fa522411e35b381d9bc9", + "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_RUN_HEADER": "sha256:66a6ad6d4388872490417e4210dc5eae1581a7531695ca002e9b2ecf3ebc6700", + "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_UPLOAD_SESSION_HEADER": "sha256:898a1a671ddb06ceeda91aa49ef7b845ac85467bf04c420ec0f9034e221c116f", + "packages/contracts/src/daemon-http.ts#buildDaemonHttpRunHeaders": "sha256:a635b2e3c2086e53f2e99c5b4d7bd143b9872dc95829029b3bace4b579b084f5", + "packages/daemon/src/resources/artifact-tracking.ts#ArtifactOwner": "sha256:8276ec62a036cf84d728d1a18ba6f854682f10e13636f03ab13c461ca4dd45ae", + "packages/daemon/src/server/upload-authority.ts#UploadAuthority": "sha256:0bdfd0ab989ac6b8a3a2e87a0a7487bb0694acd6c92cd0c1638bdc403dae86df", + "packages/daemon/src/server/upload-http.ts#AdmittedUploadAuthorizer": "sha256:33a728028556997c3507efcbe11ce43452429457e392d35c7a9b113b45bb7972", + "packages/remote/src/upload-client.ts#uploadControlHeaders": "sha256:bad38c678150330a5f1bd2b63c844298acb990da9870868e0d8d642984451b5b", + "packages/remote/src/upload-client.ts#uploadScopeHeaders": "sha256:b045546f8cc221d0f60e5c3358db0d1f26970134707ddc34e1d7c282b594d2ce" }, "compatibleChanges": [ { @@ -507,21 +515,6 @@ "digest": "sha256:d3135992646992fc7e5644c72731062fa44ee82187ad703f875f1aa358616b3f", "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). The client admits the diagnostics GET at send time, then receives and writes its body after release. The HTTP request and error framing are unchanged. The client deadline bounds admission and the request. A timed-out download closes and removes its local file before it reports failure. HTTP messages stay the same." }, - { - "declaration": "packages/remote/src/upload-client.ts#uploadDirectArtifact", - "digest": "sha256:97fb5ccba0a36326fe05e190d14068b68a3bbafa33f5f650f5e5bb0292b99908", - "rationale": "Clients name a held agent-device lease in an optional x-agent-device-lease-id request header on upload, artifact download and request diagnostics HTTP calls, so a gateway can route them. Released daemons ignore unknown request headers and the proxy forwards only its allowlist, so routes, bodies and responses parse as before; with no lease held the request is unchanged (ADR 0006). #4441 also stops passing a timeout message and hint that no caller could see, and requires the preparation aggregate's signal. The ticket PUT keeps its route, method, headers and body. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages." - }, - { - "declaration": "packages/remote/src/upload-client.ts#tryDirectUploadWithResume", - "digest": "sha256:cb90256a3d3d85b7f7b2db8d354327c89d2c6477de8155fdf29066d4f8de00f9", - "rationale": "#4441 ends the direct-upload sequence when a transfer phase's own budget expires, instead of re-preflighting for a fresh ticket or falling back, because a second attempt would be permission that budget already refused. Preflight, ticket PUT and finalize requests are unchanged in route, method, headers and body, so a protocol-2 daemon parses everything it parsed before; it just receives no further legs once the caller's aggregate has expired. Its signal is now required, because the preparation aggregate is always the one passed down, and it is read directly; no request changes. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. The client judges a retry ticket URL locally." - }, - { - "declaration": "packages/remote/src/upload-client.ts#uploadLegacyArtifact", - "digest": "sha256:0fe842e708b3ebeb0e252a0b1e650a85335b99c4f8d1a8a519a51dc48821f851", - "rationale": "#4441 drops the hint that named the removed 5-minute timeout, and an expired transfer phase is no longer treated as a transport break, so this route is not re-entered by a fallback after the client's own budget ended the attempt. The POST /upload request itself is unchanged: same method, headers, chunked body and response parsing. A protocol-2 daemon sees the identical request in every case that completes, and no further request in a stalled one. The unreachable timeout message and hint are no longer passed, and the aggregate signal is required. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages." - }, { "declaration": "packages/daemon-client/src/daemon-client-progress.ts#shouldReadDaemonProgressStream", "digest": "sha256:27ac0a5299324aab39fa2c4fe0e0d32b1eb1515df47c7f4aa75a75d66b8b5a3e", @@ -532,11 +525,6 @@ "digest": "sha256:25b138457410480048ee3899ce758cdd80bd7a4d11dc6e025f1365e7e8729116", "rationale": "The client names its request as DaemonWireRequest (packages/contracts/src/daemon-wire-request.ts, a narrowing of the listed kernel DaemonRequest) and its response as the kernel DaemonResponse, instead of the daemon package's DaemonRequest/DaemonResponse aliases, so the daemon package is no longer a client import. The declaration's serialized fields, method names and framing are unchanged; only the compile-time type names in its signature moved, so a peer on protocol 2 parses exactly what it did. #4171 records a request that names no session in daemon-only request state: a missing or blank session, or meta.sessionExplicit false with no named flag. A missing name becomes default, a blank one keeps its literal as released daemons did, and the literal default from a client stays. Lease params gain an optional sessionExplicit, which a released daemon ignores. A released client that names no session on a provider lease through the command method now gets a normal INVALID_ARGS error with reason REMOTE_SESSION_REQUIRED, and no peer misreads a payload." }, - { - "declaration": "packages/daemon/src/server/http-errors.ts#statusCodeForNormalizedError", - "digest": "sha256:39aa61eed8459527d7077e31e23be4fe0275021ed99c70ad692538091db91125", - "rationale": "The mapper now takes the normalized error (code plus details) instead of the code alone. A gone resource now answers 404 instead of 500: COMMAND_FAILED with details.reason RESOURCE_EXPIRED (an artifact, upload ticket, uploaded artifact or materialized path id the TTL registry no longer holds) maps to 404. The mapper also takes over the DEVICE_IN_USE human_control_active 423 rule, which statusCodeForDaemonError applied only to a failed response a /rpc handler returned. The rule now also reaches the REST routes and thrown /rpc failures, which answered 500: a PUT /admin/leases/ refused during a human-control hold, or a non-streamed /rpc call whose handler throws human_control_active, now answers 423. /admin/* is host-only on the loopback port and the proxy never forwards it, and the host already reads 423 for the same refusal on a returned /rpc failure. No released client branches on 404 versus 500 for these routes: downloadRemoteArtifactFromUrl treats any status >= 400 alike, the upload client fails any non-2xx and decides retries from a typed stream detail rather than the status, the /rpc client parses the JSON-RPC error envelope whatever the status and only special-cases 409, and the proxy passes the status through. The error code, message and JSON-RPC error data a peer parses are unchanged, so a protocol 2 peer reports the same failure it did before." - }, { "declaration": "packages/daemon/src/server/http-errors.ts#sendRestJsonError", "digest": "sha256:226399f1ecfc9024c44198568d39970c7b9fb7ef2f6ab58afe57ed8b0d8edd27", @@ -577,21 +565,6 @@ "digest": "sha256:eed6cb154db2b67ffe5f058ef0570fec247a5d2a43af2d42952dee0b08870a87", "rationale": "The /rpc body limit is now DAEMON_REQUEST_MAX_BYTES (64 MiB), the one request limit the socket transport, the proxy default, and client writers share, raised from 1 MiB. A larger limit refuses nothing a released client sends; a new client refuses a request over 64 MiB before sending it, and a released daemon still answers anything between 1 MiB and 64 MiB with its own -32700 refusal, as before." }, - { - "declaration": "packages/remote/src/upload-client.ts#requestUploadControl", - "digest": "sha256:0d6d02e327a0fe791817525cbd9cb72ac4c66d704540f582e2d1aa872e0ed3ff", - "rationale": "Lists the shared control Fetch/JSON owner so changes to method, headers, body or redirect forwarding remain wire-gated. Existing preflight/finalize routes and protocol-2 payloads are preserved; the original 30-second ceiling now retains typed local phase expiry and stops later legs. Non-success status handling is unchanged. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. The client starts the network watchdog at admission and explicitly hands off streamed headers before releasing it. Request headers, route, body framing and response parsing are unchanged." - }, - { - "declaration": "packages/remote/src/upload-client.ts#requestUploadPreflight", - "digest": "sha256:e43a2aa251d0881b77a1c29858b5c6007dc38c59971275a0e7472ac8b330dd81", - "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages. An inadmissible ticket URL is refused locally before sending and the legacy upload route remains available." - }, - { - "declaration": "packages/remote/src/upload-client.ts#finalizeDirectUpload", - "digest": "sha256:a947153dc39b154776b0d2f2ae8bbf184026ec832e41e4ad34280be277ed8724", - "rationale": "#4441 preserves the 30-second control-request ceiling but reports its typed phase timeout instead of retrying or falling back after expiry. The shared Fetch/JSON owner retains route, method, authentication, request body, redirect refusal and successful response parsing, so protocol-2 peers parse the same messages; only the local timeout outcome stops subsequent upload legs. The optional client-local handoff checks ownership when the send starts. Peers receive the same HTTP messages." - }, { "declaration": "packages/daemon/src/server/http/http-rpc-methods.ts#toInstallFromSourceDaemonRequest", "digest": "sha256:5110ccd2e370ec4f85b64a692cbeaf6ecab44b745e31d2c11e7559aab45d5238", @@ -627,31 +600,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", @@ -662,16 +610,6 @@ "digest": "sha256:f6b0b0ff2db474168b53af51994c81d32459b5010f643c965eba66f3ca89b737", "rationale": "#4441 adds an optional signal to the auth hook context, aborted when the authorized upload request expires or its client disconnects. The field is server-internal to the hook module the operator loads; no wire request or response field changes, so a released peer parses everything as before." }, - { - "declaration": "packages/daemon/src/server/upload-http.ts#AuxiliaryHttpAuthorizer", - "digest": "sha256:939b227d303574f90d59f01dd1bcb99eec7c5831b8e40dc5a6412be62c673e7e", - "rationale": "#4441 adds the upload ingress signal to the internal authorizer callback the upload routes call. It is not a wire field; routes, headers, bodies and status codes are unchanged, so a released peer interoperates as before. An auth-hook or tenant-trust refusal answered after the hook now goes through the request owner's commit gate, so a deadline that passed first answers with its own typed expiry; refusal status and body shapes are unchanged." - }, - { - "declaration": "packages/daemon/src/server/upload-http.ts#authorizeUpload", - "digest": "sha256:69ee5039c7eadbe0f96cdf57bcd947b16cdc815671ba4c966ace93ad353cc740", - "rationale": "#4441 moves the upload routes' existing authorize call into one helper: the same command 'upload', the same per-route positionals and the same token/auth-hook gate, now under the ingress signal. No request, response or status framing changes for a released peer. An auth-hook or tenant-trust refusal answered after the hook now goes through the request owner's commit gate, so a deadline that passed first answers with its own typed expiry; refusal status and body shapes are unchanged." - }, { "declaration": "packages/contracts/src/request-progress.ts#CommandProgressEvent", "digest": "sha256:5ed7aee1157326d6ed99232c4b14375640ca7aef829131eb6c98bb54f3b1aed0", @@ -737,11 +675,6 @@ "digest": "sha256:a5921503176f31ccab0cd1dc62aa315b7fab9b4dabedf420cf73922fc7c77c97", "rationale": "Adds the optional coordinates label, which a daemon writes only on a response to a request that sent coordinateUnit dp. A released client never sends that field, so it never receives the label, and a client that reads the response as a record ignores an unknown key." }, - { - "declaration": "packages/daemon/src/server/http/http-rpc-methods.ts#toReleaseMaterializedPathsDaemonRequest", - "digest": "sha256:d1b91e9abe8d1527c5dfbc855b0b31eee61766020a940acfe2310e7d3eb69e9d", - "rationale": "#4171 records a request that names no session in daemon-only request state: a missing or blank session, or meta.sessionExplicit false with no named flag. A missing name becomes default, a blank one keeps its literal as released daemons did, and the literal default from a client stays. Lease params gain an optional sessionExplicit, which a released daemon ignores. A released client that names no session on a provider lease through the command method now gets a normal INVALID_ARGS error with reason REMOTE_SESSION_REQUIRED, and no peer misreads a payload. The 0.22 lease-id fix also reads an optional tenantId (or tenant) param, so a release names the tenant that the paired install recorded as owner. A released daemon ignores it; a released client never sends it and keeps the previous tenant resolution. A caller that sent a tenant on install_from_source sends the same tenant on the paired release." - }, { "declaration": "packages/daemon/src/core/request-session-intake.ts#resolveRequestSessionAtIntake", "digest": "sha256:d620b6ee56a8c2f74d2c161016fa19974cbc833e3b87fa522411e35b381d9bc9", diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index ff55a2fb705..1e3bea7b3c4 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -240,8 +240,14 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'buildDaemonHttpAuthHeaders', 'DAEMON_HTTP_TENANT_HEADER', 'buildDaemonHttpTenantHeaders', + 'DAEMON_HTTP_RUN_HEADER', + 'DAEMON_HTTP_UPLOAD_SESSION_HEADER', + 'buildDaemonHttpRunHeaders', 'isTenantOwnedSessionName', ), + ...from('packages/daemon/src/resources/artifact-tracking.ts', 'ArtifactOwner'), + ...from('packages/daemon/src/server/upload-authority.ts', 'UploadAuthority'), + ...from(UPLOAD_HTTP, 'AdmittedUploadAuthorizer'), ...from( HTTP_AUTHORIZATION, 'HttpAuthHookContext', @@ -479,6 +485,8 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'isStringRecord', 'requestUploadPreflight', 'requestUploadControl', + 'uploadControlHeaders', + 'uploadScopeHeaders', 'uploadDirectArtifact', 'tryDirectUploadWithResume', 'shouldRetryDirectUpload', diff --git a/test/wire-compat/wire-mutations.test.ts b/test/wire-compat/wire-mutations.test.ts index 32d5022c6dd..7097ac9f60b 100644 --- a/test/wire-compat/wire-mutations.test.ts +++ b/test/wire-compat/wire-mutations.test.ts @@ -53,7 +53,7 @@ const MUTATIONS: readonly WireMutation[] = [ breakClass: 'upload control: Fetch drops authentication headers and the JSON body', file: 'packages/remote/src/upload-client.ts', name: 'requestUploadControl', - from: '...init,', + from: 'headers: uploadControlHeaders(options),', to: '', }, { diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 33c3d3f084f..49cf0c07124 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -523,6 +523,13 @@ When lease release cannot be confirmed, `error.details.releaseStatus` is `unknow These reasons can come from more than one command. +### RPC ingress + +| Reason | Meaning | +| --- | --- | +| `RPC_PREAUTH_CAPACITY_EXCEEDED` | The daemon has no free slot to receive and authenticate another RPC request. | +| `RPC_PREAUTH_DEADLINE_EXCEEDED` | The RPC body or authentication did not finish before its preauthorization deadline, so nothing was dispatched. | + ### Swift helper cache | Reason | Meaning | @@ -1077,6 +1084,13 @@ These reasons can come from more than one command. | --- | --- | | `provider-not-registered` | The daemon has no runtime for the requested provider. Inspect failedPlugins or install the named managed plugin. | +### Proxy RPC ingress + +| Reason | Meaning | +| --- | --- | +| `PROXY_RPC_BODY_CAPACITY_EXCEEDED` | Proxy RPC request bodies exceed the aggregate buffered-byte limit. | +| `PROXY_RPC_PREAUTH_DEADLINE_EXCEEDED` | Proxy RPC body or authentication did not finish before its deadline, so nothing was dispatched. | + ### Ref frames | Reason | Meaning | @@ -1111,6 +1125,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `REMOTE_HOST_INPUT_DENIED` | A remote request supplied a host path or other host input (`details.field`), which a remote daemon refuses. | +| `remote_web_browser_unconfined` | The managed browser cannot confine a remote tenant's network traffic. | ### Remote transfer @@ -1228,9 +1243,11 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | +| `UPLOAD_CAPACITY_EXCEEDED` | A new upload would exceed the active upload count or reserved byte budget. | | `UPLOAD_STATE_CORRUPT` | The staged upload holds more bytes than it declared, so it cannot resume; start a new upload. | | `UPLOAD_ROLLBACK_FAILED` | A failed chunk could not be rolled back, so the upload ticket was invalidated; start a new upload. | | `UPLOAD_FINALIZE_CLEANUP_FAILED` | Finalizing the upload failed, and removing its staged files failed too; `details.originalError` holds the first failure. | +| `RESUMABLE_UPLOAD_LEASE_MISMATCH` | A staged upload belongs to another lease of the same tenant. | | `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. | diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index bea0453832d..f9b7005c9fd 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -347,7 +347,7 @@ stop that daemon first. A denied request fails with `UNAUTHORIZED` and ## What the proxy exposes -The proxy serves only the daemon HTTP contract: `/health`, `/rpc`, `/rpc/checked` (which requires the `x-agent-device-rpc-protocol` header), `/upload` plus resumable `/upload/*` routes, and `/artifacts/*`, with the same routes also available under `/agent-device/*`. Health checks are unauthenticated; command, upload, and artifact routes require the bearer token. `GET /artifacts` lists the caller tenant's downloadable artifacts. An entry has `sessionName` when the daemon registered it outside a request reply, for example a recording kept when its leased session ended. `session list` shows a leased session only to a request that sends its lease ID. Without tenant isolation, the proxy lists only sessions whose lease ID you send. See [session visibility](/docs/sessions#session-visibility). +The proxy serves only the daemon HTTP contract: `/health`, `/rpc`, `/rpc/checked` (which requires the `x-agent-device-rpc-protocol` header), `/upload` plus resumable `/upload/*` routes, and `/artifacts/*`, with the same routes also available under `/agent-device/*`. Health checks are unauthenticated; command, upload, and artifact routes require the bearer token. `GET /artifacts` lists artifacts in the authenticated tenant's producing scope. Without a lease ID, it lists only unleased artifacts. To list or download leased output, send the original `x-agent-device-lease-id`, including after close; an empty list does not mean that another lease has no retained output. An entry has `sessionName` when the daemon registered it outside a request reply, for example a recording kept when its leased session ended. `session list` shows a leased session only to a request that sends its lease ID. Without tenant isolation, the proxy lists only sessions whose lease ID you send. See [session visibility](/docs/sessions#session-visibility). The proxy passes the daemon's HTTP status through. Most failed upload and artifact requests answer a JSON body `{ "ok": false, "error": "...", "code": "..." }`. When the daemon writes this body, it @@ -412,3 +412,13 @@ daemons omit it. ## Clean up Run `agent-device disconnect` when you finish the remote session. Stop the tunnel and the `agent-device proxy` process only when the host should stop accepting remote clients. Restarting the proxy generates a fresh token unless you supplied `--daemon-auth-token` explicitly. + +### Stage an app for a leased session + +Keep the same remote connection and `--session` when you upload and install an app. Staging names the consuming session with `x-agent-device-session`. For a leased session, it also sends the original lease ID and tenant; the run ID may be omitted, but any supplied run must match. A session name alone does not grant lease access. The daemon refuses missing or mismatched authority before accepting file bytes. A hookless daemon accepts a declared tenant only with its valid daemon credential and a matching active lease credential. An auth hook's attested tenant takes precedence over a client declaration. + +Ordinary unleased staging remains available. An upload belongs to its original tenant and lease. Replacing the session or changing scope after staging does not transfer the upload to the new owner; upload again for that owner. + +Upgrade the client and daemon together for RPC protocol 4. Finish active captures before upgrading. Retained artifacts keep their existing expiry windows. Upload capacity failures return `UPLOAD_CAPACITY_EXCEEDED` with the exhausted count or byte limit; retry after earlier uploads finish or expire. + +RPC receipt and authentication have a five-second deadline. A preauthorization timeout returns a retriable 408 with `dispatched: no`. A full preauthorization pool returns a retriable 503 before dispatch. Command execution uses its own deadline after admission. From 777a0b349e36f2ef27699934ba19cf72a62670a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 19:07:00 +0100 Subject: [PATCH 2/3] fix(daemon): validate backend aliases before resource dispatch --- .../http-server-rpc-validation.test.ts | 43 +++++++++++++++++++ .../src/server/http/http-rpc-methods.ts | 12 +++++- 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts b/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts index 5d161563b2d..cb2452acbc2 100644 --- a/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts +++ b/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts @@ -601,3 +601,46 @@ async function postCommandRpc( }); return { status: response.status, body: (await response.json()) as RpcErrorResponse }; } + +test.for(['install_from_source', 'release_materialized_paths'])( + '%s validates every backend alias before dispatch', + async (method, t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let dispatched = 0; + const server = await createDaemonHttpServer({ + cwd: process.cwd(), + env: {}, + handleRequest: async () => { + dispatched++; + return { ok: true }; + }, + }); + try { + const port = await listenOnLoopback(server); + for (const backend of ['not-a-backend', 42]) { + const response = await fetch(`http://127.0.0.1:${port}/rpc`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: method, + method: `agent_device.${method}`, + params: { + platform: 'android', + source: { kind: 'url', url: 'https://example.com/app.apk' }, + materializationId: 'retained-output', + backend, + leaseBackend: 'android-instance', + }, + }), + }); + const body = (await response.json()) as RpcErrorResponse; + assert.equal(response.status, 400); + assert.equal(body.error?.data?.code, 'INVALID_ARGS'); + } + assert.equal(dispatched, 0); + } finally { + await closeLoopbackServer(server); + } + }, +); diff --git a/packages/daemon/src/server/http/http-rpc-methods.ts b/packages/daemon/src/server/http/http-rpc-methods.ts index 9cbc00ca816..8e9aac6aca7 100644 --- a/packages/daemon/src/server/http/http-rpc-methods.ts +++ b/packages/daemon/src/server/http/http-rpc-methods.ts @@ -5,7 +5,7 @@ import type { IncomingHttpHeaders } from 'node:http'; import { readDevicePin } from '@agent-device/contracts/device'; import { AppError } from '@agent-device/kernel/errors'; import type { CommandRpcParams, DaemonInstallSource } from '@agent-device/kernel/contracts'; -import { commandRpcParamsSchema } from '@agent-device/kernel/contracts'; +import { commandRpcParamsSchema, readLeaseBackend } from '@agent-device/kernel/contracts'; import { readLeaseAllocateProviderFlags, type LeaseScope, @@ -226,6 +226,16 @@ function readLeaseLabelParams(params: Record) { const displaced: Record = {}; for (const [field, keys] of Object.entries(LEASE_LABEL_PARAMS)) { const values = keys.map((key) => params[key]).filter((value) => value !== undefined); + if ( + field === 'leaseBackend' && + values.some( + (value) => + typeof value !== 'string' || + (value.trim() !== '' && readLeaseBackend(value) === undefined), + ) + ) { + throw new AppError('INVALID_ARGS', 'Invalid lease backend.', { field: 'leaseBackend' }); + } const label = values.findIndex((value) => typeof value === 'string'); if (label >= 0) meta[field] = values[label] as string; displaced[field] = values.filter((_, index) => index !== label); From e6079b08814d8160648de5ab676d7f502e1697c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 19:12:30 +0100 Subject: [PATCH 3/3] fix(proxy): preserve admitted lease credentials and public errors --- .../daemon/src/server/http/http-server.ts | 2 -- packages/proxy/src/daemon-proxy.test.ts | 27 ++++++++++++++++++- packages/proxy/src/daemon-proxy.ts | 3 ++- packages/proxy/src/rpc-refusals.ts | 6 +++-- 4 files changed, 32 insertions(+), 6 deletions(-) diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index ce7243a1804..87107246a81 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -224,7 +224,6 @@ export async function createDaemonHttpServer(options: { tryHandleUploadHttpRoute({ req, res, - leaseRegistry: options.leaseRegistry, token: resolveToken({}, req.headers), origin: publicOrigin ?? ingressUrl.origin, leaseRegistry: options.leaseRegistry, @@ -239,7 +238,6 @@ export async function createDaemonHttpServer(options: { tryHandleDownloadableArtifactHttpRoute({ req, res, - leaseRegistry: options.leaseRegistry, retainArtifacts, hostEnv: environment, authorize: authorizeAuxiliary, diff --git a/packages/proxy/src/daemon-proxy.test.ts b/packages/proxy/src/daemon-proxy.test.ts index da033696077..cdec85e1c51 100644 --- a/packages/proxy/src/daemon-proxy.test.ts +++ b/packages/proxy/src/daemon-proxy.test.ts @@ -1,5 +1,8 @@ import { expect, test, vi } from 'vitest'; -import { buildDaemonHttpAuthHeaders } from '@agent-device/contracts/daemon-http'; +import { + DAEMON_HTTP_LEASE_HEADER, + buildDaemonHttpAuthHeaders, +} from '@agent-device/contracts/daemon-http'; import { AppError } from '@agent-device/kernel/errors'; import { createDaemonProxy, @@ -793,3 +796,25 @@ test('unsuccessful plain-text preflight responses pass through', async () => { expect(response.status).toBe(503); expect(await response.text()).toBe('unavailable'); }); + +test.each(['/upload', '/artifacts', '/artifacts/owned-output'])( + 'forwards the presenting lease credential through %s', + async (path) => { + const upstream = recordingUpstream(() => Response.json({ ok: true })); + const response = await proxyWith(upstream.fetch).handle( + new Request(`${PROXY_ORIGIN}${path}`, { + ...(path === '/upload' ? { method: 'POST', body: 'payload' } : {}), + headers: { + authorization: 'Bearer client-secret', + [DAEMON_HTTP_LEASE_HEADER]: 'producing-lease-credential', + }, + }), + ); + expect(response.status).toBe(200); + expect(upstream.requests).toHaveLength(1); + expect(upstream.requests[0]?.headers.get(DAEMON_HTTP_LEASE_HEADER)).toBe( + 'producing-lease-credential', + ); + expect(upstream.requests[0]?.headers.get('authorization')).toBe('Bearer daemon-secret'); + }, +); diff --git a/packages/proxy/src/daemon-proxy.ts b/packages/proxy/src/daemon-proxy.ts index e1d2bccfff1..3cdff16a70e 100644 --- a/packages/proxy/src/daemon-proxy.ts +++ b/packages/proxy/src/daemon-proxy.ts @@ -151,6 +151,7 @@ const FORWARDED_REQUEST_HEADERS = [ 'x-artifact-hash-algorithm', DAEMON_HTTP_TENANT_HEADER, DAEMON_HTTP_RUN_HEADER, + DAEMON_HTTP_LEASE_HEADER, DAEMON_HTTP_UPLOAD_SESSION_HEADER, ]; const FORWARDED_RESPONSE_HEADERS = [ @@ -260,7 +261,7 @@ async function handleRpcRoute( refusal === preauth.signal.reason && typeof id === 'string' && id.length > DAEMON_RPC_PREAUTH_MAX_ID_LENGTH; - return rpcErrorResponse(oversizedTimeoutId ? null : id, refusal); + return rpcErrorResponse(oversizedTimeoutId ? null : id, publicProxyError(refusal)); } finally { clearTimeout(deadline); ingress?.release(); diff --git a/packages/proxy/src/rpc-refusals.ts b/packages/proxy/src/rpc-refusals.ts index a9f48d27aad..4cd88cdf278 100644 --- a/packages/proxy/src/rpc-refusals.ts +++ b/packages/proxy/src/rpc-refusals.ts @@ -43,8 +43,10 @@ function rpcRefusalResponse(code: number, message: string): Response { } /** An `/rpc` failure in the JSON-RPC envelope the client reads its error code and message from. */ -export function rpcErrorResponse(rpcId: string | number | null, error: unknown): Response { - const normalized = normalizeError(error); +export function rpcErrorResponse( + rpcId: string | number | null, + normalized: ReturnType, +): Response { const invalidArgs = normalized.code === 'INVALID_ARGS'; const capacityExceeded = normalized.details?.reason === 'PROXY_RPC_BODY_CAPACITY_EXCEEDED'; const preauthDeadline =