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 and developer config.
46    Release,
47    /// Exec sessions.
48    Operate,
49    /// The next version of the signer list.
50    Admin,
51}
52
53impl Role {
54    /// The role's name in JSON.
55    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    /// Every kind.
66    pub const ALL: [Kind; 4] = [Kind::Release, Kind::Config, Kind::Session, Kind::SignerList];
67
68    /// The `type` string.
69    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    /// The kind a `type` string names.
79    pub fn parse(text: &str) -> Option<Self> {
80        Self::ALL.into_iter().find(|kind| kind.as_str() == text)
81    }
82
83    /// Role a signer needs to sign this kind.
84    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    /// Whether statements of this kind name exactly one install. Releases
93    /// and signer lists are the same for every install of a project.
94    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/// The signed payload: a header and a kind-specific body.
106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107#[serde(rename_all = "camelCase", deny_unknown_fields)]
108pub struct Envelope<B> {
109    /// Statement kind, one of [`Kind`]'s `type` strings.
110    #[serde(rename = "type")]
111    pub kind: String,
112    /// Project the statement belongs to, as named by signer list version 1.
113    pub project: String,
114    /// Install the statement is for, on install-bound kinds, in the form
115    /// [`crate::InstallId`] prints.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub install: Option<String>,
118    /// Grows with every statement of a kind; for signer lists, the version.
119    pub sequence: u64,
120    /// When the statement stops being valid, if ever.
121    pub not_after: Option<DateTime<Utc>>,
122    /// Signer list version the signer took its keys from. For a signer list,
123    /// the version that authorizes it: its own for version 1, otherwise the
124    /// one before.
125    pub signer_list_version: u64,
126    /// Kind-specific content.
127    pub body: B,
128}
129
130impl<B: Serialize> Envelope<B> {
131    /// The payload bytes to sign.
132    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/// One signature over a statement's payload.
142#[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    /// Id of the signer on the signer list.
147    pub signer: String,
148    /// Base64 DER ECDSA P-256 signature over the payload bytes.
149    pub sig: String,
150}
151
152/// A statement as it is stored and carried.
153#[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    /// Base64 of the payload bytes.
158    pub payload: String,
159    /// Signatures over the payload bytes.
160    pub signatures: Vec<Signature>,
161}
162
163impl SignedStatement {
164    /// An unsigned statement around `payload`.
165    pub fn new(payload: &[u8]) -> Self {
166        Self {
167            payload: STANDARD.encode(payload),
168            signatures: Vec::new(),
169        }
170    }
171
172    /// Parse the JSON form.
173    pub fn from_json(bytes: &[u8]) -> Result<Self> {
174        serde_json::from_slice(bytes).map_err(|error| malformed(format!("{error}")))
175    }
176
177    /// The JSON form.
178    pub fn to_json(&self) -> String {
179        serde_json::to_string(self).expect("a signed statement always serializes")
180    }
181
182    /// Decode the payload and read its header, without checking signatures.
183    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/// A decoded statement whose signatures are not yet checked.
215#[derive(Debug, Clone)]
216pub struct Opened {
217    /// Statement kind.
218    pub kind: Kind,
219    /// Project the statement names.
220    pub project: String,
221    /// Install the statement names.
222    pub install: Option<String>,
223    /// Sequence.
224    pub sequence: u64,
225    /// Expiry.
226    pub not_after: Option<DateTime<Utc>>,
227    /// Signer list version the signer took its keys from.
228    pub signer_list_version: u64,
229    /// `sha256:<hex>` of the payload bytes. It identifies the statement exactly.
230    pub digest: String,
231    /// The payload bytes that were signed.
232    pub bytes: Vec<u8>,
233    /// Signatures over `bytes`.
234    pub signatures: Vec<Signature>,
235}
236
237impl Opened {
238    /// Read the body as `B`, refusing unknown fields. Parsing the bytes again,
239    /// rather than a parsed value, keeps duplicate fields an error.
240    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}