Skip to main content

anodizer_core/
env_preflight.rs

1//! Config-derived environment preflight: requirement vocabulary + check engine.
2//!
3//! Before any release stage runs, every enabled publisher and stage declares
4//! the environment it needs — CLI tools on PATH, env vars/secrets, endpoint
5//! reachability, loadable key material — derived from the **same resolved
6//! config its run path reads** (publishers via
7//! [`crate::Publisher::requirements`], stages via their crate's
8//! `env_requirements` function). The engine checks every requirement in one
9//! pass and reports **all** failures together, so one run shows the complete
10//! environment state instead of failing on the first missing secret.
11//!
12//! Failure messages never include env-var *values* — only names, tool names,
13//! configured URLs, and structural descriptions of key material.
14
15use serde::Serialize;
16
17// ---------------------------------------------------------------------------
18// Requirement vocabulary
19// ---------------------------------------------------------------------------
20
21/// Key-material families the preflight can structurally validate.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
23#[serde(rename_all = "snake_case")]
24pub enum KeyKind {
25    /// OpenSSH / PEM private key (AUR pushes over ssh).
26    SshPrivate,
27    /// PGP private key — ASCII-armored block or binary keyring packet
28    /// (gpg signing, nfpm deb/rpm signatures).
29    PgpPrivate,
30    /// Cosign / sigstore private key (`COSIGN_KEY`, `env://` refs).
31    Cosign,
32}
33
34impl KeyKind {
35    /// Human label used in failure messages.
36    pub fn label(self) -> &'static str {
37        match self {
38            KeyKind::SshPrivate => "SSH private key",
39            KeyKind::PgpPrivate => "PGP private key",
40            KeyKind::Cosign => "cosign private key",
41        }
42    }
43}
44
45/// One environment prerequisite a publisher or stage derives from its
46/// resolved config.
47#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
48#[serde(tag = "type", rename_all = "snake_case")]
49pub enum EnvRequirement {
50    /// A CLI tool that must be resolvable on PATH.
51    Tool { name: String },
52    /// At least one of the listed CLI tools must be resolvable on PATH
53    /// (stages with a detection ladder, e.g. dmg's
54    /// hdiutil → genisoimage → mkisofs).
55    ToolAnyOf { names: Vec<String> },
56    /// Every listed env var must be present and non-empty.
57    EnvAllOf { vars: Vec<String> },
58    /// At least one of the listed env vars must be present and non-empty.
59    EnvAnyOf { vars: Vec<String> },
60    /// An HTTP(S) endpoint from config that must be reachable.
61    Endpoint { url: String },
62    /// A reachable docker daemon (`docker info` must succeed).
63    DockerDaemon,
64    /// An env var that must hold parseable key material of `kind`.
65    KeyEnv { kind: KeyKind, var: String },
66    /// A file path (already template-rendered) that must hold parseable
67    /// key material of `kind`.
68    KeyFile { kind: KeyKind, path: String },
69}
70
71/// A requirement tagged with the publisher/stage that declared it.
72#[derive(Debug, Clone)]
73pub struct SourcedRequirement {
74    /// Declaring surface, e.g. `"publish:aur"` or `"stage:nfpm"`.
75    pub source: String,
76    pub requirement: EnvRequirement,
77    /// When `true`, a failed probe is a non-fatal WARNING rather than a gate
78    /// failure: the declaring surface degrades gracefully without it. The
79    /// canonical case is the build stage's cross-compilation toolchain, which
80    /// falls back `zigbuild → cargo → system gcc` per target — so a missing
81    /// `zig`/`cargo-zigbuild` must surface as "recommended", never block a
82    /// release. `anodizer tools` still reports advisory requirements; only the
83    /// pass/fail gate treats them as non-blocking.
84    pub advisory: bool,
85}
86
87impl SourcedRequirement {
88    /// A hard requirement: a failed probe fails the preflight gate.
89    pub fn new(source: impl Into<String>, requirement: EnvRequirement) -> Self {
90        Self {
91            source: source.into(),
92            requirement,
93            advisory: false,
94        }
95    }
96
97    /// An advisory requirement: a failed probe WARNS instead of failing the
98    /// gate, because the declaring surface degrades gracefully without it (see
99    /// [`SourcedRequirement::advisory`]).
100    pub fn new_advisory(source: impl Into<String>, requirement: EnvRequirement) -> Self {
101        Self {
102            source: source.into(),
103            requirement,
104            advisory: true,
105        }
106    }
107}
108
109// ---------------------------------------------------------------------------
110// Report
111// ---------------------------------------------------------------------------
112
113/// Classification of a preflight failure.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
115#[serde(rename_all = "snake_case")]
116pub enum FailureKind {
117    MissingTool,
118    MissingEnv,
119    EndpointUnreachable,
120    DockerUnavailable,
121    BadKeyMaterial,
122}
123
124/// One failed check, with every publisher/stage that needs it.
125#[derive(Debug, Clone, Serialize)]
126pub struct EnvCheckFailure {
127    pub kind: FailureKind,
128    /// Human-readable description. Never contains secret values.
129    pub message: String,
130    /// Sources (publishers/stages) whose declared requirement failed.
131    pub needed_by: Vec<String>,
132}
133
134/// Aggregate result of one preflight pass.
135#[derive(Debug, Clone, Serialize)]
136pub struct EnvPreflightReport {
137    /// Distinct checks evaluated (after de-duplication across sources).
138    pub checks: usize,
139    pub failures: Vec<EnvCheckFailure>,
140    /// Advisory checks that failed: the environment lacks a tool the run would
141    /// PREFER but does not require, because the declaring surface degrades
142    /// gracefully (e.g. a missing cross-compile toolchain that the build stage
143    /// falls back from). Surfaced as warnings; never flips [`ok`](Self::ok).
144    #[serde(default)]
145    pub warnings: Vec<EnvCheckFailure>,
146}
147
148impl EnvPreflightReport {
149    pub fn ok(&self) -> bool {
150        self.failures.is_empty()
151    }
152
153    /// Record a failure discovered outside the requirement-evaluation engine
154    /// (e.g. the offline cosign key-load verification, which needs to spawn a
155    /// tool and so cannot live in this pure module). Counts toward `checks` and
156    /// flips `ok()` to `false`, so a single non-ok report still drives the
157    /// caller's abort/exit-non-zero decision.
158    pub fn note_failure(&mut self, needed_by: &str, message: &str) {
159        self.checks += 1;
160        self.failures.push(EnvCheckFailure {
161            kind: FailureKind::BadKeyMaterial,
162            message: message.to_string(),
163            needed_by: vec![needed_by.to_string()],
164        });
165    }
166}
167
168impl std::fmt::Display for EnvPreflightReport {
169    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170        // `checks` counts every evaluated requirement; a failed advisory check
171        // is neither a pass nor a hard failure, so it must not inflate the
172        // "passed" count. Detail for each warning is emitted separately by the
173        // caller's warning logger — here we only summarise the count.
174        let warned = self.warnings.len();
175        let advisory_note = if warned > 0 {
176            format!(" ({warned} advisory warning(s))")
177        } else {
178            String::new()
179        };
180        if self.failures.is_empty() {
181            return write!(
182                f,
183                "{} preflight check(s) passed{advisory_note}",
184                self.checks.saturating_sub(warned)
185            );
186        }
187        writeln!(
188            f,
189            "{} of {} preflight check(s) failed{advisory_note}:",
190            self.failures.len(),
191            self.checks
192        )?;
193        for failure in &self.failures {
194            writeln!(
195                f,
196                "  ✗ {} [needed by: {}]",
197                failure.message,
198                failure.needed_by.join(", ")
199            )?;
200        }
201        Ok(())
202    }
203}
204
205// ---------------------------------------------------------------------------
206// Probes — injectable so the engine stays pure and unit-testable
207// ---------------------------------------------------------------------------
208
209/// Side-effecting probes injected into [`evaluate`]. Production callers wire
210/// `tool` to [`crate::tool_detect::on_path`] (a pure PATH lookup mirroring how
211/// stages spawn commands), `endpoint` to [`crate::http`], and `docker` to
212/// [`crate::tool_detect`]; tests inject closures.
213pub struct EnvProbes<'a> {
214    /// `true` when the tool resolves on PATH.
215    pub tool: &'a dyn Fn(&str) -> bool,
216    /// `Ok(())` when the endpoint answers HTTP; `Err(reason)` otherwise.
217    pub endpoint: &'a dyn Fn(&str) -> Result<(), String>,
218    /// `true` when a docker daemon answers `docker info`.
219    pub docker: &'a dyn Fn() -> bool,
220}
221
222// ---------------------------------------------------------------------------
223// Engine
224// ---------------------------------------------------------------------------
225
226/// Evaluate every requirement, de-duplicating identical requirements across
227/// sources, and return a collect-all report.
228///
229/// `env` resolves an env-var name to its value (callers typically merge the
230/// template `Env` map — which includes `env_files` entries — with the
231/// process environment). Values are only tested for presence/shape; they
232/// never appear in the report.
233pub fn evaluate(
234    requirements: &[SourcedRequirement],
235    env: &dyn Fn(&str) -> Option<String>,
236    probes: &EnvProbes<'_>,
237) -> EnvPreflightReport {
238    // De-duplicate while preserving first-seen order; N is small enough
239    // that linear scan beats pulling in an ordered-map dependency. A merged
240    // requirement is advisory only when EVERY source that needs it is advisory —
241    // one hard source makes a failed probe a gate failure.
242    let mut unique: Vec<(EnvRequirement, Vec<String>, bool)> = Vec::new();
243    for sr in requirements {
244        match unique.iter_mut().find(|(r, _, _)| *r == sr.requirement) {
245            Some((_, sources, advisory)) => {
246                if !sources.contains(&sr.source) {
247                    sources.push(sr.source.clone());
248                }
249                *advisory = *advisory && sr.advisory;
250            }
251            None => unique.push((sr.requirement.clone(), vec![sr.source.clone()], sr.advisory)),
252        }
253    }
254
255    let mut failures = Vec::new();
256    let mut warnings = Vec::new();
257    let checks = unique.len();
258    for (req, needed_by, advisory) in unique {
259        if let Some((kind, message)) = check_one(&req, env, probes) {
260            let failure = EnvCheckFailure {
261                kind,
262                message,
263                needed_by,
264            };
265            // Advisory failures warn; the surface degrades gracefully without
266            // the tool, so they must not flip `ok()` or block the release gate.
267            if advisory {
268                warnings.push(failure);
269            } else {
270                failures.push(failure);
271            }
272        }
273    }
274    EnvPreflightReport {
275        checks,
276        failures,
277        warnings,
278    }
279}
280
281fn present(env: &dyn Fn(&str) -> Option<String>, var: &str) -> bool {
282    env(var).is_some_and(|v| !v.is_empty())
283}
284
285fn check_one(
286    req: &EnvRequirement,
287    env: &dyn Fn(&str) -> Option<String>,
288    probes: &EnvProbes<'_>,
289) -> Option<(FailureKind, String)> {
290    match req {
291        // No "required" in the message: the same text serves hard failures and
292        // advisory warnings. Required-ness is conveyed by the surrounding frame
293        // (a hard `✗ … [needed by]` vs an advisory `Warning … [recommended by]`),
294        // so "required tool 'zig' … [recommended by]" would self-contradict.
295        EnvRequirement::Tool { name } => (!(probes.tool)(name)).then(|| {
296            (
297                FailureKind::MissingTool,
298                format!("tool '{name}' not found on PATH"),
299            )
300        }),
301        EnvRequirement::ToolAnyOf { names } => {
302            let any = names.iter().any(|n| (probes.tool)(n));
303            (!any).then(|| {
304                (
305                    FailureKind::MissingTool,
306                    format!("none of the tool(s) [{}] found on PATH", names.join(", ")),
307                )
308            })
309        }
310        EnvRequirement::EnvAllOf { vars } => {
311            let missing: Vec<&str> = vars
312                .iter()
313                .filter(|v| !present(env, v))
314                .map(String::as_str)
315                .collect();
316            (!missing.is_empty()).then(|| {
317                (
318                    FailureKind::MissingEnv,
319                    format!("env var(s) missing or empty: {}", missing.join(", ")),
320                )
321            })
322        }
323        EnvRequirement::EnvAnyOf { vars } => {
324            let any = vars.iter().any(|v| present(env, v));
325            (!any).then(|| {
326                (
327                    FailureKind::MissingEnv,
328                    format!(
329                        "none of the env var(s) [{}] is set and non-empty",
330                        vars.join(", ")
331                    ),
332                )
333            })
334        }
335        EnvRequirement::Endpoint { url } => match (probes.endpoint)(url) {
336            Ok(()) => None,
337            Err(reason) => Some((
338                FailureKind::EndpointUnreachable,
339                format!("endpoint '{url}' unreachable: {reason}"),
340            )),
341        },
342        EnvRequirement::DockerDaemon => (!(probes.docker)()).then(|| {
343            (
344                FailureKind::DockerUnavailable,
345                "docker daemon unreachable ('docker info' failed)".to_string(),
346            )
347        }),
348        EnvRequirement::KeyEnv { kind, var } => match env(var).filter(|v| !v.is_empty()) {
349            None => Some((
350                FailureKind::MissingEnv,
351                format!("env var(s) missing or empty: {var}"),
352            )),
353            Some(value) => validate_key_material(*kind, &value).err().map(|reason| {
354                (
355                    FailureKind::BadKeyMaterial,
356                    format!(
357                        "env var {var} does not hold a usable {}: {reason}",
358                        kind.label()
359                    ),
360                )
361            }),
362        },
363        EnvRequirement::KeyFile { kind, path } => match std::fs::read(path) {
364            Err(e) => Some((
365                FailureKind::BadKeyMaterial,
366                format!(
367                    "key file '{path}' not readable ({}): {}",
368                    kind.label(),
369                    e.kind()
370                ),
371            )),
372            Ok(bytes) => {
373                // Binary (non-UTF-8) content is accepted for PGP keyring
374                // exports; the armored validators only apply to text.
375                match String::from_utf8(bytes) {
376                    Err(_) if *kind == KeyKind::PgpPrivate => None,
377                    Err(_) => Some((
378                        FailureKind::BadKeyMaterial,
379                        format!(
380                            "key file '{path}' is not valid UTF-8 (expected {})",
381                            kind.label()
382                        ),
383                    )),
384                    Ok(text) => validate_key_material(*kind, &text).err().map(|reason| {
385                        (
386                            FailureKind::BadKeyMaterial,
387                            format!(
388                                "key file '{path}' does not hold a usable {}: {reason}",
389                                kind.label()
390                            ),
391                        )
392                    }),
393                }
394            }
395        },
396    }
397}
398
399// ---------------------------------------------------------------------------
400// Key-material validation (structural parse — never echoes content)
401// ---------------------------------------------------------------------------
402
403/// Structurally validate key material. Returns `Err(reason)` with a
404/// description that never includes the key content.
405pub fn validate_key_material(kind: KeyKind, content: &str) -> Result<(), String> {
406    match kind {
407        KeyKind::SshPrivate => validate_ssh_private_key(content),
408        KeyKind::PgpPrivate => validate_pgp_private_key(content),
409        KeyKind::Cosign => validate_cosign_key(content),
410    }
411}
412
413fn validate_ssh_private_key(content: &str) -> Result<(), String> {
414    let trimmed_start = content.trim_start();
415    if !trimmed_start.starts_with("-----BEGIN ") {
416        return Err("missing '-----BEGIN ... PRIVATE KEY-----' header".to_string());
417    }
418    let header_line = trimmed_start.lines().next().unwrap_or("");
419    if !header_line.contains("PRIVATE KEY-----") {
420        return Err("first line is not a PRIVATE KEY PEM header".to_string());
421    }
422    let Some(end_pos) = content.rfind("-----END ") else {
423        return Err("missing '-----END ... PRIVATE KEY-----' footer".to_string());
424    };
425    let footer = &content[end_pos..];
426    if !footer.contains("PRIVATE KEY-----") {
427        return Err("footer is not a PRIVATE KEY PEM footer".to_string());
428    }
429    // A missing trailing newline after the END marker is NOT an error:
430    // the key writer normalizes the content to exactly one trailing
431    // newline before ssh ever reads it, so a secret stored via a tool
432    // that strips the final newline still works at run time. Failing
433    // here would reject input the pipeline provably tolerates.
434    Ok(())
435}
436
437fn validate_pgp_private_key(content: &str) -> Result<(), String> {
438    let trimmed = content.trim_start();
439    if trimmed.starts_with("-----BEGIN PGP PRIVATE KEY BLOCK-----") {
440        if !content.contains("-----END PGP PRIVATE KEY BLOCK-----") {
441            return Err("missing '-----END PGP PRIVATE KEY BLOCK-----' footer".to_string());
442        }
443        return Ok(());
444    }
445    // Binary OpenPGP packet: first byte has the packet-tag high bit set.
446    if trimmed.as_bytes().first().is_some_and(|b| b & 0x80 == 0x80) {
447        return Ok(());
448    }
449    Err(
450        "missing '-----BEGIN PGP PRIVATE KEY BLOCK-----' header (not armored or binary OpenPGP)"
451            .to_string(),
452    )
453}
454
455fn validate_cosign_key(content: &str) -> Result<(), String> {
456    let trimmed = content.trim_start();
457    let known = [
458        "-----BEGIN ENCRYPTED SIGSTORE PRIVATE KEY-----",
459        "-----BEGIN ENCRYPTED COSIGN PRIVATE KEY-----",
460        "-----BEGIN PRIVATE KEY-----",
461        "-----BEGIN EC PRIVATE KEY-----",
462    ];
463    if known.iter().any(|h| trimmed.starts_with(h)) {
464        if !content.contains("-----END ") {
465            return Err("missing PEM END footer".to_string());
466        }
467        return Ok(());
468    }
469    Err("missing sigstore/cosign PEM header".to_string())
470}
471
472// ---------------------------------------------------------------------------
473// Template env-reference extraction
474// ---------------------------------------------------------------------------
475
476/// Extract env-var names referenced as `{{ .Env.NAME }}` / `{{ Env.NAME }}`
477/// from a templated config string.
478///
479/// References inside a template expression that applies a `default(`
480/// filter are skipped — a defaulted lookup is satisfiable without the var.
481pub fn template_env_refs(s: &str) -> Vec<String> {
482    let mut out = Vec::new();
483    let mut rest = s;
484    while let Some(open) = rest.find("{{") {
485        let after = &rest[open + 2..];
486        let Some(close) = after.find("}}") else {
487            break;
488        };
489        let expr = &after[..close];
490        if !expr.contains("default(") {
491            collect_env_names(expr, &mut out);
492        }
493        rest = &after[close + 2..];
494    }
495    out
496}
497
498/// The artifact-producing stage tokens a resolved config actually
499/// configures — i.e. carries a non-empty config block for. Tokens match the
500/// determinism harness's stage names (`nfpm`, `flatpak`, `dmg`, …) and the
501/// `--skip=`/preflight vocabulary.
502///
503/// Each token gates on the SAME `Config` / `CrateConfig` field the matching
504/// stage crate's `env_requirements` reads (per-crate blocks unioned across
505/// [`crate::config::Config::crate_universe`]; top-level blocks read directly), so a consumer of this
506/// set cannot drift from which producers the pipeline will actually run. The
507/// determinism harness intersects its OS-native default partition with this
508/// set so a `--stages`-absent run only byte-verifies — and, under
509/// `--require-tools`, only requires the tools for — producers the project
510/// configures.
511///
512/// Pass a config that has already had [`crate::defaults_merge::apply_defaults`]
513/// run on it: `defaults:` materializes producer blocks onto crates, and the
514/// stage gates read the post-merge config, so a raw (pre-merge) config would
515/// miss any producer declared only under `defaults:`.
516///
517/// Block PRESENCE (≥1 entry) is the predicate; per-entry `skip:` conditions
518/// are not evaluated (a declared block is intent-to-produce — over-covering
519/// the determinism set is safe, silently under-covering is the bug this
520/// guards). The always-on stages (`build` / `source` / `archive` / `checksum`
521/// / `sbom` / `sign` / `upx`) are deliberately NOT enumerated: they carry no
522/// installer tool and emit nothing when unconfigured, so the determinism
523/// default keeps them unconditionally rather than gating on config.
524pub fn configured_producer_stages(
525    config: &crate::config::Config,
526) -> std::collections::BTreeSet<&'static str> {
527    let crates = config.crate_universe();
528    CONFIGURED_PRODUCERS
529        .iter()
530        .filter(|p| (p.configured)(config, &crates))
531        .map(|p| p.token)
532        .collect()
533}
534
535/// Stage tokens of every config-gated producer whose payload binary `host_os`
536/// natively builds. `host_os` is a `target`-style OS token
537/// (`"linux"` / `"macos"` / `"windows"`); an unrecognized value yields an
538/// empty list. Order follows `CONFIGURED_PRODUCERS` within the OS group.
539///
540/// The determinism harness's `--stages`-absent default unions its always-on
541/// base with this set so each OS-native installer runs on the shard that
542/// builds what it packages — routing one to a shard that lacks its payload
543/// binary is how a format silently ships in NO release.
544pub fn os_native_producer_tokens(host_os: &str) -> Vec<&'static str> {
545    CONFIGURED_PRODUCERS
546        .iter()
547        .filter(|p| p.native_os == host_os)
548        .map(|p| p.token)
549        .collect()
550}
551
552/// One artifact-producing stage the determinism harness gates on config and
553/// routes to the host OS that natively builds its payload binary.
554///
555/// Single source for both the config-configured producer set
556/// ([`configured_producer_stages`]) and the per-host OS-native producer set
557/// ([`os_native_producer_tokens`]): adding a producer to `CONFIGURED_PRODUCERS`
558/// extends both derivations at once, so the determinism default and the
559/// preflight set cannot list a producer the other misses.
560struct ConfiguredProducer {
561    /// Canonical stage token — matches the determinism harness's `StageId`
562    /// token vocabulary and the `--skip=` / `--stages=` names.
563    token: &'static str,
564    /// `target`-style host-OS token (`"linux"` / `"macos"` / `"windows"`)
565    /// whose native toolchain builds this producer's payload binary.
566    native_os: &'static str,
567    /// Fires when the resolved config carries ≥1 block for this producer
568    /// (per-crate blocks unioned across the supplied [`crate::config::Config::crate_universe`];
569    /// top-level blocks read off `Config` directly).
570    configured: fn(&crate::config::Config, &[&crate::config::CrateConfig]) -> bool,
571}
572
573/// Every config-gated artifact producer the determinism harness can verify,
574/// with the host OS that natively builds it and the config predicate that
575/// decides whether the project configures it.
576///
577/// Order within each OS group is load-bearing for [`os_native_producer_tokens`]:
578/// on macOS `appbundle` precedes `dmg`/`pkg` so their `use: appbundle` finds a
579/// source `.app`. The always-on base stages (`build` / `source` / `archive` /
580/// `checksum` / `sbom` / `sign` / `upx`) are deliberately absent — they carry
581/// no installer tool and emit nothing when unconfigured, so the harness keeps
582/// them unconditionally rather than gating on config or OS.
583const CONFIGURED_PRODUCERS: &[ConfiguredProducer] = &[
584    ConfiguredProducer {
585        token: "nfpm",
586        native_os: "linux",
587        configured: |_, cs| cs.iter().any(|c| c.nfpms.iter().flatten().next().is_some()),
588    },
589    ConfiguredProducer {
590        token: "makeself",
591        native_os: "linux",
592        configured: |cfg, _| !cfg.makeselfs.is_empty(),
593    },
594    ConfiguredProducer {
595        token: "snapcraft",
596        native_os: "linux",
597        configured: |_, cs| {
598            cs.iter()
599                .any(|c| c.snapcrafts.iter().flatten().next().is_some())
600        },
601    },
602    ConfiguredProducer {
603        token: "srpm",
604        native_os: "linux",
605        configured: |cfg, _| cfg.srpms.is_some(),
606    },
607    ConfiguredProducer {
608        token: "docker",
609        native_os: "linux",
610        configured: |_, cs| {
611            cs.iter()
612                .any(|c| c.dockers_v2.iter().flatten().next().is_some())
613        },
614    },
615    ConfiguredProducer {
616        token: "appimage",
617        native_os: "linux",
618        configured: |cfg, _| !cfg.appimages.is_empty(),
619    },
620    ConfiguredProducer {
621        token: "flatpak",
622        native_os: "linux",
623        configured: |_, cs| {
624            cs.iter()
625                .any(|c| c.flatpaks.iter().flatten().next().is_some())
626        },
627    },
628    ConfiguredProducer {
629        token: "appbundle",
630        native_os: "macos",
631        configured: |_, cs| {
632            cs.iter()
633                .any(|c| c.app_bundles.iter().flatten().next().is_some())
634        },
635    },
636    ConfiguredProducer {
637        token: "dmg",
638        native_os: "macos",
639        configured: |_, cs| cs.iter().any(|c| c.dmgs.iter().flatten().next().is_some()),
640    },
641    ConfiguredProducer {
642        token: "pkg",
643        native_os: "macos",
644        configured: |_, cs| cs.iter().any(|c| c.pkgs.iter().flatten().next().is_some()),
645    },
646    ConfiguredProducer {
647        token: "msi",
648        native_os: "windows",
649        configured: |_, cs| cs.iter().any(|c| c.msis.iter().flatten().next().is_some()),
650    },
651    ConfiguredProducer {
652        token: "nsis",
653        native_os: "windows",
654        configured: |_, cs| cs.iter().any(|c| c.nsis.iter().flatten().next().is_some()),
655    },
656];
657
658/// When the entire string is a single `{{ [.]Env.NAME }}` expression,
659/// return `NAME`. Used to decide whether a templated secret field maps to
660/// validatable key material from one env var (vs. a composite template,
661/// where only presence of the referenced vars can be required).
662pub fn sole_env_ref(s: &str) -> Option<String> {
663    let t = s.trim();
664    if !(t.starts_with("{{") && t.ends_with("}}")) || t[2..].contains("{{") {
665        return None;
666    }
667    let refs = template_env_refs(t);
668    let inner = t[2..t.len() - 2].trim();
669    let bare = inner.strip_prefix('.').unwrap_or(inner);
670    match refs.as_slice() {
671        [only] if bare == format!("Env.{only}") => Some(only.clone()),
672        _ => None,
673    }
674}
675
676/// Extract env-var names referenced via cosign's `env://NAME` key scheme.
677pub fn env_scheme_refs(s: &str) -> Vec<String> {
678    let mut out = Vec::new();
679    let mut rest = s;
680    while let Some(pos) = rest.find("env://") {
681        let tail = &rest[pos + 6..];
682        let name: String = tail
683            .chars()
684            .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
685            .collect();
686        if !name.is_empty() && !out.contains(&name) {
687            out.push(name.clone());
688        }
689        rest = &tail[name.len()..];
690    }
691    out
692}
693
694fn collect_env_names(expr: &str, out: &mut Vec<String>) {
695    let mut rest = expr;
696    while let Some(pos) = rest.find("Env.") {
697        // Accept both `.Env.NAME` (Go-template style the preprocessor
698        // translates) and bare `Env.NAME` (native Tera object lookup), but
699        // not identifiers that merely end in `Env.` (e.g. `MyEnv.`).
700        let preceded_ok = match rest[..pos].chars().next_back() {
701            None => true,
702            Some(c) => !(c.is_ascii_alphanumeric() || c == '_'),
703        };
704        let tail = &rest[pos + 4..];
705        let name: String = tail
706            .chars()
707            .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
708            .collect();
709        if preceded_ok && !name.is_empty() && !out.contains(&name) {
710            out.push(name.clone());
711        }
712        rest = &tail[name.len().min(tail.len())..];
713    }
714}
715
716/// Convenience: map every env reference in a templated config string
717/// (both `{{ .Env.X }}` and `env://X` forms) to an [`EnvRequirement`],
718/// tagged with `source`.
719pub fn env_ref_requirements(source: &str, value: &str) -> Vec<SourcedRequirement> {
720    let mut out = Vec::new();
721    let refs = template_env_refs(value);
722    if !refs.is_empty() {
723        out.push(SourcedRequirement::new(
724            source,
725            EnvRequirement::EnvAllOf { vars: refs },
726        ));
727    }
728    for var in env_scheme_refs(value) {
729        out.push(SourcedRequirement::new(
730            source,
731            EnvRequirement::EnvAllOf { vars: vec![var] },
732        ));
733    }
734    out
735}
736
737/// True when a config entry is statically inactive for this run: its
738/// `skip:` / `skip_upload:` evaluates truthy, or its `if:` condition
739/// renders falsy. Mirrors the run-path gating for requirement derivation —
740/// a `skip: true` entry must not demand tools or credentials from
741/// preflight. Anything unrenderable is treated as ACTIVE so preflight
742/// over-collects rather than silently under-collecting.
743pub fn entry_inactive(
744    ctx: &crate::context::Context,
745    skip: Option<&crate::config::StringOrBool>,
746    skip_upload: Option<&crate::config::StringOrBool>,
747    if_condition: Option<&str>,
748) -> bool {
749    let truthy = |v: &crate::config::StringOrBool| {
750        v.try_evaluates_to_true(|t| ctx.render_template(t))
751            .unwrap_or(false)
752    };
753    if skip.is_some_and(truthy) || skip_upload.is_some_and(truthy) {
754        return true;
755    }
756    if_condition.is_some_and(|cond| {
757        matches!(
758            crate::config::evaluate_if_condition(Some(cond), "preflight", |t| ctx
759                .render_template(t)),
760            Ok(false)
761        )
762    })
763}
764
765/// Requirement for a templated secret-bearing config value with an env-var
766/// fallback: a set value declares its `{{ .Env.X }}` references (a literal
767/// declares nothing — the credential is inline); an unset value declares
768/// the fallback env var the run path reads instead.
769pub fn secret_requirement(
770    config_value: Option<&str>,
771    fallback_env: &str,
772) -> Option<EnvRequirement> {
773    match config_value.filter(|v| !v.is_empty()) {
774        Some(v) => {
775            let refs = template_env_refs(v);
776            (!refs.is_empty()).then_some(EnvRequirement::EnvAllOf { vars: refs })
777        }
778        None => Some(EnvRequirement::EnvAllOf {
779            vars: vec![fallback_env.to_string()],
780        }),
781    }
782}
783
784/// The union of build targets this run would compile, routed through the
785/// build-synthesis SSOT ([`crate::build_plan::planned_builds`] +
786/// [`crate::build_plan::build_produces`]): per-build `targets:` (an explicitly
787/// empty list means "skip this build"), else `defaults.targets`, else the
788/// canonical default matrix (via [`crate::config::Config::effective_default_targets`]).
789/// A build the planner compiles nothing for — a library crate's materialized
790/// `binary: None` build with no matching `--bin` — contributes nothing; a
791/// skipped build (`skip:` truthy) contributes nothing; an unrenderable `skip:`
792/// counts as active (over-collect). `--single-target` narrows the union to the
793/// requested triple (exact match first, then the same OS/arch alias fallback the
794/// build stage applies), so a host-only release never demands cross-platform
795/// bundler tools.
796pub fn configured_build_targets(ctx: &crate::context::Context) -> Vec<String> {
797    let default_targets: Vec<String> = ctx.config.effective_default_targets();
798    let mut out: Vec<String> = Vec::new();
799    let mut push = |t: &str| {
800        if !out.iter().any(|x| x == t) {
801            out.push(t.to_string());
802        }
803    };
804    for krate in ctx.config.crate_universe() {
805        // A library crate with no default binary yields no builds, so it
806        // contributes nothing — the planner's compile/artifact gate.
807        let Some(builds) = crate::build_plan::planned_builds(krate) else {
808            continue;
809        };
810        for build in &builds {
811            if entry_inactive(ctx, build.skip.as_ref(), None, None) {
812                continue;
813            }
814            if !crate::build_plan::build_produces(krate, build) {
815                continue;
816            }
817            match build.targets.as_ref() {
818                Some(targets) => targets.iter().for_each(|t| push(t)),
819                None => default_targets.iter().for_each(|t| push(t)),
820            }
821        }
822    }
823    if let Some(single) = ctx.options.single_target.as_deref() {
824        if out.iter().any(|t| t == single) {
825            out.retain(|t| t == single);
826        } else {
827            out = crate::partial::find_runtime_target(single, &out)
828                .into_iter()
829                .collect();
830        }
831    }
832    out
833}
834
835#[cfg(test)]
836mod tests {
837    use super::*;
838
839    #[test]
840    fn configured_producer_stages_reports_only_present_blocks() {
841        use crate::config::{Config, CrateConfig, FlatpakConfig, NfpmConfig, SrpmConfig};
842
843        // Empty config configures no producers.
844        let empty = Config {
845            crates: vec![CrateConfig {
846                name: "x".to_string(),
847                path: ".".to_string(),
848                ..Default::default()
849            }],
850            ..Default::default()
851        };
852        assert!(configured_producer_stages(&empty).is_empty());
853
854        // A per-crate block (nfpm/flatpak) and a top-level block (srpm) each
855        // surface their token; nothing else does.
856        let configured = Config {
857            crates: vec![CrateConfig {
858                name: "x".to_string(),
859                path: ".".to_string(),
860                nfpms: Some(vec![NfpmConfig::default()]),
861                flatpaks: Some(vec![FlatpakConfig::default()]),
862                ..Default::default()
863            }],
864            srpms: Some(SrpmConfig::default()),
865            ..Default::default()
866        };
867        let got = configured_producer_stages(&configured);
868        assert!(got.contains("nfpm"));
869        assert!(got.contains("flatpak"));
870        assert!(got.contains("srpm"));
871        assert!(!got.contains("docker"));
872        assert!(!got.contains("appimage"));
873        // Always-on base stages are never enumerated here.
874        assert!(!got.contains("build"));
875        assert!(!got.contains("archive"));
876
877        // A `Some(empty vec)` block is NOT "configured".
878        let empty_vec = Config {
879            crates: vec![CrateConfig {
880                name: "x".to_string(),
881                path: ".".to_string(),
882                nfpms: Some(vec![]),
883                ..Default::default()
884            }],
885            ..Default::default()
886        };
887        assert!(!configured_producer_stages(&empty_vec).contains("nfpm"));
888    }
889
890    fn no_env(_: &str) -> Option<String> {
891        None
892    }
893
894    fn all_pass_probes() -> EnvProbes<'static> {
895        EnvProbes {
896            tool: &|_| true,
897            endpoint: &|_| Ok(()),
898            docker: &|| true,
899        }
900    }
901
902    fn req(source: &str, r: EnvRequirement) -> SourcedRequirement {
903        SourcedRequirement::new(source, r)
904    }
905
906    #[test]
907    fn empty_requirements_pass() {
908        let report = evaluate(&[], &no_env, &all_pass_probes());
909        assert!(report.ok());
910        assert_eq!(report.checks, 0);
911    }
912
913    #[test]
914    fn advisory_tool_failure_warns_and_does_not_fail_the_gate() {
915        // A missing ADVISORY tool (the cross-compile toolchain the build stage
916        // falls back from) must surface as a warning, never a gate failure —
917        // the regression that made `anodizer release` abort on any box without
918        // zig/cargo-zigbuild.
919        let none = EnvProbes {
920            tool: &|_| false,
921            endpoint: &|_| Ok(()),
922            docker: &|| true,
923        };
924        let reqs = vec![SourcedRequirement::new_advisory(
925            "stage:build",
926            EnvRequirement::Tool { name: "zig".into() },
927        )];
928        let report = evaluate(&reqs, &no_env, &none);
929        assert!(report.ok(), "advisory failure must not flip ok()");
930        assert!(report.failures.is_empty());
931        assert_eq!(report.warnings.len(), 1);
932        assert!(report.warnings[0].message.contains("zig"));
933        assert_eq!(report.checks, 1);
934    }
935
936    #[test]
937    fn hard_source_overrides_advisory_for_the_same_tool() {
938        // A tool needed by BOTH a hard and an advisory source is a gate failure
939        // when absent: one hard need is enough. (Guards the dedup's advisory AND.)
940        let none = EnvProbes {
941            tool: &|_| false,
942            endpoint: &|_| Ok(()),
943            docker: &|| true,
944        };
945        let reqs = vec![
946            SourcedRequirement::new_advisory(
947                "stage:build",
948                EnvRequirement::Tool { name: "cc".into() },
949            ),
950            SourcedRequirement::new("stage:other", EnvRequirement::Tool { name: "cc".into() }),
951        ];
952        let report = evaluate(&reqs, &no_env, &none);
953        assert!(
954            !report.ok(),
955            "a hard source makes the merged check blocking"
956        );
957        assert_eq!(report.failures.len(), 1);
958        assert!(report.warnings.is_empty());
959    }
960
961    #[test]
962    fn advisory_merge_is_order_independent_and_holds_for_many_advisory_sources() {
963        // The dedup `advisory = advisory && sr.advisory` must be commutative:
964        // hard-THEN-advisory blocks just like advisory-then-hard, and a tool
965        // needed only by several advisory sources stays a warning. `cc` is
966        // hard-first then advisory; `zig` is advisory from two sources.
967        let none = EnvProbes {
968            tool: &|_| false,
969            endpoint: &|_| Ok(()),
970            docker: &|| true,
971        };
972        let reqs = vec![
973            SourcedRequirement::new("stage:other", EnvRequirement::Tool { name: "cc".into() }),
974            SourcedRequirement::new_advisory(
975                "stage:build",
976                EnvRequirement::Tool { name: "cc".into() },
977            ),
978            SourcedRequirement::new_advisory(
979                "stage:build",
980                EnvRequirement::Tool { name: "zig".into() },
981            ),
982            SourcedRequirement::new_advisory(
983                "stage:archive",
984                EnvRequirement::Tool { name: "zig".into() },
985            ),
986        ];
987        let report = evaluate(&reqs, &no_env, &none);
988        assert_eq!(report.checks, 2, "cc and zig dedup to two checks");
989        assert!(
990            !report.ok(),
991            "hard-first cc still blocks regardless of order"
992        );
993        assert_eq!(report.failures.len(), 1);
994        assert!(report.failures[0].message.contains("cc"));
995        assert_eq!(
996            report.warnings.len(),
997            1,
998            "zig stays a single advisory warning"
999        );
1000        assert!(report.warnings[0].message.contains("zig"));
1001        // Both advisory sources are credited as needing zig.
1002        assert_eq!(report.warnings[0].needed_by.len(), 2);
1003    }
1004
1005    #[test]
1006    fn tool_any_of_passes_when_one_is_present() {
1007        let ladder = EnvRequirement::ToolAnyOf {
1008            names: vec!["hdiutil".into(), "genisoimage".into(), "mkisofs".into()],
1009        };
1010        let probes = EnvProbes {
1011            tool: &|name| name == "mkisofs",
1012            endpoint: &|_| Ok(()),
1013            docker: &|| true,
1014        };
1015        let report = evaluate(&[req("stage:dmg", ladder.clone())], &no_env, &probes);
1016        assert!(report.ok(), "one available tool must satisfy the ladder");
1017
1018        let none_available = EnvProbes {
1019            tool: &|_| false,
1020            endpoint: &|_| Ok(()),
1021            docker: &|| true,
1022        };
1023        let report = evaluate(&[req("stage:dmg", ladder)], &no_env, &none_available);
1024        assert_eq!(report.failures.len(), 1);
1025        assert_eq!(report.failures[0].kind, FailureKind::MissingTool);
1026        assert!(
1027            report.failures[0].message.contains("hdiutil")
1028                && report.failures[0].message.contains("mkisofs"),
1029            "message must list the whole ladder: {}",
1030            report.failures[0].message
1031        );
1032    }
1033
1034    #[test]
1035    fn collects_all_failures_in_one_pass() {
1036        let reqs = vec![
1037            req(
1038                "stage:nfpm",
1039                EnvRequirement::Tool {
1040                    name: "nfpm".into(),
1041                },
1042            ),
1043            req(
1044                "publish:cargo",
1045                EnvRequirement::EnvAllOf {
1046                    vars: vec!["CARGO_REGISTRY_TOKEN".into()],
1047                },
1048            ),
1049            req("stage:docker", EnvRequirement::DockerDaemon),
1050            req(
1051                "stage:blob",
1052                EnvRequirement::Endpoint {
1053                    url: "http://minio.example".into(),
1054                },
1055            ),
1056        ];
1057        let probes = EnvProbes {
1058            tool: &|_| false,
1059            endpoint: &|_| Err("connection refused".into()),
1060            docker: &|| false,
1061        };
1062        let report = evaluate(&reqs, &no_env, &probes);
1063        assert_eq!(report.checks, 4);
1064        assert_eq!(
1065            report.failures.len(),
1066            4,
1067            "every failure must be reported in one pass: {report}"
1068        );
1069    }
1070
1071    #[test]
1072    fn classifies_tool_vs_env_failures() {
1073        let reqs = vec![
1074            req(
1075                "a",
1076                EnvRequirement::Tool {
1077                    name: "syft".into(),
1078                },
1079            ),
1080            req(
1081                "b",
1082                EnvRequirement::EnvAllOf {
1083                    vars: vec!["NPM_TOKEN".into()],
1084                },
1085            ),
1086        ];
1087        let probes = EnvProbes {
1088            tool: &|_| false,
1089            endpoint: &|_| Ok(()),
1090            docker: &|| true,
1091        };
1092        let report = evaluate(&reqs, &no_env, &probes);
1093        assert_eq!(report.failures[0].kind, FailureKind::MissingTool);
1094        assert_eq!(report.failures[1].kind, FailureKind::MissingEnv);
1095    }
1096
1097    #[test]
1098    fn dedup_merges_sources_for_identical_requirements() {
1099        let reqs = vec![
1100            req(
1101                "publish:homebrew",
1102                EnvRequirement::Tool { name: "git".into() },
1103            ),
1104            req("publish:scoop", EnvRequirement::Tool { name: "git".into() }),
1105            req(
1106                "publish:homebrew",
1107                EnvRequirement::Tool { name: "git".into() },
1108            ),
1109        ];
1110        let probes = EnvProbes {
1111            tool: &|_| false,
1112            endpoint: &|_| Ok(()),
1113            docker: &|| true,
1114        };
1115        let report = evaluate(&reqs, &no_env, &probes);
1116        assert_eq!(report.checks, 1, "identical requirements must merge");
1117        assert_eq!(
1118            report.failures[0].needed_by,
1119            vec!["publish:homebrew".to_string(), "publish:scoop".to_string()]
1120        );
1121    }
1122
1123    #[test]
1124    fn env_any_of_passes_when_one_var_present() {
1125        let reqs = vec![req(
1126            "publish:release",
1127            EnvRequirement::EnvAnyOf {
1128                vars: vec!["ANODIZER_GITHUB_TOKEN".into(), "GITHUB_TOKEN".into()],
1129            },
1130        )];
1131        let env = |k: &str| (k == "GITHUB_TOKEN").then(|| "tok".to_string());
1132        let report = evaluate(&reqs, &env, &all_pass_probes());
1133        assert!(report.ok(), "{report}");
1134    }
1135
1136    #[test]
1137    fn empty_env_value_counts_as_missing() {
1138        let reqs = vec![req(
1139            "s",
1140            EnvRequirement::EnvAllOf {
1141                vars: vec!["EMPTY_VAR".into()],
1142            },
1143        )];
1144        let env = |_: &str| Some(String::new());
1145        let report = evaluate(&reqs, &env, &all_pass_probes());
1146        assert_eq!(report.failures.len(), 1);
1147        assert_eq!(report.failures[0].kind, FailureKind::MissingEnv);
1148    }
1149
1150    #[test]
1151    fn report_never_echoes_secret_values() {
1152        const SECRET: &str = "hunter2-super-secret-value";
1153        let reqs = vec![
1154            req(
1155                "publish:aur",
1156                EnvRequirement::KeyEnv {
1157                    kind: KeyKind::SshPrivate,
1158                    var: "AUR_SSH_KEY".into(),
1159                },
1160            ),
1161            req(
1162                "stage:sign",
1163                EnvRequirement::KeyEnv {
1164                    kind: KeyKind::Cosign,
1165                    var: "COSIGN_KEY".into(),
1166                },
1167            ),
1168        ];
1169        // Both vars hold the secret but are structurally invalid keys, so
1170        // both checks fail — the failure text must never leak the value.
1171        let env = |_: &str| Some(SECRET.to_string());
1172        let report = evaluate(&reqs, &env, &all_pass_probes());
1173        assert_eq!(report.failures.len(), 2);
1174        let rendered = report.to_string();
1175        assert!(
1176            !rendered.contains(SECRET),
1177            "report leaked a secret value: {rendered}"
1178        );
1179        let json = serde_json::to_string(&report).unwrap();
1180        assert!(!json.contains(SECRET), "json report leaked a secret value");
1181    }
1182
1183    #[test]
1184    fn ssh_key_valid_openssh_block_passes() {
1185        let key = "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaA==\n-----END OPENSSH PRIVATE KEY-----\n";
1186        assert!(validate_key_material(KeyKind::SshPrivate, key).is_ok());
1187    }
1188
1189    #[test]
1190    fn ssh_key_missing_trailing_newline_passes() {
1191        let key =
1192            "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaA==\n-----END OPENSSH PRIVATE KEY-----";
1193        assert!(validate_key_material(KeyKind::SshPrivate, key).is_ok());
1194    }
1195
1196    #[test]
1197    fn ssh_key_garbage_is_rejected_without_echo() {
1198        let err = validate_key_material(KeyKind::SshPrivate, "not-a-key-material").unwrap_err();
1199        assert!(!err.contains("not-a-key-material"));
1200    }
1201
1202    #[test]
1203    fn pgp_armored_and_binary_pass_garbage_fails() {
1204        let armored =
1205            "-----BEGIN PGP PRIVATE KEY BLOCK-----\nxx\n-----END PGP PRIVATE KEY BLOCK-----\n";
1206        assert!(validate_key_material(KeyKind::PgpPrivate, armored).is_ok());
1207        // 0x95 = binary OpenPGP secret-key packet tag byte.
1208        let binary = "\u{95}binarystuff";
1209        assert!(validate_key_material(KeyKind::PgpPrivate, binary).is_ok());
1210        assert!(validate_key_material(KeyKind::PgpPrivate, "plain text").is_err());
1211    }
1212
1213    #[test]
1214    fn cosign_sigstore_header_passes() {
1215        let key = "-----BEGIN ENCRYPTED SIGSTORE PRIVATE KEY-----\nxx\n-----END ENCRYPTED SIGSTORE PRIVATE KEY-----\n";
1216        assert!(validate_key_material(KeyKind::Cosign, key).is_ok());
1217        assert!(validate_key_material(KeyKind::Cosign, "ghp_token").is_err());
1218    }
1219
1220    #[test]
1221    fn key_env_missing_var_classifies_as_missing_env() {
1222        let reqs = vec![req(
1223            "publish:aur",
1224            EnvRequirement::KeyEnv {
1225                kind: KeyKind::SshPrivate,
1226                var: "AUR_SSH_KEY".into(),
1227            },
1228        )];
1229        let report = evaluate(&reqs, &no_env, &all_pass_probes());
1230        assert_eq!(report.failures[0].kind, FailureKind::MissingEnv);
1231    }
1232
1233    #[test]
1234    fn key_file_missing_and_invalid_are_flagged() {
1235        let dir = tempfile::tempdir().unwrap();
1236        let missing = dir.path().join("absent.key");
1237        let invalid = dir.path().join("invalid.key");
1238        std::fs::write(&invalid, "not a pgp key").unwrap();
1239        let reqs = vec![
1240            req(
1241                "stage:nfpm",
1242                EnvRequirement::KeyFile {
1243                    kind: KeyKind::PgpPrivate,
1244                    path: missing.display().to_string(),
1245                },
1246            ),
1247            req(
1248                "stage:nfpm",
1249                EnvRequirement::KeyFile {
1250                    kind: KeyKind::PgpPrivate,
1251                    path: invalid.display().to_string(),
1252                },
1253            ),
1254        ];
1255        let report = evaluate(&reqs, &no_env, &all_pass_probes());
1256        assert_eq!(report.failures.len(), 2);
1257        assert!(
1258            report
1259                .failures
1260                .iter()
1261                .all(|f| f.kind == FailureKind::BadKeyMaterial)
1262        );
1263    }
1264
1265    #[test]
1266    fn template_env_refs_handles_both_styles_and_default_filter() {
1267        assert_eq!(
1268            template_env_refs("{{ .Env.AUR_SSH_KEY }}"),
1269            vec!["AUR_SSH_KEY"]
1270        );
1271        assert_eq!(
1272            template_env_refs("{{ Env.MINIO_ENDPOINT }}/bucket"),
1273            vec!["MINIO_ENDPOINT"]
1274        );
1275        assert_eq!(
1276            template_env_refs("{{ Env.A }}-{{ .Env.B }}"),
1277            vec!["A", "B"]
1278        );
1279        assert!(
1280            template_env_refs(r#"{{ Env.OPTIONAL | default(value="x") }}"#).is_empty(),
1281            "default()-filtered refs are satisfiable without the var"
1282        );
1283        assert!(template_env_refs("no refs here").is_empty());
1284        assert!(
1285            template_env_refs("{{ MyEnv.NOT_AN_ENV }}").is_empty(),
1286            "identifiers ending in 'Env.' must not match"
1287        );
1288    }
1289
1290    #[test]
1291    fn sole_env_ref_only_matches_whole_single_expressions() {
1292        assert_eq!(
1293            sole_env_ref("{{ .Env.AUR_SSH_KEY }}"),
1294            Some("AUR_SSH_KEY".to_string())
1295        );
1296        assert_eq!(
1297            sole_env_ref("{{ Env.AUR_SSH_KEY }}"),
1298            Some("AUR_SSH_KEY".to_string())
1299        );
1300        assert_eq!(sole_env_ref("prefix {{ .Env.X }}"), None);
1301        assert_eq!(sole_env_ref("{{ .Env.X }}{{ .Env.Y }}"), None);
1302        assert_eq!(sole_env_ref("/path/to/key"), None);
1303    }
1304
1305    #[test]
1306    fn env_scheme_refs_extracts_cosign_style() {
1307        assert_eq!(
1308            env_scheme_refs("--key=env://COSIGN_KEY"),
1309            vec!["COSIGN_KEY"]
1310        );
1311        assert!(env_scheme_refs("--key=cosign.key").is_empty());
1312    }
1313
1314    #[test]
1315    fn endpoint_failure_includes_url_and_reason() {
1316        let reqs = vec![req(
1317            "stage:blob",
1318            EnvRequirement::Endpoint {
1319                url: "http://minio.local:9000".into(),
1320            },
1321        )];
1322        let probes = EnvProbes {
1323            tool: &|_| true,
1324            endpoint: &|_| Err("timed out".into()),
1325            docker: &|| true,
1326        };
1327        let report = evaluate(&reqs, &no_env, &probes);
1328        assert!(
1329            report.failures[0]
1330                .message
1331                .contains("http://minio.local:9000")
1332        );
1333        assert!(report.failures[0].message.contains("timed out"));
1334    }
1335
1336    #[test]
1337    fn configured_build_targets_mirror_build_resolution() {
1338        use crate::config::{BuildConfig, Config, CrateConfig, StringOrBool};
1339        use crate::context::{Context, ContextOptions};
1340
1341        let krate = |name: &str, builds: Option<Vec<BuildConfig>>| CrateConfig {
1342            name: name.to_string(),
1343            builds,
1344            ..Default::default()
1345        };
1346
1347        // A producing build with targets unset inherits the default matrix.
1348        // (A `binary` clears the planner's compile/artifact gate; a `binary:
1349        // None` build on a crate with no `--bin` would compile nothing.)
1350        let config = Config {
1351            crates: vec![krate(
1352                "app",
1353                Some(vec![BuildConfig {
1354                    binary: Some("app".to_string()),
1355                    ..Default::default()
1356                }]),
1357            )],
1358            ..Default::default()
1359        };
1360        let ctx = Context::new(config, ContextOptions::default());
1361        assert_eq!(
1362            configured_build_targets(&ctx),
1363            crate::target::DEFAULT_TARGETS
1364                .iter()
1365                .map(|s| (*s).to_string())
1366                .collect::<Vec<_>>()
1367        );
1368
1369        // Explicit per-build targets win; a skipped build and an
1370        // explicitly-empty target list contribute nothing; the union spans
1371        // crates. Each producing build carries a `binary` so it clears the
1372        // compile/artifact gate.
1373        let config = Config {
1374            crates: vec![
1375                krate(
1376                    "app",
1377                    Some(vec![
1378                        BuildConfig {
1379                            binary: Some("app".to_string()),
1380                            targets: Some(vec!["x86_64-unknown-linux-gnu".to_string()]),
1381                            ..Default::default()
1382                        },
1383                        BuildConfig {
1384                            binary: Some("app".to_string()),
1385                            targets: Some(vec!["x86_64-pc-windows-msvc".to_string()]),
1386                            skip: Some(StringOrBool::Bool(true)),
1387                            ..Default::default()
1388                        },
1389                    ]),
1390                ),
1391                krate(
1392                    "helper",
1393                    Some(vec![BuildConfig {
1394                        binary: Some("helper".to_string()),
1395                        targets: Some(vec![
1396                            "aarch64-apple-darwin".to_string(),
1397                            "x86_64-unknown-linux-gnu".to_string(),
1398                        ]),
1399                        ..Default::default()
1400                    }]),
1401                ),
1402            ],
1403            ..Default::default()
1404        };
1405        let ctx = Context::new(config.clone(), ContextOptions::default());
1406        assert_eq!(
1407            configured_build_targets(&ctx),
1408            vec![
1409                "x86_64-unknown-linux-gnu".to_string(),
1410                "aarch64-apple-darwin".to_string(),
1411            ]
1412        );
1413
1414        // --single-target narrows the union to the requested triple.
1415        let ctx = Context::new(
1416            config,
1417            ContextOptions {
1418                single_target: Some("aarch64-apple-darwin".to_string()),
1419                ..Default::default()
1420            },
1421        );
1422        assert_eq!(
1423            configured_build_targets(&ctx),
1424            vec!["aarch64-apple-darwin".to_string()]
1425        );
1426    }
1427
1428    #[test]
1429    fn configured_build_targets_no_bin_crate_with_defaults_builds_template_contributes_nothing() {
1430        use crate::config::{BuildConfig, Config, CrateConfig};
1431        use crate::context::{Context, ContextOptions};
1432
1433        // A library crate (no src/main.rs, no [[bin]]) that inherited a
1434        // `defaults.builds` template carries a build with `binary: None`. The
1435        // planner's compile/artifact gate compiles nothing for it, so the
1436        // preflight target union must be empty — no cross bundler tools demanded.
1437        let dir = tempfile::tempdir().unwrap();
1438        std::fs::write(
1439            dir.path().join("Cargo.toml"),
1440            "[package]\nname = \"lib\"\nversion = \"0.0.0\"\n",
1441        )
1442        .unwrap();
1443        let config = Config {
1444            crates: vec![CrateConfig {
1445                name: "lib".to_string(),
1446                path: dir.path().to_string_lossy().into_owned(),
1447                builds: Some(vec![BuildConfig {
1448                    // binary: None — the materialized template default.
1449                    targets: Some(vec!["aarch64-unknown-linux-gnu".to_string()]),
1450                    ..Default::default()
1451                }]),
1452                ..Default::default()
1453            }],
1454            ..Default::default()
1455        };
1456        let ctx = Context::new(config, ContextOptions::default());
1457        assert!(
1458            configured_build_targets(&ctx).is_empty(),
1459            "library crate with a binary:None template build compiles nothing",
1460        );
1461    }
1462}