gix_object/signature/
mod.rs1use std::ops::Range;
4
5use bstr::{BStr, BString, ByteSlice};
6use gix_error::Result;
7
8#[cfg(feature = "signature")]
10pub mod sign;
11#[cfg(feature = "signature")]
13pub mod verify;
14
15#[cfg(feature = "signature")]
16fn ssh_path_argument(path: &std::path::Path) -> Result<std::path::PathBuf> {
17 gix_path::from_bstring(gix_path::to_unix_separators_on_windows(gix_path::into_bstr(path)?).into_owned())
19}
20
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
23pub struct SignatureRef<'a> {
24 pub format: Format,
26 pub data: &'a BStr,
28}
29
30#[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 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
62pub(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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
79pub enum Format {
80 OpenPgp,
82 X509,
84 Ssh,
86}
87
88impl Format {
89 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 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}