1use 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#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
35pub struct SpiffeId {
36 pub trust_domain: String,
38 pub path: String,
40}
41
42impl SpiffeId {
43 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 let (trust_domain, path) = match stripped.find('/') {
61 Some(idx) => (&stripped[..idx], &stripped[idx..]),
62 None => (stripped, ""),
63 };
64
65 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 if path.contains('?') || path.contains('#') {
80 return Err(AuthError::validation(
81 "SPIFFE ID must not contain query or fragment",
82 ));
83 }
84
85 if path.len() > 1 && path.ends_with('/') {
87 return Err(AuthError::validation(
88 "SPIFFE ID path must not end with '/'",
89 ));
90 }
91
92 if path.contains("//") {
94 return Err(AuthError::validation(
95 "SPIFFE ID path must not contain empty segments",
96 ));
97 }
98
99 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 pub fn to_uri(&self) -> String {
116 format!("spiffe://{}{}", self.trust_domain, self.path)
117 }
118
119 pub fn is_member_of(&self, trust_domain: &str) -> bool {
121 self.trust_domain == trust_domain
122 }
123
124 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#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct JwtSvidClaims {
141 pub sub: String,
143 pub aud: Vec<String>,
145 pub exp: u64,
147 #[serde(default)]
149 pub iat: Option<u64>,
150}
151
152#[derive(Debug, Clone)]
154pub struct ValidatedJwtSvid {
155 pub spiffe_id: SpiffeId,
157 pub claims: JwtSvidClaims,
159 pub header: serde_json::Value,
161}
162
163pub 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 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 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 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 let spiffe_id = SpiffeId::parse(&claims.sub)?;
209
210 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
237pub struct X509SvidInfo {
238 pub spiffe_id: SpiffeId,
240 pub fingerprint: String,
242 #[serde(default)]
244 pub serial: Option<String>,
245 #[serde(default)]
247 pub not_before: Option<u64>,
248 #[serde(default)]
250 pub not_after: Option<u64>,
251}
252
253pub fn extract_spiffe_id_from_der(cert_der: &[u8]) -> Result<X509SvidInfo> {
258 let fingerprint = hex::encode(Sha256::digest(cert_der));
260
261 let cert_str = String::from_utf8_lossy(cert_der);
263 let spiffe_uri = find_spiffe_uri_in_bytes(cert_der)
264 .or_else(|| {
265 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
288fn 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
315pub struct SpiffeAuthzPolicy {
316 pub source: String,
318 pub destination: String,
320 pub allowed_actions: Vec<String>,
322}
323
324pub struct SpiffeTrustManager {
326 trust_bundles: Arc<RwLock<HashMap<String, Vec<Vec<u8>>>>>,
328 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 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 pub async fn has_trust_bundle(&self, trust_domain: &str) -> bool {
350 self.trust_bundles.read().await.contains_key(trust_domain)
351 }
352
353 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 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 pub async fn add_policy(&self, policy: SpiffeAuthzPolicy) {
369 self.policies.write().await.push(policy);
370 }
371
372 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 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 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 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#[derive(Clone)]
442pub enum SvidResponse {
443 X509 {
445 spiffe_id: String,
446 cert_chain: Vec<Vec<u8>>,
447 private_key: Zeroizing<Vec<u8>>,
448 bundle: Vec<Vec<u8>>,
450 expires_at: u64,
452 },
453 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#[derive(Debug, Clone, Serialize, Deserialize)]
494pub struct WorkloadApiConfig {
495 pub endpoint: String,
498 pub rotation_interval_secs: u64,
500 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
514pub struct WorkloadApiClient {
520 config: WorkloadApiConfig,
521 x509_svids: Arc<RwLock<HashMap<String, SvidResponse>>>,
523 jwt_svids: Arc<RwLock<HashMap<String, SvidResponse>>>,
525 bundles: Arc<RwLock<HashMap<String, Vec<Vec<u8>>>>>,
527}
528
529impl WorkloadApiClient {
530 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 pub fn endpoint(&self) -> &str {
542 &self.config.endpoint
543 }
544
545 pub fn rotation_interval(&self) -> Duration {
547 Duration::from_secs(self.config.rotation_interval_secs)
548 }
549
550 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 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 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 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 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 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 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 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 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 pub async fn x509_count(&self) -> usize {
642 self.x509_svids.read().await.len()
643 }
644
645 pub async fn jwt_count(&self) -> usize {
647 self.jwt_svids.read().await.len()
648 }
649}
650
651#[derive(Clone, Serialize, Deserialize)]
655pub struct AttestationEvidence {
656 pub attestor: String,
658 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#[derive(Debug, Clone, Serialize, Deserialize)]
673pub struct AttestationResult {
674 pub spiffe_ids: Vec<SpiffeId>,
676 pub selectors: Vec<WorkloadSelector>,
678}
679
680#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
682pub struct WorkloadSelector {
683 pub selector_type: String,
685 pub value: String,
687}
688
689impl WorkloadSelector {
690 pub fn unix_uid(uid: u32) -> Self {
692 Self {
693 selector_type: "unix".to_string(),
694 value: format!("uid:{uid}"),
695 }
696 }
697
698 pub fn unix_gid(gid: u32) -> Self {
700 Self {
701 selector_type: "unix".to_string(),
702 value: format!("gid:{gid}"),
703 }
704 }
705
706 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 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
733pub struct RegistrationEntry {
734 pub spiffe_id: SpiffeId,
736 pub parent_id: SpiffeId,
738 pub selectors: Vec<WorkloadSelector>,
740 pub ttl: u64,
742 pub downstream: bool,
744}
745
746pub struct RegistrationStore {
748 entries: Arc<RwLock<Vec<RegistrationEntry>>>,
749}
750
751impl RegistrationStore {
752 pub fn new() -> Self {
754 Self {
755 entries: Arc::new(RwLock::new(Vec::new())),
756 }
757 }
758
759 pub async fn register(&self, entry: RegistrationEntry) {
761 self.entries.write().await.push(entry);
762 }
763
764 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 pub async fn attest(&self, evidence: &AttestationEvidence) -> Result<AttestationResult> {
784 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 pub async fn count(&self) -> usize {
815 self.entries.read().await.len()
816 }
817
818 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#[derive(Debug, Clone, Serialize, Deserialize)]
834pub struct FederatedBundle {
835 pub trust_domain: String,
837 pub ca_certs: Vec<Vec<u8>>,
839 pub refreshed_at: u64,
841 pub sequence_number: u64,
843}
844
845pub struct FederatedTrustBundleManager {
849 local_domain: String,
851 bundles: Arc<RwLock<HashMap<String, FederatedBundle>>>,
853 endpoints: Arc<RwLock<HashMap<String, String>>>,
855}
856
857impl FederatedTrustBundleManager {
858 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 pub fn local_domain(&self) -> &str {
869 &self.local_domain
870 }
871
872 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 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 pub async fn get_bundle(&self, trust_domain: &str) -> Option<FederatedBundle> {
890 self.bundles.read().await.get(trust_domain).cloned()
891 }
892
893 pub async fn get_endpoint(&self, trust_domain: &str) -> Option<String> {
895 self.endpoints.read().await.get(trust_domain).cloned()
896 }
897
898 pub async fn federated_domains(&self) -> Vec<String> {
900 self.bundles.read().await.keys().cloned().collect()
901 }
902
903 pub async fn is_federated_id_trusted(&self, id: &SpiffeId) -> bool {
905 if id.trust_domain == self.local_domain {
906 return true; }
908 self.bundles.read().await.contains_key(&id.trust_domain)
909 }
910
911 pub async fn remove_bundle(&self, trust_domain: &str) -> bool {
913 self.bundles.write().await.remove(trust_domain).is_some()
914 }
915
916 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 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 #[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 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 #[test]
1112 fn test_extract_spiffe_id_from_synthetic_der() {
1113 let mut data = vec![0x30, 0x82]; data.extend_from_slice(&[0x00, 0x50]); data.extend_from_slice(b"some-cert-fields-");
1117 data.extend_from_slice(b"spiffe://example.org/workload/web");
1118 data.push(0x00); data.extend_from_slice(&[0xFF; 20]); 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); }
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 #[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 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 #[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 #[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 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 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, };
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 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 #[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 #[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 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 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 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 #[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 assert!(mgr.is_federated_id_trusted(&local_id).await);
1472 assert!(!mgr.is_federated_id_trusted(&remote_id).await);
1474
1475 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 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 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}