Skip to main content

alien_signing/
envelope.rs

1//! The one envelope every statement uses.
2//!
3//! A signed statement is the payload bytes, base64, beside the signatures over
4//! them. Signatures sit outside the payload so nothing is ever re-serialized
5//! before it is verified, and no canonical JSON form is needed: whoever stores
6//! or forwards a statement carries the two strings unchanged.
7
8use 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
20/// Largest payload an enforcer decodes. A release with a full stack is well
21/// under this.
22pub const MAX_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;
23
24/// Most signatures one statement may carry.
25pub const MAX_SIGNATURES: usize = 16;
26
27/// What a statement may be about. The `type` strings are neutral, because
28/// they are stored in the customer's environment.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
30pub enum Kind {
31    /// A release: every workload of one platform on one channel, exactly.
32    Release,
33    /// Developer config values for one install.
34    Config,
35    /// One exec session on one install.
36    Session,
37    /// The next version of the signer list.
38    SignerList,
39}
40
41/// A key's authority on the signer list.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
43#[serde(rename_all = "camelCase")]
44pub enum Role {
45    /// Releases, developer config and exec sessions.
46    Release,
47    /// The next version of the signer list.
48    Admin,
49}
50
51impl Role {
52    /// The role's name in JSON.
53    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    /// Every kind.
63    pub const ALL: [Kind; 4] = [Kind::Release, Kind::Config, Kind::Session, Kind::SignerList];
64
65    /// The `type` string.
66    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    /// The kind a `type` string names.
76    pub fn parse(text: &str) -> Option<Self> {
77        Self::ALL.into_iter().find(|kind| kind.as_str() == text)
78    }
79
80    /// Role a signer needs to sign this kind.
81    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    /// Whether statements of this kind name exactly one install. Releases
89    /// and signer lists are the same for every install of a project.
90    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/// The signed payload: a header and a kind-specific body.
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
103#[serde(rename_all = "camelCase", deny_unknown_fields)]
104pub struct Envelope<B> {
105    /// Statement kind, one of [`Kind`]'s `type` strings.
106    #[serde(rename = "type")]
107    pub kind: String,
108    /// Project the statement belongs to, as named by signer list version 1.
109    pub project: String,
110    /// Install the statement is for, on install-bound kinds, in the form
111    /// [`crate::InstallId`] prints.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub install: Option<String>,
114    /// Grows with every statement of a kind; for signer lists, the version.
115    pub sequence: u64,
116    /// When the statement stops being valid, if ever.
117    pub not_after: Option<DateTime<Utc>>,
118    /// Signer list version the signer took its keys from. For a signer list,
119    /// the version that authorizes it: its own for version 1, otherwise the
120    /// one before.
121    pub signer_list_version: u64,
122    /// Kind-specific content.
123    pub body: B,
124}
125
126impl<B: Serialize> Envelope<B> {
127    /// The payload bytes to sign.
128    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/// One signature over a statement's payload.
138#[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    /// Id of the signer on the signer list.
143    pub signer: String,
144    /// Base64 DER ECDSA P-256 signature over the payload bytes.
145    pub sig: String,
146}
147
148/// A statement as it is stored and carried.
149#[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    /// Base64 of the payload bytes.
154    pub payload: String,
155    /// Signatures over the payload bytes.
156    pub signatures: Vec<Signature>,
157}
158
159impl SignedStatement {
160    /// An unsigned statement around `payload`.
161    pub fn new(payload: &[u8]) -> Self {
162        Self {
163            payload: STANDARD.encode(payload),
164            signatures: Vec::new(),
165        }
166    }
167
168    /// Parse the JSON form.
169    pub fn from_json(bytes: &[u8]) -> Result<Self> {
170        serde_json::from_slice(bytes).map_err(|error| malformed(format!("{error}")))
171    }
172
173    /// The JSON form.
174    pub fn to_json(&self) -> String {
175        serde_json::to_string(self).expect("a signed statement always serializes")
176    }
177
178    /// Decode the payload and read its header, without checking signatures.
179    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/// A decoded statement whose signatures are not yet checked.
211#[derive(Debug, Clone)]
212pub struct Opened {
213    /// Statement kind.
214    pub kind: Kind,
215    /// Project the statement names.
216    pub project: String,
217    /// Install the statement names.
218    pub install: Option<String>,
219    /// Sequence.
220    pub sequence: u64,
221    /// Expiry.
222    pub not_after: Option<DateTime<Utc>>,
223    /// Signer list version the signer took its keys from.
224    pub signer_list_version: u64,
225    /// `sha256:<hex>` of the payload bytes. It identifies the statement exactly.
226    pub digest: String,
227    /// The payload bytes that were signed.
228    pub bytes: Vec<u8>,
229    /// Signatures over `bytes`.
230    pub signatures: Vec<Signature>,
231}
232
233impl Opened {
234    /// Read the body as `B`, refusing unknown fields. Parsing the bytes again,
235    /// rather than a parsed value, keeps duplicate fields an error.
236    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}