Skip to main content

vgi_cli/
inputs.rs

1//! The plan's inputs that `vgi repo init` finds for itself when they are
2//! not given: the repository, the registry, the pinned action and — for
3//! Forgejo — the release checksum and the web-flow key.
4
5use std::path::Path;
6use std::process::Command;
7
8use anyhow::{Context, Result, anyhow, bail};
9use serde_json::Value;
10use vgi_forge::Resource;
11
12/// Where the verify-trust action and its releases live.
13pub const VGI_REPO: &str = "OpenVTC/verifiable-git-infrastructure";
14/// The action's path inside [`VGI_REPO`].
15pub const ACTION_PATH: &str = ".github/actions/verify-trust";
16/// The release tarball a Forgejo runner (Linux x86-64) downloads.
17pub const LINUX_ASSET: &str = "verify-trust-x86_64-unknown-linux-gnu.tar.gz";
18
19/// The repository `origin` names in the clone at `dir`, as a resource.
20pub fn resource_from_origin(dir: &Path) -> Result<Resource> {
21    let out = Command::new("git")
22        .arg("-C")
23        .arg(dir)
24        .args(["remote", "get-url", "origin"])
25        .output()
26        .context("running git")?;
27    if !out.status.success() {
28        bail!(
29            "no --resource given and this is not a clone with an `origin` remote; pass \
30             --resource <host>/<owner>/<repo>"
31        );
32    }
33    let url = String::from_utf8(out.stdout).context("origin URL is not UTF-8")?;
34    resource_from_remote(url.trim())
35}
36
37/// `https://github.com/Acme/Widgets.git`, `git@github.com:Acme/Widgets.git`
38/// or `ssh://git@host:2222/acme/widgets` → `github.com/acme/widgets`.
39pub fn resource_from_remote(url: &str) -> Result<Resource> {
40    let unsupported =
41        || anyhow!("cannot read a repository from the remote URL `{url}`; pass --resource");
42    let (host, path) = if let Some(rest) = url.split_once("://").map(|(_, r)| r) {
43        let (authority, path) = rest.split_once('/').ok_or_else(unsupported)?;
44        let host = authority.rsplit('@').next().unwrap_or(authority);
45        let host = host.split(':').next().unwrap_or(host);
46        (host.to_string(), path.to_string())
47    } else if let Some((userhost, path)) = url.split_once(':') {
48        // scp-like: [user@]host:owner/repo
49        let host = userhost.rsplit('@').next().unwrap_or(userhost);
50        (host.to_string(), path.to_string())
51    } else {
52        return Err(unsupported());
53    };
54    let path = path.trim_end_matches('/');
55    let path = path.strip_suffix(".git").unwrap_or(path);
56    let r = Resource::parse_owner_repo(&format!("{host}/{path}"))?;
57    r.require_owner_repo()?;
58    Ok(r)
59}
60
61/// The registry DID a DID document refers to (shared with `vgi-bridge
62/// setup`, which reads the same referral).
63pub use vgi_core::registry_referral;
64
65/// Resolve `vtc_did` and take its `TrustRegistry` referral.
66pub async fn resolve_registry(vtc_did: &str) -> Result<String> {
67    let tdk = verify_trust::build_resolver(false).await?;
68    let resolved = tdk
69        .did_resolver()
70        .resolve(vtc_did)
71        .await
72        .map_err(|e| anyhow!("could not resolve the VTC DID {vtc_did}: {e}"))?;
73    let doc = serde_json::to_value(&resolved.doc).context("the VTC's DID document")?;
74    registry_referral(&doc).ok_or_else(|| {
75        anyhow!(
76            "the VTC's DID document names no TrustRegistry; pass --registry <did> (the \
77             community's Trust Registry DID)"
78        )
79    })
80}
81
82fn check_tag(tag: &str) -> Result<()> {
83    let ok = !tag.is_empty()
84        && tag
85            .bytes()
86            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'));
87    if !ok {
88        bail!("`{tag}` is not a release tag");
89    }
90    Ok(())
91}
92
93fn http() -> Result<reqwest::Client> {
94    reqwest::Client::builder()
95        .user_agent(concat!("vgi/", env!("CARGO_PKG_VERSION")))
96        .timeout(std::time::Duration::from_secs(30))
97        // Every URL here is https; a redirect must not downgrade it.
98        .https_only(true)
99        .build()
100        .context("HTTP client")
101}
102
103async fn fetch_text(url: &str, accept: &str) -> Result<String> {
104    let resp = http()?
105        .get(url)
106        .header("Accept", accept)
107        .send()
108        .await
109        .with_context(|| format!("fetching {url}"))?;
110    let status = resp.status();
111    if !status.is_success() {
112        bail!("fetching {url}: HTTP {status}");
113    }
114    resp.text().await.with_context(|| format!("reading {url}"))
115}
116
117/// Annotated tags followed before giving up (a tag of a tag of …).
118const MAX_TAG_DEPTH: usize = 5;
119
120/// The `object` a git ref or annotated tag points at: its type and sha.
121fn git_object(v: &Value) -> Result<(String, String)> {
122    let obj = v
123        .get("object")
124        .ok_or_else(|| anyhow!("no `object` in GitHub's reply"))?;
125    let kind = obj
126        .get("type")
127        .and_then(Value::as_str)
128        .ok_or_else(|| anyhow!("no object type in GitHub's reply"))?;
129    let sha = obj
130        .get("sha")
131        .and_then(Value::as_str)
132        .ok_or_else(|| anyhow!("no object sha in GitHub's reply"))?;
133    if sha.len() != 40 || !sha.bytes().all(|b| b.is_ascii_hexdigit()) {
134        bail!("`{sha}` is not a commit sha");
135    }
136    Ok((kind.to_string(), sha.to_ascii_lowercase()))
137}
138
139async fn fetch_json(url: &str) -> Result<Value> {
140    let text = fetch_text(url, "application/vnd.github+json").await?;
141    serde_json::from_str(&text).with_context(|| format!("{url} is not JSON"))
142}
143
144/// The action pinned to the commit `tag` names: the tag ref
145/// (`git/ref/tags/<tag>` — only a tag, never a branch of that name), with
146/// an annotated tag dereferenced to its commit.
147pub async fn resolve_action(tag: &str) -> Result<String> {
148    check_tag(tag)?;
149    let api = format!("https://api.github.com/repos/{VGI_REPO}/git");
150    let fail = |e: anyhow::Error| {
151        anyhow!("could not resolve the tag {tag} of {VGI_REPO} ({e:#}); pass --verify-trust-action")
152    };
153    let mut obj = git_object(
154        &fetch_json(&format!("{api}/ref/tags/{tag}"))
155            .await
156            .map_err(fail)?,
157    )
158    .map_err(fail)?;
159    for _ in 0..MAX_TAG_DEPTH {
160        if obj.0 != "tag" {
161            break;
162        }
163        obj = git_object(
164            &fetch_json(&format!("{api}/tags/{}", obj.1))
165                .await
166                .map_err(fail)?,
167        )
168        .map_err(fail)?;
169    }
170    match obj {
171        (kind, sha) if kind == "commit" => Ok(format!("{VGI_REPO}/{ACTION_PATH}@{sha}")),
172        (kind, _) => Err(fail(anyhow!("the tag names a {kind}, not a commit"))),
173    }
174}
175
176/// The SHA-256 the release publishes next to its Linux x86-64 tarball.
177pub async fn release_sha256(tag: &str) -> Result<String> {
178    check_tag(tag)?;
179    let url = format!("https://github.com/{VGI_REPO}/releases/download/{tag}/{LINUX_ASSET}.sha256");
180    let text = fetch_text(&url, "text/plain").await?;
181    let hex = text
182        .split_whitespace()
183        .next()
184        .unwrap_or("")
185        .to_ascii_lowercase();
186    if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
187        bail!("{url} is not a SHA-256; pass --verify-trust-sha256");
188    }
189    Ok(hex)
190}
191
192/// GitHub's `web-flow` key, from `https://github.com/web-flow.gpg`.
193pub async fn web_flow_key() -> Result<Vec<u8>> {
194    let text = fetch_text("https://github.com/web-flow.gpg", "*/*").await?;
195    Ok(text.into_bytes())
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    use serde_json::json;
202
203    #[test]
204    fn remotes_become_resources() {
205        for (url, want) in [
206            (
207                "https://github.com/Acme/Widgets.git",
208                "github.com/acme/widgets",
209            ),
210            ("https://github.com/acme/widgets", "github.com/acme/widgets"),
211            ("git@github.com:Acme/Widgets.git", "github.com/acme/widgets"),
212            (
213                "ssh://git@codeberg.org:2222/alice/tool.git",
214                "codeberg.org/alice/tool",
215            ),
216            (
217                "https://user:pw@git.example.org/team/repo/",
218                "git.example.org/team/repo",
219            ),
220        ] {
221            assert_eq!(resource_from_remote(url).unwrap().as_str(), want, "{url}");
222        }
223        for bad in ["/tmp/repo", "https://github.com/acme", "file:///x/y"] {
224            assert!(resource_from_remote(bad).is_err(), "{bad}");
225        }
226    }
227
228    #[test]
229    fn the_registry_referral_is_read_from_the_document() {
230        let doc = json!({
231            "id": "did:webvh:Qm:vtc.example",
232            "service": [
233                { "id": "#didcomm", "type": "DIDCommMessaging", "serviceEndpoint": "did:web:m" },
234                {
235                    "id": "did:webvh:Qm:vtc.example#trust-registry",
236                    "type": "TrustRegistry",
237                    "serviceEndpoint": {
238                        "uri": "did:webvh:QmReg:registry.example",
239                        "profile": "https://trustoverip.org/profiles/trqp/v2"
240                    }
241                }
242            ]
243        });
244        assert_eq!(
245            registry_referral(&doc).as_deref(),
246            Some("did:webvh:QmReg:registry.example")
247        );
248        // An https endpoint is a registry *serving* TRQP, not a referral.
249        let doc = json!({ "service": [
250            { "type": ["TRQPRest", "TrustRegistry"], "serviceEndpoint": "https://r.example" }
251        ]});
252        assert_eq!(registry_referral(&doc), None);
253        assert_eq!(registry_referral(&json!({})), None);
254    }
255
256    #[test]
257    fn git_objects_are_read_from_refs_and_annotated_tags() {
258        let sha = "0123456789ABCDEF0123456789abcdef01234567";
259        let r = json!({ "ref": "refs/tags/v1", "object": { "type": "tag", "sha": sha } });
260        assert_eq!(
261            git_object(&r).unwrap(),
262            ("tag".into(), sha.to_ascii_lowercase())
263        );
264        let t = json!({ "tag": "v1", "object": { "type": "commit", "sha": sha } });
265        assert_eq!(git_object(&t).unwrap().0, "commit");
266        assert!(git_object(&json!({ "object": { "type": "commit", "sha": "abc" } })).is_err());
267        // A list of refs (what `git/refs` answers) is not one ref.
268        assert!(git_object(&json!([{ "object": { "type": "commit", "sha": sha } }])).is_err());
269    }
270
271    #[test]
272    fn tags_are_checked_before_they_reach_a_url() {
273        assert!(check_tag("v0.4.14").is_ok());
274        for bad in ["", "v1/../x", "v1?x", "v 1"] {
275            assert!(check_tag(bad).is_err(), "{bad}");
276        }
277    }
278}