use std::fmt;
use alien_error::AlienError;
use base64::engine::general_purpose::STANDARD;
use base64::Engine as _;
use chrono::{DateTime, Utc};
use serde::de::{DeserializeOwned, IgnoredAny};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::error::{ErrorData, Result};
pub const MAX_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;
pub const MAX_SIGNATURES: usize = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Kind {
Release,
Config,
Session,
SignerList,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Role {
Release,
Admin,
}
impl Role {
pub fn as_str(self) -> &'static str {
match self {
Self::Release => "release",
Self::Admin => "admin",
}
}
}
impl Kind {
pub const ALL: [Kind; 4] = [Kind::Release, Kind::Config, Kind::Session, Kind::SignerList];
pub fn as_str(self) -> &'static str {
match self {
Self::Release => "release/v2",
Self::Config => "config/v1",
Self::Session => "session/v1",
Self::SignerList => "signer-list/v1",
}
}
pub fn parse(text: &str) -> Option<Self> {
Self::ALL.into_iter().find(|kind| kind.as_str() == text)
}
pub fn role(self) -> Role {
match self {
Self::Release | Self::Config | Self::Session => Role::Release,
Self::SignerList => Role::Admin,
}
}
pub fn is_install_bound(self) -> bool {
matches!(self, Self::Config | Self::Session)
}
}
impl fmt::Display for Kind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Envelope<B> {
#[serde(rename = "type")]
pub kind: String,
pub project: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub install: Option<String>,
pub sequence: u64,
pub not_after: Option<DateTime<Utc>>,
pub signer_list_version: u64,
pub body: B,
}
impl<B: Serialize> Envelope<B> {
pub fn to_payload(&self) -> Result<Vec<u8>> {
serde_json::to_vec(self).map_err(|error| {
AlienError::new(ErrorData::StatementMalformed {
reason: format!("the statement could not be serialized: {error}"),
})
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Signature {
pub signer: String,
pub sig: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SignedStatement {
pub payload: String,
pub signatures: Vec<Signature>,
}
impl SignedStatement {
pub fn new(payload: &[u8]) -> Self {
Self {
payload: STANDARD.encode(payload),
signatures: Vec::new(),
}
}
pub fn from_json(bytes: &[u8]) -> Result<Self> {
serde_json::from_slice(bytes).map_err(|error| malformed(format!("{error}")))
}
pub fn to_json(&self) -> String {
serde_json::to_string(self).expect("a signed statement always serializes")
}
pub fn open(&self) -> Result<Opened> {
if self.payload.len() > MAX_PAYLOAD_BYTES / 3 * 4 + 4 {
return Err(malformed("the payload is too large"));
}
let bytes = STANDARD
.decode(&self.payload)
.map_err(|_| malformed("the payload is not valid base64"))?;
if self.signatures.len() > MAX_SIGNATURES {
return Err(malformed(format!(
"the statement carries more than {MAX_SIGNATURES} signatures"
)));
}
let header: Envelope<IgnoredAny> = serde_json::from_slice(&bytes)
.map_err(|error| malformed(format!("the payload is not a statement: {error}")))?;
let kind = Kind::parse(&header.kind)
.ok_or_else(|| malformed(format!("unknown statement type '{}'", header.kind)))?;
let digest = format!("sha256:{}", hex::encode(Sha256::digest(&bytes)));
Ok(Opened {
kind,
project: header.project,
install: header.install,
sequence: header.sequence,
not_after: header.not_after,
signer_list_version: header.signer_list_version,
digest,
bytes,
signatures: self.signatures.clone(),
})
}
}
#[derive(Debug, Clone)]
pub struct Opened {
pub kind: Kind,
pub project: String,
pub install: Option<String>,
pub sequence: u64,
pub not_after: Option<DateTime<Utc>>,
pub signer_list_version: u64,
pub digest: String,
pub bytes: Vec<u8>,
pub signatures: Vec<Signature>,
}
impl Opened {
pub fn body<B: DeserializeOwned>(&self) -> Result<B> {
let envelope: Envelope<B> = serde_json::from_slice(&self.bytes).map_err(|error| {
AlienError::new(ErrorData::BodyRefused {
kind: self.kind.as_str().to_string(),
reason: format!("the body does not match the kind: {error}"),
})
})?;
Ok(envelope.body)
}
}
pub(crate) fn malformed(reason: impl Into<String>) -> AlienError<ErrorData> {
AlienError::new(ErrorData::StatementMalformed {
reason: reason.into(),
})
}