Skip to main content

polyc_runtime/
ghcr.rs

1//! Shared OCI-registry helpers: the published-component roster plus immutable
2//! manifest-digest resolution, registry-agnostic.
3//!
4//! The cluster-upgrade path lives in two binaries — the operator CLI's
5//! executor (`polychrome upgrade --cluster`) rolls the images, and the control
6//! plane's mailbox originator captures the digests when it opens the approval
7//! ask. Both must agree on *which* images are published, *where* they live, and
8//! *how* a version's tag resolves to an immutable `sha256:…` content address, so
9//! that logic lives here once rather than duplicated per binary.
10//!
11//! Where the images live is configuration, not a constant. The open-source
12//! default is the public GHCR repositories; a private deployment overrides each
13//! component's full image reference (registry host + repository) through the
14//! `POLYCHROME_UPGRADE_IMAGE_*` environment variables — for example a Google
15//! Artifact Registry path like
16//! `us-east4-docker.pkg.dev/<project>/docker/polychrome-control-plane`. The
17//! reference carries no tag; the tag is derived from the target version.
18//!
19//! Resolution follows the OCI distribution flow: obtain a bearer token for the
20//! registry, `GET` the manifest, and read the registry-computed
21//! `Docker-Content-Digest` header — the canonical content address pinned onto
22//! the cluster. We never float a tag onto a running cluster. Which credential
23//! the token comes from depends on the registry host: a public GHCR repository
24//! uses the anonymous pull-token endpoint, while Google Artifact Registry / GCR
25//! uses a GCP OAuth access token.
26
27use std::time::Duration;
28
29/// Registry host assumed when a configured image reference names no host (the
30/// standard Docker heuristic: a leading path segment without a `.` or `:` is a
31/// repository namespace, not a registry).
32const DEFAULT_REGISTRY: &str = "ghcr.io";
33
34/// Bounds the registry TCP connect so a dead host fails fast.
35const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
36
37/// Overall per-request budget for a registry round-trip.
38const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
39
40/// A digest-resolution failure.
41///
42/// A library error (`thiserror`) so callers on `anyhow` can add context and
43/// callers on `thiserror` can wrap it.
44#[derive(Debug, thiserror::Error)]
45pub enum GhcrError {
46    /// The target version did not parse as semver (so it can't map to a
47    /// published image tag).
48    #[error("target version `{0}` is not valid semver")]
49    Version(String),
50    /// The HTTP client could not be built or a request failed in transport.
51    #[error("registry request failed: {0}")]
52    Http(#[from] reqwest::Error),
53    /// The registry accepted the request but returned no usable body/header
54    /// (no token, or no digest header on the manifest response).
55    #[error("registry response for {repo} had no {what}")]
56    Malformed {
57        /// The image repository the request was for.
58        repo: String,
59        /// What was missing (`pull token` / `digest header`).
60        what: &'static str,
61    },
62    /// A GCP access token could not be obtained for a `*.pkg.dev` / `*.gcr.io`
63    /// registry, so the digest cannot be resolved. Fail closed rather than fall
64    /// back to an anonymous request that would 401.
65    #[error("could not obtain a GCP access token for registry `{registry}`: {reason}")]
66    GcpToken {
67        /// The registry host the token was needed for.
68        registry: String,
69        /// Why the token could not be obtained.
70        reason: String,
71    },
72}
73
74/// One published component the cluster upgrade rolls.
75///
76/// Carries a short stable `name` (also the key an operator decision's signed
77/// digest set is keyed on and the `--digest <name>=…` CLI arg uses), the
78/// `Deployment` resource name, the `container` name inside the pod spec, the
79/// environment variable that overrides its image reference, and the GHCR
80/// default reference used when that variable is unset.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct Component {
83    /// Short stable identifier (`control-plane` / `slack` / `telegram`). The key
84    /// in a signed decision's digest set and the `--digest` CLI arg.
85    pub name: &'static str,
86    /// `metadata.name` of the `Deployment`.
87    pub deployment: &'static str,
88    /// `spec.template.spec.containers[].name` the image lives on.
89    pub container: &'static str,
90    /// Environment variable that, when set, overrides this component's full
91    /// image reference (registry host + repository, no tag).
92    pub image_env: &'static str,
93    /// Default image reference (public GHCR) used when [`Component::image_env`]
94    /// is unset. May name a host or be a bare `owner/repo` (defaults to
95    /// `ghcr.io`).
96    pub default_image: &'static str,
97}
98
99impl Component {
100    /// The bare GHCR image name this component actually publishes under —
101    /// [`Component::default_image`]'s final path segment (e.g. `polychrome`,
102    /// `polychrome-slack`, `polychrome-telegram`).
103    ///
104    /// This, not [`Component::name`], is the key
105    /// `.github/workflows/publish.yml`'s `channel` job and
106    /// `scripts/make_channel.sh` write `release-images.yaml` entries under
107    /// (`crate::release_manifest::ManifestImage::name`) — the manifest is
108    /// keyed by what was actually published, not by the CLI-facing
109    /// identifier. [`Component::name`] remains the short stable id used for
110    /// the `--digest <name>=…` CLI arg and a signed decision's digest set.
111    #[must_use]
112    pub fn ghcr_basename(&self) -> &str {
113        self.default_image
114            .rsplit('/')
115            .next()
116            .unwrap_or(self.default_image)
117    }
118
119    /// Rank that orders a rollout. A component with a lower rank must reach the
120    /// new version before a component with a higher rank.
121    ///
122    /// The state plane rolls first. The control plane dials it as the first
123    /// statement of `run` and fails closed, so a control plane that starts
124    /// against a state plane still on the old version crash-loops. See
125    /// `docs/operations/promotion.md`, "Roll the state plane first".
126    ///
127    /// Every other component shares one rank. The runbook states no order among
128    /// them, so this method does not invent one. A stable sort therefore keeps
129    /// them in [`COMPONENTS`] order.
130    #[must_use]
131    pub fn rollout_rank(&self) -> u8 {
132        u8::from(self.name != STATE_COMPONENT_NAME)
133    }
134}
135
136/// [`Component::name`] of the state plane, the component that rolls first.
137///
138/// Named once so [`Component::rollout_rank`] does not repeat the literal, and
139/// so `state_rolls_before_every_other_component` fails loudly if the roster
140/// entry is ever renamed out from under the ordering.
141pub const STATE_COMPONENT_NAME: &str = "state";
142
143/// The Deployments an upgrade rolls.
144///
145/// Names/containers verified against `manifests/base/*-deployment.yaml`,
146/// `manifests/components/edges/trigger/deployment.yaml`, and
147/// `manifests/components/scaffold/deployment.yaml`; default images against
148/// `publish.yml`.
149///
150/// `scaffold`'s `default_image` names the GHCR basename it *would* publish
151/// under if it ever did, purely so `Component::ghcr_basename` stays
152/// well-formed — `.github/workflows/publish.yml` deliberately does NOT
153/// publish it (`cloudbuild.yaml`: "scaffold is a GAR-only provisioning
154/// connector"), so a hand-run upgrade with no `POLYCHROME_UPGRADE_IMAGE_SCAFFOLD`
155/// override correctly fails loud (`ReleaseManifestError::MissingComponent`)
156/// rather than silently resolving a public image that doesn't exist — the
157/// same no-legacy, no-silent-fallback rule every other digest source already
158/// follows. Every real deployment (including prod) sets the override.
159///
160/// `trigger` (#1325 investigation) — unlike scaffold, it IS published to GHCR
161/// (`publish.yml`'s edge matrix) — was missing from this list entirely, so a
162/// hand-run upgrade could never roll it past its `REPLACE_AT_BUILD_TIME`
163/// placeholder image; a fresh `polychrome install` left that Deployment
164/// permanently stuck at `InvalidImageName` with no sanctioned way to fix it.
165/// Reproduced live bringing up a second GKE cluster with the gke overlay's
166/// full edge set composed.
167pub const COMPONENTS: [Component; 7] = [
168    Component {
169        name: "control-plane",
170        deployment: "polychrome-control-plane",
171        container: "polychrome",
172        image_env: "POLYCHROME_UPGRADE_IMAGE_CONTROL_PLANE",
173        default_image: "ghcr.io/officialunofficial/polychrome",
174    },
175    Component {
176        name: "state",
177        deployment: "polychrome-state",
178        container: "polychrome-state",
179        image_env: "POLYCHROME_UPGRADE_IMAGE_STATE",
180        default_image: "ghcr.io/officialunofficial/polychrome-state",
181    },
182    Component {
183        name: "harness",
184        deployment: "polychrome-harness",
185        container: "polychrome-harness",
186        image_env: "POLYCHROME_UPGRADE_IMAGE_HARNESS",
187        default_image: "ghcr.io/officialunofficial/polychrome-harness",
188    },
189    Component {
190        name: "slack",
191        deployment: "polychrome-slack",
192        container: "polychrome-slack",
193        image_env: "POLYCHROME_UPGRADE_IMAGE_SLACK",
194        default_image: "ghcr.io/officialunofficial/polychrome-slack",
195    },
196    Component {
197        name: "telegram",
198        deployment: "polychrome-telegram",
199        container: "polychrome-telegram",
200        image_env: "POLYCHROME_UPGRADE_IMAGE_TELEGRAM",
201        default_image: "ghcr.io/officialunofficial/polychrome-telegram",
202    },
203    Component {
204        name: "trigger",
205        deployment: "polychrome-trigger",
206        container: "polychrome-trigger",
207        image_env: "POLYCHROME_UPGRADE_IMAGE_TRIGGER",
208        default_image: "ghcr.io/officialunofficial/polychrome-trigger",
209    },
210    Component {
211        name: "scaffold",
212        deployment: "polychrome-scaffold",
213        container: "scaffold",
214        image_env: "POLYCHROME_UPGRADE_IMAGE_SCAFFOLD",
215        default_image: "ghcr.io/officialunofficial/polychrome-scaffold",
216    },
217];
218
219/// A resolved image reference — a registry host plus a repository, carrying no
220/// tag. The tag is derived per upgrade from the target version.
221#[derive(Debug, Clone, PartialEq, Eq)]
222pub struct ImageRef {
223    /// Registry host (e.g. `ghcr.io` or `us-east4-docker.pkg.dev`).
224    pub registry: String,
225    /// Repository path within the registry (e.g.
226    /// `officialunofficial/polychrome` or
227    /// `official-unofficial/docker/polychrome-control-plane`).
228    pub repository: String,
229}
230
231/// Split a full image reference string into its registry host and repository.
232///
233/// Applies the standard Docker heuristic: the segment before the first `/` is
234/// the registry host **iff** it contains a `.` or a `:` (a hostname or
235/// `host:port`); otherwise there is no host and the whole string is a
236/// repository under the default registry (`ghcr.io`).
237///
238/// # Examples
239/// - `us-east4-docker.pkg.dev/official-unofficial/docker/polychrome-control-plane`
240///   → registry `us-east4-docker.pkg.dev`, repo
241///   `official-unofficial/docker/polychrome-control-plane`.
242/// - `officialunofficial/polychrome` → registry `ghcr.io`, repo
243///   `officialunofficial/polychrome`.
244#[must_use]
245pub fn parse_image_ref(full: &str) -> ImageRef {
246    match full.split_once('/') {
247        Some((host, rest)) if host.contains('.') || host.contains(':') => ImageRef {
248            registry: host.to_owned(),
249            repository: rest.to_owned(),
250        },
251        _ => ImageRef {
252            registry: DEFAULT_REGISTRY.to_owned(),
253            repository: full.to_owned(),
254        },
255    }
256}
257
258/// Resolve a component's image reference from the environment, falling back to
259/// its public GHCR default.
260///
261/// The environment lookup is injected (rather than read from the process) so
262/// this stays a pure function — unit-testable without touching global state.
263/// Production callers pass `|k| std::env::var(k).ok()`.
264#[must_use]
265pub fn image_ref<F>(component: &Component, env_lookup: F) -> ImageRef
266where
267    F: Fn(&str) -> Option<String>,
268{
269    let raw = env_lookup(component.image_env).unwrap_or_else(|| component.default_image.to_owned());
270    parse_image_ref(&raw)
271}
272
273/// Normalize a `--version` / release tag into the image tag published.
274///
275/// `publish.yml` tags release manifests `{{version}}` (no leading `v`), so a
276/// release `v0.4.0` (or `--version v0.4.0`) maps to the image tag `0.4.0`. The
277/// tag is validated as semver so a typo can't pin the cluster to a
278/// non-existent / floating tag.
279///
280/// # Errors
281/// Returns [`GhcrError::Version`] if the stripped tag is not valid semver.
282pub fn image_tag_for_version(version: &str) -> Result<String, GhcrError> {
283    let tag = version.trim().trim_start_matches('v');
284    semver::Version::parse(tag).map_err(|_| GhcrError::Version(version.to_owned()))?;
285    Ok(tag.to_owned())
286}
287
288/// Build the digest-pinned image reference from a resolved [`ImageRef`] and a
289/// content digest (`{registry}/{repository}@{digest}`).
290#[must_use]
291pub fn pinned_reference(image: &ImageRef, digest: &str) -> String {
292    format!("{}/{}@{}", image.registry, image.repository, digest)
293}
294
295/// How to authenticate a digest-resolution request against a registry host.
296///
297/// Selected purely from the host by [`auth_for`]; the effectful token fetch is
298/// isolated behind each variant in [`resolve_digest`].
299#[derive(Debug, Clone, Copy, PartialEq, Eq)]
300pub enum RegistryAuth {
301    /// The OCI anonymous pull-token flow (public GHCR): `GET /token?scope=…`.
302    AnonymousToken,
303    /// A GCP OAuth access token, for Google Artifact Registry (`*.pkg.dev`) and
304    /// Container Registry (`*.gcr.io`).
305    GcpMetadata,
306}
307
308/// Pick the registry-auth strategy for a host.
309///
310/// Google Artifact Registry (`*.pkg.dev`) and Container Registry (`gcr.io` /
311/// `*.gcr.io`) require a GCP OAuth token; every other host (notably public
312/// GHCR) uses the anonymous pull-token flow.
313#[must_use]
314pub fn auth_for(registry: &str) -> RegistryAuth {
315    if registry.ends_with(".pkg.dev") || registry == "gcr.io" || registry.ends_with(".gcr.io") {
316        RegistryAuth::GcpMetadata
317    } else {
318        RegistryAuth::AnonymousToken
319    }
320}
321
322/// Build the shared HTTP client used for registry round-trips (bounded connect
323/// and request timeouts, a `polychrome/<version>` user agent).
324///
325/// # Errors
326/// Returns [`GhcrError::Http`] if the client can't be constructed.
327pub fn http_client() -> Result<reqwest::Client, GhcrError> {
328    Ok(reqwest::Client::builder()
329        .timeout(REQUEST_TIMEOUT)
330        .connect_timeout(CONNECT_TIMEOUT)
331        .user_agent(concat!("polychrome/", env!("CARGO_PKG_VERSION")))
332        .build()?)
333}
334
335/// Resolve the immutable manifest digest for `repository:tag` against `registry`.
336///
337/// The auth strategy is chosen from the host by [`auth_for`]: a public GHCR
338/// repository authenticates with an anonymous bearer token from the registry
339/// `token` endpoint, while a Google Artifact Registry / GCR host authenticates
340/// with a GCP OAuth access token.
341///
342/// The `GET` reads the `Docker-Content-Digest` response header — the registry
343/// computes it over the manifest bytes, so it is the canonical content address.
344///
345/// # Errors
346/// Returns [`GhcrError`] if the bearer token can't be obtained, the manifest
347/// request fails, or the response carries no digest header.
348pub async fn resolve_digest(
349    client: &reqwest::Client,
350    registry: &str,
351    repository: &str,
352    tag: &str,
353) -> Result<String, GhcrError> {
354    let token = match auth_for(registry) {
355        RegistryAuth::AnonymousToken => anonymous_pull_token(client, registry, repository).await?,
356        RegistryAuth::GcpMetadata => gcp_access_token(client, registry).await?,
357    };
358    let url = format!("https://{registry}/v2/{repository}/manifests/{tag}");
359    let resp = client
360        .get(&url)
361        .bearer_auth(&token)
362        // Accept both the OCI image index and the Docker manifest-list media
363        // types so multi-arch published images resolve to their index digest.
364        .header(
365            reqwest::header::ACCEPT,
366            "application/vnd.oci.image.index.v1+json, \
367             application/vnd.docker.distribution.manifest.list.v2+json, \
368             application/vnd.oci.image.manifest.v1+json, \
369             application/vnd.docker.distribution.manifest.v2+json",
370        )
371        .send()
372        .await?
373        .error_for_status()?;
374    let digest = resp
375        .headers()
376        .get("docker-content-digest")
377        .and_then(|v| v.to_str().ok())
378        .ok_or_else(|| GhcrError::Malformed {
379            repo: repository.to_owned(),
380            what: "digest header",
381        })?
382        .to_owned();
383    Ok(digest)
384}
385
386/// Fetch an anonymous pull token for a public repository (the OCI distribution
387/// flow — GHCR).
388async fn anonymous_pull_token(
389    client: &reqwest::Client,
390    registry: &str,
391    repository: &str,
392) -> Result<String, GhcrError> {
393    let url =
394        format!("https://{registry}/token?service={registry}&scope=repository:{repository}:pull");
395    let body: serde_json::Value = client
396        .get(&url)
397        .send()
398        .await?
399        .error_for_status()?
400        .json()
401        .await?;
402    // GHCR returns the bearer under `token`; some registries use `access_token`.
403    body["token"]
404        .as_str()
405        .or_else(|| body["access_token"].as_str())
406        .map(str::to_owned)
407        .ok_or_else(|| GhcrError::Malformed {
408            repo: repository.to_owned(),
409            what: "pull token",
410        })
411}
412
413/// Fetch a GCP OAuth access token for an Artifact Registry / GCR host.
414///
415/// In-cluster (with Workload Identity) this reads the token off the GCE
416/// metadata server. For local use, point at Application Default Credentials
417/// instead — export a token from `gcloud auth print-access-token` into the
418/// environment ahead of the process, or run against a metadata proxy; the
419/// resolver only needs a valid bearer for the registry host.
420async fn gcp_access_token(client: &reqwest::Client, registry: &str) -> Result<String, GhcrError> {
421    const METADATA_TOKEN_URL: &str = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token";
422    let body: serde_json::Value = client
423        .get(METADATA_TOKEN_URL)
424        .header("Metadata-Flavor", "Google")
425        .send()
426        .await
427        .map_err(|e| GhcrError::GcpToken {
428            registry: registry.to_owned(),
429            reason: format!("metadata request failed: {e}"),
430        })?
431        .error_for_status()
432        .map_err(|e| GhcrError::GcpToken {
433            registry: registry.to_owned(),
434            reason: format!("metadata server returned an error: {e}"),
435        })?
436        .json()
437        .await
438        .map_err(|e| GhcrError::GcpToken {
439            registry: registry.to_owned(),
440            reason: format!("metadata response was not JSON: {e}"),
441        })?;
442    body["access_token"]
443        .as_str()
444        .map(str::to_owned)
445        .ok_or_else(|| GhcrError::GcpToken {
446            registry: registry.to_owned(),
447            reason: "metadata response carried no `access_token`".to_owned(),
448        })
449}
450
451#[cfg(test)]
452mod tests {
453    #![allow(clippy::pedantic, clippy::nursery)]
454
455    use super::*;
456
457    fn component(name: &str) -> &'static Component {
458        COMPONENTS.iter().find(|c| c.name == name).unwrap()
459    }
460
461    #[test]
462    fn image_tag_strips_v_and_validates() {
463        assert_eq!(image_tag_for_version("v0.4.0").unwrap(), "0.4.0");
464        assert_eq!(image_tag_for_version("0.4.0").unwrap(), "0.4.0");
465        assert_eq!(image_tag_for_version("  v1.2.3 ").unwrap(), "1.2.3");
466    }
467
468    #[test]
469    fn image_tag_rejects_non_semver() {
470        assert!(image_tag_for_version("latest").is_err());
471        assert!(image_tag_for_version("1.2").is_err());
472        assert!(image_tag_for_version("v").is_err());
473    }
474
475    #[test]
476    fn parse_splits_gar_host_from_repository() {
477        let r = parse_image_ref(
478            "us-east4-docker.pkg.dev/official-unofficial/docker/polychrome-control-plane",
479        );
480        assert_eq!(r.registry, "us-east4-docker.pkg.dev");
481        assert_eq!(
482            r.repository,
483            "official-unofficial/docker/polychrome-control-plane"
484        );
485    }
486
487    #[test]
488    fn parse_defaults_hostless_ref_to_ghcr() {
489        let r = parse_image_ref("officialunofficial/polychrome");
490        assert_eq!(r.registry, "ghcr.io");
491        assert_eq!(r.repository, "officialunofficial/polychrome");
492    }
493
494    #[test]
495    fn parse_treats_host_port_as_registry() {
496        let r = parse_image_ref("localhost:5000/team/app");
497        assert_eq!(r.registry, "localhost:5000");
498        assert_eq!(r.repository, "team/app");
499    }
500
501    #[test]
502    fn image_ref_defaults_to_ghcr_with_empty_env() {
503        let cp = image_ref(component("control-plane"), |_| None);
504        assert_eq!(cp.registry, "ghcr.io");
505        assert_eq!(cp.repository, "officialunofficial/polychrome");
506
507        let slack = image_ref(component("slack"), |_| None);
508        assert_eq!(
509            pinned_reference(&slack, "sha256:x"),
510            "ghcr.io/officialunofficial/polychrome-slack@sha256:x"
511        );
512    }
513
514    #[test]
515    fn image_ref_honors_gar_override() {
516        let env = |k: &str| match k {
517            "POLYCHROME_UPGRADE_IMAGE_CONTROL_PLANE" => Some(
518                "us-east4-docker.pkg.dev/official-unofficial/docker/polychrome-control-plane"
519                    .to_owned(),
520            ),
521            _ => None,
522        };
523        let cp = image_ref(component("control-plane"), env);
524        assert_eq!(cp.registry, "us-east4-docker.pkg.dev");
525        assert_eq!(
526            cp.repository,
527            "official-unofficial/docker/polychrome-control-plane"
528        );
529        // An unset component still falls back to its GHCR default.
530        let slack = image_ref(component("slack"), env);
531        assert_eq!(slack.registry, "ghcr.io");
532    }
533
534    #[test]
535    fn pinned_reference_format_for_ghcr_and_gar() {
536        let ghcr = ImageRef {
537            registry: "ghcr.io".to_owned(),
538            repository: "officialunofficial/polychrome".to_owned(),
539        };
540        assert_eq!(
541            pinned_reference(&ghcr, "sha256:abc"),
542            "ghcr.io/officialunofficial/polychrome@sha256:abc"
543        );
544        let gar = ImageRef {
545            registry: "us-east4-docker.pkg.dev".to_owned(),
546            repository: "official-unofficial/docker/polychrome-control-plane".to_owned(),
547        };
548        assert_eq!(
549            pinned_reference(&gar, "sha256:def"),
550            "us-east4-docker.pkg.dev/official-unofficial/docker/polychrome-control-plane@sha256:def"
551        );
552    }
553
554    #[test]
555    fn auth_for_selects_by_host() {
556        assert_eq!(auth_for("ghcr.io"), RegistryAuth::AnonymousToken);
557        assert_eq!(
558            auth_for("us-east4-docker.pkg.dev"),
559            RegistryAuth::GcpMetadata
560        );
561        assert_eq!(auth_for("us.gcr.io"), RegistryAuth::GcpMetadata);
562        assert_eq!(auth_for("gcr.io"), RegistryAuth::GcpMetadata);
563        assert_eq!(auth_for("docker.io"), RegistryAuth::AnonymousToken);
564    }
565
566    #[test]
567    fn components_carry_stable_names() {
568        let names: Vec<&str> = COMPONENTS.iter().map(|c| c.name).collect();
569        assert_eq!(
570            names,
571            vec![
572                "control-plane",
573                "state",
574                "harness",
575                "slack",
576                "telegram",
577                "trigger",
578                "scaffold"
579            ]
580        );
581    }
582
583    /// The state plane must reach the new version before anything that dials
584    /// it. This pins both halves of that: exactly one component ranks first,
585    /// and it is the state `Deployment`. Renaming the roster entry without
586    /// updating [`STATE_COMPONENT_NAME`] would silently flatten the ordering
587    /// back to roster order, which is the defect this rank exists to prevent
588    /// (control-plane is `COMPONENTS[0]`).
589    #[test]
590    fn state_rolls_before_every_other_component() {
591        let first: Vec<&str> = COMPONENTS
592            .iter()
593            .filter(|c| c.rollout_rank() == 0)
594            .map(|c| c.deployment)
595            .collect();
596        assert_eq!(first, vec!["polychrome-state"]);
597
598        let state = component(STATE_COMPONENT_NAME);
599        for c in COMPONENTS.iter().filter(|c| c.name != STATE_COMPONENT_NAME) {
600            assert!(
601                state.rollout_rank() < c.rollout_rank(),
602                "state must rank before {}",
603                c.name
604            );
605        }
606    }
607
608    /// The GHCR basename is deliberately NOT the same string as
609    /// `Component::name` — it's the published image name
610    /// (`.github/workflows/publish.yml`'s matrix), which is what
611    /// `release_manifest::resolve_release_digests` must key its manifest
612    /// lookup on. A regression test for the naming mismatch that let the
613    /// release manifest reader and the publish workflow disagree on the key.
614    #[test]
615    fn ghcr_basename_matches_the_published_image_name_not_component_name() {
616        let basenames: Vec<&str> = COMPONENTS.iter().map(Component::ghcr_basename).collect();
617        assert_eq!(
618            basenames,
619            vec![
620                "polychrome",
621                "polychrome-state",
622                "polychrome-harness",
623                "polychrome-slack",
624                "polychrome-telegram",
625                "polychrome-trigger",
626                "polychrome-scaffold",
627            ]
628        );
629    }
630}