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 Operate,
49 Admin,
51}
52
53impl Role {
54 pub fn as_str(self) -> &'static str {
56 match self {
57 Self::Release => "release",
58 Self::Operate => "operate",
59 Self::Admin => "admin",
60 }
61 }
62}
63
64impl Kind {
65 pub const ALL: [Kind; 4] = [Kind::Release, Kind::Config, Kind::Session, Kind::SignerList];
67
68 pub fn as_str(self) -> &'static str {
70 match self {
71 Self::Release => "release/v2",
72 Self::Config => "config/v1",
73 Self::Session => "session/v1",
74 Self::SignerList => "signer-list/v1",
75 }
76 }
77
78 pub fn parse(text: &str) -> Option<Self> {
80 Self::ALL.into_iter().find(|kind| kind.as_str() == text)
81 }
82
83 pub fn role(self) -> Role {
85 match self {
86 Self::Release | Self::Config => Role::Release,
87 Self::Session => Role::Operate,
88 Self::SignerList => Role::Admin,
89 }
90 }
91
92 pub fn is_install_bound(self) -> bool {
95 matches!(self, Self::Config | Self::Session)
96 }
97}
98
99impl fmt::Display for Kind {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 f.write_str(self.as_str())
102 }
103}
104
105#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107#[serde(rename_all = "camelCase", deny_unknown_fields)]
108pub struct Envelope<B> {
109 #[serde(rename = "type")]
111 pub kind: String,
112 pub project: String,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub install: Option<String>,
118 pub sequence: u64,
120 pub not_after: Option<DateTime<Utc>>,
122 pub signer_list_version: u64,
126 pub body: B,
128}
129
130impl<B: Serialize> Envelope<B> {
131 pub fn to_payload(&self) -> Result<Vec<u8>> {
133 serde_json::to_vec(self).map_err(|error| {
134 AlienError::new(ErrorData::StatementMalformed {
135 reason: format!("the statement could not be serialized: {error}"),
136 })
137 })
138 }
139}
140
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
143#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
144#[serde(rename_all = "camelCase", deny_unknown_fields)]
145pub struct Signature {
146 pub signer: String,
148 pub sig: String,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
155#[serde(rename_all = "camelCase", deny_unknown_fields)]
156pub struct SignedStatement {
157 pub payload: String,
159 pub signatures: Vec<Signature>,
161}
162
163impl SignedStatement {
164 pub fn new(payload: &[u8]) -> Self {
166 Self {
167 payload: STANDARD.encode(payload),
168 signatures: Vec::new(),
169 }
170 }
171
172 pub fn from_json(bytes: &[u8]) -> Result<Self> {
174 serde_json::from_slice(bytes).map_err(|error| malformed(format!("{error}")))
175 }
176
177 pub fn to_json(&self) -> String {
179 serde_json::to_string(self).expect("a signed statement always serializes")
180 }
181
182 pub fn open(&self) -> Result<Opened> {
184 if self.payload.len() > MAX_PAYLOAD_BYTES / 3 * 4 + 4 {
185 return Err(malformed("the payload is too large"));
186 }
187 let bytes = STANDARD
188 .decode(&self.payload)
189 .map_err(|_| malformed("the payload is not valid base64"))?;
190 if self.signatures.len() > MAX_SIGNATURES {
191 return Err(malformed(format!(
192 "the statement carries more than {MAX_SIGNATURES} signatures"
193 )));
194 }
195 let header: Envelope<IgnoredAny> = serde_json::from_slice(&bytes)
196 .map_err(|error| malformed(format!("the payload is not a statement: {error}")))?;
197 let kind = Kind::parse(&header.kind)
198 .ok_or_else(|| malformed(format!("unknown statement type '{}'", header.kind)))?;
199 let digest = format!("sha256:{}", hex::encode(Sha256::digest(&bytes)));
200 Ok(Opened {
201 kind,
202 project: header.project,
203 install: header.install,
204 sequence: header.sequence,
205 not_after: header.not_after,
206 signer_list_version: header.signer_list_version,
207 digest,
208 bytes,
209 signatures: self.signatures.clone(),
210 })
211 }
212}
213
214#[derive(Debug, Clone)]
216pub struct Opened {
217 pub kind: Kind,
219 pub project: String,
221 pub install: Option<String>,
223 pub sequence: u64,
225 pub not_after: Option<DateTime<Utc>>,
227 pub signer_list_version: u64,
229 pub digest: String,
231 pub bytes: Vec<u8>,
233 pub signatures: Vec<Signature>,
235}
236
237impl Opened {
238 pub fn body<B: DeserializeOwned>(&self) -> Result<B> {
241 let envelope: Envelope<B> = serde_json::from_slice(&self.bytes).map_err(|error| {
242 AlienError::new(ErrorData::BodyRefused {
243 kind: self.kind.as_str().to_string(),
244 reason: format!("the body does not match the kind: {error}"),
245 })
246 })?;
247 Ok(envelope.body)
248 }
249}
250
251pub(crate) fn malformed(reason: impl Into<String>) -> AlienError<ErrorData> {
252 AlienError::new(ErrorData::StatementMalformed {
253 reason: reason.into(),
254 })
255}