diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 99aa29010b..9d150b47ac 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -13,6 +13,11 @@ export const DAEMON_HTTP_TENANT_HEADER = 'x-agent-device-tenant'; // 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'; diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 839ca9e7df..9fe0cc6e26 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -80,6 +80,7 @@ type ArtifactEntry = { type ArtifactTrackingState = { artifacts: Map; uploads: Map; + onStagedUploadCleanupDeferred?: (tempDir: string, error: unknown, retryDelayMs: number) => void; }; const ARTIFACT_TRACKING_SLOT = Symbol('artifactTracking'); @@ -94,13 +95,19 @@ const artifactTracking = (): ArtifactTrackingState => } for (const entry of state.uploads.values()) { clearTimeout(entry.timer); - removeBestEffort(entry.tempDir); + removeStagedUpload(entry.tempDir, entry.releaseReservation); } }, ); const pendingArtifacts = () => artifactTracking().artifacts; const pendingUploads = () => artifactTracking().uploads; +export function setStagedUploadCleanupDiagnostic( + emit: NonNullable, +): void { + artifactTracking().onStagedUploadCleanupDeferred = emit; +} + /** What a finished request registers for each artifact it hands back to the client. */ export type DownloadableArtifactRegistration = { artifactPath: string; @@ -532,6 +539,7 @@ function cleanupDirectoryArchive(entry: ArtifactEntry): void { // --- Upload artifact tracking --- const UPLOAD_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes +const STAGED_UPLOAD_RETRY_DELAY_MS = 30_000; const UPLOADED_ARTIFACT_RESOURCE: TenantOwnedResourceKind = { label: 'Uploaded artifact', @@ -543,6 +551,7 @@ type UploadEntry = { tempDir: string; tenantId?: string; leaseId?: string; + releaseReservation?: () => void; timer: ReturnType; }; @@ -551,6 +560,7 @@ export function trackUploadedArtifact(params: { tempDir: string; tenantId?: string; leaseId?: string; + releaseReservation?: () => void; }): string { const uploadId = crypto.randomUUID(); const timer = setTimeout(() => { @@ -562,6 +572,7 @@ export function trackUploadedArtifact(params: { tempDir: params.tempDir, tenantId: params.tenantId, leaseId: normalizeLeaseId(params.leaseId) ?? params.leaseId, + releaseReservation: params.releaseReservation, timer, }); return uploadId; @@ -592,5 +603,49 @@ 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); } diff --git a/packages/daemon/src/server/__tests__/resumable-upload.test.ts b/packages/daemon/src/server/__tests__/resumable-upload.test.ts index 3d65f866ad..e26fa4a338 100644 --- a/packages/daemon/src/server/__tests__/resumable-upload.test.ts +++ b/packages/daemon/src/server/__tests__/resumable-upload.test.ts @@ -172,6 +172,43 @@ test('expiry aborts an active receive and invalidates the ticket after rollback' } }); +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({ + 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(); + } +}); + test('an ignored out-of-order chunk does not extend upload expiry', async () => { vi.useFakeTimers(); try { @@ -610,6 +647,7 @@ test('upload preflights reserve tenant capacity and preserve idempotent tickets' }; 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() }), @@ -622,6 +660,52 @@ test('upload preflights reserve tenant capacity and preserve idempotent tickets' } }); +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)), + tenantId: 'expiry-capacity-tenant', + 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(); + } +}); + function beginUpload(bytes: Buffer): ReturnType { return beginResumableUpload(uploadOptions(bytes)); } 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 0000000000..252f3c666d --- /dev/null +++ b/packages/daemon/src/server/__tests__/upload-http-capacity.test.ts @@ -0,0 +1,113 @@ +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(); + } + } +}); diff --git a/packages/daemon/src/server/artifact-archive.ts b/packages/daemon/src/server/artifact-archive.ts index 00eb3d6e9f..b3e43c4a6d 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 2e34548d58..4f45df0eb5 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/daemon-runtime.ts b/packages/daemon/src/server/http/daemon-runtime.ts index db5c41a180..65b36272ef 100644 --- a/packages/daemon/src/server/http/daemon-runtime.ts +++ b/packages/daemon/src/server/http/daemon-runtime.ts @@ -21,7 +21,10 @@ import { resolveDaemonServerMode, type DaemonRuntimeOwnership, } from '@agent-device/daemon-contracts/daemon-resolution'; -import { trackDownloadableArtifact } from '../../resources/artifact-tracking.ts'; +import { + setStagedUploadCleanupDiagnostic, + trackDownloadableArtifact, +} from '../../resources/artifact-tracking.ts'; import { installProviderDeviceAdmission } from '../../core/provider-device-admission.ts'; import { loadDaemonPolicy, @@ -216,6 +219,13 @@ async function startDaemonRuntimeOnHost( const { baseDir, infoPath, logPath, sessionsDir } = daemonPaths; // A daemon from another build, or embedded, reaches the root without the launcher's admission. admitDaemonStateRoot({ paths: daemonPaths, mode: 'establish' }); + setStagedUploadCleanupDiagnostic((tempDir, error, retryDelayMs) => { + void emitDaemonDiagnostic(logPath, 'staged_upload_cleanup_deferred', { + tempDir, + error: normalizeError(error), + retryDelayMs, + }).catch(() => {}); + }); const daemonServerMode = resolveDaemonServerMode(env.AGENT_DEVICE_DAEMON_SERVER_MODE); const retainArtifacts = isEnvTruthy(env.AGENT_DEVICE_RETAIN_ARTIFACTS); // ADR 0029: a policy that cannot be read or validated stops startup; the daemon never runs 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 e2219518ab..4f785637fb 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 @@ -115,6 +115,52 @@ test('HTTP install rejection leaves an uploaded artifact available', async (t) = } }); +test('HTTP upload and install dispatch resolve the same declared tenant without an auth hook', async (t) => { + if (await skipWhenLoopbackUnavailable(t, 'HTTP upload and install')) return; + const host = createLiveTestHostEnvironment(); + const env = { ...host.env }; + delete env.AGENT_DEVICE_HTTP_AUTH_HOOK; + let uploadedId: string | undefined; + const server = await createDaemonHttpServer({ + token: 'test-token', + ...host, + env, + handleRequest: async (req) => { + assert.equal(req.command, 'install'); + assert.equal(req.meta?.tenantId, 'tenant-a'); + assert.equal(req.meta?.uploadedArtifactId, uploadedId); + const artifactPath = prepareUploadedArtifact(uploadedId!, req.meta?.tenantId); + assert.equal(fs.readFileSync(artifactPath, 'utf8'), 'uploaded-apk'); + return { ok: true, data: { installed: true } }; + }, + }); + try { + const port = await listenOnLoopback(server); + const upload = 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: 'uploaded-apk', + }); + assert.equal(upload.status, 200); + uploadedId = ((await upload.json()) as { uploadId: string }).uploadId; + const install = await callRpc(port, 'agent_device.command', { + command: 'install', + positionals: ['app.apk'], + meta: { tenantId: 'tenant-a', uploadedArtifactId: uploadedId }, + }); + assert.equal(install.status, 200); + assert.equal(((await install.json()) as { result?: { ok: boolean } }).result?.ok, true); + } finally { + if (uploadedId) cleanupUploadedArtifact(uploadedId); + await closeLoopbackServer(server); + } +}); + test('HTTP leased resumable upload remains readable by install dispatch', async (t) => { if (await skipWhenLoopbackUnavailable(t, 'leased resumable upload')) return; const host = createLiveTestHostEnvironment(); diff --git a/packages/daemon/src/server/resumable-upload.ts b/packages/daemon/src/server/resumable-upload.ts index da12e0d1f1..55aa292d5c 100644 --- a/packages/daemon/src/server/resumable-upload.ts +++ b/packages/daemon/src/server/resumable-upload.ts @@ -1,3 +1,4 @@ +import { 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'; @@ -19,22 +20,17 @@ import { import { computeUploadHash, receiveResumableTransfer } from './resumable-upload-transfer.ts'; import { resolveIngressFailure, throwIfIngressAborted } from './upload-ingress.ts'; import { normalizeLeaseId } from '@agent-device/contracts/lease-scope'; +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 new upload would exceed the active upload count or reserved byte budget. - capacityExceeded: { reason: 'UPLOAD_CAPACITY_EXCEEDED' }, // A staged upload belongs to another lease of the same tenant. leaseMismatch: { reason: 'RESUMABLE_UPLOAD_LEASE_MISMATCH' }, } as const satisfies ReasonTable<'uploads'>; const RESUMABLE_UPLOAD_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000; -const MAX_ACTIVE_UPLOADS_PER_TENANT = 32; -const MAX_ACTIVE_UPLOADS_TOTAL = 256; -const MAX_RESERVED_UPLOAD_BYTES_PER_TENANT = 4 * 1024 * 1024 * 1024; -const MAX_RESERVED_UPLOAD_BYTES_TOTAL = 16 * 1024 * 1024 * 1024; const RESUMABLE_UPLOAD_RESOURCE: TenantOwnedResourceKind = { label: 'Upload', expiredHint: `Resumable uploads expire ${RESUMABLE_UPLOAD_CLEANUP_TIMEOUT_MS / 60_000} minutes after the last received chunk. Start the upload again from the beginning.`, @@ -52,11 +48,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); } }, ); @@ -95,7 +87,7 @@ type ResumableUploadEntry = { /** Aborts the active receive with the ticket's typed expiry. */ activeReceive?: AbortController; closed: boolean; - finalized: boolean; + reservation: UploadCapacityReservation; }; type ResumableUploadTicket = { @@ -118,47 +110,20 @@ export function beginResumableUpload( const key = buildResumableUploadKey(options); const existingId = RESUMABLE_UPLOADS_BY_KEY().get(key); const existing = existingId ? RESUMABLE_UPLOADS_BY_ID().get(existingId) : undefined; - if (!existing) assertResumableUploadCapacity(options); const entry = existing ?? createResumableUploadEntry(options, key); const ticket = describeResumableUploadTicket(entry, options); if (!publish) return ticket; 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; } return ticket; } -function assertResumableUploadCapacity(options: BeginResumableUploadOptions): void { - let tenantCount = 0; - let tenantBytes = 0; - let totalBytes = 0; - for (const entry of RESUMABLE_UPLOADS_BY_ID().values()) { - totalBytes += entry.sizeBytes; - if (entry.tenantId === options.tenantId) { - tenantCount += 1; - tenantBytes += entry.sizeBytes; - } - } - if ( - tenantCount < MAX_ACTIVE_UPLOADS_PER_TENANT && - RESUMABLE_UPLOADS_BY_ID().size < MAX_ACTIVE_UPLOADS_TOTAL && - tenantBytes + options.sizeBytes <= MAX_RESERVED_UPLOAD_BYTES_PER_TENANT && - totalBytes + options.sizeBytes <= MAX_RESERVED_UPLOAD_BYTES_TOTAL - ) { - return; - } - throw new AppError('COMMAND_FAILED', 'Too many active resumable uploads', { - reason: UPLOAD_FINALIZE_REASONS.capacityExceeded.reason, - retriable: true, - }); -} - function describeResumableUploadTicket( entry: ResumableUploadEntry, options: BeginResumableUploadOptions, @@ -241,7 +206,7 @@ export async function finalizeResumableUpload( tenantId?: string, ingress?: FinalizeUploadIngressLink, leaseId?: string, -): Promise<{ artifactPath: string; tempDir: string }> { +): Promise<{ artifactPath: string; tempDir: string; releaseReservation: () => void }> { const entry = requireResumableUpload(uploadId, tenantId, leaseId); const signal = ingress?.signal; // The owner's typed expiry, including a recorded deadline whose timer has not run yet. @@ -270,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(); @@ -285,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. @@ -302,30 +272,38 @@ 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, - leaseId: canonicalLeaseId(options.leaseId), - 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.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, + tenantId: options.tenantId, + leaseId: canonicalLeaseId(options.leaseId), + 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 { @@ -350,15 +328,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(() => {}); } @@ -410,29 +387,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( @@ -448,15 +426,17 @@ 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( diff --git a/packages/daemon/src/server/upload-capacity.ts b/packages/daemon/src/server/upload-capacity.ts new file mode 100644 index 0000000000..aaa9793e68 --- /dev/null +++ b/packages/daemon/src/server/upload-capacity.ts @@ -0,0 +1,69 @@ +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 }; + const setBytes = (nextBytes: number) => { + 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; + } + } + if ( + tenantCount > MAX_UPLOADS_PER_TENANT || + totalCount > MAX_UPLOADS_TOTAL || + occupiedTenantBytes > MAX_BYTES_PER_TENANT || + occupiedTotalBytes > MAX_BYTES_TOTAL + ) { + throw new AppError('COMMAND_FAILED', 'Upload capacity exceeded', { + reason: UPLOAD_CAPACITY_REASONS.exceeded.reason, + retriable: true, + }); + } + reservation.bytes = nextBytes; + }; + setBytes(bytes); + active.add(reservation); + return { + release: () => { + 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 eb5116a10c..de6973031d 100644 --- a/packages/daemon/src/server/upload-http.ts +++ b/packages/daemon/src/server/upload-http.ts @@ -1,8 +1,7 @@ -import fs from 'node:fs'; import http from 'node:http'; import { AppError, normalizeError, type ReasonTable } from '@agent-device/kernel/errors'; import type { DaemonRequest } from '../core/daemon-request.ts'; -import { trackUploadedArtifact } from '../resources/artifact-tracking.ts'; +import { removeStagedUpload, trackUploadedArtifact } from '../resources/artifact-tracking.ts'; import { type BeginResumableUploadOptions, beginResumableUpload, @@ -13,6 +12,7 @@ import { receiveUpload } from './upload.ts'; import { sendRestJsonError } from './http-errors.ts'; import { beginUploadTransferIngress, type UploadTransferIngress } from './upload-ingress.ts'; import { readNodeHttpRequestBody } from '@agent-device/host-kit/transport'; +import { reserveUploadCapacity } from './upload-capacity.ts'; import { DAEMON_HTTP_LEASE_HEADER, DAEMON_HTTP_RUN_HEADER, @@ -194,17 +194,13 @@ async function handleUpload( leaseRegistry?: LeaseRegistry, ): Promise { await runUploadRoute(req, res, authorize, leaseRegistry, [], async (auth, ingress) => { - sendUploadedArtifactResponse( - res, - await receiveUpload(req, { - signal: ingress.signal, - onBodyBytes: (bytes) => ingress.onAcceptedBodyBytes(bytes), - onBodyComplete: () => ingress.bodyComplete(), - }), - auth.tenantId, - ingress.commit, - auth.leaseId, - ); + const upload = await receiveUpload(req, { + signal: ingress.signal, + onBodyBytes: ingress.onAcceptedBodyBytes, + onBodyComplete: ingress.bodyComplete, + reserveCapacity: (bytes) => reserveUploadCapacity(auth.tenantId, bytes), + }); + sendUploadedArtifactResponse(res, upload, auth.tenantId, ingress.commit, auth.leaseId); }); } @@ -324,7 +320,7 @@ function sendJson(res: http.ServerResponse, body: Record): void */ function sendUploadedArtifactResponse( res: http.ServerResponse, - result: { artifactPath: string; tempDir: string }, + result: { artifactPath: string; tempDir: string; releaseReservation?: () => void }, tenantId: string | undefined, commit: (work: () => T) => T, leaseId?: string, @@ -337,12 +333,15 @@ function sendUploadedArtifactResponse( tempDir: result.tempDir, tenantId, leaseId, + 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 ab1532ee55..03a0aaa6a6 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/host-kit/src/archive.ts b/packages/host-kit/src/archive.ts index 3300b1f413..b938aac530 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 21cbfd75d4..9ef997633f 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/remote/src/__tests__/upload-client-capacity.test.ts b/packages/remote/src/__tests__/upload-client-capacity.test.ts new file mode 100644 index 0000000000..6e07294554 --- /dev/null +++ b/packages/remote/src/__tests__/upload-client-capacity.test.ts @@ -0,0 +1,198 @@ +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 } 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); + } +}); diff --git a/packages/remote/src/__tests__/upload-client.test.ts b/packages/remote/src/__tests__/upload-client.test.ts index bc3d805bcd..657d9809af 100644 --- a/packages/remote/src/__tests__/upload-client.test.ts +++ b/packages/remote/src/__tests__/upload-client.test.ts @@ -91,6 +91,7 @@ test('uploadArtifact uploads with hash headers after preflight cache miss', asyn return; } if (req.method === 'POST' && req.url === '/upload') { + assert.equal(req.headers['x-agent-device-tenant'], 'tenant-a'); assert.equal(req.headers['x-artifact-type'], 'file'); assert.equal(req.headers['x-artifact-filename'], 'app.apk'); assert.equal(req.headers['x-artifact-hash'], expectedHash); @@ -109,6 +110,7 @@ test('uploadArtifact uploads with hash headers after preflight cache miss', asyn localPath: artifactPath, baseUrl: server.baseUrl, token: TEST_TOKEN, + tenantId: 'tenant-a', }); assert.equal(uploadId, 'upload-miss'); assert.deepEqual(requests, ['POST /upload/preflight', 'POST /upload']); @@ -392,6 +394,7 @@ test('uploadArtifact uses direct upload ticket and finalize flow', async () => { const server = await startServer(async (req, res) => { requests.push(`${req.method} ${req.url}`); if (req.method === 'POST' && req.url === '/upload/preflight') { + assert.equal(req.headers['x-agent-device-tenant'], 'tenant-a'); const body = JSON.parse((await readRequestBody(req)).toString('utf8')) as { uploadAttemptId: string; sha256: string; @@ -420,6 +423,7 @@ test('uploadArtifact uses direct upload ticket and finalize flow', async () => { return; } if (req.method === 'PUT' && req.url === '/signed-upload') { + assert.equal(req.headers['x-agent-device-tenant'], 'tenant-a'); assert.equal(req.headers.authorization, undefined); assert.equal(req.headers['x-agent-device-token'], undefined); assert.equal(req.headers['x-signed-ticket'], 'ticket-header'); @@ -429,6 +433,7 @@ test('uploadArtifact uses direct upload ticket and finalize flow', async () => { return; } if (req.method === 'POST' && req.url === '/upload/finalize') { + assert.equal(req.headers['x-agent-device-tenant'], 'tenant-a'); assert.equal(req.headers.authorization, `Bearer ${TEST_TOKEN}`); const body = JSON.parse((await readRequestBody(req)).toString('utf8')) as { uploadId: string; @@ -446,6 +451,7 @@ test('uploadArtifact uses direct upload ticket and finalize flow', async () => { localPath: artifactPath, baseUrl: server.baseUrl, token: TEST_TOKEN, + tenantId: 'tenant-a', onProgress: (event) => progressEvents.push(event), }); assert.equal(uploadId, 'upload-finalized'); diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 9c48df82e9..6dec3363c0 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -197,6 +197,17 @@ async function prepareRemoteInstallPackage( const localPath = resolveLocalInstallPath(rawPath, req.meta?.cwd, host); if (!localPath) return undefined; + return await uploadLocalInstallArtifact(req, info, localPath, onProgress, signal, host); +} + +async function uploadLocalInstallArtifact( + req: Omit, + info: DaemonArtifactEndpoint, + localPath: string, + onProgress: UploadProgressSink | undefined, + signal: AbortSignal, + host: HostEnvironment, +): Promise { return await uploadArtifact({ env: host.env, localPath, @@ -302,16 +313,14 @@ async function prepareRemoteInstallSource( }; } - const uploadedArtifactId = await uploadArtifact({ - env: host.env, + const uploadedArtifactId = await uploadLocalInstallArtifact( + req, + info, localPath, - baseUrl: info.baseUrl!, - token: info.token, - platform: req.flags?.platform, - ...leaseScopeFromRequest(req), onProgress, signal, - }); + host, + ); return { installSource: { ...source, diff --git a/packages/remote/src/upload-client.ts b/packages/remote/src/upload-client.ts index 6eae684849..24a484c4c7 100644 --- a/packages/remote/src/upload-client.ts +++ b/packages/remote/src/upload-client.ts @@ -6,6 +6,7 @@ import { buildDaemonHttpLeaseHeaders, buildDaemonHttpRunHeaders, buildDaemonHttpTenantHeaders, + UPLOAD_CAPACITY_REASONS, } from '@agent-device/contracts/daemon-http'; import { prepareUploadArtifact, type PreparedUploadArtifact } from './upload-client-artifact.ts'; import { @@ -189,6 +190,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); } @@ -238,6 +244,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; } } @@ -268,7 +279,9 @@ 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), uploadScopeHeaders(options)); @@ -288,7 +301,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}`); } @@ -299,7 +318,7 @@ async function uploadLegacyArtifact(options: { } } -function uploadScopeHeaders(scope: Pick) { +function uploadScopeHeaders(scope: { tenantId?: string; leaseId?: string; runId?: string }) { return { ...buildDaemonHttpTenantHeaders(scope.tenantId), ...buildDaemonHttpLeaseHeaders(scope.leaseId), @@ -307,9 +326,12 @@ function uploadScopeHeaders(scope: Pick, -) { +function uploadControlHeaders(scope: { + token: string; + tenantId?: string; + leaseId?: string; + runId?: string; +}) { return { 'content-type': 'application/json', ...buildDaemonHttpAuthHeaders(scope.token), @@ -328,25 +350,19 @@ async function requestUploadPreflight(options: { env: HostEnvironment['env']; signal?: AbortSignal; }): Promise { - const preflightUrl = new URL('upload/preflight', options.normalizedBase); - const headers = uploadControlHeaders(options); - 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, ).catch((error: unknown) => { // A failed preflight is ordinary here — the caller falls back to the legacy upload. A canceled // one is not: there is nothing to fall back to when the lease that paid for this upload is gone. @@ -354,6 +370,7 @@ async function requestUploadPreflight(options: { return undefined; }); + throwIfUploadCapacityRefused(result); if (!result?.response.ok) { return undefined; } @@ -369,22 +386,32 @@ async function requestUploadPreflight(options: { async function requestUploadControl( url: URL, - init: { headers: Record; body: string }, + options: { + token: string; + leaseId?: string; + runId?: string; + tenantId?: string; + signal?: AbortSignal; + }, + requestBody: string, phase: 'preflight' | 'finalize', - callerSignal?: AbortSignal, ): Promise<{ response: Response; body: unknown }> { - const watchdog = createTransferPhaseWatchdog(callerSignal); + const watchdog = createTransferPhaseWatchdog(options.signal); watchdog.signal.throwIfAborted(); watchdog.arm(phase, UPLOAD_CONTROL_PLANE_TIMEOUT_MS); try { // Redirects could forward the daemon token, so these control requests never follow them. const response = await fetch(url, { - ...init, + headers: uploadControlHeaders(options), + body: requestBody, method: 'POST', redirect: 'error', signal: watchdog.signal, }); - const body: unknown = response.ok ? await response.json().catch(() => undefined) : undefined; + const body: unknown = + response.ok || response.status === 503 + ? await response.json().catch(() => undefined) + : undefined; watchdog.signal.throwIfAborted(); return { response, body }; } catch (error) { @@ -395,6 +422,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; @@ -487,17 +529,11 @@ async function finalizeDirectUpload(options: { uploadId: string; signal?: AbortSignal; }): Promise { - const finalizeUrl = new URL('upload/finalize', options.normalizedBase); - const headers = uploadControlHeaders(options); - 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, ).catch((error: unknown) => { // As with preflight: a canceled finalize is not a transport failure to report, it is the caller // saying this upload is no longer worth finishing. @@ -505,6 +541,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/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 97279ea249..b7f96c0dcc 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -142,7 +142,7 @@ "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:d187993ad77280476bd3cbec2269a995f35e5f4284c5c1bec384ecf1012fedb2", - "packages/daemon/src/server/upload-http.ts#handleUpload": "sha256:0f9e4ee9fad26c471393584da829fabdb0a88a697202379b9318fc3fa3eaeb71", + "packages/daemon/src/server/upload-http.ts#handleUpload": "sha256:f46ddb324f86411809fb4a277136880288bf4be95443ace63d2db7c529b6e6c4", "packages/daemon/src/server/upload-http.ts#handleUploadFinalize": "sha256:8f801ed381173e9ddd4cf16b6d889feb3a11aef565374e0ee2fdb0dc300092a4", "packages/daemon/src/server/upload-http.ts#handleUploadPreflight": "sha256:f5203a0767ac6f0387c7138c7d61bf98fb1c3f1cf9994cb950ce7f6380e480a2", "packages/daemon/src/server/upload-http.ts#readUploadFinalizeBody": "sha256:076298afa73d7e498a964b6c48d823de1cc8b15e9e971d0a22b7e6c3fd98d685", @@ -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:02d2e73fac5cf94cf5d7a019f2e507a550b82d2378bb71195fcb222d459b8a81", + "packages/daemon/src/server/upload-http.ts#sendUploadedArtifactResponse": "sha256:c836b1460b04a1de9a7462d5f87134a501461c5e985904609ba9d954467292b6", "packages/remote/src/artifact-download.ts#RemoteArtifactDownload": "sha256:d3eeaf9a072123004d868a0261067456793a7121836d6f6b354fcd65aa0826bd", "packages/remote/src/artifact-download.ts#downloadRemoteArtifactFromUrl": "sha256:4772ec65900be31f0ac6fb889967a9f35a4a565f6bb87e72458e3ab6e54cc941", "packages/remote/src/daemon-artifacts.ts#DaemonArtifactEndpoint": "sha256:45226717ac52c0af2a62f74e91549582d95f4a4abc49be87989e026291a88c82", @@ -174,15 +174,17 @@ "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:dc86827543249852132213585db86b47fab482ecf5df01eaad93110d234e8625", + "packages/remote/src/upload-client.ts#finalizeDirectUpload": "sha256:cfe3065a964e92080d4a5145a988bbe29432a629e28db6b432f3a4311395eacf", "packages/remote/src/upload-client.ts#isStringRecord": "sha256:b6d6b571b90baf0976d9c347c4a45a4363a4df5ad184ea1087cb3b9febd4b624", "packages/remote/src/upload-client.ts#parseUploadPreflightResult": "sha256:7ce3f43b45c03df8b7f2690432beedc7a537c1bba540961716862f8a632d5623", - "packages/remote/src/upload-client.ts#requestUploadControl": "sha256:5689da0c0cd18d0293e5bb05ddc0d8a07d1bca9ab1d94f8ca185b03bc5b8d758", - "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:73831aa50b752300836e1e5d6c0bd3fa0e31d5535f45f0b708973b4d62bb81d0", + "packages/remote/src/upload-client.ts#requestUploadControl": "sha256:313687862d1a9f7237f4b56b353af5b9dcdbb5419a7bfdb298895d4fc0ed046c", + "packages/remote/src/upload-client.ts#requestUploadPreflight": "sha256:88d0b2fe8f3bc0f1b2c9ce9789df31ae5d993ee0731b19a6d4fb2d16c04c60f1", "packages/remote/src/upload-client.ts#shouldRetryDirectUpload": "sha256:29059f076ff7f2b9540ad15408be48792b2d63a601ef2b9fb2d54f5576d49bbd", - "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:1922f3de72d9b24f5d02df0a6d4d911e40086763bace3fe0e22facf8b9f7b47b", + "packages/remote/src/upload-client.ts#tryDirectUploadWithResume": "sha256:2a50ec3e81263f945805ce310a889e2c5998a3a6e398f20afc5bfa3b8363764d", + "packages/remote/src/upload-client.ts#uploadControlHeaders": "sha256:7fcac0a98caa0c96899c5aaae087c158a3e54e2afeb24e6672cc9f6916668177", + "packages/remote/src/upload-client.ts#uploadScopeHeaders": "sha256:0d4da90164b13ae8c3ae75072203da9c26fb19c4c5563cf61533c15eb37e5b0c", "packages/remote/src/upload-client.ts#uploadDirectArtifact": "sha256:da21e40e125d8f8a45f3c1ba184e7e034e50d5f4f997cd0dc0f5ce21db36771b", - "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:9c4e373fc0eb2684a78faf1d8f3321a149e944d94c2be2fad0a66c7932d31a18", + "packages/remote/src/upload-client.ts#uploadLegacyArtifact": "sha256:24ea193aa944f27b4705548aef9abf1e225d6523ca767175fe21c31215ea5f99", "packages/remote/src/upload-stream.ts#MAX_UPLOAD_REDIRECTS": "sha256:12ff46dfe33a1dce95bdb79c90c17a3ba4f3919e7dc4b3a1b04590fff430f79f", "packages/remote/src/upload-stream.ts#UploadStreamResponse": "sha256:724e284c2a6bd7b4b3a49b1d8c61c8923d6cc24777c3d76224a69d190e56adce", "packages/remote/src/upload-stream.ts#buildUploadRequestHeaders": "sha256:827576b13a9f3e6cea445119a6a29b2ac5eaa23b66436cf810b2d09765c82a4c", @@ -528,11 +530,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:5689da0c0cd18d0293e5bb05ddc0d8a07d1bca9ab1d94f8ca185b03bc5b8d758", - "rationale": "Lists the shared control Fetch/JSON owner so changes to method, headers, body or redirect forwarding remain wire-gated. Existing preflight/finalize routes and protocol-2 payloads are preserved; the original 30-second ceiling now retains typed local phase expiry and stops later legs. Non-success status handling is unchanged." - }, { "declaration": "packages/contracts/src/lease-scope.ts#buildDaemonRpcRequest", "digest": "sha256:b3d03bb08f8f332b04dea6d2ea30abca2faf83a10f11cb874df2344b3f54c2b6", diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index 5f32b9e16b..b821fb1a3d 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -471,6 +471,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 738cbe442f..cd3dab1dd4 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),\n body: requestBody,\n', to: '', }, { diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index c21bf4be17..297cc732af 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -1074,10 +1074,10 @@ 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. | -| `UPLOAD_CAPACITY_EXCEEDED` | A new upload would exceed the active upload count or reserved byte budget. | | `RESUMABLE_UPLOAD_LEASE_MISMATCH` | A staged upload belongs to another lease of the same tenant. | | `UPLOAD_LEASE_ADMISSION_REQUIRED` | A leased upload needs a tenant and lease registry. | | `transfer_ingress_deadline_exceeded` | The upload request exceeded its aggregate deadline (`details.timeoutMs`), which also covers processing after the body arrived. | diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 2be6432623..70dd11af60 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -18,7 +18,7 @@ CLI commands run through a per-user background daemon: - The daemon binds to `127.0.0.1` only, on ephemeral ports, for both its socket and HTTP transports. It is not reachable from the network unless you put your own proxy in front of it. - Command (RPC), upload, artifact-download, and `/admin/human-control/*` requests must present a token that the daemon generates fresh on each start (24 random bytes). The only unauthenticated endpoint is `GET /health`, which returns only liveness, package and protocol version, instance ID, and host CPU architecture; like the rest of the server, it is reachable only over loopback. The token is stored in `daemon.json` inside the daemon state directory (`~/.agent-device` for packaged installs; source checkouts use a worktree-scoped directory under `~/.agent-device/dev/`) with `0600` permissions. Anyone who can read that file already has your user account. - A client reuses a running daemon only when the daemon runs the same version and the same code. Two installs of the same published version share one daemon. An older client refuses to replace a reachable daemon on a newer version, so it does not disrupt that daemon's sessions; upgrade the client instead. Any other mismatch, such as a source checkout against an install, restarts the daemon instead of running code the client cannot identify. The code check compares file sizes and timestamps, not contents, so it does not detect an install whose files were hand-replaced under the same version. -- Artifact uploads are size-capped, filenames are sanitized, and archive extraction rejects path-traversal entries. Resumable uploads allow at most 32 active tickets and 4 GiB of reserved bytes per tenant, with daemon-wide limits of 256 tickets and 16 GiB. A ticket expires after five minutes without a received chunk. Artifact downloads resolve through server-side IDs, never client-supplied paths. +- Artifact uploads are size-capped, filenames are sanitized, and archive extraction rejects path-traversal entries. Legacy uploads, resumable uploads, and staged uploads waiting for install share a limit of 32 uploads and 6 GiB per tenant, with daemon-wide limits of 256 uploads and 16 GiB. A resumable ticket expires after five minutes without a received chunk. Artifact downloads resolve through server-side IDs, never client-supplied paths. - `install-from-source` protects the daemon host while it downloads and extracts the artifact; it does not vouch for the app inside. An app installed and launched on an iOS simulator runs as a process on the host Mac, so treat permission to send install requests as permission to run code on that Mac. For remote or cloud deployments, you can add a custom auth hook for remotely consumable HTTP routes: set `AGENT_DEVICE_HTTP_AUTH_HOOK` to a module path that the daemon imports, and `AGENT_DEVICE_HTTP_AUTH_EXPORT` to select the export. Relative hook paths resolve from the daemon host's working directory. The host-local `/admin/human-control/*` route uses the daemon token instead. The hook runs with the daemon's full privileges, so treat it as trusted code: point it only at a read-only path you control, never at a location that less-trusted users or processes can write to. Whoever controls the daemon's environment controls the hook. On upload and RPC routes, the hook context carries a `signal` that aborts when the client disconnects. An upload deadline also aborts its signal. The daemon stops waiting for the hook at that point, so a hook that calls a slow identity service can use the signal to stop that call.