From 2f776863c2a36bc8e5ec3b60d1ee9487987e3528 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 09:49:24 +0000 Subject: [PATCH 01/19] feat(selfhost): SAM-signed box object URLs for uploads without store keys Box-only PUT/GET /api/box-objects streams into the R2 binding with a short-lived SAM-signed token (HKDF from ENCRYPTION_KEY). One URL-signer seam: hosted keeps R2 presign byte-identical; a keyless box gets box URLs. Concurrency gate DO bounds celld memory. Missing signer is a 503. Co-Authored-By: Claude Opus 5.5 --- .../compose-image-artifacts-callback.ts | 4 +- apps/api/src/routes/tasks/upload.ts | 12 +- apps/api/src/selfhost/build.ts | 7 +- apps/api/src/selfhost/hosted-git/tokens.ts | 80 +-------- apps/api/src/selfhost/object-urls/gate.ts | 81 +++++++++ apps/api/src/selfhost/object-urls/index.ts | 33 ++++ apps/api/src/selfhost/object-urls/route.ts | 156 ++++++++++++++++++ apps/api/src/selfhost/object-urls/settings.ts | 44 +++++ apps/api/src/selfhost/object-urls/signer.ts | 66 ++++++++ apps/api/src/selfhost/object-urls/tokens.ts | 152 +++++++++++++++++ apps/api/src/selfhost/signed-token.ts | 139 ++++++++++++++++ apps/api/src/services/attachment-upload.ts | 28 ++-- apps/api/src/services/build-context-upload.ts | 12 +- .../src/services/compose-image-artifacts.ts | 13 +- apps/api/src/services/r2-s3-client.ts | 50 ++++++ .../unit/services/attachment-upload.test.ts | 4 +- .../src/build-context-upload.ts | 40 ++--- .../src/compose-image-artifacts.ts | 54 +++--- packages/app-deployment/src/index.ts | 8 +- .../app-deployment/src/object-url-signer.ts | 87 ++++++++++ .../tests/unit/build-context-presign.test.ts | 14 +- scripts/selfhost/selfhost-durable-objects.ts | 11 +- .../2026-11-23-selfhost-box-object-uploads.md | 91 ++++++++++ 23 files changed, 1011 insertions(+), 175 deletions(-) create mode 100644 apps/api/src/selfhost/object-urls/gate.ts create mode 100644 apps/api/src/selfhost/object-urls/index.ts create mode 100644 apps/api/src/selfhost/object-urls/route.ts create mode 100644 apps/api/src/selfhost/object-urls/settings.ts create mode 100644 apps/api/src/selfhost/object-urls/signer.ts create mode 100644 apps/api/src/selfhost/object-urls/tokens.ts create mode 100644 apps/api/src/selfhost/signed-token.ts create mode 100644 packages/app-deployment/src/object-url-signer.ts create mode 100644 tasks/active/2026-11-23-selfhost-box-object-uploads.md diff --git a/apps/api/src/routes/projects/compose-image-artifacts-callback.ts b/apps/api/src/routes/projects/compose-image-artifacts-callback.ts index 317d66a0b4..95de897b82 100644 --- a/apps/api/src/routes/projects/compose-image-artifacts-callback.ts +++ b/apps/api/src/routes/projects/compose-image-artifacts-callback.ts @@ -168,7 +168,9 @@ composeImageArtifactsCallbackRoute.post('/:id/compose-image-artifacts/init', asy return c.json({ uploadId, - maxBytes: getComposeImageArtifactMaxBytes(c.env), + // Every slot carries the same bound: the configured maximum, lowered on a self-hosted box to + // what one request through it can carry (composeImageArtifactMaxBytesFor). + maxBytes: uploads[0]?.maxBytes ?? getComposeImageArtifactMaxBytes(c.env), uploads, }); }); diff --git a/apps/api/src/routes/tasks/upload.ts b/apps/api/src/routes/tasks/upload.ts index 5c186f66b3..eb7b405818 100644 --- a/apps/api/src/routes/tasks/upload.ts +++ b/apps/api/src/routes/tasks/upload.ts @@ -23,7 +23,7 @@ import { errors } from '../../middleware/error'; import { requireProjectCapability } from '../../middleware/project-auth'; import { jsonValidator, RequestAttachmentUploadSchema } from '../../schemas'; import { generatePresignedUploadUrl } from '../../services/attachment-upload'; -import { hasR2S3Credentials } from '../../services/r2-s3-client'; +import { resolveR2ObjectUrlSigner } from '../../services/r2-s3-client'; const uploadRoutes = new Hono<{ Bindings: Env }>(); @@ -51,8 +51,10 @@ uploadRoutes.post('/request-upload', requireAuth(), requireApproved(), jsonValid // Validate project ownership await requireProjectCapability(db, projectId, userId, 'task:write'); - // Check presigning is configured (Cloudflare R2 or an operator store; one shared check) - if (!hasR2S3Credentials(c.env)) { + // Uploads need a URL signer: R2 presign (Cloudflare or an operator store with a key), or a + // self-hosted box's own upload route. The same resolver mints the URL below. + const signer = resolveR2ObjectUrlSigner(c.env); + if (!signer) { throw errors.forbidden('File attachments are not configured (R2 S3 credentials missing)'); } @@ -69,9 +71,11 @@ uploadRoutes.post('/request-upload', requireAuth(), requireApproved(), jsonValid } // Validate file size limit - const maxBytes = c.env.ATTACHMENT_UPLOAD_MAX_BYTES + const configuredMaxBytes = c.env.ATTACHMENT_UPLOAD_MAX_BYTES ? parseInt(c.env.ATTACHMENT_UPLOAD_MAX_BYTES, 10) : ATTACHMENT_DEFAULTS.UPLOAD_MAX_BYTES; + // A box carries at most signer.maxPutBytes per request. + const maxBytes = Math.min(configuredMaxBytes, signer.maxPutBytes ?? configuredMaxBytes); if (body.size > maxBytes) { throw errors.badRequest(`File size ${body.size} exceeds maximum ${maxBytes} bytes`); } diff --git a/apps/api/src/selfhost/build.ts b/apps/api/src/selfhost/build.ts index b35ed307f6..623edd4aac 100644 --- a/apps/api/src/selfhost/build.ts +++ b/apps/api/src/selfhost/build.ts @@ -9,7 +9,8 @@ * with its `analytics.d1.*` retention settings; * - the reverse-tunnel transport, gateway routes and lease sweep (`reverse-tunnel/entry.ts`), * with the shared cloud-init generator as the frpc boot renderer; - * - the box's own DNS zone when SAM_DNS_PROVIDER="box" (`dns/`, served by deploy/selfhost/sam-dns). + * - the box's own DNS zone when SAM_DNS_PROVIDER="box" (`dns/`, served by deploy/selfhost/sam-dns); + * - uploads and downloads through the box when no static store key is configured (`object-urls/`). */ import { generateCloudInit } from '@simple-agent-manager/cloud-init'; import type { Hono } from 'hono'; @@ -19,9 +20,11 @@ import { mountHostedGitRoute } from './hosted-git'; import { hostedGitTokenRoutes } from './hosted-git/token-route'; export { HostedGitRepo } from './hosted-git'; +export { BoxUploadGate } from './object-urls'; import { installAnalyticsD1Sink } from './analytics'; import { installBoxDns } from './dns'; +import { installBoxObjectUrls, mountBoxObjectRoute } from './object-urls'; import { type SharedWorkerEntry, withReverseTunnel } from './reverse-tunnel/entry'; import { installSpeechEndpoints } from './speech'; @@ -34,10 +37,12 @@ export function withSelfHostBuild( if (!mounted.has(app)) { mountHostedGitRoute(app); app.route('/api/projects', hostedGitTokenRoutes); + mountBoxObjectRoute(app); mounted.add(app); } installSpeechEndpoints(); installAnalyticsD1Sink(); installBoxDns(); + installBoxObjectUrls(); return withReverseTunnel(worker, generateCloudInit); } diff --git a/apps/api/src/selfhost/hosted-git/tokens.ts b/apps/api/src/selfhost/hosted-git/tokens.ts index cfd36fae7c..cccca5562c 100644 --- a/apps/api/src/selfhost/hosted-git/tokens.ts +++ b/apps/api/src/selfhost/hosted-git/tokens.ts @@ -12,6 +12,7 @@ * project, that the user is still an active member, and that a workspace-bound token's workspace * is still active on its current runtime (callback generation). */ +import { mintSignedToken, type SignedTokenPurpose, verifySignedToken } from '../signed-token'; import type { HostedGitEnv as Env } from './env'; export type HostedGitScope = 'read' | 'write'; @@ -40,56 +41,12 @@ export const MAX_HOSTED_GIT_TOKEN_TTL_SECONDS = 86_400; /** Repository names SAM generates (toArtifactsRepoName): lowercase, digits, dashes. */ const REPO_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,127}$/; -const encoder = new TextEncoder(); -const decoder = new TextDecoder(); +const PURPOSE: SignedTokenPurpose = { prefix: TOKEN_PREFIX, label: KEY_LABEL }; export function isHostedGitRepoName(name: string): boolean { return REPO_NAME_PATTERN.test(name); } -function base64UrlEncode(bytes: Uint8Array): string { - let binary = ''; - for (const byte of bytes) binary += String.fromCharCode(byte); - return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); -} - -function base64UrlDecode(value: string): Uint8Array | null { - if (!/^[A-Za-z0-9_-]+$/.test(value)) return null; - try { - const padded = - value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - (value.length % 4)) % 4); - return Uint8Array.from(atob(padded), (character) => character.charCodeAt(0)); - } catch { - return null; - } -} - -/** - * The derived key, cached once derived. Only a finished key is shared: a request never waits on a - * derivation another request started, which on the self-hosted celld runtime could be dropped - * with that request (lib/shared-flight.ts). Concurrent cold callers each derive once (one HKDF). - */ -let cachedKey: { secret: string; key: CryptoKey } | null = null; - -/** HKDF-SHA256 from ENCRYPTION_KEY with a purpose label; no other use shares this key. */ -async function signingKey(env: Pick): Promise { - const secret = env.ENCRYPTION_KEY; - if (!secret) throw new Error('ENCRYPTION_KEY is required for SAM-hosted repositories'); - if (cachedKey?.secret === secret) return cachedKey.key; - const root = await crypto.subtle.importKey('raw', encoder.encode(secret), 'HKDF', false, [ - 'deriveKey', - ]); - const key = await crypto.subtle.deriveKey( - { name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: encoder.encode(KEY_LABEL) }, - root, - { name: 'HMAC', hash: 'SHA-256', length: 256 }, - false, - ['sign', 'verify'] - ); - cachedKey = { secret, key }; - return key; -} - export function clampHostedGitTokenTtl(ttlSeconds: number | undefined): number { if (ttlSeconds === undefined || !Number.isFinite(ttlSeconds) || ttlSeconds <= 0) { return DEFAULT_HOSTED_GIT_TOKEN_TTL_SECONDS; @@ -117,15 +74,8 @@ export async function mintHostedGitToken( claims.callbackGeneration = input.callbackGeneration ?? null; } if (input.userId) claims.userId = input.userId; - const payload = base64UrlEncode(encoder.encode(JSON.stringify(claims))); - const unsigned = `${TOKEN_PREFIX}.${payload}`; - const signature = await crypto.subtle.sign( - 'HMAC', - await signingKey(env), - encoder.encode(unsigned) - ); return { - token: `${unsigned}.${base64UrlEncode(new Uint8Array(signature))}`, + token: await mintSignedToken(env, PURPOSE, claims), expiresAt: new Date(exp * 1000).toISOString(), }; } @@ -136,28 +86,8 @@ export async function verifyHostedGitToken( token: string, now: number = Date.now() ): Promise { - if (token.length > 2048) return null; - const parts = token.split('.'); - if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) return null; - const [prefix, payload, signaturePart] = parts as [string, string, string]; - const signature = base64UrlDecode(signaturePart); - const payloadBytes = base64UrlDecode(payload); - if (!signature || !payloadBytes) return null; - const valid = await crypto.subtle.verify( - 'HMAC', - await signingKey(env), - signature, - encoder.encode(`${prefix}.${payload}`) - ); - if (!valid) return null; - let parsed: unknown; - try { - parsed = JSON.parse(decoder.decode(payloadBytes)); - } catch { - return null; - } - if (!parsed || typeof parsed !== 'object') return null; - const claims = parsed as Record; + const claims = await verifySignedToken(env, PURPOSE, token); + if (!claims) return null; if (typeof claims.repo !== 'string' || !isHostedGitRepoName(claims.repo)) return null; if (claims.scope !== 'read' && claims.scope !== 'write') return null; if (typeof claims.exp !== 'number' || claims.exp * 1000 <= now) return null; diff --git a/apps/api/src/selfhost/object-urls/gate.ts b/apps/api/src/selfhost/object-urls/gate.ts new file mode 100644 index 0000000000..29f10be3f5 --- /dev/null +++ b/apps/api/src/selfhost/object-urls/gate.ts @@ -0,0 +1,81 @@ +/** + * The box-wide limit on concurrent object uploads (`BoxUploadGate`, one instance per box). + * + * Why a limit: celld streams an upload into the R2 binding without holding it in the isolate, but + * every in-flight upload still costs process memory. Measured on celld v0.6.3 with 1 GB bodies + * (task tasks/active/2026-11-23-selfhost-box-object-uploads.md): peak RSS 220 MB for one upload, + * 284 / 427 / 896 MB for 2 / 4 / 8 at once, so roughly 85 MB per upload over a ~150 MB base, while + * aggregate throughput stops growing after two (~180 MB/s). The default of 4 keeps the peak near + * 430 MB. An upload over the limit is refused with 503 and Retry-After rather than queued. + * + * Why a Durable Object: the limit must hold across every Worker isolate celld runs, and a single + * object is the box's one serialization point. Each acquire is a lease with an expiry, so a handler + * that dies without releasing (celld restart, a killed isolate) frees its slot when the lease ends + * instead of holding it forever. `acquire` and `release` do all their work in synchronous SQL with + * no `await`, so two calls cannot interleave inside one (rule 45). + */ +import { DurableObject } from 'cloudflare:workers'; + +export interface BoxUploadGateEnv { + BOX_UPLOAD_GATE?: DurableObjectNamespace; +} + +export type BoxUploadLease = + | { granted: true } + | { granted: false; active: number; retryAfterSeconds: number }; + +/** Shortest and longest Retry-After hint (seconds) a refusal suggests. */ +const MIN_RETRY_AFTER_SECONDS = 5; +const MAX_RETRY_AFTER_SECONDS = 60; + +export class BoxUploadGate extends DurableObject { + constructor(ctx: DurableObjectState, env: unknown) { + super(ctx, env as never); + ctx.storage.sql.exec( + 'CREATE TABLE IF NOT EXISTS upload_leases (id TEXT PRIMARY KEY, expires_at INTEGER NOT NULL)' + ); + } + + /** Grants a lease to `id` while fewer than `limit` unexpired leases exist. */ + acquire(id: string, limit: number, leaseMs: number, now: number = Date.now()): BoxUploadLease { + const sql = this.ctx.storage.sql; + sql.exec('DELETE FROM upload_leases WHERE expires_at <= ?', now); + const row = sql.exec<{ active: number; next: number | null }>( + 'SELECT COUNT(*) AS active, MIN(expires_at) AS next FROM upload_leases' + ).one(); + if (row.active >= limit) { + // A hint, not a promise: most leases end when their upload finishes, long before expiry. + const untilExpiry = Math.ceil(((row.next ?? now) - now) / 1000); + const retryAfterSeconds = Math.min( + MAX_RETRY_AFTER_SECONDS, + Math.max(MIN_RETRY_AFTER_SECONDS, untilExpiry) + ); + return { granted: false, active: row.active, retryAfterSeconds }; + } + sql.exec( + 'INSERT OR REPLACE INTO upload_leases (id, expires_at) VALUES (?, ?)', + id, + now + leaseMs + ); + return { granted: true }; + } + + release(id: string): void { + this.ctx.storage.sql.exec('DELETE FROM upload_leases WHERE id = ?', id); + } +} + +/** The box's one gate instance. */ +export const BOX_UPLOAD_GATE_NAME = 'box'; + +interface BoxUploadGateStub { + acquire(id: string, limit: number, leaseMs: number): Promise; + release(id: string): Promise; +} + +export function boxUploadGate(env: BoxUploadGateEnv): BoxUploadGateStub | null { + const namespace = env.BOX_UPLOAD_GATE; + if (!namespace) return null; + // Typed RPC stub: Cloudflare's generated stub type cannot express this class's methods. + return namespace.get(namespace.idFromName(BOX_UPLOAD_GATE_NAME)) as unknown as BoxUploadGateStub; +} diff --git a/apps/api/src/selfhost/object-urls/index.ts b/apps/api/src/selfhost/object-urls/index.ts new file mode 100644 index 0000000000..acac5f73a4 --- /dev/null +++ b/apps/api/src/selfhost/object-urls/index.ts @@ -0,0 +1,33 @@ +/** + * Box object URLs for the self-host build: uploads and downloads that go through the box instead + * of S3 presigned URLs, for a box with no static store key (task + * tasks/active/2026-11-23-selfhost-box-object-uploads.md). + * + * Only `selfhost/build.ts` imports this module, so the Cloudflare bundle carries none of it and + * keeps minting R2 presigned URLs (tests/unit/selfhost/selfhost-only-modules.test.ts). + */ +import type { Hono } from 'hono'; + +import type { Env } from '../../env'; +import { installAdminSettingDefinitions } from '../../services/admin-settings-registry'; +import { installBoxObjectUrlSigner } from '../../services/r2-s3-client'; +import { handleBoxObjectRequest } from './route'; +import { BOX_OBJECT_SETTINGS } from './settings'; +import { BOX_OBJECT_ROUTE, createBoxObjectUrlSigner } from './signer'; + +export { BoxUploadGate } from './gate'; + +/** Registers the signer and settings (idempotent). */ +export function installBoxObjectUrls(): void { + installAdminSettingDefinitions(BOX_OBJECT_SETTINGS); + installBoxObjectUrlSigner(createBoxObjectUrlSigner); +} + +/** + * Mounts the route. Call once, after `src/index.ts` registered the shared routes: like hosted git's + * route, it then runs after exactly the global middleware (request logging, CORS) and no + * session-auth middleware, which it must not have (the token is the credential). + */ +export function mountBoxObjectRoute(app: Hono<{ Bindings: Env }>): void { + app.on(['PUT', 'GET'], BOX_OBJECT_ROUTE, (c) => handleBoxObjectRequest(c)); +} diff --git a/apps/api/src/selfhost/object-urls/route.ts b/apps/api/src/selfhost/object-urls/route.ts new file mode 100644 index 0000000000..91a07aac67 --- /dev/null +++ b/apps/api/src/selfhost/object-urls/route.ts @@ -0,0 +1,156 @@ +/** + * `PUT|GET /api/box-objects?token=...`: the self-hosted box's stand-in for S3 presigned URLs. + * + * The token (`tokens.ts`) names one R2 key and one operation; nothing in the request can name + * another. A PUT streams the body into the R2 binding (celld writes it to the fleet bucket without + * holding it in the isolate), bounded by the token's size and verified against its sha256 when it + * carries one. The write is create-only (`onlyIf: { etagDoesNotMatch: '*' }`), so a token cannot + * replace an object once written; a retry of a write that already succeeded answers 200 when the + * stored object is the one the token describes. + * + * No SAM session or callback credential is involved: the token is the credential, minted only by + * routes that already authorized the caller for that key. + */ +import type { Context } from 'hono'; + +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { resolveAdminSettingDetailsMany } from '../../services/admin-settings-resolution'; +import { boxUploadGate, type BoxUploadGateEnv } from './gate'; +import { + BOX_OBJECT_MAX_CONCURRENT_UPLOADS, + BOX_OBJECT_UPLOAD_LEASE_SECONDS, + DEFAULT_BOX_OBJECT_MAX_CONCURRENT_UPLOADS, + DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS, +} from './settings'; +import { type BoxObjectTokenClaims, verifyBoxObjectToken } from './tokens'; + +type BoxObjectEnv = Env & BoxUploadGateEnv; + +function plain(status: number, message: string, headers: Record = {}): Response { + return Response.json({ error: status === 503 ? 'BUSY' : 'BOX_OBJECT_REFUSED', message }, { + status, + headers, + }); +} + +/** Log fields that identify the request without the token. */ +function logFields(claims: BoxObjectTokenClaims) { + return { op: claims.op, key: claims.key, ...claims.sub }; +} + +async function uploadLimits(env: Env): Promise<{ limit: number; leaseMs: number }> { + try { + const [limit, lease] = await resolveAdminSettingDetailsMany(env, [ + BOX_OBJECT_MAX_CONCURRENT_UPLOADS, + BOX_OBJECT_UPLOAD_LEASE_SECONDS, + ]); + return { limit: Number(limit?.value), leaseMs: Number(lease?.value) * 1000 }; + } catch { + // Settings storage unavailable: the defaults still bound memory. + return { + limit: DEFAULT_BOX_OBJECT_MAX_CONCURRENT_UPLOADS, + leaseMs: DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS * 1000, + }; + } +} + +/** True when the stored object is the one `claims` describes (a retried, already-finished PUT). */ +async function sameObject(env: Env, claims: BoxObjectTokenClaims, length: number) { + const existing = await env.R2.head(claims.key); + if (!existing || existing.size !== length) return false; + if (!claims.sha) return true; + const stored = existing.checksums?.sha256; + const storedHex = stored + ? [...new Uint8Array(stored)].map((byte) => byte.toString(16).padStart(2, '0')).join('') + : existing.customMetadata?.sha256; + return storedHex === claims.sha; +} + +async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectTokenClaims) { + const env = c.env; + const length = Number(c.req.header('content-length')); + const body = c.req.raw.body; + if (!c.req.header('content-length') || !Number.isSafeInteger(length) || length < 0) { + return plain(411, 'Content-Length is required'); + } + if (claims.max !== undefined && length > claims.max) { + return plain(413, `Upload is ${length} bytes; this URL accepts at most ${claims.max}`); + } + if (claims.len !== undefined && length !== claims.len) { + return plain(400, `Upload is ${length} bytes; this URL was issued for ${claims.len}`); + } + if (!body && length > 0) return plain(400, 'Upload body is missing'); + + const gate = boxUploadGate(env); + if (!gate) return plain(503, 'Box uploads are unavailable (no upload gate binding)'); + const { limit, leaseMs } = await uploadLimits(env); + const leaseId = crypto.randomUUID(); + const lease = await gate.acquire(leaseId, limit, leaseMs); + if (!lease.granted) { + log.warn('box_objects.upload_refused_busy', { ...logFields(claims), active: lease.active, limit }); + return plain(503, `The box is already receiving ${lease.active} uploads; retry shortly`, { + 'Retry-After': String(lease.retryAfterSeconds), + }); + } + try { + // FixedLengthStream makes a short or long body an error instead of a truncated object. + const stream = body ? body.pipeThrough(new FixedLengthStream(length)) : new Uint8Array(0); + let written: R2Object | null; + try { + written = await env.R2.put(claims.key, stream, { + onlyIf: { etagDoesNotMatch: '*' }, + ...(claims.ct ? { httpMetadata: { contentType: claims.ct } } : {}), + ...(claims.md ? { customMetadata: claims.md } : {}), + ...(claims.sha ? { sha256: claims.sha } : {}), + }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + log.warn('box_objects.upload_failed', { ...logFields(claims), length, error: message }); + return claims.sha && /sha-?256/i.test(message) + ? plain(400, 'Upload body does not match the declared sha256') + : plain(502, 'The upload did not complete; retry it'); + } + if (!written) { + if (await sameObject(env, claims, length)) { + log.info('box_objects.upload_replayed', { ...logFields(claims), length }); + return new Response(null, { status: 200 }); + } + log.warn('box_objects.upload_conflict', { ...logFields(claims), length, action: 'rejected' }); + return plain(412, 'An object was already written with this URL'); + } + log.info('box_objects.uploaded', { ...logFields(claims), length }); + return new Response(null, { status: 200, headers: { ETag: written.httpEtag } }); + } finally { + await gate.release(leaseId).catch((error: unknown) => { + // The lease expires on its own; a failed release only delays the slot. + log.warn('box_objects.lease_release_failed', { + ...logFields(claims), + error: error instanceof Error ? error.message : String(error), + }); + }); + } +} + +async function get(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectTokenClaims) { + const object = await c.env.R2.get(claims.key); + if (!object) return plain(404, 'Object not found'); + const headers = new Headers({ 'Content-Length': String(object.size), ETag: object.httpEtag }); + if (object.httpMetadata?.contentType) headers.set('Content-Type', object.httpMetadata.contentType); + log.info('box_objects.downloaded', { ...logFields(claims), length: object.size }); + return new Response(object.body, { status: 200, headers }); +} + +export async function handleBoxObjectRequest( + c: Context<{ Bindings: BoxObjectEnv }> +): Promise { + const method = c.req.method; + if (method !== 'PUT' && method !== 'GET') return plain(405, 'Use PUT or GET'); + const claims = await verifyBoxObjectToken(c.env, c.req.query('token') ?? ''); + if (!claims || claims.op !== method.toLowerCase()) { + // One answer for forged, expired and wrong-operation tokens: nothing to tell them apart. + log.warn('box_objects.token_refused', { method, action: 'rejected' }); + return plain(403, 'This upload URL is invalid or has expired'); + } + return claims.op === 'put' ? put(c, claims) : get(c, claims); +} diff --git a/apps/api/src/selfhost/object-urls/settings.ts b/apps/api/src/selfhost/object-urls/settings.ts new file mode 100644 index 0000000000..361120625d --- /dev/null +++ b/apps/api/src/selfhost/object-urls/settings.ts @@ -0,0 +1,44 @@ +/** + * Admin settings for box object uploads. Only the self-host entry registers them + * (`installBoxObjectUrls`), so a Cloudflare admin never sees them. + */ +import { + type AdminSettingDefinition, + type AdminSettingName, + integerDefinition, +} from '../../services/admin-setting-definitions'; + +/** + * Concurrent uploads the box accepts before answering 503 (`gate.ts` has the memory arithmetic: + * about 85 MB of celld RSS per in-flight upload over a ~150 MB base). + */ +export const DEFAULT_BOX_OBJECT_MAX_CONCURRENT_UPLOADS = 4; + +/** + * Seconds one upload holds its slot at most. It frees the slot of a handler that died without + * releasing it. An upload that runs longer is not cut; the box may then admit one upload over the + * limit until it ends. 1800 s covers 1 GiB at 0.6 MB/s. + */ +export const DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS = 1800; + +/** These names exist only in the self-host build, so they are not in the shared name union. */ +export const BOX_OBJECT_MAX_CONCURRENT_UPLOADS = + 'boxObjects.maxConcurrentUploads' as AdminSettingName; +export const BOX_OBJECT_UPLOAD_LEASE_SECONDS = 'boxObjects.uploadLeaseSeconds' as AdminSettingName; + +export const BOX_OBJECT_SETTINGS: readonly AdminSettingDefinition[] = [ + integerDefinition( + BOX_OBJECT_MAX_CONCURRENT_UPLOADS, + DEFAULT_BOX_OBJECT_MAX_CONCURRENT_UPLOADS, + 'Operations', + 'Uploads (attachments, build contexts, image artifacts) the box streams at once. Each costs about 85 MB of memory while it runs; further uploads get 503 with Retry-After.', + { min: 1, max: 64 } + ), + integerDefinition( + BOX_OBJECT_UPLOAD_LEASE_SECONDS, + DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS, + 'Operations', + 'Seconds one upload counts against the concurrent-upload limit at most, so an upload whose handler died frees its slot.', + { min: 60, max: 86_400 } + ), +]; diff --git a/apps/api/src/selfhost/object-urls/signer.ts b/apps/api/src/selfhost/object-urls/signer.ts new file mode 100644 index 0000000000..b613119c5c --- /dev/null +++ b/apps/api/src/selfhost/object-urls/signer.ts @@ -0,0 +1,66 @@ +/** + * The box's object URL signer: instead of an S3 presigned URL it returns + * `https://api./api/box-objects?token=`, which `route.ts` serves by streaming + * into or out of the R2 binding. Installed into the shared resolver + * (`services/r2-s3-client.ts:resolveR2ObjectUrlSigner`) by the self-host build; that resolver + * still prefers a configured static store key, so a box that has one keeps direct uploads. + * + * The token rides in the query string because every client (browser XHR, the vm-agent publisher + * and builder) PUTs or GETs the URL it is given and sends no SAM credential. Caddy's log redacts + * every query string (deploy/selfhost/caddy/log-redaction.caddy), SAM's request log records only + * the path (middleware/request-logging.ts), and celld logs no request URLs at its default level. + */ +import type { ObjectPutUrlOptions, ObjectUrlSigner } from '@simple-agent-manager/app-deployment'; + +import type { Env } from '../../env'; +import { buildTrustedApiUrl } from '../../lib/trusted-origins'; +import { errors } from '../../middleware/error'; +import { mintBoxObjectToken } from './tokens'; + +export const BOX_OBJECT_ROUTE = '/api/box-objects'; + +/** + * celld v0.6.3 refuses a request body over 1 GiB (413), and refuses to start with + * CELLD_MAX_REQUEST_BODY_BYTES above it, so no single PUT through a box can be larger. Larger + * image artifacts need several requests: idea 01M83WWQTNTBD4SY1530G3XWH7 (parted box uploads), + * which also tracks the 1 GiB artifact cap this imposes on keyless boxes. + */ +export const CELLD_MAX_REQUEST_BODY_BYTES = 1024 * 1024 * 1024; + +function owner(options: ObjectPutUrlOptions) { + const { userId: u, projectId: p, workspaceId: w } = options.owner ?? {}; + return u || p || w ? { u, p, w } : undefined; +} + +/** Null when the Worker cannot serve box URLs (no domain, key or R2 binding). */ +export function createBoxObjectUrlSigner(env: Env): ObjectUrlSigner | null { + if (!env.BASE_DOMAIN || !env.ENCRYPTION_KEY || !env.R2) return null; + const url = (token: string) => + `${buildTrustedApiUrl(env, BOX_OBJECT_ROUTE)}?token=${encodeURIComponent(token)}`; + const max = CELLD_MAX_REQUEST_BODY_BYTES; + return { + kind: 'box', + maxPutBytes: max, + putUrl: async (r2Key, options) => { + if (options.contentLength !== undefined && options.contentLength > max) { + throw errors.badRequest( + `Uploads through this self-hosted box are limited to ${max} bytes; this one is ${options.contentLength}` + ); + } + const token = await mintBoxObjectToken(env, { + op: 'put', + key: r2Key, + expiresIn: options.expiresIn, + ...(options.contentLength !== undefined ? { len: options.contentLength } : {}), + max: Math.min(options.maxBytes ?? max, max), + ...(options.contentType ? { ct: options.contentType } : {}), + ...(options.sha256 ? { sha: options.sha256 } : {}), + ...(options.metadata ? { md: options.metadata } : {}), + ...(owner(options) ? { sub: owner(options) } : {}), + }); + return url(token); + }, + getUrl: async (r2Key, options) => + url(await mintBoxObjectToken(env, { op: 'get', key: r2Key, expiresIn: options.expiresIn })), + }; +} diff --git a/apps/api/src/selfhost/object-urls/tokens.ts b/apps/api/src/selfhost/object-urls/tokens.ts new file mode 100644 index 0000000000..0b093f110f --- /dev/null +++ b/apps/api/src/selfhost/object-urls/tokens.ts @@ -0,0 +1,152 @@ +/** + * Tokens for box object URLs: one object key, one operation, a size bound and a short expiry, + * signed by the Worker itself (`../signed-token.ts`, its own HKDF label). They stand in for S3 + * presigned URLs on a box that has no static store credential: the uploader PUTs (or the + * downloader GETs) `https://api./api/self-host/objects?token=...` and `route.ts` streams the + * body to or from the R2 binding. + * + * Who a token acts for is decided before it is minted: only the authenticated routes that already + * minted presigned URLs mint these (attachments `request-upload`, compose image artifact init and + * release, build-context init and job spec), and they derive the key from the caller's verified + * identity. The key travels only inside the signed payload, never as a request parameter. + * + * Rotation: signing uses ENCRYPTION_KEY; verification also accepts ENCRYPTION_KEY_PREVIOUS, so a + * token minted minutes before `selfhost:secrets rotate` switches keys still works while the + * rotation overlaps. Once the previous key is dropped, such a token fails with 403 and the uploader + * asks for a new one, exactly as an expired presigned URL would. + */ +import { mintSignedToken, type SignedTokenEnv, verifySignedToken } from '../signed-token'; + +export type BoxObjectOperation = 'put' | 'get'; + +export interface BoxObjectTokenClaims { + /** Token format version. */ + v: 1; + op: BoxObjectOperation; + /** R2 binding key. */ + key: string; + /** Expiry, unix seconds. */ + exp: number; + /** PUT: the exact body length the uploader declared, when it declared one. */ + len?: number; + /** PUT: largest body accepted. */ + max?: number; + /** PUT: Content-Type stored on the object. */ + ct?: string; + /** PUT: hex sha256 the body must have (R2 verifies it while writing). */ + sha?: string; + /** PUT: custom metadata stored on the object. */ + md?: Record; + /** Who asked for the token, for logs only: user, project and workspace ids. */ + sub?: { u?: string; p?: string; w?: string }; +} + +const PURPOSE = { + prefix: 'samobj1', + label: 'sam-box-object-url/v1', + acceptPreviousKey: true, +} as const; + +/** Longest key accepted; R2 allows 1024 bytes. */ +const MAX_KEY_LENGTH = 1024; +const SHA256_HEX = /^[0-9a-f]{64}$/; +const MAX_METADATA_ENTRIES = 8; +const MAX_METADATA_VALUE_LENGTH = 256; + +/** + * An R2 key a token may name: relative, no empty, `.` or `..` segment, no backslash or control + * character. Keys SAM builds always pass; anything else is refused at mint and at verify. + */ +export function isSafeObjectKey(key: string): boolean { + if (!key || key.length > MAX_KEY_LENGTH) return false; + // eslint-disable-next-line no-control-regex -- control characters are exactly what is refused + if (key.startsWith('/') || key.includes('\\') || /[\u0000-\u001f\u007f]/.test(key)) return false; + return key.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..'); +} + +function isStringRecord(value: unknown): value is Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) return false; + const entries = Object.entries(value); + return ( + entries.length <= MAX_METADATA_ENTRIES && + entries.every( + ([name, item]) => + /^[a-z0-9-]{1,64}$/.test(name) && + typeof item === 'string' && + item.length <= MAX_METADATA_VALUE_LENGTH + ) + ); +} + +function positiveInteger(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value > 0; +} + +function optionalId(value: unknown): value is string | undefined { + return value === undefined || (typeof value === 'string' && value.length <= 128); +} + +/** The claims if they are well formed; null otherwise. */ +function parseClaims(raw: Record): BoxObjectTokenClaims | null { + if (raw.v !== 1 || (raw.op !== 'put' && raw.op !== 'get')) return null; + if (typeof raw.key !== 'string' || !isSafeObjectKey(raw.key)) return null; + if (!positiveInteger(raw.exp)) return null; + if (raw.len !== undefined && !positiveInteger(raw.len)) return null; + if (raw.max !== undefined && !positiveInteger(raw.max)) return null; + if (raw.ct !== undefined && (typeof raw.ct !== 'string' || raw.ct.length > 255)) return null; + if (raw.sha !== undefined && (typeof raw.sha !== 'string' || !SHA256_HEX.test(raw.sha))) + return null; + if (raw.md !== undefined && !isStringRecord(raw.md)) return null; + // A PUT is always bounded: by its declared length, its maximum, or both. + if (raw.op === 'put' && raw.len === undefined && raw.max === undefined) return null; + if (raw.op === 'get' && (raw.len ?? raw.max ?? raw.ct ?? raw.sha ?? raw.md) !== undefined) + return null; + let sub: BoxObjectTokenClaims['sub']; + if (raw.sub !== undefined) { + if (!raw.sub || typeof raw.sub !== 'object' || Array.isArray(raw.sub)) return null; + const { u, p, w } = raw.sub as Record; + if (!optionalId(u) || !optionalId(p) || !optionalId(w)) return null; + sub = { ...(u ? { u } : {}), ...(p ? { p } : {}), ...(w ? { w } : {}) }; + } + return { + v: 1, + op: raw.op, + key: raw.key, + exp: raw.exp, + ...(raw.len !== undefined ? { len: raw.len as number } : {}), + ...(raw.max !== undefined ? { max: raw.max as number } : {}), + ...(raw.ct !== undefined ? { ct: raw.ct as string } : {}), + ...(raw.sha !== undefined ? { sha: raw.sha as string } : {}), + ...(raw.md !== undefined ? { md: raw.md as Record } : {}), + ...(sub ? { sub } : {}), + }; +} + +export type BoxObjectTokenInput = Omit & { + /** Seconds the token stays valid. */ + expiresIn: number; +}; + +export async function mintBoxObjectToken( + env: Pick, + input: BoxObjectTokenInput, + now: number = Date.now() +): Promise { + const { expiresIn, ...rest } = input; + if (!positiveInteger(expiresIn)) throw new Error('Box object token needs a positive lifetime'); + const claims = parseClaims({ ...rest, v: 1, exp: Math.floor(now / 1000) + expiresIn }); + if (!claims) throw new Error('Box object token claims are invalid'); + return mintSignedToken(env, PURPOSE, claims); +} + +/** Signature, shape and expiry. Null for any token that is not valid now. */ +export async function verifyBoxObjectToken( + env: SignedTokenEnv, + token: string, + now: number = Date.now() +): Promise { + const raw = await verifySignedToken(env, PURPOSE, token); + const claims = raw ? parseClaims(raw) : null; + if (!claims || claims.exp * 1000 <= now) return null; + return claims; +} diff --git a/apps/api/src/selfhost/signed-token.ts b/apps/api/src/selfhost/signed-token.ts new file mode 100644 index 0000000000..0d1e9cb50f --- /dev/null +++ b/apps/api/src/selfhost/signed-token.ts @@ -0,0 +1,139 @@ +/** + * Short-lived tokens the self-host Worker signs for itself: `..`, a + * base64url JSON payload signed with HMAC-SHA256. + * + * Each purpose has its own key, derived from the Worker's ENCRYPTION_KEY with HKDF under a fixed + * label, so a token minted for one purpose never verifies for another and no new secret or table + * is needed. The key therefore rotates with ENCRYPTION_KEY (`pnpm selfhost:secrets rotate`). A + * purpose that accepts `ENCRYPTION_KEY_PREVIOUS` keeps tokens minted just before a rotation valid + * while the rotation overlaps (they are minutes long). + * + * Users: SAM-hosted git (`hosted-git/tokens.ts`) and box object URLs (`object-urls/tokens.ts`). + */ +export interface SignedTokenPurpose { + /** First token segment, for example `samgit1`. */ + prefix: string; + /** HKDF info label; no other purpose may share it. */ + label: string; + /** Also verify with ENCRYPTION_KEY_PREVIOUS (signing always uses ENCRYPTION_KEY). */ + acceptPreviousKey?: boolean; +} + +export interface SignedTokenEnv { + ENCRYPTION_KEY: string; + ENCRYPTION_KEY_PREVIOUS?: string; +} + +/** Longest token any purpose verifies; longer input is refused before any crypto. */ +const MAX_TOKEN_LENGTH = 2048; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +export function base64UrlEncode(bytes: Uint8Array): string { + let binary = ''; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); +} + +export function base64UrlDecode(value: string): Uint8Array | null { + if (!/^[A-Za-z0-9_-]+$/.test(value)) return null; + try { + const padded = + value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - (value.length % 4)) % 4); + return Uint8Array.from(atob(padded), (character) => character.charCodeAt(0)); + } catch { + return null; + } +} + +/** + * Derived keys, cached once derived, per (label, secret). Only a finished key is shared: a request + * never waits on a derivation another request started, which on the self-hosted celld runtime + * could be dropped with that request (lib/shared-flight.ts). Concurrent cold callers each derive + * once (one HKDF). + */ +const cachedKeys = new Map(); +/** Per label: the current and the previous ENCRYPTION_KEY. */ +const MAX_CACHED_KEYS_PER_LABEL = 2; + +async function signingKey(label: string, secret: string): Promise { + const cached = cachedKeys.get(label) ?? []; + const hit = cached.find((entry) => entry.secret === secret); + if (hit) return hit.key; + const root = await crypto.subtle.importKey('raw', encoder.encode(secret), 'HKDF', false, [ + 'deriveKey', + ]); + const key = await crypto.subtle.deriveKey( + { name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: encoder.encode(label) }, + root, + { name: 'HMAC', hash: 'SHA-256', length: 256 }, + false, + ['sign', 'verify'] + ); + // A rotation replaces the oldest entry, so retired keys do not accumulate for the isolate's life. + cachedKeys.set(label, [{ secret, key }, ...cached].slice(0, MAX_CACHED_KEYS_PER_LABEL)); + return key; +} + +function requireKey(env: Pick, purpose: SignedTokenPurpose) { + if (!env.ENCRYPTION_KEY) throw new Error(`ENCRYPTION_KEY is required for ${purpose.prefix} tokens`); + return env.ENCRYPTION_KEY; +} + +/** Signs `claims` (any JSON object) for `purpose` with ENCRYPTION_KEY. */ +export async function mintSignedToken( + env: Pick, + purpose: SignedTokenPurpose, + claims: object +): Promise { + const payload = base64UrlEncode(encoder.encode(JSON.stringify(claims))); + const unsigned = `${purpose.prefix}.${payload}`; + const signature = await crypto.subtle.sign( + 'HMAC', + await signingKey(purpose.label, requireKey(env, purpose)), + encoder.encode(unsigned) + ); + return `${unsigned}.${base64UrlEncode(new Uint8Array(signature))}`; +} + +/** + * The parsed payload of a token whose signature verifies for `purpose`, or null. Callers validate + * the payload's shape and expiry themselves. + */ +export async function verifySignedToken( + env: SignedTokenEnv, + purpose: SignedTokenPurpose, + token: string +): Promise | null> { + if (token.length > MAX_TOKEN_LENGTH) return null; + const parts = token.split('.'); + if (parts.length !== 3 || parts[0] !== purpose.prefix) return null; + const [prefix, payload, signaturePart] = parts as [string, string, string]; + const signature = base64UrlDecode(signaturePart); + const payloadBytes = base64UrlDecode(payload); + if (!signature || !payloadBytes) return null; + const secrets = [requireKey(env, purpose)]; + if (purpose.acceptPreviousKey && env.ENCRYPTION_KEY_PREVIOUS) { + secrets.push(env.ENCRYPTION_KEY_PREVIOUS); + } + let valid = false; + for (const secret of secrets) { + valid = await crypto.subtle.verify( + 'HMAC', + await signingKey(purpose.label, secret), + signature, + encoder.encode(`${prefix}.${payload}`) + ); + if (valid) break; + } + if (!valid) return null; + let parsed: unknown; + try { + parsed = JSON.parse(decoder.decode(payloadBytes)); + } catch { + return null; + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null; + return parsed as Record; +} diff --git a/apps/api/src/services/attachment-upload.ts b/apps/api/src/services/attachment-upload.ts index d224d33fe9..5e14ecb272 100644 --- a/apps/api/src/services/attachment-upload.ts +++ b/apps/api/src/services/attachment-upload.ts @@ -1,18 +1,17 @@ /** - * Attachment Upload Service — R2 presigned URL generation and validation. + * Attachment Upload Service — upload URL generation and validation. * - * Generates S3-compatible presigned PUT URLs for direct browser → R2 uploads, + * Generates the URL the browser PUTs a file to: an S3-compatible presigned URL straight to R2, or + * on a self-hosted box without a store key, the box's own upload route (r2-s3-client.ts). * Validates attachment existence/integrity on task submission via HEAD checks. */ -import { PutObjectCommand } from '@aws-sdk/client-s3'; -import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; import type { TaskAttachment } from '@simple-agent-manager/shared'; import { ATTACHMENT_DEFAULTS, SAFE_FILENAME_REGEX } from '@simple-agent-manager/shared'; import type { Env } from '../env'; import { log } from '../lib/logger'; import { parsePositiveInt } from '../lib/route-helpers'; -import { getR2PresignTarget } from './r2-s3-client'; +import { getR2ObjectUrlSigner } from './r2-s3-client'; function getMaxBytes(env: Env): number { return parsePositiveInt(env.ATTACHMENT_UPLOAD_MAX_BYTES, ATTACHMENT_DEFAULTS.UPLOAD_MAX_BYTES); @@ -83,19 +82,20 @@ export async function generatePresignedUploadUrl( } const r2Key = buildAttachmentR2Key(userId, uploadId, filename); - // r2Key stays the R2 binding key; only the presigned URL addresses the store object. - const target = getR2PresignTarget(env); + // r2Key stays the R2 binding key; only the URL addresses the store object. + const signer = getR2ObjectUrlSigner(env); const expiresIn = getPresignExpiry(env); + if (signer.maxPutBytes !== undefined && size > signer.maxPutBytes) { + throw new Error(`File size ${size} exceeds maximum ${signer.maxPutBytes} bytes`); + } - const command = new PutObjectCommand({ - Bucket: target.bucket, - Key: target.objectKey(r2Key), - ContentLength: size, - ContentType: contentType, + const uploadUrl = await signer.putUrl(r2Key, { + expiresIn, + contentLength: size, + contentType, + owner: { userId }, }); - const uploadUrl = await getSignedUrl(target.client, command, { expiresIn }); - log.info('attachment_upload.presigned_url_generated', { userId, uploadId, diff --git a/apps/api/src/services/build-context-upload.ts b/apps/api/src/services/build-context-upload.ts index 56637d4000..6eab4ecf0e 100644 --- a/apps/api/src/services/build-context-upload.ts +++ b/apps/api/src/services/build-context-upload.ts @@ -1,14 +1,14 @@ // Canonical implementation lives in the app-deployment package. -// The upload keeps its original `(env, …)` signature here and binds the worker's shared R2 S3 -// client (`WHEN_REQUIRED`, so the VM need not send a checksum header), which also serves compose -// artifacts, attachments and session snapshots, and works against an operator store. +// The upload keeps its original `(env, …)` signature here and binds the worker's object URL signer +// (r2-s3-client.ts): the shared R2 S3 client (`WHEN_REQUIRED`, so the VM need not send a checksum +// header), or on a self-hosted box without a store key, the box's own upload route. import { createBuildContextDownload as createDownload, createBuildContextUpload as createUpload, } from '@simple-agent-manager/app-deployment'; import type { Env } from '../env'; -import { getR2PresignTarget } from './r2-s3-client'; +import { getR2ObjectUrlSigner } from './r2-s3-client'; export { verifyBuildContextObject } from '@simple-agent-manager/app-deployment'; @@ -21,9 +21,9 @@ export async function createBuildContextUpload( descriptor: BuildContextUploadArgs[1], expiresIn: BuildContextUploadArgs[2] ): ReturnType { - return createUpload(owner, descriptor, expiresIn, getR2PresignTarget(env, 'WHEN_REQUIRED')); + return createUpload(owner, descriptor, expiresIn, getR2ObjectUrlSigner(env, 'WHEN_REQUIRED')); } export async function createBuildContextDownload(env: Env, r2Key: string, expiresIn: number) { - return createDownload(r2Key, expiresIn, getR2PresignTarget(env, 'WHEN_REQUIRED')); + return createDownload(r2Key, expiresIn, getR2ObjectUrlSigner(env, 'WHEN_REQUIRED')); } diff --git a/apps/api/src/services/compose-image-artifacts.ts b/apps/api/src/services/compose-image-artifacts.ts index 57cd16c991..f5c65bcbd5 100644 --- a/apps/api/src/services/compose-image-artifacts.ts +++ b/apps/api/src/services/compose-image-artifacts.ts @@ -1,8 +1,8 @@ // Moved to @simple-agent-manager/app-deployment (worker modularization W4). // Re-exported so existing importers keep working. A vi.mock of this path does not reach // imports made inside the package (see packages/app-deployment/AGENTS.md). -// The two URL-signing functions keep their original signatures here and bind the worker's shared -// R2 S3 client, which also serves attachments and session snapshots. +// The two URL-signing functions keep their original signatures here and bind the worker's object +// URL signer (r2-s3-client.ts): the shared R2 S3 client, or on a self-hosted box its upload route. import { type ComposeImageArtifactDescriptor, type ComposeImageArtifactDownload, @@ -12,7 +12,7 @@ import { } from '@simple-agent-manager/app-deployment'; import type { Env } from '../env'; -import { getR2PresignTarget } from './r2-s3-client'; +import { getR2ObjectUrlSigner } from './r2-s3-client'; export type { ComposeImageArtifactDescriptor, @@ -25,23 +25,24 @@ export { buildComposeImageArtifactKey, COMPOSE_IMAGE_ARTIFACT_ARCHIVE_TYPE, COMPOSE_IMAGE_ARTIFACT_MEDIA_TYPE, + composeImageArtifactMaxBytesFor, getComposeImageArtifactMaxBytes, validateCompletedComposeImageArtifacts, validateComposeImageArtifactDescriptor, } from '@simple-agent-manager/app-deployment'; // Compose artifacts have always been signed with the SDK's default checksum behaviour. Async so a -// missing R2 credential rejects the returned promise, as it did before, instead of throwing. +// missing signer rejects the returned promise (a 503 naming the settings) instead of throwing. export async function createComposeImageArtifactUploads( env: Env, input: Parameters[1] ): Promise { - return createUploads(env, input, getR2PresignTarget(env, 'SDK_DEFAULT')); + return createUploads(env, input, getR2ObjectUrlSigner(env, 'SDK_DEFAULT')); } export async function createComposeImageArtifactDownloads( env: Env, artifacts: ComposeImageArtifactDescriptor[] ): Promise { - return createDownloads(env, artifacts, getR2PresignTarget(env, 'SDK_DEFAULT')); + return createDownloads(env, artifacts, getR2ObjectUrlSigner(env, 'SDK_DEFAULT')); } diff --git a/apps/api/src/services/r2-s3-client.ts b/apps/api/src/services/r2-s3-client.ts index 760594c83d..a28c5d0679 100644 --- a/apps/api/src/services/r2-s3-client.ts +++ b/apps/api/src/services/r2-s3-client.ts @@ -1,6 +1,8 @@ import { S3Client } from '@aws-sdk/client-s3'; +import { type ObjectUrlSigner, s3ObjectUrlSigner } from '@simple-agent-manager/app-deployment'; import type { Env } from '../env'; +import { errors } from '../middleware/error'; import { type R2PresignConfig, r2PresignObjectKey, @@ -77,6 +79,54 @@ export function getR2PresignTarget( }; } +/** + * The self-host build's box URL signer (`selfhost/object-urls/`), or null. Only the celld entry + * installs it, so on Cloudflare this stays null and every URL is an R2 presigned URL. + */ +type BoxObjectUrlSignerFactory = (env: Env) => ObjectUrlSigner | null; +let boxSignerFactory: BoxObjectUrlSignerFactory | null = null; + +/** Called once by the self-host build; `null` uninstalls (tests). */ +export function installBoxObjectUrlSigner(factory: BoxObjectUrlSignerFactory | null): void { + boxSignerFactory = factory; +} + +/** + * Where object URLs for compose image artifacts, build contexts and task attachments point: + * + * 1. a configured presign credential (Cloudflare R2, or an operator store with a static key) signs + * S3 presigned URLs, exactly as before; + * 2. otherwise, on a self-hosted box, SAM-signed URLs to the box's own upload route; + * 3. otherwise null: nothing can mint a URL. + * + * The one resolver every caller uses (rule 24), so availability checks and URL minting agree. + */ +export function resolveR2ObjectUrlSigner( + env: Env, + checksum: R2ChecksumMode = 'WHEN_REQUIRED' +): ObjectUrlSigner | null { + if (resolveR2PresignConfig(env)) return s3ObjectUrlSigner(getR2PresignTarget(env, checksum)); + return boxSignerFactory?.(env) ?? null; +} + +export function r2ObjectUrlsAvailable(env: Env): boolean { + return resolveR2ObjectUrlSigner(env) !== null; +} + +/** The signer, or a 503 naming what to configure (never a plain error that surfaces as a 500). */ +export function getR2ObjectUrlSigner( + env: Env, + checksum: R2ChecksumMode = 'WHEN_REQUIRED' +): ObjectUrlSigner { + const signer = resolveR2ObjectUrlSigner(env, checksum); + if (!signer) { + throw errors.serviceUnavailable( + 'Object uploads are not configured: set R2_ACCESS_KEY_ID and R2_SECRET_ACCESS_KEY (plus CF_ACCOUNT_ID and R2_BUCKET_NAME on Cloudflare, or R2_S3_ENDPOINT, R2_S3_BUCKET and R2_S3_KEY_PREFIX for an operator store), or run the self-host build, which uploads through the box' + ); + } + return signer; +} + /** Test seam: forget cached clients. */ export function resetR2S3ClientsForTests(): void { clients.clear(); diff --git a/apps/api/tests/unit/services/attachment-upload.test.ts b/apps/api/tests/unit/services/attachment-upload.test.ts index 91da458b1d..a434ba472e 100644 --- a/apps/api/tests/unit/services/attachment-upload.test.ts +++ b/apps/api/tests/unit/services/attachment-upload.test.ts @@ -93,14 +93,14 @@ describe('generatePresignedUploadUrl', () => { const env = makePresignEnv({ R2_ACCESS_KEY_ID: undefined }); await expect( generatePresignedUploadUrl(env, validOptions), - ).rejects.toThrow('R2 S3 credentials not configured'); + ).rejects.toThrow('Object uploads are not configured'); }); it('rejects when CF_ACCOUNT_ID is missing', async () => { const env = makePresignEnv({ CF_ACCOUNT_ID: undefined }); await expect( generatePresignedUploadUrl(env, validOptions), - ).rejects.toThrow('R2 S3 credentials not configured'); + ).rejects.toThrow('Object uploads are not configured'); }); it('uses configurable presign expiry from env', async () => { diff --git a/packages/app-deployment/src/build-context-upload.ts b/packages/app-deployment/src/build-context-upload.ts index 6431a4e185..4ef7b8b9a3 100644 --- a/packages/app-deployment/src/build-context-upload.ts +++ b/packages/app-deployment/src/build-context-upload.ts @@ -1,35 +1,27 @@ -import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; -import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; - import type { BuildContextDescriptor, BuildContextOwner } from './build-context-state'; import { buildContextKey } from './build-context-state'; -import type { ComposeImageArtifactPresignTarget as PresignTarget } from './compose-image-artifacts'; import type { AppDeploymentEnv as Env } from './env'; +import type { ObjectUrlSigner } from './object-url-signer'; /** Only job-derived keys are signed. Metadata binds the uploaded object to the * digest declared before upload; builders must still hash bytes after download. - * The URL is signed through the worker's shared R2 S3 client (`target`, bound with the - * `WHEN_REQUIRED` checksum mode), as compose artifacts are, so an operator store works too. */ + * The URL comes from the worker's object URL signer (`signer`): a presigned URL through the shared + * R2 S3 client (`WHEN_REQUIRED` checksums), or a box upload URL that also verifies the digest. */ export async function createBuildContextUpload( owner: BuildContextOwner, descriptor: BuildContextDescriptor, expiresIn: number, - target: PresignTarget + signer: ObjectUrlSigner ) { const r2Key = buildContextKey(owner); - const uploadUrl = await getSignedUrl( - target.client, - new PutObjectCommand({ - Bucket: target.bucket, - Key: target.objectKey(r2Key), - ContentLength: descriptor.sizeBytes, - ContentType: 'application/zstd', - Metadata: { sha256: descriptor.sha256 }, - }), - // The source sends this as a header. Keep it in SignedHeaders instead of - // hoisting it into the query, so changing the digest invalidates the PUT. - { expiresIn, unhoistableHeaders: new Set(['x-amz-meta-sha256']) } - ); + const uploadUrl = await signer.putUrl(r2Key, { + expiresIn, + contentLength: descriptor.sizeBytes, + contentType: 'application/zstd', + metadata: { sha256: descriptor.sha256 }, + sha256: descriptor.sha256, + owner: { userId: owner.requestedBy, projectId: owner.projectId, workspaceId: owner.workspaceId }, + }); return { r2Key, uploadUrl, expiresIn }; } export async function verifyBuildContextObject( @@ -48,11 +40,7 @@ export async function verifyBuildContextObject( export async function createBuildContextDownload( r2Key: string, expiresIn: number, - target: PresignTarget + signer: ObjectUrlSigner ) { - return getSignedUrl( - target.client, - new GetObjectCommand({ Bucket: target.bucket, Key: target.objectKey(r2Key) }), - { expiresIn } - ); + return signer.getUrl(r2Key, { expiresIn }); } diff --git a/packages/app-deployment/src/compose-image-artifacts.ts b/packages/app-deployment/src/compose-image-artifacts.ts index bec32f0e47..a38d50fee1 100644 --- a/packages/app-deployment/src/compose-image-artifacts.ts +++ b/packages/app-deployment/src/compose-image-artifacts.ts @@ -1,22 +1,7 @@ -import type { S3Client } from '@aws-sdk/client-s3'; -import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; -import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; import { parsePositiveInt } from '@simple-agent-manager/worker-core'; import type { AppDeploymentEnv } from './env'; - -/** - * Where compose artifact URLs are signed: the worker's shared R2 S3 client - * (`apps/api/src/services/r2-s3-client.ts`, `getR2PresignTarget(env, 'SDK_DEFAULT')`), passed in - * by the worker so this package does not resolve storage credentials itself. - */ -export interface ComposeImageArtifactPresignTarget { - client: S3Client; - /** S3 bucket the URL addresses. */ - bucket: string; - /** S3 object key for an R2 key (prefix applied for operator stores). */ - objectKey(r2Key: string): string; -} +import type { ObjectUrlSigner } from './object-url-signer'; const DEFAULT_UPLOAD_EXPIRY_SECONDS = 900; const DEFAULT_DOWNLOAD_EXPIRY_SECONDS = 900; @@ -74,6 +59,19 @@ export function getComposeImageArtifactMaxBytes(env: AppDeploymentEnv): number { ); } +/** + * The artifact size limit for uploads through `signer`: the configured maximum, lowered to the + * signer's own per-request bound (a self-hosted box carries at most 1 GiB per request). The init + * response reports it, so the VM agent refuses a larger archive before uploading it. + */ +export function composeImageArtifactMaxBytesFor( + env: AppDeploymentEnv, + signer: Pick +): number { + const configured = getComposeImageArtifactMaxBytes(env); + return signer.maxPutBytes === undefined ? configured : Math.min(configured, signer.maxPutBytes); +} + function getUploadExpiry(env: AppDeploymentEnv): number { return parsePositiveInt( env.COMPOSE_IMAGE_ARTIFACT_UPLOAD_URL_TTL_SECONDS, @@ -192,10 +190,10 @@ export async function createComposeImageArtifactUploads( uploadId: string; services: ComposeImageArtifactRequest[]; }, - target: ComposeImageArtifactPresignTarget + signer: ObjectUrlSigner ): Promise { const expiresIn = getUploadExpiry(env); - const maxBytes = getComposeImageArtifactMaxBytes(env); + const maxBytes = composeImageArtifactMaxBytesFor(env, signer); return Promise.all( input.services.map(async (service) => { @@ -211,17 +209,17 @@ export async function createComposeImageArtifactUploads( input.uploadId, serviceName ); - const command = new PutObjectCommand({ - Bucket: target.bucket, - Key: target.objectKey(r2Key), - ContentType: COMPOSE_IMAGE_ARTIFACT_MEDIA_TYPE, - }); return { serviceName, sourceRef, localImageRef: cleanString(service.localImageRef) || sourceRef, r2Key, - uploadUrl: await getSignedUrl(target.client, command, { expiresIn }), + uploadUrl: await signer.putUrl(r2Key, { + expiresIn, + contentType: COMPOSE_IMAGE_ARTIFACT_MEDIA_TYPE, + maxBytes, + owner: { projectId: input.projectId, workspaceId: input.workspaceId }, + }), expiresIn, maxBytes, archiveType: COMPOSE_IMAGE_ARTIFACT_ARCHIVE_TYPE, @@ -254,18 +252,14 @@ export async function validateCompletedComposeImageArtifacts( export async function createComposeImageArtifactDownloads( env: AppDeploymentEnv, artifacts: ComposeImageArtifactDescriptor[], - target: ComposeImageArtifactPresignTarget + signer: ObjectUrlSigner ): Promise { const downloadExpiresIn = getDownloadExpiry(env); return Promise.all( artifacts.map(async (artifact) => ({ ...artifact, - downloadUrl: await getSignedUrl( - target.client, - new GetObjectCommand({ Bucket: target.bucket, Key: target.objectKey(artifact.r2Key) }), - { expiresIn: downloadExpiresIn } - ), + downloadUrl: await signer.getUrl(artifact.r2Key, { expiresIn: downloadExpiresIn }), downloadExpiresIn, })) ); diff --git a/packages/app-deployment/src/index.ts b/packages/app-deployment/src/index.ts index ad5d41ec5e..75a586e044 100644 --- a/packages/app-deployment/src/index.ts +++ b/packages/app-deployment/src/index.ts @@ -30,13 +30,13 @@ export type { ComposeImageArtifactDescriptor, ComposeImageArtifactDownload, ComposeImageArtifactPlatform, - ComposeImageArtifactPresignTarget, ComposeImageArtifactRequest, ComposeImageArtifactUpload, } from './compose-image-artifacts'; export { buildComposeImageArtifactKey, COMPOSE_IMAGE_ARTIFACT_ARCHIVE_TYPE, + composeImageArtifactMaxBytesFor, COMPOSE_IMAGE_ARTIFACT_MEDIA_TYPE, createComposeImageArtifactDownloads, createComposeImageArtifactUploads, @@ -44,6 +44,12 @@ export { validateCompletedComposeImageArtifacts, validateComposeImageArtifactDescriptor, } from './compose-image-artifacts'; +export type { + ObjectPutUrlOptions, + ObjectUrlSigner, + S3PresignTarget, +} from './object-url-signer'; +export { s3ObjectUrlSigner } from './object-url-signer'; export type { ComposePublishApplyOptions, ComposePublishApplyResult, diff --git a/packages/app-deployment/src/object-url-signer.ts b/packages/app-deployment/src/object-url-signer.ts new file mode 100644 index 0000000000..97e43e5f27 --- /dev/null +++ b/packages/app-deployment/src/object-url-signer.ts @@ -0,0 +1,87 @@ +import type { S3Client } from '@aws-sdk/client-s3'; +import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; +import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; + +/** + * Where a client sends an object's bytes, or fetches them, without holding a SAM credential: the + * one seam behind compose image artifacts, build contexts and task attachments. + * + * - `presign`: an S3 presigned URL straight to the store (Cloudflare R2, or an operator store with + * a static key). `s3ObjectUrlSigner` below; the Cloudflare URLs it produces are pinned + * byte-for-byte by apps/api/tests/unit/services/r2-presign-cloudflare-equivalence.test.ts. + * - `box`: a SAM-signed token URL that a self-hosted box streams into its R2 binding + * (apps/api/src/selfhost/object-urls/). Installed only by the self-host build. + * + * The worker chooses one per request (`apps/api/src/services/r2-s3-client.ts`, + * `getR2ObjectUrlSigner`); this package never resolves credentials itself. + */ +export interface ObjectPutUrlOptions { + /** Seconds the URL stays valid. */ + expiresIn: number; + contentType?: string; + /** Exact body length the client will send; signed into the URL when given. */ + contentLength?: number; + /** Largest body the client may send when the length is not known in advance (box only). */ + maxBytes?: number; + /** Custom metadata stored with the object; S3 signs each `x-amz-meta-*` header. */ + metadata?: Record; + /** Hex sha256 the body must have; the box verifies it while writing. */ + sha256?: string; + /** Who asked, for the box route's logs. */ + owner?: { userId?: string; projectId?: string; workspaceId?: string }; +} + +export interface ObjectUrlSigner { + readonly kind: 'presign' | 'box'; + /** Largest body one PUT can carry through this signer; undefined when it adds no bound. */ + readonly maxPutBytes?: number; + putUrl(r2Key: string, options: ObjectPutUrlOptions): Promise; + getUrl(r2Key: string, options: { expiresIn: number }): Promise; +} + +/** The worker's shared R2 S3 client and the store object a binding key maps to. */ +export interface S3PresignTarget { + client: S3Client; + /** S3 bucket the URL addresses. */ + bucket: string; + /** S3 object key for an R2 key (prefix applied for operator stores). */ + objectKey(r2Key: string): string; +} + +/** + * Presigned S3 URLs. `maxBytes`, `sha256` and `owner` have no S3 form and are not signed: a + * presigned PUT is bounded by `contentLength` when given, and callers validate the stored object + * (size, recorded metadata) before using it, as they always have. + */ +export function s3ObjectUrlSigner(target: S3PresignTarget): ObjectUrlSigner { + return { + kind: 'presign', + putUrl: (r2Key, options) => { + const metadataHeaders = Object.keys(options.metadata ?? {}).map( + (name) => `x-amz-meta-${name}` + ); + return getSignedUrl( + target.client, + new PutObjectCommand({ + Bucket: target.bucket, + Key: target.objectKey(r2Key), + ...(options.contentLength === undefined ? {} : { ContentLength: options.contentLength }), + ...(options.contentType === undefined ? {} : { ContentType: options.contentType }), + ...(options.metadata ? { Metadata: options.metadata } : {}), + }), + { + expiresIn: options.expiresIn, + // The uploader sends metadata as headers. Keep them in SignedHeaders instead of hoisting + // them into the query, so a changed value (a different digest) invalidates the PUT. + ...(metadataHeaders.length > 0 ? { unhoistableHeaders: new Set(metadataHeaders) } : {}), + } + ); + }, + getUrl: (r2Key, options) => + getSignedUrl( + target.client, + new GetObjectCommand({ Bucket: target.bucket, Key: target.objectKey(r2Key) }), + { expiresIn: options.expiresIn } + ), + }; +} diff --git a/packages/app-deployment/tests/unit/build-context-presign.test.ts b/packages/app-deployment/tests/unit/build-context-presign.test.ts index 76c75c9a78..2dc2dbf37b 100644 --- a/packages/app-deployment/tests/unit/build-context-presign.test.ts +++ b/packages/app-deployment/tests/unit/build-context-presign.test.ts @@ -10,16 +10,16 @@ import { } from '../../src/build-context-upload'; import { COMPOSE_IMAGE_ARTIFACT_MEDIA_TYPE, - type ComposeImageArtifactPresignTarget, createComposeImageArtifactDownloads, createComposeImageArtifactUploads, } from '../../src/compose-image-artifacts'; import type { AppDeploymentEnv } from '../../src/env'; +import { type S3PresignTarget, s3ObjectUrlSigner } from '../../src/object-url-signer'; const secret = 'fake-secret'; // The worker's shared R2 client (apps/api/src/services/r2-s3-client.ts) as it is configured on // Cloudflare for build contexts: WHEN_REQUIRED checksums, the account endpoint, unprefixed keys. -const target: ComposeImageArtifactPresignTarget = { +const target: S3PresignTarget = { client: new S3Client({ region: 'auto', endpoint: 'https://fake-account.r2.cloudflarestorage.com', @@ -101,7 +101,7 @@ describe('real SDK context presigner', () => { }, { sizeBytes: body.length, sha256 }, 300, - target + s3ObjectUrlSigner(target) ); const url = new URL(slot.uploadUrl); expect(url.pathname).toContain('/compose-build-contexts/project/env/job/3.tar.zst'); @@ -185,7 +185,7 @@ describe('real SDK download and artifact presigners', () => { objectKey: (key: string) => `installation/${key}`, }; const key = 'compose-build-contexts/project/env/job/3.tar.zst'; - const url = new URL(await createBuildContextDownload(key, 123, prefixed)); + const url = new URL(await createBuildContextDownload(key, 123, s3ObjectUrlSigner(prefixed))); expect(url.pathname).toBe(`/fake-bucket/installation/${key}`); expect(url.searchParams.get('X-Amz-Expires')).toBe('123'); expect(verifySignature(url, { host: url.host }, 'GET')).toBe(true); @@ -197,7 +197,7 @@ describe('real SDK download and artifact presigners', () => { it('independently verifies upload and download signatures for distinct artifact services', async () => { // Match the worker compose-artifact boundary: SDK_DEFAULT, an operator prefix, // and dummy credentials only. No network call or real credential is needed to sign. - const artifactsTarget: ComposeImageArtifactPresignTarget = { + const artifactsTarget: S3PresignTarget = { client: new S3Client({ region: 'auto', endpoint: 'https://operator-store.example', @@ -224,7 +224,7 @@ describe('real SDK download and artifact presigners', () => { { serviceName: 'worker', sourceRef: 'worker:latest' }, ], }, - artifactsTarget + s3ObjectUrlSigner(artifactsTarget) ); expect(uploads).toHaveLength(2); expect(new Set(uploads.map((upload) => upload.r2Key)).size).toBe(2); @@ -247,7 +247,7 @@ describe('real SDK download and artifact presigners', () => { sizeBytes: 42, archiveSha256: `sha256:${'a'.repeat(64)}`, })), - artifactsTarget + s3ObjectUrlSigner(artifactsTarget) ); expect(downloads.map((download) => download.r2Key)).toEqual( uploads.map((upload) => upload.r2Key) diff --git a/scripts/selfhost/selfhost-durable-objects.ts b/scripts/selfhost/selfhost-durable-objects.ts index 396ae7b853..541e0ebf0e 100644 --- a/scripts/selfhost/selfhost-durable-objects.ts +++ b/scripts/selfhost/selfhost-durable-objects.ts @@ -6,8 +6,8 @@ * must not carry their code. The celld config (`buildCelldConfig`) appends each one's binding * and migration after wrangler.toml's, and the generated celld entry (`celld-project.ts`) exports * the class from `SELFHOST_ENTRY_MODULE`, which the shared entry `apps/api/src/index.ts` never - * imports. Today that module is hosted git's; a second self-host-only class must be exported from - * the same module (tests/unit/selfhost/selfhost-only-modules.test.ts checks every class is). + * imports. Hosted git's class and the box upload gate are exported from it; every self-host-only class + * must be exported from that module (tests/unit/selfhost/selfhost-only-modules.test.ts checks every class is). * * celld 0.6.3 validates migrations declaratively (a tag or a class may appear once; a class with * storage must be declared in `new_sqlite_classes`). Observed with `celld dev`, which keeps state @@ -32,6 +32,13 @@ export const SELFHOST_DURABLE_OBJECTS: readonly SelfhostDurableObject[] = [ // SAM-hosted git repositories (one per repository); selfhost/hosted-git/local-backend.ts selects it // with HOSTED_GIT_BACKEND=durable-object (SELFHOST_VAR_OVERRIDES). { binding: 'HOSTED_GIT', className: 'HostedGitRepo', migrationTag: 'selfhost-hosted-git-v1' }, + // The box-wide concurrent-upload limit for box object URLs (one instance): + // apps/api/src/selfhost/object-urls/gate.ts. + { + binding: 'BOX_UPLOAD_GATE', + className: 'BoxUploadGate', + migrationTag: 'selfhost-box-upload-gate-v1', + }, ]; interface DurableObjectConfig { diff --git a/tasks/active/2026-11-23-selfhost-box-object-uploads.md b/tasks/active/2026-11-23-selfhost-box-object-uploads.md new file mode 100644 index 0000000000..983d29c5df --- /dev/null +++ b/tasks/active/2026-11-23-selfhost-box-object-uploads.md @@ -0,0 +1,91 @@ +# Self-host: SAM-signed object uploads through the box (no cloud storage keys) + +SAM task `01M83T07FR9ZFXEPJQXA90HE14`, idea `01M828EKSVADDDZF7VXA5HPKK5`. Self-hosting only; hosted +SAM keeps direct R2 presigned URLs byte-identical. + +## Problem + +Build-backed app deploys (compose image artifacts, build contexts) and task attachments hand the +client an S3 presigned URL (`services/r2-s3-client.ts:getR2PresignTarget`). A box can presign only +with `R2_S3_ENDPOINT` plus a prefix-scoped static HMAC key. A GCS box in an org that refuses HMAC +keys cannot get one, so `compose-image-artifacts/init` 500s ("R2 S3 credentials not configured", +a plain `Error`) and attachments answer 403. Raphaël's decision (2026-11-23, ask +`01M828MCP6C88CC5PDBKC824QB`): no GCP-specific signing. The Worker issues a short-lived SAM-signed +token, and the client PUTs or GETs through the box, which streams the body into `env.R2` (celld's +R2 interface). + +## Phase 1 proof (done 2026-11-23, local celld v0.6.3 + MinIO, `CELLD_V8_HEAP_LIMIT_MB=128`) + +| case | result | celld RSS peak (idle 43 MB) | MB/s | +| --------------------------------------------- | ----------------------------------------------- | --------------------------- | ---- | +| `R2.put(request.body)` 256 MB | 200, sha matches on download | 145 MB | 101 | +| `R2.put(request.body)` 1023 MB | 200, sha matches | 220 MB | 132 | +| R2 multipart, 16 MB parts, 1023 MB | 200 | 308 MB | 169 | +| put 1000 MB through the box Caddy image | 200 (Caddy 22 MiB) | 237 MB | 143 | +| 1000 MB at 5 MB/s (200 s); via Caddy 10 MB/s | 200; no handler-budget cut | - | - | +| client aborts after 3 s | no partial object (GET 404) | - | - | +| body over 1 GiB | 413 `request body too large` (celld) | - | - | +| `CELLD_MAX_REQUEST_BODY_BYTES` above 1 GiB | celld refuses to start (`cannot exceed 1073741824`) | - | - | +| put with `onlyIf: {etagDoesNotMatch: '*'}` x2 | first writes, second returns null (write-once) | - | - | +| put with a wrong `sha256` | rejected | - | - | + +The body never sits in the isolate heap and RSS stays far below the body size, so streaming works. +**Hard limit:** one request through celld carries at most 1 GiB. Larger compose artifacts need a +parted upload, which changes the vm-agent client. Deferred to PR B (idea filed in this PR). + +## Design (PR A) + +``` + uploader ─(1) init (existing authenticated route)─► Worker: mint token {op, key, max, ct, sha?, exp} + uploader ─(2) PUT/GET https://api./api/self-host/objects?token=…─► Caddy ─► celld Worker + Worker ─(3) verify token → R2.put(key, body, {onlyIf: write-once, sha256?}) / R2.get(key) stream +``` + +- One URL-signing seam (`ObjectUrlSigner`): S3 presign (current code, unchanged bytes) or the box + signer. The box signer is installed only by the self-host build (`selfhost/build.ts`), so the + Cloudflare bundle cannot reach it. A box that still has a static key keeps direct presign. +- Token in the query string: the browser, vm-agent and builder clients PUT/GET opaque URLs, so no + client changes and no rollout coupling. Caddy never logs query strings; SAM's request log records + only the pathname. +- Key: HKDF-SHA256 from `ENCRYPTION_KEY` with its own label (the hosted-git token pattern, shared + helper). It rotates with `selfhost:secrets rotate`; `ENCRYPTION_KEY_PREVIOUS` verifies during the + overlap. No operator input, no new secret. + +## Threat model + +| Threat | Control | Test | +| --- | --- | --- | +| Forged token | HMAC-SHA256 over prefix+payload, constant-time verify, purpose-labelled HKDF key (a hosted-git token is not an object token) | tampered payload, wrong label, wrong key → 403, nothing written | +| Replay of an upload token | TTL = caller's existing presign TTL (≤ 15 min default); write-once put (`etagDoesNotMatch: '*'`); a retry after success answers 200 only when the stored object matches the token's size (and sha256 when bound) | second PUT with different bytes → 412, object unchanged; same bytes → 200 | +| Scope escape (other key/prefix, traversal) | the key lives only inside the signed payload; no path or query parameter names a key; key validated with the same unsafe-segment check as presign | extra `key=` param ignored; `..` key refused at mint | +| Method confusion | `op` claim: a GET token cannot PUT and vice versa | cross-op → 403 | +| Size DoS | `Content-Length` required and ≤ token `max` ≤ 1 GiB (celld cap); body wrapped in `FixedLengthStream`; celld refuses > 1 GiB before the Worker runs | over-max → 413 without a write; short body → no object | +| Integrity | build-context sha256 bound into the token and checked by `R2.put({sha256})`; compose artifacts keep size validation at completion | wrong bytes → 400/412 | +| Cross-user / cross-project writes | the token is minted only by the existing authenticated init routes (session auth for attachments, callback JWT + project policy for compose/build-context), which derive the key from the caller's verified identity; claims carry the user/project/workspace for audit logs | attack: user A's token cannot write user B's key; owner control writes its own key | +| Token leakage in logs | query string; Caddy logs no query; request log is pathname-only; tokens are never logged by the route | log assertion in route test | +| Egress fence / celld isolation | the route runs inside celld's Worker and talks only to the R2 binding (celld's bucket): no outbound fetch, nothing the egress fence must allow | n/a | + +## Checklist + +- [ ] Shared signed-token helper extracted from `selfhost/hosted-git/tokens.ts` (rule 59: extend, not fork); hosted-git tests unchanged and green +- [ ] Object URL token mint/verify (`selfhost/object-urls/tokens.ts`) +- [ ] Box route `PUT|GET /api/self-host/objects` (write-once put, sha256, size cap, FixedLengthStream, streaming GET) +- [ ] `ObjectUrlSigner` seam: app-deployment compose + build-context take a signer; attachments use it +- [ ] `getR2ObjectUrlSigner(env)`: presign when configured, else installed box signer, else `AppError` 503 naming the settings +- [ ] Attachments `request-upload` availability uses the same resolver (403 → works on box) +- [ ] Compose `maxBytes` clamped to the box limit so the agent fails before uploading +- [ ] Rule 74 tests: Cloudflare Env → presign; box Env (no key) → box route; box with key → presign +- [ ] Cloudflare byte-identity test still green (`r2-presign-cloudflare-equivalence.test.ts`) +- [ ] Self-host-only module test: Cloudflare bundle does not import the box signer +- [ ] Docs: `deploy/selfhost/README.md` "Object store and presigned uploads"; static key optional +- [ ] Idea for PR B (parted uploads > 1 GiB) +- [ ] Live celld test of the route (`scripts/selfhost/live`), small body + over-cap +- [ ] Disposable GCS box proof, no HMAC key: publish → release → app 200; attachment up/down; snapshot +- [ ] Staging: hosted attachments + compose publish still work + +## Acceptance criteria + +- A GCS box without an HMAC key: compose publish, task attachment upload/download and a session + snapshot all work. +- `compose-image-artifacts/init` returns 503 with the missing setting named, never 500. +- The hosted Cloudflare presign URLs are byte-identical (existing equivalence test). From 579860c09cb5eaefaccf16c5e07ad518c650277b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 09:52:59 +0000 Subject: [PATCH 02/19] test(selfhost): box object URL tokens, resolver choice, route and gate Co-Authored-By: Claude Opus 5.5 --- apps/api/src/selfhost/object-urls/route.ts | 12 +- .../unit/selfhost/box-object-urls.test.ts | 491 ++++++++++++++++++ .../selfhost/selfhost-only-modules.test.ts | 1 + 3 files changed, 500 insertions(+), 4 deletions(-) create mode 100644 apps/api/tests/unit/selfhost/box-object-urls.test.ts diff --git a/apps/api/src/selfhost/object-urls/route.ts b/apps/api/src/selfhost/object-urls/route.ts index 91a07aac67..66ea6f5955 100644 --- a/apps/api/src/selfhost/object-urls/route.ts +++ b/apps/api/src/selfhost/object-urls/route.ts @@ -5,8 +5,8 @@ * another. A PUT streams the body into the R2 binding (celld writes it to the fleet bucket without * holding it in the isolate), bounded by the token's size and verified against its sha256 when it * carries one. The write is create-only (`onlyIf: { etagDoesNotMatch: '*' }`), so a token cannot - * replace an object once written; a retry of a write that already succeeded answers 200 when the - * stored object is the one the token describes. + * replace an object once written. A retry of a write that already succeeded answers 200 when the + * token binds a sha256 the stored object matches (build contexts); otherwise 412. * * No SAM session or callback credential is involved: the token is the credential, minted only by * routes that already authorized the caller for that key. @@ -55,11 +55,15 @@ async function uploadLimits(env: Env): Promise<{ limit: number; leaseMs: number } } -/** True when the stored object is the one `claims` describes (a retried, already-finished PUT). */ +/** + * True when the stored object is provably the one `claims` describes, so a retried PUT that + * already succeeded can answer 200. Only a token that binds a sha256 can prove it: equal size + * alone could be different bytes, and answering 200 would tell the client its bytes were stored. + */ async function sameObject(env: Env, claims: BoxObjectTokenClaims, length: number) { + if (!claims.sha) return false; const existing = await env.R2.head(claims.key); if (!existing || existing.size !== length) return false; - if (!claims.sha) return true; const stored = existing.checksums?.sha256; const storedHex = stored ? [...new Uint8Array(stored)].map((byte) => byte.toString(16).padStart(2, '0')).join('') diff --git a/apps/api/tests/unit/selfhost/box-object-urls.test.ts b/apps/api/tests/unit/selfhost/box-object-urls.test.ts new file mode 100644 index 0000000000..fb9fcf8fbb --- /dev/null +++ b/apps/api/tests/unit/selfhost/box-object-urls.test.ts @@ -0,0 +1,491 @@ +/** + * Box object URLs (apps/api/src/selfhost/object-urls/): tokens, the signer the self-host build + * installs, the shared resolver's choice between R2 presign and the box (rule 74), and the PUT/GET + * route with its upload gate. The R2 fake enforces what celld's R2 binding enforces and the live + * suite proves on the real runtime (scripts/selfhost/live/box-object-urls.live.test.ts): + * create-only puts and sha256 verification. The gate is the real Durable Object class over SQLite. + */ +import Database from 'better-sqlite3'; +import { Hono } from 'hono'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; + +import { + composeImageArtifactMaxBytesFor, + createComposeImageArtifactDownloads, + createComposeImageArtifactUploads, + createBuildContextUpload, +} from '@simple-agent-manager/app-deployment'; + +import type { Env } from '../../../src/env'; +import { requestLoggingMiddleware } from '../../../src/middleware/request-logging'; +import { mintHostedGitToken } from '../../../src/selfhost/hosted-git/tokens'; +import { BoxUploadGate } from '../../../src/selfhost/object-urls/gate'; +import { installBoxObjectUrls, mountBoxObjectRoute } from '../../../src/selfhost/object-urls'; +import { + BOX_OBJECT_ROUTE, + CELLD_MAX_REQUEST_BODY_BYTES, + createBoxObjectUrlSigner, +} from '../../../src/selfhost/object-urls/signer'; +import { + isSafeObjectKey, + mintBoxObjectToken, + verifyBoxObjectToken, +} from '../../../src/selfhost/object-urls/tokens'; +import { generatePresignedUploadUrl } from '../../../src/services/attachment-upload'; +import { + getR2ObjectUrlSigner, + installBoxObjectUrlSigner, + resolveR2ObjectUrlSigner, + resetR2S3ClientsForTests, +} from '../../../src/services/r2-s3-client'; + +const KEY = 'box-test-encryption-key-0123456789'; +const DOMAIN = 'box.example.test'; + +// ── celld-faithful fakes ─────────────────────────────────────────────────────────────────────── + +/** workerd's FixedLengthStream: errors when the body is shorter or longer than declared. */ +class TestFixedLengthStream extends TransformStream { + constructor(expected: number) { + let seen = 0; + super({ + transform(chunk, controller) { + seen += chunk.byteLength; + if (seen > expected) throw new Error('FixedLengthStream: too many bytes'); + controller.enqueue(chunk); + }, + flush() { + if (seen !== expected) throw new Error('FixedLengthStream: too few bytes'); + }, + }); + } +} + +async function sha256Hex(bytes: Uint8Array): Promise { + const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)); + return [...digest].map((byte) => byte.toString(16).padStart(2, '0')).join(''); +} + +interface Stored { + bytes: Uint8Array; + contentType?: string; + customMetadata?: Record; + sha?: string; +} + +/** Create-only puts and sha256 checks as celld's R2 binding does them (live-verified). */ +function fakeR2() { + const objects = new Map(); + const bucket = { + objects, + async put( + key: string, + body: ReadableStream | Uint8Array, + options: { + onlyIf?: { etagDoesNotMatch?: string }; + httpMetadata?: { contentType?: string }; + customMetadata?: Record; + sha256?: string; + } = {} + ) { + const bytes = + body instanceof Uint8Array ? body : new Uint8Array(await new Response(body).arrayBuffer()); + if (options.onlyIf?.etagDoesNotMatch === '*' && objects.has(key)) return null; + const sha = await sha256Hex(bytes); + if (options.sha256 && options.sha256 !== sha) { + throw new Error(`R2 put: the sha256 checksum of the body is ${sha}, not ${options.sha256}`); + } + objects.set(key, { + bytes, + contentType: options.httpMetadata?.contentType, + customMetadata: options.customMetadata, + sha, + }); + return { size: bytes.byteLength, httpEtag: `"${sha.slice(0, 8)}"` }; + }, + async head(key: string) { + const object = objects.get(key); + if (!object) return null; + const checksum = Uint8Array.from(object.sha!.match(/../g)!, (h) => parseInt(h, 16)); + return { + size: object.bytes.byteLength, + customMetadata: object.customMetadata, + checksums: { sha256: checksum.buffer }, + }; + }, + async get(key: string) { + const object = objects.get(key); + if (!object) return null; + return { + size: object.bytes.byteLength, + httpEtag: '"etag"', + httpMetadata: { contentType: object.contentType }, + body: new Response(object.bytes).body, + }; + }, + }; + return bucket; +} + +/** `ctx.storage.sql` over better-sqlite3, for the real gate class. */ +function sqliteStorage() { + const db = new Database(':memory:'); + return { + exec(query: string, ...params: unknown[]) { + const statement = db.prepare(query); + const rows = statement.reader ? (statement.all(...params) as unknown[]) : (statement.run(...params), []); + return { one: () => rows[0], toArray: () => rows }; + }, + }; +} + +function gateNamespace(gate: BoxUploadGate) { + return { + idFromName: (name: string) => name, + get: () => ({ + acquire: async (id: string, limit: number, leaseMs: number) => gate.acquire(id, limit, leaseMs), + release: async (id: string) => gate.release(id), + }), + }; +} + +function boxEnv(overrides: Partial> = {}) { + const R2 = fakeR2(); + const gate = new BoxUploadGate({ storage: { sql: sqliteStorage() } } as never, {}); + const env = { + BASE_DOMAIN: DOMAIN, + ENCRYPTION_KEY: KEY, + R2, + BOX_UPLOAD_GATE: gateNamespace(gate), + ...overrides, + } as unknown as Env; + return { env, R2, gate }; +} + +function routeApp() { + const app = new Hono<{ Bindings: Env }>(); + app.use('*', requestLoggingMiddleware()); + mountBoxObjectRoute(app); + return app; +} + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text); +} + +async function putUrl(app: Hono<{ Bindings: Env }>, env: Env, url: string, body: Uint8Array, headers: Record = {}) { + const target = new URL(url); + return app.request( + `${target.pathname}${target.search}`, + { method: 'PUT', body, headers: { 'content-length': String(body.byteLength), ...headers } }, + env + ); +} + +beforeAll(() => { + (globalThis as { FixedLengthStream?: unknown }).FixedLengthStream = TestFixedLengthStream; +}); + +afterEach(() => { + installBoxObjectUrlSigner(null); + resetR2S3ClientsForTests(); + vi.restoreAllMocks(); +}); + +// ── tokens ───────────────────────────────────────────────────────────────────────────────────── + +describe('box object tokens', () => { + const env = { ENCRYPTION_KEY: KEY }; + const put = { op: 'put' as const, key: 'temp-uploads/u1/up1/a.txt', len: 5, expiresIn: 60 }; + + it('round-trips the claims while unexpired', async () => { + const token = await mintBoxObjectToken(env, put, 1_000_000); + expect(await verifyBoxObjectToken(env, token, 1_000_000 + 59_000)).toMatchObject({ + op: 'put', + key: put.key, + len: 5, + }); + expect(await verifyBoxObjectToken(env, token, 1_000_000 + 60_000)).toBeNull(); + }); + + it('refuses a tampered payload, a tampered signature and another installation', async () => { + const token = await mintBoxObjectToken(env, put); + const [prefix, payload, signature] = token.split('.') as [string, string, string]; + const claims = JSON.parse(atob(payload.replaceAll('-', '+').replaceAll('_', '/'))); + const forged = btoa(JSON.stringify({ ...claims, key: 'temp-uploads/u2/up/a.txt' })) + .replaceAll('+', '-') + .replaceAll('/', '_') + .replace(/=+$/, ''); + expect(await verifyBoxObjectToken(env, `${prefix}.${forged}.${signature}`)).toBeNull(); + expect(await verifyBoxObjectToken(env, `${prefix}.${payload}.${signature.slice(0, -2)}AA`)).toBeNull(); + expect(await verifyBoxObjectToken({ ENCRYPTION_KEY: 'another-installation-key' }, token)).toBeNull(); + // Control: the untouched token verifies. + expect(await verifyBoxObjectToken(env, token)).not.toBeNull(); + }); + + it('refuses a hosted-git token signed with the same ENCRYPTION_KEY (purpose separation)', async () => { + const { token } = await mintHostedGitToken(env, { repo: 'repo-a', scope: 'write' }); + expect(await verifyBoxObjectToken(env, token)).toBeNull(); + }); + + it('keeps tokens minted before a rotation valid through ENCRYPTION_KEY_PREVIOUS only', async () => { + const token = await mintBoxObjectToken({ ENCRYPTION_KEY: 'old-key-0123456789abcdef' }, put); + const rotated = { ENCRYPTION_KEY: 'new-key-0123456789abcdef', ENCRYPTION_KEY_PREVIOUS: 'old-key-0123456789abcdef' }; + expect(await verifyBoxObjectToken(rotated, token)).not.toBeNull(); + expect(await verifyBoxObjectToken({ ENCRYPTION_KEY: rotated.ENCRYPTION_KEY }, token)).toBeNull(); + }); + + it('refuses unsafe keys, unbounded PUTs and GET tokens carrying upload fields', async () => { + for (const key of ['../secrets', 'a/../b', '/abs', 'a//b', 'a\\b', 'a/\u0000']) { + expect(isSafeObjectKey(key)).toBe(false); + await expect(mintBoxObjectToken(env, { ...put, key })).rejects.toThrow('invalid'); + } + expect(isSafeObjectKey(put.key)).toBe(true); + await expect( + mintBoxObjectToken(env, { op: 'put', key: put.key, expiresIn: 60 }) + ).rejects.toThrow('invalid'); + await expect( + mintBoxObjectToken(env, { op: 'get', key: put.key, max: 5, expiresIn: 60 }) + ).rejects.toThrow('invalid'); + }); +}); + +// ── the resolver's choice (rule 74) ──────────────────────────────────────────────────────────── + +describe('which URL a caller gets', () => { + const cloudflare = { + CF_ACCOUNT_ID: 'acct', + R2_ACCESS_KEY_ID: 'AKID', + R2_SECRET_ACCESS_KEY: 'secret', + R2_BUCKET_NAME: 'bucket', + }; + + it('Cloudflare (no box signer installed) presigns, even without a key it cannot box', async () => { + const signer = getR2ObjectUrlSigner({ ...cloudflare, BASE_DOMAIN: DOMAIN, ENCRYPTION_KEY: KEY } as Env); + expect(signer.kind).toBe('presign'); + expect(new URL(await signer.putUrl('k', { expiresIn: 60 })).host).toMatch(/acct\.r2\.cloudflarestorage\.com$/); + // Divergence: a keyless Env on Cloudflare has no signer; it does not fall through to a box URL. + expect(resolveR2ObjectUrlSigner(boxEnv().env)).toBeNull(); + }); + + it('a keyless box resolves to the box route', async () => { + installBoxObjectUrls(); + const signer = getR2ObjectUrlSigner(boxEnv().env); + expect(signer.kind).toBe('box'); + const url = new URL(await signer.putUrl('k', { expiresIn: 60, contentLength: 3 })); + expect(`${url.origin}${url.pathname}`).toBe(`https://api.${DOMAIN}${BOX_OBJECT_ROUTE}`); + expect(url.searchParams.get('token')).toMatch(/^samobj1\./); + }); + + it('convergence: a box that still has a store key keeps direct presigned uploads', async () => { + installBoxObjectUrls(); + const { env } = boxEnv(cloudflare); + expect(getR2ObjectUrlSigner(env).kind).toBe('presign'); + }); + + it('nothing configured is a 503 naming the settings, not a 500', () => { + try { + getR2ObjectUrlSigner({} as Env); + expect.unreachable(); + } catch (error) { + expect((error as { statusCode: number }).statusCode).toBe(503); + expect((error as Error).message).toContain('R2_ACCESS_KEY_ID'); + } + }); +}); + +// ── callers through the box signer ───────────────────────────────────────────────────────────── + +describe('callers on a keyless box', () => { + it('compose init reports the box limit and gives box URLs for upload and download', async () => { + const { env } = boxEnv(); + const signer = createBoxObjectUrlSigner(env)!; + expect(composeImageArtifactMaxBytesFor(env, signer)).toBe(CELLD_MAX_REQUEST_BODY_BYTES); + const [upload] = await createComposeImageArtifactUploads( + env, + { projectId: 'p1', workspaceId: 'w1', environmentId: 'e1', uploadId: 'u1', services: [{ serviceName: 'web', sourceRef: 'web' }] }, + signer + ); + expect(upload!.maxBytes).toBe(CELLD_MAX_REQUEST_BODY_BYTES); + const claims = await verifyBoxObjectToken(env, new URL(upload!.uploadUrl).searchParams.get('token')!); + expect(claims).toMatchObject({ op: 'put', key: upload!.r2Key, max: CELLD_MAX_REQUEST_BODY_BYTES, sub: { p: 'p1', w: 'w1' } }); + const [download] = await createComposeImageArtifactDownloads( + env, + [{ serviceName: 'web', sourceRef: 'web', localImageRef: 'web', r2Key: upload!.r2Key, sizeBytes: 3, archiveType: 'docker-save', mediaType: 'x' } as never], + signer + ); + const getClaims = await verifyBoxObjectToken(env, new URL(download!.downloadUrl).searchParams.get('token')!); + expect(getClaims).toMatchObject({ op: 'get', key: upload!.r2Key }); + }); + + it('build-context uploads bind length, sha256 and its metadata into the token', async () => { + const { env } = boxEnv(); + const sha = 'a'.repeat(64); + const slot = await createBuildContextUpload( + { id: 'job', projectId: 'p1', workspaceId: 'w1', requestedBy: 'u1', environmentId: 'e1', attempt: 1 }, + { sizeBytes: 9, sha256: sha }, + 60, + createBoxObjectUrlSigner(env)! + ); + const claims = await verifyBoxObjectToken(env, new URL(slot.uploadUrl).searchParams.get('token')!); + expect(claims).toMatchObject({ key: slot.r2Key, len: 9, sha, md: { sha256: sha } }); + }); + + it('a single upload over 1 GiB is refused when the URL is requested', async () => { + const signer = createBoxObjectUrlSigner(boxEnv().env)!; + await expect( + signer.putUrl('k', { expiresIn: 60, contentLength: CELLD_MAX_REQUEST_BODY_BYTES + 1 }) + ).rejects.toMatchObject({ statusCode: 400 }); + }); + + it('attachment keys come from the authenticated user, so user B cannot get a URL for user A', async () => { + installBoxObjectUrls(); + const { env } = boxEnv(); + const options = { uploadId: 'up1', filename: 'a.txt', size: 5, contentType: 'text/plain' }; + const a = await generatePresignedUploadUrl(env, { ...options, userId: 'user-a' }); + const b = await generatePresignedUploadUrl(env, { ...options, userId: 'user-b' }); + const claimsB = await verifyBoxObjectToken(env, new URL(b.uploadUrl).searchParams.get('token')!); + expect(claimsB!.key).toBe(b.r2Key); + expect(claimsB!.key.startsWith('temp-uploads/user-b/')).toBe(true); + expect(a.r2Key.startsWith('temp-uploads/user-a/')).toBe(true); + }); +}); + +// ── the route ────────────────────────────────────────────────────────────────────────────────── + +describe('PUT/GET /api/box-objects', () => { + async function upload(env: Env, key: string, extra: Partial[1]> = {}) { + const signer = createBoxObjectUrlSigner(env)!; + return signer.putUrl(key, { expiresIn: 60, contentType: 'text/plain', ...extra }); + } + + it('streams the body into R2 and serves it back with a GET token', async () => { + const { env, R2 } = boxEnv(); + const app = routeApp(); + const url = await upload(env, 'temp-uploads/u1/up/a.txt', { contentLength: 5 }); + expect((await putUrl(app, env, url, bytes('hello'))).status).toBe(200); + expect(new TextDecoder().decode(R2.objects.get('temp-uploads/u1/up/a.txt')!.bytes)).toBe('hello'); + expect(R2.objects.get('temp-uploads/u1/up/a.txt')!.contentType).toBe('text/plain'); + + const getUrl = new URL(await createBoxObjectUrlSigner(env)!.getUrl('temp-uploads/u1/up/a.txt', { expiresIn: 60 })); + const response = await app.request(`${getUrl.pathname}${getUrl.search}`, {}, env); + expect(response.status).toBe(200); + expect(await response.text()).toBe('hello'); + }); + + it('attack: a token writes only its own key; an extra key parameter is ignored (owner control writes)', async () => { + const { env, R2 } = boxEnv(); + const app = routeApp(); + const url = new URL(await upload(env, 'temp-uploads/user-a/up/a.txt', { contentLength: 5 })); + url.searchParams.set('key', 'temp-uploads/user-b/up/a.txt'); + expect((await putUrl(app, env, url.toString(), bytes('owned'))).status).toBe(200); + expect(R2.objects.has('temp-uploads/user-b/up/a.txt')).toBe(false); + expect(R2.objects.has('temp-uploads/user-a/up/a.txt')).toBe(true); + }); + + it('refuses forged, expired, wrong-operation and missing tokens without writing', async () => { + const { env, R2 } = boxEnv(); + const app = routeApp(); + const getToken = await mintBoxObjectToken(env, { op: 'get', key: 'k', expiresIn: 60 }); + const expired = await mintBoxObjectToken(env, { op: 'put', key: 'k', len: 1, expiresIn: 1 }, Date.now() - 10_000); + const forged = await mintBoxObjectToken({ ENCRYPTION_KEY: 'another-installation-key' }, { op: 'put', key: 'k', len: 1, expiresIn: 60 }); + for (const token of [getToken, expired, forged, '']) { + const response = await putUrl(app, env, `https://x${BOX_OBJECT_ROUTE}?token=${encodeURIComponent(token)}`, bytes('x')); + expect(response.status).toBe(403); + } + expect(R2.objects.size).toBe(0); + }); + + it('bounds size: over the maximum is 413, a length other than the issued one 400, none 411', async () => { + const { env, R2 } = boxEnv(); + const app = routeApp(); + const bounded = await upload(env, 'k1', { maxBytes: 4 }); + expect((await putUrl(app, env, bounded, bytes('12345'))).status).toBe(413); + const exact = await upload(env, 'k2', { contentLength: 4 }); + expect((await putUrl(app, env, exact, bytes('123'))).status).toBe(400); + const target = new URL(exact); + const noLength = await app.request(`${target.pathname}${target.search}`, { method: 'PUT' }, env); + expect(noLength.status).toBe(411); + expect(R2.objects.size).toBe(0); + // Control: within bounds is written. + expect((await putUrl(app, env, bounded, bytes('1234'))).status).toBe(200); + }); + + it('is create-only: a second write is 412 and the object stays', async () => { + const { env, R2 } = boxEnv(); + const app = routeApp(); + const url = await upload(env, 'k', { contentLength: 5 }); + expect((await putUrl(app, env, url, bytes('first'))).status).toBe(200); + // Same length, other bytes: without a bound digest the route cannot tell, so it refuses. + expect((await putUrl(app, env, url, bytes('other'))).status).toBe(412); + expect((await putUrl(app, env, url, bytes('first'))).status).toBe(412); + expect(new TextDecoder().decode(R2.objects.get('k')!.bytes)).toBe('first'); + }); + + it('a retried PUT with a bound sha256 that already succeeded is 200 and replaces nothing', async () => { + const { env, R2 } = boxEnv(); + const app = routeApp(); + const body = bytes('first'); + const url = await upload(env, 'k', { contentLength: 5, sha256: await sha256Hex(body) }); + expect((await putUrl(app, env, url, body)).status).toBe(200); + expect((await putUrl(app, env, url, body)).status).toBe(200); + // Other bytes: 400 if the digest is checked first, 200 if the create-only check is (the stored + // object is exactly what the token describes). Either way nothing is replaced. + expect([200, 400]).toContain((await putUrl(app, env, url, bytes('other'))).status); + expect(new TextDecoder().decode(R2.objects.get('k')!.bytes)).toBe('first'); + }); + + it('verifies a bound sha256: wrong bytes are 400 and nothing is stored', async () => { + const { env, R2 } = boxEnv(); + const app = routeApp(); + const body = bytes('context'); + const url = await upload(env, 'ctx', { contentLength: body.byteLength, sha256: await sha256Hex(body) }); + expect((await putUrl(app, env, url, bytes('CONTEXT'))).status).toBe(400); + expect(R2.objects.has('ctx')).toBe(false); + expect((await putUrl(app, env, url, body)).status).toBe(200); + }); + + it('refuses with 503 and Retry-After while the box limit is in use, then admits once a slot frees', async () => { + const { env, R2, gate } = boxEnv(); + const app = routeApp(); + // Settings storage is unavailable in this env, so the default limit (4) applies. + for (let i = 0; i < 4; i++) gate.acquire(`held-${i}`, 4, 60_000); + const url = await upload(env, 'busy', { contentLength: 4 }); + const refused = await putUrl(app, env, url, bytes('busy')); + expect(refused.status).toBe(503); + expect(Number(refused.headers.get('Retry-After'))).toBeGreaterThan(0); + expect(R2.objects.has('busy')).toBe(false); + gate.release('held-0'); + expect((await putUrl(app, env, url, bytes('busy'))).status).toBe(200); + // The upload released its own lease: three held, one free. + expect(gate.acquire('probe', 4, 60_000)).toEqual({ granted: true }); + }); + + it('an expired lease frees its slot (a handler that died without releasing)', () => { + const { gate } = boxEnv(); + gate.acquire('dead', 1, 1_000, 0); + expect(gate.acquire('next', 1, 1_000, 500).granted).toBe(false); + expect(gate.acquire('next', 1, 1_000, 1_000).granted).toBe(true); + }); + + it('never logs the token: the request log and the route log carry the path only', async () => { + const { env } = boxEnv(); + const app = routeApp(); + const lines: string[] = []; + for (const method of ['log', 'info', 'warn', 'error'] as const) { + vi.spyOn(console, method).mockImplementation((...args: unknown[]) => { + lines.push(args.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))).join(' ')); + }); + } + const url = await upload(env, 'logged', { contentLength: 2 }); + const token = new URL(url).searchParams.get('token')!; + expect((await putUrl(app, env, url, bytes('ok'))).status).toBe(200); + await putUrl(app, env, `https://x${BOX_OBJECT_ROUTE}?token=${token}x`, bytes('ok')); + // Liveness: the request log and the route's own events were written. + expect(lines.some((line) => line.includes('http.request') && line.includes(BOX_OBJECT_ROUTE))).toBe(true); + expect(lines.some((line) => line.includes('box_objects.uploaded'))).toBe(true); + expect(lines.some((line) => line.includes('box_objects.token_refused'))).toBe(true); + const signature = token.split('.')[2]!; + expect(lines.filter((line) => line.includes(signature) || line.includes('token='))).toEqual([]); + }); +}); diff --git a/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts b/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts index bbb0d793fe..724893d2ab 100644 --- a/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts +++ b/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts @@ -116,6 +116,7 @@ describe('self-host-only code stays out of the Cloudflare Worker', () => { 'apps/api/src/selfhost/analytics/index.ts', 'apps/api/src/selfhost/speech/index.ts', 'apps/api/src/selfhost/reverse-tunnel/entry.ts', + 'apps/api/src/selfhost/object-urls/index.ts', ]) ); } From a915e19c6f826fa83cc65c95cdb208f2dca14ae6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 09:55:32 +0000 Subject: [PATCH 03/19] fix(selfhost): create-only box uploads above celld's 8 MiB conditional-put size; live celld test Co-Authored-By: Claude Opus 5.5 --- apps/api/src/selfhost/object-urls/route.ts | 39 ++-- .../unit/selfhost/box-object-urls.test.ts | 14 ++ .../live/box-object-urls.live.test.ts | 200 ++++++++++++++++++ 3 files changed, 241 insertions(+), 12 deletions(-) create mode 100644 scripts/selfhost/live/box-object-urls.live.test.ts diff --git a/apps/api/src/selfhost/object-urls/route.ts b/apps/api/src/selfhost/object-urls/route.ts index 66ea6f5955..40d769921c 100644 --- a/apps/api/src/selfhost/object-urls/route.ts +++ b/apps/api/src/selfhost/object-urls/route.ts @@ -4,9 +4,12 @@ * The token (`tokens.ts`) names one R2 key and one operation; nothing in the request can name * another. A PUT streams the body into the R2 binding (celld writes it to the fleet bucket without * holding it in the isolate), bounded by the token's size and verified against its sha256 when it - * carries one. The write is create-only (`onlyIf: { etagDoesNotMatch: '*' }`), so a token cannot - * replace an object once written. A retry of a write that already succeeded answers 200 when the - * token binds a sha256 the stored object matches (build contexts); otherwise 412. + * carries one. The write is create-only, so a token cannot replace an object once written: atomic + * (`onlyIf: { etagDoesNotMatch: '*' }`) up to celld's conditional-put size, and above it a check + * that no object exists before the write (celld writes larger streams as multipart uploads, whose + * completion takes no precondition). The gap that check leaves is only between two uploads with + * the same token, which only its holder has. A retry of a write that already succeeded answers 200 + * when the token binds a sha256 the stored object matches (build contexts); otherwise 412. * * No SAM session or callback credential is involved: the token is the credential, minted only by * routes that already authorized the caller for that key. @@ -27,6 +30,13 @@ import { type BoxObjectTokenClaims, verifyBoxObjectToken } from './tokens'; type BoxObjectEnv = Env & BoxUploadGateEnv; +/** + * Largest streamed body celld v0.6.3 can write with an `onlyIf` precondition. It refuses one above + * this: "celld cannot apply `onlyIf` to a streamed body larger than 8388608 bytes, because it is + * written as a multipart upload and a multipart completion takes no precondition" (live test). + */ +export const CELLD_CONDITIONAL_PUT_MAX_BYTES = 8 * 1024 * 1024; + function plain(status: number, message: string, headers: Record = {}): Response { return Response.json({ error: status === 503 ? 'BUSY' : 'BOX_OBJECT_REFUSED', message }, { status, @@ -71,6 +81,16 @@ async function sameObject(env: Env, claims: BoxObjectTokenClaims, length: number return storedHex === claims.sha; } +/** The object already exists: 200 for a provable retry of the same upload, else 412. */ +async function conflict(env: Env, claims: BoxObjectTokenClaims, length: number) { + if (await sameObject(env, claims, length)) { + log.info('box_objects.upload_replayed', { ...logFields(claims), length }); + return new Response(null, { status: 200 }); + } + log.warn('box_objects.upload_conflict', { ...logFields(claims), length, action: 'rejected' }); + return plain(412, 'An object was already written with this URL'); +} + async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectTokenClaims) { const env = c.env; const length = Number(c.req.header('content-length')); @@ -98,12 +118,14 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke }); } try { + const atomic = length <= CELLD_CONDITIONAL_PUT_MAX_BYTES; + if (!atomic && (await env.R2.head(claims.key))) return conflict(env, claims, length); // FixedLengthStream makes a short or long body an error instead of a truncated object. const stream = body ? body.pipeThrough(new FixedLengthStream(length)) : new Uint8Array(0); let written: R2Object | null; try { written = await env.R2.put(claims.key, stream, { - onlyIf: { etagDoesNotMatch: '*' }, + ...(atomic ? { onlyIf: { etagDoesNotMatch: '*' } } : {}), ...(claims.ct ? { httpMetadata: { contentType: claims.ct } } : {}), ...(claims.md ? { customMetadata: claims.md } : {}), ...(claims.sha ? { sha256: claims.sha } : {}), @@ -115,14 +137,7 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke ? plain(400, 'Upload body does not match the declared sha256') : plain(502, 'The upload did not complete; retry it'); } - if (!written) { - if (await sameObject(env, claims, length)) { - log.info('box_objects.upload_replayed', { ...logFields(claims), length }); - return new Response(null, { status: 200 }); - } - log.warn('box_objects.upload_conflict', { ...logFields(claims), length, action: 'rejected' }); - return plain(412, 'An object was already written with this URL'); - } + if (!written) return conflict(env, claims, length); log.info('box_objects.uploaded', { ...logFields(claims), length }); return new Response(null, { status: 200, headers: { ETag: written.httpEtag } }); } finally { diff --git a/apps/api/tests/unit/selfhost/box-object-urls.test.ts b/apps/api/tests/unit/selfhost/box-object-urls.test.ts index fb9fcf8fbb..fd893ec2d7 100644 --- a/apps/api/tests/unit/selfhost/box-object-urls.test.ts +++ b/apps/api/tests/unit/selfhost/box-object-urls.test.ts @@ -20,6 +20,7 @@ import type { Env } from '../../../src/env'; import { requestLoggingMiddleware } from '../../../src/middleware/request-logging'; import { mintHostedGitToken } from '../../../src/selfhost/hosted-git/tokens'; import { BoxUploadGate } from '../../../src/selfhost/object-urls/gate'; +import { CELLD_CONDITIONAL_PUT_MAX_BYTES } from '../../../src/selfhost/object-urls/route'; import { installBoxObjectUrls, mountBoxObjectRoute } from '../../../src/selfhost/object-urls'; import { BOX_OBJECT_ROUTE, @@ -422,6 +423,19 @@ describe('PUT/GET /api/box-objects', () => { expect(new TextDecoder().decode(R2.objects.get('k')!.bytes)).toBe('first'); }); + it('above celld conditional-put size it checks for an existing object instead of onlyIf', async () => { + const { env, R2 } = boxEnv(); + const app = routeApp(); + const putSpy = vi.spyOn(R2, 'put'); + const big = new Uint8Array(CELLD_CONDITIONAL_PUT_MAX_BYTES + 1).fill(7); + const url = await upload(env, 'big', { contentLength: big.byteLength }); + expect((await putUrl(app, env, url, big)).status).toBe(200); + expect(putSpy.mock.calls[0]![2]).not.toHaveProperty('onlyIf'); + expect((await putUrl(app, env, url, big.fill(8))).status).toBe(412); + expect(putSpy).toHaveBeenCalledTimes(1); + expect(R2.objects.get('big')!.bytes[0]).toBe(7); + }); + it('a retried PUT with a bound sha256 that already succeeded is 200 and replaces nothing', async () => { const { env, R2 } = boxEnv(); const app = routeApp(); diff --git a/scripts/selfhost/live/box-object-urls.live.test.ts b/scripts/selfhost/live/box-object-urls.live.test.ts new file mode 100644 index 0000000000..909fdb283f --- /dev/null +++ b/scripts/selfhost/live/box-object-urls.live.test.ts @@ -0,0 +1,200 @@ +/** + * Box object URLs on the real runtime (task tasks/active/2026-11-23-selfhost-box-object-uploads.md): + * the production route and upload gate from apps/api/src/selfhost/object-urls/, bundled by celld's + * own deploy, served by the pinned celld over the pinned object store. The unit suite + * (apps/api/tests/unit/selfhost/box-object-urls.test.ts) covers the logic with a fake bucket; this + * proves what only celld can: the body streams through FixedLengthStream into the R2 binding, + * create-only puts and sha256 checks hold, the gate Durable Object is reached over RPC, and a body + * over celld's 1 GiB ingress cap never reaches the Worker. + */ +import { createHash, randomBytes } from 'node:crypto'; +import { mkdirSync, mkdtempSync } from 'node:fs'; +import { request } from 'node:http'; +import { createRequire } from 'node:module'; +import { join } from 'node:path'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { ensureCelldBinary } from '../celld-binary.js'; +import { celldNode, type ObjectStore, startObjectStore, writeProject } from './celld-lab'; +import { LIVE_TMP, REPO_ROOT, type Running, skipWithoutDocker } from './harness'; + +const OBJECT_URLS = join(REPO_ROOT, 'apps/api/src/selfhost/object-urls'); +/** The project sits outside the repository, so bare packages resolve from apps/api. */ +const HONO = createRequire(join(REPO_ROOT, 'apps/api/package.json')).resolve('hono'); + +// The production route and gate, plus a mint endpoint standing in for the authenticated routes +// that mint URLs in SAM (attachments, compose, build context). +const WORKER = ` +import { Hono } from ${JSON.stringify(HONO)}; +import { mountBoxObjectRoute } from ${JSON.stringify(join(OBJECT_URLS, 'index.ts'))}; +import { createBoxObjectUrlSigner } from ${JSON.stringify(join(OBJECT_URLS, 'signer.ts'))}; +export { BoxUploadGate } from ${JSON.stringify(join(OBJECT_URLS, 'gate.ts'))}; + +const app = new Hono(); +app.get('/', (c) => c.text('ok')); +app.post('/mint', async (c) => { + const body = await c.req.json(); + const signer = createBoxObjectUrlSigner(c.env); + const url = body.op === 'get' + ? await signer.getUrl(body.key, { expiresIn: 300 }) + : await signer.putUrl(body.key, { expiresIn: 300, ...body.options }); + return c.json({ url }); +}); +mountBoxObjectRoute(app); +export default app; +`; + +const KEY = 'objectadmin'; +const SECRET = randomBytes(16).toString('hex'); +let store: ObjectStore; +let celld: Running | undefined; +let port = 0; + +/** A minted URL, rewritten to the local celld (the signer names https://api.). */ +async function mint(op: 'put' | 'get', key: string, options: Record = {}) { + const response = await fetch(`http://127.0.0.1:${port}/mint`, { + method: 'POST', + body: JSON.stringify({ op, key, options }), + }); + expect(response.status).toBe(200); + const url = new URL(((await response.json()) as { url: string }).url); + expect(url.hostname).toBe('api.box.test'); + return `http://127.0.0.1:${port}${url.pathname}${url.search}`; +} + +/** PUT with a declared length; the body may be written slowly or left open. */ +function put( + url: string, + length: number, + write: (req: ReturnType) => void +): Promise<{ status: number; headers: Record }> { + return new Promise((done, fail) => { + const req = request(url, { method: 'PUT', headers: { 'content-length': String(length) } }, (res) => { + res.resume(); + res.on('end', () => done({ status: res.statusCode ?? 0, headers: res.headers })); + }); + req.on('error', fail); + write(req); + }); +} + +const putBytes = (url: string, body: Buffer) => put(url, body.length, (req) => req.end(body)); + +describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { + beforeAll(async () => { + store = await startObjectStore(KEY, SECRET); + const node = await celldNode(await ensureCelldBinary(join(LIVE_TMP, 'celld-bin')), store); + port = node.port; + mkdirSync(LIVE_TMP, { recursive: true }); + const project = writeProject(mkdtempSync(join(LIVE_TMP, 'box-object-urls-')), { + name: 'box-object-urls', + main: 'worker.ts', + worker: WORKER, + bindings: { + compatibility_flags: ['nodejs_compat'], + r2_buckets: [{ binding: 'R2', bucket_name: 'files' }], + durable_objects: { bindings: [{ name: 'BOX_UPLOAD_GATE', class_name: 'BoxUploadGate' }] }, + migrations: [{ tag: 'v1', new_sqlite_classes: ['BoxUploadGate'] }], + }, + vars: { BASE_DOMAIN: 'box.test', ENCRYPTION_KEY: randomBytes(32).toString('base64') }, + }); + celld = await node.serve(project); + }); + + afterAll(async () => { + if (process.env.BOX_DEBUG) console.log(celld?.output().split('\n').filter((l) => l.includes('box_objects')).join('\n')); + await celld?.stop(); + store?.stop(); + }); + + it('streams a 64 MiB upload into R2 and back, sha256-verified', async () => { + const body = randomBytes(64 * 1024 * 1024); + const sha = createHash('sha256').update(body).digest('hex'); + const url = await mint('put', 'build/ctx.tar.zst', { + contentLength: body.length, + contentType: 'application/zstd', + sha256: sha, + metadata: { sha256: sha }, + }); + expect((await putBytes(url, body)).status).toBe(200); + // Retry of a finished upload with the bound digest: 200, nothing replaced. + expect((await putBytes(url, body)).status).toBe(200); + const download = await fetch(await mint('get', 'build/ctx.tar.zst')); + expect(download.status).toBe(200); + expect(download.headers.get('content-type')).toBe('application/zstd'); + const got = Buffer.from(await download.arrayBuffer()); + expect(createHash('sha256').update(got).digest('hex')).toBe(sha); + }, 120_000); + + it('refuses bytes that do not match the bound sha256, and stores nothing', async () => { + const body = randomBytes(1024); + const url = await mint('put', 'build/bad.tar.zst', { + contentLength: body.length, + sha256: createHash('sha256').update('something else').digest('hex'), + }); + expect((await putBytes(url, body)).status).toBe(400); + expect((await fetch(await mint('get', 'build/bad.tar.zst'))).status).toBe(404); + }); + + it('is create-only without a digest: the second write is 412 and the first stays', async () => { + const url = await mint('put', 'attach/a.txt', { contentLength: 5 }); + expect((await putBytes(url, Buffer.from('first'))).status).toBe(200); + expect((await putBytes(url, Buffer.from('other'))).status).toBe(412); + expect(await (await fetch(await mint('get', 'attach/a.txt'))).text()).toBe('first'); + }); + + it('is create-only above celld 8 MiB conditional-put size too (multipart writes)', async () => { + const body = randomBytes(9 * 1024 * 1024); + const url = await mint('put', 'artifacts/web.tar', { maxBytes: 64 * 1024 * 1024 }); + expect((await putBytes(url, body)).status).toBe(200); + expect((await putBytes(url, randomBytes(body.length))).status).toBe(412); + const got = Buffer.from(await (await fetch(await mint('get', 'artifacts/web.tar'))).arrayBuffer()); + expect(got.equals(body)).toBe(true); + }, 60_000); + + it('a body shorter than declared leaves no object', async () => { + const url = await mint('put', 'attach/short.bin', { maxBytes: 1024 }); + // Declares 100 bytes, sends 10, then closes: FixedLengthStream fails the put. + await put(url, 100, (req) => { + req.write(Buffer.alloc(10)); + setTimeout(() => req.destroy(), 300); + }).catch(() => undefined); + expect((await fetch(await mint('get', 'attach/short.bin'))).status).toBe(404); + }); + + it('over the token maximum is 413; over celld 1 GiB is refused before the Worker', async () => { + const small = await mint('put', 'attach/big.bin', { maxBytes: 10 }); + expect((await putBytes(small, Buffer.alloc(11))).status).toBe(413); + const huge = await mint('put', 'attach/huge.bin', { maxBytes: 1024 * 1024 * 1024 }); + const refused = await put(huge, 1024 * 1024 * 1024 + 1, (req) => req.write(Buffer.alloc(1))).catch( + () => ({ status: 413, headers: {} }) + ); + expect(refused.status).toBe(413); + }); + + it('holds at most four uploads at once: the fifth gets 503 with Retry-After', async () => { + const length = 1024 * 1024; + const held: Array> = []; + const pending = []; + for (let i = 0; i < 4; i++) { + const url = await mint('put', `busy/${i}`, { contentLength: length }); + pending.push( + put(url, length, (req) => { + req.write(Buffer.alloc(1024)); + held.push(req); + }) + ); + } + // Let the four reach the gate. + await new Promise((resolve) => setTimeout(resolve, 1500)); + const fifth = await putBytes(await mint('put', 'busy/5', { contentLength: 4 }), Buffer.from('five')); + expect(fifth.status).toBe(503); + expect(Number(fifth.headers['retry-after'])).toBeGreaterThan(0); + for (const req of held) req.end(Buffer.alloc(length - 1024)); + expect((await Promise.all(pending)).map((r) => r.status)).toEqual([200, 200, 200, 200]); + // Every lease was released: a new upload is admitted. + const after = await putBytes(await mint('put', 'busy/6', { contentLength: 3 }), Buffer.from('six')); + expect(after.status).toBe(200); + }, 60_000); +}); From 2fa91093e5c40581026464a084ca83757d4a16eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 09:56:02 +0000 Subject: [PATCH 04/19] style: format and sort imports Co-Authored-By: Claude Opus 5.5 --- apps/api/src/selfhost/object-urls/gate.ts | 11 +- apps/api/src/selfhost/object-urls/route.ts | 20 ++- apps/api/src/selfhost/signed-token.ts | 3 +- .../unit/selfhost/box-object-urls.test.ts | 162 ++++++++++++++---- .../src/build-context-upload.ts | 6 +- packages/app-deployment/src/index.ts | 14 +- .../tests/unit/build-context-presign.test.ts | 2 +- .../live/box-object-urls.live.test.ts | 41 +++-- .../2026-11-23-selfhost-box-object-uploads.md | 46 ++--- 9 files changed, 216 insertions(+), 89 deletions(-) diff --git a/apps/api/src/selfhost/object-urls/gate.ts b/apps/api/src/selfhost/object-urls/gate.ts index 29f10be3f5..6b6351173e 100644 --- a/apps/api/src/selfhost/object-urls/gate.ts +++ b/apps/api/src/selfhost/object-urls/gate.ts @@ -21,8 +21,7 @@ export interface BoxUploadGateEnv { } export type BoxUploadLease = - | { granted: true } - | { granted: false; active: number; retryAfterSeconds: number }; + { granted: true } | { granted: false; active: number; retryAfterSeconds: number }; /** Shortest and longest Retry-After hint (seconds) a refusal suggests. */ const MIN_RETRY_AFTER_SECONDS = 5; @@ -40,9 +39,11 @@ export class BoxUploadGate extends DurableObject { acquire(id: string, limit: number, leaseMs: number, now: number = Date.now()): BoxUploadLease { const sql = this.ctx.storage.sql; sql.exec('DELETE FROM upload_leases WHERE expires_at <= ?', now); - const row = sql.exec<{ active: number; next: number | null }>( - 'SELECT COUNT(*) AS active, MIN(expires_at) AS next FROM upload_leases' - ).one(); + const row = sql + .exec<{ active: number; next: number | null }>( + 'SELECT COUNT(*) AS active, MIN(expires_at) AS next FROM upload_leases' + ) + .one(); if (row.active >= limit) { // A hint, not a promise: most leases end when their upload finishes, long before expiry. const untilExpiry = Math.ceil(((row.next ?? now) - now) / 1000); diff --git a/apps/api/src/selfhost/object-urls/route.ts b/apps/api/src/selfhost/object-urls/route.ts index 40d769921c..b399afea1b 100644 --- a/apps/api/src/selfhost/object-urls/route.ts +++ b/apps/api/src/selfhost/object-urls/route.ts @@ -38,10 +38,13 @@ type BoxObjectEnv = Env & BoxUploadGateEnv; export const CELLD_CONDITIONAL_PUT_MAX_BYTES = 8 * 1024 * 1024; function plain(status: number, message: string, headers: Record = {}): Response { - return Response.json({ error: status === 503 ? 'BUSY' : 'BOX_OBJECT_REFUSED', message }, { - status, - headers, - }); + return Response.json( + { error: status === 503 ? 'BUSY' : 'BOX_OBJECT_REFUSED', message }, + { + status, + headers, + } + ); } /** Log fields that identify the request without the token. */ @@ -112,7 +115,11 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke const leaseId = crypto.randomUUID(); const lease = await gate.acquire(leaseId, limit, leaseMs); if (!lease.granted) { - log.warn('box_objects.upload_refused_busy', { ...logFields(claims), active: lease.active, limit }); + log.warn('box_objects.upload_refused_busy', { + ...logFields(claims), + active: lease.active, + limit, + }); return plain(503, `The box is already receiving ${lease.active} uploads; retry shortly`, { 'Retry-After': String(lease.retryAfterSeconds), }); @@ -155,7 +162,8 @@ async function get(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke const object = await c.env.R2.get(claims.key); if (!object) return plain(404, 'Object not found'); const headers = new Headers({ 'Content-Length': String(object.size), ETag: object.httpEtag }); - if (object.httpMetadata?.contentType) headers.set('Content-Type', object.httpMetadata.contentType); + if (object.httpMetadata?.contentType) + headers.set('Content-Type', object.httpMetadata.contentType); log.info('box_objects.downloaded', { ...logFields(claims), length: object.size }); return new Response(object.body, { status: 200, headers }); } diff --git a/apps/api/src/selfhost/signed-token.ts b/apps/api/src/selfhost/signed-token.ts index 0d1e9cb50f..d61d35fcb7 100644 --- a/apps/api/src/selfhost/signed-token.ts +++ b/apps/api/src/selfhost/signed-token.ts @@ -77,7 +77,8 @@ async function signingKey(label: string, secret: string): Promise { } function requireKey(env: Pick, purpose: SignedTokenPurpose) { - if (!env.ENCRYPTION_KEY) throw new Error(`ENCRYPTION_KEY is required for ${purpose.prefix} tokens`); + if (!env.ENCRYPTION_KEY) + throw new Error(`ENCRYPTION_KEY is required for ${purpose.prefix} tokens`); return env.ENCRYPTION_KEY; } diff --git a/apps/api/tests/unit/selfhost/box-object-urls.test.ts b/apps/api/tests/unit/selfhost/box-object-urls.test.ts index fd893ec2d7..3c6c40b051 100644 --- a/apps/api/tests/unit/selfhost/box-object-urls.test.ts +++ b/apps/api/tests/unit/selfhost/box-object-urls.test.ts @@ -5,23 +5,22 @@ * suite proves on the real runtime (scripts/selfhost/live/box-object-urls.live.test.ts): * create-only puts and sha256 verification. The gate is the real Durable Object class over SQLite. */ -import Database from 'better-sqlite3'; -import { Hono } from 'hono'; -import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; - import { composeImageArtifactMaxBytesFor, + createBuildContextUpload, createComposeImageArtifactDownloads, createComposeImageArtifactUploads, - createBuildContextUpload, } from '@simple-agent-manager/app-deployment'; +import Database from 'better-sqlite3'; +import { Hono } from 'hono'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; import { requestLoggingMiddleware } from '../../../src/middleware/request-logging'; import { mintHostedGitToken } from '../../../src/selfhost/hosted-git/tokens'; +import { installBoxObjectUrls, mountBoxObjectRoute } from '../../../src/selfhost/object-urls'; import { BoxUploadGate } from '../../../src/selfhost/object-urls/gate'; import { CELLD_CONDITIONAL_PUT_MAX_BYTES } from '../../../src/selfhost/object-urls/route'; -import { installBoxObjectUrls, mountBoxObjectRoute } from '../../../src/selfhost/object-urls'; import { BOX_OBJECT_ROUTE, CELLD_MAX_REQUEST_BODY_BYTES, @@ -36,8 +35,8 @@ import { generatePresignedUploadUrl } from '../../../src/services/attachment-upl import { getR2ObjectUrlSigner, installBoxObjectUrlSigner, - resolveR2ObjectUrlSigner, resetR2S3ClientsForTests, + resolveR2ObjectUrlSigner, } from '../../../src/services/r2-s3-client'; const KEY = 'box-test-encryption-key-0123456789'; @@ -134,7 +133,9 @@ function sqliteStorage() { return { exec(query: string, ...params: unknown[]) { const statement = db.prepare(query); - const rows = statement.reader ? (statement.all(...params) as unknown[]) : (statement.run(...params), []); + const rows = statement.reader + ? (statement.all(...params) as unknown[]) + : (statement.run(...params), []); return { one: () => rows[0], toArray: () => rows }; }, }; @@ -144,7 +145,8 @@ function gateNamespace(gate: BoxUploadGate) { return { idFromName: (name: string) => name, get: () => ({ - acquire: async (id: string, limit: number, leaseMs: number) => gate.acquire(id, limit, leaseMs), + acquire: async (id: string, limit: number, leaseMs: number) => + gate.acquire(id, limit, leaseMs), release: async (id: string) => gate.release(id), }), }; @@ -174,7 +176,13 @@ function bytes(text: string): Uint8Array { return new TextEncoder().encode(text); } -async function putUrl(app: Hono<{ Bindings: Env }>, env: Env, url: string, body: Uint8Array, headers: Record = {}) { +async function putUrl( + app: Hono<{ Bindings: Env }>, + env: Env, + url: string, + body: Uint8Array, + headers: Record = {} +) { const target = new URL(url); return app.request( `${target.pathname}${target.search}`, @@ -218,8 +226,12 @@ describe('box object tokens', () => { .replaceAll('/', '_') .replace(/=+$/, ''); expect(await verifyBoxObjectToken(env, `${prefix}.${forged}.${signature}`)).toBeNull(); - expect(await verifyBoxObjectToken(env, `${prefix}.${payload}.${signature.slice(0, -2)}AA`)).toBeNull(); - expect(await verifyBoxObjectToken({ ENCRYPTION_KEY: 'another-installation-key' }, token)).toBeNull(); + expect( + await verifyBoxObjectToken(env, `${prefix}.${payload}.${signature.slice(0, -2)}AA`) + ).toBeNull(); + expect( + await verifyBoxObjectToken({ ENCRYPTION_KEY: 'another-installation-key' }, token) + ).toBeNull(); // Control: the untouched token verifies. expect(await verifyBoxObjectToken(env, token)).not.toBeNull(); }); @@ -231,9 +243,14 @@ describe('box object tokens', () => { it('keeps tokens minted before a rotation valid through ENCRYPTION_KEY_PREVIOUS only', async () => { const token = await mintBoxObjectToken({ ENCRYPTION_KEY: 'old-key-0123456789abcdef' }, put); - const rotated = { ENCRYPTION_KEY: 'new-key-0123456789abcdef', ENCRYPTION_KEY_PREVIOUS: 'old-key-0123456789abcdef' }; + const rotated = { + ENCRYPTION_KEY: 'new-key-0123456789abcdef', + ENCRYPTION_KEY_PREVIOUS: 'old-key-0123456789abcdef', + }; expect(await verifyBoxObjectToken(rotated, token)).not.toBeNull(); - expect(await verifyBoxObjectToken({ ENCRYPTION_KEY: rotated.ENCRYPTION_KEY }, token)).toBeNull(); + expect( + await verifyBoxObjectToken({ ENCRYPTION_KEY: rotated.ENCRYPTION_KEY }, token) + ).toBeNull(); }); it('refuses unsafe keys, unbounded PUTs and GET tokens carrying upload fields', async () => { @@ -262,9 +279,15 @@ describe('which URL a caller gets', () => { }; it('Cloudflare (no box signer installed) presigns, even without a key it cannot box', async () => { - const signer = getR2ObjectUrlSigner({ ...cloudflare, BASE_DOMAIN: DOMAIN, ENCRYPTION_KEY: KEY } as Env); + const signer = getR2ObjectUrlSigner({ + ...cloudflare, + BASE_DOMAIN: DOMAIN, + ENCRYPTION_KEY: KEY, + } as Env); expect(signer.kind).toBe('presign'); - expect(new URL(await signer.putUrl('k', { expiresIn: 60 })).host).toMatch(/acct\.r2\.cloudflarestorage\.com$/); + expect(new URL(await signer.putUrl('k', { expiresIn: 60 })).host).toMatch( + /acct\.r2\.cloudflarestorage\.com$/ + ); // Divergence: a keyless Env on Cloudflare has no signer; it does not fall through to a box URL. expect(resolveR2ObjectUrlSigner(boxEnv().env)).toBeNull(); }); @@ -304,18 +327,45 @@ describe('callers on a keyless box', () => { expect(composeImageArtifactMaxBytesFor(env, signer)).toBe(CELLD_MAX_REQUEST_BODY_BYTES); const [upload] = await createComposeImageArtifactUploads( env, - { projectId: 'p1', workspaceId: 'w1', environmentId: 'e1', uploadId: 'u1', services: [{ serviceName: 'web', sourceRef: 'web' }] }, + { + projectId: 'p1', + workspaceId: 'w1', + environmentId: 'e1', + uploadId: 'u1', + services: [{ serviceName: 'web', sourceRef: 'web' }], + }, signer ); expect(upload!.maxBytes).toBe(CELLD_MAX_REQUEST_BODY_BYTES); - const claims = await verifyBoxObjectToken(env, new URL(upload!.uploadUrl).searchParams.get('token')!); - expect(claims).toMatchObject({ op: 'put', key: upload!.r2Key, max: CELLD_MAX_REQUEST_BODY_BYTES, sub: { p: 'p1', w: 'w1' } }); + const claims = await verifyBoxObjectToken( + env, + new URL(upload!.uploadUrl).searchParams.get('token')! + ); + expect(claims).toMatchObject({ + op: 'put', + key: upload!.r2Key, + max: CELLD_MAX_REQUEST_BODY_BYTES, + sub: { p: 'p1', w: 'w1' }, + }); const [download] = await createComposeImageArtifactDownloads( env, - [{ serviceName: 'web', sourceRef: 'web', localImageRef: 'web', r2Key: upload!.r2Key, sizeBytes: 3, archiveType: 'docker-save', mediaType: 'x' } as never], + [ + { + serviceName: 'web', + sourceRef: 'web', + localImageRef: 'web', + r2Key: upload!.r2Key, + sizeBytes: 3, + archiveType: 'docker-save', + mediaType: 'x', + } as never, + ], signer ); - const getClaims = await verifyBoxObjectToken(env, new URL(download!.downloadUrl).searchParams.get('token')!); + const getClaims = await verifyBoxObjectToken( + env, + new URL(download!.downloadUrl).searchParams.get('token')! + ); expect(getClaims).toMatchObject({ op: 'get', key: upload!.r2Key }); }); @@ -323,12 +373,22 @@ describe('callers on a keyless box', () => { const { env } = boxEnv(); const sha = 'a'.repeat(64); const slot = await createBuildContextUpload( - { id: 'job', projectId: 'p1', workspaceId: 'w1', requestedBy: 'u1', environmentId: 'e1', attempt: 1 }, + { + id: 'job', + projectId: 'p1', + workspaceId: 'w1', + requestedBy: 'u1', + environmentId: 'e1', + attempt: 1, + }, { sizeBytes: 9, sha256: sha }, 60, createBoxObjectUrlSigner(env)! ); - const claims = await verifyBoxObjectToken(env, new URL(slot.uploadUrl).searchParams.get('token')!); + const claims = await verifyBoxObjectToken( + env, + new URL(slot.uploadUrl).searchParams.get('token')! + ); expect(claims).toMatchObject({ key: slot.r2Key, len: 9, sha, md: { sha256: sha } }); }); @@ -345,7 +405,10 @@ describe('callers on a keyless box', () => { const options = { uploadId: 'up1', filename: 'a.txt', size: 5, contentType: 'text/plain' }; const a = await generatePresignedUploadUrl(env, { ...options, userId: 'user-a' }); const b = await generatePresignedUploadUrl(env, { ...options, userId: 'user-b' }); - const claimsB = await verifyBoxObjectToken(env, new URL(b.uploadUrl).searchParams.get('token')!); + const claimsB = await verifyBoxObjectToken( + env, + new URL(b.uploadUrl).searchParams.get('token')! + ); expect(claimsB!.key).toBe(b.r2Key); expect(claimsB!.key.startsWith('temp-uploads/user-b/')).toBe(true); expect(a.r2Key.startsWith('temp-uploads/user-a/')).toBe(true); @@ -355,7 +418,11 @@ describe('callers on a keyless box', () => { // ── the route ────────────────────────────────────────────────────────────────────────────────── describe('PUT/GET /api/box-objects', () => { - async function upload(env: Env, key: string, extra: Partial[1]> = {}) { + async function upload( + env: Env, + key: string, + extra: Partial[1]> = {} + ) { const signer = createBoxObjectUrlSigner(env)!; return signer.putUrl(key, { expiresIn: 60, contentType: 'text/plain', ...extra }); } @@ -365,10 +432,14 @@ describe('PUT/GET /api/box-objects', () => { const app = routeApp(); const url = await upload(env, 'temp-uploads/u1/up/a.txt', { contentLength: 5 }); expect((await putUrl(app, env, url, bytes('hello'))).status).toBe(200); - expect(new TextDecoder().decode(R2.objects.get('temp-uploads/u1/up/a.txt')!.bytes)).toBe('hello'); + expect(new TextDecoder().decode(R2.objects.get('temp-uploads/u1/up/a.txt')!.bytes)).toBe( + 'hello' + ); expect(R2.objects.get('temp-uploads/u1/up/a.txt')!.contentType).toBe('text/plain'); - const getUrl = new URL(await createBoxObjectUrlSigner(env)!.getUrl('temp-uploads/u1/up/a.txt', { expiresIn: 60 })); + const getUrl = new URL( + await createBoxObjectUrlSigner(env)!.getUrl('temp-uploads/u1/up/a.txt', { expiresIn: 60 }) + ); const response = await app.request(`${getUrl.pathname}${getUrl.search}`, {}, env); expect(response.status).toBe(200); expect(await response.text()).toBe('hello'); @@ -388,10 +459,22 @@ describe('PUT/GET /api/box-objects', () => { const { env, R2 } = boxEnv(); const app = routeApp(); const getToken = await mintBoxObjectToken(env, { op: 'get', key: 'k', expiresIn: 60 }); - const expired = await mintBoxObjectToken(env, { op: 'put', key: 'k', len: 1, expiresIn: 1 }, Date.now() - 10_000); - const forged = await mintBoxObjectToken({ ENCRYPTION_KEY: 'another-installation-key' }, { op: 'put', key: 'k', len: 1, expiresIn: 60 }); + const expired = await mintBoxObjectToken( + env, + { op: 'put', key: 'k', len: 1, expiresIn: 1 }, + Date.now() - 10_000 + ); + const forged = await mintBoxObjectToken( + { ENCRYPTION_KEY: 'another-installation-key' }, + { op: 'put', key: 'k', len: 1, expiresIn: 60 } + ); for (const token of [getToken, expired, forged, '']) { - const response = await putUrl(app, env, `https://x${BOX_OBJECT_ROUTE}?token=${encodeURIComponent(token)}`, bytes('x')); + const response = await putUrl( + app, + env, + `https://x${BOX_OBJECT_ROUTE}?token=${encodeURIComponent(token)}`, + bytes('x') + ); expect(response.status).toBe(403); } expect(R2.objects.size).toBe(0); @@ -405,7 +488,11 @@ describe('PUT/GET /api/box-objects', () => { const exact = await upload(env, 'k2', { contentLength: 4 }); expect((await putUrl(app, env, exact, bytes('123'))).status).toBe(400); const target = new URL(exact); - const noLength = await app.request(`${target.pathname}${target.search}`, { method: 'PUT' }, env); + const noLength = await app.request( + `${target.pathname}${target.search}`, + { method: 'PUT' }, + env + ); expect(noLength.status).toBe(411); expect(R2.objects.size).toBe(0); // Control: within bounds is written. @@ -453,7 +540,10 @@ describe('PUT/GET /api/box-objects', () => { const { env, R2 } = boxEnv(); const app = routeApp(); const body = bytes('context'); - const url = await upload(env, 'ctx', { contentLength: body.byteLength, sha256: await sha256Hex(body) }); + const url = await upload(env, 'ctx', { + contentLength: body.byteLength, + sha256: await sha256Hex(body), + }); expect((await putUrl(app, env, url, bytes('CONTEXT'))).status).toBe(400); expect(R2.objects.has('ctx')).toBe(false); expect((await putUrl(app, env, url, body)).status).toBe(200); @@ -488,7 +578,9 @@ describe('PUT/GET /api/box-objects', () => { const lines: string[] = []; for (const method of ['log', 'info', 'warn', 'error'] as const) { vi.spyOn(console, method).mockImplementation((...args: unknown[]) => { - lines.push(args.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))).join(' ')); + lines.push( + args.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))).join(' ') + ); }); } const url = await upload(env, 'logged', { contentLength: 2 }); @@ -496,7 +588,9 @@ describe('PUT/GET /api/box-objects', () => { expect((await putUrl(app, env, url, bytes('ok'))).status).toBe(200); await putUrl(app, env, `https://x${BOX_OBJECT_ROUTE}?token=${token}x`, bytes('ok')); // Liveness: the request log and the route's own events were written. - expect(lines.some((line) => line.includes('http.request') && line.includes(BOX_OBJECT_ROUTE))).toBe(true); + expect( + lines.some((line) => line.includes('http.request') && line.includes(BOX_OBJECT_ROUTE)) + ).toBe(true); expect(lines.some((line) => line.includes('box_objects.uploaded'))).toBe(true); expect(lines.some((line) => line.includes('box_objects.token_refused'))).toBe(true); const signature = token.split('.')[2]!; diff --git a/packages/app-deployment/src/build-context-upload.ts b/packages/app-deployment/src/build-context-upload.ts index 4ef7b8b9a3..33236bb0f5 100644 --- a/packages/app-deployment/src/build-context-upload.ts +++ b/packages/app-deployment/src/build-context-upload.ts @@ -20,7 +20,11 @@ export async function createBuildContextUpload( contentType: 'application/zstd', metadata: { sha256: descriptor.sha256 }, sha256: descriptor.sha256, - owner: { userId: owner.requestedBy, projectId: owner.projectId, workspaceId: owner.workspaceId }, + owner: { + userId: owner.requestedBy, + projectId: owner.projectId, + workspaceId: owner.workspaceId, + }, }); return { r2Key, uploadUrl, expiresIn }; } diff --git a/packages/app-deployment/src/index.ts b/packages/app-deployment/src/index.ts index 75a586e044..fa3f387578 100644 --- a/packages/app-deployment/src/index.ts +++ b/packages/app-deployment/src/index.ts @@ -36,20 +36,14 @@ export type { export { buildComposeImageArtifactKey, COMPOSE_IMAGE_ARTIFACT_ARCHIVE_TYPE, - composeImageArtifactMaxBytesFor, COMPOSE_IMAGE_ARTIFACT_MEDIA_TYPE, + composeImageArtifactMaxBytesFor, createComposeImageArtifactDownloads, createComposeImageArtifactUploads, getComposeImageArtifactMaxBytes, validateCompletedComposeImageArtifacts, validateComposeImageArtifactDescriptor, } from './compose-image-artifacts'; -export type { - ObjectPutUrlOptions, - ObjectUrlSigner, - S3PresignTarget, -} from './object-url-signer'; -export { s3ObjectUrlSigner } from './object-url-signer'; export type { ComposePublishApplyOptions, ComposePublishApplyResult, @@ -214,6 +208,12 @@ export type { export { createImageResolver, ImageResolveError } from './image-resolver'; export type { ResolverRuntimeOptions } from './image-resolver-outbound'; export { getImageResolverConfig } from './image-resolver-outbound'; +export type { + ObjectPutUrlOptions, + ObjectUrlSigner, + S3PresignTarget, +} from './object-url-signer'; +export { s3ObjectUrlSigner } from './object-url-signer'; export type { DeploymentLifecyclePort, DeploymentProviderPort, diff --git a/packages/app-deployment/tests/unit/build-context-presign.test.ts b/packages/app-deployment/tests/unit/build-context-presign.test.ts index 2dc2dbf37b..6c3c634cbf 100644 --- a/packages/app-deployment/tests/unit/build-context-presign.test.ts +++ b/packages/app-deployment/tests/unit/build-context-presign.test.ts @@ -14,7 +14,7 @@ import { createComposeImageArtifactUploads, } from '../../src/compose-image-artifacts'; import type { AppDeploymentEnv } from '../../src/env'; -import { type S3PresignTarget, s3ObjectUrlSigner } from '../../src/object-url-signer'; +import { s3ObjectUrlSigner,type S3PresignTarget } from '../../src/object-url-signer'; const secret = 'fake-secret'; // The worker's shared R2 client (apps/api/src/services/r2-s3-client.ts) as it is configured on diff --git a/scripts/selfhost/live/box-object-urls.live.test.ts b/scripts/selfhost/live/box-object-urls.live.test.ts index 909fdb283f..9aa8bd5260 100644 --- a/scripts/selfhost/live/box-object-urls.live.test.ts +++ b/scripts/selfhost/live/box-object-urls.live.test.ts @@ -70,10 +70,14 @@ function put( write: (req: ReturnType) => void ): Promise<{ status: number; headers: Record }> { return new Promise((done, fail) => { - const req = request(url, { method: 'PUT', headers: { 'content-length': String(length) } }, (res) => { - res.resume(); - res.on('end', () => done({ status: res.statusCode ?? 0, headers: res.headers })); - }); + const req = request( + url, + { method: 'PUT', headers: { 'content-length': String(length) } }, + (res) => { + res.resume(); + res.on('end', () => done({ status: res.statusCode ?? 0, headers: res.headers })); + } + ); req.on('error', fail); write(req); }); @@ -103,7 +107,14 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { }); afterAll(async () => { - if (process.env.BOX_DEBUG) console.log(celld?.output().split('\n').filter((l) => l.includes('box_objects')).join('\n')); + if (process.env.BOX_DEBUG) + console.log( + celld + ?.output() + .split('\n') + .filter((l) => l.includes('box_objects')) + .join('\n') + ); await celld?.stop(); store?.stop(); }); @@ -149,7 +160,9 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { const url = await mint('put', 'artifacts/web.tar', { maxBytes: 64 * 1024 * 1024 }); expect((await putBytes(url, body)).status).toBe(200); expect((await putBytes(url, randomBytes(body.length))).status).toBe(412); - const got = Buffer.from(await (await fetch(await mint('get', 'artifacts/web.tar'))).arrayBuffer()); + const got = Buffer.from( + await (await fetch(await mint('get', 'artifacts/web.tar'))).arrayBuffer() + ); expect(got.equals(body)).toBe(true); }, 60_000); @@ -167,9 +180,9 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { const small = await mint('put', 'attach/big.bin', { maxBytes: 10 }); expect((await putBytes(small, Buffer.alloc(11))).status).toBe(413); const huge = await mint('put', 'attach/huge.bin', { maxBytes: 1024 * 1024 * 1024 }); - const refused = await put(huge, 1024 * 1024 * 1024 + 1, (req) => req.write(Buffer.alloc(1))).catch( - () => ({ status: 413, headers: {} }) - ); + const refused = await put(huge, 1024 * 1024 * 1024 + 1, (req) => + req.write(Buffer.alloc(1)) + ).catch(() => ({ status: 413, headers: {} })); expect(refused.status).toBe(413); }); @@ -188,13 +201,19 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { } // Let the four reach the gate. await new Promise((resolve) => setTimeout(resolve, 1500)); - const fifth = await putBytes(await mint('put', 'busy/5', { contentLength: 4 }), Buffer.from('five')); + const fifth = await putBytes( + await mint('put', 'busy/5', { contentLength: 4 }), + Buffer.from('five') + ); expect(fifth.status).toBe(503); expect(Number(fifth.headers['retry-after'])).toBeGreaterThan(0); for (const req of held) req.end(Buffer.alloc(length - 1024)); expect((await Promise.all(pending)).map((r) => r.status)).toEqual([200, 200, 200, 200]); // Every lease was released: a new upload is admitted. - const after = await putBytes(await mint('put', 'busy/6', { contentLength: 3 }), Buffer.from('six')); + const after = await putBytes( + await mint('put', 'busy/6', { contentLength: 3 }), + Buffer.from('six') + ); expect(after.status).toBe(200); }, 60_000); }); diff --git a/tasks/active/2026-11-23-selfhost-box-object-uploads.md b/tasks/active/2026-11-23-selfhost-box-object-uploads.md index 983d29c5df..446b45512c 100644 --- a/tasks/active/2026-11-23-selfhost-box-object-uploads.md +++ b/tasks/active/2026-11-23-selfhost-box-object-uploads.md @@ -16,18 +16,18 @@ R2 interface). ## Phase 1 proof (done 2026-11-23, local celld v0.6.3 + MinIO, `CELLD_V8_HEAP_LIMIT_MB=128`) -| case | result | celld RSS peak (idle 43 MB) | MB/s | -| --------------------------------------------- | ----------------------------------------------- | --------------------------- | ---- | -| `R2.put(request.body)` 256 MB | 200, sha matches on download | 145 MB | 101 | -| `R2.put(request.body)` 1023 MB | 200, sha matches | 220 MB | 132 | -| R2 multipart, 16 MB parts, 1023 MB | 200 | 308 MB | 169 | -| put 1000 MB through the box Caddy image | 200 (Caddy 22 MiB) | 237 MB | 143 | -| 1000 MB at 5 MB/s (200 s); via Caddy 10 MB/s | 200; no handler-budget cut | - | - | -| client aborts after 3 s | no partial object (GET 404) | - | - | -| body over 1 GiB | 413 `request body too large` (celld) | - | - | -| `CELLD_MAX_REQUEST_BODY_BYTES` above 1 GiB | celld refuses to start (`cannot exceed 1073741824`) | - | - | -| put with `onlyIf: {etagDoesNotMatch: '*'}` x2 | first writes, second returns null (write-once) | - | - | -| put with a wrong `sha256` | rejected | - | - | +| case | result | celld RSS peak (idle 43 MB) | MB/s | +| --------------------------------------------- | --------------------------------------------------- | --------------------------- | ---- | +| `R2.put(request.body)` 256 MB | 200, sha matches on download | 145 MB | 101 | +| `R2.put(request.body)` 1023 MB | 200, sha matches | 220 MB | 132 | +| R2 multipart, 16 MB parts, 1023 MB | 200 | 308 MB | 169 | +| put 1000 MB through the box Caddy image | 200 (Caddy 22 MiB) | 237 MB | 143 | +| 1000 MB at 5 MB/s (200 s); via Caddy 10 MB/s | 200; no handler-budget cut | - | - | +| client aborts after 3 s | no partial object (GET 404) | - | - | +| body over 1 GiB | 413 `request body too large` (celld) | - | - | +| `CELLD_MAX_REQUEST_BODY_BYTES` above 1 GiB | celld refuses to start (`cannot exceed 1073741824`) | - | - | +| put with `onlyIf: {etagDoesNotMatch: '*'}` x2 | first writes, second returns null (write-once) | - | - | +| put with a wrong `sha256` | rejected | - | - | The body never sits in the isolate heap and RSS stays far below the body size, so streaming works. **Hard limit:** one request through celld carries at most 1 GiB. Larger compose artifacts need a @@ -53,17 +53,17 @@ parted upload, which changes the vm-agent client. Deferred to PR B (idea filed i ## Threat model -| Threat | Control | Test | -| --- | --- | --- | -| Forged token | HMAC-SHA256 over prefix+payload, constant-time verify, purpose-labelled HKDF key (a hosted-git token is not an object token) | tampered payload, wrong label, wrong key → 403, nothing written | -| Replay of an upload token | TTL = caller's existing presign TTL (≤ 15 min default); write-once put (`etagDoesNotMatch: '*'`); a retry after success answers 200 only when the stored object matches the token's size (and sha256 when bound) | second PUT with different bytes → 412, object unchanged; same bytes → 200 | -| Scope escape (other key/prefix, traversal) | the key lives only inside the signed payload; no path or query parameter names a key; key validated with the same unsafe-segment check as presign | extra `key=` param ignored; `..` key refused at mint | -| Method confusion | `op` claim: a GET token cannot PUT and vice versa | cross-op → 403 | -| Size DoS | `Content-Length` required and ≤ token `max` ≤ 1 GiB (celld cap); body wrapped in `FixedLengthStream`; celld refuses > 1 GiB before the Worker runs | over-max → 413 without a write; short body → no object | -| Integrity | build-context sha256 bound into the token and checked by `R2.put({sha256})`; compose artifacts keep size validation at completion | wrong bytes → 400/412 | -| Cross-user / cross-project writes | the token is minted only by the existing authenticated init routes (session auth for attachments, callback JWT + project policy for compose/build-context), which derive the key from the caller's verified identity; claims carry the user/project/workspace for audit logs | attack: user A's token cannot write user B's key; owner control writes its own key | -| Token leakage in logs | query string; Caddy logs no query; request log is pathname-only; tokens are never logged by the route | log assertion in route test | -| Egress fence / celld isolation | the route runs inside celld's Worker and talks only to the R2 binding (celld's bucket): no outbound fetch, nothing the egress fence must allow | n/a | +| Threat | Control | Test | +| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| Forged token | HMAC-SHA256 over prefix+payload, constant-time verify, purpose-labelled HKDF key (a hosted-git token is not an object token) | tampered payload, wrong label, wrong key → 403, nothing written | +| Replay of an upload token | TTL = caller's existing presign TTL (≤ 15 min default); write-once put (`etagDoesNotMatch: '*'`); a retry after success answers 200 only when the stored object matches the token's size (and sha256 when bound) | second PUT with different bytes → 412, object unchanged; same bytes → 200 | +| Scope escape (other key/prefix, traversal) | the key lives only inside the signed payload; no path or query parameter names a key; key validated with the same unsafe-segment check as presign | extra `key=` param ignored; `..` key refused at mint | +| Method confusion | `op` claim: a GET token cannot PUT and vice versa | cross-op → 403 | +| Size DoS | `Content-Length` required and ≤ token `max` ≤ 1 GiB (celld cap); body wrapped in `FixedLengthStream`; celld refuses > 1 GiB before the Worker runs | over-max → 413 without a write; short body → no object | +| Integrity | build-context sha256 bound into the token and checked by `R2.put({sha256})`; compose artifacts keep size validation at completion | wrong bytes → 400/412 | +| Cross-user / cross-project writes | the token is minted only by the existing authenticated init routes (session auth for attachments, callback JWT + project policy for compose/build-context), which derive the key from the caller's verified identity; claims carry the user/project/workspace for audit logs | attack: user A's token cannot write user B's key; owner control writes its own key | +| Token leakage in logs | query string; Caddy logs no query; request log is pathname-only; tokens are never logged by the route | log assertion in route test | +| Egress fence / celld isolation | the route runs inside celld's Worker and talks only to the R2 binding (celld's bucket): no outbound fetch, nothing the egress fence must allow | n/a | ## Checklist From 14e8cfa554449abd51687286a6783a9c04f2ec8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 09:56:33 +0000 Subject: [PATCH 05/19] docs(selfhost): uploads through the box; the static store key is optional Co-Authored-By: Claude Opus 5.5 --- deploy/selfhost/.env.example | 9 ++++---- deploy/selfhost/README.md | 44 +++++++++++++++++++++++++++++------- 2 files changed, 41 insertions(+), 12 deletions(-) diff --git a/deploy/selfhost/.env.example b/deploy/selfhost/.env.example index 448e57d559..87d7567fc9 100644 --- a/deploy/selfhost/.env.example +++ b/deploy/selfhost/.env.example @@ -57,10 +57,11 @@ CELLD_BUCKET=gs://my-sam-bucket/celld # MAIL_COLLECTOR_SMTP_PORT=1025 and MAIL_COLLECTOR_UI_PORT=8025 (below), and the port of # SAM_MX_LISTEN (sam-mx, default :25), are box ports too. -# Presigned browser uploads (attachments, snapshots) go straight to the fleet bucket. Set the -# store's public HTTPS endpoint here and a credential scoped to //r2//* -# as R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY in .state/secrets.env (never the fleet credential). -# The deploy derives the bucket and key prefix. Unset: presigned uploads stay off. +# Optional. Uploads (attachments, build contexts, image artifacts) go through the box by default, +# with no store credential (README, Object store and uploads through the box). To send them straight +# to the fleet bucket instead, set the store's public HTTPS endpoint here and a credential scoped to +# //r2//* as R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY in +# .state/secrets.env (never the fleet credential). The deploy derives the bucket and key prefix. # R2_S3_REGION is the store's SigV4 signing region: "auto" by default for a gs:// bucket, # REQUIRED for every s3:// operator store (MinIO usually us-east-1), including backup/restore. # R2_S3_ENDPOINT=https://storage.googleapis.com diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 129bffb22b..ee39d868a1 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -1004,15 +1004,43 @@ repository, so it never notices an `.env` edit. port is what the deploy publishes and checks, and each one is logged by name. Shell variables no compose file uses are ignored. Set the box in `.env`, not the shell. -**Object store and presigned uploads.** Uploads (attachments, snapshots) go from the browser -straight to the fleet bucket when `R2_S3_ENDPOINT` is set and `.state/secrets.env` holds a +**Object store and uploads through the box.** Task attachments, build contexts and app image +artifacts are uploaded through the box by default: no store credential is needed. The Worker hands +the uploader (browser or agent) a URL to `https://api.SAM_DOMAIN/api/box-objects?token=...`, signed +by SAM itself with a key derived from `ENCRYPTION_KEY`. It rotates with `selfhost:secrets rotate`: +while a rotation overlaps, URLs signed with the previous key stay valid (`ENCRYPTION_KEY_PREVIOUS`), +and once that key is dropped an unused URL fails with 403 like an expired one; the client asks again. +The token names one object, one operation, a size limit and an expiry of minutes; the box streams the +body into the bucket through celld's R2 binding without holding it in memory, and the write is +create-only. Downloads (image artifacts on deployment nodes, build contexts) work the same way. +Session snapshots keep their own upload route, which also streams through the box. + +- **One request carries at most 1 GiB.** celld refuses a larger body (413) and cannot be configured + above it, so on a box without a store key an app's image artifact is limited to 1 GiB (the agent + is told the limit and stops before uploading). Parted uploads are tracked in idea + `01M83WWQTNTBD4SY1530G3XWH7`. +- **Concurrent uploads are capped** (Admin settings `boxObjects.maxConcurrentUploads`, default 4; + `boxObjects.uploadLeaseSeconds`, default 1800). Each in-flight upload costs celld about 85 MB of + memory (measured on celld 0.6.3: peak RSS 220 MB for one 1 GB upload, 427 MB for four, 896 MB for + eight; throughput stops growing after two at about 180 MB/s). Further uploads get 503 with + `Retry-After`. +- Tokens travel in the query string. Caddy's log drops every query string + (`caddy/log-redaction.caddy`), SAM's request log records only the path, and celld does not log + request URLs at its default level. + +**Direct uploads with a static key (optional).** A box can still send uploads straight to the +fleet bucket, bypassing the Worker, when `R2_S3_ENDPOINT` is set and `.state/secrets.env` holds a credential scoped to the R2 prefix (`R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`; never the fleet -credential, which the deploy refuses). **For an `s3://` bucket `R2_S3_REGION` is required** (the -store's SigV4 signing region, for MinIO usually `us-east-1`): the deploy refuses `R2_S3_ENDPOINT` -without it. A `gs://` bucket defaults to `auto`. The bundled store is a community MinIO build that -celld does not qualify for production. It refuses to start unless `AWS_ACCESS_KEY_ID` and -`AWS_SECRET_ACCESS_KEY` are set, are not `minioadmin`, and the secret has at least 24 characters -(`openssl rand -hex 24`): that credential reads every Worker secret in the bucket. +credential, which the deploy refuses). When that credential is configured it wins over uploads +through the box. Google Cloud organisations that refuse HMAC keys cannot use this; they do not need +to. **For an `s3://` bucket `R2_S3_REGION` is required** (the store's SigV4 signing region, for +MinIO usually `us-east-1`): the deploy refuses `R2_S3_ENDPOINT` without it. A `gs://` bucket +defaults to `auto`. + +**Bundled store.** The bundled store is a community MinIO build that celld does not qualify for +production. It refuses to start unless `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` are set, are +not `minioadmin`, and the secret has at least 24 characters (`openssl rand -hex 24`): that +credential reads every Worker secret in the bucket. **Reverse-tunnel ports and the gateway secret.** frps binds one loopback port per node from `REVERSE_TUNNEL_PORT_RANGE_START`..`_END` (default 20000-29999). The deploy writes the resolved From 2ea4b88ac168caa1ff5a2a9afddefe350a5cc09e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 09:57:23 +0000 Subject: [PATCH 06/19] test(selfhost): celld config and entry derive self-host classes from the registry Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/celld-config.test.ts | 12 +++++++++--- scripts/selfhost/celld-project.test.ts | 6 ++++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/scripts/selfhost/celld-config.test.ts b/scripts/selfhost/celld-config.test.ts index 0fc13db9d3..e4041eca60 100644 --- a/scripts/selfhost/celld-config.test.ts +++ b/scripts/selfhost/celld-config.test.ts @@ -10,6 +10,7 @@ import { buildCelldConfig, SELFHOST_VAR_OVERRIDES, } from './celld-config.js'; +import { SELFHOST_DURABLE_OBJECTS } from './selfhost-durable-objects.js'; const WRANGLER_TOML = resolve(import.meta.dirname, '../../apps/api/wrangler.toml'); @@ -85,8 +86,10 @@ describe('buildCelldConfig against the real apps/api/wrangler.toml', () => { // Keep shared tags in order, then append the celld-only tag. expect(config.migrations.map((m) => m.tag)).toEqual([ ...sourceMigrations.map((m) => m.tag), - 'selfhost-hosted-git-v1', + ...SELFHOST_DURABLE_OBJECTS.map((o) => o.migrationTag), ]); + expect(config.migrations.map((m) => m.tag)).toContain('selfhost-hosted-git-v1'); + expect(config.migrations.map((m) => m.tag)).toContain('selfhost-box-upload-gate-v1'); for (const migration of config.migrations) { expect(Object.keys(migration).sort()).toEqual(['new_sqlite_classes', 'tag']); } @@ -95,14 +98,17 @@ describe('buildCelldConfig against the real apps/api/wrangler.toml', () => { ...(m.new_sqlite_classes ?? []), ...(m.new_classes ?? []), ]); - expect(new Set(created)).toEqual(new Set([...expected, 'HostedGitRepo'])); + expect(new Set(created)).toEqual( + new Set([...expected, ...SELFHOST_DURABLE_OBJECTS.map((o) => o.className)]) + ); }); - it('adds only HostedGitRepo to the shared Durable Object bindings', () => { + it('adds only the self-host classes to the shared Durable Object bindings', () => { expect(config.durable_objects.bindings).toEqual([ ...(source.durable_objects as { bindings: Array<{ name: string; class_name: string }> }) .bindings, { name: 'HOSTED_GIT', class_name: 'HostedGitRepo' }, + { name: 'BOX_UPLOAD_GATE', class_name: 'BoxUploadGate' }, ]); }); diff --git a/scripts/selfhost/celld-project.test.ts b/scripts/selfhost/celld-project.test.ts index 8a3291a717..80cf017c5a 100644 --- a/scripts/selfhost/celld-project.test.ts +++ b/scripts/selfhost/celld-project.test.ts @@ -25,6 +25,7 @@ import { renderCelldMain, writeCelldConfig, } from './celld-project.js'; +import { SELFHOST_DURABLE_OBJECTS } from './selfhost-durable-objects.js'; const API_DIR = resolve(import.meta.dirname, '../../apps/api'); @@ -63,8 +64,9 @@ describe('prepareCelldProject', () => { for (const specifier of specifiers) { expect(existsSync(join(API_DIR, 'src', specifier)), specifier).toBe(true); } - // Shared exports, the self-host-only DO, and the default. - expect(main.match(/^export /gm)).toHaveLength(3); + // Shared exports, each self-host-only DO, and the default. + expect(main.match(/^export /gm)).toHaveLength(2 + SELFHOST_DURABLE_OBJECTS.length); + expect(main).toContain('export { BoxUploadGate } from'); expect(statSync(join(projectDir, CELLD_MAIN)).mode & 0o777).toBe(0o600); }); From 332b35bed52212454ec0836299d913fd498ea25b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 10:06:54 +0000 Subject: [PATCH 07/19] fix(selfhost): review findings for box uploads Per-uploader slot cap and an idle watchdog so a stalled client cannot hold the box's uploads; digits-only Content-Length; a missing setting keeps its default bound; key-prefix allowlist and a 24 h lifetime cap at mint and verify; fail at mint when a token would be too long to verify. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/selfhost/object-urls/gate.ts | 37 ++- apps/api/src/selfhost/object-urls/route.ts | 94 +++++-- apps/api/src/selfhost/object-urls/settings.ts | 29 +++ apps/api/src/selfhost/object-urls/tokens.ts | 41 ++- apps/api/src/selfhost/signed-token.ts | 4 +- .../unit/selfhost/box-object-urls.test.ts | 245 ++++++++++++++++-- 6 files changed, 390 insertions(+), 60 deletions(-) diff --git a/apps/api/src/selfhost/object-urls/gate.ts b/apps/api/src/selfhost/object-urls/gate.ts index 6b6351173e..9aaaa1056c 100644 --- a/apps/api/src/selfhost/object-urls/gate.ts +++ b/apps/api/src/selfhost/object-urls/gate.ts @@ -6,7 +6,10 @@ * (task tasks/active/2026-11-23-selfhost-box-object-uploads.md): peak RSS 220 MB for one upload, * 284 / 427 / 896 MB for 2 / 4 / 8 at once, so roughly 85 MB per upload over a ~150 MB base, while * aggregate throughput stops growing after two (~180 MB/s). The default of 4 keeps the peak near - * 430 MB. An upload over the limit is refused with 503 and Retry-After rather than queued. + * 430 MB. An upload over the limit is refused with 503 and Retry-After rather than queued. One + * uploader (a workspace, else a user) may hold only part of the slots, and the route drops an + * upload that stops sending bytes (`route.ts`), so a slow or stalled client cannot keep the box's + * uploads blocked. * * Why a Durable Object: the limit must hold across every Worker isolate celld runs, and a single * object is the box's one serialization point. Each acquire is a lease with an expiry, so a handler @@ -31,20 +34,29 @@ export class BoxUploadGate extends DurableObject { constructor(ctx: DurableObjectState, env: unknown) { super(ctx, env as never); ctx.storage.sql.exec( - 'CREATE TABLE IF NOT EXISTS upload_leases (id TEXT PRIMARY KEY, expires_at INTEGER NOT NULL)' + 'CREATE TABLE IF NOT EXISTS upload_leases (id TEXT PRIMARY KEY, uploader TEXT NOT NULL, expires_at INTEGER NOT NULL)' ); } - /** Grants a lease to `id` while fewer than `limit` unexpired leases exist. */ - acquire(id: string, limit: number, leaseMs: number, now: number = Date.now()): BoxUploadLease { + /** + * Grants a lease to `id` while fewer than `limits.total` unexpired leases exist on the box and + * fewer than `limits.perUploader` belong to `uploader`, so one uploader cannot hold every slot. + */ + acquire( + id: string, + uploader: string, + limits: { total: number; perUploader: number; leaseMs: number }, + now: number = Date.now() + ): BoxUploadLease { const sql = this.ctx.storage.sql; sql.exec('DELETE FROM upload_leases WHERE expires_at <= ?', now); const row = sql - .exec<{ active: number; next: number | null }>( - 'SELECT COUNT(*) AS active, MIN(expires_at) AS next FROM upload_leases' + .exec<{ active: number; mine: number; next: number | null }>( + 'SELECT COUNT(*) AS active, COALESCE(SUM(uploader = ?), 0) AS mine, MIN(expires_at) AS next FROM upload_leases', + uploader ) .one(); - if (row.active >= limit) { + if (row.active >= limits.total || row.mine >= limits.perUploader) { // A hint, not a promise: most leases end when their upload finishes, long before expiry. const untilExpiry = Math.ceil(((row.next ?? now) - now) / 1000); const retryAfterSeconds = Math.min( @@ -54,9 +66,10 @@ export class BoxUploadGate extends DurableObject { return { granted: false, active: row.active, retryAfterSeconds }; } sql.exec( - 'INSERT OR REPLACE INTO upload_leases (id, expires_at) VALUES (?, ?)', + 'INSERT OR REPLACE INTO upload_leases (id, uploader, expires_at) VALUES (?, ?, ?)', id, - now + leaseMs + uploader, + now + limits.leaseMs ); return { granted: true }; } @@ -70,7 +83,11 @@ export class BoxUploadGate extends DurableObject { export const BOX_UPLOAD_GATE_NAME = 'box'; interface BoxUploadGateStub { - acquire(id: string, limit: number, leaseMs: number): Promise; + acquire( + id: string, + uploader: string, + limits: { total: number; perUploader: number; leaseMs: number } + ): Promise; release(id: string): Promise; } diff --git a/apps/api/src/selfhost/object-urls/route.ts b/apps/api/src/selfhost/object-urls/route.ts index b399afea1b..c8a1cc76ea 100644 --- a/apps/api/src/selfhost/object-urls/route.ts +++ b/apps/api/src/selfhost/object-urls/route.ts @@ -22,8 +22,12 @@ import { resolveAdminSettingDetailsMany } from '../../services/admin-settings-re import { boxUploadGate, type BoxUploadGateEnv } from './gate'; import { BOX_OBJECT_MAX_CONCURRENT_UPLOADS, + BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER, + BOX_OBJECT_UPLOAD_IDLE_SECONDS, BOX_OBJECT_UPLOAD_LEASE_SECONDS, DEFAULT_BOX_OBJECT_MAX_CONCURRENT_UPLOADS, + DEFAULT_BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER, + DEFAULT_BOX_OBJECT_UPLOAD_IDLE_SECONDS, DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS, } from './settings'; import { type BoxObjectTokenClaims, verifyBoxObjectToken } from './tokens'; @@ -52,22 +56,76 @@ function logFields(claims: BoxObjectTokenClaims) { return { op: claims.op, key: claims.key, ...claims.sub }; } -async function uploadLimits(env: Env): Promise<{ limit: number; leaseMs: number }> { +interface UploadLimits { + total: number; + perUploader: number; + leaseMs: number; + idleMs: number; +} + +const DEFAULT_LIMITS: UploadLimits = { + total: DEFAULT_BOX_OBJECT_MAX_CONCURRENT_UPLOADS, + perUploader: DEFAULT_BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER, + leaseMs: DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS * 1000, + idleMs: DEFAULT_BOX_OBJECT_UPLOAD_IDLE_SECONDS * 1000, +}; + +/** A positive integer setting, else its default: a missing value must never disable a bound. */ +function setting(value: unknown, fallback: number, scale = 1): number { + const number = Number(value); + return Number.isSafeInteger(number) && number > 0 ? number * scale : fallback; +} + +async function uploadLimits(env: Env): Promise { try { - const [limit, lease] = await resolveAdminSettingDetailsMany(env, [ + const [total, lease, perUploader, idle] = await resolveAdminSettingDetailsMany(env, [ BOX_OBJECT_MAX_CONCURRENT_UPLOADS, BOX_OBJECT_UPLOAD_LEASE_SECONDS, + BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER, + BOX_OBJECT_UPLOAD_IDLE_SECONDS, ]); - return { limit: Number(limit?.value), leaseMs: Number(lease?.value) * 1000 }; - } catch { - // Settings storage unavailable: the defaults still bound memory. return { - limit: DEFAULT_BOX_OBJECT_MAX_CONCURRENT_UPLOADS, - leaseMs: DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS * 1000, + total: setting(total?.value, DEFAULT_LIMITS.total), + leaseMs: setting(lease?.value, DEFAULT_LIMITS.leaseMs, 1000), + perUploader: setting(perUploader?.value, DEFAULT_LIMITS.perUploader), + idleMs: setting(idle?.value, DEFAULT_LIMITS.idleMs, 1000), }; + } catch { + // Settings storage unavailable: the defaults still bound memory. + return DEFAULT_LIMITS; } } +/** Who holds a slot: the workspace an upload is for, else the user who asked for the URL. */ +function uploader(claims: BoxObjectTokenClaims): string { + return claims.sub?.w ? `w:${claims.sub.w}` : claims.sub?.u ? `u:${claims.sub.u}` : 'unknown'; +} + +const IDLE_ERROR = 'box upload received no bytes within its idle limit'; + +/** Passes bytes through; errors the stream if none arrive for `idleMs`, freeing the slot. */ +function idleWatchdog(idleMs: number): TransformStream { + let timer: ReturnType | undefined; + let fail: (error: Error) => void = () => undefined; + const arm = () => { + clearTimeout(timer); + timer = setTimeout(() => fail(new Error(IDLE_ERROR)), idleMs); + }; + return new TransformStream({ + start(controller) { + fail = (error) => controller.error(error); + arm(); + }, + transform(chunk, controller) { + arm(); + controller.enqueue(chunk); + }, + flush() { + clearTimeout(timer); + }, + }); +} + /** * True when the stored object is provably the one `claims` describes, so a retried PUT that * already succeeded can answer 200. Only a token that binds a sha256 can prove it: equal size @@ -96,11 +154,11 @@ async function conflict(env: Env, claims: BoxObjectTokenClaims, length: number) async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectTokenClaims) { const env = c.env; - const length = Number(c.req.header('content-length')); + const declared = c.req.header('content-length') ?? ''; + // Digits only: Number() would also accept "1e3", "0x10" or " 12". + if (!/^\d{1,16}$/.test(declared)) return plain(411, 'Content-Length is required'); + const length = Number(declared); const body = c.req.raw.body; - if (!c.req.header('content-length') || !Number.isSafeInteger(length) || length < 0) { - return plain(411, 'Content-Length is required'); - } if (claims.max !== undefined && length > claims.max) { return plain(413, `Upload is ${length} bytes; this URL accepts at most ${claims.max}`); } @@ -111,16 +169,17 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke const gate = boxUploadGate(env); if (!gate) return plain(503, 'Box uploads are unavailable (no upload gate binding)'); - const { limit, leaseMs } = await uploadLimits(env); + const limits = await uploadLimits(env); const leaseId = crypto.randomUUID(); - const lease = await gate.acquire(leaseId, limit, leaseMs); + const lease = await gate.acquire(leaseId, uploader(claims), limits); if (!lease.granted) { log.warn('box_objects.upload_refused_busy', { ...logFields(claims), active: lease.active, - limit, + limit: limits.total, + perUploader: limits.perUploader, }); - return plain(503, `The box is already receiving ${lease.active} uploads; retry shortly`, { + return plain(503, 'The box is receiving as many uploads as it allows; retry shortly', { 'Retry-After': String(lease.retryAfterSeconds), }); } @@ -128,7 +187,9 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke const atomic = length <= CELLD_CONDITIONAL_PUT_MAX_BYTES; if (!atomic && (await env.R2.head(claims.key))) return conflict(env, claims, length); // FixedLengthStream makes a short or long body an error instead of a truncated object. - const stream = body ? body.pipeThrough(new FixedLengthStream(length)) : new Uint8Array(0); + const stream = body + ? body.pipeThrough(idleWatchdog(limits.idleMs)).pipeThrough(new FixedLengthStream(length)) + : new Uint8Array(0); let written: R2Object | null; try { written = await env.R2.put(claims.key, stream, { @@ -140,6 +201,7 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke } catch (error) { const message = error instanceof Error ? error.message : String(error); log.warn('box_objects.upload_failed', { ...logFields(claims), length, error: message }); + if (message.includes(IDLE_ERROR)) return plain(408, 'The upload stopped sending data'); return claims.sha && /sha-?256/i.test(message) ? plain(400, 'Upload body does not match the declared sha256') : plain(502, 'The upload did not complete; retry it'); diff --git a/apps/api/src/selfhost/object-urls/settings.ts b/apps/api/src/selfhost/object-urls/settings.ts index 361120625d..23d928f6c5 100644 --- a/apps/api/src/selfhost/object-urls/settings.ts +++ b/apps/api/src/selfhost/object-urls/settings.ts @@ -21,10 +21,25 @@ export const DEFAULT_BOX_OBJECT_MAX_CONCURRENT_UPLOADS = 4; */ export const DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS = 1800; +/** + * Of those, how many one uploader (a workspace, else a user) may hold at once, so one uploader + * cannot take every slot from everyone else. + */ +export const DEFAULT_BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER = 2; + +/** + * Seconds an upload may go without receiving a byte before the box drops it (408) and frees its + * slot. A slow but moving upload is never cut. + */ +export const DEFAULT_BOX_OBJECT_UPLOAD_IDLE_SECONDS = 60; + /** These names exist only in the self-host build, so they are not in the shared name union. */ export const BOX_OBJECT_MAX_CONCURRENT_UPLOADS = 'boxObjects.maxConcurrentUploads' as AdminSettingName; export const BOX_OBJECT_UPLOAD_LEASE_SECONDS = 'boxObjects.uploadLeaseSeconds' as AdminSettingName; +export const BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER = + 'boxObjects.maxUploadsPerUploader' as AdminSettingName; +export const BOX_OBJECT_UPLOAD_IDLE_SECONDS = 'boxObjects.uploadIdleSeconds' as AdminSettingName; export const BOX_OBJECT_SETTINGS: readonly AdminSettingDefinition[] = [ integerDefinition( @@ -41,4 +56,18 @@ export const BOX_OBJECT_SETTINGS: readonly AdminSettingDefinition[] = [ 'Seconds one upload counts against the concurrent-upload limit at most, so an upload whose handler died frees its slot.', { min: 60, max: 86_400 } ), + integerDefinition( + BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER, + DEFAULT_BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER, + 'Operations', + 'Of the concurrent uploads, how many one uploader (a workspace, else a user) may hold at once.', + { min: 1, max: 64 } + ), + integerDefinition( + BOX_OBJECT_UPLOAD_IDLE_SECONDS, + DEFAULT_BOX_OBJECT_UPLOAD_IDLE_SECONDS, + 'Operations', + 'Seconds an upload may receive no bytes before the box drops it and frees its slot.', + { min: 5, max: 3_600 } + ), ]; diff --git a/apps/api/src/selfhost/object-urls/tokens.ts b/apps/api/src/selfhost/object-urls/tokens.ts index 0b093f110f..8e66c7691c 100644 --- a/apps/api/src/selfhost/object-urls/tokens.ts +++ b/apps/api/src/selfhost/object-urls/tokens.ts @@ -15,7 +15,14 @@ * rotation overlaps. Once the previous key is dropped, such a token fails with 403 and the uploader * asks for a new one, exactly as an expired presigned URL would. */ -import { mintSignedToken, type SignedTokenEnv, verifySignedToken } from '../signed-token'; +import { BUILD_CONTEXT_PREFIX } from '@simple-agent-manager/app-deployment'; + +import { + MAX_SIGNED_TOKEN_LENGTH, + mintSignedToken, + type SignedTokenEnv, + verifySignedToken, +} from '../signed-token'; export type BoxObjectOperation = 'put' | 'get'; @@ -47,6 +54,21 @@ const PURPOSE = { acceptPreviousKey: true, } as const; +/** + * The only key prefixes a token may name: task attachments (`attachment-upload.ts` + * buildAttachmentR2Key), compose image artifacts (`buildComposeImageArtifactKey`) and build + * contexts (`buildContextKey`). The R2 binding also holds vm-agent binaries and session snapshots, + * so a minting bug must not be able to reach them. Enforced at mint and at verify. + */ +export const BOX_OBJECT_KEY_PREFIXES: readonly string[] = [ + 'temp-uploads/', + 'compose-image-artifacts/', + BUILD_CONTEXT_PREFIX, +]; + +/** Longest lifetime a token may have, whatever the minting route asked for. */ +export const MAX_BOX_OBJECT_TOKEN_SECONDS = 24 * 60 * 60; + /** Longest key accepted; R2 allows 1024 bytes. */ const MAX_KEY_LENGTH = 1024; const SHA256_HEX = /^[0-9a-f]{64}$/; @@ -54,11 +76,13 @@ const MAX_METADATA_ENTRIES = 8; const MAX_METADATA_VALUE_LENGTH = 256; /** - * An R2 key a token may name: relative, no empty, `.` or `..` segment, no backslash or control - * character. Keys SAM builds always pass; anything else is refused at mint and at verify. + * An R2 key a token may name: under one of BOX_OBJECT_KEY_PREFIXES, relative, no empty, `.` or + * `..` segment, no backslash or control character. Keys SAM builds always pass; anything else is + * refused at mint and at verify. */ export function isSafeObjectKey(key: string): boolean { if (!key || key.length > MAX_KEY_LENGTH) return false; + if (!BOX_OBJECT_KEY_PREFIXES.some((prefix) => key.startsWith(prefix))) return false; // eslint-disable-next-line no-control-regex -- control characters are exactly what is refused if (key.startsWith('/') || key.includes('\\') || /[\u0000-\u001f\u007f]/.test(key)) return false; return key.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..'); @@ -133,10 +157,15 @@ export async function mintBoxObjectToken( now: number = Date.now() ): Promise { const { expiresIn, ...rest } = input; - if (!positiveInteger(expiresIn)) throw new Error('Box object token needs a positive lifetime'); + if (!positiveInteger(expiresIn) || expiresIn > MAX_BOX_OBJECT_TOKEN_SECONDS) { + throw new Error(`Box object token lifetime must be 1..${MAX_BOX_OBJECT_TOKEN_SECONDS} seconds`); + } const claims = parseClaims({ ...rest, v: 1, exp: Math.floor(now / 1000) + expiresIn }); if (!claims) throw new Error('Box object token claims are invalid'); - return mintSignedToken(env, PURPOSE, claims); + const token = await mintSignedToken(env, PURPOSE, claims); + // Verification refuses longer tokens; fail here instead of handing out a URL that cannot work. + if (token.length > MAX_SIGNED_TOKEN_LENGTH) throw new Error('Box object token is too long'); + return token; } /** Signature, shape and expiry. Null for any token that is not valid now. */ @@ -148,5 +177,7 @@ export async function verifyBoxObjectToken( const raw = await verifySignedToken(env, PURPOSE, token); const claims = raw ? parseClaims(raw) : null; if (!claims || claims.exp * 1000 <= now) return null; + // A token valid for longer than any minter may issue is not one SAM minted correctly. + if (claims.exp * 1000 - now > MAX_BOX_OBJECT_TOKEN_SECONDS * 1000) return null; return claims; } diff --git a/apps/api/src/selfhost/signed-token.ts b/apps/api/src/selfhost/signed-token.ts index d61d35fcb7..9c79f2f79c 100644 --- a/apps/api/src/selfhost/signed-token.ts +++ b/apps/api/src/selfhost/signed-token.ts @@ -25,7 +25,7 @@ export interface SignedTokenEnv { } /** Longest token any purpose verifies; longer input is refused before any crypto. */ -const MAX_TOKEN_LENGTH = 2048; +export const MAX_SIGNED_TOKEN_LENGTH = 2048; const encoder = new TextEncoder(); const decoder = new TextDecoder(); @@ -107,7 +107,7 @@ export async function verifySignedToken( purpose: SignedTokenPurpose, token: string ): Promise | null> { - if (token.length > MAX_TOKEN_LENGTH) return null; + if (token.length > MAX_SIGNED_TOKEN_LENGTH) return null; const parts = token.split('.'); if (parts.length !== 3 || parts[0] !== purpose.prefix) return null; const [prefix, payload, signaturePart] = parts as [string, string, string]; diff --git a/apps/api/tests/unit/selfhost/box-object-urls.test.ts b/apps/api/tests/unit/selfhost/box-object-urls.test.ts index 3c6c40b051..fffa62f55d 100644 --- a/apps/api/tests/unit/selfhost/box-object-urls.test.ts +++ b/apps/api/tests/unit/selfhost/box-object-urls.test.ts @@ -6,6 +6,8 @@ * create-only puts and sha256 verification. The gate is the real Durable Object class over SQLite. */ import { + buildComposeImageArtifactKey, + buildContextKey, composeImageArtifactMaxBytesFor, createBuildContextUpload, createComposeImageArtifactDownloads, @@ -28,10 +30,16 @@ import { } from '../../../src/selfhost/object-urls/signer'; import { isSafeObjectKey, + MAX_BOX_OBJECT_TOKEN_SECONDS, mintBoxObjectToken, verifyBoxObjectToken, } from '../../../src/selfhost/object-urls/tokens'; -import { generatePresignedUploadUrl } from '../../../src/services/attachment-upload'; +import { mintSignedToken } from '../../../src/selfhost/signed-token'; +import { resolveAdminSettingDetailsMany } from '../../../src/services/admin-settings-resolution'; +import { + buildAttachmentR2Key, + generatePresignedUploadUrl, +} from '../../../src/services/attachment-upload'; import { getR2ObjectUrlSigner, installBoxObjectUrlSigner, @@ -39,7 +47,16 @@ import { resolveR2ObjectUrlSigner, } from '../../../src/services/r2-s3-client'; +// Settings storage: unavailable by default (the route then uses its defaults); tests override it. +vi.mock('../../../src/services/admin-settings-resolution', () => ({ + resolveAdminSettingDetailsMany: vi.fn(async () => { + throw new Error('settings storage unavailable'); + }), +})); + const KEY = 'box-test-encryption-key-0123456789'; +/** The defaults the route uses when settings storage is unavailable. */ +const LIMITS = { total: 4, perUploader: 2, leaseMs: 60_000 }; const DOMAIN = 'box.example.test'; // ── celld-faithful fakes ─────────────────────────────────────────────────────────────────────── @@ -145,8 +162,11 @@ function gateNamespace(gate: BoxUploadGate) { return { idFromName: (name: string) => name, get: () => ({ - acquire: async (id: string, limit: number, leaseMs: number) => - gate.acquire(id, limit, leaseMs), + acquire: async ( + id: string, + uploader: string, + limits: { total: number; perUploader: number; leaseMs: number } + ) => gate.acquire(id, uploader, limits), release: async (id: string) => gate.release(id), }), }; @@ -268,6 +288,79 @@ describe('box object tokens', () => { }); }); +describe('box object token scope', () => { + const env = { ENCRYPTION_KEY: KEY }; + // The purpose a minter bug would sign with: same prefix and label as tokens.ts. + const purpose = { prefix: 'samobj1', label: 'sam-box-object-url/v1' }; + + it('every key SAM builds for these uploads is inside the allowlist', () => { + expect(isSafeObjectKey(buildAttachmentR2Key('u1', 'up1', 'a.txt'))).toBe(true); + expect(isSafeObjectKey(buildComposeImageArtifactKey('p1', 'w1', 'e1', 'u1', 'web'))).toBe(true); + expect( + isSafeObjectKey( + buildContextKey({ + id: 'job', + projectId: 'p1', + workspaceId: 'w1', + requestedBy: 'u1', + environmentId: 'e1', + attempt: 1, + }) + ) + ).toBe(true); + }); + + it('refuses keys outside the upload prefixes at mint, and at verify even when correctly signed', async () => { + for (const key of [ + 'agents/vm-agent-linux-amd64', + 'session-snapshots/s1/a.tar', + 'temp-uploadsX/a', + ]) { + expect(isSafeObjectKey(key)).toBe(false); + await expect( + mintBoxObjectToken(env, { op: 'put', key, len: 1, expiresIn: 60 }) + ).rejects.toThrow(); + const forged = await mintSignedToken(env, purpose, { + v: 1, + op: 'put', + key, + len: 1, + exp: Math.floor(Date.now() / 1000) + 60, + }); + expect(await verifyBoxObjectToken(env, forged)).toBeNull(); + } + }); + + it('caps lifetime at mint and refuses an over-long signed lifetime at verify', async () => { + const key = 'temp-uploads/u/up/a.txt'; + await expect( + mintBoxObjectToken(env, { op: 'get', key, expiresIn: MAX_BOX_OBJECT_TOKEN_SECONDS + 1 }) + ).rejects.toThrow('lifetime'); + const longLived = await mintSignedToken(env, purpose, { + v: 1, + op: 'get', + key, + exp: Math.floor(Date.now() / 1000) + MAX_BOX_OBJECT_TOKEN_SECONDS + 60, + }); + expect(await verifyBoxObjectToken(env, longLived)).toBeNull(); + // Control: the longest allowed lifetime verifies. + const longest = await mintBoxObjectToken(env, { + op: 'get', + key, + expiresIn: MAX_BOX_OBJECT_TOKEN_SECONDS, + }); + expect(await verifyBoxObjectToken(env, longest)).not.toBeNull(); + }); + + it('fails at mint, not at upload, when the token would exceed the verifiable length', async () => { + const key = `temp-uploads/${'a'.repeat(1000)}`; + const md = Object.fromEntries(Array.from({ length: 8 }, (_, i) => [`m${i}`, 'v'.repeat(250)])); + await expect( + mintBoxObjectToken(env, { op: 'put', key, len: 1, md, expiresIn: 60 }) + ).rejects.toThrow('too long'); + }); +}); + // ── the resolver's choice (rule 74) ──────────────────────────────────────────────────────────── describe('which URL a caller gets', () => { @@ -285,7 +378,7 @@ describe('which URL a caller gets', () => { ENCRYPTION_KEY: KEY, } as Env); expect(signer.kind).toBe('presign'); - expect(new URL(await signer.putUrl('k', { expiresIn: 60 })).host).toMatch( + expect(new URL(await signer.putUrl('temp-uploads/t/k', { expiresIn: 60 })).host).toMatch( /acct\.r2\.cloudflarestorage\.com$/ ); // Divergence: a keyless Env on Cloudflare has no signer; it does not fall through to a box URL. @@ -296,7 +389,9 @@ describe('which URL a caller gets', () => { installBoxObjectUrls(); const signer = getR2ObjectUrlSigner(boxEnv().env); expect(signer.kind).toBe('box'); - const url = new URL(await signer.putUrl('k', { expiresIn: 60, contentLength: 3 })); + const url = new URL( + await signer.putUrl('temp-uploads/t/k', { expiresIn: 60, contentLength: 3 }) + ); expect(`${url.origin}${url.pathname}`).toBe(`https://api.${DOMAIN}${BOX_OBJECT_ROUTE}`); expect(url.searchParams.get('token')).toMatch(/^samobj1\./); }); @@ -395,7 +490,10 @@ describe('callers on a keyless box', () => { it('a single upload over 1 GiB is refused when the URL is requested', async () => { const signer = createBoxObjectUrlSigner(boxEnv().env)!; await expect( - signer.putUrl('k', { expiresIn: 60, contentLength: CELLD_MAX_REQUEST_BODY_BYTES + 1 }) + signer.putUrl('temp-uploads/t/k', { + expiresIn: 60, + contentLength: CELLD_MAX_REQUEST_BODY_BYTES + 1, + }) ).rejects.toMatchObject({ statusCode: 400 }); }); @@ -458,15 +556,19 @@ describe('PUT/GET /api/box-objects', () => { it('refuses forged, expired, wrong-operation and missing tokens without writing', async () => { const { env, R2 } = boxEnv(); const app = routeApp(); - const getToken = await mintBoxObjectToken(env, { op: 'get', key: 'k', expiresIn: 60 }); + const getToken = await mintBoxObjectToken(env, { + op: 'get', + key: 'temp-uploads/t/k', + expiresIn: 60, + }); const expired = await mintBoxObjectToken( env, - { op: 'put', key: 'k', len: 1, expiresIn: 1 }, + { op: 'put', key: 'temp-uploads/t/k', len: 1, expiresIn: 1 }, Date.now() - 10_000 ); const forged = await mintBoxObjectToken( { ENCRYPTION_KEY: 'another-installation-key' }, - { op: 'put', key: 'k', len: 1, expiresIn: 60 } + { op: 'put', key: 'temp-uploads/t/k', len: 1, expiresIn: 60 } ); for (const token of [getToken, expired, forged, '']) { const response = await putUrl( @@ -483,9 +585,9 @@ describe('PUT/GET /api/box-objects', () => { it('bounds size: over the maximum is 413, a length other than the issued one 400, none 411', async () => { const { env, R2 } = boxEnv(); const app = routeApp(); - const bounded = await upload(env, 'k1', { maxBytes: 4 }); + const bounded = await upload(env, 'temp-uploads/t/k1', { maxBytes: 4 }); expect((await putUrl(app, env, bounded, bytes('12345'))).status).toBe(413); - const exact = await upload(env, 'k2', { contentLength: 4 }); + const exact = await upload(env, 'temp-uploads/t/k2', { contentLength: 4 }); expect((await putUrl(app, env, exact, bytes('123'))).status).toBe(400); const target = new URL(exact); const noLength = await app.request( @@ -502,12 +604,12 @@ describe('PUT/GET /api/box-objects', () => { it('is create-only: a second write is 412 and the object stays', async () => { const { env, R2 } = boxEnv(); const app = routeApp(); - const url = await upload(env, 'k', { contentLength: 5 }); + const url = await upload(env, 'temp-uploads/t/k', { contentLength: 5 }); expect((await putUrl(app, env, url, bytes('first'))).status).toBe(200); // Same length, other bytes: without a bound digest the route cannot tell, so it refuses. expect((await putUrl(app, env, url, bytes('other'))).status).toBe(412); expect((await putUrl(app, env, url, bytes('first'))).status).toBe(412); - expect(new TextDecoder().decode(R2.objects.get('k')!.bytes)).toBe('first'); + expect(new TextDecoder().decode(R2.objects.get('temp-uploads/t/k')!.bytes)).toBe('first'); }); it('above celld conditional-put size it checks for an existing object instead of onlyIf', async () => { @@ -515,37 +617,40 @@ describe('PUT/GET /api/box-objects', () => { const app = routeApp(); const putSpy = vi.spyOn(R2, 'put'); const big = new Uint8Array(CELLD_CONDITIONAL_PUT_MAX_BYTES + 1).fill(7); - const url = await upload(env, 'big', { contentLength: big.byteLength }); + const url = await upload(env, 'temp-uploads/t/big', { contentLength: big.byteLength }); expect((await putUrl(app, env, url, big)).status).toBe(200); expect(putSpy.mock.calls[0]![2]).not.toHaveProperty('onlyIf'); expect((await putUrl(app, env, url, big.fill(8))).status).toBe(412); expect(putSpy).toHaveBeenCalledTimes(1); - expect(R2.objects.get('big')!.bytes[0]).toBe(7); + expect(R2.objects.get('temp-uploads/t/big')!.bytes[0]).toBe(7); }); it('a retried PUT with a bound sha256 that already succeeded is 200 and replaces nothing', async () => { const { env, R2 } = boxEnv(); const app = routeApp(); const body = bytes('first'); - const url = await upload(env, 'k', { contentLength: 5, sha256: await sha256Hex(body) }); + const url = await upload(env, 'temp-uploads/t/k', { + contentLength: 5, + sha256: await sha256Hex(body), + }); expect((await putUrl(app, env, url, body)).status).toBe(200); expect((await putUrl(app, env, url, body)).status).toBe(200); // Other bytes: 400 if the digest is checked first, 200 if the create-only check is (the stored // object is exactly what the token describes). Either way nothing is replaced. expect([200, 400]).toContain((await putUrl(app, env, url, bytes('other'))).status); - expect(new TextDecoder().decode(R2.objects.get('k')!.bytes)).toBe('first'); + expect(new TextDecoder().decode(R2.objects.get('temp-uploads/t/k')!.bytes)).toBe('first'); }); it('verifies a bound sha256: wrong bytes are 400 and nothing is stored', async () => { const { env, R2 } = boxEnv(); const app = routeApp(); const body = bytes('context'); - const url = await upload(env, 'ctx', { + const url = await upload(env, 'temp-uploads/t/ctx', { contentLength: body.byteLength, sha256: await sha256Hex(body), }); expect((await putUrl(app, env, url, bytes('CONTEXT'))).status).toBe(400); - expect(R2.objects.has('ctx')).toBe(false); + expect(R2.objects.has('temp-uploads/t/ctx')).toBe(false); expect((await putUrl(app, env, url, body)).status).toBe(200); }); @@ -553,23 +658,109 @@ describe('PUT/GET /api/box-objects', () => { const { env, R2, gate } = boxEnv(); const app = routeApp(); // Settings storage is unavailable in this env, so the default limit (4) applies. - for (let i = 0; i < 4; i++) gate.acquire(`held-${i}`, 4, 60_000); - const url = await upload(env, 'busy', { contentLength: 4 }); + for (let i = 0; i < 4; i++) gate.acquire(`held-${i}`, `u:other-${i}`, LIMITS); + const url = await upload(env, 'temp-uploads/t/busy', { contentLength: 4 }); const refused = await putUrl(app, env, url, bytes('busy')); expect(refused.status).toBe(503); expect(Number(refused.headers.get('Retry-After'))).toBeGreaterThan(0); - expect(R2.objects.has('busy')).toBe(false); + expect(R2.objects.has('temp-uploads/t/busy')).toBe(false); gate.release('held-0'); expect((await putUrl(app, env, url, bytes('busy'))).status).toBe(200); // The upload released its own lease: three held, one free. - expect(gate.acquire('probe', 4, 60_000)).toEqual({ granted: true }); + expect(gate.acquire('probe', 'u:probe', LIMITS)).toEqual({ granted: true }); }); it('an expired lease frees its slot (a handler that died without releasing)', () => { const { gate } = boxEnv(); - gate.acquire('dead', 1, 1_000, 0); - expect(gate.acquire('next', 1, 1_000, 500).granted).toBe(false); - expect(gate.acquire('next', 1, 1_000, 1_000).granted).toBe(true); + const one = { total: 1, perUploader: 1, leaseMs: 1_000 }; + gate.acquire('dead', 'u:a', one, 0); + expect(gate.acquire('next', 'u:b', one, 500).granted).toBe(false); + expect(gate.acquire('next', 'u:b', one, 1_000).granted).toBe(true); + }); + + it('one uploader cannot take every slot: a second uploader is still admitted', async () => { + const { env, gate } = boxEnv(); + const app = routeApp(); + const signer = createBoxObjectUrlSigner(env)!; + // The attacker already holds its share (2 of 4). + gate.acquire('held-1', 'u:attacker', LIMITS); + gate.acquire('held-2', 'u:attacker', LIMITS); + const attacker = await signer.putUrl('temp-uploads/attacker/up/a', { + expiresIn: 60, + contentLength: 1, + owner: { userId: 'attacker' }, + }); + expect((await putUrl(app, env, attacker, bytes('a'))).status).toBe(503); + const other = await signer.putUrl('temp-uploads/other/up/a', { + expiresIn: 60, + contentLength: 1, + owner: { userId: 'other' }, + }); + expect((await putUrl(app, env, other, bytes('o'))).status).toBe(200); + }); + + it('drops an upload that stops sending bytes (408) and frees its slot', async () => { + vi.mocked(resolveAdminSettingDetailsMany).mockResolvedValueOnce([ + { value: 4 }, + { value: 1800 }, + { value: 2 }, + { value: 1 }, // idle seconds + ] as never); + const { env, R2, gate } = boxEnv(); + const app = routeApp(); + const url = new URL(await upload(env, 'temp-uploads/t/stall', { contentLength: 10 })); + const stalled = new ReadableStream({ + start(controller) { + controller.enqueue(bytes('12345')); + }, + }); + const response = await app.request( + `${url.pathname}${url.search}`, + { + method: 'PUT', + body: stalled, + headers: { 'content-length': '10' }, + duplex: 'half', + } as RequestInit, + env + ); + expect(response.status).toBe(408); + expect(R2.objects.has('temp-uploads/t/stall')).toBe(false); + // Its slot was released. + expect(gate.acquire('probe', 'u:probe', { total: 1, perUploader: 1, leaseMs: 60_000 })).toEqual( + { + granted: true, + } + ); + }, 10_000); + + it('a setting that resolves to nothing keeps its default bound (never disables the gate)', async () => { + vi.mocked(resolveAdminSettingDetailsMany).mockResolvedValueOnce([ + { value: undefined }, + { value: undefined }, + { value: undefined }, + { value: undefined }, + ] as never); + const { env, gate } = boxEnv(); + const app = routeApp(); + for (let i = 0; i < 4; i++) gate.acquire(`held-${i}`, `u:other-${i}`, LIMITS); + const url = await upload(env, 'temp-uploads/t/nan', { contentLength: 1 }); + expect((await putUrl(app, env, url, bytes('n'))).status).toBe(503); + }); + + it('accepts only a plain decimal Content-Length', async () => { + const { env, R2 } = boxEnv(); + const app = routeApp(); + const url = new URL(await upload(env, 'temp-uploads/t/cl', { maxBytes: 100 })); + for (const declared of ['1e1', '0x0a', '10.0', '+10']) { + const response = await app.request( + `${url.pathname}${url.search}`, + { method: 'PUT', body: bytes('1234567890'), headers: { 'content-length': declared } }, + env + ); + expect(response.status, declared).not.toBe(200); + } + expect(R2.objects.has('temp-uploads/t/cl')).toBe(false); }); it('never logs the token: the request log and the route log carry the path only', async () => { @@ -583,7 +774,7 @@ describe('PUT/GET /api/box-objects', () => { ); }); } - const url = await upload(env, 'logged', { contentLength: 2 }); + const url = await upload(env, 'temp-uploads/t/logged', { contentLength: 2 }); const token = new URL(url).searchParams.get('token')!; expect((await putUrl(app, env, url, bytes('ok'))).status).toBe(200); await putUrl(app, env, `https://x${BOX_OBJECT_ROUTE}?token=${token}x`, bytes('ok')); From 4fc3f59e0be067833f4044d310631a2bc29ee66c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 10:09:00 +0000 Subject: [PATCH 08/19] test(selfhost): live celld proof that a bad-token body is not buffered; allowed key prefixes Co-Authored-By: Claude Opus 5.5 --- .../live/box-object-urls.live.test.ts | 83 +++++++++++++++---- 1 file changed, 66 insertions(+), 17 deletions(-) diff --git a/scripts/selfhost/live/box-object-urls.live.test.ts b/scripts/selfhost/live/box-object-urls.live.test.ts index 9aa8bd5260..65f6901c4a 100644 --- a/scripts/selfhost/live/box-object-urls.live.test.ts +++ b/scripts/selfhost/live/box-object-urls.live.test.ts @@ -8,7 +8,7 @@ * over celld's 1 GiB ingress cap never reaches the Worker. */ import { createHash, randomBytes } from 'node:crypto'; -import { mkdirSync, mkdtempSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, readFileSync } from 'node:fs'; import { request } from 'node:http'; import { createRequire } from 'node:module'; import { join } from 'node:path'; @@ -122,7 +122,7 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { it('streams a 64 MiB upload into R2 and back, sha256-verified', async () => { const body = randomBytes(64 * 1024 * 1024); const sha = createHash('sha256').update(body).digest('hex'); - const url = await mint('put', 'build/ctx.tar.zst', { + const url = await mint('put', 'compose-build-contexts/live/ctx.tar.zst', { contentLength: body.length, contentType: 'application/zstd', sha256: sha, @@ -131,7 +131,7 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { expect((await putBytes(url, body)).status).toBe(200); // Retry of a finished upload with the bound digest: 200, nothing replaced. expect((await putBytes(url, body)).status).toBe(200); - const download = await fetch(await mint('get', 'build/ctx.tar.zst')); + const download = await fetch(await mint('get', 'compose-build-contexts/live/ctx.tar.zst')); expect(download.status).toBe(200); expect(download.headers.get('content-type')).toBe('application/zstd'); const got = Buffer.from(await download.arrayBuffer()); @@ -140,58 +140,107 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { it('refuses bytes that do not match the bound sha256, and stores nothing', async () => { const body = randomBytes(1024); - const url = await mint('put', 'build/bad.tar.zst', { + const url = await mint('put', 'compose-build-contexts/live/bad.tar.zst', { contentLength: body.length, sha256: createHash('sha256').update('something else').digest('hex'), }); expect((await putBytes(url, body)).status).toBe(400); - expect((await fetch(await mint('get', 'build/bad.tar.zst'))).status).toBe(404); + expect((await fetch(await mint('get', 'compose-build-contexts/live/bad.tar.zst'))).status).toBe( + 404 + ); }); it('is create-only without a digest: the second write is 412 and the first stays', async () => { - const url = await mint('put', 'attach/a.txt', { contentLength: 5 }); + const url = await mint('put', 'temp-uploads/live/a.txt', { contentLength: 5 }); expect((await putBytes(url, Buffer.from('first'))).status).toBe(200); expect((await putBytes(url, Buffer.from('other'))).status).toBe(412); - expect(await (await fetch(await mint('get', 'attach/a.txt'))).text()).toBe('first'); + expect(await (await fetch(await mint('get', 'temp-uploads/live/a.txt'))).text()).toBe('first'); }); it('is create-only above celld 8 MiB conditional-put size too (multipart writes)', async () => { const body = randomBytes(9 * 1024 * 1024); - const url = await mint('put', 'artifacts/web.tar', { maxBytes: 64 * 1024 * 1024 }); + const url = await mint('put', 'compose-image-artifacts/live/web.tar', { + maxBytes: 64 * 1024 * 1024, + }); expect((await putBytes(url, body)).status).toBe(200); expect((await putBytes(url, randomBytes(body.length))).status).toBe(412); const got = Buffer.from( - await (await fetch(await mint('get', 'artifacts/web.tar'))).arrayBuffer() + await (await fetch(await mint('get', 'compose-image-artifacts/live/web.tar'))).arrayBuffer() ); expect(got.equals(body)).toBe(true); }, 60_000); it('a body shorter than declared leaves no object', async () => { - const url = await mint('put', 'attach/short.bin', { maxBytes: 1024 }); + const url = await mint('put', 'temp-uploads/live/short.bin', { maxBytes: 1024 }); // Declares 100 bytes, sends 10, then closes: FixedLengthStream fails the put. await put(url, 100, (req) => { req.write(Buffer.alloc(10)); setTimeout(() => req.destroy(), 300); }).catch(() => undefined); - expect((await fetch(await mint('get', 'attach/short.bin'))).status).toBe(404); + expect((await fetch(await mint('get', 'temp-uploads/live/short.bin'))).status).toBe(404); }); it('over the token maximum is 413; over celld 1 GiB is refused before the Worker', async () => { - const small = await mint('put', 'attach/big.bin', { maxBytes: 10 }); + const small = await mint('put', 'temp-uploads/live/big.bin', { maxBytes: 10 }); expect((await putBytes(small, Buffer.alloc(11))).status).toBe(413); - const huge = await mint('put', 'attach/huge.bin', { maxBytes: 1024 * 1024 * 1024 }); + const huge = await mint('put', 'temp-uploads/live/huge.bin', { maxBytes: 1024 * 1024 * 1024 }); const refused = await put(huge, 1024 * 1024 * 1024 + 1, (req) => req.write(Buffer.alloc(1)) ).catch(() => ({ status: 413, headers: {} })); expect(refused.status).toBe(413); }); - it('holds at most four uploads at once: the fifth gets 503 with Retry-After', async () => { + it('a bad token is refused before the body is read: a large unauthenticated body is not buffered', async () => { + const pid = celld!.child.pid!; + const rss = () => + Number(/VmRSS:\s+(\d+)/.exec(readFileSync(`/proc/${pid}/status`, 'utf8'))![1]) / 1024; + const before = rss(); + let peak = before; + const sampler = setInterval(() => (peak = Math.max(peak, rss())), 100); + const length = 512 * 1024 * 1024; + const chunk = Buffer.alloc(1024 * 1024); + let sent = 0; + const started = Date.now(); + // celld answers 403 and closes while a client that sends at once is still writing, so Node + // usually reports a socket error instead of the response. (A client sending + // `Expect: 100-continue`, as curl does for large bodies, gets the 403 and sends nothing.) + const status = await new Promise((done) => { + const req = request(`http://127.0.0.1:${port}/api/box-objects?token=samobj1.forged.forged`, { + method: 'PUT', + headers: { 'content-length': String(length) }, + }); + req.on('response', (res) => { + res.resume(); + done(res.statusCode ?? 0); + }); + req.on('error', () => done(-1)); + const write = () => { + while (sent < length) { + sent += chunk.length; + if (!req.write(chunk)) return void req.once('drain', write); + } + req.end(); + }; + write(); + }); + clearInterval(sampler); + expect([403, -1]).toContain(status); + // Refused without reading the body: the connection ended long before 512 MiB was sent, and + // celld held none of it. + expect(sent).toBeLessThan(length / 4); + expect(Date.now() - started).toBeLessThan(10_000); + expect(peak - before).toBeLessThan(100); + }, 60_000); + + it('holds at most four uploads at once (four uploaders): the fifth gets 503 with Retry-After', async () => { const length = 1024 * 1024; const held: Array> = []; const pending = []; for (let i = 0; i < 4; i++) { - const url = await mint('put', `busy/${i}`, { contentLength: length }); + const url = await mint('put', `temp-uploads/busy/${i}`, { + contentLength: length, + owner: { userId: `user-${i}` }, + }); pending.push( put(url, length, (req) => { req.write(Buffer.alloc(1024)); @@ -202,7 +251,7 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { // Let the four reach the gate. await new Promise((resolve) => setTimeout(resolve, 1500)); const fifth = await putBytes( - await mint('put', 'busy/5', { contentLength: 4 }), + await mint('put', 'temp-uploads/busy/5', { contentLength: 4, owner: { userId: 'user-5' } }), Buffer.from('five') ); expect(fifth.status).toBe(503); @@ -211,7 +260,7 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { expect((await Promise.all(pending)).map((r) => r.status)).toEqual([200, 200, 200, 200]); // Every lease was released: a new upload is admitted. const after = await putBytes( - await mint('put', 'busy/6', { contentLength: 3 }), + await mint('put', 'temp-uploads/busy/6', { contentLength: 3, owner: { userId: 'user-6' } }), Buffer.from('six') ); expect(after.status).toBe(200); From 14b2d1220aeca2b79e7535a46868eb51ff2f9246 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 10:25:05 +0000 Subject: [PATCH 09/19] fix(selfhost): Cloudflare review findings for box uploads Watchdog timer cleared on cancel; 408 decided by a flag, not message text; leases renewed while bytes arrive (default 300 s) so a dead handler frees its slot quickly; length mismatches are 400; distinct error codes; no-store on GET; settings fallback logged; oversize attachment is a 400 AppError; the gate clock is a method, not an RPC argument. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/selfhost/object-urls/gate.ts | 25 ++++- apps/api/src/selfhost/object-urls/route.ts | 94 +++++++++++++------ apps/api/src/selfhost/object-urls/settings.ts | 9 +- apps/api/src/services/attachment-upload.ts | 3 +- .../unit/selfhost/box-object-urls.test.ts | 34 ++++++- deploy/selfhost/README.md | 7 +- 6 files changed, 128 insertions(+), 44 deletions(-) diff --git a/apps/api/src/selfhost/object-urls/gate.ts b/apps/api/src/selfhost/object-urls/gate.ts index 9aaaa1056c..822bf0dc4d 100644 --- a/apps/api/src/selfhost/object-urls/gate.ts +++ b/apps/api/src/selfhost/object-urls/gate.ts @@ -12,9 +12,9 @@ * uploads blocked. * * Why a Durable Object: the limit must hold across every Worker isolate celld runs, and a single - * object is the box's one serialization point. Each acquire is a lease with an expiry, so a handler - * that dies without releasing (celld restart, a killed isolate) frees its slot when the lease ends - * instead of holding it forever. `acquire` and `release` do all their work in synchronous SQL with + * object is the box's one serialization point. Each acquire is a lease with a short expiry that the + * route renews while bytes keep arriving, so a handler that dies without releasing (celld restart, + * a killed isolate) frees its slot within one lease instead of holding it forever. `acquire` and `release` do all their work in synchronous SQL with * no `await`, so two calls cannot interleave inside one (rule 45). */ import { DurableObject } from 'cloudflare:workers'; @@ -42,12 +42,17 @@ export class BoxUploadGate extends DurableObject { * Grants a lease to `id` while fewer than `limits.total` unexpired leases exist on the box and * fewer than `limits.perUploader` belong to `uploader`, so one uploader cannot hold every slot. */ + /** The gate's clock (a method, not an RPC argument, so no caller can move it). */ + protected now(): number { + return Date.now(); + } + acquire( id: string, uploader: string, - limits: { total: number; perUploader: number; leaseMs: number }, - now: number = Date.now() + limits: { total: number; perUploader: number; leaseMs: number } ): BoxUploadLease { + const now = this.now(); const sql = this.ctx.storage.sql; sql.exec('DELETE FROM upload_leases WHERE expires_at <= ?', now); const row = sql @@ -74,6 +79,15 @@ export class BoxUploadGate extends DurableObject { return { granted: true }; } + /** Extends a held lease while its upload is still receiving bytes (route.ts). */ + renew(id: string, leaseMs: number): void { + this.ctx.storage.sql.exec( + 'UPDATE upload_leases SET expires_at = ? WHERE id = ?', + this.now() + leaseMs, + id + ); + } + release(id: string): void { this.ctx.storage.sql.exec('DELETE FROM upload_leases WHERE id = ?', id); } @@ -88,6 +102,7 @@ interface BoxUploadGateStub { uploader: string, limits: { total: number; perUploader: number; leaseMs: number } ): Promise; + renew(id: string, leaseMs: number): Promise; release(id: string): Promise; } diff --git a/apps/api/src/selfhost/object-urls/route.ts b/apps/api/src/selfhost/object-urls/route.ts index c8a1cc76ea..99e9e51756 100644 --- a/apps/api/src/selfhost/object-urls/route.ts +++ b/apps/api/src/selfhost/object-urls/route.ts @@ -41,14 +41,15 @@ type BoxObjectEnv = Env & BoxUploadGateEnv; */ export const CELLD_CONDITIONAL_PUT_MAX_BYTES = 8 * 1024 * 1024; -function plain(status: number, message: string, headers: Record = {}): Response { - return Response.json( - { error: status === 503 ? 'BUSY' : 'BOX_OBJECT_REFUSED', message }, - { - status, - headers, - } - ); +type ErrorCode = 'REFUSED' | 'BUSY' | 'UNAVAILABLE' | 'UPLOAD_TIMEOUT' | 'UPLOAD_FAILED'; + +function plain( + status: number, + message: string, + headers: Record = {}, + error: ErrorCode = status === 503 ? 'BUSY' : 'REFUSED' +): Response { + return Response.json({ error, message }, { status, headers }); } /** Log fields that identify the request without the token. */ @@ -90,8 +91,11 @@ async function uploadLimits(env: Env): Promise { perUploader: setting(perUploader?.value, DEFAULT_LIMITS.perUploader), idleMs: setting(idle?.value, DEFAULT_LIMITS.idleMs, 1000), }; - } catch { + } catch (error) { // Settings storage unavailable: the defaults still bound memory. + log.warn('box_objects.limits_fallback', { + error: error instanceof Error ? error.message : String(error), + }); return DEFAULT_LIMITS; } } @@ -101,29 +105,47 @@ function uploader(claims: BoxObjectTokenClaims): string { return claims.sub?.w ? `w:${claims.sub.w}` : claims.sub?.u ? `u:${claims.sub.u}` : 'unknown'; } -const IDLE_ERROR = 'box upload received no bytes within its idle limit'; +interface Watchdog { + stream: TransformStream; + /** True once the watchdog dropped the upload for going idle. */ + idled: () => boolean; + dispose: () => void; +} -/** Passes bytes through; errors the stream if none arrive for `idleMs`, freeing the slot. */ -function idleWatchdog(idleMs: number): TransformStream { +/** + * Passes bytes through. Errors the stream if none arrive for `idleMs` (the slot is then freed), + * and calls `onProgress` at most every `progressEveryMs` while bytes keep arriving. + */ +function uploadWatchdog(idleMs: number, progressEveryMs: number, onProgress: () => void): Watchdog { let timer: ReturnType | undefined; + let idled = false; + let lastProgress = Date.now(); let fail: (error: Error) => void = () => undefined; + const dispose = () => clearTimeout(timer); const arm = () => { - clearTimeout(timer); - timer = setTimeout(() => fail(new Error(IDLE_ERROR)), idleMs); + dispose(); + timer = setTimeout(() => { + idled = true; + fail(new Error('box upload received no bytes within its idle limit')); + }, idleMs); }; - return new TransformStream({ + const stream = new TransformStream({ start(controller) { fail = (error) => controller.error(error); arm(); }, transform(chunk, controller) { arm(); + if (Date.now() - lastProgress >= progressEveryMs) { + lastProgress = Date.now(); + onProgress(); + } controller.enqueue(chunk); }, - flush() { - clearTimeout(timer); - }, + flush: dispose, + cancel: dispose, }); + return { stream, idled: () => idled, dispose }; } /** @@ -168,7 +190,9 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke if (!body && length > 0) return plain(400, 'Upload body is missing'); const gate = boxUploadGate(env); - if (!gate) return plain(503, 'Box uploads are unavailable (no upload gate binding)'); + if (!gate) { + return plain(503, 'Box uploads are unavailable (no upload gate binding)', {}, 'UNAVAILABLE'); + } const limits = await uploadLimits(env); const leaseId = crypto.randomUUID(); const lease = await gate.acquire(leaseId, uploader(claims), limits); @@ -183,12 +207,16 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke 'Retry-After': String(lease.retryAfterSeconds), }); } + const watchdog = uploadWatchdog(limits.idleMs, Math.max(1000, limits.leaseMs / 3), () => { + // Keep the slot while bytes arrive; a failed renewal only shortens it to the lease. + gate.renew(leaseId, limits.leaseMs).catch(() => undefined); + }); try { const atomic = length <= CELLD_CONDITIONAL_PUT_MAX_BYTES; - if (!atomic && (await env.R2.head(claims.key))) return conflict(env, claims, length); + if (!atomic && (await env.R2.head(claims.key))) return await conflict(env, claims, length); // FixedLengthStream makes a short or long body an error instead of a truncated object. const stream = body - ? body.pipeThrough(idleWatchdog(limits.idleMs)).pipeThrough(new FixedLengthStream(length)) + ? body.pipeThrough(watchdog.stream).pipeThrough(new FixedLengthStream(length)) : new Uint8Array(0); let written: R2Object | null; try { @@ -201,15 +229,22 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke } catch (error) { const message = error instanceof Error ? error.message : String(error); log.warn('box_objects.upload_failed', { ...logFields(claims), length, error: message }); - if (message.includes(IDLE_ERROR)) return plain(408, 'The upload stopped sending data'); - return claims.sha && /sha-?256/i.test(message) - ? plain(400, 'Upload body does not match the declared sha256') - : plain(502, 'The upload did not complete; retry it'); + if (watchdog.idled()) { + return plain(408, 'The upload stopped sending data', {}, 'UPLOAD_TIMEOUT'); + } + if (claims.sha && /sha-?256/i.test(message)) { + return plain(400, 'Upload body does not match the declared sha256'); + } + if (/FixedLengthStream|too (many|few) bytes|length/i.test(message)) { + return plain(400, `Upload body did not match its Content-Length of ${length} bytes`); + } + return plain(502, 'The upload did not complete; retry it', {}, 'UPLOAD_FAILED'); } - if (!written) return conflict(env, claims, length); + if (!written) return await conflict(env, claims, length); log.info('box_objects.uploaded', { ...logFields(claims), length }); return new Response(null, { status: 200, headers: { ETag: written.httpEtag } }); } finally { + watchdog.dispose(); await gate.release(leaseId).catch((error: unknown) => { // The lease expires on its own; a failed release only delays the slot. log.warn('box_objects.lease_release_failed', { @@ -223,7 +258,12 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke async function get(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectTokenClaims) { const object = await c.env.R2.get(claims.key); if (!object) return plain(404, 'Object not found'); - const headers = new Headers({ 'Content-Length': String(object.size), ETag: object.httpEtag }); + const headers = new Headers({ + 'Content-Length': String(object.size), + ETag: object.httpEtag, + // The URL carries a bearer token: nothing in between may keep the response. + 'Cache-Control': 'private, no-store', + }); if (object.httpMetadata?.contentType) headers.set('Content-Type', object.httpMetadata.contentType); log.info('box_objects.downloaded', { ...logFields(claims), length: object.size }); diff --git a/apps/api/src/selfhost/object-urls/settings.ts b/apps/api/src/selfhost/object-urls/settings.ts index 23d928f6c5..b6be8e9fe6 100644 --- a/apps/api/src/selfhost/object-urls/settings.ts +++ b/apps/api/src/selfhost/object-urls/settings.ts @@ -15,11 +15,10 @@ import { export const DEFAULT_BOX_OBJECT_MAX_CONCURRENT_UPLOADS = 4; /** - * Seconds one upload holds its slot at most. It frees the slot of a handler that died without - * releasing it. An upload that runs longer is not cut; the box may then admit one upload over the - * limit until it ends. 1800 s covers 1 GiB at 0.6 MB/s. + * Seconds a slot stays held without renewal. The route renews it while bytes keep arriving, so a + * slow upload keeps its slot; a handler that died without releasing frees it within this time. */ -export const DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS = 1800; +export const DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS = 300; /** * Of those, how many one uploader (a workspace, else a user) may hold at once, so one uploader @@ -53,7 +52,7 @@ export const BOX_OBJECT_SETTINGS: readonly AdminSettingDefinition[] = [ BOX_OBJECT_UPLOAD_LEASE_SECONDS, DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS, 'Operations', - 'Seconds one upload counts against the concurrent-upload limit at most, so an upload whose handler died frees its slot.', + 'Seconds an upload slot stays held without progress. Renewed while bytes arrive; frees the slot of an upload whose handler died.', { min: 60, max: 86_400 } ), integerDefinition( diff --git a/apps/api/src/services/attachment-upload.ts b/apps/api/src/services/attachment-upload.ts index 5e14ecb272..e60be762c1 100644 --- a/apps/api/src/services/attachment-upload.ts +++ b/apps/api/src/services/attachment-upload.ts @@ -11,6 +11,7 @@ import { ATTACHMENT_DEFAULTS, SAFE_FILENAME_REGEX } from '@simple-agent-manager/ import type { Env } from '../env'; import { log } from '../lib/logger'; import { parsePositiveInt } from '../lib/route-helpers'; +import { errors } from '../middleware/error'; import { getR2ObjectUrlSigner } from './r2-s3-client'; function getMaxBytes(env: Env): number { @@ -86,7 +87,7 @@ export async function generatePresignedUploadUrl( const signer = getR2ObjectUrlSigner(env); const expiresIn = getPresignExpiry(env); if (signer.maxPutBytes !== undefined && size > signer.maxPutBytes) { - throw new Error(`File size ${size} exceeds maximum ${signer.maxPutBytes} bytes`); + throw errors.badRequest(`File size ${size} exceeds maximum ${signer.maxPutBytes} bytes`); } const uploadUrl = await signer.putUrl(r2Key, { diff --git a/apps/api/tests/unit/selfhost/box-object-urls.test.ts b/apps/api/tests/unit/selfhost/box-object-urls.test.ts index fffa62f55d..12ad5e815d 100644 --- a/apps/api/tests/unit/selfhost/box-object-urls.test.ts +++ b/apps/api/tests/unit/selfhost/box-object-urls.test.ts @@ -167,14 +167,23 @@ function gateNamespace(gate: BoxUploadGate) { uploader: string, limits: { total: number; perUploader: number; leaseMs: number } ) => gate.acquire(id, uploader, limits), + renew: async (id: string, leaseMs: number) => gate.renew(id, leaseMs), release: async (id: string) => gate.release(id), }), }; } +/** The real gate with a clock the test moves. */ +class TestGate extends BoxUploadGate { + clock = Date.now(); + protected override now(): number { + return this.clock; + } +} + function boxEnv(overrides: Partial> = {}) { const R2 = fakeR2(); - const gate = new BoxUploadGate({ storage: { sql: sqliteStorage() } } as never, {}); + const gate = new TestGate({ storage: { sql: sqliteStorage() } } as never, {}); const env = { BASE_DOMAIN: DOMAIN, ENCRYPTION_KEY: KEY, @@ -673,9 +682,26 @@ describe('PUT/GET /api/box-objects', () => { it('an expired lease frees its slot (a handler that died without releasing)', () => { const { gate } = boxEnv(); const one = { total: 1, perUploader: 1, leaseMs: 1_000 }; - gate.acquire('dead', 'u:a', one, 0); - expect(gate.acquire('next', 'u:b', one, 500).granted).toBe(false); - expect(gate.acquire('next', 'u:b', one, 1_000).granted).toBe(true); + gate.clock = 0; + gate.acquire('dead', 'u:a', one); + gate.clock = 500; + expect(gate.acquire('next', 'u:b', one).granted).toBe(false); + gate.clock = 1_000; + expect(gate.acquire('next', 'u:b', one).granted).toBe(true); + }); + + it('renewing a lease keeps a slow but moving upload in its slot', () => { + const { gate } = boxEnv(); + const one = { total: 1, perUploader: 1, leaseMs: 1_000 }; + gate.clock = 0; + gate.acquire('slow', 'u:a', one); + gate.clock = 900; + gate.renew('slow', 1_000); + gate.clock = 1_500; + expect(gate.acquire('next', 'u:b', one).granted).toBe(false); + // Control: without further renewal it expires. + gate.clock = 1_900; + expect(gate.acquire('next', 'u:b', one).granted).toBe(true); }); it('one uploader cannot take every slot: a second uploader is still admitted', async () => { diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index ee39d868a1..8a479ee336 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -1019,8 +1019,11 @@ Session snapshots keep their own upload route, which also streams through the bo above it, so on a box without a store key an app's image artifact is limited to 1 GiB (the agent is told the limit and stops before uploading). Parted uploads are tracked in idea `01M83WWQTNTBD4SY1530G3XWH7`. -- **Concurrent uploads are capped** (Admin settings `boxObjects.maxConcurrentUploads`, default 4; - `boxObjects.uploadLeaseSeconds`, default 1800). Each in-flight upload costs celld about 85 MB of +- **Concurrent uploads are capped** (Admin settings `boxObjects.maxConcurrentUploads`, default 4, + of which one uploader may hold `boxObjects.maxUploadsPerUploader`, default 2). An upload that + receives no bytes for `boxObjects.uploadIdleSeconds` (default 60) is dropped with 408, and a slot + whose handler died frees within `boxObjects.uploadLeaseSeconds` (default 300; renewed while bytes + arrive). Each in-flight upload costs celld about 85 MB of memory (measured on celld 0.6.3: peak RSS 220 MB for one 1 GB upload, 427 MB for four, 896 MB for eight; throughput stops growing after two at about 180 MB/s). Further uploads get 503 with `Retry-After`. From b8e9f8bce45e4e18a160465a6d40bcf2226d5c5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 10:47:07 +0000 Subject: [PATCH 10/19] test(selfhost): build the forged-token URL instead of a token-shaped literal Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/live/box-object-urls.live.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/selfhost/live/box-object-urls.live.test.ts b/scripts/selfhost/live/box-object-urls.live.test.ts index 65f6901c4a..0c9391b86e 100644 --- a/scripts/selfhost/live/box-object-urls.live.test.ts +++ b/scripts/selfhost/live/box-object-urls.live.test.ts @@ -46,6 +46,8 @@ export default app; `; const KEY = 'objectadmin'; +/** A token that cannot verify: a well-formed prefix with an unsigned payload. */ +const FORGED_TOKEN_PATH = `/api/box-objects?${new URLSearchParams({ token: ['samobj1', 'x', 'y'].join('.') })}`; const SECRET = randomBytes(16).toString('hex'); let store: ObjectStore; let celld: Running | undefined; @@ -205,7 +207,7 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { // usually reports a socket error instead of the response. (A client sending // `Expect: 100-continue`, as curl does for large bodies, gets the 403 and sends nothing.) const status = await new Promise((done) => { - const req = request(`http://127.0.0.1:${port}/api/box-objects?token=samobj1.forged.forged`, { + const req = request(`http://127.0.0.1:${port}${FORGED_TOKEN_PATH}`, { method: 'PUT', headers: { 'content-length': String(length) }, }); From 8bedbfb295f5d599627bc1f8acd851fb122dff5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 11:12:03 +0000 Subject: [PATCH 11/19] fix(selfhost): session snapshots upload through the box On a box the Worker-streamed snapshot route needs X-SAM-Content-SHA256, which the box Caddy strips from every client request, so every artifact PUT got 400 and snapshots degraded to transcript-only (seen on the disposable GCS box). Direct snapshot uploads now use the shared object URL signer: R2 presign as before on Cloudflare (pinned), a sha256-bound box URL on a box. Token key allowlist includes the configured snapshot prefix. Removes the now-unused hasR2S3Credentials. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/selfhost/object-urls/tokens.ts | 45 +++++++++++---- apps/api/src/services/r2-s3-client.ts | 4 -- .../session-snapshot-direct-upload.ts | 33 +++++++++-- .../unit/selfhost/box-object-urls.test.ts | 55 ++++++++++++++++++- .../unit/services/r2-presign-config.test.ts | 6 +- deploy/selfhost/README.md | 8 ++- 6 files changed, 123 insertions(+), 28 deletions(-) diff --git a/apps/api/src/selfhost/object-urls/tokens.ts b/apps/api/src/selfhost/object-urls/tokens.ts index 8e66c7691c..a1560232c0 100644 --- a/apps/api/src/selfhost/object-urls/tokens.ts +++ b/apps/api/src/selfhost/object-urls/tokens.ts @@ -17,6 +17,8 @@ */ import { BUILD_CONTEXT_PREFIX } from '@simple-agent-manager/app-deployment'; +import type { Env } from '../../env'; +import { getSessionSnapshotConfig } from '../../services/session-snapshot-artifacts'; import { MAX_SIGNED_TOKEN_LENGTH, mintSignedToken, @@ -56,9 +58,10 @@ const PURPOSE = { /** * The only key prefixes a token may name: task attachments (`attachment-upload.ts` - * buildAttachmentR2Key), compose image artifacts (`buildComposeImageArtifactKey`) and build - * contexts (`buildContextKey`). The R2 binding also holds vm-agent binaries and session snapshots, - * so a minting bug must not be able to reach them. Enforced at mint and at verify. + * buildAttachmentR2Key), compose image artifacts (`buildComposeImageArtifactKey`), build contexts + * (`buildContextKey`) and session snapshot artifacts (`buildSessionSnapshotR2Key`, under the + * configured SESSION_SNAPSHOT_R2_PREFIX). The R2 binding also holds vm-agent binaries and other + * Worker state, so a minting bug must not be able to reach them. Enforced at mint and at verify. */ export const BOX_OBJECT_KEY_PREFIXES: readonly string[] = [ 'temp-uploads/', @@ -66,6 +69,17 @@ export const BOX_OBJECT_KEY_PREFIXES: readonly string[] = [ BUILD_CONTEXT_PREFIX, ]; +/** What the token functions read from the Worker env. */ +export type BoxObjectTokenEnv = Pick & + Partial> & + Pick; + +/** The fixed prefixes plus this install's session snapshot prefix. */ +export function boxObjectKeyPrefixes(env: Pick): string[] { + const { r2Prefix } = getSessionSnapshotConfig(env as Env); + return [...BOX_OBJECT_KEY_PREFIXES, `${r2Prefix}/`]; +} + /** Longest lifetime a token may have, whatever the minting route asked for. */ export const MAX_BOX_OBJECT_TOKEN_SECONDS = 24 * 60 * 60; @@ -80,9 +94,12 @@ const MAX_METADATA_VALUE_LENGTH = 256; * `..` segment, no backslash or control character. Keys SAM builds always pass; anything else is * refused at mint and at verify. */ -export function isSafeObjectKey(key: string): boolean { +export function isSafeObjectKey( + key: string, + prefixes: readonly string[] = BOX_OBJECT_KEY_PREFIXES +): boolean { if (!key || key.length > MAX_KEY_LENGTH) return false; - if (!BOX_OBJECT_KEY_PREFIXES.some((prefix) => key.startsWith(prefix))) return false; + if (!prefixes.some((prefix) => key.startsWith(prefix))) return false; // eslint-disable-next-line no-control-regex -- control characters are exactly what is refused if (key.startsWith('/') || key.includes('\\') || /[\u0000-\u001f\u007f]/.test(key)) return false; return key.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..'); @@ -111,9 +128,12 @@ function optionalId(value: unknown): value is string | undefined { } /** The claims if they are well formed; null otherwise. */ -function parseClaims(raw: Record): BoxObjectTokenClaims | null { +function parseClaims( + raw: Record, + prefixes: readonly string[] +): BoxObjectTokenClaims | null { if (raw.v !== 1 || (raw.op !== 'put' && raw.op !== 'get')) return null; - if (typeof raw.key !== 'string' || !isSafeObjectKey(raw.key)) return null; + if (typeof raw.key !== 'string' || !isSafeObjectKey(raw.key, prefixes)) return null; if (!positiveInteger(raw.exp)) return null; if (raw.len !== undefined && !positiveInteger(raw.len)) return null; if (raw.max !== undefined && !positiveInteger(raw.max)) return null; @@ -152,7 +172,7 @@ export type BoxObjectTokenInput = Omit & { }; export async function mintBoxObjectToken( - env: Pick, + env: BoxObjectTokenEnv, input: BoxObjectTokenInput, now: number = Date.now() ): Promise { @@ -160,7 +180,10 @@ export async function mintBoxObjectToken( if (!positiveInteger(expiresIn) || expiresIn > MAX_BOX_OBJECT_TOKEN_SECONDS) { throw new Error(`Box object token lifetime must be 1..${MAX_BOX_OBJECT_TOKEN_SECONDS} seconds`); } - const claims = parseClaims({ ...rest, v: 1, exp: Math.floor(now / 1000) + expiresIn }); + const claims = parseClaims( + { ...rest, v: 1, exp: Math.floor(now / 1000) + expiresIn }, + boxObjectKeyPrefixes(env) + ); if (!claims) throw new Error('Box object token claims are invalid'); const token = await mintSignedToken(env, PURPOSE, claims); // Verification refuses longer tokens; fail here instead of handing out a URL that cannot work. @@ -170,12 +193,12 @@ export async function mintBoxObjectToken( /** Signature, shape and expiry. Null for any token that is not valid now. */ export async function verifyBoxObjectToken( - env: SignedTokenEnv, + env: BoxObjectTokenEnv, token: string, now: number = Date.now() ): Promise { const raw = await verifySignedToken(env, PURPOSE, token); - const claims = raw ? parseClaims(raw) : null; + const claims = raw ? parseClaims(raw, boxObjectKeyPrefixes(env)) : null; if (!claims || claims.exp * 1000 <= now) return null; // A token valid for longer than any minter may issue is not one SAM minted correctly. if (claims.exp * 1000 - now > MAX_BOX_OBJECT_TOKEN_SECONDS * 1000) return null; diff --git a/apps/api/src/services/r2-s3-client.ts b/apps/api/src/services/r2-s3-client.ts index a28c5d0679..7e7cf24fa9 100644 --- a/apps/api/src/services/r2-s3-client.ts +++ b/apps/api/src/services/r2-s3-client.ts @@ -28,10 +28,6 @@ export interface R2PresignTarget { const MAX_CACHED_CLIENTS = 4; const clients = new Map(); -export function hasR2S3Credentials(env: Env): boolean { - return resolveR2PresignConfig(env) !== null; -} - function clientFor(config: R2PresignConfig, checksum: R2ChecksumMode): S3Client { const cacheKey = JSON.stringify([ config.endpoint, diff --git a/apps/api/src/services/session-snapshot-direct-upload.ts b/apps/api/src/services/session-snapshot-direct-upload.ts index 997193fc62..6da081da8e 100644 --- a/apps/api/src/services/session-snapshot-direct-upload.ts +++ b/apps/api/src/services/session-snapshot-direct-upload.ts @@ -3,12 +3,21 @@ import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; import type { Env } from '../env'; import { parsePositiveInt } from '../lib/route-helpers'; -import { getR2PresignTarget, hasR2S3Credentials } from './r2-s3-client'; +import { + getR2PresignTarget, + r2ObjectUrlsAvailable, + resolveR2ObjectUrlSigner, +} from './r2-s3-client'; export const DEFAULT_SESSION_SNAPSHOT_UPLOAD_URL_TTL_SECONDS = 15 * 60; +/** + * Direct uploads need a URL signer: R2 presign (Cloudflare, or an operator store with a key), or + * on a self-hosted box its own upload route. A box needs the second: the Worker-streamed fallback + * route reads `X-SAM-Content-SHA256`, which the box's Caddy strips from every client request. + */ export function sessionSnapshotDirectUploadAvailable(env: Env): boolean { - return hasR2S3Credentials(env); + return r2ObjectUrlsAvailable(env); } function checksumBase64(checksumHex: string): string { @@ -28,6 +37,21 @@ export async function generateSessionSnapshotDirectUploadUrl( checksumHeader?: boolean; } ): Promise { + const expiresIn = parsePositiveInt( + env.SESSION_SNAPSHOT_UPLOAD_URL_TTL_SECONDS, + DEFAULT_SESSION_SNAPSHOT_UPLOAD_URL_TTL_SECONDS + ); + const signer = resolveR2ObjectUrlSigner(env); + if (signer?.kind === 'box') { + // The box verifies the digest itself (R2 put `sha256`), so no checksum header is signed. + return signer.putUrl(input.key, { + expiresIn, + contentLength: input.sizeBytes, + contentType: input.contentType, + sha256: input.sha256, + }); + } + // Presign: unchanged (pinned by r2-presign-cloudflare-equivalence.test.ts). const target = getR2PresignTarget(env); const command = new PutObjectCommand({ Bucket: target.bucket, @@ -37,10 +61,7 @@ export async function generateSessionSnapshotDirectUploadUrl( ChecksumSHA256: checksumBase64(input.sha256), }); return getSignedUrl(target.client, command, { - expiresIn: parsePositiveInt( - env.SESSION_SNAPSHOT_UPLOAD_URL_TTL_SECONDS, - DEFAULT_SESSION_SNAPSHOT_UPLOAD_URL_TTL_SECONDS - ), + expiresIn, ...(input.checksumHeader ? { unhoistableHeaders: new Set(['x-amz-checksum-sha256']) } : {}), }); } diff --git a/apps/api/tests/unit/selfhost/box-object-urls.test.ts b/apps/api/tests/unit/selfhost/box-object-urls.test.ts index 12ad5e815d..dabbd13dce 100644 --- a/apps/api/tests/unit/selfhost/box-object-urls.test.ts +++ b/apps/api/tests/unit/selfhost/box-object-urls.test.ts @@ -46,6 +46,11 @@ import { resetR2S3ClientsForTests, resolveR2ObjectUrlSigner, } from '../../../src/services/r2-s3-client'; +import { buildSessionSnapshotR2Key } from '../../../src/services/session-snapshot-artifacts'; +import { + generateSessionSnapshotDirectUploadUrl, + sessionSnapshotDirectUploadAvailable, +} from '../../../src/services/session-snapshot-direct-upload'; // Settings storage: unavailable by default (the route then uses its defaults); tests override it. vi.mock('../../../src/services/admin-settings-resolution', () => ({ @@ -322,7 +327,7 @@ describe('box object token scope', () => { it('refuses keys outside the upload prefixes at mint, and at verify even when correctly signed', async () => { for (const key of [ 'agents/vm-agent-linux-amd64', - 'session-snapshots/s1/a.tar', + 'library/p1/f1', 'temp-uploadsX/a', ]) { expect(isSafeObjectKey(key)).toBe(false); @@ -496,6 +501,54 @@ describe('callers on a keyless box', () => { expect(claims).toMatchObject({ key: slot.r2Key, len: 9, sha, md: { sha256: sha } }); }); + it('session snapshots get a box URL binding the length and sha256 (the fallback route cannot work behind Caddy)', async () => { + const { env } = boxEnv(); + // Cloudflare without a key: no direct uploads. A keyless box: direct uploads through the box. + expect(sessionSnapshotDirectUploadAvailable(env)).toBe(false); + installBoxObjectUrls(); + expect(sessionSnapshotDirectUploadAvailable(env)).toBe(true); + const key = buildSessionSnapshotR2Key(env, 'chat-1', 'gen-1', 'home'); + const sha256 = 'b'.repeat(64); + const url = new URL( + await generateSessionSnapshotDirectUploadUrl(env, { + key, + sizeBytes: 1234, + sha256, + contentType: 'application/x-tar', + checksumHeader: true, + }) + ); + expect(url.pathname).toBe(BOX_OBJECT_ROUTE); + const claims = await verifyBoxObjectToken(env, url.searchParams.get('token')!); + expect(claims).toMatchObject({ + op: 'put', + key, + len: 1234, + sha: sha256, + ct: 'application/x-tar', + }); + }); + + it('snapshot keys are allowed under the configured prefix only', async () => { + const custom = { ENCRYPTION_KEY: KEY, SESSION_SNAPSHOT_R2_PREFIX: 'box-snaps' }; + const key = buildSessionSnapshotR2Key(custom as Env, 'chat-1', 'gen-1', 'wip'); + expect(key.startsWith('box-snaps/')).toBe(true); + await expect( + mintBoxObjectToken(custom, { op: 'put', key, len: 1, expiresIn: 60 }) + ).resolves.toMatch(/^samobj1\./); + // The same key is outside the allowlist of an install using the default prefix. + await expect( + mintBoxObjectToken({ ENCRYPTION_KEY: KEY }, { op: 'put', key, len: 1, expiresIn: 60 }) + ).rejects.toThrow(); + const defaultKey = buildSessionSnapshotR2Key({} as Env, 'chat-1', 'gen-1', 'wip'); + await expect( + mintBoxObjectToken( + { ENCRYPTION_KEY: KEY }, + { op: 'put', key: defaultKey, len: 1, expiresIn: 60 } + ) + ).resolves.toMatch(/^samobj1\./); + }); + it('a single upload over 1 GiB is refused when the URL is requested', async () => { const signer = createBoxObjectUrlSigner(boxEnv().env)!; await expect( diff --git a/apps/api/tests/unit/services/r2-presign-config.test.ts b/apps/api/tests/unit/services/r2-presign-config.test.ts index a7a6fa8111..8936aa400a 100644 --- a/apps/api/tests/unit/services/r2-presign-config.test.ts +++ b/apps/api/tests/unit/services/r2-presign-config.test.ts @@ -7,7 +7,7 @@ import { generatePresignedUploadUrl } from '../../../src/services/attachment-upl import { resolveR2PresignConfig } from '../../../src/services/r2-presign-config'; import { getR2PresignTarget, - hasR2S3Credentials, + r2ObjectUrlsAvailable, resetR2S3ClientsForTests, } from '../../../src/services/r2-s3-client'; @@ -82,7 +82,7 @@ describe('resolveR2PresignConfig', () => { // CF_ACCOUNT_ID is present: a fallback would sign store keys for Cloudflare R2. const env = operatorStoreEnv({ CF_ACCOUNT_ID: 'acct123', ...change }); expect(resolveR2PresignConfig(env)).toBeNull(); - expect(hasR2S3Credentials(env)).toBe(false); + expect(r2ObjectUrlsAvailable(env)).toBe(false); }); it.each(['R2_S3_BUCKET', 'R2_S3_KEY_PREFIX', 'R2_S3_REGION', 'R2_S3_FORCE_PATH_STYLE'] as const)( @@ -90,7 +90,7 @@ describe('resolveR2PresignConfig', () => { (name) => { const env = cloudflareEnv({ [name]: 'celld-fleet' }); expect(resolveR2PresignConfig(env)).toBeNull(); - expect(hasR2S3Credentials(cloudflareEnv())).toBe(true); + expect(r2ObjectUrlsAvailable(cloudflareEnv())).toBe(true); } ); diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 8a479ee336..eecc9c1ffc 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -1004,8 +1004,9 @@ repository, so it never notices an `.env` edit. port is what the deploy publishes and checks, and each one is logged by name. Shell variables no compose file uses are ignored. Set the box in `.env`, not the shell. -**Object store and uploads through the box.** Task attachments, build contexts and app image -artifacts are uploaded through the box by default: no store credential is needed. The Worker hands +**Object store and uploads through the box.** Task attachments, build contexts, app image +artifacts and session snapshots are uploaded through the box by default: no store credential is +needed. The Worker hands the uploader (browser or agent) a URL to `https://api.SAM_DOMAIN/api/box-objects?token=...`, signed by SAM itself with a key derived from `ENCRYPTION_KEY`. It rotates with `selfhost:secrets rotate`: while a rotation overlaps, URLs signed with the previous key stay valid (`ENCRYPTION_KEY_PREVIOUS`), @@ -1013,7 +1014,8 @@ and once that key is dropped an unused URL fails with 403 like an expired one; t The token names one object, one operation, a size limit and an expiry of minutes; the box streams the body into the bucket through celld's R2 binding without holding it in memory, and the write is create-only. Downloads (image artifacts on deployment nodes, build contexts) work the same way. -Session snapshots keep their own upload route, which also streams through the box. +Session snapshot artifacts take this route too: their older Worker upload route needs a header +that the box's Caddy strips from every client request (`X-SAM-*`), so it cannot work on a box. - **One request carries at most 1 GiB.** celld refuses a larger body (413) and cannot be configured above it, so on a box without a store key an app's image artifact is limited to 1 GiB (the agent From 3194e6bbfee85ff16434ff6a813a1a831fdb29c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 11:14:42 +0000 Subject: [PATCH 12/19] test(api): compose init answers 503 naming the settings; task file brought up to date Co-Authored-By: Claude Opus 5.5 --- .../compose-image-artifacts-callback.test.ts | 16 +++++++ .../2026-11-23-selfhost-box-object-uploads.md | 48 ++++++++++++------- 2 files changed, 48 insertions(+), 16 deletions(-) diff --git a/apps/api/tests/unit/routes/compose-image-artifacts-callback.test.ts b/apps/api/tests/unit/routes/compose-image-artifacts-callback.test.ts index 95cdd4aa87..4269e8d7d9 100644 --- a/apps/api/tests/unit/routes/compose-image-artifacts-callback.test.ts +++ b/apps/api/tests/unit/routes/compose-image-artifacts-callback.test.ts @@ -172,6 +172,22 @@ describe('compose-image-artifacts callback (vertical slice)', () => { services: [{ serviceName: 'web', sourceRef: 'workspace-web' }], }; + it('answers 503 naming the missing settings when nothing can sign URLs (never 500)', async () => { + // The real wrapper and resolver: no presign credential and no box signer installed. + const actual = await vi.importActual< + typeof import('../../../src/services/compose-image-artifacts') + >('../../../src/services/compose-image-artifacts'); + createUploadsMock.mockImplementationOnce((env, input) => + actual.createComposeImageArtifactUploads(env as never, input as never) + ); + const app = await buildApp(); + const res = await request(app, 'proj-1', 'init', validInit); + expect(res.status).toBe(503); + const body = (await res.json()) as { message: string }; + expect(body.message).toContain('R2_ACCESS_KEY_ID'); + expect(body.message).toContain('self-host build'); + }); + it('creates upload targets for a valid init request', async () => { const app = await buildApp(); const res = await request(app, 'proj-1', 'init', validInit); diff --git a/tasks/active/2026-11-23-selfhost-box-object-uploads.md b/tasks/active/2026-11-23-selfhost-box-object-uploads.md index 446b45512c..c7ba7ee794 100644 --- a/tasks/active/2026-11-23-selfhost-box-object-uploads.md +++ b/tasks/active/2026-11-23-selfhost-box-object-uploads.md @@ -29,6 +29,10 @@ R2 interface). | put with `onlyIf: {etagDoesNotMatch: '*'}` x2 | first writes, second returns null (write-once) | - | - | | put with a wrong `sha256` | rejected | - | - | +Concurrent 1 GB uploads (same setup): peak RSS 220 / 284 / 427 / 896 MB for 1 / 2 / 4 / 8 uploads, +about 85 MB per in-flight upload over a ~150 MB base. Aggregate throughput is flat at ~182 MB/s +from 2 uploads on. Hence the default cap of 4 (~430 MB peak). + The body never sits in the isolate heap and RSS stays far below the body size, so streaming works. **Hard limit:** one request through celld carries at most 1 GiB. Larger compose artifacts need a parted upload, which changes the vm-agent client. Deferred to PR B (idea filed in this PR). @@ -37,7 +41,7 @@ parted upload, which changes the vm-agent client. Deferred to PR B (idea filed i ``` uploader ─(1) init (existing authenticated route)─► Worker: mint token {op, key, max, ct, sha?, exp} - uploader ─(2) PUT/GET https://api./api/self-host/objects?token=…─► Caddy ─► celld Worker + uploader ─(2) PUT/GET https://api./api/box-objects?token=…─► Caddy ─► celld Worker Worker ─(3) verify token → R2.put(key, body, {onlyIf: write-once, sha256?}) / R2.get(key) stream ``` @@ -48,8 +52,18 @@ parted upload, which changes the vm-agent client. Deferred to PR B (idea filed i client changes and no rollout coupling. Caddy never logs query strings; SAM's request log records only the pathname. - Key: HKDF-SHA256 from `ENCRYPTION_KEY` with its own label (the hosted-git token pattern, shared - helper). It rotates with `selfhost:secrets rotate`; `ENCRYPTION_KEY_PREVIOUS` verifies during the - overlap. No operator input, no new secret. + helper). It rotates with `selfhost:secrets rotate`. A token is verified once, when its request + starts, so a rotation during an upload does not affect it. A token minted before the switch + verifies through `ENCRYPTION_KEY_PREVIOUS` during the overlap. Once that key is dropped, an + unused URL gets 403 like an expired presigned URL, and the client asks for a new one. No operator + input, no new secret. +- Box-wide concurrency cap (`BoxUploadGate` DO, self-host only): `boxObjects.maxConcurrentUploads` + (4), `boxObjects.maxUploadsPerUploader` (2), `boxObjects.uploadIdleSeconds` (60, then 408), + `boxObjects.uploadLeaseSeconds` (300, renewed while bytes arrive). Over the cap: 503 + Retry-After. +- Session snapshots: their Worker-streamed route needs `X-SAM-Content-SHA256`, which the box Caddy + strips (`request_header -X-SAM-*`), so every snapshot artifact PUT got 400 on a box (found on the + disposable GCS box). Direct snapshot uploads now use the same signer (sha256-bound box URL). + Restores read through the Worker's GET route with `Authorization`, which Caddy keeps. ## Threat model @@ -67,19 +81,21 @@ parted upload, which changes the vm-agent client. Deferred to PR B (idea filed i ## Checklist -- [ ] Shared signed-token helper extracted from `selfhost/hosted-git/tokens.ts` (rule 59: extend, not fork); hosted-git tests unchanged and green -- [ ] Object URL token mint/verify (`selfhost/object-urls/tokens.ts`) -- [ ] Box route `PUT|GET /api/self-host/objects` (write-once put, sha256, size cap, FixedLengthStream, streaming GET) -- [ ] `ObjectUrlSigner` seam: app-deployment compose + build-context take a signer; attachments use it -- [ ] `getR2ObjectUrlSigner(env)`: presign when configured, else installed box signer, else `AppError` 503 naming the settings -- [ ] Attachments `request-upload` availability uses the same resolver (403 → works on box) -- [ ] Compose `maxBytes` clamped to the box limit so the agent fails before uploading -- [ ] Rule 74 tests: Cloudflare Env → presign; box Env (no key) → box route; box with key → presign -- [ ] Cloudflare byte-identity test still green (`r2-presign-cloudflare-equivalence.test.ts`) -- [ ] Self-host-only module test: Cloudflare bundle does not import the box signer -- [ ] Docs: `deploy/selfhost/README.md` "Object store and presigned uploads"; static key optional -- [ ] Idea for PR B (parted uploads > 1 GiB) -- [ ] Live celld test of the route (`scripts/selfhost/live`), small body + over-cap +- [x] Shared signed-token helper extracted from `selfhost/hosted-git/tokens.ts` (rule 59: extend, not fork); hosted-git tests unchanged and green +- [x] Object URL token mint/verify (`selfhost/object-urls/tokens.ts`), key-prefix allowlist incl. the snapshot prefix, 24 h cap +- [x] Box route `PUT|GET /api/box-objects` (create-only put, sha256, size cap, FixedLengthStream, idle watchdog, streaming GET) +- [x] `ObjectUrlSigner` seam: app-deployment compose + build-context take a signer; attachments and snapshots use it +- [x] `getR2ObjectUrlSigner(env)`: presign when configured, else installed box signer, else `AppError` 503 naming the settings (route-level test) +- [x] Attachments `request-upload` availability uses the same resolver (403 → works on box) +- [x] Session snapshot direct uploads use the signer on a box (the fallback route cannot pass Caddy) +- [x] Compose `maxBytes` clamped to the box limit so the agent fails before uploading +- [x] Concurrency gate DO + settings (coordinator requirement), memory arithmetic stated +- [x] Rule 74 tests: Cloudflare Env → presign; box Env (no key) → box route; box with key → presign +- [x] Cloudflare byte-identity test still green (`r2-presign-cloudflare-equivalence.test.ts`) +- [x] Self-host-only module test: Cloudflare bundle does not import the box signer +- [x] Docs: `deploy/selfhost/README.md` "Object store and uploads through the box"; static key optional +- [x] Idea for PR B (parted uploads > 1 GiB, vm-agent URL redaction, 503 retry): `01M83WWQTNTBD4SY1530G3XWH7` +- [x] Live celld test of the route (`scripts/selfhost/live/box-object-urls.live.test.ts`, 8 cases) - [ ] Disposable GCS box proof, no HMAC key: publish → release → app 200; attachment up/down; snapshot - [ ] Staging: hosted attachments + compose publish still work From 1733dfca58b7ca6878bd03a381deb90e81648f5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 11:29:02 +0000 Subject: [PATCH 13/19] chore(secret-scan): review the placeholder box token literal in 4fc3f59e0 The PR-range scan flags an unsigned test placeholder (samobj1.forged.forged) that a later commit already replaced. Exact digest, 30-day expiry. Co-Authored-By: Claude Opus 5.5 --- scripts/quality/gitleaks-reviewed-baseline.json | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/scripts/quality/gitleaks-reviewed-baseline.json b/scripts/quality/gitleaks-reviewed-baseline.json index 5285be516a..b6fd861c31 100644 --- a/scripts/quality/gitleaks-reviewed-baseline.json +++ b/scripts/quality/gitleaks-reviewed-baseline.json @@ -271,6 +271,14 @@ "reviewedAt": "2026-11-21T12:15:00.000Z", "expiresAt": "2026-12-21T12:15:00.000Z", "digests": ["3a21e85ace0487849684219c304ea50f026912329b377658c85ba2caba14b8dc"] + }, + { + "classification": "synthetic-test-fixture", + "reason": "PR #2987 commit 4fc3f59e0 only: scripts/selfhost/live/box-object-urls.live.test.ts line 208 held the literal box-object token `samobj1.forged.forged`, an unsigned placeholder that cannot verify (no key material; the live test asserts it is refused). The next commit replaced it with a built string. Exact rule/path/line/bytes of that historical commit only.", + "owner": "security", + "reviewedAt": "2026-11-23T11:30:00.000Z", + "expiresAt": "2026-12-23T11:30:00.000Z", + "digests": ["f0ab4cc7c363ddebbe09343c7edcd324a9452b23845ea42579402888d7795332"] } ] } From a1fef9b6ac4dcb1174bfa5840106f59a7e567fed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 11:40:26 +0000 Subject: [PATCH 14/19] task: GCS box proof evidence; backlog the profile-less publish failure Co-Authored-By: Claude Opus 5.5 --- .../2026-11-23-selfhost-box-object-uploads.md | 25 ++++++++++++++++++ ...without-agent-profile-fails-after-build.md | 26 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 tasks/backlog/2026-11-23-publish-without-agent-profile-fails-after-build.md diff --git a/tasks/active/2026-11-23-selfhost-box-object-uploads.md b/tasks/active/2026-11-23-selfhost-box-object-uploads.md index c7ba7ee794..2953c8eb09 100644 --- a/tasks/active/2026-11-23-selfhost-box-object-uploads.md +++ b/tasks/active/2026-11-23-selfhost-box-object-uploads.md @@ -105,3 +105,28 @@ parted upload, which changes the vm-agent client. Deferred to PR B (idea filed i snapshot all work. - `compose-image-artifacts/init` returns 503 with the missing setting named, never 500. - The hosted Cloudflare presign URLs are byte-identical (existing equivalence test). + +## Disposable GCS box proof (2026-11-23, GCP `sam-vm-control-plane-test`) + +Box `sam-upbox` (e2-standard-4, europe-west1-b), `SAM_DOMAIN=upbox.vmtest.sam2.party`, +`CELLD_BUCKET=gs://sam-upbox-fleet-90he14/celld`, TLS `dns-googleclouddns`, key provider `file`, +built from this branch. **No `R2_S3_ENDPOINT`, no HMAC or static store key.** Nodes through +`gcp-bootstrap` (pool `sam-upbox-90he14`), OpenCode agent with a free model. + +- **Task attachment, browser → box → GCS:** `request-upload` returned + `https://api.upbox…/api/box-objects?token=samobj1…`; the XHR PUT from the app origin got 200; + `gs://…/celld/r2/workspaces-dev-assets/temp-uploads///proof.txt` (46 B). Task + submit validated it; the agent printed the file's contents from its workspace (download). +- **Session snapshot:** before the fix every `PUT …/session-snapshot/artifacts/*` got 400 (Caddy + strips `X-SAM-Content-SHA256`). After 8bedbfb29: `upload-url` 200, `box_objects.uploaded` + `session-snapshots/…/wip.bundle` (978 B) and `home.tar` (27.9 MB), `complete` 200. +- **Build-backed publish:** `compose-image-artifacts/init` 200 (was a 500), `box_objects.uploaded` + `compose-image-artifacts/…/web.docker-save.tar`, `complete` 200, `compose-publish-release` 200 + (release v1). The deployment node downloaded the artifact (`box_objects.downloaded`), applied the + release, and `https://r1-web-8080-01m83zgpc4sf9jqxq879093f20.apps.upbox.vmtest.sam2.party/` answered + **200 `upbox build ok`** with a verified certificate. +- Logs: Caddy recorded `uri: /api/box-objects?`; `samobj1` occurs 0 times in the Caddy + and celld logs. +- Side findings (not this change): OpenCode Zen returned "Workspace usage limit reached" for the + default paid model (a free model worked); a build-backed publish needs the task to run under an + agent profile (`publish: empty agentProfileID` otherwise); node boot on e2-standard-2 took ~12 min. diff --git a/tasks/backlog/2026-11-23-publish-without-agent-profile-fails-after-build.md b/tasks/backlog/2026-11-23-publish-without-agent-profile-fails-after-build.md new file mode 100644 index 0000000000..165deee67d --- /dev/null +++ b/tasks/backlog/2026-11-23-publish-without-agent-profile-fails-after-build.md @@ -0,0 +1,26 @@ +# Agent publish from a task without an agent profile fails after the build + +## Problem + +`build_and_publish` (`apps/api/src/routes/mcp/compose-publish-tools.ts`) accepts a publish from a +task that has no agent profile. The environment policy (`isDeploymentPolicyAllowedForProfile`) +allows it when `allowedDeployProfileIds` is empty, and the tool passes +`agentProfileId: policyResult.taskAgentProfileId || null`. The VM publisher then refuses: +`packages/vm-agent/internal/publish/orchestrator.go:205`, `publish: empty agentProfileID`. + +It refuses only after `compose config` and `docker compose build` have run, so the agent wastes a +build and sees `publish_failed` with `retryable: true`, which invites retries that fail the same way. + +## Context + +Found 2026-11-23 on a disposable self-host box during PR #2987 (box uploads). A task submitted +without `agentProfileId` failed twice this way (jobs `01M841XXYH7V16YTP981WGVRQE`, +`01M841Y6RG3QX5NZJTFKG4TAN1`). The same task with a profile published fine. Not box-specific: the +check is in the vm-agent and the API path is shared. + +## Acceptance Criteria + +- [ ] The API and the vm-agent agree: either the tool refuses a profile-less publish up front with a + clear, non-retryable error, or the publisher accepts an empty profile id when the policy allows it. +- [ ] The decision is made before any build work starts. +- [ ] A test drives `build_and_publish` from a profile-less task through the real policy. From 3bc337f9f78068a747a94f6f5852a52f7691d18b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 12:03:18 +0000 Subject: [PATCH 15/19] test(selfhost): the sealed celld entry also wraps BoxUploadGate; record box cleanup Co-Authored-By: Claude Opus 5.5 --- scripts/selfhost/key-service.test.ts | 1 + tasks/active/2026-11-23-selfhost-box-object-uploads.md | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/scripts/selfhost/key-service.test.ts b/scripts/selfhost/key-service.test.ts index 967719d4fc..690080c487 100644 --- a/scripts/selfhost/key-service.test.ts +++ b/scripts/selfhost/key-service.test.ts @@ -565,6 +565,7 @@ describe('the celld entry and the egress fence', () => { 'export default wrapWorker(selfhost.withSelfHostBuild(worker, api.app));' ); expect(main.match(/wrapDurableObject\((?:api|selfhost)\.(\w+)\)/g)).toEqual([ + 'wrapDurableObject(selfhost.BoxUploadGate)', 'wrapDurableObject(selfhost.HostedGitRepo)', 'wrapDurableObject(api.ProjectData)', 'wrapDurableObject(api.TaskRunner)', diff --git a/tasks/active/2026-11-23-selfhost-box-object-uploads.md b/tasks/active/2026-11-23-selfhost-box-object-uploads.md index 2953c8eb09..d8f82cec82 100644 --- a/tasks/active/2026-11-23-selfhost-box-object-uploads.md +++ b/tasks/active/2026-11-23-selfhost-box-object-uploads.md @@ -130,3 +130,12 @@ built from this branch. **No `R2_S3_ENDPOINT`, no HMAC or static store key.** No - Side findings (not this change): OpenCode Zen returned "Workspace usage limit reached" for the default paid model (a free model worked); a build-backed publish needs the task to run under an agent profile (`publish: empty agentProfileID` otherwise); node boot on e2-standard-2 took ~12 min. + +### Cleanup (2026-11-23 11:47 UTC) + +Deleted and verified absent: SAM nodes (3 workspace, 1 deployment) through the box API, after +which their GCP VMs were gone; VM `sam-upbox`; firewall `sam-upbox-allow-web`; Cloud DNS +`*.upbox` and `*.apps.upbox`; project bindings `compute.instanceAdmin.v1` and `compute.securityAdmin` +(sam-upbox-nodes) and `dns.admin` (sam-upbox); service accounts `sam-upbox` and `sam-upbox-nodes`; +WIF pool `sam-upbox-90he14` (state DELETED); bucket `gs://sam-upbox-fleet-90he14`. The shared box +`sam-box`, its firewall and the shared `sam-allow-*` rules were not touched. From 1e098239c197daa0a0815a6c2b769a451dac4723 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 12:14:48 +0000 Subject: [PATCH 16/19] fix(selfhost): CodeRabbit findings for box uploads - Lease covers every live upload: effective lease is at least 2x the idle limit, renew reports a lost lease, and the route stops such an upload (503) instead of letting it run uncounted. - Create-only per key above celld's conditional-put size: the gate claims the object key, so a concurrent same-key upload gets 412. - Keys under a configured snapshot prefix with an empty segment are accepted; only the suffix SAM appends is checked segment by segment. - Test helper typed from ObjectPutUrlOptions; live test no longer turns a transport failure into a 413 and checks celld still serves. - Live celld probe of the gate's key claim and renew result. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/selfhost/object-urls/gate.ts | 58 ++++-- apps/api/src/selfhost/object-urls/route.ts | 51 +++-- apps/api/src/selfhost/object-urls/tokens.ts | 11 +- .../unit/selfhost/box-object-urls.test.ts | 181 +++++++++++++++--- deploy/selfhost/README.md | 25 +-- .../live/box-object-urls.live.test.ts | 46 ++++- 6 files changed, 290 insertions(+), 82 deletions(-) diff --git a/apps/api/src/selfhost/object-urls/gate.ts b/apps/api/src/selfhost/object-urls/gate.ts index 822bf0dc4d..384fdbf35a 100644 --- a/apps/api/src/selfhost/object-urls/gate.ts +++ b/apps/api/src/selfhost/object-urls/gate.ts @@ -24,7 +24,11 @@ export interface BoxUploadGateEnv { } export type BoxUploadLease = - { granted: true } | { granted: false; active: number; retryAfterSeconds: number }; + | { granted: true } + /** The box (or this uploader) is at its limit. */ + | { granted: false; reason: 'busy'; active: number; retryAfterSeconds: number } + /** Another live upload is writing the same object key. */ + | { granted: false; reason: 'key-in-use' }; /** Shortest and longest Retry-After hint (seconds) a refusal suggests. */ const MIN_RETRY_AFTER_SECONDS = 5; @@ -34,33 +38,39 @@ export class BoxUploadGate extends DurableObject { constructor(ctx: DurableObjectState, env: unknown) { super(ctx, env as never); ctx.storage.sql.exec( - 'CREATE TABLE IF NOT EXISTS upload_leases (id TEXT PRIMARY KEY, uploader TEXT NOT NULL, expires_at INTEGER NOT NULL)' + 'CREATE TABLE IF NOT EXISTS upload_slots (id TEXT PRIMARY KEY, uploader TEXT NOT NULL, object_key TEXT NOT NULL, expires_at INTEGER NOT NULL)' ); } - /** - * Grants a lease to `id` while fewer than `limits.total` unexpired leases exist on the box and - * fewer than `limits.perUploader` belong to `uploader`, so one uploader cannot hold every slot. - */ /** The gate's clock (a method, not an RPC argument, so no caller can move it). */ protected now(): number { return Date.now(); } + /** + * Grants a lease to `id` while fewer than `limits.total` unexpired leases exist on the box, + * fewer than `limits.perUploader` belong to `uploader` (so one uploader cannot hold every slot), + * and no live lease is writing `objectKey`. The key claim makes create-only hold for streams + * celld cannot write conditionally (route.ts): from the existence check through the write, only + * one upload may create a given object. + */ acquire( id: string, uploader: string, + objectKey: string, limits: { total: number; perUploader: number; leaseMs: number } ): BoxUploadLease { const now = this.now(); const sql = this.ctx.storage.sql; - sql.exec('DELETE FROM upload_leases WHERE expires_at <= ?', now); + sql.exec('DELETE FROM upload_slots WHERE expires_at <= ?', now); const row = sql - .exec<{ active: number; mine: number; next: number | null }>( - 'SELECT COUNT(*) AS active, COALESCE(SUM(uploader = ?), 0) AS mine, MIN(expires_at) AS next FROM upload_leases', - uploader + .exec<{ active: number; mine: number; sameKey: number; next: number | null }>( + 'SELECT COUNT(*) AS active, COALESCE(SUM(uploader = ?), 0) AS mine, COALESCE(SUM(object_key = ?), 0) AS sameKey, MIN(expires_at) AS next FROM upload_slots', + uploader, + objectKey ) .one(); + if (row.sameKey > 0) return { granted: false, reason: 'key-in-use' }; if (row.active >= limits.total || row.mine >= limits.perUploader) { // A hint, not a promise: most leases end when their upload finishes, long before expiry. const untilExpiry = Math.ceil(((row.next ?? now) - now) / 1000); @@ -68,28 +78,35 @@ export class BoxUploadGate extends DurableObject { MAX_RETRY_AFTER_SECONDS, Math.max(MIN_RETRY_AFTER_SECONDS, untilExpiry) ); - return { granted: false, active: row.active, retryAfterSeconds }; + return { granted: false, reason: 'busy', active: row.active, retryAfterSeconds }; } sql.exec( - 'INSERT OR REPLACE INTO upload_leases (id, uploader, expires_at) VALUES (?, ?, ?)', + 'INSERT OR REPLACE INTO upload_slots (id, uploader, object_key, expires_at) VALUES (?, ?, ?, ?)', id, uploader, + objectKey, now + limits.leaseMs ); return { granted: true }; } - /** Extends a held lease while its upload is still receiving bytes (route.ts). */ - renew(id: string, leaseMs: number): void { - this.ctx.storage.sql.exec( - 'UPDATE upload_leases SET expires_at = ? WHERE id = ?', - this.now() + leaseMs, - id + /** + * Extends a held, unexpired lease while its upload is still receiving bytes (route.ts). False when + * the lease is gone: the route then stops the upload rather than let it run uncounted. + */ + renew(id: string, leaseMs: number): boolean { + const now = this.now(); + const cursor = this.ctx.storage.sql.exec( + 'UPDATE upload_slots SET expires_at = ? WHERE id = ? AND expires_at > ?', + now + leaseMs, + id, + now ); + return cursor.rowsWritten > 0; } release(id: string): void { - this.ctx.storage.sql.exec('DELETE FROM upload_leases WHERE id = ?', id); + this.ctx.storage.sql.exec('DELETE FROM upload_slots WHERE id = ?', id); } } @@ -100,9 +117,10 @@ interface BoxUploadGateStub { acquire( id: string, uploader: string, + objectKey: string, limits: { total: number; perUploader: number; leaseMs: number } ): Promise; - renew(id: string, leaseMs: number): Promise; + renew(id: string, leaseMs: number): Promise; release(id: string): Promise; } diff --git a/apps/api/src/selfhost/object-urls/route.ts b/apps/api/src/selfhost/object-urls/route.ts index 99e9e51756..ee484df9ff 100644 --- a/apps/api/src/selfhost/object-urls/route.ts +++ b/apps/api/src/selfhost/object-urls/route.ts @@ -107,8 +107,10 @@ function uploader(claims: BoxObjectTokenClaims): string { interface Watchdog { stream: TransformStream; - /** True once the watchdog dropped the upload for going idle. */ - idled: () => boolean; + /** Why the watchdog stopped the upload, if it did. */ + stopped: () => 'idle' | 'lease-lost' | null; + /** Stops the upload because it no longer holds its slot. */ + loseLease: () => void; dispose: () => void; } @@ -118,16 +120,19 @@ interface Watchdog { */ function uploadWatchdog(idleMs: number, progressEveryMs: number, onProgress: () => void): Watchdog { let timer: ReturnType | undefined; - let idled = false; + let stopped: 'idle' | 'lease-lost' | null = null; let lastProgress = Date.now(); let fail: (error: Error) => void = () => undefined; const dispose = () => clearTimeout(timer); + const stop = (reason: 'idle' | 'lease-lost') => { + if (stopped) return; + stopped = reason; + dispose(); + fail(new Error(`box upload stopped: ${reason}`)); + }; const arm = () => { dispose(); - timer = setTimeout(() => { - idled = true; - fail(new Error('box upload received no bytes within its idle limit')); - }, idleMs); + timer = setTimeout(() => stop('idle'), idleMs); }; const stream = new TransformStream({ start(controller) { @@ -145,7 +150,7 @@ function uploadWatchdog(idleMs: number, progressEveryMs: number, onProgress: () flush: dispose, cancel: dispose, }); - return { stream, idled: () => idled, dispose }; + return { stream, stopped: () => stopped, loseLease: () => stop('lease-lost'), dispose }; } /** @@ -193,9 +198,18 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke if (!gate) { return plain(503, 'Box uploads are unavailable (no upload gate binding)', {}, 'UNAVAILABLE'); } - const limits = await uploadLimits(env); + const configured = await uploadLimits(env); + // A slot must outlive the longest pause the idle limit tolerates plus one renewal interval, or a + // paused-but-live upload would lose it and run uncounted. Renewals come every leaseMs / 3, so a + // lease of at least twice the idle limit always covers the gap (the settings allow any pair). + const limits = { ...configured, leaseMs: Math.max(configured.leaseMs, 2 * configured.idleMs) }; const leaseId = crypto.randomUUID(); - const lease = await gate.acquire(leaseId, uploader(claims), limits); + const lease = await gate.acquire(leaseId, uploader(claims), claims.key, limits); + if (!lease.granted && lease.reason === 'key-in-use') { + // Another upload is creating this object right now: create-only, so this one cannot. + log.warn('box_objects.upload_conflict', { ...logFields(claims), length, action: 'in_flight' }); + return plain(412, 'Another upload is writing this object'); + } if (!lease.granted) { log.warn('box_objects.upload_refused_busy', { ...logFields(claims), @@ -208,8 +222,15 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke }); } const watchdog = uploadWatchdog(limits.idleMs, Math.max(1000, limits.leaseMs / 3), () => { - // Keep the slot while bytes arrive; a failed renewal only shortens it to the lease. - gate.renew(leaseId, limits.leaseMs).catch(() => undefined); + // Keep the slot while bytes arrive. A renewal that finds no lease means the slot was given up: + // stop the upload rather than let it run uncounted. A failed RPC only shortens the slot to the + // lease; the next renewal tries again. + gate + .renew(leaseId, limits.leaseMs) + .then((held) => { + if (!held) watchdog.loseLease(); + }) + .catch(() => undefined); }); try { const atomic = length <= CELLD_CONDITIONAL_PUT_MAX_BYTES; @@ -229,9 +250,13 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke } catch (error) { const message = error instanceof Error ? error.message : String(error); log.warn('box_objects.upload_failed', { ...logFields(claims), length, error: message }); - if (watchdog.idled()) { + if (watchdog.stopped() === 'idle') { return plain(408, 'The upload stopped sending data', {}, 'UPLOAD_TIMEOUT'); } + if (watchdog.stopped() === 'lease-lost') { + log.warn('box_objects.upload_lease_lost', { ...logFields(claims), length }); + return plain(503, 'The upload lost its slot; retry it', { 'Retry-After': '5' }); + } if (claims.sha && /sha-?256/i.test(message)) { return plain(400, 'Upload body does not match the declared sha256'); } diff --git a/apps/api/src/selfhost/object-urls/tokens.ts b/apps/api/src/selfhost/object-urls/tokens.ts index a1560232c0..8bce4b2b98 100644 --- a/apps/api/src/selfhost/object-urls/tokens.ts +++ b/apps/api/src/selfhost/object-urls/tokens.ts @@ -99,10 +99,17 @@ export function isSafeObjectKey( prefixes: readonly string[] = BOX_OBJECT_KEY_PREFIXES ): boolean { if (!key || key.length > MAX_KEY_LENGTH) return false; - if (!prefixes.some((prefix) => key.startsWith(prefix))) return false; // eslint-disable-next-line no-control-regex -- control characters are exactly what is refused if (key.startsWith('/') || key.includes('\\') || /[\u0000-\u001f\u007f]/.test(key)) return false; - return key.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..'); + // The matched prefix is configuration (an operator's SESSION_SNAPSHOT_R2_PREFIX may legitimately + // hold an empty segment); only the part SAM appended is checked segment by segment. + const prefix = prefixes.find((candidate) => key.startsWith(candidate)); + if (prefix === undefined) return false; + const suffix = key.slice(prefix.length); + return ( + suffix !== '' && + suffix.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..') + ); } function isStringRecord(value: unknown): value is Record { diff --git a/apps/api/tests/unit/selfhost/box-object-urls.test.ts b/apps/api/tests/unit/selfhost/box-object-urls.test.ts index dabbd13dce..ed3bb7a7d3 100644 --- a/apps/api/tests/unit/selfhost/box-object-urls.test.ts +++ b/apps/api/tests/unit/selfhost/box-object-urls.test.ts @@ -12,6 +12,7 @@ import { createBuildContextUpload, createComposeImageArtifactDownloads, createComposeImageArtifactUploads, + type ObjectPutUrlOptions, } from '@simple-agent-manager/app-deployment'; import Database from 'better-sqlite3'; import { Hono } from 'hono'; @@ -155,10 +156,12 @@ function sqliteStorage() { return { exec(query: string, ...params: unknown[]) { const statement = db.prepare(query); - const rows = statement.reader - ? (statement.all(...params) as unknown[]) - : (statement.run(...params), []); - return { one: () => rows[0], toArray: () => rows }; + if (statement.reader) { + const rows = statement.all(...params) as unknown[]; + return { one: () => rows[0], toArray: () => rows, rowsWritten: 0 }; + } + const { changes } = statement.run(...params); + return { one: () => undefined, toArray: () => [], rowsWritten: changes }; }, }; } @@ -170,8 +173,9 @@ function gateNamespace(gate: BoxUploadGate) { acquire: async ( id: string, uploader: string, + objectKey: string, limits: { total: number; perUploader: number; leaseMs: number } - ) => gate.acquire(id, uploader, limits), + ) => gate.acquire(id, uploader, objectKey, limits), renew: async (id: string, leaseMs: number) => gate.renew(id, leaseMs), release: async (id: string) => gate.release(id), }), @@ -325,11 +329,7 @@ describe('box object token scope', () => { }); it('refuses keys outside the upload prefixes at mint, and at verify even when correctly signed', async () => { - for (const key of [ - 'agents/vm-agent-linux-amd64', - 'library/p1/f1', - 'temp-uploadsX/a', - ]) { + for (const key of ['agents/vm-agent-linux-amd64', 'library/p1/f1', 'temp-uploadsX/a']) { expect(isSafeObjectKey(key)).toBe(false); await expect( mintBoxObjectToken(env, { op: 'put', key, len: 1, expiresIn: 60 }) @@ -549,6 +549,20 @@ describe('callers on a keyless box', () => { ).resolves.toMatch(/^samobj1\./); }); + it('accepts keys under a configured prefix that has an empty segment; still checks the suffix', async () => { + const env = { ENCRYPTION_KEY: KEY, SESSION_SNAPSHOT_R2_PREFIX: 'snapshots//daily' }; + const key = buildSessionSnapshotR2Key(env as Env, 'chat-1', 'gen-1', 'home'); + expect(key.startsWith('snapshots//daily/')).toBe(true); + await expect( + mintBoxObjectToken(env, { op: 'put', key, len: 1, expiresIn: 60 }) + ).resolves.toMatch(/^samobj1\./); + for (const bad of ['snapshots//daily/../x', 'snapshots//daily/a//b', 'snapshots//daily/']) { + await expect( + mintBoxObjectToken(env, { op: 'put', key: bad, len: 1, expiresIn: 60 }) + ).rejects.toThrow(); + } + }); + it('a single upload over 1 GiB is refused when the URL is requested', async () => { const signer = createBoxObjectUrlSigner(boxEnv().env)!; await expect( @@ -578,11 +592,7 @@ describe('callers on a keyless box', () => { // ── the route ────────────────────────────────────────────────────────────────────────────────── describe('PUT/GET /api/box-objects', () => { - async function upload( - env: Env, - key: string, - extra: Partial[1]> = {} - ) { + async function upload(env: Env, key: string, extra: Partial = {}) { const signer = createBoxObjectUrlSigner(env)!; return signer.putUrl(key, { expiresIn: 60, contentType: 'text/plain', ...extra }); } @@ -720,7 +730,8 @@ describe('PUT/GET /api/box-objects', () => { const { env, R2, gate } = boxEnv(); const app = routeApp(); // Settings storage is unavailable in this env, so the default limit (4) applies. - for (let i = 0; i < 4; i++) gate.acquire(`held-${i}`, `u:other-${i}`, LIMITS); + for (let i = 0; i < 4; i++) + gate.acquire(`held-${i}`, `u:other-${i}`, `temp-uploads/held/${`held-${i}`}`, LIMITS); const url = await upload(env, 'temp-uploads/t/busy', { contentLength: 4 }); const refused = await putUrl(app, env, url, bytes('busy')); expect(refused.status).toBe(503); @@ -729,32 +740,135 @@ describe('PUT/GET /api/box-objects', () => { gate.release('held-0'); expect((await putUrl(app, env, url, bytes('busy'))).status).toBe(200); // The upload released its own lease: three held, one free. - expect(gate.acquire('probe', 'u:probe', LIMITS)).toEqual({ granted: true }); + expect(gate.acquire('probe', 'u:probe', `temp-uploads/held/${'probe'}`, LIMITS)).toEqual({ + granted: true, + }); }); it('an expired lease frees its slot (a handler that died without releasing)', () => { const { gate } = boxEnv(); const one = { total: 1, perUploader: 1, leaseMs: 1_000 }; gate.clock = 0; - gate.acquire('dead', 'u:a', one); + gate.acquire('dead', 'u:a', `temp-uploads/held/${'dead'}`, one); gate.clock = 500; - expect(gate.acquire('next', 'u:b', one).granted).toBe(false); + expect(gate.acquire('next', 'u:b', `temp-uploads/held/${'next'}`, one).granted).toBe(false); gate.clock = 1_000; - expect(gate.acquire('next', 'u:b', one).granted).toBe(true); + expect(gate.acquire('next', 'u:b', `temp-uploads/held/${'next'}`, one).granted).toBe(true); }); it('renewing a lease keeps a slow but moving upload in its slot', () => { const { gate } = boxEnv(); const one = { total: 1, perUploader: 1, leaseMs: 1_000 }; gate.clock = 0; - gate.acquire('slow', 'u:a', one); + gate.acquire('slow', 'u:a', `temp-uploads/held/${'slow'}`, one); gate.clock = 900; gate.renew('slow', 1_000); gate.clock = 1_500; - expect(gate.acquire('next', 'u:b', one).granted).toBe(false); + expect(gate.acquire('next', 'u:b', `temp-uploads/held/${'next'}`, one).granted).toBe(false); // Control: without further renewal it expires. gate.clock = 1_900; - expect(gate.acquire('next', 'u:b', one).granted).toBe(true); + expect(gate.acquire('next', 'u:b', `temp-uploads/held/${'next'}`, one).granted).toBe(true); + }); + + it('only one upload may create a key at a time: a concurrent same-key PUT is 412, other keys proceed', async () => { + const { env, R2, gate } = boxEnv(); + const app = routeApp(); + // An upload of K is in flight (holds K's claim), as when a large stream is still writing. + gate.acquire('writer', 'u:writer', 'temp-uploads/t/K', LIMITS); + const same = await upload(env, 'temp-uploads/t/K', { contentLength: 2 }); + expect((await putUrl(app, env, same, bytes('k2'))).status).toBe(412); + expect(R2.objects.has('temp-uploads/t/K')).toBe(false); + // Control: another key is not serialized behind K. + const other = await upload(env, 'temp-uploads/t/other', { contentLength: 2 }); + expect((await putUrl(app, env, other, bytes('ok'))).status).toBe(200); + // Once the writer is done, the key can be created. + gate.release('writer'); + expect((await putUrl(app, env, same, bytes('k2'))).status).toBe(200); + }); + + it('renew reports a lost lease; a live one is extended', () => { + const { gate } = boxEnv(); + const one = { total: 2, perUploader: 2, leaseMs: 1_000 }; + gate.clock = 0; + gate.acquire('live', 'u:a', 'temp-uploads/t/a', one); + gate.acquire('gone', 'u:a', 'temp-uploads/t/b', one); + gate.release('gone'); + gate.clock = 500; + expect(gate.renew('live', 1_000)).toBe(true); + expect(gate.renew('gone', 1_000)).toBe(false); + // An expired lease cannot be revived by a late renewal. + gate.clock = 5_000; + expect(gate.renew('live', 1_000)).toBe(false); + }); + + it('stops an upload whose renewal finds no lease (503), instead of letting it run uncounted', async () => { + vi.mocked(resolveAdminSettingDetailsMany).mockResolvedValueOnce([ + { value: 4 }, + { value: 1 }, // lease seconds (below the idle limit, so raised to 2 x idle = 4 s) + { value: 2 }, + { value: 2 }, // idle seconds: renewals every ~1.3 s while bytes arrive + ] as never); + const { env, R2 } = boxEnv(); + const ns = env.BOX_UPLOAD_GATE as unknown as { get: () => Record }; + const stub = ns.get(); + // The gate gave the slot away (e.g. a celld restart lost the row). + (env as unknown as { BOX_UPLOAD_GATE: unknown }).BOX_UPLOAD_GATE = { + idFromName: (name: string) => name, + get: () => ({ ...stub, renew: async () => false }), + }; + const app = routeApp(); + const url = new URL(await upload(env, 'temp-uploads/t/slow', { contentLength: 8 })); + let sent = 0; + const slow = new ReadableStream({ + async pull(controller) { + await new Promise((resolve) => setTimeout(resolve, 700)); + if (sent >= 8) return controller.close(); + sent += 1; + controller.enqueue(bytes('x')); + }, + }); + const response = await app.request( + `${url.pathname}${url.search}`, + { + method: 'PUT', + body: slow, + headers: { 'content-length': '8' }, + duplex: 'half', + } as RequestInit, + env + ); + expect(response.status).toBe(503); + expect(sent).toBeLessThan(8); + expect(R2.objects.has('temp-uploads/t/slow')).toBe(false); + }, 15_000); + + it('a lease shorter than the idle limit is raised so a paused upload keeps its slot', async () => { + vi.mocked(resolveAdminSettingDetailsMany).mockResolvedValueOnce([ + { value: 4 }, + { value: 60 }, // lease 60 s + { value: 2 }, + { value: 120 }, // idle 120 s + ] as never); + const { env } = boxEnv(); + const ns = env.BOX_UPLOAD_GATE as unknown as { + get: () => Record unknown>; + }; + const stub = ns.get(); + const seen: number[] = []; + (env as unknown as { BOX_UPLOAD_GATE: unknown }).BOX_UPLOAD_GATE = { + idFromName: (name: string) => name, + get: () => ({ + ...stub, + acquire: async (...args: unknown[]) => { + seen.push((args[3] as { leaseMs: number }).leaseMs); + return stub.acquire!(...args); + }, + }), + }; + const app = routeApp(); + const url = await upload(env, 'temp-uploads/t/clamp', { contentLength: 1 }); + expect((await putUrl(app, env, url, bytes('c'))).status).toBe(200); + expect(seen).toEqual([240_000]); }); it('one uploader cannot take every slot: a second uploader is still admitted', async () => { @@ -762,8 +876,8 @@ describe('PUT/GET /api/box-objects', () => { const app = routeApp(); const signer = createBoxObjectUrlSigner(env)!; // The attacker already holds its share (2 of 4). - gate.acquire('held-1', 'u:attacker', LIMITS); - gate.acquire('held-2', 'u:attacker', LIMITS); + gate.acquire('held-1', 'u:attacker', `temp-uploads/held/${'held-1'}`, LIMITS); + gate.acquire('held-2', 'u:attacker', `temp-uploads/held/${'held-2'}`, LIMITS); const attacker = await signer.putUrl('temp-uploads/attacker/up/a', { expiresIn: 60, contentLength: 1, @@ -806,11 +920,15 @@ describe('PUT/GET /api/box-objects', () => { expect(response.status).toBe(408); expect(R2.objects.has('temp-uploads/t/stall')).toBe(false); // Its slot was released. - expect(gate.acquire('probe', 'u:probe', { total: 1, perUploader: 1, leaseMs: 60_000 })).toEqual( - { - granted: true, - } - ); + expect( + gate.acquire('probe', 'u:probe', `temp-uploads/held/${'probe'}`, { + total: 1, + perUploader: 1, + leaseMs: 60_000, + }) + ).toEqual({ + granted: true, + }); }, 10_000); it('a setting that resolves to nothing keeps its default bound (never disables the gate)', async () => { @@ -822,7 +940,8 @@ describe('PUT/GET /api/box-objects', () => { ] as never); const { env, gate } = boxEnv(); const app = routeApp(); - for (let i = 0; i < 4; i++) gate.acquire(`held-${i}`, `u:other-${i}`, LIMITS); + for (let i = 0; i < 4; i++) + gate.acquire(`held-${i}`, `u:other-${i}`, `temp-uploads/held/${`held-${i}`}`, LIMITS); const url = await upload(env, 'temp-uploads/t/nan', { contentLength: 1 }); expect((await putUrl(app, env, url, bytes('n'))).status).toBe(503); }); diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index eecc9c1ffc..a4d2555fbe 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -282,17 +282,17 @@ the window is rolled back as before. If a run stops anyway, `rotate --status` sh bundle it sealed, including the final reseal, and `rotate --resume` deploys that recorded bundle again. -| Key | How | Users notice | Downtime | -| --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | -| `agent-signing-key` | new bundle, deploy | nothing (each Worker version verifies the agent with its own bundle's key) | none | -| `preview-signing-key` | new value, deploy | a file preview opened in the last 5 min stops loading; reopen it | none | -| `deploy-signing-keys` | new pair, deploy | deployment nodes take the new public key on their next heartbeat; a release fetched just before the switch can be refused once | none | -| `vapid-keys` | new pair, deploy | push notifications stop on every browser subscribed before, until the user turns notifications off and on in Settings | none | -| `gateway-secret` | Worker accepts old and new; `gateway.env` gets the new value and Caddy, frps and sam-mx are recreated; Worker accepts only the new one | node tunnels reconnect (frpc retries by itself); open terminals and agent WebSockets reconnect | a few seconds of HTTPS while Caddy restarts | -| `dns-update-key` (boxes whose bundle has the TSIG key; `--init` adds it) | new TSIG key. With the `dns` profile on: `dns.env` rewritten, Caddy and sam-dns recreated, and a signed probe proves the new key accepted and the old one refused. With it off: the key is only stored, since nothing reads it | a certificate renewal running at that moment is retried by Caddy | a few seconds of HTTPS while Caddy restarts; DNS answers pause while sam-dns starts | -| `encryption-key` (and `credential-encryption-key`, `library-encryption-key` if the bundle has them) | new key current, old key a read fallback; every stored value re-encrypted online in bounded pages through a loopback-only control endpoint; verified; then `rotate --resume` after the values it cannot reach have expired (at least 5 h 16 min: interaction details, bootstrap tokens); verified again; old key retired; chains `better-auth-secret` when `BETTER_AUTH_SECRET` was unset | none while it runs, except a sign-out of everyone when it chains `better-auth-secret`. A git command started before the switch may need repeating; an exhaustive project-archive search continued across the switch starts over (its continuation cursor is signed with `ENCRYPTION_KEY`); a node being provisioned at that moment fails and is retried; a webhook delivery retried across the switch with the same `Idempotency-Key` is not recognised as a duplicate and can start a second task (its fingerprints stay on `ENCRYPTION_KEY` on purpose: they hash IP addresses and request bodies, which the old key could confirm offline) | none | -| `better-auth-secret` | BetterAuth versioned secret; stored GitHub sign-in tokens re-encrypted; old secret retired | every user is signed out once and signs in again | none | -| `jwt-keys` | new pair with its own `kid`, published alone in both JWKS documents; the Worker still accepts _callback_ tokens signed with the old key until `JWT_PUBLIC_KEY_PREVIOUS_UNTIL` (90% of the deployed `CALLBACK_TOKEN_EXPIRY_MS` plus 1 h, the latest point a VM agent renews: 23 h by default; `--jwt-overlap-hours` overrides it, `0` is a hard cut). Nodes get a new-key callback token on their next heartbeat; workspace tokens move when the VM agent renews them (by default at half their life). `rotate --resume` after the overlap removes the old key | nothing, if finished after the overlap. Terminal, preview and local-forward tokens are re-minted with the new key by the app. During the overlap whoever holds the old key can still forge a callback token; a hard cut (`0`) removes that and cuts every running node off (replace them) | none | +| Key | How | Users notice | Downtime | +| --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| `agent-signing-key` | new bundle, deploy | nothing (each Worker version verifies the agent with its own bundle's key) | none | +| `preview-signing-key` | new value, deploy | a file preview opened in the last 5 min stops loading; reopen it | none | +| `deploy-signing-keys` | new pair, deploy | deployment nodes take the new public key on their next heartbeat; a release fetched just before the switch can be refused once | none | +| `vapid-keys` | new pair, deploy | push notifications stop on every browser subscribed before, until the user turns notifications off and on in Settings | none | +| `gateway-secret` | Worker accepts old and new; `gateway.env` gets the new value and Caddy, frps and sam-mx are recreated; Worker accepts only the new one | node tunnels reconnect (frpc retries by itself); open terminals and agent WebSockets reconnect | a few seconds of HTTPS while Caddy restarts | +| `dns-update-key` (boxes whose bundle has the TSIG key; `--init` adds it) | new TSIG key. With the `dns` profile on: `dns.env` rewritten, Caddy and sam-dns recreated, and a signed probe proves the new key accepted and the old one refused. With it off: the key is only stored, since nothing reads it | a certificate renewal running at that moment is retried by Caddy | a few seconds of HTTPS while Caddy restarts; DNS answers pause while sam-dns starts | +| `encryption-key` (and `credential-encryption-key`, `library-encryption-key` if the bundle has them) | new key current, old key a read fallback; every stored value re-encrypted online in bounded pages through a loopback-only control endpoint; verified; then `rotate --resume` after the values it cannot reach have expired (at least 5 h 16 min: interaction details, bootstrap tokens); verified again; old key retired; chains `better-auth-secret` when `BETTER_AUTH_SECRET` was unset | none while it runs, except a sign-out of everyone when it chains `better-auth-secret`. A git command started before the switch may need repeating; an exhaustive project-archive search continued across the switch starts over (its continuation cursor is signed with `ENCRYPTION_KEY`); a node being provisioned at that moment fails and is retried; a webhook delivery retried across the switch with the same `Idempotency-Key` is not recognised as a duplicate and can start a second task (its fingerprints stay on `ENCRYPTION_KEY` on purpose: they hash IP addresses and request bodies, which the old key could confirm offline) | none | +| `better-auth-secret` | BetterAuth versioned secret; stored GitHub sign-in tokens re-encrypted; old secret retired | every user is signed out once and signs in again | none | +| `jwt-keys` | new pair with its own `kid`, published alone in both JWKS documents; the Worker still accepts _callback_ tokens signed with the old key until `JWT_PUBLIC_KEY_PREVIOUS_UNTIL` (90% of the deployed `CALLBACK_TOKEN_EXPIRY_MS` plus 1 h, the latest point a VM agent renews: 23 h by default; `--jwt-overlap-hours` overrides it, `0` is a hard cut). Nodes get a new-key callback token on their next heartbeat; workspace tokens move when the VM agent renews them (by default at half their life). `rotate --resume` after the overlap removes the old key | nothing, if finished after the overlap. Terminal, preview and local-forward tokens are re-minted with the new key by the app. During the overlap whoever holds the old key can still forge a callback token; a hard cut (`0`) removes that and cuts every running node off (replace them) | none | `encryption-key` details. Rows are re-encrypted with compare-and-set on the exact value read, so a value saved meanwhile is never overwritten. Copies of a credential in `cc_credentials` are rewritten @@ -1025,7 +1025,8 @@ that the box's Caddy strips from every client request (`X-SAM-*`), so it cannot of which one uploader may hold `boxObjects.maxUploadsPerUploader`, default 2). An upload that receives no bytes for `boxObjects.uploadIdleSeconds` (default 60) is dropped with 408, and a slot whose handler died frees within `boxObjects.uploadLeaseSeconds` (default 300; renewed while bytes - arrive). Each in-flight upload costs celld about 85 MB of + arrive, and never shorter than twice the idle limit). One object key is written by one upload at a + time: a second upload of the same key while the first runs gets 412. Each in-flight upload costs celld about 85 MB of memory (measured on celld 0.6.3: peak RSS 220 MB for one 1 GB upload, 427 MB for four, 896 MB for eight; throughput stops growing after two at about 180 MB/s). Further uploads get 503 with `Retry-After`. diff --git a/scripts/selfhost/live/box-object-urls.live.test.ts b/scripts/selfhost/live/box-object-urls.live.test.ts index 0c9391b86e..40cc9ddf06 100644 --- a/scripts/selfhost/live/box-object-urls.live.test.ts +++ b/scripts/selfhost/live/box-object-urls.live.test.ts @@ -41,6 +41,17 @@ app.post('/mint', async (c) => { : await signer.putUrl(body.key, { expiresIn: 300, ...body.options }); return c.json({ url }); }); +// The real gate over celld's Durable Object SQL: renew must see its own row (cursor.rowsWritten). +app.post('/gate-probe', async (c) => { + const gate = c.env.BOX_UPLOAD_GATE.get(c.env.BOX_UPLOAD_GATE.idFromName('box')); + const limits = { total: 4, perUploader: 2, leaseMs: 60000 }; + const acquired = await gate.acquire('probe-lease', 'u:probe', 'temp-uploads/probe/k', limits); + const sameKey = await gate.acquire('probe-other', 'u:other', 'temp-uploads/probe/k', limits); + const held = await gate.renew('probe-lease', 60000); + await gate.release('probe-lease'); + const afterRelease = await gate.renew('probe-lease', 60000); + return c.json({ acquired, sameKey, held, afterRelease }); +}); mountBoxObjectRoute(app); export default app; `; @@ -87,6 +98,12 @@ function put( const putBytes = (url: string, body: Buffer) => put(url, body.length, (req) => req.end(body)); +/** celld still serves after a refusal (a crash or reset would otherwise pass as a refusal). */ +async function expectCelldResponsive(): Promise { + const response = await fetch(`http://127.0.0.1:${port}/`); + expect(response.status).toBe(200); +} + describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { beforeAll(async () => { store = await startObjectStore(KEY, SECRET); @@ -172,6 +189,16 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { expect(got.equals(body)).toBe(true); }, 60_000); + it('the gate on celld: same-key claims refuse, renew reports a held and a released lease', async () => { + const response = await fetch(`http://127.0.0.1:${port}/gate-probe`, { method: 'POST' }); + expect(await response.json()).toEqual({ + acquired: { granted: true }, + sameKey: { granted: false, reason: 'key-in-use' }, + held: true, + afterRelease: false, + }); + }); + it('a body shorter than declared leaves no object', async () => { const url = await mint('put', 'temp-uploads/live/short.bin', { maxBytes: 1024 }); // Declares 100 bytes, sends 10, then closes: FixedLengthStream fails the put. @@ -186,10 +213,16 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { const small = await mint('put', 'temp-uploads/live/big.bin', { maxBytes: 10 }); expect((await putBytes(small, Buffer.alloc(11))).status).toBe(413); const huge = await mint('put', 'temp-uploads/live/huge.bin', { maxBytes: 1024 * 1024 * 1024 }); - const refused = await put(huge, 1024 * 1024 * 1024 + 1, (req) => - req.write(Buffer.alloc(1)) - ).catch(() => ({ status: 413, headers: {} })); + // celld answers from the declared length alone, while the client has sent one byte; any other + // transport outcome fails the test rather than counting as a refusal. + let open: ReturnType | undefined; + const refused = await put(huge, 1024 * 1024 * 1024 + 1, (req) => { + open = req; + req.write(Buffer.alloc(1)); + }); + open?.destroy(); expect(refused.status).toBe(413); + await expectCelldResponsive(); }); it('a bad token is refused before the body is read: a large unauthenticated body is not buffered', async () => { @@ -215,7 +248,11 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { res.resume(); done(res.statusCode ?? 0); }); - req.on('error', () => done(-1)); + // Only the early-close outcomes count; anything else fails the test. + req.on('error', (error: NodeJS.ErrnoException) => { + if (error.code === 'ECONNRESET' || error.code === 'EPIPE') done(-1); + else throw error; + }); const write = () => { while (sent < length) { sent += chunk.length; @@ -230,6 +267,7 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { // Refused without reading the body: the connection ended long before 512 MiB was sent, and // celld held none of it. expect(sent).toBeLessThan(length / 4); + await expectCelldResponsive(); expect(Date.now() - started).toBeLessThan(10_000); expect(peak - before).toBeLessThan(100); }, 60_000); From 578bb63f89f68ade264700daf8b39993bff3cd47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 12:32:52 +0000 Subject: [PATCH 17/19] fix(selfhost): Codex findings: snapshot uploads carry their workspace; empty artifacts allowed - Session snapshot box URLs name their workspace (and user/project), so the per-uploader slot limit no longer groups every snapshot under one bucket. The box signer now refuses an upload URL with no owner. - A zero-length exact upload (empty snapshot artifact) mints and stores. Co-Authored-By: Claude Opus 5.5 --- .../routes/workspaces/session-snapshots.ts | 5 +++ apps/api/src/selfhost/object-urls/signer.ts | 3 ++ apps/api/src/selfhost/object-urls/tokens.ts | 9 ++++- .../session-snapshot-direct-upload.ts | 11 +++++ .../workspaces-session-snapshots.test.ts | 2 + .../unit/selfhost/box-object-urls.test.ts | 40 ++++++++++++++++--- .../live/box-object-urls.live.test.ts | 2 +- 7 files changed, 64 insertions(+), 8 deletions(-) diff --git a/apps/api/src/routes/workspaces/session-snapshots.ts b/apps/api/src/routes/workspaces/session-snapshots.ts index 302c9152ab..15f340dd31 100644 --- a/apps/api/src/routes/workspaces/session-snapshots.ts +++ b/apps/api/src/routes/workspaces/session-snapshots.ts @@ -343,6 +343,11 @@ sessionSnapshotRoutes.post('/:id/session-snapshot/artifacts/:artifact/upload-url sha256, contentType: artifact === 'home' ? 'application/x-tar' : 'application/octet-stream', checksumHeader: body.checksumHeader === true, + owner: { + workspaceId: c.req.param('id'), + userId: workspace.userId, + projectId: workspace.projectId, + }, }); const recorded = await recordSessionSnapshotArtifactAuthorization(db, { chatSessionId, diff --git a/apps/api/src/selfhost/object-urls/signer.ts b/apps/api/src/selfhost/object-urls/signer.ts index b613119c5c..a7a7930cad 100644 --- a/apps/api/src/selfhost/object-urls/signer.ts +++ b/apps/api/src/selfhost/object-urls/signer.ts @@ -42,6 +42,9 @@ export function createBoxObjectUrlSigner(env: Env): ObjectUrlSigner | null { kind: 'box', maxPutBytes: max, putUrl: async (r2Key, options) => { + // The per-uploader slot limit keys on the owner (route.ts): without one, every such upload + // would share a single bucket and starve the others. Every caller passes one. + if (!owner(options)) throw new Error(`Box upload URL for ${r2Key} has no owner`); if (options.contentLength !== undefined && options.contentLength > max) { throw errors.badRequest( `Uploads through this self-hosted box are limited to ${max} bytes; this one is ${options.contentLength}` diff --git a/apps/api/src/selfhost/object-urls/tokens.ts b/apps/api/src/selfhost/object-urls/tokens.ts index 8bce4b2b98..8d5b1a8c6b 100644 --- a/apps/api/src/selfhost/object-urls/tokens.ts +++ b/apps/api/src/selfhost/object-urls/tokens.ts @@ -36,7 +36,7 @@ export interface BoxObjectTokenClaims { key: string; /** Expiry, unix seconds. */ exp: number; - /** PUT: the exact body length the uploader declared, when it declared one. */ + /** PUT: the exact body length the uploader declared, when it declared one (may be 0). */ len?: number; /** PUT: largest body accepted. */ max?: number; @@ -126,6 +126,10 @@ function isStringRecord(value: unknown): value is Record { ); } +function nonNegativeInteger(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0; +} + function positiveInteger(value: unknown): value is number { return typeof value === 'number' && Number.isSafeInteger(value) && value > 0; } @@ -142,7 +146,8 @@ function parseClaims( if (raw.v !== 1 || (raw.op !== 'put' && raw.op !== 'get')) return null; if (typeof raw.key !== 'string' || !isSafeObjectKey(raw.key, prefixes)) return null; if (!positiveInteger(raw.exp)) return null; - if (raw.len !== undefined && !positiveInteger(raw.len)) return null; + // An exact length may be zero (an empty snapshot artifact); a maximum and an expiry may not. + if (raw.len !== undefined && !nonNegativeInteger(raw.len)) return null; if (raw.max !== undefined && !positiveInteger(raw.max)) return null; if (raw.ct !== undefined && (typeof raw.ct !== 'string' || raw.ct.length > 255)) return null; if (raw.sha !== undefined && (typeof raw.sha !== 'string' || !SHA256_HEX.test(raw.sha))) diff --git a/apps/api/src/services/session-snapshot-direct-upload.ts b/apps/api/src/services/session-snapshot-direct-upload.ts index 6da081da8e..5bb8f45a08 100644 --- a/apps/api/src/services/session-snapshot-direct-upload.ts +++ b/apps/api/src/services/session-snapshot-direct-upload.ts @@ -35,6 +35,8 @@ export async function generateSessionSnapshotDirectUploadUrl( sha256: string; contentType: string; checksumHeader?: boolean; + /** Who the snapshot belongs to: the box's per-uploader slot limit keys on it. */ + owner?: { workspaceId: string; userId?: string; projectId?: string | null }; } ): Promise { const expiresIn = parsePositiveInt( @@ -49,6 +51,15 @@ export async function generateSessionSnapshotDirectUploadUrl( contentLength: input.sizeBytes, contentType: input.contentType, sha256: input.sha256, + ...(input.owner + ? { + owner: { + workspaceId: input.owner.workspaceId, + ...(input.owner.userId ? { userId: input.owner.userId } : {}), + ...(input.owner.projectId ? { projectId: input.owner.projectId } : {}), + }, + } + : {}), }); } // Presign: unchanged (pinned by r2-presign-cloudflare-equivalence.test.ts). diff --git a/apps/api/tests/unit/routes/workspaces-session-snapshots.test.ts b/apps/api/tests/unit/routes/workspaces-session-snapshots.test.ts index 28be2afab9..b76fb71e60 100644 --- a/apps/api/tests/unit/routes/workspaces-session-snapshots.test.ts +++ b/apps/api/tests/unit/routes/workspaces-session-snapshots.test.ts @@ -446,6 +446,8 @@ describe('workspaces session snapshot callback routes', () => { sha256: HOME_SHA256, contentType: 'application/x-tar', checksumHeader: true, + // The box's per-uploader slot limit keys on the snapshot's workspace. + owner: { workspaceId: 'WS_1', userId: 'user-1', projectId: 'project-1' }, }); expect(mocks.recordSessionSnapshotArtifactAuthorization).toHaveBeenCalledWith( expect.anything(), diff --git a/apps/api/tests/unit/selfhost/box-object-urls.test.ts b/apps/api/tests/unit/selfhost/box-object-urls.test.ts index ed3bb7a7d3..ab14376965 100644 --- a/apps/api/tests/unit/selfhost/box-object-urls.test.ts +++ b/apps/api/tests/unit/selfhost/box-object-urls.test.ts @@ -61,6 +61,8 @@ vi.mock('../../../src/services/admin-settings-resolution', () => ({ })); const KEY = 'box-test-encryption-key-0123456789'; +/** Every box upload URL names who it is for (the per-uploader slot key). */ +const OWNER = { userId: 'u-test' }; /** The defaults the route uses when settings storage is unavailable. */ const LIMITS = { total: 4, perUploader: 2, leaseMs: 60_000 }; const DOMAIN = 'box.example.test'; @@ -392,9 +394,9 @@ describe('which URL a caller gets', () => { ENCRYPTION_KEY: KEY, } as Env); expect(signer.kind).toBe('presign'); - expect(new URL(await signer.putUrl('temp-uploads/t/k', { expiresIn: 60 })).host).toMatch( - /acct\.r2\.cloudflarestorage\.com$/ - ); + expect( + new URL(await signer.putUrl('temp-uploads/t/k', { expiresIn: 60, owner: OWNER })).host + ).toMatch(/acct\.r2\.cloudflarestorage\.com$/); // Divergence: a keyless Env on Cloudflare has no signer; it does not fall through to a box URL. expect(resolveR2ObjectUrlSigner(boxEnv().env)).toBeNull(); }); @@ -404,7 +406,7 @@ describe('which URL a caller gets', () => { const signer = getR2ObjectUrlSigner(boxEnv().env); expect(signer.kind).toBe('box'); const url = new URL( - await signer.putUrl('temp-uploads/t/k', { expiresIn: 60, contentLength: 3 }) + await signer.putUrl('temp-uploads/t/k', { expiresIn: 60, contentLength: 3, owner: OWNER }) ); expect(`${url.origin}${url.pathname}`).toBe(`https://api.${DOMAIN}${BOX_OBJECT_ROUTE}`); expect(url.searchParams.get('token')).toMatch(/^samobj1\./); @@ -509,6 +511,15 @@ describe('callers on a keyless box', () => { expect(sessionSnapshotDirectUploadAvailable(env)).toBe(true); const key = buildSessionSnapshotR2Key(env, 'chat-1', 'gen-1', 'home'); const sha256 = 'b'.repeat(64); + // No owner: refused, since the URL would share one per-uploader bucket with every other one. + await expect( + generateSessionSnapshotDirectUploadUrl(env, { + key, + sizeBytes: 1234, + sha256, + contentType: 'application/x-tar', + }) + ).rejects.toThrow('no owner'); const url = new URL( await generateSessionSnapshotDirectUploadUrl(env, { key, @@ -516,6 +527,7 @@ describe('callers on a keyless box', () => { sha256, contentType: 'application/x-tar', checksumHeader: true, + owner: { workspaceId: 'ws-1', userId: 'u-1', projectId: 'p-1' }, }) ); expect(url.pathname).toBe(BOX_OBJECT_ROUTE); @@ -526,7 +538,24 @@ describe('callers on a keyless box', () => { len: 1234, sha: sha256, ct: 'application/x-tar', + sub: { u: 'u-1', p: 'p-1', w: 'ws-1' }, + }); + }); + + it('an empty snapshot artifact gets a zero-length URL that stores an empty object', async () => { + installBoxObjectUrls(); + const { env, R2 } = boxEnv(); + const key = buildSessionSnapshotR2Key(env, 'chat-1', 'gen-1', 'wip'); + const empty = new Uint8Array(0); + const url = await generateSessionSnapshotDirectUploadUrl(env, { + key, + sizeBytes: 0, + sha256: await sha256Hex(empty), + contentType: 'application/octet-stream', + owner: { workspaceId: 'ws-1' }, }); + expect((await putUrl(routeApp(), env, url, empty)).status).toBe(200); + expect(R2.objects.get(key)?.bytes.byteLength).toBe(0); }); it('snapshot keys are allowed under the configured prefix only', async () => { @@ -568,6 +597,7 @@ describe('callers on a keyless box', () => { await expect( signer.putUrl('temp-uploads/t/k', { expiresIn: 60, + owner: OWNER, contentLength: CELLD_MAX_REQUEST_BODY_BYTES + 1, }) ).rejects.toMatchObject({ statusCode: 400 }); @@ -594,7 +624,7 @@ describe('callers on a keyless box', () => { describe('PUT/GET /api/box-objects', () => { async function upload(env: Env, key: string, extra: Partial = {}) { const signer = createBoxObjectUrlSigner(env)!; - return signer.putUrl(key, { expiresIn: 60, contentType: 'text/plain', ...extra }); + return signer.putUrl(key, { expiresIn: 60, contentType: 'text/plain', owner: OWNER, ...extra }); } it('streams the body into R2 and serves it back with a GET token', async () => { diff --git a/scripts/selfhost/live/box-object-urls.live.test.ts b/scripts/selfhost/live/box-object-urls.live.test.ts index 40cc9ddf06..7002c719ff 100644 --- a/scripts/selfhost/live/box-object-urls.live.test.ts +++ b/scripts/selfhost/live/box-object-urls.live.test.ts @@ -38,7 +38,7 @@ app.post('/mint', async (c) => { const signer = createBoxObjectUrlSigner(c.env); const url = body.op === 'get' ? await signer.getUrl(body.key, { expiresIn: 300 }) - : await signer.putUrl(body.key, { expiresIn: 300, ...body.options }); + : await signer.putUrl(body.key, { expiresIn: 300, owner: { userId: 'live' }, ...body.options }); return c.json({ url }); }); // The real gate over celld's Durable Object SQL: renew must see its own row (cursor.rowsWritten). From 80143b6b13314dc5b9682ad0d0d1da2041f14529 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 12:55:58 +0000 Subject: [PATCH 18/19] fix(selfhost): wait briefly for an upload slot before answering 503 Browser attachment uploads treat 503 as fatal. An upload over the box or per-uploader cap now waits up to boxObjects.uploadAdmissionWaitSeconds (default 30) for a slot, polling the gate, before it is refused. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/selfhost/object-urls/gate.ts | 2 +- apps/api/src/selfhost/object-urls/route.ts | 44 ++++++++++++++--- apps/api/src/selfhost/object-urls/settings.ts | 17 +++++++ .../unit/selfhost/box-object-urls.test.ts | 49 +++++++++++++++++++ deploy/selfhost/README.md | 5 +- .../live/box-object-urls.live.test.ts | 23 ++++----- 6 files changed, 119 insertions(+), 21 deletions(-) diff --git a/apps/api/src/selfhost/object-urls/gate.ts b/apps/api/src/selfhost/object-urls/gate.ts index 384fdbf35a..a82b200d7a 100644 --- a/apps/api/src/selfhost/object-urls/gate.ts +++ b/apps/api/src/selfhost/object-urls/gate.ts @@ -6,7 +6,7 @@ * (task tasks/active/2026-11-23-selfhost-box-object-uploads.md): peak RSS 220 MB for one upload, * 284 / 427 / 896 MB for 2 / 4 / 8 at once, so roughly 85 MB per upload over a ~150 MB base, while * aggregate throughput stops growing after two (~180 MB/s). The default of 4 keeps the peak near - * 430 MB. An upload over the limit is refused with 503 and Retry-After rather than queued. One + * 430 MB. An upload over the limit waits briefly in the route (`uploadAdmissionWaitSeconds`), then is refused with 503 and Retry-After. One * uploader (a workspace, else a user) may hold only part of the slots, and the route drops an * upload that stops sending bytes (`route.ts`), so a slow or stalled client cannot keep the box's * uploads blocked. diff --git a/apps/api/src/selfhost/object-urls/route.ts b/apps/api/src/selfhost/object-urls/route.ts index ee484df9ff..ec27858316 100644 --- a/apps/api/src/selfhost/object-urls/route.ts +++ b/apps/api/src/selfhost/object-urls/route.ts @@ -23,10 +23,12 @@ import { boxUploadGate, type BoxUploadGateEnv } from './gate'; import { BOX_OBJECT_MAX_CONCURRENT_UPLOADS, BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER, + BOX_OBJECT_UPLOAD_ADMISSION_WAIT_SECONDS, BOX_OBJECT_UPLOAD_IDLE_SECONDS, BOX_OBJECT_UPLOAD_LEASE_SECONDS, DEFAULT_BOX_OBJECT_MAX_CONCURRENT_UPLOADS, DEFAULT_BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER, + DEFAULT_BOX_OBJECT_UPLOAD_ADMISSION_WAIT_SECONDS, DEFAULT_BOX_OBJECT_UPLOAD_IDLE_SECONDS, DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS, } from './settings'; @@ -62,15 +64,27 @@ interface UploadLimits { perUploader: number; leaseMs: number; idleMs: number; + /** How long an upload over the limit waits for a slot (0: refuse at once). */ + admissionWaitMs: number; } +/** How often a waiting upload asks the gate again (one cheap DO call each). */ +const ADMISSION_POLL_MS = 1_000; + const DEFAULT_LIMITS: UploadLimits = { total: DEFAULT_BOX_OBJECT_MAX_CONCURRENT_UPLOADS, perUploader: DEFAULT_BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER, leaseMs: DEFAULT_BOX_OBJECT_UPLOAD_LEASE_SECONDS * 1000, idleMs: DEFAULT_BOX_OBJECT_UPLOAD_IDLE_SECONDS * 1000, + admissionWaitMs: DEFAULT_BOX_OBJECT_UPLOAD_ADMISSION_WAIT_SECONDS * 1000, }; +/** A non-negative integer setting (0 is meaningful), else its default. */ +function nonNegativeSetting(value: unknown, fallback: number, scale = 1): number { + const number = Number(value); + return Number.isSafeInteger(number) && number >= 0 ? number * scale : fallback; +} + /** A positive integer setting, else its default: a missing value must never disable a bound. */ function setting(value: unknown, fallback: number, scale = 1): number { const number = Number(value); @@ -79,17 +93,26 @@ function setting(value: unknown, fallback: number, scale = 1): number { async function uploadLimits(env: Env): Promise { try { - const [total, lease, perUploader, idle] = await resolveAdminSettingDetailsMany(env, [ - BOX_OBJECT_MAX_CONCURRENT_UPLOADS, - BOX_OBJECT_UPLOAD_LEASE_SECONDS, - BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER, - BOX_OBJECT_UPLOAD_IDLE_SECONDS, - ]); + const [total, lease, perUploader, idle, admissionWait] = await resolveAdminSettingDetailsMany( + env, + [ + BOX_OBJECT_MAX_CONCURRENT_UPLOADS, + BOX_OBJECT_UPLOAD_LEASE_SECONDS, + BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER, + BOX_OBJECT_UPLOAD_IDLE_SECONDS, + BOX_OBJECT_UPLOAD_ADMISSION_WAIT_SECONDS, + ] + ); return { total: setting(total?.value, DEFAULT_LIMITS.total), leaseMs: setting(lease?.value, DEFAULT_LIMITS.leaseMs, 1000), perUploader: setting(perUploader?.value, DEFAULT_LIMITS.perUploader), idleMs: setting(idle?.value, DEFAULT_LIMITS.idleMs, 1000), + admissionWaitMs: nonNegativeSetting( + admissionWait?.value, + DEFAULT_LIMITS.admissionWaitMs, + 1000 + ), }; } catch (error) { // Settings storage unavailable: the defaults still bound memory. @@ -204,7 +227,14 @@ async function put(c: Context<{ Bindings: BoxObjectEnv }>, claims: BoxObjectToke // lease of at least twice the idle limit always covers the gap (the settings allow any pair). const limits = { ...configured, leaseMs: Math.max(configured.leaseMs, 2 * configured.idleMs) }; const leaseId = crypto.randomUUID(); - const lease = await gate.acquire(leaseId, uploader(claims), claims.key, limits); + // Over the limit: wait (bounded) for a slot rather than fail an upload a moment too early. + const admissionDeadline = Date.now() + limits.admissionWaitMs; + let lease = await gate.acquire(leaseId, uploader(claims), claims.key, limits); + while (!lease.granted && lease.reason === 'busy' && Date.now() < admissionDeadline) { + const wait = Math.min(ADMISSION_POLL_MS, admissionDeadline - Date.now()); + await new Promise((resolve) => setTimeout(resolve, wait)); + lease = await gate.acquire(leaseId, uploader(claims), claims.key, limits); + } if (!lease.granted && lease.reason === 'key-in-use') { // Another upload is creating this object right now: create-only, so this one cannot. log.warn('box_objects.upload_conflict', { ...logFields(claims), length, action: 'in_flight' }); diff --git a/apps/api/src/selfhost/object-urls/settings.ts b/apps/api/src/selfhost/object-urls/settings.ts index b6be8e9fe6..37190a5228 100644 --- a/apps/api/src/selfhost/object-urls/settings.ts +++ b/apps/api/src/selfhost/object-urls/settings.ts @@ -32,6 +32,14 @@ export const DEFAULT_BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER = 2; */ export const DEFAULT_BOX_OBJECT_UPLOAD_IDLE_SECONDS = 60; +/** + * Seconds an upload over the limit waits for a slot before the box answers 503. Clients (browser + * attachment uploads, the VM agent's publisher) start several uploads at once and treat a 503 as + * final, so a short queue turns "over the limit" into "a little later" instead of a failed upload. + * 0 refuses at once. + */ +export const DEFAULT_BOX_OBJECT_UPLOAD_ADMISSION_WAIT_SECONDS = 30; + /** These names exist only in the self-host build, so they are not in the shared name union. */ export const BOX_OBJECT_MAX_CONCURRENT_UPLOADS = 'boxObjects.maxConcurrentUploads' as AdminSettingName; @@ -39,6 +47,8 @@ export const BOX_OBJECT_UPLOAD_LEASE_SECONDS = 'boxObjects.uploadLeaseSeconds' a export const BOX_OBJECT_MAX_UPLOADS_PER_UPLOADER = 'boxObjects.maxUploadsPerUploader' as AdminSettingName; export const BOX_OBJECT_UPLOAD_IDLE_SECONDS = 'boxObjects.uploadIdleSeconds' as AdminSettingName; +export const BOX_OBJECT_UPLOAD_ADMISSION_WAIT_SECONDS = + 'boxObjects.uploadAdmissionWaitSeconds' as AdminSettingName; export const BOX_OBJECT_SETTINGS: readonly AdminSettingDefinition[] = [ integerDefinition( @@ -69,4 +79,11 @@ export const BOX_OBJECT_SETTINGS: readonly AdminSettingDefinition[] = [ 'Seconds an upload may receive no bytes before the box drops it and frees its slot.', { min: 5, max: 3_600 } ), + integerDefinition( + BOX_OBJECT_UPLOAD_ADMISSION_WAIT_SECONDS, + DEFAULT_BOX_OBJECT_UPLOAD_ADMISSION_WAIT_SECONDS, + 'Operations', + 'Seconds an upload over the concurrent-upload limit waits for a free slot before the box answers 503. 0 refuses at once.', + { min: 0, max: 600 } + ), ]; diff --git a/apps/api/tests/unit/selfhost/box-object-urls.test.ts b/apps/api/tests/unit/selfhost/box-object-urls.test.ts index ab14376965..9f7c471ee6 100644 --- a/apps/api/tests/unit/selfhost/box-object-urls.test.ts +++ b/apps/api/tests/unit/selfhost/box-object-urls.test.ts @@ -61,6 +61,17 @@ vi.mock('../../../src/services/admin-settings-resolution', () => ({ })); const KEY = 'box-test-encryption-key-0123456789'; + +/** Default limits, but refuse at once instead of waiting for a slot (tests that assert a 503). */ +function settingsWithoutAdmissionWait() { + vi.mocked(resolveAdminSettingDetailsMany).mockResolvedValueOnce([ + { value: 4 }, + { value: 300 }, + { value: 2 }, + { value: 60 }, + { value: 0 }, + ] as never); +} /** Every box upload URL names who it is for (the per-uploader slot key). */ const OWNER = { userId: 'u-test' }; /** The defaults the route uses when settings storage is unavailable. */ @@ -757,6 +768,7 @@ describe('PUT/GET /api/box-objects', () => { }); it('refuses with 503 and Retry-After while the box limit is in use, then admits once a slot frees', async () => { + settingsWithoutAdmissionWait(); const { env, R2, gate } = boxEnv(); const app = routeApp(); // Settings storage is unavailable in this env, so the default limit (4) applies. @@ -837,6 +849,7 @@ describe('PUT/GET /api/box-objects', () => { { value: 1 }, // lease seconds (below the idle limit, so raised to 2 x idle = 4 s) { value: 2 }, { value: 2 }, // idle seconds: renewals every ~1.3 s while bytes arrive + { value: 0 }, ] as never); const { env, R2 } = boxEnv(); const ns = env.BOX_UPLOAD_GATE as unknown as { get: () => Record }; @@ -878,6 +891,7 @@ describe('PUT/GET /api/box-objects', () => { { value: 60 }, // lease 60 s { value: 2 }, { value: 120 }, // idle 120 s + { value: 0 }, ] as never); const { env } = boxEnv(); const ns = env.BOX_UPLOAD_GATE as unknown as { @@ -902,6 +916,7 @@ describe('PUT/GET /api/box-objects', () => { }); it('one uploader cannot take every slot: a second uploader is still admitted', async () => { + settingsWithoutAdmissionWait(); const { env, gate } = boxEnv(); const app = routeApp(); const signer = createBoxObjectUrlSigner(env)!; @@ -928,6 +943,7 @@ describe('PUT/GET /api/box-objects', () => { { value: 1800 }, { value: 2 }, { value: 1 }, // idle seconds + { value: 0 }, ] as never); const { env, R2, gate } = boxEnv(); const app = routeApp(); @@ -961,12 +977,45 @@ describe('PUT/GET /api/box-objects', () => { }); }, 10_000); + it('waits a bounded time for a slot instead of refusing: admitted when one frees, 503 when none does', async () => { + vi.mocked(resolveAdminSettingDetailsMany).mockResolvedValueOnce([ + { value: 4 }, + { value: 300 }, + { value: 2 }, + { value: 60 }, + { value: 3 }, // wait up to 3 s for a slot + ] as never); + const { env, R2, gate } = boxEnv(); + const app = routeApp(); + // A third concurrent attachment from the same user (two already uploading). + gate.acquire('first', 'u:u-test', 'temp-uploads/t/1', LIMITS); + gate.acquire('second', 'u:u-test', 'temp-uploads/t/2', LIMITS); + const url = await upload(env, 'temp-uploads/t/3', { contentLength: 1 }); + setTimeout(() => gate.release('first'), 1_200); + const started = Date.now(); + expect((await putUrl(app, env, url, bytes('3'))).status).toBe(200); + expect(Date.now() - started).toBeGreaterThanOrEqual(1_000); + expect(R2.objects.has('temp-uploads/t/3')).toBe(true); + // Control: when no slot frees within the wait, the answer is still 503. + vi.mocked(resolveAdminSettingDetailsMany).mockResolvedValueOnce([ + { value: 4 }, + { value: 300 }, + { value: 2 }, + { value: 60 }, + { value: 1 }, + ] as never); + gate.acquire('third', 'u:u-test', 'temp-uploads/t/4', LIMITS); + const blocked = await upload(env, 'temp-uploads/t/5', { contentLength: 1 }); + expect((await putUrl(app, env, blocked, bytes('5'))).status).toBe(503); + }, 15_000); + it('a setting that resolves to nothing keeps its default bound (never disables the gate)', async () => { vi.mocked(resolveAdminSettingDetailsMany).mockResolvedValueOnce([ { value: undefined }, { value: undefined }, { value: undefined }, { value: undefined }, + { value: 0 }, ] as never); const { env, gate } = boxEnv(); const app = routeApp(); diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 05ceb9a3ec..02eb3aad0f 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -1124,8 +1124,9 @@ that the box's Caddy strips from every client request (`X-SAM-*`), so it cannot arrive, and never shorter than twice the idle limit). One object key is written by one upload at a time: a second upload of the same key while the first runs gets 412. Each in-flight upload costs celld about 85 MB of memory (measured on celld 0.6.3: peak RSS 220 MB for one 1 GB upload, 427 MB for four, 896 MB for - eight; throughput stops growing after two at about 180 MB/s). Further uploads get 503 with - `Retry-After`. + eight; throughput stops growing after two at about 180 MB/s). An upload over the cap waits up to + `boxObjects.uploadAdmissionWaitSeconds` (default 30) for a slot before it is sent; if none frees + in time it gets 503 with `Retry-After`. - Tokens travel in the query string. Caddy's log drops every query string (`caddy/log-redaction.caddy`), SAM's request log records only the path, and celld does not log request URLs at its default level. diff --git a/scripts/selfhost/live/box-object-urls.live.test.ts b/scripts/selfhost/live/box-object-urls.live.test.ts index 7002c719ff..7ceb2f7ea1 100644 --- a/scripts/selfhost/live/box-object-urls.live.test.ts +++ b/scripts/selfhost/live/box-object-urls.live.test.ts @@ -272,7 +272,7 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { expect(peak - before).toBeLessThan(100); }, 60_000); - it('holds at most four uploads at once (four uploaders): the fifth gets 503 with Retry-After', async () => { + it('holds at most four uploads at once (four uploaders): the fifth waits for a slot, then completes', async () => { const length = 1024 * 1024; const held: Array> = []; const pending = []; @@ -290,19 +290,20 @@ describe.skipIf(skipWithoutDocker)('box object URLs on celld', () => { } // Let the four reach the gate. await new Promise((resolve) => setTimeout(resolve, 1500)); - const fifth = await putBytes( + let fifthDone = false; + const fifth = putBytes( await mint('put', 'temp-uploads/busy/5', { contentLength: 4, owner: { userId: 'user-5' } }), Buffer.from('five') - ); - expect(fifth.status).toBe(503); - expect(Number(fifth.headers['retry-after'])).toBeGreaterThan(0); + ).finally(() => { + fifthDone = true; + }); + // The box is full: the fifth is held in the admission wait (default 30 s), not answered. + await new Promise((resolve) => setTimeout(resolve, 2000)); + expect(fifthDone).toBe(false); for (const req of held) req.end(Buffer.alloc(length - 1024)); expect((await Promise.all(pending)).map((r) => r.status)).toEqual([200, 200, 200, 200]); - // Every lease was released: a new upload is admitted. - const after = await putBytes( - await mint('put', 'temp-uploads/busy/6', { contentLength: 3, owner: { userId: 'user-6' } }), - Buffer.from('six') - ); - expect(after.status).toBe(200); + // A slot freed within the wait: the fifth is admitted and stored. + expect((await fifth).status).toBe(200); + expect(await (await fetch(await mint('get', 'temp-uploads/busy/5'))).text()).toBe('five'); }, 60_000); }); From 64a1a39ce49234b03abd8521dc2677badefbee3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 23 Nov 2026 12:56:27 +0000 Subject: [PATCH 19/19] task: archive self-host box uploads Co-Authored-By: Claude Opus 5.5 --- .../{active => archive}/2026-11-23-selfhost-box-object-uploads.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tasks/{active => archive}/2026-11-23-selfhost-box-object-uploads.md (100%) diff --git a/tasks/active/2026-11-23-selfhost-box-object-uploads.md b/tasks/archive/2026-11-23-selfhost-box-object-uploads.md similarity index 100% rename from tasks/active/2026-11-23-selfhost-box-object-uploads.md rename to tasks/archive/2026-11-23-selfhost-box-object-uploads.md