feat(server): read a retained provider pack from its Runner image (#21308)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Runner executes agent work in a sandbox. It needs a provider
pack of agent tools, and the server uploads that pack when the sandbox
does not have it
> - A retained session keeps the pack it started with. When that pack is
not the server's own, the server downloads the pack's transport archives
from a registry (#19779)
> - Today the server looks for them in the application image tagged
`sha-<commit that built the pack>`
> - `master` now publishes the Runner one time for each set of inputs,
as `ghcr.io/paperclipai/paperclip-runner`. A pack from that image names
the commit that published the image, and few commits get an application
image, so that tag often does not exist
> - This pull request reads such a pack from its Runner image, and keeps
the old source for every other pack and for a Runner image that cannot
be read
> - The benefit is that a retained session can still get its pack when
the pack came out of the published Runner image

## Linked Issues or Issue Description

Refs #19779 (the retained pack source), #21228 (the pack field
`runnerInputsDigest`), and #21204, #21229, #21230 (the Runner image). No
issue exists for this change.

**Problem or motivation**

`retained-provider-pack-oci.ts` reads
`ghcr.io/paperclipai/paperclip:sha-<runnerSourceRevision>`. It needs
that image to exist, to carry the pack, and to have one layer with a
known build-history line. For a pack from a published Runner image,
`runnerSourceRevision` is the commit that published the image.
`docker.yml` writes `sha-<commit>` only when its `master` run for that
commit completes, and a newer push can replace a waiting run. The
restart-chaos harness has the same assumption in another place: it
requires the pack of a sandbox image to be built by the commit in the
image's `org.opencontainers.image.revision` label.

**Proposed solution**

A pack that names its Runner image in `payload.runnerInputsDigest` is
read from `ghcr.io/paperclipai/paperclip-runner:inputs-<digest>`. A
sandbox image can name the commit that built its Runner in a label of
its own. No application image carries a pack with that field yet, and no
image carries that label, so behaviour today does not change.

**Alternatives considered**

- Keep the application image as the only source and require an
application image for every Runner publication. Publication would then
depend on `docker.yml`, which serves one ref at a time.
- Take a fixed number of layers ("the image has four, take the last
two"). A server in the field cannot be changed when the image gets
another layer. The server now uses the rule that holds for any number of
layers: the full image is the slim image plus transport layers.
- Fall back to the application image for every failure of the Runner
image. A Runner image that exists and does not match the pack is a
fault, and a second source would hide it.

**Roadmap alignment**

This is build and runtime infrastructure. It adds no product feature and
does not overlap an item in `ROADMAP.md`.

This is part 3 of 4 of a stack ([stack
#21309](https://github.com/paperclipai/paperclip/stack/21309)). Merge
the parts in order:

1. #21306: the resolver and the no-rebuild mode
2. #21307: the report-only job in `docker.yml` and the pull-request
check of the application image's Runner path
3. #21308: reading a retained provider pack from its Runner image (this
pull request)
4. #21310: a registry build cache for the Runner image build

This pull request uses no code from parts 1 and 2. It is stacked on them
because all four parts edit `doc/runner-image-contract.md`.

## What Changed

- `server/src/services/native-runtime/retained-provider-pack-oci.ts`,
for a pack whose `payload.runnerInputsDigest` is 64 hexadecimal
characters:
- The server reads the full index `inputs-<digest>` of the Runner image.
The index must carry `io.paperclip.runner.inputs-digest` equal to the
pack's value, `org.opencontainers.image.revision` equal to the pack's
`runnerSourceRevision`, and a valid digest in
`io.paperclip.runner.slim-digest`.
- It reads the slim index by that digest, never by the slim tag, and
checks the bytes it gets against the digest.
- For the pack's platform, the layer digests of the slim image must be
the first layer digests of the full image, in the same order. The layers
after them are the transport layers. There must be at least one and at
most eight, and their total size has the existing limit.
- The server downloads only those layers. It checks each against its
descriptor and refuses every entry that is not a transport archive, the
receipt or the `provider-pack.archives` directory. A file may not be in
two layers.
- When the Runner image cannot be read, the server reads the application
image as before. That covers a registry error status for the token, for
either index or for either manifest: for example 404 for a tag or a slim
index that does not exist. Nothing is written before that point.
- A Runner image that can be read and does not match fails with
`runner_remote_provider_source_invalid`. The server does not try the
application image then.
- The same file, for every other pack: the old path, unchanged in what
it checks. Its code moved into functions that both paths use (`request`,
`pullToken`, `platformImage`, `receiveTransportLayer`).
- The downloaded layer file is removed as soon as it is unpacked.
Before, the importer removed it after its checks, so
`retained-provider-pack-source.ts` loses that one line.
- The cache record gets an optional `runnerImage` field with the inputs
digest and the digests of the transport layers. `transportLayerDigest`
is the last of them and `transportLayerBytes` their total. An older
server ignores the new field.
- `tests/restart-chaos/daytona-image.ts`: when the image has a non-empty
label `io.paperclip.runner.source-revision`, the pack must be built by
that commit. Otherwise the pack must be built by the commit in
`org.opencontainers.image.revision`, as before. The receipt field
`providerPackRunnerSourceRevision` records the pack's commit.
- `doc/runner-image-contract.md` has a new section, "Reading the
transport archives alone". `tests/restart-chaos/README.md` describes the
label.

One choice needs a reviewer's eye. When the full index can be read and
the slim index cannot (a registry error status), the server falls back
to the application image; it does not fail. Without the slim manifest
the server cannot tell which layers are transport layers, so it has not
accepted any byte of the Runner image, and the old source has its own
complete checks. A slim index that is read and has other bytes than its
digest still fails.

## Verification

Linux (`node:24.22.3-bookworm`, GNU tar 1.34, zstd 1.5.4, the worktree
mounted read-only):

- In `server/`: `retained-provider-pack-source.test.ts` (34 tests, 15 of
them new), `provider-pack-archive.test.ts`,
`remote-provider-pack-verification.test.ts`,
`remote-provider-pack.test.ts`: 127 tests pass in 4 files.
- `node node_modules/vitest/vitest.mjs run --config
tests/restart-chaos/vitest.config.ts
tests/restart-chaos/daytona-image.test.ts`: 25 tests pass, 5 of them
new.

macOS (Node 26.12.0):

- `daytona-image.test.ts`: 25 tests pass.
- `retained-provider-pack-source.test.ts`: the 15 new tests pass. Six
older tests fail, with and without this change. They run the real
uploader, which needs GNU tar, and this host has bsdtar.
- `tsc` on the two changed server files and the test, and on the two
restart-chaos files, with the settings of their test projects: no error.

The new cases:

- Read from the Runner image with 6 registry requests (two indexes, two
manifests, two layers), none to the application image and none for the
slim tag.
- Take every layer after the slim image's: one transport layer, and
three.
- Fall back when the tag does not exist, when the token is refused, and
when the slim index cannot be reached.
- Refuse, with no request to the application image: an index for other
inputs, an index for another revision, no slim annotation, a slim
annotation that is a tag, a slim index with other bytes than its digest,
a slim image that is not a prefix of the full image, a slim image equal
to the full image, nine transport layers, and a transport layer that
holds a pack file.
- Four deliberate faults in the reader each make a test fail: the slim
index bytes are not checked, no prefix check, the slim annotation is not
validated, and no bounds on the number of transport layers.

A real run, in the same Linux container (`linux/arm64`), with no
credential:

- The script took `provider-pack/provider-pack.json` of `linux/arm64`
from the published image
`ghcr.io/paperclipai/paperclip-runner:inputs-0e6662ad9c8c6451556c76bf326723645d4afaab2decc73cd5e0025f7dd8d1ca`.
Pack digest
`sha256:604c29cb32a181843cc4d425871f88c0e65c8185b0a158c801fda4eb1bfce52f`,
`runnerSourceRevision` `25e9a9c2e9277f3be8649be8c809cc81bde6f0c5`.
- `resolveProviderPackUploadSource`, with another pack as the server's
own, returned `{ archiveOnly: true }` after 23 seconds. That function
calls `receiveRetainedProviderPack` and then the importer's checks: the
manifest inside the overlay archive is the selected manifest, every
archive matches the receipt, and the content of every file archive
matches the digest of its file.
- The server code made 9 requests: one anonymous token request, the full
index, the `arm64` manifest, the slim index `sha256:f63ea436…4f3c` by
digest, its `arm64` manifest, and two layers, each with one redirect. No
request went to the application image.
- The cache record:

  ```json
  {
    "schema": "paperclip.retained-provider-pack-source.v1",
    "sourceRevision": "25e9a9c2e9277f3be8649be8c809cc81bde6f0c5",
"providerPackDigest":
"sha256:604c29cb32a181843cc4d425871f88c0e65c8185b0a158c801fda4eb1bfce52f",
"imageIndexDigest":
"sha256:84f2c051aa4ed16c5cc138c08e3533fa417e92177f7d15af5f2aa3e0ba467162",
"imageManifestDigest":
"sha256:73dbe864fbab6208616f0aa6f1610a7ece4ef22f68a73d30901cbaea60139589",
"imageConfigDigest":
"sha256:740e48463d5caf0bfead4b923cdbd8b220acb93d058419c3db9d00c7f1831d65",
"transportLayerDigest":
"sha256:35433b9f788641666b470f41c37fef9fc9b872262b7edd5bd79f0e288f75bcdf",
    "transportLayerBytes": 426602696,
    "runnerImage": {
"inputsDigest":
"0e6662ad9c8c6451556c76bf326723645d4afaab2decc73cd5e0025f7dd8d1ca",
      "transportLayerDigests": [

"sha256:6a340088ca2cfa85f10f0385d9c8f5cdccb22c3a2bbb2062620b1d90616ba5b5",

"sha256:35433b9f788641666b470f41c37fef9fc9b872262b7edd5bd79f0e288f75bcdf"
      ]
    },
"receiptSha256":
"2afdd26645845369d9e851b1e6e2884eb6c3884ea7c4866a1eeb2efb9fb230d7",
    "verifiedTarPaths": true
  }
  ```

- `uploadVerifiedProviderPack` then installed the pack from that source
through a local stand-in for the sandbox, with no further registry
request, in 4 seconds. The installed tree is 1,249,060,841 bytes. Its
`provider-pack.json` is the selected manifest, all 7 artifacts of the
manifest have the digest the manifest names, and the pack's own Node
prints `v24.22.3`.

Never run:

- The same real run for `linux/amd64`, whose transport layers are about
1 GB.
- A session in a real sandbox. The real run used a local stand-in for
the sandbox.
- The fallback against the real registry. Fixtures cover it.
- The full test suite and the full typecheck. CI must supply them.

## Risks

- The old path was moved into shared functions. Its checks are the same,
and its 19 existing tests pass on Linux, but a review must read that
code as changed.
- The layer file of the old path is now removed before the importer's
checks, not after them. The importer does not read it.
- The reader depends on two rules of the image contract: the full index
names its slim index, and the full image starts with the slim image's
layers. A Runner image that breaks either rule is refused, with no
fallback.
- The fallback covers a registry error status only. A network error ends
the import, as it does today.
- The label `io.paperclip.runner.source-revision` is new and no image
carries it yet. The change to the sandbox image that sets it must use
this name.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Fable 5.2 (`claude-fable-5-2`), Anthropic, used through Claude
Code with tool use (shell, file edits, local Docker builds).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Nicky LeachandClaude Fable 5.2 authored and GitHub committed 2026-11-12 23:02:19 -08:00
1 parent 0477f622d6
commit 23c2343015
7 files changed
+304 -86

No files matched your search

+32
View File
@@ -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-<digest>` (`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-<runnerSourceRevision>`, 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
@@ -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<string, string>; manifests: Array<Blob & { platform?: { os?: string; architecture?: string } }> };
type Unpacked = { files: Set<string>; 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<string>();
let bytes = 0;
const directories = new Set<string>();
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<typeof Readable.fromWeb>[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<Blob & { platform?: { os?: string; architecture?: string } }> };
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<string, string> }; 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<typeof Readable.fromWeb>[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 };
}
@@ -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<void>((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<void>((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<void>((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<string, string>) => 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<string>();
const observers = new Map<string, () => 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<ReturnType<typeof fixture>>) {
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<ReturnType<typeof fixture>>) => 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 });
@@ -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 });
+8
View File
@@ -1091,6 +1091,14 @@ gh api -X POST repos/paperclipai/paperclip/actions/runs/<run>/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.
+31 -4
View File
@@ -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<string> {
async function fakeImage(root: string, image: { packRevision?: string; labels?: Record<string, string> } = {}): Promise<string> {
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<string, string> }) {
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<string, string> }, 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);
+7 -3
View File
@@ -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) => {