Skip to main content

qualia_client_core/
webizen_trust.rs

1//! **Webizen trust store** — user-controlled trust anchors (P1).
2//!
3//! The software provides the *means* to import, enable, disable, and evaluate roots;
4//! it does not silently redefine the OS PKI. Default suggested set is empty until the
5//! principal coins a bundle (AU community roots, etc.).
6//!
7//! Honest scope of this module:
8//! - Persist anchors (PEM certs, DID / front-door identifiers, labels).
9//! - Produce a **trust verdict** for a URL (scheme + store membership + notes).
10//! - Supply PEM material for *our* TLS clients (agent fetch via rustls/reqwest).
11//! - OS WebView cert-override (WebView2 `ServerCertificateErrorDetected`) is a
12//!   platform hook layered in `webizen-desktop`; this store is the policy source.
13
14use std::fs;
15use std::path::{Path, PathBuf};
16
17use serde::{Deserialize, Serialize};
18use sha2::{Digest, Sha256};
19
20pub const TRUST_STORE_FILE: &str = "webizen/trust_store.json";
21/// Suggested catalog (empty until principal curates). Relative to storage or bundled.
22pub const SUGGESTED_CATALOG_FILE: &str = "webizen/suggested_trust_catalog.json";
23pub const CATALOG_VERSION: u32 = 1;
24
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
26#[serde(rename_all = "snake_case")]
27pub enum AnchorKind {
28    /// X.509 root or intermediate PEM.
29    PemRoot,
30    /// Front-door / connection DID or WebID.
31    Did,
32    /// Opaque label the principal trusts by policy (e.g. micro-commons id).
33    PolicyLabel,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct TrustAnchor {
38    pub id: String,
39    pub label: String,
40    pub kind: AnchorKind,
41    /// PEM body for PemRoot; DID URI for Did; free text for PolicyLabel.
42    pub material: String,
43    pub enabled: bool,
44    pub notes: String,
45    pub added_unix: u64,
46    #[serde(default)]
47    pub jurisdiction: Option<String>,
48    #[serde(default)]
49    pub signature_algorithm: Option<String>,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize, Default)]
53pub struct TrustStore {
54    pub version: u32,
55    pub anchors: Vec<TrustAnchor>,
56    /// When true, http(s) sites with no matching custom policy are labelled "os-default".
57    pub defer_unknown_https_to_os: bool,
58}
59
60impl TrustStore {
61    /// Creates a new instance.
62    pub fn new() -> Self {
63        Self {
64            version: 1,
65            anchors: Vec::new(),
66            defer_unknown_https_to_os: true,
67        }
68    }
69
70    /// Path.
71    pub fn path(storage_root: &Path) -> PathBuf {
72        storage_root.join(TRUST_STORE_FILE)
73    }
74
75    /// Loads.
76    pub fn load(storage_root: &Path) -> Self {
77        let p = Self::path(storage_root);
78        match fs::read_to_string(&p) {
79            Ok(s) => serde_json::from_str(&s).unwrap_or_else(|_| Self::new()),
80            Err(_) => Self::new(),
81        }
82    }
83
84    /// Saves.
85    pub fn save(&self, storage_root: &Path) -> Result<(), String> {
86        let p = Self::path(storage_root);
87        if let Some(parent) = p.parent() {
88            fs::create_dir_all(parent).map_err(|e| e.to_string())?;
89        }
90        let bytes = serde_json::to_vec_pretty(self).map_err(|e| e.to_string())?;
91        let tmp = p.with_extension("json.tmp");
92        fs::write(&tmp, &bytes).map_err(|e| e.to_string())?;
93        fs::rename(&tmp, &p).map_err(|e| e.to_string())
94    }
95
96    /// Adds pem-root.
97    pub fn add_pem_root(
98        &mut self,
99        label: &str,
100        pem: &str,
101        notes: &str,
102        now: u64,
103    ) -> Result<TrustAnchor, String> {
104        let pem = pem.trim();
105        if !pem.contains("BEGIN CERTIFICATE") {
106            return Err("expected PEM certificate (BEGIN CERTIFICATE)".into());
107        }
108        let id = format!("pem:{}", short_hash(pem.as_bytes()));
109        if self.anchors.iter().any(|a| a.id == id) {
110            return Err("anchor already present".into());
111        }
112        let a = TrustAnchor {
113            id: id.clone(),
114            label: if label.trim().is_empty() {
115                format!("Root {id}")
116            } else {
117                label.trim().into()
118            },
119            kind: AnchorKind::PemRoot,
120            material: pem.into(),
121            enabled: true,
122            notes: notes.into(),
123            added_unix: now,
124            jurisdiction: None,
125            signature_algorithm: None,
126        };
127        self.anchors.push(a.clone());
128        Ok(a)
129    }
130
131    /// Adds a PEM root with explicit jurisdiction (e.g. "AU") and signature algorithm (e.g. "ML-DSA-65", "Ed25519").
132    pub fn add_jurisdiction_pem_root(
133        &mut self,
134        label: &str,
135        pem: &str,
136        jurisdiction: &str,
137        signature_algorithm: &str,
138        notes: &str,
139        now: u64,
140    ) -> Result<TrustAnchor, String> {
141        let pem = pem.trim();
142        if !pem.contains("BEGIN CERTIFICATE") {
143            return Err("expected PEM certificate (BEGIN CERTIFICATE)".into());
144        }
145        let id = format!("pem:{}", short_hash(pem.as_bytes()));
146        if self.anchors.iter().any(|a| a.id == id) {
147            return Err("anchor already present".into());
148        }
149        let a = TrustAnchor {
150            id: id.clone(),
151            label: if label.trim().is_empty() {
152                format!("Root {id}")
153            } else {
154                label.trim().into()
155            },
156            kind: AnchorKind::PemRoot,
157            material: pem.into(),
158            enabled: true,
159            notes: notes.into(),
160            added_unix: now,
161            jurisdiction: if jurisdiction.trim().is_empty() {
162                None
163            } else {
164                Some(jurisdiction.trim().to_string())
165            },
166            signature_algorithm: if signature_algorithm.trim().is_empty() {
167                None
168            } else {
169                Some(signature_algorithm.trim().to_string())
170            },
171        };
172        self.anchors.push(a.clone());
173        Ok(a)
174    }
175
176    /// Adds did.
177    pub fn add_did(
178        &mut self,
179        label: &str,
180        did: &str,
181        notes: &str,
182        now: u64,
183    ) -> Result<TrustAnchor, String> {
184        let did = did.trim();
185        if !did.starts_with("did:") {
186            return Err("DID must start with did:".into());
187        }
188        let id = format!("did:{}", short_hash(did.as_bytes()));
189        if self.anchors.iter().any(|a| a.material == did) {
190            return Err("DID already present".into());
191        }
192        let a = TrustAnchor {
193            id,
194            label: if label.trim().is_empty() {
195                did.to_string()
196            } else {
197                label.trim().into()
198            },
199            kind: AnchorKind::Did,
200            material: did.into(),
201            enabled: true,
202            notes: notes.into(),
203            added_unix: now,
204            jurisdiction: None,
205            signature_algorithm: None,
206        };
207        self.anchors.push(a.clone());
208        Ok(a)
209    }
210
211    /// Sets enabled.
212    pub fn set_enabled(&mut self, id: &str, enabled: bool) -> Result<(), String> {
213        let a = self
214            .anchors
215            .iter_mut()
216            .find(|a| a.id == id)
217            .ok_or_else(|| format!("unknown anchor {id}"))?;
218        a.enabled = enabled;
219        Ok(())
220    }
221
222    /// Removes.
223    pub fn remove(&mut self, id: &str) -> bool {
224        let before = self.anchors.len();
225        self.anchors.retain(|a| a.id != id);
226        self.anchors.len() < before
227    }
228
229    /// Enabled PEM roots concatenated for rustls/custom clients.
230    pub fn enabled_pem_bundle(&self) -> String {
231        self.anchors
232            .iter()
233            .filter(|a| a.enabled && a.kind == AnchorKind::PemRoot)
234            .map(|a| a.material.as_str())
235            .collect::<Vec<_>>()
236            .join("\n")
237    }
238
239    /// Enabled PEM root anchors matching the given jurisdiction (e.g. "AU", case-insensitive).
240    pub fn enabled_pem_roots_for_jurisdiction(&self, jurisdiction: &str) -> Vec<&TrustAnchor> {
241        let target = jurisdiction.trim();
242        self.anchors
243            .iter()
244            .filter(|a| {
245                a.enabled
246                    && a.kind == AnchorKind::PemRoot
247                    && a.jurisdiction
248                        .as_deref()
249                        .map(|j| j.eq_ignore_ascii_case(target))
250                        .unwrap_or(false)
251            })
252            .collect()
253    }
254
255    /// Export all enabled PEM root blocks concatenated as a bundle for TLS verifiers (e.g. Chora).
256    pub fn export_enabled_pem_bundle(&self) -> String {
257        self.enabled_pem_bundle()
258    }
259
260    /// Enabled DIDs.
261    pub fn enabled_dids(&self) -> Vec<&str> {
262        self.anchors
263            .iter()
264            .filter(|a| a.enabled && a.kind == AnchorKind::Did)
265            .map(|a| a.material.as_str())
266            .collect()
267    }
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct TrustVerdict {
272    pub url: String,
273    pub scheme: String,
274    pub host: String,
275    /// os_default | custom_root_available | did_match | local_scheme | untrusted_policy | unknown
276    pub level: String,
277    pub summary: String,
278    pub matching_anchors: Vec<String>,
279    pub notes: Vec<String>,
280}
281
282/// Evaluate how *our* store thinks about this URL (does not replace OS TLS for WebView).
283pub fn evaluate_url(store: &TrustStore, url: &str) -> TrustVerdict {
284    let url = url.trim();
285    let (scheme, host) = parse_scheme_host(url);
286    let mut matching = Vec::new();
287    let mut notes = Vec::new();
288
289    if scheme == "qualia" || scheme == "webizen" {
290        return TrustVerdict {
291            url: url.into(),
292            scheme: scheme.clone(),
293            host: host.clone(),
294            level: "local_scheme".into(),
295            summary: "Local Qualia/Webizen scheme — rendered under your device policy, not public CA trust."
296                .into(),
297            matching_anchors: Vec::new(),
298            notes: vec!["Native protocol handler; not subject to public web PKI.".into()],
299        };
300    }
301
302    // DID anchors: match if host or path contains the DID, or URL is a did:
303    for a in store
304        .anchors
305        .iter()
306        .filter(|a| a.enabled && a.kind == AnchorKind::Did)
307    {
308        if url.contains(&a.material) || host.contains(&a.material) {
309            matching.push(a.label.clone());
310        }
311    }
312    if !matching.is_empty() {
313        return TrustVerdict {
314            url: url.into(),
315            scheme,
316            host,
317            level: "did_match".into(),
318            summary: format!(
319                "Matches DID/front-door anchor(s) in your store: {}.",
320                matching.join(", ")
321            ),
322            matching_anchors: matching,
323            notes: vec![
324                "DID trust is policy-level in Webizen; OS TLS may still apply for https.".into(),
325            ],
326        };
327    }
328
329    let pem_count = store
330        .anchors
331        .iter()
332        .filter(|a| a.enabled && a.kind == AnchorKind::PemRoot)
333        .count();
334    if pem_count > 0 {
335        notes.push(format!(
336            "{pem_count} custom PEM root(s) enabled — used for agent HTTPS fetch; WebView still uses OS store unless platform cert-override is wired."
337        ));
338    }
339
340    if scheme == "https" || scheme == "http" {
341        let level = if store.defer_unknown_https_to_os {
342            "os_default"
343        } else {
344            "untrusted_policy"
345        };
346        let summary = if store.defer_unknown_https_to_os {
347            "No custom DID match. HTTPS validation defers to the OS trust store (WebView)."
348                .to_string()
349        } else {
350            "defer_unknown_https_to_os=false: treat unknown public sites as untrusted by policy."
351                .to_string()
352        };
353        return TrustVerdict {
354            url: url.into(),
355            scheme,
356            host,
357            level: level.into(),
358            summary,
359            matching_anchors: matching,
360            notes,
361        };
362    }
363
364    TrustVerdict {
365        url: url.into(),
366        scheme,
367        host,
368        level: "unknown".into(),
369        summary: "Scheme not classified by the Webizen trust policy.".into(),
370        matching_anchors: matching,
371        notes,
372    }
373}
374
375fn parse_scheme_host(url: &str) -> (String, String) {
376    let u = url.trim();
377    if let Some(rest) = u.strip_prefix("https://") {
378        let host = rest.split(['/', '?', '#']).next().unwrap_or("").to_string();
379        return ("https".into(), host);
380    }
381    if let Some(rest) = u.strip_prefix("http://") {
382        let host = rest.split(['/', '?', '#']).next().unwrap_or("").to_string();
383        return ("http".into(), host);
384    }
385    if let Some(rest) = u.strip_prefix("qualia://") {
386        return ("qualia".into(), rest.to_string());
387    }
388    if let Some(rest) = u.strip_prefix("webizen://") {
389        return ("webizen".into(), rest.to_string());
390    }
391    if u.starts_with("did:") {
392        return ("did".into(), u.to_string());
393    }
394    ("unknown".into(), u.to_string())
395}
396
397fn short_hash(bytes: &[u8]) -> String {
398    let mut h = Sha256::new();
399    h.update(bytes);
400    let d = h.finalize();
401    hex::encode(&d[..8])
402}
403
404// ── Suggested trust catalog (T0/T1) — means only; no invented roots ──────────
405
406/// One **suggested** anchor. Never auto-enabled unless `enabled_by_default` is true
407/// (must stay false until the principal explicitly curates a default).
408#[derive(Debug, Clone, Serialize, Deserialize)]
409pub struct SuggestedAnchor {
410    pub id: String,
411    pub label: String,
412    /// Jurisdiction or community tag (e.g. "AU", "micro-commons") — free text.
413    #[serde(default)]
414    pub jurisdiction: String,
415    pub kind: AnchorKind,
416    /// Inline PEM / DID / label material. Prefer inline for small catalogs.
417    #[serde(default)]
418    pub material: String,
419    /// Optional path relative to catalog dir (e.g. `roots/example.pem`). Loaded if material empty.
420    #[serde(default)]
421    pub material_path: Option<String>,
422    /// Must be false for ship defaults until principal curates.
423    #[serde(default)]
424    pub enabled_by_default: bool,
425    #[serde(default)]
426    pub notes: String,
427    #[serde(default)]
428    pub source_url: Option<String>,
429    #[serde(default)]
430    pub license: Option<String>,
431}
432
433#[derive(Debug, Clone, Serialize, Deserialize)]
434pub struct SuggestedTrustCatalog {
435    pub version: u32,
436    #[serde(default)]
437    pub description: String,
438    #[serde(default)]
439    pub entries: Vec<SuggestedAnchor>,
440}
441
442impl Default for SuggestedTrustCatalog {
443    fn default() -> Self {
444        Self {
445            version: CATALOG_VERSION,
446            description: "Empty suggested trust catalog. Principal curates content; software provides means only.".into(),
447            entries: Vec::new(),
448        }
449    }
450}
451
452impl SuggestedTrustCatalog {
453    /// `true` when empty / empty set.
454    pub fn empty() -> Self {
455        Self::default()
456    }
457
458    /// Load catalog from JSON bytes. Malformed → Err (fail closed).
459    pub fn from_json_bytes(bytes: &[u8]) -> Result<Self, String> {
460        if bytes.is_empty() {
461            return Ok(Self::empty());
462        }
463        serde_json::from_slice(bytes).map_err(|e| format!("suggested catalog parse: {e}"))
464    }
465
466    /// Constructs from json-str.
467    pub fn from_json_str(s: &str) -> Result<Self, String> {
468        Self::from_json_bytes(s.as_bytes())
469    }
470
471    /// Load from a file path; missing file → empty catalog (not an error).
472    pub fn load_path(path: &Path) -> Result<Self, String> {
473        match fs::read(path) {
474            Ok(b) => Self::from_json_bytes(&b),
475            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::empty()),
476            Err(e) => Err(e.to_string()),
477        }
478    }
479
480    /// Prefer storage override, else bundled path next to catalog default location.
481    pub fn load_for_storage(storage_root: &Path) -> Result<Self, String> {
482        let storage_cat = storage_root.join(SUGGESTED_CATALOG_FILE);
483        if storage_cat.is_file() {
484            return Self::load_path(&storage_cat);
485        }
486        // Bundled empty catalog (repo / package).
487        if let Some(bundled) = bundled_catalog_path() {
488            return Self::load_path(&bundled);
489        }
490        Ok(Self::empty())
491    }
492
493    /// Gets.
494    pub fn get(&self, id: &str) -> Option<&SuggestedAnchor> {
495        self.entries.iter().find(|e| e.id == id)
496    }
497
498    /// Resolve material for an entry (inline or file relative to `base_dir`).
499    pub fn resolve_material(
500        &self,
501        entry: &SuggestedAnchor,
502        base_dir: &Path,
503    ) -> Result<String, String> {
504        let inline = entry.material.trim();
505        if !inline.is_empty() {
506            return Ok(inline.to_string());
507        }
508        if let Some(rel) = entry.material_path.as_deref() {
509            let p = base_dir.join(rel);
510            return fs::read_to_string(&p).map_err(|e| format!("read {}: {e}", p.display()));
511        }
512        Err(format!("suggested anchor {} has no material", entry.id))
513    }
514}
515
516/// Path to repo/package empty catalog when present.
517pub fn bundled_catalog_path() -> Option<PathBuf> {
518    // Desktop: next to exe resources or relative to CARGO_MANIFEST of client-core.
519    let candidates = [
520        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../bundled/trust/catalog.json"),
521        PathBuf::from("bundled/trust/catalog.json"),
522    ];
523    candidates.into_iter().find(|p| p.is_file())
524}
525
526/// Import a suggested entry into the live store.
527/// `force_enabled` overrides `enabled_by_default` (UI "Enable now").
528pub fn import_suggested_into_store(
529    store: &mut TrustStore,
530    catalog: &SuggestedTrustCatalog,
531    entry_id: &str,
532    base_dir: &Path,
533    now: u64,
534    force_enabled: bool,
535) -> Result<TrustAnchor, String> {
536    let entry = catalog
537        .get(entry_id)
538        .ok_or_else(|| format!("unknown suggested id {entry_id}"))?;
539    let material = catalog.resolve_material(entry, base_dir)?;
540    let enabled = force_enabled || entry.enabled_by_default;
541    match entry.kind {
542        AnchorKind::PemRoot => {
543            let mut a = store.add_pem_root(&entry.label, &material, &entry.notes, now)?;
544            if !entry.jurisdiction.trim().is_empty() {
545                if let Some(anchor) = store.anchors.iter_mut().find(|x| x.id == a.id) {
546                    anchor.jurisdiction = Some(entry.jurisdiction.trim().to_string());
547                    a.jurisdiction = Some(entry.jurisdiction.trim().to_string());
548                }
549            }
550            if !enabled {
551                let _ = store.set_enabled(&a.id, false);
552            }
553            Ok(store
554                .anchors
555                .iter()
556                .find(|x| x.id == a.id)
557                .cloned()
558                .unwrap_or(a))
559        }
560        AnchorKind::Did => {
561            let a = store.add_did(&entry.label, &material, &entry.notes, now)?;
562            if !enabled {
563                let _ = store.set_enabled(&a.id, false);
564            }
565            Ok(store
566                .anchors
567                .iter()
568                .find(|x| x.id == a.id)
569                .cloned()
570                .unwrap_or(a))
571        }
572        AnchorKind::PolicyLabel => {
573            let id = format!("policy:{}", short_hash(material.as_bytes()));
574            if store.anchors.iter().any(|a| a.id == id) {
575                return Err("anchor already present".into());
576            }
577            let a = TrustAnchor {
578                id: id.clone(),
579                label: entry.label.clone(),
580                kind: AnchorKind::PolicyLabel,
581                material,
582                enabled,
583                notes: entry.notes.clone(),
584                added_unix: now,
585                jurisdiction: if entry.jurisdiction.trim().is_empty() {
586                    None
587                } else {
588                    Some(entry.jurisdiction.trim().to_string())
589                },
590                signature_algorithm: None,
591            };
592            store.anchors.push(a.clone());
593            Ok(a)
594        }
595    }
596}
597
598/// Host / session / chain policy decision for cert-override (swarm-2).
599///
600/// Security model: host-pin (A) by default path; chain vs **enabled** PEMs (B) only
601/// after cryptographic verify; never auto-allow solely because PEMs exist.
602#[derive(Debug, Clone, Copy, PartialEq, Eq)]
603pub enum CertOverrideDecision {
604    /// No policy match — deny by default.
605    Deny,
606    /// Soft sticky deny (principal chose Deny and asked not to re-prompt).
607    SoftDenied,
608    /// Explicit host allow entry (policy label `host-allow:example.com`) — A.
609    AllowHostPinned,
610    /// Session allow-once (process memory; not a permanent pin).
611    AllowSessionOnce,
612    /// PEM roots enabled: platform **must** call chain verify; without cert material → deny.
613    /// This is **not** an automatic allow.
614    CandidateCustomRoots,
615    /// Chain verified against enabled PEMs (B accepted).
616    AllowChainVerified,
617    /// SPKI pin matched.
618    AllowSpkiPinned,
619}
620
621/// SPKI pin material: `spki-pin:<host>:<sha256hex>`
622pub fn spki_pin_material(host: &str, spki_sha256_hex: &str) -> String {
623    format!(
624        "spki-pin:{}:{}",
625        host.trim().to_ascii_lowercase(),
626        spki_sha256_hex.trim().to_ascii_lowercase()
627    )
628}
629
630/// Soft-deny material: `host-deny:<host>`
631pub fn host_deny_material(host: &str) -> String {
632    format!("host-deny:{}", host.trim().to_ascii_lowercase())
633}
634
635/// Policy for ServerCertificateErrorDetected handlers (store only — no session).
636/// Prefer [`cert_override_decision_full`] for production hooks.
637pub fn cert_override_decision(store: &TrustStore, host: &str) -> CertOverrideDecision {
638    cert_override_decision_full(store, host, false, false, None)
639}
640
641/// Full policy: store + optional session allow-once + optional chain verify result.
642///
643/// `session_allow` — process-local allow-once for this host.  
644/// `soft_denied` — sticky deny without re-prompt.  
645/// `chain_verified` — `Some(true/false)` after B path crypto; `None` if no leaf PEM available.
646pub fn cert_override_decision_full(
647    store: &TrustStore,
648    host: &str,
649    session_allow: bool,
650    soft_denied: bool,
651    chain_verified: Option<bool>,
652) -> CertOverrideDecision {
653    let host = host.trim().to_ascii_lowercase();
654    if host.is_empty() {
655        return CertOverrideDecision::Deny;
656    }
657    if soft_denied {
658        return CertOverrideDecision::SoftDenied;
659    }
660    // Soft-deny in store
661    for a in store.anchors.iter().filter(|a| a.enabled) {
662        if a.kind == AnchorKind::PolicyLabel {
663            let m = a.material.trim().to_ascii_lowercase();
664            if m == host_deny_material(&host) {
665                return CertOverrideDecision::SoftDenied;
666            }
667        }
668    }
669    // A: host pin
670    for a in store.anchors.iter().filter(|a| a.enabled) {
671        if a.kind == AnchorKind::PolicyLabel {
672            let m = a.material.trim().to_ascii_lowercase();
673            if m == format!("host-allow:{host}") || m == host {
674                return CertOverrideDecision::AllowHostPinned;
675            }
676        }
677    }
678    // Session allow-once (escape hatch; not permanent)
679    if session_allow {
680        return CertOverrideDecision::AllowSessionOnce;
681    }
682    // B: chain verify result
683    if let Some(ok) = chain_verified {
684        if ok {
685            return CertOverrideDecision::AllowChainVerified;
686        }
687        // verified false → fall through to candidate/deny
688    }
689    let pem_n = store
690        .anchors
691        .iter()
692        .filter(|a| a.enabled && a.kind == AnchorKind::PemRoot)
693        .count();
694    if pem_n > 0 {
695        // Without a successful chain_verified=true, do **not** allow.
696        // Signal that B could apply if platform supplies leaf PEM.
697        return CertOverrideDecision::CandidateCustomRoots;
698    }
699    CertOverrideDecision::Deny
700}
701
702/// Whether the decision should allow the WebView TLS connection.
703pub fn decision_allows(d: CertOverrideDecision) -> bool {
704    matches!(
705        d,
706        CertOverrideDecision::AllowHostPinned
707            | CertOverrideDecision::AllowSessionOnce
708            | CertOverrideDecision::AllowChainVerified
709            | CertOverrideDecision::AllowSpkiPinned
710    )
711}
712
713/// Audit-friendly reason string.
714pub fn decision_reason(d: CertOverrideDecision) -> &'static str {
715    match d {
716        CertOverrideDecision::Deny => "deny",
717        CertOverrideDecision::SoftDenied => "soft_deny",
718        CertOverrideDecision::AllowHostPinned => "host_pin",
719        CertOverrideDecision::AllowSessionOnce => "session_once",
720        CertOverrideDecision::CandidateCustomRoots => "candidate_custom_roots_need_verify",
721        CertOverrideDecision::AllowChainVerified => "chain_verified",
722        CertOverrideDecision::AllowSpkiPinned => "spki_pin",
723    }
724}
725
726// ── Signed suggested catalog (principal key) ─────────────────────────────────
727
728/// Envelope for a suggested catalog signed by the principal.
729#[derive(Debug, Clone, Serialize, Deserialize)]
730pub struct SignedSuggestedCatalog {
731    pub catalog: SuggestedTrustCatalog,
732    /// Ed25519 signature over `canonical_catalog_bytes` (hex).
733    pub signature_hex: String,
734    /// Ed25519 public key (32 bytes hex) of the signing principal.
735    pub public_key_hex: String,
736    #[serde(default)]
737    pub algorithm: String,
738}
739
740/// Canonical bytes for signing: JSON of catalog with sorted keys (serde_json value dump).
741pub fn catalog_signing_payload(catalog: &SuggestedTrustCatalog) -> Result<Vec<u8>, String> {
742    // Deterministic: pretty=false, field order as struct definition.
743    serde_json::to_vec(catalog).map_err(|e| e.to_string())
744}
745
746/// Verify Ed25519 signature over the catalog payload.
747pub fn verify_signed_catalog(envelope: &SignedSuggestedCatalog) -> Result<(), String> {
748    use ed25519_dalek::{Signature, Verifier, VerifyingKey};
749    let algo = envelope.algorithm.trim().to_ascii_lowercase();
750    if !algo.is_empty() && algo != "ed25519" {
751        return Err(format!(
752            "unsupported catalog algorithm '{algo}' (ed25519 only in this build)"
753        ));
754    }
755    let pk_bytes =
756        hex::decode(envelope.public_key_hex.trim()).map_err(|e| format!("public_key_hex: {e}"))?;
757    if pk_bytes.len() != 32 {
758        return Err("public_key_hex must be 32 bytes".into());
759    }
760    let mut pk_arr = [0u8; 32];
761    pk_arr.copy_from_slice(&pk_bytes);
762    let vk = VerifyingKey::from_bytes(&pk_arr).map_err(|e| format!("verifying key: {e}"))?;
763    let sig_bytes =
764        hex::decode(envelope.signature_hex.trim()).map_err(|e| format!("signature_hex: {e}"))?;
765    if sig_bytes.len() != 64 {
766        return Err("signature must be 64 bytes".into());
767    }
768    let mut sig_arr = [0u8; 64];
769    sig_arr.copy_from_slice(&sig_bytes);
770    let sig = Signature::from_bytes(&sig_arr);
771    let payload = catalog_signing_payload(&envelope.catalog)?;
772    vk.verify(&payload, &sig)
773        .map_err(|_| "catalog signature invalid".to_string())?;
774    Ok(())
775}
776
777/// Load signed catalog from path; unsigned plain catalog still loads via SuggestedTrustCatalog.
778pub fn load_signed_catalog_path(path: &Path) -> Result<SuggestedTrustCatalog, String> {
779    let bytes = fs::read(path).map_err(|e| e.to_string())?;
780    // Try signed envelope first
781    if let Ok(env) = serde_json::from_slice::<SignedSuggestedCatalog>(&bytes) {
782        if !env.signature_hex.is_empty() {
783            verify_signed_catalog(&env)?;
784            return Ok(env.catalog);
785        }
786    }
787    SuggestedTrustCatalog::from_json_bytes(&bytes)
788}
789
790#[cfg(test)]
791mod tests {
792    use super::*;
793
794    #[test]
795    fn pem_and_did_roundtrip() {
796        let dir = tempfile::tempdir().unwrap();
797        let mut s = TrustStore::new();
798        s.add_did("Front door", "did:web:example.org", "test", 1)
799            .unwrap();
800        let pem = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n";
801        s.add_pem_root("Test root", pem, "", 2).unwrap();
802        s.save(dir.path()).unwrap();
803        let loaded = TrustStore::load(dir.path());
804        assert_eq!(loaded.anchors.len(), 2);
805        let v = evaluate_url(&loaded, "https://example.org/x?ref=did:web:example.org");
806        assert_eq!(v.level, "did_match");
807        let v2 = evaluate_url(&loaded, "https://google.com/");
808        assert_eq!(v2.level, "os_default");
809        let v3 = evaluate_url(&loaded, "qualia://webid/did:q42:local");
810        assert_eq!(v3.level, "local_scheme");
811    }
812
813    #[test]
814    fn add_did_then_remove_reverts_verdict() {
815        let dir = tempfile::tempdir().unwrap();
816        let mut s = TrustStore::new();
817        let a = s
818            .add_did("Peer", "did:web:trusted.example", "", 10)
819            .unwrap();
820        s.save(dir.path()).unwrap();
821        let loaded = TrustStore::load(dir.path());
822        let url = "https://site.test/?id=did:web:trusted.example";
823        assert_eq!(evaluate_url(&loaded, url).level, "did_match");
824        let mut s2 = TrustStore::load(dir.path());
825        assert!(s2.remove(&a.id));
826        s2.save(dir.path()).unwrap();
827        let loaded2 = TrustStore::load(dir.path());
828        assert_eq!(evaluate_url(&loaded2, url).level, "os_default");
829    }
830
831    #[test]
832    fn disable_anchor_skips_match() {
833        let dir = tempfile::tempdir().unwrap();
834        let mut s = TrustStore::new();
835        let a = s.add_did("Peer", "did:web:off.example", "", 1).unwrap();
836        s.set_enabled(&a.id, false).unwrap();
837        s.save(dir.path()).unwrap();
838        let loaded = TrustStore::load(dir.path());
839        let v = evaluate_url(&loaded, "https://x/?did:web:off.example");
840        assert_eq!(v.level, "os_default");
841    }
842
843    #[test]
844    fn empty_catalog_loads() {
845        let c = SuggestedTrustCatalog::from_json_str(
846            r#"{"version":1,"description":"test","entries":[]}"#,
847        )
848        .unwrap();
849        assert!(c.entries.is_empty());
850        assert_eq!(SuggestedTrustCatalog::empty().entries.len(), 0);
851    }
852
853    #[test]
854    fn malformed_catalog_fails_closed() {
855        assert!(SuggestedTrustCatalog::from_json_str("{not json").is_err());
856    }
857
858    #[test]
859    fn import_suggested_did_disabled_by_default() {
860        let cat = SuggestedTrustCatalog {
861            version: 1,
862            description: "fixture".into(),
863            entries: vec![SuggestedAnchor {
864                id: "sug-did-1".into(),
865                label: "Suggested peer".into(),
866                jurisdiction: "test".into(),
867                kind: AnchorKind::Did,
868                material: "did:web:suggested.example".into(),
869                material_path: None,
870                enabled_by_default: false,
871                notes: "fixture only".into(),
872                source_url: None,
873                license: None,
874            }],
875        };
876        let mut store = TrustStore::new();
877        let a =
878            import_suggested_into_store(&mut store, &cat, "sug-did-1", Path::new("."), 1, false)
879                .unwrap();
880        assert!(!a.enabled);
881        assert_eq!(
882            cert_override_decision(&store, "evil.example"),
883            CertOverrideDecision::Deny
884        );
885    }
886
887    #[test]
888    fn cert_override_host_pin() {
889        let mut s = TrustStore::new();
890        s.anchors.push(TrustAnchor {
891            id: "policy:host".into(),
892            label: "Pin".into(),
893            kind: AnchorKind::PolicyLabel,
894            material: "host-allow:intranet.local".into(),
895            enabled: true,
896            notes: "".into(),
897            added_unix: 1,
898            jurisdiction: None,
899            signature_algorithm: None,
900        });
901        assert_eq!(
902            cert_override_decision(&s, "intranet.local"),
903            CertOverrideDecision::AllowHostPinned
904        );
905        assert_eq!(
906            cert_override_decision(&s, "other.local"),
907            CertOverrideDecision::Deny
908        );
909    }
910
911    #[test]
912    fn pem_roots_alone_do_not_allow() {
913        let mut s = TrustStore::new();
914        s.anchors.push(TrustAnchor {
915            id: "pem:x".into(),
916            label: "x".into(),
917            kind: AnchorKind::PemRoot,
918            material: "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n".into(),
919            enabled: true,
920            notes: "".into(),
921            added_unix: 1,
922            jurisdiction: None,
923            signature_algorithm: None,
924        });
925        // Swarm-2: PEMs present → candidate only, never auto-allow without chain verify.
926        assert_eq!(
927            cert_override_decision(&s, "intranet.local"),
928            CertOverrideDecision::CandidateCustomRoots
929        );
930        assert!(!decision_allows(CertOverrideDecision::CandidateCustomRoots));
931        assert!(decision_allows(CertOverrideDecision::AllowHostPinned));
932        let d = cert_override_decision_full(&s, "h.test", false, false, Some(true));
933        assert_eq!(d, CertOverrideDecision::AllowChainVerified);
934        assert!(decision_allows(d));
935    }
936
937    #[test]
938    fn jurisdiction_pem_roots_and_bundle_export() {
939        let mut s = TrustStore::new();
940        let pem_au = "-----BEGIN CERTIFICATE-----\nMIIC_AU_ROOT\n-----END CERTIFICATE-----\n";
941        let pem_global = "-----BEGIN CERTIFICATE-----\nMIIC_GLOBAL_ROOT\n-----END CERTIFICATE-----\n";
942
943        let au_anchor = s
944            .add_jurisdiction_pem_root(
945                "Australian Community Root",
946                pem_au,
947                "AU",
948                "ML-DSA-65",
949                "Community Post-Quantum Root for AU ecosystem",
950                100,
951            )
952            .unwrap();
953
954        assert_eq!(au_anchor.jurisdiction.as_deref(), Some("AU"));
955        assert_eq!(au_anchor.signature_algorithm.as_deref(), Some("ML-DSA-65"));
956
957        let global_anchor = s
958            .add_pem_root("Global Root", pem_global, "Standard X.509 root", 101)
959            .unwrap();
960        assert_eq!(global_anchor.jurisdiction, None);
961        assert_eq!(global_anchor.signature_algorithm, None);
962
963        // Filter by "AU"
964        let au_roots = s.enabled_pem_roots_for_jurisdiction("AU");
965        assert_eq!(au_roots.len(), 1);
966        assert_eq!(au_roots[0].id, au_anchor.id);
967
968        // Case-insensitive jurisdiction filter
969        let au_roots_lower = s.enabled_pem_roots_for_jurisdiction("au");
970        assert_eq!(au_roots_lower.len(), 1);
971
972        // Mismatched jurisdiction filter
973        let us_roots = s.enabled_pem_roots_for_jurisdiction("US");
974        assert_eq!(us_roots.len(), 0);
975
976        // Export bundle contains both enabled roots
977        let bundle = s.export_enabled_pem_bundle();
978        assert!(bundle.contains("MIIC_AU_ROOT"));
979        assert!(bundle.contains("MIIC_GLOBAL_ROOT"));
980
981        // When AU root is disabled, it is excluded from jurisdiction query and bundle
982        s.set_enabled(&au_anchor.id, false).unwrap();
983        assert_eq!(s.enabled_pem_roots_for_jurisdiction("AU").len(), 0);
984        let bundle2 = s.export_enabled_pem_bundle();
985        assert!(!bundle2.contains("MIIC_AU_ROOT"));
986        assert!(bundle2.contains("MIIC_GLOBAL_ROOT"));
987    }
988
989    #[test]
990    fn soft_deny_and_session_once() {
991        let s = TrustStore::new();
992        assert_eq!(
993            cert_override_decision_full(&s, "x.test", false, true, None),
994            CertOverrideDecision::SoftDenied
995        );
996        assert_eq!(
997            cert_override_decision_full(&s, "x.test", true, false, None),
998            CertOverrideDecision::AllowSessionOnce
999        );
1000    }
1001
1002    #[test]
1003    fn signed_catalog_roundtrip_ed25519() {
1004        use ed25519_dalek::{Signer, SigningKey};
1005        let rng_bytes = [7u8; 32];
1006        let sk = SigningKey::from_bytes(&rng_bytes);
1007        let vk = sk.verifying_key();
1008        let catalog = SuggestedTrustCatalog {
1009            version: 1,
1010            description: "signed empty".into(),
1011            entries: vec![],
1012        };
1013        let payload = catalog_signing_payload(&catalog).unwrap();
1014        let sig = sk.sign(&payload);
1015        let env = SignedSuggestedCatalog {
1016            catalog,
1017            signature_hex: hex::encode(sig.to_bytes()),
1018            public_key_hex: hex::encode(vk.as_bytes()),
1019            algorithm: "ed25519".into(),
1020        };
1021        verify_signed_catalog(&env).unwrap();
1022        // Tamper
1023        let mut bad = env.clone();
1024        bad.catalog.description = "tampered".into();
1025        assert!(verify_signed_catalog(&bad).is_err());
1026    }
1027}