Skip to main content

zaun_community_protocol/signed/bot_package/
container.rs

1//! The `.zbot` package file (§4.9):
2//! `"ZBOT" ‖ 0x01 ‖ bytes(header) ‖ Signature ‖ bytes(manifest) ‖ bytes(component)`.
3
4use serde::Deserialize;
5
6use super::BotPackage;
7use crate::crypto::{self, content_hash, publisher_id};
8use crate::encoding::{DecodeError, EncodeError, Reader, Writer};
9use crate::ids::PublisherId;
10use crate::keys::{SIGNATURE_LEN, Signature};
11use crate::limits::{BOT_COMPONENT_MAX, BOT_HEADER_MAX, BOT_MANIFEST_MAX};
12use crate::signed::{Signed, SignedError, SignedObject};
13
14/// The file's first four bytes.
15pub const PACKAGE_MAGIC: &[u8; 4] = b"ZBOT";
16/// The container version byte after the magic.
17pub const PACKAGE_VERSION: u8 = 0x01;
18
19/// A `.zbot` file that does not verify.
20#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
21pub enum PackageError {
22    /// Not a package file: wrong magic or container version, a part over its limit,
23    /// truncated or with trailing bytes, or a header that is not a canonical `BotPackage`.
24    #[error("malformed package: {0}")]
25    Malformed(#[from] DecodeError),
26    /// The publisher signature does not verify (or is not a signature encoding).
27    #[error("invalid package signature: {0}")]
28    Signature(#[from] SignedError),
29    /// The package is unsigned and the host does not accept unsigned packages.
30    #[error("unsigned package")]
31    Unsigned,
32    /// The manifest is not the one the header names.
33    #[error("the manifest does not match the header's hash")]
34    ManifestHash,
35    /// The component is not the one the header names.
36    #[error("the component does not match the header's hash")]
37    ComponentHash,
38    /// The manifest is not JSON with `app_id` and `version` equal to the header's.
39    #[error("the manifest's app_id or version differs from the header")]
40    Manifest,
41}
42
43/// The parts of a `.zbot` file, not yet verified.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct ParsedPackage {
46    /// The decoded header (read only to find the publisher key until verified).
47    pub header: BotPackage,
48    /// The header's canonical bytes, which the signature covers.
49    pub header_bytes: Vec<u8>,
50    /// The 3 374 signature bytes (all zero for an unsigned package).
51    pub signature: Vec<u8>,
52    /// The manifest JSON bytes.
53    pub manifest: Vec<u8>,
54    /// The WebAssembly component bytes.
55    pub component: Vec<u8>,
56}
57
58/// A package whose signature (unless unsigned was allowed), hashes and manifest ids were
59/// checked.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct VerifiedPackage {
62    /// The header.
63    pub header: BotPackage,
64    /// `SHA3-256` of the header bytes: the package's identity.
65    pub header_hash: [u8; 32],
66    /// The publisher, or `None` for an unsigned development package.
67    pub publisher: Option<PublisherId>,
68    /// The manifest JSON bytes.
69    pub manifest: Vec<u8>,
70    /// The component bytes.
71    pub component: Vec<u8>,
72}
73
74impl VerifiedPackage {
75    /// Whether a publisher signed it.
76    #[must_use]
77    pub const fn signed(&self) -> bool {
78        self.publisher.is_some()
79    }
80}
81
82/// Splits a `.zbot` file into its parts, checking every limit and that nothing trails.
83///
84/// # Errors
85/// [`PackageError::Malformed`].
86pub fn parse_package(file: &[u8]) -> Result<ParsedPackage, PackageError> {
87    let mut r = Reader::new(file);
88    if r.fixed(PACKAGE_MAGIC.len())? != PACKAGE_MAGIC {
89        return Err(DecodeError::Invalid("magic").into());
90    }
91    if r.u8()? != PACKAGE_VERSION {
92        return Err(DecodeError::Invalid("container version").into());
93    }
94    let header_bytes = r.bytes(BOT_HEADER_MAX)?.to_vec();
95    let signature = r.fixed(SIGNATURE_LEN)?.to_vec();
96    let manifest = r.bytes(BOT_MANIFEST_MAX)?.to_vec();
97    let component = r.bytes(BOT_COMPONENT_MAX)?.to_vec();
98    r.finish()?;
99    let header = BotPackage::decode_unverified(&header_bytes)?;
100    Ok(ParsedPackage {
101        header,
102        header_bytes,
103        signature,
104        manifest,
105        component,
106    })
107}
108
109/// The two manifest fields that must equal the header's.
110#[derive(Deserialize)]
111struct ManifestIds {
112    app_id: String,
113    version: String,
114}
115
116/// Verifies the signature under the header's publisher key (`min_suite` 1) before anything
117/// else, then both hashes and the manifest's `app_id` and `version`. An all-zero signature is
118/// accepted only with `allow_unsigned`.
119///
120/// # Errors
121/// [`PackageError`] naming the first failed check.
122pub fn verify_package(
123    parsed: ParsedPackage,
124    allow_unsigned: bool,
125) -> Result<VerifiedPackage, PackageError> {
126    let publisher = if parsed.signature.iter().all(|b| *b == 0) {
127        if !allow_unsigned {
128            return Err(PackageError::Unsigned);
129        }
130        None
131    } else {
132        let sig = Signature::from_bytes(&parsed.signature).map_err(SignedError::from)?;
133        // A signature needs a key: the all-zero placeholder is only for unsigned packages.
134        let key = parsed
135            .header
136            .publisher_key
137            .as_ref()
138            .ok_or(PackageError::Signature(SignedError::Signature(
139                crypto::VerifyError::SuiteMismatch {
140                    key: 0,
141                    sig: parsed.signature.first().copied().unwrap_or(0),
142                },
143            )))?;
144        crypto::verify(key, &sig, BotPackage::CONTEXT, &parsed.header_bytes, 1)
145            .map_err(SignedError::from)?;
146        Some(publisher_id(key))
147    };
148    let header = parsed.header;
149    if content_hash(&parsed.manifest) != header.manifest_sha3 {
150        return Err(PackageError::ManifestHash);
151    }
152    if content_hash(&parsed.component) != header.component_sha3 {
153        return Err(PackageError::ComponentHash);
154    }
155    let ids: ManifestIds =
156        serde_json::from_slice(&parsed.manifest).map_err(|_| PackageError::Manifest)?;
157    if ids.app_id != header.app_id || ids.version != header.version {
158        return Err(PackageError::Manifest);
159    }
160    Ok(VerifiedPackage {
161        header_hash: content_hash(&parsed.header_bytes),
162        header,
163        publisher,
164        manifest: parsed.manifest,
165        component: parsed.component,
166    })
167}
168
169fn write(
170    header: &[u8],
171    sig: &[u8],
172    manifest: &[u8],
173    component: &[u8],
174) -> Result<Vec<u8>, EncodeError> {
175    let mut w = Writer::new();
176    w.fixed(PACKAGE_MAGIC);
177    w.u8(PACKAGE_VERSION);
178    w.bytes(header, BOT_HEADER_MAX)?;
179    w.fixed(sig);
180    w.bytes(manifest, BOT_MANIFEST_MAX)?;
181    w.bytes(component, BOT_COMPONENT_MAX)?;
182    Ok(w.into_bytes())
183}
184
185/// Writes a `.zbot` file from a signed header and its parts. The caller computed the
186/// header's hashes from these exact `manifest` and `component` bytes.
187///
188/// # Errors
189/// [`EncodeError::OverLimit`] for a part over its limit.
190pub fn write_package(
191    header: &Signed<BotPackage>,
192    manifest: &[u8],
193    component: &[u8],
194) -> Result<Vec<u8>, EncodeError> {
195    write(
196        header.bytes(),
197        header.signature().as_bytes(),
198        manifest,
199        component,
200    )
201}
202
203/// Writes an unsigned development `.zbot` file (all-zero signature, §4.9).
204///
205/// # Errors
206/// [`EncodeError`] for a broken header rule or a part over its limit.
207pub fn write_unsigned_package(
208    header: &BotPackage,
209    manifest: &[u8],
210    component: &[u8],
211) -> Result<Vec<u8>, EncodeError> {
212    write(
213        &header.to_bytes()?,
214        &[0u8; SIGNATURE_LEN],
215        manifest,
216        component,
217    )
218}