Skip to content

tsbox pull: an OCI registry over HTTP

tsbox run alpine:3.20 needs the files of that image on disk first. An image is not one download: it is a few small JSON documents and some compressed tarballs (layers), all served by a registry over plain HTTPS. The first version of tsbox pull trusted every byte. A mirror served a tampered layer and nothing noticed, and a digest string sha256:../../etc/x from a hostile manifest was joined into a file path.

This lesson builds the parts of the pull that are pure functions of bytes and JSON, and a pull that takes its fetch and its blob store as arguments, so every test runs against recorded fixtures with no network.

The OCI distribution protocol is small. Pulling library/alpine:3.20 from a registry goes like this:

Terminal window
GET /v2/library/alpine/manifests/3.20 # 401 + WWW-Authenticate header
GET <realm>?service=...&scope=... # the token endpoint: {"token": "..."}
GET /v2/library/alpine/manifests/3.20 # again, with Authorization: Bearer <token>
GET /v2/library/alpine/manifests/sha256:<arm64 manifest digest>
GET /v2/library/alpine/blobs/sha256:<layer digest> # once per config and layer

Public images still need a token: the registry just hands one out to anyone. The 401 tells the client where.

The 401 response carries a header like this one:

Terminal window
www-authenticate: Bearer realm="https://auth.registry.test/token",service="registry.test",scope="repository:library/alpine:pull"

realm is where to ask for a token, and service and scope are query parameters for that request. The header is text from the network, so parse it defensively: a Basic challenge is an error, and a header with no realm is an error, not a request to undefined.

interface Challenge {
readonly realm: string
readonly service: string | undefined
readonly scope: string | undefined
}
function parseChallenge(header: string): Challenge | undefined {
const match = /^Bearer\s+(.*)$/i.exec(header.trim())
if (match === null) return undefined
const params = new Map<string, string>()
for (const [, key, value] of (match[1] ?? "").matchAll(/(\w+)="([^"]*)"/g)) {
if (key !== undefined && value !== undefined) params.set(key, value)
}
const realm = params.get("realm")
return realm === undefined ? undefined : { realm, service: params.get("service"), scope: params.get("scope") }
}

Splitting on , would break a scope like repository:x:pull,push: quoted values may contain commas. That is why the pattern matches key="value" pairs instead. The exercise returns a Result with a message instead of undefined (errors as values).

A tag points at one of two shapes, and the mediaType field says which:

  • An image index (OCI) or manifest list (Docker): a list of platform entries, each with a digest of the manifest for that platform. alpine:3.20 is one of these, so one tag works on amd64 and arm64.
  • An image manifest: a config descriptor and a list of layers, each { mediaType, digest, size }.

Both exist in an OCI and a Docker flavor, four media types in all, so the decoder accepts four. Model the result as a union you can narrow on (discriminated unions):

interface Descriptor {
readonly mediaType: string
readonly digest: string
readonly size: number
}
interface Platform {
readonly os: string
readonly architecture: string
readonly variant?: string
}
type Manifest =
| { readonly _tag: "Index"; readonly manifests: readonly (Descriptor & { readonly platform: Platform })[] }
| { readonly _tag: "Image"; readonly config: Descriptor; readonly layers: readonly Descriptor[] }
declare const manifest: Manifest
if (manifest._tag === "Index") {
console.log(manifest.manifests.length) // only an index has platform entries
} else {
console.log(manifest.layers.length) // only an image has layers
}

The JSON arrives as unknown. There is no schema library: decode it by hand, field by field, as in parsing and validation at the trust boundary, and report the path of the first bad field, for example manifest.layers[1].digest: expected sha256 digest. A registry is a network peer; its documents are as untrusted as a webhook body.

Real indexes contain entries you must skip. Recent Docker images list “attestation” manifests with platform unknown/unknown. Picking a platform by exact os and architecture skips them without any special case. Ignore variant for arm64 (v8 is the only one that exists in practice).

Everything in a registry is addressed by its digest: sha256: and 64 hex characters of the SHA-256 of the exact bytes. That gives a rule that makes mirrors and caches safe: fetch by digest, hash what you got, compare, and only then use it.

function digestOf(bytes: Uint8Array): string {
return `sha256:${new Bun.CryptoHasher("sha256").update(bytes).digest("hex")}`
}
// The web-standard version (async, no Bun API):
async function digestOfWeb(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
const hash = await crypto.subtle.digest("SHA-256", bytes)
return `sha256:${new Uint8Array(hash).toHex()}`
}

A tag (3.20) is a mutable name: you cannot verify the bytes you get for a tag. But the index you got lists the digest of each platform manifest, and each manifest lists the digest of each layer, so everything after the first request is verified, as a chain. A pull that checks the layers but forgets the platform manifest has an unverified link, and the tests include exactly that case.

Hash before writing. A file that was written and then found wrong still has to be deleted, and a crash in between leaves a poisoned cache.

Blobs are stored under their own digest: <root>/blobs/sha256/<hex>. Two images that share a base layer share one file, and “do I have this layer?” is a stat. This is the layout the OCI image layout specification uses.

The digest is data from a manifest, and it becomes part of a path. Validate it with the same strict pattern before joining it (/^sha256:[0-9a-f]{64}$/). sha256:../../../etc/cron.d/x must be an error, not a path:

const DIGEST = /^sha256:[0-9a-f]{64}$/
function blobPath(root: string, digest: string): string | undefined {
return DIGEST.test(digest) ? `${root}/blobs/sha256/${digest.slice("sha256:".length)}` : undefined
}

pull needs two capabilities: an HTTP client and a place to put blobs. Both are arguments (ports). The fetch type is just the part of fetch you use, so a function that returns new Response(...) satisfies it, and so does the real one:

type FetchFn = (url: string, init?: { headers?: Record<string, string> }) => Promise<Response>
interface BlobStore {
has(digest: string): Promise<boolean>
put(digest: string, bytes: Uint8Array): Promise<void>
}
const real: FetchFn = fetch // the global fetch is assignable: it accepts more than FetchFn asks for

The flow inside is the five requests above, with one rule per step: keep the token after the first 401 and reuse it for every later request; choose the platform from an index and fetch that manifest by digest; skip blobs the store already has; verify each blob before put; turn every failure into a value (Auth, Http, Decode, Platform, Digest) and return it. Nothing throws on bad input from the network.

fixtures.ts is a fake registry that answers the same URLs, including the 401 and the token endpoint, and can corrupt one blob on request.

The tests never touch a network. To pull a real image, call your pull with the global fetch and a store backed by files. This works on macOS and Linux (it needs network access and downloads about 3 MB). Docker Hub’s registry host is registry-1.docker.io:

import { mkdirSync } from "node:fs"
import { blobPath, pull } from "./main.ts"
const root = `${process.env.HOME}/.local/share/tsbox`
const store = {
has: async (digest) => {
const path = blobPath(root, digest)
return path.ok && (await Bun.file(path.value).exists())
},
put: async (digest, bytes) => {
const path = blobPath(root, digest)
if (!path.ok) throw new Error(path.error)
mkdirSync(`${root}/blobs/sha256`, { recursive: true })
await Bun.write(path.value, bytes)
},
}
const ref = { registry: "registry-1.docker.io", repository: "library/alpine", tag: "3.20" }
console.log(await pull({ fetch, store }, ref, { os: "linux", architecture: "arm64" }))

Run it twice: the second time every blob is in cached. Pick arm64 or amd64 to match the Linux VM you will use in lesson 4: the platform is the container’s, not your Mac’s, because the VM runs Linux on your CPU.

Local, because it is a few files. Copy fixtures.ts unchanged, main.starter.ts as main.ts, and the tests, into the Relay project from tooling. Run bun test. The starter has the types and stubs that throw.

Write parseChallenge, decodeManifest, pickPlatform, digestOf, verifyDigest, blobPath and pull. The tests cover both manifest flavors, error paths, an attestation entry, the exact request order (anonymous, token, authorized retry, then authorized only), a cache hit, a tampered layer that must not reach the store, and a tampered platform manifest.

main.ts
// `tsbox pull alpine:3.20` talks to an OCI registry over HTTPS. The first draft trusted whatever came
// back: a mirror served a tampered layer, and a digest like "sha256:../../etc/x" became a file path.
// Build the pure parts, then `pull` on top of them. Everything arrives as `unknown` or text and is
// checked by hand; fixtures.ts holds a fake registry, so nothing here touches the network.
//
// Rules:
// - parseChallenge(header): a `Bearer realm="...",service="...",scope="..."` header. Values are quoted
// and may contain commas. Errors: "not a Bearer challenge", "challenge has no realm".
// - decodeManifest(u): `mediaType` decides the shape. OCI and Docker index/list types give Index (with a
// platform per entry, `variant` optional), OCI and Docker manifest types give Image (config + layers).
// Digests must match sha256:<64 hex>. Errors name the first bad path, for example
// "manifest.layers[1].digest: expected sha256 digest", "manifest: expected object",
// 'manifest.mediaType: unsupported "text/html"'.
// - pickPlatform(index, { os, architecture }): the descriptor for that platform, ignoring `variant`.
// Error: "no manifest for linux/riscv64".
// - digestOf(bytes) is "sha256:<hex>". verifyDigest(bytes, expected) errors:
// "unsupported digest algorithm: sha512", "malformed digest: <expected>",
// "digest mismatch: expected <expected>, got <actual>".
// - blobPath(root, digest): `<root>/blobs/sha256/<hex>`; a digest that is not plain sha256:<64 hex>
// is "malformed digest: <digest>" (never build a path from it).
// - pull(deps, ref, platform): GET https://<registry>/v2/<repository>/manifests/<tag>. On 401 read
// WWW-Authenticate, GET the token from realm?service=...&scope=..., then retry with
// `authorization: Bearer <token>` and keep using it. Choose the platform from an index and fetch
// that manifest BY DIGEST, verified against the digest in the index. Then fetch config and layers
// from /blobs/<digest>, skipping ones `store.has`, verifying each before `store.put`.
// Errors: { _tag: "Auth" | "Http" | "Decode" | "Platform" | "Digest", message }.
// Success: { manifestDigest (of the image manifest), fetched, cached } in config-then-layers order.
export type Result<T, E> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: E }
export interface Challenge {
readonly realm: string
readonly service: string | undefined
readonly scope: string | undefined
}
export function parseChallenge(_header: string): Result<Challenge, string> {
throw new Error("not implemented")
}
export interface Descriptor {
readonly mediaType: string
readonly digest: string
readonly size: number
}
export interface Platform {
readonly os: string
readonly architecture: string
readonly variant?: string
}
export type Manifest =
| { readonly _tag: "Index"; readonly manifests: readonly (Descriptor & { readonly platform: Platform })[] }
| { readonly _tag: "Image"; readonly config: Descriptor; readonly layers: readonly Descriptor[] }
export function decodeManifest(_u: unknown): Result<Manifest, string> {
throw new Error("not implemented")
}
export function pickPlatform(
_index: Extract<Manifest, { _tag: "Index" }>,
_want: { readonly os: string; readonly architecture: string },
): Result<Descriptor, string> {
throw new Error("not implemented")
}
export function digestOf(_bytes: Uint8Array): string {
throw new Error("not implemented")
}
export function verifyDigest(_bytes: Uint8Array, _expected: string): Result<true, string> {
throw new Error("not implemented")
}
export function blobPath(_root: string, _digest: string): Result<string, string> {
throw new Error("not implemented")
}
export type FetchFn = (url: string, init?: { headers?: Record<string, string> }) => Promise<Response>
export interface BlobStore {
has(digest: string): Promise<boolean>
put(digest: string, bytes: Uint8Array): Promise<void>
}
export interface ImageRef {
readonly registry: string
readonly repository: string
readonly tag: string
}
export interface PullError {
readonly _tag: "Auth" | "Http" | "Decode" | "Platform" | "Digest"
readonly message: string
}
export interface Pulled {
readonly manifestDigest: string
readonly fetched: readonly string[]
readonly cached: readonly string[]
}
export async function pull(
_deps: { readonly fetch: FetchFn; readonly store: BlobStore },
_ref: ImageRef,
_platform: { readonly os: string; readonly architecture: string },
): Promise<Result<Pulled, PullError>> {
throw new Error("not implemented")
}
fixtures.ts
const encoder = new TextEncoder()
function sha256(bytes: Uint8Array): string {
return `sha256:${new Bun.CryptoHasher("sha256").update(bytes).digest("hex")}`
}
export const REGISTRY = "registry.test"
export const REPOSITORY = "library/alpine"
export const TAG = "3.20"
export const TOKEN = "t0k3n"
export const OCI_INDEX = "application/vnd.oci.image.index.v1+json"
export const OCI_MANIFEST = "application/vnd.oci.image.manifest.v1+json"
export const CHALLENGE_HEADER = `Bearer realm="https://auth.${REGISTRY}/token",service="${REGISTRY}",scope="repository:${REPOSITORY}:pull"`
export interface Blob {
readonly bytes: Uint8Array<ArrayBuffer>
readonly digest: string
}
function blob(text: string): Blob {
const bytes = encoder.encode(text)
return { bytes, digest: sha256(bytes) }
}
function image(architecture: string) {
const config = blob(JSON.stringify({ architecture, os: "linux", rootfs: { type: "layers" } }))
const layers = [blob(`${architecture}: base layer`), blob(`${architecture}: app layer`)]
const manifest = blob(
JSON.stringify({
schemaVersion: 2,
mediaType: OCI_MANIFEST,
config: { mediaType: "application/vnd.oci.image.config.v1+json", digest: config.digest, size: config.bytes.length },
layers: layers.map((l) => ({
mediaType: "application/vnd.oci.image.layer.v1.tar+gzip",
digest: l.digest,
size: l.bytes.length,
})),
}),
)
return { config, layers, manifest }
}
export const AMD64 = image("amd64")
export const ARM64 = image("arm64")
export const INDEX_JSON: unknown = {
schemaVersion: 2,
mediaType: OCI_INDEX,
manifests: [
{ mediaType: OCI_MANIFEST, digest: AMD64.manifest.digest, size: AMD64.manifest.bytes.length, platform: { architecture: "amd64", os: "linux" } },
{ mediaType: OCI_MANIFEST, digest: ARM64.manifest.digest, size: ARM64.manifest.bytes.length, platform: { architecture: "arm64", os: "linux", variant: "v8" } },
{ mediaType: OCI_MANIFEST, digest: sha256(encoder.encode("attestation")), size: 11, platform: { architecture: "unknown", os: "unknown" } },
],
}
export const INDEX_BYTES = encoder.encode(JSON.stringify(INDEX_JSON))
export const INDEX_DIGEST = sha256(INDEX_BYTES)
export const IMAGE_JSON: unknown = JSON.parse(new TextDecoder().decode(ARM64.manifest.bytes))
export interface RegistryRequest {
readonly url: string
readonly authorized: boolean
}
export function fakeRegistry(options: { readonly corrupt?: string } = {}) {
const requests: RegistryRequest[] = []
const blobs = new Map<string, Uint8Array<ArrayBuffer>>()
for (const img of [AMD64, ARM64]) {
for (const b of [img.config, ...img.layers]) blobs.set(b.digest, b.bytes)
blobs.set(img.manifest.digest, img.manifest.bytes)
}
const fetchFn = async (url: string, init?: { headers?: Record<string, string> }): Promise<Response> => {
const authorized = init?.headers?.["authorization"] === `Bearer ${TOKEN}`
requests.push({ url, authorized })
const u = new URL(url)
if (u.hostname === `auth.${REGISTRY}`) {
const ok = u.searchParams.get("service") === REGISTRY && u.searchParams.get("scope") === `repository:${REPOSITORY}:pull`
return ok ? Response.json({ token: TOKEN, expires_in: 300 }) : new Response("bad scope", { status: 400 })
}
if (!authorized) {
return new Response("unauthorized", { status: 401, headers: { "www-authenticate": CHALLENGE_HEADER } })
}
const prefix = `/v2/${REPOSITORY}/`
if (!u.pathname.startsWith(prefix)) return new Response("not found", { status: 404 })
const [kind, ref = ""] = u.pathname.slice(prefix.length).split("/")
if (kind === "manifests" && ref === TAG) {
return new Response(INDEX_BYTES, { headers: { "content-type": OCI_INDEX, "docker-content-digest": INDEX_DIGEST } })
}
const bytes = blobs.get(ref)
if (bytes === undefined) return new Response("not found", { status: 404 })
if (ref === options.corrupt) return new Response(encoder.encode("tampered"))
return new Response(bytes)
}
return { fetch: fetchFn, requests }
}
main.test.ts
import { expect, test } from "bun:test"
import { AMD64, ARM64, CHALLENGE_HEADER, IMAGE_JSON, INDEX_JSON, REGISTRY, REPOSITORY, TAG, fakeRegistry } from "./fixtures.ts"
import { blobPath, decodeManifest, digestOf, parseChallenge, pickPlatform, pull, verifyDigest } from "./main.ts"
import type { BlobStore } from "./main.ts"
function memoryStore(initial: readonly string[] = []) {
const blobs = new Map<string, Uint8Array>(initial.map((d) => [d, new Uint8Array()]))
const store: BlobStore & { blobs: typeof blobs } = {
blobs,
has: async (digest) => blobs.has(digest),
put: async (digest, bytes) => void blobs.set(digest, bytes),
}
return store
}
const ref = { registry: REGISTRY, repository: REPOSITORY, tag: TAG }
const arm64 = { os: "linux", architecture: "arm64" }
test("parseChallenge reads realm, service and scope, even with commas inside quotes", () => {
expect(parseChallenge(CHALLENGE_HEADER)).toEqual({
ok: true,
value: { realm: `https://auth.${REGISTRY}/token`, service: REGISTRY, scope: `repository:${REPOSITORY}:pull` },
})
const multi = parseChallenge('Bearer realm="https://a/token",scope="repository:x:pull,push"')
expect(multi).toEqual({ ok: true, value: { realm: "https://a/token", service: undefined, scope: "repository:x:pull,push" } })
})
test("parseChallenge rejects Basic challenges and a missing realm", () => {
expect(parseChallenge('Basic realm="registry"')).toEqual({ ok: false, error: "not a Bearer challenge" })
expect(parseChallenge('Bearer service="registry.test"')).toEqual({ ok: false, error: "challenge has no realm" })
})
test("decodeManifest tells an index from an image by mediaType", () => {
const index = decodeManifest(INDEX_JSON)
expect(index.ok && index.value._tag).toBe("Index")
if (index.ok && index.value._tag === "Index") {
expect(index.value.manifests.length).toBe(3)
expect(index.value.manifests[1]?.platform).toEqual({ os: "linux", architecture: "arm64", variant: "v8" })
expect(index.value.manifests[0]?.platform).toEqual({ os: "linux", architecture: "amd64" })
}
const image = decodeManifest(IMAGE_JSON)
expect(image.ok && image.value._tag).toBe("Image")
if (image.ok && image.value._tag === "Image") {
expect(image.value.config.digest).toBe(ARM64.config.digest)
expect(image.value.layers.map((l) => l.digest)).toEqual(ARM64.layers.map((l) => l.digest))
}
})
test("decodeManifest accepts the Docker media types too", () => {
const docker = { ...(IMAGE_JSON as object), mediaType: "application/vnd.docker.distribution.manifest.v2+json" }
const result = decodeManifest(docker)
expect(result.ok && result.value._tag).toBe("Image")
})
test("decodeManifest reports the path of the first bad field", () => {
expect(decodeManifest("nope")).toEqual({ ok: false, error: "manifest: expected object" })
expect(decodeManifest({ mediaType: "text/html" })).toEqual({ ok: false, error: 'manifest.mediaType: unsupported "text/html"' })
const badLayer = {
...(IMAGE_JSON as object),
layers: [(IMAGE_JSON as { layers: unknown[] }).layers[0], { mediaType: "x", digest: "sha256:zz", size: 1 }],
}
expect(decodeManifest(badLayer)).toEqual({ ok: false, error: "manifest.layers[1].digest: expected sha256 digest" })
const badPlatform = {
...(INDEX_JSON as object),
manifests: [{ mediaType: "x", digest: AMD64.manifest.digest, size: 1, platform: { os: "linux" } }],
}
expect(decodeManifest(badPlatform)).toEqual({ ok: false, error: "manifest.manifests[0].platform.architecture: expected string" })
})
test("pickPlatform finds linux/arm64 and skips the attestation entry", () => {
const index = decodeManifest(INDEX_JSON)
if (!index.ok || index.value._tag !== "Index") throw new Error("fixture must decode")
const picked = pickPlatform(index.value, arm64)
expect(picked.ok && picked.value.digest).toBe(ARM64.manifest.digest)
const amd = pickPlatform(index.value, { os: "linux", architecture: "amd64" })
expect(amd.ok && amd.value.digest).toBe(AMD64.manifest.digest)
expect(pickPlatform(index.value, { os: "linux", architecture: "riscv64" })).toEqual({
ok: false,
error: "no manifest for linux/riscv64",
})
expect(pickPlatform(index.value, { os: "unknown", architecture: "arm64" }).ok).toBe(false)
})
test("verifyDigest accepts the right bytes and names the problem otherwise", () => {
const bytes = new TextEncoder().encode("hello")
const digest = digestOf(bytes)
expect(digest).toBe("sha256:2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824")
expect(verifyDigest(bytes, digest)).toEqual({ ok: true, value: true })
const bad = verifyDigest(new TextEncoder().encode("hellp"), digest)
expect(bad.ok).toBe(false)
if (!bad.ok) expect(bad.error.startsWith(`digest mismatch: expected ${digest}, got sha256:`)).toBe(true)
expect(verifyDigest(bytes, "sha512:abcd")).toEqual({ ok: false, error: "unsupported digest algorithm: sha512" })
expect(verifyDigest(bytes, "sha256:abcd")).toEqual({ ok: false, error: "malformed digest: sha256:abcd" })
})
test("blobPath is content-addressed and refuses path tricks", () => {
const hex = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
expect(blobPath("/var/tsbox", `sha256:${hex}`)).toEqual({ ok: true, value: `/var/tsbox/blobs/sha256/${hex}` })
expect(blobPath("/var/tsbox", "sha256:../../../etc/passwd")).toEqual({ ok: false, error: "malformed digest: sha256:../../../etc/passwd" })
})
test("pull does the token dance once, picks arm64, and stores config and layers", async () => {
const registry = fakeRegistry()
const store = memoryStore()
const result = await pull({ fetch: registry.fetch, store }, ref, arm64)
expect(result).toEqual({
ok: true,
value: {
manifestDigest: ARM64.manifest.digest,
fetched: [ARM64.config.digest, ...ARM64.layers.map((l) => l.digest)],
cached: [],
},
})
expect([...store.blobs.keys()].sort()).toEqual([ARM64.config.digest, ...ARM64.layers.map((l) => l.digest)].sort())
expect(store.blobs.get(ARM64.layers[0]?.digest ?? "")).toEqual(ARM64.layers[0]?.bytes)
const urls = registry.requests.map((r) => `${r.authorized ? "auth" : "anon"} ${r.url.replace(`https://`, "")}`)
expect(urls[0]).toBe(`anon ${REGISTRY}/v2/${REPOSITORY}/manifests/${TAG}`)
expect(urls[1]).toBe(`anon auth.${REGISTRY}/token?service=${REGISTRY}&scope=repository%3A${encodeURIComponent(REPOSITORY)}%3Apull`)
expect(urls[2]).toBe(`auth ${REGISTRY}/v2/${REPOSITORY}/manifests/${TAG}`)
expect(urls.length).toBe(2 + 1 + 1 + 3)
expect(urls.slice(3).every((u) => u.startsWith("auth "))).toBe(true)
})
test("pull skips blobs the store already has", async () => {
const store = memoryStore([ARM64.layers[0]?.digest ?? ""])
const result = await pull({ fetch: fakeRegistry().fetch, store }, ref, arm64)
expect(result.ok && result.value.cached).toEqual([ARM64.layers[0]?.digest ?? ""])
expect(result.ok && result.value.fetched.length).toBe(2)
})
test("pull refuses a blob whose bytes do not match its digest and stores nothing for it", async () => {
const bad = ARM64.layers[1]?.digest ?? ""
const store = memoryStore()
const result = await pull({ fetch: fakeRegistry({ corrupt: bad }).fetch, store }, ref, arm64)
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.error._tag).toBe("Digest")
expect(result.error.message.startsWith(`digest mismatch: expected ${bad}`)).toBe(true)
}
expect(store.blobs.has(bad)).toBe(false)
})
test("pull verifies the platform manifest against the digest in the index", async () => {
const registry = fakeRegistry({ corrupt: ARM64.manifest.digest })
const result = await pull({ fetch: registry.fetch, store: memoryStore() }, ref, arm64)
expect(result.ok).toBe(false)
if (!result.ok) expect(result.error._tag).toBe("Digest")
})
test("pull reports a missing platform and a missing tag", async () => {
const noPlatform = await pull({ fetch: fakeRegistry().fetch, store: memoryStore() }, ref, { os: "linux", architecture: "s390x" })
expect(noPlatform).toEqual({ ok: false, error: { _tag: "Platform", message: "no manifest for linux/s390x" } })
const noTag = await pull({ fetch: fakeRegistry().fetch, store: memoryStore() }, { ...ref, tag: "nope" }, arm64)
expect(noTag.ok).toBe(false)
if (!noTag.ok) expect(noTag.error._tag).toBe("Http")
})
  • Pulling is five kinds of request: manifest, 401 challenge, token, platform manifest, blobs.
  • Parse WWW-Authenticate by key="value" pairs. Basic or no realm is an error.
  • mediaType tells an index from an image. Decode from unknown, report the bad field’s path.
  • Fetch by digest, hash, compare, then store. A tag cannot be verified, everything under it can.
  • A digest that becomes a path must match sha256:<64 hex> first.
  • Inject fetch and the store: the same pull runs on fixtures and on the real registry.