Skip to main content

auth_framework/protocols/
ws_trust.rs

1//! WS-Trust 1.3 Security Token Service (STS) Support
2//!
3//! This module provides WS-Trust 1.3 Security Token Service functionality for token exchange,
4//! issuance, and validation scenarios.
5
6use crate::errors::{AuthError, Result};
7use crate::protocols::saml_assertions::SamlAssertionBuilder;
8// SamlAssertion removed from import - not currently used but may be needed later
9use crate::protocols::ws_security::{PasswordType, WsSecurityClient, WsSecurityConfig};
10use base64::Engine as _;
11use chrono::{DateTime, Duration, Utc};
12use jsonwebtoken::{Algorithm, EncodingKey, Header, encode as jwt_encode};
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15
16/// WS-Trust Security Token Service
17///
18/// **Note:** Issued tokens are stored in an in-memory `HashMap`. They will be
19/// lost on restart and are not shared across STS instances. For production
20/// multi-instance deployments, integrate with the `StorageBackend` KV store
21/// for persistent/shared token state.
22pub struct SecurityTokenService {
23    /// STS configuration
24    config: StsConfig,
25
26    /// WS-Security client for generating secure headers
27    ws_security: WsSecurityClient,
28
29    /// Issued tokens cache
30    issued_tokens: HashMap<String, IssuedToken>,
31}
32
33/// STS Configuration
34#[derive(Clone)]
35pub struct StsConfig {
36    /// STS issuer identifier
37    pub issuer: String,
38
39    /// Default token lifetime
40    pub default_token_lifetime: Duration,
41
42    /// Maximum token lifetime
43    pub max_token_lifetime: Duration,
44
45    /// Supported token types
46    pub supported_token_types: Vec<String>,
47
48    /// STS endpoint URL
49    pub endpoint_url: String,
50
51    /// Whether to include proof tokens
52    pub include_proof_tokens: bool,
53
54    /// Trust relationships
55    pub trust_relationships: Vec<TrustRelationship>,
56
57    /// HMAC-HS256 signing secret used when issuing JWT tokens.
58    ///
59    /// **Must be set to a strong, randomly-generated value in production.**
60    /// `StsConfig::default()` generates a cryptographically random secret
61    /// automatically; override this field when you need a stable / shared
62    /// signing key (e.g. for multi-node deployments that share the same
63    /// validator).
64    pub jwt_signing_secret: String,
65}
66
67impl std::fmt::Debug for StsConfig {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        let mut d = f.debug_struct("StsConfig");
70        d.field("issuer", &self.issuer);
71        d.field("default_token_lifetime", &self.default_token_lifetime);
72        d.field("max_token_lifetime", &self.max_token_lifetime);
73        d.field("supported_token_types", &self.supported_token_types);
74        d.field("endpoint_url", &self.endpoint_url);
75        d.field("include_proof_tokens", &self.include_proof_tokens);
76        d.field("trust_relationships", &self.trust_relationships);
77        d.field(
78            "jwt_signing_secret",
79            &crate::utils::redact::redacted(&self.jwt_signing_secret),
80        );
81        d.finish()
82    }
83}
84
85/// Trust relationship with relying parties
86#[derive(Debug, Clone)]
87pub struct TrustRelationship {
88    /// Relying party identifier
89    pub rp_identifier: String,
90
91    /// Certificate for encryption/signing
92    pub certificate: Option<Vec<u8>>,
93
94    /// Allowed token types
95    pub allowed_token_types: Vec<String>,
96
97    /// Maximum token lifetime for this RP
98    pub max_token_lifetime: Option<Duration>,
99}
100
101/// Issued token information
102#[derive(Clone, Serialize, Deserialize)]
103pub struct IssuedToken {
104    /// Token ID
105    pub token_id: String,
106
107    /// Token type
108    pub token_type: String,
109
110    /// Token content (SAML assertion, JWT, etc.)
111    pub token_content: String,
112
113    /// Issue time
114    pub issued_at: DateTime<Utc>,
115
116    /// Expiration time
117    pub expires_at: DateTime<Utc>,
118
119    /// Subject identifier
120    pub subject: String,
121
122    /// Audience/relying party
123    pub audience: String,
124
125    /// Proof token (if any)
126    pub proof_token: Option<ProofToken>,
127}
128
129impl std::fmt::Debug for IssuedToken {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        let mut d = f.debug_struct("IssuedToken");
132        d.field("token_id", &crate::utils::redact::redacted(&self.token_id));
133        d.field("token_type", &self.token_type);
134        d.field(
135            "token_content",
136            &crate::utils::redact::redacted(&self.token_content),
137        );
138        d.field("issued_at", &self.issued_at);
139        d.field("expires_at", &self.expires_at);
140        d.field("subject", &self.subject);
141        d.field("audience", &self.audience);
142        d.field("proof_token", &self.proof_token);
143        d.finish()
144    }
145}
146
147/// Proof token for holder-of-key scenarios
148#[derive(Clone, Serialize, Deserialize)]
149pub struct ProofToken {
150    /// Proof token type (symmetric key, certificate, etc.)
151    pub token_type: String,
152
153    /// Key material
154    pub key_material: Vec<u8>,
155
156    /// Key identifier
157    pub key_identifier: String,
158}
159
160impl std::fmt::Debug for ProofToken {
161    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162        let mut d = f.debug_struct("ProofToken");
163        d.field("token_type", &self.token_type);
164        d.field(
165            "key_material",
166            &crate::utils::redact::redacted(&self.key_material),
167        );
168        d.field("key_identifier", &self.key_identifier);
169        d.finish()
170    }
171}
172
173/// WS-Trust Request Security Token (RST)
174#[derive(Clone, Serialize, Deserialize)]
175pub struct RequestSecurityToken {
176    /// Request type (Issue, Renew, Cancel, Validate)
177    pub request_type: String,
178
179    /// Token type being requested
180    pub token_type: String,
181
182    /// Applies to (target service/audience)
183    pub applies_to: Option<String>,
184
185    /// Lifetime requirements
186    pub lifetime: Option<TokenLifetime>,
187
188    /// Key type (Bearer, Symmetric, Asymmetric)
189    pub key_type: Option<String>,
190
191    /// Key size for symmetric keys
192    pub key_size: Option<u32>,
193
194    /// Existing token (for renew/validate operations)
195    pub existing_token: Option<String>,
196
197    /// Authentication context
198    pub auth_context: Option<AuthenticationContext>,
199}
200
201impl std::fmt::Debug for RequestSecurityToken {
202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203        let mut d = f.debug_struct("RequestSecurityToken");
204        d.field("request_type", &self.request_type);
205        d.field("token_type", &self.token_type);
206        d.field("applies_to", &self.applies_to);
207        d.field("lifetime", &self.lifetime);
208        d.field("key_type", &self.key_type);
209        d.field("key_size", &self.key_size);
210        d.field(
211            "existing_token",
212            &crate::utils::redact::redacted(&self.existing_token),
213        );
214        d.field("auth_context", &self.auth_context);
215        d.finish()
216    }
217}
218
219/// Token lifetime specification
220#[derive(Debug, Clone, Serialize, Deserialize)]
221pub struct TokenLifetime {
222    /// Created time
223    pub created: DateTime<Utc>,
224
225    /// Expires time
226    pub expires: DateTime<Utc>,
227}
228
229/// Authentication context for token requests
230#[derive(Debug, Clone, Serialize, Deserialize)]
231pub struct AuthenticationContext {
232    /// Username
233    pub username: String,
234
235    /// Authentication method
236    pub auth_method: String,
237
238    /// Additional claims
239    pub claims: HashMap<String, String>,
240}
241
242/// WS-Trust Request Security Token Response (RSTR)
243#[derive(Clone, Serialize, Deserialize)]
244pub struct RequestSecurityTokenResponse {
245    /// Request type being responded to
246    pub request_type: String,
247
248    /// Token type issued
249    pub token_type: String,
250
251    /// Lifetime of issued token
252    pub lifetime: TokenLifetime,
253
254    /// Applies to (target audience)
255    pub applies_to: Option<String>,
256
257    /// Requested security token
258    pub requested_security_token: String,
259
260    /// Requested proof token
261    pub requested_proof_token: Option<ProofToken>,
262
263    /// Token reference for future operations
264    pub requested_attached_reference: Option<String>,
265
266    /// Token reference for external use
267    pub requested_unattached_reference: Option<String>,
268}
269
270impl std::fmt::Debug for RequestSecurityTokenResponse {
271    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
272        let mut d = f.debug_struct("RequestSecurityTokenResponse");
273        d.field("request_type", &self.request_type);
274        d.field("token_type", &self.token_type);
275        d.field("lifetime", &self.lifetime);
276        d.field("applies_to", &self.applies_to);
277        d.field(
278            "requested_security_token",
279            &crate::utils::redact::redacted(&self.requested_security_token),
280        );
281        d.field("requested_proof_token", &self.requested_proof_token);
282        d.field(
283            "requested_attached_reference",
284            &self.requested_attached_reference,
285        );
286        d.field(
287            "requested_unattached_reference",
288            &self.requested_unattached_reference,
289        );
290        d.finish()
291    }
292}
293
294impl SecurityTokenService {
295    /// Create a new Security Token Service
296    pub fn new(config: StsConfig) -> Self {
297        let ws_security_config = WsSecurityConfig::default();
298        let ws_security = WsSecurityClient::new(ws_security_config);
299
300        Self {
301            config,
302            ws_security,
303            issued_tokens: HashMap::new(),
304        }
305    }
306
307    /// Process a WS-Trust Request Security Token
308    pub fn process_request(
309        &mut self,
310        request: RequestSecurityToken,
311    ) -> Result<RequestSecurityTokenResponse> {
312        match request.request_type.as_str() {
313            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue" => self.issue_token(request),
314            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Renew" => self.renew_token(request),
315            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Cancel" => self.cancel_token(request),
316            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Validate" => {
317                self.validate_token(request)
318            }
319            _ => Err(AuthError::auth_method(
320                "wstrust",
321                "Unsupported request type",
322            )),
323        }
324    }
325
326    /// Issue a new security token
327    fn issue_token(
328        &mut self,
329        request: RequestSecurityToken,
330    ) -> Result<RequestSecurityTokenResponse> {
331        // Validate authentication context
332        let auth_context = request
333            .auth_context
334            .as_ref()
335            .ok_or_else(|| AuthError::auth_method("wstrust", "Authentication context required"))?;
336
337        // Determine token lifetime
338        let now = Utc::now();
339        let lifetime = if let Some(ref requested_lifetime) = request.lifetime {
340            // Validate requested lifetime
341            let max_expires = now + self.config.max_token_lifetime;
342            let expires = if requested_lifetime.expires > max_expires {
343                max_expires
344            } else {
345                requested_lifetime.expires
346            };
347
348            TokenLifetime {
349                created: now,
350                expires,
351            }
352        } else {
353            TokenLifetime {
354                created: now,
355                expires: now + self.config.default_token_lifetime,
356            }
357        };
358
359        // Generate token based on type
360        let token_content = match request.token_type.as_str() {
361            "urn:oasis:names:tc:SAML:2.0:assertion" => {
362                self.issue_saml_token(auth_context, &request, &lifetime)?
363            }
364            "urn:ietf:params:oauth:token-type:jwt" => {
365                self.issue_jwt_token(auth_context, &request, &lifetime)?
366            }
367            _ => {
368                return Err(AuthError::auth_method("wstrust", "Unsupported token type"));
369            }
370        };
371
372        // Generate proof token if required
373        let proof_token = if self.config.include_proof_tokens
374            && request.key_type.as_deref()
375                == Some("http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey")
376        {
377            Some(self.generate_proof_token()?)
378        } else {
379            None
380        };
381
382        // Store issued token
383        let token_id = format!("token-{}", uuid::Uuid::new_v4());
384        let issued_token = IssuedToken {
385            token_id: token_id.clone(),
386            token_type: request.token_type.clone(),
387            token_content: token_content.clone(),
388            issued_at: lifetime.created,
389            expires_at: lifetime.expires,
390            subject: auth_context.username.clone(),
391            audience: request.applies_to.clone().unwrap_or_default(),
392            proof_token: proof_token.clone(),
393        };
394
395        self.issued_tokens.insert(token_id.clone(), issued_token);
396
397        Ok(RequestSecurityTokenResponse {
398            request_type: request.request_type,
399            token_type: request.token_type,
400            lifetime,
401            applies_to: request.applies_to,
402            requested_security_token: token_content,
403            requested_proof_token: proof_token,
404            requested_attached_reference: Some(format!("#{}", token_id)),
405            requested_unattached_reference: Some(token_id),
406        })
407    }
408
409    /// Issue a SAML 2.0 assertion token
410    fn issue_saml_token(
411        &self,
412        auth_context: &AuthenticationContext,
413        request: &RequestSecurityToken,
414        lifetime: &TokenLifetime,
415    ) -> Result<String> {
416        let mut assertion_builder = SamlAssertionBuilder::new(&self.config.issuer)
417            .with_validity_period(lifetime.created, lifetime.expires)
418            .with_attribute("username", &auth_context.username)
419            .with_attribute("auth_method", &auth_context.auth_method);
420
421        // Add audience if specified
422        if let Some(ref audience) = request.applies_to {
423            assertion_builder = assertion_builder.with_audience(audience);
424        }
425
426        // Add additional claims as attributes
427        for (key, value) in &auth_context.claims {
428            assertion_builder = assertion_builder.with_attribute(key, value);
429        }
430
431        let assertion = assertion_builder.build();
432        assertion.to_xml()
433    }
434
435    /// Issue a JWT token signed with HMAC-HS256 using `StsConfig::jwt_signing_secret`.
436    fn issue_jwt_token(
437        &self,
438        auth_context: &AuthenticationContext,
439        request: &RequestSecurityToken,
440        lifetime: &TokenLifetime,
441    ) -> Result<String> {
442        #[derive(Serialize)]
443        struct WsTrustClaims<'a> {
444            iss: &'a str,
445            sub: &'a str,
446            aud: &'a str,
447            iat: i64,
448            exp: i64,
449            auth_method: &'a str,
450            #[serde(skip_serializing_if = "std::collections::HashMap::is_empty")]
451            claims: &'a HashMap<String, String>,
452        }
453
454        let jwt_claims = WsTrustClaims {
455            iss: &self.config.issuer,
456            sub: &auth_context.username,
457            aud: request.applies_to.as_deref().unwrap_or(""),
458            iat: lifetime.created.timestamp(),
459            exp: lifetime.expires.timestamp(),
460            auth_method: &auth_context.auth_method,
461            claims: &auth_context.claims,
462        };
463
464        let encoding_key = EncodingKey::from_secret(self.config.jwt_signing_secret.as_bytes());
465
466        jwt_encode(&Header::new(Algorithm::HS256), &jwt_claims, &encoding_key)
467            .map_err(|e| AuthError::internal(format!("WS-Trust JWT signing failed: {e}")))
468    }
469
470    /// Generate a proof token for holder-of-key scenarios
471    fn generate_proof_token(&self) -> Result<ProofToken> {
472        use rand::Rng;
473        let mut rng = rand::rng();
474        let mut key_material = vec![0u8; 32]; // 256-bit symmetric key
475        rng.fill_bytes(&mut key_material);
476
477        Ok(ProofToken {
478            token_type: "SymmetricKey".to_string(),
479            key_material,
480            key_identifier: format!("key-{}", uuid::Uuid::new_v4()),
481        })
482    }
483
484    /// Renew an existing token
485    fn renew_token(
486        &mut self,
487        request: RequestSecurityToken,
488    ) -> Result<RequestSecurityTokenResponse> {
489        let existing_token = request.existing_token.ok_or_else(|| {
490            AuthError::auth_method("wstrust", "Existing token required for renewal")
491        })?;
492
493        // Find the token — try direct lookup first, then attempt JWT parsing
494        // to extract claims from the existing token if it looks like a JWT.
495        let mut renewal_claims = HashMap::new();
496        let token_id = if existing_token.matches('.').count() == 2 {
497            // Token looks like a JWT — extract claims from payload
498            if let Some(payload_b64) = existing_token.split('.').nth(1) {
499                if let Ok(payload_bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD
500                    .decode(payload_b64)
501                    .or_else(|_| base64::engine::general_purpose::STANDARD.decode(payload_b64))
502                {
503                    if let Ok(claims) =
504                        serde_json::from_slice::<HashMap<String, serde_json::Value>>(&payload_bytes)
505                    {
506                        for (k, v) in &claims {
507                            if let Some(s) = v.as_str() {
508                                renewal_claims.insert(k.clone(), s.to_string());
509                            }
510                        }
511                        // Use "jti" or "sub" as token ID for lookup
512                        claims
513                            .get("jti")
514                            .or_else(|| claims.get("sub"))
515                            .and_then(|v| v.as_str())
516                            .unwrap_or(&existing_token)
517                            .to_string()
518                    } else {
519                        existing_token.clone()
520                    }
521                } else {
522                    existing_token.clone()
523                }
524            } else {
525                existing_token.clone()
526            }
527        } else {
528            existing_token.clone()
529        };
530
531        let issued_token = self
532            .issued_tokens
533            .get(&token_id)
534            .ok_or_else(|| AuthError::auth_method("wstrust", "Token not found"))?;
535
536        // Check if token is still valid
537        let now = Utc::now();
538        if now >= issued_token.expires_at {
539            return Err(AuthError::auth_method("wstrust", "Token has expired"));
540        }
541
542        // Create renewed token with new lifetime
543        let new_lifetime = TokenLifetime {
544            created: now,
545            expires: now + self.config.default_token_lifetime,
546        };
547
548        // Issue new token (carry forward original claims where available)
549        let auth_context = AuthenticationContext {
550            username: issued_token.subject.clone(),
551            auth_method: "token_renewal".to_string(),
552            claims: if renewal_claims.is_empty() {
553                HashMap::new()
554            } else {
555                renewal_claims
556            },
557        };
558
559        let new_request = RequestSecurityToken {
560            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
561            token_type: issued_token.token_type.clone(),
562            applies_to: Some(issued_token.audience.clone()),
563            lifetime: Some(new_lifetime.clone()),
564            key_type: None,
565            key_size: None,
566            existing_token: None,
567            auth_context: Some(auth_context),
568        };
569
570        self.issue_token(new_request)
571    }
572
573    /// Cancel an existing token
574    fn cancel_token(
575        &mut self,
576        request: RequestSecurityToken,
577    ) -> Result<RequestSecurityTokenResponse> {
578        let existing_token = request
579            .existing_token
580            .ok_or_else(|| AuthError::auth_method("wstrust", "Token required for cancellation"))?;
581
582        // Remove token from cache
583        self.issued_tokens.remove(&existing_token);
584
585        Ok(RequestSecurityTokenResponse {
586            request_type: request.request_type,
587            token_type: "Cancelled".to_string(),
588            lifetime: TokenLifetime {
589                created: Utc::now(),
590                expires: Utc::now(),
591            },
592            applies_to: None,
593            requested_security_token: "Token cancelled".to_string(),
594            requested_proof_token: None,
595            requested_attached_reference: None,
596            requested_unattached_reference: None,
597        })
598    }
599
600    /// Validate an existing token
601    fn validate_token(
602        &self,
603        request: RequestSecurityToken,
604    ) -> Result<RequestSecurityTokenResponse> {
605        let existing_token = request
606            .existing_token
607            .ok_or_else(|| AuthError::auth_method("wstrust", "Token required for validation"))?;
608
609        // Find and validate token
610        let token_id = existing_token;
611        let issued_token = self
612            .issued_tokens
613            .get(&token_id)
614            .ok_or_else(|| AuthError::auth_method("wstrust", "Token not found"))?;
615
616        let now = Utc::now();
617        let is_valid = now < issued_token.expires_at;
618
619        let status = if is_valid { "Valid" } else { "Invalid" };
620
621        Ok(RequestSecurityTokenResponse {
622            request_type: request.request_type,
623            token_type: "ValidationResponse".to_string(),
624            lifetime: TokenLifetime {
625                created: issued_token.issued_at,
626                expires: issued_token.expires_at,
627            },
628            applies_to: Some(issued_token.audience.clone()),
629            requested_security_token: status.to_string(),
630            requested_proof_token: None,
631            requested_attached_reference: None,
632            requested_unattached_reference: None,
633        })
634    }
635
636    /// Create a complete WS-Trust SOAP request
637    pub fn create_rst_soap_request(
638        &self,
639        request: &RequestSecurityToken,
640        username: &str,
641        password: Option<&str>,
642    ) -> Result<String> {
643        let header = self.ws_security.create_username_token_header(
644            username,
645            password,
646            PasswordType::PasswordText,
647        )?;
648
649        let security_header = self.ws_security.header_to_xml(&header)?;
650
651        let soap_request = format!(
652            r#"<?xml version="1.0" encoding="UTF-8"?>
653<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
654               xmlns:wst="http://docs.oasis-open.org/ws-sx/ws-trust/200512"
655               xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
656    <soap:Header>
657        {}
658    </soap:Header>
659    <soap:Body>
660        <wst:RequestSecurityToken>
661            <wst:RequestType>{}</wst:RequestType>
662            <wst:TokenType>{}</wst:TokenType>
663            {}
664            {}
665            {}
666        </wst:RequestSecurityToken>
667    </soap:Body>
668</soap:Envelope>"#,
669            security_header,
670            request.request_type,
671            request.token_type,
672            request.applies_to.as_ref().map(|a| format!("<wsp:AppliesTo><wsp:EndpointReference><wsp:Address>{}</wsp:Address></wsp:EndpointReference></wsp:AppliesTo>", a)).unwrap_or_default(),
673            request.lifetime.as_ref().map(|l| format!("<wst:Lifetime><wsu:Created>{}</wsu:Created><wsu:Expires>{}</wsu:Expires></wst:Lifetime>",
674                l.created.format("%Y-%m-%dT%H:%M:%S%.3fZ"),
675                l.expires.format("%Y-%m-%dT%H:%M:%S%.3fZ"))).unwrap_or_default(),
676            request.key_type.as_ref().map(|k| format!("<wst:KeyType>{}</wst:KeyType>", k)).unwrap_or_default()
677        );
678
679        Ok(soap_request)
680    }
681}
682
683impl Default for StsConfig {
684    fn default() -> Self {
685        use ring::rand::{SecureRandom, SystemRandom};
686        // SAFETY: CSPRNG failure at initialization is terminal; the framework
687        // cannot operate without entropy.
688        let rng = SystemRandom::new();
689        let mut bytes = [0u8; 32];
690        rng.fill(&mut bytes)
691            .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
692        let jwt_signing_secret = bytes.iter().fold(String::with_capacity(64), |mut s, b| {
693            s.push_str(&format!("{b:02x}"));
694            s
695        });
696
697        Self {
698            issuer: "https://sts.example.com".to_string(),
699            default_token_lifetime: Duration::hours(1),
700            max_token_lifetime: Duration::hours(8),
701            supported_token_types: vec![
702                "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
703                "urn:ietf:params:oauth:token-type:jwt".to_string(),
704            ],
705            endpoint_url: "https://sts.example.com/trust".to_string(),
706            include_proof_tokens: false,
707            trust_relationships: Vec::new(),
708            jwt_signing_secret,
709        }
710    }
711}
712
713#[cfg(test)]
714mod tests {
715    use super::*;
716
717    #[test]
718    fn test_sts_issue_saml_token() {
719        let config = StsConfig::default();
720        let mut sts = SecurityTokenService::new(config);
721
722        let auth_context = AuthenticationContext {
723            username: "testuser".to_string(),
724            auth_method: "password".to_string(),
725            claims: {
726                let mut claims = HashMap::new();
727                claims.insert("role".to_string(), "admin".to_string());
728                claims
729            },
730        };
731
732        let request = RequestSecurityToken {
733            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
734            token_type: "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
735            applies_to: Some("https://rp.example.com".to_string()),
736            lifetime: None,
737            key_type: None,
738            key_size: None,
739            existing_token: None,
740            auth_context: Some(auth_context),
741        };
742
743        let response = sts.process_request(request).unwrap();
744
745        assert_eq!(response.token_type, "urn:oasis:names:tc:SAML:2.0:assertion");
746        assert!(
747            response
748                .requested_security_token
749                .contains("<saml:Assertion")
750        );
751        assert!(response.requested_security_token.contains("testuser"));
752    }
753
754    #[test]
755    fn test_sts_issue_jwt_token() {
756        use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode as jwt_decode};
757
758        let config = StsConfig::default();
759        let signing_secret = config.jwt_signing_secret.clone();
760        let mut sts = SecurityTokenService::new(config);
761
762        let auth_context = AuthenticationContext {
763            username: "testuser".to_string(),
764            auth_method: "certificate".to_string(),
765            claims: HashMap::new(),
766        };
767
768        let request = RequestSecurityToken {
769            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
770            token_type: "urn:ietf:params:oauth:token-type:jwt".to_string(),
771            applies_to: Some("https://api.example.com".to_string()),
772            lifetime: None,
773            key_type: None,
774            key_size: None,
775            existing_token: None,
776            auth_context: Some(auth_context),
777        };
778
779        let response = sts.process_request(request).unwrap();
780
781        assert_eq!(response.token_type, "urn:ietf:params:oauth:token-type:jwt");
782
783        // Verify the issued JWT has exactly 3 Base64URL parts.
784        let parts: Vec<&str> = response.requested_security_token.split('.').collect();
785        assert_eq!(parts.len(), 3, "JWT must have header.payload.signature");
786
787        // Verify the signature is valid by decoding with the same secret.
788        let decoding_key = DecodingKey::from_secret(signing_secret.as_bytes());
789        let mut validation = Validation::new(Algorithm::HS256);
790        validation.set_audience(&["https://api.example.com"]);
791        let token_data = jwt_decode::<serde_json::Value>(
792            &response.requested_security_token,
793            &decoding_key,
794            &validation,
795        )
796        .expect("Issued WS-Trust JWT must be verifiable with the config signing secret");
797        assert_eq!(token_data.claims["sub"], "testuser");
798        assert_eq!(token_data.claims["auth_method"], "certificate");
799    }
800
801    #[test]
802    fn test_sts_soap_request_generation() {
803        let config = StsConfig::default();
804        let sts = SecurityTokenService::new(config);
805
806        let request = RequestSecurityToken {
807            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
808            token_type: "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
809            applies_to: Some("https://rp.example.com".to_string()),
810            lifetime: None,
811            key_type: Some("http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer".to_string()),
812            key_size: None,
813            existing_token: None,
814            auth_context: None,
815        };
816
817        let soap_request = sts
818            .create_rst_soap_request(&request, "test_user", Some("test_pass"))
819            .unwrap();
820
821        assert!(soap_request.contains("<soap:Envelope"));
822        assert!(soap_request.contains("<wsse:Security"));
823        assert!(soap_request.contains("<wst:RequestSecurityToken"));
824        assert!(soap_request.contains("https://rp.example.com"));
825        assert!(soap_request.contains("</soap:Envelope>"));
826    }
827
828    #[test]
829    fn test_unsupported_request_type() {
830        let mut sts = SecurityTokenService::new(StsConfig::default());
831
832        let request = RequestSecurityToken {
833            request_type: "http://invalid/BadRequest".to_string(),
834            token_type: "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
835            applies_to: None,
836            lifetime: None,
837            key_type: None,
838            key_size: None,
839            existing_token: None,
840            auth_context: None,
841        };
842
843        let err = sts.process_request(request).unwrap_err();
844        let msg = format!("{err}");
845        assert!(msg.contains("Unsupported request type"), "got: {msg}");
846    }
847
848    #[test]
849    fn test_issue_missing_auth_context() {
850        let mut sts = SecurityTokenService::new(StsConfig::default());
851
852        let request = RequestSecurityToken {
853            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
854            token_type: "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
855            applies_to: None,
856            lifetime: None,
857            key_type: None,
858            key_size: None,
859            existing_token: None,
860            auth_context: None,
861        };
862
863        let err = sts.process_request(request).unwrap_err();
864        let msg = format!("{err}");
865        assert!(
866            msg.contains("Authentication context required"),
867            "got: {msg}"
868        );
869    }
870
871    #[test]
872    fn test_issue_unsupported_token_type() {
873        let mut sts = SecurityTokenService::new(StsConfig::default());
874
875        let request = RequestSecurityToken {
876            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
877            token_type: "urn:unknown:token:type".to_string(),
878            applies_to: None,
879            lifetime: None,
880            key_type: None,
881            key_size: None,
882            existing_token: None,
883            auth_context: Some(AuthenticationContext {
884                username: "user".to_string(),
885                auth_method: "password".to_string(),
886                claims: HashMap::new(),
887            }),
888        };
889
890        let err = sts.process_request(request).unwrap_err();
891        let msg = format!("{err}");
892        assert!(msg.contains("Unsupported token type"), "got: {msg}");
893    }
894
895    #[test]
896    #[allow(clippy::field_reassign_with_default)] // each override stays on its own line so the diff against Default is readable
897    fn test_lifetime_clamped_to_max() {
898        let mut config = StsConfig::default();
899        config.max_token_lifetime = Duration::hours(2);
900        let mut sts = SecurityTokenService::new(config);
901
902        let now = Utc::now();
903        let request = RequestSecurityToken {
904            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
905            token_type: "urn:ietf:params:oauth:token-type:jwt".to_string(),
906            applies_to: Some("https://rp.example.com".to_string()),
907            lifetime: Some(TokenLifetime {
908                created: now,
909                expires: now + Duration::hours(999), // way beyond max
910            }),
911            key_type: None,
912            key_size: None,
913            existing_token: None,
914            auth_context: Some(AuthenticationContext {
915                username: "user".to_string(),
916                auth_method: "password".to_string(),
917                claims: HashMap::new(),
918            }),
919        };
920
921        let resp = sts.process_request(request).unwrap();
922        // Expires must be clamped to ~2 h from now, not 999 h
923        let delta = resp.lifetime.expires - now;
924        assert!(
925            delta <= Duration::hours(2) + Duration::seconds(5),
926            "lifetime should be clamped to max_token_lifetime, got {delta}"
927        );
928    }
929
930    #[test]
931    fn test_cancel_nonexistent_token() {
932        let mut sts = SecurityTokenService::new(StsConfig::default());
933
934        let request = RequestSecurityToken {
935            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Cancel".to_string(),
936            token_type: "".to_string(),
937            applies_to: None,
938            lifetime: None,
939            key_type: None,
940            key_size: None,
941            existing_token: Some("nonexistent-id".to_string()),
942            auth_context: None,
943        };
944
945        // Cancel of a non-existent token should succeed silently (idempotent)
946        let resp = sts.process_request(request).unwrap();
947        assert_eq!(resp.requested_security_token, "Token cancelled");
948    }
949
950    #[test]
951    fn test_cancel_missing_existing_token_field() {
952        let mut sts = SecurityTokenService::new(StsConfig::default());
953
954        let request = RequestSecurityToken {
955            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Cancel".to_string(),
956            token_type: "".to_string(),
957            applies_to: None,
958            lifetime: None,
959            key_type: None,
960            key_size: None,
961            existing_token: None, // missing
962            auth_context: None,
963        };
964
965        let err = sts.process_request(request).unwrap_err();
966        let msg = format!("{err}");
967        assert!(
968            msg.contains("Token required for cancellation"),
969            "got: {msg}"
970        );
971    }
972
973    #[test]
974    fn test_validate_nonexistent_token() {
975        let mut sts = SecurityTokenService::new(StsConfig::default());
976
977        let request = RequestSecurityToken {
978            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Validate".to_string(),
979            token_type: "".to_string(),
980            applies_to: None,
981            lifetime: None,
982            key_type: None,
983            key_size: None,
984            existing_token: Some("does-not-exist".to_string()),
985            auth_context: None,
986        };
987
988        let err = sts.process_request(request).unwrap_err();
989        let msg = format!("{err}");
990        assert!(msg.contains("Token not found"), "got: {msg}");
991    }
992
993    #[test]
994    fn test_renew_missing_existing_token() {
995        let mut sts = SecurityTokenService::new(StsConfig::default());
996
997        let request = RequestSecurityToken {
998            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Renew".to_string(),
999            token_type: "".to_string(),
1000            applies_to: None,
1001            lifetime: None,
1002            key_type: None,
1003            key_size: None,
1004            existing_token: None, // missing
1005            auth_context: None,
1006        };
1007
1008        let err = sts.process_request(request).unwrap_err();
1009        let msg = format!("{err}");
1010        assert!(
1011            msg.contains("Existing token required for renewal"),
1012            "got: {msg}"
1013        );
1014    }
1015
1016    #[test]
1017    #[allow(clippy::field_reassign_with_default)] // each override stays on its own line so the diff against Default is readable
1018    fn test_issue_with_proof_token_symmetric_key() {
1019        let mut config = StsConfig::default();
1020        config.include_proof_tokens = true;
1021        let mut sts = SecurityTokenService::new(config);
1022
1023        let request = RequestSecurityToken {
1024            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
1025            token_type: "urn:ietf:params:oauth:token-type:jwt".to_string(),
1026            applies_to: Some("https://rp.example.com".to_string()),
1027            lifetime: None,
1028            key_type: Some(
1029                "http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey".to_string(),
1030            ),
1031            key_size: None,
1032            existing_token: None,
1033            auth_context: Some(AuthenticationContext {
1034                username: "keyuser".to_string(),
1035                auth_method: "certificate".to_string(),
1036                claims: HashMap::new(),
1037            }),
1038        };
1039
1040        let resp = sts.process_request(request).unwrap();
1041        let proof = resp
1042            .requested_proof_token
1043            .expect("proof token should be present for symmetric key request");
1044        assert_eq!(proof.token_type, "SymmetricKey");
1045        assert_eq!(proof.key_material.len(), 32); // 256-bit key
1046        assert!(proof.key_identifier.starts_with("key-"));
1047    }
1048
1049    #[test]
1050    fn test_issue_and_validate_roundtrip() {
1051        let mut sts = SecurityTokenService::new(StsConfig::default());
1052
1053        // Issue
1054        let issue_req = RequestSecurityToken {
1055            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
1056            token_type: "urn:ietf:params:oauth:token-type:jwt".to_string(),
1057            applies_to: Some("https://rp.example.com".to_string()),
1058            lifetime: None,
1059            key_type: None,
1060            key_size: None,
1061            existing_token: None,
1062            auth_context: Some(AuthenticationContext {
1063                username: "roundtrip_user".to_string(),
1064                auth_method: "password".to_string(),
1065                claims: HashMap::new(),
1066            }),
1067        };
1068
1069        let issue_resp = sts.process_request(issue_req).unwrap();
1070        let token_id = issue_resp
1071            .requested_unattached_reference
1072            .expect("token id should be returned");
1073
1074        // Validate
1075        let validate_req = RequestSecurityToken {
1076            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Validate".to_string(),
1077            token_type: "".to_string(),
1078            applies_to: None,
1079            lifetime: None,
1080            key_type: None,
1081            key_size: None,
1082            existing_token: Some(token_id),
1083            auth_context: None,
1084        };
1085
1086        let validate_resp = sts.process_request(validate_req).unwrap();
1087        assert_eq!(validate_resp.requested_security_token, "Valid");
1088        assert_eq!(
1089            validate_resp.applies_to.as_deref(),
1090            Some("https://rp.example.com")
1091        );
1092    }
1093
1094    #[test]
1095    fn test_issue_and_cancel_then_validate_fails() {
1096        let mut sts = SecurityTokenService::new(StsConfig::default());
1097
1098        // Issue
1099        let issue_req = RequestSecurityToken {
1100            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
1101            token_type: "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
1102            applies_to: None,
1103            lifetime: None,
1104            key_type: None,
1105            key_size: None,
1106            existing_token: None,
1107            auth_context: Some(AuthenticationContext {
1108                username: "cancelme".to_string(),
1109                auth_method: "password".to_string(),
1110                claims: HashMap::new(),
1111            }),
1112        };
1113
1114        let issue_resp = sts.process_request(issue_req).unwrap();
1115        let token_id = issue_resp
1116            .requested_unattached_reference
1117            .expect("should have token id");
1118
1119        // Cancel
1120        let cancel_req = RequestSecurityToken {
1121            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Cancel".to_string(),
1122            token_type: "".to_string(),
1123            applies_to: None,
1124            lifetime: None,
1125            key_type: None,
1126            key_size: None,
1127            existing_token: Some(token_id.clone()),
1128            auth_context: None,
1129        };
1130        sts.process_request(cancel_req).unwrap();
1131
1132        // Validate should now fail (token was removed)
1133        let validate_req = RequestSecurityToken {
1134            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Validate".to_string(),
1135            token_type: "".to_string(),
1136            applies_to: None,
1137            lifetime: None,
1138            key_type: None,
1139            key_size: None,
1140            existing_token: Some(token_id),
1141            auth_context: None,
1142        };
1143
1144        let err = sts.process_request(validate_req).unwrap_err();
1145        let msg = format!("{err}");
1146        assert!(msg.contains("Token not found"), "got: {msg}");
1147    }
1148}