Skip to main content

auth_framework/
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::saml_assertions::SamlAssertionBuilder;
8// SamlAssertion removed from import - not currently used but may be needed later
9use crate::ws_security::{PasswordType, WsSecurityClient, WsSecurityConfig};
10use base64::{Engine as _, engine::general_purpose::STANDARD};
11use chrono::{DateTime, Duration, Utc};
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14
15/// WS-Trust Security Token Service
16pub struct SecurityTokenService {
17    /// STS configuration
18    config: StsConfig,
19
20    /// WS-Security client for generating secure headers
21    ws_security: WsSecurityClient,
22
23    /// Issued tokens cache
24    issued_tokens: HashMap<String, IssuedToken>,
25}
26
27/// STS Configuration
28#[derive(Debug, Clone)]
29pub struct StsConfig {
30    /// STS issuer identifier
31    pub issuer: String,
32
33    /// Default token lifetime
34    pub default_token_lifetime: Duration,
35
36    /// Maximum token lifetime
37    pub max_token_lifetime: Duration,
38
39    /// Supported token types
40    pub supported_token_types: Vec<String>,
41
42    /// STS endpoint URL
43    pub endpoint_url: String,
44
45    /// Whether to include proof tokens
46    pub include_proof_tokens: bool,
47
48    /// Trust relationships
49    pub trust_relationships: Vec<TrustRelationship>,
50}
51
52/// Trust relationship with relying parties
53#[derive(Debug, Clone)]
54pub struct TrustRelationship {
55    /// Relying party identifier
56    pub rp_identifier: String,
57
58    /// Certificate for encryption/signing
59    pub certificate: Option<Vec<u8>>,
60
61    /// Allowed token types
62    pub allowed_token_types: Vec<String>,
63
64    /// Maximum token lifetime for this RP
65    pub max_token_lifetime: Option<Duration>,
66}
67
68/// Issued token information
69#[derive(Clone, Serialize, Deserialize)]
70pub struct IssuedToken {
71    /// Token ID
72    pub token_id: String,
73
74    /// Token type
75    pub token_type: String,
76
77    /// Token content (SAML assertion, JWT, etc.)
78    pub token_content: String,
79
80    /// Issue time
81    pub issued_at: DateTime<Utc>,
82
83    /// Expiration time
84    pub expires_at: DateTime<Utc>,
85
86    /// Subject identifier
87    pub subject: String,
88
89    /// Audience/relying party
90    pub audience: String,
91
92    /// Proof token (if any)
93    pub proof_token: Option<ProofToken>,
94}
95
96impl std::fmt::Debug for IssuedToken {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        let mut d = f.debug_struct("IssuedToken");
99        d.field("token_id", &crate::utils::redact::redacted(&self.token_id));
100        d.field("token_type", &self.token_type);
101        d.field(
102            "token_content",
103            &crate::utils::redact::redacted(&self.token_content),
104        );
105        d.field("issued_at", &self.issued_at);
106        d.field("expires_at", &self.expires_at);
107        d.field("subject", &self.subject);
108        d.field("audience", &self.audience);
109        d.field("proof_token", &self.proof_token);
110        d.finish()
111    }
112}
113
114/// Proof token for holder-of-key scenarios
115#[derive(Clone, Serialize, Deserialize)]
116pub struct ProofToken {
117    /// Proof token type (symmetric key, certificate, etc.)
118    pub token_type: String,
119
120    /// Key material
121    pub key_material: Vec<u8>,
122
123    /// Key identifier
124    pub key_identifier: String,
125}
126
127impl std::fmt::Debug for ProofToken {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        let mut d = f.debug_struct("ProofToken");
130        d.field("token_type", &self.token_type);
131        d.field(
132            "key_material",
133            &crate::utils::redact::redacted(&self.key_material),
134        );
135        d.field("key_identifier", &self.key_identifier);
136        d.finish()
137    }
138}
139
140/// WS-Trust Request Security Token (RST)
141#[derive(Clone, Serialize, Deserialize)]
142pub struct RequestSecurityToken {
143    /// Request type (Issue, Renew, Cancel, Validate)
144    pub request_type: String,
145
146    /// Token type being requested
147    pub token_type: String,
148
149    /// Applies to (target service/audience)
150    pub applies_to: Option<String>,
151
152    /// Lifetime requirements
153    pub lifetime: Option<TokenLifetime>,
154
155    /// Key type (Bearer, Symmetric, Asymmetric)
156    pub key_type: Option<String>,
157
158    /// Key size for symmetric keys
159    pub key_size: Option<u32>,
160
161    /// Existing token (for renew/validate operations)
162    pub existing_token: Option<String>,
163
164    /// Authentication context
165    pub auth_context: Option<AuthenticationContext>,
166}
167
168impl std::fmt::Debug for RequestSecurityToken {
169    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170        let mut d = f.debug_struct("RequestSecurityToken");
171        d.field("request_type", &self.request_type);
172        d.field("token_type", &self.token_type);
173        d.field("applies_to", &self.applies_to);
174        d.field("lifetime", &self.lifetime);
175        d.field("key_type", &self.key_type);
176        d.field("key_size", &self.key_size);
177        d.field(
178            "existing_token",
179            &crate::utils::redact::redacted(&self.existing_token),
180        );
181        d.field("auth_context", &self.auth_context);
182        d.finish()
183    }
184}
185
186/// Token lifetime specification
187#[derive(Debug, Clone, Serialize, Deserialize)]
188pub struct TokenLifetime {
189    /// Created time
190    pub created: DateTime<Utc>,
191
192    /// Expires time
193    pub expires: DateTime<Utc>,
194}
195
196/// Authentication context for token requests
197#[derive(Debug, Clone, Serialize, Deserialize)]
198pub struct AuthenticationContext {
199    /// Username
200    pub username: String,
201
202    /// Authentication method
203    pub auth_method: String,
204
205    /// Additional claims
206    pub claims: HashMap<String, String>,
207}
208
209/// WS-Trust Request Security Token Response (RSTR)
210#[derive(Clone, Serialize, Deserialize)]
211pub struct RequestSecurityTokenResponse {
212    /// Request type being responded to
213    pub request_type: String,
214
215    /// Token type issued
216    pub token_type: String,
217
218    /// Lifetime of issued token
219    pub lifetime: TokenLifetime,
220
221    /// Applies to (target audience)
222    pub applies_to: Option<String>,
223
224    /// Requested security token
225    pub requested_security_token: String,
226
227    /// Requested proof token
228    pub requested_proof_token: Option<ProofToken>,
229
230    /// Token reference for future operations
231    pub requested_attached_reference: Option<String>,
232
233    /// Token reference for external use
234    pub requested_unattached_reference: Option<String>,
235}
236
237impl std::fmt::Debug for RequestSecurityTokenResponse {
238    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239        let mut d = f.debug_struct("RequestSecurityTokenResponse");
240        d.field("request_type", &self.request_type);
241        d.field("token_type", &self.token_type);
242        d.field("lifetime", &self.lifetime);
243        d.field("applies_to", &self.applies_to);
244        d.field(
245            "requested_security_token",
246            &crate::utils::redact::redacted(&self.requested_security_token),
247        );
248        d.field("requested_proof_token", &self.requested_proof_token);
249        d.field(
250            "requested_attached_reference",
251            &self.requested_attached_reference,
252        );
253        d.field(
254            "requested_unattached_reference",
255            &self.requested_unattached_reference,
256        );
257        d.finish()
258    }
259}
260
261impl SecurityTokenService {
262    /// Create a new Security Token Service
263    pub fn new(config: StsConfig) -> Self {
264        let ws_security_config = WsSecurityConfig::default();
265        let ws_security = WsSecurityClient::new(ws_security_config);
266
267        Self {
268            config,
269            ws_security,
270            issued_tokens: HashMap::new(),
271        }
272    }
273
274    /// Process a WS-Trust Request Security Token
275    pub fn process_request(
276        &mut self,
277        request: RequestSecurityToken,
278    ) -> Result<RequestSecurityTokenResponse> {
279        match request.request_type.as_str() {
280            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue" => self.issue_token(request),
281            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Renew" => self.renew_token(request),
282            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Cancel" => self.cancel_token(request),
283            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Validate" => {
284                self.validate_token(request)
285            }
286            _ => Err(AuthError::auth_method(
287                "wstrust",
288                "Unsupported request type",
289            )),
290        }
291    }
292
293    /// Issue a new security token
294    fn issue_token(
295        &mut self,
296        request: RequestSecurityToken,
297    ) -> Result<RequestSecurityTokenResponse> {
298        // Validate authentication context
299        let auth_context = request
300            .auth_context
301            .as_ref()
302            .ok_or_else(|| AuthError::auth_method("wstrust", "Authentication context required"))?;
303
304        // Determine token lifetime
305        let now = Utc::now();
306        let lifetime = if let Some(ref requested_lifetime) = request.lifetime {
307            // Validate requested lifetime
308            let max_expires = now + self.config.max_token_lifetime;
309            let expires = if requested_lifetime.expires > max_expires {
310                max_expires
311            } else {
312                requested_lifetime.expires
313            };
314
315            TokenLifetime {
316                created: now,
317                expires,
318            }
319        } else {
320            TokenLifetime {
321                created: now,
322                expires: now + self.config.default_token_lifetime,
323            }
324        };
325
326        // Generate token based on type
327        let token_content = match request.token_type.as_str() {
328            "urn:oasis:names:tc:SAML:2.0:assertion" => {
329                self.issue_saml_token(auth_context, &request, &lifetime)?
330            }
331            "urn:ietf:params:oauth:token-type:jwt" => {
332                self.issue_jwt_token(auth_context, &request, &lifetime)?
333            }
334            _ => {
335                return Err(AuthError::auth_method("wstrust", "Unsupported token type"));
336            }
337        };
338
339        // Generate proof token if required
340        let proof_token = if self.config.include_proof_tokens
341            && request.key_type.as_deref()
342                == Some("http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey")
343        {
344            Some(self.generate_proof_token()?)
345        } else {
346            None
347        };
348
349        // Store issued token
350        let token_id = format!("token-{}", uuid::Uuid::new_v4());
351        let issued_token = IssuedToken {
352            token_id: token_id.clone(),
353            token_type: request.token_type.clone(),
354            token_content: token_content.clone(),
355            issued_at: lifetime.created,
356            expires_at: lifetime.expires,
357            subject: auth_context.username.clone(),
358            audience: request.applies_to.clone().unwrap_or_default(),
359            proof_token: proof_token.clone(),
360        };
361
362        self.issued_tokens.insert(token_id.clone(), issued_token);
363
364        Ok(RequestSecurityTokenResponse {
365            request_type: request.request_type,
366            token_type: request.token_type,
367            lifetime,
368            applies_to: request.applies_to,
369            requested_security_token: token_content,
370            requested_proof_token: proof_token,
371            requested_attached_reference: Some(format!("#{}", token_id)),
372            requested_unattached_reference: Some(token_id),
373        })
374    }
375
376    /// Issue a SAML 2.0 assertion token
377    fn issue_saml_token(
378        &self,
379        auth_context: &AuthenticationContext,
380        request: &RequestSecurityToken,
381        lifetime: &TokenLifetime,
382    ) -> Result<String> {
383        let mut assertion_builder = SamlAssertionBuilder::new(&self.config.issuer)
384            .with_validity_period(lifetime.created, lifetime.expires)
385            .with_attribute("username", &auth_context.username)
386            .with_attribute("auth_method", &auth_context.auth_method);
387
388        // Add audience if specified
389        if let Some(ref audience) = request.applies_to {
390            assertion_builder = assertion_builder.with_audience(audience);
391        }
392
393        // Add additional claims as attributes
394        for (key, value) in &auth_context.claims {
395            assertion_builder = assertion_builder.with_attribute(key, value);
396        }
397
398        let assertion = assertion_builder.build();
399        assertion.to_xml()
400    }
401
402    /// Issue a JWT token
403    fn issue_jwt_token(
404        &self,
405        auth_context: &AuthenticationContext,
406        request: &RequestSecurityToken,
407        lifetime: &TokenLifetime,
408    ) -> Result<String> {
409        // Simplified JWT creation - would use proper JWT library in production
410        let header = r#"{"alg":"HS256","typ":"JWT"}"#;
411        let payload = format!(
412            r#"{{"iss":"{}","sub":"{}","aud":"{}","iat":{},"exp":{},"auth_method":"{}"}}"#,
413            self.config.issuer,
414            auth_context.username,
415            request.applies_to.as_deref().unwrap_or(""),
416            lifetime.created.timestamp(),
417            lifetime.expires.timestamp(),
418            auth_context.auth_method
419        );
420
421        let header_b64 = STANDARD.encode(header);
422        let payload_b64 = STANDARD.encode(payload);
423        let signature_b64 = STANDARD.encode("dummy_signature"); // Would be real signature
424
425        Ok(format!("{}.{}.{}", header_b64, payload_b64, signature_b64))
426    }
427
428    /// Generate a proof token for holder-of-key scenarios
429    fn generate_proof_token(&self) -> Result<ProofToken> {
430        use rand::RngCore;
431        let mut rng = rand::rng();
432        let mut key_material = vec![0u8; 32]; // 256-bit symmetric key
433        rng.fill_bytes(&mut key_material);
434
435        Ok(ProofToken {
436            token_type: "SymmetricKey".to_string(),
437            key_material,
438            key_identifier: format!("key-{}", uuid::Uuid::new_v4()),
439        })
440    }
441
442    /// Renew an existing token
443    fn renew_token(
444        &mut self,
445        request: RequestSecurityToken,
446    ) -> Result<RequestSecurityTokenResponse> {
447        let existing_token = request.existing_token.ok_or_else(|| {
448            AuthError::auth_method("wstrust", "Existing token required for renewal")
449        })?;
450
451        // Find the token (simplified - would parse and validate the token)
452        let token_id = existing_token; // Assuming token ID is passed directly
453        let issued_token = self
454            .issued_tokens
455            .get(&token_id)
456            .ok_or_else(|| AuthError::auth_method("wstrust", "Token not found"))?;
457
458        // Check if token is still valid
459        let now = Utc::now();
460        if now >= issued_token.expires_at {
461            return Err(AuthError::auth_method("wstrust", "Token has expired"));
462        }
463
464        // Create renewed token with new lifetime
465        let new_lifetime = TokenLifetime {
466            created: now,
467            expires: now + self.config.default_token_lifetime,
468        };
469
470        // Issue new token (simplified - would copy original claims)
471        let auth_context = AuthenticationContext {
472            username: issued_token.subject.clone(),
473            auth_method: "token_renewal".to_string(),
474            claims: HashMap::new(),
475        };
476
477        let new_request = RequestSecurityToken {
478            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
479            token_type: issued_token.token_type.clone(),
480            applies_to: Some(issued_token.audience.clone()),
481            lifetime: Some(new_lifetime.clone()),
482            key_type: None,
483            key_size: None,
484            existing_token: None,
485            auth_context: Some(auth_context),
486        };
487
488        self.issue_token(new_request)
489    }
490
491    /// Cancel an existing token
492    fn cancel_token(
493        &mut self,
494        request: RequestSecurityToken,
495    ) -> Result<RequestSecurityTokenResponse> {
496        let existing_token = request
497            .existing_token
498            .ok_or_else(|| AuthError::auth_method("wstrust", "Token required for cancellation"))?;
499
500        // Remove token from cache
501        self.issued_tokens.remove(&existing_token);
502
503        Ok(RequestSecurityTokenResponse {
504            request_type: request.request_type,
505            token_type: "Cancelled".to_string(),
506            lifetime: TokenLifetime {
507                created: Utc::now(),
508                expires: Utc::now(),
509            },
510            applies_to: None,
511            requested_security_token: "Token cancelled".to_string(),
512            requested_proof_token: None,
513            requested_attached_reference: None,
514            requested_unattached_reference: None,
515        })
516    }
517
518    /// Validate an existing token
519    fn validate_token(
520        &self,
521        request: RequestSecurityToken,
522    ) -> Result<RequestSecurityTokenResponse> {
523        let existing_token = request
524            .existing_token
525            .ok_or_else(|| AuthError::auth_method("wstrust", "Token required for validation"))?;
526
527        // Find and validate token
528        let token_id = existing_token;
529        let issued_token = self
530            .issued_tokens
531            .get(&token_id)
532            .ok_or_else(|| AuthError::auth_method("wstrust", "Token not found"))?;
533
534        let now = Utc::now();
535        let is_valid = now < issued_token.expires_at;
536
537        let status = if is_valid { "Valid" } else { "Invalid" };
538
539        Ok(RequestSecurityTokenResponse {
540            request_type: request.request_type,
541            token_type: "ValidationResponse".to_string(),
542            lifetime: TokenLifetime {
543                created: issued_token.issued_at,
544                expires: issued_token.expires_at,
545            },
546            applies_to: Some(issued_token.audience.clone()),
547            requested_security_token: status.to_string(),
548            requested_proof_token: None,
549            requested_attached_reference: None,
550            requested_unattached_reference: None,
551        })
552    }
553
554    /// Create a complete WS-Trust SOAP request
555    pub fn create_rst_soap_request(&self, request: &RequestSecurityToken) -> Result<String> {
556        let header = self.ws_security.create_username_token_header(
557            "client_user",
558            Some("client_password"),
559            PasswordType::PasswordText,
560        )?;
561
562        let security_header = self.ws_security.header_to_xml(&header)?;
563
564        let soap_request = format!(
565            r#"<?xml version="1.0" encoding="UTF-8"?>
566<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
567               xmlns:wst="http://docs.oasis-open.org/ws-sx/ws-trust/200512"
568               xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
569    <soap:Header>
570        {}
571    </soap:Header>
572    <soap:Body>
573        <wst:RequestSecurityToken>
574            <wst:RequestType>{}</wst:RequestType>
575            <wst:TokenType>{}</wst:TokenType>
576            {}
577            {}
578            {}
579        </wst:RequestSecurityToken>
580    </soap:Body>
581</soap:Envelope>"#,
582            security_header,
583            request.request_type,
584            request.token_type,
585            request.applies_to.as_ref().map(|a| format!("<wsp:AppliesTo><wsp:EndpointReference><wsp:Address>{}</wsp:Address></wsp:EndpointReference></wsp:AppliesTo>", a)).unwrap_or_default(),
586            request.lifetime.as_ref().map(|l| format!("<wst:Lifetime><wsu:Created>{}</wsu:Created><wsu:Expires>{}</wsu:Expires></wst:Lifetime>",
587                l.created.format("%Y-%m-%dT%H:%M:%S%.3fZ"),
588                l.expires.format("%Y-%m-%dT%H:%M:%S%.3fZ"))).unwrap_or_default(),
589            request.key_type.as_ref().map(|k| format!("<wst:KeyType>{}</wst:KeyType>", k)).unwrap_or_default()
590        );
591
592        Ok(soap_request)
593    }
594}
595
596impl Default for StsConfig {
597    fn default() -> Self {
598        Self {
599            issuer: "https://sts.example.com".to_string(),
600            default_token_lifetime: Duration::hours(1),
601            max_token_lifetime: Duration::hours(8),
602            supported_token_types: vec![
603                "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
604                "urn:ietf:params:oauth:token-type:jwt".to_string(),
605            ],
606            endpoint_url: "https://sts.example.com/trust".to_string(),
607            include_proof_tokens: false,
608            trust_relationships: Vec::new(),
609        }
610    }
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616
617    #[test]
618    fn test_sts_issue_saml_token() {
619        let config = StsConfig::default();
620        let mut sts = SecurityTokenService::new(config);
621
622        let auth_context = AuthenticationContext {
623            username: "testuser".to_string(),
624            auth_method: "password".to_string(),
625            claims: {
626                let mut claims = HashMap::new();
627                claims.insert("role".to_string(), "admin".to_string());
628                claims
629            },
630        };
631
632        let request = RequestSecurityToken {
633            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
634            token_type: "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
635            applies_to: Some("https://rp.example.com".to_string()),
636            lifetime: None,
637            key_type: None,
638            key_size: None,
639            existing_token: None,
640            auth_context: Some(auth_context),
641        };
642
643        let response = sts.process_request(request).unwrap();
644
645        assert_eq!(response.token_type, "urn:oasis:names:tc:SAML:2.0:assertion");
646        assert!(
647            response
648                .requested_security_token
649                .contains("<saml:Assertion")
650        );
651        assert!(response.requested_security_token.contains("testuser"));
652    }
653
654    #[test]
655    fn test_sts_issue_jwt_token() {
656        let config = StsConfig::default();
657        let mut sts = SecurityTokenService::new(config);
658
659        let auth_context = AuthenticationContext {
660            username: "testuser".to_string(),
661            auth_method: "certificate".to_string(),
662            claims: HashMap::new(),
663        };
664
665        let request = RequestSecurityToken {
666            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
667            token_type: "urn:ietf:params:oauth:token-type:jwt".to_string(),
668            applies_to: Some("https://api.example.com".to_string()),
669            lifetime: None,
670            key_type: None,
671            key_size: None,
672            existing_token: None,
673            auth_context: Some(auth_context),
674        };
675
676        let response = sts.process_request(request).unwrap();
677
678        assert_eq!(response.token_type, "urn:ietf:params:oauth:token-type:jwt");
679        assert!(response.requested_security_token.contains("."));
680
681        // Decode JWT payload to verify content
682        let parts: Vec<&str> = response.requested_security_token.split('.').collect();
683        assert_eq!(parts.len(), 3);
684    }
685
686    #[test]
687    fn test_sts_soap_request_generation() {
688        let config = StsConfig::default();
689        let sts = SecurityTokenService::new(config);
690
691        let request = RequestSecurityToken {
692            request_type: "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue".to_string(),
693            token_type: "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
694            applies_to: Some("https://rp.example.com".to_string()),
695            lifetime: None,
696            key_type: Some("http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer".to_string()),
697            key_size: None,
698            existing_token: None,
699            auth_context: None,
700        };
701
702        let soap_request = sts.create_rst_soap_request(&request).unwrap();
703
704        assert!(soap_request.contains("<soap:Envelope"));
705        assert!(soap_request.contains("<wsse:Security"));
706        assert!(soap_request.contains("<wst:RequestSecurityToken"));
707        assert!(soap_request.contains("https://rp.example.com"));
708        assert!(soap_request.contains("</soap:Envelope>"));
709    }
710}