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                    && now >= not_on_or_after + self.clock_skew
575                {
576                    return Err(AuthError::auth_method(
577                        "saml",
578                        "Subject confirmation has expired (NotOnOrAfter)",
579                    ));
580                }
581
582                // NotBefore must have passed.
583                if let Some(not_before) = data.not_before
584                    && now < not_before - self.clock_skew
585                {
586                    return Err(AuthError::auth_method(
587                        "saml",
588                        "Subject confirmation is not yet valid (NotBefore)",
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                    && !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        Ok(())
606    }
607}
608
609impl SamlAssertion {
610    /// Convert assertion to XML
611    pub fn to_xml(&self) -> Result<String> {
612        let mut xml = String::new();
613
614        xml.push_str(&format!(
615            r#"<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="{}" IssueInstant="{}" Version="{}">"#,
616            xml_escape(&self.id),
617            self.issue_instant.format("%Y-%m-%dT%H:%M:%S%.3fZ"),
618            xml_escape(&self.version)
619        ));
620
621        // Issuer
622        xml.push_str(&format!(
623            "<saml:Issuer>{}</saml:Issuer>",
624            xml_escape(&self.issuer)
625        ));
626
627        // Subject
628        if let Some(ref subject) = self.subject {
629            xml.push_str(&subject.to_xml()?);
630        }
631
632        // Conditions
633        if let Some(ref conditions) = self.conditions {
634            xml.push_str(&conditions.to_xml()?);
635        }
636
637        // Attribute statements
638        for statement in &self.attribute_statements {
639            xml.push_str(&statement.to_xml()?);
640        }
641
642        // Authentication statements
643        for statement in &self.authn_statements {
644            xml.push_str(&statement.to_xml()?);
645        }
646
647        // Authorization decision statements
648        for statement in &self.authz_decision_statements {
649            xml.push_str(&statement.to_xml()?);
650        }
651
652        xml.push_str("</saml:Assertion>");
653
654        Ok(xml)
655    }
656}
657
658impl SamlSubject {
659    /// Convert subject to XML
660    pub fn to_xml(&self) -> Result<String> {
661        let mut xml = String::new();
662
663        xml.push_str("<saml:Subject>");
664
665        if let Some(ref name_id) = self.name_id {
666            xml.push_str(&name_id.to_xml()?);
667        }
668
669        for confirmation in &self.subject_confirmations {
670            xml.push_str(&confirmation.to_xml()?);
671        }
672
673        xml.push_str("</saml:Subject>");
674
675        Ok(xml)
676    }
677}
678
679impl SamlNameId {
680    /// Convert name ID to XML
681    pub fn to_xml(&self) -> Result<String> {
682        let mut xml = String::new();
683
684        xml.push_str("<saml:NameID");
685
686        if let Some(ref format) = self.format {
687            xml.push_str(&format!(" Format=\"{}\"", xml_escape(format)));
688        }
689
690        if let Some(ref name_qualifier) = self.name_qualifier {
691            xml.push_str(&format!(
692                " NameQualifier=\"{}\"",
693                xml_escape(name_qualifier)
694            ));
695        }
696
697        if let Some(ref sp_name_qualifier) = self.sp_name_qualifier {
698            xml.push_str(&format!(
699                " SPNameQualifier=\"{}\"",
700                xml_escape(sp_name_qualifier)
701            ));
702        }
703
704        xml.push_str(&format!(">{}</saml:NameID>", xml_escape(&self.value)));
705
706        Ok(xml)
707    }
708}
709
710impl SamlSubjectConfirmation {
711    /// Convert subject confirmation to XML
712    pub fn to_xml(&self) -> Result<String> {
713        let mut xml = String::new();
714
715        xml.push_str(&format!(
716            "<saml:SubjectConfirmation Method=\"{}\">",
717            xml_escape(&self.method)
718        ));
719
720        if let Some(ref data) = self.subject_confirmation_data {
721            xml.push_str(&data.to_xml()?);
722        }
723
724        xml.push_str("</saml:SubjectConfirmation>");
725
726        Ok(xml)
727    }
728}
729
730impl SamlSubjectConfirmationData {
731    /// Convert subject confirmation data to XML
732    pub fn to_xml(&self) -> Result<String> {
733        let mut xml = String::new();
734
735        xml.push_str("<saml:SubjectConfirmationData");
736
737        if let Some(not_before) = self.not_before {
738            xml.push_str(&format!(
739                " NotBefore=\"{}\"",
740                not_before.format("%Y-%m-%dT%H:%M:%S%.3fZ")
741            ));
742        }
743
744        if let Some(not_on_or_after) = self.not_on_or_after {
745            xml.push_str(&format!(
746                " NotOnOrAfter=\"{}\"",
747                not_on_or_after.format("%Y-%m-%dT%H:%M:%S%.3fZ")
748            ));
749        }
750
751        if let Some(ref recipient) = self.recipient {
752            xml.push_str(&format!(" Recipient=\"{}\"", xml_escape(recipient)));
753        }
754
755        if let Some(ref in_response_to) = self.in_response_to {
756            xml.push_str(&format!(" InResponseTo=\"{}\"", xml_escape(in_response_to)));
757        }
758
759        if let Some(ref address) = self.address {
760            xml.push_str(&format!(" Address=\"{}\"", xml_escape(address)));
761        }
762
763        xml.push_str("/>");
764
765        Ok(xml)
766    }
767}
768
769impl SamlConditions {
770    /// Convert conditions to XML
771    pub fn to_xml(&self) -> Result<String> {
772        let mut xml = String::new();
773
774        xml.push_str("<saml:Conditions");
775
776        if let Some(not_before) = self.not_before {
777            xml.push_str(&format!(
778                " NotBefore=\"{}\"",
779                not_before.format("%Y-%m-%dT%H:%M:%S%.3fZ")
780            ));
781        }
782
783        if let Some(not_on_or_after) = self.not_on_or_after {
784            xml.push_str(&format!(
785                " NotOnOrAfter=\"{}\"",
786                not_on_or_after.format("%Y-%m-%dT%H:%M:%S%.3fZ")
787            ));
788        }
789
790        xml.push('>');
791
792        for restriction in &self.audience_restrictions {
793            xml.push_str(&restriction.to_xml()?);
794        }
795
796        if self.one_time_use {
797            xml.push_str("<saml:OneTimeUse/>");
798        }
799
800        if let Some(ref proxy_restriction) = self.proxy_restriction {
801            xml.push_str(&proxy_restriction.to_xml()?);
802        }
803
804        xml.push_str("</saml:Conditions>");
805
806        Ok(xml)
807    }
808}
809
810impl SamlAudienceRestriction {
811    /// Convert audience restriction to XML
812    pub fn to_xml(&self) -> Result<String> {
813        let mut xml = String::new();
814
815        xml.push_str("<saml:AudienceRestriction>");
816
817        for audience in &self.audiences {
818            xml.push_str(&format!(
819                "<saml:Audience>{}</saml:Audience>",
820                xml_escape(audience)
821            ));
822        }
823
824        xml.push_str("</saml:AudienceRestriction>");
825
826        Ok(xml)
827    }
828}
829
830impl SamlProxyRestriction {
831    /// Convert proxy restriction to XML
832    pub fn to_xml(&self) -> Result<String> {
833        let mut xml = String::new();
834
835        xml.push_str("<saml:ProxyRestriction");
836
837        if let Some(count) = self.count {
838            xml.push_str(&format!(" Count=\"{}\"", count));
839        }
840
841        xml.push('>');
842
843        for audience in &self.audiences {
844            xml.push_str(&format!(
845                "<saml:Audience>{}</saml:Audience>",
846                xml_escape(audience)
847            ));
848        }
849
850        xml.push_str("</saml:ProxyRestriction>");
851
852        Ok(xml)
853    }
854}
855
856impl SamlAttributeStatement {
857    /// Convert attribute statement to XML
858    pub fn to_xml(&self) -> Result<String> {
859        let mut xml = String::new();
860
861        xml.push_str("<saml:AttributeStatement>");
862
863        for attribute in &self.attributes {
864            xml.push_str(&attribute.to_xml()?);
865        }
866
867        // Encrypted attributes would be handled here
868        for encrypted_attr in &self.encrypted_attributes {
869            xml.push_str(encrypted_attr);
870        }
871
872        xml.push_str("</saml:AttributeStatement>");
873
874        Ok(xml)
875    }
876}
877
878impl SamlAttribute {
879    /// Convert attribute to XML
880    pub fn to_xml(&self) -> Result<String> {
881        let mut xml = String::new();
882
883        xml.push_str(&format!(
884            "<saml:Attribute Name=\"{}\">",
885            xml_escape(&self.name)
886        ));
887
888        if let Some(ref name_format) = self.name_format {
889            xml = xml.replace(
890                ">",
891                &format!(" NameFormat=\"{}\">", xml_escape(name_format)),
892            );
893        }
894
895        if let Some(ref friendly_name) = self.friendly_name {
896            xml = xml.replace(
897                ">",
898                &format!(" FriendlyName=\"{}\">", xml_escape(friendly_name)),
899            );
900        }
901
902        for value in &self.values {
903            xml.push_str(&value.to_xml()?);
904        }
905
906        xml.push_str("</saml:Attribute>");
907
908        Ok(xml)
909    }
910}
911
912impl SamlAttributeValue {
913    /// Convert attribute value to XML
914    pub fn to_xml(&self) -> Result<String> {
915        let mut xml = String::new();
916
917        xml.push_str("<saml:AttributeValue");
918
919        if let Some(ref type_info) = self.type_info {
920            xml.push_str(&format!(" xsi:type=\"{}\"", xml_escape(type_info)));
921        }
922
923        xml.push_str(&format!(
924            ">{}</saml:AttributeValue>",
925            xml_escape(&self.value)
926        ));
927
928        Ok(xml)
929    }
930}
931
932impl SamlAuthnStatement {
933    /// Convert authentication statement to XML
934    pub fn to_xml(&self) -> Result<String> {
935        let mut xml = String::new();
936
937        xml.push_str(&format!(
938            "<saml:AuthnStatement AuthnInstant=\"{}\"",
939            self.authn_instant.format("%Y-%m-%dT%H:%M:%S%.3fZ")
940        ));
941
942        if let Some(ref session_index) = self.session_index {
943            xml.push_str(&format!(" SessionIndex=\"{}\"", xml_escape(session_index)));
944        }
945
946        if let Some(session_not_on_or_after) = self.session_not_on_or_after {
947            xml.push_str(&format!(
948                " SessionNotOnOrAfter=\"{}\"",
949                session_not_on_or_after.format("%Y-%m-%dT%H:%M:%S%.3fZ")
950            ));
951        }
952
953        xml.push('>');
954
955        if let Some(ref locality) = self.subject_locality {
956            xml.push_str(&locality.to_xml()?);
957        }
958
959        xml.push_str(&self.authn_context.to_xml()?);
960
961        xml.push_str("</saml:AuthnStatement>");
962
963        Ok(xml)
964    }
965}
966
967impl SamlAuthnContext {
968    /// Convert authentication context to XML
969    pub fn to_xml(&self) -> Result<String> {
970        let mut xml = String::new();
971
972        xml.push_str("<saml:AuthnContext>");
973
974        if let Some(ref class_ref) = self.authn_context_class_ref {
975            xml.push_str(&format!(
976                "<saml:AuthnContextClassRef>{}</saml:AuthnContextClassRef>",
977                xml_escape(class_ref)
978            ));
979        }
980
981        if let Some(ref decl) = self.authn_context_decl {
982            xml.push_str(&format!(
983                "<saml:AuthnContextDecl>{}</saml:AuthnContextDecl>",
984                xml_escape(decl)
985            ));
986        }
987
988        if let Some(ref decl_ref) = self.authn_context_decl_ref {
989            xml.push_str(&format!(
990                "<saml:AuthnContextDeclRef>{}</saml:AuthnContextDeclRef>",
991                xml_escape(decl_ref)
992            ));
993        }
994
995        for authority in &self.authenticating_authorities {
996            xml.push_str(&format!(
997                "<saml:AuthenticatingAuthority>{}</saml:AuthenticatingAuthority>",
998                xml_escape(authority)
999            ));
1000        }
1001
1002        xml.push_str("</saml:AuthnContext>");
1003
1004        Ok(xml)
1005    }
1006}
1007
1008impl SamlSubjectLocality {
1009    /// Convert subject locality to XML
1010    pub fn to_xml(&self) -> Result<String> {
1011        let mut xml = String::new();
1012
1013        xml.push_str("<saml:SubjectLocality");
1014
1015        if let Some(ref address) = self.address {
1016            xml.push_str(&format!(" Address=\"{}\"", xml_escape(address)));
1017        }
1018
1019        if let Some(ref dns_name) = self.dns_name {
1020            xml.push_str(&format!(" DNSName=\"{}\"", xml_escape(dns_name)));
1021        }
1022
1023        xml.push_str("/>");
1024
1025        Ok(xml)
1026    }
1027}
1028
1029impl SamlAuthzDecisionStatement {
1030    /// Convert authorization decision statement to XML
1031    pub fn to_xml(&self) -> Result<String> {
1032        let mut xml = String::new();
1033
1034        let decision_str = match self.decision {
1035            SamlDecision::Permit => "Permit",
1036            SamlDecision::Deny => "Deny",
1037            SamlDecision::Indeterminate => "Indeterminate",
1038        };
1039
1040        xml.push_str(&format!(
1041            "<saml:AuthzDecisionStatement Decision=\"{}\" Resource=\"{}\">",
1042            decision_str,
1043            xml_escape(&self.resource)
1044        ));
1045
1046        for action in &self.actions {
1047            xml.push_str(&action.to_xml()?);
1048        }
1049
1050        if let Some(ref evidence) = self.evidence {
1051            xml.push_str(&evidence.to_xml()?);
1052        }
1053
1054        xml.push_str("</saml:AuthzDecisionStatement>");
1055
1056        Ok(xml)
1057    }
1058}
1059
1060impl SamlAction {
1061    /// Convert action to XML
1062    pub fn to_xml(&self) -> Result<String> {
1063        let mut xml = String::new();
1064
1065        xml.push_str("<saml:Action");
1066
1067        if let Some(ref namespace) = self.namespace {
1068            xml.push_str(&format!(" Namespace=\"{}\"", xml_escape(namespace)));
1069        }
1070
1071        xml.push_str(&format!(">{}</saml:Action>", xml_escape(&self.value)));
1072
1073        Ok(xml)
1074    }
1075}
1076
1077impl SamlEvidence {
1078    /// Convert evidence to XML
1079    pub fn to_xml(&self) -> Result<String> {
1080        let mut xml = String::new();
1081
1082        xml.push_str("<saml:Evidence>");
1083
1084        for assertion in &self.assertions {
1085            xml.push_str(assertion);
1086        }
1087
1088        for id_ref in &self.assertion_id_refs {
1089            xml.push_str(&format!(
1090                "<saml:AssertionIDRef>{}</saml:AssertionIDRef>",
1091                xml_escape(id_ref)
1092            ));
1093        }
1094
1095        for uri_ref in &self.assertion_uri_refs {
1096            xml.push_str(&format!(
1097                "<saml:AssertionURIRef>{}</saml:AssertionURIRef>",
1098                xml_escape(uri_ref)
1099            ));
1100        }
1101
1102        xml.push_str("</saml:Evidence>");
1103
1104        Ok(xml)
1105    }
1106}
1107
1108impl Default for SamlAssertionValidator {
1109    fn default() -> Self {
1110        Self::new()
1111    }
1112}
1113
1114#[cfg(test)]
1115mod tests {
1116    use super::*;
1117
1118    #[test]
1119    fn test_saml_assertion_builder() {
1120        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1121            .with_attribute("username", "testuser")
1122            .with_attribute("email", "test@example.com")
1123            .with_audience("https://sp.example.com")
1124            .build();
1125
1126        assert_eq!(assertion.issuer, "https://idp.example.com");
1127        assert_eq!(assertion.version, "2.0");
1128        assert!(!assertion.attribute_statements.is_empty());
1129        assert!(assertion.conditions.is_some());
1130    }
1131
1132    #[test]
1133    fn test_saml_assertion_xml() {
1134        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1135            .with_attribute("username", "testuser")
1136            .build();
1137
1138        let xml = assertion.to_xml().unwrap();
1139        assert!(xml.contains("<saml:Assertion"));
1140        assert!(xml.contains("https://idp.example.com"));
1141        assert!(xml.contains("testuser"));
1142        assert!(xml.contains("</saml:Assertion>"));
1143    }
1144
1145    #[test]
1146    fn test_saml_assertion_validation() {
1147        let validator = SamlAssertionValidator::new()
1148            .with_trusted_issuer("https://idp.example.com")
1149            .with_expected_audience("https://sp.example.com");
1150
1151        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1152            .with_audience("https://sp.example.com")
1153            .with_validity_period(
1154                Utc::now() - Duration::minutes(1),
1155                Utc::now() + Duration::hours(1),
1156            )
1157            .build();
1158
1159        assert!(validator.validate(&assertion).is_ok());
1160    }
1161
1162    #[test]
1163    fn test_expired_assertion_validation() {
1164        let validator = SamlAssertionValidator::new();
1165
1166        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1167            .with_validity_period(
1168                Utc::now() - Duration::hours(2),
1169                Utc::now() - Duration::hours(1),
1170            )
1171            .build();
1172
1173        assert!(validator.validate(&assertion).is_err());
1174    }
1175
1176    #[test]
1177    fn test_untrusted_issuer_rejected() {
1178        let validator =
1179            SamlAssertionValidator::new().with_trusted_issuer("https://trusted-idp.example.com");
1180
1181        let assertion = SamlAssertionBuilder::new("https://evil-idp.example.com")
1182            .with_validity_period(
1183                Utc::now() - Duration::minutes(1),
1184                Utc::now() + Duration::hours(1),
1185            )
1186            .build();
1187
1188        let err = validator.validate(&assertion).unwrap_err();
1189        let msg = format!("{err}");
1190        assert!(msg.contains("Untrusted issuer"), "got: {msg}");
1191    }
1192
1193    #[test]
1194    fn test_wrong_audience_rejected() {
1195        let validator = SamlAssertionValidator::new()
1196            .with_trusted_issuer("https://idp.example.com")
1197            .with_expected_audience("https://sp-a.example.com");
1198
1199        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1200            .with_validity_period(
1201                Utc::now() - Duration::minutes(1),
1202                Utc::now() + Duration::hours(1),
1203            )
1204            .with_audience("https://sp-b.example.com") // wrong audience
1205            .build();
1206
1207        let err = validator.validate(&assertion).unwrap_err();
1208        let msg = format!("{err}");
1209        assert!(msg.contains("No matching audience found"), "got: {msg}");
1210    }
1211
1212    #[test]
1213    fn test_assertion_no_attributes() {
1214        let assertion = SamlAssertionBuilder::new("https://idp.example.com").build();
1215        assert!(assertion.attribute_statements.is_empty());
1216
1217        let xml = assertion.to_xml().unwrap();
1218        assert!(xml.contains("<saml:Assertion"));
1219        assert!(xml.contains("https://idp.example.com"));
1220        // No AttributeStatement element should be present
1221        assert!(!xml.contains("<saml:AttributeStatement"));
1222    }
1223
1224    #[test]
1225    fn test_not_yet_valid_assertion_rejected() {
1226        let validator = SamlAssertionValidator::new().with_clock_skew(Duration::seconds(0)); // strict, no skew
1227
1228        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1229            .with_validity_period(
1230                Utc::now() + Duration::hours(1), // far in the future
1231                Utc::now() + Duration::hours(2),
1232            )
1233            .build();
1234
1235        let err = validator.validate(&assertion).unwrap_err();
1236        let msg = format!("{err}");
1237        assert!(msg.contains("not yet valid"), "got: {msg}");
1238    }
1239
1240    #[test]
1241    fn test_xml_special_characters_in_attributes() {
1242        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1243            .with_attribute("org", "A&B <Corp> \"Quoted\" 'Apos'")
1244            .build();
1245
1246        let xml = assertion.to_xml().unwrap();
1247        // Special chars must be escaped
1248        assert!(xml.contains("A&amp;B"), "& not escaped: {xml}");
1249        assert!(xml.contains("&lt;Corp&gt;"), "< > not escaped: {xml}");
1250        assert!(xml.contains("&quot;Quoted&quot;"), "\" not escaped: {xml}");
1251        assert!(xml.contains("&apos;Apos&apos;"), "' not escaped: {xml}");
1252    }
1253
1254    #[test]
1255    fn test_multiple_audience_restrictions() {
1256        let validator =
1257            SamlAssertionValidator::new().with_expected_audience("https://sp-b.example.com");
1258
1259        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1260            .with_validity_period(
1261                Utc::now() - Duration::minutes(1),
1262                Utc::now() + Duration::hours(1),
1263            )
1264            .with_audience("https://sp-a.example.com")
1265            .with_audience("https://sp-b.example.com") // second audience matches
1266            .build();
1267
1268        // Should succeed because the expected audience is in the list
1269        assert!(validator.validate(&assertion).is_ok());
1270    }
1271
1272    #[test]
1273    fn test_validator_no_constraints_accepts_any() {
1274        let validator = SamlAssertionValidator::new();
1275
1276        let assertion = SamlAssertionBuilder::new("https://random-idp.example.com")
1277            .with_validity_period(
1278                Utc::now() - Duration::minutes(1),
1279                Utc::now() + Duration::hours(1),
1280            )
1281            .build();
1282
1283        // No trusted issuers and no expected audiences → accept anything within time
1284        assert!(validator.validate(&assertion).is_ok());
1285    }
1286
1287    #[test]
1288    fn test_assertion_with_subject_confirmation() {
1289        let validator = SamlAssertionValidator::new()
1290            .with_trusted_issuer("https://idp.example.com")
1291            .with_expected_audience("https://sp.example.com");
1292
1293        let mut assertion = SamlAssertionBuilder::new("https://idp.example.com")
1294            .with_validity_period(
1295                Utc::now() - Duration::minutes(1),
1296                Utc::now() + Duration::hours(1),
1297            )
1298            .with_audience("https://sp.example.com")
1299            .build();
1300
1301        assertion.subject = Some(SamlSubject {
1302            name_id: Some(SamlNameId {
1303                value: "user@example.com".to_string(),
1304                format: Some("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress".into()),
1305                name_qualifier: None,
1306                sp_name_qualifier: None,
1307            }),
1308            subject_confirmations: vec![SamlSubjectConfirmation {
1309                method: "urn:oasis:names:tc:SAML:2.0:cm:bearer".to_string(),
1310                subject_confirmation_data: Some(SamlSubjectConfirmationData {
1311                    not_before: None,
1312                    not_on_or_after: Some(Utc::now() + Duration::hours(1)),
1313                    recipient: Some("https://sp.example.com".into()),
1314                    in_response_to: Some("req-123".into()),
1315                    address: None,
1316                }),
1317            }],
1318        });
1319
1320        assert!(validator.validate(&assertion).is_ok());
1321
1322        // Check XML output includes subject
1323        let xml = assertion.to_xml().unwrap();
1324        assert!(xml.contains("<saml:Subject>"));
1325        assert!(xml.contains("user@example.com"));
1326        assert!(xml.contains("urn:oasis:names:tc:SAML:2.0:cm:bearer"));
1327    }
1328
1329    #[test]
1330    fn test_unsupported_subject_confirmation_method_rejected() {
1331        let validator = SamlAssertionValidator::new();
1332
1333        let mut assertion = SamlAssertionBuilder::new("https://idp.example.com")
1334            .with_validity_period(
1335                Utc::now() - Duration::minutes(1),
1336                Utc::now() + Duration::hours(1),
1337            )
1338            .build();
1339
1340        assertion.subject = Some(SamlSubject {
1341            name_id: None,
1342            subject_confirmations: vec![SamlSubjectConfirmation {
1343                method: "urn:oasis:names:tc:SAML:2.0:cm:INVALID".to_string(),
1344                subject_confirmation_data: None,
1345            }],
1346        });
1347
1348        let err = validator.validate(&assertion).unwrap_err();
1349        let msg = format!("{err}");
1350        assert!(
1351            msg.contains("Unsupported subject confirmation method"),
1352            "got: {msg}"
1353        );
1354    }
1355
1356    #[test]
1357    fn test_expired_subject_confirmation_rejected() {
1358        let validator = SamlAssertionValidator::new().with_clock_skew(Duration::seconds(0));
1359
1360        let mut assertion = SamlAssertionBuilder::new("https://idp.example.com")
1361            .with_validity_period(
1362                Utc::now() - Duration::hours(2),
1363                Utc::now() + Duration::hours(1), // assertion itself is still valid
1364            )
1365            .build();
1366
1367        assertion.subject = Some(SamlSubject {
1368            name_id: None,
1369            subject_confirmations: vec![SamlSubjectConfirmation {
1370                method: "urn:oasis:names:tc:SAML:2.0:cm:bearer".to_string(),
1371                subject_confirmation_data: Some(SamlSubjectConfirmationData {
1372                    not_before: None,
1373                    not_on_or_after: Some(Utc::now() - Duration::hours(1)), // expired
1374                    recipient: None,
1375                    in_response_to: None,
1376                    address: None,
1377                }),
1378            }],
1379        });
1380
1381        let err = validator.validate(&assertion).unwrap_err();
1382        let msg = format!("{err}");
1383        assert!(
1384            msg.contains("Subject confirmation has expired"),
1385            "got: {msg}"
1386        );
1387    }
1388
1389    #[test]
1390    fn test_recipient_mismatch_rejected() {
1391        let validator =
1392            SamlAssertionValidator::new().with_expected_audience("https://sp.example.com");
1393
1394        let mut assertion = SamlAssertionBuilder::new("https://idp.example.com")
1395            .with_validity_period(
1396                Utc::now() - Duration::minutes(1),
1397                Utc::now() + Duration::hours(1),
1398            )
1399            .with_audience("https://sp.example.com")
1400            .build();
1401
1402        assertion.subject = Some(SamlSubject {
1403            name_id: None,
1404            subject_confirmations: vec![SamlSubjectConfirmation {
1405                method: "urn:oasis:names:tc:SAML:2.0:cm:bearer".to_string(),
1406                subject_confirmation_data: Some(SamlSubjectConfirmationData {
1407                    not_before: None,
1408                    not_on_or_after: Some(Utc::now() + Duration::hours(1)),
1409                    recipient: Some("https://wrong-sp.example.com".into()), // wrong
1410                    in_response_to: None,
1411                    address: None,
1412                }),
1413            }],
1414        });
1415
1416        let err = validator.validate(&assertion).unwrap_err();
1417        let msg = format!("{err}");
1418        assert!(msg.contains("recipient does not match"), "got: {msg}");
1419    }
1420
1421    #[test]
1422    fn test_clock_skew_tolerance() {
1423        // With default 5-minute skew, an assertion that expired 3 minutes ago
1424        // should still be accepted
1425        let validator = SamlAssertionValidator::new().with_clock_skew(Duration::minutes(5));
1426
1427        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1428            .with_validity_period(
1429                Utc::now() - Duration::hours(1),
1430                Utc::now() - Duration::minutes(3), // expired 3 min ago, within 5-min skew
1431            )
1432            .build();
1433
1434        assert!(
1435            validator.validate(&assertion).is_ok(),
1436            "should tolerate expiration within clock skew"
1437        );
1438    }
1439
1440    #[test]
1441    fn test_authz_decision_statement_xml() {
1442        let mut assertion = SamlAssertionBuilder::new("https://idp.example.com").build();
1443
1444        assertion
1445            .authz_decision_statements
1446            .push(SamlAuthzDecisionStatement {
1447                resource: "https://api.example.com/data".to_string(),
1448                decision: SamlDecision::Permit,
1449                actions: vec![SamlAction {
1450                    value: "GET".to_string(),
1451                    namespace: Some("urn:oasis:names:tc:SAML:1.0:action:rwedc".to_string()),
1452                }],
1453                evidence: None,
1454            });
1455
1456        let xml = assertion.to_xml().unwrap();
1457        assert!(xml.contains("AuthzDecisionStatement"));
1458        assert!(xml.contains("Permit"));
1459        assert!(xml.contains("GET"));
1460    }
1461}