Skip to main content

gix_object/signature/
mod.rs

1//! Discover, sign, and verify Git object signatures.
2
3use std::ops::Range;
4
5use bstr::{BStr, BString, ByteSlice};
6use gix_error::Result;
7
8/// Object signing with external-program options.
9#[cfg(feature = "signature")]
10pub mod sign;
11/// Object signature verification with external-program options.
12#[cfg(feature = "signature")]
13pub mod verify;
14
15#[cfg(feature = "signature")]
16fn ssh_path_argument(path: &std::path::Path) -> Result<std::path::PathBuf> {
17    // The mixed `C:/…` form works with native Windows and Git for Windows' MSYS OpenSSH.
18    gix_path::from_bstring(gix_path::to_unix_separators_on_windows(gix_path::into_bstr(path)?).into_owned())
19}
20
21/// A borrowed armored signature and its detected format.
22#[derive(Clone, Copy, Debug, Eq, PartialEq)]
23pub struct SignatureRef<'a> {
24    /// The signature format detected from the armor marker.
25    pub format: Format,
26    /// The complete armored signature, from its marker through end of object.
27    pub data: &'a BStr,
28}
29
30/// Exact object bytes covered by a [signature](SignatureRef).
31#[derive(PartialEq, Eq, Debug, Hash, Clone)]
32#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
33pub struct SignedData<'a> {
34    data: &'a [u8],
35    excluded: Range<usize>,
36}
37
38impl<'a> SignedData<'a> {
39    pub(crate) fn new(data: &'a [u8], excluded: Range<usize>) -> Self {
40        SignedData { data, excluded }
41    }
42
43    pub(crate) fn segments(&self) -> [&[u8]; 2] {
44        [&self.data[..self.excluded.start], &self.data[self.excluded.end..]]
45    }
46
47    /// Return an exact copy of the bytes covered by the signature.
48    pub fn to_bstring(&self) -> BString {
49        let [before, after] = self.segments();
50        let mut out = BString::from(before);
51        out.extend_from_slice(after);
52        out
53    }
54}
55
56impl From<SignedData<'_>> for BString {
57    fn from(value: SignedData<'_>) -> Self {
58        value.to_bstring()
59    }
60}
61
62/// Find the last supported armor marker at a line boundary, matching Git's `parse_signed_buffer()`.
63pub(crate) fn find(data: &[u8]) -> Option<(usize, Format)> {
64    let mut found = None;
65    let mut offset = 0;
66    while offset < data.len() {
67        if let Some(format) = Format::from_signature(&data[offset..]) {
68            found = Some((offset, format));
69        }
70        offset = data[offset..]
71            .find_byte(b'\n')
72            .map_or(data.len(), |newline| offset + newline + 1);
73    }
74    found
75}
76
77/// A Git-supported signature format.
78#[derive(Clone, Copy, Debug, Eq, PartialEq)]
79pub enum Format {
80    /// An OpenPGP signature made with `gpg` by default.
81    OpenPgp,
82    /// An X.509 signature made with `gpgsm` by default.
83    X509,
84    /// An SSH signature made with `ssh-keygen` by default.
85    Ssh,
86}
87
88impl Format {
89    /// Parse a case-insensitive format name, ignoring surrounding whitespace.
90    /// Unknown names are unsupported; empty or malformed names are validation failures.
91    pub fn parse(value: &BStr) -> Result<Self> {
92        use gix_error::{bail, validation};
93
94        let trimmed = value.trim();
95        if trimmed.eq_ignore_ascii_case(b"openpgp") {
96            Ok(Self::OpenPgp)
97        } else if trimmed.eq_ignore_ascii_case(b"x509") {
98            Ok(Self::X509)
99        } else if trimmed.eq_ignore_ascii_case(b"ssh") {
100            Ok(Self::Ssh)
101        } else {
102            let error = validation("Unsupported signature format").with_input(value);
103            let is_format_name = !trimmed.is_empty()
104                && trimmed
105                    .iter()
106                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'));
107            bail!(if is_format_name { error.unsupported() } else { error });
108        }
109    }
110
111    /// Detect the format from the signature's armor header, or return `None` if it is unsupported.
112    pub fn from_signature(signature: &[u8]) -> Option<Self> {
113        if signature.starts_with(b"-----BEGIN PGP SIGNATURE-----")
114            || signature.starts_with(b"-----BEGIN PGP MESSAGE-----")
115        {
116            Some(Format::OpenPgp)
117        } else if signature.starts_with(b"-----BEGIN SIGNED MESSAGE-----") {
118            Some(Format::X509)
119        } else if signature.starts_with(b"-----BEGIN SSH SIGNATURE-----") {
120            Some(Format::Ssh)
121        } else {
122            None
123        }
124    }
125}