Skip to main content

release_kit/setup/
context.rs

1//! The resolved context one setup run works in: target, repository, forge,
2//! the forge CLI binary, and the environment a step receives.
3//!
4//! The environment is constructed, not inherited: `env_clear` plus exactly
5//! the declared variables, the forge CLI's own configuration and
6//! authentication variables, and — only for the steps that need them — the
7//! bot credentials. The parent's environment does not leak into a
8//! privileged child, no secret is ever an argv value, and key material
9//! reaches no environment at all: `rk` reads the key the operator named and
10//! writes it to the step's standard input. [`super::secrets`] owns that
11//! boundary.
12
13use std::ffi::OsString;
14use std::path::{Path, PathBuf};
15
16use camino::Utf8PathBuf;
17use zeroize::Zeroizing;
18
19use super::secrets;
20use crate::detect::{self, Forge};
21use crate::diagnostic::{Diagnostic, Reason};
22use crate::error::RkError;
23use crate::profile::{CapabilityRequests, ProfileSnapshot, ReleaseMode};
24
25// The trunk every setup asserts is the one permanent branch the target
26// states in its own committed configuration, read through `Ctx::trunk`.
27// A target that names none keeps the compiled default, so a landing
28// predating the key behaves exactly as it did.
29
30/// A policy boolean as the JSON word a forge body carries.
31const fn bool_word(value: bool) -> &'static str {
32    if value { "true" } else { "false" }
33}
34
35/// A policy list as the JSON array a forge body carries. Every element
36/// passed the floor table, so this quotes rather than escapes.
37fn json_list(values: &[String]) -> String {
38    let inner: Vec<String> = values.iter().map(|value| format!("\"{value}\"")).collect();
39    format!("[{}]", inner.join(", "))
40}
41
42/// The GitHub API objects named by the policy's stable bypass vocabulary.
43///
44/// GitHub's built-in repository-administrator role is actor 5. Keeping that
45/// API encoding here lets configuration, diagnostics, and prose name intent
46/// while the setup owns the forge representation in one place.
47pub(super) fn github_bypass_actors(values: &[String]) -> serde_json::Value {
48    serde_json::Value::Array(
49        values
50            .iter()
51            .filter_map(|value| match value.as_str() {
52                crate::config::LOCAL_GITHUB_BYPASS => Some(serde_json::json!({
53                    "actor_id": 5,
54                    "actor_type": "RepositoryRole",
55                    "bypass_mode": "always",
56                })),
57                _ => None,
58            })
59            .collect(),
60    )
61}
62
63/// One GitHub ruleset's `rules` array, as JSON.
64///
65/// Every rule comes from `protection.owned_trunk_rules`, which the floor
66/// table judges per integration mode and the observer checks against, so
67/// one key decides what a run installs and what the check expects. A rule
68/// this convention parameterizes carries its parameters; the rest are
69/// bare type entries.
70///
71/// `wanted` selects which of the owned rules this ruleset carries. The
72/// trunk's rules live in two rulesets because a bypass actor is recorded
73/// on a ruleset: the rules a bypass may excuse are kept apart from the
74/// rules that must hold against everyone.
75fn compose_rules(
76    protection: &crate::config::Protection,
77    wanted: &[&str],
78    required_check: &str,
79    title_check: &str,
80) -> String {
81    let rules: Vec<serde_json::Value> = protection
82        .owned_trunk_rules
83        .iter()
84        .filter(|rule| wanted.iter().any(|kind| kind == &rule.as_str()))
85        .map(|rule| match rule.as_str() {
86            "pull_request" => serde_json::json!({
87                "type": "pull_request",
88                "parameters": {
89                    "required_approving_review_count": protection.required_approving_review_count,
90                    "dismiss_stale_reviews_on_push": protection.dismiss_stale_reviews_on_push,
91                    "require_code_owner_review": protection.require_code_owner_review,
92                    "require_last_push_approval": protection.require_last_push_approval,
93                    "required_review_thread_resolution": false,
94                    "require_extra_approval_for_unattributed_changes": false,
95                    "allowed_merge_methods": protection.allowed_merge_methods,
96                }
97            }),
98            "required_status_checks" => serde_json::json!({
99                "type": "required_status_checks",
100                "parameters": {
101                    "do_not_enforce_on_create": true,
102                    "strict_required_status_checks_policy":
103                        protection.strict_required_status_checks,
104                    "required_status_checks": [
105                        { "context": required_check },
106                        { "context": title_check },
107                    ],
108                }
109            }),
110            other => serde_json::json!({ "type": other }),
111        })
112        .collect();
113    // Pretty rather than compact: the body a run sends is what an
114    // operator reads back off the forge when a protection is in doubt.
115    serde_json::to_string_pretty(&rules).unwrap_or_else(|_| "[]".to_owned())
116}
117
118/// One target's effective protection policy: what it stated, resolved
119/// against the authority that carries an implementation onto its trunk.
120///
121/// A target that stated a policy gets its own values: the floor table
122/// already judged them under the same mode, and an operator who narrowed
123/// or widened something meant it. The one exception is the former compiled
124/// local tuple: it remains readable so an upgrade can migrate it, but setup
125/// must never reinstall its missing freshness rules. A target that stated nothing gets the
126/// compiled defaults, which describe forge integration because that is
127/// the shape this convention had before the axis existed — so under
128/// local integration they are adjusted rather than installed.
129///
130/// Two adjustments, and both only where the target stated nothing. GitHub
131/// names the repository-administrator role as the bypass authority while
132/// retaining every rule, so a local integrator may push but the release App
133/// may merge only the tested request. The GitLab push level moves off zero
134/// to the narrowest level that still admits a push.
135///
136/// One resolution serves the body a step sends, the observer that reads
137/// the answer back, and the prerequisites, so a canonical apply cannot
138/// install one shape and then fault its own result for not being another.
139fn effective_protection(
140    stated: Option<&crate::config::Protection>,
141    integration: crate::landing::Integration,
142) -> crate::config::Protection {
143    if let Some(stated) = stated {
144        if integration == crate::landing::Integration::Local
145            && crate::config::legacy_local_protection(stated)
146        {
147            let mut migrated = stated.clone();
148            let current = crate::config::local_protection();
149            migrated.bypass_actors = current.bypass_actors;
150            migrated.owned_trunk_rules = current.owned_trunk_rules;
151            migrated.gitlab.push_access_level = current.gitlab.push_access_level;
152            return migrated;
153        }
154        return stated.clone();
155    }
156    if integration == crate::landing::Integration::Local {
157        return crate::config::local_protection();
158    }
159    crate::config::Protection::default()
160}
161
162/// The variables that pass through from the operator's environment to a
163/// step: the interpreter's search path, the forge CLI's configuration and
164/// authentication, and nothing else.
165const PASSTHROUGH: [&str; 11] = [
166    "PATH",
167    "HOME",
168    "XDG_CONFIG_HOME",
169    "GH_TOKEN",
170    "GITHUB_TOKEN",
171    "GH_HOST",
172    "GH_CONFIG_DIR",
173    "GLAB_TOKEN",
174    "GITLAB_TOKEN",
175    "GITLAB_HOST",
176    "GLAB_CONFIG_DIR",
177];
178
179/// The value-bearing bot variables, forwarded only to the steps that
180/// consume them and recorded in the journal as handling, never as value.
181/// The key is in no list here: it reaches its step as bytes on standard
182/// input, and neither it nor its path is ever put in an environment.
183/// [`secrets`] owns that.
184pub use super::secrets::VALUE_VARS as SECRET_VARS;
185
186/// One resolved run context.
187#[derive(Debug, Clone)]
188pub struct Ctx {
189    /// The repository being set up.
190    pub target: Utf8PathBuf,
191    /// The project path on the forge, empty where the profile names none.
192    pub repo: String,
193    /// The forge adapter the run acts through, where the profile names a
194    /// forge this release drives. A target with no forge, or one this
195    /// release has no adapter for, carries none: its local steps still
196    /// run and its forge steps report as not applicable.
197    pub forge: Option<Forge>,
198    /// The forge the profile declares, preserved whatever the adapter
199    /// says, so an unknown name stays readable.
200    pub declared_forge: Option<String>,
201    /// What the project is, as the target configuration resolves it.
202    pub profile: ProfileSnapshot,
203    /// Which optional products the target requests.
204    pub capabilities: CapabilityRequests,
205    /// The remote host, where one was detected.
206    pub host: Option<String>,
207    /// The value of `--required-check`, where given.
208    pub required_check: Option<String>,
209    /// The committed `setup.required_workflow`, on GitHub alone. No flag
210    /// answers it: the setup never writes it, it reads it to prove that
211    /// the workflow the release gate waits on is the workflow that carries
212    /// the check the gate judges.
213    pub required_workflow: Option<String>,
214    /// The resolved forge CLI binary.
215    pub cli: PathBuf,
216    /// The detected technology, where the version file names one.
217    pub tech: Option<&'static str>,
218    /// The one permanent branch this target states, or the compiled
219    /// default where it states none.
220    trunk: String,
221    /// The release-line prefix this target states, or the compiled
222    /// default where it states none.
223    line_prefix: String,
224    /// The long-lived branches a single trunk retires, as this target
225    /// names them.
226    retired_branches: Vec<String>,
227    /// Whether a full apply runs the release-line protection, which a
228    /// project that keeps no line does not want run at all.
229    release_lines: bool,
230    /// The steps this target declared it does not run, each against its
231    /// stated reason. A run reports them and judges none of them.
232    excluded_steps: std::collections::BTreeMap<String, String>,
233    /// The bot App's public identifier where this target states one; the
234    /// environment still wins over it, and no private credential is here.
235    bot_app_id: Option<String>,
236    /// The ruleset that protects the trunk, as this target names it.
237    trunk_ruleset: String,
238    /// The ruleset that keeps the trunk undeletable and unrewritable, as
239    /// this target names it. It names no bypass actor.
240    safety_ruleset: String,
241    /// The ruleset that makes published tags immutable.
242    tag_ruleset: String,
243    /// The ruleset that protects the release lines.
244    lines_ruleset: String,
245    /// The context the landed title job reports under.
246    title_check: String,
247    /// The effective policy this target runs under: what the target
248    /// stated, resolved against the recorded integration mode. Every
249    /// stated value passed the floor table at load, so a run passes this
250    /// to a step without judging it again, and one resolution serves the
251    /// body a step sends, the observer that reads the answer back, and
252    /// every prerequisite — so a run cannot install one shape and then
253    /// fault its own result for not being another.
254    protection: crate::config::Protection,
255    /// Which authority carries an implementation onto this target's trunk.
256    /// A local-integration trunk takes the direct push that mode's
257    /// integrations end in, so the protection a run installs is not the
258    /// forge-integration one.
259    integration: crate::landing::Integration,
260}
261
262impl Ctx {
263    /// Resolve detection, overrides, and the forge CLI in one pass, before
264    /// any step runs.
265    ///
266    /// # Errors
267    ///
268    /// Refuses when the target is missing, when no remote resolves and no
269    /// override covers the gap, when the host is unrecognized, and when the
270    /// forge CLI is not on `PATH`.
271    pub fn resolve(
272        target: &Utf8PathBuf,
273        repo_flag: Option<&str>,
274        forge_flag: Option<&str>,
275        required_check: Option<&str>,
276    ) -> Result<Self, RkError> {
277        if !target.is_dir() {
278            return Err(RkError::missing(
279                Diagnostic::new(
280                    Reason::TargetNotFound,
281                    format!("target {target} is not a directory; nothing was run"),
282                )
283                .expected("an existing repository to set up"),
284            ));
285        }
286        let forge_flag = forge_flag
287            .map(|name| {
288                detect::Forge::parse(name).ok_or_else(|| {
289                    RkError::Usage(format!(
290                        "unknown forge '{name}'; the forges are: github, gitlab"
291                    ))
292                })
293            })
294            .transpose()?;
295        let detected = detect::detect(target.as_std_path());
296        let config = crate::config::load(target.as_std_path())?;
297        let record = crate::landing::manifest::load(target)?;
298        // The setup reads the same target configuration a landing records,
299        // so which steps apply follows the profile rather than a second
300        // detection of its own.
301        let resolved = crate::profile::Params::resolve(
302            target,
303            &crate::profile::Inputs {
304                forge: forge_flag.map(Forge::as_str),
305                repo: repo_flag,
306                ..crate::profile::Inputs::default()
307            },
308            config.as_ref(),
309            record.as_ref(),
310            crate::profile::Purpose::Preview,
311        )?;
312        let declared_forge = resolved.forge().map(str::to_owned);
313        let forge = declared_forge.as_deref().and_then(Forge::parse);
314        let repo = resolved.repo().to_owned();
315        let repo = if repo == crate::projection::REPO_PLACEHOLDER {
316            String::new()
317        } else {
318            repo
319        };
320        // The forge CLI is not a prerequisite of building a context: it is
321        // a prerequisite of the steps a run actually calls the forge for,
322        // which `require_cli` resolves at that point.
323        let cli = PathBuf::new();
324        let answers = config
325            .as_ref()
326            .map_or_else(crate::config::Setup::default, |held| held.setup.clone());
327        // The flag wins, and the committed answer fills the gap on GitHub
328        // alone: GitLab names no individual check and refuses a supplied
329        // one, so a shared configuration must not make that refusal fire.
330        let required_check = required_check.map(str::to_owned).or_else(|| {
331            Some(answers.required_check.clone())
332                .filter(|name| !name.is_empty() && forge == Some(Forge::Github))
333        });
334        let required_workflow = Some(answers.required_workflow.clone())
335            .filter(|name| !name.is_empty() && forge == Some(Forge::Github));
336        let bot_app_id = Some(answers.bot.app_id.clone()).filter(|id| !id.is_empty());
337        let trunk = resolved.trunk().to_owned();
338        // The record, not the resolution's compiled default: a setup
339        // configures a forge to match what landed, and a target with no
340        // record has landed nothing here. Forge is what such a target
341        // carries, the same compatibility answer `rk integrate` reads.
342        let integration = record
343            .as_ref()
344            .map_or_else(crate::landing::manifest::integration_forge, |held| {
345                held.git.integration
346            });
347        let stated = config.as_ref().map(|held| &held.protection);
348        let protection = effective_protection(stated, integration);
349        Ok(Self {
350            target: target.clone(),
351            repo,
352            forge,
353            host: detected.host,
354            required_check,
355            required_workflow,
356            cli,
357            tech: resolved.driver().and_then(|driver| {
358                ["rust", "python", "bash"]
359                    .into_iter()
360                    .find(|known| *known == driver)
361            }),
362            trunk_ruleset: protection.trunk_ruleset(&trunk),
363            safety_ruleset: protection.safety_ruleset(&trunk),
364            tag_ruleset: protection.tag_ruleset.clone(),
365            lines_ruleset: protection.lines_ruleset.clone(),
366            title_check: protection.title_check.clone(),
367            protection,
368            integration,
369            trunk,
370            line_prefix: resolved.line_prefix().to_owned(),
371            profile: resolved.profile().clone(),
372            capabilities: resolved.capabilities().clone(),
373            declared_forge,
374            retired_branches: answers.retired_branches,
375            release_lines: answers.release_lines,
376            excluded_steps: answers.excluded_steps,
377            bot_app_id,
378        })
379    }
380
381    /// Resolve the forge CLI where this run will call the forge for one of
382    /// `steps`, and refuse where it cannot be found.
383    ///
384    /// The prerequisite belongs to the call, not to the command. A step is
385    /// only a caller when the target's configuration selects it, the
386    /// target has not excluded it, and the step reaches the forge at this
387    /// particular forge. A preview writes nothing, and asks anyway for the
388    /// steps it would act on, because it names the command it would run
389    /// and a CLI nothing could find is worth saying then.
390    ///
391    /// # Errors
392    /// Propagates the refusal when the forge CLI cannot be resolved.
393    ///
394    /// SATISFIES forge-setup:applicability-follows-the-target-configuration
395    pub fn require_cli(&mut self, steps: &[&crate::setup::steps::StepSpec]) -> Result<(), RkError> {
396        let Some(forge) = self.forge else {
397            return Ok(());
398        };
399        let calls = steps.iter().any(|step| {
400            step.forge_cli.contains(&forge) && crate::commands::setup::stance(self, step).acts()
401        });
402        if calls && self.cli.as_os_str().is_empty() {
403            self.cli = resolve_cli(forge)?;
404        }
405        Ok(())
406    }
407
408    /// A context the integration tests build directly, for an observer
409    /// exercised against recorded forge answers rather than a repository.
410    /// The trunk and the prefix take their compiled defaults, because such
411    /// a test reads no target configuration.
412    #[doc(hidden)]
413    #[must_use]
414    pub fn for_tests(
415        target: Utf8PathBuf,
416        repo: String,
417        forge: Forge,
418        cli: PathBuf,
419        tech: Option<&'static str>,
420    ) -> Self {
421        let defaults = crate::config::Protection::default();
422        Self {
423            // The forge-integration shape, which is what every observer
424            // and request-body test here asserts; a local-mode case states it.
425            integration: crate::landing::Integration::Forge,
426            target,
427            repo,
428            forge: Some(forge),
429            declared_forge: Some(forge.as_str().to_owned()),
430            profile: ProfileSnapshot {
431                technologies: tech.into_iter().map(str::to_owned).collect(),
432                forge: Some(forge.as_str().to_owned()),
433                release: crate::profile::ReleaseIntent {
434                    mode: ReleaseMode::Automatic,
435                    driver: tech.map(str::to_owned),
436                    style: Some(crate::landing::Style::Trunk),
437                    line_prefix: Some(crate::config::LINE_PREFIX_DEFAULT.to_owned()),
438                },
439            },
440            capabilities: CapabilityRequests {
441                nix_packaging: false,
442                reporting_policy: true,
443                scorecard: false,
444                code_scanning: None,
445            },
446            host: None,
447            required_check: None,
448            required_workflow: None,
449            cli,
450            tech,
451            trunk: crate::config::TRUNK_DEFAULT.to_owned(),
452            line_prefix: crate::config::LINE_PREFIX_DEFAULT.to_owned(),
453            retired_branches: crate::config::Setup::default().retired_branches,
454            release_lines: false,
455            excluded_steps: std::collections::BTreeMap::new(),
456            bot_app_id: None,
457            trunk_ruleset: format!("{}-protection", crate::config::TRUNK_DEFAULT),
458            safety_ruleset: format!("{}-safety", crate::config::TRUNK_DEFAULT),
459            tag_ruleset: defaults.tag_ruleset.clone(),
460            lines_ruleset: defaults.lines_ruleset.clone(),
461            title_check: defaults.title_check.clone(),
462            protection: defaults,
463        }
464    }
465
466    /// Whether the run has a forge adapter to act through.
467    #[must_use]
468    pub const fn has_adapter(&self) -> bool {
469        self.forge.is_some()
470    }
471
472    /// The forge adapter, or the refusal a forge operation answers where
473    /// the profile names no forge this release drives.
474    ///
475    /// # Errors
476    ///
477    /// A `prerequisite-unmet` refusal naming the declared forge and the
478    /// ones this release drives.
479    pub fn adapter(&self) -> Result<Forge, RkError> {
480        self.forge.ok_or_else(|| {
481            let named = self.declared_forge.as_deref();
482            let message = named.map_or_else(
483                || "the profile names no forge, and this operation acts on one".to_owned(),
484                |name| {
485                    format!(
486                        "the profile names the forge {name}, which this release has no adapter for"
487                    )
488                },
489            );
490            RkError::refusal(
491                Diagnostic::new(Reason::PrerequisiteUnmet, message)
492                    .expected("a profile naming github or gitlab")
493                    .action("set profile.forge in .release-kit/config.toml, or pass --forge <github|gitlab>")
494                    .target_state("unchanged"),
495            )
496        })
497    }
498
499    /// Whether this target's release is one release-kit drives.
500    #[must_use]
501    pub const fn automatic_release(&self) -> bool {
502        matches!(self.profile.release.mode, ReleaseMode::Automatic)
503    }
504
505    /// The release driver, where the profile names one.
506    #[must_use]
507    pub fn driver(&self) -> Option<&str> {
508        self.profile.release.driver.as_deref()
509    }
510
511    /// The forge the profile declares, whatever the adapter says.
512    #[must_use]
513    pub fn declared_forge(&self) -> Option<&str> {
514        self.declared_forge.as_deref()
515    }
516
517    /// Whether the target requested the landed reporting policy.
518    #[must_use]
519    pub const fn reporting_policy(&self) -> bool {
520        self.capabilities.reporting_policy
521    }
522
523    /// The one permanent branch this run asserts.
524    #[must_use]
525    pub fn trunk(&self) -> &str {
526        &self.trunk
527    }
528
529    /// The release-line prefix this run asserts.
530    #[must_use]
531    pub fn line_prefix(&self) -> &str {
532        &self.line_prefix
533    }
534
535    /// The long-lived branches this run's single-trunk step retires.
536    #[must_use]
537    pub fn retired_branches(&self) -> &[String] {
538        &self.retired_branches
539    }
540
541    /// Whether a full apply runs the release-line protection.
542    #[must_use]
543    pub const fn release_lines(&self) -> bool {
544        self.release_lines
545    }
546
547    /// Why this target does not run the named step, where it declared an
548    /// exclusion for it. The reason is what the report prints, so an
549    /// excluded step is always visible with the answer behind it.
550    #[must_use]
551    pub fn excluded(&self, step: &str) -> Option<&str> {
552        self.excluded_steps.get(step).map(String::as_str)
553    }
554
555    /// How many steps this target declared it does not run.
556    #[must_use]
557    pub fn excluded_count(&self) -> usize {
558        self.excluded_steps.len()
559    }
560
561    /// The bot App's public identifier this target states, where it does.
562    #[must_use]
563    pub fn bot_app_id(&self) -> Option<&str> {
564        self.bot_app_id.as_deref()
565    }
566
567    /// The ruleset that protects the trunk.
568    #[must_use]
569    pub fn trunk_ruleset(&self) -> &str {
570        &self.trunk_ruleset
571    }
572
573    /// The ruleset that keeps the trunk undeletable and unrewritable.
574    #[must_use]
575    pub fn safety_ruleset(&self) -> &str {
576        &self.safety_ruleset
577    }
578
579    /// The ruleset that makes published tags immutable.
580    #[must_use]
581    pub fn tag_ruleset(&self) -> &str {
582        &self.tag_ruleset
583    }
584
585    /// The ruleset that protects the release lines.
586    #[must_use]
587    pub fn lines_ruleset(&self) -> &str {
588        &self.lines_ruleset
589    }
590
591    /// The context the landed title job reports under.
592    #[must_use]
593    pub fn title_check(&self) -> &str {
594        &self.title_check
595    }
596
597    /// Which authority carries an implementation onto this trunk.
598    #[must_use]
599    pub const fn integration(&self) -> crate::landing::Integration {
600        self.integration
601    }
602
603    /// The trunk ruleset's rules: the request and the check it carries,
604    /// which the recorded bypass actors may be excused from.
605    fn trunk_rules(&self) -> String {
606        compose_rules(
607            &self.protection,
608            &crate::config::REQUEST_RULES,
609            self.required_check.as_deref().unwrap_or_default(),
610            &self.title_check,
611        )
612    }
613
614    /// The safety ruleset's rules: what holds against every actor.
615    fn safety_rules(&self) -> String {
616        compose_rules(
617            &self.protection,
618            &crate::config::SAFETY_RULES,
619            self.required_check.as_deref().unwrap_or_default(),
620            &self.title_check,
621        )
622    }
623
624    /// The floored policy this target states, already judged at load.
625    #[must_use]
626    pub const fn protection(&self) -> &crate::config::Protection {
627        &self.protection
628    }
629
630    /// Whether this run targets a GitLab instance that is not gitlab.com,
631    /// where registry trusted publishing cannot reach.
632    #[must_use]
633    pub fn self_hosted_gitlab(&self) -> bool {
634        self.forge == Some(Forge::Gitlab)
635            && self
636                .host
637                .as_deref()
638                .is_some_and(|host| host != "gitlab.com")
639    }
640
641    /// The constructed environment a step receives. Secrets enter only for
642    /// the step that consumes them; the caller records their handling.
643    #[must_use]
644    #[allow(
645        clippy::too_many_lines,
646        reason = "one pass builds the whole environment a step receives, and splitting it would separate a variable from the value it carries"
647    )]
648    pub fn child_env(&self, step: &str) -> Vec<(OsString, OsString)> {
649        let mut env: Vec<(OsString, OsString)> = vec![
650            (
651                "RK_FORGE".into(),
652                self.forge.map_or("", Forge::as_str).into(),
653            ),
654            ("RK_REPO".into(), self.repo.clone().into()),
655            ("RK_TRUNK_BRANCH".into(), self.trunk.clone().into()),
656            ("RK_LINE_PREFIX".into(), self.line_prefix.clone().into()),
657            ("RK_TRUNK_RULESET".into(), self.trunk_ruleset.clone().into()),
658            (
659                "RK_SAFETY_RULESET".into(),
660                self.safety_ruleset.clone().into(),
661            ),
662            ("RK_TAG_RULESET".into(), self.tag_ruleset.clone().into()),
663            ("RK_LINES_RULESET".into(), self.lines_ruleset.clone().into()),
664            ("RK_TITLE_CHECK".into(), self.title_check.clone().into()),
665            // The floored policy, already judged against the floor table
666            // at load. A step receives values, never a judgment: one
667            // owner decides what passes, and it is not a shell script.
668            (
669                "RK_TAG_PATTERN".into(),
670                self.protection.tag_pattern.clone().into(),
671            ),
672            (
673                "RK_REVIEW_COUNT".into(),
674                self.protection
675                    .required_approving_review_count
676                    .to_string()
677                    .into(),
678            ),
679            (
680                "RK_DISMISS_STALE_REVIEWS".into(),
681                bool_word(self.protection.dismiss_stale_reviews_on_push).into(),
682            ),
683            (
684                "RK_CODE_OWNER_REVIEW".into(),
685                bool_word(self.protection.require_code_owner_review).into(),
686            ),
687            (
688                "RK_LAST_PUSH_APPROVAL".into(),
689                bool_word(self.protection.require_last_push_approval).into(),
690            ),
691            (
692                "RK_MERGE_METHODS".into(),
693                json_list(&self.protection.allowed_merge_methods).into(),
694            ),
695            (
696                "RK_STRICT_CHECKS".into(),
697                bool_word(self.protection.strict_required_status_checks).into(),
698            ),
699            (
700                "RK_BYPASS_ACTORS".into(),
701                github_bypass_actors(&self.protection.bypass_actors)
702                    .to_string()
703                    .into(),
704            ),
705            (
706                "RK_SQUASH_TITLE_SOURCE".into(),
707                self.protection.github.squash_title_source.clone().into(),
708            ),
709            (
710                "RK_SQUASH_BODY_SOURCE".into(),
711                self.protection.github.squash_body_source.clone().into(),
712            ),
713            (
714                "RK_GITLAB_MERGE_METHOD".into(),
715                self.protection.gitlab.merge_method.clone().into(),
716            ),
717            (
718                "RK_GITLAB_SQUASH_OPTION".into(),
719                self.protection.gitlab.squash_option.clone().into(),
720            ),
721            (
722                "RK_GITLAB_SQUASH_TEMPLATE".into(),
723                self.protection.gitlab.squash_commit_template.clone().into(),
724            ),
725            (
726                "RK_GITLAB_PUSH_LEVEL".into(),
727                self.protection.gitlab.push_access_level.to_string().into(),
728            ),
729            // The two rulesets' rules, built from the one key the floor
730            // table judges and the observer reads, so the body a run
731            // sends cannot install a rule the check does not expect, or
732            // omit one it does. The split is what a bypass costs: an
733            // actor excused from the trunk ruleset is excused from every
734            // rule in it, so the rules that must hold against everyone
735            // live in the safety ruleset, which names nobody.
736            ("RK_TRUNK_RULES".into(), self.trunk_rules().into()),
737            ("RK_SAFETY_RULES".into(), self.safety_rules().into()),
738            (
739                "RK_GITLAB_MERGE_LEVEL".into(),
740                self.protection.gitlab.merge_access_level.to_string().into(),
741            ),
742            ("GH_PAGER".into(), "".into()),
743            ("GLAB_PAGER".into(), "".into()),
744        ];
745        if let Some(check) = &self.required_check
746            && self.forge == Some(Forge::Github)
747            && matches!(step, "protect-trunk" | "protections-check")
748        {
749            env.push(("RK_REQUIRED_CHECK".into(), check.clone().into()));
750        }
751        for name in PASSTHROUGH {
752            if let Some(value) = std::env::var_os(name) {
753                env.push((name.into(), value));
754            }
755        }
756        // The forge CLI override substitutes the binary for the run's own
757        // calls; a step resolves the CLI by name, so the override's
758        // directory leads the child's search path.
759        if let Some(dir) = self.cli_override_dir() {
760            let mut paths: Vec<PathBuf> = vec![dir];
761            if let Some(existing) = std::env::var_os("PATH") {
762                paths.extend(std::env::split_paths(&existing));
763            }
764            if let Ok(joined) = std::env::join_paths(paths) {
765                env.retain(|(name, _)| name != "PATH");
766                env.push(("PATH".into(), joined));
767            }
768        }
769        if step == "bot-secrets" {
770            for name in SECRET_VARS {
771                if let Some(value) = secrets::value_of(name) {
772                    env.push((name.into(), value));
773                }
774            }
775        }
776        env
777    }
778
779    /// The directory of an explicitly overridden forge CLI, where one is set.
780    fn cli_override_dir(&self) -> Option<PathBuf> {
781        let overridden = std::env::var_os(match self.forge? {
782            Forge::Github => "RK_GH_BIN",
783            Forge::Gitlab => "RK_GLAB_BIN",
784        })?;
785        Path::new(&overridden).parent().map(Path::to_path_buf)
786    }
787
788    /// The secret bytes a run must keep out of its own output: the values
789    /// the environment carries. Every buffer is scrubbed on drop; none is
790    /// ever logged or echoed.
791    ///
792    /// Key material is not read here. The step that transmits a key adds
793    /// the very bytes it sends, so the needle cannot describe one file
794    /// while the child receives another.
795    #[must_use]
796    pub fn secret_values() -> Vec<Zeroizing<Vec<u8>>> {
797        SECRET_VARS
798            .iter()
799            .filter_map(|name| secrets::value_of(name))
800            .map(|value| Zeroizing::new(value.into_encoded_bytes()))
801            .collect()
802    }
803}
804
805/// Resolve the forge CLI once, at context time: the `RK_GH_BIN` and
806/// `RK_GLAB_BIN` overrides first, then a `PATH` search.
807///
808/// Not found and not executable are distinct failures, in the shell
809/// convention. `rk branches prune` shares it for the verify path.
810///
811/// # Errors
812///
813/// Refuses when the override or the search resolves no usable binary.
814pub fn resolve_cli(forge: Forge) -> Result<PathBuf, RkError> {
815    let override_var = match forge {
816        Forge::Github => "RK_GH_BIN",
817        Forge::Gitlab => "RK_GLAB_BIN",
818    };
819    if let Some(overridden) = std::env::var_os(override_var).filter(|v| !v.is_empty()) {
820        let path = PathBuf::from(&overridden);
821        if !path.is_file() {
822            return Err(RkError::refusal(
823                Diagnostic::new(
824                    Reason::PrerequisiteUnmet,
825                    format!(
826                        "{override_var} names {}, which does not exist",
827                        path.display()
828                    ),
829                )
830                .expected("the override to name the forge CLI binary"),
831            ));
832        }
833        // The scripts invoke the CLI by its canonical name through the
834        // child's search path, so an override under any other name would
835        // split one lifecycle across two binaries: observed through the
836        // override, applied through whatever the name resolves to.
837        if path.file_name().is_none_or(|name| name != forge.cli()) {
838            return Err(RkError::refusal(
839                Diagnostic::new(
840                    Reason::PrerequisiteUnmet,
841                    format!(
842                        "{override_var} must name a binary called {}, and {} is not one",
843                        forge.cli(),
844                        path.display()
845                    ),
846                )
847                .expected(format!(
848                    "an override whose file name is {}, so scripts and observations run one binary",
849                    forge.cli()
850                )),
851            ));
852        }
853        return Ok(path);
854    }
855    let name = forge.cli();
856    let found = std::env::var_os("PATH").and_then(|path| {
857        std::env::split_paths(&path)
858            .map(|dir| dir.join(name))
859            .find(|candidate| candidate.is_file())
860    });
861    found.ok_or_else(|| {
862        RkError::refusal(
863            Diagnostic::new(
864                Reason::PrerequisiteUnmet,
865                format!(
866                    "{name} is not on PATH, and a step this run acts on calls it on {}",
867                    forge.as_str()
868                ),
869            )
870            .expected(format!("the {name} CLI installed and authenticated"))
871            .action(format!("install {name}, then run {name} auth login")),
872        )
873    })
874}
875
876#[cfg(test)]
877mod tests {
878    /// Both rulesets' rules come from the one owned-rules key, so what a
879    /// run installs, what the floor table judges, and what the check
880    /// expects cannot disagree. The split is what a bypass costs: a
881    /// recorded actor is excused from every rule in the ruleset it names,
882    /// so the rules that hold against everyone are composed apart, and a
883    /// target under either authority composes the same two halves.
884    #[test]
885    fn each_ruleset_composes_its_half_of_the_owned_rule_key() {
886        let kinds = |text: &str| -> Vec<String> {
887            let parsed: Vec<serde_json::Value> =
888                serde_json::from_str(text).expect("the rules parse");
889            parsed
890                .iter()
891                .filter_map(|rule| rule["type"].as_str())
892                .map(str::to_owned)
893                .collect()
894        };
895        let mut policy = crate::config::Protection::default();
896        let request =
897            super::compose_rules(&policy, &crate::config::REQUEST_RULES, "gate", "pr-title");
898        assert_eq!(kinds(&request), ["pull_request", "required_status_checks"]);
899        let safety =
900            super::compose_rules(&policy, &crate::config::SAFETY_RULES, "gate", "pr-title");
901        assert_eq!(kinds(&safety), ["deletion", "non_fast_forward"]);
902
903        let parsed: Vec<serde_json::Value> =
904            serde_json::from_str(&request).expect("the rules parse");
905        let checks = parsed
906            .iter()
907            .find(|rule| rule["type"] == "required_status_checks")
908            .expect("the check rule");
909        assert_eq!(
910            checks["parameters"]["required_status_checks"],
911            serde_json::json!([{ "context": "gate" }, { "context": "pr-title" }])
912        );
913
914        // The recorded bypass changes who is excused, never which rules
915        // each ruleset carries.
916        policy.bypass_actors = vec![crate::config::LOCAL_GITHUB_BYPASS.into()];
917        assert_eq!(
918            kinds(&super::compose_rules(
919                &policy,
920                &crate::config::REQUEST_RULES,
921                "gate",
922                "pr-title"
923            )),
924            ["pull_request", "required_status_checks"]
925        );
926        assert_eq!(
927            kinds(&super::compose_rules(
928                &policy,
929                &crate::config::SAFETY_RULES,
930                "gate",
931                "pr-title"
932            )),
933            ["deletion", "non_fast_forward"]
934        );
935    }
936
937    /// One effective policy serves the body a step sends, the observer
938    /// that reads the answer back, and every prerequisite.
939    ///
940    /// A target that stated nothing gets the compiled defaults, which
941    /// describe forge integration because that is the shape this
942    /// convention had before the axis existed — so under local
943    /// integration they are adjusted: the GitHub administrator role gains
944    /// the bypass that admits the direct push, and the GitLab level moves
945    /// off the zero that would close the trunk to that push. A
946    /// target that stated a policy keeps every value it stated, because
947    /// the floor table already judged it under the same mode. The former
948    /// compiled local tuple is migrated before setup can reinstall it.
949    #[test]
950    fn the_effective_policy_follows_the_recorded_authority() {
951        use crate::landing::Integration;
952        let silent = super::effective_protection(None, Integration::Forge);
953        assert!(
954            silent
955                .owned_trunk_rules
956                .contains(&"pull_request".to_owned())
957        );
958        assert_eq!(silent.gitlab.push_access_level, 0);
959
960        let silent = super::effective_protection(None, Integration::Local);
961        assert_eq!(
962            silent.owned_trunk_rules,
963            crate::config::Protection::default().owned_trunk_rules,
964            "local integration retains the release request's atomic check"
965        );
966        assert_eq!(
967            silent.bypass_actors,
968            [crate::config::LOCAL_GITHUB_BYPASS.to_owned()]
969        );
970        assert_eq!(
971            silent.gitlab.push_access_level, 40,
972            "zero would close the trunk to the push this mode ends in"
973        );
974
975        let mut stated = crate::config::Protection::default();
976        stated.gitlab.push_access_level = 0;
977        stated.owned_trunk_rules = vec!["deletion".into()];
978        let held = super::effective_protection(Some(&stated), Integration::Local);
979        assert_eq!(held.gitlab.push_access_level, 0, "a stated value wins");
980        assert_eq!(held.owned_trunk_rules, ["deletion".to_owned()]);
981
982        let legacy = crate::config::Protection {
983            owned_trunk_rules: vec!["deletion".into(), "non_fast_forward".into()],
984            gitlab: crate::config::Gitlab {
985                push_access_level: 40,
986                ..crate::config::Gitlab::default()
987            },
988            ..crate::config::Protection::default()
989        };
990        let migrated = super::effective_protection(Some(&legacy), Integration::Local);
991        assert_eq!(
992            migrated,
993            crate::config::local_protection(),
994            "setup cannot reinstall the legacy policy while upgrade remains able to read it"
995        );
996    }
997}