1use std::path::Path;
6use std::process::Command;
7
8use anyhow::{Context, Result, anyhow, bail};
9use serde_json::Value;
10use vgi_forge::Resource;
11
12pub const VGI_REPO: &str = "OpenVTC/verifiable-git-infrastructure";
14pub const ACTION_PATH: &str = ".github/actions/verify-trust";
16pub const LINUX_ASSET: &str = "verify-trust-x86_64-unknown-linux-gnu.tar.gz";
18
19pub 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
37pub 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 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
61pub use vgi_core::registry_referral;
64
65pub 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 .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
117const MAX_TAG_DEPTH: usize = 5;
119
120fn 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
144pub 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
176pub 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
192pub 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 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 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}