Skip to main content

auth_framework/protocols/
saml_assertions.rs

1//! SAML 2.0 Assertion Support for WS-Security
2//!
3//! This module provides SAML 2.0 assertion generation and validation for WS-Security scenarios.
4
5use crate::errors::{AuthError, Result};
6use chrono::{DateTime, Duration, Utc};
7use serde::{Deserialize, Serialize};
8
9/// Escape user-provided values for safe inclusion in XML text and attributes.
10fn xml_escape(s: &str) -> String {
11    let mut out = String::with_capacity(s.len());
12    for c in s.chars() {
13        match c {
14            '&' => out.push_str("&"),
15            '<' => out.push_str("&lt;"),
16            '>' => out.push_str("&gt;"),
17            '"' => out.push_str("&quot;"),
18            '\'' => out.push_str("&apos;"),
19            _ => out.push(c),
20        }
21    }
22    out
23}
24
25/// SAML 2.0 Assertion
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct SamlAssertion {
28    /// Assertion ID
29    pub id: String,
30
31    /// Issuer of the assertion
32    pub issuer: String,
33
34    /// Issue instant
35    pub issue_instant: DateTime<Utc>,
36
37    /// Version (always "2.0" for SAML 2.0)
38    pub version: String,
39
40    /// Subject information
41    pub subject: Option<SamlSubject>,
42
43    /// Conditions (validity constraints)
44    pub conditions: Option<SamlConditions>,
45
46    /// Attribute statements
47    pub attribute_statements: Vec<SamlAttributeStatement>,
48
49    /// Authentication statements
50    pub authn_statements: Vec<SamlAuthnStatement>,
51
52    /// Authorization decision statements
53    pub authz_decision_statements: Vec<SamlAuthzDecisionStatement>,
54}
55
56/// SAML Subject
57#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct SamlSubject {
59    /// Name identifier
60    pub name_id: Option<SamlNameId>,
61
62    /// Subject confirmations
63    pub subject_confirmations: Vec<SamlSubjectConfirmation>,
64}
65
66/// SAML Name Identifier
67#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct SamlNameId {
69    /// Value of the name identifier
70    pub value: String,
71
72    /// Format of the name identifier
73    pub format: Option<String>,
74
75    /// Name qualifier
76    pub name_qualifier: Option<String>,
77
78    /// SP name qualifier
79    pub sp_name_qualifier: Option<String>,
80}
81
82/// SAML Subject Confirmation
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct SamlSubjectConfirmation {
85    /// Method (bearer, holder-of-key, etc.)
86    pub method: String,
87
88    /// Subject confirmation data
89    pub subject_confirmation_data: Option<SamlSubjectConfirmationData>,
90}
91
92/// SAML Subject Confirmation Data
93#[derive(Debug, Clone, Serialize, Deserialize)]
94pub struct SamlSubjectConfirmationData {
95    /// Not before timestamp
96    pub not_before: Option<DateTime<Utc>>,
97
98    /// Not on or after timestamp
99    pub not_on_or_after: Option<DateTime<Utc>>,
100
101    /// Recipient URL
102    pub recipient: Option<String>,
103
104    /// In response to (for response assertions)
105    pub in_response_to: Option<String>,
106
107    /// Address restriction
108    pub address: Option<String>,
109}
110
111/// SAML Conditions
112#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct SamlConditions {
114    /// Not before timestamp
115    pub not_before: Option<DateTime<Utc>>,
116
117    /// Not on or after timestamp
118    pub not_on_or_after: Option<DateTime<Utc>>,
119
120    /// Audience restrictions
121    pub audience_restrictions: Vec<SamlAudienceRestriction>,
122
123    /// One time use
124    pub one_time_use: bool,
125
126    /// Proxy restrictions
127    pub proxy_restriction: Option<SamlProxyRestriction>,
128}
129
130/// SAML Audience Restriction
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct SamlAudienceRestriction {
133    /// Audience URIs
134    pub audiences: Vec<String>,
135}
136
137/// SAML Proxy Restriction
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct SamlProxyRestriction {
140    /// Count limit
141    pub count: Option<u32>,
142
143    /// Allowed audiences
144    pub audiences: Vec<String>,
145}
146
147/// SAML Attribute Statement
148#[derive(Debug, Clone, Serialize, Deserialize)]
149pub struct SamlAttributeStatement {
150    /// Attributes
151    pub attributes: Vec<SamlAttribute>,
152
153    /// Encrypted attributes
154    pub encrypted_attributes: Vec<String>, // Would be proper encrypted elements in production
155}
156
157/// SAML Attribute
158#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct SamlAttribute {
160    /// Attribute name
161    pub name: String,
162
163    /// Name format
164    pub name_format: Option<String>,
165
166    /// Friendly name
167    pub friendly_name: Option<String>,
168
169    /// Attribute values
170    pub values: Vec<SamlAttributeValue>,
171}
172
173/// SAML Attribute Value
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct SamlAttributeValue {
176    /// Value content
177    pub value: String,
178
179    /// Type information
180    pub type_info: Option<String>,
181}
182
183/// SAML Authentication Statement
184#[derive(Debug, Clone, Serialize, Deserialize)]
185pub struct SamlAuthnStatement {
186    /// Authentication instant
187    pub authn_instant: DateTime<Utc>,
188
189    /// Session index
190    pub session_index: Option<String>,
191
192    /// Session not on or after
193    pub session_not_on_or_after: Option<DateTime<Utc>>,
194
195    /// Authentication context
196    pub authn_context: SamlAuthnContext,
197
198    /// Subject locality
199    pub subject_locality: Option<SamlSubjectLocality>,
200}
201
202/// SAML Authentication Context
203#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct SamlAuthnContext {
205    /// Authentication context class reference
206    pub authn_context_class_ref: Option<String>,
207
208    /// Authentication context declaration
209    pub authn_context_decl: Option<String>,
210
211    /// Authentication context declaration reference
212    pub authn_context_decl_ref: Option<String>,
213
214    /// Authenticating authorities
215    pub authenticating_authorities: Vec<String>,
216}
217
218/// SAML Subject Locality
219#[derive(Debug, Clone, Serialize, Deserialize)]
220pub struct SamlSubjectLocality {
221    /// IP address
222    pub address: Option<String>,
223
224    /// DNS name
225    pub dns_name: Option<String>,
226}
227
228/// SAML Authorization Decision Statement
229#[derive(Debug, Clone, Serialize, Deserialize)]
230pub struct SamlAuthzDecisionStatement {
231    /// Resource being accessed
232    pub resource: String,
233
234    /// Decision (Permit, Deny, Indeterminate)
235    pub decision: SamlDecision,
236
237    /// Actions being performed
238    pub actions: Vec<SamlAction>,
239
240    /// Evidence supporting the decision
241    pub evidence: Option<SamlEvidence>,
242}
243
244/// SAML Decision
245#[derive(Debug, Clone, Serialize, Deserialize)]
246pub enum SamlDecision {
247    /// Access permitted
248    Permit,
249
250    /// Access denied
251    Deny,
252
253    /// Decision cannot be made
254    Indeterminate,
255}
256
257/// SAML Action
258#[derive(Debug, Clone, Serialize, Deserialize)]
259pub struct SamlAction {
260    /// Action value
261    pub value: String,
262
263    /// Action namespace
264    pub namespace: Option<String>,
265}
266
267/// SAML Evidence
268#[derive(Debug, Clone, Serialize, Deserialize)]
269pub struct SamlEvidence {
270    /// Supporting assertions
271    pub assertions: Vec<String>, // References to other assertions
272
273    /// Assertion ID references
274    pub assertion_id_refs: Vec<String>,
275
276    /// Assertion URI references
277    pub assertion_uri_refs: Vec<String>,
278}
279
280/// SAML Assertion Builder
281pub struct SamlAssertionBuilder {
282    /// Current assertion being built
283    assertion: SamlAssertion,
284}
285
286/// SAML Assertion Validator
287pub struct SamlAssertionValidator {
288    /// Allowed clock skew
289    clock_skew: Duration,
290
291    /// Trusted issuers
292    trusted_issuers: Vec<String>,
293
294    /// Expected audiences
295    expected_audiences: Vec<String>,
296}
297
298impl SamlAssertionBuilder {
299    /// Create a new SAML assertion builder
300    pub fn new(issuer: &str) -> Self {
301        let assertion = SamlAssertion {
302            id: format!("_{}", uuid::Uuid::new_v4()),
303            issuer: issuer.to_string(),
304            issue_instant: Utc::now(),
305            version: "2.0".to_string(),
306            subject: None,
307            conditions: None,
308            attribute_statements: Vec::new(),
309            authn_statements: Vec::new(),
310            authz_decision_statements: Vec::new(),
311        };
312
313        Self { assertion }
314    }
315
316    /// Set the subject
317    pub fn with_subject(mut self, subject: SamlSubject) -> Self {
318        self.assertion.subject = Some(subject);
319        self
320    }
321
322    /// Set conditions
323    pub fn with_conditions(mut self, conditions: SamlConditions) -> Self {
324        self.assertion.conditions = Some(conditions);
325        self
326    }
327
328    /// Add an attribute statement
329    pub fn with_attribute_statement(mut self, statement: SamlAttributeStatement) -> Self {
330        self.assertion.attribute_statements.push(statement);
331        self
332    }
333
334    /// Add an authentication statement
335    pub fn with_authn_statement(mut self, statement: SamlAuthnStatement) -> Self {
336        self.assertion.authn_statements.push(statement);
337        self
338    }
339
340    /// Add an authorization decision statement
341    pub fn with_authz_decision_statement(mut self, statement: SamlAuthzDecisionStatement) -> Self {
342        self.assertion.authz_decision_statements.push(statement);
343        self
344    }
345
346    /// Add a simple attribute
347    pub fn with_attribute(mut self, name: &str, value: &str) -> Self {
348        let attribute = SamlAttribute {
349            name: name.to_string(),
350            name_format: Some("urn:oasis:names:tc:SAML:2.0:attrname-format:basic".to_string()),
351            friendly_name: None,
352            values: vec![SamlAttributeValue {
353                value: value.to_string(),
354                type_info: None,
355            }],
356        };
357
358        // Find or create attribute statement
359        if self.assertion.attribute_statements.is_empty() {
360            self.assertion
361                .attribute_statements
362                .push(SamlAttributeStatement {
363                    attributes: vec![attribute],
364                    encrypted_attributes: Vec::new(),
365                });
366        } else {
367            self.assertion.attribute_statements[0]
368                .attributes
369                .push(attribute);
370        }
371
372        self
373    }
374
375    /// Set validity period
376    pub fn with_validity_period(
377        mut self,
378        not_before: DateTime<Utc>,
379        not_on_or_after: DateTime<Utc>,
380    ) -> Self {
381        if let Some(ref mut conditions) = self.assertion.conditions {
382            // Update existing conditions
383            conditions.not_before = Some(not_before);
384            conditions.not_on_or_after = Some(not_on_or_after);
385        } else {
386            // Create new conditions
387            let conditions = SamlConditions {
388                not_before: Some(not_before),
389                not_on_or_after: Some(not_on_or_after),
390                audience_restrictions: Vec::new(),
391                one_time_use: false,
392                proxy_restriction: None,
393            };
394            self.assertion.conditions = Some(conditions);
395        }
396        self
397    }
398
399    /// Add audience restriction
400    pub fn with_audience(mut self, audience: &str) -> Self {
401        if let Some(ref mut conditions) = self.assertion.conditions {
402            if conditions.audience_restrictions.is_empty() {
403                conditions
404                    .audience_restrictions
405                    .push(SamlAudienceRestriction {
406                        audiences: vec![audience.to_string()],
407                    });
408            } else {
409                conditions.audience_restrictions[0]
410                    .audiences
411                    .push(audience.to_string());
412            }
413        } else {
414            let conditions = SamlConditions {
415                not_before: None,
416                not_on_or_after: None,
417                audience_restrictions: vec![SamlAudienceRestriction {
418                    audiences: vec![audience.to_string()],
419                }],
420                one_time_use: false,
421                proxy_restriction: None,
422            };
423            self.assertion.conditions = Some(conditions);
424        }
425
426        self
427    }
428
429    /// Build the assertion
430    pub fn build(self) -> SamlAssertion {
431        self.assertion
432    }
433
434    /// Build and convert to XML
435    pub fn build_xml(self) -> Result<String> {
436        let assertion = self.assertion;
437        assertion.to_xml()
438    }
439}
440
441impl SamlAssertionValidator {
442    /// Create a new SAML assertion validator
443    pub fn new() -> Self {
444        Self {
445            clock_skew: Duration::minutes(5),
446            trusted_issuers: Vec::new(),
447            expected_audiences: Vec::new(),
448        }
449    }
450
451    /// Set clock skew tolerance
452    pub fn with_clock_skew(mut self, skew: Duration) -> Self {
453        self.clock_skew = skew;
454        self
455    }
456
457    /// Add trusted issuer
458    pub fn with_trusted_issuer(mut self, issuer: &str) -> Self {
459        self.trusted_issuers.push(issuer.to_string());
460        self
461    }
462
463    /// Add expected audience
464    pub fn with_expected_audience(mut self, audience: &str) -> Self {
465        self.expected_audiences.push(audience.to_string());
466        self
467    }
468
469    /// Validate a SAML assertion
470    pub fn validate(&self, assertion: &SamlAssertion) -> Result<()> {
471        // Check issuer
472        if !self.trusted_issuers.is_empty() && !self.trusted_issuers.contains(&assertion.issuer) {
473            return Err(AuthError::auth_method("saml", "Untrusted issuer"));
474        }
475
476        // Check time validity
477        self.validate_timing(assertion)?;
478
479        // Check audience restrictions
480        self.validate_audience(assertion)?;
481
482        // Check subject confirmation (if present)
483        if let Some(ref subject) = assertion.subject {
484            self.validate_subject_confirmation(subject)?;
485        }
486
487        Ok(())
488    }
489
490    /// Validate timing constraints
491    fn validate_timing(&self, assertion: &SamlAssertion) -> Result<()> {
492        let now = Utc::now();
493
494        // Check issue instant (shouldn't be too far in the future)
495        if assertion.issue_instant > now + self.clock_skew {
496            return Err(AuthError::auth_method(
497                "saml",
498                "Assertion issued in the future",
499            ));
500        }
501
502        // Check conditions timing
503        if let Some(ref conditions) = assertion.conditions {
504            if let Some(not_before) = conditions.not_before
505                && now < not_before - self.clock_skew
506            {
507                return Err(AuthError::auth_method("saml", "Assertion not yet valid"));
508            }
509
510            if let Some(not_on_or_after) = conditions.not_on_or_after
511                && now >= not_on_or_after + self.clock_skew
512            {
513                return Err(AuthError::auth_method("saml", "Assertion has expired"));
514            }
515        }
516
517        Ok(())
518    }
519
520    /// Validate audience restrictions
521    fn validate_audience(&self, assertion: &SamlAssertion) -> Result<()> {
522        if self.expected_audiences.is_empty() {
523            return Ok(());
524        }
525
526        if let Some(ref conditions) = assertion.conditions {
527            for restriction in &conditions.audience_restrictions {
528                for audience in &restriction.audiences {
529                    if self.expected_audiences.contains(audience) {
530                        return Ok(());
531                    }
532                }
533            }
534
535            if !conditions.audience_restrictions.is_empty() {
536                return Err(AuthError::auth_method("saml", "No matching audience found"));
537            }
538        }
539
540        Ok(())
541    }
542
543    /// Validate subject confirmation.
544    ///
545    /// Verifies each `SubjectConfirmation` element:
546    /// - The Method is a recognised SAML 2.0 confirmation method.
547    /// - If `NotOnOrAfter` is present it has not passed (accounting for clock skew).
548    /// - If `Recipient` is present it matches one of the expected audiences.
549    fn validate_subject_confirmation(&self, subject: &SamlSubject) -> Result<()> {
550        const ALLOWED_METHODS: &[&str] = &[
551            "urn:oasis:names:tc:SAML:2.0:cm:bearer",
552            "urn:oasis:names:tc:SAML:2.0:cm:holder-of-key",
553            "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches",
554        ];
555
556        for confirmation in &subject.subject_confirmations {
557            // 1. Method must be recognised.
558            if !ALLOWED_METHODS.contains(&confirmation.method.as_str()) {
559                return Err(AuthError::auth_method(
560                    "saml",
561                    &format!(
562                        "Unsupported subject confirmation method: {}",
563                        confirmation.method
564                    ),
565                ));
566            }
567
568            // 2. Check SubjectConfirmationData constraints (if present).
569            if let Some(ref data) = confirmation.subject_confirmation_data {
570                let now = Utc::now();
571
572                // NotOnOrAfter must not have passed.
573                if let Some(not_on_or_after) = data.not_on_or_after {
574                    if now >= not_on_or_after + self.clock_skew {
575                        return Err(AuthError::auth_method(
576                            "saml",
577                            "Subject confirmation has expired (NotOnOrAfter)",
578                        ));
579                    }
580                }
581
582                // NotBefore must have passed.
583                if let Some(not_before) = data.not_before {
584                    if now < not_before - self.clock_skew {
585                        return Err(AuthError::auth_method(
586                            "saml",
587                            "Subject confirmation is not yet valid (NotBefore)",
588                        ));
589                    }
590                }
591
592                // Recipient must match one of our expected audiences (if we have any).
593                if let Some(ref recipient) = data.recipient {
594                    if !self.expected_audiences.is_empty()
595                        && !self.expected_audiences.contains(recipient)
596                    {
597                        return Err(AuthError::auth_method(
598                            "saml",
599                            "Subject confirmation recipient does not match expected audience",
600                        ));
601                    }
602                }
603            }
604        }
605
606        Ok(())
607    }
608}
609
610impl SamlAssertion {
611    /// Convert assertion to XML
612    pub fn to_xml(&self) -> Result<String> {
613        let mut xml = String::new();
614
615        xml.push_str(&format!(
616            r#"<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="{}" IssueInstant="{}" Version="{}">"#,
617            xml_escape(&self.id),
618            self.issue_instant.format("%Y-%m-%dT%H:%M:%S%.3fZ"),
619            xml_escape(&self.version)
620        ));
621
622        // Issuer
623        xml.push_str(&format!(
624            "<saml:Issuer>{}</saml:Issuer>",
625            xml_escape(&self.issuer)
626        ));
627
628        // Subject
629        if let Some(ref subject) = self.subject {
630            xml.push_str(&subject.to_xml()?);
631        }
632
633        // Conditions
634        if let Some(ref conditions) = self.conditions {
635            xml.push_str(&conditions.to_xml()?);
636        }
637
638        // Attribute statements
639        for statement in &self.attribute_statements {
640            xml.push_str(&statement.to_xml()?);
641        }
642
643        // Authentication statements
644        for statement in &self.authn_statements {
645            xml.push_str(&statement.to_xml()?);
646        }
647
648        // Authorization decision statements
649        for statement in &self.authz_decision_statements {
650            xml.push_str(&statement.to_xml()?);
651        }
652
653        xml.push_str("</saml:Assertion>");
654
655        Ok(xml)
656    }
657}
658
659impl SamlSubject {
660    /// Convert subject to XML
661    pub fn to_xml(&self) -> Result<String> {
662        let mut xml = String::new();
663
664        xml.push_str("<saml:Subject>");
665
666        if let Some(ref name_id) = self.name_id {
667            xml.push_str(&name_id.to_xml()?);
668        }
669
670        for confirmation in &self.subject_confirmations {
671            xml.push_str(&confirmation.to_xml()?);
672        }
673
674        xml.push_str("</saml:Subject>");
675
676        Ok(xml)
677    }
678}
679
680impl SamlNameId {
681    /// Convert name ID to XML
682    pub fn to_xml(&self) -> Result<String> {
683        let mut xml = String::new();
684
685        xml.push_str("<saml:NameID");
686
687        if let Some(ref format) = self.format {
688            xml.push_str(&format!(" Format=\"{}\"", xml_escape(format)));
689        }
690
691        if let Some(ref name_qualifier) = self.name_qualifier {
692            xml.push_str(&format!(
693                " NameQualifier=\"{}\"",
694                xml_escape(name_qualifier)
695            ));
696        }
697
698        if let Some(ref sp_name_qualifier) = self.sp_name_qualifier {
699            xml.push_str(&format!(
700                " SPNameQualifier=\"{}\"",
701                xml_escape(sp_name_qualifier)
702            ));
703        }
704
705        xml.push_str(&format!(">{}</saml:NameID>", xml_escape(&self.value)));
706
707        Ok(xml)
708    }
709}
710
711impl SamlSubjectConfirmation {
712    /// Convert subject confirmation to XML
713    pub fn to_xml(&self) -> Result<String> {
714        let mut xml = String::new();
715
716        xml.push_str(&format!(
717            "<saml:SubjectConfirmation Method=\"{}\">",
718            xml_escape(&self.method)
719        ));
720
721        if let Some(ref data) = self.subject_confirmation_data {
722            xml.push_str(&data.to_xml()?);
723        }
724
725        xml.push_str("</saml:SubjectConfirmation>");
726
727        Ok(xml)
728    }
729}
730
731impl SamlSubjectConfirmationData {
732    /// Convert subject confirmation data to XML
733    pub fn to_xml(&self) -> Result<String> {
734        let mut xml = String::new();
735
736        xml.push_str("<saml:SubjectConfirmationData");
737
738        if let Some(not_before) = self.not_before {
739            xml.push_str(&format!(
740                " NotBefore=\"{}\"",
741                not_before.format("%Y-%m-%dT%H:%M:%S%.3fZ")
742            ));
743        }
744
745        if let Some(not_on_or_after) = self.not_on_or_after {
746            xml.push_str(&format!(
747                " NotOnOrAfter=\"{}\"",
748                not_on_or_after.format("%Y-%m-%dT%H:%M:%S%.3fZ")
749            ));
750        }
751
752        if let Some(ref recipient) = self.recipient {
753            xml.push_str(&format!(" Recipient=\"{}\"", xml_escape(recipient)));
754        }
755
756        if let Some(ref in_response_to) = self.in_response_to {
757            xml.push_str(&format!(" InResponseTo=\"{}\"", xml_escape(in_response_to)));
758        }
759
760        if let Some(ref address) = self.address {
761            xml.push_str(&format!(" Address=\"{}\"", xml_escape(address)));
762        }
763
764        xml.push_str("/>");
765
766        Ok(xml)
767    }
768}
769
770impl SamlConditions {
771    /// Convert conditions to XML
772    pub fn to_xml(&self) -> Result<String> {
773        let mut xml = String::new();
774
775        xml.push_str("<saml:Conditions");
776
777        if let Some(not_before) = self.not_before {
778            xml.push_str(&format!(
779                " NotBefore=\"{}\"",
780                not_before.format("%Y-%m-%dT%H:%M:%S%.3fZ")
781            ));
782        }
783
784        if let Some(not_on_or_after) = self.not_on_or_after {
785            xml.push_str(&format!(
786                " NotOnOrAfter=\"{}\"",
787                not_on_or_after.format("%Y-%m-%dT%H:%M:%S%.3fZ")
788            ));
789        }
790
791        xml.push('>');
792
793        for restriction in &self.audience_restrictions {
794            xml.push_str(&restriction.to_xml()?);
795        }
796
797        if self.one_time_use {
798            xml.push_str("<saml:OneTimeUse/>");
799        }
800
801        if let Some(ref proxy_restriction) = self.proxy_restriction {
802            xml.push_str(&proxy_restriction.to_xml()?);
803        }
804
805        xml.push_str("</saml:Conditions>");
806
807        Ok(xml)
808    }
809}
810
811impl SamlAudienceRestriction {
812    /// Convert audience restriction to XML
813    pub fn to_xml(&self) -> Result<String> {
814        let mut xml = String::new();
815
816        xml.push_str("<saml:AudienceRestriction>");
817
818        for audience in &self.audiences {
819            xml.push_str(&format!(
820                "<saml:Audience>{}</saml:Audience>",
821                xml_escape(audience)
822            ));
823        }
824
825        xml.push_str("</saml:AudienceRestriction>");
826
827        Ok(xml)
828    }
829}
830
831impl SamlProxyRestriction {
832    /// Convert proxy restriction to XML
833    pub fn to_xml(&self) -> Result<String> {
834        let mut xml = String::new();
835
836        xml.push_str("<saml:ProxyRestriction");
837
838        if let Some(count) = self.count {
839            xml.push_str(&format!(" Count=\"{}\"", count));
840        }
841
842        xml.push('>');
843
844        for audience in &self.audiences {
845            xml.push_str(&format!(
846                "<saml:Audience>{}</saml:Audience>",
847                xml_escape(audience)
848            ));
849        }
850
851        xml.push_str("</saml:ProxyRestriction>");
852
853        Ok(xml)
854    }
855}
856
857impl SamlAttributeStatement {
858    /// Convert attribute statement to XML
859    pub fn to_xml(&self) -> Result<String> {
860        let mut xml = String::new();
861
862        xml.push_str("<saml:AttributeStatement>");
863
864        for attribute in &self.attributes {
865            xml.push_str(&attribute.to_xml()?);
866        }
867
868        // Encrypted attributes would be handled here
869        for encrypted_attr in &self.encrypted_attributes {
870            xml.push_str(encrypted_attr);
871        }
872
873        xml.push_str("</saml:AttributeStatement>");
874
875        Ok(xml)
876    }
877}
878
879impl SamlAttribute {
880    /// Convert attribute to XML
881    pub fn to_xml(&self) -> Result<String> {
882        let mut xml = String::new();
883
884        xml.push_str(&format!(
885            "<saml:Attribute Name=\"{}\">",
886            xml_escape(&self.name)
887        ));
888
889        if let Some(ref name_format) = self.name_format {
890            xml = xml.replace(
891                ">",
892                &format!(" NameFormat=\"{}\">", xml_escape(name_format)),
893            );
894        }
895
896        if let Some(ref friendly_name) = self.friendly_name {
897            xml = xml.replace(
898                ">",
899                &format!(" FriendlyName=\"{}\">", xml_escape(friendly_name)),
900            );
901        }
902
903        for value in &self.values {
904            xml.push_str(&value.to_xml()?);
905        }
906
907        xml.push_str("</saml:Attribute>");
908
909        Ok(xml)
910    }
911}
912
913impl SamlAttributeValue {
914    /// Convert attribute value to XML
915    pub fn to_xml(&self) -> Result<String> {
916        let mut xml = String::new();
917
918        xml.push_str("<saml:AttributeValue");
919
920        if let Some(ref type_info) = self.type_info {
921            xml.push_str(&format!(" xsi:type=\"{}\"", xml_escape(type_info)));
922        }
923
924        xml.push_str(&format!(
925            ">{}</saml:AttributeValue>",
926            xml_escape(&self.value)
927        ));
928
929        Ok(xml)
930    }
931}
932
933impl SamlAuthnStatement {
934    /// Convert authentication statement to XML
935    pub fn to_xml(&self) -> Result<String> {
936        let mut xml = String::new();
937
938        xml.push_str(&format!(
939            "<saml:AuthnStatement AuthnInstant=\"{}\"",
940            self.authn_instant.format("%Y-%m-%dT%H:%M:%S%.3fZ")
941        ));
942
943        if let Some(ref session_index) = self.session_index {
944            xml.push_str(&format!(" SessionIndex=\"{}\"", xml_escape(session_index)));
945        }
946
947        if let Some(session_not_on_or_after) = self.session_not_on_or_after {
948            xml.push_str(&format!(
949                " SessionNotOnOrAfter=\"{}\"",
950                session_not_on_or_after.format("%Y-%m-%dT%H:%M:%S%.3fZ")
951            ));
952        }
953
954        xml.push('>');
955
956        if let Some(ref locality) = self.subject_locality {
957            xml.push_str(&locality.to_xml()?);
958        }
959
960        xml.push_str(&self.authn_context.to_xml()?);
961
962        xml.push_str("</saml:AuthnStatement>");
963
964        Ok(xml)
965    }
966}
967
968impl SamlAuthnContext {
969    /// Convert authentication context to XML
970    pub fn to_xml(&self) -> Result<String> {
971        let mut xml = String::new();
972
973        xml.push_str("<saml:AuthnContext>");
974
975        if let Some(ref class_ref) = self.authn_context_class_ref {
976            xml.push_str(&format!(
977                "<saml:AuthnContextClassRef>{}</saml:AuthnContextClassRef>",
978                xml_escape(class_ref)
979            ));
980        }
981
982        if let Some(ref decl) = self.authn_context_decl {
983            xml.push_str(&format!(
984                "<saml:AuthnContextDecl>{}</saml:AuthnContextDecl>",
985                xml_escape(decl)
986            ));
987        }
988
989        if let Some(ref decl_ref) = self.authn_context_decl_ref {
990            xml.push_str(&format!(
991                "<saml:AuthnContextDeclRef>{}</saml:AuthnContextDeclRef>",
992                xml_escape(decl_ref)
993            ));
994        }
995
996        for authority in &self.authenticating_authorities {
997            xml.push_str(&format!(
998                "<saml:AuthenticatingAuthority>{}</saml:AuthenticatingAuthority>",
999                xml_escape(authority)
1000            ));
1001        }
1002
1003        xml.push_str("</saml:AuthnContext>");
1004
1005        Ok(xml)
1006    }
1007}
1008
1009impl SamlSubjectLocality {
1010    /// Convert subject locality to XML
1011    pub fn to_xml(&self) -> Result<String> {
1012        let mut xml = String::new();
1013
1014        xml.push_str("<saml:SubjectLocality");
1015
1016        if let Some(ref address) = self.address {
1017            xml.push_str(&format!(" Address=\"{}\"", xml_escape(address)));
1018        }
1019
1020        if let Some(ref dns_name) = self.dns_name {
1021            xml.push_str(&format!(" DNSName=\"{}\"", xml_escape(dns_name)));
1022        }
1023
1024        xml.push_str("/>");
1025
1026        Ok(xml)
1027    }
1028}
1029
1030impl SamlAuthzDecisionStatement {
1031    /// Convert authorization decision statement to XML
1032    pub fn to_xml(&self) -> Result<String> {
1033        let mut xml = String::new();
1034
1035        let decision_str = match self.decision {
1036            SamlDecision::Permit => "Permit",
1037            SamlDecision::Deny => "Deny",
1038            SamlDecision::Indeterminate => "Indeterminate",
1039        };
1040
1041        xml.push_str(&format!(
1042            "<saml:AuthzDecisionStatement Decision=\"{}\" Resource=\"{}\">",
1043            decision_str,
1044            xml_escape(&self.resource)
1045        ));
1046
1047        for action in &self.actions {
1048            xml.push_str(&action.to_xml()?);
1049        }
1050
1051        if let Some(ref evidence) = self.evidence {
1052            xml.push_str(&evidence.to_xml()?);
1053        }
1054
1055        xml.push_str("</saml:AuthzDecisionStatement>");
1056
1057        Ok(xml)
1058    }
1059}
1060
1061impl SamlAction {
1062    /// Convert action to XML
1063    pub fn to_xml(&self) -> Result<String> {
1064        let mut xml = String::new();
1065
1066        xml.push_str("<saml:Action");
1067
1068        if let Some(ref namespace) = self.namespace {
1069            xml.push_str(&format!(" Namespace=\"{}\"", xml_escape(namespace)));
1070        }
1071
1072        xml.push_str(&format!(">{}</saml:Action>", xml_escape(&self.value)));
1073
1074        Ok(xml)
1075    }
1076}
1077
1078impl SamlEvidence {
1079    /// Convert evidence to XML
1080    pub fn to_xml(&self) -> Result<String> {
1081        let mut xml = String::new();
1082
1083        xml.push_str("<saml:Evidence>");
1084
1085        for assertion in &self.assertions {
1086            xml.push_str(assertion);
1087        }
1088
1089        for id_ref in &self.assertion_id_refs {
1090            xml.push_str(&format!(
1091                "<saml:AssertionIDRef>{}</saml:AssertionIDRef>",
1092                xml_escape(id_ref)
1093            ));
1094        }
1095
1096        for uri_ref in &self.assertion_uri_refs {
1097            xml.push_str(&format!(
1098                "<saml:AssertionURIRef>{}</saml:AssertionURIRef>",
1099                xml_escape(uri_ref)
1100            ));
1101        }
1102
1103        xml.push_str("</saml:Evidence>");
1104
1105        Ok(xml)
1106    }
1107}
1108
1109impl Default for SamlAssertionValidator {
1110    fn default() -> Self {
1111        Self::new()
1112    }
1113}
1114
1115#[cfg(test)]
1116mod tests {
1117    use super::*;
1118
1119    #[test]
1120    fn test_saml_assertion_builder() {
1121        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1122            .with_attribute("username", "testuser")
1123            .with_attribute("email", "test@example.com")
1124            .with_audience("https://sp.example.com")
1125            .build();
1126
1127        assert_eq!(assertion.issuer, "https://idp.example.com");
1128        assert_eq!(assertion.version, "2.0");
1129        assert!(!assertion.attribute_statements.is_empty());
1130        assert!(assertion.conditions.is_some());
1131    }
1132
1133    #[test]
1134    fn test_saml_assertion_xml() {
1135        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1136            .with_attribute("username", "testuser")
1137            .build();
1138
1139        let xml = assertion.to_xml().unwrap();
1140        assert!(xml.contains("<saml:Assertion"));
1141        assert!(xml.contains("https://idp.example.com"));
1142        assert!(xml.contains("testuser"));
1143        assert!(xml.contains("</saml:Assertion>"));
1144    }
1145
1146    #[test]
1147    fn test_saml_assertion_validation() {
1148        let validator = SamlAssertionValidator::new()
1149            .with_trusted_issuer("https://idp.example.com")
1150            .with_expected_audience("https://sp.example.com");
1151
1152        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1153            .with_audience("https://sp.example.com")
1154            .with_validity_period(
1155                Utc::now() - Duration::minutes(1),
1156                Utc::now() + Duration::hours(1),
1157            )
1158            .build();
1159
1160        assert!(validator.validate(&assertion).is_ok());
1161    }
1162
1163    #[test]
1164    fn test_expired_assertion_validation() {
1165        let validator = SamlAssertionValidator::new();
1166
1167        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1168            .with_validity_period(
1169                Utc::now() - Duration::hours(2),
1170                Utc::now() - Duration::hours(1),
1171            )
1172            .build();
1173
1174        assert!(validator.validate(&assertion).is_err());
1175    }
1176
1177    #[test]
1178    fn test_untrusted_issuer_rejected() {
1179        let validator =
1180            SamlAssertionValidator::new().with_trusted_issuer("https://trusted-idp.example.com");
1181
1182        let assertion = SamlAssertionBuilder::new("https://evil-idp.example.com")
1183            .with_validity_period(
1184                Utc::now() - Duration::minutes(1),
1185                Utc::now() + Duration::hours(1),
1186            )
1187            .build();
1188
1189        let err = validator.validate(&assertion).unwrap_err();
1190        let msg = format!("{err}");
1191        assert!(msg.contains("Untrusted issuer"), "got: {msg}");
1192    }
1193
1194    #[test]
1195    fn test_wrong_audience_rejected() {
1196        let validator = SamlAssertionValidator::new()
1197            .with_trusted_issuer("https://idp.example.com")
1198            .with_expected_audience("https://sp-a.example.com");
1199
1200        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1201            .with_validity_period(
1202                Utc::now() - Duration::minutes(1),
1203                Utc::now() + Duration::hours(1),
1204            )
1205            .with_audience("https://sp-b.example.com") // wrong audience
1206            .build();
1207
1208        let err = validator.validate(&assertion).unwrap_err();
1209        let msg = format!("{err}");
1210        assert!(msg.contains("No matching audience found"), "got: {msg}");
1211    }
1212
1213    #[test]
1214    fn test_assertion_no_attributes() {
1215        let assertion = SamlAssertionBuilder::new("https://idp.example.com").build();
1216        assert!(assertion.attribute_statements.is_empty());
1217
1218        let xml = assertion.to_xml().unwrap();
1219        assert!(xml.contains("<saml:Assertion"));
1220        assert!(xml.contains("https://idp.example.com"));
1221        // No AttributeStatement element should be present
1222        assert!(!xml.contains("<saml:AttributeStatement"));
1223    }
1224
1225    #[test]
1226    fn test_not_yet_valid_assertion_rejected() {
1227        let validator = SamlAssertionValidator::new().with_clock_skew(Duration::seconds(0)); // strict, no skew
1228
1229        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1230            .with_validity_period(
1231                Utc::now() + Duration::hours(1), // far in the future
1232                Utc::now() + Duration::hours(2),
1233            )
1234            .build();
1235
1236        let err = validator.validate(&assertion).unwrap_err();
1237        let msg = format!("{err}");
1238        assert!(msg.contains("not yet valid"), "got: {msg}");
1239    }
1240
1241    #[test]
1242    fn test_xml_special_characters_in_attributes() {
1243        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1244            .with_attribute("org", "A&B <Corp> \"Quoted\" 'Apos'")
1245            .build();
1246
1247        let xml = assertion.to_xml().unwrap();
1248        // Special chars must be escaped
1249        assert!(xml.contains("A&amp;B"), "& not escaped: {xml}");
1250        assert!(xml.contains("&lt;Corp&gt;"), "< > not escaped: {xml}");
1251        assert!(xml.contains("&quot;Quoted&quot;"), "\" not escaped: {xml}");
1252        assert!(xml.contains("&apos;Apos&apos;"), "' not escaped: {xml}");
1253    }
1254
1255    #[test]
1256    fn test_multiple_audience_restrictions() {
1257        let validator =
1258            SamlAssertionValidator::new().with_expected_audience("https://sp-b.example.com");
1259
1260        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1261            .with_validity_period(
1262                Utc::now() - Duration::minutes(1),
1263                Utc::now() + Duration::hours(1),
1264            )
1265            .with_audience("https://sp-a.example.com")
1266            .with_audience("https://sp-b.example.com") // second audience matches
1267            .build();
1268
1269        // Should succeed because the expected audience is in the list
1270        assert!(validator.validate(&assertion).is_ok());
1271    }
1272
1273    #[test]
1274    fn test_validator_no_constraints_accepts_any() {
1275        let validator = SamlAssertionValidator::new();
1276
1277        let assertion = SamlAssertionBuilder::new("https://random-idp.example.com")
1278            .with_validity_period(
1279                Utc::now() - Duration::minutes(1),
1280                Utc::now() + Duration::hours(1),
1281            )
1282            .build();
1283
1284        // No trusted issuers and no expected audiences → accept anything within time
1285        assert!(validator.validate(&assertion).is_ok());
1286    }
1287
1288    #[test]
1289    fn test_assertion_with_subject_confirmation() {
1290        let validator = SamlAssertionValidator::new()
1291            .with_trusted_issuer("https://idp.example.com")
1292            .with_expected_audience("https://sp.example.com");
1293
1294        let mut assertion = SamlAssertionBuilder::new("https://idp.example.com")
1295            .with_validity_period(
1296                Utc::now() - Duration::minutes(1),
1297                Utc::now() + Duration::hours(1),
1298            )
1299            .with_audience("https://sp.example.com")
1300            .build();
1301
1302        assertion.subject = Some(SamlSubject {
1303            name_id: Some(SamlNameId {
1304                value: "user@example.com".to_string(),
1305                format: Some("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress".into()),
1306                name_qualifier: None,
1307                sp_name_qualifier: None,
1308            }),
1309            subject_confirmations: vec![SamlSubjectConfirmation {
1310                method: "urn:oasis:names:tc:SAML:2.0:cm:bearer".to_string(),
1311                subject_confirmation_data: Some(SamlSubjectConfirmationData {
1312                    not_before: None,
1313                    not_on_or_after: Some(Utc::now() + Duration::hours(1)),
1314                    recipient: Some("https://sp.example.com".into()),
1315                    in_response_to: Some("req-123".into()),
1316                    address: None,
1317                }),
1318            }],
1319        });
1320
1321        assert!(validator.validate(&assertion).is_ok());
1322
1323        // Check XML output includes subject
1324        let xml = assertion.to_xml().unwrap();
1325        assert!(xml.contains("<saml:Subject>"));
1326        assert!(xml.contains("user@example.com"));
1327        assert!(xml.contains("urn:oasis:names:tc:SAML:2.0:cm:bearer"));
1328    }
1329
1330    #[test]
1331    fn test_unsupported_subject_confirmation_method_rejected() {
1332        let validator = SamlAssertionValidator::new();
1333
1334        let mut assertion = SamlAssertionBuilder::new("https://idp.example.com")
1335            .with_validity_period(
1336                Utc::now() - Duration::minutes(1),
1337                Utc::now() + Duration::hours(1),
1338            )
1339            .build();
1340
1341        assertion.subject = Some(SamlSubject {
1342            name_id: None,
1343            subject_confirmations: vec![SamlSubjectConfirmation {
1344                method: "urn:oasis:names:tc:SAML:2.0:cm:INVALID".to_string(),
1345                subject_confirmation_data: None,
1346            }],
1347        });
1348
1349        let err = validator.validate(&assertion).unwrap_err();
1350        let msg = format!("{err}");
1351        assert!(
1352            msg.contains("Unsupported subject confirmation method"),
1353            "got: {msg}"
1354        );
1355    }
1356
1357    #[test]
1358    fn test_expired_subject_confirmation_rejected() {
1359        let validator = SamlAssertionValidator::new().with_clock_skew(Duration::seconds(0));
1360
1361        let mut assertion = SamlAssertionBuilder::new("https://idp.example.com")
1362            .with_validity_period(
1363                Utc::now() - Duration::hours(2),
1364                Utc::now() + Duration::hours(1), // assertion itself is still valid
1365            )
1366            .build();
1367
1368        assertion.subject = Some(SamlSubject {
1369            name_id: None,
1370            subject_confirmations: vec![SamlSubjectConfirmation {
1371                method: "urn:oasis:names:tc:SAML:2.0:cm:bearer".to_string(),
1372                subject_confirmation_data: Some(SamlSubjectConfirmationData {
1373                    not_before: None,
1374                    not_on_or_after: Some(Utc::now() - Duration::hours(1)), // expired
1375                    recipient: None,
1376                    in_response_to: None,
1377                    address: None,
1378                }),
1379            }],
1380        });
1381
1382        let err = validator.validate(&assertion).unwrap_err();
1383        let msg = format!("{err}");
1384        assert!(
1385            msg.contains("Subject confirmation has expired"),
1386            "got: {msg}"
1387        );
1388    }
1389
1390    #[test]
1391    fn test_recipient_mismatch_rejected() {
1392        let validator =
1393            SamlAssertionValidator::new().with_expected_audience("https://sp.example.com");
1394
1395        let mut assertion = SamlAssertionBuilder::new("https://idp.example.com")
1396            .with_validity_period(
1397                Utc::now() - Duration::minutes(1),
1398                Utc::now() + Duration::hours(1),
1399            )
1400            .with_audience("https://sp.example.com")
1401            .build();
1402
1403        assertion.subject = Some(SamlSubject {
1404            name_id: None,
1405            subject_confirmations: vec![SamlSubjectConfirmation {
1406                method: "urn:oasis:names:tc:SAML:2.0:cm:bearer".to_string(),
1407                subject_confirmation_data: Some(SamlSubjectConfirmationData {
1408                    not_before: None,
1409                    not_on_or_after: Some(Utc::now() + Duration::hours(1)),
1410                    recipient: Some("https://wrong-sp.example.com".into()), // wrong
1411                    in_response_to: None,
1412                    address: None,
1413                }),
1414            }],
1415        });
1416
1417        let err = validator.validate(&assertion).unwrap_err();
1418        let msg = format!("{err}");
1419        assert!(msg.contains("recipient does not match"), "got: {msg}");
1420    }
1421
1422    #[test]
1423    fn test_clock_skew_tolerance() {
1424        // With default 5-minute skew, an assertion that expired 3 minutes ago
1425        // should still be accepted
1426        let validator = SamlAssertionValidator::new().with_clock_skew(Duration::minutes(5));
1427
1428        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1429            .with_validity_period(
1430                Utc::now() - Duration::hours(1),
1431                Utc::now() - Duration::minutes(3), // expired 3 min ago, within 5-min skew
1432            )
1433            .build();
1434
1435        assert!(
1436            validator.validate(&assertion).is_ok(),
1437            "should tolerate expiration within clock skew"
1438        );
1439    }
1440
1441    #[test]
1442    fn test_authz_decision_statement_xml() {
1443        let mut assertion = SamlAssertionBuilder::new("https://idp.example.com").build();
1444
1445        assertion
1446            .authz_decision_statements
1447            .push(SamlAuthzDecisionStatement {
1448                resource: "https://api.example.com/data".to_string(),
1449                decision: SamlDecision::Permit,
1450                actions: vec![SamlAction {
1451                    value: "GET".to_string(),
1452                    namespace: Some("urn:oasis:names:tc:SAML:1.0:action:rwedc".to_string()),
1453                }],
1454                evidence: None,
1455            });
1456
1457        let xml = assertion.to_xml().unwrap();
1458        assert!(xml.contains("AuthzDecisionStatement"));
1459        assert!(xml.contains("Permit"));
1460        assert!(xml.contains("GET"));
1461    }
1462}