agentmux_srv_core/backend/vault/
github_secret.rs1use super::aws_import::Described;
15use super::source_link::{Link, GITHUB_SECRET};
16use crate::identity::aws_broker::mint::{RunError, RunSpec, Runner, RECIPE_TIMEOUT};
17
18pub const NO_SUCH_SECRET: &str = "GitHub has no secret by that name there";
20pub 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";
24const SESSION: [&str; 2] = ["DBUS_SESSION_BUS_ADDRESS", "XDG_RUNTIME_DIR"];
27
28#[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
37fn 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 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 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 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 fn secret_endpoint(&self) -> String {
83 format!("{}/{}", self.collection(), self.name)
84 }
85
86 fn collection_endpoint(&self) -> String {
88 format!("{}?per_page=1", self.collection())
89 }
90}
91
92fn argv(endpoint: String) -> Vec<String> {
94 ["api", "--hostname", HOST, "--method", "GET", "--include"].iter().map(|s| s.to_string()).chain([endpoint]).collect()
95}
96
97struct Answer(Vec<u8>);
100
101impl Answer {
102 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 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
115async 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
134pub 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;