forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiBe587be7Tahinli11 hours ago323 commits

verify.rs527 lines, 18.9 KiBHistoryRawDownload
1//! Commit signature verification through `git verify-commit`. Parses git's output into a
2//! [`RawVerify`]. It does not decide ownership: forge-web matches the fingerprint to a user and
3//! checks the committer email.
4//!
5//! The commit object is read first, so an unsigned commit never runs `verify-commit`. Every
6//! commit id is checked as hex before it reaches git.
7
8use std::path::Path;
9
10use forge_core::store::signatures::SigKind;
11
12use crate::command::{GitCommand, GitEnv};
13use crate::error::{Error, Result};
14use crate::history::validate_oid;
15
16/// What git said about one commit's signature.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct RawVerify {
19 /// False when the commit has no signature header. Every other field is then empty.
20 pub signed: bool,
21 /// From the signature header: `Ssh` for an SSH signature, `Gpg` for a PGP one.
22 pub kind: Option<SigKind>,
23 /// git reported a good signature.
24 pub good: bool,
25 /// git reported a bad signature (`BADSIG`, or `Bad "git" signature`).
26 pub bad: bool,
27 /// The signing key is not known to git: `ERRSIG` or `NO_PUBKEY` for GPG, or `No principal
28 /// matched` for SSH.
29 pub missing_key: bool,
30 /// GPG: the primary key fingerprint, or the signing key's if git gave no primary. SSH: the
31 /// `SHA256:` fingerprint.
32 pub fingerprint: Option<String>,
33 /// SSH only: the allowed-signers principal that matched.
34 pub principal: Option<String>,
35}
36
37impl RawVerify {
38 fn unsigned() -> Self {
39 Self {
40 signed: false,
41 kind: None,
42 good: false,
43 bad: false,
44 missing_key: false,
45 fingerprint: None,
46 principal: None,
47 }
48 }
49}
50
51/// The raw commit object (`git cat-file commit <oid>`).
52async fn commit_object(env: &GitEnv, repo: &Path, oid: &str) -> Result<Vec<u8>> {
53 validate_oid(oid)?;
54 GitCommand::new(env, "cat-file")
55 .git_dir(repo)
56 .arg("commit")
57 .user_arg(oid)?
58 .output()
59 .await
60}
61
62/// `None` when the commit has no `gpgsig` header. `Some(kind)` when it has one, where the kind is
63/// read from the armor line (`None` if the armor is neither SSH nor PGP).
64fn signature_header(object: &[u8]) -> Option<Option<SigKind>> {
65 for line in object.split(|&b| b == b'\n') {
66 if line.is_empty() {
67 // End of headers.
68 break;
69 }
70 let value = line
71 .strip_prefix(b"gpgsig ")
72 .or_else(|| line.strip_prefix(b"gpgsig-sha256 "));
73 if let Some(value) = value {
74 return Some(if value.starts_with(b"-----BEGIN SSH SIGNATURE-----") {
75 Some(SigKind::Ssh)
76 } else if value.starts_with(b"-----BEGIN PGP SIGNATURE-----") {
77 Some(SigKind::Gpg)
78 } else {
79 None
80 });
81 }
82 }
83 None
84}
85
86/// The committer email of a commit, without the angle brackets.
87pub async fn committer_email(env: &GitEnv, repo: &Path, oid: &str) -> Result<String> {
88 let object = commit_object(env, repo, oid).await?;
89 for line in object.split(|&b| b == b'\n') {
90 if line.is_empty() {
91 break;
92 }
93 if let Some(who) = line.strip_prefix(b"committer ") {
94 let who = String::from_utf8_lossy(who);
95 let start = who.rfind('<');
96 let end = who.rfind('>');
97 return match (start, end) {
98 (Some(s), Some(e)) if s < e => Ok(who[s + 1..e].trim().to_string()),
99 _ => Err(Error::Failed(format!(
100 "commit {oid} has no committer email"
101 ))),
102 };
103 }
104 }
105 Err(Error::Failed(format!("commit {oid} has no committer line")))
106}
107
108/// Verifies the signature of `oid` in the repo at `repo` (a git dir). `allowed_signers` is the
109/// SSH allowed-signers file. `gnupg_home`, when given, is the keyring for GPG signatures.
110///
111/// A non-zero exit from `verify-commit` is normal for a bad or unknown signature. The output is
112/// parsed either way. Only a failure to start git is an error.
113pub async fn verify_commit(
114 env: &GitEnv,
115 repo: &Path,
116 oid: &str,
117 allowed_signers: &Path,
118 gnupg_home: Option<&Path>,
119) -> Result<RawVerify> {
120 let object = commit_object(env, repo, oid).await?;
121 let Some(kind) = signature_header(&object) else {
122 return Ok(RawVerify::unsigned());
123 };
124 let allowed = allowed_signers
125 .to_str()
126 .ok_or_else(|| Error::InvalidInput("allowed signers path is not UTF-8".into()))?;
127 let mut cmd = GitCommand::new(env, "verify-commit")
128 .git_dir(repo)
129 .config_checked(format!("gpg.ssh.allowedSignersFile={allowed}"))?
130 .arg("--raw")
131 .user_revs(&[oid])?;
132 if let Some(home) = gnupg_home {
133 cmd = cmd.env("GNUPGHOME", home.as_os_str());
134 }
135 let out = cmd.into_tokio().output().await?;
136 let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
137 text.push('\n');
138 text.push_str(&String::from_utf8_lossy(&out.stderr));
139 Ok(parse_output(&text, kind))
140}
141
142/// Reads git's verification output. GPG status lines have the `[GNUPG:]` prefix. SSH results
143/// are the `Good "git" signature` / `Bad "git" signature` sentences.
144fn parse_output(text: &str, kind: Option<SigKind>) -> RawVerify {
145 let mut raw = RawVerify {
146 signed: true,
147 kind,
148 ..RawVerify::unsigned()
149 };
150 for line in text.lines() {
151 let line = line.trim();
152 if let Some(status) = line.strip_prefix("[GNUPG:] ") {
153 let mut parts = status.split_whitespace();
154 match parts.next() {
155 Some("VALIDSIG") => {
156 // VALIDSIG <fpr> <date> <ts> <exp> <ver> <res> <pk> <hash> <class> [<primary>]
157 let fields: Vec<&str> = parts.collect();
158 let fpr = fields.get(9).or_else(|| fields.first());
159 if let Some(fpr) = fpr {
160 raw.fingerprint = Some((*fpr).to_string());
161 }
162 }
163 Some("GOODSIG") => raw.good = true,
164 Some("BADSIG") => raw.bad = true,
165 Some("ERRSIG") | Some("NO_PUBKEY") => raw.missing_key = true,
166 _ => {}
167 }
168 } else if line.starts_with("No principal matched") {
169 raw.missing_key = true;
170 } else if let Some(rest) = line.strip_prefix("Good \"git\" signature") {
171 apply_ssh_sentence(&mut raw, rest);
172 // Without a principal the key matched no allowed signer. git still calls the
173 // signature good, but nobody vouches for the key, so it counts as an unknown key.
174 if raw.principal.is_some() {
175 raw.good = true;
176 } else {
177 raw.missing_key = true;
178 }
179 } else if let Some(rest) = line.strip_prefix("Bad \"git\" signature") {
180 raw.bad = true;
181 apply_ssh_sentence(&mut raw, rest);
182 }
183 }
184 raw
185}
186
187/// `rest` is what follows `Good "git" signature`: either ` for <principal> with <type> key
188/// SHA256:<fp>` or ` with <type> key SHA256:<fp>`.
189fn apply_ssh_sentence(raw: &mut RawVerify, rest: &str) {
190 if let Some(idx) = rest.strip_prefix(" for ").and_then(|s| s.find(" with ")) {
191 let after_for = &rest[" for ".len()..];
192 raw.principal = Some(after_for[..idx].to_string());
193 }
194 if let Some(idx) = rest.find("SHA256:") {
195 let token = rest[idx..].split_whitespace().next().unwrap_or_default();
196 raw.fingerprint = Some(token.to_string());
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203 use std::process::Command;
204
205 /// A git invocation for test setup only, with no user or system config.
206 fn git(home: &Path, dir: &Path, args: &[&str]) -> String {
207 let out = Command::new("git")
208 .arg("-C")
209 .arg(dir)
210 .args(args)
211 .env_clear()
212 .env("PATH", "/usr/local/bin:/usr/bin:/bin")
213 .env("HOME", home)
214 .env("GIT_CONFIG_NOSYSTEM", "1")
215 .env("GIT_CONFIG_GLOBAL", home.join("gitconfig"))
216 .output()
217 .expect("run git");
218 assert!(
219 out.status.success(),
220 "git {args:?} failed: {}",
221 String::from_utf8_lossy(&out.stderr)
222 );
223 String::from_utf8_lossy(&out.stdout).trim().to_string()
224 }
225
226 fn env_for(home: &Path) -> GitEnv {
227 GitEnv {
228 git_bin: "/usr/bin/git".into(),
229 data_dir: home.to_path_buf(),
230 }
231 }
232
233 /// Makes a repo with one unsigned commit by `email`, and returns (work dir, git dir).
234 fn repo_with_base(home: &Path, email: &str) -> (std::path::PathBuf, std::path::PathBuf) {
235 let work = home.join("work");
236 std::fs::create_dir_all(&work).unwrap();
237 git(home, &work, &["init", "-q", "-b", "main"]);
238 git(home, &work, &["config", "user.name", "Test"]);
239 git(home, &work, &["config", "user.email", email]);
240 std::fs::write(work.join("a.txt"), "a\n").unwrap();
241 git(home, &work, &["add", "a.txt"]);
242 git(
243 home,
244 &work,
245 &["commit", "-q", "--no-gpg-sign", "-m", "base"],
246 );
247 let git_dir = work.join(".git");
248 (work, git_dir)
249 }
250
251 fn ssh_keygen(home: &Path, name: &str, email: &str) -> std::path::PathBuf {
252 let key = home.join(name);
253 let status = Command::new("ssh-keygen")
254 .args(["-q", "-t", "ed25519", "-N", "", "-C", email, "-f"])
255 .arg(&key)
256 .status()
257 .expect("run ssh-keygen");
258 assert!(status.success());
259 key
260 }
261
262 /// `allowed_signers` line for `email` from a `.pub` file.
263 fn allowed_line(pub_path: &Path, email: &str) -> String {
264 let text = std::fs::read_to_string(pub_path).unwrap();
265 let mut fields = text.split_whitespace();
266 let algo = fields.next().unwrap();
267 let blob = fields.next().unwrap();
268 format!("{email} namespaces=\"git\" {algo} {blob}\n")
269 }
270
271 /// The SHA256 fingerprint of a `.pub` file, as `ssh-keygen -lf` prints it.
272 fn ssh_fingerprint(pub_path: &Path) -> String {
273 let out = Command::new("ssh-keygen")
274 .arg("-lf")
275 .arg(pub_path)
276 .output()
277 .unwrap();
278 let text = String::from_utf8_lossy(&out.stdout).into_owned();
279 text.split_whitespace().nth(1).unwrap().to_string()
280 }
281
282 fn signed_commit(home: &Path, work: &Path, key_pub: &Path, email: &str) {
283 std::fs::write(work.join("b.txt"), email).unwrap();
284 git(home, work, &["add", "b.txt"]);
285 git(
286 home,
287 work,
288 &[
289 "-c",
290 "gpg.format=ssh",
291 "-c",
292 &format!("user.signingkey={}", key_pub.display()),
293 "-c",
294 "commit.gpgsign=true",
295 "-c",
296 &format!("user.email={email}"),
297 "commit",
298 "-q",
299 "-m",
300 "signed",
301 ],
302 );
303 }
304
305 #[tokio::test]
306 async fn ssh_good_signature_is_parsed() {
307 let home = tempfile::tempdir().unwrap();
308 let home = home.path();
309 let email = "tahinli@example.com";
310 ssh_keygen(home, "tahinli", email);
311 let pub_path = home.join("tahinli.pub");
312 let (work, git_dir) = repo_with_base(home, email);
313 signed_commit(home, &work, &pub_path, email);
314 let oid = git(home, &work, &["rev-parse", "HEAD"]);
315 let signers = home.join("allowed_signers");
316 std::fs::write(&signers, allowed_line(&pub_path, email)).unwrap();
317
318 let raw = verify_commit(&env_for(home), &git_dir, &oid, &signers, None)
319 .await
320 .unwrap();
321 assert!(raw.signed);
322 assert_eq!(raw.kind, Some(SigKind::Ssh));
323 assert!(raw.good, "{raw:?}");
324 assert!(!raw.bad && !raw.missing_key);
325 assert_eq!(raw.principal.as_deref(), Some(email));
326 assert_eq!(raw.fingerprint, Some(ssh_fingerprint(&pub_path)));
327 assert_eq!(
328 committer_email(&env_for(home), &git_dir, &oid)
329 .await
330 .unwrap(),
331 email
332 );
333 }
334
335 #[tokio::test]
336 async fn ssh_signer_not_in_allowed_signers_is_missing_key() {
337 let home = tempfile::tempdir().unwrap();
338 let home = home.path();
339 let email = "tahinli@example.com";
340 ssh_keygen(home, "tahinli", email);
341 let pub_path = home.join("tahinli.pub");
342 let (work, git_dir) = repo_with_base(home, email);
343 signed_commit(home, &work, &pub_path, email);
344 let oid = git(home, &work, &["rev-parse", "HEAD"]);
345 let signers = home.join("allowed_signers");
346 std::fs::write(&signers, "").unwrap();
347
348 let raw = verify_commit(&env_for(home), &git_dir, &oid, &signers, None)
349 .await
350 .unwrap();
351 assert!(raw.signed);
352 assert!(!raw.good);
353 assert!(raw.missing_key, "{raw:?}");
354 }
355
356 #[tokio::test]
357 async fn unsigned_commit_is_reported_without_verify() {
358 let home = tempfile::tempdir().unwrap();
359 let home = home.path();
360 let email = "tahinli@example.com";
361 let (work, git_dir) = repo_with_base(home, email);
362 let oid = git(home, &work, &["rev-parse", "HEAD"]);
363 // The signers file does not exist. An unsigned commit must not reach verify-commit.
364 let signers = home.join("does-not-exist");
365
366 let raw = verify_commit(&env_for(home), &git_dir, &oid, &signers, None)
367 .await
368 .unwrap();
369 assert_eq!(raw, RawVerify::unsigned());
370 }
371
372 #[tokio::test]
373 async fn bad_oid_is_rejected_before_git() {
374 let home = tempfile::tempdir().unwrap();
375 let env = env_for(home.path());
376 let err = verify_commit(
377 &env,
378 home.path(),
379 "--output=x",
380 &home.path().join("s"),
381 None,
382 )
383 .await;
384 assert!(matches!(err, Err(Error::InvalidInput(_))));
385 }
386
387 #[test]
388 fn parses_gpg_status_lines() {
389 let text = "[GNUPG:] NEWSIG\n[GNUPG:] VALIDSIG AAAA 2026-01-01 1 0 4 0 1 10 00 PRIMARY\n[GNUPG:] GOODSIG 1 Tahinli\n";
390 let raw = parse_output(text, Some(SigKind::Gpg));
391 assert!(raw.good && !raw.bad && !raw.missing_key);
392 assert_eq!(raw.fingerprint.as_deref(), Some("PRIMARY"));
393
394 let raw = parse_output("[GNUPG:] NO_PUBKEY 1\n", Some(SigKind::Gpg));
395 assert!(raw.missing_key && !raw.good);
396
397 let raw = parse_output("[GNUPG:] BADSIG 1 Tahinli\n", Some(SigKind::Gpg));
398 assert!(raw.bad && !raw.good);
399 }
400
401 #[test]
402 fn parses_ssh_sentences() {
403 let text =
404 "Good \"git\" signature for tahinli@example.com with ED25519 key SHA256:abc+def\n";
405 let raw = parse_output(text, Some(SigKind::Ssh));
406 assert!(raw.good);
407 assert_eq!(raw.principal.as_deref(), Some("tahinli@example.com"));
408 assert_eq!(raw.fingerprint.as_deref(), Some("SHA256:abc+def"));
409
410 let raw = parse_output(
411 "Good \"git\" signature with ED25519 key SHA256:xyz\n",
412 Some(SigKind::Ssh),
413 );
414 assert!(!raw.good && raw.missing_key);
415 assert_eq!(raw.principal, None);
416 assert_eq!(raw.fingerprint.as_deref(), Some("SHA256:xyz"));
417 }
418
419 #[test]
420 fn signature_header_kinds() {
421 let ssh = b"tree x\nauthor a\ncommitter a <a@x> 1 +0000\ngpgsig -----BEGIN SSH SIGNATURE-----\n y\n\nmsg";
422 assert_eq!(signature_header(ssh), Some(Some(SigKind::Ssh)));
423 let pgp = b"tree x\ngpgsig-sha256 -----BEGIN PGP SIGNATURE-----\n\nmsg";
424 assert_eq!(signature_header(pgp), Some(Some(SigKind::Gpg)));
425 let none = b"tree x\ncommitter a <a@x> 1 +0000\n\ngpgsig in body";
426 assert_eq!(signature_header(none), None);
427 }
428
429 /// GPG round trip. Skipped when `gpg` is not installed.
430 #[tokio::test]
431 async fn gpg_good_signature_is_parsed() {
432 if Command::new("gpg").arg("--version").output().is_err() {
433 eprintln!("skipping gpg test: gpg is not installed");
434 return;
435 }
436 let home = tempfile::tempdir().unwrap();
437 let home = home.path();
438 let gnupg = home.join("gnupg");
439 std::fs::create_dir_all(&gnupg).unwrap();
440 std::fs::set_permissions(&gnupg, std::os::unix::fs::PermissionsExt::from_mode(0o700))
441 .unwrap();
442 let email = "tahinli@example.com";
443 let generated = Command::new("gpg")
444 .env("GNUPGHOME", &gnupg)
445 .args([
446 "--batch",
447 "--passphrase",
448 "",
449 "--quick-gen-key",
450 email,
451 "default",
452 "default",
453 "never",
454 ])
455 .output()
456 .unwrap();
457 assert!(
458 generated.status.success(),
459 "{}",
460 String::from_utf8_lossy(&generated.stderr)
461 );
462 let listing = Command::new("gpg")
463 .env("GNUPGHOME", &gnupg)
464 .args(["--batch", "--with-colons", "--list-keys", email])
465 .output()
466 .unwrap();
467 let listing = String::from_utf8_lossy(&listing.stdout).into_owned();
468 let primary = listing
469 .lines()
470 .find(|l| l.starts_with("fpr:"))
471 .and_then(|l| l.split(':').nth(9))
472 .unwrap()
473 .to_string();
474
475 let (work, git_dir) = repo_with_base(home, email);
476 std::fs::write(work.join("b.txt"), "b").unwrap();
477 git(home, &work, &["add", "b.txt"]);
478 let commit = Command::new("git")
479 .arg("-C")
480 .arg(&work)
481 .args([
482 "-c",
483 &format!("user.signingkey={primary}"),
484 "-c",
485 "commit.gpgsign=true",
486 "-c",
487 &format!("user.email={email}"),
488 "commit",
489 "-q",
490 "-m",
491 "gpg signed",
492 ])
493 .env_clear()
494 .env("PATH", "/usr/local/bin:/usr/bin:/bin")
495 .env("HOME", home)
496 .env("GNUPGHOME", &gnupg)
497 .env("GIT_CONFIG_NOSYSTEM", "1")
498 .env("GIT_CONFIG_GLOBAL", home.join("gitconfig"))
499 .output()
500 .unwrap();
501 assert!(
502 commit.status.success(),
503 "{}",
504 String::from_utf8_lossy(&commit.stderr)
505 );
506 let oid = git(home, &work, &["rev-parse", "HEAD"]);
507 let signers = home.join("unused");
508
509 let raw = verify_commit(
510 &env_for(home),
511 &git_dir,
512 &oid,
513 &signers,
514 Some(gnupg.as_path()),
515 )
516 .await
517 .unwrap();
518 // Stop the agent that gpg started for this keyring.
519 let _ = Command::new("gpgconf")
520 .env("GNUPGHOME", &gnupg)
521 .args(["--kill", "gpg-agent"])
522 .output();
523 assert_eq!(raw.kind, Some(SigKind::Gpg));
524 assert!(raw.good, "{raw:?}");
525 assert_eq!(raw.fingerprint.as_deref(), Some(primary.as_str()));
526 }
527}