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
120/// The Deployments an upgrade rolls.
121///
122/// Names/containers verified against `manifests/base/*-deployment.yaml`,
123/// `manifests/components/edges/trigger/deployment.yaml`, and
124/// `manifests/components/scaffold/deployment.yaml`; default images against
125/// `publish.yml`.
126///
127/// `scaffold`'s `default_image` names the GHCR basename it *would* publish
128/// under if it ever did, purely so `Component::ghcr_basename` stays
129/// well-formed — `.github/workflows/publish.yml` deliberately does NOT
130/// publish it (`cloudbuild.yaml`: "scaffold is a GAR-only provisioning
131/// connector"), so a hand-run upgrade with no `POLYCHROME_UPGRADE_IMAGE_SCAFFOLD`
132/// override correctly fails loud (`ReleaseManifestError::MissingComponent`)
133/// rather than silently resolving a public image that doesn't exist — the
134/// same no-legacy, no-silent-fallback rule every other digest source already
135/// follows. Every real deployment (including prod) sets the override.
136///
137/// `trigger` (#1325 investigation) — unlike scaffold, it IS published to GHCR
138/// (`publish.yml`'s edge matrix) — was missing from this list entirely, so a
139/// hand-run upgrade could never roll it past its `REPLACE_AT_BUILD_TIME`
140/// placeholder image; a fresh `polychrome install` left that Deployment
141/// permanently stuck at `InvalidImageName` with no sanctioned way to fix it.
142/// Reproduced live bringing up a second GKE cluster with the gke overlay's
143/// full edge set composed.
144pub const COMPONENTS: [Component; 6] = [
145    Component {
146        name: "control-plane",
147        deployment: "polychrome-control-plane",
148        container: "polychrome",
149        image_env: "POLYCHROME_UPGRADE_IMAGE_CONTROL_PLANE",
150        default_image: "ghcr.io/officialunofficial/polychrome",
151    },
152    Component {
153        name: "harness",
154        deployment: "polychrome-harness",
155        container: "polychrome-harness",
156        image_env: "POLYCHROME_UPGRADE_IMAGE_HARNESS",
157        default_image: "ghcr.io/officialunofficial/polychrome-harness",
158    },
159    Component {
160        name: "slack",
161        deployment: "polychrome-slack",
162        container: "polychrome-slack",
163        image_env: "POLYCHROME_UPGRADE_IMAGE_SLACK",
164        default_image: "ghcr.io/officialunofficial/polychrome-slack",
165    },
166    Component {
167        name: "telegram",
168        deployment: "polychrome-telegram",
169        container: "polychrome-telegram",
170        image_env: "POLYCHROME_UPGRADE_IMAGE_TELEGRAM",
171        default_image: "ghcr.io/officialunofficial/polychrome-telegram",
172    },
173    Component {
174        name: "trigger",
175        deployment: "polychrome-trigger",
176        container: "polychrome-trigger",
177        image_env: "POLYCHROME_UPGRADE_IMAGE_TRIGGER",
178        default_image: "ghcr.io/officialunofficial/polychrome-trigger",
179    },
180    Component {
181        name: "scaffold",
182        deployment: "polychrome-scaffold",
183        container: "scaffold",
184        image_env: "POLYCHROME_UPGRADE_IMAGE_SCAFFOLD",
185        default_image: "ghcr.io/officialunofficial/polychrome-scaffold",
186    },
187];
188
189/// A resolved image reference — a registry host plus a repository, carrying no
190/// tag. The tag is derived per upgrade from the target version.
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct ImageRef {
193    /// Registry host (e.g. `ghcr.io` or `us-east4-docker.pkg.dev`).
194    pub registry: String,
195    /// Repository path within the registry (e.g.
196    /// `officialunofficial/polychrome` or
197    /// `official-unofficial/docker/polychrome-control-plane`).
198    pub repository: String,
199}
200
201/// Split a full image reference string into its registry host and repository.
202///
203/// Applies the standard Docker heuristic: the segment before the first `/` is
204/// the registry host **iff** it contains a `.` or a `:` (a hostname or
205/// `host:port`); otherwise there is no host and the whole string is a
206/// repository under the default registry (`ghcr.io`).
207///
208/// # Examples
209/// - `us-east4-docker.pkg.dev/official-unofficial/docker/polychrome-control-plane`
210///   → registry `us-east4-docker.pkg.dev`, repo
211///   `official-unofficial/docker/polychrome-control-plane`.
212/// - `officialunofficial/polychrome` → registry `ghcr.io`, repo
213///   `officialunofficial/polychrome`.
214#[must_use]
215pub fn parse_image_ref(full: &str) -> ImageRef {
216    match full.split_once('/') {
217        Some((host, rest)) if host.contains('.') || host.contains(':') => ImageRef {
218            registry: host.to_owned(),
219            repository: rest.to_owned(),
220        },
221        _ => ImageRef {
222            registry: DEFAULT_REGISTRY.to_owned(),
223            repository: full.to_owned(),
224        },
225    }
226}
227
228/// Resolve a component's image reference from the environment, falling back to
229/// its public GHCR default.
230///
231/// The environment lookup is injected (rather than read from the process) so
232/// this stays a pure function — unit-testable without touching global state.
233/// Production callers pass `|k| std::env::var(k).ok()`.
234#[must_use]
235pub fn image_ref<F>(component: &Component, env_lookup: F) -> ImageRef
236where
237    F: Fn(&str) -> Option<String>,
238{
239    let raw = env_lookup(component.image_env).unwrap_or_else(|| component.default_image.to_owned());
240    parse_image_ref(&raw)
241}
242
243/// Normalize a `--version` / release tag into the image tag published.
244///
245/// `publish.yml` tags release manifests `{{version}}` (no leading `v`), so a
246/// release `v0.4.0` (or `--version v0.4.0`) maps to the image tag `0.4.0`. The
247/// tag is validated as semver so a typo can't pin the cluster to a
248/// non-existent / floating tag.
249///
250/// # Errors
251/// Returns [`GhcrError::Version`] if the stripped tag is not valid semver.
252pub fn image_tag_for_version(version: &str) -> Result<String, GhcrError> {
253    let tag = version.trim().trim_start_matches('v');
254    semver::Version::parse(tag).map_err(|_| GhcrError::Version(version.to_owned()))?;
255    Ok(tag.to_owned())
256}
257
258/// Build the digest-pinned image reference from a resolved [`ImageRef`] and a
259/// content digest (`{registry}/{repository}@{digest}`).
260#[must_use]
261pub fn pinned_reference(image: &ImageRef, digest: &str) -> String {
262    format!("{}/{}@{}", image.registry, image.repository, digest)
263}
264
265/// How to authenticate a digest-resolution request against a registry host.
266///
267/// Selected purely from the host by [`auth_for`]; the effectful token fetch is
268/// isolated behind each variant in [`resolve_digest`].
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
270pub enum RegistryAuth {
271    /// The OCI anonymous pull-token flow (public GHCR): `GET /token?scope=…`.
272    AnonymousToken,
273    /// A GCP OAuth access token, for Google Artifact Registry (`*.pkg.dev`) and
274    /// Container Registry (`*.gcr.io`).
275    GcpMetadata,
276}
277
278/// Pick the registry-auth strategy for a host.
279///
280/// Google Artifact Registry (`*.pkg.dev`) and Container Registry (`gcr.io` /
281/// `*.gcr.io`) require a GCP OAuth token; every other host (notably public
282/// GHCR) uses the anonymous pull-token flow.
283#[must_use]
284pub fn auth_for(registry: &str) -> RegistryAuth {
285    if registry.ends_with(".pkg.dev") || registry == "gcr.io" || registry.ends_with(".gcr.io") {
286        RegistryAuth::GcpMetadata
287    } else {
288        RegistryAuth::AnonymousToken
289    }
290}
291
292/// Build the shared HTTP client used for registry round-trips (bounded connect
293/// and request timeouts, a `polychrome/<version>` user agent).
294///
295/// # Errors
296/// Returns [`GhcrError::Http`] if the client can't be constructed.
297pub fn http_client() -> Result<reqwest::Client, GhcrError> {
298    Ok(reqwest::Client::builder()
299        .timeout(REQUEST_TIMEOUT)
300        .connect_timeout(CONNECT_TIMEOUT)
301        .user_agent(concat!("polychrome/", env!("CARGO_PKG_VERSION")))
302        .build()?)
303}
304
305/// Resolve the immutable manifest digest for `repository:tag` against `registry`.
306///
307/// The auth strategy is chosen from the host by [`auth_for`]: a public GHCR
308/// repository authenticates with an anonymous bearer token from the registry
309/// `token` endpoint, while a Google Artifact Registry / GCR host authenticates
310/// with a GCP OAuth access token.
311///
312/// The `GET` reads the `Docker-Content-Digest` response header — the registry
313/// computes it over the manifest bytes, so it is the canonical content address.
314///
315/// # Errors
316/// Returns [`GhcrError`] if the bearer token can't be obtained, the manifest
317/// request fails, or the response carries no digest header.
318pub async fn resolve_digest(
319    client: &reqwest::Client,
320    registry: &str,
321    repository: &str,
322    tag: &str,
323) -> Result<String, GhcrError> {
324    let token = match auth_for(registry) {
325        RegistryAuth::AnonymousToken => anonymous_pull_token(client, registry, repository).await?,
326        RegistryAuth::GcpMetadata => gcp_access_token(client, registry).await?,
327    };
328    let url = format!("https://{registry}/v2/{repository}/manifests/{tag}");
329    let resp = client
330        .get(&url)
331        .bearer_auth(&token)
332        // Accept both the OCI image index and the Docker manifest-list media
333        // types so multi-arch published images resolve to their index digest.
334        .header(
335            reqwest::header::ACCEPT,
336            "application/vnd.oci.image.index.v1+json, \
337             application/vnd.docker.distribution.manifest.list.v2+json, \
338             application/vnd.oci.image.manifest.v1+json, \
339             application/vnd.docker.distribution.manifest.v2+json",
340        )
341        .send()
342        .await?
343        .error_for_status()?;
344    let digest = resp
345        .headers()
346        .get("docker-content-digest")
347        .and_then(|v| v.to_str().ok())
348        .ok_or_else(|| GhcrError::Malformed {
349            repo: repository.to_owned(),
350            what: "digest header",
351        })?
352        .to_owned();
353    Ok(digest)
354}
355
356/// Fetch an anonymous pull token for a public repository (the OCI distribution
357/// flow — GHCR).
358async fn anonymous_pull_token(
359    client: &reqwest::Client,
360    registry: &str,
361    repository: &str,
362) -> Result<String, GhcrError> {
363    let url =
364        format!("https://{registry}/token?service={registry}&scope=repository:{repository}:pull");
365    let body: serde_json::Value = client
366        .get(&url)
367        .send()
368        .await?
369        .error_for_status()?
370        .json()
371        .await?;
372    // GHCR returns the bearer under `token`; some registries use `access_token`.
373    body["token"]
374        .as_str()
375        .or_else(|| body["access_token"].as_str())
376        .map(str::to_owned)
377        .ok_or_else(|| GhcrError::Malformed {
378            repo: repository.to_owned(),
379            what: "pull token",
380        })
381}
382
383/// Fetch a GCP OAuth access token for an Artifact Registry / GCR host.
384///
385/// In-cluster (with Workload Identity) this reads the token off the GCE
386/// metadata server. For local use, point at Application Default Credentials
387/// instead — export a token from `gcloud auth print-access-token` into the
388/// environment ahead of the process, or run against a metadata proxy; the
389/// resolver only needs a valid bearer for the registry host.
390async fn gcp_access_token(client: &reqwest::Client, registry: &str) -> Result<String, GhcrError> {
391    const METADATA_TOKEN_URL: &str = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token";
392    let body: serde_json::Value = client
393        .get(METADATA_TOKEN_URL)
394        .header("Metadata-Flavor", "Google")
395        .send()
396        .await
397        .map_err(|e| GhcrError::GcpToken {
398            registry: registry.to_owned(),
399            reason: format!("metadata request failed: {e}"),
400        })?
401        .error_for_status()
402        .map_err(|e| GhcrError::GcpToken {
403            registry: registry.to_owned(),
404            reason: format!("metadata server returned an error: {e}"),
405        })?
406        .json()
407        .await
408        .map_err(|e| GhcrError::GcpToken {
409            registry: registry.to_owned(),
410            reason: format!("metadata response was not JSON: {e}"),
411        })?;
412    body["access_token"]
413        .as_str()
414        .map(str::to_owned)
415        .ok_or_else(|| GhcrError::GcpToken {
416            registry: registry.to_owned(),
417            reason: "metadata response carried no `access_token`".to_owned(),
418        })
419}
420
421#[cfg(test)]
422mod tests {
423    #![allow(clippy::pedantic, clippy::nursery)]
424
425    use super::*;
426
427    fn component(name: &str) -> &'static Component {
428        COMPONENTS.iter().find(|c| c.name == name).unwrap()
429    }
430
431    #[test]
432    fn image_tag_strips_v_and_validates() {
433        assert_eq!(image_tag_for_version("v0.4.0").unwrap(), "0.4.0");
434        assert_eq!(image_tag_for_version("0.4.0").unwrap(), "0.4.0");
435        assert_eq!(image_tag_for_version("  v1.2.3 ").unwrap(), "1.2.3");
436    }
437
438    #[test]
439    fn image_tag_rejects_non_semver() {
440        assert!(image_tag_for_version("latest").is_err());
441        assert!(image_tag_for_version("1.2").is_err());
442        assert!(image_tag_for_version("v").is_err());
443    }
444
445    #[test]
446    fn parse_splits_gar_host_from_repository() {
447        let r = parse_image_ref(
448            "us-east4-docker.pkg.dev/official-unofficial/docker/polychrome-control-plane",
449        );
450        assert_eq!(r.registry, "us-east4-docker.pkg.dev");
451        assert_eq!(
452            r.repository,
453            "official-unofficial/docker/polychrome-control-plane"
454        );
455    }
456
457    #[test]
458    fn parse_defaults_hostless_ref_to_ghcr() {
459        let r = parse_image_ref("officialunofficial/polychrome");
460        assert_eq!(r.registry, "ghcr.io");
461        assert_eq!(r.repository, "officialunofficial/polychrome");
462    }
463
464    #[test]
465    fn parse_treats_host_port_as_registry() {
466        let r = parse_image_ref("localhost:5000/team/app");
467        assert_eq!(r.registry, "localhost:5000");
468        assert_eq!(r.repository, "team/app");
469    }
470
471    #[test]
472    fn image_ref_defaults_to_ghcr_with_empty_env() {
473        let cp = image_ref(component("control-plane"), |_| None);
474        assert_eq!(cp.registry, "ghcr.io");
475        assert_eq!(cp.repository, "officialunofficial/polychrome");
476
477        let slack = image_ref(component("slack"), |_| None);
478        assert_eq!(
479            pinned_reference(&slack, "sha256:x"),
480            "ghcr.io/officialunofficial/polychrome-slack@sha256:x"
481        );
482    }
483
484    #[test]
485    fn image_ref_honors_gar_override() {
486        let env = |k: &str| match k {
487            "POLYCHROME_UPGRADE_IMAGE_CONTROL_PLANE" => Some(
488                "us-east4-docker.pkg.dev/official-unofficial/docker/polychrome-control-plane"
489                    .to_owned(),
490            ),
491            _ => None,
492        };
493        let cp = image_ref(component("control-plane"), env);
494        assert_eq!(cp.registry, "us-east4-docker.pkg.dev");
495        assert_eq!(
496            cp.repository,
497            "official-unofficial/docker/polychrome-control-plane"
498        );
499        // An unset component still falls back to its GHCR default.
500        let slack = image_ref(component("slack"), env);
501        assert_eq!(slack.registry, "ghcr.io");
502    }
503
504    #[test]
505    fn pinned_reference_format_for_ghcr_and_gar() {
506        let ghcr = ImageRef {
507            registry: "ghcr.io".to_owned(),
508            repository: "officialunofficial/polychrome".to_owned(),
509        };
510        assert_eq!(
511            pinned_reference(&ghcr, "sha256:abc"),
512            "ghcr.io/officialunofficial/polychrome@sha256:abc"
513        );
514        let gar = ImageRef {
515            registry: "us-east4-docker.pkg.dev".to_owned(),
516            repository: "official-unofficial/docker/polychrome-control-plane".to_owned(),
517        };
518        assert_eq!(
519            pinned_reference(&gar, "sha256:def"),
520            "us-east4-docker.pkg.dev/official-unofficial/docker/polychrome-control-plane@sha256:def"
521        );
522    }
523
524    #[test]
525    fn auth_for_selects_by_host() {
526        assert_eq!(auth_for("ghcr.io"), RegistryAuth::AnonymousToken);
527        assert_eq!(
528            auth_for("us-east4-docker.pkg.dev"),
529            RegistryAuth::GcpMetadata
530        );
531        assert_eq!(auth_for("us.gcr.io"), RegistryAuth::GcpMetadata);
532        assert_eq!(auth_for("gcr.io"), RegistryAuth::GcpMetadata);
533        assert_eq!(auth_for("docker.io"), RegistryAuth::AnonymousToken);
534    }
535
536    #[test]
537    fn components_carry_stable_names() {
538        let names: Vec<&str> = COMPONENTS.iter().map(|c| c.name).collect();
539        assert_eq!(
540            names,
541            vec![
542                "control-plane",
543                "harness",
544                "slack",
545                "telegram",
546                "trigger",
547                "scaffold"
548            ]
549        );
550    }
551
552    /// The GHCR basename is deliberately NOT the same string as
553    /// `Component::name` — it's the published image name
554    /// (`.github/workflows/publish.yml`'s matrix), which is what
555    /// `release_manifest::resolve_release_digests` must key its manifest
556    /// lookup on. A regression test for the naming mismatch that let the
557    /// release manifest reader and the publish workflow disagree on the key.
558    #[test]
559    fn ghcr_basename_matches_the_published_image_name_not_component_name() {
560        let basenames: Vec<&str> = COMPONENTS.iter().map(Component::ghcr_basename).collect();
561        assert_eq!(
562            basenames,
563            vec![
564                "polychrome",
565                "polychrome-harness",
566                "polychrome-slack",
567                "polychrome-telegram",
568                "polychrome-trigger",
569                "polychrome-scaffold",
570            ]
571        );
572    }
573}