Skip to main content

auth_framework/
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::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/// WS-Security Header builder
14#[derive(Debug, Clone, Default)]
15pub struct WsSecurityHeader {
16    /// Username token (if used)
17    pub username_token: Option<UsernameToken>,
18
19    /// Timestamp (if used)
20    pub timestamp: Option<Timestamp>,
21
22    /// Binary security token (X.509 certificate)
23    pub binary_security_token: Option<BinarySecurityToken>,
24
25    /// SAML assertions
26    pub saml_assertions: Vec<SamlAssertionRef>,
27
28    /// Signature elements
29    pub signature: Option<WsSecuritySignature>,
30
31    /// Additional custom elements
32    pub custom_elements: Vec<String>,
33}
34
35/// UsernameToken for basic authentication
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct UsernameToken {
38    /// Username
39    pub username: String,
40
41    /// Password (optional - can be omitted for cert-based auth)
42    pub password: Option<UsernamePassword>,
43
44    /// Nonce for replay protection
45    pub nonce: Option<String>,
46
47    /// Created timestamp
48    pub created: Option<DateTime<Utc>>,
49
50    /// WSU ID for referencing in signatures
51    pub wsu_id: Option<String>,
52}
53
54/// Password element with type
55#[derive(Clone, Serialize, Deserialize)]
56pub struct UsernamePassword {
57    /// Password value
58    pub value: String,
59
60    /// Password type (PasswordText or PasswordDigest)
61    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/// Password types for UsernameToken
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub enum PasswordType {
76    /// Plain text password (not recommended)
77    PasswordText,
78
79    /// SHA-1 digest of password, nonce, and created time
80    PasswordDigest,
81}
82
83/// Timestamp for message freshness
84#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct Timestamp {
86    /// When the message was created
87    pub created: DateTime<Utc>,
88
89    /// When the message expires
90    pub expires: DateTime<Utc>,
91
92    /// WSU ID for referencing in signatures
93    pub wsu_id: Option<String>,
94}
95
96/// Binary Security Token (typically X.509 certificate)
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct BinarySecurityToken {
99    /// Token value (base64 encoded certificate)
100    pub value: String,
101
102    /// Value type (X.509 certificate identifier)
103    pub value_type: String,
104
105    /// Encoding type (Base64Binary)
106    pub encoding_type: String,
107
108    /// WSU ID for referencing
109    pub wsu_id: Option<String>,
110}
111
112/// SAML Assertion for identity/attribute exchange
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct SamlAssertionRef {
115    /// Reference to the SAML assertion
116    pub assertion: SamlAssertion,
117
118    /// WSU ID for referencing in signatures
119    pub wsu_id: Option<String>,
120}
121
122/// WS-Security Signature
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct WsSecuritySignature {
125    /// Signature method algorithm
126    pub signature_method: String,
127
128    /// Canonicalization method
129    pub canonicalization_method: String,
130
131    /// Digest method
132    pub digest_method: String,
133
134    /// References to signed elements
135    pub references: Vec<SignatureReference>,
136
137    /// Key info (certificate reference)
138    pub key_info: Option<KeyInfo>,
139
140    /// Signature value
141    pub signature_value: Option<String>,
142}
143
144/// Reference to a signed element
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct SignatureReference {
147    /// URI reference to the element
148    pub uri: String,
149
150    /// Digest value
151    pub digest_value: String,
152
153    /// Transforms applied
154    pub transforms: Vec<String>,
155}
156
157/// Key information for signature verification
158#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct KeyInfo {
160    /// Reference to security token
161    pub security_token_reference: Option<String>,
162
163    /// Direct key value
164    pub key_value: Option<String>,
165
166    /// X.509 certificate data
167    pub x509_data: Option<String>,
168}
169
170/// WS-Security configuration
171#[derive(Clone)]
172pub struct WsSecurityConfig {
173    /// Whether to include timestamp
174    pub include_timestamp: bool,
175
176    /// Timestamp TTL
177    pub timestamp_ttl: Duration,
178
179    /// Whether to sign the message
180    pub sign_message: bool,
181
182    /// Elements to sign (by local name)
183    pub elements_to_sign: Vec<String>,
184
185    /// Certificate for signing (PEM format)
186    pub signing_certificate: Option<Vec<u8>>,
187
188    /// Private key for signing (PEM format)
189    pub signing_private_key: Option<Vec<u8>>,
190
191    /// Whether to include certificate in message
192    pub include_certificate: bool,
193
194    /// SAML token provider endpoint
195    pub saml_token_endpoint: Option<String>,
196
197    /// Actor value for delegation scenarios
198    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
220/// WS-Security client for generating secure SOAP headers
221pub struct WsSecurityClient {
222    /// Configuration
223    config: WsSecurityConfig,
224
225    /// XML namespace prefixes
226    namespaces: HashMap<String, String>,
227}
228
229impl WsSecurityClient {
230    /// Create a new WS-Security client
231    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    /// Create WS-Security header with UsernameToken
256    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    /// Create WS-Security header with X.509 certificate
302    pub fn create_certificate_header(&self, certificate: &[u8]) -> Result<WsSecurityHeader> {
303        let mut header = WsSecurityHeader::default();
304
305        // Encode certificate as base64
306        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    /// Create WS-Security header with SAML assertion
327    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    /// Convert WS-Security header to XML
344    pub fn header_to_xml(&self, header: &WsSecurityHeader) -> Result<String> {
345        let mut xml = String::new();
346
347        // Start Security header
348        xml.push_str(&format!(
349            r#"<wsse:Security xmlns:wsse="{}" xmlns:wsu="{}">"#,
350            self.namespaces["wsse"], self.namespaces["wsu"]
351        ));
352
353        // Add timestamp
354        if let Some(ref timestamp) = header.timestamp {
355            xml.push_str(&self.timestamp_to_xml(timestamp));
356        }
357
358        // Add username token
359        if let Some(ref username_token) = header.username_token {
360            xml.push_str(&self.username_token_to_xml(username_token));
361        }
362
363        // Add binary security token
364        if let Some(ref bst) = header.binary_security_token {
365            xml.push_str(&self.binary_security_token_to_xml(bst));
366        }
367
368        // Add SAML assertions
369        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        // Add signature
375        if let Some(ref signature) = header.signature {
376            xml.push_str(&self.signature_to_xml(signature));
377        }
378
379        // End Security header
380        xml.push_str("</wsse:Security>");
381
382        Ok(xml)
383    }
384
385    /// Generate a random nonce
386    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    /// Compute password digest (SHA-1 of nonce + created + password)
395    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    /// Create timestamp element
418    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    /// Create signature template
430    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(), // Will be computed during signing
443                        transforms: vec!["http://www.w3.org/2001/10/xml-exc-c14n#".to_string()],
444                    }
445                })
446                .collect(),
447            key_info: None,        // Will be set based on certificate
448            signature_value: None, // Will be computed during signing
449        })
450    }
451
452    /// Convert timestamp to XML
453    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    /// Convert username token to XML
477    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    /// Convert binary security token to XML
526    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    /// Convert signature to XML (simplified template)
546    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=="; // base64 of "1234567890123456"
626        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}