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(Debug, Clone, Serialize, Deserialize)]
655pub struct AttestationEvidence {
656 pub attestor: String,
658 pub payload: HashMap<String, String>,
660}
661
662#[derive(Debug, Clone, Serialize, Deserialize)]
664pub struct AttestationResult {
665 pub spiffe_ids: Vec<SpiffeId>,
667 pub selectors: Vec<WorkloadSelector>,
669}
670
671#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
673pub struct WorkloadSelector {
674 pub selector_type: String,
676 pub value: String,
678}
679
680impl WorkloadSelector {
681 pub fn unix_uid(uid: u32) -> Self {
683 Self {
684 selector_type: "unix".to_string(),
685 value: format!("uid:{uid}"),
686 }
687 }
688
689 pub fn unix_gid(gid: u32) -> Self {
691 Self {
692 selector_type: "unix".to_string(),
693 value: format!("gid:{gid}"),
694 }
695 }
696
697 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 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
724pub struct RegistrationEntry {
725 pub spiffe_id: SpiffeId,
727 pub parent_id: SpiffeId,
729 pub selectors: Vec<WorkloadSelector>,
731 pub ttl: u64,
733 pub downstream: bool,
735}
736
737pub struct RegistrationStore {
739 entries: Arc<RwLock<Vec<RegistrationEntry>>>,
740}
741
742impl RegistrationStore {
743 pub fn new() -> Self {
745 Self {
746 entries: Arc::new(RwLock::new(Vec::new())),
747 }
748 }
749
750 pub async fn register(&self, entry: RegistrationEntry) {
752 self.entries.write().await.push(entry);
753 }
754
755 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 pub async fn attest(&self, evidence: &AttestationEvidence) -> Result<AttestationResult> {
775 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 pub async fn count(&self) -> usize {
806 self.entries.read().await.len()
807 }
808
809 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#[derive(Debug, Clone, Serialize, Deserialize)]
825pub struct FederatedBundle {
826 pub trust_domain: String,
828 pub ca_certs: Vec<Vec<u8>>,
830 pub refreshed_at: u64,
832 pub sequence_number: u64,
834}
835
836pub struct FederatedTrustBundleManager {
840 local_domain: String,
842 bundles: Arc<RwLock<HashMap<String, FederatedBundle>>>,
844 endpoints: Arc<RwLock<HashMap<String, String>>>,
846}
847
848impl FederatedTrustBundleManager {
849 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 pub fn local_domain(&self) -> &str {
860 &self.local_domain
861 }
862
863 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 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 pub async fn get_bundle(&self, trust_domain: &str) -> Option<FederatedBundle> {
881 self.bundles.read().await.get(trust_domain).cloned()
882 }
883
884 pub async fn get_endpoint(&self, trust_domain: &str) -> Option<String> {
886 self.endpoints.read().await.get(trust_domain).cloned()
887 }
888
889 pub async fn federated_domains(&self) -> Vec<String> {
891 self.bundles.read().await.keys().cloned().collect()
892 }
893
894 pub async fn is_federated_id_trusted(&self, id: &SpiffeId) -> bool {
896 if id.trust_domain == self.local_domain {
897 return true; }
899 self.bundles.read().await.contains_key(&id.trust_domain)
900 }
901
902 pub async fn remove_bundle(&self, trust_domain: &str) -> bool {
904 self.bundles.write().await.remove(trust_domain).is_some()
905 }
906
907 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 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 #[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 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 #[test]
1103 fn test_extract_spiffe_id_from_synthetic_der() {
1104 let mut data = vec![0x30, 0x82]; data.extend_from_slice(&[0x00, 0x50]); data.extend_from_slice(b"some-cert-fields-");
1108 data.extend_from_slice(b"spiffe://example.org/workload/web");
1109 data.push(0x00); data.extend_from_slice(&[0xFF; 20]); 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); }
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 #[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 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 #[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 #[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 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 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, };
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 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 #[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 #[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 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 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 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 #[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 assert!(mgr.is_federated_id_trusted(&local_id).await);
1463 assert!(!mgr.is_federated_id_trusted(&remote_id).await);
1465
1466 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 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 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}