1use crate::errors::{AuthError, Result};
7use crate::saml_assertions::SamlAssertion;
8use base64::{Engine as _, engine::general_purpose::STANDARD};
9use chrono::{DateTime, Duration, Utc};
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12
13#[derive(Debug, Clone, Default)]
15pub struct WsSecurityHeader {
16 pub username_token: Option<UsernameToken>,
18
19 pub timestamp: Option<Timestamp>,
21
22 pub binary_security_token: Option<BinarySecurityToken>,
24
25 pub saml_assertions: Vec<SamlAssertionRef>,
27
28 pub signature: Option<WsSecuritySignature>,
30
31 pub custom_elements: Vec<String>,
33}
34
35#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct UsernameToken {
38 pub username: String,
40
41 pub password: Option<UsernamePassword>,
43
44 pub nonce: Option<String>,
46
47 pub created: Option<DateTime<Utc>>,
49
50 pub wsu_id: Option<String>,
52}
53
54#[derive(Clone, Serialize, Deserialize)]
56pub struct UsernamePassword {
57 pub value: String,
59
60 pub password_type: PasswordType,
62}
63
64impl std::fmt::Debug for UsernamePassword {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 let mut d = f.debug_struct("UsernamePassword");
67 d.field("value", &crate::utils::redact::redacted(&self.value));
68 d.field("password_type", &self.password_type);
69 d.finish()
70 }
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub enum PasswordType {
76 PasswordText,
78
79 PasswordDigest,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct Timestamp {
86 pub created: DateTime<Utc>,
88
89 pub expires: DateTime<Utc>,
91
92 pub wsu_id: Option<String>,
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct BinarySecurityToken {
99 pub value: String,
101
102 pub value_type: String,
104
105 pub encoding_type: String,
107
108 pub wsu_id: Option<String>,
110}
111
112#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct SamlAssertionRef {
115 pub assertion: SamlAssertion,
117
118 pub wsu_id: Option<String>,
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct WsSecuritySignature {
125 pub signature_method: String,
127
128 pub canonicalization_method: String,
130
131 pub digest_method: String,
133
134 pub references: Vec<SignatureReference>,
136
137 pub key_info: Option<KeyInfo>,
139
140 pub signature_value: Option<String>,
142}
143
144#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct SignatureReference {
147 pub uri: String,
149
150 pub digest_value: String,
152
153 pub transforms: Vec<String>,
155}
156
157#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct KeyInfo {
160 pub security_token_reference: Option<String>,
162
163 pub key_value: Option<String>,
165
166 pub x509_data: Option<String>,
168}
169
170#[derive(Clone)]
172pub struct WsSecurityConfig {
173 pub include_timestamp: bool,
175
176 pub timestamp_ttl: Duration,
178
179 pub sign_message: bool,
181
182 pub elements_to_sign: Vec<String>,
184
185 pub signing_certificate: Option<Vec<u8>>,
187
188 pub signing_private_key: Option<Vec<u8>>,
190
191 pub include_certificate: bool,
193
194 pub saml_token_endpoint: Option<String>,
196
197 pub actor: Option<String>,
199}
200
201impl std::fmt::Debug for WsSecurityConfig {
202 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203 let mut d = f.debug_struct("WsSecurityConfig");
204 d.field("include_timestamp", &self.include_timestamp);
205 d.field("timestamp_ttl", &self.timestamp_ttl);
206 d.field("sign_message", &self.sign_message);
207 d.field("elements_to_sign", &self.elements_to_sign);
208 d.field("signing_certificate", &self.signing_certificate);
209 d.field(
210 "signing_private_key",
211 &crate::utils::redact::redacted(&self.signing_private_key),
212 );
213 d.field("include_certificate", &self.include_certificate);
214 d.field("saml_token_endpoint", &self.saml_token_endpoint);
215 d.field("actor", &self.actor);
216 d.finish()
217 }
218}
219
220pub struct WsSecurityClient {
222 config: WsSecurityConfig,
224
225 namespaces: HashMap<String, String>,
227}
228
229impl WsSecurityClient {
230 pub fn new(config: WsSecurityConfig) -> Self {
232 let mut namespaces = HashMap::new();
233 namespaces.insert(
234 "wsse".to_string(),
235 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
236 .to_string(),
237 );
238 namespaces.insert(
239 "wsu".to_string(),
240 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
241 .to_string(),
242 );
243 namespaces.insert(
244 "ds".to_string(),
245 "http://www.w3.org/2000/09/xmldsig#".to_string(),
246 );
247 namespaces.insert(
248 "saml".to_string(),
249 "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
250 );
251
252 Self { config, namespaces }
253 }
254
255 pub fn create_username_token_header(
257 &self,
258 username: &str,
259 password: Option<&str>,
260 password_type: PasswordType,
261 ) -> Result<WsSecurityHeader> {
262 let mut header = WsSecurityHeader::default();
263
264 let (nonce, created) = if password_type == PasswordType::PasswordDigest {
265 (Some(self.generate_nonce()), Some(Utc::now()))
266 } else {
267 (None, None)
268 };
269
270 let password_element = if let Some(pwd) = password {
271 let pwd_value = match password_type {
272 PasswordType::PasswordText => pwd.to_string(),
273 PasswordType::PasswordDigest => {
274 self.compute_password_digest(pwd, nonce.as_ref().unwrap(), &created.unwrap())?
275 }
276 };
277
278 Some(UsernamePassword {
279 value: pwd_value,
280 password_type,
281 })
282 } else {
283 None
284 };
285
286 header.username_token = Some(UsernameToken {
287 username: username.to_string(),
288 password: password_element,
289 nonce,
290 created,
291 wsu_id: Some(format!("UsernameToken-{}", uuid::Uuid::new_v4())),
292 });
293
294 if self.config.include_timestamp {
295 header.timestamp = Some(self.create_timestamp());
296 }
297
298 Ok(header)
299 }
300
301 pub fn create_certificate_header(&self, certificate: &[u8]) -> Result<WsSecurityHeader> {
303 let mut header = WsSecurityHeader::default();
304
305 let cert_b64 = STANDARD.encode(certificate);
307
308 header.binary_security_token = Some(BinarySecurityToken {
309 value: cert_b64,
310 value_type: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3".to_string(),
311 encoding_type: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary".to_string(),
312 wsu_id: Some(format!("X509Token-{}", uuid::Uuid::new_v4())),
313 });
314
315 if self.config.include_timestamp {
316 header.timestamp = Some(self.create_timestamp());
317 }
318
319 if self.config.sign_message {
320 header.signature = Some(self.create_signature_template()?);
321 }
322
323 Ok(header)
324 }
325
326 pub fn create_saml_header(&self, assertion: SamlAssertion) -> Result<WsSecurityHeader> {
328 let mut header = WsSecurityHeader::default();
329
330 let assertion_ref = SamlAssertionRef {
331 assertion,
332 wsu_id: Some(format!("SamlAssertion-{}", uuid::Uuid::new_v4())),
333 };
334
335 header.saml_assertions.push(assertion_ref);
336
337 if self.config.include_timestamp {
338 header.timestamp = Some(self.create_timestamp());
339 }
340
341 Ok(header)
342 }
343 pub fn header_to_xml(&self, header: &WsSecurityHeader) -> Result<String> {
345 let mut xml = String::new();
346
347 xml.push_str(&format!(
349 r#"<wsse:Security xmlns:wsse="{}" xmlns:wsu="{}">"#,
350 self.namespaces["wsse"], self.namespaces["wsu"]
351 ));
352
353 if let Some(ref timestamp) = header.timestamp {
355 xml.push_str(&self.timestamp_to_xml(timestamp));
356 }
357
358 if let Some(ref username_token) = header.username_token {
360 xml.push_str(&self.username_token_to_xml(username_token));
361 }
362
363 if let Some(ref bst) = header.binary_security_token {
365 xml.push_str(&self.binary_security_token_to_xml(bst));
366 }
367
368 for assertion_ref in &header.saml_assertions {
370 let assertion_xml = assertion_ref.assertion.to_xml()?;
371 xml.push_str(&assertion_xml);
372 }
373
374 if let Some(ref signature) = header.signature {
376 xml.push_str(&self.signature_to_xml(signature));
377 }
378
379 xml.push_str("</wsse:Security>");
381
382 Ok(xml)
383 }
384
385 fn generate_nonce(&self) -> String {
387 use rand::RngCore;
388 let mut rng = rand::rng();
389 let mut nonce = [0u8; 16];
390 rng.fill_bytes(&mut nonce);
391 STANDARD.encode(nonce)
392 }
393
394 fn compute_password_digest(
396 &self,
397 password: &str,
398 nonce: &str,
399 created: &DateTime<Utc>,
400 ) -> Result<String> {
401 use sha1::{Digest, Sha1};
402
403 let nonce_bytes = STANDARD
404 .decode(nonce)
405 .map_err(|_| AuthError::auth_method("ws_security", "Invalid nonce encoding"))?;
406 let created_str = created.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
407
408 let mut hasher = Sha1::new();
409 hasher.update(&nonce_bytes);
410 hasher.update(created_str.as_bytes());
411 hasher.update(password.as_bytes());
412
413 let digest = hasher.finalize();
414 Ok(STANDARD.encode(digest))
415 }
416
417 fn create_timestamp(&self) -> Timestamp {
419 let now = Utc::now();
420 let expires = now + self.config.timestamp_ttl;
421
422 Timestamp {
423 created: now,
424 expires,
425 wsu_id: Some(format!("Timestamp-{}", uuid::Uuid::new_v4())),
426 }
427 }
428
429 fn create_signature_template(&self) -> Result<WsSecuritySignature> {
431 Ok(WsSecuritySignature {
432 signature_method: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256".to_string(),
433 canonicalization_method: "http://www.w3.org/2001/10/xml-exc-c14n#".to_string(),
434 digest_method: "http://www.w3.org/2001/04/xmlenc#sha256".to_string(),
435 references: self
436 .config
437 .elements_to_sign
438 .iter()
439 .map(|element| {
440 SignatureReference {
441 uri: format!("#{}", element),
442 digest_value: String::new(), transforms: vec!["http://www.w3.org/2001/10/xml-exc-c14n#".to_string()],
444 }
445 })
446 .collect(),
447 key_info: None, signature_value: None, })
450 }
451
452 fn timestamp_to_xml(&self, timestamp: &Timestamp) -> String {
454 let mut xml = String::new();
455
456 if let Some(ref id) = timestamp.wsu_id {
457 xml.push_str(&format!(r#"<wsu:Timestamp wsu:Id="{}">"#, id));
458 } else {
459 xml.push_str("<wsu:Timestamp>");
460 }
461
462 xml.push_str(&format!(
463 "<wsu:Created>{}</wsu:Created>",
464 timestamp.created.format("%Y-%m-%dT%H:%M:%S%.3fZ")
465 ));
466
467 xml.push_str(&format!(
468 "<wsu:Expires>{}</wsu:Expires>",
469 timestamp.expires.format("%Y-%m-%dT%H:%M:%S%.3fZ")
470 ));
471
472 xml.push_str("</wsu:Timestamp>");
473 xml
474 }
475
476 fn username_token_to_xml(&self, token: &UsernameToken) -> String {
478 let mut xml = String::new();
479
480 if let Some(ref id) = token.wsu_id {
481 xml.push_str(&format!(r#"<wsse:UsernameToken wsu:Id="{}">"#, id));
482 } else {
483 xml.push_str("<wsse:UsernameToken>");
484 }
485
486 xml.push_str(&format!(
487 "<wsse:Username>{}</wsse:Username>",
488 token.username
489 ));
490
491 if let Some(ref password) = token.password {
492 let type_attr = match password.password_type {
493 PasswordType::PasswordText => {
494 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"
495 }
496 PasswordType::PasswordDigest => {
497 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest"
498 }
499 };
500
501 xml.push_str(&format!(
502 r#"<wsse:Password Type="{}">{}</wsse:Password>"#,
503 type_attr, password.value
504 ));
505 }
506
507 if let Some(ref nonce) = token.nonce {
508 xml.push_str(&format!(
509 r#"<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">{}</wsse:Nonce>"#,
510 nonce
511 ));
512 }
513
514 if let Some(ref created) = token.created {
515 xml.push_str(&format!(
516 "<wsu:Created>{}</wsu:Created>",
517 created.format("%Y-%m-%dT%H:%M:%S%.3fZ")
518 ));
519 }
520
521 xml.push_str("</wsse:UsernameToken>");
522 xml
523 }
524
525 fn binary_security_token_to_xml(&self, token: &BinarySecurityToken) -> String {
527 let mut xml = String::new();
528
529 xml.push_str(&format!(
530 r#"<wsse:BinarySecurityToken ValueType="{}" EncodingType="{}""#,
531 token.value_type, token.encoding_type
532 ));
533
534 if let Some(ref id) = token.wsu_id {
535 xml.push_str(&format!(r#" wsu:Id="{}""#, id));
536 }
537
538 xml.push('>');
539 xml.push_str(&token.value);
540 xml.push_str("</wsse:BinarySecurityToken>");
541
542 xml
543 }
544
545 fn signature_to_xml(&self, signature: &WsSecuritySignature) -> String {
547 format!(
548 r#"<ds:Signature xmlns:ds="{}">
549 <ds:SignedInfo>
550 <ds:CanonicalizationMethod Algorithm="{}"/>
551 <ds:SignatureMethod Algorithm="{}"/>
552 {}
553 </ds:SignedInfo>
554 <ds:SignatureValue></ds:SignatureValue>
555 <ds:KeyInfo></ds:KeyInfo>
556 </ds:Signature>"#,
557 self.namespaces["ds"],
558 signature.canonicalization_method,
559 signature.signature_method,
560 signature
561 .references
562 .iter()
563 .map(|r| format!(
564 r#"<ds:Reference URI="{}">
565 <ds:Transforms>
566 {}
567 </ds:Transforms>
568 <ds:DigestMethod Algorithm="{}"/>
569 <ds:DigestValue></ds:DigestValue>
570 </ds:Reference>"#,
571 r.uri,
572 r.transforms
573 .iter()
574 .map(|t| format!(r#"<ds:Transform Algorithm="{}"/>"#, t))
575 .collect::<Vec<_>>()
576 .join(""),
577 signature.digest_method
578 ))
579 .collect::<Vec<_>>()
580 .join("")
581 )
582 }
583}
584
585impl Default for WsSecurityConfig {
586 fn default() -> Self {
587 Self {
588 include_timestamp: true,
589 timestamp_ttl: Duration::minutes(5),
590 sign_message: false,
591 elements_to_sign: vec!["Body".to_string(), "Timestamp".to_string()],
592 signing_certificate: None,
593 signing_private_key: None,
594 include_certificate: true,
595 saml_token_endpoint: None,
596 actor: None,
597 }
598 }
599}
600
601#[cfg(test)]
602mod tests {
603 use super::*;
604
605 #[test]
606 fn test_username_token_creation() {
607 let config = WsSecurityConfig::default();
608 let client = WsSecurityClient::new(config);
609
610 let header = client
611 .create_username_token_header("testuser", Some("testpass"), PasswordType::PasswordText)
612 .unwrap();
613
614 assert!(header.username_token.is_some());
615 let token = header.username_token.unwrap();
616 assert_eq!(token.username, "testuser");
617 assert!(token.password.is_some());
618 }
619
620 #[test]
621 fn test_password_digest() {
622 let config = WsSecurityConfig::default();
623 let client = WsSecurityClient::new(config);
624
625 let nonce = "MTIzNDU2Nzg5MDEyMzQ1Ng=="; let created = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
627 .unwrap()
628 .with_timezone(&Utc);
629 let password = "secret";
630
631 let digest = client
632 .compute_password_digest(password, nonce, &created)
633 .unwrap();
634 assert!(!digest.is_empty());
635 }
636
637 #[test]
638 fn test_timestamp_creation() {
639 let config = WsSecurityConfig::default();
640 let client = WsSecurityClient::new(config);
641
642 let timestamp = client.create_timestamp();
643 assert!(timestamp.expires > timestamp.created);
644 assert!(timestamp.wsu_id.is_some());
645 }
646
647 #[test]
648 fn test_xml_generation() {
649 let config = WsSecurityConfig::default();
650 let client = WsSecurityClient::new(config);
651
652 let header = client
653 .create_username_token_header("testuser", Some("testpass"), PasswordType::PasswordText)
654 .unwrap();
655
656 let xml = client.header_to_xml(&header).unwrap();
657 assert!(xml.contains("<wsse:Security"));
658 assert!(xml.contains("<wsse:UsernameToken"));
659 assert!(xml.contains("testuser"));
660 assert!(xml.contains("</wsse:Security>"));
661 }
662
663 #[test]
664 fn test_certificate_header() {
665 let config = WsSecurityConfig::default();
666 let client = WsSecurityClient::new(config);
667
668 let dummy_cert = b"dummy certificate data";
669 let header = client.create_certificate_header(dummy_cert).unwrap();
670
671 assert!(header.binary_security_token.is_some());
672 let bst = header.binary_security_token.unwrap();
673 assert_eq!(bst.value, STANDARD.encode(dummy_cert));
674 }
675}