diff --git a/doc/runner-image-contract.md b/doc/runner-image-contract.md index 5d531f6bf33..f744e5102d6 100644 --- a/doc/runner-image-contract.md +++ b/doc/runner-image-contract.md @@ -216,6 +216,38 @@ repository and nowhere else. Other runs build and check, and publish nothing. - **First publication.** GitHub creates the package private. A maintainer must make it public once. +## Reading the transport archives alone + +The server needs the transport form of an older pack when a retained session +names a pack that is not the server's own. A pack with +`payload.runnerInputsDigest` came out of this image, so the server reads it +from `inputs-` (`retained-provider-pack-oci.ts`). It does not count +layers. It uses the rule of "Layers": the full image is the slim image, then +layers that hold transport content and nothing else. + +- The full index must carry the annotations + `io.paperclip.runner.inputs-digest`, equal to the pack's digest of inputs, + `org.opencontainers.image.revision`, equal to the pack's + `runnerSourceRevision`, and `io.paperclip.runner.slim-digest`. +- The server reads the slim index by that digest, never by the slim tag, and + checks the bytes against the digest. +- For the pack's platform, the layers of the slim image must be the first + layers of the full image, as the same blobs in the same order. The layers + after them are the transport layers: at least one and at most eight. +- The server downloads only those layers. It refuses any entry in them that + is not a transport archive or the receipt, and any file that is in two of + them. +- The importer then checks every archive against the pack's manifest, as for + any other source. +- The record the server keeps of the source names the digest of inputs and + every transport layer under `runnerImage`. Its `transportLayerDigest` is + then the last of those layers and `transportLayerBytes` their total. + +When the image cannot be read (a tag or the slim index does not exist, or the +registry refuses a request), the server reads the application image tagged +`sha-`, as it does for a pack without +`runnerInputsDigest`. An image that can be read and does not match fails. + ## Known limits - A build without `PAPERCLIP_RUNNER_SOURCE_REVISION` or diff --git a/server/src/services/native-runtime/retained-provider-pack-oci.ts b/server/src/services/native-runtime/retained-provider-pack-oci.ts index 7e2126a4334..a5255730310 100644 --- a/server/src/services/native-runtime/retained-provider-pack-oci.ts +++ b/server/src/services/native-runtime/retained-provider-pack-oci.ts @@ -1,6 +1,6 @@ import { createHash } from "node:crypto"; import { createReadStream, createWriteStream } from "node:fs"; -import { mkdir } from "node:fs/promises"; +import { mkdir, unlink } from "node:fs/promises"; import { join } from "node:path"; import { Readable, Transform } from "node:stream"; import { pipeline } from "node:stream/promises"; @@ -8,8 +8,10 @@ import { createGunzip } from "node:zlib"; import tar from "tar-stream"; import type { ProviderPackIdentity } from "./remote-provider-pack-verification.js"; -const repository = "paperclipai/paperclip"; +const applicationRepository = "paperclipai/paperclip"; +const runnerRepository = "paperclipai/paperclip-runner"; const registry = "https://ghcr.io"; +const unavailable = "runner_remote_provider_source_unavailable"; export const MAX_RETAINED_PACK_BYTES = 4 * 1024 ** 3; const maxMetadataBytes = 1024 * 1024; const digest = (bytes: Buffer) => `sha256:${createHash("sha256").update(bytes).digest("hex")}`; @@ -17,6 +19,8 @@ const validDigest = (value: unknown): value is string => typeof value === "strin function fail(): never { throw Error("runner_remote_provider_source_invalid"); } type Blob = { digest: string; size: number; mediaType?: string }; type Manifest = { schemaVersion: number; config: Blob; layers: Blob[] }; +type Index = { schemaVersion: number; annotations?: Record; manifests: Array }; +type Unpacked = { files: Set; bytes: number }; export type RetainedPackProvenance = { schema: "paperclip.retained-provider-pack-source.v1"; sourceRevision: string; @@ -26,6 +30,7 @@ export type RetainedPackProvenance = { imageConfigDigest: string; transportLayerDigest: string; transportLayerBytes: number; + runnerImage?: { inputsDigest: string; transportLayerDigests: string[] }; }; function blob(value: Blob, maximum: number): Blob { @@ -61,27 +66,29 @@ function bounded(limit: number) { } }); } -async function unpackTransport(layer: string, target: string, signal: AbortSignal) { +async function unpackTransport(layer: string, target: string, signal: AbortSignal, prefix: string, unpacked: Unpacked) { const archive = tar.extract(); - const names = new Set(); - let bytes = 0; + const directories = new Set(); + const parents = prefix.split("/").filter(Boolean).map((_part, index, parts) => parts.slice(0, index + 1).join("/")); + const allowed = [...parents, `${prefix}provider-pack.archives`]; archive.on("entry", (header, body, next) => { body.on("error", () => undefined); void (async () => { signal.throwIfAborted(); const normalized = header.name.replace(/^\.\//u, ""); const name = header.type === "directory" ? normalized.replace(/\/$/u, "") : normalized; - if (names.has(name) || names.size >= 10_010) fail(); - names.add(name); + if (directories.has(name) || unpacked.files.has(name) || directories.size + unpacked.files.size >= 10_010) fail(); if (header.type === "directory") { - if (!["opt", "opt/paperclip-runner", "opt/paperclip-runner/provider-pack.archives"].includes(name)) fail(); + if (!allowed.includes(name)) fail(); + directories.add(name); body.resume(); return; } - if (header.type !== "file" || !/^opt\/paperclip-runner\/provider-pack(?:\.archive\.json|\.archives\/(?:overlay|[0-9]{1,4})\.tar\.zst)$/u.test(name) - || !Number.isSafeInteger(header.size) || header.size! < 1 || (bytes += header.size!) > MAX_RETAINED_PACK_BYTES - || name.endsWith(".json") && header.size! > maxMetadataBytes) fail(); - const relative = name.slice("opt/paperclip-runner/".length); + const relative = name.startsWith(prefix) ? name.slice(prefix.length) : ""; + if (header.type !== "file" || !/^provider-pack(?:\.archive\.json|\.archives\/(?:overlay|[0-9]{1,4})\.tar\.zst)$/u.test(relative) + || !Number.isSafeInteger(header.size) || header.size! < 1 || (unpacked.bytes += header.size!) > MAX_RETAINED_PACK_BYTES + || relative.endsWith(".json") && header.size! > maxMetadataBytes) fail(); + unpacked.files.add(name); if (relative.includes("/")) await mkdir(join(target, "provider-pack.archives"), { recursive: true, mode: 0o700 }); await pipeline(body, createWriteStream(join(target, relative), { flags: "wx", mode: 0o600 }), { signal }); })().then(() => next(), error => archive.destroy(error)); @@ -89,6 +96,67 @@ async function unpackTransport(layer: string, target: string, signal: AbortSigna await pipeline(createReadStream(layer), createGunzip(), bounded(MAX_RETAINED_PACK_BYTES + 16 * 1024 ** 2), archive, { signal }); } +async function request(signal: AbortSignal, path: string, token?: string, allowRedirect = false) { + signal.throwIfAborted(); + let response = await fetch(`${registry}${path}`, { redirect: "manual", signal, headers: { + Accept: "application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.docker.distribution.manifest.v2+json", + ...(token ? { Authorization: `Bearer ${token}` } : {}), + } }); + if ([302, 307].includes(response.status) && allowRedirect) { + const location = response.headers.get("location"); + await response.body?.cancel(); + if (!location || location.length > 8192) fail(); + const url = new URL(location, registry); + if (url.protocol !== "https:" || url.username || url.password || !["ghcr.io", "pkg-containers.githubusercontent.com"].includes(url.hostname)) fail(); + response = await fetch(url, { redirect: "error", signal }); + } + if (!response.ok) { + await response.body?.cancel(); + throw Error(`${unavailable}: HTTP ${response.status}`); + } + return response; +} + +async function pullToken(repository: string, signal: AbortSignal) { + const authentication = JSON.parse((await metadata(await request(signal, `/token?service=ghcr.io&scope=repository:${repository}:pull`), signal)).toString()) as { token?: unknown }; + if (typeof authentication.token !== "string" || authentication.token.length < 1 || authentication.token.length > 32 * 1024) fail(); + return authentication.token; +} + +async function platformImage(repository: string, token: string, reference: string, architecture: string, signal: AbortSignal) { + const indexBytes = await metadata(await request(signal, `/v2/${repository}/manifests/${reference}`, token), signal); + if (validDigest(reference) && digest(indexBytes) !== reference) fail(); + const index = JSON.parse(indexBytes.toString()) as Index; + if (index.schemaVersion !== 2 || !Array.isArray(index.manifests) || index.manifests.length > 32) fail(); + const candidates = index.manifests.filter(row => row.platform?.os === "linux" && row.platform.architecture === architecture); + if (candidates.length !== 1) fail(); + const child = blob(candidates[0]!, maxMetadataBytes); + const manifestBytes = await metadata(await request(signal, `/v2/${repository}/manifests/${child.digest}`, token), signal, child); + const image = JSON.parse(manifestBytes.toString()) as Manifest; + if (image.schemaVersion !== 2 || !Array.isArray(image.layers) || image.layers.length > 128) fail(); + return { repository, token, index, indexDigest: digest(indexBytes), child, image, config: blob(image.config, maxMetadataBytes) }; +} + +async function receiveTransportLayer(source: { repository: string; token: string }, layer: Blob, prefix: string, directory: string, unpacked: Unpacked, signal: AbortSignal) { + const transport = blob(layer, MAX_RETAINED_PACK_BYTES); + if (!["application/vnd.oci.image.layer.v1.tar+gzip", "application/vnd.docker.image.rootfs.diff.tar.gzip"].includes(transport.mediaType ?? "")) fail(); + const response = await request(signal, `/v2/${source.repository}/blobs/${transport.digest}`, source.token, true); + if (!response.body) fail(); + let bytes = 0; + const hash = createHash("sha256"); + const meter = new Transform({ transform(chunk, _encoding, done) { + bytes += chunk.length; + hash.update(chunk); + done(bytes > transport.size ? Error("runner_remote_provider_source_size_limit") : null, chunk); + } }); + const file = join(directory, "transport.tar.gz"); + await pipeline(Readable.fromWeb(response.body as Parameters[0]), meter, createWriteStream(file, { flags: "wx", mode: 0o600 }), { signal }); + if (bytes !== transport.size || `sha256:${hash.digest("hex")}` !== transport.digest) fail(); + await unpackTransport(file, directory, signal, prefix, unpacked); + await unlink(file); + return transport; +} + export async function receiveRetainedProviderPack(input: { manifest: ProviderPackIdentity; directory: string; @@ -98,64 +166,46 @@ export async function receiveRetainedProviderPack(input: { const revision = selected.payload.runnerSourceRevision; const architecture = selected.payload.target.architecture === "x64" ? "amd64" : selected.payload.target.architecture === "arm64" ? "arm64" : null; if (!/^[a-f0-9]{40}$/.test(revision) || selected.payload.target.platform !== "linux" || !architecture) fail(); - const request = async (path: string, token?: string, allowRedirect = false) => { - signal.throwIfAborted(); - let response = await fetch(`${registry}${path}`, { redirect: "manual", signal, headers: { - Accept: "application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.docker.distribution.manifest.v2+json", - ...(token ? { Authorization: `Bearer ${token}` } : {}), - } }); - if ([302, 307].includes(response.status) && allowRedirect) { - const location = response.headers.get("location"); - await response.body?.cancel(); - if (!location || location.length > 8192) fail(); - const url = new URL(location, registry); - if (url.protocol !== "https:" || url.username || url.password || !["ghcr.io", "pkg-containers.githubusercontent.com"].includes(url.hostname)) fail(); - response = await fetch(url, { redirect: "error", signal }); + const unpacked: Unpacked = { files: new Set(), bytes: 0 }; + const provenance = { schema: "paperclip.retained-provider-pack-source.v1" as const, sourceRevision: revision, providerPackDigest: selected.digest }; + + const inputsDigest = selected.payload.runnerInputsDigest; + if (typeof inputsDigest === "string" && /^[a-f0-9]{64}$/.test(inputsDigest)) { + const runner = await (async () => { + const token = await pullToken(runnerRepository, signal); + const full = await platformImage(runnerRepository, token, `inputs-${inputsDigest}`, architecture, signal); + const slimDigest = full.index.annotations?.["io.paperclip.runner.slim-digest"]; + if (full.index.annotations?.["io.paperclip.runner.inputs-digest"] !== inputsDigest + || full.index.annotations["org.opencontainers.image.revision"] !== revision || !validDigest(slimDigest)) fail(); + return { full, slim: await platformImage(runnerRepository, token, slimDigest, architecture, signal) }; + })().catch((error: unknown) => { + if (error instanceof Error && error.message.startsWith(unavailable)) return null; + throw error; + }); + if (runner) { + const { full, slim } = runner; + const shared = slim.image.layers.length; + const transport = full.image.layers.slice(shared).map(layer => blob(layer, MAX_RETAINED_PACK_BYTES)); + if (slim.image.layers.some((layer, index) => !validDigest(layer?.digest) || layer.digest !== full.image.layers[index]?.digest) + || transport.length < 1 || transport.length > 8 || transport.reduce((bytes, layer) => bytes + layer.size, 0) > MAX_RETAINED_PACK_BYTES) fail(); + for (const layer of transport) await receiveTransportLayer(full, layer, "", directory, unpacked, signal); + return { ...provenance, imageIndexDigest: full.indexDigest, imageManifestDigest: full.child.digest, imageConfigDigest: full.config.digest, + transportLayerDigest: transport.at(-1)!.digest, transportLayerBytes: transport.reduce((bytes, layer) => bytes + layer.size, 0), + runnerImage: { inputsDigest, transportLayerDigests: transport.map(layer => layer.digest) } }; } - if (!response.ok) { - await response.body?.cancel(); - throw Error(`runner_remote_provider_source_unavailable: HTTP ${response.status}`); - } - return response; - }; - const authentication = JSON.parse((await metadata(await request(`/token?service=ghcr.io&scope=repository:${repository}:pull`), signal)).toString()) as { token?: unknown }; - if (typeof authentication.token !== "string" || authentication.token.length < 1 || authentication.token.length > 32 * 1024) fail(); - const token = authentication.token; - const indexBytes = await metadata(await request(`/v2/${repository}/manifests/sha-${revision}`, token), signal); - const index = JSON.parse(indexBytes.toString()) as { schemaVersion: number; manifests: Array }; - if (index.schemaVersion !== 2 || !Array.isArray(index.manifests) || index.manifests.length > 32) fail(); - const candidates = index.manifests.filter(row => row.platform?.os === "linux" && row.platform.architecture === architecture); - if (candidates.length !== 1) fail(); - const child = blob(candidates[0]!, maxMetadataBytes); - const manifestBytes = await metadata(await request(`/v2/${repository}/manifests/${child.digest}`, token), signal, child); - const image = JSON.parse(manifestBytes.toString()) as Manifest; - if (image.schemaVersion !== 2 || !Array.isArray(image.layers) || image.layers.length > 128) fail(); - const configBlob = blob(image.config, maxMetadataBytes); - const configBytes = await metadata(await request(`/v2/${repository}/blobs/${configBlob.digest}`, token, true), signal, configBlob); + } + + const source = await platformImage(applicationRepository, await pullToken(applicationRepository, signal), `sha-${revision}`, architecture, signal); + const configBytes = await metadata(await request(signal, `/v2/${applicationRepository}/blobs/${source.config.digest}`, source.token, true), signal, source.config); const config = JSON.parse(configBytes.toString()) as { architecture: string; os: string; config?: { Labels?: Record }; history: Array<{ empty_layer?: boolean; created_by?: string }> }; if (config.architecture !== architecture || config.os !== "linux" || config.config?.Labels?.["org.opencontainers.image.revision"] !== revision || config.config.Labels["org.opencontainers.image.source"] !== "https://github.com/paperclipai/paperclip" || !Array.isArray(config.history) || config.history.length > 1024) fail(); const history = config.history.filter(row => !row.empty_layer); - if (history.length !== image.layers.length) fail(); + if (history.length !== source.image.layers.length) fail(); const indices = history.flatMap((row, index) => /^COPY \/provider-pack-transport\/? \/opt\/paperclip-runner\/? # buildkit$/u.test(row.created_by ?? "") ? [index] : []); if (indices.length !== 1) fail(); - const transport = blob(image.layers[indices[0]!]!, MAX_RETAINED_PACK_BYTES); - if (!["application/vnd.oci.image.layer.v1.tar+gzip", "application/vnd.docker.image.rootfs.diff.tar.gzip"].includes(transport.mediaType ?? "")) fail(); - const response = await request(`/v2/${repository}/blobs/${transport.digest}`, token, true); - if (!response.body) fail(); - let bytes = 0; - const hash = createHash("sha256"); - const meter = new Transform({ transform(chunk, _encoding, done) { - bytes += chunk.length; - hash.update(chunk); - done(bytes > transport.size ? Error("runner_remote_provider_source_size_limit") : null, chunk); - } }); - const layer = join(directory, "transport.tar.gz"); - await pipeline(Readable.fromWeb(response.body as Parameters[0]), meter, createWriteStream(layer, { flags: "wx", mode: 0o600 }), { signal }); - if (bytes !== transport.size || `sha256:${hash.digest("hex")}` !== transport.digest) fail(); - await unpackTransport(layer, directory, signal); - return { schema: "paperclip.retained-provider-pack-source.v1", sourceRevision: revision, providerPackDigest: selected.digest, - imageIndexDigest: digest(indexBytes), imageManifestDigest: child.digest, imageConfigDigest: configBlob.digest, + const transport = await receiveTransportLayer(source, source.image.layers[indices[0]!]!, "opt/paperclip-runner/", directory, unpacked, signal); + return { ...provenance, imageIndexDigest: source.indexDigest, imageManifestDigest: source.child.digest, imageConfigDigest: source.config.digest, transportLayerDigest: transport.digest, transportLayerBytes: transport.size }; } diff --git a/server/src/services/native-runtime/retained-provider-pack-source.test.ts b/server/src/services/native-runtime/retained-provider-pack-source.test.ts index 1897c08f17d..54fa96386d6 100644 --- a/server/src/services/native-runtime/retained-provider-pack-source.test.ts +++ b/server/src/services/native-runtime/retained-provider-pack-source.test.ts @@ -33,7 +33,12 @@ afterEach(async () => { await Promise.all(roots.splice(0).map(root => fs.rm(root, { recursive: true, force: true }))); }); -async function fixture(options: { wrongCode?: boolean; unsafeOverlay?: boolean; changedFileLayer?: boolean; hardlink?: "safe" | "escape" | "unknown" } = {}) { +const runnerInputs = "c".repeat(64); +type RunnerImage = "published" | "one-transport-layer" | "three-transport-layers" | "unpublished" | "token-refused" | "slim-unreachable" + | "other-inputs" | "other-revision" | "no-slim-annotation" | "slim-annotation-is-a-tag" | "slim-is-other-bytes" | "slim-not-a-prefix" | "slim-is-the-full-image" + | "nine-transport-layers" | "pack-file-in-transport"; + +async function fixture(options: { wrongCode?: boolean; unsafeOverlay?: boolean; changedFileLayer?: boolean; hardlink?: "safe" | "escape" | "unknown"; runnerImage?: RunnerImage } = {}) { const root = await fs.mkdtemp(path.join(os.tmpdir(), "retained-pack-test-")); roots.push(root); const temporary = path.join(root, "tmp"); @@ -44,6 +49,7 @@ async function fixture(options: { wrongCode?: boolean; unsafeOverlay?: boolean; await fs.mkdir(path.join(pack, "bin"), { recursive: true }); const artifact = { path: "bin/tool", sha256: `sha256:${hash(tool)}` }; const payload = { pins: { opencode: "1.18.34" }, target: { platform: "linux", architecture: "x64" }, runnerSourceRevision: source, + ...(options.runnerImage ? { runnerInputsDigest: runnerInputs } : {}), contractDigest: `sha256:${hash(tool)}`, artifacts: { nodeCommand: artifact, opencodeCommand: artifact, opencodeProxy: artifact } }; const manifest = { schema: "paperclip-runner/remote-provider-pack/v1", payload, digest: `sha256:${hash(canonicalProviderPackJson(payload))}` }; await fs.writeFile(path.join(pack, "provider-pack.json"), JSON.stringify(manifest)); @@ -81,16 +87,21 @@ async function fixture(options: { wrongCode?: boolean; unsafeOverlay?: boolean; await fs.writeFile(selected.pack + ".archive.json", JSON.stringify(receipt)); } const transportPack = options.wrongCode ? current.pack : selected.pack; - const archive = tar.pack(); - const chunks: Buffer[] = []; - const collected = (async () => { for await (const chunk of archive) chunks.push(Buffer.from(chunk)); })(); - for (const name of ["provider-pack.archive.json", ...await fs.readdir(transportPack + ".archives").then(names => names.map(name => `provider-pack.archives/${name}`))]) { - const bytes = await fs.readFile(path.join(path.dirname(transportPack), name.replace("provider-pack", path.basename(transportPack)))); - await new Promise((done, reject) => archive.entry({ name: `opt/paperclip-runner/${name}`, type: "file", size: bytes.length }, bytes, error => error ? reject(error) : done())); - } - archive.finalize(); - await collected; - const layer = gzipSync(Buffer.concat(chunks)); + const transportNames = ["provider-pack.archive.json", ...await fs.readdir(transportPack + ".archives").then(names => names.map(name => `provider-pack.archives/${name}`))]; + const transportLayer = async (prefix: string, names: string[], directories: string[] = []) => { + const archive = tar.pack(); + const chunks: Buffer[] = []; + const collected = (async () => { for await (const chunk of archive) chunks.push(Buffer.from(chunk)); })(); + for (const name of directories) await new Promise((done, reject) => archive.entry({ name: `${name}/`, type: "directory" }, error => error ? reject(error) : done())); + for (const name of names) { + const bytes = name.startsWith("provider-pack/") ? Buffer.from("{}") : await fs.readFile(path.join(path.dirname(transportPack), name.replace("provider-pack", path.basename(transportPack)))); + await new Promise((done, reject) => archive.entry({ name: `${prefix}${name}`, type: "file", size: bytes.length }, bytes, error => error ? reject(error) : done())); + } + archive.finalize(); + await collected; + return gzipSync(Buffer.concat(chunks)); + }; + const layer = await transportLayer("opt/paperclip-runner/", transportNames); const config = Buffer.from(JSON.stringify({ architecture: "amd64", os: "linux", config: { Labels: { "org.opencontainers.image.revision": selected.manifest.payload.runnerSourceRevision, "org.opencontainers.image.source": "https://github.com/paperclipai/paperclip", @@ -104,14 +115,44 @@ async function fixture(options: { wrongCode?: boolean; unsafeOverlay?: boolean; [`/v2/paperclipai/paperclip/blobs/sha256:${hash(config)}`, config], [`/v2/paperclipai/paperclip/blobs/sha256:${hash(layer)}`, layer], ]); + if (options.runnerImage && options.runnerImage !== "unpublished") { + const kind = options.runnerImage, repository = "/v2/paperclipai/paperclip-runner"; + const stable = transportNames.filter(name => /\/[0-9]+\.tar\.zst$/.test(name)), rest = transportNames.filter(name => !stable.includes(name)); + const archives = ["provider-pack.archives"]; + const transport = kind === "one-transport-layer" ? [await transportLayer("", transportNames, archives)] + : kind === "three-transport-layers" ? [await transportLayer("", stable, archives), await transportLayer("", ["provider-pack.archive.json"]), await transportLayer("", rest.slice(1), archives)] + : [await transportLayer("", stable, archives), await transportLayer("", [...rest, ...(kind === "pack-file-in-transport" ? ["provider-pack/provider-pack.json"] : [])], archives)]; + const described = (bytes: Buffer | string) => ({ digest: `sha256:${hash(bytes)}`, size: bytes.length, mediaType: "application/vnd.oci.image.layer.v1.tar+gzip" }); + const shared = [described("large pack files"), described("the rest of the pack")]; + const added = kind === "nine-transport-layers" ? Array.from({ length: 9 }, (_value, index) => described(`transport ${index}`)) : transport.map(described); + const imageOf = (layers: unknown[]) => Buffer.from(JSON.stringify({ schemaVersion: 2, config: { digest: `sha256:${hash("runner config")}`, size: 13 }, layers })); + const indexOf = (image: Buffer, annotations?: Record) => Buffer.from(JSON.stringify({ schemaVersion: 2, + manifests: [{ digest: `sha256:${hash(image)}`, size: image.length, platform: { os: "linux", architecture: "amd64" } }], ...(annotations ? { annotations } : {}) })); + const full = imageOf([...shared, ...added]); + const slim = imageOf(kind === "slim-not-a-prefix" ? [shared[1], shared[0]] : kind === "slim-is-the-full-image" ? [...shared, ...added] : shared); + const slimIndex = indexOf(slim), slimDigest = `sha256:${hash(slimIndex)}`; + const fullIndex = indexOf(full, { + "io.paperclip.runner.inputs-digest": kind === "other-inputs" ? "d".repeat(64) : runnerInputs, + "org.opencontainers.image.revision": kind === "other-revision" ? "e".repeat(40) : selected.manifest.payload.runnerSourceRevision, + ...(kind === "no-slim-annotation" ? {} : { "io.paperclip.runner.slim-digest": kind === "slim-annotation-is-a-tag" ? `inputs-${runnerInputs}-slim` : slimDigest }), + }); + routes.set(`${repository}/manifests/inputs-${runnerInputs}`, fullIndex); + routes.set(`${repository}/manifests/inputs-${runnerInputs}-slim`, slimIndex); + routes.set(`${repository}/manifests/sha256:${hash(full)}`, full); + routes.set(`${repository}/manifests/sha256:${hash(slim)}`, slim); + if (kind !== "slim-unreachable") routes.set(`${repository}/manifests/${slimDigest}`, kind === "slim-is-other-bytes" ? indexOf(slim, { moved: "true" }) : slimIndex); + for (const bytes of transport) routes.set(`${repository}/blobs/sha256:${hash(bytes)}`, bytes); + } const requests: string[] = []; const stalled = new Set(); const observers = new Map void>(); const server = createServer((request, response) => { - const route = new URL(request.url!, "http://fixture").pathname; + const url = new URL(request.url!, "http://fixture"); + const route = url.pathname; requests.push(route); - const bytes = routes.get(route); - response.writeHead(bytes ? 200 : 404, { "content-length": bytes?.length ?? 0 }); + const refused = options.runnerImage === "token-refused" && route === "/token" && url.searchParams.get("scope") === "repository:paperclipai/paperclip-runner:pull"; + const bytes = refused ? undefined : routes.get(route); + response.writeHead(bytes ? 200 : refused ? 403 : 404, { "content-length": bytes?.length ?? 0 }); response.flushHeaders(); observers.get(route)?.(); if (stalled.has(route)) return; @@ -168,6 +209,63 @@ it("installs the exact retained pack through the real uploader on an empty host expect(input.requests.some(route => route.includes("/blobs/"))).toBe(true); }); +const fromRunnerImage = (route: string) => route.startsWith("/v2/paperclipai/paperclip-runner/"); +const fromApplicationImage = (route: string) => route.startsWith("/v2/paperclipai/paperclip/"); + +async function importedSource(input: Awaited>) { + const source = await resolveProviderPackUploadSource({ root: input.current.pack, sourceDigest: input.current.manifest.digest, manifest: input.selected.manifest }); + expect(source.archiveOnly).toBe(true); + expect(JSON.parse(await fs.readFile(path.join(source.root, "provider-pack.json"), "utf8"))).toEqual(input.selected.manifest); + expect(await fs.readFile(source.root + ".archive.json")).toEqual(await fs.readFile(input.selected.pack + ".archive.json")); + for (const name of await fs.readdir(input.selected.pack + ".archives")) { + expect(await fs.readFile(path.join(source.root + ".archives", name))).toEqual(await fs.readFile(path.join(input.selected.pack + ".archives", name))); + } + return source; +} + +const transportBlobs = (input: Awaited>) => input.requests.filter(fromRunnerImage).filter(route => route.includes("/blobs/")); + +it("reads a retained pack that names its Runner image from only the layers that image adds to its slim image, and never reads the slim tag", async () => { + const input = await fixture({ runnerImage: "published" }); + const source = await importedSource(input); + expect(input.requests.filter(fromRunnerImage)).toHaveLength(6); + expect(transportBlobs(input)).toHaveLength(2); + expect(input.requests.filter(fromApplicationImage)).toEqual([]); + expect(input.requests.filter(route => route.endsWith("-slim"))).toEqual([]); + expect((await fs.readdir(path.dirname(source.root))).sort()).toEqual(["provider-pack", "provider-pack.archive.json", "provider-pack.archives"]); + const pointer = JSON.parse(await fs.readFile(path.join(path.dirname(path.dirname(source.root)), input.selected.manifest.digest.slice(7) + ".json"), "utf8")); + expect(pointer.runnerImage).toMatchObject({ inputsDigest: runnerInputs }); + expect(pointer.runnerImage.transportLayerDigests).toHaveLength(2); + expect(pointer.transportLayerDigest).toBe(pointer.runnerImage.transportLayerDigests[1]); +}); + +it.each([["one-transport-layer", 1], ["three-transport-layers", 3]] as const)("takes every layer after the slim image's, however many (%s)", async (runnerImage, layers) => { + const input = await fixture({ runnerImage }); + await importedSource(input); + expect(transportBlobs(input)).toHaveLength(layers); + expect(input.requests.filter(fromApplicationImage)).toEqual([]); +}); + +it.each(["unpublished", "token-refused", "slim-unreachable"] as const)("falls back to the application image when the Runner image cannot be read (%s)", async runnerImage => { + const input = await fixture({ runnerImage }); + const source = await importedSource(input); + expect(transportBlobs(input)).toEqual([]); + expect(input.requests.filter(fromApplicationImage).some(route => route.includes("/blobs/"))).toBe(true); + expect((await fs.readdir(path.dirname(source.root))).sort()).toEqual(["provider-pack", "provider-pack.archive.json", "provider-pack.archives"]); +}); + +it.each(["other-inputs", "other-revision", "no-slim-annotation", "slim-annotation-is-a-tag", "slim-is-other-bytes", "slim-not-a-prefix", "slim-is-the-full-image", + "nine-transport-layers", "pack-file-in-transport"] as const)( + "refuses a Runner image that does not match the pack or the layer contract, without trying another source (%s)", async runnerImage => { + const input = await fixture({ runnerImage }); + await expect(upload(input)).rejects.toThrow("runner_remote_provider_source_invalid"); + expect(input.requests.filter(fromApplicationImage)).toEqual([]); + expect(input.requests.filter(route => route.endsWith("-slim"))).toEqual([]); + if (runnerImage !== "pack-file-in-transport") expect(transportBlobs(input)).toEqual([]); + expect(input.runner.execute).not.toHaveBeenCalled(); + expect(input.runner.syncIn).not.toHaveBeenCalled(); + }); + it("keeps a matching current pack on its existing path without registry or cache reads", async () => { const input = await fixture(); await upload(input, { root: input.selected.pack, sourceDigest: input.selected.manifest.digest }); diff --git a/server/src/services/native-runtime/retained-provider-pack-source.ts b/server/src/services/native-runtime/retained-provider-pack-source.ts index f3a1f293a31..44cfc396247 100644 --- a/server/src/services/native-runtime/retained-provider-pack-source.ts +++ b/server/src/services/native-runtime/retained-provider-pack-source.ts @@ -1,6 +1,6 @@ import { createHash, randomUUID } from "node:crypto"; import { constants, createReadStream } from "node:fs"; -import { link, lstat, mkdir, mkdtemp, open, readdir, realpath, rm, statfs, unlink, writeFile } from "node:fs/promises"; +import { link, lstat, mkdir, mkdtemp, open, readdir, realpath, rm, statfs, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { basename, join } from "node:path"; import { Transform } from "node:stream"; @@ -242,7 +242,6 @@ async function importSource(cache: string, pointer: string, manifest: ProviderPa while (parent.includes("/")) { parent = parent.slice(0, parent.lastIndexOf("/")); if (overlay.files.has(parent)) fail(); } await verifyFileContents(join(archive.sourceRoot, `${index}.tar.zst`), file, signal); } - await unlink(join(directory, "transport.tar.gz")); signal.throwIfAborted(); const publication: Published = { ...provenance, entry: basename(directory), receiptSha256: digest(await readStable(root + ".archive.json")), verifiedTarPaths: true }; await writeFile(temporaryPointer, JSON.stringify(publication), { flag: "wx", mode: 0o600 }); diff --git a/tests/restart-chaos/README.md b/tests/restart-chaos/README.md index 9d2107a22ae..b2f2a52ccbf 100644 --- a/tests/restart-chaos/README.md +++ b/tests/restart-chaos/README.md @@ -1091,6 +1091,14 @@ gh api -X POST repos/paperclipai/paperclip/actions/runs//pending_deployment The digest is in the "Publish verified Daytona image" job log (`pushing manifest for …@sha256:…`), or check out the image's `org.opencontainers.image.revision`. +The harness also requires the image's provider pack to be the one a named +commit built: the commit in the image's `io.paperclip.runner.source-revision` +label, or, when the image has no such label, the image's own +`org.opencontainers.image.revision`. An image that copied its Runner names +the commit that built it in that label; an image that built its own Runner +has none. An empty label counts as absent, because an image can empty a label +of its base but cannot drop it. + **Setup** reuses runner-e2e: the bundled Daytona plugin (`installFixtureDaytonaProvider`, prepared outside the root workspace as CI does), the `daytona` environment fixture from `catalog.ts`, and the native Codex platform-qualification probe. diff --git a/tests/restart-chaos/daytona-image.test.ts b/tests/restart-chaos/daytona-image.test.ts index 05cbf50e6b6..3c437ff875a 100644 --- a/tests/restart-chaos/daytona-image.test.ts +++ b/tests/restart-chaos/daytona-image.test.ts @@ -3,7 +3,7 @@ import { chmod, mkdir, mkdtemp, readFile, readlink, rm, stat, writeFile } from " import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; -import { assertControllerMatchesImage, assertProviderPackMismatch, copyImageToDir, extractFromLayers, prepareDaytonaImageArtifacts, normalizeLayerPath, walkTar, type LayerSource } from "./daytona-image.js"; +import { RUNNER_REVISION_LABEL, assertControllerMatchesImage, assertProviderPackMismatch, copyImageToDir, extractFromLayers, prepareDaytonaImageArtifacts, normalizeLayerPath, walkTar, type LayerSource } from "./daytona-image.js"; type Entry = | { path: string; type: "file"; content: string; mode?: number } @@ -266,18 +266,18 @@ describe("prepareDaytonaImageArtifacts with a shared cache", () => { const sha = (bytes: Buffer | string) => createHash("sha256").update(bytes).digest("hex"); const revision = "a".repeat(40); - async function fakeImage(root: string): Promise { + async function fakeImage(root: string, image: { packRevision?: string; labels?: Record } = {}): Promise { const source = path.join(root, "image"); await mkdir(source, { recursive: true }); const elf = Buffer.alloc(64); elf.writeUInt32BE(0x7f454c46, 0); elf[4] = 2; elf[5] = 1; elf.writeUInt16LE(62, 18); const pack = JSON.stringify({ schema: "paperclip-runner/remote-provider-pack/v1", digest: `sha256:${"b".repeat(64)}`, - payload: { runnerSourceRevision: revision } }); + payload: { runnerSourceRevision: image.packRevision ?? revision } }); const layerBytes = tar([ { path: RUNNERD, type: "file", content: elf.toString("latin1"), mode: 0o755 }, { path: `${PACK}/provider-pack.json`, type: "file", content: pack }, ]); const config = Buffer.from(JSON.stringify({ os: "linux", architecture: "amd64", - config: { Labels: { "io.paperclip.runner.content-id": "c".repeat(64), "org.opencontainers.image.revision": revision } } })); + config: { Labels: { "io.paperclip.runner.content-id": "c".repeat(64), "org.opencontainers.image.revision": revision, ...image.labels } } })); await writeFile(path.join(source, sha(layerBytes)), layerBytes); await writeFile(path.join(source, sha(config)), config); await writeFile(path.join(source, "manifest.json"), JSON.stringify({ config: { digest: `sha256:${sha(config)}` }, @@ -312,6 +312,33 @@ cp -R "${source}/." "$dest/" } }); + async function extract(image: { packRevision?: string; labels?: Record }) { + const root = await mkdtemp(path.join(os.tmpdir(), "daytona-cache-")); + directories.push(root); + const skopeo = await fakeImage(root, image); + await writeFile(path.join(root, "barrier", "other"), ""); + return prepareDaytonaImageArtifacts({ image: `ghcr.io/paperclipai/paperclip-daytona-runner@sha256:${"9".repeat(64)}`, cacheRoot: path.join(root, "cache"), skopeo }); + } + const runnerCommit = "b".repeat(40); + + it("accepts a pack another commit built when the image names that commit as its Runner's, and reads an empty label as absent", async () => { + const receipt = await extract({ packRevision: runnerCommit, labels: { [RUNNER_REVISION_LABEL]: runnerCommit } }); + expect(receipt).toMatchObject({ sourceRevision: revision, providerPackRunnerSourceRevision: runnerCommit }); + await expect(extract({ labels: { [RUNNER_REVISION_LABEL]: "" } })).resolves.toMatchObject({ sourceRevision: revision, providerPackRunnerSourceRevision: revision }); + }); + + it.each<[string, { packRevision?: string; labels?: Record }, RegExp]>([ + ["the image names another Runner commit", { packRevision: runnerCommit, labels: { [RUNNER_REVISION_LABEL]: "e".repeat(40) } }, + /built from b{40}, but the image label io\.paperclip\.runner\.source-revision is e{40}/], + ["the image names its Runner and carries its own commit's pack", { labels: { [RUNNER_REVISION_LABEL]: runnerCommit } }, + /built from a{40}, but the image label io\.paperclip\.runner\.source-revision is b{40}/], + ["no Runner commit is named and the pack is another commit's", { packRevision: runnerCommit }, + /built from b{40}, but the image label org\.opencontainers\.image\.revision is a{40}/], + ["the Runner commit is not a full commit", { labels: { [RUNNER_REVISION_LABEL]: "bbbbbbb" } }, /io\.paperclip\.runner\.source-revision is not a full commit/], + ])("refuses the image when %s", async (_label, image, message) => { + await expect(extract(image)).rejects.toThrow(message); + }); + it("leaves a corrupt leftover in place and publishes beside it", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "daytona-cache-")); directories.push(root); diff --git a/tests/restart-chaos/daytona-image.ts b/tests/restart-chaos/daytona-image.ts index 3fd49d73591..4193402f36e 100644 --- a/tests/restart-chaos/daytona-image.ts +++ b/tests/restart-chaos/daytona-image.ts @@ -28,6 +28,7 @@ export const RUNNERD_PATH = "usr/local/bin/paperclip-runnerd"; export const PROVIDER_PACK_PATH = "opt/paperclip-runner/provider-pack"; export const CONTENT_ID_LABEL = "io.paperclip.runner.content-id"; export const REVISION_LABEL = "org.opencontainers.image.revision"; +export const RUNNER_REVISION_LABEL = "io.paperclip.runner.source-revision"; const RECEIPT_SCHEMA = "paperclip-restart-chaos/daytona-image-artifacts/v1"; const IMMUTABLE_IMAGE = /^[a-z0-9.-]+(?::[0-9]+)?\/[a-z0-9._/-]+@sha256:([0-9a-f]{64})$/; @@ -416,14 +417,17 @@ export async function prepareDaytonaImageArtifacts(input: { image: string; cache if (pack.schema !== "paperclip-runner/remote-provider-pack/v1" || !/^sha256:[0-9a-f]{64}$/.test(pack.digest ?? "")) { throw new Error("Image provider-pack.json is not a paperclip-runner/remote-provider-pack/v1 manifest"); } - if (pack.payload?.runnerSourceRevision !== sourceRevision) { - throw new Error(`Provider pack was built from ${pack.payload?.runnerSourceRevision ?? "an unknown revision"}, but the image revision label is ${sourceRevision}`); + const runnerLabel = config.config?.Labels?.[RUNNER_REVISION_LABEL] ? RUNNER_REVISION_LABEL : REVISION_LABEL; + const runnerRevision = config.config?.Labels?.[runnerLabel] ?? ""; + if (!/^[0-9a-f]{40}$/.test(runnerRevision)) throw new Error(`Image label ${runnerLabel} is not a full commit`); + if (pack.payload?.runnerSourceRevision !== runnerRevision) { + throw new Error(`Provider pack was built from ${pack.payload?.runnerSourceRevision ?? "an unknown revision"}, but the image label ${runnerLabel} is ${runnerRevision}`); } const receiptFor = (root: string): DaytonaImageArtifacts => ({ schema: RECEIPT_SCHEMA, image: input.image, platformManifestDigest: `sha256:${sha256(manifestBytes)}`, contentId, sourceRevision, runnerdPath: path.join(root, "rootfs", ...RUNNERD_PATH.split("/")), runnerdSha256: "", providerPackPath: path.join(root, "rootfs", ...PROVIDER_PACK_PATH.split("/")), providerPackManifestSha256: sha256(packBytes), - providerPackDigest: pack.digest!, providerPackRunnerSourceRevision: sourceRevision, extractedAt: new Date().toISOString(), + providerPackDigest: pack.digest!, providerPackRunnerSourceRevision: runnerRevision, extractedAt: new Date().toISOString(), }); const runnerdSha256 = await fileSha256(runnerd); const publishTo = async (root: string) => {