Skip to main content

grit_lib/
signing.rs

1//! Commit/tag GPG (and gpgsm/ssh) signing and signature verification.
2//!
3//! This is a port of the parts of Git's `gpg-interface.c` and `commit.c`
4//! signature handling that the grit CLI needs:
5//!
6//! * read `gpg.format`, `gpg.<fmt>.program` / `gpg.program`, `user.signingkey`
7//!   and `gpg.minTrustLevel`,
8//! * resolve the signing program (handling a leading `~`, absolute paths, and
9//!   bare names looked up on `$PATH`),
10//! * [`sign_buffer`] — spawn `<program> --status-fd=2 -bsau <key>` and capture
11//!   the armored detached signature,
12//! * [`add_header_signature`] — splice a `gpgsig` header into a serialized
13//!   commit object (Git `commit.c:add_header_signature`),
14//! * [`extract_signed_payload`] / [`verify_commit`] — strip the `gpgsig` header
15//!   to rebuild the signed payload and run `<program> --verify` over it,
16//!   parsing the `[GNUPG:]` status lines into a [`SignatureCheck`].
17//!
18//! OpenPGP, X.509 (`gpgsm`), and SSH (`ssh-keygen -Y sign`) commit signing are
19//! supported when porcelain commit creation honors `commit.gpgsign`.
20
21use std::ffi::OsString;
22use std::io::Write;
23use std::path::{Path, PathBuf};
24use std::sync::Arc;
25
26use crate::command_runner::{
27    system_command_runner, CommandEnvironment, CommandOutput, CommandRunner, CommandSpec,
28    CommandStdin, CommandStdio,
29};
30use crate::config::ConfigSet;
31use crate::error::{ConfigError, Error, Result};
32use crate::porcelain::commit_error::CommitError;
33
34fn program_display(path: &std::path::Path) -> String {
35    path.to_string_lossy().into_owned()
36}
37
38fn commit_signing_io_failure(program: &std::path::Path, source: std::io::Error) -> CommitError {
39    CommitError::signing_failure(program_display(program), None, source.to_string())
40}
41
42fn commit_signing_process_failure(
43    program: &std::path::Path,
44    status: crate::command_runner::CommandExit,
45    stderr: impl Into<String>,
46) -> CommitError {
47    CommitError::signing_failure(program_display(program), status.code, stderr.into())
48}
49use crate::objects::HashAlgo;
50
51/// The hash header label for a sha1 repository.
52pub const GPG_SIG_HEADER_SHA1: &str = "gpgsig";
53/// The hash header label for a sha256 repository.
54pub const GPG_SIG_HEADER_SHA256: &str = "gpgsig-sha256";
55
56/// Signature trust level, as reported for a verified signature.
57///
58/// The numeric ordering matters: `gpg.minTrustLevel` comparisons use it.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
60pub enum TrustLevel {
61    #[default]
62    /// `Undefined = 0` variant.
63    Undefined = 0,
64    /// `Never = 1` variant.
65    Never = 1,
66    /// `Marginal = 2` variant.
67    Marginal = 2,
68    /// `Fully = 3` variant.
69    Fully = 3,
70    /// `Ultimate = 4` variant.
71    Ultimate = 4,
72}
73
74impl TrustLevel {
75    /// The `%GT` display string (`undefined`, `never`, ...).
76    pub fn display_key(self) -> &'static str {
77        match self {
78            TrustLevel::Undefined => "undefined",
79            TrustLevel::Never => "never",
80            TrustLevel::Marginal => "marginal",
81            TrustLevel::Fully => "fully",
82            TrustLevel::Ultimate => "ultimate",
83        }
84    }
85
86    /// Parse an uppercase GNUPG `TRUST_<LEVEL>` suffix.
87    fn from_status(level: &str) -> Option<TrustLevel> {
88        match level {
89            "UNDEFINED" => Some(TrustLevel::Undefined),
90            "NEVER" => Some(TrustLevel::Never),
91            "MARGINAL" => Some(TrustLevel::Marginal),
92            "FULLY" => Some(TrustLevel::Fully),
93            "ULTIMATE" => Some(TrustLevel::Ultimate),
94            _ => None,
95        }
96    }
97
98    /// Parse a configured `gpg.minTrustLevel` value (case-insensitive).
99    pub fn from_config(value: &str) -> Option<TrustLevel> {
100        TrustLevel::from_status(&value.to_ascii_uppercase())
101    }
102}
103
104/// The signature format selected via `gpg.format`.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum GpgFormat {
107    /// `OpenPgp` variant.
108    OpenPgp,
109    /// `X509` variant.
110    X509,
111    /// `Ssh` variant.
112    Ssh,
113}
114
115impl GpgFormat {
116    /// Resolve a `gpg.format` value case-sensitively (Git `get_format_by_name`).
117    ///
118    /// `openpgp` is valid; `OpEnPgP` is not (matches subtest 24).
119    pub fn from_name(name: &str) -> Option<GpgFormat> {
120        match name {
121            "openpgp" => Some(GpgFormat::OpenPgp),
122            "x509" => Some(GpgFormat::X509),
123            "ssh" => Some(GpgFormat::Ssh),
124            _ => None,
125        }
126    }
127
128    /// The format name used in `gpg.<fmt>.program`.
129    fn name(self) -> &'static str {
130        match self {
131            GpgFormat::OpenPgp => "openpgp",
132            GpgFormat::X509 => "x509",
133            GpgFormat::Ssh => "ssh",
134        }
135    }
136
137    /// Default program for this format.
138    fn default_program(self) -> &'static str {
139        match self {
140            GpgFormat::OpenPgp => "gpg",
141            GpgFormat::X509 => "gpgsm",
142            GpgFormat::Ssh => "ssh-keygen",
143        }
144    }
145
146    /// Detect the format from a signature's armor header
147    /// (Git `gpg-interface.c:get_format_by_sig`). Returns `None` for an
148    /// unrecognized signature.
149    pub fn from_signature(sig: &[u8]) -> Option<GpgFormat> {
150        const OPENPGP: &[&[u8]] = &[
151            b"-----BEGIN PGP SIGNATURE-----",
152            b"-----BEGIN PGP MESSAGE-----",
153        ];
154        const X509: &[&[u8]] = &[b"-----BEGIN SIGNED MESSAGE-----"];
155        const SSH: &[&[u8]] = &[b"-----BEGIN SSH SIGNATURE-----"];
156        for prefix in OPENPGP {
157            if sig.starts_with(prefix) {
158                return Some(GpgFormat::OpenPgp);
159            }
160        }
161        for prefix in X509 {
162            if sig.starts_with(prefix) {
163                return Some(GpgFormat::X509);
164            }
165        }
166        for prefix in SSH {
167            if sig.starts_with(prefix) {
168                return Some(GpgFormat::Ssh);
169            }
170        }
171        None
172    }
173
174    /// Extra arguments passed before `--verify` for this format.
175    fn verify_args(self) -> &'static [&'static str] {
176        match self {
177            GpgFormat::OpenPgp => &["--keyid-format=long"],
178            GpgFormat::X509 => &["--keyid-format=long"],
179            GpgFormat::Ssh => &[],
180        }
181    }
182}
183
184/// Resolved signing/verification configuration.
185#[derive(Clone)]
186pub struct GpgConfig {
187    /// The selected format.
188    pub format: GpgFormat,
189    /// The resolved program command for [`Self::format`] (used for signing; may
190    /// be a bare name to look up on `$PATH`).
191    pub program: String,
192    /// `gpg.program` (the format-agnostic fallback), if set.
193    pub generic_program: Option<String>,
194    /// `gpg.openpgp.program`, if set.
195    pub openpgp_program: Option<String>,
196    /// `gpg.x509.program`, if set.
197    pub x509_program: Option<String>,
198    /// `gpg.ssh.program`, if set.
199    pub ssh_program: Option<String>,
200    /// `user.signingkey`, if set.
201    pub signing_key: Option<String>,
202    /// `gpg.minTrustLevel`, if set.
203    pub min_trust_level: Option<TrustLevel>,
204    /// `gpg.ssh.allowedSignersFile`, if set (path; leading `~/` expanded).
205    pub ssh_allowed_signers: Option<String>,
206    /// `gpg.ssh.revocationFile`, if set (path; leading `~/` expanded).
207    pub ssh_revocation_file: Option<String>,
208    /// Subprocess runner for gpg/gpgsm/ssh-signing helpers.
209    pub command_runner: Arc<dyn CommandRunner>,
210}
211
212impl std::fmt::Debug for GpgConfig {
213    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214        f.debug_struct("GpgConfig")
215            .field("format", &self.format)
216            .field("program", &self.program)
217            .finish_non_exhaustive()
218    }
219}
220
221fn signing_spawn(
222    cfg: &GpgConfig,
223    spec: CommandSpec,
224    payload: Option<&[u8]>,
225) -> crate::error::Result<CommandOutput> {
226    let program = spec.program.clone();
227    let running = cfg
228        .command_runner
229        .spawn(&spec)
230        .map_err(|e| commit_signing_io_failure(&program, e))?;
231    let output = if let Some(data) = payload {
232        running
233            .feed_stdin_and_wait_with_output(Some(
234                crate::command_runner::ConcurrentStdinFeed::Bytes(data),
235            ))
236            .map_err(|e| commit_signing_io_failure(&program, e))?
237    } else {
238        running
239            .wait_with_output()
240            .map_err(|e| commit_signing_io_failure(&program, e))?
241    };
242    Ok(output)
243}
244
245fn stdin_pipe(data: &[u8]) -> CommandStdin {
246    CommandStdin::Pipe(data.to_vec())
247}
248
249impl GpgConfig {
250    /// Read the signing configuration from a [`ConfigSet`].
251    ///
252    /// # Errors
253    ///
254    /// Returns [`Error::Config`] when `gpg.format` holds an unrecognized
255    /// value (Git rejects this case-sensitively).
256    pub fn from_config(config: &ConfigSet) -> Result<GpgConfig> {
257        let format = match config.value("gpg.format") {
258            Some(raw) => GpgFormat::from_name(&raw).ok_or_else(|| {
259                Error::Config(ConfigError::UnknownValue {
260                    key: "gpg.format".to_owned(),
261                    value: raw.clone(),
262                })
263            })?,
264            None => GpgFormat::OpenPgp,
265        };
266
267        let nonempty = |k: &str| config.value(k).filter(|p| !p.is_empty());
268        let generic_program = nonempty("gpg.program");
269        let fmt_program = |f: GpgFormat| nonempty(&format!("gpg.{}.program", f.name()));
270        let openpgp_program = fmt_program(GpgFormat::OpenPgp);
271        let x509_program = fmt_program(GpgFormat::X509);
272        let ssh_program = fmt_program(GpgFormat::Ssh);
273
274        // `gpg.<fmt>.program` takes precedence over `gpg.program`.
275        let program = resolve_program_for_format(
276            format,
277            generic_program.as_deref(),
278            match format {
279                GpgFormat::OpenPgp => openpgp_program.as_deref(),
280                GpgFormat::X509 => x509_program.as_deref(),
281                GpgFormat::Ssh => ssh_program.as_deref(),
282            },
283        );
284
285        let signing_key = config.value("user.signingkey").filter(|k| !k.is_empty());
286
287        let min_trust_level = config
288            .value("gpg.mintrustlevel")
289            .and_then(|v| TrustLevel::from_config(&v));
290
291        // Path values: Git uses `git_config_pathname`, which expands a leading
292        // `~/` relative to $HOME. `ConfigSet` lowercases section/variable names.
293        let ssh_allowed_signers = config
294            .value("gpg.ssh.allowedsignersfile")
295            .filter(|p| !p.is_empty())
296            .map(|p| expand_tilde(&p));
297        let ssh_revocation_file = config
298            .value("gpg.ssh.revocationfile")
299            .filter(|p| !p.is_empty())
300            .map(|p| expand_tilde(&p));
301
302        Ok(GpgConfig {
303            format,
304            program,
305            generic_program,
306            openpgp_program,
307            x509_program,
308            ssh_program,
309            signing_key,
310            min_trust_level,
311            ssh_allowed_signers,
312            ssh_revocation_file,
313            command_runner: system_command_runner(),
314        })
315    }
316
317    /// Override the subprocess runner (tests and embedders).
318    #[must_use]
319    pub fn with_command_runner(mut self, runner: Arc<dyn CommandRunner>) -> Self {
320        self.command_runner = runner;
321        self
322    }
323
324    /// Resolve the program for a specific format (honoring `gpg.<fmt>.program`
325    /// then `gpg.program`, falling back to the format default). Used by
326    /// verification, where the format is detected from the signature armor and
327    /// may differ from the configured [`Self::format`].
328    fn program_for(&self, format: GpgFormat) -> String {
329        let fmt_program = match format {
330            GpgFormat::OpenPgp => self.openpgp_program.as_deref(),
331            GpgFormat::X509 => self.x509_program.as_deref(),
332            GpgFormat::Ssh => self.ssh_program.as_deref(),
333        };
334        resolve_program_for_format(format, self.generic_program.as_deref(), fmt_program)
335    }
336
337    /// The signing key to use: the explicit `key_override`, else
338    /// `user.signingkey`, else the supplied committer identity (Git passes
339    /// `git_committer_info(IDENT_STRICT | IDENT_NO_DATE)`).
340    pub fn resolve_signing_key(
341        &self,
342        key_override: Option<&str>,
343        committer_default: &str,
344    ) -> String {
345        if let Some(k) = key_override {
346            if !k.is_empty() {
347                return k.to_owned();
348            }
349        }
350        if let Some(k) = &self.signing_key {
351            return k.clone();
352        }
353        committer_default.to_owned()
354    }
355
356    /// Resolve [`Self::program`] to an executable path.
357    ///
358    /// Mirrors Git's program resolution: a leading `~/` expands to `$HOME`, an
359    /// absolute path is used verbatim, and a bare name is searched on `$PATH`.
360    pub fn resolve_program_path(&self) -> crate::error::Result<PathBuf> {
361        resolve_program(&self.program)
362    }
363}
364
365/// Resolve the program *string* for `format`: `gpg.<fmt>.program` (if set),
366/// else `gpg.program` (if set), else the format's built-in default.
367fn resolve_program_for_format(
368    format: GpgFormat,
369    generic_program: Option<&str>,
370    fmt_program: Option<&str>,
371) -> String {
372    fmt_program
373        .or(generic_program)
374        .filter(|p| !p.is_empty())
375        .map(|p| p.to_owned())
376        .unwrap_or_else(|| format.default_program().to_owned())
377}
378
379/// Resolve a program string to an executable path.
380fn resolve_program(program: &str) -> crate::error::Result<PathBuf> {
381    // `~` / `~/...` expansion relative to $HOME.
382    if program == "~" {
383        if let Some(home) = home_dir() {
384            return Ok(home);
385        }
386    }
387    if let Some(rest) = program.strip_prefix("~/") {
388        if let Some(home) = home_dir() {
389            return Ok(home.join(rest));
390        }
391    }
392
393    let path = Path::new(program);
394    // Absolute path, or any relative path that contains a separator: use as-is.
395    if path.is_absolute() || program.contains('/') {
396        return Ok(path.to_path_buf());
397    }
398
399    // Bare name: search $PATH.
400    if let Some(found) = search_path(program) {
401        return Ok(found);
402    }
403
404    // Fall back to the bare name and let the OS resolve it (preserves Git's
405    // behavior of handing the name straight to exec when not found on PATH).
406    Ok(path.to_path_buf())
407}
408
409/// Look up a bare program name on `$PATH`.
410fn search_path(name: &str) -> Option<PathBuf> {
411    let paths = crate::environment::Environment::empty().var_os("PATH")?;
412    for dir in paths.to_string_lossy().split(':').map(PathBuf::from) {
413        if dir.as_os_str().is_empty() {
414            continue;
415        }
416        let candidate = dir.join(name);
417        if is_executable_file(&candidate) {
418            return Some(candidate);
419        }
420    }
421    None
422}
423
424#[cfg(unix)]
425fn is_executable_file(path: &Path) -> bool {
426    use std::os::unix::fs::PermissionsExt;
427    match std::fs::metadata(path) {
428        Ok(meta) => meta.is_file() && (meta.permissions().mode() & 0o111 != 0),
429        Err(_) => false,
430    }
431}
432
433#[cfg(not(unix))]
434fn is_executable_file(path: &Path) -> bool {
435    path.is_file()
436}
437
438/// The user's home directory (`$HOME`).
439fn home_dir() -> Option<PathBuf> {
440    crate::environment::Environment::empty()
441        .var_os("HOME")
442        .map(PathBuf::from)
443}
444
445/// Expand a leading `~/` (and a bare `~`) relative to `$HOME`, like Git's
446/// `interpolate_path` / `git_config_pathname` for the simple home case.
447fn expand_tilde(path: &str) -> String {
448    if path == "~" {
449        if let Some(home) = home_dir() {
450            return home.to_string_lossy().into_owned();
451        }
452    }
453    if let Some(rest) = path.strip_prefix("~/") {
454        if let Some(home) = home_dir() {
455            return home.join(rest).to_string_lossy().into_owned();
456        }
457    }
458    path.to_owned()
459}
460
461/// Whether a new commit object should be signed.
462///
463/// Honors `commit.gpgsign` (and `commit.gpgSign`) when `sign_override` is `None`.
464/// When `sign_override` is `Some(true)` or `Some(false)`, that choice wins over config.
465///
466/// # Errors
467///
468/// Returns [`Error::Config`] when `commit.gpgsign` holds a non-boolean value.
469pub fn should_sign_commit(config: &ConfigSet, sign_override: Option<bool>) -> Result<bool> {
470    if let Some(force) = sign_override {
471        return Ok(force);
472    }
473    Ok(config.get_bool("commit.gpgSign")?.unwrap_or(false))
474}
475
476/// Whether a new annotated tag object should be signed.
477///
478/// Honors `tag.gpgSign` (and `tag.gpgsign`) when `sign_override` is `None`.
479/// When `sign_override` is `Some(true)` or `Some(false)`, that choice wins over config.
480///
481/// # Errors
482///
483/// Returns [`Error::Config`] when `tag.gpgSign` holds a non-boolean value.
484pub fn should_sign_tag(config: &ConfigSet, sign_override: Option<bool>) -> Result<bool> {
485    if let Some(force) = sign_override {
486        return Ok(force);
487    }
488    Ok(config.get_bool("tag.gpgSign")?.unwrap_or(false))
489}
490
491/// Header name for an embedded commit signature for `hash_algo`.
492#[must_use]
493pub fn commit_gpg_sig_header(hash_algo: HashAlgo) -> &'static str {
494    match hash_algo {
495        HashAlgo::Sha256 => GPG_SIG_HEADER_SHA256,
496        HashAlgo::Sha1 => GPG_SIG_HEADER_SHA1,
497    }
498}
499
500/// Sign a serialized commit object (without `gpgsig`) and splice the signature header.
501///
502/// Uses [`sign_buffer`] on `unsigned_bytes` and [`add_header_signature`] with the
503/// header from [`commit_gpg_sig_header`]. The signing key comes from
504/// `signing_key_override`, else `user.signingkey`, else
505/// [`committer_signing_default`] applied to `committer_ident`.
506///
507/// # Errors
508///
509/// Returns [`[`CommitError::Signing`](crate::porcelain::commit_error::CommitError::Signing)`] when the signing program fails, and [`Error::Config`]
510/// when `GpgConfig` cannot be built from the repository config (callers typically
511/// construct [`GpgConfig`] first).
512pub fn sign_serialized_commit(
513    cfg: &GpgConfig,
514    unsigned_bytes: &[u8],
515    committer_ident: &str,
516    signing_key_override: Option<&str>,
517    hash_algo: HashAlgo,
518) -> crate::error::Result<Vec<u8>> {
519    let committer_key = committer_signing_default(committer_ident);
520    let signing_key = cfg.resolve_signing_key(signing_key_override, &committer_key);
521    let sig = sign_buffer(cfg, unsigned_bytes, &signing_key)?;
522    let header = commit_gpg_sig_header(hash_algo);
523    Ok(add_header_signature(unsigned_bytes, &sig, header))
524}
525
526/// Append an armored detached signature to a serialized tag object.
527///
528/// Tag signatures are stored after the tag body (unlike commits, which use a
529/// `gpgsig` header). See [`parse_signed_buffer`].
530#[must_use]
531pub fn append_tag_signature(unsigned_bytes: &[u8], sig: &[u8]) -> Vec<u8> {
532    let mut out = Vec::with_capacity(unsigned_bytes.len() + sig.len());
533    out.extend_from_slice(unsigned_bytes);
534    out.extend_from_slice(sig);
535    out
536}
537
538/// Sign a serialized tag object (without an appended signature).
539///
540/// Uses [`sign_buffer`] on `unsigned_bytes` and [`append_tag_signature`]. The
541/// signing key comes from `signing_key_override`, else `user.signingkey`, else
542/// [`committer_signing_default`] applied to `tagger_ident`.
543///
544/// # Errors
545///
546/// Returns [`[`CommitError::Signing`](crate::porcelain::commit_error::CommitError::Signing)`] when the signing program fails.
547pub fn sign_serialized_tag(
548    cfg: &GpgConfig,
549    unsigned_bytes: &[u8],
550    tagger_ident: &str,
551    signing_key_override: Option<&str>,
552) -> crate::error::Result<Vec<u8>> {
553    let tagger_key = committer_signing_default(tagger_ident);
554    let signing_key = cfg.resolve_signing_key(signing_key_override, &tagger_key);
555    let sig = sign_buffer(cfg, unsigned_bytes, &signing_key)?;
556    Ok(append_tag_signature(unsigned_bytes, &sig))
557}
558
559/// Sign `payload` with `signing_key` using the configured program.
560///
561/// Spawns `<program> --status-fd=2 -bsau <signing_key>`, writes `payload` to
562/// stdin, and returns the armored detached signature from stdout.  Fails if the
563/// child exits non-zero or does not emit a `[GNUPG:] SIG_CREATED` status line —
564/// in either case the program's stderr is surfaced in the error (the
565/// `LET_GPG_PROGRAM_FAIL`/`zOMG` path of subtest 28).
566///
567/// # Errors
568///
569/// Returns [`[`CommitError::Signing`](crate::porcelain::commit_error::CommitError::Signing)`] when the program cannot be spawned, exits
570/// non-zero, or fails to produce a signature.
571pub fn sign_buffer(
572    cfg: &GpgConfig,
573    payload: &[u8],
574    signing_key: &str,
575) -> crate::error::Result<Vec<u8>> {
576    if cfg.format == GpgFormat::Ssh {
577        return sign_buffer_ssh(cfg, payload, signing_key);
578    }
579
580    let program = cfg.resolve_program_path()?;
581
582    let spec = CommandSpec {
583        program: program.clone(),
584        args: vec![
585            OsString::from("--status-fd=2"),
586            OsString::from("-bsau"),
587            OsString::from(signing_key),
588        ],
589        shell: None,
590        cwd: None,
591        env: CommandEnvironment::inherit_process_only(),
592        stdin: stdin_pipe(payload),
593        stdout: CommandStdio::Pipe,
594        stderr: CommandStdio::Pipe,
595    };
596    let output = signing_spawn(cfg, spec, None)?;
597
598    let status_text = String::from_utf8_lossy(&output.stderr);
599
600    if !output.status.success || !has_sig_created(&status_text) {
601        let detail = if status_text.trim().is_empty() {
602            "(no gpg output)".to_owned()
603        } else {
604            status_text.into_owned()
605        };
606        return Err(crate::error::Error::from(commit_signing_process_failure(
607            &program,
608            output.status,
609            format!("gpg failed to sign the data:\n{detail}"),
610        )));
611    }
612
613    Ok(output.stdout)
614}
615
616/// True when a `[GNUPG:] SIG_CREATED ` status line is present at the start of a
617/// line (Git's `sign_buffer_gpg` SIG_CREATED scan).
618fn has_sig_created(status: &str) -> bool {
619    status
620        .lines()
621        .any(|line| line.starts_with("[GNUPG:] SIG_CREATED "))
622}
623
624/// Detect a literal ssh key (Git `gpg-interface.c:is_literal_ssh_key`).
625///
626/// Returns `Some(rest)` for `key::<rest>`, `Some(s)` for a value starting with
627/// `ssh-`, else `None`.
628fn is_literal_ssh_key(s: &str) -> Option<&str> {
629    if let Some(rest) = s.strip_prefix("key::") {
630        return Some(rest);
631    }
632    if s.starts_with("ssh-") {
633        return Some(s);
634    }
635    None
636}
637
638/// Sign `payload` with an ssh key using `ssh-keygen -Y sign`.
639///
640/// Port of Git's `gpg-interface.c:sign_buffer_ssh`.  `signing_key` is either a
641/// literal public key (`key::...` or `ssh-...`) or a path to a key file
642/// (`~/` expanded).  Returns the armored `-----BEGIN SSH SIGNATURE-----` blob.
643///
644/// # Errors
645///
646/// Returns [`[`CommitError::Signing`](crate::porcelain::commit_error::CommitError::Signing)`] when `signing_key` is empty, a temp file cannot be
647/// written, `ssh-keygen` cannot be run or exits non-zero, or the `.sig` output
648/// cannot be read.
649fn sign_buffer_ssh(
650    cfg: &GpgConfig,
651    payload: &[u8],
652    signing_key: &str,
653) -> crate::error::Result<Vec<u8>> {
654    if signing_key.is_empty() {
655        let program = cfg.resolve_program_path()?;
656        return Err(CommitError::signing_failure(
657            program_display(&program),
658            None,
659            "user.signingKey needs to be set for ssh signing",
660        )
661        .into());
662    }
663
664    let program = cfg.resolve_program_path()?;
665
666    // Resolve the key file: either a literal key written to a temp file (with
667    // the `-U` flag), or a path on disk.
668    let mut literal_key_tmp: Option<PathBuf> = None;
669    let (key_file, literal): (String, bool) = match is_literal_ssh_key(signing_key) {
670        Some(literal_key) => {
671            let path = write_temp_file_named(literal_key.as_bytes(), "git_signing_key")?;
672            let p = path.to_string_lossy().into_owned();
673            literal_key_tmp = Some(path);
674            (p, true)
675        }
676        None => (expand_tilde(signing_key), false),
677    };
678
679    // Write the payload to a temp buffer file; ssh-keygen reads it as the file
680    // to sign and writes `<file>.sig` alongside it.
681    let buffer_path = match write_temp_file_named(payload, "git_signing_buffer") {
682        Ok(p) => p,
683        Err(e) => {
684            if let Some(p) = &literal_key_tmp {
685                let _ = std::fs::remove_file(p);
686            }
687            return Err(e);
688        }
689    };
690
691    let mut args = vec![
692        OsString::from("-Y"),
693        OsString::from("sign"),
694        OsString::from("-n"),
695        OsString::from("git"),
696        OsString::from("-f"),
697        OsString::from(key_file.as_str()),
698    ];
699    if literal {
700        args.push(OsString::from("-U"));
701    }
702    args.push(OsString::from(buffer_path.to_string_lossy().as_ref()));
703    let spec = CommandSpec {
704        program: program.clone(),
705        args,
706        shell: None,
707        cwd: None,
708        env: CommandEnvironment::inherit_process_only(),
709        stdin: CommandStdin::Null,
710        stdout: CommandStdio::Pipe,
711        stderr: CommandStdio::Pipe,
712    };
713
714    let cleanup = |literal_key_tmp: &Option<PathBuf>, buffer_path: &Path| {
715        if let Some(p) = literal_key_tmp {
716            let _ = std::fs::remove_file(p);
717        }
718        let _ = std::fs::remove_file(buffer_path);
719        let _ = std::fs::remove_file(sig_sibling(buffer_path));
720    };
721
722    let output = match signing_spawn(cfg, spec, None) {
723        Ok(o) => o,
724        Err(e) => {
725            cleanup(&literal_key_tmp, &buffer_path);
726            return Err(e);
727        }
728    };
729
730    if !output.status.success {
731        let stderr = String::from_utf8_lossy(&output.stderr);
732        cleanup(&literal_key_tmp, &buffer_path);
733        if stderr.contains("usage:") {
734            return Err(CommitError::signing_from_message(
735                "ssh-keygen -Y sign is needed for ssh signing (available in openssh version 8.2p1+)"
736                    .to_owned(),
737            ).into());
738        }
739        return Err(crate::error::Error::from(commit_signing_process_failure(
740            &program,
741            output.status,
742            stderr.into_owned(),
743        )));
744    }
745
746    let sig_path = sig_sibling(&buffer_path);
747    let result = std::fs::read(&sig_path).map_err(|e| commit_signing_io_failure(&program, e));
748    cleanup(&literal_key_tmp, &buffer_path);
749
750    let mut sig = result?;
751    // Strip a trailing CR (Windows line endings) from each line, mirroring
752    // Git's `remove_cr_after`.
753    strip_cr(&mut sig);
754    Ok(sig)
755}
756
757/// The `<path>.sig` sibling file produced by `ssh-keygen -Y sign`.
758fn sig_sibling(buffer_path: &Path) -> PathBuf {
759    let mut s = buffer_path.as_os_str().to_owned();
760    s.push(".sig");
761    PathBuf::from(s)
762}
763
764/// Remove `\r` characters that immediately precede a `\n` (Git `remove_cr_after`).
765fn strip_cr(buf: &mut Vec<u8>) {
766    let mut out = Vec::with_capacity(buf.len());
767    let mut i = 0;
768    while i < buf.len() {
769        if buf[i] == b'\r' && buf.get(i + 1) == Some(&b'\n') {
770            i += 1;
771            continue;
772        }
773        out.push(buf[i]);
774        i += 1;
775    }
776    *buf = out;
777}
778
779/// Splice a signature into a serialized commit object as a `gpgsig` header.
780///
781/// Port of Git's `commit.c:add_header_signature`: find the first `\n\n`, insert
782/// the header at the position right after that first `\n`, prefix the first
783/// signature line with `<header> ` and every subsequent line with a single
784/// space.  `header` is [`GPG_SIG_HEADER_SHA1`] or [`GPG_SIG_HEADER_SHA256`].
785pub fn add_header_signature(buf: &[u8], sig: &[u8], header: &str) -> Vec<u8> {
786    // Find end of header (first occurrence of "\n\n"); inspos is just past the
787    // first '\n'. If absent, append at the end.
788    let inspos = find_double_newline(buf).map(|p| p + 1).unwrap_or(buf.len());
789
790    let mut out = Vec::with_capacity(buf.len() + sig.len() + header.len() + 16);
791    out.extend_from_slice(&buf[..inspos]);
792
793    let mut first = true;
794    let mut copypos = 0usize;
795    while copypos < sig.len() {
796        let bol = copypos;
797        // End of this line, including the trailing '\n' when present.
798        let end = match memchr(sig, copypos, b'\n') {
799            Some(idx) => idx + 1,
800            None => sig.len(),
801        };
802
803        if first {
804            out.extend_from_slice(header.as_bytes());
805            first = false;
806        }
807        out.push(b' ');
808        out.extend_from_slice(&sig[bol..end]);
809        copypos = end;
810    }
811
812    out.extend_from_slice(&buf[inspos..]);
813    out
814}
815
816/// Find the first `\n\n` in `buf`, returning the index of the first `\n`.
817fn find_double_newline(buf: &[u8]) -> Option<usize> {
818    let mut i = 0;
819    while i + 1 < buf.len() {
820        if buf[i] == b'\n' && buf[i + 1] == b'\n' {
821            return Some(i);
822        }
823        i += 1;
824    }
825    None
826}
827
828/// Find the byte `needle` in `buf` starting at `from`.
829fn memchr(buf: &[u8], from: usize, needle: u8) -> Option<usize> {
830    buf.get(from..)
831        .and_then(|s| s.iter().position(|&b| b == needle))
832        .map(|p| p + from)
833}
834
835/// A parsed signature check result.
836#[derive(Debug, Clone, Default)]
837pub struct SignatureCheck {
838    /// The detached armored signature extracted from the object.
839    pub signature: Vec<u8>,
840    /// The signed payload (object with `gpgsig` header removed).
841    pub payload: Vec<u8>,
842    /// `%G?` result: `G` good, `B` bad, `U` good+untrusted, `E` error,
843    /// `N` no signature, `X`/`Y`/`R` expired/expired-key/revoked.
844    pub result: char,
845    /// `%GT` trust level.
846    pub trust_level: TrustLevel,
847    /// `%GK` key id.
848    pub key: Option<String>,
849    /// `%GS` signer (uid).
850    pub signer: Option<String>,
851    /// `%GF` signing key fingerprint.
852    pub fingerprint: Option<String>,
853    /// `%GP` primary key fingerprint.
854    pub primary_key_fingerprint: Option<String>,
855    /// Human-readable gpg output (stderr); shown by `--show-signature`.
856    pub output: String,
857    /// Raw `[GNUPG:]` status lines; shown by `verify-commit --raw`.
858    pub gpg_status: String,
859    /// True when the underlying verifier reported failure regardless of the
860    /// parsed `%G?` result.  For ssh this captures Git's
861    /// `verify_ssh_signed_buffer` return code (e.g. an untrusted key that still
862    /// produces a `Good "git" signature with ...` line must fail verification).
863    pub verifier_failed: bool,
864}
865
866impl SignatureCheck {
867    /// Construct the "no signature" result (`%G?` -> `N`).
868    pub fn default_none() -> SignatureCheck {
869        SignatureCheck {
870            result: 'N',
871            trust_level: TrustLevel::Undefined,
872            ..Default::default()
873        }
874    }
875
876    /// True when the signature verified as good (`G`) or good-but-expired-key
877    /// (`Y`) — Git's success criterion in `check_signature`.
878    pub fn is_good(&self) -> bool {
879        self.result == 'G' || self.result == 'Y'
880    }
881
882    /// Overall verification result honoring `min_trust_level`: `Ok(())` when the
883    /// signature is good and meets the configured minimum trust level.
884    pub fn verify_status(&self, min_trust_level: Option<TrustLevel>) -> bool {
885        if self.verifier_failed {
886            return false;
887        }
888        if !self.is_good() {
889            return false;
890        }
891        if let Some(min) = min_trust_level {
892            if self.trust_level < min {
893                return false;
894            }
895        }
896        true
897    }
898}
899
900/// Extract the `gpgsig` (or `gpgsig-sha256`) header value and the signed
901/// payload from a raw commit object.
902///
903/// Returns `(payload, signature)` where `payload` is the commit object with the
904/// `gpgsig` header removed (the bytes that were actually signed), and
905/// `signature` is the de-indented armored signature.  Returns `None` when the
906/// object carries no signature header.
907pub fn extract_signed_payload(raw_commit: &[u8]) -> Option<(Vec<u8>, Vec<u8>)> {
908    // Header region ends at first "\n\n".
909    let header_end = find_double_newline(raw_commit)?;
910    let header = &raw_commit[..=header_end]; // includes trailing first '\n'
911    let body = &raw_commit[header_end + 1..]; // remaining (starts with '\n')
912
913    let mut payload = Vec::with_capacity(raw_commit.len());
914    let mut signature = Vec::new();
915    let mut found = false;
916
917    let mut idx = 0;
918    while idx < header.len() {
919        let line_end = memchr(header, idx, b'\n')
920            .map(|p| p + 1)
921            .unwrap_or(header.len());
922        let line = &header[idx..line_end];
923
924        let Some((_, prefix_len)) = gpg_sig_header_line(line) else {
925            payload.extend_from_slice(line);
926            idx = line_end;
927            continue;
928        };
929
930        if !found {
931            found = true;
932            signature.extend_from_slice(&line[prefix_len..]);
933            idx = line_end;
934            // Subsequent continuation lines (leading space) belong to the sig.
935            while idx < header.len() {
936                let cont_end = memchr(header, idx, b'\n')
937                    .map(|p| p + 1)
938                    .unwrap_or(header.len());
939                let cont = &header[idx..cont_end];
940                if cont.first() == Some(&b' ') {
941                    signature.extend_from_slice(&cont[1..]);
942                    idx = cont_end;
943                } else {
944                    break;
945                }
946            }
947            continue;
948        }
949
950        payload.extend_from_slice(line);
951        idx = line_end;
952    }
953
954    if !found {
955        return None;
956    }
957
958    payload.extend_from_slice(body);
959    Some((payload, signature))
960}
961
962/// Remove embedded commit signature headers from [`crate::objects::CommitData::extra_headers`].
963///
964/// Used when amending: the rewritten object must not carry the replaced tip's
965/// `gpgsig` / `gpgsig-sha256` block; signing (if any) adds a fresh header later.
966#[must_use]
967pub fn extra_headers_without_commit_signatures(extra: &[u8]) -> Vec<u8> {
968    let mut out = Vec::with_capacity(extra.len());
969    let mut idx = 0;
970    while idx < extra.len() {
971        let line_end = memchr(extra, idx, b'\n')
972            .map(|p| p + 1)
973            .unwrap_or(extra.len());
974        let line = &extra[idx..line_end];
975
976        if gpg_sig_header_line(line).is_some() {
977            idx = line_end;
978            while idx < extra.len() {
979                let cont_end = memchr(extra, idx, b'\n')
980                    .map(|p| p + 1)
981                    .unwrap_or(extra.len());
982                let cont = &extra[idx..cont_end];
983                if cont.first() == Some(&b' ') {
984                    idx = cont_end;
985                } else {
986                    break;
987                }
988            }
989            continue;
990        }
991
992        out.extend_from_slice(line);
993        idx = line_end;
994    }
995    out
996}
997
998/// If `line` begins a `gpgsig` / `gpgsig-sha256` header, return the header name and
999/// the byte offset after `"<header> "`.
1000fn gpg_sig_header_line(line: &[u8]) -> Option<(&'static str, usize)> {
1001    for header in [GPG_SIG_HEADER_SHA256, GPG_SIG_HEADER_SHA1] {
1002        if line.starts_with(header.as_bytes()) && line.get(header.len()) == Some(&b' ') {
1003            return Some((header, header.len() + 1));
1004        }
1005    }
1006    None
1007}
1008
1009/// Verify a raw commit object's embedded signature.
1010///
1011/// Extracts the payload + signature, then (for gpg-based formats) writes the
1012/// signature to a temp file and runs `<program> --status-fd=1 <verify_args>
1013/// --verify <sigfile> -`, feeding the payload on stdin, and parses the
1014/// `[GNUPG:]` status lines.
1015pub fn verify_commit(cfg: &GpgConfig, raw_commit: &[u8]) -> crate::error::Result<SignatureCheck> {
1016    let (payload, signature) = match extract_signed_payload(raw_commit) {
1017        Some(parts) => parts,
1018        None => return Ok(SignatureCheck::default_none()),
1019    };
1020
1021    // Git picks the verifier from the *signature* armor (`get_format_by_sig`),
1022    // not from `gpg.format`: a `git verify-commit` over an ssh-signed commit must
1023    // use ssh-keygen even when `gpg.format` is unset/openpgp, and vice-versa.
1024    let detected_format = GpgFormat::from_signature(&signature).unwrap_or(cfg.format);
1025
1026    if detected_format == GpgFormat::Ssh {
1027        return verify_ssh_signed_buffer(cfg, payload, signature);
1028    }
1029
1030    let program = resolve_program(&cfg.program_for(detected_format))?;
1031
1032    // Write the detached signature to a temp file.
1033    let sig_path = write_temp_file(&signature)?;
1034
1035    let mut args = vec![OsString::from("--status-fd=1")];
1036    for a in detected_format.verify_args() {
1037        args.push(OsString::from(a));
1038    }
1039    args.push(OsString::from("--verify"));
1040    args.push(OsString::from(sig_path.to_string_lossy().as_ref()));
1041    args.push(OsString::from("-"));
1042    let spec = CommandSpec {
1043        program: program.clone(),
1044        args,
1045        shell: None,
1046        cwd: None,
1047        env: CommandEnvironment::inherit_process_only(),
1048        stdin: stdin_pipe(&payload),
1049        stdout: CommandStdio::Pipe,
1050        stderr: CommandStdio::Pipe,
1051    };
1052
1053    let output = match signing_spawn(cfg, spec, None) {
1054        Ok(o) => o,
1055        Err(e) => {
1056            let _ = std::fs::remove_file(&sig_path);
1057            return Err(e);
1058        }
1059    };
1060    let _ = std::fs::remove_file(&sig_path);
1061
1062    // status-fd=1 routes GNUPG status to stdout; human-readable goes to stderr.
1063    let gpg_status = String::from_utf8_lossy(&output.stdout).into_owned();
1064    let human = String::from_utf8_lossy(&output.stderr).into_owned();
1065
1066    let mut sigc = SignatureCheck {
1067        signature,
1068        payload,
1069        result: 'N',
1070        trust_level: TrustLevel::Undefined,
1071        gpg_status: gpg_status.clone(),
1072        output: human,
1073        ..Default::default()
1074    };
1075
1076    parse_gpg_output(&mut sigc, &gpg_status);
1077
1078    Ok(sigc)
1079}
1080
1081/// Parse `ssh-keygen -Y verify` human output into `sigc`
1082/// (produces the same parse as Git's `gpg-interface.c:parse_ssh_output`).
1083///
1084/// Expected first line of `sigc.output`:
1085/// * `Good "git" signature for PRINCIPAL with ... key SHA256:FINGERPRINT`
1086///   -> result `G`, trust `Fully`, signer = PRINCIPAL.
1087/// * `Good "git" signature with ... key SHA256:FINGERPRINT`
1088///   -> result `G`, trust `Undefined` (unknown key, signer unset).
1089/// * anything else -> result `B`, trust `Never`.
1090///
1091/// In the two good cases the substring after `key ` becomes both the
1092/// fingerprint (`%GF`) and the key (`%GK`); `%GP` is never set.
1093fn parse_ssh_output(sigc: &mut SignatureCheck) {
1094    sigc.result = 'B';
1095    sigc.trust_level = TrustLevel::Never;
1096    sigc.key = None;
1097    sigc.signer = None;
1098    sigc.fingerprint = None;
1099    sigc.primary_key_fingerprint = None;
1100
1101    let first_line = sigc.output.split('\n').next().unwrap_or("");
1102
1103    let after_key;
1104    if let Some(rest) = first_line.strip_prefix("Good \"git\" signature for ") {
1105        // The principal can contain whitespace; the trailing
1106        // ` with <algo> key <fpr>` is fixed, so split on the *last* " with ".
1107        match rest.rfind(" with ") {
1108            Some(idx) => {
1109                let principal = &rest[..idx];
1110                if principal.is_empty() {
1111                    return;
1112                }
1113                sigc.result = 'G';
1114                sigc.trust_level = TrustLevel::Fully;
1115                sigc.signer = Some(principal.to_owned());
1116                after_key = &rest[idx + " with ".len()..];
1117            }
1118            None => return,
1119        }
1120    } else if let Some(rest) = first_line.strip_prefix("Good \"git\" signature with ") {
1121        sigc.result = 'G';
1122        sigc.trust_level = TrustLevel::Undefined;
1123        after_key = rest;
1124    } else {
1125        return;
1126    }
1127
1128    // The fingerprint follows the literal `key ` token.
1129    match after_key.find("key ") {
1130        Some(pos) => {
1131            let fpr = after_key[pos + "key ".len()..].to_owned();
1132            sigc.fingerprint = Some(fpr.clone());
1133            sigc.key = Some(fpr);
1134        }
1135        None => {
1136            // Output did not match what we expected: treat as bad.
1137            sigc.result = 'B';
1138        }
1139    }
1140}
1141
1142/// Extract the committer (or tagger) unix timestamp from a signed payload,
1143/// porting Git's `parse_payload_metadata` for the `committer`/`tagger` header.
1144fn payload_committer_timestamp(payload: &[u8]) -> Option<u64> {
1145    let ident_line =
1146        find_header_line(payload, b"committer").or_else(|| find_header_line(payload, b"tagger"))?;
1147    let line = std::str::from_utf8(ident_line).ok()?;
1148    // Ident line: "Name <email> <timestamp> <tz>"; the timestamp is the
1149    // second-to-last whitespace-separated token.
1150    let mut it = line.split_whitespace().rev();
1151    let _tz = it.next()?;
1152    let ts = it.next()?;
1153    ts.parse::<u64>().ok()
1154}
1155
1156/// Return the bytes after `"<name> "` for the first header line matching `name`
1157/// (within the header region, i.e. before the first blank line).
1158fn find_header_line<'a>(payload: &'a [u8], name: &[u8]) -> Option<&'a [u8]> {
1159    let mut idx = 0;
1160    while idx < payload.len() {
1161        let line_end = memchr(payload, idx, b'\n').unwrap_or(payload.len());
1162        let line = &payload[idx..line_end];
1163        if line.is_empty() {
1164            // End of header region.
1165            return None;
1166        }
1167        if line.len() > name.len() + 1 && &line[..name.len()] == name && line[name.len()] == b' ' {
1168            return Some(&line[name.len() + 1..]);
1169        }
1170        idx = line_end + 1;
1171    }
1172    None
1173}
1174
1175/// Format a `-Overify-time=YYYYMMDDhhmmss` argument from a unix timestamp using
1176/// the local timezone, mirroring Git's `verify_date_mode` (DATE_STRFTIME, local).
1177fn verify_time_arg(timestamp: u64) -> String {
1178    use crate::git_date::show::{show_date, DateMode, DateModeType};
1179    let mut mode = DateMode {
1180        ty: DateModeType::Strftime,
1181        local: true,
1182        strftime_fmt: Some("%Y%m%d%H%M%S".to_owned()),
1183    };
1184    let formatted = show_date(timestamp, 0, &mut mode);
1185    format!("-Overify-time={formatted}")
1186}
1187
1188/// Verify an ssh-signed `payload` against `signature` using `ssh-keygen -Y`.
1189///
1190/// Port of Git's `gpg-interface.c:verify_ssh_signed_buffer`.  Requires
1191/// `gpg.ssh.allowedSignersFile`; runs `find-principals`, then either
1192/// `check-novalidate` (no principal matched -> untrusted) or `verify` for each
1193/// matched principal.  Populates `sigc.output`/`sigc.gpg_status` and parses them
1194/// via [`parse_ssh_output`].
1195fn verify_ssh_signed_buffer(
1196    cfg: &GpgConfig,
1197    payload: Vec<u8>,
1198    signature: Vec<u8>,
1199) -> crate::error::Result<SignatureCheck> {
1200    let mut sigc = SignatureCheck {
1201        signature: signature.clone(),
1202        payload: payload.clone(),
1203        result: 'N',
1204        trust_level: TrustLevel::Undefined,
1205        ..Default::default()
1206    };
1207
1208    let allowed = match &cfg.ssh_allowed_signers {
1209        Some(a) if !a.is_empty() => a.clone(),
1210        _ => {
1211            sigc.result = 'B';
1212            sigc.trust_level = TrustLevel::Never;
1213            sigc.output = "gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification".to_owned();
1214            sigc.gpg_status = sigc.output.clone();
1215            return Ok(sigc);
1216        }
1217    };
1218
1219    // The format here is detected from the signature armor, which may differ
1220    // from `cfg.format`; always resolve the ssh program (`gpg.ssh.program` /
1221    // `gpg.program` / `ssh-keygen`).
1222    let program = resolve_program(&cfg.program_for(GpgFormat::Ssh))?;
1223
1224    // Write the detached signature to a temp `.git_vtag` file.
1225    let sig_path = write_temp_file_named(&signature, "git_vtag")?;
1226
1227    let verify_time = payload_committer_timestamp(&payload).map(verify_time_arg);
1228
1229    // 1. find-principals: which allowed principals can verify this signature?
1230    let mut find_args = vec![
1231        OsString::from("-Y"),
1232        OsString::from("find-principals"),
1233        OsString::from("-f"),
1234        OsString::from(allowed.as_str()),
1235        OsString::from("-s"),
1236        OsString::from(sig_path.to_string_lossy().as_ref()),
1237    ];
1238    if let Some(vt) = &verify_time {
1239        find_args.push(OsString::from(vt.as_str()));
1240    }
1241    let find_spec = CommandSpec {
1242        program: program.clone(),
1243        args: find_args,
1244        shell: None,
1245        cwd: None,
1246        env: CommandEnvironment::inherit_process_only(),
1247        stdin: CommandStdin::Null,
1248        stdout: CommandStdio::Pipe,
1249        stderr: CommandStdio::Pipe,
1250    };
1251    let find_out = signing_spawn(cfg, find_spec, None).inspect_err(|_| {
1252        let _ = std::fs::remove_file(&sig_path);
1253    })?;
1254
1255    let find_stdout = String::from_utf8_lossy(&find_out.stdout).into_owned();
1256    let find_stderr = String::from_utf8_lossy(&find_out.stderr).into_owned();
1257
1258    if !find_out.status.success && find_stderr.contains("usage:") {
1259        let _ = std::fs::remove_file(&sig_path);
1260        return Err(CommitError::signing_from_message(
1261            "ssh-keygen -Y find-principals/verify is needed for ssh signature verification (available in openssh version 8.2p1+)"
1262                .to_owned(),
1263        ).into());
1264    }
1265
1266    let mut verify_stdout = String::new();
1267    let mut verify_stderr = String::new();
1268    // Tracks Git's `ret` in verify_ssh_signed_buffer: true means failure.
1269    let mut verifier_failed;
1270
1271    if !find_out.status.success || find_stdout.trim().is_empty() {
1272        // No matching principal: run check-novalidate to surface signature info,
1273        // but treat as untrusted (Git forces ret = -1).
1274        let mut check_args = vec![
1275            OsString::from("-Y"),
1276            OsString::from("check-novalidate"),
1277            OsString::from("-n"),
1278            OsString::from("git"),
1279            OsString::from("-s"),
1280            OsString::from(sig_path.to_string_lossy().as_ref()),
1281        ];
1282        if let Some(vt) = &verify_time {
1283            check_args.push(OsString::from(vt.as_str()));
1284        }
1285        let (out, err) = run_with_stdin(cfg, &program, check_args, &payload);
1286        verify_stdout = out;
1287        verify_stderr = err;
1288        verifier_failed = true;
1289    } else {
1290        // Try each matched principal until one verifies as Good.
1291        verifier_failed = true;
1292        for principal in find_stdout.lines() {
1293            let principal = principal.trim_end_matches('\r');
1294            if principal.is_empty() {
1295                continue;
1296            }
1297            let mut verify_args = vec![
1298                OsString::from("-Y"),
1299                OsString::from("verify"),
1300                OsString::from("-n"),
1301                OsString::from("git"),
1302                OsString::from("-f"),
1303                OsString::from(allowed.as_str()),
1304                OsString::from("-I"),
1305                OsString::from(principal),
1306                OsString::from("-s"),
1307                OsString::from(sig_path.to_string_lossy().as_ref()),
1308            ];
1309            if let Some(vt) = &verify_time {
1310                verify_args.push(OsString::from(vt.as_str()));
1311            }
1312            if let Some(rev) = &cfg.ssh_revocation_file {
1313                if Path::new(rev).exists() {
1314                    verify_args.push(OsString::from("-r"));
1315                    verify_args.push(OsString::from(rev.as_str()));
1316                }
1317            }
1318            let (out, err, ok) = run_with_stdin_status(cfg, &program, verify_args, &payload);
1319            verify_stdout = out;
1320            verify_stderr = err;
1321            // Git: ret = !ok; if !ret { ret = !starts_with("Good"); }
1322            verifier_failed = !(ok && verify_stdout.starts_with("Good"));
1323            if !verifier_failed {
1324                break;
1325            }
1326        }
1327    }
1328
1329    let _ = std::fs::remove_file(&sig_path);
1330
1331    // Build sigc.output exactly as Git: stripspace the ssh stdout and stderr
1332    // (each non-empty line keeps a trailing newline), then append the
1333    // find-principals stderr and the verify/check stderr (gpg-interface.c
1334    // 601-608). The trailing newline left by stripspace keeps the `Good "..."`
1335    // line separate from any appended `No principal matched.` text so
1336    // parse_ssh_output sees a clean first line.
1337    let mut output = stripspace(&verify_stdout);
1338    let verify_stderr = stripspace(&verify_stderr);
1339    output.push_str(&find_stderr);
1340    output.push_str(&verify_stderr);
1341
1342    sigc.output = output;
1343    sigc.gpg_status = sigc.output.clone();
1344    parse_ssh_output(&mut sigc);
1345    // Git combines the verifier return code with the parsed result/trust; the
1346    // parse already drives result/trust, so just carry the verifier failure.
1347    sigc.verifier_failed = verifier_failed;
1348
1349    Ok(sigc)
1350}
1351
1352/// Run `program` with `args`, feeding `input` on stdin.
1353fn run_with_stdin(
1354    cfg: &GpgConfig,
1355    program: &Path,
1356    args: Vec<OsString>,
1357    input: &[u8],
1358) -> (String, String) {
1359    let (out, err, _ok) = run_with_stdin_status(cfg, program, args, input);
1360    (out, err)
1361}
1362
1363/// Like [`run_with_stdin`] but also returns whether the child exited zero.
1364fn run_with_stdin_status(
1365    cfg: &GpgConfig,
1366    program: &Path,
1367    args: Vec<OsString>,
1368    input: &[u8],
1369) -> (String, String, bool) {
1370    let spec = CommandSpec {
1371        program: program.to_path_buf(),
1372        args,
1373        shell: None,
1374        cwd: None,
1375        env: CommandEnvironment::inherit_process_only(),
1376        stdin: stdin_pipe(input),
1377        stdout: CommandStdio::Pipe,
1378        stderr: CommandStdio::Pipe,
1379    };
1380    match signing_spawn(cfg, spec, None) {
1381        Ok(o) => (
1382            String::from_utf8_lossy(&o.stdout).into_owned(),
1383            String::from_utf8_lossy(&o.stderr).into_owned(),
1384            o.status.success,
1385        ),
1386        Err(_) => (String::new(), String::new(), false),
1387    }
1388}
1389
1390/// Port of Git's `strbuf_stripspace` (without comment handling): trim trailing
1391/// whitespace from each line, collapse runs of blank lines to a single blank
1392/// line, and terminate every non-empty line with a single `\n`. The retained
1393/// trailing newline is what keeps the ssh `Good "..."` line separate from the
1394/// appended `No principal matched.` stderr.
1395fn stripspace(s: &str) -> String {
1396    let mut out = String::with_capacity(s.len());
1397    let mut pending_empties = 0usize;
1398    let mut wrote_any = false;
1399    for line in s.split('\n') {
1400        let trimmed = line.trim_end_matches([' ', '\t', '\r']);
1401        if trimmed.is_empty() {
1402            pending_empties += 1;
1403            continue;
1404        }
1405        if pending_empties > 0 && wrote_any {
1406            out.push('\n');
1407        }
1408        pending_empties = 0;
1409        out.push_str(trimmed);
1410        out.push('\n');
1411        wrote_any = true;
1412    }
1413    out
1414}
1415
1416/// Parse `[GNUPG:]` status lines into `sigc` (port of `parse_gpg_output`).
1417fn parse_gpg_output(sigc: &mut SignatureCheck, status: &str) {
1418    // (result-char, prefix, exclusive, keyid, uid, fingerprint, trust)
1419    struct Entry {
1420        result: Option<char>,
1421        check: &'static str,
1422        exclusive: bool,
1423        keyid: bool,
1424        uid: bool,
1425        fingerprint: bool,
1426        trust: bool,
1427    }
1428    const TABLE: &[Entry] = &[
1429        Entry {
1430            result: Some('G'),
1431            check: "GOODSIG ",
1432            exclusive: true,
1433            keyid: true,
1434            uid: true,
1435            fingerprint: false,
1436            trust: false,
1437        },
1438        Entry {
1439            result: Some('B'),
1440            check: "BADSIG ",
1441            exclusive: true,
1442            keyid: true,
1443            uid: true,
1444            fingerprint: false,
1445            trust: false,
1446        },
1447        Entry {
1448            result: Some('E'),
1449            check: "ERRSIG ",
1450            exclusive: true,
1451            keyid: true,
1452            uid: false,
1453            fingerprint: false,
1454            trust: false,
1455        },
1456        Entry {
1457            result: Some('X'),
1458            check: "EXPSIG ",
1459            exclusive: true,
1460            keyid: true,
1461            uid: true,
1462            fingerprint: false,
1463            trust: false,
1464        },
1465        Entry {
1466            result: Some('Y'),
1467            check: "EXPKEYSIG ",
1468            exclusive: true,
1469            keyid: true,
1470            uid: true,
1471            fingerprint: false,
1472            trust: false,
1473        },
1474        Entry {
1475            result: Some('R'),
1476            check: "REVKEYSIG ",
1477            exclusive: true,
1478            keyid: true,
1479            uid: true,
1480            fingerprint: false,
1481            trust: false,
1482        },
1483        Entry {
1484            result: None,
1485            check: "VALIDSIG ",
1486            exclusive: false,
1487            keyid: false,
1488            uid: false,
1489            fingerprint: true,
1490            trust: false,
1491        },
1492        Entry {
1493            result: None,
1494            check: "TRUST_",
1495            exclusive: false,
1496            keyid: false,
1497            uid: false,
1498            fingerprint: false,
1499            trust: true,
1500        },
1501    ];
1502
1503    let mut seen_exclusive = false;
1504
1505    for raw_line in status.lines() {
1506        let line = match raw_line.strip_prefix("[GNUPG:] ") {
1507            Some(l) => l,
1508            None => continue,
1509        };
1510
1511        for entry in TABLE {
1512            let rest = match line.strip_prefix(entry.check) {
1513                Some(r) => r,
1514                None => continue,
1515            };
1516
1517            if entry.exclusive {
1518                if seen_exclusive {
1519                    // Multiple exclusive statuses => multiple signatures: reject.
1520                    error_reset(sigc);
1521                    return;
1522                }
1523                seen_exclusive = true;
1524            }
1525
1526            if let Some(r) = entry.result {
1527                sigc.result = r;
1528            }
1529
1530            let mut cursor = rest;
1531
1532            if entry.keyid {
1533                let (key, after) = split_at_space(cursor);
1534                sigc.key = Some(key.to_owned());
1535                if entry.uid && !after.is_empty() {
1536                    // signer is the rest of the line.
1537                    let signer = after.split('\n').next().unwrap_or("");
1538                    sigc.signer = Some(signer.to_owned());
1539                }
1540            }
1541
1542            if entry.trust {
1543                let level: String = cursor
1544                    .chars()
1545                    .take_while(|&c| c != ' ' && c != '\n')
1546                    .collect();
1547                match TrustLevel::from_status(&level) {
1548                    Some(t) => sigc.trust_level = t,
1549                    None => {
1550                        error_reset(sigc);
1551                        return;
1552                    }
1553                }
1554            }
1555
1556            if entry.fingerprint {
1557                // VALIDSIG <fingerprint> ... <primary-fingerprint>
1558                let (fpr, mut after) = split_at_space(cursor);
1559                sigc.fingerprint = Some(fpr.to_owned());
1560                // Skip 9 interim fields to reach the primary fingerprint.
1561                cursor = after;
1562                let mut remaining = 9;
1563                while remaining > 0 && !cursor.is_empty() {
1564                    let (_, next) = split_at_space(cursor);
1565                    after = next;
1566                    if after.is_empty() {
1567                        break;
1568                    }
1569                    cursor = after;
1570                    remaining -= 1;
1571                }
1572                if remaining == 0 {
1573                    let primary = cursor.split('\n').next().unwrap_or("");
1574                    sigc.primary_key_fingerprint = Some(primary.to_owned());
1575                }
1576            }
1577
1578            break;
1579        }
1580    }
1581}
1582
1583/// Reset `sigc` to the error state, clearing partial fields.
1584fn error_reset(sigc: &mut SignatureCheck) {
1585    sigc.result = 'E';
1586    sigc.primary_key_fingerprint = None;
1587    sigc.fingerprint = None;
1588    sigc.signer = None;
1589    sigc.key = None;
1590}
1591
1592/// Split `s` at the first space, returning `(before, after_space)`.
1593fn split_at_space(s: &str) -> (&str, &str) {
1594    match s.find(' ') {
1595        Some(i) => (&s[..i], &s[i + 1..]),
1596        None => (s, ""),
1597    }
1598}
1599
1600/// Write `data` to a fresh temp file and return its path.
1601fn write_temp_file(data: &[u8]) -> crate::error::Result<PathBuf> {
1602    write_temp_file_named(data, "git_vtag")
1603}
1604
1605/// Build a fresh, reasonably unique temp path with the given name stem (without
1606/// creating the file).
1607fn temp_file_path(stem: &str) -> PathBuf {
1608    let dir = std::env::temp_dir();
1609    let unique = format!("{stem}_{}_{}", std::process::id(), next_temp_counter());
1610    dir.join(unique)
1611}
1612
1613/// Write `data` to a fresh temp file named with `stem` and return its path.
1614fn write_temp_file_named(data: &[u8], stem: &str) -> crate::error::Result<PathBuf> {
1615    let path = temp_file_path(stem);
1616    let mut f = std::fs::File::create(&path).map_err(|e| {
1617        CommitError::signing_from_message(format!("could not create temporary file: {e}"))
1618    })?;
1619    f.write_all(data).map_err(|e| {
1620        CommitError::signing_from_message(format!("failed writing to temporary file: {e}"))
1621    })?;
1622    Ok(path)
1623}
1624
1625/// Monotonic counter used to disambiguate temp file names within a process.
1626fn next_temp_counter() -> u64 {
1627    use std::sync::atomic::{AtomicU64, Ordering};
1628    static COUNTER: AtomicU64 = AtomicU64::new(0);
1629    let now = crate::git_date::tm::process_wall_clock_sec() as u64;
1630    now ^ COUNTER.fetch_add(1, Ordering::Relaxed)
1631}
1632
1633/// Build the committer-info default signing key (Git's
1634/// `git_committer_info(IDENT_STRICT | IDENT_NO_DATE)` — `"Name <email>"`).
1635///
1636/// `committer_ident` is a full ident line (`"Name <email> <ts> <tz>"`); this
1637/// trims the trailing timestamp/timezone.
1638pub fn committer_signing_default(committer_ident: &str) -> String {
1639    if let Some(angle_end) = committer_ident.find('>') {
1640        committer_ident[..=angle_end].to_owned()
1641    } else {
1642        committer_ident.to_owned()
1643    }
1644}
1645
1646/// Split a signed buffer (e.g. a tag object) into `(payload, signature)`.
1647///
1648/// Port of Git's `gpg-interface.c:parse_signed_buffer`/`parse_signature`: scans
1649/// the buffer line by line and records the offset of the *last* line that begins
1650/// a recognized signature armor ([`GpgFormat::from_signature`]).  The payload is
1651/// everything before that offset and the signature is everything from it to the
1652/// end.  Unlike commits, a signed tag appends the armored signature directly
1653/// after the tag body with no `gpgsig` header and no per-line indentation.
1654///
1655/// Returns `None` when no armor line is found (the buffer is unsigned).
1656pub fn parse_signed_buffer(buf: &[u8]) -> Option<(Vec<u8>, Vec<u8>)> {
1657    let size = buf.len();
1658    let mut len = 0usize;
1659    let mut matched: Option<usize> = None;
1660    while len < size {
1661        if GpgFormat::from_signature(&buf[len..]).is_some() {
1662            matched = Some(len);
1663        }
1664        let eol = memchr(buf, len, b'\n');
1665        len = match eol {
1666            Some(p) => p + 1,
1667            None => size,
1668        };
1669    }
1670    let m = matched?;
1671    Some((buf[..m].to_vec(), buf[m..].to_vec()))
1672}
1673
1674/// Verify a raw tag object's appended signature.
1675///
1676/// Mirrors [`verify_commit`] but uses [`parse_signed_buffer`] (tag signatures are
1677/// appended, not stored in a `gpgsig` header).  The verifier is chosen from the
1678/// signature armor (`get_format_by_sig`), reusing the internal `verify_ssh_signed_buffer` helper
1679/// for ssh and the gpg/gpgsm path otherwise.  Returns the "no signature" result
1680/// when the tag carries no signature.
1681pub fn verify_tag(cfg: &GpgConfig, raw_tag: &[u8]) -> crate::error::Result<SignatureCheck> {
1682    let (payload, signature) = match parse_signed_buffer(raw_tag) {
1683        Some(parts) => parts,
1684        None => return Ok(SignatureCheck::default_none()),
1685    };
1686
1687    let detected_format = GpgFormat::from_signature(&signature).unwrap_or(cfg.format);
1688
1689    if detected_format == GpgFormat::Ssh {
1690        return verify_ssh_signed_buffer(cfg, payload, signature);
1691    }
1692
1693    let program = resolve_program(&cfg.program_for(detected_format))?;
1694
1695    let sig_path = write_temp_file(&signature)?;
1696
1697    let mut args = vec![OsString::from("--status-fd=1")];
1698    for a in detected_format.verify_args() {
1699        args.push(OsString::from(a));
1700    }
1701    args.push(OsString::from("--verify"));
1702    args.push(OsString::from(sig_path.to_string_lossy().as_ref()));
1703    args.push(OsString::from("-"));
1704    let spec = CommandSpec {
1705        program: program.clone(),
1706        args,
1707        shell: None,
1708        cwd: None,
1709        env: CommandEnvironment::inherit_process_only(),
1710        stdin: stdin_pipe(&payload),
1711        stdout: CommandStdio::Pipe,
1712        stderr: CommandStdio::Pipe,
1713    };
1714
1715    let output = match signing_spawn(cfg, spec, None) {
1716        Ok(o) => o,
1717        Err(e) => {
1718            let _ = std::fs::remove_file(&sig_path);
1719            return Err(e);
1720        }
1721    };
1722    let _ = std::fs::remove_file(&sig_path);
1723
1724    let gpg_status = String::from_utf8_lossy(&output.stdout).into_owned();
1725    let human = String::from_utf8_lossy(&output.stderr).into_owned();
1726
1727    let mut sigc = SignatureCheck {
1728        signature,
1729        payload,
1730        result: 'N',
1731        trust_level: TrustLevel::Undefined,
1732        gpg_status: gpg_status.clone(),
1733        output: human,
1734        ..Default::default()
1735    };
1736
1737    parse_gpg_output(&mut sigc, &gpg_status);
1738
1739    Ok(sigc)
1740}
1741
1742#[cfg(test)]
1743mod tests {
1744    use super::*;
1745
1746    #[test]
1747    fn format_name_is_case_sensitive() {
1748        assert_eq!(GpgFormat::from_name("openpgp"), Some(GpgFormat::OpenPgp));
1749        assert_eq!(GpgFormat::from_name("x509"), Some(GpgFormat::X509));
1750        assert_eq!(GpgFormat::from_name("ssh"), Some(GpgFormat::Ssh));
1751        assert_eq!(GpgFormat::from_name("OpEnPgP"), None);
1752        assert_eq!(GpgFormat::from_name("OPENPGP"), None);
1753    }
1754
1755    #[test]
1756    fn add_header_signature_splices_gpgsig() {
1757        let commit = b"tree 0123\nparent 4567\nauthor a\ncommitter c\n\nmessage\n";
1758        let sig = b"-----BEGIN PGP SIGNATURE-----\nABC\n-----END PGP SIGNATURE-----\n";
1759        let out = add_header_signature(commit, sig, GPG_SIG_HEADER_SHA1);
1760        let text = String::from_utf8(out).unwrap();
1761        assert!(text.contains("\ncommitter c\ngpgsig -----BEGIN PGP SIGNATURE-----\n ABC\n -----END PGP SIGNATURE-----\n\nmessage\n"));
1762    }
1763
1764    #[test]
1765    fn extract_round_trips_signature() {
1766        let commit = b"tree 0123\nparent 4567\nauthor a\ncommitter c\n\nmessage\n";
1767        let sig = b"-----BEGIN PGP SIGNATURE-----\nABC\n-----END PGP SIGNATURE-----\n";
1768        let signed = add_header_signature(commit, sig, GPG_SIG_HEADER_SHA1);
1769        let (payload, extracted) = extract_signed_payload(&signed).unwrap();
1770        assert_eq!(payload, commit);
1771        assert_eq!(extracted, sig);
1772    }
1773
1774    #[test]
1775    fn extract_none_when_unsigned() {
1776        let commit = b"tree 0123\ncommitter c\n\nmsg\n";
1777        assert!(extract_signed_payload(commit).is_none());
1778    }
1779
1780    #[test]
1781    fn extra_headers_without_commit_signatures_drops_gpgsig_block() {
1782        let extra = b"mergetag foo\ngpgsig -----BEGIN PGP SIGNATURE-----\n ABC\n -----END PGP SIGNATURE-----\n";
1783        let stripped = extra_headers_without_commit_signatures(extra);
1784        assert_eq!(stripped, b"mergetag foo\n");
1785    }
1786
1787    #[test]
1788    fn parse_signed_buffer_splits_appended_tag_signature() {
1789        // A signed tag appends the armored signature directly after the body
1790        // with no `gpgsig` header and no per-line indentation.
1791        let body = b"object 0123\ntype commit\ntag v1\ntagger t <t@e> 1 +0000\n\nmessage\n";
1792        let sig = b"-----BEGIN SSH SIGNATURE-----\nAAAA\n-----END SSH SIGNATURE-----\n";
1793        let mut tag = body.to_vec();
1794        tag.extend_from_slice(sig);
1795        let (payload, signature) = parse_signed_buffer(&tag).expect("should split");
1796        assert_eq!(payload, body);
1797        assert_eq!(signature, sig);
1798    }
1799
1800    #[test]
1801    fn parse_signed_buffer_none_when_unsigned() {
1802        let body = b"object 0123\ntype commit\ntag v1\ntagger t <t@e> 1 +0000\n\nmessage\n";
1803        assert!(parse_signed_buffer(body).is_none());
1804    }
1805
1806    #[test]
1807    fn parse_goodsig_and_trust() {
1808        let status = "\
1809[GNUPG:] NEWSIG\n\
1810[GNUPG:] GOODSIG 73D758744BE721698EC54E8713D758744BE7216 C O Mitter <committer@example.com>\n\
1811[GNUPG:] VALIDSIG FINGERPRINT 2010-04-01 1270074988 0 4 0 17 2 00 PRIMARYFPR\n\
1812[GNUPG:] TRUST_ULTIMATE 0 pgp\n";
1813        let mut sigc = SignatureCheck::default_none();
1814        parse_gpg_output(&mut sigc, status);
1815        assert_eq!(sigc.result, 'G');
1816        assert_eq!(sigc.trust_level, TrustLevel::Ultimate);
1817        assert_eq!(
1818            sigc.signer.as_deref(),
1819            Some("C O Mitter <committer@example.com>")
1820        );
1821        assert_eq!(
1822            sigc.key.as_deref(),
1823            Some("73D758744BE721698EC54E8713D758744BE7216")
1824        );
1825        assert!(sigc.verify_status(None));
1826        assert!(sigc.verify_status(Some(TrustLevel::Ultimate)));
1827        assert!(sigc.verify_status(Some(TrustLevel::Marginal)));
1828    }
1829
1830    #[test]
1831    fn parse_badsig() {
1832        let status = "[GNUPG:] BADSIG KEYID Some Signer <s@example.com>\n";
1833        let mut sigc = SignatureCheck::default_none();
1834        parse_gpg_output(&mut sigc, status);
1835        assert_eq!(sigc.result, 'B');
1836        assert!(!sigc.is_good());
1837    }
1838
1839    #[test]
1840    fn double_exclusive_status_is_error() {
1841        let status = "[GNUPG:] GOODSIG K1 A <a@x>\n[GNUPG:] BADSIG K2 B <b@x>\n";
1842        let mut sigc = SignatureCheck::default_none();
1843        parse_gpg_output(&mut sigc, status);
1844        assert_eq!(sigc.result, 'E');
1845    }
1846
1847    #[test]
1848    fn min_trust_level_from_config_is_case_insensitive() {
1849        assert_eq!(
1850            TrustLevel::from_config("marginal"),
1851            Some(TrustLevel::Marginal)
1852        );
1853        assert_eq!(TrustLevel::from_config("FULLY"), Some(TrustLevel::Fully));
1854        assert_eq!(TrustLevel::from_config("bogus"), None);
1855    }
1856
1857    #[test]
1858    fn format_detected_from_signature_armor() {
1859        assert_eq!(
1860            GpgFormat::from_signature(b"-----BEGIN SSH SIGNATURE-----\nABC\n"),
1861            Some(GpgFormat::Ssh)
1862        );
1863        assert_eq!(
1864            GpgFormat::from_signature(b"-----BEGIN PGP SIGNATURE-----\n"),
1865            Some(GpgFormat::OpenPgp)
1866        );
1867        assert_eq!(
1868            GpgFormat::from_signature(b"-----BEGIN PGP MESSAGE-----\n"),
1869            Some(GpgFormat::OpenPgp)
1870        );
1871        assert_eq!(
1872            GpgFormat::from_signature(b"-----BEGIN SIGNED MESSAGE-----\n"),
1873            Some(GpgFormat::X509)
1874        );
1875        assert_eq!(GpgFormat::from_signature(b"garbage"), None);
1876    }
1877
1878    #[test]
1879    fn should_sign_commit_honors_override_and_config() {
1880        let mut cfg = ConfigSet::default();
1881        assert!(!should_sign_commit(&cfg, None).unwrap());
1882        assert!(should_sign_commit(&cfg, Some(true)).unwrap());
1883        assert!(!should_sign_commit(&cfg, Some(false)).unwrap());
1884
1885        cfg.add_command_override("commit.gpgsign", "true").unwrap();
1886        assert!(should_sign_commit(&cfg, None).unwrap());
1887        assert!(!should_sign_commit(&cfg, Some(false)).unwrap());
1888    }
1889
1890    #[test]
1891    fn should_sign_tag_honors_override_and_config() {
1892        let mut cfg = ConfigSet::default();
1893        assert!(!should_sign_tag(&cfg, None).unwrap());
1894        assert!(should_sign_tag(&cfg, Some(true)).unwrap());
1895        assert!(!should_sign_tag(&cfg, Some(false)).unwrap());
1896
1897        cfg.add_command_override("tag.gpgSign", "true").unwrap();
1898        assert!(should_sign_tag(&cfg, None).unwrap());
1899        assert!(!should_sign_tag(&cfg, Some(false)).unwrap());
1900    }
1901
1902    #[test]
1903    fn should_sign_rejects_a_non_boolean_naming_the_key() {
1904        let mut cfg = ConfigSet::default();
1905        cfg.add_command_override("tag.gpgsign", "sometimes")
1906            .unwrap();
1907        let err = should_sign_tag(&cfg, None).unwrap_err();
1908        assert!(matches!(
1909            err,
1910            Error::Config(crate::error::ConfigError::InvalidValue { ref key, .. }) if key == "tag.gpgSign"
1911        ));
1912        assert!(should_sign_tag(&cfg, Some(true)).unwrap());
1913    }
1914
1915    #[test]
1916    fn append_tag_signature_concatenates_armor() {
1917        let body = b"object 0\ntype commit\ntag v1\ntagger t <t@e> 1 +0000\n\nmsg\n";
1918        let sig = b"-----BEGIN SSH SIGNATURE-----\nX\n-----END SSH SIGNATURE-----\n";
1919        let out = append_tag_signature(body, sig);
1920        assert_eq!(out.len(), body.len() + sig.len());
1921        assert_eq!(&out[..body.len()], body);
1922        assert_eq!(&out[body.len()..], sig);
1923    }
1924
1925    #[test]
1926    fn committer_signing_default_strips_timestamp() {
1927        assert_eq!(
1928            committer_signing_default("T <t@example.com> 1700000000 +0000"),
1929            "T <t@example.com>"
1930        );
1931    }
1932
1933    #[test]
1934    fn resolve_signing_key_uses_no_date_committer_default() {
1935        let cfg = GpgConfig::from_config(&ConfigSet::default()).expect("gpg config");
1936        let key = cfg.resolve_signing_key(
1937            None,
1938            &committer_signing_default("T <t@example.com> 1700000000 +0000"),
1939        );
1940        assert_eq!(key, "T <t@example.com>");
1941    }
1942
1943    #[test]
1944    fn literal_ssh_key_detection() {
1945        assert_eq!(
1946            is_literal_ssh_key("key::ssh-ed25519 AAAA"),
1947            Some("ssh-ed25519 AAAA")
1948        );
1949        assert_eq!(
1950            is_literal_ssh_key("ssh-ed25519 AAAA"),
1951            Some("ssh-ed25519 AAAA")
1952        );
1953        assert_eq!(is_literal_ssh_key("/home/u/.ssh/id_ed25519"), None);
1954    }
1955
1956    #[test]
1957    fn parse_ssh_output_trusted_principal() {
1958        let mut sigc = SignatureCheck::default_none();
1959        sigc.output =
1960            "Good \"git\" signature for principal with number 1 with ED25519 key SHA256:ABC\n"
1961                .to_owned();
1962        parse_ssh_output(&mut sigc);
1963        assert_eq!(sigc.result, 'G');
1964        assert_eq!(sigc.trust_level, TrustLevel::Fully);
1965        assert_eq!(sigc.signer.as_deref(), Some("principal with number 1"));
1966        assert_eq!(sigc.key.as_deref(), Some("SHA256:ABC"));
1967        assert_eq!(sigc.fingerprint.as_deref(), Some("SHA256:ABC"));
1968        assert!(sigc.primary_key_fingerprint.is_none());
1969    }
1970
1971    #[test]
1972    fn parse_ssh_output_untrusted_unknown_key() {
1973        let mut sigc = SignatureCheck::default_none();
1974        // The trailing `No principal matched.` is appended on its own line by
1975        // stripspace; only the first line should be parsed.
1976        sigc.output = "Good \"git\" signature with ED25519 key SHA256:XYZ\nNo principal matched.\n"
1977            .to_owned();
1978        parse_ssh_output(&mut sigc);
1979        assert_eq!(sigc.result, 'G');
1980        assert_eq!(sigc.trust_level, TrustLevel::Undefined);
1981        assert!(sigc.signer.is_none());
1982        assert_eq!(sigc.key.as_deref(), Some("SHA256:XYZ"));
1983        assert_eq!(sigc.fingerprint.as_deref(), Some("SHA256:XYZ"));
1984    }
1985
1986    #[test]
1987    fn parse_ssh_output_bad_signature() {
1988        let mut sigc = SignatureCheck::default_none();
1989        sigc.output = "Signature verification failed: incorrect signature\n".to_owned();
1990        parse_ssh_output(&mut sigc);
1991        assert_eq!(sigc.result, 'B');
1992        assert_eq!(sigc.trust_level, TrustLevel::Never);
1993        assert!(sigc.key.is_none());
1994    }
1995
1996    #[test]
1997    fn stripspace_keeps_line_terminators() {
1998        // Each non-empty line keeps a trailing newline; trailing blanks dropped.
1999        assert_eq!(stripspace("Good ... SHA256:FPR\n"), "Good ... SHA256:FPR\n");
2000        assert_eq!(stripspace("a  \n\n\nb\n\n"), "a\n\nb\n");
2001        assert_eq!(stripspace(""), "");
2002        // Concatenating a stripspaced line with following stderr keeps them on
2003        // separate lines.
2004        let mut out = stripspace("Good ... SHA256:FPR\n");
2005        out.push_str("No principal matched.\n");
2006        assert_eq!(out.lines().next(), Some("Good ... SHA256:FPR"));
2007    }
2008
2009    #[test]
2010    fn payload_committer_timestamp_parsed() {
2011        let payload =
2012            b"tree 0123\nauthor A <a@x> 1112912173 -0700\ncommitter C <c@x> 1112912273 +0200\n\nmsg\n";
2013        assert_eq!(payload_committer_timestamp(payload), Some(1112912273));
2014        // Falls back to tagger for tag payloads.
2015        let tag = b"object 0123\ntype commit\ntag v1\ntagger T <t@x> 1112912000 -0500\n\nmsg\n";
2016        assert_eq!(payload_committer_timestamp(tag), Some(1112912000));
2017        // No ident header.
2018        assert_eq!(payload_committer_timestamp(b"tree 0123\n\nmsg\n"), None);
2019    }
2020}