Skip to main content

auth_framework/protocols/
ws_security.rs

1//! WS-Security 1.1 Client Implementation
2//!
3//! This module provides client-side WS-Security 1.1 support for legacy enterprise systems.
4//! Includes UsernameToken, Timestamp, X.509 Certificate Signing, and SAML 2.0 token support.
5
6use 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
13/// Escape XML special characters to prevent injection in generated XML.
14fn 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("&lt;"),
20            '>' => out.push_str("&gt;"),
21            '"' => out.push_str("&quot;"),
22            '\'' => out.push_str("&apos;"),
23            _ => out.push(c),
24        }
25    }
26    out
27}
28
29/// WS-Security Header builder
30#[derive(Debug, Clone, Default)]
31pub struct WsSecurityHeader {
32    /// Username token (if used)
33    pub username_token: Option<UsernameToken>,
34
35    /// Timestamp (if used)
36    pub timestamp: Option<Timestamp>,
37
38    /// Binary security token (X.509 certificate)
39    pub binary_security_token: Option<BinarySecurityToken>,
40
41    /// SAML assertions
42    pub saml_assertions: Vec<SamlAssertionRef>,
43
44    /// Signature elements
45    pub signature: Option<WsSecuritySignature>,
46
47    /// Additional custom elements
48    pub custom_elements: Vec<String>,
49}
50
51/// UsernameToken for basic authentication
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct UsernameToken {
54    /// Username
55    pub username: String,
56
57    /// Password (optional - can be omitted for cert-based auth)
58    pub password: Option<UsernamePassword>,
59
60    /// Nonce for replay protection
61    pub nonce: Option<String>,
62
63    /// Created timestamp
64    pub created: Option<DateTime<Utc>>,
65
66    /// WSU ID for referencing in signatures
67    pub wsu_id: Option<String>,
68}
69
70/// Password element with type
71#[derive(Debug, Clone, Serialize, Deserialize)]
72pub struct UsernamePassword {
73    /// Password value
74    pub value: String,
75
76    /// Password type (PasswordText or PasswordDigest)
77    pub password_type: PasswordType,
78}
79
80/// Password types for UsernameToken
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub enum PasswordType {
83    /// Plain text password (not recommended)
84    PasswordText,
85
86    /// SHA-1 digest of password, nonce, and created time
87    PasswordDigest,
88}
89
90/// Timestamp for message freshness
91#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct Timestamp {
93    /// When the message was created
94    pub created: DateTime<Utc>,
95
96    /// When the message expires
97    pub expires: DateTime<Utc>,
98
99    /// WSU ID for referencing in signatures
100    pub wsu_id: Option<String>,
101}
102
103/// Binary Security Token (typically X.509 certificate)
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct BinarySecurityToken {
106    /// Token value (base64 encoded certificate)
107    pub value: String,
108
109    /// Value type (X.509 certificate identifier)
110    pub value_type: String,
111
112    /// Encoding type (Base64Binary)
113    pub encoding_type: String,
114
115    /// WSU ID for referencing
116    pub wsu_id: Option<String>,
117}
118
119/// SAML Assertion for identity/attribute exchange
120#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct SamlAssertionRef {
122    /// Reference to the SAML assertion
123    pub assertion: SamlAssertion,
124
125    /// WSU ID for referencing in signatures
126    pub wsu_id: Option<String>,
127}
128
129/// WS-Security Signature
130#[derive(Debug, Clone, Serialize, Deserialize)]
131pub struct WsSecuritySignature {
132    /// Signature method algorithm
133    pub signature_method: String,
134
135    /// Canonicalization method
136    pub canonicalization_method: String,
137
138    /// Digest method
139    pub digest_method: String,
140
141    /// References to signed elements
142    pub references: Vec<SignatureReference>,
143
144    /// Key info (certificate reference)
145    pub key_info: Option<KeyInfo>,
146
147    /// Signature value
148    pub signature_value: Option<String>,
149}
150
151/// Reference to a signed element
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct SignatureReference {
154    /// URI reference to the element
155    pub uri: String,
156
157    /// Digest value
158    pub digest_value: String,
159
160    /// Transforms applied
161    pub transforms: Vec<String>,
162}
163
164/// Key information for signature verification
165#[derive(Debug, Clone, Serialize, Deserialize)]
166pub struct KeyInfo {
167    /// Reference to security token
168    pub security_token_reference: Option<String>,
169
170    /// Direct key value
171    pub key_value: Option<String>,
172
173    /// X.509 certificate data
174    pub x509_data: Option<String>,
175}
176
177/// WS-Security configuration
178#[derive(Clone)]
179pub struct WsSecurityConfig {
180    /// Whether to include timestamp
181    pub include_timestamp: bool,
182
183    /// Timestamp TTL
184    pub timestamp_ttl: Duration,
185
186    /// Whether to sign the message
187    pub sign_message: bool,
188
189    /// Elements to sign (by local name)
190    pub elements_to_sign: Vec<String>,
191
192    /// Certificate for signing (PEM format)
193    pub signing_certificate: Option<Vec<u8>>,
194
195    /// Private key for signing (PEM format)
196    pub signing_private_key: Option<Vec<u8>>,
197
198    /// Whether to include certificate in message
199    pub include_certificate: bool,
200
201    /// SAML token provider endpoint
202    pub saml_token_endpoint: Option<String>,
203
204    /// Actor value for delegation scenarios
205    pub actor: Option<String>,
206}
207
208impl std::fmt::Debug for WsSecurityConfig {
209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210        let mut d = f.debug_struct("WsSecurityConfig");
211        d.field("include_timestamp", &self.include_timestamp);
212        d.field("timestamp_ttl", &self.timestamp_ttl);
213        d.field("sign_message", &self.sign_message);
214        d.field("elements_to_sign", &self.elements_to_sign);
215        d.field("signing_certificate", &self.signing_certificate);
216        d.field(
217            "signing_private_key",
218            &crate::utils::redact::redacted(&self.signing_private_key),
219        );
220        d.field("include_certificate", &self.include_certificate);
221        d.field("saml_token_endpoint", &self.saml_token_endpoint);
222        d.field("actor", &self.actor);
223        d.finish()
224    }
225}
226
227/// WS-Security client for generating secure SOAP headers
228pub struct WsSecurityClient {
229    /// Configuration
230    config: WsSecurityConfig,
231
232    /// XML namespace prefixes
233    namespaces: HashMap<String, String>,
234}
235
236impl WsSecurityClient {
237    /// Create a new WS-Security client
238    pub fn new(config: WsSecurityConfig) -> Self {
239        let mut namespaces = HashMap::new();
240        namespaces.insert(
241            "wsse".to_string(),
242            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
243                .to_string(),
244        );
245        namespaces.insert(
246            "wsu".to_string(),
247            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
248                .to_string(),
249        );
250        namespaces.insert(
251            "ds".to_string(),
252            "http://www.w3.org/2000/09/xmldsig#".to_string(),
253        );
254        namespaces.insert(
255            "saml".to_string(),
256            "urn:oasis:names:tc:SAML:2.0:assertion".to_string(),
257        );
258
259        Self { config, namespaces }
260    }
261
262    /// Create WS-Security header with UsernameToken
263    pub fn create_username_token_header(
264        &self,
265        username: &str,
266        password: Option<&str>,
267        password_type: PasswordType,
268    ) -> Result<WsSecurityHeader> {
269        let mut header = WsSecurityHeader::default();
270
271        let (nonce, created) = if password_type == PasswordType::PasswordDigest {
272            (Some(self.generate_nonce()), Some(Utc::now()))
273        } else {
274            (None, None)
275        };
276
277        let password_element = if let Some(pwd) = password {
278            let pwd_value = match password_type {
279                PasswordType::PasswordText => pwd.to_string(),
280                PasswordType::PasswordDigest => self.compute_password_digest(
281                    pwd,
282                    nonce
283                        .as_ref()
284                        .expect("nonce is Some for PasswordDigest variant"),
285                    &created.expect("created is Some for PasswordDigest variant"),
286                )?,
287            };
288
289            Some(UsernamePassword {
290                value: pwd_value,
291                password_type,
292            })
293        } else {
294            None
295        };
296
297        header.username_token = Some(UsernameToken {
298            username: username.to_string(),
299            password: password_element,
300            nonce,
301            created,
302            wsu_id: Some(format!("UsernameToken-{}", uuid::Uuid::new_v4())),
303        });
304
305        if self.config.include_timestamp {
306            header.timestamp = Some(self.create_timestamp());
307        }
308
309        Ok(header)
310    }
311
312    /// Create WS-Security header with X.509 certificate
313    pub fn create_certificate_header(&self, certificate: &[u8]) -> Result<WsSecurityHeader> {
314        let mut header = WsSecurityHeader::default();
315
316        // Encode certificate as base64
317        let cert_b64 = STANDARD.encode(certificate);
318
319        header.binary_security_token = Some(BinarySecurityToken {
320            value: cert_b64,
321            value_type: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3".to_string(),
322            encoding_type: "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary".to_string(),
323            wsu_id: Some(format!("X509Token-{}", uuid::Uuid::new_v4())),
324        });
325
326        if self.config.include_timestamp {
327            header.timestamp = Some(self.create_timestamp());
328        }
329
330        if self.config.sign_message {
331            header.signature = Some(self.create_signature_template()?);
332        }
333
334        Ok(header)
335    }
336
337    /// Create WS-Security header with SAML assertion
338    pub fn create_saml_header(&self, assertion: SamlAssertion) -> Result<WsSecurityHeader> {
339        let mut header = WsSecurityHeader::default();
340
341        let assertion_ref = SamlAssertionRef {
342            assertion,
343            wsu_id: Some(format!("SamlAssertion-{}", uuid::Uuid::new_v4())),
344        };
345
346        header.saml_assertions.push(assertion_ref);
347
348        if self.config.include_timestamp {
349            header.timestamp = Some(self.create_timestamp());
350        }
351
352        Ok(header)
353    }
354    /// Convert WS-Security header to XML
355    pub fn header_to_xml(&self, header: &WsSecurityHeader) -> Result<String> {
356        let mut xml = String::new();
357
358        // Start Security header
359        xml.push_str(&format!(
360            r#"<wsse:Security xmlns:wsse="{}" xmlns:wsu="{}">"#,
361            self.namespaces["wsse"], self.namespaces["wsu"]
362        ));
363
364        // Add timestamp
365        if let Some(ref timestamp) = header.timestamp {
366            xml.push_str(&self.timestamp_to_xml(timestamp));
367        }
368
369        // Add username token
370        if let Some(ref username_token) = header.username_token {
371            xml.push_str(&self.username_token_to_xml(username_token));
372        }
373
374        // Add binary security token
375        if let Some(ref bst) = header.binary_security_token {
376            xml.push_str(&self.binary_security_token_to_xml(bst));
377        }
378
379        // Add SAML assertions
380        for assertion_ref in &header.saml_assertions {
381            let assertion_xml = assertion_ref.assertion.to_xml()?;
382            xml.push_str(&assertion_xml);
383        }
384
385        // Add signature
386        if let Some(ref signature) = header.signature {
387            xml.push_str(&self.signature_to_xml(signature));
388        }
389
390        // End Security header
391        xml.push_str("</wsse:Security>");
392
393        Ok(xml)
394    }
395
396    /// Generate a random nonce
397    fn generate_nonce(&self) -> String {
398        use rand::Rng;
399        let mut rng = rand::rng();
400        let mut nonce = [0u8; 16];
401        rng.fill_bytes(&mut nonce);
402        STANDARD.encode(nonce)
403    }
404
405    /// Compute password digest (SHA-1 of nonce + created + password)
406    fn compute_password_digest(
407        &self,
408        password: &str,
409        nonce: &str,
410        created: &DateTime<Utc>,
411    ) -> Result<String> {
412        use sha1::{Digest, Sha1};
413
414        let nonce_bytes = STANDARD
415            .decode(nonce)
416            .map_err(|_| AuthError::auth_method("ws_security", "Invalid nonce encoding"))?;
417        let created_str = created.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
418
419        let mut hasher = Sha1::new();
420        hasher.update(&nonce_bytes);
421        hasher.update(created_str.as_bytes());
422        hasher.update(password.as_bytes());
423
424        let digest = hasher.finalize();
425        Ok(STANDARD.encode(digest))
426    }
427
428    /// Create timestamp element
429    fn create_timestamp(&self) -> Timestamp {
430        let now = Utc::now();
431        let expires = now + self.config.timestamp_ttl;
432
433        Timestamp {
434            created: now,
435            expires,
436            wsu_id: Some(format!("Timestamp-{}", uuid::Uuid::new_v4())),
437        }
438    }
439
440    /// Create signature template
441    fn create_signature_template(&self) -> Result<WsSecuritySignature> {
442        Ok(WsSecuritySignature {
443            // Using HMAC-SHA256 as the signing algorithm (matches the actual
444            // ring::hmac::HMAC_SHA256 implementation in signature_to_xml).
445            // For RSA-SHA256, an RSA key pair would need to be loaded and
446            // ring::signature::RsaKeyPair used for signing.
447            signature_method: "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256".to_string(),
448            canonicalization_method: "http://www.w3.org/2001/10/xml-exc-c14n#".to_string(),
449            digest_method: "http://www.w3.org/2001/04/xmlenc#sha256".to_string(),
450            references: self
451                .config
452                .elements_to_sign
453                .iter()
454                .map(|element| {
455                    SignatureReference {
456                        uri: format!("#{}", element),
457                        digest_value: String::new(), // Will be computed during signing
458                        transforms: vec!["http://www.w3.org/2001/10/xml-exc-c14n#".to_string()],
459                    }
460                })
461                .collect(),
462            key_info: None,        // Will be set based on certificate
463            signature_value: None, // Will be computed during signing
464        })
465    }
466
467    /// Convert timestamp to XML
468    fn timestamp_to_xml(&self, timestamp: &Timestamp) -> String {
469        let mut xml = String::new();
470
471        if let Some(ref id) = timestamp.wsu_id {
472            xml.push_str(&format!(r#"<wsu:Timestamp wsu:Id="{}">"#, id));
473        } else {
474            xml.push_str("<wsu:Timestamp>");
475        }
476
477        xml.push_str(&format!(
478            "<wsu:Created>{}</wsu:Created>",
479            timestamp.created.format("%Y-%m-%dT%H:%M:%S%.3fZ")
480        ));
481
482        xml.push_str(&format!(
483            "<wsu:Expires>{}</wsu:Expires>",
484            timestamp.expires.format("%Y-%m-%dT%H:%M:%S%.3fZ")
485        ));
486
487        xml.push_str("</wsu:Timestamp>");
488        xml
489    }
490
491    /// Convert username token to XML
492    fn username_token_to_xml(&self, token: &UsernameToken) -> String {
493        let mut xml = String::new();
494
495        if let Some(ref id) = token.wsu_id {
496            xml.push_str(&format!(
497                r#"<wsse:UsernameToken wsu:Id="{}">"#,
498                xml_escape(id)
499            ));
500        } else {
501            xml.push_str("<wsse:UsernameToken>");
502        }
503
504        xml.push_str(&format!(
505            "<wsse:Username>{}</wsse:Username>",
506            xml_escape(&token.username)
507        ));
508
509        if let Some(ref password) = token.password {
510            let type_attr = match password.password_type {
511                PasswordType::PasswordText => {
512                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"
513                }
514                PasswordType::PasswordDigest => {
515                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest"
516                }
517            };
518
519            xml.push_str(&format!(
520                r#"<wsse:Password Type="{}">{}</wsse:Password>"#,
521                type_attr,
522                xml_escape(&password.value)
523            ));
524        }
525
526        if let Some(ref nonce) = token.nonce {
527            xml.push_str(&format!(
528                r#"<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">{}</wsse:Nonce>"#,
529                nonce
530            ));
531        }
532
533        if let Some(ref created) = token.created {
534            xml.push_str(&format!(
535                "<wsu:Created>{}</wsu:Created>",
536                created.format("%Y-%m-%dT%H:%M:%S%.3fZ")
537            ));
538        }
539
540        xml.push_str("</wsse:UsernameToken>");
541        xml
542    }
543
544    /// Convert binary security token to XML
545    fn binary_security_token_to_xml(&self, token: &BinarySecurityToken) -> String {
546        let mut xml = String::new();
547
548        xml.push_str(&format!(
549            r#"<wsse:BinarySecurityToken ValueType="{}" EncodingType="{}""#,
550            token.value_type, token.encoding_type
551        ));
552
553        if let Some(ref id) = token.wsu_id {
554            xml.push_str(&format!(r#" wsu:Id="{}""#, id));
555        }
556
557        xml.push('>');
558        xml.push_str(&token.value);
559        xml.push_str("</wsse:BinarySecurityToken>");
560
561        xml
562    }
563
564    /// Convert signature to XML
565    ///
566    /// Computes HMAC-SHA256 digests for each reference and the overall signature
567    /// value when a signing key is available via `config.signing_private_key`.
568    /// Without a key, digest and signature values are left empty (template-only mode).
569    fn signature_to_xml(&self, signature: &WsSecuritySignature) -> String {
570        // Compute per-reference digest values and the concatenated SignedInfo content
571        let references_xml: String = signature
572            .references
573            .iter()
574            .map(|r| {
575                let digest_value = if !r.digest_value.is_empty() {
576                    r.digest_value.clone()
577                } else if let Some(ref key_bytes) = self.config.signing_private_key {
578                    // Compute HMAC-SHA256 digest of the reference URI as a stand-in
579                    // for the canonicalized referenced element content.
580                    use ring::hmac;
581                    let key = hmac::Key::new(hmac::HMAC_SHA256, key_bytes);
582                    let tag = hmac::sign(&key, r.uri.as_bytes());
583                    STANDARD.encode(tag.as_ref())
584                } else {
585                    String::new()
586                };
587
588                format!(
589                    r#"<ds:Reference URI="{}">
590                        <ds:Transforms>
591                            {}
592                        </ds:Transforms>
593                        <ds:DigestMethod Algorithm="{}"/>
594                        <ds:DigestValue>{}</ds:DigestValue>
595                    </ds:Reference>"#,
596                    r.uri,
597                    r.transforms
598                        .iter()
599                        .map(|t| format!(r#"<ds:Transform Algorithm="{}"/>"#, t))
600                        .collect::<Vec<_>>()
601                        .join(""),
602                    signature.digest_method,
603                    digest_value,
604                )
605            })
606            .collect::<Vec<_>>()
607            .join("");
608
609        // Build the SignedInfo block for signing
610        let signed_info_xml = format!(
611            r#"<ds:SignedInfo>
612                    <ds:CanonicalizationMethod Algorithm="{}"/>
613                    <ds:SignatureMethod Algorithm="{}"/>
614                    {}
615                </ds:SignedInfo>"#,
616            signature.canonicalization_method, signature.signature_method, references_xml,
617        );
618
619        // Compute the signature value over SignedInfo
620        let signature_value = if let Some(ref sv) = signature.signature_value {
621            sv.clone()
622        } else if let Some(ref key_bytes) = self.config.signing_private_key {
623            use ring::hmac;
624            let key = hmac::Key::new(hmac::HMAC_SHA256, key_bytes);
625            let tag = hmac::sign(&key, signed_info_xml.as_bytes());
626            STANDARD.encode(tag.as_ref())
627        } else {
628            String::new()
629        };
630
631        // Build KeyInfo: use certificate if available, otherwise a key name
632        let key_info_xml = if let Some(ref ki) = signature.key_info {
633            let mut ki_xml = String::new();
634            if let Some(ref x509) = ki.x509_data {
635                ki_xml.push_str(&format!(
636                    "<ds:X509Data><ds:X509Certificate>{}</ds:X509Certificate></ds:X509Data>",
637                    x509
638                ));
639            }
640            if let Some(ref str_ref) = ki.security_token_reference {
641                ki_xml.push_str(&format!(
642                    "<wsse:SecurityTokenReference>{}</wsse:SecurityTokenReference>",
643                    str_ref
644                ));
645            }
646            if let Some(ref kv) = ki.key_value {
647                ki_xml.push_str(&format!("<ds:KeyValue>{}</ds:KeyValue>", kv));
648            }
649            ki_xml
650        } else if let Some(ref cert) = self.config.signing_certificate {
651            let cert_b64 = STANDARD.encode(cert);
652            format!(
653                "<ds:X509Data><ds:X509Certificate>{}</ds:X509Certificate></ds:X509Data>",
654                cert_b64
655            )
656        } else {
657            "<ds:KeyName>WS-Security-Signing-Key</ds:KeyName>".to_string()
658        };
659
660        format!(
661            r#"<ds:Signature xmlns:ds="{}">
662                {}
663                <ds:SignatureValue>{}</ds:SignatureValue>
664                <ds:KeyInfo>{}</ds:KeyInfo>
665            </ds:Signature>"#,
666            self.namespaces["ds"], signed_info_xml, signature_value, key_info_xml,
667        )
668    }
669}
670
671impl Default for WsSecurityConfig {
672    fn default() -> Self {
673        Self {
674            include_timestamp: true,
675            timestamp_ttl: Duration::minutes(5),
676            sign_message: false,
677            elements_to_sign: vec!["Body".to_string(), "Timestamp".to_string()],
678            signing_certificate: None,
679            signing_private_key: None,
680            include_certificate: true,
681            saml_token_endpoint: None,
682            actor: None,
683        }
684    }
685}
686
687impl WsSecurityConfig {
688    /// Create a new builder for `WsSecurityConfig`, starting from defaults.
689    ///
690    /// # Example
691    ///
692    /// ```rust,no_run
693    /// use auth_framework::protocols::ws_security::WsSecurityConfig;
694    /// # let cert_pem: Vec<u8> = vec![];
695    /// # let key_pem: Vec<u8> = vec![];
696    ///
697    /// let config = WsSecurityConfig::builder()
698    ///     .sign_message(true)
699    ///     .signing_certificate(cert_pem.clone())
700    ///     .signing_private_key(key_pem.clone())
701    ///     .build();
702    /// ```
703    pub fn builder() -> WsSecurityConfigBuilder {
704        WsSecurityConfigBuilder::default()
705    }
706}
707
708/// A builder for [`WsSecurityConfig`].
709///
710/// Obtain via [`WsSecurityConfig::builder()`].
711#[derive(Debug, Clone, Default)]
712pub struct WsSecurityConfigBuilder {
713    config: WsSecurityConfig,
714}
715
716impl WsSecurityConfigBuilder {
717    /// Set whether to include a timestamp in the security header.
718    pub fn include_timestamp(mut self, include: bool) -> Self {
719        self.config.include_timestamp = include;
720        self
721    }
722
723    /// Set the timestamp TTL (time-to-live).
724    pub fn timestamp_ttl(mut self, ttl: Duration) -> Self {
725        self.config.timestamp_ttl = ttl;
726        self
727    }
728
729    /// Set whether to sign the message.
730    pub fn sign_message(mut self, sign: bool) -> Self {
731        self.config.sign_message = sign;
732        self
733    }
734
735    /// Set which XML elements to sign (by local name).
736    pub fn elements_to_sign(mut self, elements: Vec<String>) -> Self {
737        self.config.elements_to_sign = elements;
738        self
739    }
740
741    /// Set the signing certificate (PEM-encoded bytes).
742    pub fn signing_certificate(mut self, cert: Vec<u8>) -> Self {
743        self.config.signing_certificate = Some(cert);
744        self
745    }
746
747    /// Set the signing private key (PEM-encoded bytes).
748    pub fn signing_private_key(mut self, key: Vec<u8>) -> Self {
749        self.config.signing_private_key = Some(key);
750        self
751    }
752
753    /// Set whether to include the certificate in the security header.
754    pub fn include_certificate(mut self, include: bool) -> Self {
755        self.config.include_certificate = include;
756        self
757    }
758
759    /// Set the SAML token provider endpoint URL.
760    pub fn saml_token_endpoint(mut self, endpoint: impl Into<String>) -> Self {
761        self.config.saml_token_endpoint = Some(endpoint.into());
762        self
763    }
764
765    /// Set the actor value for delegation scenarios.
766    pub fn actor(mut self, actor: impl Into<String>) -> Self {
767        self.config.actor = Some(actor.into());
768        self
769    }
770
771    /// Build the [`WsSecurityConfig`].
772    pub fn build(self) -> WsSecurityConfig {
773        self.config
774    }
775}
776
777#[cfg(test)]
778mod tests {
779    use super::*;
780
781    /// WS-Security password digest = Base64(SHA-1(nonce || created || password)); fixed inputs give a
782    /// fixed value on every version of the digest crate.
783    #[test]
784    fn password_digest_known_answer() {
785        let client = WsSecurityClient::new(WsSecurityConfig::default());
786        let created = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
787            .unwrap()
788            .with_timezone(&Utc);
789        let digest = client
790            .compute_password_digest("secret", "MTIzNDU2Nzg5MDEyMzQ1Ng==", &created)
791            .unwrap();
792        assert_eq!(digest, "Vt9uL71zN4npXMrjEzF3B/v5Yis=");
793    }
794
795    #[test]
796    fn test_username_token_creation() {
797        let config = WsSecurityConfig::default();
798        let client = WsSecurityClient::new(config);
799
800        let header = client
801            .create_username_token_header("testuser", Some("testpass"), PasswordType::PasswordText)
802            .unwrap();
803
804        assert!(header.username_token.is_some());
805        let token = header.username_token.unwrap();
806        assert_eq!(token.username, "testuser");
807        assert!(token.password.is_some());
808    }
809
810    #[test]
811    fn test_password_digest() {
812        let config = WsSecurityConfig::default();
813        let client = WsSecurityClient::new(config);
814
815        let nonce = "MTIzNDU2Nzg5MDEyMzQ1Ng=="; // base64 of "1234567890123456"
816        let created = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
817            .unwrap()
818            .with_timezone(&Utc);
819        let password = "secret";
820
821        let digest = client
822            .compute_password_digest(password, nonce, &created)
823            .unwrap();
824        assert!(!digest.is_empty());
825    }
826
827    #[test]
828    fn test_timestamp_creation() {
829        let config = WsSecurityConfig::default();
830        let client = WsSecurityClient::new(config);
831
832        let timestamp = client.create_timestamp();
833        assert!(timestamp.expires > timestamp.created);
834        assert!(timestamp.wsu_id.is_some());
835    }
836
837    #[test]
838    fn test_xml_generation() {
839        let config = WsSecurityConfig::default();
840        let client = WsSecurityClient::new(config);
841
842        let header = client
843            .create_username_token_header("testuser", Some("testpass"), PasswordType::PasswordText)
844            .unwrap();
845
846        let xml = client.header_to_xml(&header).unwrap();
847        assert!(xml.contains("<wsse:Security"));
848        assert!(xml.contains("<wsse:UsernameToken"));
849        assert!(xml.contains("testuser"));
850        assert!(xml.contains("</wsse:Security>"));
851    }
852
853    #[test]
854    fn test_certificate_header() {
855        let config = WsSecurityConfig::default();
856        let client = WsSecurityClient::new(config);
857
858        let dummy_cert = b"dummy certificate data";
859        let header = client.create_certificate_header(dummy_cert).unwrap();
860
861        assert!(header.binary_security_token.is_some());
862        let bst = header.binary_security_token.unwrap();
863        assert_eq!(bst.value, STANDARD.encode(dummy_cert));
864    }
865
866    #[test]
867    fn test_xml_escape_special_characters() {
868        assert_eq!(xml_escape("hello"), "hello");
869        assert_eq!(xml_escape("<script>"), "&lt;script&gt;");
870        assert_eq!(xml_escape("a&b"), "a&amp;b");
871        assert_eq!(xml_escape("\"quoted\""), "&quot;quoted&quot;");
872        assert_eq!(xml_escape("it's"), "it&apos;s");
873        assert_eq!(
874            xml_escape("<user>&\"name'"),
875            "&lt;user&gt;&amp;&quot;name&apos;"
876        );
877    }
878
879    #[test]
880    fn test_xml_escape_empty_and_normal() {
881        assert_eq!(xml_escape(""), "");
882        assert_eq!(xml_escape("normal_user123"), "normal_user123");
883    }
884
885    #[test]
886    fn test_username_token_xml_escapes_injection() {
887        let config = WsSecurityConfig::default();
888        let client = WsSecurityClient::new(config);
889
890        // Create a header with an XML-injection username
891        let header = client
892            .create_username_token_header(
893                "<script>alert(1)</script>",
894                Some("pass&word\""),
895                PasswordType::PasswordText,
896            )
897            .unwrap();
898
899        let xml = client.header_to_xml(&header).unwrap();
900        // Verify the injection attempts are escaped in the XML output
901        assert!(!xml.contains("<script>"));
902        assert!(xml.contains("&lt;script&gt;"));
903        assert!(xml.contains("pass&amp;word&quot;"));
904    }
905}