Skip to main content

zaun_client/
registry.rs

1//! Bot registries for apps: a signed catalog, a history file and a `.zbot` package, checked as
2//! the registry's own browser verifier (`zaun-registry-wasm`) checks them.
3//!
4//! An app pins one key per registry it trusts. [`verify_catalog`] picks the pinned key whose
5//! id the catalog names (a hint only; the signature decides) and gives the registry's report,
6//! plus the verified catalog itself so the app reads package URLs, digests and permissions
7//! from what was verified. Failures are reports, never panics or errors.
8
9use serde::{Deserialize, Serialize};
10use zaun_registry::keys::public_key_from_b64;
11use zaun_registry::spec::limits::CATALOG_BYTES_MAX;
12use zaun_registry::spec::{Catalog, History, RegistryKey, read};
13use zaun_registry::{Diagnostic, ErrorCode};
14
15pub use zaun_registry_wasm::{
16    CatalogReport, ErrorReport, HistoryReport, Identity, Inspection, SeenInput,
17};
18
19/// [`verify_catalog`]'s answer: the registry's report and, when `ok`, the verified catalog.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
21pub struct CatalogCheck {
22    /// The registry's report: `ok`, `installable`, `registry_id`, `seen`, `errors`, …
23    #[serde(flatten)]
24    pub report: CatalogReport,
25    /// The verified catalog, present only when `ok`.
26    pub catalog: Option<Catalog>,
27}
28
29/// [`verify_history`]'s answer: the registry's report and, when `ok`, the verified history.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
31pub struct HistoryCheck {
32    /// The registry's report: `ok`, `versions`, `errors`.
33    #[serde(flatten)]
34    pub report: HistoryReport,
35    /// The verified history file, present only when `ok`.
36    pub history: Option<History>,
37}
38
39/// [`key_id`]'s answer.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
41pub struct KeyIdReport {
42    /// Whether the text is a public key.
43    pub ok: bool,
44    /// The key's id (a registry id for a registry key), base64url.
45    pub id: Option<String>,
46    /// Why it is not a key.
47    pub errors: Vec<ErrorReport>,
48}
49
50/// Verifies `catalog.json` bytes and the text of `catalog.json.sig` against the key of
51/// `pinned` (base64url public keys) that the catalog names, at Unix time `now` (seconds),
52/// after `seen` (the `seen` an earlier success returned for that registry, as JSON).
53#[must_use]
54pub fn verify_catalog(
55    bytes: &[u8],
56    sig: &str,
57    pinned: &[String],
58    now: u64,
59    seen: Option<&str>,
60) -> CatalogCheck {
61    let seen = match SeenInput::parse(seen) {
62        Ok(s) => s,
63        Err(d) => return CatalogCheck::failed(d),
64    };
65    let key = match pick(bytes, pinned) {
66        Ok(k) => k,
67        Err(d) => return CatalogCheck::failed(d),
68    };
69    let report = zaun_registry_wasm::verify(bytes, sig, key, now, seen.as_ref());
70    let catalog = report
71        .ok
72        .then(|| read::<Catalog>("catalog.json", bytes).ok())
73        .flatten();
74    CatalogCheck { report, catalog }
75}
76
77/// Verifies the catalog as [`verify_catalog`] does (no stored serial), then
78/// `history/<app_id>.json` against the hash the verified catalog lists for it.
79#[must_use]
80pub fn verify_history(
81    catalog: &[u8],
82    sig: &str,
83    pinned: &[String],
84    now: u64,
85    app_id: &str,
86    bytes: &[u8],
87) -> HistoryCheck {
88    let report = match pick(catalog, pinned) {
89        Ok(key) => zaun_registry_wasm::history(catalog, sig, key, now, app_id, bytes),
90        Err(d) => return HistoryCheck::failed(d),
91    };
92    let file = format!("history/{app_id}.json");
93    let history = report
94        .ok
95        .then(|| read::<History>(&file, bytes).ok())
96        .flatten();
97    HistoryCheck { report, history }
98}
99
100/// What a `.zbot` file says, whether its signature verifies and whether it passes the
101/// registry's package checks.
102#[must_use]
103pub fn inspect_package(bytes: &[u8]) -> Inspection {
104    zaun_registry_wasm::inspect(bytes)
105}
106
107/// The id of a base64url public key: what a bot card's `source.registry_id` is compared with.
108#[must_use]
109pub fn key_id(key: &str) -> KeyIdReport {
110    match public_key_from_b64(key) {
111        Ok(k) => KeyIdReport {
112            ok: true,
113            id: Some(RegistryKey(k).id().to_string()),
114            errors: Vec::new(),
115        },
116        Err(d) => KeyIdReport {
117            ok: false,
118            id: None,
119            errors: vec![d.into()],
120        },
121    }
122}
123
124impl CatalogCheck {
125    /// The answer of one failure.
126    #[must_use]
127    pub fn failed(d: Diagnostic) -> Self {
128        Self {
129            report: CatalogReport::failed(d),
130            catalog: None,
131        }
132    }
133}
134
135impl HistoryCheck {
136    /// The answer of one failure.
137    #[must_use]
138    pub fn failed(d: Diagnostic) -> Self {
139        Self {
140            report: HistoryReport {
141                ok: false,
142                versions: Vec::new(),
143                errors: vec![d.into()],
144            },
145            history: None,
146        }
147    }
148}
149
150/// The catalog's own claim of its registry id, read only to choose a key.
151#[derive(Deserialize)]
152struct Claim {
153    registry: ClaimedRegistry,
154}
155
156#[derive(Deserialize)]
157struct ClaimedRegistry {
158    id: String,
159}
160
161/// The pinned key to verify with: the one whose id the catalog names. With one key pinned,
162/// that key, so its report says exactly what failed. A catalog that cannot be read is left to
163/// the first key's checks to report.
164fn pick<'a>(bytes: &[u8], pinned: &'a [String]) -> Result<&'a str, Diagnostic> {
165    let mut ids = Vec::with_capacity(pinned.len());
166    for (i, key) in pinned.iter().enumerate() {
167        let k = public_key_from_b64(key).map_err(|d| {
168            Diagnostic::error(d.code, format!("pinned key {i}: {}", d.message))
169                .with_hint("Pin the `key` from the registry's registry.toml.")
170        })?;
171        ids.push((RegistryKey(k).id().to_string(), key.as_str()));
172    }
173    let Some(&(_, first)) = ids.first() else {
174        return Err(
175            Diagnostic::error(ErrorCode::CatalogRegistry, "no registry key is pinned")
176                .with_hint("Pin the `key` from the registry's registry.toml."),
177        );
178    };
179    let claim = (bytes.len() <= CATALOG_BYTES_MAX)
180        .then(|| serde_json::from_slice::<Claim>(bytes).ok())
181        .flatten();
182    let Some(claim) = claim else { return Ok(first) };
183    if let Some(&(_, key)) = ids.iter().find(|(id, _)| *id == claim.registry.id) {
184        return Ok(key);
185    }
186    if ids.len() == 1 {
187        return Ok(first);
188    }
189    let message = format!(
190        "the catalog names registry {}, which none of the pinned keys is",
191        claim.registry.id
192    );
193    Err(Diagnostic::error(ErrorCode::CatalogRegistry, message)
194        .with_hint("Pin that registry's key, from its registry.toml, after checking its id."))
195}