@soleur/opencode 3.361.7 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soleur/opencode",
3
- "version": "3.361.7",
3
+ "version": "3.362.0",
4
4
  "description": "Soleur AI organization plugin for OpenCode",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,227 @@
1
+ ---
2
+ name: registry-breakglass-mirror
3
+ description: "This skill should be used for GHCR-to-Zot break-glass mirrors."
4
+ ---
5
+
6
+ <!-- soleur-cloud-mode:start -->
7
+ **Cloud Mode (Devin):** before pipeline work run `bash "${CLAUDE_PLUGIN_ROOT}/scripts/cloud-detect.sh"`. If `CLAUDE_PLUGIN_ROOT` is unset (cloud exec shells do not export it), resolve the root by IDENTITY, never by script basename: for `d` in `"$HOME/.local/share/devin/cli/plugins/cache"` and `/opt/.devin/plugins`, skip unless `[ -d "$d" ]`, then `MANIFEST="$(find "$d" -path '*/.claude-plugin/plugin.json' -exec grep -l '"name"[[:space:]]*:[[:space:]]*"soleur"' {} + 2>/dev/null | head -1)"`, `ROOT="${MANIFEST%/.claude-plugin/plugin.json}"` — one resolution, two consumers: `$ROOT/scripts/cloud-detect.sh` and `$ROOT/scripts/precommit-guard.sh`. (Shape check, not authentication: a planted `{"name":"soleur"}` dir passes — ADR-179 A11.) `local` or `not-local:no-devin-env` proceeds normally; any other `not-local:<reason>` applies `<plugin-root>/devin/INSTRUCTIONS.md` §Cloud Mode: emit the `--banner`, fan out sequentially with `Reviewed-Coverage: sequential-fallback` disclosure (never claim an independent review ran), `message_user` ack before any secrets read or production mutation, and run `precommit-guard.sh` before any `git commit` — hooks do not fire in cloud.
8
+ <!-- soleur-cloud-mode:end -->
9
+
10
+ <!-- grok-harness-invoke:start -->
11
+ **Grok Build (`plugins/soleur/lib/harness.ts` `invokeSkill()`):** Read this SKILL.md in this process and run it to completion. A one-segment `soleur:<name>` in this document names a SKILL — on Grok Build, Read `plugins/soleur/skills/<name>/SKILL.md` in this process; it is not a nested tool_use. A multi-segment id such as `soleur:<domain>:<name>` names an AGENT: spawn it, never Read it, and on Grok Build spawn_subagent takes the id with its colons replaced by hyphens (`agentIdToGrokSubagentType`). **Claude Code:** Skill tool for a skill (`soleur:<name>`), Task tool with `subagent_type` for an agent. Forbidden is executing a subset, not the Read.
12
+ <!-- grok-harness-invoke:end -->
13
+
14
+ # registry-breakglass-mirror
15
+
16
+ Re-materialize production's zot store (`10.0.1.30:5000`) from GHCR when the
17
+ Cloudflare Tunnel registry bridge is **down** — the one window in which
18
+ `registry-restore-from-ghcr.sh` (the luks-recut restore engine) cannot run,
19
+ because every CI path to zot traverses that bridge
20
+ (`.github/actions/cf-tunnel-registry-bridge/action.yml`).
21
+
22
+ This is a **break-glass** procedure. It is the documented, name-scoped exception
23
+ to the #9169 hosts-file ghcr deny (ADR-096 amendment 2026-10-28): a manual
24
+ operator/agent-invoked run, not a standing code path, not a host service, not a
25
+ standing credential.
26
+
27
+ ## When to use
28
+
29
+ - The `registry.` tunnel ingress (or the tunnel itself) is down **and** the zot
30
+ store must be (re)populated: post-restore backfill, a zot store that lost its
31
+ pinned image set, or a release image that never made the mirror leg.
32
+ - Do **not** reach for it when the bridge is alive — the routine restore path is
33
+ `registry-restore-from-ghcr.sh` over the tunnel, and the routine mirror is the
34
+ release pipeline itself.
35
+ - Do **not** use it to "test" GHCR connectivity — it writes to the sole pull
36
+ path production deploys read from.
37
+
38
+ ## Connectivity matrix — reaching the mirror host
39
+
40
+ The mirror runs **on a private-net datacenter host**, never on the operator's
41
+ machine and never over a forwarded connection (see **The hard DO-NOT** below).
42
+
43
+ `MIRROR_HOST` is parameterized — default `web-1`; any `10.0.1.0/24` member works.
44
+ Since ADR-304, `web-2` is the tunnel-connector host and `web-1` is LUKS-pinned
45
+ and unreplaceable (#6964); prefer a fresh cattle host when one is up, and prefer
46
+ `web-1` when the alternative is the connector host mid-incident.
47
+
48
+ | Path | Reach | Precondition |
49
+ |------|-------|--------------|
50
+ | **Primary** | `ssh.soleur.ai` through the Cloudflare Tunnel (`cloudflared access ssh` ProxyCommand, as `deploy`) | the tunnel is alive — i.e., NOT the break-glass window itself, but fine for a degraded-registry store while SSH still converges |
51
+ | **Fallback** | direct SSH to the host's public address as `deploy` | the operator's **current egress IP** must be in the Hetzner firewall allow-list (`Doppler prd_terraform/ADMIN_IPS`) — run `soleur:admin-ip-refresh` FIRST when the IP may have rotated; this is an L3 dependency that precedes every SSH-layer assumption |
52
+
53
+ If neither path reaches the host, stop here: the fault is connectivity, not the
54
+ mirror. Do not widen the firewall beyond `admin-ip-refresh`'s documented
55
+ mutation.
56
+
57
+ ## Credential sourcing (least privilege, exact forms)
58
+
59
+ | Credential | Source | Notes |
60
+ |------------|--------|-------|
61
+ | `DEPLOY_SSH_PRIVATE_KEY` | `doppler secrets get DEPLOY_SSH_PRIVATE_KEY -p soleur -c prd_terraform --plain` | write to a `0600` keyfile for the SSH legs |
62
+ | `ZOT_PUSH_USER` | `doppler secrets get ZOT_PUSH_USER -p soleur -c prd --plain` | root `prd` config, not `prd_terraform`; never "rotate ZOT_PUSH_* first" — `/etc/zot/htpasswd` is baked at registry boot |
63
+ | `ZOT_PUSH_TOKEN` | `doppler secrets get ZOT_PUSH_TOKEN -p soleur -c prd --plain` | second call — the multi-name form is an unverified CLI shape |
64
+ | `GHCR_TOKEN` | **operator-supplied at invocation** — a `read:packages` PAT the operator types or pastes | the Doppler `GHCR_READ_TOKEN` copy is **revoked BY DESIGN** (ADR-096 §5.5/B3 — no host reads GHCR); never reach for it |
65
+ | `GHCR_USER` | fixed | basic-auth username for the token exchange; default `operator`, charset-checked by the script |
66
+
67
+ Two `doppler secrets get` calls for `ZOT_PUSH_*` — one per secret, mirroring the
68
+ `scheduled-inngest-health.yml` credential pattern.
69
+
70
+ Host prerequisites on the mirror host: `curl`, `jq`, `sha256sum`, `timeout`
71
+ (the script die-6s on a missing one); `crane` is fetched pinned when absent.
72
+
73
+ ## Inputs — which repo, which refs
74
+
75
+ - **Repo:** `jikig-ai/soleur-web-platform` (the only image set production
76
+ deploys pin).
77
+ - **Refs:** the pinned image set. The canonical generator is
78
+ [registry-pull-path-health.sh](../../../../scripts/registry-pull-path-health.sh)
79
+ with `--prepare --tags-out` — the same
80
+ `entries[]` manifest `registry-restore-from-ghcr.sh --tags-from` consumes —
81
+ or the `registry-restore-pins` workflow artifact from the last restore run.
82
+ Digest refs (`repo@sha256:<d>`) are preferred — they bind the pin exactly;
83
+ tag refs resolve to the digest GHCR serves at mirror time.
84
+ - **Example:** `mirror-ghcr-to-zot.sh jikig-ai/soleur-web-platform \
85
+ jikig-ai/soleur-web-platform@sha256:<d1> jikig-ai/soleur-web-platform@sha256:<d2>`
86
+
87
+ ## The mirror host's GHCR exception (what the script does)
88
+
89
+ The web hosts sinkhole `ghcr.io`, `pkg-containers.githubusercontent.com`, and
90
+ `docker.pkg.github.com` to `0.0.0.0`/`::` in `/etc/hosts` (the #9169 accident
91
+ guard on name resolution — enumerated from
92
+ `apps/web-platform/infra/server.tf` `ghcr_deny_sh`). The script bypasses it with
93
+ **per-command `curl --resolve <name>:443:<ip>`** for the two names a pull needs —
94
+ `/etc/hosts` is never edited, TLS verification stays on (`--resolve` pins only
95
+ the dial address; SNI, the handshake, and CA verification still target the
96
+ hostname), and every pulled byte is verified at its sha256, so a wrong answer
97
+ cannot inject content. `pkg-containers.githubusercontent.com` MUST be resolved
98
+ too: GHCR blob GETs 307-redirect to it.
99
+
100
+ The IPs come from DNS-over-HTTPS at runtime (the host's own `getent` would
101
+ return the sinkhole), or from `GHCR_IP`/`PKGC_IP` env overrides when DoH is
102
+ unreachable.
103
+
104
+ ## The hard DO-NOT
105
+
106
+ **Never upload blobs through a forwarded registry connection.** zot PATCH
107
+ uploads die mid-stream over `ssh -L` and registries do not resume upload
108
+ sessions — measured during the 2026-10-28 O2 recovery: ~1.1–2.4 GB over the
109
+ operator's residential uplink failed repeatedly (~250 KiB–1.5 MB/s, HTTP/2
110
+ PROTOCOL_ERROR drops, ~1 h+), while the datacenter-side fetch on web-1 finished
111
+ in ~3 minutes. The doctrine: **pull where the bandwidth is; push over the
112
+ private net.** An operator improvising `ssh -L 5000:10.0.1.30:5000` + `crane
113
+ copy` reopens exactly this failure mode — the skill exists so that is never the
114
+ path of least resistance.
115
+
116
+ ## Cosign-signature mirroring is obligatory
117
+
118
+ `ci-deploy` cosign-verifies at deploy time and fetches the signature **from the
119
+ same registry it pulled the image from** (ADR-087). A mirrored image whose
120
+ signature is absent fails verification on the host — there is no
121
+ unsigned-mirror arm, and a missing signature is a hard failure, never a
122
+ warning. The signature rides the OCI referrers tag `sha256-<image-digest-hex>`
123
+ (the plan's `sha256-<hex>.sig` shorthand names this reference): GHCR serves it
124
+ as an OCI **index** whose *child* carries the `artifactType`
125
+ (`application/vnd.dev.sigstore.bundle.v0.3+json`) — the #7410 lesson. Reading
126
+ the tag as a plain manifest fail-closes a healthy signature; the script
127
+ mirrors the index structure and checks the child's `.subject.digest` binding
128
+ **where present** (a `sha256-<hex>` referrers tag name already carries the
129
+ binding).
130
+
131
+ ## Procedure
132
+
133
+ 1. **Stage credentials (operator side).** Source the four secrets per the table
134
+ above. `GHCR_TOKEN` is supplied by the operator at invocation.
135
+ 2. **Copy the engine to the host.** Copy
136
+ [mirror-ghcr-to-zot.sh](./scripts/mirror-ghcr-to-zot.sh) via `scp` to the
137
+ mirror host (`deploy@<MIRROR_HOST>` through whichever connectivity row is
138
+ up).
139
+ 3. **Dry-run first.** `mirror-ghcr-to-zot.sh --dry-run <repo> <ref>...` prints
140
+ the plan — resolved refs, blob counts, declared bytes, signature presence,
141
+ target — and pushes nothing. **Read the plan text, not just the exit code:**
142
+ a `sig=… ABSENT` verdict or `blobs=unmeasured` still exits 0 — both mean
143
+ "do not proceed" (supply `GHCR_TOKEN` for the count, and never mirror a ref
144
+ whose signature shows ABSENT).
145
+ 4. **Mirror.** Carry the environment to the host WITHOUT putting secrets on a
146
+ command line — never `ssh host 'GHCR_TOKEN=… bash …'` (the PAT lands on the
147
+ remote `bash -c` argv and the local `ssh` argv for the whole run). Feed
148
+ env+invocation over `ssh host bash -s` stdin, or write a `0600` env file,
149
+ `scp` it, then
150
+ `ssh deploy@<host> 'set -a; . ./mirror.env; set +a; ./mirror-ghcr-to-zot.sh …; rm -f ./mirror.env'`
151
+ (the `rm` matters — the env-file arm must not strand a credential file on
152
+ a prod host). The script pulls
153
+ manifests+blobs via `curl
154
+ --resolve`, assembles each ref into an OCI layout, `crane push`es to
155
+ `10.0.1.30:5000/<repo>` (plain-HTTP private net — `--insecure`, the standing
156
+ `hetzner -> zotRegistry` posture), mirrors the `sha256-<hex>` signature ref,
157
+ then read-back-verifies every pushed ref with `crane validate --remote`
158
+ (platform children) plus blob-presence (attestation/signature children) —
159
+ never `crane digest` alone; a manifest can outlive its layers under zot
160
+ gc+dedupe.
161
+ 5. **Close out.** Exit `0` prints `mirror_summary ... result=ok`. Anything else
162
+ is a non-zero exit with the failing ref named — do not treat the store as
163
+ usable. Then verify the deploy path resolves the digest: from a second
164
+ `10.0.1.0/24` member,
165
+ `crane digest --insecure 10.0.1.30:5000/jikig-ai/soleur-web-platform@sha256:<d>`
166
+ must return the same `sha256:<d>` (or `ssh deploy@<host> 'docker manifest
167
+ inspect 10.0.1.30:5000/jikig-ai/soleur-web-platform@sha256:<d>'`).
168
+
169
+ ## Failure vocabulary
170
+
171
+ Name **only measured causes** (ADR-166). On this path the measured facts are the
172
+ http_code the pull leg observed and the crane error the push/verify leg
173
+ observed. The closed verdict vocabulary for the CI mirror path —
174
+ `live` / `stale` / `unverifiable` / `unmeasured` — lives in
175
+ [zot-mirror-diagnosis.sh](../../../../scripts/zot-mirror-diagnosis.sh); its rule
176
+ applies here too: no failure message may name a cause nothing measured (e.g.,
177
+ GHCR 404 means "absent **or not visible to this credential**", not "the image
178
+ is gone").
179
+
180
+ ## Exit codes (the script's)
181
+
182
+ - `0` — every required reference pushed AND read-back-verified.
183
+ - `1` — usage/configuration error.
184
+ - `2` — GHCR/source leg failed (unreachable, 5xx, credential rejected, 404).
185
+ - `3` — sink (zot) unavailable; retryable.
186
+ - `4` — verification failed: the copy "succeeded" and the result is unusable
187
+ (missing blob, digest mismatch, missing signature). NOT retryable.
188
+ - `5` — credential unusable (absent/empty, or rejected by the sink).
189
+ - `6` — unclassified; loudest arm, file it.
190
+ - `78` — refused to run under `bash -x` while a credential is set (#7797).
191
+
192
+ ## Sharp Edges
193
+
194
+ - **`docker.pkg.github.com` is sinkholed too** and is deliberately never
195
+ resolved — nothing on the GHCR pull path needs it.
196
+ - **`GHCR_TOKEN` is operator-supplied on purpose.** There is no zero-touch GHCR
197
+ read path by construction (ADR-088 arm-b): the Doppler copy is revoked and
198
+ stays revoked.
199
+ - **Digest refs push by digest** (`<repo>@sha256:<d>`); tag refs push by tag.
200
+ zot keeps digest-pushed manifests digest-addressable — exactly what the
201
+ pinned deploy refs need. Prefer passing a tag ref when the intended pull is
202
+ `repo:tag`, a digest ref when it is `repo@sha256:`.
203
+ - **Do not edit `/etc/hosts`** "to make it easier" — the deny must stay in
204
+ force after the mirror; per-command `--resolve` is the whole exception.
205
+ - **`crane` is fetched pinned** (v0.20.2 release tarball + sha256) when absent —
206
+ github.com is not sinkholed.
207
+ - **Multiple refs in one run are fine** and each is verified independently; a
208
+ later failure does not un-verify earlier successes — re-run the failing refs.
209
+
210
+ ## Related
211
+
212
+ - [mirror-ghcr-to-zot.sh](./scripts/mirror-ghcr-to-zot.sh) — the engine (usage,
213
+ env contract, exit codes in its header).
214
+ - `registry-restore-from-ghcr.sh` — the luks-recut restore engine this skill
215
+ stands in for while the bridge is down (runs over the tunnel; its
216
+ invariants — signature copy, `crane validate --remote`, credential hygiene —
217
+ are carried, not the engine).
218
+ - [zot-mirror-diagnosis.sh](../../../../scripts/zot-mirror-diagnosis.sh) — the
219
+ measured-cause vocabulary (`live`/`stale`/`unverifiable`/`unmeasured`).
220
+ - `soleur:admin-ip-refresh` — the direct-SSH fallback's firewall precondition.
221
+ - `soleur:cf-token-scope` — Cloudflare-token probe discipline reference.
222
+ - ADR-096 (the deny + its 2026-10-28 break-glass amendment), ADR-087 (cosign),
223
+ ADR-166 (cause vocabulary), ADR-169 (restore authorization), ADR-304
224
+ (connector placement). Learnings:
225
+ `2026-09-28-an-ssh-drop-without-a-pty-is-sigpipe-and-my-cleanup-trap-read-it-as-success`,
226
+ `2026-08-05-every-green-signal-certified-something-other-than-what-it-claimed`.
227
+ - Issue: #11424.
@@ -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
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env bash
2
+ # Network-free fixture suite for mirror-ghcr-to-zot.sh (#11424, review coverage
3
+ # P3 — the engine's declared CRANE_CMD/PATH seams are exercised here).
4
+ #
5
+ # Method: a stub `curl` on PATH serves canned responses by URL shape (DoH JSON,
6
+ # token exchange, manifest GETs); a stub `crane` proves the binary is never
7
+ # invoked under --dry-run. The whole resolve→exchange→count→report path runs
8
+ # offline; nothing contacts GHCR, zot, or the internet.
9
+ #
10
+ # Run: bash plugins/soleur/skills/registry-breakglass-mirror/test/mirror-ghcr-to-zot.test.sh
11
+ set -uo pipefail
12
+
13
+ DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
14
+ SCRIPT="$DIR/../scripts/mirror-ghcr-to-zot.sh"
15
+ passes=0; fails=0
16
+ pass() { passes=$((passes + 1)); }
17
+ fail() { fails=$((fails + 1)); echo "FAIL: $1" >&2; }
18
+
19
+ [ -f "$SCRIPT" ] || { echo "FAIL: engine not found at $SCRIPT" >&2; exit 1; }
20
+ [ -x "$SCRIPT" ] || { echo "FAIL: engine not executable at $SCRIPT" >&2; exit 1; }
21
+
22
+ WORK_T="$(mktemp -d)"; trap 'rm -rf "$WORK_T"' EXIT
23
+ STUB="$WORK_T/bin"; mkdir -p "$STUB"
24
+ FIX="$WORK_T/fix"; mkdir -p "$FIX" "$FIX/blobs" "$FIX/bydigest"
25
+
26
+ # --- fixtures -----------------------------------------------------------------
27
+ # Real-content blobs: every digest the fixtures declare is backed by a file
28
+ # whose sha256 IS that digest — the script's every-byte-verified discipline
29
+ # can run honestly offline.
30
+ mkblob() { local c="$1" h; printf '%s' "$c" > "$FIX/raw"; h="$(sha256sum "$FIX/raw" | cut -d' ' -f1)"; cp "$FIX/raw" "$FIX/blobs/$h"; printf '%s' "$h"; }
31
+ CFG="$(mkblob 'cfg')" L1="$(mkblob 'l1')" L2="$(mkblob 'l2')"
32
+ SIGB="$(mkblob 'sig-payload')" SIGCFG="$(mkblob 'sigcfg')"
33
+
34
+ cat > "$FIX/manifest.json" <<EOF
35
+ {"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{"mediaType":"application/vnd.oci.image.config.v1+json","digest":"sha256:${CFG}","size":3},"layers":[{"mediaType":"application/vnd.oci.image.layer.v1.tar+gzip","digest":"sha256:${L1}","size":2},{"mediaType":"application/vnd.oci.image.layer.v1.tar+gzip","digest":"sha256:${L2}","size":2}]}
36
+ EOF
37
+ MHEX="$(sha256sum "$FIX/manifest.json" | cut -d' ' -f1)"
38
+ cp "$FIX/manifest.json" "$FIX/bydigest/$MHEX"
39
+ # Signature child: a plain manifest whose subject binds the image digest.
40
+ cat > "$FIX/sigchild.json" <<EOF
41
+ {"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{"mediaType":"application/vnd.oci.image.config.v1+json","digest":"sha256:${SIGCFG}","size":6},"layers":[{"mediaType":"application/vnd.dev.sigstore.bundle.v0.3+json","digest":"sha256:${SIGB}","size":10}],"subject":{"digest":"sha256:${MHEX}"}}
42
+ EOF
43
+ SCHEX="$(sha256sum "$FIX/sigchild.json" | cut -d' ' -f1)"
44
+ cp "$FIX/sigchild.json" "$FIX/bydigest/$SCHEX"
45
+ # Signature index: referrers tag sha256-<MHEX> serves this index.
46
+ SZC=$(stat -c %s "$FIX/sigchild.json")
47
+ cat > "$FIX/sigidx.json" <<EOF
48
+ {"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json","manifests":[{"mediaType":"application/vnd.oci.image.manifest.v1+json","digest":"sha256:${SCHEX}","size":${SZC},"artifactType":"application/vnd.dev.sigstore.bundle.v0.3+json"}]}
49
+ EOF
50
+ SHEX="$(sha256sum "$FIX/sigidx.json" | cut -d' ' -f1)"
51
+ cp "$FIX/sigidx.json" "$FIX/bydigest/$SHEX"
52
+ cp "$FIX/sigidx.json" "$FIX/sig-tag.json" # the sha256-<hex> referrers tag body
53
+
54
+ cat > "$FIX/token.json" <<'EOF'
55
+ {"token":"test-bearer"}
56
+ EOF
57
+ cat > "$FIX/doh.json" <<'EOF'
58
+ {"Status":0,"Answer":[{"name":"ghcr.io","type":1,"data":"140.82.121.34"}]}
59
+ EOF
60
+
61
+ # --- stubs --------------------------------------------------------------------
62
+ cat > "$STUB/curl" <<EOF
63
+ #!/usr/bin/env bash
64
+ # Serve canned bodies by URL shape; -o FILE is the last-but-two arg convention
65
+ # the engine uses. http_code is printed to stdout by -w.
66
+ url=""; out=""; wfmt=""
67
+ while [[ \$# -gt 0 ]]; do
68
+ case "\$1" in
69
+ -o) out="\$2"; shift 2 ;;
70
+ -w) wfmt="\$2"; shift 2 ;;
71
+ http*|ghcr.io*|pkg-containers*) url="\$1"; shift ;;
72
+ *) shift ;;
73
+ esac
74
+ done
75
+ body=""
76
+ case "\$url" in
77
+ *dns-query*|*dns.google*|*resolve?*) body="$FIX/doh.json" ;;
78
+ *"/token?"*) body="$FIX/token.json" ;;
79
+ */manifests/sha256-*) body="$FIX/sig-tag.json" ;; # referrers tag
80
+ */manifests/sha256:*)
81
+ hex="\${url##*sha256:}"; [[ -f "$FIX/bydigest/\$hex" ]] && body="$FIX/bydigest/\$hex" ;;
82
+ */manifests/*) body="$FIX/manifest.json" ;;
83
+ */blobs/sha256:*)
84
+ hex="\${url##*sha256:}"; [[ -f "$FIX/blobs/\$hex" ]] && body="$FIX/blobs/\$hex" ;;
85
+ *) body="" ;;
86
+ esac
87
+ if [[ -n "\$out" ]]; then
88
+ [[ -n "\$body" ]] && cp "\$body" "\$out" || printf '{}' > "\$out"
89
+ elif [[ -n "\$body" ]]; then
90
+ cat "\$body" # no -o: caller (DoH probe) reads the body on stdout
91
+ fi
92
+ [[ "\$wfmt" == *http_code* ]] && printf '200'
93
+ exit 0
94
+ EOF
95
+ cat > "$STUB/crane" <<EOF
96
+ #!/usr/bin/env bash
97
+ echo "STUB-CRANE-INVOKED \$*" >> "\${CRANE_LOG:-/dev/null}"
98
+ sub="\$1"; shift 2>/dev/null || true
99
+ ref=""
100
+ for a in "\$@"; do case "\$a" in *@sha256:*|*:sha256-*) ref="\$a" ;; esac; done
101
+ case "\$sub" in
102
+ manifest) hex="\${ref##*sha256:}"; [[ -f "$FIX/bydigest/\$hex" ]] && cat "$FIX/bydigest/\$hex" || exit 1 ;;
103
+ digest) case "\$ref" in *:sha256-*) printf 'sha256:%s\n' "\$(sha256sum "$FIX/sig-tag.json" | cut -d' ' -f1)" ;; *) grep -oE 'sha256:[0-9a-f]{64}' <<<"\$ref" | head -1 ;; esac ;;
104
+ push|blob|validate|auth) exit 0 ;;
105
+ *) exit 0 ;;
106
+ esac
107
+ exit 0
108
+ EOF
109
+ chmod +x "$STUB/curl" "$STUB/crane"
110
+
111
+ run_dry() { # <args...> → OUT/RC; stub PATH + token + CRANE_CMD
112
+ CRANE_LOG="$WORK_T/crane.log"; : > "$CRANE_LOG"; export CRANE_LOG
113
+ OUT="$(env PATH="$STUB:$PATH" GHCR_TOKEN="test-pat" CRANE_CMD="$STUB/crane" GHCR_IP="" PKGC_IP="" \
114
+ bash "$SCRIPT" --dry-run "$@" 2>/dev/null)"
115
+ RC=$?
116
+ }
117
+
118
+ # ── (a) a manifest ref dry-runs with measured blob counts — kills the
119
+ # `[.layers | .size]` array-index bug class (must print blobs=3 bytes=7) ──
120
+ HEX="$MHEX"
121
+ run_dry jikig-ai/soleur-web-platform "jikig-ai/soleur-web-platform@sha256:${HEX}"
122
+ if [[ "$RC" -eq 0 ]] && [[ "$OUT" == *"blobs=3"* ]]; then pass; else fail "(a) manifest dry-run → expected rc=0 blobs=3, got rc=$RC OUT='$OUT'"; fi
123
+
124
+ # ── (b) crane is never invoked under --dry-run (the fetch is gated) ──
125
+ if [[ ! -s "$CRANE_LOG" ]]; then pass; else fail "(b) dry-run invoked crane: $(cat "$CRANE_LOG")"; fi
126
+
127
+ # ── (c) tokenless dry-run prints blobs=unmeasured and exits 0 ──
128
+ OUT="$(env -u GHCR_TOKEN PATH="$STUB:$PATH" CRANE_CMD="$STUB/crane" bash "$SCRIPT" --dry-run jikig-ai/soleur-web-platform v1.2.3 2>/dev/null)"
129
+ RC=$?
130
+ if [[ "$RC" -eq 0 ]] && [[ "$OUT" == *"blobs=unmeasured"* ]]; then pass; else fail "(c) tokenless dry-run → expected rc=0 blobs=unmeasured, got rc=$RC OUT='$OUT'"; fi
131
+
132
+ # ── (d) malformed ref dies 1 (usage), never reaches the network leg ──
133
+ OUT="$(env PATH="$STUB:$PATH" bash "$SCRIPT" --dry-run jikig-ai/soleur-web-platform 'not a ref' 2>&1 >/dev/null)"
134
+ RC=$?
135
+ if [[ "$RC" -eq 1 ]] && [[ "$OUT" == *"mirror-ghcr-to-zot:"* ]]; then pass; else fail "(d) malformed ref → expected rc=1 + diagnostic, got rc=$RC OUT='$OUT'"; fi
136
+
137
+ # ── (e) ZOT_TARGET shape guard fails closed on a hostile value ──
138
+ OUT="$(env PATH="$STUB:$PATH" GHCR_TOKEN="x" ZOT_TARGET="evil host:5000" bash "$SCRIPT" --dry-run jikig-ai/soleur-web-platform v1.2.3 2>&1 >/dev/null)"
139
+ RC=$?
140
+ if [[ "$RC" -eq 1 ]] && [[ "$OUT" == *"ZOT_TARGET"* ]]; then pass; else fail "(e) hostile ZOT_TARGET → expected rc=1 naming ZOT_TARGET, got rc=$RC OUT='$OUT'"; fi
141
+
142
+ # ── (h) LIVE path end-to-end with stubs: pull→layout→push→verify → result=ok.
143
+ # Exercises verify_blobs_of's manifest arm (the signature child) — the
144
+ # array-index jq bug class must never regress on the verify path. ──
145
+ OUT="$(env PATH="$STUB:$PATH" GHCR_TOKEN="test-pat" ZOT_PUSH_USER="u" ZOT_PUSH_TOKEN="t" CRANE_CMD="$STUB/crane" GHCR_IP="" PKGC_IP="" \
146
+ bash "$SCRIPT" "jikig-ai/soleur-web-platform" "jikig-ai/soleur-web-platform@sha256:${MHEX}" 2>/dev/null)"
147
+ RC=$?
148
+ if [[ "$RC" -eq 0 ]] && [[ "$OUT" == *"result=ok"* && "$OUT" == *"mode=signature"* ]]; then pass; else fail "(h) live run → expected rc=0 result=ok + signature verify, got rc=$RC OUT='$OUT'"; fi
149
+
150
+ # ── (f) GHCR_USER charset guard fails closed ──
151
+ OUT="$(env PATH="$STUB:$PATH" GHCR_TOKEN="x" GHCR_USER='bad"user' bash "$SCRIPT" --dry-run jikig-ai/soleur-web-platform "jikig-ai/soleur-web-platform@sha256:${HEX}" 2>&1 >/dev/null)"
152
+ RC=$?
153
+ if [[ "$RC" -eq 5 ]] && [[ "$OUT" == *"GHCR_USER"* ]]; then pass; else fail "(f) bad GHCR_USER → expected rc=5 naming GHCR_USER, got rc=$RC OUT='$OUT'"; fi
154
+
155
+ echo "mirror-ghcr-to-zot: $passes passed, $fails failed"
156
+ [ "$fails" -eq 0 ] || exit 1