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