1use std::fmt;
9
10use alien_error::AlienError;
11use base64::engine::general_purpose::STANDARD;
12use base64::Engine as _;
13use chrono::{DateTime, Utc};
14use serde::de::{DeserializeOwned, IgnoredAny};
15use serde::{Deserialize, Serialize};
16use sha2::{Digest, Sha256};
17
18use crate::error::{ErrorData, Result};
19
20pub const MAX_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;
23
24pub const MAX_SIGNATURES: usize = 16;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
30pub enum Kind {
31 Release,
33 Config,
35 Session,
37 SignerList,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
43#[serde(rename_all = "camelCase")]
44pub enum Role {
45 Release,
47 Admin,
49}
50
51impl Role {
52 pub fn as_str(self) -> &'static str {
54 match self {
55 Self::Release => "release",
56 Self::Admin => "admin",
57 }
58 }
59}
60
61impl Kind {
62 pub const ALL: [Kind; 4] = [Kind::Release, Kind::Config, Kind::Session, Kind::SignerList];
64
65 pub fn as_str(self) -> &'static str {
67 match self {
68 Self::Release => "release/v2",
69 Self::Config => "config/v1",
70 Self::Session => "session/v1",
71 Self::SignerList => "signer-list/v1",
72 }
73 }
74
75 pub fn parse(text: &str) -> Option<Self> {
77 Self::ALL.into_iter().find(|kind| kind.as_str() == text)
78 }
79
80 pub fn role(self) -> Role {
82 match self {
83 Self::Release | Self::Config | Self::Session => Role::Release,
84 Self::SignerList => Role::Admin,
85 }
86 }
87
88 pub fn is_install_bound(self) -> bool {
91 matches!(self, Self::Config | Self::Session)
92 }
93}
94
95impl fmt::Display for Kind {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 f.write_str(self.as_str())
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
103#[serde(rename_all = "camelCase", deny_unknown_fields)]
104pub struct Envelope<B> {
105 #[serde(rename = "type")]
107 pub kind: String,
108 pub project: String,
110 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub install: Option<String>,
114 pub sequence: u64,
116 pub not_after: Option<DateTime<Utc>>,
118 pub signer_list_version: u64,
122 pub body: B,
124}
125
126impl<B: Serialize> Envelope<B> {
127 pub fn to_payload(&self) -> Result<Vec<u8>> {
129 serde_json::to_vec(self).map_err(|error| {
130 AlienError::new(ErrorData::StatementMalformed {
131 reason: format!("the statement could not be serialized: {error}"),
132 })
133 })
134 }
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
140#[serde(rename_all = "camelCase", deny_unknown_fields)]
141pub struct Signature {
142 pub signer: String,
144 pub sig: String,
146}
147
148#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
150#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
151#[serde(rename_all = "camelCase", deny_unknown_fields)]
152pub struct SignedStatement {
153 pub payload: String,
155 pub signatures: Vec<Signature>,
157}
158
159impl SignedStatement {
160 pub fn new(payload: &[u8]) -> Self {
162 Self {
163 payload: STANDARD.encode(payload),
164 signatures: Vec::new(),
165 }
166 }
167
168 pub fn from_json(bytes: &[u8]) -> Result<Self> {
170 serde_json::from_slice(bytes).map_err(|error| malformed(format!("{error}")))
171 }
172
173 pub fn to_json(&self) -> String {
175 serde_json::to_string(self).expect("a signed statement always serializes")
176 }
177
178 pub fn open(&self) -> Result<Opened> {
180 if self.payload.len() > MAX_PAYLOAD_BYTES / 3 * 4 + 4 {
181 return Err(malformed("the payload is too large"));
182 }
183 let bytes = STANDARD
184 .decode(&self.payload)
185 .map_err(|_| malformed("the payload is not valid base64"))?;
186 if self.signatures.len() > MAX_SIGNATURES {
187 return Err(malformed(format!(
188 "the statement carries more than {MAX_SIGNATURES} signatures"
189 )));
190 }
191 let header: Envelope<IgnoredAny> = serde_json::from_slice(&bytes)
192 .map_err(|error| malformed(format!("the payload is not a statement: {error}")))?;
193 let kind = Kind::parse(&header.kind)
194 .ok_or_else(|| malformed(format!("unknown statement type '{}'", header.kind)))?;
195 let digest = format!("sha256:{}", hex::encode(Sha256::digest(&bytes)));
196 Ok(Opened {
197 kind,
198 project: header.project,
199 install: header.install,
200 sequence: header.sequence,
201 not_after: header.not_after,
202 signer_list_version: header.signer_list_version,
203 digest,
204 bytes,
205 signatures: self.signatures.clone(),
206 })
207 }
208}
209
210#[derive(Debug, Clone)]
212pub struct Opened {
213 pub kind: Kind,
215 pub project: String,
217 pub install: Option<String>,
219 pub sequence: u64,
221 pub not_after: Option<DateTime<Utc>>,
223 pub signer_list_version: u64,
225 pub digest: String,
227 pub bytes: Vec<u8>,
229 pub signatures: Vec<Signature>,
231}
232
233impl Opened {
234 pub fn body<B: DeserializeOwned>(&self) -> Result<B> {
237 let envelope: Envelope<B> = serde_json::from_slice(&self.bytes).map_err(|error| {
238 AlienError::new(ErrorData::BodyRefused {
239 kind: self.kind.as_str().to_string(),
240 reason: format!("the body does not match the kind: {error}"),
241 })
242 })?;
243 Ok(envelope.body)
244 }
245}
246
247pub(crate) fn malformed(reason: impl Into<String>) -> AlienError<ErrorData> {
248 AlienError::new(ErrorData::StatementMalformed {
249 reason: reason.into(),
250 })
251}