diff --git a/packages/daemon/src/server/__tests__/resumable-upload.test.ts b/packages/daemon/src/server/__tests__/resumable-upload.test.ts index 36c6e177c0..b6e8c44e8b 100644 --- a/packages/daemon/src/server/__tests__/resumable-upload.test.ts +++ b/packages/daemon/src/server/__tests__/resumable-upload.test.ts @@ -5,7 +5,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { PassThrough, Readable } from 'node:stream'; import type { IncomingMessage } from 'node:http'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; import { beginResumableUpload, finalizeResumableUpload, @@ -14,6 +14,14 @@ import { import { mkdtempForTestSync } from '@agent-device/test-kit'; import { runCmdSync } from '@agent-device/host-kit/command'; +function acceptedWrite(): { promise: Promise; resolve: () => void } { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + test('finalizing an unknown upload reports expiry with a recovery hint', async () => { const error = await finalizeResumableUpload('missing-upload-id').then( () => null, @@ -183,6 +191,365 @@ test('an ignored un-ranged retry does not extend upload expiry', async () => { } }); +test('accepted body progress renews the ticket idle lifetime mid-chunk', async () => { + // Fake only the ticket clock; real stream I/O keeps running (repo fake-timer pattern). + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const body = requestStream(); + try { + const bytes = Buffer.from('ABC'); + const options = uploadOptions(bytes); + const uploadId = beginResumableUpload(options).uploadId; + let accepted = acceptedWrite(); + const receiving = receiveResumableUploadChunk({ + uploadId, + req: body, + onAcceptedBytes: () => accepted.resolve(), + }); + try { + body.write('A'); + await Promise.race([accepted.promise, receiving]); + await vi.advanceTimersByTimeAsync(4 * 60 * 1000); + accepted = acceptedWrite(); + body.write('B'); + await Promise.race([accepted.promise, receiving]); + // 8 minutes since the ticket was created, but only 4 since accepted bytes: + // the idempotent preflight still resolves to the same live ticket. + await vi.advanceTimersByTimeAsync(4 * 60 * 1000); + assert.equal(beginResumableUpload(options).uploadId, uploadId); + body.end('C'); + assert.deepEqual(await receiving, { complete: true, offset: 3 }); + } finally { + body.destroy(); + await receiving.catch(() => {}); + } + // 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); + } finally { + vi.useRealTimers(); + } +}); + +test('finalize is not expired by the idle timer during its post-write checks', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + try { + const bytes = Buffer.from('AB'); + const options = uploadOptions(bytes); + const uploadId = beginResumableUpload(options).uploadId; + await receiveResumableUploadChunk({ uploadId, req: request(bytes) }); + const finalizing = finalizeResumableUpload(uploadId); + // 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); + assert.equal(beginResumableUpload(options).uploadId, uploadId); + const finalized = await finalizing; + try { + assert.equal(fs.readFileSync(finalized.artifactPath, 'utf8'), 'AB'); + } finally { + fs.rmSync(finalized.tempDir, { recursive: true, force: true }); + } + await assert.rejects(finalizeResumableUpload(uploadId), /not found or expired/i); + } finally { + vi.useRealTimers(); + } +}); + +test('an incomplete finalize leaves the original idle lifetime intact', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + try { + const bytes = Buffer.from('AB'); + const uploadId = beginUpload(bytes).uploadId; + 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 vi.advanceTimersByTimeAsync(60 * 1000 + 1); + await assert.rejects(finalizeResumableUpload(uploadId), /not found or expired/i); + } finally { + vi.useRealTimers(); + } +}); + +test('an aborted ingress signal maps to its owned typed reason and rolls back the chunk', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const flushIO = async () => { + for (let i = 0; i < 100; i += 1) await new Promise((r) => setImmediate(r)); + }; + try { + const bytes = Buffer.from('ABCD'); + const uploadId = beginUpload(bytes).uploadId; + const controller = new AbortController(); + const body = requestStream({ 'content-range': 'bytes 0-3/4' }); + const receiving = receiveResumableUploadChunk({ + uploadId, + req: body, + signal: controller.signal, + }); + body.write('AB'); + await flushIO(); + controller.abort( + new AppError('COMMAND_FAILED', 'Upload transfer deadline exceeded', { + reason: 'transfer_ingress_deadline_exceeded', + transferPhase: 'request-body', + timeoutMs: 600_000, + }), + ); + const error = (await receiving.then( + () => null, + (error: unknown) => error, + )) as AppError | null; + assert.equal(error instanceof AppError, true); + assert.equal(error?.details?.reason, 'transfer_ingress_deadline_exceeded'); + assert.equal(error?.details?.timeoutMs, 600_000); + // The chunk rolled back to the pre-chunk offset and the ticket stays resumable: + // a full retry completes the upload. + assert.deepEqual( + await receiveResumableUploadChunk({ + uploadId, + req: request(bytes, { 'content-range': 'bytes 0-3/4' }), + }), + { complete: true, offset: 4 }, + ); + const finalized = await finalizeResumableUpload(uploadId); + try { + assert.equal(fs.readFileSync(finalized.artifactPath, 'utf8'), 'ABCD'); + } finally { + fs.rmSync(finalized.tempDir, { recursive: true, force: true }); + } + } finally { + vi.useRealTimers(); + } +}); + +test('an earlier classified pipeline failure survives a later abort of the same signal', async () => { + const bytes = Buffer.from('AB'); + const uploadId = beginUpload(bytes).uploadId; + const controller = new AbortController(); + const body = requestStream({ 'content-range': 'bytes 0-0/2' }); + const accepted = acceptedWrite(); + const receiving = receiveResumableUploadChunk({ + uploadId, + req: body, + signal: controller.signal, + onAcceptedBytes: () => accepted.resolve(), + }); + const outcome = receiving.then( + () => null, + (error: unknown) => error, + ); + body.write('A'); + await Promise.race([accepted.promise, receiving]); + const closed = new Promise((resolve) => body.once('close', resolve)); + body.destroy( + new AppError('COMMAND_FAILED', 'Upload expired while receiving data', { + reason: 'RESOURCE_EXPIRED', + }), + ); + await closed; + controller.abort( + new AppError('COMMAND_FAILED', 'Upload transfer deadline exceeded', { + reason: 'transfer_ingress_deadline_exceeded', + }), + ); + const error = (await outcome) as AppError | null; + assert.equal(error instanceof AppError, true); + assert.equal(error?.details?.reason, 'RESOURCE_EXPIRED'); +}); + +test('an ingress owner aborted while finalize waits in the admission queue owns the rejection and the ticket recovers', async () => { + const flushIO = async () => { + for (let i = 0; i < 100; i += 1) await new Promise((r) => setImmediate(r)); + }; + const bytes = Buffer.from('AB'); + 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 }); + blocker.write('A'); + await flushIO(); + const controller = new AbortController(); + const finalizing = finalizeResumableUpload(uploadId, undefined, { + signal: controller.signal, + }).then( + () => null, + (error: unknown) => error, + ); + await flushIO(); + // The synthetic owner fires while the finalize is still pending admission. + controller.abort( + new AppError('COMMAND_FAILED', 'Upload transfer deadline exceeded', { + reason: 'transfer_ingress_deadline_exceeded', + transferPhase: 'request-body', + timeoutMs: 600_000, + }), + ); + blocker.end('B'); + assert.deepEqual(await receiving, { complete: true, offset: 2 }); + const error = (await finalizing) as AppError | null; + assert.equal(error instanceof AppError, true); + 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); + try { + assert.equal(fs.readFileSync(finalized.artifactPath, 'utf8'), 'AB'); + } finally { + fs.rmSync(finalized.tempDir, { recursive: true, force: true }); + } +}); + +test('an aborted queued PUT releases at once while later work still waits for the active owner', async () => { + const flushIO = async () => { + for (let i = 0; i < 100; i += 1) await new Promise((r) => setImmediate(r)); + }; + 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 }); + blocker.write('A'); + await flushIO(); + const controller = new AbortController(); + const queued = receiveResumableUploadChunk({ + uploadId, + req: requestStream({ 'content-range': 'bytes 0-1/2' }), + signal: controller.signal, + }).then( + () => null, + (error: unknown) => error, + ); + const finalizing = finalizeResumableUpload(uploadId); + let finalizeSettled = false; + void finalizing.then( + () => { + finalizeSettled = true; + }, + () => { + finalizeSettled = true; + }, + ); + await flushIO(); + let queuedOutcome: unknown = 'pending'; + void queued.then((outcome) => { + queuedOutcome = outcome; + }); + controller.abort(createRequestCanceledError()); + await flushIO(); + // The disconnected waiter is released without waiting for the receive it does not own. + assert.equal(queuedOutcome instanceof AppError, true, 'the aborted waiter settles at once'); + assert.equal((queuedOutcome as AppError).details?.reason, 'request_canceled'); + // Serialization holds: the finalize queued behind the released waiter still waits. + assert.equal(finalizeSettled, false); + blocker.end('B'); + assert.deepEqual(await receiving, { complete: true, offset: 2 }); + const finalized = await finalizing; + try { + assert.equal(fs.readFileSync(finalized.artifactPath, 'utf8'), 'AB'); + } finally { + fs.rmSync(finalized.tempDir, { recursive: true, force: true }); + } +}); + +test('a chunk cancelled during its final offset check rolls back and never advances the offset', async () => { + const bytes = Buffer.from('ABCD'); + const uploadId = beginUpload(bytes).uploadId; + const controller = new AbortController(); + const stat = fs.promises.stat.bind(fs.promises); + let payloadStats = 0; + const held = vi.spyOn(fs.promises, 'stat').mockImplementation((async ( + target: fs.PathLike, + options?: fs.StatOptions, + ) => { + const result = await stat(target, options); + if (path.basename(String(target)) === 'payload' && (payloadStats += 1) === 2) { + // The body is fully appended; the owner fires before the offset is committed. + controller.abort( + new AppError('COMMAND_FAILED', 'Upload transfer deadline exceeded', { + reason: 'transfer_ingress_deadline_exceeded', + }), + ); + } + return result; + }) as typeof fs.promises.stat); + try { + const error = (await receiveResumableUploadChunk({ + uploadId, + req: request(bytes, { 'content-range': 'bytes 0-3/4' }), + signal: controller.signal, + }).then( + () => null, + (error: unknown) => error, + )) as AppError | null; + assert.equal(payloadStats, 2); + assert.equal(error instanceof AppError, true); + assert.equal(error?.details?.reason, 'transfer_ingress_deadline_exceeded'); + } finally { + held.mockRestore(); + } + // The cancelled chunk rolled back: a full retry from offset zero completes. + assert.deepEqual( + await receiveResumableUploadChunk({ + uploadId, + req: request(bytes, { 'content-range': 'bytes 0-3/4' }), + }), + { complete: true, offset: 4 }, + ); + const finalized = await finalizeResumableUpload(uploadId); + fs.rmSync(finalized.tempDir, { recursive: true, force: true }); +}); + +test('an ingress owner aborted mid-hash cancels the finalize with its typed reason and cleans up', async () => { + const tempRoot = mkdtempForTestSync('agent-device-finalize-abort-'); + const previousTmpDir = process.env.TMPDIR; + process.env.TMPDIR = tempRoot; + try { + // 64 MiB stays under the 2 GiB cap but hashes across real I/O time, so the + // 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) }); + const controller = new AbortController(); + const finalizing = finalizeResumableUpload(uploadId, undefined, { signal: controller.signal }); + await new Promise((resolve) => setTimeout(resolve, 5)); + controller.abort( + new AppError('COMMAND_FAILED', 'Upload transfer deadline exceeded', { + reason: 'transfer_ingress_deadline_exceeded', + transferPhase: 'request-body', + timeoutMs: 600_000, + }), + ); + const error = (await finalizing.then( + () => null, + (error: unknown) => error, + )) as AppError | null; + assert.equal(error instanceof AppError, true); + 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); + assert.deepEqual(fs.readdirSync(tempRoot), []); + } finally { + if (previousTmpDir === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = previousTmpDir; + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +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, + }); + try { + assert.equal(controller.signal.aborted, false); + assert.equal(fs.readFileSync(finalized.artifactPath, 'utf8'), 'OWNED'); + } finally { + fs.rmSync(finalized.tempDir, { recursive: true, force: true }); + } +}); + test('idempotent preflight does not extend upload expiry', async () => { vi.useFakeTimers(); try { diff --git a/packages/daemon/src/server/__tests__/upload-http-deadline.test.ts b/packages/daemon/src/server/__tests__/upload-http-deadline.test.ts new file mode 100644 index 0000000000..f2d7016760 --- /dev/null +++ b/packages/daemon/src/server/__tests__/upload-http-deadline.test.ts @@ -0,0 +1,991 @@ +import { test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import http from 'node:http'; +import net from 'node:net'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { createDaemonHttpServer } from '../http/http-server.ts'; +import { cleanupUploadedArtifact } from '../../resources/artifact-tracking.ts'; +import { + closeLoopbackServer, + listenOnLoopback, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; + +const realSetTimeout = setTimeout; +const realClearTimeout = clearTimeout; +const TOKEN = 'daemon-secret'; +const AUTH = { authorization: `Bearer ${TOKEN}` }; +const JSON_HEADERS = { ...AUTH, 'content-type': 'application/json' }; + +type RouteResponse = { status: number; headers: http.IncomingHttpHeaders; body: string }; + +async function withIO(pending: Promise, label: string): Promise { + let timeout: ReturnType | undefined; + const guard = new Promise((_, reject) => { + timeout = realSetTimeout(() => reject(new Error(`${label} did not complete in 3s`)), 3_000); + }); + try { + return await Promise.race([pending, guard]); + } finally { + realClearTimeout(timeout); + } +} + +function barrier(): { promise: Promise; resolve: () => void } { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +async function flushIO(): Promise { + for (let i = 0; i < 100; i += 1) await new Promise((r) => setImmediate(r)); +} + +function routeRequest(port: number, options: http.RequestOptions, body?: string | Buffer) { + return new Promise((resolve, reject) => { + const req = http.request({ host: '127.0.0.1', port, agent: false, ...options }, (res) => { + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('end', () => + resolve({ + status: res.statusCode ?? 0, + headers: res.headers, + body: Buffer.concat(chunks).toString('utf8'), + }), + ); + }); + req.on('error', reject); + req.end(body); + }); +} + +async function startServer() { + const server = await createDaemonHttpServer({ + token: TOKEN, + handleRequest: async (): Promise => ({ ok: true, data: {} }), + env: process.env, + cwd: process.cwd(), + }); + return { server, port: await listenOnLoopback(server) }; +} + +async function preflight(port: number, bytes: Buffer, sizeBytes = bytes.length): Promise { + const response = await routeRequest( + port, + { method: 'POST', path: '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/upload/preflight', headers: JSON_HEADERS }, + JSON.stringify({ + sha256: crypto.createHash('sha256').update(bytes).digest('hex'), + uploadAttemptId: crypto.randomUUID(), + fileName: 'artifact.bin', + sizeBytes, + artifactType: 'file', + }), + ); + assert.equal(response.status, 200); + return (JSON.parse(response.body) as { uploadId: string }).uploadId; +} + +/** Holds every read of one payload file (the finalize hash) until released. */ +function holdPayloadReads(isPayload: (path: fs.PathLike) => boolean) { + const started = barrier(); + const release = barrier(); + const createReadStream = fs.createReadStream; + const spy = vi.spyOn(fs, 'createReadStream').mockImplementation((path, options) => { + if (!isPayload(path) || typeof options !== 'object') return createReadStream(path, options); + return createReadStream(path, { + ...options, + fs: { + open: fs.open, + close: fs.close, + read(...args) { + started.resolve(); + void release.promise.then(() => Reflect.apply(fs.read, fs, args)); + }, + }, + }); + }); + return { started, release, restore: () => spy.mockRestore() }; +} + +test('a timeout ends the exchange with a typed answer while a chunk write is still pending', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const writeStarted = barrier(); + const releaseWrite = barrier(); + const createWriteStream = fs.createWriteStream; + const writers = vi.spyOn(fs, 'createWriteStream').mockImplementation((path, options) => { + if (typeof options !== 'object' || options.flags !== 'a') + return createWriteStream(path, options); + return createWriteStream(path, { + ...options, + fs: { + open: fs.open, + close: fs.close, + write(...args) { + // The body reached EOF; its file write callback is held. + writeStarted.resolve(); + void releaseWrite.promise.then(() => Reflect.apply(fs.write, fs, args)); + }, + }, + }); + }); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const bytes = Buffer.from('ABCD'); + const uploadId = await withIO(preflight(port, bytes), 'the preflight'); + const put = routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...AUTH, 'content-range': 'bytes 0-3/4', 'content-length': '4' }, + }, + bytes, + ); + void put.catch(() => {}); + await withIO(writeStarted.promise, 'the held chunk write'); + await vi.advanceTimersByTimeAsync(120_000); + const answered = await withIO(put, 'the typed timeout answer'); + assert.equal(answered.status, 500); + assert.equal(JSON.parse(answered.body).reason, 'transfer_phase_timeout'); + // The handler still owns the write: once it settles, the chunk rolls back. + releaseWrite.resolve(); + await flushIO(); + vi.useRealTimers(); + const retry = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...AUTH, 'content-range': 'bytes 0-3/4', 'content-length': '4' }, + }, + bytes, + ), + 'the retry', + ); + assert.equal(retry.status, 200); + } finally { + releaseWrite.resolve(); + writers.mockRestore(); + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('a finalize whose hash crosses the deadline never publishes success', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const bytes = Buffer.from('ABCD'); + const reads = holdPayloadReads((path) => String(path).endsWith('/payload')); + const realNow = performance.now.bind(performance); + let skewMs = 0; + const clock = vi.spyOn(performance, 'now').mockImplementation(() => realNow() + skewMs); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const uploadId = await withIO(preflight(port, bytes), 'the preflight'); + const put = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...AUTH, 'content-range': 'bytes 0-3/4', 'content-length': '4' }, + }, + bytes, + ), + 'the chunk', + ); + assert.equal(put.status, 200); + const finalize = routeRequest( + port, + { method: 'POST', path: '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/upload/finalize', headers: JSON_HEADERS }, + JSON.stringify({ uploadId }), + ); + void finalize.catch(() => {}); + await withIO(reads.started.promise, 'the held hash read'); + // The monotonic clock crosses the 600 s aggregate inside the held read, before the + // aggregate timer callback has a chance to run. + skewMs = 600_001; + reads.release.resolve(); + const answered = await withIO(finalize, 'the finalize answer'); + if (answered.status === 200) cleanupUploadedArtifact(JSON.parse(answered.body).uploadId); + assert.equal(answered.status, 500); + assert.equal(JSON.parse(answered.body).reason, 'transfer_ingress_deadline_exceeded'); + } finally { + reads.release.resolve(); + reads.restore(); + clock.mockRestore(); + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('a queued 308 behind a long finalize never closes the socket under the earlier answer', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const reads = holdPayloadReads((path) => String(path).endsWith('/payload')); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const bytesA = Buffer.from('ABCD'); + const uploadA = await withIO(preflight(port, bytesA), 'preflight A'); + const putA = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadA}`, + headers: { ...AUTH, 'content-range': 'bytes 0-3/4', 'content-length': '4' }, + }, + bytesA, + ), + 'chunk A', + ); + assert.equal(putA.status, 200); + const sizeB = 64 * 1024 * 1024; + const uploadB = await withIO(preflight(port, Buffer.alloc(0), sizeB), 'preflight B'); + const seedB = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadB}`, + headers: { ...AUTH, 'content-range': `bytes 0-0/${sizeB}`, 'content-length': '1' }, + }, + 'a', + ), + 'seed B', + ); + assert.equal(seedB.headers['x-upload-offset'], '1'); + + // One keep-alive socket: a complete finalize for A, then a stale-offset PUT for B whose + // body stays unfinished. B's 308 queues behind A's long hash. + const socket = net.connect(port, '127.0.0.1'); + let received = ''; + const closed = new Promise((resolve) => socket.once('close', () => resolve())); + socket.on('data', (data: Buffer) => { + received += data.toString('latin1'); + }); + socket.on('error', () => {}); + const finalizeBody = JSON.stringify({ uploadId: uploadA }); + socket.write( + `POST /upload/finalize HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + + `Content-Type: application/json\r\nContent-Length: ${Buffer.byteLength(finalizeBody)}\r\n\r\n${finalizeBody}` + + `PUT /upload/direct/${uploadB} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + + `Transfer-Encoding: chunked\r\n\r\n1\r\na\r\n`, + ); + await withIO(reads.started.promise, 'the held finalize hash'); + await flushIO(); + // B's inactivity ceiling passes while A's in-budget hash still owns the socket. + await vi.advanceTimersByTimeAsync(150_000); + await flushIO(); + assert.equal(socket.destroyed, false, 'the socket survives B timing out behind A'); + reads.release.resolve(); + await withIO(closed, 'the socket close after both answers'); + const statuses = [...received.matchAll(/HTTP\/1\.1 (\d+)/g)].map((match) => match[1]); + assert.equal(statuses[0], '200', 'A finalizes with its own answer'); + assert.equal(statuses[1], '308', "B's queued answer follows"); + const artifact = received.match(/"uploadId":"([^"]+)"/)?.[1]; + if (artifact) cleanupUploadedArtifact(artifact); + } finally { + reads.release.resolve(); + reads.restore(); + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +/** A monotonic clock the test can push past a deadline without running any timer callback. */ +function skewableClock() { + const realNow = performance.now.bind(performance); + const clock = { skewMs: 0, restore: () => spy.mockRestore() }; + const spy = vi.spyOn(performance, 'now').mockImplementation(() => realNow() + clock.skewMs); + return clock; +} + +test('a preflight whose ticket creation crosses the deadline answers the expiry and removes the new ticket', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const clock = skewableClock(); + const mkdtempSync = fs.mkdtempSync; + const created: string[] = []; + const dirs = vi.spyOn(fs, 'mkdtempSync').mockImplementation(((prefix: string) => { + const dir = mkdtempSync(prefix); + if (String(prefix).includes('upload')) { + created.push(String(dir)); + // The synchronous ticket creation crosses the aggregate; no timer callback can run. + clock.skewMs = 600_001; + } + return dir; + }) as typeof fs.mkdtempSync); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const answered = await withIO( + routeRequest( + port, + { method: 'POST', path: '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/upload/preflight', headers: JSON_HEADERS }, + JSON.stringify({ + sha256: 'a'.repeat(64), + uploadAttemptId: crypto.randomUUID(), + fileName: 'artifact.bin', + sizeBytes: 4, + artifactType: 'file', + }), + ), + 'the preflight answer', + ); + assert.equal(answered.status, 500); + assert.equal(JSON.parse(answered.body).reason, 'transfer_ingress_deadline_exceeded'); + assert.equal(created.length, 1); + assert.equal(fs.existsSync(created[0]!), false, 'the provisional ticket directory is removed'); + } finally { + dirs.mockRestore(); + clock.restore(); + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('an ignored PUT whose offset check crosses the deadline answers the expiry, not a 308', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const bytes = Buffer.from('ABCD'); + const uploadId = await withIO(preflight(port, bytes), 'the preflight'); + const clock = skewableClock(); + const stat = fs.promises.stat.bind(fs.promises); + const stats = vi.spyOn(fs.promises, 'stat').mockImplementation((async ( + target: fs.PathLike, + options?: fs.StatOptions, + ) => { + const result = await stat(target, options); + // The payload stat completes after the inactivity deadline, before its timer runs. + if (String(target).endsWith('/payload')) clock.skewMs = 120_001; + return result; + }) as typeof fs.promises.stat); + try { + const answered = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...AUTH, 'content-range': 'bytes 2-3/4', 'content-length': '2' }, + }, + 'CD', + ), + 'the ignored PUT answer', + ); + assert.equal(answered.status, 500, 'no 308 is committed after the deadline'); + assert.equal(JSON.parse(answered.body).reason, 'transfer_phase_timeout'); + } finally { + stats.mockRestore(); + clock.restore(); + } + } finally { + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('a ticket expiring under a held first write never closes the socket under an earlier finalize', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const reads = holdPayloadReads((path) => String(path).endsWith('/payload')); + const writeStarted = barrier(); + const releaseWrite = barrier(); + const createWriteStream = fs.createWriteStream; + let holdWrites = false; + const writers = vi.spyOn(fs, 'createWriteStream').mockImplementation((path, options) => { + if (!holdWrites || typeof options !== 'object' || options.flags !== 'a') { + return createWriteStream(path, options); + } + return createWriteStream(path, { + ...options, + fs: { + open: fs.open, + close: fs.close, + write(...args) { + writeStarted.resolve(); + void releaseWrite.promise.then(() => Reflect.apply(fs.write, fs, args)); + }, + }, + }); + }); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + // Ticket B is created first and idles to one second before its 5-minute expiry. + const bytesB = Buffer.from('WXYZ'); + const uploadB = await withIO(preflight(port, bytesB), 'preflight B'); + await vi.advanceTimersByTimeAsync(5 * 60 * 1000 - 1_000); + const bytesA = Buffer.from('ABCD'); + const uploadA = await withIO(preflight(port, bytesA), 'preflight A'); + const putA = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadA}`, + headers: { ...AUTH, 'content-range': 'bytes 0-3/4', 'content-length': '4' }, + }, + bytesA, + ), + 'chunk A', + ); + assert.equal(putA.status, 200); + holdWrites = true; + + // One keep-alive socket: a finalize for A (hash held), then a valid PUT for B whose + // body is still arriving and whose first write is held while its ticket expires. + const socket = net.connect(port, '127.0.0.1'); + let received = ''; + const closed = new Promise((resolve) => socket.once('close', () => resolve())); + socket.on('data', (data: Buffer) => { + received += data.toString('latin1'); + }); + socket.on('error', () => {}); + const finalizeBody = JSON.stringify({ uploadId: uploadA }); + socket.write( + `POST /upload/finalize HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + + `Content-Type: application/json\r\nContent-Length: ${Buffer.byteLength(finalizeBody)}\r\n\r\n${finalizeBody}` + + `PUT /upload/direct/${uploadB} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + + `Content-Range: bytes 0-3/4\r\nContent-Length: 4\r\nConnection: close\r\n\r\nWX`, + ); + await withIO(reads.started.promise, 'the held finalize hash'); + await withIO(writeStarted.promise, "B's held first write"); + // B's ticket idle timer fires while A's in-budget hash still owns the socket. + await vi.advanceTimersByTimeAsync(2_000); + await flushIO(); + assert.equal(socket.destroyed, false, 'the ticket expiry does not close the shared socket'); + reads.release.resolve(); + releaseWrite.resolve(); + await withIO(closed, 'the socket close after both answers'); + const statuses = [...received.matchAll(/HTTP\/1\.1 (\d+)/g)].map((match) => match[1]); + assert.equal(statuses[0], '200', 'A finalizes with its own answer'); + assert.equal(statuses[1], '404', 'B answers its typed ticket expiry'); + assert.match(received, /"reason":"RESOURCE_EXPIRED"/); + const artifact = received.match(/"uploadId":"([^"]+)"/)?.[1]; + if (artifact) cleanupUploadedArtifact(artifact); + } finally { + reads.release.resolve(); + releaseWrite.resolve(); + reads.restore(); + writers.mockRestore(); + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('a preflight whose body completes past the deadline creates no ticket', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const clock = skewableClock(); + const mkdtempSync = fs.mkdtempSync; + let ticketDirs = 0; + const dirs = vi.spyOn(fs, 'mkdtempSync').mockImplementation(((prefix: string) => { + if (String(prefix).includes('upload')) ticketDirs += 1; + return mkdtempSync(prefix); + }) as typeof fs.mkdtempSync); + // The JSON body's last byte is read after the aggregate deadline, before its timer runs. + server.prependOnceListener('request', (req: http.IncomingMessage) => + req.prependOnceListener('end', () => { + clock.skewMs = 600_001; + }), + ); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const answered = await withIO( + routeRequest( + port, + { method: 'POST', path: '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/upload/preflight', headers: JSON_HEADERS }, + JSON.stringify({ + sha256: 'a'.repeat(64), + uploadAttemptId: crypto.randomUUID(), + fileName: 'artifact.bin', + sizeBytes: 4, + artifactType: 'file', + }), + ), + 'the preflight answer', + ); + assert.equal(answered.status, 500); + assert.equal(JSON.parse(answered.body).reason, 'transfer_ingress_deadline_exceeded'); + assert.equal(ticketDirs, 0, 'no ticket directory is created after the deadline'); + } finally { + dirs.mockRestore(); + clock.restore(); + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('a chunk whose final offset check crosses the deadline rolls back instead of committing', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const bytes = Buffer.from('ABCD'); + const uploadId = await withIO(preflight(port, bytes), 'the preflight'); + const clock = skewableClock(); + const stat = fs.promises.stat.bind(fs.promises); + let payloadStats = 0; + const stats = vi.spyOn(fs.promises, 'stat').mockImplementation((async ( + target: fs.PathLike, + options?: fs.StatOptions, + ) => { + const result = await stat(target, options); + // The second payload stat is the final offset check, after the body was appended. + if (String(target).endsWith('/payload') && (payloadStats += 1) === 2) clock.skewMs = 600_001; + return result; + }) as typeof fs.promises.stat); + const put = { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...AUTH, 'content-range': 'bytes 0-3/4', 'content-length': '4' }, + }; + try { + const answered = await withIO(routeRequest(port, put, bytes), 'the chunk answer'); + assert.equal(payloadStats, 2); + assert.equal(answered.status, 500, 'the chunk offset is not committed after the deadline'); + assert.equal(JSON.parse(answered.body).reason, 'transfer_ingress_deadline_exceeded'); + } finally { + stats.mockRestore(); + clock.restore(); + } + // The chunk rolled back: a retry from offset zero completes. + const retry = await withIO(routeRequest(port, put, bytes), 'the retry'); + assert.equal(retry.status, 200); + } finally { + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +/** + * One keep-alive socket: a finalize for A (hash held), then a stale-offset PUT for B that + * the client keeps sending. B expires while queued. Resolves with the answers once the + * socket closes cleanly; rejects on a reset. + */ +function pipelinedFinalizeThenStreamingPut(port: number, uploadA: string, uploadB: string) { + const socket = net.connect({ port, host: '127.0.0.1', allowHalfOpen: true }); + let received = ''; + socket.on('data', (data: Buffer) => { + received += data.toString('latin1'); + }); + const outcome = new Promise((resolve, reject) => { + socket.on('error', reject); + socket.on('close', (hadError) => { + if (!hadError) resolve(received); + }); + }); + const finalizeBody = JSON.stringify({ uploadId: uploadA }); + socket.write( + `POST /upload/finalize HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + + `Content-Type: application/json\r\nContent-Length: ${Buffer.byteLength(finalizeBody)}\r\n\r\n${finalizeBody}` + + `PUT /upload/direct/${uploadB} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + + `Transfer-Encoding: chunked\r\n\r\n`, + ); + const chunk = Buffer.alloc(64 * 1024, 0x61); + const framed = Buffer.concat([ + Buffer.from(`${chunk.length.toString(16)}\r\n`), + chunk, + Buffer.from('\r\n'), + ]); + /** The client keeps sending B's body: 8 MiB more, then it ends its side. */ + const keepSending = () => { + let sent = 0; + const pump = () => { + while (sent < 8 * 1024 * 1024 && socket.writable) { + sent += chunk.length; + if (!socket.write(framed)) { + socket.once('drain', pump); + return; + } + } + if (socket.writable) socket.end(); + }; + pump(); + }; + return { socket, outcome, keepSending }; +} + +test('an expired queued request with an unread body never resets the earlier answer', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + // A reset on close with unread body bytes is timing dependent, so the case repeats. + for (let attempt = 0; attempt < 5; attempt += 1) { + const reads = holdPayloadReads((path) => String(path).endsWith('/payload')); + try { + const bytesA = Buffer.from('ABCD'); + const uploadA = await withIO(preflight(port, bytesA), 'preflight A'); + const putA = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadA}`, + headers: { ...AUTH, 'content-range': 'bytes 0-3/4', 'content-length': '4' }, + }, + bytesA, + ), + 'chunk A', + ); + assert.equal(putA.status, 200); + const sizeB = 64 * 1024 * 1024; + const uploadB = await withIO(preflight(port, Buffer.alloc(0), sizeB), 'preflight B'); + await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadB}`, + headers: { ...AUTH, 'content-range': `bytes 0-0/${sizeB}`, 'content-length': '1' }, + }, + 'a', + ), + 'seed B', + ); + const pipelined = pipelinedFinalizeThenStreamingPut(port, uploadA, uploadB); + void pipelined.outcome.catch(() => {}); + await withIO(reads.started.promise, 'the held finalize hash'); + await flushIO(); + // B's inactivity ceiling passes while queued behind A's in-budget hash. + await vi.advanceTimersByTimeAsync(150_000); + reads.release.resolve(); + pipelined.keepSending(); + const received = await withIO(pipelined.outcome, 'a clean close after both answers'); + const statuses = [...received.matchAll(/HTTP\/1\.1 (\d+)/g)].map((match) => match[1]); + assert.deepEqual(statuses, ['200', '308'], 'the client reads both answers intact'); + const artifact = received.match(/"uploadId":"([^"]+)"/)?.[1]; + if (artifact) cleanupUploadedArtifact(artifact); + } finally { + reads.release.resolve(); + reads.restore(); + } + } + } finally { + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +// A guard, not a regression proof: it also passes before the forwarder change, because Node +// attaches no socket to a queued request. It pins the response order for a pipelined +// single-shot expiry. +test('guard: a single-shot upload expiring behind a long finalize keeps the earlier answer first', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const reads = holdPayloadReads((path) => String(path).endsWith('/payload')); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const bytesA = Buffer.from('ABCD'); + const uploadA = await withIO(preflight(port, bytesA), 'preflight A'); + const putA = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadA}`, + headers: { ...AUTH, 'content-range': 'bytes 0-3/4', 'content-length': '4' }, + }, + bytesA, + ), + 'chunk A', + ); + assert.equal(putA.status, 200); + + // One keep-alive socket: a finalize for A (hash held), then a single-shot upload B + // whose body stalls after its first bytes. + const socket = net.connect(port, '127.0.0.1'); + let received = ''; + socket.on('data', (data: Buffer) => { + received += data.toString('latin1'); + }); + socket.on('error', () => {}); + const finalizeBody = JSON.stringify({ uploadId: uploadA }); + socket.write( + `POST /upload/finalize HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + + `Content-Type: application/json\r\nContent-Length: ${Buffer.byteLength(finalizeBody)}\r\n\r\n${finalizeBody}` + + `POST /upload HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + + `X-Artifact-Type: file\r\nX-Artifact-Filename: single.bin\r\nContent-Length: 1000\r\n\r\n0123456789`, + ); + await withIO(reads.started.promise, 'the held finalize hash'); + await flushIO(); + // B's 120 s inactivity ceiling passes while A's in-budget hash still owns the socket. + await vi.advanceTimersByTimeAsync(150_000); + await flushIO(); + assert.equal(socket.destroyed, false, "B's expiry does not close the socket under A"); + reads.release.resolve(); + const answers = async () => { + for (let i = 0; i < 50; i += 1) { + if ((received.match(/HTTP\/1\.1 /g) ?? []).length >= 2) return; + await flushIO(); + } + }; + await withIO(answers(), 'both answers'); + const statuses = [...received.matchAll(/HTTP\/1\.1 (\d+)/g)].map((match) => match[1]); + assert.deepEqual(statuses, ['200', '500'], 'A finalizes, then B answers its typed expiry'); + assert.match(received, /"reason":"transfer_phase_timeout"/); + const artifact = received.match(/"uploadId":"([^"]+)"/)?.[1]; + if (artifact) cleanupUploadedArtifact(artifact); + socket.destroy(); + } finally { + reads.release.resolve(); + reads.restore(); + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('a single-shot upload that expires mid-body answers a client that is still sending', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + // A reset on close with unread body bytes is timing dependent, so the case repeats. + for (let attempt = 0; attempt < 5; attempt += 1) { + const socket = net.connect({ port, host: '127.0.0.1', allowHalfOpen: true }); + let received = ''; + let answered = false; + const socketErrors: unknown[] = []; + socket.on('error', (error) => socketErrors.push(error)); + // Resolves once the typed answer is read completely; rejects on a reset before it. + const answer = new Promise((resolve, reject) => { + socket.on('data', (data: Buffer) => { + received += data.toString('latin1'); + if (!answered && /\r\n\r\n\{.*\}$/s.test(received)) { + answered = true; + resolve(received); + } + }); + socket.on('error', (error) => { + if (!answered) reject(error); + }); + }); + void answer.catch(() => {}); + socket.write( + `POST /upload HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + + `X-Artifact-Type: file\r\nX-Artifact-Filename: single.bin\r\nContent-Length: ${64 * 1024 * 1024}\r\n\r\n`, + ); + const chunk = Buffer.alloc(64 * 1024, 0x61); + // The body keeps making progress, so only the 600 s aggregate can end it. The last + // step stops 1 s past the aggregate, inside the expired request's lingering grace. + for (let step = 0; step < 10 && !answered; step += 1) { + socket.write(chunk); + await flushIO(); + await vi.advanceTimersByTimeAsync(step < 9 ? 61_000 : 52_000); + } + // The client is still sending when its typed answer arrives, as the remote upload + // client does until it reads the answer. + let sent = 0; + const pump = () => { + while (!answered && sent < 16 * 1024 * 1024 && socket.writable) { + sent += chunk.length; + if (!socket.write(chunk)) { + socket.once('drain', pump); + return; + } + } + }; + pump(); + try { + const read = await withIO(answer, 'the typed answer to a client still sending'); + assert.match(read, /^HTTP\/1\.1 500 /); + // Under load a progress write can land after the 120 s ceiling; either typed + // expiry is the owner's answer. + assert.match(read, /"reason":"transfer_(ingress_deadline_exceeded|phase_timeout)"/); + // The expiry did not destroy the connection: the server lingers and discards, so a + // client that has not read its answer yet keeps sending without a reset. + const sentAfterAnswer = new Promise((resolve, reject) => { + socket.once('error', reject); + let more = 0; + const pumpMore = () => { + while (more < 4 * 1024 * 1024) { + more += chunk.length; + const last = more >= 4 * 1024 * 1024; + const flushed = socket.write(chunk, last ? () => resolve() : undefined); + if (!flushed && !last) { + socket.once('drain', pumpMore); + return; + } + } + }; + pumpMore(); + }); + await withIO(sentAfterAnswer, 'the body bytes sent after the answer'); + await flushIO(); + assert.equal(socket.destroyed, false, 'the server did not reset the connection'); + // The server closes cleanly: it half-closed with a FIN after the answer, and its + // lingering grace ends the connection without a reset. + await vi.advanceTimersByTimeAsync(5_000); + await flushIO(); + assert.equal(socket.readableEnded, true, 'the server sent a FIN, not a reset'); + assert.deepEqual(socketErrors, [], 'no reset reached the client'); + } finally { + socket.destroy(); + } + } + } finally { + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('a hash mismatch found past the deadline answers the deadline expiry', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const reads = holdPayloadReads((path) => String(path).endsWith('/payload')); + const clock = skewableClock(); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + // The ticket declares the hash of different bytes, so the finalize hash mismatches. + const uploadId = await withIO(preflight(port, Buffer.from('WXYZ'), 4), 'the preflight'); + const put = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...AUTH, 'content-range': 'bytes 0-3/4', 'content-length': '4' }, + }, + 'ABCD', + ), + 'the chunk', + ); + assert.equal(put.status, 200); + const finalize = routeRequest( + port, + { method: 'POST', path: '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/upload/finalize', headers: JSON_HEADERS }, + JSON.stringify({ uploadId }), + ); + void finalize.catch(() => {}); + await withIO(reads.started.promise, 'the held hash read'); + clock.skewMs = 600_001; + reads.release.resolve(); + const answered = await withIO(finalize, 'the finalize answer'); + assert.equal(answered.status, 500, 'the deadline, not the mismatch, is reported'); + assert.equal(JSON.parse(answered.body).reason, 'transfer_ingress_deadline_exceeded'); + } finally { + reads.release.resolve(); + reads.restore(); + clock.restore(); + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('a chunk refused by its byte cap lingers only for the grace, not the inactivity ceiling', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const uploadId = await withIO(preflight(port, Buffer.alloc(0), 4), 'the preflight'); + const socket = net.connect({ port, host: '127.0.0.1', allowHalfOpen: true }); + let received = ''; + socket.on('data', (data: Buffer) => { + received += data.toString('latin1'); + }); + socket.on('error', () => {}); + const ended = new Promise((resolve) => socket.once('end', () => resolve())); + // A chunked body that overruns its 2-byte range: the limiter refuses it mid-body. + const chunk = Buffer.alloc(64 * 1024, 0x61); + socket.write( + `PUT /upload/direct/${uploadId} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + + `Content-Range: bytes 0-1/4\r\nTransfer-Encoding: chunked\r\n\r\n`, + ); + socket.write( + Buffer.concat([Buffer.from(`${chunk.length.toString(16)}\r\n`), chunk, Buffer.from('\r\n')]), + ); + const answer = async () => { + for (let i = 0; i < 50 && !/\r\n\r\n\{.*\}$/s.test(received); i += 1) await flushIO(); + }; + await withIO(answer(), 'the byte-cap answer'); + assert.match(received, /^HTTP\/1\.1 400 /); + // The rest of the refused body is discarded for at most the grace, then the server + // closes its side of the connection, long before the 120 s inactivity ceiling. + await withIO(ended, "the server's half-close after its answer"); + const openConnections = () => + new Promise((resolve, reject) => + server.getConnections((error, count) => (error ? reject(error) : resolve(count))), + ); + assert.equal(await openConnections(), 1); + await vi.advanceTimersByTimeAsync(5_000); + await flushIO(); + assert.equal(await openConnections(), 0, 'the grace closed the connection'); + socket.destroy(); + } finally { + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +for (const route of ['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/upload/preflight', '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/upload/finalize']) { + test(`an oversized JSON body on ${route} gets its 400 and a clean close while the client keeps sending`, async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const socket = net.connect({ port, host: '127.0.0.1', allowHalfOpen: true }); + let received = ''; + const socketErrors: unknown[] = []; + socket.on('error', (error) => socketErrors.push(error)); + socket.on('data', (data: Buffer) => { + received += data.toString('latin1'); + }); + // A chunked body declares no length, so the reader refuses it as it passes 64 KiB. + socket.write( + `POST ${route} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n` + + `Content-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n`, + ); + const chunk = Buffer.alloc(16 * 1024, 0x20); + const framed = Buffer.concat([ + Buffer.from(`${chunk.length.toString(16)}\r\n`), + chunk, + Buffer.from('\r\n'), + ]); + // The client keeps sending 2 MiB, well past the refusal, as a client that has not + // read its answer yet would. + const sent = new Promise((resolve, reject) => { + socket.once('error', reject); + let total = 0; + const pump = () => { + while (total < 2 * 1024 * 1024) { + total += chunk.length; + const last = total >= 2 * 1024 * 1024; + const flushed = socket.write(framed, last ? () => resolve() : undefined); + if (!flushed && !last) { + socket.once('drain', pump); + return; + } + } + }; + pump(); + }); + await withIO(sent, 'the oversized body sent past the refusal'); + await flushIO(); + assert.match(received, /^HTTP\/1\.1 400 /, 'the client reads its typed refusal'); + assert.equal(socket.readableEnded, true, 'the server half-closed with a FIN'); + assert.deepEqual(socketErrors, [], 'no reset reached the client'); + // After its lingering grace the server closes the connection. + const openConnections = () => + new Promise((resolve, reject) => + server.getConnections((error, count) => (error ? reject(error) : resolve(count))), + ); + await vi.advanceTimersByTimeAsync(5_000); + await flushIO(); + assert.equal(await openConnections(), 0); + assert.deepEqual(socketErrors, []); + socket.destroy(); + } finally { + vi.useRealTimers(); + await closeLoopbackServer(server); + } + }); +} diff --git a/packages/daemon/src/server/__tests__/upload-http-ingress.test.ts b/packages/daemon/src/server/__tests__/upload-http-ingress.test.ts new file mode 100644 index 0000000000..53dd0257a0 --- /dev/null +++ b/packages/daemon/src/server/__tests__/upload-http-ingress.test.ts @@ -0,0 +1,681 @@ +import { test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import http from 'node:http'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { createDaemonHttpServer } from '../http/http-server.ts'; +import { cleanupUploadedArtifact } from '../../resources/artifact-tracking.ts'; +import { + closeLoopbackServer, + listenOnLoopback, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; + +type RouteResponse = { + status: number; + headers: http.IncomingHttpHeaders; + body: string; +}; + +const realSetTimeout = setTimeout; +const realClearTimeout = clearTimeout; + +/** A loopback request over the real route, using the node:http client so fake timers cannot stall it. */ +function routeRequest( + port: number, + options: http.RequestOptions, + write?: (req: http.ClientRequest) => void, +): Promise { + return new Promise((resolve, reject) => { + const req = http.request({ host: '127.0.0.1', port, ...options }, (res) => { + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('end', () => + resolve({ + status: res.statusCode ?? 0, + headers: res.headers, + body: Buffer.concat(chunks).toString('utf8'), + }), + ); + }); + req.on('error', reject); + if (write) write(req); + else req.end(); + }); +} + +/** Bounds a promise against a real-I/O stall while the clock is faked. */ +async function withIO(pending: Promise, label = 'loopback I/O'): Promise { + let timeout: ReturnType | undefined; + const guard = new Promise((_, reject) => { + timeout = realSetTimeout(() => reject(new Error(`${label} did not complete in 3s`)), 3_000); + }); + try { + return await Promise.race([pending, guard]); + } finally { + realClearTimeout(timeout); + } +} + +function ioBarrier(): { promise: Promise; resolve: () => void } { + let release!: () => void; + const promise = new Promise((resolve) => { + release = resolve; + }); + return { promise, resolve: release }; +} + +async function flushIO(): Promise { + for (let i = 0; i < 100; i += 1) await new Promise((r) => setImmediate(r)); +} + +function preflightBody(bytes: Buffer): string { + return JSON.stringify({ + sha256: crypto.createHash('sha256').update(bytes).digest('hex'), + uploadAttemptId: crypto.randomUUID(), + fileName: 'artifact.bin', + sizeBytes: bytes.length, + artifactType: 'file', + }); +} + +async function startServer(): Promise<{ server: http.Server; port: number }> { + const server = await createDaemonHttpServer({ + token: 'daemon-secret', + handleRequest: async (): Promise => ({ ok: true, data: {} }), + env: process.env, + cwd: process.cwd(), + }); + const port = await listenOnLoopback(server); + return { server, port }; +} + +test('upload route progress renews the ticket idle lifetime and keeps 308 framing', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + try { + // Controlled timers are installed before the ticket is created. + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const auth = { authorization: 'Bearer daemon-secret' }; + const bytes = Buffer.from('ABCD'); + const body = preflightBody(bytes); + const json = { ...auth, 'content-type': 'application/json' }; + + const preflight = await withIO( + routeRequest(port, { method: 'POST', path: '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/upload/preflight', headers: json }, (req) => + req.end(body), + ), + ); + assert.equal(preflight.status, 200); + const uploadId = (JSON.parse(preflight.body) as { uploadId: string }).uploadId; + + const first = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...auth, 'content-range': 'bytes 0-1/4', 'content-length': '2' }, + }, + (req) => req.end('AB'), + ), + ); + assert.equal(first.status, 308); + assert.equal(first.headers.range, 'bytes=0-1'); + assert.equal(first.headers['x-upload-offset'], '2'); + // A chunk answered after its body is read keeps the connection. + assert.notEqual(first.headers.connection, 'close'); + + // Four idle minutes pass, then accepted bytes renew the ticket's idle lifetime. + await vi.advanceTimersByTimeAsync(4 * 60 * 1000); + const second = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...auth, 'content-range': 'bytes 2-3/4', 'content-length': '2' }, + }, + (req) => req.end('CD'), + ), + ); + assert.equal(second.status, 200); + assert.equal(second.body, 'ok'); + assert.notEqual(second.headers.connection, 'close'); + + // Eight minutes after ticket creation but under five since accepted progress, the + // idempotent preflight still resolves to the same live ticket. + await vi.advanceTimersByTimeAsync(4 * 60 * 1000); + const again = await withIO( + routeRequest(port, { method: 'POST', path: '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/upload/preflight', headers: json }, (req) => + req.end(body), + ), + ); + assert.equal(again.status, 200); + assert.equal((JSON.parse(again.body) as { uploadId: string }).uploadId, uploadId); + + const finalized = await withIO( + routeRequest(port, { method: 'POST', path: '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/upload/finalize', headers: json }, (req) => + req.end(JSON.stringify({ uploadId })), + ), + ); + assert.equal(finalized.status, 200); + assert.notEqual(preflight.headers.connection, 'close'); + assert.notEqual(finalized.headers.connection, 'close'); + const artifact = JSON.parse(finalized.body) as { ok: boolean; uploadId: string }; + assert.equal(artifact.ok, true); + cleanupUploadedArtifact(artifact.uploadId); + } finally { + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('both upload JSON routes accept a progressing body across the 120 s idle window', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const bytes = Buffer.from('ABCD'); + const auth = { authorization: 'Bearer daemon-secret' }; + const sendSlowJson = async (path: string, json: string) => { + const firstRead = ioBarrier(); + const secondRead = ioBarrier(); + let client: http.ClientRequest | undefined; + server.prependOnceListener('request', (req) => { + const read = req.read.bind(req); + let bodyBytes = 0; + req.read = (size?: number) => { + const chunk = read(size); + if (Buffer.isBuffer(chunk)) { + bodyBytes += chunk.length; + if (bodyBytes >= 1) firstRead.resolve(); + if (bodyBytes >= 2) secondRead.resolve(); + } + return chunk; + }; + }); + const reply = routeRequest( + port, + { + method: 'POST', + path, + headers: { + ...auth, + 'content-type': 'application/json', + 'content-length': Buffer.byteLength(json), + }, + }, + (req) => { + client = req; + req.write(json.slice(0, 1)); + }, + ); + void reply.catch(() => {}); + try { + await withIO(firstRead.promise); + assert.ok(client); + await vi.advanceTimersByTimeAsync(90_000); + client.write(json.slice(1, 2)); + await withIO(secondRead.promise); + await vi.advanceTimersByTimeAsync(90_000); + client.end(json.slice(2)); + return await withIO(reply); + } finally { + client?.destroy(); + } + }; + + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const preflight = await sendSlowJson('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/upload/preflight', preflightBody(bytes)); + assert.equal(preflight.status, 200); + const { uploadId } = JSON.parse(preflight.body) as { uploadId: string }; + const put = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...auth, 'content-range': 'bytes 0-3/4' }, + }, + (req) => req.end(bytes), + ), + ); + assert.equal(put.status, 200); + + const finalized = await sendSlowJson('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/upload/finalize', JSON.stringify({ uploadId })); + assert.equal(finalized.status, 200); + const artifact = JSON.parse(finalized.body) as { ok: boolean; uploadId: string }; + assert.equal(artifact.ok, true); + cleanupUploadedArtifact(artifact.uploadId); + } finally { + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('client cancellation mid-chunk aborts the receive, rolls back, and the ticket expires on schedule', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const auth = { authorization: 'Bearer daemon-secret' }; + const bytes = Buffer.from('ABCD'); + const json = { ...auth, 'content-type': 'application/json' }; + + const preflight = await withIO( + routeRequest(port, { method: 'POST', path: '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/upload/preflight', headers: json }, (req) => + req.end(preflightBody(bytes)), + ), + ); + assert.equal(preflight.status, 200); + const uploadId = (JSON.parse(preflight.body) as { uploadId: string }).uploadId; + + // Cancel the chunk request mid-body: the route's ingress owner aborts the receive. + const cancelled = withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...auth, 'content-range': 'bytes 0-3/4', 'content-length': '4' }, + }, + (req) => { + req.write('AB'); + req.destroy(new Error('client canceled')); + }, + ), + ); + await assert.rejects(cancelled, /client canceled/); + await flushIO(); + + // A full retry completes, proving the canceled chunk rolled back to offset zero. + const retry = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...auth, 'content-range': 'bytes 0-3/4', 'content-length': '4' }, + }, + (req) => req.end('ABCD'), + ), + ); + assert.equal(retry.status, 200); + assert.equal(retry.body, 'ok'); + + // After the idle lifetime with no further progress, the ticket is gone: cleanup ran. + await vi.advanceTimersByTimeAsync(5 * 60 * 1000 + 1); + const finalized = await withIO( + routeRequest(port, { method: 'POST', path: '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/upload/finalize', headers: json }, (req) => + req.end(JSON.stringify({ uploadId })), + ), + ); + assert.equal(finalized.status, 404); + assert.match(finalized.body, /not found or expired/i); + } finally { + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('stalled PUT rolls back at 120 s and finalize can spend longer on its hash', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const partialWritten = ioBarrier(); + const hashStarted = ioBarrier(); + const releaseHash = ioBarrier(); + const createWriteStream = fs.createWriteStream; + const createReadStream = fs.createReadStream; + let payloadPath: fs.PathLike | undefined; + const writers = vi.spyOn(fs, 'createWriteStream').mockImplementation((path, options) => { + if (typeof options !== 'object' || options.flags !== 'a') { + return createWriteStream(path, options); + } + payloadPath = path; + return createWriteStream(path, { + ...options, + fs: { + open: fs.open, + close: fs.close, + write(fd, buffer, offset, length, position, callback) { + fs.write(fd, buffer, offset, length, position, (error, written, data) => { + callback(error, written, data); + if (!error) partialWritten.resolve(); + }); + }, + }, + }); + }); + const readers = vi.spyOn(fs, 'createReadStream').mockImplementation((path, options) => { + if (path !== payloadPath || typeof options !== 'object') { + return createReadStream(path, options); + } + return createReadStream(path, { + ...options, + fs: { + open: fs.open, + close: fs.close, + read(...args) { + hashStarted.resolve(); + void releaseHash.promise.then(() => Reflect.apply(fs.read, fs, args)); + }, + }, + }); + }); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const auth = { authorization: 'Bearer daemon-secret' }; + const json = { ...auth, 'content-type': 'application/json' }; + const bytes = Buffer.from('ABCD'); + const preflight = await withIO( + routeRequest(port, { method: 'POST', path: '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/upload/preflight', headers: json }, (req) => + req.end(preflightBody(bytes)), + ), + ); + assert.equal(preflight.status, 200); + const { uploadId } = JSON.parse(preflight.body) as { uploadId: string }; + const put: http.RequestOptions = { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...auth, 'content-range': 'bytes 0-3/4' }, + }; + const socketClosed = ioBarrier(); + let stalledSettled = false; + const closed = routeRequest( + port, + { ...put, headers: { ...put.headers, connection: 'close', 'content-length': 4 } }, + (req) => { + req.once('socket', (socket) => socket.once('close', () => socketClosed.resolve())); + req.write('AB'); + }, + ) + .then( + ({ status, body }) => { + assert.equal(status, 500); + assert.equal(JSON.parse(body).reason, 'transfer_phase_timeout'); + }, + (error) => assert.equal(error.code, 'ECONNRESET'), + ) + .finally(() => { + stalledSettled = true; + }); + void closed.catch(() => {}); + await withIO(partialWritten.promise); + await vi.advanceTimersByTimeAsync(119_999); + assert.equal(stalledSettled, false); + await vi.advanceTimersByTimeAsync(1); + await withIO(Promise.all([closed, socketClosed.promise])); + + const retry = await withIO(routeRequest(port, put, (req) => req.end(bytes))); + assert.equal(retry.status, 200); + assert.equal(retry.body, 'ok'); + + const finalize = routeRequest( + port, + { method: 'POST', path: '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/upload/finalize', headers: json }, + (req) => req.end(JSON.stringify({ uploadId })), + ); + void finalize.catch(() => {}); + // Hold the real hash read after body completion, independent of disk speed. + await withIO(hashStarted.promise); + await vi.advanceTimersByTimeAsync(150_000); + releaseHash.resolve(); + const finalized = await withIO(finalize); + assert.equal(finalized.status, 200); + const artifact = JSON.parse(finalized.body) as { ok: boolean; uploadId: string }; + assert.equal(artifact.ok, true); + cleanupUploadedArtifact(artifact.uploadId); + } finally { + releaseHash.resolve(); + readers.mockRestore(); + writers.mockRestore(); + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('a finalize queued behind a held ticket answers at its own deadline', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const partialWritten = ioBarrier(); + const rollbackStarted = ioBarrier(); + const releaseRollback = ioBarrier(); + const createWriteStream = fs.createWriteStream; + const writers = vi.spyOn(fs, 'createWriteStream').mockImplementation((path, options) => { + const stream = createWriteStream(path, options); + if (typeof options === 'object' && options.flags === 'a') { + stream.once('ready', () => stream.once('drain', () => partialWritten.resolve())); + const write = stream.write.bind(stream); + stream.write = ((chunk: unknown, ...rest: never[]) => { + const accepted = write(chunk as never, ...rest); + if (accepted) partialWritten.resolve(); + return accepted; + }) as typeof stream.write; + } + return stream; + }); + const truncate = fs.promises.truncate.bind(fs.promises); + // The stalled chunk's rollback holds the ticket past the queued finalize's deadline. + const rollbacks = vi.spyOn(fs.promises, 'truncate').mockImplementation(async (target, length) => { + rollbackStarted.resolve(); + await releaseRollback.promise; + await truncate(target, length); + }); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const auth = { authorization: 'Bearer daemon-secret' }; + const json = { ...auth, 'content-type': 'application/json' }; + const preflight = await withIO( + routeRequest(port, { method: 'POST', path: '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/upload/preflight', headers: json }, (req) => + req.end(preflightBody(Buffer.from('ABCD'))), + ), + ); + assert.equal(preflight.status, 200); + const { uploadId } = JSON.parse(preflight.body) as { uploadId: string }; + + const stalled = routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { + ...auth, + connection: 'close', + 'content-range': 'bytes 0-3/4', + 'content-length': 4, + }, + }, + (req) => req.write('AB'), + ); + void stalled.catch(() => {}); + await withIO(partialWritten.promise); + + const finalizeBodyRead = ioBarrier(); + server.prependOnceListener('request', (req: http.IncomingMessage) => + req.once('end', () => finalizeBodyRead.resolve()), + ); + const finalize = routeRequest( + port, + { method: 'POST', path: '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/upload/finalize', headers: json }, + (req) => req.end(JSON.stringify({ uploadId })), + ); + void finalize.catch(() => {}); + await withIO(finalizeBodyRead.promise); + await flushIO(); + + // The chunk stalls at 120 s and its rollback keeps the ticket held. + await vi.advanceTimersByTimeAsync(120_000); + await withIO(rollbackStarted.promise); + // The finalize's own 600 s deadline releases it from the queue. + await vi.advanceTimersByTimeAsync(480_000); + const answered = await withIO(finalize, 'the queued finalize answer'); + assert.equal(answered.status, 500); + assert.equal(JSON.parse(answered.body).reason, 'transfer_ingress_deadline_exceeded'); + } finally { + releaseRollback.resolve(); + rollbacks.mockRestore(); + writers.mockRestore(); + vi.useRealTimers(); + await flushIO(); + await closeLoopbackServer(server); + } +}); + +test('an early answer to an unfinished body closes the connection and keeps the 308 offset', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const agent = new http.Agent({ keepAlive: true }); + const sendUnfinished = async (options: http.RequestOptions) => { + const socketClosed = ioBarrier(); + const reply = routeRequest(port, { ...options, agent }, (req) => { + req.once('socket', (socket) => socket.once('close', () => socketClosed.resolve())); + req.write('A'); + }); + const answered = await withIO(reply, 'the early answer'); + // The server closes the connection instead of draining the unread body. + await withIO(socketClosed.promise, 'the server close of the early-answered connection'); + return answered; + }; + try { + const auth = { authorization: 'Bearer daemon-secret' }; + const json = { ...auth, 'content-type': 'application/json' }; + const preflight = await withIO( + routeRequest(port, { method: 'POST', path: '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/upload/preflight', headers: json }, (req) => + req.end(preflightBody(Buffer.from('ABCD'))), + ), + ); + assert.equal(preflight.status, 200); + const { uploadId } = JSON.parse(preflight.body) as { uploadId: string }; + const first = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...auth, 'content-range': 'bytes 0-1/4', 'content-length': '2' }, + }, + (req) => req.end('AB'), + ), + ); + assert.equal(first.status, 308); + + // An offset mismatch answers 308 before its body arrives. + const mismatch = await sendUnfinished({ + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...auth, 'content-range': 'bytes 0-1/4', 'content-length': '2' }, + }); + assert.equal(mismatch.status, 308); + assert.equal(mismatch.headers.range, 'bytes=0-1'); + assert.equal(mismatch.headers['x-upload-offset'], '2'); + assert.equal(mismatch.headers.connection, 'close'); + + // An authorization refusal answers before its body arrives. + const refused = await sendUnfinished({ + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { 'content-range': 'bytes 2-3/4', 'content-length': '2' }, + }); + assert.equal(refused.status, 401); + assert.equal(refused.headers.connection, 'close'); + } finally { + agent.destroy(); + await closeLoopbackServer(server); + } +}); + +test('an early 308 reaches a client that is still streaming its body', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + const auth = { authorization: 'Bearer daemon-secret' }; + const sizeBytes = 64 * 1024 * 1024; + const chunk = Buffer.alloc(1024 * 1024, 0x61); + /** Streams the body until the answer arrives, as the remote upload client does. */ + const streamUntilAnswered = (uploadId: string) => + new Promise((resolve, reject) => { + let answered = false; + const req = http.request( + { + host: '127.0.0.1', + port, + agent: false, + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: auth, + }, + (res) => { + answered = true; + const chunks: Buffer[] = []; + res.on('data', (data: Buffer) => chunks.push(data)); + res.on('end', () => { + req.destroy(); + resolve({ + status: res.statusCode ?? 0, + headers: res.headers, + body: Buffer.concat(chunks).toString(), + }); + }); + }, + ); + req.on('error', (error) => { + if (!answered) reject(error); + }); + let sent = 0; + const pump = () => { + while (!answered && sent < sizeBytes) { + sent += chunk.length; + if (!req.write(chunk)) { + req.once('drain', pump); + return; + } + } + }; + pump(); + }); + try { + const preflight = await withIO( + routeRequest( + port, + { + method: 'POST', + path: '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/upload/preflight', + headers: { ...auth, 'content-type': 'application/json' }, + }, + (req) => + req.end( + JSON.stringify({ + sha256: 'a'.repeat(64), + uploadAttemptId: crypto.randomUUID(), + fileName: 'artifact.bin', + sizeBytes, + artifactType: 'file', + }), + ), + ), + ); + assert.equal(preflight.status, 200); + const { uploadId } = JSON.parse(preflight.body) as { uploadId: string }; + const seeded = await withIO( + routeRequest( + port, + { + method: 'PUT', + path: `/upload/direct/${uploadId}`, + headers: { ...auth, 'content-range': `bytes 0-0/${sizeBytes}`, 'content-length': '1' }, + }, + (req) => req.end('a'), + ), + ); + assert.equal(seeded.headers['x-upload-offset'], '1'); + // A reset on close with unread body bytes is timing dependent, so the case repeats. + for (let attempt = 0; attempt < 20; attempt += 1) { + const answer = await withIO(streamUntilAnswered(uploadId), 'the early 308 answer'); + assert.equal(answer.status, 308); + assert.equal(answer.headers['x-upload-offset'], '1'); + assert.equal(answer.headers.connection, 'close'); + } + } finally { + await closeLoopbackServer(server); + } +}); diff --git a/packages/daemon/src/server/__tests__/upload-http-socket-ownership.test.ts b/packages/daemon/src/server/__tests__/upload-http-socket-ownership.test.ts new file mode 100644 index 0000000000..a025fcf971 --- /dev/null +++ b/packages/daemon/src/server/__tests__/upload-http-socket-ownership.test.ts @@ -0,0 +1,234 @@ +import { test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import http from 'node:http'; +import net from 'node:net'; +import path from 'node:path'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { AppError } from '@agent-device/kernel/errors'; +import { createDaemonHttpServer } from '../http/http-server.ts'; +import { + closeLoopbackServer, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; + +const realSetTimeout = setTimeout; +const realClearTimeout = clearTimeout; +const TOKEN = 'daemon-secret'; +const SIZE_BYTES = 64 * 1024 * 1024; + +async function withIO(pending: Promise, label: string): Promise { + let timeout: ReturnType | undefined; + const guard = new Promise((_, reject) => { + timeout = realSetTimeout(() => reject(new Error(`${label} did not complete in 3s`)), 3_000); + }); + try { + return await Promise.race([pending, guard]); + } finally { + realClearTimeout(timeout); + } +} + +async function flushIO(): Promise { + for (let i = 0; i < 100; i += 1) await new Promise((r) => setImmediate(r)); +} + +async function startServer(env: NodeJS.ProcessEnv = process.env) { + const server = await createDaemonHttpServer({ + token: TOKEN, + handleRequest: async (): Promise => ({ ok: true, data: {} }), + env, + cwd: process.cwd(), + }); + return { server, port: await listenOnLoopback(server) }; +} + +async function preflight(port: number): Promise { + const response = await fetch(`http://127.0.0.1:${port}/upload/preflight`, { + method: 'POST', + headers: { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' }, + body: JSON.stringify({ + sha256: 'a'.repeat(64), + uploadAttemptId: crypto.randomUUID(), + fileName: 'artifact.bin', + sizeBytes: SIZE_BYTES, + artifactType: 'file', + }), + }); + assert.equal(response.status, 200); + return ((await response.json()) as { uploadId: string }).uploadId; +} + +/** + * Two pipelined PUTs on one keep-alive socket: the first carries a full 2-byte chunk, the + * second starts at offset 0 again and keeps streaming. After the second answer arrives, + * the client sends 16 MiB more, as a client that has not read its answer yet would, and + * then ends. Resolves with the second answer once the socket closes cleanly, and rejects + * when the server resets the connection. + */ +function pipelinedUploads(port: number, uploadId: string): Promise { + return new Promise((resolve, reject) => { + const socket = net.connect(port, '127.0.0.1'); + const headers = `Host: 127.0.0.1\r\nAuthorization: Bearer ${TOKEN}\r\n`; + const chunk = Buffer.alloc(1024 * 1024, 0x61); + const framedChunk = Buffer.concat([ + Buffer.from(`${chunk.length.toString(16)}\r\n`), + chunk, + Buffer.from('\r\n'), + ]); + let received = ''; + let answer: string | undefined; + let sentAfterAnswer = 0; + const findSecondAnswer = () => { + const starts = [...received.matchAll(/HTTP\/1\.1 /g)].map((match) => match.index ?? 0); + if (starts.length < 2) return undefined; + const end = received.indexOf('\r\n\r\n', starts[1]); + return end === -1 ? undefined : received.slice(starts[1], end); + }; + socket.on('data', (data: Buffer) => { + received += data.toString('latin1'); + answer ??= findSecondAnswer(); + }); + socket.on('error', reject); + socket.on('close', (hadError) => { + if (hadError) return; + if (answer === undefined) reject(new Error('socket closed before the second answer')); + else resolve(answer); + }); + socket.write( + `PUT /upload/direct/${uploadId} HTTP/1.1\r\n${headers}Content-Range: bytes 0-1/${SIZE_BYTES}\r\nContent-Length: 2\r\n\r\nAB` + + `PUT /upload/direct/${uploadId} HTTP/1.1\r\n${headers}Transfer-Encoding: chunked\r\n\r\n`, + ); + let sent = 0; + const pump = () => { + while (sent < SIZE_BYTES && sentAfterAnswer < 16 * 1024 * 1024 && socket.writable) { + sent += chunk.length; + if (answer !== undefined) sentAfterAnswer += chunk.length; + if (!socket.write(framedChunk)) { + socket.once('drain', pump); + return; + } + } + if (socket.writable) socket.end(); + }; + pump(); + }); +} + +test('the second of two pipelined uploads reads its early 308 while it is still streaming', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startServer(); + try { + // A reset on close with unread body bytes is timing dependent, so the case repeats. + for (let attempt = 0; attempt < 20; attempt += 1) { + const uploadId = await withIO(preflight(port), 'the preflight'); + const answer = await withIO(pipelinedUploads(port, uploadId), 'the second 308 answer'); + assert.match(answer, /^HTTP\/1\.1 308 /); + assert.match(answer, /\r\nx-upload-offset: 2\r\n/i); + assert.match(answer, /\r\nconnection: close\r\n/i); + } + } finally { + await closeLoopbackServer(server); + } +}); + +type HeldHookCall = { signal?: AbortSignal }; +const HELD_HOOK_CALLS = '__agentDeviceHeldUploadAuthHook'; + +function heldHookCalls(): HeldHookCall[] { + const store = globalThis as Record; + store[HELD_HOOK_CALLS] ??= []; + return store[HELD_HOOK_CALLS] as HeldHookCall[]; +} + +async function startHeldHookServer() { + const dir = mkdtempForTestSync('agent-device-held-auth-hook-'); + const hookPath = path.join(dir, 'held-hook.mjs'); + // The hook never answers: it stands for an identity service that hangs. + fs.writeFileSync( + hookPath, + `export default (context) => { + const calls = (globalThis[${JSON.stringify(HELD_HOOK_CALLS)}] ??= []); + calls.push({ signal: context.signal }); + return new Promise(() => {}); + };\n`, + ); + heldHookCalls().length = 0; + return await startServer({ ...process.env, AGENT_DEVICE_HTTP_AUTH_HOOK: hookPath }); +} + +async function waitForHookCall(): Promise { + for (let i = 0; i < 50 && heldHookCalls().length === 0; i += 1) await flushIO(); + const [call] = heldHookCalls(); + assert.ok(call, 'the auth hook was called'); + return call; +} + +test('a held auth hook sees the upload ingress deadline through its signal', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startHeldHookServer(); + try { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const req = http.request({ + host: '127.0.0.1', + port, + method: 'PUT', + path: '/upload/direct/held', + headers: { authorization: `Bearer ${TOKEN}`, 'content-length': '2' }, + }); + const answer = new Promise<{ status: number; body: string }>((resolve, reject) => { + req.on('response', (res) => { + let body = ''; + res.setEncoding('utf8'); + res.on('data', (chunk: string) => { + body += chunk; + }); + res.on('end', () => resolve({ status: res.statusCode ?? 0, body })); + }); + req.on('error', reject); + }); + void answer.catch(() => {}); + req.end('AB'); + const call = await waitForHookCall(); + // The body stays unread behind the held hook, so the 120 s inactivity ceiling fires. + await vi.advanceTimersByTimeAsync(120_000); + assert.equal(call.signal?.aborted, true, 'the hook signal aborts at the deadline'); + const reason = call.signal?.reason as AppError | undefined; + assert.equal(reason instanceof AppError, true); + assert.equal(reason?.details?.reason, 'transfer_phase_timeout'); + // The route's wait on the hook settles: the exchange ends with the typed answer. + const answered = await withIO(answer, 'the typed answer behind the held hook'); + assert.equal(answered.status, 500); + assert.equal(JSON.parse(answered.body).reason, 'transfer_phase_timeout'); + } finally { + vi.useRealTimers(); + await closeLoopbackServer(server); + } +}); + +test('a held auth hook sees a client disconnect through its signal', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { server, port } = await startHeldHookServer(); + try { + const req = http.request({ + host: '127.0.0.1', + port, + method: 'POST', + path: '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/upload/preflight', + headers: { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' }, + }); + req.on('error', () => {}); + req.end('{}'); + const call = await waitForHookCall(); + req.destroy(); + for (let i = 0; i < 50 && !call.signal?.aborted; i += 1) await flushIO(); + assert.equal(call.signal?.aborted, true, 'the hook signal aborts on disconnect'); + const reason = call.signal?.reason as AppError | undefined; + assert.equal(reason?.details?.reason, 'request_canceled'); + } finally { + await closeLoopbackServer(server); + } +}); diff --git a/packages/daemon/src/server/__tests__/upload-ingress.test.ts b/packages/daemon/src/server/__tests__/upload-ingress.test.ts new file mode 100644 index 0000000000..bbe1b9bc7f --- /dev/null +++ b/packages/daemon/src/server/__tests__/upload-ingress.test.ts @@ -0,0 +1,264 @@ +import { test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { PassThrough } from 'node:stream'; +import type { IncomingMessage, ServerResponse } from 'node:http'; +import { AppError } from '@agent-device/kernel/errors'; +import { beginUploadTransferIngress, resolveIngressFailure } from '../upload-ingress.ts'; + +const AGGREGATE_MS = 600_000; +const INACTIVITY_MS = 120_000; + +function fakeReq(): PassThrough & IncomingMessage { + return Object.assign(new PassThrough(), { headers: {} }) as PassThrough & IncomingMessage; +} + +function fakeRes(): ServerResponse { + const res = new EventEmitter() as ServerResponse & { + writableFinished: boolean; + destroyed: boolean; + }; + res.writableFinished = false; + res.destroyed = false; + const headers = new Map(); + Object.assign(res, { + headersSent: false, + statusCode: 200, + setHeader: (name: string, value: string) => headers.set(name.toLowerCase(), value), + removeHeader: (name: string) => headers.delete(name.toLowerCase()), + getHeader: (name: string) => headers.get(name.toLowerCase()), + end: (body?: string) => { + Object.assign(res, { headersSent: true, writableFinished: true, body }); + res.emit('finish'); + }, + }); + return res; +} + +/** Resolves with the typed reason the ingress aborts its signal with on expiry. */ +function abortReason(signal: AbortSignal): Promise { + return new Promise((resolve) => + signal.addEventListener('abort', () => resolve(signal.reason), { once: true }), + ); +} + +test('a stalled upload body expires at the 120-second inactivity ceiling with a typed reason', async () => { + vi.useFakeTimers(); + try { + const req = fakeReq(); + const ingress = beginUploadTransferIngress({ req, res: fakeRes() }); + const failure = abortReason(ingress.signal); + await vi.advanceTimersByTimeAsync(INACTIVITY_MS); + const error = (await failure) as AppError; + assert.equal(ingress.signal.aborted, true); + assert.equal(ingress.signal.aborted, true); + assert.equal(error instanceof AppError, true); + assert.equal(error.details?.reason, 'transfer_phase_timeout'); + assert.equal(error.details?.transferPhase, 'request-body'); + assert.equal(error.details?.timeoutMs, INACTIVITY_MS); + ingress.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test('body progress renews inactivity but never the 600-second aggregate', async () => { + vi.useFakeTimers(); + try { + const req = fakeReq(); + const ingress = beginUploadTransferIngress({ req, res: fakeRes() }); + const failure = abortReason(ingress.signal); + // Five progress windows of 119s stay under the inactivity ceiling and pass 595s + // of the aggregate without renewing it. + for (let i = 0; i < 5; i += 1) { + await vi.advanceTimersByTimeAsync(INACTIVITY_MS - 1_000); + ingress.onAcceptedBodyBytes(1); + await vi.advanceTimersByTimeAsync(0); + assert.equal(ingress.signal.aborted, false); + } + await vi.advanceTimersByTimeAsync(AGGREGATE_MS - 5 * (INACTIVITY_MS - 1_000) + 1); + const error = (await failure) as AppError; + assert.equal(ingress.signal.aborted, true); + assert.equal(error.details?.reason, 'transfer_ingress_deadline_exceeded'); + assert.equal(error.details?.timeoutMs, AGGREGATE_MS); + ingress.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test('bodyComplete stops only the inactivity ceiling; post-body work observes the aggregate', async () => { + vi.useFakeTimers(); + try { + const req = fakeReq(); + const ingress = beginUploadTransferIngress({ req, res: fakeRes() }); + const failure = abortReason(ingress.signal); + // The body completed: the inactivity ceiling must not fire for post-body work… + ingress.bodyComplete(); + ingress.bodyComplete(); + await vi.advanceTimersByTimeAsync(INACTIVITY_MS * 4); + assert.equal(ingress.signal.aborted, false); + assert.equal(ingress.signal.aborted, false); + // …but the 600-second aggregate still bounds it. + await vi.advanceTimersByTimeAsync(AGGREGATE_MS - INACTIVITY_MS * 4 + 1); + const error = (await failure) as AppError; + assert.equal(ingress.signal.aborted, true); + assert.equal(error.details?.reason, 'transfer_ingress_deadline_exceeded'); + assert.equal(error.details?.timeoutMs, AGGREGATE_MS); + ingress.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test('body bytes received after bodyComplete re-arm only the inactivity ceiling', async () => { + vi.useFakeTimers(); + try { + const req = fakeReq(); + const ingress = beginUploadTransferIngress({ req, res: fakeRes() }); + const failure = abortReason(ingress.signal); + ingress.bodyComplete(); + await vi.advanceTimersByTimeAsync(AGGREGATE_MS - 1_000); + // A late body byte renews inactivity only; the aggregate still fires on schedule. + ingress.onAcceptedBodyBytes(1); + await vi.advanceTimersByTimeAsync(1_001); + const error = (await failure) as AppError; + assert.equal(error.details?.reason, 'transfer_ingress_deadline_exceeded'); + ingress.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test('dispose stops both timers without aborting', async () => { + vi.useFakeTimers(); + try { + const req = fakeReq(); + const ingress = beginUploadTransferIngress({ req, res: fakeRes() }); + ingress.dispose(); + await vi.advanceTimersByTimeAsync(AGGREGATE_MS + INACTIVITY_MS); + assert.equal(ingress.signal.aborted, false); + assert.equal(ingress.signal.aborted, false); + } finally { + vi.useRealTimers(); + } +}); + +test('late progress after an overdue inactivity ceiling expires instead of renewing it', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const realNow = performance.now.bind(performance); + let skewMs = 0; + const clock = vi.spyOn(performance, 'now').mockImplementation(() => realNow() + skewMs); + try { + const req = fakeReq(); + const ingress = beginUploadTransferIngress({ req, res: fakeRes() }); + req.on('error', () => {}); + // The inactivity deadline has passed, but its timer callback has not run yet. + skewMs = INACTIVITY_MS + 1; + ingress.onAcceptedBodyBytes(1); + assert.equal(ingress.signal.aborted, true, 'late progress does not renew an overdue ceiling'); + const reason = ingress.signal.reason as AppError; + assert.equal(reason.details?.reason, 'transfer_phase_timeout'); + ingress.dispose(); + } finally { + clock.mockRestore(); + vi.useRealTimers(); + } +}); + +test('body completion after an overdue inactivity ceiling expires instead of clearing it', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const realNow = performance.now.bind(performance); + let skewMs = 0; + const clock = vi.spyOn(performance, 'now').mockImplementation(() => realNow() + skewMs); + try { + const req = fakeReq(); + const ingress = beginUploadTransferIngress({ req, res: fakeRes() }); + req.on('error', () => {}); + // The body terminator arrives after the inactivity deadline, before its timer runs. + skewMs = INACTIVITY_MS + 1; + assert.throws( + () => ingress.bodyComplete(), + (error: unknown) => (error as AppError).details?.reason === 'transfer_phase_timeout', + ); + assert.equal(ingress.signal.aborted, true, 'the overdue ceiling is not cleared'); + ingress.dispose(); + } finally { + clock.mockRestore(); + vi.useRealTimers(); + } +}); + +test('a release after an overdue aggregate expires the request instead of clearing it', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const realNow = performance.now.bind(performance); + let skewMs = 0; + const clock = vi.spyOn(performance, 'now').mockImplementation(() => realNow() + skewMs); + try { + const res = fakeRes(); + const ingress = beginUploadTransferIngress({ req: fakeReq(), res }); + // The aggregate deadline passed, but its timer callback has not run yet. + skewMs = AGGREGATE_MS + 1; + ingress.dispose(); + assert.equal(ingress.signal.aborted, true, 'dispose does not clear an overdue deadline'); + assert.equal( + (ingress.signal.reason as AppError).details?.reason, + 'transfer_ingress_deadline_exceeded', + ); + assert.equal(res.statusCode, 500, 'the expiry answers with its typed error'); + } finally { + clock.mockRestore(); + vi.useRealTimers(); + } +}); + +test('an answer before body completion carries Connection: close and bodyComplete clears it', () => { + const res = fakeRes(); + const ingress = beginUploadTransferIngress({ req: fakeReq(), res }); + assert.equal(res.getHeader('connection'), 'close'); + ingress.bodyComplete(); + assert.equal(res.getHeader('connection'), undefined); + ingress.dispose(); +}); + +test('a client disconnect on an unfinished response aborts the transfer signal', async () => { + const req = fakeReq(); + const res = fakeRes(); + const ingress = beginUploadTransferIngress({ req, res }); + res.emit('close'); + assert.equal(ingress.signal.aborted, true); + ingress.dispose(); +}); + +test('resolveIngressFailure lets the aborted signal own every unclassified failure, whatever its name', () => { + const typed = new AppError('COMMAND_FAILED', 'Upload transfer deadline exceeded', { + reason: 'transfer_ingress_deadline_exceeded', + transferPhase: 'request-body', + timeoutMs: 600_000, + }); + const controller = new AbortController(); + controller.abort(typed); + const aborted = controller.signal; + + // The signal state decides, not the error's name or code: a Node AbortError, a + // premature close, and an error with no abort marker all report the owner's reason. + const genericAbort = Object.assign(new Error('Aborted'), { name: 'AbortError' }); + assert.equal(resolveIngressFailure(aborted, genericAbort), typed); + const prematureClose = Object.assign(new Error('Premature close'), { + code: 'ERR_STREAM_PREMATURE_CLOSE', + }); + assert.equal(resolveIngressFailure(aborted, prematureClose), typed); + assert.equal(resolveIngressFailure(aborted, new Error('no abort marker')), typed); + assert.equal(resolveIngressFailure(aborted, typed), typed); + + // An earlier classified failure is preserved even when the signal aborted afterwards. + const classified = new AppError('COMMAND_FAILED', 'Upload expired while receiving data', { + reason: 'RESOURCE_EXPIRED', + }); + assert.equal(resolveIngressFailure(aborted, classified), classified); + + // Without an abort, the pipeline error passes through unchanged, even an AbortError. + const plain = new AbortController().signal; + assert.equal(resolveIngressFailure(plain, genericAbort), genericAbort); + assert.equal(resolveIngressFailure(undefined, genericAbort), genericAbort); +}); diff --git a/packages/daemon/src/server/__tests__/upload.test.ts b/packages/daemon/src/server/__tests__/upload.test.ts index 4833a0baa6..8f7e7e479a 100644 --- a/packages/daemon/src/server/__tests__/upload.test.ts +++ b/packages/daemon/src/server/__tests__/upload.test.ts @@ -3,10 +3,10 @@ import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; -import { Readable } from 'node:stream'; +import { PassThrough, Readable } from 'node:stream'; import type { IncomingMessage } from 'node:http'; import { receiveUpload } from '../upload.ts'; -import { streamReadableToFile, validateArtifactContentLength } from '../artifact-download.ts'; +import { validateArtifactContentLength } from '../artifact-download.ts'; import { AppError } from '@agent-device/kernel/errors'; import { runCmdSync } from '@agent-device/host-kit/command'; import { mkdtempForTestSync } from '@agent-device/test-kit'; @@ -55,6 +55,82 @@ test('receiveUpload verifies x-artifact-hash and removes its temp dir on mismatc } }); +test('receiveUpload cancels post-body work when its ingress owner fires at body completion', async () => { + const tempRoot = mkdtempForTestSync('agent-device-upload-owned-'); + const previousTmpDir = process.env.TMPDIR; + process.env.TMPDIR = tempRoot; + try { + const body = Buffer.from('owned-bytes'); + const controller = new AbortController(); + const typed = new AppError('COMMAND_FAILED', 'Upload transfer deadline exceeded', { + reason: 'transfer_ingress_deadline_exceeded', + transferPhase: 'request-body', + timeoutMs: 600_000, + }); + // The synthetic owner fires exactly when the body pipeline completes, before the + // hash phase: the post-body work is owned, not admitted unbounded behind the cap. + await assert.rejects( + receiveUpload( + makeUploadRequest(body, { + 'x-artifact-type': 'file', + 'x-artifact-filename': 'Sample.apk', + 'x-artifact-hash': sha256(body), + }), + { + signal: controller.signal, + onBodyComplete: () => controller.abort(typed), + }, + ), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'transfer_ingress_deadline_exceeded', + ); + assert.deepEqual(fs.readdirSync(tempRoot), []); + } finally { + if (previousTmpDir === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = previousTmpDir; + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('receiveUpload aborts an in-flight post-body hash under its ingress owner', async () => { + const tempRoot = mkdtempForTestSync('agent-device-upload-hash-abort-'); + const previousTmpDir = process.env.TMPDIR; + process.env.TMPDIR = tempRoot; + try { + // 64 MiB hashes across real I/O time, so the owner can fire mid-hash. + const body = Buffer.alloc(64 * 1024 * 1024, 0x62); + const controller = new AbortController(); + const typed = new AppError('COMMAND_FAILED', 'Upload body stalled', { + reason: 'transfer_phase_timeout', + transferPhase: 'request-body', + timeoutMs: 120_000, + }); + const upload = receiveUpload( + makeUploadRequest(body, { + 'x-artifact-type': 'file', + 'x-artifact-filename': 'Sample.apk', + 'x-artifact-hash': sha256(body), + }), + { + signal: controller.signal, + onBodyComplete: () => { + setTimeout(() => controller.abort(typed), 5); + }, + }, + ); + await assert.rejects( + upload, + (error: unknown) => + error instanceof AppError && error.details?.reason === 'transfer_phase_timeout', + ); + assert.deepEqual(fs.readdirSync(tempRoot), []); + } finally { + if (previousTmpDir === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = previousTmpDir; + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + test('receiveUpload refuses a hash algorithm other than sha256', async () => { const req = makeUploadRequest(Buffer.from('apk-bytes'), { 'x-artifact-type': 'file', @@ -136,20 +212,24 @@ test('receiveUpload extracts gzip-compressed app bundle archives', async () => { } }); -test('streamReadableToFile removes partial files after stream errors', async () => { +test('receiveUpload removes its partial file when the request stream fails', async () => { const tempRoot = mkdtempForTestSync('agent-device-upload-error-'); - const destPath = path.join(tempRoot, 'partial.bin'); - const source = new Readable({ - read() { - this.push('partial'); - this.destroy(new Error('source failed')); - }, + const previousTmpDir = process.env.TMPDIR; + process.env.TMPDIR = tempRoot; + const source = Object.assign(new PassThrough(), { + headers: { 'x-artifact-type': 'file', 'x-artifact-filename': 'partial.bin' }, }); - try { - await assert.rejects(async () => await streamReadableToFile(source, destPath), /source failed/); - assert.equal(fs.existsSync(destPath), false); + const failure = new Error('source failed'); + const receiving = receiveUpload(source as unknown as IncomingMessage, { + onBodyBytes: () => source.destroy(failure), + }); + source.write('partial'); + await assert.rejects(receiving, (error: unknown) => error === failure); + assert.deepEqual(fs.readdirSync(tempRoot), []); } finally { + if (previousTmpDir === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = previousTmpDir; fs.rmSync(tempRoot, { recursive: true, force: true }); } }); diff --git a/packages/daemon/src/server/artifact-archive.ts b/packages/daemon/src/server/artifact-archive.ts index 41492d3185..00eb3d6e9f 100644 --- a/packages/daemon/src/server/artifact-archive.ts +++ b/packages/daemon/src/server/artifact-archive.ts @@ -8,19 +8,27 @@ export async function extractTarInstallableArtifact(params: { tempDir: string; platform: 'ios' | 'android'; expectedRootName?: string; + signal?: AbortSignal; }): Promise { + params.signal?.throwIfAborted(); const outputRoot = path.join(params.tempDir, 'extracted'); let rootName = ''; + // The signature read does not accept a signal. Check the owner before and after it. const type = await detectTarArchiveType(params.archivePath); + params.signal?.throwIfAborted(); await extractArchiveSafely({ archivePath: params.archivePath, outputRoot, type, + signal: params.signal, validateManifest: (manifest) => { rootName = resolveArchiveRootName(manifest, params.platform, params.expectedRootName); }, }); + params.signal?.throwIfAborted(); const installablePath = path.join(outputRoot, rootName); + // existsSync/rmSync are inherently synchronous; the owner was checked immediately + // before this point and the extraction stream itself was abort-owned. if (!fs.existsSync(installablePath)) { fs.rmSync(outputRoot, { recursive: true, force: true }); throw new AppError( diff --git a/packages/daemon/src/server/artifact-download.ts b/packages/daemon/src/server/artifact-download.ts index 92057433dc..2e34548d58 100644 --- a/packages/daemon/src/server/artifact-download.ts +++ b/packages/daemon/src/server/artifact-download.ts @@ -1,16 +1,10 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { once } from 'node:events'; -import { pipeline } from 'node:stream/promises'; import { AppError } from '@agent-device/kernel/errors'; -import { - MAX_ARTIFACT_COMPRESSED_BYTES, - createByteLimitStream, -} from '@agent-device/host-kit/archive'; +import { MAX_ARTIFACT_COMPRESSED_BYTES } from '@agent-device/host-kit/archive'; const TEMP_PREFIX = 'agent-device-artifact-'; -const REQUEST_IDLE_TIMEOUT_MS = 60_000; export function sanitizeArtifactFilename(raw: string): string { const trimmed = raw.trim(); @@ -44,76 +38,6 @@ export function validateArtifactContentLength(rawLength: string | number | undef } } -export function streamReadableToFile( - source: NodeJS.ReadableStream, - destPath: string, -): Promise { - return new Promise((resolve, reject) => { - let settled = false; - let timeoutHandle: ReturnType | undefined; - const output = fs.createWriteStream(destPath); - - const settle = (error?: unknown) => { - if (settled) return; - settled = true; - if (timeoutHandle) clearTimeout(timeoutHandle); - if (error) { - void removePartialFile(output, destPath).finally(() => reject(error)); - return; - } - resolve(); - }; - const armTimeout = () => { - if (timeoutHandle) clearTimeout(timeoutHandle); - timeoutHandle = setTimeout(() => { - const error = new AppError( - 'COMMAND_FAILED', - 'Artifact transfer timed out due to inactivity', - { - timeoutMs: REQUEST_IDLE_TIMEOUT_MS, - }, - ); - if ('destroy' in source && typeof source.destroy === 'function') { - source.destroy(error); - } - byteLimit.destroy(error); - settle(error); - }, REQUEST_IDLE_TIMEOUT_MS); - }; - - const byteLimit = createByteLimitStream({ - maxBytes: MAX_ARTIFACT_COMPRESSED_BYTES, - createLimitError: () => - new AppError( - 'INVALID_ARGS', - `Upload exceeds maximum size of ${MAX_ARTIFACT_COMPRESSED_BYTES} bytes`, - ), - }); - byteLimit.on('data', armTimeout); - - source.on('aborted', () => { - settle(new AppError('COMMAND_FAILED', 'Artifact transfer was interrupted')); - }); - armTimeout(); - void pipeline(source, byteLimit, output).then( - () => settle(), - (error: unknown) => settle(error), - ); - }); -} - -async function removePartialFile(output: fs.WriteStream, destPath: string): Promise { - output.destroy(); - if (!output.closed) { - try { - await once(output, 'close'); - } catch { - // best-effort cleanup only - } - } - await fs.promises.rm(destPath, { force: true }).catch(() => {}); -} - function sanitizeRequestId(raw: string | undefined): string { const trimmed = raw?.trim(); if (!trimmed) return 'request'; diff --git a/packages/daemon/src/server/http/http-authorization.ts b/packages/daemon/src/server/http/http-authorization.ts index 2d0bcfffdc..abd5c61318 100644 --- a/packages/daemon/src/server/http/http-authorization.ts +++ b/packages/daemon/src/server/http/http-authorization.ts @@ -7,6 +7,7 @@ import path from 'node:path'; import { pathToFileURL } from 'node:url'; import { AppError, normalizeError, toAppErrorCode } from '@agent-device/kernel/errors'; import { timingSafeStringEqual } from '@agent-device/host-kit/transport'; +import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import type { DaemonRequest } from '../../core/daemon-request.ts'; import { restrictRemoteHostInputs } from '../remote-host-input-policy.ts'; import { @@ -26,6 +27,12 @@ export type HttpAuthHookContext = { headers: IncomingHttpHeaders; rpcRequest: JsonRpcRequest; daemonRequest: DaemonRequest; + /** + * Aborts when the request that the hook authorizes expires or its client disconnects. + * The daemon stops waiting for the hook at that moment; a hook that does slow work can + * observe it to stop that work too. + */ + signal?: AbortSignal; }; export type HttpAuthHookResult = @@ -79,7 +86,7 @@ async function runHttpAuthHook( context: HttpAuthHookContext, ): Promise { if (!authHook) return { ok: true }; - const result = await authHook(context); + const result = await awaitWithSignal(Promise.resolve(authHook(context)), context.signal); if (result === undefined || result === true) return { ok: true }; const reject = (statusCode: number, rpcCode: number, error: AppError): HttpAuthDecision => { const normalized = normalizeError(error); @@ -170,8 +177,16 @@ async function authorizeAuxiliaryHttpRequest(params: { authHook: HttpAuthHook | null; expectedToken?: string; daemonRequest: Pick; + /** The request's own cancellation: the hook gets it, and a late result is not applied. */ + signal?: AbortSignal; + /** + * The request owner's commit gate: a refusal answered after the hook goes through the + * same deadline check as any other answer. + */ + commit?: (work: () => T) => T; }): Promise<{ tenantId?: string; sessionNamespace?: TenantSessionNamespace } | null> { - const { req, res, authHook, expectedToken, daemonRequest } = params; + const { req, res, authHook, expectedToken, daemonRequest, signal } = params; + const commit = params.commit ?? ((work: () => T): T => work()); const token = resolveToken({}, req.headers); const tenantId = normalizeTenantId(readHeaderValue(req.headers, DAEMON_HTTP_TENANT_HEADER)); const tokenError = enforceDaemonToken(token, expectedToken); @@ -195,9 +210,11 @@ async function authorizeAuxiliaryHttpRequest(params: { positionals: daemonRequest.positionals, ...(tenantId ? { meta: { tenantId } } : {}), }, + ...(signal ? { signal } : {}), }); + signal?.throwIfAborted(); if (!authResult.ok) { - sendAuxiliaryAuthHookRejection(res, authResult); + commit(() => sendAuxiliaryAuthHookRejection(res, authResult)); return null; } @@ -207,7 +224,7 @@ async function authorizeAuxiliaryHttpRequest(params: { clientDeclaredTenant: tenantId, }); if (!tenantTrust.trusted) { - sendRestJsonError(res, tenantTrustRejectionError()); + commit(() => sendRestJsonError(res, tenantTrustRejectionError())); return null; } diff --git a/packages/daemon/src/server/http/http-server-ingress-limits.test.ts b/packages/daemon/src/server/http/http-server-ingress-limits.test.ts new file mode 100644 index 0000000000..6c661e9b6f --- /dev/null +++ b/packages/daemon/src/server/http/http-server-ingress-limits.test.ts @@ -0,0 +1,33 @@ +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { createDaemonHttpServer } from './http-server.ts'; +import { UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS } from './ingress-budget.ts'; + +test('the daemon HTTP server carries a 30-second header ceiling and a request ceiling behind the upload aggregate', async () => { + const server = await createDaemonHttpServer({ + handleRequest: async (): Promise => ({ ok: true, data: {} }), + env: process.env, + cwd: process.cwd(), + }); + try { + // Constructed settings, not a live wall-clock disconnect (#4441). + assert.equal(server.headersTimeout, 30_000); + // The upload owner answers an expired body with its typed reason before the socket + // timeout can close the request. + assert.ok(server.requestTimeout > UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS); + // Node starts the request clock at message start and polls header expiry only at + // its checking interval, so the ceiling also covers the worst admitted header time. + assert.ok( + server.requestTimeout > + server.headersTimeout + + (server as typeof server & { connectionsCheckingInterval: number }) + .connectionsCheckingInterval + + UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS, + ); + } finally { + await new Promise((resolve) => { + server.close(() => resolve()); + }); + } +}); diff --git a/packages/daemon/src/server/http/http-server-slow-headers.test.ts b/packages/daemon/src/server/http/http-server-slow-headers.test.ts new file mode 100644 index 0000000000..6456bf0b8f --- /dev/null +++ b/packages/daemon/src/server/http/http-server-slow-headers.test.ts @@ -0,0 +1,84 @@ +import { test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import net from 'node:net'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { + closeLoopbackServer, + listenOnLoopback, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; + +// The real ingress budget, scaled down: Node's own header and request clocks run on real +// time, so the case shrinks the owner's values instead of faking a clock. +vi.mock('./ingress-budget.ts', async (importOriginal) => ({ + ...(await importOriginal()), + DAEMON_HTTP_HEADERS_TIMEOUT_MS: 400, + DAEMON_HTTP_CONNECTIONS_CHECKING_INTERVAL_MS: 200, + UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS: 1_000, + UPLOAD_AGGREGATE_SOCKET_MARGIN_MS: 50, +})); + +const TOKEN = 'daemon-secret'; +const SIZE_BYTES = 1024 * 1024; + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +test('slow headers and a progressing body are answered by the upload owner, not by Node', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { createDaemonHttpServer } = await import('./http-server.ts'); + const server = await createDaemonHttpServer({ + token: TOKEN, + handleRequest: async (): Promise => ({ ok: true, data: {} }), + env: process.env, + cwd: process.cwd(), + }); + const port = await listenOnLoopback(server); + const socket = net.connect(port, '127.0.0.1'); + try { + const preflight = await fetch(`http://127.0.0.1:${port}/upload/preflight`, { + method: 'POST', + headers: { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' }, + body: JSON.stringify({ + sha256: 'a'.repeat(64), + uploadAttemptId: crypto.randomUUID(), + fileName: 'artifact.bin', + sizeBytes: SIZE_BYTES, + artifactType: 'file', + }), + }); + assert.equal(preflight.status, 200); + const { uploadId } = (await preflight.json()) as { uploadId: string }; + + let received = ''; + socket.on('data', (data: Buffer) => { + received += data.toString('latin1'); + }); + socket.on('error', () => {}); + const closed = new Promise((resolve) => socket.once('close', () => resolve())); + // The header block arrives slowly, just inside the 400 ms header ceiling, so admission + // starts about 350 ms after Node's request clock. A ceiling of aggregate plus margin + // (1050 ms) would let Node close the request before the owner's 1000 ms aggregate. + const head = + `PUT /upload/direct/${uploadId} HTTP/1.1\r\nHost: 127.0.0.1\r\n` + + `Authorization: Bearer ${TOKEN}\r\nContent-Range: bytes 0-${SIZE_BYTES - 1}/${SIZE_BYTES}\r\n` + + `Content-Length: ${SIZE_BYTES}\r\n\r\n`; + const pieces = 8; + for (let i = 0; i < pieces; i += 1) { + socket.write(head.slice((i * head.length) / pieces, ((i + 1) * head.length) / pieces)); + await sleep(50); + } + // The body keeps making progress until the upload owner's aggregate ends it. + const chunk = Buffer.alloc(1024, 0x61); + while (!received && !socket.destroyed) { + socket.write(chunk); + await sleep(50); + } + await closed; + assert.match(received, /^HTTP\/1\.1 500 /, 'the upload owner answers, not a Node 408'); + assert.match(received, /"reason":"transfer_ingress_deadline_exceeded"/); + } finally { + socket.destroy(); + await closeLoopbackServer(server); + } +}); diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index ddfba3bda6..47d031d661 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -40,6 +40,13 @@ import { readHostCpuArch } from '@agent-device/host-kit/process'; import { shouldStreamRequestProgress } from '@agent-device/daemon-contracts/request-progress-protocol'; import { statusCodeForNormalizedError } from '../http-errors.ts'; import { tryHandleUploadHttpRoute } from '../upload-http.ts'; +import { + DAEMON_HTTP_CONNECTIONS_CHECKING_INTERVAL_MS, + DAEMON_HTTP_HEADERS_TIMEOUT_MS, + UPLOAD_AGGREGATE_SOCKET_MARGIN_MS, + UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS, + requestTimeoutBehindUploads, +} from './ingress-budget.ts'; import { tryHandleDownloadableArtifactHttpRoute } from '../downloadable-artifact-http.ts'; import { tryHandleRequestDiagnosticsHttpRoute } from '../request-diagnostics-http.ts'; import { tryHandleHostAdminHttpRoute } from '../host-lease-http.ts'; @@ -172,6 +179,8 @@ export async function createDaemonHttpServer(options: { authHook, expectedToken: token, daemonRequest: request.daemonRequest, + signal: request.signal, + commit: request.commit, }), }) ) { @@ -239,7 +248,25 @@ export async function createDaemonHttpServer(options: { }); }); }); - return http.createServer(onRequest); + // 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 + // and per connection: when a later pipelined header block expires, Node closes the whole + // socket, including earlier answers still owned on it. No upload owner exists yet at that + // point, so this stays socket-wide by design. + const server = http.createServer( + { + headersTimeout: DAEMON_HTTP_HEADERS_TIMEOUT_MS, + requestTimeout: requestTimeoutBehindUploads({ + headersTimeoutMs: DAEMON_HTTP_HEADERS_TIMEOUT_MS, + connectionsCheckingIntervalMs: DAEMON_HTTP_CONNECTIONS_CHECKING_INTERVAL_MS, + uploadAggregateMs: UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS, + marginMs: UPLOAD_AGGREGATE_SOCKET_MARGIN_MS, + }), + connectionsCheckingInterval: DAEMON_HTTP_CONNECTIONS_CHECKING_INTERVAL_MS, + }, + onRequest, + ); + return server; } /** Accumulates one `/rpc` body and hands it to the flow once the stream ends. */ diff --git a/packages/daemon/src/server/http/ingress-budget.ts b/packages/daemon/src/server/http/ingress-budget.ts new file mode 100644 index 0000000000..5a9678e137 --- /dev/null +++ b/packages/daemon/src/server/http/ingress-budget.ts @@ -0,0 +1,31 @@ +/** + * The one owner of the daemon's HTTP ingress budgets (#4441). + * + * Node starts its request clock when the parser starts a message, and it checks header + * and request expiry only once per connections-checking interval. A header block can + * therefore reach the request callback up to one interval after the header ceiling, and + * the request ceiling can fire up to one interval early relative to admission. The upload + * owner starts its aggregate at admission, so the native request ceiling covers the worst + * admitted header time, one polling interval, the upload aggregate, and a margin. Node + * then never closes an upload body that is still inside its own budget. + */ +export const DAEMON_HTTP_HEADERS_TIMEOUT_MS = 30_000; +export const DAEMON_HTTP_CONNECTIONS_CHECKING_INTERVAL_MS = 5_000; +/** The upload aggregate from request admission through finalization. */ +export const UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS = 600_000; +export const UPLOAD_AGGREGATE_SOCKET_MARGIN_MS = 30_000; + +/** The native request ceiling that stays behind every admitted upload's own aggregate. */ +export function requestTimeoutBehindUploads(budget: { + headersTimeoutMs: number; + connectionsCheckingIntervalMs: number; + uploadAggregateMs: number; + marginMs: number; +}): number { + return ( + budget.headersTimeoutMs + + budget.connectionsCheckingIntervalMs + + budget.uploadAggregateMs + + budget.marginMs + ); +} diff --git a/packages/daemon/src/server/resumable-upload-transfer.ts b/packages/daemon/src/server/resumable-upload-transfer.ts index 7106c53efe..a864d7e9ef 100644 --- a/packages/daemon/src/server/resumable-upload-transfer.ts +++ b/packages/daemon/src/server/resumable-upload-transfer.ts @@ -1,10 +1,12 @@ import fs from 'node:fs'; import crypto from 'node:crypto'; import type { IncomingMessage } from 'node:http'; +import { PassThrough, finished, type Transform, type Writable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import { AppError } from '@agent-device/kernel/errors'; import { createByteLimitStream } from '@agent-device/host-kit/archive'; import { parseUploadContentLength, parseUploadContentRange } from './resumable-upload-range.ts'; +import { resolveIngressFailure, throwIfIngressAborted } from './upload-ingress.ts'; export type ResumableTransferEntry = { payloadPath: string; @@ -15,6 +17,11 @@ export async function receiveResumableTransfer(params: { entry: ResumableTransferEntry; req: IncomingMessage; invalidate: (error: unknown) => Promise; + signal?: AbortSignal; + /** The request owner's commit gate; the offset commits through it inside rollback. */ + commit?: (work: () => T) => T; + onAcceptedBytes?: (bytes: number) => void; + onBodyComplete?: () => void; }): Promise<{ complete: boolean; offset: number; appended: boolean }> { const oldSize = await currentOffset(params.entry); const range = parseUploadContentRange( @@ -40,29 +47,112 @@ export async function receiveResumableTransfer(params: { createLimitError: () => new AppError('INVALID_ARGS', 'Upload chunk exceeds its permitted byte range'), }); + const payloadStream = fs.createWriteStream(params.entry.payloadPath, { flags: 'a' }); + observeAcceptedWrites(payloadStream, params.onAcceptedBytes); + let offset: number; try { - await pipeline( - params.req, - limiter, - fs.createWriteStream(params.entry.payloadPath, { flags: 'a' }), - ); + await pipeRequestBody(params.req, limiter, payloadStream, params.signal); if (range && limiter.bytesSeen !== range.span) { throw new AppError('INVALID_ARGS', 'Upload chunk length does not match content-range'); } if (contentLength !== undefined && limiter.bytesSeen !== contentLength) { throw new AppError('INVALID_ARGS', 'Upload chunk length does not match content-length'); } + // The body is complete: inactivity no longer applies to this request, so valid + // post-body work observes only the owner's aggregate (#4441). + params.onBodyComplete?.(); + // The final offset check and the owner's last cancellation check stay inside the + // rollback boundary: a cancelled chunk never commits its offset (#4441). + const finalOffset = await currentOffset(params.entry); + throwIfIngressAborted(params.signal); + offset = params.commit ? params.commit(() => finalOffset) : finalOffset; } catch (error) { - await rollback(params.entry.payloadPath, oldSize, error, params.invalidate); - throw error; + // An aborted ingress signal owns the failure with its typed reason; an earlier + // classified failure (limiter, ticket expiry) is preserved unchanged (#4441). + const failure = resolveIngressFailure(params.signal, error); + await rollback(params.entry.payloadPath, oldSize, failure, params.invalidate); + throw failure; } - const offset = await currentOffset(params.entry); return { complete: offset === params.entry.sizeBytes, offset, appended: offset > oldSize }; } -export async function computeUploadHash(filePath: string): Promise { +/** + * Pipes an upload request body through `limiter` into `output` without handing the + * request to the pipeline. A pipeline that owns the request destroys it on any abort or + * failure (expiry, byte cap, length mismatch), and Node then detaches the request's + * socket, so the ingress owner's lingering close finds no socket and the connection + * closes under a client that is still sending. Keeping the request out of the pipeline + * keeps `req.socket` attached: the ingress owner answers and ends the exchange with its + * lingering close in response order. A request that fails (client disconnect) still + * fails the pipeline. + */ +export async function pipeRequestBody( + req: IncomingMessage, + limiter: Transform, + output: Writable, + signal: AbortSignal | undefined, +): Promise { + const body = new PassThrough(); + req.pipe(body); + const stopWatching = finished(req, (error) => { + if (error) body.destroy(error); + }); + try { + await pipeline(body, limiter, output, { signal }); + } finally { + req.unpipe(body); + stopWatching(); + } +} + +/** + * Reports each nonempty chunk only after its write to the payload file completed + * without error: completed-byte progress, never bytes merely read from the socket. + * The wrapper preserves the caller's arguments and callback. + */ +export function observeAcceptedWrites( + stream: fs.WriteStream, + onAcceptedBytes: ((bytes: number) => void) | undefined, +): void { + if (!onAcceptedBytes) return; + const originalWrite = stream.write.bind(stream); + stream.write = function ( + chunk: unknown, + encodingOrCallback?: BufferEncoding | ((error?: Error | null) => void), + callback?: (error?: Error | null) => void, + ): boolean { + const encoding = typeof encodingOrCallback === 'string' ? encodingOrCallback : undefined; + const callerCallback = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback; + const bytes = + typeof chunk === 'string' + ? Buffer.byteLength(chunk, encoding ?? 'utf8') + : Buffer.isBuffer(chunk) || ArrayBuffer.isView(chunk) + ? chunk.byteLength + : 0; + return originalWrite(chunk as never, encoding as never, (error?: Error | null) => { + if (!error && bytes > 0) onAcceptedBytes(bytes); + callerCallback?.(error); + }); + } as typeof stream.write; +} + +/** + * Hashes a received payload under the ingress owner's signal when given: the read + * stream is destroyed with the owner's typed reason on abort, and an abort-owned + * generic failure is mapped back to that reason. The file is bounded by the byte + * cap that admitted it. + */ +export async function computeUploadHash(filePath: string, signal?: AbortSignal): Promise { const hash = crypto.createHash('sha256'); - for await (const chunk of fs.createReadStream(filePath)) hash.update(chunk); + try { + const stream = fs.createReadStream(filePath, signal ? { signal } : undefined); + for await (const chunk of stream) { + signal?.throwIfAborted(); + hash.update(chunk); + } + } catch (error) { + throw resolveIngressFailure(signal, error); + } return hash.digest('hex'); } diff --git a/packages/daemon/src/server/resumable-upload.ts b/packages/daemon/src/server/resumable-upload.ts index 03109a4147..61f9cb444e 100644 --- a/packages/daemon/src/server/resumable-upload.ts +++ b/packages/daemon/src/server/resumable-upload.ts @@ -4,6 +4,7 @@ import fs from 'node:fs'; import path from 'node:path'; import type { IncomingMessage } from 'node:http'; import { AppError } from '@agent-device/kernel/errors'; +import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import { extractTarInstallableArtifact } from './artifact-archive.ts'; import { requireTenantOwnedEntry, @@ -15,6 +16,7 @@ import { validateArtifactContentLength, } from './artifact-download.ts'; import { computeUploadHash, receiveResumableTransfer } from './resumable-upload-transfer.ts'; +import { resolveIngressFailure, throwIfIngressAborted } from './upload-ingress.ts'; const RESUMABLE_UPLOAD_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000; const RESUMABLE_UPLOAD_RESOURCE: TenantOwnedResourceKind = { @@ -72,21 +74,51 @@ type ResumableUploadEntry = { timer?: ReturnType; generation: number; tail: Promise; - activeReceive?: IncomingMessage; + /** Aborts the active receive with the ticket's typed expiry. */ + activeReceive?: AbortController; closed: boolean; finalized: boolean; }; -export function beginResumableUpload(options: BeginResumableUploadOptions): { +type ResumableUploadTicket = { uploadId: string; cacheHit: false; upload: { url: string; headers: Record }; -} { +}; + +/** + * Returns the ticket for this upload attempt, creating it when none exists. With `publish`, + * a newly created ticket is provisional until `publish` returns: when `publish` throws (a + * refused commit), the new ticket and its directory are removed again. An existing ticket + * returned for the same attempt is kept either way. + */ +export function beginResumableUpload( + options: BeginResumableUploadOptions, + publish?: (ticket: ResumableUploadTicket) => void, +): ResumableUploadTicket { validateResumableUploadOptions(options); const key = buildResumableUploadKey(options); const existingId = RESUMABLE_UPLOADS_BY_KEY().get(key); const existing = existingId ? RESUMABLE_UPLOADS_BY_ID().get(existingId) : undefined; 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 }); + } + throw error; + } + return ticket; +} + +function describeResumableUploadTicket( + entry: ResumableUploadEntry, + options: BeginResumableUploadOptions, +): ResumableUploadTicket { return { uploadId: entry.id, cacheHit: false, @@ -107,49 +139,116 @@ export async function receiveResumableUploadChunk(params: { uploadId: string; req: IncomingMessage; tenantId?: string; + signal?: AbortSignal; + /** The request owner's commit gate; the chunk offset commits through it. */ + commit?: (work: () => T) => T; + onAcceptedBytes?: (bytes: number) => void; + onBodyComplete?: () => void; }): Promise<{ complete: boolean; offset: number }> { const entry = requireResumableUpload(params.uploadId, params.tenantId); - return await runExclusive(entry, 'receive', params.req, async () => { - const { appended, ...result } = await receiveResumableTransfer({ - entry, - req: params.req, - invalidate: async () => await terminateEntry(entry), - }); - if (appended && !entry.closed) refreshResumableUploadTimer(entry); - return result; - }); + // 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(); + const signal = params.signal + ? AbortSignal.any([params.signal, ticketExpiry.signal]) + : ticketExpiry.signal; + return await runExclusive( + entry, + 'receive', + ticketExpiry, + async () => { + const { appended, ...result } = await receiveResumableTransfer({ + entry, + req: params.req, + signal, + commit: params.commit, + invalidate: async () => await terminateEntry(entry), + onAcceptedBytes: (bytes) => { + // Accepted (flushed) body bytes renew the ticket's idle lifetime during + // actual progress, not only when a whole chunk completes (#4441). The request + // deadline is checked first, so an overdue write never extends the ticket. + params.onAcceptedBytes?.(bytes); + if (!entry.closed && !signal.aborted) refreshResumableUploadTimer(entry); + }, + onBodyComplete: params.onBodyComplete, + }); + if (appended && !entry.closed) refreshResumableUploadTimer(entry); + return result; + }, + params.signal, + ); } +/** + * The ingress owner a finalize runs under (#4441): its signal is threaded through the + * serialized admission and into the post-body hash, the owned extraction stream, and + * the artifact materialization, so expiry or client disconnect cancels that work with + * the owner's typed reason instead of running it unbounded. + */ +export type FinalizeUploadIngressLink = { + signal?: AbortSignal; + /** The request owner's commit gate; each finalize step checks it. */ + commit?: (work: () => T) => T; +}; + export async function finalizeResumableUpload( uploadId: string, tenantId?: string, + ingress?: FinalizeUploadIngressLink, ): Promise<{ artifactPath: string; tempDir: string }> { const entry = requireResumableUpload(uploadId, tenantId); - return await runExclusive(entry, 'finalize', undefined, async () => { - const offset = fs.statSync(entry.payloadPath).size; - if (offset !== entry.sizeBytes) { - throw new AppError('INVALID_ARGS', 'Upload is incomplete', { - uploadId, - offset, - sizeBytes: entry.sizeBytes, - }); - } - try { - const actualHash = await computeUploadHash(entry.payloadPath); - if (actualHash !== entry.sha256) { - throw new AppError('INVALID_ARGS', 'Upload hash mismatch', { + const signal = ingress?.signal; + // The owner's typed expiry, including a recorded deadline whose timer has not run yet. + const ensureActive = () => { + ingress?.commit?.(() => undefined); + throwIfIngressAborted(signal); + }; + return await runExclusive( + entry, + 'finalize', + undefined, + async () => { + // Admission of the serialized queue: an already-fired owner stays authoritative, + // and a close/cancel that raced the wait keeps its own typed expiry error. + ensureActive(); + // fs.statSync is inherently synchronous; the owner was checked immediately before. + const offset = fs.statSync(entry.payloadPath).size; + if (offset !== entry.sizeBytes) { + // An incomplete finalize is not terminal: the ticket stays resumable and keeps + // its original idle lifetime, so the timer is left armed exactly as it was (#4441). + throw new AppError('INVALID_ARGS', 'Upload is incomplete', { uploadId, - expectedSha256: entry.sha256, - actualSha256: actualHash, + offset, + sizeBytes: entry.sizeBytes, }); } - const artifactPath = await materializeFinalArtifact(entry); - markFinalized(entry); - return { artifactPath, tempDir: entry.tempDir }; - } catch (error) { - throw await cleanupTerminalFinalizeFailure(entry, error); - } - }); + // 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). + disarmResumableUploadTimer(entry); + try { + ensureActive(); + const actualHash = await computeUploadHash(entry.payloadPath, signal); + if (actualHash !== entry.sha256) { + throw new AppError('INVALID_ARGS', 'Upload hash mismatch', { + uploadId, + expectedSha256: entry.sha256, + actualSha256: actualHash, + }); + } + ensureActive(); + const artifactPath = await materializeFinalArtifact(entry, signal); + ensureActive(); + markFinalized(entry); + return { artifactPath, tempDir: entry.tempDir }; + } 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. + throw await cleanupTerminalFinalizeFailure(entry, resolveIngressFailure(signal, error)); + } + }, + signal, + ); } function createResumableUploadEntry( @@ -193,12 +292,20 @@ function refreshResumableUploadTimer(entry: ResumableUploadEntry): void { entry.timer.unref(); } +/** + * Stops the idle timer without arming a new one and invalidates any in-flight fire, + * for an operation (finalize) that owns the entry until it closes it. + */ +function disarmResumableUploadTimer(entry: ResumableUploadEntry): void { + if (entry.timer) clearTimeout(entry.timer); + entry.timer = undefined; + entry.generation += 1; +} + function expireEntry(entry: ResumableUploadEntry, generation: number): void { if (entry.generation !== generation || entry.closed) return; closeEntry(entry); - const activeReceive = entry.activeReceive; - activeReceive?.once('error', () => {}); - activeReceive?.destroy( + entry.activeReceive?.abort( new AppError('COMMAND_FAILED', 'Upload expired while receiving data', { reason: 'RESOURCE_EXPIRED', }), @@ -212,30 +319,47 @@ function expireEntry(entry: ResumableUploadEntry, generation: number): void { async function runExclusive( entry: ResumableUploadEntry, kind: 'receive' | 'finalize', - req: IncomingMessage | undefined, + receive: AbortController | undefined, action: () => Promise, + signal?: AbortSignal, ): Promise { - const operation = entry.tail - .catch(() => {}) - .then(async () => { - if (entry.closed) requireResumableUpload(entry.id, entry.tenantId); - if (kind === 'receive') entry.activeReceive = req; - try { - return await action(); - } finally { - if (kind === 'receive') entry.activeReceive = undefined; - } - }); - entry.tail = operation.then( - () => {}, - () => {}, - ); + const predecessor = entry.tail; + const operation = (async () => { + // Admission is abortable: an expired or disconnected waiter leaves the queue with the + // owner's typed reason and never waits for a predecessor it does not own (#4441). + await awaitWithSignal( + predecessor.catch(() => {}), + signal, + () => { + throwIfIngressAborted(signal); + }, + ); + if (entry.closed) requireResumableUpload(entry.id, entry.tenantId); + // 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); + if (kind === 'receive') entry.activeReceive = receive; + try { + return await action(); + } finally { + if (kind === 'receive') entry.activeReceive = undefined; + } + })(); + // Later work waits for both the predecessor and this operation, so a released + // waiter never lets its successor overlap the work still running ahead of it. + entry.tail = Promise.allSettled([predecessor, operation]).then(() => {}); return await operation; } -async function materializeFinalArtifact(entry: ResumableUploadEntry): Promise { +async function materializeFinalArtifact( + entry: ResumableUploadEntry, + signal?: AbortSignal, +): Promise { if (entry.artifactType === 'file') { const artifactPath = path.join(entry.tempDir, entry.fileName); + // rename is a single non-cancellable filesystem operation; the owner is checked + // immediately before it and the entry's cleanup still owns any failure. + throwIfIngressAborted(signal); await fs.promises.rename(entry.payloadPath, artifactPath); return artifactPath; } @@ -244,6 +368,7 @@ async function materializeFinalArtifact(entry: ResumableUploadEntry): Promise; + /** The upload ingress signal: authorization stops at the same deadline or disconnect. */ + signal: AbortSignal; + /** The upload ingress commit gate: a refusal after the hook answers through it. */ + commit: (work: () => T) => T; }) => Promise<{ tenantId?: string } | null>; export function tryHandleUploadHttpRoute(params: { @@ -94,28 +100,66 @@ function resolveUploadHttpRoute(req: http.IncomingMessage): UploadHttpRoute | nu return null; } -async function handleUpload( +/** + * Runs one upload route under its ingress owner (#4441): finite budgets admitted at the + * callback (a 600-second aggregate plus a 120-second body-inactivity ceiling), the + * authorization under the same signal, one failure answer, and one release. + */ +async function runUploadRoute( req: http.IncomingMessage, res: http.ServerResponse, authorize: AuxiliaryHttpAuthorizer, + positionals: string[], + handle: (auth: { tenantId?: string }, ingress: UploadTransferIngress) => Promise, ): Promise { + const ingress = beginUploadTransferIngress({ req, res }); try { - const auth = await authorize({ - req, - res, - daemonRequest: { - command: 'upload', - positionals: [], - }, - }); + const auth = await authorizeUpload(authorize, req, res, ingress, positionals); if (!auth) return; - - sendUploadedArtifactResponse(res, await receiveUpload(req), auth.tenantId); + await handle(auth, ingress); } catch (error) { - sendRestJsonError(res, normalizeError(error)); + answerUploadFailure(res, error, ingress.commit); + } finally { + ingress.dispose(); } } +/** The upload command and positionals the auth hook sees, under the ingress signal. */ +async function authorizeUpload( + authorize: AuxiliaryHttpAuthorizer, + req: http.IncomingMessage, + res: http.ServerResponse, + ingress: { signal: AbortSignal; commit: (work: () => T) => T }, + positionals: string[], +): Promise<{ tenantId?: string } | null> { + return await authorize({ + req, + res, + signal: ingress.signal, + commit: ingress.commit, + daemonRequest: { command: 'upload', positionals }, + }); +} + +async function handleUpload( + req: http.IncomingMessage, + res: http.ServerResponse, + authorize: AuxiliaryHttpAuthorizer, +): Promise { + await runUploadRoute(req, res, authorize, [], async (auth, ingress) => { + sendUploadedArtifactResponse( + res, + await receiveUpload(req, { + signal: ingress.signal, + onBodyBytes: (bytes) => ingress.onAcceptedBodyBytes(bytes), + onBodyComplete: () => ingress.bodyComplete(), + }), + auth.tenantId, + ingress.commit, + ); + }); +} + async function handleUploadPreflight( req: http.IncomingMessage, res: http.ServerResponse, @@ -123,30 +167,25 @@ async function handleUploadPreflight( token: string, origin: string, ): Promise { - try { - const auth = await authorize({ - req, - res, - daemonRequest: { - command: 'upload', - positionals: ['preflight'], - }, - }); - if (!auth) return; - - const body = await readRestJsonBody(req, 64 * 1024); + await runUploadRoute(req, res, authorize, ['preflight'], async (auth, ingress) => { + const body = await readRestJsonBody(req, 64 * 1024, ingress.onAcceptedBodyBytes); + // The JSON body is fully received: inactivity stops here and the remaining work + // observes only the aggregate (#4441). + ingress.bodyComplete(); const preflight = readUploadPreflightBody(body); - const upload = beginResumableUpload({ - baseUrl: origin, - tokenHeaders: buildUploadTicketAuthHeaders(token), - ...preflight, - tenantId: auth.tenantId, - }); - - sendJson(res, { ok: true, ...upload }); - } catch (error) { - sendRestJsonError(res, normalizeError(error)); - } + // bodyComplete above committed under the recorded deadlines in this same turn, so no + // ticket is created after a deadline. A ticket created here is published only when + // its answer commits; a refused commit removes it again. + beginResumableUpload( + { + baseUrl: origin, + tokenHeaders: buildUploadTicketAuthHeaders(token), + ...preflight, + tenantId: auth.tenantId, + }, + (upload) => ingress.commit(() => sendJson(res, { ok: true, ...upload })), + ); + }); } async function handleResumableUpload( @@ -155,33 +194,30 @@ async function handleResumableUpload( res: http.ServerResponse, authorize: AuxiliaryHttpAuthorizer, ): Promise { - try { - const auth = await authorize({ + await runUploadRoute(req, res, authorize, ['direct', uploadId], async (auth, ingress) => { + const result = await receiveResumableUploadChunk({ + uploadId, req, - res, - daemonRequest: { - command: 'upload', - positionals: ['direct', uploadId], - }, + tenantId: auth.tenantId, + signal: ingress.signal, + commit: ingress.commit, + onAcceptedBytes: (bytes) => ingress.onAcceptedBodyBytes(bytes), + onBodyComplete: () => ingress.bodyComplete(), }); - if (!auth) return; - - const result = await receiveResumableUploadChunk({ uploadId, req, tenantId: auth.tenantId }); - if (result.complete) { - res.statusCode = 200; - res.end('ok'); - return; - } - - res.statusCode = 308; - if (result.offset > 0) { - res.setHeader('range', `bytes=0-${result.offset - 1}`); - } - res.setHeader('x-upload-offset', String(result.offset)); - res.end(); - } catch (error) { - sendRestJsonError(res, normalizeError(error)); - } + ingress.commit(() => { + if (result.complete) { + res.statusCode = 200; + res.end('ok'); + return; + } + res.statusCode = 308; + if (result.offset > 0) { + res.setHeader('range', `bytes=0-${result.offset - 1}`); + } + res.setHeader('x-upload-offset', String(result.offset)); + res.end(); + }); + }); } async function handleUploadFinalize( @@ -189,27 +225,24 @@ async function handleUploadFinalize( res: http.ServerResponse, authorize: AuxiliaryHttpAuthorizer, ): Promise { - try { - const auth = await authorize({ - req, - res, - daemonRequest: { - command: 'upload', - positionals: ['finalize'], - }, - }); - if (!auth) return; - - const body = await readRestJsonBody(req, 64 * 1024); + await runUploadRoute(req, res, authorize, ['finalize'], async (auth, ingress) => { + const body = await readRestJsonBody(req, 64 * 1024, ingress.onAcceptedBodyBytes); + // The JSON body is fully received: inactivity stops here, so the post-body hash, + // extraction and registration observe only the aggregate (#4441). + ingress.bodyComplete(); const finalize = readUploadFinalizeBody(body); sendUploadedArtifactResponse( res, - await finalizeResumableUpload(finalize.uploadId, auth.tenantId), + // The request's ingress signal is threaded through the serialized admission into + // the post-body hash, the owned extraction stream and artifact materialization. + await finalizeResumableUpload(finalize.uploadId, auth.tenantId, { + signal: ingress.signal, + commit: ingress.commit, + }), auth.tenantId, + ingress.commit, ); - } catch (error) { - sendRestJsonError(res, normalizeError(error)); - } + }); } function sendJson(res: http.ServerResponse, body: Record): void { @@ -218,25 +251,59 @@ function sendJson(res: http.ServerResponse, body: Record): void res.end(JSON.stringify(body)); } +/** + * Registers a finished artifact and answers, as one commit. A refused commit (a deadline + * that passed first) removes the unregistered directory and answers with the same typed + * expiry as the timer. + */ function sendUploadedArtifactResponse( res: http.ServerResponse, result: { artifactPath: string; tempDir: string }, tenantId: string | undefined, + commit: (work: () => T) => T, ): void { - const uploadId = trackUploadedArtifact({ - artifactPath: result.artifactPath, - tempDir: result.tempDir, - tenantId, - }); - sendJson(res, { ok: true, uploadId }); + let registered = false; + try { + commit(() => { + const uploadId = trackUploadedArtifact({ + artifactPath: result.artifactPath, + tempDir: result.tempDir, + tenantId, + }); + registered = true; + sendJson(res, { ok: true, uploadId }); + }); + } catch (error) { + if (!registered) fs.rmSync(result.tempDir, { recursive: true, force: true }); + throw error; + } +} + +/** + * Answers a route failure through the same deadline check as a success: a deadline that + * passed first answers with its own expiry instead, and an exchange the ingress already + * ended gets no second answer. + */ +function answerUploadFailure( + res: http.ServerResponse, + error: unknown, + commit: (work: () => T) => T, +): void { + if (res.headersSent) return; + try { + commit(() => sendRestJsonError(res, normalizeError(error))); + } catch { + // The ingress answered with its expiry, or the client is gone. + } } async function readRestJsonBody( req: http.IncomingMessage, maxBodyBytes: number, + onAcceptedBytes: (bytes: number) => void, ): Promise> { const raw = ( - await readNodeHttpRequestBody(req, maxBodyBytes, 'Request body is too large.') + await readNodeHttpRequestBody(req, maxBodyBytes, 'Request body is too large.', onAcceptedBytes) ).toString('utf8'); try { const parsed = JSON.parse(raw) as unknown; diff --git a/packages/daemon/src/server/upload-ingress.ts b/packages/daemon/src/server/upload-ingress.ts new file mode 100644 index 0000000000..daf5eb6bdc --- /dev/null +++ b/packages/daemon/src/server/upload-ingress.ts @@ -0,0 +1,313 @@ +import type { IncomingMessage, ServerResponse } from 'node:http'; +import type { Socket } from 'node:net'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { TRANSFER_BODY_INACTIVITY_TIMEOUT_MS } from '@agent-device/host-kit/transport'; +import { responseDisconnectSignal } from './http/response-disconnect-signal.ts'; +import { UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS } from './http/ingress-budget.ts'; +import { sendRestJsonError } from './http-errors.ts'; + +/** + * The finite budgets one inbound upload request runs under (#4441): a 600-second + * aggregate armed when the request is admitted at the callback, and a 120-second + * body-inactivity ceiling admitted at the same moment and renewed only by body + * progress. The header phase keeps its own server-level ceiling (ingress-budget.ts). + * Progress never renews the aggregate, and client disconnect shares this owner + * through the existing response-disconnect signal. + */ +const TRANSFER_PHASE_TIMEOUT_REASON = 'transfer_phase_timeout'; +const TRANSFER_INGRESS_AGGREGATE_REASON = 'transfer_ingress_deadline_exceeded'; + +export type UploadTransferIngress = { + /** Aborts on aggregate expiry or client disconnect while the request is unfinished. */ + readonly signal: AbortSignal; + /** + * Renews only the inactivity ceiling; never the aggregate. Progress that arrives after + * a deadline has passed expires the request instead of renewing it. + */ + onAcceptedBodyBytes(bytes: number): void; + /** + * Stops only the inactivity ceiling once the request body is complete, and keeps the + * connection open for the answer. Post-body work (hash, extraction, registration) then + * observes just the aggregate. It clears a deadline, so it commits through `commit` and + * throws the typed expiry when the inactivity deadline already passed. + */ + bodyComplete(): void; + /** + * The only way to commit work that becomes externally visible: an answer, a ticket, a + * registration, an offset, or a cleared deadline. It first compares the recorded + * monotonic deadlines, so a deadline that passed before its timer callback ran expires + * the request through the same path as the timer and the work is refused with the typed + * expiry. `commit(() => undefined)` is the same gate for a cancellation point. + */ + commit(work: () => T): T; + /** + * Releases the request. With the body read, both timers stop at once. With the body + * unread, the connection closes after the answer flushes, and both timers keep bounding + * it until the socket closes. Safe to call more than once; does not abort. + */ + dispose(): void; +}; + +/** + * Admits one upload request's transfer budgets. Armed at the request callback, not + * lazily on the first byte, so a stalled body is bounded from admission. Each deadline + * is also recorded on the monotonic clock, so work that crosses it before the timer + * callback runs cannot commit or publish success. + * + * Expiry aborts owned work with a typed reason and ends the HTTP exchange whatever the + * request stream's state: it answers with the typed error when no answer has started, + * and it closes a connection whose body is unread once this request's answer flushes. + * A request whose answer is queued behind an earlier pipelined answer never closes the + * socket under that earlier answer. The handler keeps owning its in-flight filesystem + * work through cleanup or rollback. + * + * The ingress also owns the early-answer rule: every answer sent before the body is + * consumed carries `Connection: close`, and that connection ends after the answer + * flushes, under these timers. A keep-alive connection never drains an unread body + * outside the ingress budget. The close lingers (RFC 9112 §9.6): the server half-closes + * after the answer and discards the rest of the body until the body ends, the client + * closes, or a timer fires. A full close with unread bytes resets the connection, and + * a client that is still sending then loses the answer. + */ +export function beginUploadTransferIngress(params: { + req: IncomingMessage; + res: ServerResponse; +}): UploadTransferIngress { + const { req, res } = params; + // Until the body is complete, any answer is an early answer. + res.setHeader('connection', 'close'); + const releaseLinger = holdLingeringClose(req); + const expiry = new AbortController(); + const signal = AbortSignal.any([expiry.signal, responseDisconnectSignal(req, res)]); + const admittedAt = performance.now(); + const aggregateDeadline = admittedAt + UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS; + let inactivityDeadline: number | undefined; + const aggregateTimer: ReturnType = setTimeout( + () => fail(aggregateExpiry()), + UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS, + ); + aggregateTimer.unref(); + let inactivityTimer: ReturnType | undefined; + let disposed = false; + let released = false; + + const stopInactivity = () => { + if (inactivityTimer !== undefined) clearTimeout(inactivityTimer); + inactivityTimer = undefined; + inactivityDeadline = undefined; + }; + + const stopTimers = () => { + if (disposed) return; + disposed = true; + clearTimeout(aggregateTimer); + stopInactivity(); + }; + + const overdueExpiry = (): AppError | undefined => { + const now = performance.now(); + if (now >= aggregateDeadline) return aggregateExpiry(); + if (inactivityDeadline !== undefined && now >= inactivityDeadline) return inactivityExpiry(); + return undefined; + }; + + const dispose = () => { + if (disposed || released) return; + // An overdue deadline is never cleared by a release: it expires the request instead. + const overdue = overdueExpiry(); + if (overdue) { + fail(overdue); + return; + } + released = true; + // A finished exchange may already have detached its socket. + const socket = req.socket as IncomingMessage['socket'] | null; + if (req.complete || !socket || socket.destroyed) { + releaseLinger(); + stopTimers(); + return; + } + // The body is unread (an early answer, or a pipeline stopped by a byte cap, a length + // mismatch or an expired ticket): after the answer flushes, the same lingering close + // as an expiry discards the rest within its grace. The timers bound the wait until then. + socket.once('close', stopTimers); + const closeConnection = () => lingerThenClose(req); + if (res.writableFinished) closeConnection(); + else res.once('finish', closeConnection); + }; + + const fail = (error: AppError) => { + if (disposed) return; + stopTimers(); + expiry.abort(error); + endExchange(req, res, error); + }; + + const armInactivity = () => { + if (inactivityTimer !== undefined) clearTimeout(inactivityTimer); + inactivityDeadline = performance.now() + TRANSFER_BODY_INACTIVITY_TIMEOUT_MS; + inactivityTimer = setTimeout( + () => fail(inactivityExpiry()), + TRANSFER_BODY_INACTIVITY_TIMEOUT_MS, + ); + inactivityTimer.unref(); + }; + + const commit = (work: () => T): T => { + if (!disposed) { + const overdue = overdueExpiry(); + if (overdue) fail(overdue); + } + throwIfIngressAborted(signal); + return work(); + }; + + armInactivity(); + + return { + signal, + onAcceptedBodyBytes(bytes: number) { + if (disposed || bytes <= 0) return; + const overdue = overdueExpiry(); + if (overdue) { + fail(overdue); + return; + } + armInactivity(); + }, + bodyComplete() { + commit(() => { + releaseLinger(); + if (!res.headersSent) res.removeHeader('connection'); + stopInactivity(); + }); + }, + commit, + dispose, + }; +} + +function aggregateExpiry(): AppError { + return new AppError('COMMAND_FAILED', 'Upload transfer deadline exceeded', { + reason: TRANSFER_INGRESS_AGGREGATE_REASON, + transferPhase: 'request-body', + timeoutMs: UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS, + }); +} + +function inactivityExpiry(): AppError { + return new AppError('COMMAND_FAILED', 'Upload body stalled', { + reason: TRANSFER_PHASE_TIMEOUT_REASON, + transferPhase: 'request-body', + timeoutMs: TRANSFER_BODY_INACTIVITY_TIMEOUT_MS, + }); +} + +/** + * Ends one expired exchange in response order. No answer started: answer with the typed + * error now; Node writes it after any earlier pipelined answer. Body unread: once this + * request's own answer flushes, hand the socket to its close owner's lingering close and + * discard the rest of the body, bounded by a short grace. A queued request therefore never + * closes the socket under an earlier answer, and a full close never resets a client that + * is still sending before it reads the answers. + */ +function endExchange(req: IncomingMessage, res: ServerResponse, error: AppError): void { + if (!res.headersSent) { + res.setHeader('connection', 'close'); + sendRestJsonError(res, normalizeError(error)); + } + if (req.complete) return; + const closeConnection = () => lingerThenClose(req); + if (res.writableFinished) closeConnection(); + else res.once('finish', closeConnection); +} + +/** How long a connection may linger after its answer to discard an unread body. */ +const EXPIRED_BODY_LINGER_GRACE_MS = 5_000; + +function lingerThenClose(req: IncomingMessage): void { + const socket = req.socket as IncomingMessage['socket'] | null; + if (!socket || socket.destroyed) return; + const grace = setTimeout(() => socket.destroy(), EXPIRED_BODY_LINGER_GRACE_MS); + grace.unref(); + socket.once('close', () => clearTimeout(grace)); + // Discard the rest of the expired body; the close owner half-closes until it ends. + req.resume(); + socket.destroySoon(); +} + +/** + * The one close owner of a socket. Node calls `destroySoon` after a `Connection: close` + * answer. While any request on the socket still has an unread body, the owner only + * half-closes, and the full close waits until the last such body ends or its request + * closes. Requests register their interest; none of them replaces the owner. + */ +type SocketCloseOwner = { + readonly unread: Set; + lingering: boolean; + readonly closeNow: () => void; +}; + +const socketCloseOwners = new WeakMap(); + +function socketCloseOwner(socket: Socket): SocketCloseOwner { + const existing = socketCloseOwners.get(socket); + if (existing) return existing; + const destroySoon = socket.destroySoon; + const owner: SocketCloseOwner = { + unread: new Set(), + lingering: false, + closeNow: () => destroySoon.call(socket), + }; + socket.destroySoon = function lingeringClose(this: Socket): void { + if (owner.unread.size === 0) { + owner.closeNow(); + return; + } + if (this.writable) this.end(); + owner.lingering = true; + }; + socketCloseOwners.set(socket, owner); + return owner; +} + +/** + * Registers this request's unread body with its socket's close owner. Returns the release + * for the moment the body no longer needs a lingering close; release is idempotent. + */ +function holdLingeringClose(req: IncomingMessage): () => void { + const socket = req.socket as IncomingMessage['socket'] | null; + if (!socket || req.complete) return () => {}; + const owner = socketCloseOwner(socket); + owner.unread.add(req); + const release = () => { + if (!owner.unread.delete(req)) return; + if (owner.lingering && owner.unread.size === 0) owner.closeNow(); + }; + req.once('end', release); + req.once('close', release); + return release; +} + +/** + * Resolves which failure a joined upload pipeline reports, by the owned signal state and + * never by error text. When the ingress signal is aborted, it owns every unclassified + * failure, so its typed reason is reported. A failure that is already a typed AppError + * (an earlier classification such as a byte limit or ticket expiry) is kept unchanged. + */ +export function resolveIngressFailure(signal: AbortSignal | undefined, failure: unknown): unknown { + if (!signal?.aborted || failure instanceof AppError) return failure; + try { + throwIfIngressAborted(signal); + } catch (error) { + return error; + } + return failure; +} + +/** Throws the ingress owner's typed abort reason when its signal already fired. */ +export function throwIfIngressAborted(signal: AbortSignal | undefined): void { + if (!signal?.aborted) return; + if (signal.reason instanceof Error) throw signal.reason; + throw new AppError('COMMAND_FAILED', 'Upload canceled', { reason: 'upload_canceled' }); +} diff --git a/packages/daemon/src/server/upload.ts b/packages/daemon/src/server/upload.ts index 9a8af504d1..ab1532ee55 100644 --- a/packages/daemon/src/server/upload.ts +++ b/packages/daemon/src/server/upload.ts @@ -2,17 +2,37 @@ import fs from 'node:fs'; import path from 'node:path'; import type { IncomingMessage } from 'node:http'; import { AppError } from '@agent-device/kernel/errors'; +import { + MAX_ARTIFACT_COMPRESSED_BYTES, + createByteLimitStream, +} from '@agent-device/host-kit/archive'; import { extractTarInstallableArtifact } from './artifact-archive.ts'; import { createArtifactTempDir, sanitizeArtifactFilename, - streamReadableToFile, validateArtifactContentLength, } from './artifact-download.ts'; -import { computeUploadHash } from './resumable-upload-transfer.ts'; +import { + computeUploadHash, + observeAcceptedWrites, + pipeRequestBody, +} from './resumable-upload-transfer.ts'; +import { resolveIngressFailure, throwIfIngressAborted } from './upload-ingress.ts'; + +/** + * The ingress owner a single-shot upload runs under (#4441): its signal aborts the joined + * body pipeline with a typed reason, owns the post-body hash and extraction, and its + * inactivity ceiling renews only on accepted (flushed) body bytes until the body completes. + */ +export type UploadIngressLink = { + signal?: AbortSignal; + onBodyBytes?: (bytes: number) => void; + onBodyComplete?: () => void; +}; export async function receiveUpload( req: IncomingMessage, + ingress?: UploadIngressLink, ): Promise<{ artifactPath: string; tempDir: string }> { const artifactType = req.headers['x-artifact-type'] as string | undefined; const rawFilename = req.headers['x-artifact-filename'] as string | undefined; @@ -36,25 +56,66 @@ export async function receiveUpload( try { if (artifactType === 'file') { const artifactPath = path.join(tempDir, artifactFilename); - await streamReadableToFile(req, artifactPath); - await verifyUploadSha256(artifactPath, expectedSha256); + 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 }; } const archivePath = path.join(tempDir, 'artifact.tar'); - await streamReadableToFile(req, archivePath); - await verifyUploadSha256(archivePath, expectedSha256); + 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. const artifactPath = await extractTarInstallableArtifact({ archivePath, tempDir, platform: 'ios', expectedRootName: artifactFilename, + signal: ingress?.signal, }); fs.rmSync(archivePath, { force: true }); return { artifactPath, tempDir }; } catch (error) { fs.rmSync(tempDir, { recursive: true, force: true }); - throw error; + throw resolveIngressFailure(ingress?.signal, error); + } +} + +/** + * One joined pipeline for the request body, owned by the ingress link: the signal + * destroys every pipeline stream with its typed reason (the earliest failure wins) but + * never the request itself, each + * accepted (flushed) byte renews the owner's inactivity ceiling, and the ceiling stops + * at body completion so post-body work observes only the aggregate. The byte cap keeps + * the later local phases (hash, extract) bounded by the same limit. + */ +async function receiveUploadBody( + req: IncomingMessage, + destPath: string, + ingress?: UploadIngressLink, +): Promise { + const byteLimit = createByteLimitStream({ + maxBytes: MAX_ARTIFACT_COMPRESSED_BYTES, + createLimitError: () => + new AppError( + 'INVALID_ARGS', + `Upload exceeds maximum size of ${MAX_ARTIFACT_COMPRESSED_BYTES} bytes`, + ), + }); + const output = fs.createWriteStream(destPath); + observeAcceptedWrites(output, ingress?.onBodyBytes); + try { + await pipeRequestBody(req, byteLimit, output, ingress?.signal); + ingress?.onBodyComplete?.(); + } catch (error) { + throw resolveIngressFailure(ingress?.signal, error); } } @@ -74,9 +135,10 @@ function readExpectedUploadSha256(req: IncomingMessage): string | undefined { async function verifyUploadSha256( payloadPath: string, expectedSha256: string | undefined, + signal?: AbortSignal, ): Promise { if (expectedSha256 === undefined) return; - const actualSha256 = await computeUploadHash(payloadPath); + const actualSha256 = await computeUploadHash(payloadPath, signal); if (actualSha256 !== expectedSha256) { throw new AppError('INVALID_ARGS', 'Upload hash mismatch', { expectedSha256, actualSha256 }); } diff --git a/packages/host-kit/src/internal/archive-extraction-tar.test.ts b/packages/host-kit/src/internal/archive-extraction-tar.test.ts index 7cfc61093a..111b744d0d 100644 --- a/packages/host-kit/src/internal/archive-extraction-tar.test.ts +++ b/packages/host-kit/src/internal/archive-extraction-tar.test.ts @@ -1,11 +1,37 @@ import assert from 'node:assert/strict'; import { promises as fs } from 'node:fs'; -import { test } from 'vitest'; +import { test, vi } from 'vitest'; +import * as tar from 'tar-stream'; import { AppError } from '@agent-device/kernel/errors'; import { extractTarArchive } from './archive-extraction-tar.ts'; import { ArchiveBudget } from './archive-safety.ts'; import { createArchiveWorkspace, createTruncatedTgz } from '../archive.fixtures.ts'; +/** While set, entry writers hold each file write until the release resolves. */ +const writeHold = vi.hoisted(() => ({ + current: undefined as undefined | { started: () => void; release: Promise }, +})); + +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal(); + const createWriteStream: typeof actual.createWriteStream = (path, options) => { + const hold = writeHold.current; + if (!hold || typeof options !== 'object') return actual.createWriteStream(path, options); + return actual.createWriteStream(path, { + ...options, + fs: { + open: actual.open, + close: actual.close, + write(...args: unknown[]) { + hold.started(); + void hold.release.then(() => Reflect.apply(actual.write, actual, args)); + }, + }, + }); + }; + return { ...actual, createWriteStream }; +}); + test('tar inspection rejects declared bytes before draining an over-budget entry', async () => { const workspace = await createArchiveWorkspace(); try { @@ -30,3 +56,131 @@ test('tar inspection rejects declared bytes before draining an over-budget entry await fs.rm(workspace.root, { recursive: true, force: true }); } }); + +test('a tar extraction cancelled during an entry filesystem operation keeps its typed reason without an unhandled rejection', async () => { + const workspace = await createArchiveWorkspace(); + const rejections: unknown[] = []; + const observeRejection = (reason: unknown) => rejections.push(reason); + const entryStarted = barrier(); + const releaseEntry = barrier(); + const mkdir = fs.mkdir.bind(fs); + const held = vi.spyOn(fs, 'mkdir').mockImplementation(async (target, options) => { + if (target === workspace.outputRoot) { + entryStarted.resolve(); + await releaseEntry.promise; + } + return await mkdir(target, options); + }); + process.on('unhandledRejection', observeRejection); + try { + await createSingleFileTar(workspace.archivePath); + const controller = new AbortController(); + const outcome = extractTarArchive({ + archivePath: workspace.archivePath, + outputRoot: workspace.outputRoot, + gzip: false, + signal: controller.signal, + }).then( + () => null, + (error: unknown) => error, + ); + // The entry loop awaits the held filesystem operation while the signal fires. + await entryStarted.promise; + controller.abort( + new AppError('COMMAND_FAILED', 'Upload transfer deadline exceeded', { + reason: 'transfer_ingress_deadline_exceeded', + }), + ); + await flushIO(); + assert.deepEqual(rejections, [], 'the cancelled pipeline never reaches the process'); + releaseEntry.resolve(); + const error = await outcome; + assert.equal(error instanceof AppError, true); + assert.equal((error as AppError).details?.reason, 'transfer_ingress_deadline_exceeded'); + await flushIO(); + assert.deepEqual(rejections, []); + // No entry writer opened after the cancellation, so nothing outlives the cleanup. + assert.deepEqual(await fs.readdir(workspace.outputRoot), []); + } finally { + releaseEntry.resolve(); + process.off('unhandledRejection', observeRejection); + held.mockRestore(); + await fs.rm(workspace.root, { recursive: true, force: true }); + } +}); + +async function createSingleFileTar(archivePath: string): Promise { + const pack = tar.pack(); + pack.entry({ name: 'payload.bin' }, Buffer.from('AB')); + pack.finalize(); + const chunks: Buffer[] = []; + for await (const chunk of pack) chunks.push(Buffer.from(chunk)); + await fs.writeFile(archivePath, Buffer.concat(chunks)); +} + +function barrier(): { promise: Promise; resolve: () => void } { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +async function flushIO(): Promise { + for (let i = 0; i < 20; i += 1) await new Promise((r) => setImmediate(r)); +} + +test('a tar extraction cancelled with an entry write in flight joins the write before it settles', async () => { + const workspace = await createArchiveWorkspace(); + const rejections: unknown[] = []; + const observeRejection = (reason: unknown) => rejections.push(reason); + const writeStarted = barrier(); + const releaseWrite = barrier(); + process.on('unhandledRejection', observeRejection); + try { + const pack = tar.pack(); + pack.entry({ name: 'payload.bin' }, Buffer.alloc(64 * 1024, 0x61)); + pack.finalize(); + const chunks: Buffer[] = []; + for await (const chunk of pack) chunks.push(Buffer.from(chunk)); + await fs.writeFile(workspace.archivePath, Buffer.concat(chunks)); + writeHold.current = { started: writeStarted.resolve, release: releaseWrite.promise }; + const controller = new AbortController(); + let settled = false; + const outcome = extractTarArchive({ + archivePath: workspace.archivePath, + outputRoot: workspace.outputRoot, + gzip: false, + signal: controller.signal, + }) + .then( + () => null, + (error: unknown) => error, + ) + .finally(() => { + settled = true; + }); + await writeStarted.promise; + controller.abort( + new AppError('COMMAND_FAILED', 'Upload transfer deadline exceeded', { + reason: 'transfer_ingress_deadline_exceeded', + }), + ); + await flushIO(); + assert.equal(settled, false, 'the extraction waits for its in-flight write'); + releaseWrite.resolve(); + const error = await outcome; + assert.equal((error as AppError).details?.reason, 'transfer_ingress_deadline_exceeded'); + // Cleanup after the outcome is final: no write lands after the output is removed. + await fs.rm(workspace.outputRoot, { recursive: true, force: true }); + await fs.mkdir(workspace.outputRoot); + await flushIO(); + assert.deepEqual(await fs.readdir(workspace.outputRoot), []); + assert.deepEqual(rejections, []); + } finally { + writeHold.current = undefined; + releaseWrite.resolve(); + process.off('unhandledRejection', observeRejection); + await fs.rm(workspace.root, { recursive: true, force: true }); + } +}); diff --git a/packages/host-kit/src/internal/archive-extraction-tar.ts b/packages/host-kit/src/internal/archive-extraction-tar.ts index 87127db10f..5d43381b11 100644 --- a/packages/host-kit/src/internal/archive-extraction-tar.ts +++ b/packages/host-kit/src/internal/archive-extraction-tar.ts @@ -3,6 +3,7 @@ import path from 'node:path'; import { createGunzip } from 'node:zlib'; import { pipeline } from 'node:stream/promises'; import * as tar from 'tar-stream'; +import { AppError } from '@agent-device/kernel/errors'; import { ArchiveBudget, archiveError, @@ -49,14 +50,14 @@ export async function extractTarArchive(options: TarOptions): Promise { 'Archive contents changed after inspection', ); } - await writeTarEntry(entry, manifestEntry, options.outputRoot, reservation); + await writeTarEntry(entry, manifestEntry, options.outputRoot, reservation, options.signal); reservation.commitEntry(); } await extraction; } catch (error) { extractor.destroy(); await extraction.catch(() => {}); - throw error; + throw cancellationOwnedFailure(options.signal, error); } if (manifest.length !== 0) { throw archiveError('ARCHIVE_MANIFEST_MISMATCH', 'Archive contents changed after inspection'); @@ -94,20 +95,32 @@ async function inspectTar( } catch (error) { extractor.destroy(); await inspection.catch(() => {}); - throw error; + throw cancellationOwnedFailure(options.signal, error); } return manifest; } +/** + * Starts the archive pipeline with its outcome observed at once: a cancellation can reject it + * while the entry loop still awaits a filesystem operation, before the loop joins it. + */ function streamTar( archivePath: string, gzip: boolean, extractor: tar.Extract, signal?: AbortSignal, ): Promise { - return gzip + const stream = gzip ? pipeline(createReadStream(archivePath), createGunzip(), extractor, { signal }) : pipeline(createReadStream(archivePath), extractor, { signal }); + stream.catch(() => {}); + return stream; +} + +/** A cancelled walk reports the signal's typed reason; a classified archive failure stays. */ +function cancellationOwnedFailure(signal: AbortSignal | undefined, error: unknown): unknown { + if (!signal?.aborted || error instanceof AppError) return error; + return signal.reason; } function readTarKind(type: tar.Headers['type']): 'directory' | 'file' { @@ -133,19 +146,27 @@ function manifestEntryFromTarHeader(header: tar.Headers): ArchiveManifestEntry | return { name, kind, size, mode: extractedEntryMode(kind, header.mode) }; } +/** + * Writes one entry under the extraction's signal. The signal is checked after each + * filesystem await, so no writer opens after a cancellation, and the entry pipeline joins + * its own writer before it settles, so cleanup never races an open write. + */ async function writeTarEntry( entry: tar.Entry, manifestEntry: ArchiveManifestEntry, outputRoot: string, reservation: { chargeBytes(bytes: number): void }, + signal: AbortSignal | undefined, ): Promise { const outputPath = resolveArchiveOutputPath(outputRoot, manifestEntry.name); if (manifestEntry.kind === 'directory') { - await createExtractedDirectory(outputPath, manifestEntry.mode); + await createExtractedDirectory(outputPath, manifestEntry.mode, signal); + signal?.throwIfAborted(); await drainTarEntry(entry); return; } await fs.mkdir(path.dirname(outputPath), { recursive: true }); + signal?.throwIfAborted(); await pipeline( entry, async function* (source) { @@ -155,6 +176,7 @@ async function writeTarEntry( } }, createWriteStream(outputPath, { flags: 'wx', mode: manifestEntry.mode }), + { signal }, ); } diff --git a/packages/host-kit/src/internal/archive-safety.ts b/packages/host-kit/src/internal/archive-safety.ts index 01324e34bd..1a400e244b 100644 --- a/packages/host-kit/src/internal/archive-safety.ts +++ b/packages/host-kit/src/internal/archive-safety.ts @@ -201,16 +201,23 @@ export function extractedEntryMode( * Creates one directory entry with its own mode. Parents an archive never declared are created * with the default mode. Whether the directory is new or an earlier entry already implied it, it * ends up with the declared mode under the process umask, as the kernel applies to files, so entry - * order does not change the extracted permissions. + * order does not change the extracted permissions. A given signal is checked between the + * directory mutations. */ -export async function createExtractedDirectory(outputPath: string, mode: number): Promise { +export async function createExtractedDirectory( + outputPath: string, + mode: number, + signal?: AbortSignal, +): Promise { await fs.mkdir(path.dirname(outputPath), { recursive: true }); + signal?.throwIfAborted(); try { await fs.mkdir(outputPath); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; if (!(await fs.lstat(outputPath)).isDirectory()) throw error; } + signal?.throwIfAborted(); await fs.chmod(outputPath, (mode & ~process.umask()) | OWNER_ENTRY_ACCESS.directory); } diff --git a/packages/host-kit/src/internal/transport.test.ts b/packages/host-kit/src/internal/transport.test.ts index 0cc966a8a8..51dfd5420b 100644 --- a/packages/host-kit/src/internal/transport.test.ts +++ b/packages/host-kit/src/internal/transport.test.ts @@ -54,18 +54,19 @@ test('readNodeHttpResponseBody decodes the complete response stream', async () = }); test('readNodeHttpRequestBody returns bytes and preserves the caller error message at the limit', async () => { - const request = Readable.from([ - Buffer.from('hello '), - Buffer.from('world'), - ]) as unknown as IncomingMessage; + const request = bodyRequest([Buffer.from('hello '), Buffer.alloc(0), Buffer.from('world')]); + const accepted: number[] = []; + const onAcceptedBytes = (bytes: number) => accepted.push(bytes); assert.deepEqual( - await readNodeHttpRequestBody(request, 11, 'body exceeded'), + await readNodeHttpRequestBody(request, 11, 'body exceeded', onAcceptedBytes), Buffer.from('hello world'), ); + assert.deepEqual(accepted, [6, 5]); - const oversized = Readable.from([Buffer.from('hello world!')]) as unknown as IncomingMessage; + const oversized = bodyRequest([Buffer.from('hello '), Buffer.from('world!')]); + accepted.length = 0; await assert.rejects( - readNodeHttpRequestBody(oversized, 11, 'body exceeded'), + readNodeHttpRequestBody(oversized, 11, 'body exceeded', onAcceptedBytes), (error: unknown) => { assert.ok(error instanceof AppError); assert.equal(error.code, 'INVALID_ARGS'); @@ -73,8 +74,24 @@ test('readNodeHttpRequestBody returns bytes and preserves the caller error messa return true; }, ); + assert.deepEqual(accepted, [6]); + // The refusal leaves the request intact for its response owner to end. + assert.equal((oversized as unknown as Readable).destroyed, false); }); +test('readNodeHttpRequestBody refuses a declared length over the bound before reading', async () => { + const declared = bodyRequest([Buffer.from('ok')], { 'content-length': '12' }); + await assert.rejects( + readNodeHttpRequestBody(declared, 11, 'body exceeded'), + (error: unknown) => error instanceof AppError && error.message === 'body exceeded', + ); + assert.equal(declared.readableEnded, false, 'no byte was read'); +}); + +function bodyRequest(chunks: Buffer[], headers: Record = {}): IncomingMessage { + return Object.assign(Readable.from(chunks), { headers }) as unknown as IncomingMessage; +} + test('timingSafeStringEqual handles equal, unequal, and unequal-length secrets', () => { assert.equal(timingSafeStringEqual('secret', 'secret'), true); assert.equal(timingSafeStringEqual('secret', 'secreT'), false); diff --git a/packages/host-kit/src/internal/transport.ts b/packages/host-kit/src/internal/transport.ts index 165236b05e..99ba9455d2 100644 --- a/packages/host-kit/src/internal/transport.ts +++ b/packages/host-kit/src/internal/transport.ts @@ -60,20 +60,32 @@ export function readNodeHttpResponseBody( }); } +/** + * Reads a bounded request body. A declared length over the bound is refused before any + * byte is read. A refusal leaves the request intact (`destroyOnReturn: false`): destroying + * it would detach its socket and reset a client that is still sending, so the caller's + * response owner answers and decides how the connection ends. + */ export async function readNodeHttpRequestBody( req: IncomingMessage, maxBodyBytes: number, tooLargeMessage: string, + onAcceptedBytes?: (bytes: number) => void, ): Promise { + const declaredLength = Number(req.headers['content-length']); + if (Number.isFinite(declaredLength) && declaredLength > maxBodyBytes) { + throw new AppError('INVALID_ARGS', tooLargeMessage); + } const chunks: Buffer[] = []; let bodyBytes = 0; - for await (const chunk of req) { + for await (const chunk of req.iterator({ destroyOnReturn: false })) { const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); bodyBytes += buffer.length; if (bodyBytes > maxBodyBytes) { throw new AppError('INVALID_ARGS', tooLargeMessage); } chunks.push(buffer); + if (buffer.length > 0) onAcceptedBytes?.(buffer.length); } return Buffer.concat(chunks); } diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 268b705ff1..9e3a316a25 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -100,7 +100,7 @@ "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", - "packages/daemon/src/server/http/http-authorization.ts#HttpAuthHookContext": "sha256:c555532dcc31c106d893445d2cff01ad6c5e5b3390b86fad982385059ec69663", + "packages/daemon/src/server/http/http-authorization.ts#HttpAuthHookContext": "sha256:f6b0b0ff2db474168b53af51994c81d32459b5010f643c965eba66f3ca89b737", "packages/daemon/src/server/http/http-authorization.ts#HttpAuthHookResult": "sha256:d52c3f14ff05da925a8efc53b9eac4538826ba615ab9fc073eeed4f3df678086", "packages/daemon/src/server/http/http-rpc-methods.ts#INSTALL_FROM_SOURCE_RPC_METHODS": "sha256:d0dc3f3d872e7384343e28aaaf2b57e0da822e654a2e345fb108d160f520c16d", "packages/daemon/src/server/http/http-rpc-envelope.ts#JsonRpcRequest": "sha256:7c299fe17818993a0bacbb48e12dcd1fd28b3595cf8efcae3484acbec383ce22", @@ -110,7 +110,7 @@ "packages/contracts/src/daemon-http.ts#DAEMON_REQUEST_MAX_BYTES": "sha256:4348e1d7a6d025d6d75fddf075e52fe0555ce7c7b69b4dd4d64dc28ce1f73a87", "packages/daemon/src/server/http/http-rpc-methods.ts#RELEASE_MATERIALIZED_PATHS_RPC_METHODS": "sha256:75a18d3496894309dd6042b16c4dcc241c16ec6336783e6310eddd6db7437ccb", "packages/daemon/src/server/http/http-rpc-methods.ts#SUPPORTED_RPC_METHODS": "sha256:4d5ed730dcb669b0dacca3bb4977f35686bab9b7fb464c0590fd50f838e6c243", - "packages/daemon/src/server/http/http-authorization.ts#authorizeAuxiliaryHttpRequest": "sha256:1c323f97c3cefec8f95633b6abd127342bf75494bfb109d1cc6eadf3ceacaeae", + "packages/daemon/src/server/http/http-authorization.ts#authorizeAuxiliaryHttpRequest": "sha256:be2f3a9965bb6fe456ab8b1f0a696cf80ffcc8016262a4aee28dee25d18650d0", "packages/daemon/src/server/http/http-rpc-envelope.ts#createRpcError": "sha256:1921762129636afc7772937d48e8afb8f09047b343e3a27d18b49c1c4385bbe8", "packages/daemon/src/server/http/http-authorization.ts#enforceDaemonToken": "sha256:60036cffc34388b33fc0dad39c905d9cb3fc18c9ed0cf24255bb7105f5d444c7", "packages/daemon/src/server/http/http-rpc-methods.ts#isCommandRpcMethod": "sha256:9922102ba9c72c3032f205717d772ab7c3506c6f3012f55b8e7e5636b672ed7e", @@ -128,16 +128,16 @@ "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:6521ffa355c57af97bfc8095699f2a2b38745a6ef8d61a34c8cfc80ee690b6b5", + "packages/daemon/src/server/upload-http.ts#AuxiliaryHttpAuthorizer": "sha256:939b227d303574f90d59f01dd1bcb99eec7c5831b8e40dc5a6412be62c673e7e", "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:b1e1cfd79f13470a1111a377b87975ed5c721500d99f3160a8b631194af37ce5", - "packages/daemon/src/server/upload-http.ts#handleUpload": "sha256:bba7347a32f53b265cded1c7d73f943431ba3b5a0c8b347d621266ea20c10cd6", - "packages/daemon/src/server/upload-http.ts#handleUploadFinalize": "sha256:f6879ce6b62d916265d98f6b6aa5f99650c82a9d391a7d5873015036d9289a24", - "packages/daemon/src/server/upload-http.ts#handleUploadPreflight": "sha256:8f9915c23fbf86903bee4db02e1b45aa835bc4d234c8e9a0fe4da5e67da8163e", + "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#readUploadFinalizeBody": "sha256:076298afa73d7e498a964b6c48d823de1cc8b15e9e971d0a22b7e6c3fd98d685", "packages/daemon/src/server/upload-http.ts#readUploadPreflightBody": "sha256:2e56302178b75d9a6f5424f01dfc46551dca2056ba06a43e48ae09ec528956b6", "packages/contracts/src/daemon-http.ts#resolveHttpRequestBaseUrl": "sha256:6ef76a849a7c61c7ae035cbf162dd1dfac3631f6a2df421560f19f798853e50f", @@ -146,7 +146,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:9e418403448d58a96284fed605762fa71f9349bf2c70ad79df69b2b3e27487d6", + "packages/daemon/src/server/upload-http.ts#sendUploadedArtifactResponse": "sha256:8a8873eb6437a32f7045c87a7b16226a48ff7fc4d61c5de459809e2558758768", "packages/remote/src/artifact-download.ts#RemoteArtifactDownload": "sha256:e87a625bdff05fa55f6321ff09a35496f59edd228a1d7420268d54fcc2982868", "packages/remote/src/artifact-download.ts#downloadRemoteArtifactFromUrl": "sha256:68a4237fd5bc884d90443fb197b84f8500e44e9a32c08fbcbeb74d26c1e896a9", "packages/remote/src/daemon-artifacts.ts#DaemonArtifactEndpoint": "sha256:45226717ac52c0af2a62f74e91549582d95f4a4abc49be87989e026291a88c82", @@ -217,7 +217,8 @@ "packages/remote/src/script-version-publisher.ts#publishScriptVersion": "sha256:d4fb07e7b2035bbe10e84948232343c9cfc2cb4ce7b6a113f7a1021a4c636243", "packages/remote/src/script-version-publisher.ts#PublishOutcome": "sha256:52c7d164a1150bfdfa5636ca3b1938e9bfc818848545d0a3e89c42a9c3f9f061", "packages/remote/src/session-script-destination.ts#sendRemoteScriptOpen": "sha256:10ab07a6f276c7b03996c6b46fa218e03e7b1d21e2c95df5515dfb88095416b6", - "packages/remote/src/session-script-destination.ts#RemoteEndpoint": "sha256:9c48e8e0ee14a25b85ebd930243fd263134836b35ecda55fb927919911263c15" + "packages/remote/src/session-script-destination.ts#RemoteEndpoint": "sha256:9c48e8e0ee14a25b85ebd930243fd263134836b35ecda55fb927919911263c15", + "packages/daemon/src/server/upload-http.ts#authorizeUpload": "sha256:69ee5039c7eadbe0f96cdf57bcd947b16cdc815671ba4c966ace93ad353cc740" }, "compatibleChanges": [ { @@ -312,8 +313,8 @@ }, { "declaration": "packages/daemon/src/server/http/http-authorization.ts#authorizeAuxiliaryHttpRequest", - "digest": "sha256:1c323f97c3cefec8f95633b6abd127342bf75494bfb109d1cc6eadf3ceacaeae", - "rationale": "#2198 context: adds one optional field to the value this DAEMON-INTERNAL gate hands its own route handlers — sessionNamespace, the caller's tenant plus whether the daemon partitioned that caller's session names. Nothing about it is serialized: no request header is read that was not read before, no response field is added, and a refusal keeps the same 401 {ok:false,error,code} REST body sendRestJsonError already sent. What it enables is a refusal DROPPED, never one added — an unattested (client-declared) tenant no longer has the : prefix rule applied to it, because scopeRequestSession never applied that prefix to its sessions either. A released peer that now gets 200 where it got 401 is getting the ndjson record it asked for and already parses." + "digest": "sha256:be2f3a9965bb6fe456ab8b1f0a696cf80ffcc8016262a4aee28dee25d18650d0", + "rationale": "#2198 context: adds one optional field to the value this DAEMON-INTERNAL gate hands its own route handlers — sessionNamespace, the caller's tenant plus whether the daemon partitioned that caller's session names. Nothing about it is serialized: no request header is read that was not read before, no response field is added, and a refusal keeps the same 401 {ok:false,error,code} REST body sendRestJsonError already sent. What it enables is a refusal DROPPED, never one added — an unattested (client-declared) tenant no longer has the : prefix rule applied to it, because scopeRequestSession never applied that prefix to its sessions either. A released peer that now gets 200 where it got 401 is getting the ndjson record it asked for and already parses. 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. 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/request-diagnostics-http.ts#RequestDiagnosticsHttpAuthorizer", @@ -572,8 +573,28 @@ }, { "declaration": "packages/daemon/src/server/upload-http.ts#handleUploadPreflight", - "digest": "sha256:8f9915c23fbf86903bee4db02e1b45aa835bc4d234c8e9a0fe4da5e67da8163e", - "rationale": "#4434 passes the origin validated by the HTTP ingress owner, or the explicitly configured publicOrigin, into the existing ticket producer. Protocol-2 clients receive the same uploadId and upload URL/header object, use the returned absolute URL, and keep the existing byte, range, authentication and finalize contracts. Forwarding headers no longer select authority under the documented operator migration; no wire field becomes required or changes interpretation." + "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", @@ -584,6 +605,21 @@ "declaration": "packages/remote/src/artifact-download.ts#RemoteArtifactDownload", "digest": "sha256:e87a625bdff05fa55f6321ff09a35496f59edd228a1d7420268d54fcc2982868", "rationale": "#4511 adds the optional client-local privateFile field: the download creates a new 0600 file exclusively, never through a symbolic link, and stops once it crosses maxBytes. It is never sent, and every existing call site omits it, so the GET /artifacts/:id framing is unchanged." + }, + { + "declaration": "packages/daemon/src/server/http/http-authorization.ts#HttpAuthHookContext", + "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." } ] } diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index 0c6eff1148..3def47f48a 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -197,7 +197,14 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'enforceDaemonToken', 'authorizeAuxiliaryHttpRequest', ), - ...from(UPLOAD_HTTP, 'AuxiliaryHttpAuthorizer', 'buildUploadTicketAuthHeaders'), + // Every upload route authorizes through authorizeUpload: it names the command the + // auth hook sees, and each route names its positionals. + ...from( + UPLOAD_HTTP, + 'AuxiliaryHttpAuthorizer', + 'buildUploadTicketAuthHeaders', + 'authorizeUpload', + ), ...from(ARTIFACT_HTTP, 'DownloadableArtifactHttpAuthorizer'), // The diagnostics route's authorization: the same token/auth-hook gate as // the artifact routes, plus the tenant rule that decides which sessions a diff --git a/website/docs/docs/security-trust.md b/website/docs/docs/security-trust.md index 55b82e65aa..c53335c7a9 100644 --- a/website/docs/docs/security-trust.md +++ b/website/docs/docs/security-trust.md @@ -21,7 +21,7 @@ CLI commands run through a per-user background daemon: - Artifact uploads are size-capped, filenames are sanitized, and archive extraction rejects path-traversal entries. 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. +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 the upload routes, the hook context carries a `signal` that aborts when the upload request times out or its client disconnects. 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. Lease-owner human-control RPCs pass normal authentication and tenant/lease admission. They can target only the admitted lease's device and cannot alter a host administrator's hold. Host