Skip to main content

hyprstream_service/service/
trust_store.rs

1//! Key-centric trust store for service identity verification.
2//!
3//! The trust store holds verified Ed25519 pubkeys and their attestations.
4//! Keys ARE identity — service names are authorization scopes.
5//!
6//! # Bootstrap
7//!
8//! PolicyService's verifying key is the root trust anchor, loaded from:
9//! - Inproc: generated in memory during `generate_independent_service_keys`
10//! - IPC: loaded from `ca-pubkey` credential file
11//!
12//! # Runtime
13//!
14//! Services register their pubkeys via `registerServiceKey` RPC.
15//! Clients verify peer keys via `is_authorized(key, scope)`.
16//!
17//! # Multi-instance
18//!
19//! Multiple services with the same scope (e.g., two "model" instances) each
20//! have their own key. The trust store holds all of them. A client connecting
21//! to any endpoint verifies the response signer is authorized for the
22//! requested scope.
23
24use dashmap::DashMap;
25use ed25519_dalek::VerifyingKey;
26use hyprstream_rpc::identity::UNAUTHENTICATED_DID_SENTINEL;
27use std::collections::HashSet;
28use std::sync::Arc;
29use tracing;
30
31/// A named, currently published service verification key.
32///
33/// `key_id` is derived from the public key, so it is stable across processes
34/// and cannot be chosen independently of the material it identifies.  The
35/// attestation carries the signed validity interval and proof of authorization.
36#[derive(Clone, Debug)]
37pub struct PublishedServiceKey {
38    pub key_id: String,
39    pub verifying_key: VerifyingKey,
40    pub attestation: Attestation,
41}
42
43/// An attestation binding a key to authorization scopes.
44#[derive(Clone, Debug)]
45pub struct Attestation {
46    /// Authorization scopes this key is valid for (e.g., "model", "policy").
47    pub scopes: HashSet<String>,
48    /// Explicit subject identity (e.g., "alice", "https://node-b:alice").
49    /// `None` for service keys (derived as "service:{scope}").
50    pub subject: Option<String>,
51    /// CA-signed JWT attesting this key.
52    pub jwt: Option<String>,
53    /// Unix timestamp when this attestation expires.
54    pub expires_at: i64,
55    /// Root/CA key that issued this attestation (for chain revocation).
56    pub attested_by: Option<[u8; 32]>,
57}
58
59/// Key-centric trust store. Thread-safe, lock-free reads.
60///
61/// Keyed by `VerifyingKey` (Ed25519 pubkey). Each entry records what
62/// scopes that key is authorized for and when the attestation expires.
63#[derive(Clone)]
64pub struct TrustStore {
65    inner: Arc<DashMap<VerifyingKey, Attestation>>,
66}
67
68impl TrustStore {
69    /// Create an empty trust store.
70    pub fn new() -> Self {
71        Self {
72            inner: Arc::new(DashMap::new()),
73        }
74    }
75
76    /// Insert a verified attestation for a key.
77    ///
78    /// If the key already exists, the attestation is replaced if the new one
79    /// expires later. Otherwise the existing entry is kept (prevents downgrade).
80    /// Logs a warning on equal-expiry discard.
81    pub fn insert(&self, key: VerifyingKey, attestation: Attestation) {
82        if attestation.subject.as_deref() == Some(UNAUTHENTICATED_DID_SENTINEL) {
83            tracing::warn!(
84                key = ?key.to_bytes()[..4],
85                "Trust store: rejected reserved unauthenticated subject binding"
86            );
87            return;
88        }
89        let subject_debug = attestation
90            .subject
91            .as_deref()
92            .unwrap_or("<scope-derived>")
93            .to_owned();
94        let scopes_debug: Vec<String> = attestation.scopes.iter().cloned().collect();
95        let expires_debug = attestation.expires_at;
96        self.inner
97            .entry(key)
98            .and_modify(|existing| {
99                if attestation.expires_at > existing.expires_at {
100                    tracing::info!(
101                        key = ?key.to_bytes()[..4],
102                        subject = %subject_debug,
103                        scopes = ?scopes_debug,
104                        expires_at = expires_debug,
105                        "Trust store: updating attestation (later expiry)"
106                    );
107                    *existing = attestation.clone();
108                } else if attestation.expires_at == existing.expires_at {
109                    tracing::warn!(
110                        key = ?key.to_bytes()[..4],
111                        new_subject = %subject_debug,
112                        existing_subject = ?existing.subject,
113                        "Trust store: equal-expiry attestation discarded (first-writer wins)"
114                    );
115                }
116            })
117            .or_insert_with(|| {
118                tracing::info!(
119                    key = ?key.to_bytes()[..4],
120                    subject = %subject_debug,
121                    scopes = ?scopes_debug,
122                    expires_at = expires_debug,
123                    "Trust store: new attestation inserted"
124                );
125                attestation
126            });
127    }
128
129    /// Publish a service registration after the caller has verified the CA
130    /// credential, service subject and signer binding. Unlike a generic cache
131    /// insertion, this may complete a same-credential, same-expiry identity
132    /// cache entry with its certified service scope. Conflicting identities,
133    /// credentials or scope sets are never silently overwritten.
134    pub fn publish_service_registration(
135        &self,
136        key: VerifyingKey,
137        service: &str,
138        attestation: Attestation,
139    ) -> anyhow::Result<()> {
140        use dashmap::mapref::entry::Entry;
141        anyhow::ensure!(!service.is_empty(), "empty registered service name");
142        anyhow::ensure!(
143            attestation.scopes.len() == 1
144                && attestation.scopes.contains(service)
145                && attestation.subject.is_none()
146                && attestation.jwt.as_ref().is_some_and(|jwt| !jwt.is_empty())
147                && attestation.attested_by.is_some()
148                && attestation.expires_at > chrono::Utc::now().timestamp(),
149            "invalid service registration attestation"
150        );
151        match self.inner.entry(key) {
152            Entry::Vacant(entry) => {
153                entry.insert(attestation);
154            }
155            Entry::Occupied(mut entry) => {
156                let existing = entry.get();
157                let subject = format!("service:{service}");
158                anyhow::ensure!(
159                    existing
160                        .subject
161                        .as_deref()
162                        .is_none_or(|value| value == subject)
163                        && existing.scopes.is_subset(&attestation.scopes),
164                    "service registration conflicts with retained key identity"
165                );
166                anyhow::ensure!(
167                    attestation.expires_at >= existing.expires_at,
168                    "stale service registration"
169                );
170                anyhow::ensure!(
171                    existing
172                        .attested_by
173                        .is_none_or(|authority| Some(authority) == attestation.attested_by),
174                    "service registration conflicts with retained authority"
175                );
176                if attestation.expires_at == existing.expires_at {
177                    anyhow::ensure!(
178                        existing.jwt == attestation.jwt,
179                        "equal-expiry service registration has conflicting credential"
180                    );
181                }
182                entry.insert(attestation);
183            }
184        }
185        Ok(())
186    }
187
188    /// Check if a key is authorized for the given scope.
189    ///
190    /// Returns `true` if:
191    /// 1. The key has an entry in the trust store
192    /// 2. The scope is in the entry's scope set
193    /// 3. The attestation has not expired
194    pub fn is_authorized(&self, key: &VerifyingKey, scope: &str) -> bool {
195        match self.inner.get(key) {
196            Some(att) => {
197                let now = chrono::Utc::now().timestamp();
198                (att.expires_at == 0 || att.expires_at > now) && att.scopes.contains(scope)
199            }
200            None => false,
201        }
202    }
203
204    /// Get all keys authorized for a given scope.
205    ///
206    /// Returns an empty Vec if no keys match. Useful for finding
207    /// candidate endpoints when multiple instances exist.
208    pub fn keys_for_scope(&self, scope: &str) -> Vec<VerifyingKey> {
209        self.published_keys_for_scope(scope)
210            .into_iter()
211            .map(|entry| entry.verifying_key)
212            .collect()
213    }
214
215    /// Get every named, unexpired verification key published for a service scope.
216    ///
217    /// Consumers must select an entry by `key_id`, or try every compatible
218    /// candidate.  This intentionally exposes no authority-bearing positional
219    /// selection: a service may publish a drain and lead key simultaneously.
220    pub fn published_keys_for_scope(&self, scope: &str) -> Vec<PublishedServiceKey> {
221        self.published_keys_for_scope_at(scope, chrono::Utc::now().timestamp())
222    }
223
224    /// Resolve the published key set at a supplied Unix timestamp.
225    ///
226    /// This is useful to consumers which evaluate a signed assertion at its
227    /// issuance time and to deterministic rotation tests.
228    pub fn published_keys_for_scope_at(&self, scope: &str, now: i64) -> Vec<PublishedServiceKey> {
229        let mut keys = self
230            .inner
231            .iter()
232            .filter(|entry| {
233                let att = entry.value();
234                (att.expires_at == 0 || att.expires_at > now) && att.scopes.contains(scope)
235            })
236            .map(|entry| PublishedServiceKey {
237                key_id: service_key_id(entry.key()),
238                verifying_key: *entry.key(),
239                attestation: entry.value().clone(),
240            })
241            .collect::<Vec<_>>();
242        keys.sort_by(|left, right| left.key_id.cmp(&right.key_id));
243        keys
244    }
245
246    /// Get the attestation for a specific key, if present and not expired.
247    pub fn get(&self, key: &VerifyingKey) -> Option<Attestation> {
248        self.inner.get(key).and_then(|att| {
249            let now = chrono::Utc::now().timestamp();
250            if att.expires_at == 0 || att.expires_at > now {
251                Some(att.clone())
252            } else {
253                None
254            }
255        })
256    }
257
258    /// Remove a specific key from the trust store.
259    pub fn remove(&self, key: &VerifyingKey) {
260        self.inner.remove(key);
261    }
262
263    /// Resolve a single key for a given scope.
264    ///
265    /// Returns the first valid (non-expired) key found for this scope.
266    /// For multi-instance deployments, use `keys_for_scope()` instead.
267    /// Returns `None` if no keys are authorized for this scope.
268    pub fn resolve_one(&self, scope: &str) -> Option<VerifyingKey> {
269        self.keys_for_scope(scope).into_iter().next()
270    }
271
272    /// Resolve a signer key to an authorization subject.
273    ///
274    /// For user keys: returns `attestation.subject` (e.g., "alice").
275    /// For service keys: returns `"service:{first_scope}"` (e.g., "service:model").
276    /// Returns `None` if the key is not in the trust store or is expired.
277    pub fn resolve_subject(
278        &self,
279        signer_pubkey: &[u8; 32],
280    ) -> Option<hyprstream_rpc::envelope::Subject> {
281        let vk = VerifyingKey::from_bytes(signer_pubkey).ok()?;
282        let att = self.get(&vk)?;
283        // User keys: explicit subject
284        if let Some(ref subject) = att.subject {
285            if subject == UNAUTHENTICATED_DID_SENTINEL {
286                tracing::warn!(
287                    key = ?vk.to_bytes()[..4],
288                    "Trust store: ignored legacy reserved unauthenticated subject binding"
289                );
290                return None;
291            }
292            return Some(hyprstream_rpc::envelope::Subject::new(subject.clone()));
293        }
294        // Service keys: derive from scope
295        att.scopes
296            .iter()
297            .next()
298            .map(|scope| hyprstream_rpc::envelope::Subject::new(format!("service:{scope}")))
299    }
300
301    /// Remove all entries whose attestation was issued by the given root key.
302    ///
303    /// Returns the number of entries removed.
304    pub fn invalidate_by_root(&self, root_key: &VerifyingKey) -> usize {
305        let root_bytes = root_key.to_bytes();
306        let before = self.inner.len();
307        self.inner
308            .retain(|_, att| att.attested_by.as_ref() != Some(&root_bytes));
309        let removed = before - self.inner.len();
310        if removed > 0 {
311            tracing::info!(
312                root = ?root_bytes[..8],
313                removed,
314                "Invalidated keys attested by revoked root"
315            );
316        }
317        removed
318    }
319
320    /// Number of entries in the trust store (including expired).
321    pub fn len(&self) -> usize {
322        self.inner.len()
323    }
324
325    /// Whether the trust store is empty.
326    pub fn is_empty(&self) -> bool {
327        self.inner.is_empty()
328    }
329}
330
331/// Canonical public identifier for an Ed25519 service verification key.
332pub fn service_key_id(key: &VerifyingKey) -> String {
333    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
334
335    format!("ed25519:{}", URL_SAFE_NO_PAD.encode(key.to_bytes()))
336}
337
338impl Default for TrustStore {
339    fn default() -> Self {
340        Self::new()
341    }
342}
343
344/// Adapter exposing the global trust store as the `hyprstream-rpc`
345/// signer-key → subject resolver (#446).
346///
347/// `hyprstream-rpc`'s dispatch core cannot reference the trust store directly
348/// (the dependency points the other way), so it defines a
349/// [`hyprstream_rpc::auth::KeySubjectResolver`] seam. This adapter wires the
350/// authoritative trust store (populated fail-closed under #441) into that seam
351/// so a signed service-to-service IPC caller resolves as its `service:<name>`
352/// identity instead of `anonymous`. Unregistered keys resolve to `None`
353/// (fail-closed); resolution never fabricates an identity.
354struct TrustStoreSubjectResolver;
355
356impl hyprstream_rpc::auth::KeySubjectResolver for TrustStoreSubjectResolver {
357    fn resolve_subject(
358        &self,
359        signer_pubkey: &[u8; 32],
360    ) -> Option<hyprstream_rpc::envelope::Subject> {
361        global_trust_store().resolve_subject(signer_pubkey)
362    }
363}
364
365/// Global trust store singleton.
366///
367/// Set once during startup (before any service threads spawn), readable
368/// from any thread thereafter. This is the "CA bundle" — the set of
369/// keys the process trusts.
370///
371/// On first access the trust store also installs itself as the process-global
372/// `hyprstream-rpc` key→subject resolver (#446), so every dispatched request
373/// (across all service crates) maps a verified signer key to its authoritative
374/// `service:<name>`/user subject via this store. The trust store is always
375/// touched during startup, so this guarantees the resolver is wired before any
376/// request is served.
377static TRUST_STORE: once_cell::sync::Lazy<TrustStore> = once_cell::sync::Lazy::new(|| {
378    hyprstream_rpc::auth::set_global_key_subject_resolver(std::sync::Arc::new(
379        TrustStoreSubjectResolver,
380    ));
381    TrustStore::new()
382});
383
384/// Get the global trust store.
385pub fn global_trust_store() -> &'static TrustStore {
386    &TRUST_STORE
387}
388#[cfg(test)]
389mod tests {
390    use super::*;
391    use ed25519_dalek::SigningKey;
392
393    fn random_key() -> (SigningKey, VerifyingKey) {
394        let sk = SigningKey::generate(&mut rand::rngs::OsRng);
395        let vk = sk.verifying_key();
396        (sk, vk)
397    }
398
399    fn make_attestation(scopes: &[&str], expires_at: i64) -> Attestation {
400        Attestation {
401            scopes: scopes
402                .iter()
403                .map(std::string::ToString::to_string)
404                .collect(),
405            subject: None,
406            jwt: None,
407            expires_at,
408            attested_by: None,
409        }
410    }
411
412    #[test]
413    fn insert_and_lookup() {
414        let store = TrustStore::new();
415        let (_, key) = random_key();
416        let now = chrono::Utc::now().timestamp();
417        let expires = now + 3600;
418
419        store.insert(key, make_attestation(&["model"], expires));
420
421        assert!(store.is_authorized(&key, "model"));
422        assert!(!store.is_authorized(&key, "policy"));
423    }
424
425    #[test]
426    fn service_registration_completes_same_credential_cache_idempotently() {
427        let store = TrustStore::new();
428        let (_, key) = random_key();
429        let expires = chrono::Utc::now().timestamp() + 3600;
430        let mut cached = make_attestation(&[], expires);
431        cached.subject = Some("service:model".to_owned());
432        cached.jwt = Some("verified-fixture-credential".to_owned());
433        cached.attested_by = Some([7; 32]);
434        store.insert(key, cached.clone());
435        assert!(store.published_keys_for_scope("model").is_empty());
436        let mut registered = cached;
437        registered.subject = None;
438        registered.scopes.insert("model".to_owned());
439        for _ in 0..2 {
440            assert!(store
441                .publish_service_registration(key, "model", registered.clone())
442                .is_ok());
443            let published = store.published_keys_for_scope("model");
444            assert_eq!(published.len(), 1);
445            assert_eq!(published[0].verifying_key, key);
446            assert_eq!(published[0].attestation.expires_at, expires);
447        }
448    }
449
450    #[test]
451    fn service_registration_completes_locally_seeded_authority() -> anyhow::Result<()> {
452        let store = TrustStore::new();
453        let (_, key) = random_key();
454        let mut seeded = make_attestation(&["model"], chrono::Utc::now().timestamp() + 3600);
455        seeded.jwt = Some("verified-fixture-credential".to_owned());
456        // Same-process boot seeds the credential before Policy verifies the
457        // registration. Missing authority is incomplete, not conflicting.
458        store.insert(key, seeded.clone());
459        let mut certified = seeded;
460        certified.attested_by = Some([7; 32]);
461        for _ in 0..2 {
462            store.publish_service_registration(key, "model", certified.clone())?;
463            let retained = store
464                .get(&key)
465                .ok_or_else(|| anyhow::anyhow!("registration missing"))?;
466            assert_eq!(retained.attested_by, certified.attested_by);
467            assert_eq!(retained.jwt, certified.jwt);
468            assert_eq!(retained.scopes, certified.scopes);
469            assert_eq!(retained.expires_at, certified.expires_at);
470        }
471        Ok(())
472    }
473
474    #[test]
475    fn service_registration_rejects_conflicts_without_changing_cached_authority(
476    ) -> anyhow::Result<()> {
477        let (_, key) = random_key();
478        let expires = chrono::Utc::now().timestamp() + 3600;
479        let mut registered = make_attestation(&["model"], expires);
480        registered.jwt = Some("verified-fixture-credential".to_owned());
481        registered.attested_by = Some([7; 32]);
482        let mut conflicting = Vec::new();
483        let mut changed = registered.clone();
484        changed.subject = Some("service:policy".to_owned());
485        conflicting.push(changed);
486        let mut changed = registered.clone();
487        changed.scopes.insert("policy".to_owned());
488        conflicting.push(changed);
489        let mut changed = registered.clone();
490        changed.jwt = Some("different-credential".to_owned());
491        conflicting.push(changed);
492        let mut changed = registered.clone();
493        changed.attested_by = Some([8; 32]);
494        conflicting.push(changed);
495        let mut changed = registered.clone();
496        changed.expires_at += 1;
497        conflicting.push(changed);
498        for existing in conflicting {
499            let store = TrustStore::new();
500            store.insert(key, existing.clone());
501            assert!(store
502                .publish_service_registration(key, "model", registered.clone())
503                .is_err());
504            let retained = store
505                .get(&key)
506                .ok_or_else(|| anyhow::anyhow!("existing authority was lost"))?;
507            assert_eq!(retained.subject, existing.subject);
508            assert_eq!(retained.scopes, existing.scopes);
509            assert_eq!(retained.jwt, existing.jwt);
510            assert_eq!(retained.expires_at, existing.expires_at);
511            assert_eq!(retained.attested_by, existing.attested_by);
512        }
513        let store = TrustStore::new();
514        let mut invalid = registered;
515        invalid.jwt = None;
516        assert!(store
517            .publish_service_registration(key, "model", invalid)
518            .is_err());
519        assert!(store.get(&key).is_none());
520        Ok(())
521    }
522
523    #[test]
524    fn service_registration_renewal_preserves_certified_authority() -> anyhow::Result<()> {
525        let (_, key) = random_key();
526        let expires = chrono::Utc::now().timestamp() + 3600;
527        for retained_expiry in [expires, expires - 7200] {
528            let store = TrustStore::new();
529            let mut retained = make_attestation(&["model"], retained_expiry);
530            retained.jwt = Some("original-credential".to_owned());
531            retained.attested_by = Some([7; 32]);
532            store.insert(key, retained.clone());
533
534            let mut renewed = retained.clone();
535            renewed.expires_at = expires + 3600;
536            renewed.jwt = Some("renewed-credential".to_owned());
537            renewed.attested_by = Some([8; 32]);
538            assert!(store
539                .publish_service_registration(key, "model", renewed.clone())
540                .is_err());
541            // Public get intentionally hides expired entries; inspect retained
542            // storage here to prove the rejected replacement did not mutate it.
543            let unchanged = store
544                .inner
545                .get(&key)
546                .ok_or_else(|| anyhow::anyhow!("retained authority lost"))?
547                .clone();
548            assert_eq!(unchanged.attested_by, retained.attested_by);
549            assert_eq!(unchanged.jwt, retained.jwt);
550            assert_eq!(unchanged.expires_at, retained.expires_at);
551            assert_eq!(unchanged.scopes, retained.scopes);
552
553            // Renewal may change the credential/expiry, but not its root.
554            renewed.attested_by = retained.attested_by;
555            store.publish_service_registration(key, "model", renewed.clone())?;
556            let updated = store
557                .get(&key)
558                .ok_or_else(|| anyhow::anyhow!("renewal missing"))?;
559            assert_eq!(updated.attested_by, retained.attested_by);
560            assert_eq!(updated.jwt, renewed.jwt);
561            assert_eq!(updated.expires_at, renewed.expires_at);
562        }
563        Ok(())
564    }
565
566    #[test]
567    fn reserved_unauthenticated_subject_is_neither_cached_nor_recovered() {
568        let store = TrustStore::new();
569        let (_, key) = random_key();
570        let mut sentinel = make_attestation(&[], chrono::Utc::now().timestamp() + 3600);
571        sentinel.subject = Some(UNAUTHENTICATED_DID_SENTINEL.to_owned());
572
573        store.insert(key, sentinel.clone());
574        assert!(
575            store.get(&key).is_none(),
576            "public insertion must reject did:unknown"
577        );
578
579        // Simulate a legacy/corrupt cache entry written before the insertion
580        // guard existed. Resolution must still refuse to resurrect it.
581        store.inner.insert(key, sentinel);
582        assert_eq!(store.resolve_subject(&key.to_bytes()), None);
583    }
584
585    /// #441 invariant: authoritative service-key resolution.
586    /// A registered service resolves to *exactly* the registered key; an
587    /// unregistered service resolves to `None` (which `handle_resolve_service_key`
588    /// turns into a "service key '<name>' not registered" error — never a
589    /// CA-derived guess).
590    #[test]
591    fn resolve_one_returns_registered_key_or_none() {
592        let store = TrustStore::new();
593        let (_, registered) = random_key();
594        store.insert(registered, make_attestation(&["model"], 0));
595
596        // Registered → exactly the registered key.
597        assert_eq!(store.resolve_one("model"), Some(registered));
598
599        // Unregistered scope → None (handler converts this to a clear error;
600        // it must NOT derive a fallback key).
601        assert_eq!(store.resolve_one("worker"), None);
602    }
603
604    #[test]
605    fn expired_attestation_is_not_authorized() {
606        let store = TrustStore::new();
607        let (_, key) = random_key();
608        let past = chrono::Utc::now().timestamp() - 3600;
609
610        store.insert(key, make_attestation(&["model"], past));
611
612        assert!(!store.is_authorized(&key, "model"));
613    }
614
615    #[test]
616    fn zero_expiry_means_never_expires() {
617        let store = TrustStore::new();
618        let (_, key) = random_key();
619
620        store.insert(key, make_attestation(&["model"], 0));
621
622        assert!(store.is_authorized(&key, "model"));
623    }
624
625    #[test]
626    fn multiple_keys_same_scope() {
627        let store = TrustStore::new();
628        let (_, key_a) = random_key();
629        let (_, key_b) = random_key();
630        let now = chrono::Utc::now().timestamp();
631        let expires = now + 3600;
632
633        store.insert(key_a, make_attestation(&["model"], expires));
634        store.insert(key_b, make_attestation(&["model"], expires));
635
636        let keys = store.keys_for_scope("model");
637        assert_eq!(keys.len(), 2);
638        assert!(keys.contains(&key_a));
639        assert!(keys.contains(&key_b));
640    }
641
642    #[test]
643    fn published_key_set_keeps_overlap_until_retirement_window_ends() {
644        let store = TrustStore::new();
645        let (_, retired) = random_key();
646        let (_, lead) = random_key();
647        let now = chrono::Utc::now().timestamp();
648        let retirement = now + 60;
649
650        store.insert(retired, make_attestation(&["model"], retirement));
651        store.insert(lead, make_attestation(&["model"], 0));
652
653        let overlap = store.published_keys_for_scope_at("model", now);
654        assert_eq!(
655            overlap.len(),
656            2,
657            "drain and lead keys must publish together"
658        );
659        assert!(overlap.iter().any(|entry| entry.verifying_key == retired));
660        assert!(overlap.iter().any(|entry| entry.verifying_key == lead));
661        assert!(store.is_authorized(&retired, "model"));
662        assert!(store.is_authorized(&lead, "model"));
663        assert!(overlap
664            .iter()
665            .all(|entry| entry.key_id.starts_with("ed25519:")));
666
667        let after_retirement = store.published_keys_for_scope_at("model", retirement);
668        assert_eq!(
669            after_retirement.len(),
670            1,
671            "retired key must leave the set at its bounded expiry"
672        );
673        assert_eq!(after_retirement[0].verifying_key, lead);
674    }
675
676    #[test]
677    fn no_downgrade_on_reinsert() {
678        let store = TrustStore::new();
679        let (_, key) = random_key();
680        let now = chrono::Utc::now().timestamp();
681
682        store.insert(key, make_attestation(&["model"], now + 7200));
683        store.insert(key, make_attestation(&["model"], now + 3600)); // earlier expiry
684
685        let att = match store.get(&key) {
686            Some(a) => a,
687            None => panic!("key should be present after insert"),
688        };
689        assert_eq!(att.expires_at, now + 7200); // kept the later expiry
690    }
691
692    #[test]
693    fn impersonation_rejected() {
694        let store = TrustStore::new();
695        let (_, model_key) = random_key();
696        let (_, policy_key) = random_key();
697        let now = chrono::Utc::now().timestamp();
698        let expires = now + 3600;
699
700        store.insert(model_key, make_attestation(&["model"], expires));
701        store.insert(policy_key, make_attestation(&["policy"], expires));
702
703        // model key is NOT authorized for policy scope
704        assert!(!store.is_authorized(&model_key, "policy"));
705        // policy key is NOT authorized for model scope
706        assert!(!store.is_authorized(&policy_key, "model"));
707    }
708
709    #[test]
710    fn key_with_multiple_scopes() {
711        let store = TrustStore::new();
712        let (_, key) = random_key();
713        let now = chrono::Utc::now().timestamp();
714        let expires = now + 3600;
715
716        store.insert(key, make_attestation(&["model", "inference"], expires));
717
718        assert!(store.is_authorized(&key, "model"));
719        assert!(store.is_authorized(&key, "inference"));
720        assert!(!store.is_authorized(&key, "policy"));
721    }
722
723    #[test]
724    fn remove_key() {
725        let store = TrustStore::new();
726        let (_, key) = random_key();
727        let now = chrono::Utc::now().timestamp();
728        let expires = now + 3600;
729
730        store.insert(key, make_attestation(&["model"], expires));
731        assert!(store.is_authorized(&key, "model"));
732
733        store.remove(&key);
734        assert!(!store.is_authorized(&key, "model"));
735    }
736
737    /// #446: accessing the global trust store installs it as the `hyprstream-rpc`
738    /// signer-key → subject resolver, and a registered service key resolves to
739    /// its authoritative `service:<scope>` subject through that seam (so a signed
740    /// service-to-service IPC caller is no longer anonymous). An unregistered key
741    /// resolves to `None` (fail-closed → anonymous).
742    #[test]
743    fn global_resolver_resolves_registered_service_key() {
744        // Touching the global store installs the global key→subject resolver.
745        let store = global_trust_store();
746        let (_, service_key) = random_key();
747        let (_, unregistered) = random_key();
748        store.insert(service_key, make_attestation(&["discovery"], 0));
749
750        // The rpc-layer global resolver routes through this same trust store.
751        let registered =
752            hyprstream_rpc::auth::key_subject_resolver::resolve_subject(&service_key.to_bytes());
753        assert_eq!(
754            registered.map(|s| s.to_string()),
755            Some("service:discovery".to_owned()),
756            "registered service key must resolve as service:discovery, not anonymous"
757        );
758
759        // Fail-closed: an unregistered key resolves to None → anonymous.
760        assert!(
761            hyprstream_rpc::auth::key_subject_resolver::resolve_subject(&unregistered.to_bytes())
762                .is_none(),
763            "unregistered key must NOT resolve to any identity"
764        );
765
766        // Cleanup so we don't leak into other tests sharing the global store.
767        store.remove(&service_key);
768    }
769}