1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
21pub struct CatalogCheck {
22 #[serde(flatten)]
24 pub report: CatalogReport,
25 pub catalog: Option<Catalog>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
31pub struct HistoryCheck {
32 #[serde(flatten)]
34 pub report: HistoryReport,
35 pub history: Option<History>,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
41pub struct KeyIdReport {
42 pub ok: bool,
44 pub id: Option<String>,
46 pub errors: Vec<ErrorReport>,
48}
49
50#[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#[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#[must_use]
103pub fn inspect_package(bytes: &[u8]) -> Inspection {
104 zaun_registry_wasm::inspect(bytes)
105}
106
107#[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 #[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 #[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#[derive(Deserialize)]
152struct Claim {
153 registry: ClaimedRegistry,
154}
155
156#[derive(Deserialize)]
157struct ClaimedRegistry {
158 id: String,
159}
160
161fn 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}