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