Skip to main content

auth_framework/
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// HashMap removed - not currently used but may be needed later
9// use std::collections::HashMap;
10
11/// SAML 2.0 Assertion
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct SamlAssertion {
14    /// Assertion ID
15    pub id: String,
16
17    /// Issuer of the assertion
18    pub issuer: String,
19
20    /// Issue instant
21    pub issue_instant: DateTime<Utc>,
22
23    /// Version (always "2.0" for SAML 2.0)
24    pub version: String,
25
26    /// Subject information
27    pub subject: Option<SamlSubject>,
28
29    /// Conditions (validity constraints)
30    pub conditions: Option<SamlConditions>,
31
32    /// Attribute statements
33    pub attribute_statements: Vec<SamlAttributeStatement>,
34
35    /// Authentication statements
36    pub authn_statements: Vec<SamlAuthnStatement>,
37
38    /// Authorization decision statements
39    pub authz_decision_statements: Vec<SamlAuthzDecisionStatement>,
40}
41
42/// SAML Subject
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct SamlSubject {
45    /// Name identifier
46    pub name_id: Option<SamlNameId>,
47
48    /// Subject confirmations
49    pub subject_confirmations: Vec<SamlSubjectConfirmation>,
50}
51
52/// SAML Name Identifier
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct SamlNameId {
55    /// Value of the name identifier
56    pub value: String,
57
58    /// Format of the name identifier
59    pub format: Option<String>,
60
61    /// Name qualifier
62    pub name_qualifier: Option<String>,
63
64    /// SP name qualifier
65    pub sp_name_qualifier: Option<String>,
66}
67
68/// SAML Subject Confirmation
69#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct SamlSubjectConfirmation {
71    /// Method (bearer, holder-of-key, etc.)
72    pub method: String,
73
74    /// Subject confirmation data
75    pub subject_confirmation_data: Option<SamlSubjectConfirmationData>,
76}
77
78/// SAML Subject Confirmation Data
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct SamlSubjectConfirmationData {
81    /// Not before timestamp
82    pub not_before: Option<DateTime<Utc>>,
83
84    /// Not on or after timestamp
85    pub not_on_or_after: Option<DateTime<Utc>>,
86
87    /// Recipient URL
88    pub recipient: Option<String>,
89
90    /// In response to (for response assertions)
91    pub in_response_to: Option<String>,
92
93    /// Address restriction
94    pub address: Option<String>,
95}
96
97/// SAML Conditions
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct SamlConditions {
100    /// Not before timestamp
101    pub not_before: Option<DateTime<Utc>>,
102
103    /// Not on or after timestamp
104    pub not_on_or_after: Option<DateTime<Utc>>,
105
106    /// Audience restrictions
107    pub audience_restrictions: Vec<SamlAudienceRestriction>,
108
109    /// One time use
110    pub one_time_use: bool,
111
112    /// Proxy restrictions
113    pub proxy_restriction: Option<SamlProxyRestriction>,
114}
115
116/// SAML Audience Restriction
117#[derive(Debug, Clone, Serialize, Deserialize)]
118pub struct SamlAudienceRestriction {
119    /// Audience URIs
120    pub audiences: Vec<String>,
121}
122
123/// SAML Proxy Restriction
124#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct SamlProxyRestriction {
126    /// Count limit
127    pub count: Option<u32>,
128
129    /// Allowed audiences
130    pub audiences: Vec<String>,
131}
132
133/// SAML Attribute Statement
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct SamlAttributeStatement {
136    /// Attributes
137    pub attributes: Vec<SamlAttribute>,
138
139    /// Encrypted attributes
140    pub encrypted_attributes: Vec<String>, // Would be proper encrypted elements in production
141}
142
143/// SAML Attribute
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub struct SamlAttribute {
146    /// Attribute name
147    pub name: String,
148
149    /// Name format
150    pub name_format: Option<String>,
151
152    /// Friendly name
153    pub friendly_name: Option<String>,
154
155    /// Attribute values
156    pub values: Vec<SamlAttributeValue>,
157}
158
159/// SAML Attribute Value
160#[derive(Debug, Clone, Serialize, Deserialize)]
161pub struct SamlAttributeValue {
162    /// Value content
163    pub value: String,
164
165    /// Type information
166    pub type_info: Option<String>,
167}
168
169/// SAML Authentication Statement
170#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct SamlAuthnStatement {
172    /// Authentication instant
173    pub authn_instant: DateTime<Utc>,
174
175    /// Session index
176    pub session_index: Option<String>,
177
178    /// Session not on or after
179    pub session_not_on_or_after: Option<DateTime<Utc>>,
180
181    /// Authentication context
182    pub authn_context: SamlAuthnContext,
183
184    /// Subject locality
185    pub subject_locality: Option<SamlSubjectLocality>,
186}
187
188/// SAML Authentication Context
189#[derive(Debug, Clone, Serialize, Deserialize)]
190pub struct SamlAuthnContext {
191    /// Authentication context class reference
192    pub authn_context_class_ref: Option<String>,
193
194    /// Authentication context declaration
195    pub authn_context_decl: Option<String>,
196
197    /// Authentication context declaration reference
198    pub authn_context_decl_ref: Option<String>,
199
200    /// Authenticating authorities
201    pub authenticating_authorities: Vec<String>,
202}
203
204/// SAML Subject Locality
205#[derive(Debug, Clone, Serialize, Deserialize)]
206pub struct SamlSubjectLocality {
207    /// IP address
208    pub address: Option<String>,
209
210    /// DNS name
211    pub dns_name: Option<String>,
212}
213
214/// SAML Authorization Decision Statement
215#[derive(Debug, Clone, Serialize, Deserialize)]
216pub struct SamlAuthzDecisionStatement {
217    /// Resource being accessed
218    pub resource: String,
219
220    /// Decision (Permit, Deny, Indeterminate)
221    pub decision: SamlDecision,
222
223    /// Actions being performed
224    pub actions: Vec<SamlAction>,
225
226    /// Evidence supporting the decision
227    pub evidence: Option<SamlEvidence>,
228}
229
230/// SAML Decision
231#[derive(Debug, Clone, Serialize, Deserialize)]
232pub enum SamlDecision {
233    /// Access permitted
234    Permit,
235
236    /// Access denied
237    Deny,
238
239    /// Decision cannot be made
240    Indeterminate,
241}
242
243/// SAML Action
244#[derive(Debug, Clone, Serialize, Deserialize)]
245pub struct SamlAction {
246    /// Action value
247    pub value: String,
248
249    /// Action namespace
250    pub namespace: Option<String>,
251}
252
253/// SAML Evidence
254#[derive(Clone, Serialize, Deserialize)]
255pub struct SamlEvidence {
256    /// Supporting assertions
257    pub assertions: Vec<String>, // References to other assertions
258
259    /// Assertion ID references
260    pub assertion_id_refs: Vec<String>,
261
262    /// Assertion URI references
263    pub assertion_uri_refs: Vec<String>,
264}
265
266impl std::fmt::Debug for SamlEvidence {
267    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
268        let mut d = f.debug_struct("SamlEvidence");
269        d.field(
270            "assertions",
271            &crate::utils::redact::redacted(&self.assertions),
272        );
273        d.field("assertion_id_refs", &self.assertion_id_refs);
274        d.field("assertion_uri_refs", &self.assertion_uri_refs);
275        d.finish()
276    }
277}
278
279/// SAML Assertion Builder
280pub struct SamlAssertionBuilder {
281    /// Current assertion being built
282    assertion: SamlAssertion,
283}
284
285/// SAML Assertion Validator
286pub struct SamlAssertionValidator {
287    /// Allowed clock skew
288    clock_skew: Duration,
289
290    /// Trusted issuers
291    trusted_issuers: Vec<String>,
292
293    /// Expected audiences
294    expected_audiences: Vec<String>,
295}
296
297impl SamlAssertionBuilder {
298    /// Create a new SAML assertion builder
299    pub fn new(issuer: &str) -> Self {
300        let assertion = SamlAssertion {
301            id: format!("_{}", uuid::Uuid::new_v4()),
302            issuer: issuer.to_string(),
303            issue_instant: Utc::now(),
304            version: "2.0".to_string(),
305            subject: None,
306            conditions: None,
307            attribute_statements: Vec::new(),
308            authn_statements: Vec::new(),
309            authz_decision_statements: Vec::new(),
310        };
311
312        Self { assertion }
313    }
314
315    /// Set the subject
316    pub fn with_subject(mut self, subject: SamlSubject) -> Self {
317        self.assertion.subject = Some(subject);
318        self
319    }
320
321    /// Set conditions
322    pub fn with_conditions(mut self, conditions: SamlConditions) -> Self {
323        self.assertion.conditions = Some(conditions);
324        self
325    }
326
327    /// Add an attribute statement
328    pub fn with_attribute_statement(mut self, statement: SamlAttributeStatement) -> Self {
329        self.assertion.attribute_statements.push(statement);
330        self
331    }
332
333    /// Add an authentication statement
334    pub fn with_authn_statement(mut self, statement: SamlAuthnStatement) -> Self {
335        self.assertion.authn_statements.push(statement);
336        self
337    }
338
339    /// Add an authorization decision statement
340    pub fn with_authz_decision_statement(mut self, statement: SamlAuthzDecisionStatement) -> Self {
341        self.assertion.authz_decision_statements.push(statement);
342        self
343    }
344
345    /// Add a simple attribute
346    pub fn with_attribute(mut self, name: &str, value: &str) -> Self {
347        let attribute = SamlAttribute {
348            name: name.to_string(),
349            name_format: Some("urn:oasis:names:tc:SAML:2.0:attrname-format:basic".to_string()),
350            friendly_name: None,
351            values: vec![SamlAttributeValue {
352                value: value.to_string(),
353                type_info: None,
354            }],
355        };
356
357        // Find or create attribute statement
358        if self.assertion.attribute_statements.is_empty() {
359            self.assertion
360                .attribute_statements
361                .push(SamlAttributeStatement {
362                    attributes: vec![attribute],
363                    encrypted_attributes: Vec::new(),
364                });
365        } else {
366            self.assertion.attribute_statements[0]
367                .attributes
368                .push(attribute);
369        }
370
371        self
372    }
373
374    /// Set validity period
375    pub fn with_validity_period(
376        mut self,
377        not_before: DateTime<Utc>,
378        not_on_or_after: DateTime<Utc>,
379    ) -> Self {
380        if let Some(ref mut conditions) = self.assertion.conditions {
381            // Update existing conditions
382            conditions.not_before = Some(not_before);
383            conditions.not_on_or_after = Some(not_on_or_after);
384        } else {
385            // Create new conditions
386            let conditions = SamlConditions {
387                not_before: Some(not_before),
388                not_on_or_after: Some(not_on_or_after),
389                audience_restrictions: Vec::new(),
390                one_time_use: false,
391                proxy_restriction: None,
392            };
393            self.assertion.conditions = Some(conditions);
394        }
395        self
396    }
397
398    /// Add audience restriction
399    pub fn with_audience(mut self, audience: &str) -> Self {
400        if let Some(ref mut conditions) = self.assertion.conditions {
401            if conditions.audience_restrictions.is_empty() {
402                conditions
403                    .audience_restrictions
404                    .push(SamlAudienceRestriction {
405                        audiences: vec![audience.to_string()],
406                    });
407            } else {
408                conditions.audience_restrictions[0]
409                    .audiences
410                    .push(audience.to_string());
411            }
412        } else {
413            let conditions = SamlConditions {
414                not_before: None,
415                not_on_or_after: None,
416                audience_restrictions: vec![SamlAudienceRestriction {
417                    audiences: vec![audience.to_string()],
418                }],
419                one_time_use: false,
420                proxy_restriction: None,
421            };
422            self.assertion.conditions = Some(conditions);
423        }
424
425        self
426    }
427
428    /// Build the assertion
429    pub fn build(self) -> SamlAssertion {
430        self.assertion
431    }
432
433    /// Build and convert to XML
434    pub fn build_xml(self) -> Result<String> {
435        let assertion = self.assertion;
436        assertion.to_xml()
437    }
438}
439
440impl SamlAssertionValidator {
441    /// Create a new SAML assertion validator
442    pub fn new() -> Self {
443        Self {
444            clock_skew: Duration::minutes(5),
445            trusted_issuers: Vec::new(),
446            expected_audiences: Vec::new(),
447        }
448    }
449
450    /// Set clock skew tolerance
451    pub fn with_clock_skew(mut self, skew: Duration) -> Self {
452        self.clock_skew = skew;
453        self
454    }
455
456    /// Add trusted issuer
457    pub fn with_trusted_issuer(mut self, issuer: &str) -> Self {
458        self.trusted_issuers.push(issuer.to_string());
459        self
460    }
461
462    /// Add expected audience
463    pub fn with_expected_audience(mut self, audience: &str) -> Self {
464        self.expected_audiences.push(audience.to_string());
465        self
466    }
467
468    /// Validate a SAML assertion
469    pub fn validate(&self, assertion: &SamlAssertion) -> Result<()> {
470        // Check issuer
471        if !self.trusted_issuers.is_empty() && !self.trusted_issuers.contains(&assertion.issuer) {
472            return Err(AuthError::auth_method("saml", "Untrusted issuer"));
473        }
474
475        // Check time validity
476        self.validate_timing(assertion)?;
477
478        // Check audience restrictions
479        self.validate_audience(assertion)?;
480
481        // Check subject confirmation (if present)
482        if let Some(ref subject) = assertion.subject {
483            self.validate_subject_confirmation(subject)?;
484        }
485
486        Ok(())
487    }
488
489    /// Validate timing constraints
490    fn validate_timing(&self, assertion: &SamlAssertion) -> Result<()> {
491        let now = Utc::now();
492
493        // Check issue instant (shouldn't be too far in the future)
494        if assertion.issue_instant > now + self.clock_skew {
495            return Err(AuthError::auth_method(
496                "saml",
497                "Assertion issued in the future",
498            ));
499        }
500
501        // Check conditions timing
502        if let Some(ref conditions) = assertion.conditions {
503            if let Some(not_before) = conditions.not_before
504                && now < not_before - self.clock_skew
505            {
506                return Err(AuthError::auth_method("saml", "Assertion not yet valid"));
507            }
508
509            if let Some(not_on_or_after) = conditions.not_on_or_after
510                && now >= not_on_or_after + self.clock_skew
511            {
512                return Err(AuthError::auth_method("saml", "Assertion has expired"));
513            }
514        }
515
516        Ok(())
517    }
518
519    /// Validate audience restrictions
520    fn validate_audience(&self, assertion: &SamlAssertion) -> Result<()> {
521        if self.expected_audiences.is_empty() {
522            return Ok(());
523        }
524
525        if let Some(ref conditions) = assertion.conditions {
526            for restriction in &conditions.audience_restrictions {
527                for audience in &restriction.audiences {
528                    if self.expected_audiences.contains(audience) {
529                        return Ok(());
530                    }
531                }
532            }
533
534            if !conditions.audience_restrictions.is_empty() {
535                return Err(AuthError::auth_method("saml", "No matching audience found"));
536            }
537        }
538
539        Ok(())
540    }
541
542    /// Validate subject confirmation
543    fn validate_subject_confirmation(&self, _subject: &SamlSubject) -> Result<()> {
544        // Simplified validation - would check bearer tokens, holder-of-key, etc.
545        Ok(())
546    }
547}
548
549impl SamlAssertion {
550    /// Convert assertion to XML
551    pub fn to_xml(&self) -> Result<String> {
552        let mut xml = String::new();
553
554        xml.push_str(&format!(
555            r#"<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="{}" IssueInstant="{}" Version="{}">"#,
556            self.id,
557            self.issue_instant.format("%Y-%m-%dT%H:%M:%S%.3fZ"),
558            self.version
559        ));
560
561        // Issuer
562        xml.push_str(&format!("<saml:Issuer>{}</saml:Issuer>", self.issuer));
563
564        // Subject
565        if let Some(ref subject) = self.subject {
566            xml.push_str(&subject.to_xml()?);
567        }
568
569        // Conditions
570        if let Some(ref conditions) = self.conditions {
571            xml.push_str(&conditions.to_xml()?);
572        }
573
574        // Attribute statements
575        for statement in &self.attribute_statements {
576            xml.push_str(&statement.to_xml()?);
577        }
578
579        // Authentication statements
580        for statement in &self.authn_statements {
581            xml.push_str(&statement.to_xml()?);
582        }
583
584        // Authorization decision statements
585        for statement in &self.authz_decision_statements {
586            xml.push_str(&statement.to_xml()?);
587        }
588
589        xml.push_str("</saml:Assertion>");
590
591        Ok(xml)
592    }
593}
594
595impl SamlSubject {
596    /// Convert subject to XML
597    pub fn to_xml(&self) -> Result<String> {
598        let mut xml = String::new();
599
600        xml.push_str("<saml:Subject>");
601
602        if let Some(ref name_id) = self.name_id {
603            xml.push_str(&name_id.to_xml()?);
604        }
605
606        for confirmation in &self.subject_confirmations {
607            xml.push_str(&confirmation.to_xml()?);
608        }
609
610        xml.push_str("</saml:Subject>");
611
612        Ok(xml)
613    }
614}
615
616impl SamlNameId {
617    /// Convert name ID to XML
618    pub fn to_xml(&self) -> Result<String> {
619        let mut xml = String::new();
620
621        xml.push_str("<saml:NameID");
622
623        if let Some(ref format) = self.format {
624            xml.push_str(&format!(" Format=\"{}\"", format));
625        }
626
627        if let Some(ref name_qualifier) = self.name_qualifier {
628            xml.push_str(&format!(" NameQualifier=\"{}\"", name_qualifier));
629        }
630
631        if let Some(ref sp_name_qualifier) = self.sp_name_qualifier {
632            xml.push_str(&format!(" SPNameQualifier=\"{}\"", sp_name_qualifier));
633        }
634
635        xml.push_str(&format!(">{}</saml:NameID>", self.value));
636
637        Ok(xml)
638    }
639}
640
641impl SamlSubjectConfirmation {
642    /// Convert subject confirmation to XML
643    pub fn to_xml(&self) -> Result<String> {
644        let mut xml = String::new();
645
646        xml.push_str(&format!(
647            "<saml:SubjectConfirmation Method=\"{}\">",
648            self.method
649        ));
650
651        if let Some(ref data) = self.subject_confirmation_data {
652            xml.push_str(&data.to_xml()?);
653        }
654
655        xml.push_str("</saml:SubjectConfirmation>");
656
657        Ok(xml)
658    }
659}
660
661impl SamlSubjectConfirmationData {
662    /// Convert subject confirmation data to XML
663    pub fn to_xml(&self) -> Result<String> {
664        let mut xml = String::new();
665
666        xml.push_str("<saml:SubjectConfirmationData");
667
668        if let Some(not_before) = self.not_before {
669            xml.push_str(&format!(
670                " NotBefore=\"{}\"",
671                not_before.format("%Y-%m-%dT%H:%M:%S%.3fZ")
672            ));
673        }
674
675        if let Some(not_on_or_after) = self.not_on_or_after {
676            xml.push_str(&format!(
677                " NotOnOrAfter=\"{}\"",
678                not_on_or_after.format("%Y-%m-%dT%H:%M:%S%.3fZ")
679            ));
680        }
681
682        if let Some(ref recipient) = self.recipient {
683            xml.push_str(&format!(" Recipient=\"{}\"", recipient));
684        }
685
686        if let Some(ref in_response_to) = self.in_response_to {
687            xml.push_str(&format!(" InResponseTo=\"{}\"", in_response_to));
688        }
689
690        if let Some(ref address) = self.address {
691            xml.push_str(&format!(" Address=\"{}\"", address));
692        }
693
694        xml.push_str("/>");
695
696        Ok(xml)
697    }
698}
699
700impl SamlConditions {
701    /// Convert conditions to XML
702    pub fn to_xml(&self) -> Result<String> {
703        let mut xml = String::new();
704
705        xml.push_str("<saml:Conditions");
706
707        if let Some(not_before) = self.not_before {
708            xml.push_str(&format!(
709                " NotBefore=\"{}\"",
710                not_before.format("%Y-%m-%dT%H:%M:%S%.3fZ")
711            ));
712        }
713
714        if let Some(not_on_or_after) = self.not_on_or_after {
715            xml.push_str(&format!(
716                " NotOnOrAfter=\"{}\"",
717                not_on_or_after.format("%Y-%m-%dT%H:%M:%S%.3fZ")
718            ));
719        }
720
721        xml.push('>');
722
723        for restriction in &self.audience_restrictions {
724            xml.push_str(&restriction.to_xml()?);
725        }
726
727        if self.one_time_use {
728            xml.push_str("<saml:OneTimeUse/>");
729        }
730
731        if let Some(ref proxy_restriction) = self.proxy_restriction {
732            xml.push_str(&proxy_restriction.to_xml()?);
733        }
734
735        xml.push_str("</saml:Conditions>");
736
737        Ok(xml)
738    }
739}
740
741impl SamlAudienceRestriction {
742    /// Convert audience restriction to XML
743    pub fn to_xml(&self) -> Result<String> {
744        let mut xml = String::new();
745
746        xml.push_str("<saml:AudienceRestriction>");
747
748        for audience in &self.audiences {
749            xml.push_str(&format!("<saml:Audience>{}</saml:Audience>", audience));
750        }
751
752        xml.push_str("</saml:AudienceRestriction>");
753
754        Ok(xml)
755    }
756}
757
758impl SamlProxyRestriction {
759    /// Convert proxy restriction to XML
760    pub fn to_xml(&self) -> Result<String> {
761        let mut xml = String::new();
762
763        xml.push_str("<saml:ProxyRestriction");
764
765        if let Some(count) = self.count {
766            xml.push_str(&format!(" Count=\"{}\"", count));
767        }
768
769        xml.push('>');
770
771        for audience in &self.audiences {
772            xml.push_str(&format!("<saml:Audience>{}</saml:Audience>", audience));
773        }
774
775        xml.push_str("</saml:ProxyRestriction>");
776
777        Ok(xml)
778    }
779}
780
781impl SamlAttributeStatement {
782    /// Convert attribute statement to XML
783    pub fn to_xml(&self) -> Result<String> {
784        let mut xml = String::new();
785
786        xml.push_str("<saml:AttributeStatement>");
787
788        for attribute in &self.attributes {
789            xml.push_str(&attribute.to_xml()?);
790        }
791
792        // Encrypted attributes would be handled here
793        for encrypted_attr in &self.encrypted_attributes {
794            xml.push_str(encrypted_attr);
795        }
796
797        xml.push_str("</saml:AttributeStatement>");
798
799        Ok(xml)
800    }
801}
802
803impl SamlAttribute {
804    /// Convert attribute to XML
805    pub fn to_xml(&self) -> Result<String> {
806        let mut xml = String::new();
807
808        xml.push_str(&format!("<saml:Attribute Name=\"{}\">", self.name));
809
810        if let Some(ref name_format) = self.name_format {
811            xml = xml.replace(">", &format!(" NameFormat=\"{}\">", name_format));
812        }
813
814        if let Some(ref friendly_name) = self.friendly_name {
815            xml = xml.replace(">", &format!(" FriendlyName=\"{}\">", friendly_name));
816        }
817
818        for value in &self.values {
819            xml.push_str(&value.to_xml()?);
820        }
821
822        xml.push_str("</saml:Attribute>");
823
824        Ok(xml)
825    }
826}
827
828impl SamlAttributeValue {
829    /// Convert attribute value to XML
830    pub fn to_xml(&self) -> Result<String> {
831        let mut xml = String::new();
832
833        xml.push_str("<saml:AttributeValue");
834
835        if let Some(ref type_info) = self.type_info {
836            xml.push_str(&format!(" xsi:type=\"{}\"", type_info));
837        }
838
839        xml.push_str(&format!(">{}</saml:AttributeValue>", self.value));
840
841        Ok(xml)
842    }
843}
844
845impl SamlAuthnStatement {
846    /// Convert authentication statement to XML
847    pub fn to_xml(&self) -> Result<String> {
848        let mut xml = String::new();
849
850        xml.push_str(&format!(
851            "<saml:AuthnStatement AuthnInstant=\"{}\"",
852            self.authn_instant.format("%Y-%m-%dT%H:%M:%S%.3fZ")
853        ));
854
855        if let Some(ref session_index) = self.session_index {
856            xml.push_str(&format!(" SessionIndex=\"{}\"", session_index));
857        }
858
859        if let Some(session_not_on_or_after) = self.session_not_on_or_after {
860            xml.push_str(&format!(
861                " SessionNotOnOrAfter=\"{}\"",
862                session_not_on_or_after.format("%Y-%m-%dT%H:%M:%S%.3fZ")
863            ));
864        }
865
866        xml.push('>');
867
868        if let Some(ref locality) = self.subject_locality {
869            xml.push_str(&locality.to_xml()?);
870        }
871
872        xml.push_str(&self.authn_context.to_xml()?);
873
874        xml.push_str("</saml:AuthnStatement>");
875
876        Ok(xml)
877    }
878}
879
880impl SamlAuthnContext {
881    /// Convert authentication context to XML
882    pub fn to_xml(&self) -> Result<String> {
883        let mut xml = String::new();
884
885        xml.push_str("<saml:AuthnContext>");
886
887        if let Some(ref class_ref) = self.authn_context_class_ref {
888            xml.push_str(&format!(
889                "<saml:AuthnContextClassRef>{}</saml:AuthnContextClassRef>",
890                class_ref
891            ));
892        }
893
894        if let Some(ref decl) = self.authn_context_decl {
895            xml.push_str(&format!(
896                "<saml:AuthnContextDecl>{}</saml:AuthnContextDecl>",
897                decl
898            ));
899        }
900
901        if let Some(ref decl_ref) = self.authn_context_decl_ref {
902            xml.push_str(&format!(
903                "<saml:AuthnContextDeclRef>{}</saml:AuthnContextDeclRef>",
904                decl_ref
905            ));
906        }
907
908        for authority in &self.authenticating_authorities {
909            xml.push_str(&format!(
910                "<saml:AuthenticatingAuthority>{}</saml:AuthenticatingAuthority>",
911                authority
912            ));
913        }
914
915        xml.push_str("</saml:AuthnContext>");
916
917        Ok(xml)
918    }
919}
920
921impl SamlSubjectLocality {
922    /// Convert subject locality to XML
923    pub fn to_xml(&self) -> Result<String> {
924        let mut xml = String::new();
925
926        xml.push_str("<saml:SubjectLocality");
927
928        if let Some(ref address) = self.address {
929            xml.push_str(&format!(" Address=\"{}\"", address));
930        }
931
932        if let Some(ref dns_name) = self.dns_name {
933            xml.push_str(&format!(" DNSName=\"{}\"", dns_name));
934        }
935
936        xml.push_str("/>");
937
938        Ok(xml)
939    }
940}
941
942impl SamlAuthzDecisionStatement {
943    /// Convert authorization decision statement to XML
944    pub fn to_xml(&self) -> Result<String> {
945        let mut xml = String::new();
946
947        let decision_str = match self.decision {
948            SamlDecision::Permit => "Permit",
949            SamlDecision::Deny => "Deny",
950            SamlDecision::Indeterminate => "Indeterminate",
951        };
952
953        xml.push_str(&format!(
954            "<saml:AuthzDecisionStatement Decision=\"{}\" Resource=\"{}\">",
955            decision_str, self.resource
956        ));
957
958        for action in &self.actions {
959            xml.push_str(&action.to_xml()?);
960        }
961
962        if let Some(ref evidence) = self.evidence {
963            xml.push_str(&evidence.to_xml()?);
964        }
965
966        xml.push_str("</saml:AuthzDecisionStatement>");
967
968        Ok(xml)
969    }
970}
971
972impl SamlAction {
973    /// Convert action to XML
974    pub fn to_xml(&self) -> Result<String> {
975        let mut xml = String::new();
976
977        xml.push_str("<saml:Action");
978
979        if let Some(ref namespace) = self.namespace {
980            xml.push_str(&format!(" Namespace=\"{}\"", namespace));
981        }
982
983        xml.push_str(&format!(">{}</saml:Action>", self.value));
984
985        Ok(xml)
986    }
987}
988
989impl SamlEvidence {
990    /// Convert evidence to XML
991    pub fn to_xml(&self) -> Result<String> {
992        let mut xml = String::new();
993
994        xml.push_str("<saml:Evidence>");
995
996        for assertion in &self.assertions {
997            xml.push_str(assertion);
998        }
999
1000        for id_ref in &self.assertion_id_refs {
1001            xml.push_str(&format!(
1002                "<saml:AssertionIDRef>{}</saml:AssertionIDRef>",
1003                id_ref
1004            ));
1005        }
1006
1007        for uri_ref in &self.assertion_uri_refs {
1008            xml.push_str(&format!(
1009                "<saml:AssertionURIRef>{}</saml:AssertionURIRef>",
1010                uri_ref
1011            ));
1012        }
1013
1014        xml.push_str("</saml:Evidence>");
1015
1016        Ok(xml)
1017    }
1018}
1019
1020impl Default for SamlAssertionValidator {
1021    fn default() -> Self {
1022        Self::new()
1023    }
1024}
1025
1026#[cfg(test)]
1027mod tests {
1028    use super::*;
1029
1030    #[test]
1031    fn test_saml_assertion_builder() {
1032        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1033            .with_attribute("username", "testuser")
1034            .with_attribute("email", "test@example.com")
1035            .with_audience("https://sp.example.com")
1036            .build();
1037
1038        assert_eq!(assertion.issuer, "https://idp.example.com");
1039        assert_eq!(assertion.version, "2.0");
1040        assert!(!assertion.attribute_statements.is_empty());
1041        assert!(assertion.conditions.is_some());
1042    }
1043
1044    #[test]
1045    fn test_saml_assertion_xml() {
1046        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1047            .with_attribute("username", "testuser")
1048            .build();
1049
1050        let xml = assertion.to_xml().unwrap();
1051        assert!(xml.contains("<saml:Assertion"));
1052        assert!(xml.contains("https://idp.example.com"));
1053        assert!(xml.contains("testuser"));
1054        assert!(xml.contains("</saml:Assertion>"));
1055    }
1056
1057    #[test]
1058    fn test_saml_assertion_validation() {
1059        let validator = SamlAssertionValidator::new()
1060            .with_trusted_issuer("https://idp.example.com")
1061            .with_expected_audience("https://sp.example.com");
1062
1063        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1064            .with_audience("https://sp.example.com")
1065            .with_validity_period(
1066                Utc::now() - Duration::minutes(1),
1067                Utc::now() + Duration::hours(1),
1068            )
1069            .build();
1070
1071        assert!(validator.validate(&assertion).is_ok());
1072    }
1073
1074    #[test]
1075    fn test_expired_assertion_validation() {
1076        let validator = SamlAssertionValidator::new();
1077
1078        let assertion = SamlAssertionBuilder::new("https://idp.example.com")
1079            .with_validity_period(
1080                Utc::now() - Duration::hours(2),
1081                Utc::now() - Duration::hours(1),
1082            )
1083            .build();
1084
1085        assert!(validator.validate(&assertion).is_err());
1086    }
1087}