Skip to main content

vgi_core/
commit.rs

1//! Git commit-object handling for signature verification.
2//!
3//! Git signs the commit object with its `gpgsig` header removed;
4//! [`split_signed_commit`] reconstructs the exact signed bytes and recovers the
5//! armored signature. [`normalize_sshsig_armor`] re-wraps an sshsig body to the
6//! 70-column width strict PEM parsers require. [`committer_did`] reads the
7//! signer identity a commit claims on its `committer` header.
8//!
9//! [`signer_did`] prefers the claim in the commit message's `Signed-by-DID:`
10//! trailer. That trailer block is located with git's own rules, ported from
11//! `find_trailer_block_start` in git's `trailer.c`, so that the DID which gets
12//! verified is the one `git log --format='%(trailers:…)'`, `git
13//! interpret-trailers --parse` and git-based review UIs show. The port is held
14//! to real git by `tests/trailer_differential.rs`.
15
16use anyhow::{Context, Result, bail};
17
18/// Re-wrap an sshsig armor's base64 body at 70 columns.
19///
20/// OpenSSH's own base64 reader accepts any line width, but the strict PEM
21/// parser underneath `SshSig::from_pem` requires exactly the 70-column
22/// wrapping ssh-keygen emits. Signatures created by did-git-sign before it
23/// matched ssh-keygen's width (76 columns) live on in git history, so the
24/// armor is normalized rather than trusted to be canonical.
25pub fn normalize_sshsig_armor(pem: &str) -> String {
26    let body: String = pem
27        .lines()
28        .filter(|line| !line.starts_with("-----"))
29        .map(str::trim)
30        .collect();
31    let mut normalized = String::from("-----BEGIN SSH SIGNATURE-----\n");
32    for chunk in body.as_bytes().chunks(70) {
33        // Chunks of an ASCII base64 string are always valid UTF-8.
34        normalized.push_str(&String::from_utf8_lossy(chunk));
35        normalized.push('\n');
36    }
37    normalized.push_str("-----END SSH SIGNATURE-----\n");
38    normalized
39}
40
41/// Split a raw commit object into (payload-as-signed, armored signature).
42///
43/// Git signs the commit object with the `gpgsig` header removed; the header's
44/// value spans continuation lines (each prefixed with one space). Returns
45/// `Ok(None)` for an unsigned commit.
46///
47/// Every *other* header whose name starts with `gpgsig` (`gpgsig-sha256`, or a
48/// made-up `gpgsig-foo`) is removed too, continuation lines and all, because
49/// git removes it: that is the "other signature" arm of
50/// `parse_buffer_signed_by_header` in git's `commit.c`. Keeping such a header
51/// made this payload a superset of git's, so anyone could add one to a
52/// validly signed commit — fsck-clean, still GOOD to git — and have it
53/// reported here as a bad signature by its real signer.
54pub fn split_signed_commit(raw: &[u8]) -> Result<Option<(Vec<u8>, String)>> {
55    #[derive(PartialEq)]
56    enum Header {
57        Signature,
58        OtherSignature,
59        Kept,
60    }
61
62    let text = std::str::from_utf8(raw).context("commit object is not UTF-8")?;
63    let Some((headers, body)) = text.split_once("\n\n") else {
64        bail!("malformed commit object: no header/body separator");
65    };
66
67    let mut kept_headers: Vec<&str> = Vec::new();
68    let mut signature_lines: Vec<&str> = Vec::new();
69    let mut current = Header::Kept;
70    for line in headers.split('\n') {
71        // Same order as git: a continuation line belongs to the header before
72        // it, and is tested before any header name.
73        if current == Header::Signature
74            && let Some(continuation) = line.strip_prefix(' ')
75        {
76            signature_lines.push(continuation);
77        } else if let Some(first) = line.strip_prefix("gpgsig ") {
78            current = Header::Signature;
79            signature_lines.push(first);
80        } else if line.starts_with("gpgsig")
81            || (current == Header::OtherSignature && line.starts_with(' '))
82        {
83            current = Header::OtherSignature;
84        } else {
85            current = Header::Kept;
86            kept_headers.push(line);
87        }
88    }
89
90    if signature_lines.is_empty() {
91        return Ok(None);
92    }
93
94    let mut payload = kept_headers.join("\n").into_bytes();
95    payload.extend_from_slice(b"\n\n");
96    payload.extend_from_slice(body.as_bytes());
97
98    let mut pem = signature_lines.join("\n");
99    pem.push('\n');
100    Ok(Some((payload, pem)))
101}
102
103/// The committer identity: the `<…>` field of the `committer` header.
104///
105/// Read from the header block only, so a body line that happens to begin with
106/// `committer ` cannot be mistaken for the header. Returns `None` for a commit
107/// with no committer header or no angle-bracketed identity.
108#[must_use]
109pub fn committer_identity(commit: &[u8]) -> Option<String> {
110    let text = std::str::from_utf8(commit).ok()?;
111    let headers = text.split_once("\n\n").map_or(text, |(headers, _)| headers);
112    let line = headers
113        .split('\n')
114        .find_map(|line| line.strip_prefix("committer "))?;
115    // `rfind` so a display name containing '<' cannot truncate the identity.
116    let open = line.rfind('<')?;
117    let close = line[open..].find('>')? + open;
118    Some(line[open + 1..close].to_string())
119}
120
121/// The signer DID a commit claims: its committer identity when that is a DID,
122/// reduced to the bare DID.
123///
124/// `did-git-sign` sets `user.email` to the verification-method id it signs
125/// with (`did:webvh:…#key-0`); the fragment names *which* key, while the DID
126/// is the identity to resolve and to ask the registry about, so any
127/// fragment, path or query is stripped.
128///
129/// This is a **claim**, not an authenticated fact — the committer header is
130/// author-controlled text. It is safe to use only as a lookup hint whose
131/// answer is then checked: the DID must publish the key that actually signed,
132/// and the signature must verify over a payload that includes this very
133/// header. A commit claiming a DID it cannot sign for fails both checks.
134#[must_use]
135pub fn committer_did(commit: &[u8]) -> Option<String> {
136    let identity = committer_identity(commit)?;
137    if !identity.starts_with("did:") {
138        return None;
139    }
140    let did = claimed_did(&identity);
141    if did.is_empty() {
142        return None;
143    }
144    Some(did.to_string())
145}
146
147/// The DID a signer claim names, keeping the one query a verifier needs to
148/// resolve it: a `did:scid` identity's `?src=` locator. The fragment (which
149/// key) and any other path or query are stripped. A did:scid claimed without
150/// its locator can only be resolved where its source is already known, so the
151/// locator stays in the claim, and identities are compared with
152/// [`same_signer`].
153fn claimed_did(value: &str) -> &str {
154    let reference = value.split('#').next().unwrap_or(value);
155    if affinidi_did_common::scid::scid_src(reference).is_some() {
156        return reference;
157    }
158    value.split(['#', '?', '/']).next().unwrap_or(value)
159}
160
161/// Whether two signer DIDs name the same identity: equal, or the same
162/// `did:scid` with or without its `?src=` locator (VTI-KEY-160). A did:scid
163/// and the did:webvh of its log are different signers (VTI-KEY-164).
164#[must_use]
165pub fn same_signer(a: &str, b: &str) -> bool {
166    affinidi_did_common::scid::same_reference(a, b)
167}
168
169/// The identity a signer DID names: a `did:scid` without its `?src=`
170/// locator, anything else unchanged. What to ask a registry about.
171#[must_use]
172pub fn signer_identity(did: &str) -> String {
173    let did = did.split('#').next().unwrap_or(did);
174    affinidi_did_common::scid::strip_scid_src(did).into_owned()
175}
176
177/// The signer DID a commit claims, checking the `Signed-by-DID:` trailer
178/// first, then falling back to the committer email for legacy commits.
179///
180/// The trailer is the canonical location for new commits (it lets
181/// `user.email` be a normal email for git-host attribution). Old commits
182/// that carried the DID in the committer email still verify via the
183/// fallback.
184#[must_use]
185pub fn signer_did(commit: &[u8]) -> Option<String> {
186    trailer_did(commit).or_else(|| committer_did(commit))
187}
188
189/// Return both explicit identity claims when the final `Signed-by-DID:`
190/// trailer and legacy DID committer identity disagree.
191#[must_use]
192pub fn conflicting_signer_dids(commit: &[u8]) -> Option<(String, String)> {
193    let trailer = trailer_did(commit)?;
194    let committer = committer_did(commit)?;
195    (!same_signer(&trailer, &committer)).then_some((trailer, committer))
196}
197
198/// The trailer key that carries the signer DID.
199const SIGNER_DID_KEY: &str = "Signed-by-DID";
200
201/// Git's default comment prefix (`core.commentChar`).
202///
203/// This code reads no git configuration, so a repository that sets a
204/// different comment character can have git see a trailer block where this
205/// does not. That direction only loses a DID claim, and a lost claim fails
206/// closed.
207const COMMENT_PREFIX: char = '#';
208
209/// The prefixes git treats as its own generated trailers
210/// (`git_generated_prefixes` in git's `trailer.c`).
211///
212/// A line starting with one of these counts as a trailer line *and* unlocks
213/// the 25%-non-trailer allowance in [`trailer_block_start`], whether or not
214/// the line has a separator — which is why `(cherry picked from commit …)`,
215/// with no `:` in it at all, can turn a mixed paragraph into a trailer block.
216const GIT_GENERATED_PREFIXES: [&str; 2] = ["Signed-off-by: ", "(cherry picked from commit "];
217
218/// Extract a bare DID from the `Signed-by-DID:` trailer of the commit
219/// message's trailer block.
220///
221/// The trailer block is located with git's own rules rather than an
222/// approximation of them, because the risk here is a *display* differential:
223/// a reviewer reads the DID that `git log --format='%(trailers:…)'`, `git
224/// interpret-trailers --parse` and every git-based UI report, so the DID that
225/// verify-trust checks has to be that same one. Where the two disagree the
226/// commit either claims a DID no reviewer is shown, or shows a DID nobody
227/// checked. `crates/vgi-core/tests/trailer_differential.rs` holds git to this
228/// by running both git commands over generated messages.
229///
230/// The claim is the *last* `Signed-by-DID` trailer git reports, and it is a
231/// claim only when that trailer's value is a DID. An earlier trailer is never
232/// promoted when a later one is not a DID: the last trailer is what a reader
233/// scanning to the bottom of the block sees, so preferring an earlier one
234/// would hide the checked DID behind it.
235fn trailer_did(commit: &[u8]) -> Option<String> {
236    let text = std::str::from_utf8(commit).ok()?;
237    let (_, message) = text.split_once("\n\n")?;
238    let value = last_trailer_value(message, SIGNER_DID_KEY)?;
239    let value = value.trim_ascii();
240    if !value.starts_with("did:") {
241        return None;
242    }
243    // The fragment names which key signed; the DID is the identity to resolve
244    // and to ask the registry about.
245    Some(claimed_did(value).to_string())
246}
247
248/// The value of the last trailer named `key` in `message`'s trailer block,
249/// unfolded as git unfolds a continuation line.
250///
251/// Mirrors git's `trailer_block_get`: the block is split into entries, a line
252/// whose first character is whitespace continues the entry before it (but
253/// only when that entry had a separator), and every other line starts a new
254/// entry. Key matching is case-insensitive, as it is for git's
255/// `%(trailers:key=…)`.
256fn last_trailer_value(message: &str, key: &str) -> Option<String> {
257    let mut lines: Vec<&str> = message.split('\n').collect();
258    // A message ending in a newline has no empty final line in git's view.
259    if lines.last().is_some_and(|line| line.is_empty()) {
260        lines.pop();
261    }
262    // git presents a commit's message from its subject onward: pretty.c's
263    // `parse_commit_message` runs `skip_blank_lines` before recording where the
264    // subject starts, and `%(trailers:…)` reads from there. So blank lines at
265    // the very start of a message are not part of it. Keeping them would make
266    // the subject look like a second paragraph, and turn a trailer-shaped
267    // subject line — which `git log` and GitHub both display as the subject —
268    // into a trailer nobody is shown.
269    let before_subject = lines.iter().take_while(|line| is_blank(line)).count();
270    let lines = &lines[before_subject..];
271
272    let start = trailer_block_start(lines)?;
273
274    let mut value: Option<String> = None;
275    // Whether an entry is open for continuation lines, and whether that entry
276    // is the one being looked for. A line without a separator (a comment or a
277    // non-trailer line inside the block) opens nothing, so a continuation
278    // after it is not folded into the trailer before it.
279    let mut open: Option<bool> = None;
280    for line in &lines[start..] {
281        if open.is_some() && line.starts_with(|c: char| c.is_ascii_whitespace()) {
282            if open == Some(true)
283                && let Some(value) = value.as_mut()
284            {
285                // Keep the raw text, newline and all: git concatenates the
286                // continuation onto the value and unfolds once, at the end.
287                value.push('\n');
288                value.push_str(line);
289            }
290            continue;
291        }
292        match separator_pos(line) {
293            Some(position) => {
294                let matched = line[..position].trim_ascii().eq_ignore_ascii_case(key);
295                if matched {
296                    value = Some(line[position + 1..].to_string());
297                }
298                open = Some(matched);
299            }
300            None => open = None,
301        }
302    }
303    // git trims the assembled value, then unfolds it.
304    value.map(|value| unfold(value.trim_ascii()))
305}
306
307/// Collapse every newline and the whitespace that follows it down to a single
308/// space, as git's `unfold_value` does, then trim.
309///
310/// Whitespace *before* a newline is left alone, so a trailer value with
311/// trailing spaces and a continuation line under it keeps those spaces and
312/// gains one more for the fold — which is the text git reports, and is why the
313/// value cannot be trimmed line by line as it is assembled.
314fn unfold(value: &str) -> String {
315    let mut unfolded = String::with_capacity(value.len());
316    let mut rest = value;
317    while let Some(newline) = rest.find('\n') {
318        unfolded.push_str(&rest[..newline]);
319        unfolded.push(' ');
320        rest = rest[newline + 1..].trim_ascii_start();
321    }
322    unfolded.push_str(rest);
323    unfolded.trim_ascii().to_string()
324}
325
326/// The index of the first line of the message's trailer block, following
327/// git's `find_trailer_block_start` (`trailer.c`). `None` when git would see
328/// no trailer block at all.
329///
330/// Only the final paragraph can be a trailer block, it cannot be the title
331/// paragraph, and it qualifies when either every line in it is a trailer, or
332/// it holds one of git's own generated trailers and is at least 25% trailer
333/// lines.
334fn trailer_block_start(lines: &[&str]) -> Option<usize> {
335    // The first paragraph is the title and cannot hold trailers, so the scan
336    // below stops at the blank line ending it. With no blank line anywhere
337    // the message is all title, and so has no trailer block.
338    let end_of_title = lines
339        .iter()
340        .position(|line| !line.starts_with(COMMENT_PREFIX) && is_blank(line))?;
341
342    let mut recognized_prefix = false;
343    let mut trailer_lines = 0_usize;
344    let mut non_trailer_lines = 0_usize;
345    // Lines that are continuations if a trailer turns up above them, and
346    // non-trailers if a non-trailer does.
347    let mut possible_continuation_lines = 0_usize;
348    let mut only_spaces = true;
349
350    for index in (end_of_title..lines.len()).rev() {
351        let line = lines[index];
352        if line.starts_with(COMMENT_PREFIX) {
353            non_trailer_lines += possible_continuation_lines;
354            possible_continuation_lines = 0;
355            continue;
356        }
357        if is_blank(line) {
358            if only_spaces {
359                continue;
360            }
361            non_trailer_lines += possible_continuation_lines;
362            if recognized_prefix && trailer_lines * 3 >= non_trailer_lines {
363                return Some(index + 1);
364            }
365            if trailer_lines > 0 && non_trailer_lines == 0 {
366                return Some(index + 1);
367            }
368            return None;
369        }
370        only_spaces = false;
371
372        if GIT_GENERATED_PREFIXES
373            .iter()
374            .any(|prefix| line.starts_with(prefix))
375        {
376            trailer_lines += 1;
377            possible_continuation_lines = 0;
378            recognized_prefix = true;
379        } else if separator_pos(line).is_some() {
380            trailer_lines += 1;
381            possible_continuation_lines = 0;
382            // git also sets `recognized_prefix` here for a key named in
383            // `trailer.<token>.key` configuration. This reads no git config,
384            // so only git's own prefixes above unlock the 25% allowance; a
385            // repository that configures more of them can have git see a
386            // block this does not, which loses a claim and fails closed.
387        } else if line.starts_with(|c: char| c.is_ascii_whitespace()) {
388            possible_continuation_lines += 1;
389        } else {
390            non_trailer_lines += 1 + possible_continuation_lines;
391            possible_continuation_lines = 0;
392        }
393    }
394    None
395}
396
397/// The offset of the `:` that ends a trailer key, following git's
398/// `find_separator` for its default separator set.
399///
400/// The key is alphanumerics and `-`, optionally followed by spaces or tabs
401/// before the colon, and the colon may not be the first character. A line
402/// starting with whitespace never has one, which is what makes it a
403/// continuation line rather than a trailer.
404fn separator_pos(line: &str) -> Option<usize> {
405    let mut whitespace_found = false;
406    for (offset, c) in line.char_indices() {
407        if c == ':' {
408            return (offset >= 1).then_some(offset);
409        }
410        if !whitespace_found && (c.is_ascii_alphanumeric() || c == '-') {
411            continue;
412        }
413        if offset != 0 && (c == ' ' || c == '\t') {
414            whitespace_found = true;
415            continue;
416        }
417        return None;
418    }
419    None
420}
421
422/// Whether a line is blank in git's sense: empty, or only whitespace.
423fn is_blank(line: &str) -> bool {
424    line.trim_ascii().is_empty()
425}
426
427#[cfg(test)]
428mod tests {
429    #![allow(clippy::unwrap_used)]
430
431    use super::*;
432
433    fn commit_with_committer(committer: &str) -> String {
434        format!(
435            "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
436             author A U Thor <a@example.com> 1700000000 +0000\n\
437             committer {committer} 1700000000 +0000\n\
438             \n\
439             a message\n"
440        )
441    }
442
443    #[test]
444    fn a_did_committer_yields_the_bare_did() {
445        let commit = commit_with_committer("Alice <did:webvh:QmAbc:example.com#key-0>");
446        assert_eq!(
447            committer_did(commit.as_bytes()).unwrap(),
448            "did:webvh:QmAbc:example.com",
449            "the fragment names the key, not the identity the registry knows"
450        );
451    }
452
453    #[test]
454    fn a_did_without_a_fragment_survives_intact() {
455        let commit = commit_with_committer("Alice <did:webvh:QmAbc:example.com>");
456        assert_eq!(
457            committer_did(commit.as_bytes()).unwrap(),
458            "did:webvh:QmAbc:example.com"
459        );
460    }
461
462    #[test]
463    fn a_plain_email_committer_claims_no_did() {
464        let commit = commit_with_committer("Alice <alice@example.com>");
465        assert!(committer_did(commit.as_bytes()).is_none());
466        assert_eq!(
467            committer_identity(commit.as_bytes()).unwrap(),
468            "alice@example.com",
469            "the identity is still reported, so the failure can name it"
470        );
471    }
472
473    #[test]
474    fn a_body_line_cannot_impersonate_the_committer_header() {
475        // The header block ends at the first blank line; everything after it
476        // is the message, where an author controls every byte.
477        let commit = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
478             author A U Thor <a@example.com> 1700000000 +0000\n\
479             committer A U Thor <alice@example.com> 1700000000 +0000\n\
480             \n\
481             committer Evil <did:webvh:QmEvil:attacker.example> 1700000000 +0000\n";
482        assert!(
483            committer_did(commit.as_bytes()).is_none(),
484            "a DID in the message body must not be read as the committer"
485        );
486    }
487
488    #[test]
489    fn a_display_name_containing_an_angle_bracket_does_not_truncate() {
490        let commit = commit_with_committer("A <script> Thor <did:webvh:QmAbc:example.com#key-1>");
491        assert_eq!(
492            committer_did(commit.as_bytes()).unwrap(),
493            "did:webvh:QmAbc:example.com"
494        );
495    }
496
497    #[test]
498    fn a_signed_commits_payload_still_exposes_the_committer() {
499        // The committer header is a kept header, so it survives the gpgsig
500        // strip and is covered by the signature.
501        let commit = commit_with_committer("Alice <did:webvh:QmAbc:example.com#key-0>");
502        let (headers, body) = commit.split_once("\n\n").unwrap();
503        let signed = format!(
504            "{headers}\ngpgsig -----BEGIN SSH SIGNATURE-----\n \
505             AAAA\n -----END SSH SIGNATURE-----\n\n{body}"
506        );
507        let (payload, _) = split_signed_commit(signed.as_bytes()).unwrap().unwrap();
508        assert_eq!(
509            committer_did(&payload).unwrap(),
510            "did:webvh:QmAbc:example.com"
511        );
512    }
513
514    /// A signed commit with `extra` header lines inserted before or after the
515    /// `gpgsig` block, and the payload git signed (no `extra`, no `gpgsig`).
516    fn signed_with_extra_headers(extra: &str, after_signature: bool) -> (String, String) {
517        let head = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
518             author A U Thor <a@example.com> 1700000000 +0000\n\
519             committer A U Thor <a@example.com> 1700000000 +0000";
520        let signature = "gpgsig -----BEGIN SSH SIGNATURE-----\n AAAA\n -----END SSH SIGNATURE-----";
521        let headers = if after_signature {
522            format!("{head}\n{signature}\n{extra}")
523        } else {
524            format!("{head}\n{extra}\n{signature}")
525        };
526        (
527            format!("{headers}\n\na message\n"),
528            format!("{head}\n\na message\n"),
529        )
530    }
531
532    #[test]
533    fn other_gpgsig_headers_are_removed_from_the_payload_like_git() {
534        // Each of these is dropped by git's `parse_buffer_signed_by_header`
535        // (checked against git 2.50 with `git verify-commit`), so each must be
536        // dropped here or a signature git calls good is reported bad.
537        for extra in [
538            "gpgsig-sha256 -----BEGIN PGP SIGNATURE-----\n AAAA\n -----END PGP SIGNATURE-----",
539            "gpgsig-sha256 ",
540            "gpgsigx junk",
541            "gpgsig-foo bar",
542            "gpgsig",
543        ] {
544            for after_signature in [false, true] {
545                let (commit, expected) = signed_with_extra_headers(extra, after_signature);
546                let (payload, pem) = split_signed_commit(commit.as_bytes()).unwrap().unwrap();
547                assert_eq!(
548                    String::from_utf8(payload).unwrap(),
549                    expected,
550                    "{extra:?} (after the signature: {after_signature})"
551                );
552                assert_eq!(
553                    pem, "-----BEGIN SSH SIGNATURE-----\nAAAA\n-----END SSH SIGNATURE-----\n",
554                    "the other header must not leak into the signature"
555                );
556            }
557        }
558    }
559
560    #[test]
561    fn a_header_that_merely_contains_gpgsig_is_kept() {
562        // git keeps every header not *starting* with `gpgsig`, so these stay
563        // in the signed payload.
564        let (commit, _) = signed_with_extra_headers("x-gpgsig junk", false);
565        let (payload, _) = split_signed_commit(commit.as_bytes()).unwrap().unwrap();
566        assert!(
567            String::from_utf8(payload)
568                .unwrap()
569                .contains("\nx-gpgsig junk\n")
570        );
571    }
572
573    #[test]
574    fn a_header_after_another_signature_is_kept() {
575        // The other signature's continuation lines go with it; the next real
576        // header does not.
577        let (commit, expected) =
578            signed_with_extra_headers("gpgsig-sha256 first\n second\nencoding UTF-8", true);
579        let (payload, _) = split_signed_commit(commit.as_bytes()).unwrap().unwrap();
580        let expected = expected.replace("\n\na message", "\nencoding UTF-8\n\na message");
581        assert_eq!(String::from_utf8(payload).unwrap(), expected);
582    }
583
584    #[test]
585    fn a_commit_signed_only_by_another_header_is_unsigned() {
586        // A SHA-1 repository's signature is `gpgsig`; with none, there is
587        // nothing to verify, whatever other signature headers exist.
588        let commit = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
589             committer A U Thor <a@example.com> 1700000000 +0000\n\
590             gpgsig-sha256 -----BEGIN SSH SIGNATURE-----\n AAAA\n\
591             \n\
592             a message\n";
593        assert!(split_signed_commit(commit.as_bytes()).unwrap().is_none());
594    }
595
596    fn commit_with_trailer(committer: &str, trailer: &str) -> String {
597        format!(
598            "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
599             author A U Thor <a@example.com> 1700000000 +0000\n\
600             committer {committer} 1700000000 +0000\n\
601             \n\
602             a message\n\
603             \n\
604             {trailer}\n"
605        )
606    }
607
608    #[test]
609    fn a_did_scid_claim_keeps_its_src_locator() {
610        let commit = commit_with_trailer(
611            "Alice <alice@example.com>",
612            "Signed-by-DID: did:scid:vh:1:QmScid?src=dids.example.org/alice#key-0",
613        );
614        assert_eq!(
615            signer_did(commit.as_bytes()).unwrap(),
616            "did:scid:vh:1:QmScid?src=dids.example.org/alice"
617        );
618        // Any other query is still stripped, did:scid or not.
619        for (claim, did) in [
620            (
621                "did:scid:vh:1:QmScid?versionId=2#key-0",
622                "did:scid:vh:1:QmScid",
623            ),
624            (
625                "did:scid:vh:1:QmScid?src=a.example&x=1#key-0",
626                "did:scid:vh:1:QmScid",
627            ),
628            (
629                "did:webvh:Qm:a.example?versionId=2#key-0",
630                "did:webvh:Qm:a.example",
631            ),
632        ] {
633            let commit = commit_with_trailer(
634                "Alice <alice@example.com>",
635                &format!("Signed-by-DID: {claim}"),
636            );
637            assert_eq!(signer_did(commit.as_bytes()).unwrap(), did, "{claim}");
638        }
639    }
640
641    #[test]
642    fn a_did_scid_trailer_and_committer_agree_with_and_without_src() {
643        let commit = commit_with_trailer(
644            "Alice <did:scid:vh:1:QmScid#key-0>",
645            "Signed-by-DID: did:scid:vh:1:QmScid?src=dids.example.org#key-0",
646        );
647        assert_eq!(conflicting_signer_dids(commit.as_bytes()), None);
648        // The did:webvh of the same log is a different signer.
649        let commit = commit_with_trailer(
650            "Alice <did:webvh:QmScid:dids.example.org#key-0>",
651            "Signed-by-DID: did:scid:vh:1:QmScid?src=dids.example.org#key-0",
652        );
653        assert!(conflicting_signer_dids(commit.as_bytes()).is_some());
654    }
655
656    #[test]
657    fn signer_identity_drops_only_a_did_scid_src() {
658        assert_eq!(
659            signer_identity("did:scid:vh:1:QmScid?src=a.example#key-0"),
660            "did:scid:vh:1:QmScid"
661        );
662        assert_eq!(
663            signer_identity("did:webvh:Qm:a.example"),
664            "did:webvh:Qm:a.example"
665        );
666        assert!(same_signer(
667            "did:scid:vh:1:QmScid?src=a.example",
668            "did:scid:vh:1:QmScid"
669        ));
670    }
671
672    #[test]
673    fn signer_did_prefers_trailer_over_committer() {
674        let commit = commit_with_trailer(
675            "Alice <did:webvh:QmOld:old.example#key-0>",
676            "Signed-by-DID: did:webvh:QmNew:new.example#key-0",
677        );
678        assert_eq!(
679            signer_did(commit.as_bytes()).unwrap(),
680            "did:webvh:QmNew:new.example",
681            "trailer must take precedence over committer email"
682        );
683    }
684
685    #[test]
686    fn signer_did_falls_back_to_committer_for_legacy_commits() {
687        let commit = commit_with_committer("Alice <did:webvh:QmAbc:example.com#key-0>");
688        assert_eq!(
689            signer_did(commit.as_bytes()).unwrap(),
690            "did:webvh:QmAbc:example.com",
691            "legacy commits with DID in committer email must still work"
692        );
693    }
694
695    #[test]
696    fn signer_did_reads_trailer_with_normal_email_committer() {
697        let commit = commit_with_trailer(
698            "Alice <alice@example.com>",
699            "Signed-by-DID: did:webvh:QmAbc:example.com#key-0",
700        );
701        assert_eq!(
702            signer_did(commit.as_bytes()).unwrap(),
703            "did:webvh:QmAbc:example.com",
704        );
705    }
706
707    #[test]
708    fn signer_did_returns_none_without_did_anywhere() {
709        let commit = commit_with_committer("Alice <alice@example.com>");
710        assert!(signer_did(commit.as_bytes()).is_none());
711    }
712
713    #[test]
714    fn trailer_strips_fragment() {
715        let commit = commit_with_trailer(
716            "Alice <alice@example.com>",
717            "Signed-by-DID: did:webvh:QmAbc:example.com#key-1",
718        );
719        assert_eq!(
720            signer_did(commit.as_bytes()).unwrap(),
721            "did:webvh:QmAbc:example.com",
722        );
723    }
724
725    #[test]
726    fn trailer_ignores_non_did_values() {
727        let commit = commit_with_trailer("Alice <alice@example.com>", "Signed-by-DID: not-a-did");
728        assert!(signer_did(commit.as_bytes()).is_none());
729    }
730
731    #[test]
732    fn signer_did_ignores_body_line_outside_final_trailer_block() {
733        let commit = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
734             author A U Thor <a@example.com> 1700000000 +0000\n\
735             committer Alice <alice@example.com> 1700000000 +0000\n\
736             \n\
737             This line only discusses a trailer.\n\
738             Signed-by-DID: did:webvh:QmBody:example.com#key-0\n\
739             \n\
740             final prose, not a trailer block\n";
741        assert!(signer_did(commit.as_bytes()).is_none());
742    }
743
744    #[test]
745    fn signer_did_reads_final_trailer_block_only() {
746        let commit = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
747             author A U Thor <a@example.com> 1700000000 +0000\n\
748             committer Alice <alice@example.com> 1700000000 +0000\n\
749             \n\
750             Signed-by-DID: did:webvh:QmBody:ignored.example#key-0\n\
751             \n\
752             body text\n\
753             \n\
754             Signed-off-by: Alice <alice@example.com>\n\
755             Signed-by-DID: did:webvh:QmTrailer:example.com#key-0\n";
756        assert_eq!(
757            signer_did(commit.as_bytes()).unwrap(),
758            "did:webvh:QmTrailer:example.com"
759        );
760    }
761
762    #[test]
763    fn conflicting_signer_dids_reports_trailer_and_committer_disagreement() {
764        let commit = commit_with_trailer(
765            "Alice <did:webvh:QmCommitter:example.com#key-0>",
766            "Signed-by-DID: did:webvh:QmTrailer:example.com#key-0",
767        );
768        assert_eq!(
769            conflicting_signer_dids(commit.as_bytes()).unwrap(),
770            (
771                "did:webvh:QmTrailer:example.com".to_string(),
772                "did:webvh:QmCommitter:example.com".to_string(),
773            )
774        );
775    }
776
777    // Git's trailer-block rules, as fast assertions that do not need `git` on
778    // PATH. Every one of them is also checked against real git, over
779    // generated messages, by `tests/trailer_differential.rs`.
780
781    /// A commit whose committer is a plain email, so a DID claim can only come
782    /// from the trailer.
783    fn commit_with_body(body: &str) -> String {
784        format!(
785            "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
786             author A U Thor <a@example.com> 1700000000 +0000\n\
787             committer Alice <alice@example.com> 1700000000 +0000\n\
788             \n\
789             {body}"
790        )
791    }
792
793    const DID: &str = "did:webvh:QmA:example.com";
794
795    #[test]
796    fn a_trailer_in_a_mixed_paragraph_is_not_a_claim() {
797        // git accepts the final paragraph as trailers only when every line is
798        // a trailer, or when one of git's own trailers is in it. A
799        // `Signed-by-DID` line appended to a prose paragraph is not a trailer
800        // to git, so it must not be a claim here: it would be a DID that no
801        // reviewer's tooling shows as one.
802        let commit = commit_with_body(&format!(
803            "subject\n\nprose about the change\nSigned-by-DID: {DID}\n"
804        ));
805        assert!(trailer_did(commit.as_bytes()).is_none());
806    }
807
808    #[test]
809    fn a_trailer_in_the_title_paragraph_is_not_a_claim() {
810        // The first paragraph is the title, and git never reads trailers from
811        // it — not when it is the whole message, and not when the trailer is
812        // the line under the subject with no blank line between.
813        let commit = commit_with_body(&format!("Signed-by-DID: {DID}\n"));
814        assert!(trailer_did(commit.as_bytes()).is_none());
815        let commit = commit_with_body(&format!("subject\nSigned-by-DID: {DID}\n"));
816        assert!(trailer_did(commit.as_bytes()).is_none());
817    }
818
819    #[test]
820    fn whitespace_before_the_colon_still_names_the_trailer() {
821        // git's key scan allows spaces and tabs between the key and the
822        // colon, and trims them, so these are all the same trailer to it.
823        for gap in ["", " ", "  ", "\t", " \t"] {
824            let commit = commit_with_body(&format!("subject\n\nSigned-by-DID{gap}: {DID}#key-0\n"));
825            assert_eq!(
826                trailer_did(commit.as_bytes()).as_deref(),
827                Some(DID),
828                "gap {gap:?} must not hide the claim"
829            );
830        }
831    }
832
833    #[test]
834    fn the_trailer_key_is_matched_case_insensitively() {
835        // As `%(trailers:key=…)` matches it.
836        for key in [
837            "Signed-by-DID",
838            "signed-by-did",
839            "SIGNED-BY-DID",
840            "Signed-By-Did",
841        ] {
842            let commit = commit_with_body(&format!("subject\n\n{key}: {DID}#key-0\n"));
843            assert_eq!(
844                trailer_did(commit.as_bytes()).as_deref(),
845                Some(DID),
846                "key {key:?} must be recognized"
847            );
848        }
849    }
850
851    #[test]
852    fn a_folded_trailer_value_is_unfolded_like_git() {
853        // git folds a continuation line into the value with a single space and
854        // displays it that way. The result is not a resolvable DID, so the
855        // commit fails closed — but it fails on the same text git shows,
856        // rather than on a truncated prefix of it.
857        let commit = commit_with_body(&format!("subject\n\nSigned-by-DID: {DID}\n  and more\n"));
858        assert_eq!(
859            trailer_did(commit.as_bytes()).as_deref(),
860            Some("did:webvh:QmA:example.com and more")
861        );
862        // Only the whitespace *after* the newline collapses. The three spaces
863        // before it are part of the value, so git reports them and the fold's
864        // single space — four in all. Trimming the first line as it is read
865        // would report one.
866        let commit = commit_with_body(&format!("subject\n\nSigned-by-DID: {DID}   \n continued\n"));
867        assert_eq!(
868            trailer_did(commit.as_bytes()).as_deref(),
869            Some("did:webvh:QmA:example.com    continued")
870        );
871    }
872
873    #[test]
874    fn a_git_generated_trailer_unlocks_the_25_percent_allowance() {
875        // With a `Signed-off-by:` in the block, git tolerates non-trailer
876        // lines while trailers are at least a quarter of it…
877        let commit = commit_with_body(&format!(
878            "subject\n\nn1\nn2\nn3\nSigned-off-by: A U Thor <a@example.com>\nSigned-by-DID: {DID}\n"
879        ));
880        assert_eq!(trailer_did(commit.as_bytes()).as_deref(), Some(DID));
881        // …and past that boundary sees no trailer block at all.
882        let commit = commit_with_body(&format!(
883            "subject\n\nn1\nn2\nn3\nn4\nn5\nn6\nn7\n\
884             Signed-off-by: A U Thor <a@example.com>\nSigned-by-DID: {DID}\n"
885        ));
886        assert!(trailer_did(commit.as_bytes()).is_none());
887    }
888
889    #[test]
890    fn a_cherry_pick_line_unlocks_the_allowance_without_a_separator() {
891        // `(cherry picked from commit …)` holds no colon, so it is not a
892        // trailer line by the separator rule, yet git counts it as one of its
893        // own and lets the block through.
894        let commit = commit_with_body(&format!(
895            "subject\n\nprose\n\
896             (cherry picked from commit 0123456789abcdef0123456789abcdef01234567)\n\
897             Signed-by-DID: {DID}\n"
898        ));
899        assert_eq!(trailer_did(commit.as_bytes()).as_deref(), Some(DID));
900    }
901
902    #[test]
903    fn a_line_whose_colon_comes_first_defeats_the_block() {
904        // A separator at offset 0 is not a trailer to git, so the paragraph is
905        // neither all trailers nor git-generated, and holds no claim.
906        let commit = commit_with_body(&format!(
907            "subject\n\n: did:webvh:QmEvil:attacker.example\nSigned-by-DID: {DID}\n"
908        ));
909        assert!(trailer_did(commit.as_bytes()).is_none());
910    }
911
912    #[test]
913    fn the_last_trailer_wins_even_when_its_value_is_not_a_did() {
914        // git reports both trailers, and the last one is what a reader
915        // scanning to the bottom of the block sees, so an earlier DID is not
916        // promoted over it.
917        let commit = commit_with_body(
918            "subject\n\nSigned-by-DID: did:webvh:QmFirst:example.com\nSigned-by-DID: see below\n",
919        );
920        assert!(trailer_did(commit.as_bytes()).is_none());
921    }
922
923    #[test]
924    fn blank_lines_before_the_subject_are_skipped_like_git() {
925        // git shows a commit's message from its subject onward, skipping blank
926        // lines before it. So in each of these the `Signed-by-DID` line *is*
927        // the subject, with no trailer block under it, and reading a claim
928        // here would verify a DID that `git log` and GitHub display as the
929        // commit's subject line.
930        for prefix in ["\n", "   \n", "\t\n", "\n\n"] {
931            let commit = commit_with_body(&format!("{prefix}Signed-by-DID: {DID}\n"));
932            assert!(
933                trailer_did(commit.as_bytes()).is_none(),
934                "with prefix {prefix:?} the trailer line is the subject git shows"
935            );
936        }
937        // The skip must not cost a real trailer block further down.
938        let commit = commit_with_body(&format!("\nsubject\n\nSigned-by-DID: {DID}\n"));
939        assert_eq!(trailer_did(commit.as_bytes()).as_deref(), Some(DID));
940    }
941
942    #[test]
943    fn comment_lines_do_not_count_against_the_block() {
944        // git skips them when deciding what the block is.
945        let commit = commit_with_body(&format!("subject\n\n# a comment\nSigned-by-DID: {DID}\n"));
946        assert_eq!(trailer_did(commit.as_bytes()).as_deref(), Some(DID));
947    }
948}