Skip to main content

vgi_cli/
lib.rs

1//! `vgi`: VGI tools for the people who hold a repository.
2//!
3//! `vgi repo init` is the manual-mode half of the git-namespaces design
4//! (§7.3, §8): where no community bridge can act on a repository — a
5//! namespace bound in manual mode, or a personal account the community's
6//! App is not installed on — the account holder runs the bridge's own
7//! bootstrap plan themselves, with their own credentials. The plan, the
8//! files and the request bodies come from the adapters (`vgi-forge-github`,
9//! `vgi-forge-forgejo`), so what lands is byte-for-byte what the bridge
10//! would have written.
11//!
12//! It stops short of `git-ns/repo/adopt`: that is a Trust Task signed with a
13//! VTA session, which this tool does not hold. It prints the `cnm git
14//! adopt` command instead.
15
16pub mod cli;
17pub mod forgejo;
18pub mod github;
19pub mod inputs;
20pub mod report;
21pub mod shell;
22
23use std::io::Write;
24
25use anyhow::{Context, Result, bail};
26use vgi_forge::{RepoSpec, Resource, VgiConfig};
27use vgi_forge_github::plan::CheckGuard;
28
29use crate::cli::{Cli, Command, ForgeChoice, InitArgs, RepoCommand};
30use crate::report::Report;
31
32/// Run a parsed command line, writing the report to `out`.
33pub async fn run(cli: Cli, out: &mut dyn Write) -> Result<()> {
34    match cli.command {
35        Command::Repo(RepoCommand::Init(args)) => repo_init(args, out).await,
36    }
37}
38
39/// Which forge `resource` is on. `Auto` off github.com stays `Auto`, and is
40/// taken for Forgejo only once the instance answers the unauthenticated
41/// probe ([`forgejo::Client::connect`]).
42fn forge_for(choice: ForgeChoice, resource: &Resource) -> ForgeChoice {
43    match choice {
44        ForgeChoice::Auto if resource.host() == "github.com" => ForgeChoice::Github,
45        c => c,
46    }
47}
48
49/// The command the namespace admin (or the reservation's owner) runs next.
50pub fn adopt_command(resource: &Resource, owners: &[String]) -> String {
51    let mut argv = vec![
52        "cnm".to_string(),
53        "git".into(),
54        "adopt".into(),
55        resource.to_string(),
56    ];
57    if owners.is_empty() {
58        return format!("{} --owner <owner-did>", shell::command_line(&argv));
59    }
60    for o in owners {
61        argv.push("--owner".into());
62        argv.push(o.clone());
63    }
64    shell::command_line(&argv)
65}
66
67async fn repo_init(args: InitArgs, out: &mut dyn Write) -> Result<()> {
68    shell::check_did("--vtc", &args.vtc)?;
69    for o in &args.owners {
70        shell::check_did("--owner", o)?;
71    }
72    let resource = match &args.resource {
73        Some(r) => {
74            let r = Resource::parse_owner_repo(r)?;
75            r.require_owner_repo()?;
76            r
77        }
78        None => inputs::resource_from_origin(&std::env::current_dir()?)?,
79    };
80    let forge = forge_for(args.forge, &resource);
81    if forge != ForgeChoice::Github && (!args.code_owners.is_empty() || args.solo) {
82        bail!(
83            "--code-owner and --solo choose GitHub's owner-review guard; Forgejo protects the \
84             workflow paths instead"
85        );
86    }
87    let (registry, registry_from_referral) = match &args.registry {
88        Some(r) => (r.clone(), false),
89        None => (inputs::resolve_registry(&args.vtc).await?, true),
90    };
91    shell::check_did("--registry", &registry)?;
92    let (action, action_resolved) = match &args.verify_trust_action {
93        Some(a) => (a.clone(), false),
94        None => (
95            inputs::resolve_action(&args.verify_trust_version).await?,
96            true,
97        ),
98    };
99    let mut cfg = VgiConfig::new(
100        registry.clone(),
101        args.vtc.clone(),
102        action,
103        args.verify_trust_version.clone(),
104    );
105    cfg.required_check = args.required_check.clone();
106    cfg = cfg.with_verify_trust_transport(args.verify_trust_transport.into());
107
108    let owner = resource.owner().to_string();
109    let name = resource
110        .repo_name()
111        .expect("checked to be owner/repo")
112        .to_string();
113    let spec = RepoSpec::new(resource.clone());
114    let mut report = Report::new(out, args.dry_run);
115    report.line(format!(
116        "vgi repo init {resource}{}",
117        if args.dry_run {
118            " (dry run: nothing is changed)"
119        } else {
120            ""
121        }
122    ));
123    report.line(format!("  VTC       {}", args.vtc));
124    if registry_from_referral {
125        report.line(format!(
126            "  registry  {registry} (the TrustRegistry referral in the VTC's DID document; pass \
127             --registry to name one yourself)"
128        ));
129    } else {
130        report.line(format!("  registry  {registry}"));
131    }
132    if action_resolved {
133        report.line(format!(
134            "  action    {} (the commit {} named when this ran; trust on first use — pass \
135             --verify-trust-action to pin one you verified)",
136            cfg.verify_trust_action, cfg.verify_trust_version
137        ));
138    } else {
139        report.line(format!("  action    {}", cfg.verify_trust_action));
140    }
141    report.line(format!("  release   {}", cfg.verify_trust_version));
142
143    match forge {
144        ForgeChoice::Github => {
145            let keyring = match &args.platform_keyring {
146                Some(p) => std::fs::read(p)
147                    .with_context(|| format!("reading the platform keyring {}", p.display()))?,
148                None if resource.host() == "github.com" => {
149                    report.line("  keyring   web-flow key from https://github.com/web-flow.gpg");
150                    inputs::web_flow_key().await?
151                }
152                None => bail!(
153                    "on GitHub Enterprise Server pass --platform-keyring <file> (the instance's \
154                     web-flow key, <https://host>/web-flow.gpg)"
155                ),
156            };
157            cfg = cfg.with_platform_keyring(keyring);
158            let gh = github::Gh::new(resource.host());
159            let facts = github::repo_facts(&gh, &owner, &name)?;
160            let owners = github::owners(&gh, &facts, &args.code_owners, args.solo)?;
161            let guard = CheckGuard::for_owners(&owners);
162            let steps = github::plan(&spec, &cfg, &guard)?;
163            report.line(format!(
164                "  guard     {}",
165                github::describe(&guard, facts.personal)
166            ));
167            report.line("");
168            github::apply(&gh, &facts, &steps, &mut report)?;
169        }
170        ForgeChoice::Forgejo | ForgeChoice::Auto => {
171            let token = std::env::var(forgejo::TOKEN_ENV).map_err(|_| {
172                anyhow::anyhow!(
173                    "set {} to a token of yours with write:repository and read:user",
174                    forgejo::TOKEN_ENV
175                )
176            })?;
177            let base = forgejo::base_url(resource.host(), args.forgejo_url.as_ref())?;
178            // The token goes only to an instance that has answered, without
179            // it, as Forgejo or Gitea.
180            let (client, info) =
181                forgejo::Client::connect(&base, token, forge == ForgeChoice::Auto).await?;
182            let sha = match &args.verify_trust_sha256 {
183                Some(s) => s.to_ascii_lowercase(),
184                None => {
185                    let s = inputs::release_sha256(&args.verify_trust_version).await?;
186                    report.line(format!(
187                        "  sha256    {s} (published with {}; trust on first use — pass \
188                         --verify-trust-sha256 to pin one you verified)",
189                        args.verify_trust_version
190                    ));
191                    s
192                }
193            };
194            cfg = cfg.with_verify_trust_sha256(sha);
195            let steps = forgejo::plan(&spec, &cfg, &args.runs_on)?;
196            let me = forgejo::whoami(&client).await?;
197            report.line(format!("  instance  {base} ({}), as {me}", info.version));
198            report.line("");
199            forgejo::apply(&client, &owner, &name, &me, &info, &steps, &mut report).await?;
200        }
201    }
202
203    report.line("");
204    if report.dry_run() {
205        report.line(format!(
206            "{} change(s) would be made. Run again without --dry-run to make them.",
207            report.changes()
208        ));
209    } else if report.changes() == 0 {
210        report.line("Nothing to change: commit trust is already on.");
211    } else {
212        report.line(format!("{} change(s) made.", report.changes()));
213    }
214    report.line("");
215    report.line(
216        "Next, tell the VTC the repository exists. vgi cannot: git-ns/repo/adopt is a Trust \
217         Task signed with a VTA session, which this tool does not hold. A namespace admin (or \
218         the owner of the reservation `git-ns/repo/create` made) runs:",
219    );
220    report.line("");
221    report.line(format!("  {}", adopt_command(&resource, &args.owners)));
222    Ok(())
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn the_adopt_command_is_quoted() {
231        let r = Resource::parse("github.com/Acme/Widgets").unwrap();
232        assert_eq!(
233            adopt_command(
234                &r,
235                &[
236                    "did:web:a.example".into(),
237                    "did:webvh:Qm:b.example%3A80".into()
238                ]
239            ),
240            "cnm git adopt github.com/acme/widgets --owner did:web:a.example --owner \
241             did:webvh:Qm:b.example%3A80"
242        );
243        assert_eq!(
244            adopt_command(&r, &[]),
245            "cnm git adopt github.com/acme/widgets --owner <owner-did>"
246        );
247    }
248}