Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Use git verify-commit for signature checks
Git log's %G? can report N for a signed commit when GPG is missing or
SSH verification is not configured, while a missing GPG public key
produces E. These codes do not reliably distinguish unsigned commits
from verification setup failures, and bulk stderr cannot be attributed
to individual commits.

Use git verify-commit for each commit and follow its exit status and
local Git verification policy. Report stderr below the affected commit,
with bounded concurrency that preserves the commit listing order.

Remove the status allow-list and empty argument parser, centralize the
push range environment constants, and cover verifier failures and real
SSH signatures in integration tests.
  • Loading branch information
j178 committed Oct 8, 2026
commit 73be1fff1b525e106dcef840b5067a0ec0406b19
4 changes: 4 additions & 0 deletions crates/prek-consts/src/env_vars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ impl EnvVars {

pub const SKIP: &'static str = "SKIP";

// Revision range passed to hooks
pub const PRE_COMMIT_FROM_REF: &'static str = "PRE_COMMIT_FROM_REF";
pub const PRE_COMMIT_TO_REF: &'static str = "PRE_COMMIT_TO_REF";

// PREK specific environment variables, public for users
pub const PREK_HOME: &'static str = "PREK_HOME";
pub const PREK_COLOR: &'static str = "PREK_COLOR";
Expand Down
4 changes: 2 additions & 2 deletions crates/prek/src/cli/run/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -376,11 +376,11 @@ fn set_env_vars(from_ref: Option<&str>, to_ref: Option<&str>, args: &RunExtraArg
}
if let Some(from_ref) = from_ref {
std::env::set_var("PRE_COMMIT_ORIGIN", from_ref);
std::env::set_var("PRE_COMMIT_FROM_REF", from_ref);
std::env::set_var(EnvVars::PRE_COMMIT_FROM_REF, from_ref);
}
if let Some(to_ref) = to_ref {
std::env::set_var("PRE_COMMIT_SOURCE", to_ref);
std::env::set_var("PRE_COMMIT_TO_REF", to_ref);
std::env::set_var(EnvVars::PRE_COMMIT_TO_REF, to_ref);
}
if let Some(upstream) = &args.pre_rebase_upstream {
std::env::set_var("PRE_COMMIT_PRE_REBASE_UPSTREAM", upstream);
Expand Down
300 changes: 45 additions & 255 deletions crates/prek/src/hooks/builtin_hooks/check_signed_commit.rs
Original file line number Diff line number Diff line change
@@ -1,122 +1,68 @@
use std::fmt::Write as _;
use std::io::Write as _;

use anyhow::Result;
use clap::Parser;
use anyhow::{Context, Result};
use futures_util::StreamExt;
use prek_consts::env_vars::{EnvVars, EnvVarsRead};

use crate::git;
use crate::hook::Hook;
use crate::hooks::HookOutput;
use crate::hooks::pre_commit_hooks::parse_hook_args;

/// Git's per-commit signature status, as reported by `%G?` in `git log`/`git show`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SignatureStatus {
Good,
Bad,
GoodUnknownValidity,
ExpiredGood,
ExpiredKey,
RevokedKey,
CannotCheck,
NoSignature,
}

impl SignatureStatus {
fn from_code(code: &str) -> Option<Self> {
match code {
"G" => Some(Self::Good),
"B" => Some(Self::Bad),
"U" => Some(Self::GoodUnknownValidity),
"X" => Some(Self::ExpiredGood),
"Y" => Some(Self::ExpiredKey),
"R" => Some(Self::RevokedKey),
"E" => Some(Self::CannotCheck),
"N" => Some(Self::NoSignature),
_ => None,
}
}

fn code(self) -> &'static str {
match self {
Self::Good => "G",
Self::Bad => "B",
Self::GoodUnknownValidity => "U",
Self::ExpiredGood => "X",
Self::ExpiredKey => "Y",
Self::RevokedKey => "R",
Self::CannotCheck => "E",
Self::NoSignature => "N",
}
}

fn description(self) -> &'static str {
match self {
Self::Good => "good signature",
Self::Bad => "bad signature",
Self::GoodUnknownValidity => "good signature, unknown validity (untrusted)",
Self::ExpiredGood => "good signature, but expired",
Self::ExpiredKey => "good signature, made with an expired key",
Self::RevokedKey => "good signature, made with a revoked key",
Self::CannotCheck => "signature cannot be checked, e.g. missing public key",
Self::NoSignature => "no signature",
}
}
}

fn parse_allow_status(value: &str) -> Result<SignatureStatus, String> {
SignatureStatus::from_code(&value.to_ascii_uppercase()).ok_or_else(|| {
format!("invalid status code `{value}`, expected one of: G, B, U, X, Y, R, E, N")
})
}

#[derive(Parser)]
#[command(disable_help_subcommand = true)]
#[command(disable_version_flag = true)]
#[command(disable_help_flag = true)]
pub(crate) struct Args {
/// Signature status code to accept (repeatable): G, B, U, X, Y, R, E, or N.
#[arg(
long = "allow-status",
value_name = "CODE",
value_parser = parse_allow_status,
default_values = &["G", "U"]
)]
allow_status: Vec<SignatureStatus>,
}
use crate::run::INTERNAL_CONCURRENCY;

/// Runs the `check-signed-commit` hook.
pub(crate) async fn run(hook: &Hook) -> Result<HookOutput> {
let args: Args = parse_hook_args(hook)?;

let Some(range) = resolve_range().await? else {
return Ok(HookOutput::unchanged(0, Vec::new()));
};

let output = git::git_cmd()?
.current_dir(hook.work_dir())
.arg("log")
.arg("--no-merges")
.arg("-z")
.arg("--pretty=format:%h\u{1f}%G?\u{1f}%s")
.args([
"log",
"--no-merges",
"--no-show-signature",
"-z",
"--pretty=format:%H %h %s",
])
.arg(range)
Comment thread
j178 marked this conversation as resolved.
Resolved
.check(true)
.output()
.await?;

let offending: Vec<SignedCommit> = parse_signed_commits(&output.stdout)
.into_iter()
.filter(|commit| !args.allow_status.contains(&commit.status))
.collect();
let commits = String::from_utf8_lossy(&output.stdout);
let mut checks =
futures_util::stream::iter(commits.split('\0').filter(|record| !record.is_empty()))
.map(|record| async move {
let (oid, summary) = record
.split_once(' ')
.context("Invalid commit information from Git")?;
// Verify separately so each diagnostic belongs to a specific commit.
let output = git::git_cmd()?
.current_dir(hook.work_dir())
.args(["verify-commit", oid])
.check(false)
.output()
.await
.with_context(|| format!("Failed to verify commit {oid}"))?;
anyhow::Ok((summary, output))
})
.buffered(*INTERNAL_CONCURRENCY);

let mut failed = false;
let mut message = output.stderr;
if !offending.is_empty() {
message.extend_from_slice(render_message(&offending).as_bytes());
while let Some(result) = checks.next().await {
let (summary, output) = result?;
if output.status.success() {
continue;
}

failed = true;
writeln!(message, "{summary}: signature verification failed")?;
for line in String::from_utf8_lossy(&output.stderr).trim_end().lines() {
writeln!(message, " {line}")?;
}
}
Ok(HookOutput::unchanged(
i32::from(!offending.is_empty()),
message,
))

Ok(HookOutput::unchanged(i32::from(failed), message))
}

/// Resolve the commit range to check.
Expand All @@ -125,8 +71,8 @@ pub(crate) async fn run(hook: &Hook) -> Result<HookOutput> {
/// normal `pre-push` invocation). Otherwise falls back to just `HEAD`, so the hook still does
/// something useful when run manually (`prek run check-signed-commit --hook-stage manual`).
async fn resolve_range() -> Result<Option<String>> {
let from_ref = EnvVars.var("PRE_COMMIT_FROM_REF").ok();
let to_ref = EnvVars.var("PRE_COMMIT_TO_REF").ok();
let from_ref = EnvVars.var(EnvVars::PRE_COMMIT_FROM_REF).ok();
let to_ref = EnvVars.var(EnvVars::PRE_COMMIT_TO_REF).ok();

if let Some(to_ref) = to_ref {
return Ok(Some(match from_ref {
Expand All @@ -144,159 +90,3 @@ async fn resolve_range() -> Result<Option<String>> {

Ok(Some("HEAD^!".to_string()))
}

struct SignedCommit {
hash: String,
status: SignatureStatus,
subject: String,
}

/// Parse NUL-separated `<hash>\x1f<status-code>\x1f<subject>` records from `git log`.
fn parse_signed_commits(stdout: &[u8]) -> Vec<SignedCommit> {
stdout
.split(|&b| b == b'\0')
.filter_map(|record| {
let record = String::from_utf8_lossy(record);
let mut fields = record.splitn(3, '\u{1f}');
let hash = fields.next()?;
let code = fields.next()?;
let subject = fields.next()?;
Some(SignedCommit {
hash: hash.to_string(),
status: SignatureStatus::from_code(code)?,
subject: subject.to_string(),
})
})
.collect()
}

fn render_message(offending: &[SignedCommit]) -> String {
let mut message = String::new();
for commit in offending {
writeln!(
message,
"{} [{}] {}: {}",
commit.hash,
commit.status.code(),
commit.status.description(),
commit.subject
)
.expect("writing to String should never fail");
}

message.push('\n');
message.push_str(indoc::indoc! {"
Commit signature status codes:
G good signature
B bad signature
U good signature, unknown validity (untrusted)
X good signature, but expired
Y good signature, made with an expired key
R good signature, made with a revoked key
E signature cannot be checked, e.g. missing public key
N no signature

Pass `--allow-status <CODE>` (repeatable) to replace the allowed status codes (default: G, U).
"});

message
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn signature_status_round_trips_known_codes() {
for code in ["G", "B", "U", "X", "Y", "R", "E", "N"] {
let status = SignatureStatus::from_code(code).unwrap();
assert_eq!(status.code(), code);
}
}

#[test]
fn signature_status_rejects_unknown_code() {
assert!(SignatureStatus::from_code("?").is_none());
assert!(SignatureStatus::from_code("").is_none());
assert!(SignatureStatus::from_code("g").is_none());
}

#[test]
fn parse_allow_status_accepts_lowercase() {
assert_eq!(parse_allow_status("g"), Ok(SignatureStatus::Good));
}

#[test]
fn parse_allow_status_rejects_unknown_code() {
let err = parse_allow_status("Q").unwrap_err();
assert_eq!(
err,
"invalid status code `Q`, expected one of: G, B, U, X, Y, R, E, N"
);
}

#[test]
fn args_default_to_good_and_untrusted() {
let args = Args::try_parse_from(["check-signed-commit"]).unwrap();
assert_eq!(
args.allow_status,
vec![SignatureStatus::Good, SignatureStatus::GoodUnknownValidity]
);
}

#[test]
fn args_allow_status_is_repeatable_and_overrides_defaults() {
let args = Args::try_parse_from([
"check-signed-commit",
"--allow-status",
"N",
"--allow-status",
"E",
])
.unwrap();
assert_eq!(
args.allow_status,
vec![SignatureStatus::NoSignature, SignatureStatus::CannotCheck]
);
}

#[test]
fn parse_signed_commits_reads_multiple_nul_separated_records() {
let stdout = b"abc123\x1fG\x1ffirst commit\0def456\x1fN\x1fsecond commit\0";

let commits = parse_signed_commits(stdout);

assert_eq!(commits.len(), 2);
assert_eq!(commits[0].hash, "abc123");
assert_eq!(commits[0].status, SignatureStatus::Good);
assert_eq!(commits[0].subject, "first commit");
assert_eq!(commits[1].hash, "def456");
assert_eq!(commits[1].status, SignatureStatus::NoSignature);
assert_eq!(commits[1].subject, "second commit");
}

#[test]
fn parse_signed_commits_ignores_malformed_records() {
let stdout = b"onlyhash\0abc123\x1fZ\x1funknown status code\0def456\x1fG\x1fgood\0";

let commits = parse_signed_commits(stdout);

assert_eq!(commits.len(), 1);
assert_eq!(commits[0].hash, "def456");
}

#[test]
fn render_message_lists_each_offending_commit_and_a_legend() {
let offending = vec![SignedCommit {
hash: "abc123".to_string(),
status: SignatureStatus::NoSignature,
subject: "oops".to_string(),
}];

let message = render_message(&offending);

assert!(message.contains("abc123 [N] no signature: oops"));
assert!(message.contains("Commit signature status codes:"));
assert!(message.contains("--allow-status"));
}
}
1 change: 0 additions & 1 deletion crates/prek/src/hooks/builtin_hooks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ impl BuiltinHooks {
Self::CheckAddedLargeFiles => check_added_large_files::Args::command(),
Self::CheckJsonc => check_jsonc::Args::command(),
Self::CheckMergeConflict => check_merge_conflict::Args::command(),
Self::CheckSignedCommit => check_signed_commit::Args::command(),
Self::CheckVcsPermalinks => check_vcs_permalinks::Args::command(),
Self::CheckYaml => check_yaml::Args::command(),
Self::DenyFilenamePattern | Self::RequireFilenamePattern => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ use crate::hooks::pre_commit_hooks::{FilenamesArgs, hook_filenames, parse_hook_a
pub(crate) async fn run(hook: &Hook, filenames: &[&Path]) -> Result<HookOutput, anyhow::Error> {
let args: FilenamesArgs = parse_hook_args(hook)?;
let diff_arg = if let (Ok(from_ref), Ok(to_ref)) = (
EnvVars.var("PRE_COMMIT_FROM_REF"),
EnvVars.var("PRE_COMMIT_TO_REF"),
EnvVars.var(EnvVars::PRE_COMMIT_FROM_REF),
EnvVars.var(EnvVars::PRE_COMMIT_TO_REF),
) {
Cow::Owned(format!("{from_ref}...{to_ref}"))
} else {
Expand Down
Loading
Loading
⌂ 换网址