Skip to main content

signstar_common/
request_api.rs

1//! Types related to Signstar requests and responses.
2
3use std::{
4    array::TryFromSliceError,
5    collections::HashMap,
6    fmt::Display,
7    fs::File,
8    io::{Read, Write, copy},
9    path::{Path, PathBuf},
10    time::SystemTime,
11};
12
13use base64ct::{Base64, Encoding as _};
14use digest_io::IoWrapper;
15use rand::{RngExt, distr::Alphanumeric, rng};
16use semver::Version;
17use serde::{Deserialize, Serialize};
18use serde_json::{Value, from_reader, to_writer};
19// Publicly re-export the central hasher for all consumers.
20pub use sha2::Sha512;
21use sha2::{
22    Digest,
23    digest::common::hazmat::{DeserializeStateError, SerializableState},
24};
25
26use crate::backend::BackendType;
27
28/// Signature request processing error.
29#[derive(Debug, thiserror::Error)]
30pub enum Error {
31    /// System time error that occurs when the current time is before the reference time.
32    #[error("Current time is before reference time {reference_time:?}: {source}")]
33    CurrentTimeBeforeReference {
34        /// The reference time.
35        reference_time: SystemTime,
36
37        /// The error source.
38        source: std::time::SystemTimeError,
39    },
40
41    /// Deserialization of the hasher state failed.
42    #[error("Deserialization of the hasher state failed: {0}")]
43    HasherDeserialization(#[from] DeserializeStateError),
44
45    /// The internal content provided to a hasher is of wrong size.
46    #[error("The content size ({size} bytes) provided to the hasher is misaligned: {source}")]
47    HasherMisalignedSize {
48        /// The size of the content in bytes.
49        size: usize,
50
51        /// The error source.
52        source: TryFromSliceError,
53    },
54
55    /// Invalid content type.
56    #[error("Invalid content type. Found {actual:?} but expected {expected:?}.")]
57    InvalidContentType {
58        /// The content type that was found.
59        actual: HashType,
60
61        /// The content type that was expected.
62        expected: HashType,
63    },
64
65    /// An I/O error occurred.
66    #[error("I/O error while {context}: {source}")]
67    Io {
68        /// The context in which the error occurred.
69        ///
70        /// This is meant to complete the sentence "I/O error at path {path} while ".
71        context: String,
72
73        /// The error source.
74        source: std::io::Error,
75    },
76
77    /// An I/O error occurred at a specific path.
78    #[error("I/O error at path {path} while {context}: {source}")]
79    IoPath {
80        /// The path where the I/O error occurred.
81        path: PathBuf,
82
83        /// The context in which the error occurred.
84        ///
85        /// This is meant to complete the sentence "I/O error at path {path} while ".
86        context: String,
87
88        /// The error source.
89        source: std::io::Error,
90    },
91
92    /// Request deserialization failed.
93    #[error("Could not deserialize request: {source}")]
94    RequestDeserialization {
95        /// The error source.
96        source: serde_json::Error,
97    },
98
99    /// Request serialization failed.
100    #[error("Could not serialize request: {source}")]
101    RequestSerialization {
102        /// The error source.
103        source: serde_json::Error,
104    },
105
106    /// Response deserialization failed.
107    #[error("Could not deserialize response: {source}")]
108    ResponseDeserialization {
109        /// The error source.
110        source: serde_json::Error,
111    },
112
113    /// Response serialization failed.
114    #[error("Could not serialize response: {source}")]
115    ResponseSerialization {
116        /// The error source.
117        source: serde_json::Error,
118    },
119}
120
121/// Type of the input hash.
122#[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
123#[serde(rename_all = "lowercase")]
124pub enum HashType {
125    /// State of the SHA-512 hasher, as understood by the [`sha2`
126    /// crate](https://crates.io/crates/sha2) in version `0.11` and
127    /// compatible.
128    #[serde(rename = "sha2-0.11-SHA512-state")]
129    #[expect(
130        non_camel_case_types,
131        reason = "Rust suggested casing (Sha2_0_11Sha512State) is unreadable"
132    )]
133    Sha2_0_11_Sha512_State,
134}
135
136/// The requested signature type.
137#[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
138pub enum SignatureType {
139    /// OpenPGP signature (version 4).
140    #[serde(rename = "OpenPGPv4")]
141    OpenPgpV4,
142}
143
144/// Input of the signing request process.
145#[derive(Debug, Deserialize, Serialize)]
146pub struct SignatureRequestInput {
147    #[serde(rename = "type")]
148    hash_type: HashType,
149    content: Vec<u8>,
150}
151
152/// Outputs of the signing process.
153#[derive(Debug, Deserialize, Serialize)]
154pub struct SignatureRequestOutput {
155    /// Type of the signature to be produced.
156    #[serde(rename = "type")]
157    sig_type: SignatureType,
158}
159
160impl SignatureRequestOutput {
161    /// Create a new signature output which asks for OpenPGP (version
162    /// 4) signature.
163    pub fn new_openpgp_v4() -> Self {
164        Self {
165            sig_type: SignatureType::OpenPgpV4,
166        }
167    }
168
169    /// Indicates if the signature output should be OpenPGP (version
170    /// 4).
171    pub fn is_openpgp_v4(&self) -> bool {
172        self.sig_type == SignatureType::OpenPgpV4
173    }
174}
175
176impl From<Sha512> for SignatureRequestInput {
177    fn from(value: Sha512) -> Self {
178        Self {
179            hash_type: HashType::Sha2_0_11_Sha512_State,
180            content: value.serialize().to_vec(),
181        }
182    }
183}
184
185impl TryFrom<SignatureRequestInput> for Sha512 {
186    type Error = crate::Error;
187
188    fn try_from(value: SignatureRequestInput) -> Result<Self, Self::Error> {
189        if value.hash_type != HashType::Sha2_0_11_Sha512_State {
190            return Err(Error::InvalidContentType {
191                actual: value.hash_type,
192                expected: HashType::Sha2_0_11_Sha512_State,
193            }
194            .into());
195        }
196
197        let hasher = Sha512::deserialize(value.content[..].try_into().map_err(|source| {
198            Error::HasherMisalignedSize {
199                size: value.content.len(),
200                source,
201            }
202        })?)
203        .map_err(Error::HasherDeserialization)?;
204
205        Ok(hasher)
206    }
207}
208
209/// Required parameters for the signing request operation.
210#[derive(Debug, Deserialize, Serialize)]
211pub struct Required {
212    /// Inputs of the signing procedure.
213    pub input: SignatureRequestInput,
214
215    /// Outputs of the signing procedure.
216    pub output: SignatureRequestOutput,
217}
218
219/// Signing request.
220#[derive(Debug, Deserialize, Serialize)]
221pub struct Request {
222    /// Version of this signing request.
223    pub version: Version,
224
225    /// Required parameters of the signing process.
226    ///
227    /// All required parameters must be understood by the signing
228    /// process or the entire request is to be rejected.
229    pub required: Required,
230
231    /// Optional parameters for the signing process.
232    ///
233    /// The server may ignore any or all parameters in this group. If
234    /// any parameter is not understood by the server it must be
235    /// ignored.
236    pub optional: HashMap<String, Value>,
237}
238
239impl Request {
240    /// Read the request from a JSON serialized bytes.
241    ///
242    /// # Errors
243    ///
244    /// Returns an error if reading the file fails or the file contents
245    /// are not well-formed.
246    pub fn from_reader(reader: impl Read) -> Result<Self, crate::Error> {
247        let req: Request =
248            from_reader(reader).map_err(|source| Error::RequestDeserialization { source })?;
249        Ok(req)
250    }
251
252    /// Write the request as a JSON serialized form.
253    ///
254    /// # Errors
255    ///
256    /// Returns an error if serialization of the request fails or writing to
257    /// the `writer` encounters an error.
258    pub fn to_writer(&self, writer: impl Write) -> Result<(), crate::Error> {
259        to_writer(writer, &self).map_err(|source| Error::RequestSerialization { source })?;
260        Ok(())
261    }
262
263    /// Prepares a signing request for a file.
264    ///
265    /// Given a file as an `input` this function creates a well-formed request.
266    /// That request is of latest known version and contains all necessary fields.
267    ///
268    /// # Errors
269    ///
270    /// Returns an error if reading the file fails or forming the request encounters
271    /// an error.
272    ///
273    /// # Examples
274    ///
275    /// The following example creates a signing request for `Cargo.toml`:
276    ///
277    /// ```
278    /// # fn main() -> testresult::TestResult {
279    /// use signstar_common::request_api::Request;
280    ///
281    /// let signing_request = Request::for_file("Cargo.toml")?;
282    /// # Ok(()) }
283    /// ```
284    pub fn for_file(input: impl AsRef<Path>) -> Result<Self, crate::Error> {
285        let input = input.as_ref();
286        let hasher = {
287            let mut hasher = IoWrapper(Sha512::new());
288            copy(
289                &mut File::open(input).map_err(|source| Error::IoPath {
290                    path: input.to_path_buf(),
291                    context: "opening the file for reading".to_string(),
292                    source,
293                })?,
294                &mut hasher,
295            )
296            .map_err(|source| Error::IoPath {
297                path: input.to_path_buf(),
298                context: "copying the file contents".to_string(),
299                source,
300            })?;
301            hasher.0
302        };
303        let required = Required {
304            input: hasher.into(),
305            output: SignatureRequestOutput::new_openpgp_v4(),
306        };
307
308        // Add "grease" so that the server can handle any optional data
309        // See: https://lobste.rs/s/utmsph/age_plugins#c_i76hkd
310        // See: https://community.letsencrypt.org/t/adding-random-entries-to-the-directory/33417
311        let grease: String = rng()
312            .sample_iter(&Alphanumeric)
313            .take(7)
314            .map(char::from)
315            .collect();
316
317        Ok(Self {
318            version: Version::new(1, 0, 0),
319            required,
320            optional: vec![
321                (
322                    grease,
323                    Value::String(
324                        "https://gitlab.archlinux.org/archlinux/signstar/-/merge_requests/43"
325                            .to_string(),
326                    ),
327                ),
328                (
329                    "request-time".into(),
330                    Value::Number(
331                        SystemTime::now()
332                            .duration_since(SystemTime::UNIX_EPOCH)
333                            .map_err(|source| Error::CurrentTimeBeforeReference {
334                                reference_time: SystemTime::UNIX_EPOCH,
335                                source,
336                            })?
337                            .as_secs()
338                            .into(),
339                    ),
340                ),
341                (
342                    "file-name".into(),
343                    input
344                        .file_name()
345                        .and_then(|s| s.to_str())
346                        .map(Into::into)
347                        .unwrap_or(Value::Null),
348                ),
349            ]
350            .into_iter()
351            .collect(),
352        })
353    }
354}
355
356/// The response to a signing request.
357///
358/// Tracks the `version` of the signing response and the signature as `signature`.
359///
360/// The details of the format are documented in the [response specification].
361///
362/// [response specification]: https://signstar.archlinux.page/signing-api/response.html
363#[derive(Debug, Deserialize, Serialize)]
364pub struct Response {
365    /// Version of this signing response.
366    pub version: Version,
367
368    /// Raw content of the signature.
369    signature: String,
370}
371
372impl Response {
373    /// Creates a version 1 compatible signature from raw signature content.
374    pub fn v1(signature: String) -> Self {
375        Self {
376            version: Version::new(1, 0, 0),
377            signature,
378        }
379    }
380
381    /// Creates a [`Response`] from a `reader` of JSON formatted bytes.
382    ///
383    /// # Errors
384    ///
385    /// Returns an error if deserialization from `reader` fails.
386    pub fn from_reader(reader: impl Read) -> Result<Self, crate::Error> {
387        let resp: Self =
388            from_reader(reader).map_err(|source| Error::ResponseDeserialization { source })?;
389        Ok(resp)
390    }
391
392    /// Writes the [`Response`] to a `writer` in JSON serialized form.
393    ///
394    /// # Errors
395    ///
396    /// Returns an error if `self` can not be serialized or if writing to `writer` fails.
397    pub fn to_writer(&self, writer: impl Write) -> Result<(), crate::Error> {
398        to_writer(writer, &self).map_err(|source| Error::ResponseSerialization { source })?;
399        Ok(())
400    }
401
402    /// Writes the raw signature of the [`Response`] to a `writer`.
403    ///
404    /// # Errors
405    ///
406    /// Returns an error if the signature can not be written to the `writer`.
407    pub fn signature_to_writer(&self, mut writer: impl Write) -> Result<(), crate::Error> {
408        writer
409            .write_all(self.signature.as_bytes())
410            .map_err(|source| Error::Io {
411                context: "writing a signature to a buffer".to_string(),
412                source,
413            })?;
414        Ok(())
415    }
416}
417
418/// The type of the certificate that has been generated for the signing key.
419#[derive(Clone, Copy, Debug, Eq, PartialEq)]
420#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
421pub enum CertificateType {
422    /// OpenPGP certificate.
423    OpenPgp,
424}
425
426impl CertificateType {
427    /// Print raw certificate bytes with correct framing.
428    ///
429    /// For OpenPGP, for example, this is the same as using armor.
430    pub fn with_framing(&self, raw_bytes: &[u8]) -> CertificateData {
431        let bytes = Base64::encode_string(raw_bytes);
432        match self {
433            CertificateType::OpenPgp => CertificateData(format!(
434                "-----BEGIN PGP PUBLIC KEY BLOCK-----\n\n{bytes}\n-----END PGP PUBLIC KEY BLOCK-----"
435            )),
436        }
437    }
438}
439
440/// Certificate data, as presented to the user.
441///
442/// This representation already contains protocol framing and is base64-encoded.
443#[derive(Debug)]
444#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
445pub struct CertificateData(String);
446
447impl AsRef<str> for CertificateData {
448    fn as_ref(&self) -> &str {
449        &self.0
450    }
451}
452
453impl Display for CertificateData {
454    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
455        self.0.fmt(f)
456    }
457}
458
459/// Data and metadata of a certificate residing in a Signstar backend.
460#[derive(Debug)]
461#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
462pub struct Certificate {
463    /// Base64-encoded certificate with protocol framing.
464    pub certificate: CertificateData,
465
466    /// The type of the certificate.
467    pub r#type: CertificateType,
468
469    /// The name of the backend, e.g. `NetHSM` or `YubiHSM2`.
470    pub backend_id: BackendType,
471
472    /// The signing key ID on that particular backend.
473    pub signing_key_id: String,
474}
475
476/// List of certificates stored on the Signstar host.
477#[derive(Debug)]
478#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
479pub struct Certificates {
480    /// Array of base64-encoded certificates.
481    pub certs: Vec<Certificate>,
482}
483
484#[cfg(test)]
485mod tests {
486    use std::{
487        fs::File,
488        io::{Cursor, copy},
489        path::PathBuf,
490    };
491
492    use digest_io::IoWrapper;
493    use rstest::rstest;
494    use sha2::Digest;
495    use testresult::TestResult;
496
497    use super::*;
498
499    #[test]
500    fn hash_values_are_predictable() -> TestResult {
501        let mut hasher = IoWrapper(Sha512::new());
502        let mut bytes = Cursor::new(b"this is sample text");
503        copy(&mut bytes, &mut hasher)?;
504        let result: &[u8] = &hasher.0.serialize();
505
506        let expected_state = [
507            8, 201, 188, 243, 103, 230, 9, 106, 59, 167, 202, 132, 133, 174, 103, 187, 43, 248,
508            148, 254, 114, 243, 110, 60, 241, 54, 29, 95, 58, 245, 79, 165, 209, 130, 230, 173,
509            127, 82, 14, 81, 31, 108, 62, 43, 140, 104, 5, 155, 107, 189, 65, 251, 171, 217, 131,
510            31, 121, 33, 126, 19, 25, 205, 224, 91, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
511            19, 116, 104, 105, 115, 32, 105, 115, 32, 115, 97, 109, 112, 108, 101, 32, 116, 101,
512            120, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
513            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
514            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
515            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
516        ];
517
518        assert_eq!(result, expected_state);
519
520        let expected_digest = [
521            20, 253, 69, 133, 146, 76, 11, 4, 191, 13, 150, 196, 9, 97, 21, 35, 186, 95, 254, 59,
522            148, 60, 88, 155, 127, 203, 151, 216, 11, 16, 228, 73, 113, 23, 115, 110, 198, 42, 109,
523            92, 23, 33, 70, 71, 136, 219, 73, 238, 135, 13, 223, 117, 215, 69, 243, 33, 125, 109,
524            95, 121, 213, 44, 212, 166,
525        ];
526
527        let hasher = Sha512::deserialize(&expected_state.into())?;
528        let hash = &hasher.finalize()[..];
529        assert_eq!(hash, expected_digest);
530
531        //let hasher = old_sha2::Sha512::deserialize(&expected_state.try_into()?)?;
532        //let hash = &hasher.finalize()[..];
533        //assert_eq!(hash, expected_digest);
534
535        Ok(())
536    }
537
538    #[test]
539    fn sample_request_is_ok() -> TestResult {
540        let request = include_str!("../../fixtures/request/sample-request.json");
541        let reader = Request::from_reader(request.as_bytes())?;
542        let hasher: Sha512 = reader.required.input.try_into()?;
543        assert_eq!(
544            hasher.finalize(),
545            [
546                20, 253, 69, 133, 146, 76, 11, 4, 191, 13, 150, 196, 9, 97, 21, 35, 186, 95, 254,
547                59, 148, 60, 88, 155, 127, 203, 151, 216, 11, 16, 228, 73, 113, 23, 115, 110, 198,
548                42, 109, 92, 23, 33, 70, 71, 136, 219, 73, 238, 135, 13, 223, 117, 215, 69, 243,
549                33, 125, 109, 95, 121, 213, 44, 212, 166
550            ]
551        );
552        Ok(())
553    }
554
555    #[rstest]
556    fn sample_request_is_bad(
557        #[files("../fixtures/request/bad-*.json")] request_file: PathBuf,
558    ) -> TestResult {
559        let reader = File::open(request_file)?;
560        assert!(
561            Request::from_reader(reader).is_err(),
562            "parsing of the request file should fail"
563        );
564        Ok(())
565    }
566}