1use crate::errors::{AuthError, Result};
7use crate::protocols::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
13fn xml_escape(s: &str) -> String {
15 let mut out = String::with_capacity(s.len());
16 for c in s.chars() {
17 match c {
18 '&' => out.push_str("&"),
19 '<' => out.push_str("<"),
20 '>' => out.push_str(">"),
21 '"' => out.push_str("""),
22 '\'' => out.push_str("'"),
23 _ => out.push(c),
24 }
25 }
26 out
27}
28
29#[derive(Debug, Clone, Default)]
31pub struct WsSecurityHeader {
32 pub username_token: Option<UsernameToken>,
34
35 pub timestamp: Option<Timestamp>,
37
38 pub binary_security_token: Option<BinarySecurityToken>,
40
41 pub saml_assertions: Vec<SamlAssertionRef>,
43
44 pub signature: Option<WsSecuritySignature>,
46
47 pub custom_elements: Vec<String>,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct UsernameToken {
54 pub username: String,
56
57 pub password: Option<UsernamePassword>,
59
60 pub nonce: Option<String>,
62
63 pub created: Option<DateTime<Utc>>,
65
66 pub wsu_id: Option<String>,
68}
69
70#[derive(Clone, Serialize, Deserialize)]
72pub struct UsernamePassword {
73 pub value: String,
75
76 pub password_type: PasswordType,
78}
79
80impl std::fmt::Debug for UsernamePassword {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 let mut d = f.debug_struct("UsernamePassword");
83 d.field("value", &crate::utils::redact::redacted(&self.value));
84 d.field("password_type", &self.password_type);
85 d.finish()
86 }
87}
88
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub enum PasswordType {
92 PasswordText,
94
95 PasswordDigest,
97}
98
99#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct Timestamp {
102 pub created: DateTime<Utc>,
104
105 pub expires: DateTime<Utc>,
107
108 pub wsu_id: Option<String>,
110}
111
112#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct BinarySecurityToken {
115 pub value: String,
117
118 pub value_type: String,
120
121 pub encoding_type: String,
123
124 pub wsu_id: Option<String>,
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct SamlAssertionRef {
131 pub assertion: SamlAssertion,
133
134 pub wsu_id: Option<String>,
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct WsSecuritySignature {
141 pub signature_method: String,
143
144 pub canonicalization_method: String,
146
147 pub digest_method: String,
149
150 pub references: Vec<SignatureReference>,
152
153 pub key_info: Option<KeyInfo>,
155
156 pub signature_value: Option<String>,
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize)]
162pub struct SignatureReference {
163 pub uri: String,
165
166 pub digest_value: String,
168
169 pub transforms: Vec<String>,
171}
172
173#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct KeyInfo {
176 pub security_token_reference: Option<String>,
178
179 pub key_value: Option<String>,
181
182 pub x509_data: Option<String>,
184}
185
186#[derive(Clone)]
188pub struct WsSecurityConfig {
189 pub include_timestamp: bool,
191
192 pub timestamp_ttl: Duration,
194
195 pub sign_message: bool,
197
198 pub elements_to_sign: Vec<String>,
200
201 pub signing_certificate: Option<Vec<u8>>,
203
204 pub signing_private_key: Option<Vec<u8>>,
206
207 pub include_certificate: bool,
209
210 pub saml_token_endpoint: Option<String>,
212
213 pub actor: Option<String>,
215}
216
217impl std::fmt::Debug for WsSecurityConfig {
218 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
219 let mut d = f.debug_struct("WsSecurityConfig");
220 d.field("include_timestamp", &self.include_timestamp);
221 d.field("timestamp_ttl", &self.timestamp_ttl);
222 d.field("sign_message", &self.sign_message);
223 d.field("elements_to_sign", &self.elements_to_sign);
224 d.field("signing_certificate", &self.signing_certificate);
225 d.field(
226 "signing_private_key",
227 &crate::utils::redact::redacted(&self.signing_private_key),
228 );
229 d.field("include_certificate", &self.include_certificate);
230 d.field("saml_token_endpoint", &self.saml_token_endpoint);
231 d.field("actor", &self.actor);
232 d.finish()
233 }
234}
235
236pub struct WsSecurityClient {
238 config: WsSecurityConfig,
240
241 namespaces: HashMap<String, String>,
243}
244
245impl WsSecurityClient {
246 pub fn new(config: WsSecurityConfig) -> Self {
248 let mut namespaces = HashMap::new();
249 namespaces.insert(
250 "wsse".to_string(),
251 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
252 .to_string(),
253 );
254 namespaces.insert(
255 "wsu".to_string(),
256 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
257 .to_string(),
258 );
259 namespaces.insert(
260 "ds".to_string(),
261 "http://www.w3.org/2000/09/xmldsig#".to_string(),
262 );
263 namespaces.insert(
264 "saml".to_string(),
265 "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
266 );
267
268 Self { config, namespaces }
269 }
270
271 pub fn create_username_token_header(
273 &self,
274 username: &str,
275 password: Option<&str>,
276 password_type: PasswordType,
277 ) -> Result<WsSecurityHeader> {
278 let mut header = WsSecurityHeader::default();
279
280 let (nonce, created) = if password_type == PasswordType::PasswordDigest {
281 (Some(self.generate_nonce()), Some(Utc::now()))
282 } else {
283 (None, None)
284 };
285
286 let password_element = if let Some(pwd) = password {
287 let pwd_value = match password_type {
288 PasswordType::PasswordText => pwd.to_string(),
289 PasswordType::PasswordDigest => self.compute_password_digest(
290 pwd,
291 nonce
292 .as_ref()
293 .expect("nonce is Some for PasswordDigest variant"),
294 &created.expect("created is Some for PasswordDigest variant"),
295 )?,
296 };
297
298 Some(UsernamePassword {
299 value: pwd_value,
300 password_type,
301 })
302 } else {
303 None
304 };
305
306 header.username_token = Some(UsernameToken {
307 username: username.to_string(),
308 password: password_element,
309 nonce,
310 created,
311 wsu_id: Some(format!("UsernameToken-{}", uuid::Uuid::new_v4())),
312 });
313
314 if self.config.include_timestamp {
315 header.timestamp = Some(self.create_timestamp());
316 }
317
318 Ok(header)
319 }
320
321 pub fn create_certificate_header(&self, certificate: &[u8]) -> Result<WsSecurityHeader> {
323 let mut header = WsSecurityHeader::default();
324
325 let cert_b64 = STANDARD.encode(certificate);
327
328 header.binary_security_token = Some(BinarySecurityToken {
329 value: cert_b64,
330 value_type: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3".to_string(),
331 encoding_type: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary".to_string(),
332 wsu_id: Some(format!("X509Token-{}", uuid::Uuid::new_v4())),
333 });
334
335 if self.config.include_timestamp {
336 header.timestamp = Some(self.create_timestamp());
337 }
338
339 if self.config.sign_message {
340 header.signature = Some(self.create_signature_template()?);
341 }
342
343 Ok(header)
344 }
345
346 pub fn create_saml_header(&self, assertion: SamlAssertion) -> Result<WsSecurityHeader> {
348 let mut header = WsSecurityHeader::default();
349
350 let assertion_ref = SamlAssertionRef {
351 assertion,
352 wsu_id: Some(format!("SamlAssertion-{}", uuid::Uuid::new_v4())),
353 };
354
355 header.saml_assertions.push(assertion_ref);
356
357 if self.config.include_timestamp {
358 header.timestamp = Some(self.create_timestamp());
359 }
360
361 Ok(header)
362 }
363 pub fn header_to_xml(&self, header: &WsSecurityHeader) -> Result<String> {
365 let mut xml = String::new();
366
367 xml.push_str(&format!(
369 r#"<wsse:Security xmlns:wsse="{}" xmlns:wsu="{}">"#,
370 self.namespaces["wsse"], self.namespaces["wsu"]
371 ));
372
373 if let Some(ref timestamp) = header.timestamp {
375 xml.push_str(&self.timestamp_to_xml(timestamp));
376 }
377
378 if let Some(ref username_token) = header.username_token {
380 xml.push_str(&self.username_token_to_xml(username_token));
381 }
382
383 if let Some(ref bst) = header.binary_security_token {
385 xml.push_str(&self.binary_security_token_to_xml(bst));
386 }
387
388 for assertion_ref in &header.saml_assertions {
390 let assertion_xml = assertion_ref.assertion.to_xml()?;
391 xml.push_str(&assertion_xml);
392 }
393
394 if let Some(ref signature) = header.signature {
396 xml.push_str(&self.signature_to_xml(signature));
397 }
398
399 xml.push_str("</wsse:Security>");
401
402 Ok(xml)
403 }
404
405 fn generate_nonce(&self) -> String {
407 use rand::Rng;
408 let mut rng = rand::rng();
409 let mut nonce = [0u8; 16];
410 rng.fill_bytes(&mut nonce);
411 STANDARD.encode(nonce)
412 }
413
414 fn compute_password_digest(
416 &self,
417 password: &str,
418 nonce: &str,
419 created: &DateTime<Utc>,
420 ) -> Result<String> {
421 use sha1::{Digest, Sha1};
422
423 let nonce_bytes = STANDARD
424 .decode(nonce)
425 .map_err(|_| AuthError::auth_method("ws_security", "Invalid nonce encoding"))?;
426 let created_str = created.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
427
428 let mut hasher = Sha1::new();
429 hasher.update(&nonce_bytes);
430 hasher.update(created_str.as_bytes());
431 hasher.update(password.as_bytes());
432
433 let digest = hasher.finalize();
434 Ok(STANDARD.encode(digest))
435 }
436
437 fn create_timestamp(&self) -> Timestamp {
439 let now = Utc::now();
440 let expires = now + self.config.timestamp_ttl;
441
442 Timestamp {
443 created: now,
444 expires,
445 wsu_id: Some(format!("Timestamp-{}", uuid::Uuid::new_v4())),
446 }
447 }
448
449 fn create_signature_template(&self) -> Result<WsSecuritySignature> {
451 Ok(WsSecuritySignature {
452 signature_method: "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256".to_string(),
457 canonicalization_method: "http://www.w3.org/2001/10/xml-exc-c14n#".to_string(),
458 digest_method: "http://www.w3.org/2001/04/xmlenc#sha256".to_string(),
459 references: self
460 .config
461 .elements_to_sign
462 .iter()
463 .map(|element| {
464 SignatureReference {
465 uri: format!("#{}", element),
466 digest_value: String::new(), transforms: vec!["http://www.w3.org/2001/10/xml-exc-c14n#".to_string()],
468 }
469 })
470 .collect(),
471 key_info: None, signature_value: None, })
474 }
475
476 fn timestamp_to_xml(&self, timestamp: &Timestamp) -> String {
478 let mut xml = String::new();
479
480 if let Some(ref id) = timestamp.wsu_id {
481 xml.push_str(&format!(r#"<wsu:Timestamp wsu:Id="{}">"#, id));
482 } else {
483 xml.push_str("<wsu:Timestamp>");
484 }
485
486 xml.push_str(&format!(
487 "<wsu:Created>{}</wsu:Created>",
488 timestamp.created.format("%Y-%m-%dT%H:%M:%S%.3fZ")
489 ));
490
491 xml.push_str(&format!(
492 "<wsu:Expires>{}</wsu:Expires>",
493 timestamp.expires.format("%Y-%m-%dT%H:%M:%S%.3fZ")
494 ));
495
496 xml.push_str("</wsu:Timestamp>");
497 xml
498 }
499
500 fn username_token_to_xml(&self, token: &UsernameToken) -> String {
502 let mut xml = String::new();
503
504 if let Some(ref id) = token.wsu_id {
505 xml.push_str(&format!(
506 r#"<wsse:UsernameToken wsu:Id="{}">"#,
507 xml_escape(id)
508 ));
509 } else {
510 xml.push_str("<wsse:UsernameToken>");
511 }
512
513 xml.push_str(&format!(
514 "<wsse:Username>{}</wsse:Username>",
515 xml_escape(&token.username)
516 ));
517
518 if let Some(ref password) = token.password {
519 let type_attr = match password.password_type {
520 PasswordType::PasswordText => {
521 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"
522 }
523 PasswordType::PasswordDigest => {
524 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest"
525 }
526 };
527
528 xml.push_str(&format!(
529 r#"<wsse:Password Type="{}">{}</wsse:Password>"#,
530 type_attr,
531 xml_escape(&password.value)
532 ));
533 }
534
535 if let Some(ref nonce) = token.nonce {
536 xml.push_str(&format!(
537 r#"<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">{}</wsse:Nonce>"#,
538 nonce
539 ));
540 }
541
542 if let Some(ref created) = token.created {
543 xml.push_str(&format!(
544 "<wsu:Created>{}</wsu:Created>",
545 created.format("%Y-%m-%dT%H:%M:%S%.3fZ")
546 ));
547 }
548
549 xml.push_str("</wsse:UsernameToken>");
550 xml
551 }
552
553 fn binary_security_token_to_xml(&self, token: &BinarySecurityToken) -> String {
555 let mut xml = String::new();
556
557 xml.push_str(&format!(
558 r#"<wsse:BinarySecurityToken ValueType="{}" EncodingType="{}""#,
559 token.value_type, token.encoding_type
560 ));
561
562 if let Some(ref id) = token.wsu_id {
563 xml.push_str(&format!(r#" wsu:Id="{}""#, id));
564 }
565
566 xml.push('>');
567 xml.push_str(&token.value);
568 xml.push_str("</wsse:BinarySecurityToken>");
569
570 xml
571 }
572
573 fn signature_to_xml(&self, signature: &WsSecuritySignature) -> String {
579 let references_xml: String = signature
581 .references
582 .iter()
583 .map(|r| {
584 let digest_value = if !r.digest_value.is_empty() {
585 r.digest_value.clone()
586 } else if let Some(ref key_bytes) = self.config.signing_private_key {
587 use ring::hmac;
590 let key = hmac::Key::new(hmac::HMAC_SHA256, key_bytes);
591 let tag = hmac::sign(&key, r.uri.as_bytes());
592 STANDARD.encode(tag.as_ref())
593 } else {
594 String::new()
595 };
596
597 format!(
598 r#"<ds:Reference URI="{}">
599 <ds:Transforms>
600 {}
601 </ds:Transforms>
602 <ds:DigestMethod Algorithm="{}"/>
603 <ds:DigestValue>{}</ds:DigestValue>
604 </ds:Reference>"#,
605 r.uri,
606 r.transforms
607 .iter()
608 .map(|t| format!(r#"<ds:Transform Algorithm="{}"/>"#, t))
609 .collect::<Vec<_>>()
610 .join(""),
611 signature.digest_method,
612 digest_value,
613 )
614 })
615 .collect::<Vec<_>>()
616 .join("");
617
618 let signed_info_xml = format!(
620 r#"<ds:SignedInfo>
621 <ds:CanonicalizationMethod Algorithm="{}"/>
622 <ds:SignatureMethod Algorithm="{}"/>
623 {}
624 </ds:SignedInfo>"#,
625 signature.canonicalization_method, signature.signature_method, references_xml,
626 );
627
628 let signature_value = if let Some(ref sv) = signature.signature_value {
630 sv.clone()
631 } else if let Some(ref key_bytes) = self.config.signing_private_key {
632 use ring::hmac;
633 let key = hmac::Key::new(hmac::HMAC_SHA256, key_bytes);
634 let tag = hmac::sign(&key, signed_info_xml.as_bytes());
635 STANDARD.encode(tag.as_ref())
636 } else {
637 String::new()
638 };
639
640 let key_info_xml = if let Some(ref ki) = signature.key_info {
642 let mut ki_xml = String::new();
643 if let Some(ref x509) = ki.x509_data {
644 ki_xml.push_str(&format!(
645 "<ds:X509Data><ds:X509Certificate>{}</ds:X509Certificate></ds:X509Data>",
646 x509
647 ));
648 }
649 if let Some(ref str_ref) = ki.security_token_reference {
650 ki_xml.push_str(&format!(
651 "<wsse:SecurityTokenReference>{}</wsse:SecurityTokenReference>",
652 str_ref
653 ));
654 }
655 if let Some(ref kv) = ki.key_value {
656 ki_xml.push_str(&format!("<ds:KeyValue>{}</ds:KeyValue>", kv));
657 }
658 ki_xml
659 } else if let Some(ref cert) = self.config.signing_certificate {
660 let cert_b64 = STANDARD.encode(cert);
661 format!(
662 "<ds:X509Data><ds:X509Certificate>{}</ds:X509Certificate></ds:X509Data>",
663 cert_b64
664 )
665 } else {
666 "<ds:KeyName>WS-Security-Signing-Key</ds:KeyName>".to_string()
667 };
668
669 format!(
670 r#"<ds:Signature xmlns:ds="{}">
671 {}
672 <ds:SignatureValue>{}</ds:SignatureValue>
673 <ds:KeyInfo>{}</ds:KeyInfo>
674 </ds:Signature>"#,
675 self.namespaces["ds"], signed_info_xml, signature_value, key_info_xml,
676 )
677 }
678}
679
680impl Default for WsSecurityConfig {
681 fn default() -> Self {
682 Self {
683 include_timestamp: true,
684 timestamp_ttl: Duration::minutes(5),
685 sign_message: false,
686 elements_to_sign: vec!["Body".to_string(), "Timestamp".to_string()],
687 signing_certificate: None,
688 signing_private_key: None,
689 include_certificate: true,
690 saml_token_endpoint: None,
691 actor: None,
692 }
693 }
694}
695
696impl WsSecurityConfig {
697 pub fn builder() -> WsSecurityConfigBuilder {
713 WsSecurityConfigBuilder::default()
714 }
715}
716
717#[derive(Debug, Clone, Default)]
721pub struct WsSecurityConfigBuilder {
722 config: WsSecurityConfig,
723}
724
725impl WsSecurityConfigBuilder {
726 pub fn include_timestamp(mut self, include: bool) -> Self {
728 self.config.include_timestamp = include;
729 self
730 }
731
732 pub fn timestamp_ttl(mut self, ttl: Duration) -> Self {
734 self.config.timestamp_ttl = ttl;
735 self
736 }
737
738 pub fn sign_message(mut self, sign: bool) -> Self {
740 self.config.sign_message = sign;
741 self
742 }
743
744 pub fn elements_to_sign(mut self, elements: Vec<String>) -> Self {
746 self.config.elements_to_sign = elements;
747 self
748 }
749
750 pub fn signing_certificate(mut self, cert: Vec<u8>) -> Self {
752 self.config.signing_certificate = Some(cert);
753 self
754 }
755
756 pub fn signing_private_key(mut self, key: Vec<u8>) -> Self {
758 self.config.signing_private_key = Some(key);
759 self
760 }
761
762 pub fn include_certificate(mut self, include: bool) -> Self {
764 self.config.include_certificate = include;
765 self
766 }
767
768 pub fn saml_token_endpoint(mut self, endpoint: impl Into<String>) -> Self {
770 self.config.saml_token_endpoint = Some(endpoint.into());
771 self
772 }
773
774 pub fn actor(mut self, actor: impl Into<String>) -> Self {
776 self.config.actor = Some(actor.into());
777 self
778 }
779
780 pub fn build(self) -> WsSecurityConfig {
782 self.config
783 }
784}
785
786#[cfg(test)]
787mod tests {
788 use super::*;
789
790 #[test]
793 fn password_digest_known_answer() {
794 let client = WsSecurityClient::new(WsSecurityConfig::default());
795 let created = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
796 .unwrap()
797 .with_timezone(&Utc);
798 let digest = client
799 .compute_password_digest("secret", "MTIzNDU2Nzg5MDEyMzQ1Ng==", &created)
800 .unwrap();
801 assert_eq!(digest, "Vt9uL71zN4npXMrjEzF3B/v5Yis=");
802 }
803
804 #[test]
805 fn test_username_token_creation() {
806 let config = WsSecurityConfig::default();
807 let client = WsSecurityClient::new(config);
808
809 let header = client
810 .create_username_token_header("testuser", Some("testpass"), PasswordType::PasswordText)
811 .unwrap();
812
813 assert!(header.username_token.is_some());
814 let token = header.username_token.unwrap();
815 assert_eq!(token.username, "testuser");
816 assert!(token.password.is_some());
817 }
818
819 #[test]
820 fn test_password_digest() {
821 let config = WsSecurityConfig::default();
822 let client = WsSecurityClient::new(config);
823
824 let nonce = "MTIzNDU2Nzg5MDEyMzQ1Ng=="; let created = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
826 .unwrap()
827 .with_timezone(&Utc);
828 let password = "secret";
829
830 let digest = client
831 .compute_password_digest(password, nonce, &created)
832 .unwrap();
833 assert!(!digest.is_empty());
834 }
835
836 #[test]
837 fn test_timestamp_creation() {
838 let config = WsSecurityConfig::default();
839 let client = WsSecurityClient::new(config);
840
841 let timestamp = client.create_timestamp();
842 assert!(timestamp.expires > timestamp.created);
843 assert!(timestamp.wsu_id.is_some());
844 }
845
846 #[test]
847 fn test_xml_generation() {
848 let config = WsSecurityConfig::default();
849 let client = WsSecurityClient::new(config);
850
851 let header = client
852 .create_username_token_header("testuser", Some("testpass"), PasswordType::PasswordText)
853 .unwrap();
854
855 let xml = client.header_to_xml(&header).unwrap();
856 assert!(xml.contains("<wsse:Security"));
857 assert!(xml.contains("<wsse:UsernameToken"));
858 assert!(xml.contains("testuser"));
859 assert!(xml.contains("</wsse:Security>"));
860 }
861
862 #[test]
863 fn test_certificate_header() {
864 let config = WsSecurityConfig::default();
865 let client = WsSecurityClient::new(config);
866
867 let dummy_cert = b"dummy certificate data";
868 let header = client.create_certificate_header(dummy_cert).unwrap();
869
870 assert!(header.binary_security_token.is_some());
871 let bst = header.binary_security_token.unwrap();
872 assert_eq!(bst.value, STANDARD.encode(dummy_cert));
873 }
874
875 #[test]
876 fn test_xml_escape_special_characters() {
877 assert_eq!(xml_escape("hello"), "hello");
878 assert_eq!(xml_escape("<script>"), "<script>");
879 assert_eq!(xml_escape("a&b"), "a&b");
880 assert_eq!(xml_escape("\"quoted\""), ""quoted"");
881 assert_eq!(xml_escape("it's"), "it's");
882 assert_eq!(
883 xml_escape("<user>&\"name'"),
884 "<user>&"name'"
885 );
886 }
887
888 #[test]
889 fn test_xml_escape_empty_and_normal() {
890 assert_eq!(xml_escape(""), "");
891 assert_eq!(xml_escape("normal_user123"), "normal_user123");
892 }
893
894 #[test]
895 fn test_username_token_xml_escapes_injection() {
896 let config = WsSecurityConfig::default();
897 let client = WsSecurityClient::new(config);
898
899 let header = client
901 .create_username_token_header(
902 "<script>alert(1)</script>",
903 Some("pass&word\""),
904 PasswordType::PasswordText,
905 )
906 .unwrap();
907
908 let xml = client.header_to_xml(&header).unwrap();
909 assert!(!xml.contains("<script>"));
911 assert!(xml.contains("<script>"));
912 assert!(xml.contains("pass&word""));
913 }
914}