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(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
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/// Password types for UsernameToken
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub enum PasswordType {
92    /// Plain text password (not recommended)
93    PasswordText,
94
95    /// SHA-1 digest of password, nonce, and created time
96    PasswordDigest,
97}
98
99/// Timestamp for message freshness
100#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct Timestamp {
102    /// When the message was created
103    pub created: DateTime<Utc>,
104
105    /// When the message expires
106    pub expires: DateTime<Utc>,
107
108    /// WSU ID for referencing in signatures
109    pub wsu_id: Option<String>,
110}
111
112/// Binary Security Token (typically X.509 certificate)
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct BinarySecurityToken {
115    /// Token value (base64 encoded certificate)
116    pub value: String,
117
118    /// Value type (X.509 certificate identifier)
119    pub value_type: String,
120
121    /// Encoding type (Base64Binary)
122    pub encoding_type: String,
123
124    /// WSU ID for referencing
125    pub wsu_id: Option<String>,
126}
127
128/// SAML Assertion for identity/attribute exchange
129#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct SamlAssertionRef {
131    /// Reference to the SAML assertion
132    pub assertion: SamlAssertion,
133
134    /// WSU ID for referencing in signatures
135    pub wsu_id: Option<String>,
136}
137
138/// WS-Security Signature
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct WsSecuritySignature {
141    /// Signature method algorithm
142    pub signature_method: String,
143
144    /// Canonicalization method
145    pub canonicalization_method: String,
146
147    /// Digest method
148    pub digest_method: String,
149
150    /// References to signed elements
151    pub references: Vec<SignatureReference>,
152
153    /// Key info (certificate reference)
154    pub key_info: Option<KeyInfo>,
155
156    /// Signature value
157    pub signature_value: Option<String>,
158}
159
160/// Reference to a signed element
161#[derive(Debug, Clone, Serialize, Deserialize)]
162pub struct SignatureReference {
163    /// URI reference to the element
164    pub uri: String,
165
166    /// Digest value
167    pub digest_value: String,
168
169    /// Transforms applied
170    pub transforms: Vec<String>,
171}
172
173/// Key information for signature verification
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct KeyInfo {
176    /// Reference to security token
177    pub security_token_reference: Option<String>,
178
179    /// Direct key value
180    pub key_value: Option<String>,
181
182    /// X.509 certificate data
183    pub x509_data: Option<String>,
184}
185
186/// WS-Security configuration
187#[derive(Clone)]
188pub struct WsSecurityConfig {
189    /// Whether to include timestamp
190    pub include_timestamp: bool,
191
192    /// Timestamp TTL
193    pub timestamp_ttl: Duration,
194
195    /// Whether to sign the message
196    pub sign_message: bool,
197
198    /// Elements to sign (by local name)
199    pub elements_to_sign: Vec<String>,
200
201    /// Certificate for signing (PEM format)
202    pub signing_certificate: Option<Vec<u8>>,
203
204    /// Private key for signing (PEM format)
205    pub signing_private_key: Option<Vec<u8>>,
206
207    /// Whether to include certificate in message
208    pub include_certificate: bool,
209
210    /// SAML token provider endpoint
211    pub saml_token_endpoint: Option<String>,
212
213    /// Actor value for delegation scenarios
214    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
236/// WS-Security client for generating secure SOAP headers
237pub struct WsSecurityClient {
238    /// Configuration
239    config: WsSecurityConfig,
240
241    /// XML namespace prefixes
242    namespaces: HashMap<String, String>,
243}
244
245impl WsSecurityClient {
246    /// Create a new WS-Security client
247    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    /// Create WS-Security header with UsernameToken
272    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    /// Create WS-Security header with X.509 certificate
322    pub fn create_certificate_header(&self, certificate: &[u8]) -> Result<WsSecurityHeader> {
323        let mut header = WsSecurityHeader::default();
324
325        // Encode certificate as base64
326        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    /// Create WS-Security header with SAML assertion
347    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    /// Convert WS-Security header to XML
364    pub fn header_to_xml(&self, header: &WsSecurityHeader) -> Result<String> {
365        let mut xml = String::new();
366
367        // Start Security header
368        xml.push_str(&format!(
369            r#"<wsse:Security xmlns:wsse="{}" xmlns:wsu="{}">"#,
370            self.namespaces["wsse"], self.namespaces["wsu"]
371        ));
372
373        // Add timestamp
374        if let Some(ref timestamp) = header.timestamp {
375            xml.push_str(&self.timestamp_to_xml(timestamp));
376        }
377
378        // Add username token
379        if let Some(ref username_token) = header.username_token {
380            xml.push_str(&self.username_token_to_xml(username_token));
381        }
382
383        // Add binary security token
384        if let Some(ref bst) = header.binary_security_token {
385            xml.push_str(&self.binary_security_token_to_xml(bst));
386        }
387
388        // Add SAML assertions
389        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        // Add signature
395        if let Some(ref signature) = header.signature {
396            xml.push_str(&self.signature_to_xml(signature));
397        }
398
399        // End Security header
400        xml.push_str("</wsse:Security>");
401
402        Ok(xml)
403    }
404
405    /// Generate a random nonce
406    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    /// Compute password digest (SHA-1 of nonce + created + password)
415    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    /// Create timestamp element
438    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    /// Create signature template
450    fn create_signature_template(&self) -> Result<WsSecuritySignature> {
451        Ok(WsSecuritySignature {
452            // Using HMAC-SHA256 as the signing algorithm (matches the actual
453            // ring::hmac::HMAC_SHA256 implementation in signature_to_xml).
454            // For RSA-SHA256, an RSA key pair would need to be loaded and
455            // ring::signature::RsaKeyPair used for signing.
456            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(), // Will be computed during signing
467                        transforms: vec!["http://www.w3.org/2001/10/xml-exc-c14n#".to_string()],
468                    }
469                })
470                .collect(),
471            key_info: None,        // Will be set based on certificate
472            signature_value: None, // Will be computed during signing
473        })
474    }
475
476    /// Convert timestamp to XML
477    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    /// Convert username token to XML
501    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    /// Convert binary security token to XML
554    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    /// Convert signature to XML
574    ///
575    /// Computes HMAC-SHA256 digests for each reference and the overall signature
576    /// value when a signing key is available via `config.signing_private_key`.
577    /// Without a key, digest and signature values are left empty (template-only mode).
578    fn signature_to_xml(&self, signature: &WsSecuritySignature) -> String {
579        // Compute per-reference digest values and the concatenated SignedInfo content
580        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                    // Compute HMAC-SHA256 digest of the reference URI as a stand-in
588                    // for the canonicalized referenced element content.
589                    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        // Build the SignedInfo block for signing
619        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        // Compute the signature value over SignedInfo
629        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        // Build KeyInfo: use certificate if available, otherwise a key name
641        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    /// Create a new builder for `WsSecurityConfig`, starting from defaults.
698    ///
699    /// # Example
700    ///
701    /// ```rust,no_run
702    /// use auth_framework::protocols::ws_security::WsSecurityConfig;
703    /// # let cert_pem: Vec<u8> = vec![];
704    /// # let key_pem: Vec<u8> = vec![];
705    ///
706    /// let config = WsSecurityConfig::builder()
707    ///     .sign_message(true)
708    ///     .signing_certificate(cert_pem.clone())
709    ///     .signing_private_key(key_pem.clone())
710    ///     .build();
711    /// ```
712    pub fn builder() -> WsSecurityConfigBuilder {
713        WsSecurityConfigBuilder::default()
714    }
715}
716
717/// A builder for [`WsSecurityConfig`].
718///
719/// Obtain via [`WsSecurityConfig::builder()`].
720#[derive(Debug, Clone, Default)]
721pub struct WsSecurityConfigBuilder {
722    config: WsSecurityConfig,
723}
724
725impl WsSecurityConfigBuilder {
726    /// Set whether to include a timestamp in the security header.
727    pub fn include_timestamp(mut self, include: bool) -> Self {
728        self.config.include_timestamp = include;
729        self
730    }
731
732    /// Set the timestamp TTL (time-to-live).
733    pub fn timestamp_ttl(mut self, ttl: Duration) -> Self {
734        self.config.timestamp_ttl = ttl;
735        self
736    }
737
738    /// Set whether to sign the message.
739    pub fn sign_message(mut self, sign: bool) -> Self {
740        self.config.sign_message = sign;
741        self
742    }
743
744    /// Set which XML elements to sign (by local name).
745    pub fn elements_to_sign(mut self, elements: Vec<String>) -> Self {
746        self.config.elements_to_sign = elements;
747        self
748    }
749
750    /// Set the signing certificate (PEM-encoded bytes).
751    pub fn signing_certificate(mut self, cert: Vec<u8>) -> Self {
752        self.config.signing_certificate = Some(cert);
753        self
754    }
755
756    /// Set the signing private key (PEM-encoded bytes).
757    pub fn signing_private_key(mut self, key: Vec<u8>) -> Self {
758        self.config.signing_private_key = Some(key);
759        self
760    }
761
762    /// Set whether to include the certificate in the security header.
763    pub fn include_certificate(mut self, include: bool) -> Self {
764        self.config.include_certificate = include;
765        self
766    }
767
768    /// Set the SAML token provider endpoint URL.
769    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    /// Set the actor value for delegation scenarios.
775    pub fn actor(mut self, actor: impl Into<String>) -> Self {
776        self.config.actor = Some(actor.into());
777        self
778    }
779
780    /// Build the [`WsSecurityConfig`].
781    pub fn build(self) -> WsSecurityConfig {
782        self.config
783    }
784}
785
786#[cfg(test)]
787mod tests {
788    use super::*;
789
790    /// WS-Security password digest = Base64(SHA-1(nonce || created || password)); fixed inputs give a
791    /// fixed value on every version of the digest crate.
792    #[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=="; // base64 of "1234567890123456"
825        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>"), "&lt;script&gt;");
879        assert_eq!(xml_escape("a&b"), "a&amp;b");
880        assert_eq!(xml_escape("\"quoted\""), "&quot;quoted&quot;");
881        assert_eq!(xml_escape("it's"), "it&apos;s");
882        assert_eq!(
883            xml_escape("<user>&\"name'"),
884            "&lt;user&gt;&amp;&quot;name&apos;"
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        // Create a header with an XML-injection username
900        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        // Verify the injection attempts are escaped in the XML output
910        assert!(!xml.contains("<script>"));
911        assert!(xml.contains("&lt;script&gt;"));
912        assert!(xml.contains("pass&amp;word&quot;"));
913    }
914}