1use 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};
19pub use sha2::Sha512;
21use sha2::{
22 Digest,
23 digest::common::hazmat::{DeserializeStateError, SerializableState},
24};
25
26use crate::backend::BackendType;
27
28#[derive(Debug, thiserror::Error)]
30pub enum Error {
31 #[error("Current time is before reference time {reference_time:?}: {source}")]
33 CurrentTimeBeforeReference {
34 reference_time: SystemTime,
36
37 source: std::time::SystemTimeError,
39 },
40
41 #[error("Deserialization of the hasher state failed: {0}")]
43 HasherDeserialization(#[from] DeserializeStateError),
44
45 #[error("The content size ({size} bytes) provided to the hasher is misaligned: {source}")]
47 HasherMisalignedSize {
48 size: usize,
50
51 source: TryFromSliceError,
53 },
54
55 #[error("Invalid content type. Found {actual:?} but expected {expected:?}.")]
57 InvalidContentType {
58 actual: HashType,
60
61 expected: HashType,
63 },
64
65 #[error("I/O error while {context}: {source}")]
67 Io {
68 context: String,
72
73 source: std::io::Error,
75 },
76
77 #[error("I/O error at path {path} while {context}: {source}")]
79 IoPath {
80 path: PathBuf,
82
83 context: String,
87
88 source: std::io::Error,
90 },
91
92 #[error("Could not deserialize request: {source}")]
94 RequestDeserialization {
95 source: serde_json::Error,
97 },
98
99 #[error("Could not serialize request: {source}")]
101 RequestSerialization {
102 source: serde_json::Error,
104 },
105
106 #[error("Could not deserialize response: {source}")]
108 ResponseDeserialization {
109 source: serde_json::Error,
111 },
112
113 #[error("Could not serialize response: {source}")]
115 ResponseSerialization {
116 source: serde_json::Error,
118 },
119}
120
121#[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
123#[serde(rename_all = "lowercase")]
124pub enum HashType {
125 #[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#[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
138pub enum SignatureType {
139 #[serde(rename = "OpenPGPv4")]
141 OpenPgpV4,
142}
143
144#[derive(Debug, Deserialize, Serialize)]
146pub struct SignatureRequestInput {
147 #[serde(rename = "type")]
148 hash_type: HashType,
149 content: Vec<u8>,
150}
151
152#[derive(Debug, Deserialize, Serialize)]
154pub struct SignatureRequestOutput {
155 #[serde(rename = "type")]
157 sig_type: SignatureType,
158}
159
160impl SignatureRequestOutput {
161 pub fn new_openpgp_v4() -> Self {
164 Self {
165 sig_type: SignatureType::OpenPgpV4,
166 }
167 }
168
169 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#[derive(Debug, Deserialize, Serialize)]
211pub struct Required {
212 pub input: SignatureRequestInput,
214
215 pub output: SignatureRequestOutput,
217}
218
219#[derive(Debug, Deserialize, Serialize)]
221pub struct Request {
222 pub version: Version,
224
225 pub required: Required,
230
231 pub optional: HashMap<String, Value>,
237}
238
239impl Request {
240 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 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 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 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#[derive(Debug, Deserialize, Serialize)]
364pub struct Response {
365 pub version: Version,
367
368 signature: String,
370}
371
372impl Response {
373 pub fn v1(signature: String) -> Self {
375 Self {
376 version: Version::new(1, 0, 0),
377 signature,
378 }
379 }
380
381 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 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 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
420#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
421pub enum CertificateType {
422 OpenPgp,
424}
425
426impl CertificateType {
427 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#[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#[derive(Debug)]
461#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
462pub struct Certificate {
463 pub certificate: CertificateData,
465
466 pub r#type: CertificateType,
468
469 pub backend_id: BackendType,
471
472 pub signing_key_id: String,
474}
475
476#[derive(Debug)]
478#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
479pub struct Certificates {
480 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 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}