@soleur/opencode 3.361.6 → 3.362.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,905 @@
1
+ #!/usr/bin/env bash
2
+ # mirror-ghcr-to-zot.sh — break-glass GHCR→zot mirror, executed ON a private-net
3
+ # datacenter host (soleur:registry-breakglass-mirror, #11424; ADR-096 amendment
4
+ # 2026-10-28, the sanctioned name-scoped exception to the #9169 hosts-file deny).
5
+ #
6
+ # WHEN THIS RUNS. The CF-tunnel registry bridge is down, so CI and
7
+ # scripts/registry-restore-from-ghcr.sh cannot reach zot at all, and production's
8
+ # zot store must be re-materialised from GHCR. Copy this script to a datacenter
9
+ # host (default web-1; any 10.0.1.0/24 member), run it there: the pull leg rides
10
+ # the datacenter link (~3 min measured for ~2.4 GB during the 2026-10-28 O2
11
+ # recovery vs ~1 h+ of failed residential-uplink uploads) and the push leg stays
12
+ # on the private layer-2 network.
13
+ #
14
+ # THE ONE RULE THIS EXISTS FOR: never upload blobs through a forwarded registry
15
+ # connection. zot PATCH uploads die mid-stream over `ssh -L` and registries do
16
+ # not resume upload sessions. Push only here, on the private net.
17
+ #
18
+ # THE SINKHOLE BYPASS. The hosts-file ghcr deny sinkholes ghcr.io,
19
+ # pkg-containers.githubusercontent.com and docker.pkg.github.com to 0.0.0.0/:: —
20
+ # an accident guard on NAME RESOLUTION (enumerated from
21
+ # apps/web-platform/infra/server.tf local.ghcr_deny_sh), not an egress control.
22
+ # This script's only exception is per-command `curl --resolve <name>:443:<ip>`
23
+ # on exactly the two names a GHCR pull needs (docker.pkg.github.com is legacy and
24
+ # is never resolved here). /etc/hosts is never edited — there are no writes to it
25
+ # anywhere in this file — TLS verification stays ON (--resolve pins only the
26
+ # dial address; SNI, the handshake and CA verification still target the
27
+ # hostname, so -k/--insecure is forbidden on the pull leg; it appears only on
28
+ # crane calls to the plain-HTTP private-net sink, the same posture as the
29
+ # standing hetzner -> zotRegistry edge), and every pulled byte is verified at its
30
+ # sha256, so a wrong --resolve answer cannot inject content.
31
+ #
32
+ # NAME RESOLUTION FOR THE BYPASS — one mechanism: DNS-over-HTTPS. The host's own
33
+ # getent would return the sinkhole, so the script asks a public resolver over
34
+ # HTTPS (cloudflare-dns.com/dns-query, then dns.google/resolve — neither is in
35
+ # the deny set and the host's unrestricted OUTPUT chain carries it; the nftables
36
+ # egress firewall is docker0-bridge-scoped and does not cover host processes).
37
+ # GHCR_IP / PKGC_IP env overrides skip the lookup entirely.
38
+ #
39
+ # SIGNATURE OBLIGATION. ci-deploy cosign-verifies at deploy time and fetches the
40
+ # signature from the SAME registry it pulled from (ADR-087), so the cosign
41
+ # referrers tag `sha256-<image-digest-hex>` is mirrored per image. GHCR serves it
42
+ # as an OCI INDEX whose CHILD carries artifactType (the #7410 lesson — reading
43
+ # the tag as a plain manifest fail-closes a healthy signature). A missing
44
+ # signature is a hard failure, never a warning: there is no unsigned-mirror arm.
45
+ #
46
+ # VERIFICATION. `crane digest` alone is not proof — a manifest can outlive its
47
+ # layers under zot gc+dedupe (measured 2026-08-05). Read-back is
48
+ # `crane validate --remote` per platform child, blob-presence via `crane blob`
49
+ # for attestation/signature children (a whole-index validate would gunzip a
50
+ # plain-JSON in-toto/sigstore layer — #7378), per pushed digest.
51
+ #
52
+ # Usage:
53
+ # mirror-ghcr-to-zot.sh [--dry-run] <repo> <ref> [<ref>...]
54
+ #
55
+ # <repo> GHCR repository path, e.g. jikig-ai/soleur-web-platform
56
+ # (a leading ghcr.io/ is stripped).
57
+ # <ref> repo@sha256:<64hex> | repo:<tag> | sha256:<64hex> | <tag>
58
+ # (prefixed forms must name <repo>; bare forms bind to it).
59
+ #
60
+ # --dry-run resolve + read manifests, print the plan (refs, blob counts,
61
+ # target) and exit 0 without pulling blobs or pushing.
62
+ # --help this text.
63
+ #
64
+ # Env:
65
+ # GHCR_TOKEN operator-supplied read:packages PAT — required unless
66
+ # --dry-run. NEVER the Doppler GHCR_READ_TOKEN: revoked by
67
+ # design (ADR-096 §5.5/B3).
68
+ # GHCR_USER basic-auth username for the token exchange (the PAT
69
+ # carries the identity). Default: operator.
70
+ # ZOT_PUSH_USER sink credential — Doppler soleur/prd.
71
+ # ZOT_PUSH_TOKEN sink credential — Doppler soleur/prd.
72
+ # Both validated non-empty BEFORE the first network call.
73
+ # ZOT_TARGET sink registry host:port (default 10.0.1.30:5000).
74
+ # GHCR_IP, PKGC_IP optional --resolve overrides (see header).
75
+ # CRANE_CMD crane binary to invoke (test seam; default: crane, with a
76
+ # pinned v0.20.2 github-release fetch when absent —
77
+ # github.com is NOT sinkholed).
78
+ # CRANE_TIMEOUT seconds bound on every crane invocation (default 900 —
79
+ # a stalled private-net write dies retryable, never hangs).
80
+ #
81
+ # Secrets transit via env/stdin only — never argv, never logged; the tokens are
82
+ # unset after use and the private DOCKER_CONFIG is removed with the scratch dir.
83
+ # Residual: SIGKILL skips the EXIT trap, leaving the 0700 $WORK (token.json,
84
+ # dockercfg/config.json) on disk — bounded to same-UID readers; unclosable.
85
+ #
86
+ # NOTE — deliberate triplication: fetch_artifact / verify_blobs_of /
87
+ # count_artifact (and verify_pushed's TSV variant) share the enumerate-children
88
+ # / enumerate-blobs / count-check shape. This script is distributed
89
+ # self-contained to an incident host, so the copies stay inline — keep all four
90
+ # in lockstep when one changes.
91
+ #
92
+ # Exit codes (one operator action per code, mirroring the restore engine):
93
+ # 0 every required reference pushed AND verified (manifest + blobs + signature)
94
+ # 1 usage / configuration error
95
+ # 2 SOURCE (GHCR) unavailable or rejected — nothing mirrored; also covers the
96
+ # name-resolution and token-exchange legs
97
+ # 3 SINK (zot) unavailable — retryable
98
+ # 4 verification failed — the copy "succeeded" and the result is unusable
99
+ # (missing blob, digest mismatch, missing signature). NOT retryable.
100
+ # 5 CREDENTIAL unusable (absent/empty, or rejected by the sink)
101
+ # 6 unclassified — loudest arm; file it
102
+ # 78 refused to run under xtrace with a credential set (#7797)
103
+ #
104
+ # Failure text names only MEASURED causes (ADR-166): the closed verdict
105
+ # vocabulary lives in scripts/zot-mirror-diagnosis.sh on the CI path; this engine
106
+ # reports the http_code / crane error it actually observed.
107
+
108
+ set -euo pipefail
109
+
110
+ # Refuse to run under xtrace while a credential this script expands is in the
111
+ # environment — `bash -x` prints expanded values (see #7797). This precedes every
112
+ # other command on purpose (the credential-trace lint's Rule A); `set`/`shopt`
113
+ # are the only statements allowed ahead of it.
114
+ case "$-" in
115
+ *x*)
116
+ # GHCR_READ_TOKEN is never set by design (revoked, ADR-096 §5.5/B3) — naming
117
+ # it keeps this refusal honest if a future edit ever expands it.
118
+ if [ -n "${DEPLOY_SSH_PRIVATE_KEY:+x}${GHCR_READ_TOKEN:+x}${GHCR_TOKEN:+x}${ZOT_PUSH_TOKEN:+x}" ]; then
119
+ printf '[FATAL] refusing to run under xtrace while a credential is set — the trace would print it (see #7797)\n' >&2
120
+ exit 78
121
+ fi
122
+ ;;
123
+ esac
124
+
125
+ ZOT_TARGET="${ZOT_TARGET:-10.0.1.30:5000}"
126
+ GHCR_USER="${GHCR_USER:-operator}"
127
+ CRANE_VERSION="v0.20.2"
128
+ CRANE_SHA256="c14340087103ba9dadf61d45acd20675490fd0ccbd56ac7901fc1b502137f44b"
129
+ CRANE="${CRANE_CMD:-crane}"
130
+ DRY_RUN=0
131
+
132
+ usage() {
133
+ cat <<'EOF'
134
+ mirror-ghcr-to-zot.sh — break-glass GHCR→zot mirror, run ON a private-net
135
+ datacenter host (soleur:registry-breakglass-mirror, #11424).
136
+
137
+ mirror-ghcr-to-zot.sh [--dry-run] <repo> <ref> [<ref>...]
138
+
139
+ <repo> GHCR repository path (e.g. jikig-ai/soleur-web-platform;
140
+ a leading ghcr.io/ is stripped)
141
+ <ref> repo@sha256:<64hex> | repo:<tag> | sha256:<64hex> | <tag>
142
+ (prefixed forms must name <repo>; bare forms bind to it)
143
+
144
+ --dry-run resolve + read manifests, print the plan (refs, blob counts,
145
+ target) and exit 0 without pulling blobs or pushing
146
+ --help this text
147
+
148
+ Env: GHCR_TOKEN (required unless --dry-run; operator read:packages PAT — never
149
+ the revoked-by-design GHCR_READ_TOKEN), GHCR_USER (default operator),
150
+ ZOT_PUSH_USER, ZOT_PUSH_TOKEN (Doppler soleur/prd), ZOT_TARGET (default
151
+ 10.0.1.30:5000), GHCR_IP / PKGC_IP (optional --resolve overrides), CRANE_CMD
152
+ (test seam), CRANE_TIMEOUT (default 900s).
153
+
154
+ Exit: 0 verified · 1 usage · 2 GHCR/source · 3 sink retryable · 4 verification
155
+ (not retryable) · 5 credential · 6 unclassified · 78 xtrace refusal.
156
+ EOF
157
+ }
158
+
159
+ die() { # $1 = exit code, rest = message (CR/LF flattened — registry text interpolates)
160
+ local code="$1"; shift
161
+ local msg="$*"
162
+ msg="${msg//[$'\r\n']/ }"
163
+ # Registry/crane error text is interpolated into messages — strip the rest of
164
+ # the C0 range + DEL too, so a hostile response cannot write escape sequences
165
+ # into the operator's terminal.
166
+ msg="$(printf '%s' "$msg" | tr -d '\000-\010\013-\037\177')"
167
+ printf 'mirror-ghcr-to-zot: %s\n' "$msg" >&2
168
+ exit "$code"
169
+ }
170
+
171
+ while [[ $# -gt 0 ]]; do
172
+ case "$1" in
173
+ --help|-h) usage; exit 0 ;;
174
+ --dry-run) DRY_RUN=1; shift ;;
175
+ --) shift; break ;;
176
+ -*) die 1 "unknown flag '$1' — run with --help" ;;
177
+ *) break ;;
178
+ esac
179
+ done
180
+
181
+ [[ "$ZOT_TARGET" =~ ^[a-zA-Z0-9.-]+:[0-9]+$ ]] \
182
+ || die 1 "ZOT_TARGET must look like host:port (got '${ZOT_TARGET}') — the push and the sink credentials would go to a host you did not name."
183
+ [[ "${CRANE_TIMEOUT:-900}" =~ ^[1-9][0-9]*$ ]] \
184
+ || die 1 "CRANE_TIMEOUT must be a positive-integer second count (got '${CRANE_TIMEOUT:-}') — 0 disables the bound."
185
+
186
+ REPO="${1:-}"
187
+ [[ $# -ge 1 ]] || { usage >&2; die 1 "<repo> and at least one <ref> are required."; }
188
+ shift
189
+ REPO="${REPO#ghcr.io/}"
190
+ [[ "$REPO" =~ ^[a-z0-9][a-z0-9._/-]*[a-z0-9]$ && "$REPO" == */* ]] \
191
+ || die 1 "repo must look like owner/name (e.g. jikig-ai/soleur-web-platform); got '${REPO}'"
192
+ [[ $# -ge 1 ]] || die 1 "at least one <ref> is required."
193
+
194
+ # parse_ref <ref> → "tag\t<tag>" or "digest\tsha256:<64hex>"; dies on bad shape.
195
+ parse_ref() {
196
+ local ref="${1#ghcr.io/}" v
197
+ case "$ref" in
198
+ */*)
199
+ [[ "$ref" == "$REPO"@* || "$ref" == "$REPO":* ]] \
200
+ || die 1 "ref '$1' names a different repo than '${REPO}'"
201
+ v="${ref#"$REPO"}" ;;
202
+ *) v="$ref" ;;
203
+ esac
204
+ case "$v" in
205
+ @sha256:*|sha256:*)
206
+ v="sha256:${v##*sha256:}"
207
+ [[ "$v" =~ ^sha256:[0-9a-f]{64}$ ]] \
208
+ || die 1 "malformed digest in ref '$1' (expected sha256:<64 lowercase hex>)"
209
+ printf 'digest\t%s' "$v" ;;
210
+ :*|*)
211
+ local t="${v#:}"
212
+ [[ "$t" =~ ^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$ ]] \
213
+ || die 1 "malformed tag in ref '$1' (OCI tag charset)"
214
+ printf 'tag\t%s' "$t" ;;
215
+ esac
216
+ }
217
+
218
+ REF_KIND=() REF_VAL=()
219
+ for a in "$@"; do
220
+ kv="$(parse_ref "$a")"
221
+ REF_KIND+=("${kv%%$'\t'*}")
222
+ REF_VAL+=("${kv#*$'\t'}")
223
+ done
224
+ N_REFS=${#REF_KIND[@]}
225
+
226
+ # Re-assert the parsed shapes where the values are consumed: REF_VAL elements
227
+ # are argv-derived and reach a credentialed request path, so each must still
228
+ # match its strict form at the point of use (the credential-trace lint's
229
+ # destination-pin limb — an adjudication, not a shape hint).
230
+ for ((i = 0; i < N_REFS; i++)); do
231
+ [[ "${REF_VAL[$i]}" =~ ^sha256:[0-9a-f]{64}$ || "${REF_VAL[$i]}" =~ ^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$ ]] \
232
+ || die 1 "parsed ref '${REF_VAL[$i]}' escaped its strict shape contract — refusing to use it."
233
+ done
234
+
235
+ command -v curl >/dev/null 2>&1 || die 6 "curl is required on this host."
236
+ command -v jq >/dev/null 2>&1 || die 6 "jq is required on this host."
237
+ command -v sha256sum >/dev/null 2>&1 || die 6 "sha256sum is required on this host."
238
+ command -v timeout >/dev/null 2>&1 || die 6 "timeout(1) is required on this host (bounds every crane call)."
239
+
240
+ WORK="$(mktemp -d)" || die 6 "could not create a scratch directory."
241
+ case "$WORK" in /*) ;; *) die 6 "scratch dir is not absolute — refusing to own its cleanup" ;; esac
242
+ trap 'rm -rf "$WORK"' EXIT
243
+
244
+ # Credentials first, before any network call: a fault discovered halfway leaves a
245
+ # partially populated registry. In --dry-run no push is possible, so the sink
246
+ # credentials are not required; GHCR_TOKEN is optional (manifest reads only).
247
+ if (( DRY_RUN == 0 )); then
248
+ [[ -n "${ZOT_PUSH_USER:-}" ]] || die 5 "ZOT_PUSH_USER is unset or empty (Doppler soleur/prd) — cannot authenticate to the sink."
249
+ [[ -n "${ZOT_PUSH_TOKEN:-}" ]] || die 5 "ZOT_PUSH_TOKEN is unset or empty (Doppler soleur/prd) — cannot authenticate to the sink."
250
+ fi
251
+ ghcr_token_set=0
252
+ if [[ -n "${GHCR_TOKEN:-}" ]]; then ghcr_token_set=1; fi
253
+ if (( DRY_RUN == 0 )) && (( ghcr_token_set == 0 )); then
254
+ die 5 "GHCR_TOKEN is unset or empty — the operator-supplied read:packages PAT is required at invocation. NEVER Doppler GHCR_READ_TOKEN: it is revoked BY DESIGN (ADR-096 §5.5/B3)."
255
+ fi
256
+
257
+ # ── crane, pinned. github.com is not in the sinkhole set. Only the live path
258
+ # invokes crane — a dry-run never needs the binary, so its fetch is skipped there.
259
+ if (( DRY_RUN == 0 )) && ! command -v "$CRANE" >/dev/null 2>&1; then
260
+ mkdir -p "$WORK/bin"
261
+ asset="go-containerregistry_Linux_x86_64.tar.gz"
262
+ if ! curl --disable --noproxy '*' -fsSL --proto '=https' --proto-redir '=https' \
263
+ --connect-timeout 10 --max-time 120 \
264
+ -o "$WORK/crane.tgz" \
265
+ "https://github.com/google/go-containerregistry/releases/download/${CRANE_VERSION}/${asset}" \
266
+ 2>"$WORK/crane-dl.err"; then
267
+ die 6 "could not download the pinned crane ${CRANE_VERSION} tarball: $(tail -c 200 "$WORK/crane-dl.err" 2>/dev/null | tr '\r\n' ' ')"
268
+ fi
269
+ echo "${CRANE_SHA256} $WORK/crane.tgz" | sha256sum -c - >/dev/null 2>&1 \
270
+ || die 6 "the crane ${CRANE_VERSION} tarball does not hash to the pinned sha256 — refusing to run it."
271
+ tar -xzf "$WORK/crane.tgz" -C "$WORK/bin" crane \
272
+ || die 6 "could not extract the pinned crane tarball."
273
+ CRANE="$WORK/bin/crane"
274
+ fi
275
+
276
+ # ── IPv4 validation + DoH resolution (the ONE mechanism; see header). ─────────
277
+ ipv4_ok() {
278
+ local ip="$1" a b c d
279
+ [[ "$ip" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] || return 1
280
+ IFS=. read -r a b c d <<<"$ip"
281
+ (( a <= 255 && b <= 255 && c <= 255 && d <= 255 )) || return 1
282
+ return 0
283
+ }
284
+
285
+ doh_ip() { # $1=name → prints one IPv4, rc 1 if neither resolver yielded one
286
+ local name="$1" body ip
287
+ for ep in "https://cloudflare-dns.com/dns-query?name=${name}&type=A" \
288
+ "https://dns.google/resolve?name=${name}&type=A"; do
289
+ if ! body="$(curl --disable --noproxy '*' -fsS --proto '=https' \
290
+ --connect-timeout 5 --max-time 15 \
291
+ -H 'accept: application/dns-json' "$ep" 2>/dev/null)"; then
292
+ continue
293
+ fi
294
+ ip="$(jq -r '[.Answer[]? | select(.type == 1) | .data][0] // empty' <<<"$body" 2>/dev/null)" || continue
295
+ if ipv4_ok "$ip"; then printf '%s\n' "$ip"; return 0; fi
296
+ done
297
+ return 1
298
+ }
299
+
300
+ resolve_for() { # $1=name $2=env-override $3=env-name → prints IPv4 or dies 2
301
+ if [[ -n "$2" ]]; then
302
+ ipv4_ok "$2" || die 2 "$3 override '$2' is not a dotted-quad IPv4 — refusing it."
303
+ printf '%s\n' "$2"; return 0
304
+ fi
305
+ local ip
306
+ if ip="$(doh_ip "$1")"; then printf '%s\n' "$ip"; return 0; fi
307
+ die 2 "could not resolve a real address for $1 — DoH failed and no $3 override was supplied (the hosts-file answer is the 0.0.0.0 sinkhole BY DESIGN)."
308
+ }
309
+
310
+ # ── curl wrappers: TLS verification intact; credentials ride stdin only. ──────
311
+ _bearer_ok() { local LC_ALL=C; case "${1:-}" in ''|*[!A-Za-z0-9._~+/=-]*) return 1 ;; esac; }
312
+
313
+ RES=() # per-command --resolve args, populated by resolve_ghcr_names()
314
+ TOK="" # the GHCR pull bearer; unset after the pull phase
315
+
316
+ resolve_ghcr_names() {
317
+ GHCR_IP="$(resolve_for ghcr.io "${GHCR_IP:-}" GHCR_IP)"
318
+ PKGC_IP="$(resolve_for pkg-containers.githubusercontent.com "${PKGC_IP:-}" PKGC_IP)"
319
+ RES=(--resolve "ghcr.io:443:${GHCR_IP}" --resolve "pkg-containers.githubusercontent.com:443:${PKGC_IP}")
320
+ }
321
+
322
+ # ghcr_get <url> <outfile> → echoes the http_code (000 on transport failure);
323
+ # always rc 0 so callers classify the code, never the process status.
324
+ ghcr_get() {
325
+ local code
326
+ if ! code="$(curl --disable --noproxy '*' -sSL --proto '=https' --proto-redir '=https' \
327
+ --connect-timeout 10 --max-time 900 --retry 3 \
328
+ "${RES[@]}" \
329
+ -H 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json, application/vnd.docker.distribution.manifest.list.v2+json, application/octet-stream' \
330
+ --config - "$1" \
331
+ < <(printf 'header = "Authorization: Bearer %s"\n' "$TOK") \
332
+ -o "$2" -w '%{http_code}' 2>>"$WORK/curl.err")"; then
333
+ printf '000'
334
+ return 0
335
+ fi
336
+ printf '%s' "$code"
337
+ }
338
+
339
+ classify_code() {
340
+ case "$1" in
341
+ 2*) printf 'OK' ;;
342
+ 401|403) printf 'DENIED' ;;
343
+ 404) printf 'NOTFOUND' ;;
344
+ 000) printf 'NETWORK' ;;
345
+ 5*) printf 'HTTP5XX' ;;
346
+ *) printf 'UNKNOWN' ;;
347
+ esac
348
+ }
349
+
350
+ # die_by_code <what> <code> — measured-cause failure text for the pull leg.
351
+ die_by_code() {
352
+ local what="$1" code="$2"
353
+ case "$(classify_code "$code")" in
354
+ NOTFOUND) die 2 "${what} is absent or not visible to this credential on GHCR (http=${code} — GHCR returns 404 for both, so this does not prove it is gone)." ;;
355
+ DENIED) die 2 "GHCR rejected the credential reading ${what} (http=${code}). Check the PAT's read:packages scope before concluding the object is absent." ;;
356
+ NETWORK) die 2 "GHCR was unreachable while reading ${what} (transport failure). Retryable." ;;
357
+ HTTP5XX) die 2 "GHCR returned an error for ${what} (http=${code}). Retryable." ;;
358
+ *) die 6 "reading ${what} returned http=${code}, a shape this script cannot classify." ;;
359
+ esac
360
+ }
361
+
362
+ token_exchange() {
363
+ local code
364
+ _bearer_ok "${GHCR_TOKEN:-}" \
365
+ || die 5 "GHCR_TOKEN is outside the bearer charset — refusing to feed it to the auth-config channel."
366
+ [[ "$GHCR_USER" =~ ^[A-Za-z0-9._~-]+$ ]] \
367
+ || die 5 "GHCR_USER is outside the user charset — a quote or newline would corrupt the curl auth-config line."
368
+ if ! code="$(curl --disable --noproxy '*' -sS --proto '=https' \
369
+ --connect-timeout 10 --max-time 30 \
370
+ "${RES[@]}" \
371
+ --config - \
372
+ "https://ghcr.io/token?service=ghcr.io&scope=repository:${REPO}:pull" \
373
+ < <(printf 'user = "%s:%s"\n' "$GHCR_USER" "$GHCR_TOKEN") \
374
+ -o "$WORK/token.json" -w '%{http_code}' 2>>"$WORK/curl.err")"; then
375
+ code="000"
376
+ fi
377
+ case "$(classify_code "$code")" in
378
+ OK) ;;
379
+ DENIED) die 2 "the GHCR token exchange rejected the credential (http=${code}) — the PAT is wrong, expired, or lacks read:packages on ${REPO}." ;;
380
+ NETWORK) die 2 "the GHCR token exchange could not reach ghcr.io (transport failure). Nothing was fetched." ;;
381
+ *) die 2 "the GHCR token exchange returned http=${code} — an unmeasured failure shape." ;;
382
+ esac
383
+ TOK="$(jq -r '.token // .access_token // empty' "$WORK/token.json" 2>/dev/null || true)"
384
+ _bearer_ok "$TOK" \
385
+ || die 2 "the GHCR pull token came back empty or outside the bearer charset."
386
+ # The PAT is only needed for the exchange; the bearer covers the rest.
387
+ unset GHCR_TOKEN
388
+ }
389
+
390
+ sha256_file() { sha256sum "$1" | cut -d' ' -f1; }
391
+
392
+ # manifest_kind — the ONE shape answer: index | manifest | malformed | empty |
393
+ # unparseable. `.manifests` present-but-not-an-array is its own class: folding it
394
+ # into "manifest" hands a malformed index to a blob walk that reads it as empty.
395
+ manifest_kind() {
396
+ jq -r 'if (.manifests | type) == "array" then "index"
397
+ elif has("manifests") then "malformed"
398
+ elif (has("config") or has("layers")) then "manifest"
399
+ else "empty" end' "$1" 2>/dev/null || printf 'unparseable\n'
400
+ }
401
+
402
+ POOL="$WORK/pool/blobs/sha256"
403
+ CUR_BLOBS="$WORK/cur.blobs" # per-artifact record of every materialised digest
404
+
405
+ # fetch_artifact <sha256:digest> <depth> — pull a manifest/index + everything it
406
+ # declares into $POOL, verifying every sha256. Appends each materialised hex to
407
+ # $CUR_BLOBS. depth: 0 root only; an index nested in an index fails closed.
408
+ fetch_artifact() {
409
+ local dig="$1" depth="$2" hex="${1#sha256:}" mf="$POOL/${1#sha256:}"
410
+ local code kind children n_declared n c blobslist nb b
411
+ if [[ ! -f "$mf" ]]; then
412
+ mkdir -p "$POOL"
413
+ code="$(ghcr_get "https://ghcr.io/v2/${REPO}/manifests/${dig}" "$mf")"
414
+ [[ "$(classify_code "$code")" == "OK" ]] || die_by_code "manifest ${dig}" "$code"
415
+ [[ "$(sha256_file "$mf")" == "$hex" ]] \
416
+ || die 4 "manifest ${dig} bytes do not hash to their digest — refusing to mirror content the pin does not cover."
417
+ fi
418
+ printf '%s\n' "$hex" >> "$CUR_BLOBS"
419
+ kind="$(manifest_kind "$mf")"
420
+ case "$kind" in
421
+ index)
422
+ (( depth == 0 )) \
423
+ || die 4 "${dig} is an index nested inside another index — this engine mirrors one level of indirection, failing closed rather than claiming a deeper walk."
424
+ if ! children="$(jq -r '(.manifests // [])[] | (.digest // "-")' "$mf" 2>"$WORK/jq.err")"; then
425
+ die 4 "${dig}: its child list could not be fully enumerated — a truncated read would silently skip children."
426
+ fi
427
+ n_declared="$(jq -r '(.manifests // []) | length' "$mf" 2>/dev/null || printf '?')"
428
+ [[ "$n_declared" =~ ^[0-9]+$ ]] \
429
+ || die 4 "${dig}: its child count could not be read — no completeness claim is possible."
430
+ [[ -n "$children" || "$n_declared" == "0" ]] \
431
+ || die 4 "${dig}: the index enumerated ZERO child rows but declares ${n_declared} — the enumeration is unusable."
432
+ n=0
433
+ while IFS= read -r c; do
434
+ [[ -n "$c" ]] || continue
435
+ n=$((n + 1))
436
+ [[ "$c" =~ ^sha256:[0-9a-f]{64}$ && "$c" != "-" ]] \
437
+ || die 4 "${dig}: child ${n} carries a digest this engine cannot address ('${c}')."
438
+ fetch_artifact "$c" "$((depth + 1))"
439
+ done <<< "$children"
440
+ (( n == n_declared )) \
441
+ || die 4 "${dig}: enumerated ${n} children but the index declares ${n_declared} — the remainder were never fetched."
442
+ ;;
443
+ manifest)
444
+ if ! blobslist="$(jq -r '[(if has("config") then (.config.digest // "-") else empty end)] + [(.layers // [])[] | (.digest // "-")] | .[]' "$mf" 2>"$WORK/jq.err")"; then
445
+ die 4 "${dig}: its blob list could not be fully enumerated — a truncated read would silently skip blobs."
446
+ fi
447
+ n_declared="$(jq -r '((if has("config") then 1 else 0 end)) + ((.layers // []) | length)' "$mf" 2>/dev/null || printf '?')"
448
+ [[ "$n_declared" =~ ^[0-9]+$ ]] \
449
+ || die 4 "${dig}: its blob count could not be read — no completeness claim is possible."
450
+ local n_layers
451
+ n_layers="$(jq -r '(.layers // []) | length' "$mf" 2>/dev/null || printf '0')"
452
+ (( n_layers > 0 )) \
453
+ || die 4 "${dig} declares NO layers — a config alone carries no payload (the empty-object blob is not evidence an artifact is intact)."
454
+ if [[ -z "$blobslist" ]]; then
455
+ (( n_declared == 0 )) \
456
+ || die 4 "${dig}: enumerated ZERO blob rows but declares ${n_declared} — the enumeration is unusable."
457
+ else
458
+ nb=0
459
+ while IFS= read -r b; do
460
+ [[ -n "$b" ]] || continue
461
+ nb=$((nb + 1))
462
+ [[ "$b" =~ ^sha256:[0-9a-f]{64}$ && "$b" != "-" ]] \
463
+ || die 4 "${dig}: blob ${nb} declares an unaddressable digest ('${b}')."
464
+ fetch_blob "$b"
465
+ done <<< "$blobslist"
466
+ (( nb == n_declared )) \
467
+ || die 4 "${dig}: fetched ${nb} blobs but the manifest declares ${n_declared} — the remainder were never fetched."
468
+ fi
469
+ ;;
470
+ malformed) die 4 "${dig}: its manifest carries a \`manifests\` field that is not an array — neither a readable index nor a plain manifest." ;;
471
+ empty) die 4 "${dig} declares neither children nor blobs — it is not an artifact a host could pull." ;;
472
+ *) die 4 "${dig}: its manifest could not be parsed (kind=${kind}) — nothing about it was fetched." ;;
473
+ esac
474
+ }
475
+
476
+ fetch_blob() { # <sha256:digest> — pull into $POOL with digest verification
477
+ local dig="$1" hex="${1#sha256:}" code
478
+ local f="$POOL/$hex"
479
+ if [[ -f "$f" ]]; then printf '%s\n' "$hex" >> "$CUR_BLOBS"; return 0; fi
480
+ code="$(ghcr_get "https://ghcr.io/v2/${REPO}/blobs/${dig}" "$f")"
481
+ [[ "$(classify_code "$code")" == "OK" ]] || { rm -f "$f"; die_by_code "blob ${dig}" "$code"; }
482
+ [[ "$(sha256_file "$f")" == "$hex" ]] \
483
+ || die 4 "blob ${dig} bytes do not hash to their digest — refusing to mirror content outside the pin."
484
+ printf '%s\n' "$hex" >> "$CUR_BLOBS"
485
+ }
486
+
487
+ # assemble_layout <digest> <layoutdir> — hardlink the artifact's blob set into an
488
+ # OCI layout dir whose index.json names exactly the artifact digest.
489
+ assemble_layout() {
490
+ local dig="$1" ldir="$2" hex="${1#sha256:}" mt size h
491
+ local mf="$POOL/$hex"
492
+ mkdir -p "$ldir/blobs/sha256" || die 6 "could not create $ldir — filesystem fault."
493
+ while IFS= read -r h; do
494
+ [[ -n "$h" ]] || continue
495
+ [[ -f "$POOL/$h" ]] || die 6 "layout assembly references $POOL/$h which was never materialised — a bug, not a registry state."
496
+ ln -f "$POOL/$h" "$ldir/blobs/sha256/$h" || die 6 "could not hardlink $h into the layout — filesystem fault."
497
+ done < <(sort -u "$CUR_BLOBS")
498
+ mt="$(jq -r '.mediaType // empty' "$mf" 2>/dev/null || true)"
499
+ if [[ -z "$mt" ]]; then
500
+ case "$(manifest_kind "$mf")" in
501
+ index) mt="application/vnd.oci.image.index.v1+json" ;;
502
+ *) mt="application/vnd.oci.image.manifest.v1+json" ;;
503
+ esac
504
+ fi
505
+ size="$(stat -c %s "$mf")" || die 6 "could not stat $mf — filesystem fault."
506
+ printf '{"imageLayoutVersion":"1.0.0"}' > "$ldir/oci-layout"
507
+ jq -cn --arg mt "$mt" --arg d "$dig" --argjson sz "$size" \
508
+ '{schemaVersion:2,mediaType:"application/vnd.oci.image.index.v1+json",
509
+ manifests:[{mediaType:$mt,digest:$d,size:$sz}]}' > "$ldir/index.json"
510
+ }
511
+
512
+ # ── sink side: crane helpers (condensed copies of the restore engine's — this
513
+ # script is self-contained on the host; no imports). ────────────────────────────
514
+ crane_capture() { # <outfile> <errfile> <crane args...> — bounded: a stalled
515
+ # private-net write must die as retryable NETWORK, never hang the run.
516
+ local out="$1" err="$2" rc; shift 2
517
+ rc=0
518
+ timeout "${CRANE_TIMEOUT:-900}" "$CRANE" "$@" >"$out" 2>"$err" </dev/null || rc=$?
519
+ if (( rc == 124 )); then
520
+ printf 'crane invocation timed out after %ss (i/o timeout)\n' "${CRANE_TIMEOUT:-900}" >>"$err"
521
+ fi
522
+ return "$rc"
523
+ }
524
+ last_err() { tail -c 400 "$1" 2>/dev/null | tail -n 1 | tr '\r\n' ' ' | sed 's/[[:space:]]*$//' || true; }
525
+ classify() {
526
+ local err="$1"
527
+ case "$err" in
528
+ *BLOB_UNKNOWN*|*"blob unknown"*) echo BLOBMISSING ;;
529
+ *MANIFEST_UNKNOWN*|*"manifest unknown"*) echo NOTFOUND ;;
530
+ *UNAUTHORIZED*|*DENIED*|*"authentication required"*|*"denied:"*) echo DENIED ;;
531
+ *"no such host"*|*"dial tcp"*|*"connection refused"*|*"connection reset"*|\
532
+ *"i/o timeout"*|*"TLS handshake"*|*"unexpected EOF"*|*EOF|\
533
+ *"502 "*|*"503 "*|*"504 "*|*" 502"|*" 503"|*" 504") echo NETWORK ;;
534
+ *) echo UNKNOWN ;;
535
+ esac
536
+ }
537
+ sink_die() { # <what> <errfile>
538
+ local what="$1" err cls
539
+ err="$(last_err "$2")"; cls="$(classify "$err")"
540
+ case "$cls" in
541
+ NETWORK) die 3 "the sink became unavailable while handling ${what}. Retryable. crane: ${err}" ;;
542
+ DENIED) die 5 "the sink rejected this credential handling ${what} — an authorisation fault retrying will not clear. crane: ${err}" ;;
543
+ NOTFOUND|BLOBMISSING) die 4 "${what} is missing from the sink — the mirror is incomplete. crane: ${err}" ;;
544
+ *) die 6 "handling ${what} failed in a way this script cannot classify. crane: ${err}" ;;
545
+ esac
546
+ }
547
+
548
+ # verify_blobs_of <repo> <digest-ref> <what> <depth> <expect_subject>
549
+ # Presence AND integrity: `crane blob` streams the body and go-containerregistry
550
+ # verifies the content digest at EOF. Never decompresses — correct for the
551
+ # plain-JSON in-toto/sigstore payload layers that trip `crane validate` (#7378).
552
+ verify_blobs_of() {
553
+ local repo="$1" ref="$2" what="$3" depth="${4:-0}" expect_subject="${5:-}"
554
+ local out="$WORK/vb.out" kind children n_declared n c_digest blobs b n_decl n_layers subj
555
+ crane_capture "$out" "$WORK/vb.err" manifest --insecure "$ref" \
556
+ || sink_die "the manifest of ${what}" "$WORK/vb.err"
557
+ kind="$(manifest_kind "$out")"
558
+ case "$kind" in
559
+ index)
560
+ (( depth == 0 )) \
561
+ || die 4 "${what} is an index nested inside an index — deeper nesting is unverified, failing closed."
562
+ if ! children="$(jq -r '(.manifests // [])[] | (.digest // "-")' "$out" 2>"$WORK/vb.jqerr")"; then
563
+ die 4 "${what}: its child list could not be fully enumerated — a truncated read would silently skip children."
564
+ fi
565
+ n_declared="$(jq -r '(.manifests // []) | length' "$out" 2>/dev/null || printf '?')"
566
+ [[ "$n_declared" =~ ^[0-9]+$ ]] \
567
+ || die 4 "${what}: its child count could not be read — no completeness claim is possible."
568
+ [[ -n "$children" ]] \
569
+ || die 4 "${what} is an index with no readable children, so it references nothing this mirror could verify."
570
+ n=0
571
+ while IFS= read -r c_digest; do
572
+ [[ -n "$c_digest" ]] || continue
573
+ n=$((n + 1))
574
+ [[ "$c_digest" =~ ^sha256:[0-9a-f]{64}$ && "$c_digest" != "-" ]] \
575
+ || die 4 "${what}: child ${n} declares no usable digest — cannot be addressed or verified."
576
+ verify_blobs_of "$repo" "${repo}@${c_digest}" "child ${c_digest} of ${what}" "$((depth + 1))" "$expect_subject"
577
+ done <<< "$children"
578
+ (( n == n_declared )) \
579
+ || die 4 "${what}: enumerated ${n} children but the index declares ${n_declared} — the remainder were never verified."
580
+ ;;
581
+ manifest)
582
+ if ! blobs="$(jq -r '[(if has("config") then (.config.digest // "-") else empty end)] + [(.layers // [])[] | (.digest // "-")] | .[]' "$out" 2>"$WORK/vb.jqerr")"; then
583
+ die 4 "${what}: its blob list could not be fully enumerated — a truncated read would silently skip blobs."
584
+ fi
585
+ n_decl="$(jq -r '((if has("config") then 1 else 0 end)) + ((.layers // []) | length)' "$out" 2>/dev/null || printf '?')"
586
+ [[ "$n_decl" =~ ^[0-9]+$ ]] \
587
+ || die 4 "${what}: its blob count could not be read — no completeness claim is possible."
588
+ n_layers="$(jq -r '(.layers // []) | length' "$out" 2>/dev/null || printf '0')"
589
+ [[ -n "$blobs" ]] \
590
+ || die 4 "${what} declares no blobs, so its presence cannot be verified."
591
+ (( n_layers > 0 )) \
592
+ || die 4 "${what} declares NO layers — a config alone is not evidence the artifact is intact (the empty-object blob is held by every registry)."
593
+ if [[ -n "$expect_subject" ]]; then
594
+ subj="$(jq -r '.subject.digest // ""' "$out" 2>/dev/null || printf '')"
595
+ if [[ -n "$subj" && "$subj" != "$expect_subject" ]]; then
596
+ die 4 "${what}: its subject digest is ${subj} but the image being mirrored is ${expect_subject} — this signature binds a DIFFERENT image. Do NOT deploy."
597
+ fi
598
+ fi
599
+ n=0
600
+ while IFS= read -r b; do
601
+ [[ -n "$b" ]] || continue
602
+ n=$((n + 1))
603
+ [[ "$b" =~ ^sha256:[0-9a-f]{64}$ && "$b" != "-" ]] \
604
+ || die 4 "${what}: blob ${n} declares no usable digest — cannot be verified."
605
+ crane_capture /dev/null "$WORK/vb.blob.err" blob --insecure "${repo}@${b}" \
606
+ || sink_die "the blob ${b} of ${what}" "$WORK/vb.blob.err"
607
+ done <<< "$blobs"
608
+ (( n == n_decl )) \
609
+ || die 4 "${what}: verified ${n} blobs but the manifest declares ${n_decl} — the remainder were never fetched."
610
+ ;;
611
+ malformed) die 4 "${what}: the sink's manifest carries a \`manifests\` field that is not an array." ;;
612
+ empty) die 4 "${what}: the sink returned a manifest declaring neither children nor blobs." ;;
613
+ *) die 4 "${what}: the sink's manifest could not be parsed (kind=${kind})." ;;
614
+ esac
615
+ }
616
+
617
+ # verify_pushed <repo> <digest> <what> <mode:image|signature> <expect_subject>
618
+ # Digest-parity is checked by the caller; this proves the SINK holds the blobs:
619
+ # platform children via `crane validate --remote`, attestation/signature children
620
+ # via blob-presence (never whole-index validate — #7378), every child accounted.
621
+ # <expect_subject> is the IMAGE digest a signature must bind — asserted on every
622
+ # signature child that carries .subject.digest (a right-blobs/wrong-subject sig
623
+ # passes everything else).
624
+ verify_pushed() {
625
+ local repo="$1" dig="$2" what="$3" mode="${4:-image}" expect_subject="${5:-}"
626
+ local out="$WORK/vp.out" kind children n_declared n n_platform c_digest c_mt c_type c_arch c_at
627
+ crane_capture "$out" "$WORK/vp.err" manifest --insecure "${repo}@${dig}" \
628
+ || sink_die "the manifest of ${what}" "$WORK/vp.err"
629
+ kind="$(manifest_kind "$out")"
630
+ case "$kind" in
631
+ manifest)
632
+ if [[ "$mode" == "signature" ]]; then
633
+ # A plain-manifest signature root: `crane validate` trips on the
634
+ # sigstore layer shape (#7378) — blob-presence + subject binding
635
+ # instead, same as signature index children.
636
+ verify_blobs_of "$repo" "${repo}@${dig}" "${what}" 0 "$expect_subject"
637
+ else
638
+ crane_capture "$WORK/vp.val.out" "$WORK/vp.val.err" validate --insecure --remote "${repo}@${dig}" \
639
+ || sink_die "${what}" "$WORK/vp.val.err"
640
+ fi
641
+ ;;
642
+ index)
643
+ if ! children="$(jq -r '(.manifests // [])[] | [(.digest // "-"), (.mediaType // "-"), (.annotations["vnd.docker.reference.type"] // "-"), (.platform.architecture // "-"), (.artifactType // "-")] | @tsv' "$out" 2>"$WORK/vp.jqerr")"; then
644
+ die 4 "${what}: its index could not be fully enumerated — an unknown number of children were never seen."
645
+ fi
646
+ n_declared="$(jq -r '(.manifests // []) | length' "$out" 2>/dev/null || printf '?')"
647
+ [[ "$n_declared" =~ ^[0-9]+$ ]] \
648
+ || die 4 "${what}: its child count could not be read — no completeness claim is possible."
649
+ [[ -n "$children" ]] \
650
+ || die 4 "${what} is an index whose child list is empty — no child could be verified."
651
+ n=0
652
+ n_platform=0
653
+ while IFS=$'\t' read -r c_digest c_mt c_type c_arch c_at; do
654
+ [[ -n "$c_digest" ]] || continue
655
+ n=$((n + 1))
656
+ [[ "$c_digest" =~ ^sha256:[0-9a-f]{64}$ && "$c_digest" != "-" ]] \
657
+ || die 4 "${what} declares an index child with no usable digest — cannot be verified."
658
+ case "$c_mt" in
659
+ *"image.index.v1+json"|*"manifest.list.v2+json")
660
+ die 4 "${what} contains a NESTED index child ${c_digest} (${c_mt}) — blob completeness is unproven; do NOT deploy." ;;
661
+ esac
662
+ if [[ "$mode" == "signature" ]]; then
663
+ verify_blobs_of "$repo" "${repo}@${c_digest}" "the signature child ${c_digest} of ${what}" 1 "$expect_subject"
664
+ elif [[ "$c_type" == "attestation-manifest" || "$c_arch" == "unknown" || "$c_at" != "-" ]]; then
665
+ verify_blobs_of "$repo" "${repo}@${c_digest}" "the attestation child ${c_digest} of ${what}" 1
666
+ else
667
+ n_platform=$((n_platform + 1))
668
+ crane_capture "$WORK/vp.val.out" "$WORK/vp.val.err" validate --insecure --remote "${repo}@${c_digest}" \
669
+ || sink_die "the ${c_arch} child ${c_digest} of ${what}" "$WORK/vp.val.err"
670
+ fi
671
+ done <<< "$children"
672
+ (( n == n_declared )) \
673
+ || die 4 "${what} declares ${n_declared} index children but only ${n} were verified — blob completeness is unproven."
674
+ if [[ "$mode" == "image" ]]; then
675
+ (( n_platform > 0 )) \
676
+ || die 4 "${what} is an index with ${n} children and NO platform image among them — there is nothing a host could pull."
677
+ fi
678
+ ;;
679
+ malformed) die 4 "${what}: the sink's manifest carries a \`manifests\` field that is not an array." ;;
680
+ empty) die 4 "${what}: the sink returned a manifest declaring neither children nor blobs — unverifiable." ;;
681
+ *) die 4 "${what}: the sink's manifest could not be parsed (kind=${kind})." ;;
682
+ esac
683
+ }
684
+
685
+ # ── plan + dry-run ────────────────────────────────────────────────────────────
686
+ count_artifact() { # <digest> <depth> → accumulates DC_MANIFESTS DC_BLOBS DC_BYTES DC_CHILDREN
687
+ local dig="$1" depth="$2" hex="${1#sha256:}" code kind children c sz nb n n_layers
688
+ local mf="$WORK/dry/$hex"
689
+ mkdir -p "$WORK/dry" || die 6 "could not create the dry-run store — filesystem fault."
690
+ if [[ ! -f "$mf" ]]; then
691
+ code="$(ghcr_get "https://ghcr.io/v2/${REPO}/manifests/${dig}" "$mf")"
692
+ [[ "$(classify_code "$code")" == "OK" ]] || die_by_code "manifest ${dig} (dry-run)" "$code"
693
+ [[ "$(sha256_file "$mf")" == "$hex" ]] \
694
+ || die 4 "manifest ${dig} bytes do not hash to their digest (dry-run)."
695
+ fi
696
+ DC_MANIFESTS=$((DC_MANIFESTS + 1))
697
+ kind="$(manifest_kind "$mf")"
698
+ case "$kind" in
699
+ index)
700
+ (( depth == 0 )) || die 4 "${dig} is a nested index (dry-run)."
701
+ if ! children="$(jq -r '(.manifests // [])[] | (.digest // "-")' "$mf" 2>"$WORK/jq.err")"; then
702
+ die 4 "${dig}: its child list could not be fully enumerated (dry-run) — a truncated read would silently skip children."
703
+ fi
704
+ while IFS= read -r c; do
705
+ [[ -n "$c" ]] || continue
706
+ DC_CHILDREN=$((DC_CHILDREN + 1))
707
+ [[ "$c" =~ ^sha256:[0-9a-f]{64}$ ]] || die 4 "${dig}: child carries an unaddressable digest (dry-run)."
708
+ sz="$(jq -r --arg d "$c" 'first(.manifests[] | select(.digest == $d) | .size) // 0' "$mf" 2>/dev/null || printf 0)"
709
+ DC_BYTES=$((DC_BYTES + ${sz:-0}))
710
+ count_artifact "$c" "$((depth + 1))"
711
+ done <<< "$children"
712
+ ;;
713
+ manifest)
714
+ nb="$(jq -r '[ (if has("config") then [.config.size] else [] end), [(.layers // [])[] | .size] ] | flatten | "\(length) \((add // 0))"' "$mf" 2>/dev/null || printf '0 0')"
715
+ read -r n sz <<<"$nb"
716
+ n_layers="$(jq -r '(.layers // []) | length' "$mf" 2>/dev/null || printf '0')"
717
+ (( n_layers > 0 )) \
718
+ || die 4 "${dig} declares NO layers — a config alone carries no payload (dry-run parity with the live path's check)."
719
+ DC_BLOBS=$((DC_BLOBS + ${n:-0}))
720
+ DC_BYTES=$((DC_BYTES + ${sz:-0}))
721
+ ;;
722
+ *) die 4 "${dig}: unreadable manifest shape (kind=${kind}) in dry-run." ;;
723
+ esac
724
+ }
725
+
726
+ if (( DRY_RUN )); then
727
+ printf 'mirror-ghcr-to-zot: DRY RUN — nothing will be pulled or pushed\n'
728
+ printf 'repo=%s target=%s refs=%d\n' "$REPO" "$ZOT_TARGET" "$N_REFS"
729
+ if (( ghcr_token_set == 0 )); then
730
+ i=0
731
+ while (( i < N_REFS )); do
732
+ printf 'ref[%d] %s=%s blobs=unmeasured (no GHCR_TOKEN — supply the PAT to count)\n' \
733
+ "$((i + 1))" "${REF_KIND[$i]}" "${REF_VAL[$i]}"
734
+ i=$((i + 1))
735
+ done
736
+ exit 0
737
+ fi
738
+ resolve_ghcr_names
739
+ printf 'resolve ghcr.io=%s pkg-containers.githubusercontent.com=%s\n' "$GHCR_IP" "$PKGC_IP"
740
+ token_exchange
741
+ i=0
742
+ while (( i < N_REFS )); do
743
+ # resolve the ref to a digest: a digest ref is already pinned; a tag needs one read.
744
+ if [[ "${REF_KIND[$i]}" == "digest" ]]; then
745
+ D="${REF_VAL[$i]}"
746
+ mf="$WORK/dry/${D#sha256:}"
747
+ mkdir -p "$WORK/dry" || die 6 "could not create the dry-run store — filesystem fault."
748
+ if [[ ! -f "$mf" ]]; then
749
+ code="$(ghcr_get "https://ghcr.io/v2/${REPO}/manifests/${D}" "$mf")"
750
+ [[ "$(classify_code "$code")" == "OK" ]] || die_by_code "manifest ${D} (dry-run)" "$code"
751
+ [[ "$(sha256_file "$mf")" == "${D#sha256:}" ]] \
752
+ || die 4 "manifest ${D} bytes do not hash to their digest (dry-run) — every pulled byte is verified at its sha256."
753
+ fi
754
+ else
755
+ rv="${REF_VAL[$i]}"
756
+ mf="$WORK/dry/tag-$rv"
757
+ code="$(ghcr_get "https://ghcr.io/v2/${REPO}/manifests/$rv" "$mf")"
758
+ [[ "$(classify_code "$code")" == "OK" ]] || die_by_code "manifest for tag $rv (dry-run)" "$code"
759
+ D="sha256:$(sha256_file "$mf")"
760
+ # Seed the dry store under the content name so count_artifact reuses it.
761
+ [[ -f "$WORK/dry/${D#sha256:}" ]] || cp "$mf" "$WORK/dry/${D#sha256:}" || die 6 "could not seed the dry-run store — filesystem fault."
762
+ mf="$WORK/dry/${D#sha256:}"
763
+ fi
764
+ DC_MANIFESTS=0 DC_BLOBS=0 DC_BYTES=0 DC_CHILDREN=0
765
+ count_artifact "$D" 0
766
+ sig_tag="sha256-${D#sha256:}"
767
+ code="$(ghcr_get "https://ghcr.io/v2/${REPO}/manifests/${sig_tag}" "$WORK/dry/sig")"
768
+ case "$(classify_code "$code")" in
769
+ OK) sig_state="present" ;;
770
+ NOTFOUND) sig_state="ABSENT (hard failure on a real run)" ;;
771
+ *) sig_state="unmeasured (http=${code})" ;;
772
+ esac
773
+ printf 'ref[%d] %s=%s -> %s kind=%s children=%d blobs=%d declared_bytes=%d sig=%s %s\n' \
774
+ "$((i + 1))" "${REF_KIND[$i]}" "${REF_VAL[$i]}" "$D" "$(manifest_kind "$mf")" \
775
+ "$DC_CHILDREN" "$DC_BLOBS" "$DC_BYTES" "$sig_tag" "$sig_state"
776
+ i=$((i + 1))
777
+ done
778
+ exit 0
779
+ fi
780
+
781
+ # ── live run: resolve → exchange → pull all → push all → verify all ───────────
782
+ resolve_ghcr_names
783
+ printf 'mirror-ghcr-to-zot: resolved ghcr.io=%s pkg-containers.githubusercontent.com=%s (per-command --resolve only)\n' "$GHCR_IP" "$PKGC_IP"
784
+ token_exchange
785
+
786
+ # Pull phase: one blob list per push unit, into the shared dedupe pool.
787
+ UNIT_NAME=() UNIT_DIGEST=() UNIT_BLOBS=() UNIT_IS_SIG=()
788
+ SEEN_DIGESTS=" "
789
+ i=0
790
+ while (( i < N_REFS )); do
791
+ : > "$CUR_BLOBS"
792
+ if [[ "${REF_KIND[$i]}" == "digest" ]]; then
793
+ D="${REF_VAL[$i]}"
794
+ else
795
+ rv="${REF_VAL[$i]}"
796
+ mf="$WORK/tag-${i}.manifest"
797
+ code="$(ghcr_get "https://ghcr.io/v2/${REPO}/manifests/$rv" "$mf")"
798
+ [[ "$(classify_code "$code")" == "OK" ]] || die_by_code "manifest for tag $rv" "$code"
799
+ D="sha256:$(sha256_file "$mf")"
800
+ # Seed the pool under the content name so fetch_artifact reuses, not re-GETs.
801
+ mkdir -p "$POOL" || die 6 "could not create the blob pool — filesystem fault."
802
+ [[ -f "$POOL/${D#sha256:}" ]] || cp "$mf" "$POOL/${D#sha256:}" || die 6 "could not seed the manifest pool — filesystem fault."
803
+ fi
804
+ fetch_artifact "$D" 0
805
+ bl="$WORK/unit-${i}.blobs"; sort -u "$CUR_BLOBS" > "$bl" || die 6 "could not write the unit blob list — filesystem fault."
806
+ case "${REF_KIND[$i]}" in
807
+ digest) UNIT_NAME+=("${REPO}@${D}") ;;
808
+ tag) UNIT_NAME+=("${REPO}:${REF_VAL[$i]}") ;;
809
+ esac
810
+ UNIT_DIGEST+=("$D")
811
+ UNIT_BLOBS+=("$bl")
812
+ UNIT_IS_SIG+=("0")
813
+ printf 'pulled ref[%d] %s=%s -> %s (%s objects)\n' "$((i + 1))" "${REF_KIND[$i]}" "${REF_VAL[$i]}" "$D" "$(wc -l < "$bl")"
814
+ i=$((i + 1))
815
+ done
816
+
817
+ # Signature phase: per UNIQUE image digest, the cosign referrers tag
818
+ # `sha256-<hex>` must exist at GHCR — a missing signature is a hard failure
819
+ # (there is no unsigned-mirror arm; ci-deploy verifies against the same registry).
820
+ j=0
821
+ while (( j < N_REFS )); do
822
+ D="${UNIT_DIGEST[$j]}"
823
+ if [[ "$SEEN_DIGESTS" == *" $D "* ]]; then j=$((j + 1)); continue; fi
824
+ SEEN_DIGESTS+="$D "
825
+ sig_tag="sha256-${D#sha256:}"
826
+ : > "$CUR_BLOBS"
827
+ code="$(ghcr_get "https://ghcr.io/v2/${REPO}/manifests/${sig_tag}" "$WORK/sig-${j}.manifest")"
828
+ case "$(classify_code "$code")" in
829
+ OK) ;;
830
+ NOTFOUND) die 4 "no cosign signature (${sig_tag}) found at GHCR for ${REPO}@${D} — or not visible to this credential; GHCR returns 404 for both. There is no unsigned-mirror arm: a mirrored image whose signature is absent fails cosign verify on the host." ;;
831
+ *) die_by_code "the signature ${sig_tag} for ${REPO}@${D} — this does NOT mean the signature is absent" "$code" ;;
832
+ esac
833
+ SIG_D="sha256:$(sha256_file "$WORK/sig-${j}.manifest")"
834
+ cp "$WORK/sig-${j}.manifest" "$POOL/${SIG_D#sha256:}" || die 6 "could not pool the signature manifest — filesystem fault."
835
+ printf '%s\n' "${SIG_D#sha256:}" >> "$CUR_BLOBS"
836
+ fetch_artifact "$SIG_D" 0
837
+ bl="$WORK/unit-sig-${j}.blobs"; sort -u "$CUR_BLOBS" > "$bl" || die 6 "could not write the sig blob list — filesystem fault."
838
+ UNIT_NAME+=("${REPO}:${sig_tag}")
839
+ UNIT_DIGEST+=("$SIG_D")
840
+ UNIT_BLOBS+=("$bl")
841
+ UNIT_IS_SIG+=("$D")
842
+ printf 'pulled sig[%d] %s -> %s (%s objects)\n' "$((j + 1))" "$sig_tag" "$SIG_D" "$(wc -l < "$bl")"
843
+ j=$((j + 1))
844
+ done
845
+
846
+ # The bearer is only needed for the pull phase.
847
+ unset TOK
848
+
849
+ # Push phase: private keychain; the sink is plain HTTP on the private net.
850
+ export DOCKER_CONFIG="$WORK/dockercfg"
851
+ mkdir -p "$DOCKER_CONFIG" || die 6 "could not create a private docker config directory."
852
+ if ! printf '%s' "$ZOT_PUSH_TOKEN" | "$CRANE" auth login "$ZOT_TARGET" -u "$ZOT_PUSH_USER" --password-stdin --insecure \
853
+ >"$WORK/login.out" 2>"$WORK/login.err"; then
854
+ die 5 "the crane login command for the sink ${ZOT_TARGET} (as '${ZOT_PUSH_USER}') failed locally — crane login stores the credential and never contacts the registry, so a wrong credential surfaces later. crane: $(last_err "$WORK/login.err")"
855
+ fi
856
+ unset ZOT_PUSH_TOKEN
857
+
858
+ N_UNITS=${#UNIT_NAME[@]}
859
+ u=0
860
+ while (( u < N_UNITS )); do
861
+ L="$WORK/layout-$u"
862
+ CUR_BLOBS="${UNIT_BLOBS[$u]}"
863
+ assemble_layout "${UNIT_DIGEST[$u]}" "$L"
864
+ if ! crane_capture "$WORK/push.out" "$WORK/push.err" push --insecure "$L" "${ZOT_TARGET}/${UNIT_NAME[$u]}"; then
865
+ sink_die "the push of ${UNIT_NAME[$u]}" "$WORK/push.err"
866
+ fi
867
+ printf 'pushed %s\n' "${ZOT_TARGET}/${UNIT_NAME[$u]}"
868
+ u=$((u + 1))
869
+ done
870
+
871
+ # Verify phase — AFTER all pushes, per the guard contract: digest parity first
872
+ # (a tag must resolve to the pinned digest), then blob completeness.
873
+ verified=0
874
+ u=0
875
+ while (( u < N_UNITS )); do
876
+ D="${UNIT_DIGEST[$u]}"
877
+ SUBJECT=""
878
+ case "${UNIT_IS_SIG[$u]}" in
879
+ 0) MODE="image" ;;
880
+ *) MODE="signature"; SUBJECT="${UNIT_IS_SIG[$u]}" ;;
881
+ esac
882
+ if [[ "${UNIT_NAME[$u]}" == *":"* && "${UNIT_NAME[$u]}" != *"@"* ]]; then
883
+ crane_capture "$WORK/dig.out" "$WORK/dig.err" digest --insecure "${ZOT_TARGET}/${UNIT_NAME[$u]}" \
884
+ || sink_die "the read-back of ${UNIT_NAME[$u]}" "$WORK/dig.err"
885
+ dst_digest="$(grep -oE 'sha256:[0-9a-f]{64}' "$WORK/dig.out" | head -1 || true)"
886
+ [[ -n "$dst_digest" ]] \
887
+ || die 4 "could not read ${UNIT_NAME[$u]} back from the sink — the mirror is UNVERIFIED."
888
+ [[ "$dst_digest" == "$D" ]] \
889
+ || die 4 "digest parity FAILED for ${UNIT_NAME[$u]} — pushed=${D} sink=${dst_digest}. A digest-pinned pull would not resolve against this mirror."
890
+ fi
891
+ verify_pushed "${ZOT_TARGET}/${REPO}" "$D" "${UNIT_NAME[$u]}" "$MODE" "$SUBJECT"
892
+ verified=$((verified + 1))
893
+ printf 'verified %s (mode=%s)\n' "${UNIT_NAME[$u]}" "$MODE"
894
+ u=$((u + 1))
895
+ done
896
+
897
+ # Non-vacuity floor: "verified nothing" can never report success.
898
+ (( verified > 0 )) \
899
+ || die 4 "verified ZERO references — every loop completed without error, which is exactly how a vacuous mirror reports success. Refusing."
900
+ (( verified == N_UNITS )) \
901
+ || die 4 "verified ${verified} of ${N_UNITS} pushed references — the remainder were never read back."
902
+
903
+ printf 'mirror_summary target=%s refs=%d sigs=%d verified=%d result=ok\n' \
904
+ "$ZOT_TARGET" "$N_REFS" "$((N_UNITS - N_REFS))" "$verified"
905
+ exit 0