Skip to main content

vault_core/
catalogue.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! The provider catalogue: a signed, public table of issuer key prefixes that
4//! `unv enrich` consults before the table compiled into the binary.
5//!
6//! The compiled table can only be updated by a release. This one is published
7//! as a static file, fetched **whole** (a per-provider request would tell the
8//! host which providers you hold credentials for), cached locally and verified
9//! on **every load**, not only on download.
10//!
11//! Enrichment writes into the vault, so a tampered catalogue could mislabel
12//! secret types or point a card at an attacker's URL. Hence:
13//!
14//! - an Ed25519 signature over the exact payload bytes, checked against
15//!   [`PINNED_KEY_HEX`], which lives in the binary;
16//! - `generated_at` may never go backwards (replaying an old, valid file);
17//! - every field is shape-checked after the signature, because a correctly
18//!   signed typo is still a typo: prefixes under 3 characters would match
19//!   nearly every secret, and non-`https` URLs never reach a card.
20//!
21//! The catalogue holds no secrets and no user data. See ADR-0139.
22
23use base64::Engine;
24use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
25use serde::{Deserialize, Serialize};
26use std::path::PathBuf;
27
28pub const SCHEMA: u32 = 1;
29
30/// Where the scheduled `docs.yml` run publishes the signed catalogue: the project's own domain, which
31/// is what the old `github.io/EnvVault` and `github.io/UnENVerse` addresses redirect to (the first no
32/// longer answers at all, so there is no fallback to keep). The file is only there once the
33/// `CATALOGUE_SIGNING_KEY` Actions secret exists; until then a client gets a 404 and uses the
34/// catalogue built into the binary.
35pub const DEFAULT_URL: &str = "https://unenverse.darthdemono.com/catalogue/catalogue.json";
36
37/// Ed25519 public key the catalogue must be signed with. The private half is
38/// the `CATALOGUE_SIGNING_KEY` Actions secret; rotating it means a release.
39pub const PINNED_KEY_HEX: &str = "b3df5624668f28f6a3e3c3280951902d9d2ebfd32c60b4bdcd7388ae54cad19d";
40
41fn pinned_key() -> [u8; 32] {
42    let mut k = [0u8; 32];
43    hex::decode_to_slice(PINNED_KEY_HEX, &mut k).expect("PINNED_KEY_HEX is 64 hex digits");
44    k
45}
46
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
48pub struct Provider {
49    pub prefix: String,
50    pub issuer: String,
51    pub secret_type: String,
52    pub icon: String,
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub api_url: Option<String>,
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub environment: Option<String>,
57    /// Taxonomy axes (Phase 24.5), applied by `enrich` as suggestions only.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub acts_as: Option<String>,
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    pub exposure: Option<String>,
62    /// Where to revoke or rotate it: proposed into the entry's `console_url`.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub console_url: Option<String>,
65    /// Reference links. Carried for the catalogue's readers; not applied to entries.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub docs_url: Option<String>,
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub rotate_url: Option<String>,
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub revoke_url: Option<String>,
72    /// Where the prefix is published and when somebody last checked it there
73    /// (Phase 31.3). Optional so older clients and older entries still parse.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub verified_on: Option<String>,
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub source_url: Option<String>,
78}
79
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81pub struct Catalogue {
82    pub schema: u32,
83    /// RFC 3339 UTC, fixed width, so string order is time order.
84    pub generated_at: String,
85    pub providers: Vec<Provider>,
86}
87
88/// On the wire: the payload is a JSON **string**, so the signature covers the
89/// exact bytes the publisher signed and no re-serialisation can disturb it.
90#[derive(Serialize, Deserialize)]
91struct Signed {
92    payload: String,
93    signature: String,
94}
95
96fn https(u: &Option<String>) -> bool {
97    u.as_deref()
98        .is_none_or(|s| s.starts_with("https://") && s.len() < 300)
99}
100
101fn validate(c: &Catalogue) -> Result<(), String> {
102    if c.schema != SCHEMA {
103        return Err(format!("unsupported catalogue schema {}", c.schema));
104    }
105    if c.generated_at.len() != 20 || !c.generated_at.ends_with('Z') {
106        return Err("generated_at must be YYYY-MM-DDTHH:MM:SSZ".into());
107    }
108    if c.providers.is_empty() || c.providers.len() > 20_000 {
109        return Err("provider count out of range".into());
110    }
111    for p in &c.providers {
112        let ok_prefix = p.prefix.len() >= 3
113            && p.prefix.len() <= 64
114            && p.prefix.bytes().all(|b| b.is_ascii_graphic());
115        if !ok_prefix {
116            return Err(format!("unusable prefix `{}`", p.prefix.escape_debug()));
117        }
118        if p.issuer.is_empty() || p.issuer.len() > 80 || p.icon.len() > 64 {
119            return Err(format!("bad issuer/icon for `{}`", p.prefix));
120        }
121        if crate::secret_types::find(&p.secret_type).is_none() {
122            return Err(format!("unknown secret type `{}`", p.secret_type));
123        }
124        if !(https(&p.api_url)
125            && https(&p.docs_url)
126            && https(&p.rotate_url)
127            && https(&p.revoke_url))
128        {
129            return Err(format!("non-https URL for `{}`", p.prefix));
130        }
131        if !(https(&p.console_url)) {
132            return Err(format!("non-https console URL for `{}`", p.prefix));
133        }
134        const ACTS: [&str; 6] = [
135            "anonymous",
136            "user",
137            "service",
138            "bot",
139            "installation",
140            "admin",
141        ];
142        const EXPO: [&str; 3] = ["publishable", "server_only", "verify_only"];
143        if p.acts_as.as_deref().is_some_and(|v| !ACTS.contains(&v))
144            || p.exposure.as_deref().is_some_and(|v| !EXPO.contains(&v))
145        {
146            return Err(format!("unknown axis value for `{}`", p.prefix));
147        }
148        if p.environment.as_deref().is_some_and(|e| e.len() > 24) {
149            return Err(format!("bad environment for `{}`", p.prefix));
150        }
151    }
152    Ok(())
153}
154
155/// Check signature and shape. Does not look at the cache.
156pub fn verify(raw: &[u8], key: &[u8; 32]) -> Result<Catalogue, String> {
157    let signed: Signed =
158        serde_json::from_slice(raw).map_err(|e| format!("not a catalogue: {e}"))?;
159    let sig = base64::engine::general_purpose::STANDARD
160        .decode(signed.signature.trim())
161        .map_err(|_| "signature is not base64".to_string())?;
162    let sig =
163        Signature::from_slice(&sig).map_err(|_| "signature has the wrong length".to_string())?;
164    let vk = VerifyingKey::from_bytes(key).map_err(|e| e.to_string())?;
165    vk.verify(signed.payload.as_bytes(), &sig)
166        .map_err(|_| "signature does not match the pinned key".to_string())?;
167    let c: Catalogue = serde_json::from_str(&signed.payload).map_err(|e| e.to_string())?;
168    validate(&c)?;
169    Ok(c)
170}
171
172/// Publisher side: sign `c` with a 32-byte Ed25519 seed. Used by
173/// `unv catalogue sign` in the scheduled workflow.
174pub fn sign(c: &Catalogue, seed: &[u8; 32]) -> Result<String, String> {
175    validate(c)?;
176    let payload = serde_json::to_string(c).map_err(|e| e.to_string())?;
177    let sig = SigningKey::from_bytes(seed).sign(payload.as_bytes());
178    let signature = base64::engine::general_purpose::STANDARD.encode(sig.to_bytes());
179    serde_json::to_string_pretty(&Signed { payload, signature }).map_err(|e| e.to_string())
180}
181
182pub fn cache_path() -> Option<PathBuf> {
183    if let Some(p) = std::env::var_os("UNV_CATALOGUE_FILE") {
184        return Some(PathBuf::from(p));
185    }
186    dirs::data_dir().map(|d| d.join("io.unenverse").join("catalogue.json"))
187}
188
189/// The cached catalogue, re-verified now. A bad or missing file is `None`, so
190/// enrichment falls back to the compiled table instead of failing.
191pub fn load_cached() -> Option<Catalogue> {
192    let raw = std::fs::read(cache_path()?).ok()?;
193    verify(&raw, &pinned_key()).ok()
194}
195
196/// Verify `raw` against the pinned key, refuse a rollback, and cache it
197/// atomically (0600). Returns the accepted catalogue.
198pub fn store(raw: &[u8]) -> Result<Catalogue, String> {
199    store_with(raw, &pinned_key())
200}
201
202fn store_with(raw: &[u8], key: &[u8; 32]) -> Result<Catalogue, String> {
203    let c = verify(raw, key)?;
204    if let Some(old) = load_cached_with(key) {
205        if c.generated_at < old.generated_at {
206            return Err(format!(
207                "refusing to roll back: cached catalogue is {}, offered one is {}",
208                old.generated_at, c.generated_at
209            ));
210        }
211    }
212    let path = cache_path().ok_or("no data directory")?;
213    if let Some(dir) = path.parent() {
214        std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
215    }
216    let tmp = path.with_extension("tmp");
217    std::fs::write(&tmp, raw).map_err(|e| e.to_string())?;
218    #[cfg(unix)]
219    {
220        use std::os::unix::fs::PermissionsExt;
221        std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600))
222            .map_err(|e| e.to_string())?;
223    }
224    crate::platform::replace_file(&tmp, &path).map_err(|e| e.to_string())?;
225    Ok(c)
226}
227
228fn load_cached_with(key: &[u8; 32]) -> Option<Catalogue> {
229    verify(&std::fs::read(cache_path()?).ok()?, key).ok()
230}
231
232#[cfg(test)]
233mod tests {
234    #[test]
235    fn the_default_url_is_https_on_the_project_domain() {
236        // The old github.io address answers 404, so a catalogue fetched from it was never found.
237        assert!(DEFAULT_URL.starts_with("https://unenverse.darthdemono.com/"));
238        assert!(DEFAULT_URL.ends_with("/catalogue/catalogue.json"));
239    }
240
241    use super::*;
242
243    const SEED: [u8; 32] = [7; 32];
244
245    fn key() -> [u8; 32] {
246        SigningKey::from_bytes(&SEED).verifying_key().to_bytes()
247    }
248
249    fn cat(at: &str) -> Catalogue {
250        Catalogue {
251            schema: 1,
252            generated_at: at.into(),
253            providers: vec![Provider {
254                prefix: "zz_".into(),
255                issuer: "Zed".into(),
256                secret_type: "api_key".into(),
257                icon: "zed".into(),
258                api_url: Some("https://api.zed.example".into()),
259                environment: None,
260                acts_as: None,
261                exposure: None,
262                console_url: None,
263                docs_url: None,
264                rotate_url: None,
265                revoke_url: None,
266                verified_on: None,
267                source_url: None,
268            }],
269        }
270    }
271
272    #[test]
273    fn the_pinned_key_is_a_valid_point() {
274        assert!(VerifyingKey::from_bytes(&pinned_key()).is_ok());
275    }
276
277    #[test]
278    fn signed_catalogue_verifies_and_tampering_does_not() {
279        let good = sign(&cat("2026-10-08T00:00:00Z"), &SEED).unwrap();
280        assert!(verify(good.as_bytes(), &key()).is_ok());
281        let bad = good.replace("Zed", "Zex");
282        assert!(verify(bad.as_bytes(), &key()).is_err());
283        assert!(verify(good.as_bytes(), &pinned_key()).is_err(), "wrong key");
284    }
285
286    #[test]
287    fn a_signed_but_overbroad_prefix_is_refused() {
288        let mut c = cat("2026-10-08T00:00:00Z");
289        c.providers[0].prefix = "s".into();
290        assert!(sign(&c, &SEED).is_err());
291        let mut c = cat("2026-10-08T00:00:00Z");
292        c.providers[0].api_url = Some("http://evil.example".into());
293        assert!(sign(&c, &SEED).is_err());
294    }
295
296    #[test]
297    fn an_unknown_axis_value_is_refused() {
298        let mut c = cat("2026-10-08T00:00:00Z");
299        c.providers[0].exposure = Some("public_ish".into());
300        assert!(sign(&c, &SEED).is_err());
301        c.providers[0].exposure = Some("publishable".into());
302        c.providers[0].acts_as = Some("bot".into());
303        assert!(sign(&c, &SEED).is_ok());
304    }
305
306    #[test]
307    fn rollback_is_refused() {
308        let dir = std::env::temp_dir().join(format!("unv-cat-{}", std::process::id()));
309        std::fs::create_dir_all(&dir).unwrap();
310        std::env::set_var("UNV_CATALOGUE_FILE", dir.join("c.json"));
311        let new = sign(&cat("2026-10-08T00:00:00Z"), &SEED).unwrap();
312        let old = sign(&cat("2026-10-07T00:00:00Z"), &SEED).unwrap();
313        store_with(new.as_bytes(), &key()).unwrap();
314        assert!(store_with(old.as_bytes(), &key())
315            .unwrap_err()
316            .contains("roll back"));
317        store_with(new.as_bytes(), &key()).unwrap();
318        std::env::remove_var("UNV_CATALOGUE_FILE");
319        std::fs::remove_dir_all(dir).ok();
320    }
321    #[test]
322    fn the_shipped_catalogue_file_parses_and_every_sourced_entry_is_complete() {
323        let list: Vec<Provider> =
324            serde_json::from_str(include_str!("../../catalogue/providers.json")).unwrap();
325        let mut seen = std::collections::HashSet::new();
326        for p in &list {
327            assert!(
328                seen.insert(p.prefix.clone()),
329                "duplicate prefix {}",
330                p.prefix
331            );
332            assert_eq!(
333                p.verified_on.is_some(),
334                p.source_url.is_some(),
335                "{}: verified_on and source_url go together",
336                p.prefix
337            );
338            if let Some(u) = &p.source_url {
339                assert!(
340                    u.starts_with("https://"),
341                    "{}: source must be https",
342                    p.prefix
343                );
344                assert!(p.prefix.len() >= 4, "{}: too short to be safe", p.prefix);
345            }
346        }
347    }
348}