1use crate::errors::{AuthError, Result};
7use crate::saml_assertions::SamlAssertionBuilder;
8use 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
15pub struct SecurityTokenService {
17 config: StsConfig,
19
20 ws_security: WsSecurityClient,
22
23 issued_tokens: HashMap<String, IssuedToken>,
25}
26
27#[derive(Debug, Clone)]
29pub struct StsConfig {
30 pub issuer: String,
32
33 pub default_token_lifetime: Duration,
35
36 pub max_token_lifetime: Duration,
38
39 pub supported_token_types: Vec<String>,
41
42 pub endpoint_url: String,
44
45 pub include_proof_tokens: bool,
47
48 pub trust_relationships: Vec<TrustRelationship>,
50}
51
52#[derive(Debug, Clone)]
54pub struct TrustRelationship {
55 pub rp_identifier: String,
57
58 pub certificate: Option<Vec<u8>>,
60
61 pub allowed_token_types: Vec<String>,
63
64 pub max_token_lifetime: Option<Duration>,
66}
67
68#[derive(Clone, Serialize, Deserialize)]
70pub struct IssuedToken {
71 pub token_id: String,
73
74 pub token_type: String,
76
77 pub token_content: String,
79
80 pub issued_at: DateTime<Utc>,
82
83 pub expires_at: DateTime<Utc>,
85
86 pub subject: String,
88
89 pub audience: String,
91
92 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#[derive(Clone, Serialize, Deserialize)]
116pub struct ProofToken {
117 pub token_type: String,
119
120 pub key_material: Vec<u8>,
122
123 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#[derive(Clone, Serialize, Deserialize)]
142pub struct RequestSecurityToken {
143 pub request_type: String,
145
146 pub token_type: String,
148
149 pub applies_to: Option<String>,
151
152 pub lifetime: Option<TokenLifetime>,
154
155 pub key_type: Option<String>,
157
158 pub key_size: Option<u32>,
160
161 pub existing_token: Option<String>,
163
164 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#[derive(Debug, Clone, Serialize, Deserialize)]
188pub struct TokenLifetime {
189 pub created: DateTime<Utc>,
191
192 pub expires: DateTime<Utc>,
194}
195
196#[derive(Debug, Clone, Serialize, Deserialize)]
198pub struct AuthenticationContext {
199 pub username: String,
201
202 pub auth_method: String,
204
205 pub claims: HashMap<String, String>,
207}
208
209#[derive(Clone, Serialize, Deserialize)]
211pub struct RequestSecurityTokenResponse {
212 pub request_type: String,
214
215 pub token_type: String,
217
218 pub lifetime: TokenLifetime,
220
221 pub applies_to: Option<String>,
223
224 pub requested_security_token: String,
226
227 pub requested_proof_token: Option<ProofToken>,
229
230 pub requested_attached_reference: Option<String>,
232
233 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 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 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 fn issue_token(
295 &mut self,
296 request: RequestSecurityToken,
297 ) -> Result<RequestSecurityTokenResponse> {
298 let auth_context = request
300 .auth_context
301 .as_ref()
302 .ok_or_else(|| AuthError::auth_method("wstrust", "Authentication context required"))?;
303
304 let now = Utc::now();
306 let lifetime = if let Some(ref requested_lifetime) = request.lifetime {
307 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 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 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 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 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 if let Some(ref audience) = request.applies_to {
390 assertion_builder = assertion_builder.with_audience(audience);
391 }
392
393 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 fn issue_jwt_token(
404 &self,
405 auth_context: &AuthenticationContext,
406 request: &RequestSecurityToken,
407 lifetime: &TokenLifetime,
408 ) -> Result<String> {
409 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"); Ok(format!("{}.{}.{}", header_b64, payload_b64, signature_b64))
426 }
427
428 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]; 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 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 let token_id = existing_token; let issued_token = self
454 .issued_tokens
455 .get(&token_id)
456 .ok_or_else(|| AuthError::auth_method("wstrust", "Token not found"))?;
457
458 let now = Utc::now();
460 if now >= issued_token.expires_at {
461 return Err(AuthError::auth_method("wstrust", "Token has expired"));
462 }
463
464 let new_lifetime = TokenLifetime {
466 created: now,
467 expires: now + self.config.default_token_lifetime,
468 };
469
470 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 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 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 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 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 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 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}