Skip to main content

agentmux_srv_core/backend/vault/
github_secret.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The check of a CI secret: a repository's or an environment's Actions secret
5//! (docs/specs/SPEC_VAULT_LINKED_ENTRIES_FLEET_VAULT_AND_BATCH_IMPORT_2026_11_15.md ยง2.6).
6//!
7//! GitHub never gives a secret's value back. It gives a listing entry: the name and when it was last updated. This
8//! reads that one entry with the GitHub CLI signed in on this computer, and keeps of the answer only whether the
9//! secret is there and the day it last changed. The read is built from the entry's own link and nothing else: one
10//! secret, a GET, a fixed endpoint. When GitHub says "not found", the collection the secret is in is asked for one
11//! entry, and only that answer's status is read: it says whether this login can read secrets there at all, which
12//! tells a secret that is gone from one this login may not see. No other login is ever tried in the CLI's place.
13
14use super::aws_import::Described;
15use super::source_link::{Link, GITHUB_SECRET};
16use crate::identity::aws_broker::mint::{RunError, RunSpec, Runner, RECIPE_TIMEOUT};
17
18/// What the check says of a secret that isn't there, where this login can read the secrets.
19pub const NO_SUCH_SECRET: &str = "GitHub has no secret by that name there";
20/// What it says when neither the secret nor the collection it would be in answers.
21pub const CANT_READ: &str = "the secrets there can't be read with this computer's GitHub login";
22const NO_CLI: &str = "this computer has no GitHub CLI (gh), which the check of a CI secret reads with";
23const HOST: &str = "github.com";
24/// What the desktop's keyring is reached through, where the CLI keeps its login on Linux. Passed on to the child
25/// beside the allowlisted environment; neither is a credential.
26const SESSION: [&str; 2] = ["DBUS_SESSION_BUS_ADDRESS", "XDG_RUNTIME_DIR"];
27
28/// A CI secret's place, each part held to a strict name: they go into the path of a request.
29#[derive(Debug, Clone, PartialEq)]
30pub struct Place {
31    pub owner: String,
32    pub repo: String,
33    pub environment: Option<String>,
34    pub name: String,
35}
36
37/// Letters, digits and `extra`, not starting with a dash, and not a path's `.` or `..`.
38fn named(s: &str, extra: &str, max: usize) -> bool {
39    !s.is_empty() && s.len() <= max && !s.starts_with('-') && s != "." && s != ".." && s.chars().all(|c| c.is_ascii_alphanumeric() || extra.contains(c))
40}
41
42impl Place {
43    /// The place `link` names, when every part of it is a name GitHub could have given. The Vault holds a link to
44    /// the same when it is saved; it is held to it again here, where it becomes a request.
45    pub fn of(link: &Link) -> Result<Place, String> {
46        let wrong = |what: &str| format!("the entry's place is not a CI secret a check can read: {what}");
47        if link.kind != GITHUB_SECRET {
48            return Err(wrong("it is not of the kind github-secret"));
49        }
50        let (repository, environment) = link.location.split_once('@').map_or((link.location.as_str(), None), |(r, e)| (r, Some(e)));
51        let Some((owner, repo)) = repository.split_once('/') else { return Err(wrong("the repository is owner/repo")) };
52        if !named(owner, "-", 39) || !named(repo, "-_.", 100) {
53            return Err(wrong("the repository is owner/repo, in letters, digits, - _ and ."));
54        }
55        if environment.is_some_and(|e| !named(e, "-_.", 100)) {
56            return Err(wrong("the environment's name is letters, digits, - _ and ."));
57        }
58        if !named(&link.key, "_", 100) {
59            return Err(wrong("the secret's name is letters, digits and _"));
60        }
61        Ok(Place { owner: owner.into(), repo: repo.into(), environment: environment.map(str::to_string), name: link.key.clone() })
62    }
63
64    /// `owner/repo`, as the Audit names the repository of a read.
65    pub fn repository(&self) -> String {
66        format!("{}/{}", self.owner, self.repo)
67    }
68
69    fn repository_endpoint(&self) -> String {
70        format!("repos/{}/{}", self.owner, self.repo)
71    }
72
73    /// The repository's secrets, or the environment's.
74    fn collection(&self) -> String {
75        match &self.environment {
76            None => format!("{}/actions/secrets", self.repository_endpoint()),
77            Some(environment) => format!("{}/environments/{environment}/secrets", self.repository_endpoint()),
78        }
79    }
80
81    /// The one listing entry: the repository's secret, or the environment's.
82    fn secret_endpoint(&self) -> String {
83        format!("{}/{}", self.collection(), self.name)
84    }
85
86    /// The collection the secret is in, asked for one entry at most. Only its status is read.
87    fn collection_endpoint(&self) -> String {
88        format!("{}?per_page=1", self.collection())
89    }
90}
91
92/// The arguments of the one kind of run there is: a GET of `endpoint` at github.com, with the answer's status line.
93fn argv(endpoint: String) -> Vec<String> {
94    ["api", "--hostname", HOST, "--method", "GET", "--include"].iter().map(|s| s.to_string()).chain([endpoint]).collect()
95}
96
97/// What the CLI printed for one request: the status line, the headers and the body. Nothing of it is read but
98/// the status line, and the body only where [`Answer::body`] is called, which is for the secret's own entry.
99struct Answer(Vec<u8>);
100
101impl Answer {
102    /// The status code, from the first line alone.
103    fn status(&self) -> Option<u16> {
104        let line = self.0.split(|byte| *byte == b'\n').next()?;
105        std::str::from_utf8(line).ok()?.trim().strip_prefix("HTTP/")?.split_whitespace().nth(1)?.parse().ok()
106    }
107
108    /// What follows the headers.
109    fn body(&self) -> String {
110        let text = String::from_utf8_lossy(&self.0);
111        text.split_once("\r\n\r\n").or_else(|| text.split_once("\n\n")).map_or(String::new(), |(_, body)| body.to_string())
112    }
113}
114
115/// Runs the GitHub CLI for `endpoint` and gives GitHub's answer with its status code. The CLI's own words are read
116/// only to say why there was no answer, and none of them is kept.
117async fn ask<R: Runner>(runner: &R, endpoint: String) -> Result<(u16, Answer), String> {
118    let Some(program) = runner.which("gh") else { return Err(NO_CLI.into()) };
119    let mut env: Vec<(String, String)> = [("GH_PROMPT_DISABLED", "1"), ("GH_NO_UPDATE_NOTIFIER", "1"), ("NO_COLOR", "1")].iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
120    env.extend(SESSION.iter().filter_map(|name| Some((name.to_string(), std::env::var(name).ok()?))));
121    let out = match runner.run(RunSpec { program, args: argv(endpoint), env, timeout: RECIPE_TIMEOUT }).await {
122        Ok(out) => out,
123        Err(RunError::TimedOut) => return Err(format!("GitHub took too long to answer ({} s). Try again in a minute.", RECIPE_TIMEOUT.as_secs())),
124        Err(RunError::Spawn(_)) => return Err("couldn't run the GitHub CLI on this computer".into()),
125    };
126    let said = Answer(out.stdout);
127    match said.status() {
128        Some(status) => Ok((status, said)),
129        None if out.stderr.contains("gh auth login") => Err("the GitHub CLI on this computer is signed out: a person runs `gh auth login` there".into()),
130        None => Err("the GitHub CLI got no answer from GitHub: `gh auth status` on this computer says whether it is signed in".into()),
131    }
132}
133
134/// Reads the listing entry of the secret `link` names. A secret that isn't there, where this login can read the
135/// secrets, fails with [`NO_SUCH_SECRET`]; a "not found" where it can't fails with [`CANT_READ`]. The two are told
136/// apart by asking for the collection, and by each answer's status code, never by its text: the collection's
137/// answer is dropped unread. Of the secret's entry only the day it was last updated is kept.
138pub async fn describe<R: Runner>(runner: &R, link: &Link) -> Result<Described, String> {
139    let place = Place::of(link)?;
140    match ask(runner, place.secret_endpoint()).await? {
141        (200, entry) => {
142            let said: serde_json::Value = serde_json::from_str(&entry.body()).unwrap_or_default();
143            if !said["name"].as_str().is_some_and(|name| name.eq_ignore_ascii_case(&place.name)) {
144                return Err("GitHub answered with something that isn't that secret's listing entry".into());
145            }
146            let changed = said["updated_at"].as_str().and_then(|at| chrono::DateTime::parse_from_rfc3339(at.trim()).ok()).map(|t| t.with_timezone(&chrono::Utc).date_naive());
147            Ok(Described { changed, rotation: None, deleted: false })
148        }
149        (404, _) => match ask(runner, place.collection_endpoint()).await?.0 {
150            200 => Err(NO_SUCH_SECRET.into()),
151            _ => Err(CANT_READ.into()),
152        },
153        (401, _) => Err("GitHub refused this computer's GitHub login: a person signs in again with `gh auth login`".into()),
154        (403, _) => Err("GitHub refused the read (status 403): this computer's GitHub login may not read that repository's secrets".into()),
155        (code, _) => Err(format!("GitHub answered with status {code}")),
156    }
157}
158
159#[cfg(test)]
160#[path = "github_secret_tests.rs"]
161pub(super) mod tests;