Skip to main content

auth_framework/protocols/
spiffe.rs

1//! SPIFFE (Secure Production Identity Framework for Everyone) implementation.
2//!
3//! Provides SPIFFE ID parsing/validation and SVID (SPIFFE Verifiable Identity Document)
4//! verification for both X.509-SVID and JWT-SVID formats.
5//!
6//! # Architecture
7//!
8//! - **SPIFFE ID** — a URI of the form `spiffe://<trust-domain>/<workload-path>`
9//! - **X.509-SVID** — a SPIFFE identity bound to an X.509 certificate
10//! - **JWT-SVID** — a SPIFFE identity bound to a JWT
11//! - **Trust Bundle** — a set of CA certificates for a trust domain
12//!
13//! # References
14//!
15//! - [SPIFFE ID spec](https://github.com/spiffe/spiffe/blob/main/standards/SPIFFE-ID.md)
16//! - [X509-SVID spec](https://github.com/spiffe/spiffe/blob/main/standards/X509-SVID.md)
17//! - [JWT-SVID spec](https://github.com/spiffe/spiffe/blob/main/standards/JWT-SVID.md)
18
19use crate::errors::{AuthError, Result};
20use serde::{Deserialize, Serialize};
21use sha2::{Digest, Sha256};
22use std::collections::HashMap;
23use std::sync::Arc;
24use std::time::{Duration, SystemTime, UNIX_EPOCH};
25use tokio::sync::RwLock;
26
27// ── SPIFFE ID ───────────────────────────────────────────────────────
28
29/// A parsed and validated SPIFFE ID.
30///
31/// Format: `spiffe://<trust-domain>/<workload-path>`
32#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
33pub struct SpiffeId {
34    /// Trust domain (e.g., "example.org").
35    pub trust_domain: String,
36    /// Workload path segments (e.g., "/service/web").
37    pub path: String,
38}
39
40impl SpiffeId {
41    /// Parse and validate a SPIFFE ID string.
42    ///
43    /// # Errors
44    /// - Missing `spiffe://` scheme
45    /// - Empty trust domain
46    /// - Trust domain with invalid characters
47    /// - Path with query or fragment
48    pub fn parse(uri: &str) -> Result<Self> {
49        let stripped = uri
50            .strip_prefix("spiffe://")
51            .ok_or_else(|| AuthError::validation("SPIFFE ID must start with 'spiffe://'"))?;
52
53        if stripped.is_empty() {
54            return Err(AuthError::validation("SPIFFE ID trust domain is empty"));
55        }
56
57        // Split into trust domain and path
58        let (trust_domain, path) = match stripped.find('/') {
59            Some(idx) => (&stripped[..idx], &stripped[idx..]),
60            None => (stripped, ""),
61        };
62
63        // Validate trust domain (RFC: lowercase, alphanumeric, hyphens, dots)
64        if trust_domain.is_empty() {
65            return Err(AuthError::validation("SPIFFE ID trust domain is empty"));
66        }
67
68        for ch in trust_domain.chars() {
69            if !ch.is_ascii_alphanumeric() && ch != '-' && ch != '.' && ch != '_' {
70                return Err(AuthError::validation(format!(
71                    "SPIFFE ID trust domain contains invalid character: '{ch}'"
72                )));
73            }
74        }
75
76        // No query or fragment allowed
77        if path.contains('?') || path.contains('#') {
78            return Err(AuthError::validation(
79                "SPIFFE ID must not contain query or fragment",
80            ));
81        }
82
83        // No trailing slash on non-root paths
84        if path.len() > 1 && path.ends_with('/') {
85            return Err(AuthError::validation(
86                "SPIFFE ID path must not end with '/'",
87            ));
88        }
89
90        // No empty segments
91        if path.contains("//") {
92            return Err(AuthError::validation(
93                "SPIFFE ID path must not contain empty segments",
94            ));
95        }
96
97        // No dot or dotdot segments
98        for segment in path.split('/').skip(1) {
99            if segment == "." || segment == ".." {
100                return Err(AuthError::validation(
101                    "SPIFFE ID path must not contain '.' or '..' segments",
102                ));
103            }
104        }
105
106        Ok(Self {
107            trust_domain: trust_domain.to_string(),
108            path: path.to_string(),
109        })
110    }
111
112    /// Return the full SPIFFE ID URI.
113    pub fn to_uri(&self) -> String {
114        format!("spiffe://{}{}", self.trust_domain, self.path)
115    }
116
117    /// Check whether this ID belongs to the given trust domain.
118    pub fn is_member_of(&self, trust_domain: &str) -> bool {
119        self.trust_domain == trust_domain
120    }
121
122    /// Check whether this ID matches a path prefix.
123    pub fn matches_path_prefix(&self, prefix: &str) -> bool {
124        self.path.starts_with(prefix)
125    }
126}
127
128impl std::fmt::Display for SpiffeId {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        write!(f, "spiffe://{}{}", self.trust_domain, self.path)
131    }
132}
133
134// ── JWT-SVID ────────────────────────────────────────────────────────
135
136/// JWT-SVID claims.
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct JwtSvidClaims {
139    /// SPIFFE ID of the subject.
140    pub sub: String,
141    /// Intended audience(s).
142    pub aud: Vec<String>,
143    /// Expiration time (Unix timestamp).
144    pub exp: u64,
145    /// Issued-at time (Unix timestamp).
146    #[serde(default)]
147    pub iat: Option<u64>,
148}
149
150/// JWT-SVID validation result.
151#[derive(Debug, Clone)]
152pub struct ValidatedJwtSvid {
153    /// The parsed SPIFFE ID from the subject claim.
154    pub spiffe_id: SpiffeId,
155    /// The validated claims.
156    pub claims: JwtSvidClaims,
157    /// Raw header for inspection.
158    pub header: serde_json::Value,
159}
160
161/// Validate a JWT-SVID token (structural + expiration + audience check).
162///
163/// This performs all validation that does not require trust bundle access:
164/// - Splits and decodes the JWT
165/// - Validates the `sub` claim is a valid SPIFFE ID
166/// - Checks expiration
167/// - Validates audience
168///
169/// Cryptographic signature verification requires a trust bundle and is
170/// performed by `SpiffeTrustManager::verify_jwt_svid`.
171pub fn validate_jwt_svid(token: &str, expected_audience: &str) -> Result<ValidatedJwtSvid> {
172    let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;
173    use base64::Engine;
174
175    let parts: Vec<&str> = token.split('.').collect();
176    if parts.len() != 3 {
177        return Err(AuthError::validation("JWT-SVID must have 3 parts"));
178    }
179
180    // Decode header
181    let header_bytes = b64
182        .decode(parts[0])
183        .map_err(|_| AuthError::validation("Invalid JWT-SVID header encoding"))?;
184    let header: serde_json::Value = serde_json::from_slice(&header_bytes)
185        .map_err(|_| AuthError::validation("Invalid JWT-SVID header JSON"))?;
186
187    // Algorithm must be specified and not "none"
188    let alg = header
189        .get("alg")
190        .and_then(|v| v.as_str())
191        .ok_or_else(|| AuthError::validation("JWT-SVID header missing 'alg'"))?;
192    if alg.eq_ignore_ascii_case("none") {
193        return Err(AuthError::validation(
194            "JWT-SVID must not use 'none' algorithm",
195        ));
196    }
197
198    // Decode claims
199    let claims_bytes = b64
200        .decode(parts[1])
201        .map_err(|_| AuthError::validation("Invalid JWT-SVID claims encoding"))?;
202    let claims: JwtSvidClaims = serde_json::from_slice(&claims_bytes)
203        .map_err(|_| AuthError::validation("Invalid JWT-SVID claims JSON"))?;
204
205    // Validate subject is a valid SPIFFE ID
206    let spiffe_id = SpiffeId::parse(&claims.sub)?;
207
208    // Check expiration
209    let now = SystemTime::now()
210        .duration_since(UNIX_EPOCH)
211        .unwrap_or_default()
212        .as_secs();
213    if claims.exp <= now {
214        return Err(AuthError::validation("JWT-SVID has expired"));
215    }
216
217    // Validate audience
218    if !claims.aud.iter().any(|a| a == expected_audience) {
219        return Err(AuthError::validation(
220            "JWT-SVID audience does not match expected audience",
221        ));
222    }
223
224    Ok(ValidatedJwtSvid {
225        spiffe_id,
226        claims,
227        header,
228    })
229}
230
231// ── X.509-SVID ──────────────────────────────────────────────────────
232
233/// Parsed X.509-SVID metadata (from certificate fields).
234#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct X509SvidInfo {
236    /// SPIFFE ID from the SAN URI.
237    pub spiffe_id: SpiffeId,
238    /// SHA-256 fingerprint of the certificate (hex-encoded).
239    pub fingerprint: String,
240    /// Certificate serial number (if available).
241    #[serde(default)]
242    pub serial: Option<String>,
243    /// Not-before timestamp (Unix).
244    #[serde(default)]
245    pub not_before: Option<u64>,
246    /// Not-after timestamp (Unix).
247    #[serde(default)]
248    pub not_after: Option<u64>,
249}
250
251/// Extract and validate a SPIFFE ID from DER-encoded certificate bytes.
252///
253/// Performs a lightweight parse of the SAN extension to find a `spiffe://` URI.
254/// Full X.509 chain verification requires a trust bundle.
255pub fn extract_spiffe_id_from_der(cert_der: &[u8]) -> Result<X509SvidInfo> {
256    // Compute fingerprint
257    let fingerprint = hex::encode(Sha256::digest(cert_der));
258
259    // Search for spiffe:// URI in the raw cert bytes (SAN extension)
260    let cert_str = String::from_utf8_lossy(cert_der);
261    let spiffe_uri = find_spiffe_uri_in_bytes(cert_der)
262        .or_else(|| {
263            // Fallback: try scanning the lossy string
264            cert_str.find("spiffe://").map(|idx| {
265                let end = cert_str[idx..]
266                    .find(|c: char| c.is_control() || c == '\0')
267                    .unwrap_or(cert_str.len() - idx);
268                cert_str[idx..idx + end].to_string()
269            })
270        })
271        .ok_or_else(|| {
272            AuthError::validation("No SPIFFE ID (spiffe:// URI) found in certificate SAN")
273        })?;
274
275    let spiffe_id = SpiffeId::parse(&spiffe_uri)?;
276
277    Ok(X509SvidInfo {
278        spiffe_id,
279        fingerprint,
280        serial: None,
281        not_before: None,
282        not_after: None,
283    })
284}
285
286/// Scan raw DER bytes for a `spiffe://` URI, respecting UTF-8 boundaries.
287fn find_spiffe_uri_in_bytes(data: &[u8]) -> Option<String> {
288    let needle = b"spiffe://";
289    for i in 0..data.len().saturating_sub(needle.len()) {
290        if data[i..].starts_with(needle) {
291            // Read until NUL, control character, or end
292            let start = i;
293            let mut end = i + needle.len();
294            while end < data.len() {
295                let b = data[end];
296                if b < 0x20 || b == 0x7f || b == 0x00 {
297                    break;
298                }
299                end += 1;
300            }
301            if let Ok(uri) = std::str::from_utf8(&data[start..end]) {
302                return Some(uri.to_string());
303            }
304        }
305    }
306    None
307}
308
309// ── Trust Manager ───────────────────────────────────────────────────
310
311/// Authorization policy entry for SPIFFE workloads.
312#[derive(Debug, Clone, Serialize, Deserialize)]
313pub struct SpiffeAuthzPolicy {
314    /// ID of the source workload (SPIFFE ID pattern).
315    pub source: String,
316    /// ID of the destination workload (SPIFFE ID pattern).
317    pub destination: String,
318    /// Allowed actions/methods.
319    pub allowed_actions: Vec<String>,
320}
321
322/// SPIFFE Trust Manager: maintains trust bundles and validates SVIDs.
323pub struct SpiffeTrustManager {
324    /// Trust domain → trust bundle (CA certificates as DER).
325    trust_bundles: Arc<RwLock<HashMap<String, Vec<Vec<u8>>>>>,
326    /// SPIFFE authorization policies.
327    policies: Arc<RwLock<Vec<SpiffeAuthzPolicy>>>,
328}
329
330impl SpiffeTrustManager {
331    pub fn new() -> Self {
332        Self {
333            trust_bundles: Arc::new(RwLock::new(HashMap::new())),
334            policies: Arc::new(RwLock::new(Vec::new())),
335        }
336    }
337
338    /// Register a trust bundle for a trust domain.
339    pub async fn add_trust_bundle(&self, trust_domain: &str, ca_certs_der: Vec<Vec<u8>>) {
340        self.trust_bundles
341            .write()
342            .await
343            .insert(trust_domain.to_string(), ca_certs_der);
344    }
345
346    /// Check if a trust bundle exists for the given domain.
347    pub async fn has_trust_bundle(&self, trust_domain: &str) -> bool {
348        self.trust_bundles.read().await.contains_key(trust_domain)
349    }
350
351    /// Get the trust bundle for a domain.
352    pub async fn get_trust_bundle(&self, trust_domain: &str) -> Option<Vec<Vec<u8>>> {
353        self.trust_bundles.read().await.get(trust_domain).cloned()
354    }
355
356    /// Remove a trust bundle.
357    pub async fn remove_trust_bundle(&self, trust_domain: &str) -> bool {
358        self.trust_bundles
359            .write()
360            .await
361            .remove(trust_domain)
362            .is_some()
363    }
364
365    /// Add an authorization policy.
366    pub async fn add_policy(&self, policy: SpiffeAuthzPolicy) {
367        self.policies.write().await.push(policy);
368    }
369
370    /// Check if a workload-to-workload call is authorized.
371    pub async fn is_authorized(
372        &self,
373        source: &SpiffeId,
374        destination: &SpiffeId,
375        action: &str,
376    ) -> bool {
377        let policies = self.policies.read().await;
378        let source_uri = source.to_uri();
379        let dest_uri = destination.to_uri();
380
381        policies.iter().any(|p| {
382            (p.source == source_uri || p.source == "*")
383                && (p.destination == dest_uri || p.destination == "*")
384                && (p.allowed_actions.contains(&action.to_string())
385                    || p.allowed_actions.contains(&"*".to_string()))
386        })
387    }
388
389    /// Validate a JWT-SVID and check that its trust domain is in our bundles.
390    pub async fn verify_jwt_svid(
391        &self,
392        token: &str,
393        expected_audience: &str,
394    ) -> Result<ValidatedJwtSvid> {
395        let result = validate_jwt_svid(token, expected_audience)?;
396
397        // Verify the trust domain has a registered bundle
398        if !self.has_trust_bundle(&result.spiffe_id.trust_domain).await {
399            return Err(AuthError::validation(format!(
400                "No trust bundle for domain '{}'",
401                result.spiffe_id.trust_domain
402            )));
403        }
404
405        Ok(result)
406    }
407
408    /// List all registered trust domains.
409    pub async fn trust_domains(&self) -> Vec<String> {
410        self.trust_bundles.read().await.keys().cloned().collect()
411    }
412}
413
414impl Default for SpiffeTrustManager {
415    fn default() -> Self {
416        Self::new()
417    }
418}
419
420// ── Workload API Client ─────────────────────────────────────────────
421
422/// SVID type returned by the Workload API.
423#[derive(Clone, Serialize, Deserialize)]
424pub enum SvidResponse {
425    /// An X.509-SVID with DER-encoded certificate chain and private key.
426    X509 {
427        spiffe_id: String,
428        cert_chain: Vec<Vec<u8>>,
429        private_key: Vec<u8>,
430        /// DER-encoded trust bundle for the given trust domain.
431        bundle: Vec<Vec<u8>>,
432        /// When the SVID expires (UNIX timestamp seconds).
433        expires_at: u64,
434    },
435    /// A JWT-SVID.
436    Jwt {
437        spiffe_id: String,
438        token: String,
439        expires_at: u64,
440    },
441}
442
443impl std::fmt::Debug for SvidResponse {
444    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
445        match self {
446            Self::X509 {
447                spiffe_id,
448                cert_chain,
449                bundle,
450                expires_at,
451                private_key: _,
452            } => f
453                .debug_struct("SvidResponse::X509")
454                .field("spiffe_id", spiffe_id)
455                .field("cert_chain", cert_chain)
456                .field("private_key", &"[redacted]")
457                .field("bundle", bundle)
458                .field("expires_at", expires_at)
459                .finish(),
460            Self::Jwt {
461                spiffe_id,
462                expires_at,
463                token: _,
464            } => f
465                .debug_struct("SvidResponse::Jwt")
466                .field("spiffe_id", spiffe_id)
467                .field("token", &"[redacted]")
468                .field("expires_at", expires_at)
469                .finish(),
470        }
471    }
472}
473
474/// Configuration for the SPIFFE Workload API client.
475#[derive(Debug, Clone, Serialize, Deserialize)]
476pub struct WorkloadApiConfig {
477    /// Socket path or address of the Workload API endpoint.
478    /// Typically a Unix domain socket: `/tmp/spire-agent/public/api.sock`.
479    pub endpoint: String,
480    /// How often (seconds) to poll for SVID rotation.
481    pub rotation_interval_secs: u64,
482    /// Audiences to include when fetching JWT-SVIDs.
483    pub jwt_audiences: Vec<String>,
484}
485
486impl Default for WorkloadApiConfig {
487    fn default() -> Self {
488        Self {
489            endpoint: "/tmp/spire-agent/public/api.sock".to_string(),
490            rotation_interval_secs: 300,
491            jwt_audiences: Vec::new(),
492        }
493    }
494}
495
496/// A Workload API client that manages SVID lifecycle.
497///
498/// In SPIFFE/SPIRE deployments, workloads fetch SVIDs from the local SPIRE
499/// agent over a Unix domain socket. This client tracks the current SVID(s)
500/// and handles rotation.
501pub struct WorkloadApiClient {
502    config: WorkloadApiConfig,
503    /// Current X.509-SVIDs keyed by SPIFFE ID.
504    x509_svids: Arc<RwLock<HashMap<String, SvidResponse>>>,
505    /// Current JWT-SVIDs keyed by SPIFFE ID.
506    jwt_svids: Arc<RwLock<HashMap<String, SvidResponse>>>,
507    /// Trust bundles received from the Workload API, keyed by trust domain.
508    bundles: Arc<RwLock<HashMap<String, Vec<Vec<u8>>>>>,
509}
510
511impl WorkloadApiClient {
512    /// Create a new Workload API client.
513    pub fn new(config: WorkloadApiConfig) -> Self {
514        Self {
515            config,
516            x509_svids: Arc::new(RwLock::new(HashMap::new())),
517            jwt_svids: Arc::new(RwLock::new(HashMap::new())),
518            bundles: Arc::new(RwLock::new(HashMap::new())),
519        }
520    }
521
522    /// Return the configured endpoint.
523    pub fn endpoint(&self) -> &str {
524        &self.config.endpoint
525    }
526
527    /// Return the rotation interval.
528    pub fn rotation_interval(&self) -> Duration {
529        Duration::from_secs(self.config.rotation_interval_secs)
530    }
531
532    /// Store an X.509-SVID (e.g., after receiving it from the Workload API).
533    pub async fn store_x509_svid(&self, svid: SvidResponse) {
534        if let SvidResponse::X509 {
535            ref spiffe_id,
536            ref bundle,
537            ..
538        } = svid
539        {
540            // Also update the trust bundle for this domain
541            if let Ok(id) = SpiffeId::parse(spiffe_id) {
542                self.bundles
543                    .write()
544                    .await
545                    .insert(id.trust_domain.clone(), bundle.clone());
546            }
547            self.x509_svids
548                .write()
549                .await
550                .insert(spiffe_id.clone(), svid);
551        }
552    }
553
554    /// Store a JWT-SVID.
555    pub async fn store_jwt_svid(&self, svid: SvidResponse) {
556        if let SvidResponse::Jwt { ref spiffe_id, .. } = svid {
557            self.jwt_svids.write().await.insert(spiffe_id.clone(), svid);
558        }
559    }
560
561    /// Get the current X.509-SVID for a given SPIFFE ID.
562    pub async fn get_x509_svid(&self, spiffe_id: &str) -> Option<SvidResponse> {
563        self.x509_svids.read().await.get(spiffe_id).cloned()
564    }
565
566    /// Get the current JWT-SVID for a given SPIFFE ID.
567    pub async fn get_jwt_svid(&self, spiffe_id: &str) -> Option<SvidResponse> {
568        self.jwt_svids.read().await.get(spiffe_id).cloned()
569    }
570
571    /// Get the trust bundle for a given trust domain.
572    pub async fn get_bundle(&self, trust_domain: &str) -> Option<Vec<Vec<u8>>> {
573        self.bundles.read().await.get(trust_domain).cloned()
574    }
575
576    /// Check if any X.509-SVID needs rotation (within 20% of expiry window).
577    pub async fn needs_rotation(&self) -> Vec<String> {
578        let now = SystemTime::now()
579            .duration_since(UNIX_EPOCH)
580            .unwrap_or_default()
581            .as_secs();
582
583        let svids = self.x509_svids.read().await;
584        let mut needs = Vec::new();
585        for (id, svid) in svids.iter() {
586            if let SvidResponse::X509 { expires_at, .. } = svid {
587                // Rotate when 80% of the lifetime has passed
588                let remaining = expires_at.saturating_sub(now);
589                let threshold = self.config.rotation_interval_secs;
590                if remaining < threshold {
591                    needs.push(id.clone());
592                }
593            }
594        }
595        needs
596    }
597
598    /// Remove expired SVIDs.
599    pub async fn cleanup_expired(&self) {
600        let now = SystemTime::now()
601            .duration_since(UNIX_EPOCH)
602            .unwrap_or_default()
603            .as_secs();
604
605        self.x509_svids.write().await.retain(|_, svid| {
606            if let SvidResponse::X509 { expires_at, .. } = svid {
607                *expires_at > now
608            } else {
609                true
610            }
611        });
612
613        self.jwt_svids.write().await.retain(|_, svid| {
614            if let SvidResponse::Jwt { expires_at, .. } = svid {
615                *expires_at > now
616            } else {
617                true
618            }
619        });
620    }
621
622    /// Number of stored X.509-SVIDs.
623    pub async fn x509_count(&self) -> usize {
624        self.x509_svids.read().await.len()
625    }
626
627    /// Number of stored JWT-SVIDs.
628    pub async fn jwt_count(&self) -> usize {
629        self.jwt_svids.read().await.len()
630    }
631}
632
633// ── SPIRE Workload Attestation ──────────────────────────────────────
634
635/// Attestation evidence provided by a workload to prove its identity.
636#[derive(Clone, Serialize, Deserialize)]
637pub struct AttestationEvidence {
638    /// Attestor plugin name (e.g., "k8s", "unix", "docker", "aws_iid").
639    pub attestor: String,
640    /// Evidence payload — content depends on the attestor type.
641    pub payload: HashMap<String, String>,
642}
643
644impl std::fmt::Debug for AttestationEvidence {
645    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
646        let mut d = f.debug_struct("AttestationEvidence");
647        d.field("attestor", &self.attestor);
648        d.field("payload", &crate::utils::redact::redacted(&self.payload));
649        d.finish()
650    }
651}
652
653/// The result of a successful workload attestation.
654#[derive(Debug, Clone, Serialize, Deserialize)]
655pub struct AttestationResult {
656    /// The SPIFFE IDs assigned to the attested workload.
657    pub spiffe_ids: Vec<SpiffeId>,
658    /// Workload selectors discovered during attestation.
659    pub selectors: Vec<WorkloadSelector>,
660}
661
662/// A selector that identifies a workload property (used in SPIRE registration entries).
663#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
664pub struct WorkloadSelector {
665    /// Selector type (e.g., "unix", "k8s", "docker").
666    pub selector_type: String,
667    /// Selector value (e.g., "uid:1000", "sa:default", "image_id:sha256:abc").
668    pub value: String,
669}
670
671impl WorkloadSelector {
672    /// Create a Unix UID selector.
673    pub fn unix_uid(uid: u32) -> Self {
674        Self {
675            selector_type: "unix".to_string(),
676            value: format!("uid:{uid}"),
677        }
678    }
679
680    /// Create a Unix GID selector.
681    pub fn unix_gid(gid: u32) -> Self {
682        Self {
683            selector_type: "unix".to_string(),
684            value: format!("gid:{gid}"),
685        }
686    }
687
688    /// Create a Kubernetes service account selector.
689    pub fn k8s_sa(namespace: &str, name: &str) -> Self {
690        Self {
691            selector_type: "k8s".to_string(),
692            value: format!("sa:{namespace}:{name}"),
693        }
694    }
695
696    /// Create a Kubernetes pod label selector.
697    pub fn k8s_pod_label(key: &str, value: &str) -> Self {
698        Self {
699            selector_type: "k8s".to_string(),
700            value: format!("pod-label:{key}:{value}"),
701        }
702    }
703
704    /// Create a Docker image ID selector.
705    pub fn docker_image_id(image_id: &str) -> Self {
706        Self {
707            selector_type: "docker".to_string(),
708            value: format!("image_id:{image_id}"),
709        }
710    }
711}
712
713/// A SPIRE registration entry that maps selectors to SPIFFE IDs.
714#[derive(Debug, Clone, Serialize, Deserialize)]
715pub struct RegistrationEntry {
716    /// The SPIFFE ID to assign to workloads matching the selectors.
717    pub spiffe_id: SpiffeId,
718    /// The parent SPIFFE ID (typically the node agent's SPIFFE ID).
719    pub parent_id: SpiffeId,
720    /// Selectors that a workload must match to receive this SPIFFE ID.
721    pub selectors: Vec<WorkloadSelector>,
722    /// Time-to-live for the SVIDs issued under this entry (seconds).
723    pub ttl: u64,
724    /// Whether this entry is for downstream workloads (federated).
725    pub downstream: bool,
726}
727
728/// In-memory registration entry store for SPIRE-style workload attestation.
729pub struct RegistrationStore {
730    entries: Arc<RwLock<Vec<RegistrationEntry>>>,
731}
732
733impl RegistrationStore {
734    /// Create an empty registration store.
735    pub fn new() -> Self {
736        Self {
737            entries: Arc::new(RwLock::new(Vec::new())),
738        }
739    }
740
741    /// Add a registration entry.
742    pub async fn register(&self, entry: RegistrationEntry) {
743        self.entries.write().await.push(entry);
744    }
745
746    /// Find all SPIFFE IDs that match the given selectors.
747    ///
748    /// A workload matches a registration entry if the workload's selectors are
749    /// a superset of the entry's selectors.
750    pub async fn match_selectors(&self, workload_selectors: &[WorkloadSelector]) -> Vec<SpiffeId> {
751        let entries = self.entries.read().await;
752        entries
753            .iter()
754            .filter(|entry| {
755                entry
756                    .selectors
757                    .iter()
758                    .all(|s| workload_selectors.contains(s))
759            })
760            .map(|entry| entry.spiffe_id.clone())
761            .collect()
762    }
763
764    /// Perform workload attestation: given evidence, extract selectors and find matching IDs.
765    pub async fn attest(&self, evidence: &AttestationEvidence) -> Result<AttestationResult> {
766        // Build selectors from evidence payload
767        let selectors: Vec<WorkloadSelector> = evidence
768            .payload
769            .iter()
770            .map(|(key, value)| WorkloadSelector {
771                selector_type: evidence.attestor.clone(),
772                value: format!("{key}:{value}"),
773            })
774            .collect();
775
776        if selectors.is_empty() {
777            return Err(AuthError::validation(
778                "Attestation evidence contains no selectors",
779            ));
780        }
781
782        let spiffe_ids = self.match_selectors(&selectors).await;
783        if spiffe_ids.is_empty() {
784            return Err(AuthError::validation(
785                "No registration entries match the workload selectors",
786            ));
787        }
788
789        Ok(AttestationResult {
790            spiffe_ids,
791            selectors,
792        })
793    }
794
795    /// Number of registration entries.
796    pub async fn count(&self) -> usize {
797        self.entries.read().await.len()
798    }
799
800    /// Remove entries matching a SPIFFE ID.
801    pub async fn remove_by_spiffe_id(&self, id: &SpiffeId) {
802        self.entries.write().await.retain(|e| &e.spiffe_id != id);
803    }
804}
805
806impl Default for RegistrationStore {
807    fn default() -> Self {
808        Self::new()
809    }
810}
811
812// ── Federated Trust Bundle ──────────────────────────────────────────
813
814/// A federated trust bundle containing CA certificates for a remote trust domain.
815#[derive(Debug, Clone, Serialize, Deserialize)]
816pub struct FederatedBundle {
817    /// The trust domain this bundle belongs to.
818    pub trust_domain: String,
819    /// DER-encoded CA certificates.
820    pub ca_certs: Vec<Vec<u8>>,
821    /// When this bundle was last refreshed (UNIX timestamp).
822    pub refreshed_at: u64,
823    /// Sequence number for detecting updates.
824    pub sequence_number: u64,
825}
826
827/// Manages federated trust bundles across trust domains.
828///
829/// Supports SPIFFE bundle endpoint federation (SPIFFE Trust Domain and Bundle spec).
830pub struct FederatedTrustBundleManager {
831    /// Local trust domain.
832    local_domain: String,
833    /// Known federated bundles keyed by trust domain.
834    bundles: Arc<RwLock<HashMap<String, FederatedBundle>>>,
835    /// Trusted federation endpoints: trust_domain → bundle endpoint URL.
836    endpoints: Arc<RwLock<HashMap<String, String>>>,
837}
838
839impl FederatedTrustBundleManager {
840    /// Create a new federated bundle manager for the given local trust domain.
841    pub fn new(local_domain: impl Into<String>) -> Self {
842        Self {
843            local_domain: local_domain.into(),
844            bundles: Arc::new(RwLock::new(HashMap::new())),
845            endpoints: Arc::new(RwLock::new(HashMap::new())),
846        }
847    }
848
849    /// Local trust domain name.
850    pub fn local_domain(&self) -> &str {
851        &self.local_domain
852    }
853
854    /// Register a bundle fetch endpoint for a remote trust domain.
855    pub async fn add_federation_endpoint(&self, trust_domain: &str, endpoint_url: &str) {
856        self.endpoints
857            .write()
858            .await
859            .insert(trust_domain.to_string(), endpoint_url.to_string());
860    }
861
862    /// Store a federated trust bundle.
863    pub async fn store_bundle(&self, bundle: FederatedBundle) {
864        self.bundles
865            .write()
866            .await
867            .insert(bundle.trust_domain.clone(), bundle);
868    }
869
870    /// Get a federated bundle for a trust domain.
871    pub async fn get_bundle(&self, trust_domain: &str) -> Option<FederatedBundle> {
872        self.bundles.read().await.get(trust_domain).cloned()
873    }
874
875    /// Get the federation endpoint URL for a trust domain.
876    pub async fn get_endpoint(&self, trust_domain: &str) -> Option<String> {
877        self.endpoints.read().await.get(trust_domain).cloned()
878    }
879
880    /// List all federated trust domains.
881    pub async fn federated_domains(&self) -> Vec<String> {
882        self.bundles.read().await.keys().cloned().collect()
883    }
884
885    /// Check if a SPIFFE ID from a remote domain is trusted (bundle exists).
886    pub async fn is_federated_id_trusted(&self, id: &SpiffeId) -> bool {
887        if id.trust_domain == self.local_domain {
888            return true; // Local domain is always trusted
889        }
890        self.bundles.read().await.contains_key(&id.trust_domain)
891    }
892
893    /// Remove a federated bundle.
894    pub async fn remove_bundle(&self, trust_domain: &str) -> bool {
895        self.bundles.write().await.remove(trust_domain).is_some()
896    }
897
898    /// Remove stale federated bundles older than the given duration.
899    pub async fn cleanup_stale(&self, max_age: Duration) {
900        let now = SystemTime::now()
901            .duration_since(UNIX_EPOCH)
902            .unwrap_or_default()
903            .as_secs();
904        let max_age_secs = max_age.as_secs();
905        self.bundles
906            .write()
907            .await
908            .retain(|_, b| now.saturating_sub(b.refreshed_at) <= max_age_secs);
909    }
910
911    /// Count of stored federated bundles.
912    pub async fn bundle_count(&self) -> usize {
913        self.bundles.read().await.len()
914    }
915}
916
917#[cfg(test)]
918mod tests {
919    use super::*;
920    use base64::Engine;
921
922    // ── SPIFFE ID parsing ───────────────────────────────────────
923
924    #[test]
925    fn test_parse_valid_spiffe_id() {
926        let id = SpiffeId::parse("spiffe://example.org/service/web").unwrap();
927        assert_eq!(id.trust_domain, "example.org");
928        assert_eq!(id.path, "/service/web");
929        assert_eq!(id.to_uri(), "spiffe://example.org/service/web");
930    }
931
932    #[test]
933    fn test_parse_spiffe_id_no_path() {
934        let id = SpiffeId::parse("spiffe://example.org").unwrap();
935        assert_eq!(id.trust_domain, "example.org");
936        assert_eq!(id.path, "");
937    }
938
939    #[test]
940    fn test_parse_spiffe_id_deeply_nested() {
941        let id = SpiffeId::parse("spiffe://prod.example.com/ns/default/sa/api-server").unwrap();
942        assert_eq!(id.trust_domain, "prod.example.com");
943        assert_eq!(id.path, "/ns/default/sa/api-server");
944    }
945
946    #[test]
947    fn test_parse_missing_scheme() {
948        assert!(SpiffeId::parse("https://example.org/svc").is_err());
949    }
950
951    #[test]
952    fn test_parse_empty_trust_domain() {
953        assert!(SpiffeId::parse("spiffe://").is_err());
954    }
955
956    #[test]
957    fn test_parse_invalid_td_char() {
958        assert!(SpiffeId::parse("spiffe://ex ample.org/svc").is_err());
959    }
960
961    #[test]
962    fn test_parse_query_rejected() {
963        assert!(SpiffeId::parse("spiffe://example.org/svc?q=1").is_err());
964    }
965
966    #[test]
967    fn test_parse_fragment_rejected() {
968        assert!(SpiffeId::parse("spiffe://example.org/svc#frag").is_err());
969    }
970
971    #[test]
972    fn test_parse_trailing_slash_rejected() {
973        assert!(SpiffeId::parse("spiffe://example.org/svc/").is_err());
974    }
975
976    #[test]
977    fn test_parse_empty_segment_rejected() {
978        assert!(SpiffeId::parse("spiffe://example.org//svc").is_err());
979    }
980
981    #[test]
982    fn test_parse_dot_segment_rejected() {
983        assert!(SpiffeId::parse("spiffe://example.org/./svc").is_err());
984        assert!(SpiffeId::parse("spiffe://example.org/../svc").is_err());
985    }
986
987    #[test]
988    fn test_is_member_of() {
989        let id = SpiffeId::parse("spiffe://example.org/svc").unwrap();
990        assert!(id.is_member_of("example.org"));
991        assert!(!id.is_member_of("other.org"));
992    }
993
994    #[test]
995    fn test_matches_path_prefix() {
996        let id = SpiffeId::parse("spiffe://example.org/ns/prod/svc/api").unwrap();
997        assert!(id.matches_path_prefix("/ns/prod"));
998        assert!(!id.matches_path_prefix("/ns/staging"));
999    }
1000
1001    #[test]
1002    fn test_display() {
1003        let id = SpiffeId::parse("spiffe://td/path").unwrap();
1004        assert_eq!(format!("{id}"), "spiffe://td/path");
1005    }
1006
1007    // ── JWT-SVID validation ─────────────────────────────────────
1008
1009    fn make_jwt_svid(sub: &str, aud: &[&str], exp: u64, alg: &str) -> String {
1010        let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;
1011        let header = serde_json::json!({"alg": alg, "typ": "JWT"});
1012        let claims = serde_json::json!({
1013            "sub": sub,
1014            "aud": aud,
1015            "exp": exp,
1016        });
1017        let h = b64.encode(header.to_string().as_bytes());
1018        let c = b64.encode(claims.to_string().as_bytes());
1019        format!("{h}.{c}.fake-signature")
1020    }
1021
1022    #[test]
1023    fn test_validate_jwt_svid_valid() {
1024        let future = SystemTime::now()
1025            .duration_since(UNIX_EPOCH)
1026            .unwrap()
1027            .as_secs()
1028            + 3600;
1029        let token = make_jwt_svid(
1030            "spiffe://example.org/svc/api",
1031            &["https://service.example.org"],
1032            future,
1033            "ES256",
1034        );
1035        let result = validate_jwt_svid(&token, "https://service.example.org").unwrap();
1036        assert_eq!(result.spiffe_id.trust_domain, "example.org");
1037        assert_eq!(result.spiffe_id.path, "/svc/api");
1038    }
1039
1040    #[test]
1041    fn test_validate_jwt_svid_expired() {
1042        let past = 1_000_000;
1043        let token = make_jwt_svid("spiffe://example.org/svc", &["aud"], past, "ES256");
1044        assert!(validate_jwt_svid(&token, "aud").is_err());
1045    }
1046
1047    #[test]
1048    fn test_validate_jwt_svid_wrong_audience() {
1049        let future = SystemTime::now()
1050            .duration_since(UNIX_EPOCH)
1051            .unwrap()
1052            .as_secs()
1053            + 3600;
1054        let token = make_jwt_svid(
1055            "spiffe://example.org/svc",
1056            &["expected-aud"],
1057            future,
1058            "ES256",
1059        );
1060        assert!(validate_jwt_svid(&token, "wrong-aud").is_err());
1061    }
1062
1063    #[test]
1064    fn test_validate_jwt_svid_none_algorithm_rejected() {
1065        let future = SystemTime::now()
1066            .duration_since(UNIX_EPOCH)
1067            .unwrap()
1068            .as_secs()
1069            + 3600;
1070        let token = make_jwt_svid("spiffe://example.org/svc", &["aud"], future, "none");
1071        assert!(validate_jwt_svid(&token, "aud").is_err());
1072    }
1073
1074    #[test]
1075    fn test_validate_jwt_svid_invalid_sub() {
1076        let future = SystemTime::now()
1077            .duration_since(UNIX_EPOCH)
1078            .unwrap()
1079            .as_secs()
1080            + 3600;
1081        let token = make_jwt_svid("https://not-spiffe.example.org", &["aud"], future, "ES256");
1082        assert!(validate_jwt_svid(&token, "aud").is_err());
1083    }
1084
1085    #[test]
1086    fn test_validate_jwt_svid_malformed() {
1087        assert!(validate_jwt_svid("not.a.valid.jwt.token", "aud").is_err());
1088        assert!(validate_jwt_svid("only-one-part", "aud").is_err());
1089    }
1090
1091    // ── X.509-SVID extraction ───────────────────────────────────
1092
1093    #[test]
1094    fn test_extract_spiffe_id_from_synthetic_der() {
1095        // Construct a synthetic DER-like blob embedding a SPIFFE URI
1096        let mut data = vec![0x30, 0x82]; // SEQUENCE header
1097        data.extend_from_slice(&[0x00, 0x50]); // length
1098        data.extend_from_slice(b"some-cert-fields-");
1099        data.extend_from_slice(b"spiffe://example.org/workload/web");
1100        data.push(0x00); // NUL terminator
1101        data.extend_from_slice(&[0xFF; 20]); // padding
1102
1103        let info = extract_spiffe_id_from_der(&data).unwrap();
1104        assert_eq!(info.spiffe_id.trust_domain, "example.org");
1105        assert_eq!(info.spiffe_id.path, "/workload/web");
1106        assert!(!info.fingerprint.is_empty());
1107        assert_eq!(info.fingerprint.len(), 64); // SHA-256 hex = 64 chars
1108    }
1109
1110    #[test]
1111    fn test_extract_spiffe_id_no_uri() {
1112        let data = b"no spiffe uri here at all";
1113        assert!(extract_spiffe_id_from_der(data).is_err());
1114    }
1115
1116    // ── Trust Manager ───────────────────────────────────────────
1117
1118    #[tokio::test]
1119    async fn test_trust_manager_bundle_operations() {
1120        let mgr = SpiffeTrustManager::new();
1121        assert!(!mgr.has_trust_bundle("example.org").await);
1122
1123        mgr.add_trust_bundle("example.org", vec![vec![1, 2, 3]])
1124            .await;
1125        assert!(mgr.has_trust_bundle("example.org").await);
1126
1127        let bundle = mgr.get_trust_bundle("example.org").await.unwrap();
1128        assert_eq!(bundle.len(), 1);
1129
1130        let domains = mgr.trust_domains().await;
1131        assert_eq!(domains, vec!["example.org"]);
1132
1133        assert!(mgr.remove_trust_bundle("example.org").await);
1134        assert!(!mgr.has_trust_bundle("example.org").await);
1135    }
1136
1137    #[tokio::test]
1138    async fn test_trust_manager_verify_jwt_svid_no_bundle() {
1139        let mgr = SpiffeTrustManager::new();
1140        let future = SystemTime::now()
1141            .duration_since(UNIX_EPOCH)
1142            .unwrap()
1143            .as_secs()
1144            + 3600;
1145        let token = make_jwt_svid("spiffe://example.org/svc", &["aud"], future, "ES256");
1146        // No bundle registered → should fail
1147        assert!(mgr.verify_jwt_svid(&token, "aud").await.is_err());
1148    }
1149
1150    #[tokio::test]
1151    async fn test_trust_manager_verify_jwt_svid_with_bundle() {
1152        let mgr = SpiffeTrustManager::new();
1153        mgr.add_trust_bundle("example.org", vec![vec![0xCA]]).await;
1154
1155        let future = SystemTime::now()
1156            .duration_since(UNIX_EPOCH)
1157            .unwrap()
1158            .as_secs()
1159            + 3600;
1160        let token = make_jwt_svid("spiffe://example.org/svc", &["aud"], future, "ES256");
1161        let result = mgr.verify_jwt_svid(&token, "aud").await.unwrap();
1162        assert_eq!(result.spiffe_id.trust_domain, "example.org");
1163    }
1164
1165    // ── Authorization policies ──────────────────────────────────
1166
1167    #[tokio::test]
1168    async fn test_authz_policy_exact_match() {
1169        let mgr = SpiffeTrustManager::new();
1170        mgr.add_policy(SpiffeAuthzPolicy {
1171            source: "spiffe://td/frontend".to_string(),
1172            destination: "spiffe://td/backend".to_string(),
1173            allowed_actions: vec!["GET".to_string(), "POST".to_string()],
1174        })
1175        .await;
1176
1177        let src = SpiffeId::parse("spiffe://td/frontend").unwrap();
1178        let dst = SpiffeId::parse("spiffe://td/backend").unwrap();
1179
1180        assert!(mgr.is_authorized(&src, &dst, "GET").await);
1181        assert!(mgr.is_authorized(&src, &dst, "POST").await);
1182        assert!(!mgr.is_authorized(&src, &dst, "DELETE").await);
1183    }
1184
1185    #[tokio::test]
1186    async fn test_authz_policy_wildcard() {
1187        let mgr = SpiffeTrustManager::new();
1188        mgr.add_policy(SpiffeAuthzPolicy {
1189            source: "*".to_string(),
1190            destination: "spiffe://td/public-api".to_string(),
1191            allowed_actions: vec!["*".to_string()],
1192        })
1193        .await;
1194
1195        let any_src = SpiffeId::parse("spiffe://other/svc").unwrap();
1196        let dst = SpiffeId::parse("spiffe://td/public-api").unwrap();
1197
1198        assert!(mgr.is_authorized(&any_src, &dst, "GET").await);
1199        assert!(mgr.is_authorized(&any_src, &dst, "DELETE").await);
1200    }
1201
1202    #[tokio::test]
1203    async fn test_authz_policy_no_match() {
1204        let mgr = SpiffeTrustManager::new();
1205        let src = SpiffeId::parse("spiffe://td/svc1").unwrap();
1206        let dst = SpiffeId::parse("spiffe://td/svc2").unwrap();
1207        assert!(!mgr.is_authorized(&src, &dst, "GET").await);
1208    }
1209
1210    // ── Workload API Client ─────────────────────────────────────
1211
1212    #[test]
1213    fn test_workload_api_config_defaults() {
1214        let cfg = WorkloadApiConfig::default();
1215        assert!(cfg.endpoint.contains("spire-agent"));
1216        assert_eq!(cfg.rotation_interval_secs, 300);
1217        assert!(cfg.jwt_audiences.is_empty());
1218    }
1219
1220    #[tokio::test]
1221    async fn test_workload_api_store_x509_svid() {
1222        let client = WorkloadApiClient::new(WorkloadApiConfig::default());
1223        let svid = SvidResponse::X509 {
1224            spiffe_id: "spiffe://example.org/web".to_string(),
1225            cert_chain: vec![vec![0x30, 0x82]],
1226            private_key: vec![0x01],
1227            bundle: vec![vec![0xCA]],
1228            expires_at: 9999999999,
1229        };
1230        client.store_x509_svid(svid).await;
1231        assert_eq!(client.x509_count().await, 1);
1232        assert!(
1233            client
1234                .get_x509_svid("spiffe://example.org/web")
1235                .await
1236                .is_some()
1237        );
1238        // Should also have stored the bundle
1239        assert!(client.get_bundle("example.org").await.is_some());
1240    }
1241
1242    #[tokio::test]
1243    async fn test_workload_api_store_jwt_svid() {
1244        let client = WorkloadApiClient::new(WorkloadApiConfig::default());
1245        let svid = SvidResponse::Jwt {
1246            spiffe_id: "spiffe://example.org/api".to_string(),
1247            token: "eyJ...".to_string(),
1248            expires_at: 9999999999,
1249        };
1250        client.store_jwt_svid(svid).await;
1251        assert_eq!(client.jwt_count().await, 1);
1252        assert!(
1253            client
1254                .get_jwt_svid("spiffe://example.org/api")
1255                .await
1256                .is_some()
1257        );
1258    }
1259
1260    #[tokio::test]
1261    async fn test_workload_api_cleanup_expired() {
1262        let client = WorkloadApiClient::new(WorkloadApiConfig::default());
1263        // Store an already-expired SVID
1264        let svid = SvidResponse::X509 {
1265            spiffe_id: "spiffe://example.org/old".to_string(),
1266            cert_chain: vec![],
1267            private_key: vec![],
1268            bundle: vec![],
1269            expires_at: 1, // expired long ago
1270        };
1271        client.store_x509_svid(svid).await;
1272        assert_eq!(client.x509_count().await, 1);
1273        client.cleanup_expired().await;
1274        assert_eq!(client.x509_count().await, 0);
1275    }
1276
1277    #[tokio::test]
1278    async fn test_workload_api_needs_rotation() {
1279        let client = WorkloadApiClient::new(WorkloadApiConfig::default());
1280        // Store an SVID expiring in 10 seconds (less than 300s rotation interval)
1281        let now = SystemTime::now()
1282            .duration_since(UNIX_EPOCH)
1283            .unwrap()
1284            .as_secs();
1285        let svid = SvidResponse::X509 {
1286            spiffe_id: "spiffe://example.org/expiring".to_string(),
1287            cert_chain: vec![],
1288            private_key: vec![],
1289            bundle: vec![],
1290            expires_at: now + 10,
1291        };
1292        client.store_x509_svid(svid).await;
1293        let needs = client.needs_rotation().await;
1294        assert_eq!(needs.len(), 1);
1295        assert_eq!(needs[0], "spiffe://example.org/expiring");
1296    }
1297
1298    #[test]
1299    fn test_workload_api_rotation_interval() {
1300        let cfg = WorkloadApiConfig {
1301            rotation_interval_secs: 600,
1302            ..WorkloadApiConfig::default()
1303        };
1304        let client = WorkloadApiClient::new(cfg);
1305        assert_eq!(client.rotation_interval(), Duration::from_secs(600));
1306    }
1307
1308    // ── Workload Selectors ──────────────────────────────────────
1309
1310    #[test]
1311    fn test_workload_selector_unix_uid() {
1312        let s = WorkloadSelector::unix_uid(1000);
1313        assert_eq!(s.selector_type, "unix");
1314        assert_eq!(s.value, "uid:1000");
1315    }
1316
1317    #[test]
1318    fn test_workload_selector_k8s_sa() {
1319        let s = WorkloadSelector::k8s_sa("default", "api-server");
1320        assert_eq!(s.selector_type, "k8s");
1321        assert_eq!(s.value, "sa:default:api-server");
1322    }
1323
1324    #[test]
1325    fn test_workload_selector_docker_image() {
1326        let s = WorkloadSelector::docker_image_id("sha256:abc123");
1327        assert_eq!(s.selector_type, "docker");
1328        assert_eq!(s.value, "image_id:sha256:abc123");
1329    }
1330
1331    // ── Registration Store & Attestation ────────────────────────
1332
1333    #[tokio::test]
1334    async fn test_registration_store_match_selectors() {
1335        let store = RegistrationStore::new();
1336        let entry = RegistrationEntry {
1337            spiffe_id: SpiffeId::parse("spiffe://example.org/web").unwrap(),
1338            parent_id: SpiffeId::parse("spiffe://example.org/node1").unwrap(),
1339            selectors: vec![WorkloadSelector::unix_uid(1000)],
1340            ttl: 3600,
1341            downstream: false,
1342        };
1343        store.register(entry).await;
1344
1345        // Workload has matching selector
1346        let ids = store
1347            .match_selectors(&[WorkloadSelector::unix_uid(1000)])
1348            .await;
1349        assert_eq!(ids.len(), 1);
1350        assert_eq!(ids[0].path, "/web");
1351
1352        // Workload has extra selectors → still matches (superset)
1353        let ids = store
1354            .match_selectors(&[
1355                WorkloadSelector::unix_uid(1000),
1356                WorkloadSelector::unix_gid(100),
1357            ])
1358            .await;
1359        assert_eq!(ids.len(), 1);
1360
1361        // Workload missing required selector → no match
1362        let ids = store
1363            .match_selectors(&[WorkloadSelector::unix_uid(2000)])
1364            .await;
1365        assert!(ids.is_empty());
1366    }
1367
1368    #[tokio::test]
1369    async fn test_registration_store_attest() {
1370        let store = RegistrationStore::new();
1371        let entry = RegistrationEntry {
1372            spiffe_id: SpiffeId::parse("spiffe://example.org/api").unwrap(),
1373            parent_id: SpiffeId::parse("spiffe://example.org/node1").unwrap(),
1374            selectors: vec![WorkloadSelector {
1375                selector_type: "unix".to_string(),
1376                value: "uid:1000".to_string(),
1377            }],
1378            ttl: 3600,
1379            downstream: false,
1380        };
1381        store.register(entry).await;
1382
1383        let evidence = AttestationEvidence {
1384            attestor: "unix".to_string(),
1385            payload: HashMap::from([("uid".to_string(), "1000".to_string())]),
1386        };
1387        let result = store.attest(&evidence).await.unwrap();
1388        assert_eq!(result.spiffe_ids.len(), 1);
1389        assert_eq!(result.spiffe_ids[0].path, "/api");
1390        assert_eq!(result.selectors.len(), 1);
1391    }
1392
1393    #[tokio::test]
1394    async fn test_registration_store_attest_no_match() {
1395        let store = RegistrationStore::new();
1396        let evidence = AttestationEvidence {
1397            attestor: "unix".to_string(),
1398            payload: HashMap::from([("uid".to_string(), "9999".to_string())]),
1399        };
1400        assert!(store.attest(&evidence).await.is_err());
1401    }
1402
1403    #[tokio::test]
1404    async fn test_registration_store_remove_by_spiffe_id() {
1405        let store = RegistrationStore::new();
1406        let id = SpiffeId::parse("spiffe://example.org/web").unwrap();
1407        store
1408            .register(RegistrationEntry {
1409                spiffe_id: id.clone(),
1410                parent_id: SpiffeId::parse("spiffe://example.org/node").unwrap(),
1411                selectors: vec![],
1412                ttl: 3600,
1413                downstream: false,
1414            })
1415            .await;
1416        assert_eq!(store.count().await, 1);
1417        store.remove_by_spiffe_id(&id).await;
1418        assert_eq!(store.count().await, 0);
1419    }
1420
1421    // ── Federated Trust Bundle Manager ──────────────────────────
1422
1423    #[tokio::test]
1424    async fn test_federated_bundle_manager_local_domain() {
1425        let mgr = FederatedTrustBundleManager::new("example.org");
1426        assert_eq!(mgr.local_domain(), "example.org");
1427    }
1428
1429    #[tokio::test]
1430    async fn test_federated_bundle_store_and_retrieve() {
1431        let mgr = FederatedTrustBundleManager::new("local.org");
1432        let bundle = FederatedBundle {
1433            trust_domain: "remote.org".to_string(),
1434            ca_certs: vec![vec![0xCA, 0xFE]],
1435            refreshed_at: 1000000,
1436            sequence_number: 1,
1437        };
1438        mgr.store_bundle(bundle).await;
1439        assert_eq!(mgr.bundle_count().await, 1);
1440
1441        let b = mgr.get_bundle("remote.org").await.unwrap();
1442        assert_eq!(b.sequence_number, 1);
1443        assert_eq!(b.ca_certs.len(), 1);
1444    }
1445
1446    #[tokio::test]
1447    async fn test_federated_bundle_is_trusted() {
1448        let mgr = FederatedTrustBundleManager::new("local.org");
1449        let local_id = SpiffeId::parse("spiffe://local.org/svc").unwrap();
1450        let remote_id = SpiffeId::parse("spiffe://remote.org/svc").unwrap();
1451
1452        // Local domain always trusted
1453        assert!(mgr.is_federated_id_trusted(&local_id).await);
1454        // Remote not trusted yet
1455        assert!(!mgr.is_federated_id_trusted(&remote_id).await);
1456
1457        // Add federation
1458        mgr.store_bundle(FederatedBundle {
1459            trust_domain: "remote.org".to_string(),
1460            ca_certs: vec![vec![0x01]],
1461            refreshed_at: 9999999999,
1462            sequence_number: 1,
1463        })
1464        .await;
1465        assert!(mgr.is_federated_id_trusted(&remote_id).await);
1466    }
1467
1468    #[tokio::test]
1469    async fn test_federated_bundle_remove() {
1470        let mgr = FederatedTrustBundleManager::new("local.org");
1471        mgr.store_bundle(FederatedBundle {
1472            trust_domain: "remote.org".to_string(),
1473            ca_certs: vec![],
1474            refreshed_at: 0,
1475            sequence_number: 0,
1476        })
1477        .await;
1478        assert!(mgr.remove_bundle("remote.org").await);
1479        assert!(!mgr.remove_bundle("remote.org").await);
1480        assert_eq!(mgr.bundle_count().await, 0);
1481    }
1482
1483    #[tokio::test]
1484    async fn test_federated_bundle_cleanup_stale() {
1485        let mgr = FederatedTrustBundleManager::new("local.org");
1486        // Store a bundle that was refreshed at epoch 0 (very stale)
1487        mgr.store_bundle(FederatedBundle {
1488            trust_domain: "stale.org".to_string(),
1489            ca_certs: vec![],
1490            refreshed_at: 0,
1491            sequence_number: 1,
1492        })
1493        .await;
1494        // Store a fresh bundle
1495        let now = SystemTime::now()
1496            .duration_since(UNIX_EPOCH)
1497            .unwrap()
1498            .as_secs();
1499        mgr.store_bundle(FederatedBundle {
1500            trust_domain: "fresh.org".to_string(),
1501            ca_certs: vec![],
1502            refreshed_at: now,
1503            sequence_number: 1,
1504        })
1505        .await;
1506        assert_eq!(mgr.bundle_count().await, 2);
1507
1508        mgr.cleanup_stale(Duration::from_secs(3600)).await;
1509        assert_eq!(mgr.bundle_count().await, 1);
1510        assert!(mgr.get_bundle("fresh.org").await.is_some());
1511        assert!(mgr.get_bundle("stale.org").await.is_none());
1512    }
1513
1514    #[tokio::test]
1515    async fn test_federated_bundle_endpoints() {
1516        let mgr = FederatedTrustBundleManager::new("local.org");
1517        mgr.add_federation_endpoint("remote.org", "https://remote.org/.well-known/spiffe-bundle")
1518            .await;
1519        let ep = mgr.get_endpoint("remote.org").await.unwrap();
1520        assert!(ep.contains("spiffe-bundle"));
1521        assert!(mgr.get_endpoint("unknown.org").await.is_none());
1522    }
1523
1524    #[tokio::test]
1525    async fn test_federated_bundle_list_domains() {
1526        let mgr = FederatedTrustBundleManager::new("local.org");
1527        mgr.store_bundle(FederatedBundle {
1528            trust_domain: "a.org".to_string(),
1529            ca_certs: vec![],
1530            refreshed_at: 0,
1531            sequence_number: 0,
1532        })
1533        .await;
1534        mgr.store_bundle(FederatedBundle {
1535            trust_domain: "b.org".to_string(),
1536            ca_certs: vec![],
1537            refreshed_at: 0,
1538            sequence_number: 0,
1539        })
1540        .await;
1541        let mut domains = mgr.federated_domains().await;
1542        domains.sort();
1543        assert_eq!(domains, vec!["a.org", "b.org"]);
1544    }
1545}