Skip to main content

vgi_cli/
github.rs

1//! GitHub, through the person's own `gh` login.
2//!
3//! Every request is one `gh api` process with its arguments passed as an
4//! argument vector — never a shell string — and any body on stdin
5//! (`--input -`), so nothing from a repository name, a file or a DID is ever
6//! parsed by a shell or read as a flag. Each path segment is percent-encoded
7//! (including `{` and `}`, which `gh api` would otherwise fill in from the
8//! current directory's repository).
9
10use std::ffi::OsString;
11use std::io::Write;
12use std::process::{Command, Stdio};
13
14use anyhow::{Context, Result, anyhow, bail};
15use base64::Engine;
16use base64::engine::general_purpose::STANDARD;
17use serde_json::{Value, json};
18use vgi_forge::{BootstrapStep, ForgeAccount, ProtectionSpec, RepoSpec, StepAction, VgiConfig};
19use vgi_forge_github::plan::{
20    CODEOWNERS_LOCATIONS, CODEOWNERS_PATH, CheckGuard, RULESET_NAME, github_plan, render_codeowners,
21};
22use vgi_forge_github::{API_VERSION, DEFAULT_CHECKOUT_ACTION, ruleset_body, ruleset_satisfies};
23
24use crate::report::{Change, Report};
25
26/// One `gh api` reply.
27#[derive(Debug)]
28pub struct Reply {
29    /// HTTP status.
30    pub status: u16,
31    /// Body.
32    pub body: Vec<u8>,
33}
34
35impl Reply {
36    fn json(&self) -> Result<Value> {
37        if self.body.iter().all(u8::is_ascii_whitespace) {
38            return Ok(Value::Null);
39        }
40        serde_json::from_slice(&self.body).context("GitHub's reply is not JSON")
41    }
42
43    fn message(&self) -> String {
44        self.json()
45            .ok()
46            .and_then(|v| v.get("message").and_then(Value::as_str).map(str::to_string))
47            .unwrap_or_else(|| String::from_utf8_lossy(&self.body).trim().to_string())
48    }
49}
50
51/// `gh api` against one host.
52#[derive(Debug, Clone)]
53pub struct Gh {
54    program: OsString,
55    host: String,
56}
57
58/// Percent-encode one path segment: everything but RFC 3986 unreserved.
59pub fn segment(s: &str) -> String {
60    let mut out = String::with_capacity(s.len());
61    for b in s.bytes() {
62        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
63            out.push(b as char);
64        } else {
65            out.push_str(&format!("%{b:02X}"));
66        }
67    }
68    out
69}
70
71/// `a/b/c` from segments, each encoded.
72pub fn path(segments: &[&str]) -> String {
73    segments
74        .iter()
75        .map(|s| segment(s))
76        .collect::<Vec<_>>()
77        .join("/")
78}
79
80impl Gh {
81    /// `gh` from `PATH`, for `host` (`github.com`, or a GHES host).
82    pub fn new(host: impl Into<String>) -> Self {
83        Gh {
84            program: "gh".into(),
85            host: host.into(),
86        }
87    }
88
89    /// The argument vector for one request (exposed for tests).
90    pub fn argv(&self, method: &str, path: &str, with_body: bool) -> Vec<String> {
91        let mut argv = vec![
92            "api".to_string(),
93            "--hostname".into(),
94            self.host.clone(),
95            "--include".into(),
96            "--method".into(),
97            method.into(),
98            "-H".into(),
99            "Accept: application/vnd.github+json".into(),
100            "-H".into(),
101            format!("X-GitHub-Api-Version: {API_VERSION}"),
102        ];
103        if with_body {
104            argv.push("--input".into());
105            argv.push("-".into());
106        }
107        // Last, and never flag-like: every path starts with a letter.
108        argv.push(path.into());
109        argv
110    }
111
112    /// One request. A non-2xx status is a [`Reply`], not an error; failing to
113    /// run `gh`, or `gh` failing before any HTTP exchange (no login), is.
114    pub fn request(&self, method: &str, path: &str, body: Option<&Value>) -> Result<Reply> {
115        debug_assert!(path.starts_with(|c: char| c.is_ascii_alphabetic()));
116        let mut child = Command::new(&self.program)
117            .args(self.argv(method, path, body.is_some()))
118            .stdin(if body.is_some() {
119                Stdio::piped()
120            } else {
121                Stdio::null()
122            })
123            .stdout(Stdio::piped())
124            .stderr(Stdio::piped())
125            .spawn()
126            .map_err(|e| {
127                anyhow!("could not run `gh` ({e}); install the GitHub CLI and run `gh auth login`")
128            })?;
129        if let Some(body) = body {
130            let mut stdin = child.stdin.take().expect("piped stdin");
131            stdin
132                .write_all(&serde_json::to_vec(body)?)
133                .context("writing the request body to gh")?;
134        }
135        let out = child.wait_with_output().context("waiting for gh")?;
136        parse_include(&out.stdout).ok_or_else(|| {
137            anyhow!(
138                "`gh api {method} {path}` failed: {}",
139                String::from_utf8_lossy(&out.stderr).trim()
140            )
141        })
142    }
143
144    /// `GET`, with 404 as `None`.
145    pub fn get(&self, path: &str) -> Result<Option<Value>> {
146        let r = self.request("GET", path, None)?;
147        match r.status {
148            200..=299 => Ok(Some(r.json()?)),
149            404 => Ok(None),
150            s => bail!("GET {path}: HTTP {s}: {}", r.message()),
151        }
152    }
153
154    /// A change; any non-2xx is an error.
155    pub fn send(&self, method: &str, path: &str, body: Option<&Value>) -> Result<Value> {
156        let r = self.request(method, path, body)?;
157        match r.status {
158            200..=299 => r.json(),
159            s => bail!("{method} {path}: HTTP {s}: {}", r.message()),
160        }
161    }
162}
163
164/// Split `gh api --include` output into status and body.
165fn parse_include(out: &[u8]) -> Option<Reply> {
166    if !out.starts_with(b"HTTP/") {
167        return None;
168    }
169    let (head, body) = match find(out, b"\r\n\r\n") {
170        Some(i) => (&out[..i], &out[i + 4..]),
171        None => match find(out, b"\n\n") {
172            Some(i) => (&out[..i], &out[i + 2..]),
173            None => (out, &[][..]),
174        },
175    };
176    let first = std::str::from_utf8(head).ok()?.lines().next()?;
177    let status = first.split_whitespace().nth(1)?.parse().ok()?;
178    Some(Reply {
179        status,
180        body: body.to_vec(),
181    })
182}
183
184fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
185    hay.windows(needle.len()).position(|w| w == needle)
186}
187
188/// What the repository and its account say about who owns it.
189#[derive(Debug)]
190pub struct RepoFacts {
191    /// The owning account's login as the resource names it (lowercased),
192    /// used in API paths; GitHub matches it case-insensitively.
193    pub owner: String,
194    /// Repository name.
195    pub name: String,
196    /// The owning account is a user (a personal repository).
197    pub personal: bool,
198    /// The owning account.
199    pub account: ForgeAccount,
200}
201
202/// Look the repository up and check the caller can administer it.
203pub fn repo_facts(gh: &Gh, owner: &str, name: &str) -> Result<RepoFacts> {
204    let repo = gh.get(&path(&["repos", owner, name]))?.ok_or_else(|| {
205        anyhow!(
206            "{owner}/{name} does not exist, or your gh login cannot see it. Create it first: \
207             gh repo create {owner}/{name} --private (or --public)"
208        )
209    })?;
210    if repo.pointer("/permissions/admin").and_then(Value::as_bool) != Some(true) {
211        bail!(
212            "your gh login is not an admin of {owner}/{name}; the ruleset needs admin (the \
213             account holder, or an org owner, runs this)"
214        );
215    }
216    let acct = repo
217        .get("owner")
218        .ok_or_else(|| anyhow!("repository has no owner"))?;
219    let id = acct
220        .get("id")
221        .and_then(Value::as_u64)
222        .ok_or_else(|| anyhow!("repository owner has no id"))?;
223    let login = acct
224        .get("login")
225        .and_then(Value::as_str)
226        .unwrap_or(owner)
227        .to_string();
228    Ok(RepoFacts {
229        owner: owner.into(),
230        name: name.into(),
231        personal: acct.get("type").and_then(Value::as_str) == Some("User"),
232        account: ForgeAccount::new(id, login),
233    })
234}
235
236fn account(v: &Value, what: &str) -> Result<ForgeAccount> {
237    let id = v
238        .get("id")
239        .and_then(Value::as_u64)
240        .ok_or_else(|| anyhow!("{what}: no id"))?;
241    let login = v
242        .get("login")
243        .and_then(Value::as_str)
244        .ok_or_else(|| anyhow!("{what}: no login"))?;
245    Ok(ForgeAccount::new(id, login))
246}
247
248/// The owners the guard is chosen from: the person running this (on a
249/// personal repository, the account holder — the only admin one can have)
250/// plus each `--code-owner`, counted once per account id.
251///
252/// On an organisation repository fewer than two owners is refused unless
253/// `solo`: with no owner review, any other member with write access could
254/// edit the workflow in the pull request it judges.
255pub fn owners(
256    gh: &Gh,
257    facts: &RepoFacts,
258    code_owners: &[String],
259    solo: bool,
260) -> Result<Vec<ForgeAccount>> {
261    let mut out: Vec<ForgeAccount> = Vec::new();
262    let mut add = |a: ForgeAccount| {
263        if !out.iter().any(|o| o.id == a.id) {
264            out.push(a);
265        }
266    };
267    if facts.personal {
268        add(facts.account.clone());
269    } else {
270        let me = gh
271            .get("user")?
272            .ok_or_else(|| anyhow!("could not read your GitHub account"))?;
273        add(account(&me, "your account")?);
274    }
275    for login in code_owners {
276        let v = gh
277            .get(&path(&["users", login]))?
278            .ok_or_else(|| anyhow!("no GitHub account `{login}`"))?;
279        add(account(&v, login)?);
280    }
281    if !facts.personal && out.len() < 2 && !solo {
282        bail!(
283            "{}/{} belongs to an organisation and you are its only owner here. With one owner \
284             only the check is required and no one has to review workflow changes, so any other \
285             member with write access could edit .github/workflows/verify-trust.yml in the very \
286             pull request it judges. Name another owner with --code-owner <login> (two or more \
287             owners require a code owner's review of .github/), or pass --solo to accept that",
288            facts.owner,
289            facts.name
290        );
291    }
292    Ok(out)
293}
294
295/// The adapter's own plan for this repository under `guard`.
296pub fn plan(spec: &RepoSpec, cfg: &VgiConfig, guard: &CheckGuard) -> Result<Vec<BootstrapStep>> {
297    Ok(github_plan(spec, cfg, DEFAULT_CHECKOUT_ACTION, guard)?)
298}
299
300/// Run `steps` in order, check-then-apply, stopping at the first failure
301/// (as the bridge does: the ruleset must never land before the workflow).
302pub fn apply(
303    gh: &Gh,
304    facts: &RepoFacts,
305    steps: &[BootstrapStep],
306    report: &mut Report,
307) -> Result<()> {
308    let (o, n) = (facts.owner.as_str(), facts.name.as_str());
309    for step in steps {
310        let id = step.id.as_str();
311        match &step.action {
312            StepAction::WriteFile {
313                path: p,
314                contents,
315                message,
316            } => {
317                let change = write_file(gh, o, n, p, contents, message, report.dry_run())?;
318                report.step(id, p, change, Some(&String::from_utf8_lossy(contents)));
319            }
320            StepAction::RemoveFile { path: p, message } => {
321                let change = remove_file(gh, o, n, p, message, report.dry_run())?;
322                report.step(id, p, change, None);
323            }
324            StepAction::RemoveVariable { name } => {
325                let url = path(&["repos", o, n, "actions", "variables", name]);
326                let change = match gh.get(&url)? {
327                    None => Change::Unchanged,
328                    Some(_) => {
329                        if !report.dry_run() {
330                            gh.send("DELETE", &url, None)?;
331                        }
332                        Change::Remove
333                    }
334                };
335                report.step(id, &format!("variable {name}"), change, None);
336            }
337            StepAction::RequireOwnerReview {
338                paths,
339                owners,
340                community_rules,
341                message,
342            } => {
343                let (target, contents) = codeowners(gh, o, n, paths, owners, community_rules)?;
344                let change = write_file(
345                    gh,
346                    o,
347                    n,
348                    &target,
349                    contents.as_bytes(),
350                    message,
351                    report.dry_run(),
352                )?;
353                report.step(id, &target, change, Some(&contents));
354            }
355            StepAction::ProtectDefaultBranch(spec) => {
356                let (change, body) = protect(gh, o, n, spec, report.dry_run())?;
357                report.step(
358                    id,
359                    &format!("ruleset \"{RULESET_NAME}\""),
360                    change,
361                    Some(&serde_json::to_string_pretty(&body)?),
362                );
363            }
364            other => bail!(
365                "step `{id}` ({other:?}) needs the community's bridge; `vgi repo init` runs the \
366                 manual-mode plan only"
367            ),
368        }
369    }
370    Ok(())
371}
372
373fn contents_path(owner: &str, name: &str, file: &str) -> String {
374    let mut segs = vec!["repos", owner, name, "contents"];
375    segs.extend(file.split('/'));
376    path(&segs)
377}
378
379/// The file at `file` on the default branch: its blob sha and bytes.
380fn read_file(gh: &Gh, owner: &str, name: &str, file: &str) -> Result<Option<(String, Vec<u8>)>> {
381    vgi_forge::validate_repo_path(file)?;
382    let Some(v) = gh.get(&contents_path(owner, name, file))? else {
383        return Ok(None);
384    };
385    if v.is_array() || v.get("type").and_then(Value::as_str) != Some("file") {
386        bail!("`{file}` exists in {owner}/{name} and is not a file");
387    }
388    if v.get("encoding").and_then(Value::as_str) != Some("base64") {
389        bail!(
390            "`{file}` in {owner}/{name} is too large for GitHub to return inline; it was not \
391             written by the bootstrap — remove or rename it"
392        );
393    }
394    let compact: String = v
395        .get("content")
396        .and_then(Value::as_str)
397        .unwrap_or("")
398        .chars()
399        .filter(|c| !c.is_whitespace())
400        .collect();
401    let bytes = STANDARD
402        .decode(compact)
403        .with_context(|| format!("`{file}`: content is not base64"))?;
404    let sha = v
405        .get("sha")
406        .and_then(Value::as_str)
407        .ok_or_else(|| anyhow!("`{file}`: no blob sha"))?;
408    Ok(Some((sha.to_string(), bytes)))
409}
410
411fn write_file(
412    gh: &Gh,
413    owner: &str,
414    name: &str,
415    file: &str,
416    contents: &[u8],
417    message: &str,
418    dry_run: bool,
419) -> Result<Change> {
420    let existing = read_file(gh, owner, name, file)?;
421    let change = match &existing {
422        Some((_, current)) if current == contents => return Ok(Change::Unchanged),
423        Some(_) => Change::Update,
424        None => Change::Create,
425    };
426    if dry_run {
427        return Ok(change);
428    }
429    let mut body = json!({ "message": message, "content": STANDARD.encode(contents) });
430    if let Some((sha, _)) = &existing {
431        body["sha"] = json!(sha);
432    }
433    gh.send("PUT", &contents_path(owner, name, file), Some(&body))
434        .map_err(|e| {
435            e.context(format!(
436                "writing `{file}` — if the default branch is already protected, this file can \
437                 only change through a pull request (the ruleset has no bypass actors, by design)"
438            ))
439        })?;
440    Ok(change)
441}
442
443fn remove_file(
444    gh: &Gh,
445    owner: &str,
446    name: &str,
447    file: &str,
448    message: &str,
449    dry_run: bool,
450) -> Result<Change> {
451    let Some((sha, _)) = read_file(gh, owner, name, file)? else {
452        return Ok(Change::Unchanged);
453    };
454    if !dry_run {
455        let body = json!({ "message": message, "sha": sha });
456        gh.send("DELETE", &contents_path(owner, name, file), Some(&body))?;
457    }
458    Ok(Change::Remove)
459}
460
461/// The `CODEOWNERS` to write and where, as the adapter's owner-review step
462/// renders it: an existing file keeps its place and its own rules, the
463/// managed block last, naming each owner by the login their numeric id has
464/// now.
465fn codeowners(
466    gh: &Gh,
467    owner: &str,
468    name: &str,
469    paths: &[String],
470    owners: &[ForgeAccount],
471    community_rules: &[u8],
472) -> Result<(String, String)> {
473    let mut logins: Vec<String> = Vec::new();
474    for o in owners {
475        let v = gh
476            .get(&path(&["user", &o.id.to_string()]))?
477            .ok_or_else(|| anyhow!("GitHub account {} ({}) no longer exists", o.id, o.login))?;
478        let login = account(&v, &o.login)?.login;
479        if !logins.contains(&login) {
480            logins.push(login);
481        }
482    }
483    let mut found = None;
484    for loc in CODEOWNERS_LOCATIONS {
485        if let Some((_, bytes)) = read_file(gh, owner, name, loc)? {
486            let text = String::from_utf8(bytes).map_err(|_| anyhow!("`{loc}` is not UTF-8"))?;
487            found = Some((loc.to_string(), text));
488            break;
489        }
490    }
491    let (target, community) = match found {
492        Some(f) => f,
493        None => (
494            CODEOWNERS_PATH.to_string(),
495            String::from_utf8(community_rules.to_vec())
496                .map_err(|_| anyhow!("community CODEOWNERS is not UTF-8"))?,
497        ),
498    };
499    let mut managed = paths.to_vec();
500    if !target.starts_with(".github/") {
501        managed.push(format!("/{target}"));
502    }
503    Ok((
504        target.clone(),
505        render_codeowners(&community, &managed, &logins),
506    ))
507}
508
509/// Converge the managed ruleset to `spec`, the check pinned to GitHub
510/// Actions. Returns the change and the body GitHub is (or would be) sent.
511fn protect(
512    gh: &Gh,
513    owner: &str,
514    name: &str,
515    spec: &ProtectionSpec,
516    dry_run: bool,
517) -> Result<(Change, Value)> {
518    let actions_id = if spec.require_status_check {
519        let app = gh
520            .get("apps/github-actions")?
521            .ok_or_else(|| anyhow!("GitHub has no `github-actions` app on this host"))?;
522        Some(
523            app.get("id")
524                .and_then(Value::as_u64)
525                .ok_or_else(|| anyhow!("the GitHub Actions app has no id"))?,
526        )
527    } else {
528        None
529    };
530    let body = ruleset_body(spec, actions_id);
531    let list_path = format!(
532        "{}?includes_parents=false&per_page=100",
533        path(&["repos", owner, name, "rulesets"])
534    );
535    let list = gh.get(&list_path)?.unwrap_or(Value::Array(Vec::new()));
536    let existing = list
537        .as_array()
538        .into_iter()
539        .flatten()
540        .find(|r| r.get("name").and_then(Value::as_str) == Some(RULESET_NAME))
541        .and_then(|r| r.get("id").and_then(Value::as_u64));
542    match existing {
543        Some(rid) => {
544            let one = path(&["repos", owner, name, "rulesets", &rid.to_string()]);
545            let rs = gh
546                .get(&one)?
547                .ok_or_else(|| anyhow!("ruleset {rid} vanished while being read"))?;
548            if ruleset_satisfies(&rs, None, actions_id, spec)? {
549                return Ok((Change::Unchanged, body));
550            }
551            if !dry_run {
552                gh.send("PUT", &one, Some(&body))?;
553            }
554            Ok((Change::Update, body))
555        }
556        None => {
557            if !dry_run {
558                gh.send(
559                    "POST",
560                    &path(&["repos", owner, name, "rulesets"]),
561                    Some(&body),
562                )?;
563            }
564            Ok((Change::Create, body))
565        }
566    }
567}
568
569/// A one-line description of `guard` for the report. `personal`: the
570/// repository belongs to a user account rather than an organisation.
571pub fn describe(guard: &CheckGuard, personal: bool) -> String {
572    match guard {
573        CheckGuard::OwnerReview { owners } => format!(
574            "owner review — changes under .github/ need an approving review from one of {}",
575            owners
576                .iter()
577                .map(|o| format!("@{}", o.login))
578                .collect::<Vec<_>>()
579                .join(", ")
580        ),
581        CheckGuard::SoloOwner if personal => {
582            "solo owner — the ruleset requires the check; no review of workflow changes is \
583             required, so a collaborator with write access could edit the workflow in a pull \
584             request (add --code-owner <login> for a second owner)"
585                .into()
586        }
587        CheckGuard::SoloOwner => "solo owner (--solo) — the ruleset requires the check; no review \
588                                  of workflow changes is required, so any organisation member \
589                                  with write access could edit the workflow in the pull request \
590                                  it judges"
591            .into(),
592        other => format!("{other:?}"),
593    }
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599
600    #[test]
601    fn segments_cannot_become_placeholders_or_paths() {
602        assert_eq!(segment("{owner}"), "%7Bowner%7D");
603        assert_eq!(segment("a/b"), "a%2Fb");
604        assert_eq!(segment("widgets.rs"), "widgets.rs");
605        assert_eq!(
606            path(&["repos", "acme", "w", "contents", ".github", "CODEOWNERS"]),
607            "repos/acme/w/contents/.github/CODEOWNERS"
608        );
609    }
610
611    #[test]
612    fn include_output_is_split() {
613        let r = parse_include(b"HTTP/2.0 404 Not Found\r\nA: b\r\n\r\n{\"message\":\"Not Found\"}")
614            .unwrap();
615        assert_eq!(r.status, 404);
616        assert_eq!(r.message(), "Not Found");
617        let r = parse_include(b"HTTP/2.0 204 No Content\n\n").unwrap();
618        assert_eq!(r.status, 204);
619        assert_eq!(r.json().unwrap(), Value::Null);
620        assert!(
621            parse_include(b"gh: To get started with GitHub CLI, please run: gh auth login")
622                .is_none()
623        );
624    }
625
626    #[test]
627    fn the_body_goes_on_stdin_and_the_path_last() {
628        let argv = Gh::new("github.com").argv("PUT", "repos/a/b/contents/x", true);
629        assert_eq!(argv.last().unwrap(), "repos/a/b/contents/x");
630        let i = argv.iter().position(|a| a == "--input").unwrap();
631        assert_eq!(argv[i + 1], "-");
632        assert!(
633            !argv
634                .iter()
635                .any(|a| a.starts_with("-f") || a.starts_with("--raw-field"))
636        );
637    }
638}