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/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/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..a82b200d7a --- /dev/null +++ b/apps/api/src/selfhost/object-urls/gate.ts @@ -0,0 +1,132 @@ +/** + * 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 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. + * + * 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 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'; + +export interface BoxUploadGateEnv { + BOX_UPLOAD_GATE?: DurableObjectNamespace; +} + +export type BoxUploadLease = + | { 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; +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_slots (id TEXT PRIMARY KEY, uploader TEXT NOT NULL, object_key TEXT NOT NULL, expires_at INTEGER NOT NULL)' + ); + } + + /** 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_slots WHERE expires_at <= ?', now); + const row = sql + .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); + const retryAfterSeconds = Math.min( + MAX_RETRY_AFTER_SECONDS, + Math.max(MIN_RETRY_AFTER_SECONDS, untilExpiry) + ); + return { granted: false, reason: 'busy', active: row.active, retryAfterSeconds }; + } + sql.exec( + '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, 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_slots WHERE id = ?', id); + } +} + +/** The box's one gate instance. */ +export const BOX_UPLOAD_GATE_NAME = 'box'; + +interface BoxUploadGateStub { + acquire( + id: string, + uploader: string, + objectKey: string, + limits: { total: number; perUploader: number; leaseMs: number } + ): Promise; + renew(id: string, 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..ec27858316 --- /dev/null +++ b/apps/api/src/selfhost/object-urls/route.ts @@ -0,0 +1,340 @@ +/** + * `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, 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. + */ +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_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'; +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; + +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. */ +function logFields(claims: BoxObjectTokenClaims) { + return { op: claims.op, key: claims.key, ...claims.sub }; +} + +interface UploadLimits { + total: number; + 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); + return Number.isSafeInteger(number) && number > 0 ? number * scale : fallback; +} + +async function uploadLimits(env: Env): Promise { + try { + 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. + log.warn('box_objects.limits_fallback', { + error: error instanceof Error ? error.message : String(error), + }); + 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'; +} + +interface Watchdog { + stream: TransformStream; + /** 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; +} + +/** + * 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 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(() => stop('idle'), idleMs); + }; + 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: dispose, + cancel: dispose, + }); + return { stream, stopped: () => stopped, loseLease: () => stop('lease-lost'), dispose }; +} + +/** + * 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; + 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; +} + +/** 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 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 (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)', {}, 'UNAVAILABLE'); + } + 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(); + // 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' }); + return plain(412, 'Another upload is writing this object'); + } + if (!lease.granted) { + log.warn('box_objects.upload_refused_busy', { + ...logFields(claims), + active: lease.active, + limit: limits.total, + perUploader: limits.perUploader, + }); + return plain(503, 'The box is receiving as many uploads as it allows; retry shortly', { + 'Retry-After': String(lease.retryAfterSeconds), + }); + } + const watchdog = uploadWatchdog(limits.idleMs, Math.max(1000, limits.leaseMs / 3), () => { + // 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; + 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(watchdog.stream).pipeThrough(new FixedLengthStream(length)) + : new Uint8Array(0); + let written: R2Object | null; + try { + written = await env.R2.put(claims.key, stream, { + ...(atomic ? { 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 }); + 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'); + } + 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 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', { + ...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, + // 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 }); + 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..37190a5228 --- /dev/null +++ b/apps/api/src/selfhost/object-urls/settings.ts @@ -0,0 +1,89 @@ +/** + * 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 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 = 300; + +/** + * 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; + +/** + * 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; +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_UPLOAD_ADMISSION_WAIT_SECONDS = + 'boxObjects.uploadAdmissionWaitSeconds' 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 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( + 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 } + ), + 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/src/selfhost/object-urls/signer.ts b/apps/api/src/selfhost/object-urls/signer.ts new file mode 100644 index 0000000000..a7a7930cad --- /dev/null +++ b/apps/api/src/selfhost/object-urls/signer.ts @@ -0,0 +1,69 @@ +/** + * 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) => { + // 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}` + ); + } + 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..8d5b1a8c6b --- /dev/null +++ b/apps/api/src/selfhost/object-urls/tokens.ts @@ -0,0 +1,218 @@ +/** + * 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 { 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, + 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 (may be 0). */ + 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; + +/** + * The only key prefixes a token may name: task attachments (`attachment-upload.ts` + * 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/', + 'compose-image-artifacts/', + 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; + +/** 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: 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, + prefixes: readonly string[] = BOX_OBJECT_KEY_PREFIXES +): 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; + // 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 { + 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 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; +} + +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, + 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, prefixes)) return null; + if (!positiveInteger(raw.exp)) 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))) + 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: BoxObjectTokenEnv, + input: BoxObjectTokenInput, + now: number = Date.now() +): Promise { + const { expiresIn, ...rest } = input; + 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 }, + 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. + 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. */ +export async function verifyBoxObjectToken( + env: BoxObjectTokenEnv, + token: string, + now: number = Date.now() +): Promise { + const raw = await verifySignedToken(env, PURPOSE, token); + 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; + 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..9c79f2f79c --- /dev/null +++ b/apps/api/src/selfhost/signed-token.ts @@ -0,0 +1,140 @@ +/** + * 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. */ +export const MAX_SIGNED_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_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]; + 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..e60be762c1 100644 --- a/apps/api/src/services/attachment-upload.ts +++ b/apps/api/src/services/attachment-upload.ts @@ -1,18 +1,18 @@ /** - * 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 { errors } from '../middleware/error'; +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 +83,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 errors.badRequest(`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..7e7cf24fa9 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, @@ -26,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, @@ -77,6 +75,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/src/services/session-snapshot-direct-upload.ts b/apps/api/src/services/session-snapshot-direct-upload.ts index 997193fc62..5bb8f45a08 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 { @@ -26,8 +35,34 @@ 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( + 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, + ...(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). const target = getR2PresignTarget(env); const command = new PutObjectCommand({ Bucket: target.bucket, @@ -37,10 +72,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/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/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 new file mode 100644 index 0000000000..9f7c471ee6 --- /dev/null +++ b/apps/api/tests/unit/selfhost/box-object-urls.test.ts @@ -0,0 +1,1067 @@ +/** + * 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 { + buildComposeImageArtifactKey, + buildContextKey, + composeImageArtifactMaxBytesFor, + createBuildContextUpload, + createComposeImageArtifactDownloads, + createComposeImageArtifactUploads, + type ObjectPutUrlOptions, +} 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 { + BOX_OBJECT_ROUTE, + CELLD_MAX_REQUEST_BODY_BYTES, + createBoxObjectUrlSigner, +} from '../../../src/selfhost/object-urls/signer'; +import { + isSafeObjectKey, + MAX_BOX_OBJECT_TOKEN_SECONDS, + mintBoxObjectToken, + verifyBoxObjectToken, +} from '../../../src/selfhost/object-urls/tokens'; +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, + 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', () => ({ + resolveAdminSettingDetailsMany: vi.fn(async () => { + throw new Error('settings storage unavailable'); + }), +})); + +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. */ +const LIMITS = { total: 4, perUploader: 2, leaseMs: 60_000 }; +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); + 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 }; + }, + }; +} + +function gateNamespace(gate: BoxUploadGate) { + return { + idFromName: (name: string) => name, + get: () => ({ + acquire: async ( + id: string, + uploader: string, + objectKey: string, + limits: { total: number; perUploader: number; leaseMs: number } + ) => gate.acquire(id, uploader, objectKey, 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 TestGate({ 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'); + }); +}); + +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', 'library/p1/f1', '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', () => { + 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('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(); + }); + + 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('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\./); + }); + + 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('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); + // 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, + sizeBytes: 1234, + sha256, + contentType: 'application/x-tar', + checksumHeader: true, + owner: { workspaceId: 'ws-1', userId: 'u-1', projectId: 'p-1' }, + }) + ); + 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', + 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 () => { + 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('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( + signer.putUrl('temp-uploads/t/k', { + expiresIn: 60, + owner: OWNER, + 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 = {}) { + const signer = createBoxObjectUrlSigner(env)!; + 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 () => { + 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: 'temp-uploads/t/k', + expiresIn: 60, + }); + const expired = await mintBoxObjectToken( + env, + { 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: 'temp-uploads/t/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, 'temp-uploads/t/k1', { maxBytes: 4 }); + expect((await putUrl(app, env, bounded, bytes('12345'))).status).toBe(413); + 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( + `${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, '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('temp-uploads/t/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, '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('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, '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('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, '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('temp-uploads/t/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 () => { + settingsWithoutAdmissionWait(); + 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}`, `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); + expect(Number(refused.headers.get('Retry-After'))).toBeGreaterThan(0); + 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', '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', `temp-uploads/held/${'dead'}`, one); + gate.clock = 500; + expect(gate.acquire('next', 'u:b', `temp-uploads/held/${'next'}`, one).granted).toBe(false); + gate.clock = 1_000; + 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', `temp-uploads/held/${'slow'}`, one); + gate.clock = 900; + gate.renew('slow', 1_000); + gate.clock = 1_500; + 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', `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 + { value: 0 }, + ] 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 + { value: 0 }, + ] 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 () => { + settingsWithoutAdmissionWait(); + 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', `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, + 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 + { value: 0 }, + ] 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', `temp-uploads/held/${'probe'}`, { + total: 1, + perUploader: 1, + leaseMs: 60_000, + }) + ).toEqual({ + granted: true, + }); + }, 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(); + 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); + }); + + 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 () => { + 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, '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')); + // 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', ]) ); } 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/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/.env.example b/deploy/selfhost/.env.example index 88620a7f0d..6c12f6dc4d 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 58ffc7ca7e..02eb3aad0f 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -1100,15 +1100,50 @@ 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, 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`), +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 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 + 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, + 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, 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). 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. + +**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 diff --git a/packages/app-deployment/src/build-context-upload.ts b/packages/app-deployment/src/build-context-upload.ts index 6431a4e185..33236bb0f5 100644 --- a/packages/app-deployment/src/build-context-upload.ts +++ b/packages/app-deployment/src/build-context-upload.ts @@ -1,35 +1,31 @@ -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 +44,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..fa3f387578 100644 --- a/packages/app-deployment/src/index.ts +++ b/packages/app-deployment/src/index.ts @@ -30,7 +30,6 @@ export type { ComposeImageArtifactDescriptor, ComposeImageArtifactDownload, ComposeImageArtifactPlatform, - ComposeImageArtifactPresignTarget, ComposeImageArtifactRequest, ComposeImageArtifactUpload, } from './compose-image-artifacts'; @@ -38,6 +37,7 @@ export { buildComposeImageArtifactKey, COMPOSE_IMAGE_ARTIFACT_ARCHIVE_TYPE, COMPOSE_IMAGE_ARTIFACT_MEDIA_TYPE, + composeImageArtifactMaxBytesFor, createComposeImageArtifactDownloads, createComposeImageArtifactUploads, getComposeImageArtifactMaxBytes, @@ -208,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/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..6c3c634cbf 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 { 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 // 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/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"] } ] } 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); }); 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/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..7ceb2f7ea1 --- /dev/null +++ b/scripts/selfhost/live/box-object-urls.live.test.ts @@ -0,0 +1,309 @@ +/** + * 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, readFileSync } 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, 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). +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; +`; + +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; +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)); + +/** 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); + 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', 'compose-build-contexts/live/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', '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()); + 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', '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', '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', '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', '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', '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', 'compose-image-artifacts/live/web.tar'))).arrayBuffer() + ); + 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. + await put(url, 100, (req) => { + req.write(Buffer.alloc(10)); + setTimeout(() => req.destroy(), 300); + }).catch(() => undefined); + 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', '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 }); + // 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 () => { + 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}${FORGED_TOKEN_PATH}`, { + method: 'PUT', + headers: { 'content-length': String(length) }, + }); + req.on('response', (res) => { + res.resume(); + done(res.statusCode ?? 0); + }); + // 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; + 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); + await expectCelldResponsive(); + 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 waits for a slot, then completes', async () => { + const length = 1024 * 1024; + const held: Array> = []; + const pending = []; + for (let i = 0; i < 4; i++) { + 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)); + held.push(req); + }) + ); + } + // Let the four reach the gate. + await new Promise((resolve) => setTimeout(resolve, 1500)); + let fifthDone = false; + const fifth = putBytes( + await mint('put', 'temp-uploads/busy/5', { contentLength: 4, owner: { userId: 'user-5' } }), + Buffer.from('five') + ).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]); + // 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); +}); 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/archive/2026-11-23-selfhost-box-object-uploads.md b/tasks/archive/2026-11-23-selfhost-box-object-uploads.md new file mode 100644 index 0000000000..d8f82cec82 --- /dev/null +++ b/tasks/archive/2026-11-23-selfhost-box-object-uploads.md @@ -0,0 +1,141 @@ +# 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 | - | - | + +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). + +## 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/box-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`. 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 + +| 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 + +- [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 + +## 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). + +## 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. + +### 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. 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.