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(Debug, 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
662/// The result of a successful workload attestation.
663#[derive(Debug, Clone, Serialize, Deserialize)]
664pub struct AttestationResult {
665    /// The SPIFFE IDs assigned to the attested workload.
666    pub spiffe_ids: Vec<SpiffeId>,
667    /// Workload selectors discovered during attestation.
668    pub selectors: Vec<WorkloadSelector>,
669}
670
671/// A selector that identifies a workload property (used in SPIRE registration entries).
672#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
673pub struct WorkloadSelector {
674    /// Selector type (e.g., "unix", "k8s", "docker").
675    pub selector_type: String,
676    /// Selector value (e.g., "uid:1000", "sa:default", "image_id:sha256:abc").
677    pub value: String,
678}
679
680impl WorkloadSelector {
681    /// Create a Unix UID selector.
682    pub fn unix_uid(uid: u32) -> Self {
683        Self {
684            selector_type: "unix".to_string(),
685            value: format!("uid:{uid}"),
686        }
687    }
688
689    /// Create a Unix GID selector.
690    pub fn unix_gid(gid: u32) -> Self {
691        Self {
692            selector_type: "unix".to_string(),
693            value: format!("gid:{gid}"),
694        }
695    }
696
697    /// Create a Kubernetes service account selector.
698    pub fn k8s_sa(namespace: &str, name: &str) -> Self {
699        Self {
700            selector_type: "k8s".to_string(),
701            value: format!("sa:{namespace}:{name}"),
702        }
703    }
704
705    /// Create a Kubernetes pod label selector.
706    pub fn k8s_pod_label(key: &str, value: &str) -> Self {
707        Self {
708            selector_type: "k8s".to_string(),
709            value: format!("pod-label:{key}:{value}"),
710        }
711    }
712
713    /// Create a Docker image ID selector.
714    pub fn docker_image_id(image_id: &str) -> Self {
715        Self {
716            selector_type: "docker".to_string(),
717            value: format!("image_id:{image_id}"),
718        }
719    }
720}
721
722/// A SPIRE registration entry that maps selectors to SPIFFE IDs.
723#[derive(Debug, Clone, Serialize, Deserialize)]
724pub struct RegistrationEntry {
725    /// The SPIFFE ID to assign to workloads matching the selectors.
726    pub spiffe_id: SpiffeId,
727    /// The parent SPIFFE ID (typically the node agent's SPIFFE ID).
728    pub parent_id: SpiffeId,
729    /// Selectors that a workload must match to receive this SPIFFE ID.
730    pub selectors: Vec<WorkloadSelector>,
731    /// Time-to-live for the SVIDs issued under this entry (seconds).
732    pub ttl: u64,
733    /// Whether this entry is for downstream workloads (federated).
734    pub downstream: bool,
735}
736
737/// In-memory registration entry store for SPIRE-style workload attestation.
738pub struct RegistrationStore {
739    entries: Arc<RwLock<Vec<RegistrationEntry>>>,
740}
741
742impl RegistrationStore {
743    /// Create an empty registration store.
744    pub fn new() -> Self {
745        Self {
746            entries: Arc::new(RwLock::new(Vec::new())),
747        }
748    }
749
750    /// Add a registration entry.
751    pub async fn register(&self, entry: RegistrationEntry) {
752        self.entries.write().await.push(entry);
753    }
754
755    /// Find all SPIFFE IDs that match the given selectors.
756    ///
757    /// A workload matches a registration entry if the workload's selectors are
758    /// a superset of the entry's selectors.
759    pub async fn match_selectors(&self, workload_selectors: &[WorkloadSelector]) -> Vec<SpiffeId> {
760        let entries = self.entries.read().await;
761        entries
762            .iter()
763            .filter(|entry| {
764                entry
765                    .selectors
766                    .iter()
767                    .all(|s| workload_selectors.contains(s))
768            })
769            .map(|entry| entry.spiffe_id.clone())
770            .collect()
771    }
772
773    /// Perform workload attestation: given evidence, extract selectors and find matching IDs.
774    pub async fn attest(&self, evidence: &AttestationEvidence) -> Result<AttestationResult> {
775        // Build selectors from evidence payload
776        let selectors: Vec<WorkloadSelector> = evidence
777            .payload
778            .iter()
779            .map(|(key, value)| WorkloadSelector {
780                selector_type: evidence.attestor.clone(),
781                value: format!("{key}:{value}"),
782            })
783            .collect();
784
785        if selectors.is_empty() {
786            return Err(AuthError::validation(
787                "Attestation evidence contains no selectors",
788            ));
789        }
790
791        let spiffe_ids = self.match_selectors(&selectors).await;
792        if spiffe_ids.is_empty() {
793            return Err(AuthError::validation(
794                "No registration entries match the workload selectors",
795            ));
796        }
797
798        Ok(AttestationResult {
799            spiffe_ids,
800            selectors,
801        })
802    }
803
804    /// Number of registration entries.
805    pub async fn count(&self) -> usize {
806        self.entries.read().await.len()
807    }
808
809    /// Remove entries matching a SPIFFE ID.
810    pub async fn remove_by_spiffe_id(&self, id: &SpiffeId) {
811        self.entries.write().await.retain(|e| &e.spiffe_id != id);
812    }
813}
814
815impl Default for RegistrationStore {
816    fn default() -> Self {
817        Self::new()
818    }
819}
820
821// ── Federated Trust Bundle ──────────────────────────────────────────
822
823/// A federated trust bundle containing CA certificates for a remote trust domain.
824#[derive(Debug, Clone, Serialize, Deserialize)]
825pub struct FederatedBundle {
826    /// The trust domain this bundle belongs to.
827    pub trust_domain: String,
828    /// DER-encoded CA certificates.
829    pub ca_certs: Vec<Vec<u8>>,
830    /// When this bundle was last refreshed (UNIX timestamp).
831    pub refreshed_at: u64,
832    /// Sequence number for detecting updates.
833    pub sequence_number: u64,
834}
835
836/// Manages federated trust bundles across trust domains.
837///
838/// Supports SPIFFE bundle endpoint federation (SPIFFE Trust Domain and Bundle spec).
839pub struct FederatedTrustBundleManager {
840    /// Local trust domain.
841    local_domain: String,
842    /// Known federated bundles keyed by trust domain.
843    bundles: Arc<RwLock<HashMap<String, FederatedBundle>>>,
844    /// Trusted federation endpoints: trust_domain → bundle endpoint URL.
845    endpoints: Arc<RwLock<HashMap<String, String>>>,
846}
847
848impl FederatedTrustBundleManager {
849    /// Create a new federated bundle manager for the given local trust domain.
850    pub fn new(local_domain: impl Into<String>) -> Self {
851        Self {
852            local_domain: local_domain.into(),
853            bundles: Arc::new(RwLock::new(HashMap::new())),
854            endpoints: Arc::new(RwLock::new(HashMap::new())),
855        }
856    }
857
858    /// Local trust domain name.
859    pub fn local_domain(&self) -> &str {
860        &self.local_domain
861    }
862
863    /// Register a bundle fetch endpoint for a remote trust domain.
864    pub async fn add_federation_endpoint(&self, trust_domain: &str, endpoint_url: &str) {
865        self.endpoints
866            .write()
867            .await
868            .insert(trust_domain.to_string(), endpoint_url.to_string());
869    }
870
871    /// Store a federated trust bundle.
872    pub async fn store_bundle(&self, bundle: FederatedBundle) {
873        self.bundles
874            .write()
875            .await
876            .insert(bundle.trust_domain.clone(), bundle);
877    }
878
879    /// Get a federated bundle for a trust domain.
880    pub async fn get_bundle(&self, trust_domain: &str) -> Option<FederatedBundle> {
881        self.bundles.read().await.get(trust_domain).cloned()
882    }
883
884    /// Get the federation endpoint URL for a trust domain.
885    pub async fn get_endpoint(&self, trust_domain: &str) -> Option<String> {
886        self.endpoints.read().await.get(trust_domain).cloned()
887    }
888
889    /// List all federated trust domains.
890    pub async fn federated_domains(&self) -> Vec<String> {
891        self.bundles.read().await.keys().cloned().collect()
892    }
893
894    /// Check if a SPIFFE ID from a remote domain is trusted (bundle exists).
895    pub async fn is_federated_id_trusted(&self, id: &SpiffeId) -> bool {
896        if id.trust_domain == self.local_domain {
897            return true; // Local domain is always trusted
898        }
899        self.bundles.read().await.contains_key(&id.trust_domain)
900    }
901
902    /// Remove a federated bundle.
903    pub async fn remove_bundle(&self, trust_domain: &str) -> bool {
904        self.bundles.write().await.remove(trust_domain).is_some()
905    }
906
907    /// Remove stale federated bundles older than the given duration.
908    pub async fn cleanup_stale(&self, max_age: Duration) {
909        let now = SystemTime::now()
910            .duration_since(UNIX_EPOCH)
911            .unwrap_or_default()
912            .as_secs();
913        let max_age_secs = max_age.as_secs();
914        self.bundles
915            .write()
916            .await
917            .retain(|_, b| now.saturating_sub(b.refreshed_at) <= max_age_secs);
918    }
919
920    /// Count of stored federated bundles.
921    pub async fn bundle_count(&self) -> usize {
922        self.bundles.read().await.len()
923    }
924}
925
926#[cfg(test)]
927mod tests {
928    use super::*;
929    use base64::Engine;
930
931    // ── SPIFFE ID parsing ───────────────────────────────────────
932
933    #[test]
934    fn test_parse_valid_spiffe_id() {
935        let id = SpiffeId::parse("spiffe://example.org/service/web").unwrap();
936        assert_eq!(id.trust_domain, "example.org");
937        assert_eq!(id.path, "/service/web");
938        assert_eq!(id.to_uri(), "spiffe://example.org/service/web");
939    }
940
941    #[test]
942    fn test_parse_spiffe_id_no_path() {
943        let id = SpiffeId::parse("spiffe://example.org").unwrap();
944        assert_eq!(id.trust_domain, "example.org");
945        assert_eq!(id.path, "");
946    }
947
948    #[test]
949    fn test_parse_spiffe_id_deeply_nested() {
950        let id = SpiffeId::parse("spiffe://prod.example.com/ns/default/sa/api-server").unwrap();
951        assert_eq!(id.trust_domain, "prod.example.com");
952        assert_eq!(id.path, "/ns/default/sa/api-server");
953    }
954
955    #[test]
956    fn test_parse_missing_scheme() {
957        assert!(SpiffeId::parse("https://example.org/svc").is_err());
958    }
959
960    #[test]
961    fn test_parse_empty_trust_domain() {
962        assert!(SpiffeId::parse("spiffe://").is_err());
963    }
964
965    #[test]
966    fn test_parse_invalid_td_char() {
967        assert!(SpiffeId::parse("spiffe://ex ample.org/svc").is_err());
968    }
969
970    #[test]
971    fn test_parse_query_rejected() {
972        assert!(SpiffeId::parse("spiffe://example.org/svc?q=1").is_err());
973    }
974
975    #[test]
976    fn test_parse_fragment_rejected() {
977        assert!(SpiffeId::parse("spiffe://example.org/svc#frag").is_err());
978    }
979
980    #[test]
981    fn test_parse_trailing_slash_rejected() {
982        assert!(SpiffeId::parse("spiffe://example.org/svc/").is_err());
983    }
984
985    #[test]
986    fn test_parse_empty_segment_rejected() {
987        assert!(SpiffeId::parse("spiffe://example.org//svc").is_err());
988    }
989
990    #[test]
991    fn test_parse_dot_segment_rejected() {
992        assert!(SpiffeId::parse("spiffe://example.org/./svc").is_err());
993        assert!(SpiffeId::parse("spiffe://example.org/../svc").is_err());
994    }
995
996    #[test]
997    fn test_is_member_of() {
998        let id = SpiffeId::parse("spiffe://example.org/svc").unwrap();
999        assert!(id.is_member_of("example.org"));
1000        assert!(!id.is_member_of("other.org"));
1001    }
1002
1003    #[test]
1004    fn test_matches_path_prefix() {
1005        let id = SpiffeId::parse("spiffe://example.org/ns/prod/svc/api").unwrap();
1006        assert!(id.matches_path_prefix("/ns/prod"));
1007        assert!(!id.matches_path_prefix("/ns/staging"));
1008    }
1009
1010    #[test]
1011    fn test_display() {
1012        let id = SpiffeId::parse("spiffe://td/path").unwrap();
1013        assert_eq!(format!("{id}"), "spiffe://td/path");
1014    }
1015
1016    // ── JWT-SVID validation ─────────────────────────────────────
1017
1018    fn make_jwt_svid(sub: &str, aud: &[&str], exp: u64, alg: &str) -> String {
1019        let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;
1020        let header = serde_json::json!({"alg": alg, "typ": "JWT"});
1021        let claims = serde_json::json!({
1022            "sub": sub,
1023            "aud": aud,
1024            "exp": exp,
1025        });
1026        let h = b64.encode(header.to_string().as_bytes());
1027        let c = b64.encode(claims.to_string().as_bytes());
1028        format!("{h}.{c}.fake-signature")
1029    }
1030
1031    #[test]
1032    fn test_validate_jwt_svid_valid() {
1033        let future = SystemTime::now()
1034            .duration_since(UNIX_EPOCH)
1035            .unwrap()
1036            .as_secs()
1037            + 3600;
1038        let token = make_jwt_svid(
1039            "spiffe://example.org/svc/api",
1040            &["https://service.example.org"],
1041            future,
1042            "ES256",
1043        );
1044        let result = validate_jwt_svid(&token, "https://service.example.org").unwrap();
1045        assert_eq!(result.spiffe_id.trust_domain, "example.org");
1046        assert_eq!(result.spiffe_id.path, "/svc/api");
1047    }
1048
1049    #[test]
1050    fn test_validate_jwt_svid_expired() {
1051        let past = 1_000_000;
1052        let token = make_jwt_svid("spiffe://example.org/svc", &["aud"], past, "ES256");
1053        assert!(validate_jwt_svid(&token, "aud").is_err());
1054    }
1055
1056    #[test]
1057    fn test_validate_jwt_svid_wrong_audience() {
1058        let future = SystemTime::now()
1059            .duration_since(UNIX_EPOCH)
1060            .unwrap()
1061            .as_secs()
1062            + 3600;
1063        let token = make_jwt_svid(
1064            "spiffe://example.org/svc",
1065            &["expected-aud"],
1066            future,
1067            "ES256",
1068        );
1069        assert!(validate_jwt_svid(&token, "wrong-aud").is_err());
1070    }
1071
1072    #[test]
1073    fn test_validate_jwt_svid_none_algorithm_rejected() {
1074        let future = SystemTime::now()
1075            .duration_since(UNIX_EPOCH)
1076            .unwrap()
1077            .as_secs()
1078            + 3600;
1079        let token = make_jwt_svid("spiffe://example.org/svc", &["aud"], future, "none");
1080        assert!(validate_jwt_svid(&token, "aud").is_err());
1081    }
1082
1083    #[test]
1084    fn test_validate_jwt_svid_invalid_sub() {
1085        let future = SystemTime::now()
1086            .duration_since(UNIX_EPOCH)
1087            .unwrap()
1088            .as_secs()
1089            + 3600;
1090        let token = make_jwt_svid("https://not-spiffe.example.org", &["aud"], future, "ES256");
1091        assert!(validate_jwt_svid(&token, "aud").is_err());
1092    }
1093
1094    #[test]
1095    fn test_validate_jwt_svid_malformed() {
1096        assert!(validate_jwt_svid("not.a.valid.jwt.token", "aud").is_err());
1097        assert!(validate_jwt_svid("only-one-part", "aud").is_err());
1098    }
1099
1100    // ── X.509-SVID extraction ───────────────────────────────────
1101
1102    #[test]
1103    fn test_extract_spiffe_id_from_synthetic_der() {
1104        // Construct a synthetic DER-like blob embedding a SPIFFE URI
1105        let mut data = vec![0x30, 0x82]; // SEQUENCE header
1106        data.extend_from_slice(&[0x00, 0x50]); // length
1107        data.extend_from_slice(b"some-cert-fields-");
1108        data.extend_from_slice(b"spiffe://example.org/workload/web");
1109        data.push(0x00); // NUL terminator
1110        data.extend_from_slice(&[0xFF; 20]); // padding
1111
1112        let info = extract_spiffe_id_from_der(&data).unwrap();
1113        assert_eq!(info.spiffe_id.trust_domain, "example.org");
1114        assert_eq!(info.spiffe_id.path, "/workload/web");
1115        assert!(!info.fingerprint.is_empty());
1116        assert_eq!(info.fingerprint.len(), 64); // SHA-256 hex = 64 chars
1117    }
1118
1119    #[test]
1120    fn test_extract_spiffe_id_no_uri() {
1121        let data = b"no spiffe uri here at all";
1122        assert!(extract_spiffe_id_from_der(data).is_err());
1123    }
1124
1125    // ── Trust Manager ───────────────────────────────────────────
1126
1127    #[tokio::test]
1128    async fn test_trust_manager_bundle_operations() {
1129        let mgr = SpiffeTrustManager::new();
1130        assert!(!mgr.has_trust_bundle("example.org").await);
1131
1132        mgr.add_trust_bundle("example.org", vec![vec![1, 2, 3]])
1133            .await;
1134        assert!(mgr.has_trust_bundle("example.org").await);
1135
1136        let bundle = mgr.get_trust_bundle("example.org").await.unwrap();
1137        assert_eq!(bundle.len(), 1);
1138
1139        let domains = mgr.trust_domains().await;
1140        assert_eq!(domains, vec!["example.org"]);
1141
1142        assert!(mgr.remove_trust_bundle("example.org").await);
1143        assert!(!mgr.has_trust_bundle("example.org").await);
1144    }
1145
1146    #[tokio::test]
1147    async fn test_trust_manager_verify_jwt_svid_no_bundle() {
1148        let mgr = SpiffeTrustManager::new();
1149        let future = SystemTime::now()
1150            .duration_since(UNIX_EPOCH)
1151            .unwrap()
1152            .as_secs()
1153            + 3600;
1154        let token = make_jwt_svid("spiffe://example.org/svc", &["aud"], future, "ES256");
1155        // No bundle registered → should fail
1156        assert!(mgr.verify_jwt_svid(&token, "aud").await.is_err());
1157    }
1158
1159    #[tokio::test]
1160    async fn test_trust_manager_verify_jwt_svid_with_bundle() {
1161        let mgr = SpiffeTrustManager::new();
1162        mgr.add_trust_bundle("example.org", vec![vec![0xCA]]).await;
1163
1164        let future = SystemTime::now()
1165            .duration_since(UNIX_EPOCH)
1166            .unwrap()
1167            .as_secs()
1168            + 3600;
1169        let token = make_jwt_svid("spiffe://example.org/svc", &["aud"], future, "ES256");
1170        let result = mgr.verify_jwt_svid(&token, "aud").await.unwrap();
1171        assert_eq!(result.spiffe_id.trust_domain, "example.org");
1172    }
1173
1174    // ── Authorization policies ──────────────────────────────────
1175
1176    #[tokio::test]
1177    async fn test_authz_policy_exact_match() {
1178        let mgr = SpiffeTrustManager::new();
1179        mgr.add_policy(SpiffeAuthzPolicy {
1180            source: "spiffe://td/frontend".to_string(),
1181            destination: "spiffe://td/backend".to_string(),
1182            allowed_actions: vec!["GET".to_string(), "POST".to_string()],
1183        })
1184        .await;
1185
1186        let src = SpiffeId::parse("spiffe://td/frontend").unwrap();
1187        let dst = SpiffeId::parse("spiffe://td/backend").unwrap();
1188
1189        assert!(mgr.is_authorized(&src, &dst, "GET").await);
1190        assert!(mgr.is_authorized(&src, &dst, "POST").await);
1191        assert!(!mgr.is_authorized(&src, &dst, "DELETE").await);
1192    }
1193
1194    #[tokio::test]
1195    async fn test_authz_policy_wildcard() {
1196        let mgr = SpiffeTrustManager::new();
1197        mgr.add_policy(SpiffeAuthzPolicy {
1198            source: "*".to_string(),
1199            destination: "spiffe://td/public-api".to_string(),
1200            allowed_actions: vec!["*".to_string()],
1201        })
1202        .await;
1203
1204        let any_src = SpiffeId::parse("spiffe://other/svc").unwrap();
1205        let dst = SpiffeId::parse("spiffe://td/public-api").unwrap();
1206
1207        assert!(mgr.is_authorized(&any_src, &dst, "GET").await);
1208        assert!(mgr.is_authorized(&any_src, &dst, "DELETE").await);
1209    }
1210
1211    #[tokio::test]
1212    async fn test_authz_policy_no_match() {
1213        let mgr = SpiffeTrustManager::new();
1214        let src = SpiffeId::parse("spiffe://td/svc1").unwrap();
1215        let dst = SpiffeId::parse("spiffe://td/svc2").unwrap();
1216        assert!(!mgr.is_authorized(&src, &dst, "GET").await);
1217    }
1218
1219    // ── Workload API Client ─────────────────────────────────────
1220
1221    #[test]
1222    fn test_workload_api_config_defaults() {
1223        let cfg = WorkloadApiConfig::default();
1224        assert!(cfg.endpoint.contains("spire-agent"));
1225        assert_eq!(cfg.rotation_interval_secs, 300);
1226        assert!(cfg.jwt_audiences.is_empty());
1227    }
1228
1229    #[tokio::test]
1230    async fn test_workload_api_store_x509_svid() {
1231        let client = WorkloadApiClient::new(WorkloadApiConfig::default());
1232        let svid = SvidResponse::X509 {
1233            spiffe_id: "spiffe://example.org/web".to_string(),
1234            cert_chain: vec![vec![0x30, 0x82]],
1235            private_key: vec![0x01].into(),
1236            bundle: vec![vec![0xCA]],
1237            expires_at: 9999999999,
1238        };
1239        client.store_x509_svid(svid).await;
1240        assert_eq!(client.x509_count().await, 1);
1241        assert!(
1242            client
1243                .get_x509_svid("spiffe://example.org/web")
1244                .await
1245                .is_some()
1246        );
1247        // Should also have stored the bundle
1248        assert!(client.get_bundle("example.org").await.is_some());
1249    }
1250
1251    #[tokio::test]
1252    async fn test_workload_api_store_jwt_svid() {
1253        let client = WorkloadApiClient::new(WorkloadApiConfig::default());
1254        let svid = SvidResponse::Jwt {
1255            spiffe_id: "spiffe://example.org/api".to_string(),
1256            token: "eyJ...".to_string(),
1257            expires_at: 9999999999,
1258        };
1259        client.store_jwt_svid(svid).await;
1260        assert_eq!(client.jwt_count().await, 1);
1261        assert!(
1262            client
1263                .get_jwt_svid("spiffe://example.org/api")
1264                .await
1265                .is_some()
1266        );
1267    }
1268
1269    #[tokio::test]
1270    async fn test_workload_api_cleanup_expired() {
1271        let client = WorkloadApiClient::new(WorkloadApiConfig::default());
1272        // Store an already-expired SVID
1273        let svid = SvidResponse::X509 {
1274            spiffe_id: "spiffe://example.org/old".to_string(),
1275            cert_chain: vec![],
1276            private_key: vec![].into(),
1277            bundle: vec![],
1278            expires_at: 1, // expired long ago
1279        };
1280        client.store_x509_svid(svid).await;
1281        assert_eq!(client.x509_count().await, 1);
1282        client.cleanup_expired().await;
1283        assert_eq!(client.x509_count().await, 0);
1284    }
1285
1286    #[tokio::test]
1287    async fn test_workload_api_needs_rotation() {
1288        let client = WorkloadApiClient::new(WorkloadApiConfig::default());
1289        // Store an SVID expiring in 10 seconds (less than 300s rotation interval)
1290        let now = SystemTime::now()
1291            .duration_since(UNIX_EPOCH)
1292            .unwrap()
1293            .as_secs();
1294        let svid = SvidResponse::X509 {
1295            spiffe_id: "spiffe://example.org/expiring".to_string(),
1296            cert_chain: vec![],
1297            private_key: vec![].into(),
1298            bundle: vec![],
1299            expires_at: now + 10,
1300        };
1301        client.store_x509_svid(svid).await;
1302        let needs = client.needs_rotation().await;
1303        assert_eq!(needs.len(), 1);
1304        assert_eq!(needs[0], "spiffe://example.org/expiring");
1305    }
1306
1307    #[test]
1308    fn test_workload_api_rotation_interval() {
1309        let cfg = WorkloadApiConfig {
1310            rotation_interval_secs: 600,
1311            ..WorkloadApiConfig::default()
1312        };
1313        let client = WorkloadApiClient::new(cfg);
1314        assert_eq!(client.rotation_interval(), Duration::from_secs(600));
1315    }
1316
1317    // ── Workload Selectors ──────────────────────────────────────
1318
1319    #[test]
1320    fn test_workload_selector_unix_uid() {
1321        let s = WorkloadSelector::unix_uid(1000);
1322        assert_eq!(s.selector_type, "unix");
1323        assert_eq!(s.value, "uid:1000");
1324    }
1325
1326    #[test]
1327    fn test_workload_selector_k8s_sa() {
1328        let s = WorkloadSelector::k8s_sa("default", "api-server");
1329        assert_eq!(s.selector_type, "k8s");
1330        assert_eq!(s.value, "sa:default:api-server");
1331    }
1332
1333    #[test]
1334    fn test_workload_selector_docker_image() {
1335        let s = WorkloadSelector::docker_image_id("sha256:abc123");
1336        assert_eq!(s.selector_type, "docker");
1337        assert_eq!(s.value, "image_id:sha256:abc123");
1338    }
1339
1340    // ── Registration Store & Attestation ────────────────────────
1341
1342    #[tokio::test]
1343    async fn test_registration_store_match_selectors() {
1344        let store = RegistrationStore::new();
1345        let entry = RegistrationEntry {
1346            spiffe_id: SpiffeId::parse("spiffe://example.org/web").unwrap(),
1347            parent_id: SpiffeId::parse("spiffe://example.org/node1").unwrap(),
1348            selectors: vec![WorkloadSelector::unix_uid(1000)],
1349            ttl: 3600,
1350            downstream: false,
1351        };
1352        store.register(entry).await;
1353
1354        // Workload has matching selector
1355        let ids = store
1356            .match_selectors(&[WorkloadSelector::unix_uid(1000)])
1357            .await;
1358        assert_eq!(ids.len(), 1);
1359        assert_eq!(ids[0].path, "/web");
1360
1361        // Workload has extra selectors → still matches (superset)
1362        let ids = store
1363            .match_selectors(&[
1364                WorkloadSelector::unix_uid(1000),
1365                WorkloadSelector::unix_gid(100),
1366            ])
1367            .await;
1368        assert_eq!(ids.len(), 1);
1369
1370        // Workload missing required selector → no match
1371        let ids = store
1372            .match_selectors(&[WorkloadSelector::unix_uid(2000)])
1373            .await;
1374        assert!(ids.is_empty());
1375    }
1376
1377    #[tokio::test]
1378    async fn test_registration_store_attest() {
1379        let store = RegistrationStore::new();
1380        let entry = RegistrationEntry {
1381            spiffe_id: SpiffeId::parse("spiffe://example.org/api").unwrap(),
1382            parent_id: SpiffeId::parse("spiffe://example.org/node1").unwrap(),
1383            selectors: vec![WorkloadSelector {
1384                selector_type: "unix".to_string(),
1385                value: "uid:1000".to_string(),
1386            }],
1387            ttl: 3600,
1388            downstream: false,
1389        };
1390        store.register(entry).await;
1391
1392        let evidence = AttestationEvidence {
1393            attestor: "unix".to_string(),
1394            payload: HashMap::from([("uid".to_string(), "1000".to_string())]),
1395        };
1396        let result = store.attest(&evidence).await.unwrap();
1397        assert_eq!(result.spiffe_ids.len(), 1);
1398        assert_eq!(result.spiffe_ids[0].path, "/api");
1399        assert_eq!(result.selectors.len(), 1);
1400    }
1401
1402    #[tokio::test]
1403    async fn test_registration_store_attest_no_match() {
1404        let store = RegistrationStore::new();
1405        let evidence = AttestationEvidence {
1406            attestor: "unix".to_string(),
1407            payload: HashMap::from([("uid".to_string(), "9999".to_string())]),
1408        };
1409        assert!(store.attest(&evidence).await.is_err());
1410    }
1411
1412    #[tokio::test]
1413    async fn test_registration_store_remove_by_spiffe_id() {
1414        let store = RegistrationStore::new();
1415        let id = SpiffeId::parse("spiffe://example.org/web").unwrap();
1416        store
1417            .register(RegistrationEntry {
1418                spiffe_id: id.clone(),
1419                parent_id: SpiffeId::parse("spiffe://example.org/node").unwrap(),
1420                selectors: vec![],
1421                ttl: 3600,
1422                downstream: false,
1423            })
1424            .await;
1425        assert_eq!(store.count().await, 1);
1426        store.remove_by_spiffe_id(&id).await;
1427        assert_eq!(store.count().await, 0);
1428    }
1429
1430    // ── Federated Trust Bundle Manager ──────────────────────────
1431
1432    #[tokio::test]
1433    async fn test_federated_bundle_manager_local_domain() {
1434        let mgr = FederatedTrustBundleManager::new("example.org");
1435        assert_eq!(mgr.local_domain(), "example.org");
1436    }
1437
1438    #[tokio::test]
1439    async fn test_federated_bundle_store_and_retrieve() {
1440        let mgr = FederatedTrustBundleManager::new("local.org");
1441        let bundle = FederatedBundle {
1442            trust_domain: "remote.org".to_string(),
1443            ca_certs: vec![vec![0xCA, 0xFE]],
1444            refreshed_at: 1000000,
1445            sequence_number: 1,
1446        };
1447        mgr.store_bundle(bundle).await;
1448        assert_eq!(mgr.bundle_count().await, 1);
1449
1450        let b = mgr.get_bundle("remote.org").await.unwrap();
1451        assert_eq!(b.sequence_number, 1);
1452        assert_eq!(b.ca_certs.len(), 1);
1453    }
1454
1455    #[tokio::test]
1456    async fn test_federated_bundle_is_trusted() {
1457        let mgr = FederatedTrustBundleManager::new("local.org");
1458        let local_id = SpiffeId::parse("spiffe://local.org/svc").unwrap();
1459        let remote_id = SpiffeId::parse("spiffe://remote.org/svc").unwrap();
1460
1461        // Local domain always trusted
1462        assert!(mgr.is_federated_id_trusted(&local_id).await);
1463        // Remote not trusted yet
1464        assert!(!mgr.is_federated_id_trusted(&remote_id).await);
1465
1466        // Add federation
1467        mgr.store_bundle(FederatedBundle {
1468            trust_domain: "remote.org".to_string(),
1469            ca_certs: vec![vec![0x01]],
1470            refreshed_at: 9999999999,
1471            sequence_number: 1,
1472        })
1473        .await;
1474        assert!(mgr.is_federated_id_trusted(&remote_id).await);
1475    }
1476
1477    #[tokio::test]
1478    async fn test_federated_bundle_remove() {
1479        let mgr = FederatedTrustBundleManager::new("local.org");
1480        mgr.store_bundle(FederatedBundle {
1481            trust_domain: "remote.org".to_string(),
1482            ca_certs: vec![],
1483            refreshed_at: 0,
1484            sequence_number: 0,
1485        })
1486        .await;
1487        assert!(mgr.remove_bundle("remote.org").await);
1488        assert!(!mgr.remove_bundle("remote.org").await);
1489        assert_eq!(mgr.bundle_count().await, 0);
1490    }
1491
1492    #[tokio::test]
1493    async fn test_federated_bundle_cleanup_stale() {
1494        let mgr = FederatedTrustBundleManager::new("local.org");
1495        // Store a bundle that was refreshed at epoch 0 (very stale)
1496        mgr.store_bundle(FederatedBundle {
1497            trust_domain: "stale.org".to_string(),
1498            ca_certs: vec![],
1499            refreshed_at: 0,
1500            sequence_number: 1,
1501        })
1502        .await;
1503        // Store a fresh bundle
1504        let now = SystemTime::now()
1505            .duration_since(UNIX_EPOCH)
1506            .unwrap()
1507            .as_secs();
1508        mgr.store_bundle(FederatedBundle {
1509            trust_domain: "fresh.org".to_string(),
1510            ca_certs: vec![],
1511            refreshed_at: now,
1512            sequence_number: 1,
1513        })
1514        .await;
1515        assert_eq!(mgr.bundle_count().await, 2);
1516
1517        mgr.cleanup_stale(Duration::from_secs(3600)).await;
1518        assert_eq!(mgr.bundle_count().await, 1);
1519        assert!(mgr.get_bundle("fresh.org").await.is_some());
1520        assert!(mgr.get_bundle("stale.org").await.is_none());
1521    }
1522
1523    #[tokio::test]
1524    async fn test_federated_bundle_endpoints() {
1525        let mgr = FederatedTrustBundleManager::new("local.org");
1526        mgr.add_federation_endpoint("remote.org", "https://remote.org/.well-known/spiffe-bundle")
1527            .await;
1528        let ep = mgr.get_endpoint("remote.org").await.unwrap();
1529        assert!(ep.contains("spiffe-bundle"));
1530        assert!(mgr.get_endpoint("unknown.org").await.is_none());
1531    }
1532
1533    #[tokio::test]
1534    async fn test_federated_bundle_list_domains() {
1535        let mgr = FederatedTrustBundleManager::new("local.org");
1536        mgr.store_bundle(FederatedBundle {
1537            trust_domain: "a.org".to_string(),
1538            ca_certs: vec![],
1539            refreshed_at: 0,
1540            sequence_number: 0,
1541        })
1542        .await;
1543        mgr.store_bundle(FederatedBundle {
1544            trust_domain: "b.org".to_string(),
1545            ca_certs: vec![],
1546            refreshed_at: 0,
1547            sequence_number: 0,
1548        })
1549        .await;
1550        let mut domains = mgr.federated_domains().await;
1551        domains.sort();
1552        assert_eq!(domains, vec!["a.org", "b.org"]);
1553    }
1554}