samael-mdext 0.1.0

samael with unreleased fixes for SAML metadata extensions and XML escaping
use crate::metadata::{
    AttributeConsumingService, ContactPerson, Endpoint, Extensions, IndexedEndpoint, KeyDescriptor,
    Organization,
};
use crate::traits::ToXml;
use chrono::prelude::*;
use quick_xml::events::BytesText;
use quick_xml::Writer;
use serde::Deserialize;
use std::io::{self, Write};

const NAME: &str = "md:SPSSODescriptor";

#[derive(Clone, Debug, Deserialize, Default, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct SpSsoDescriptor {
    #[serde(rename = "@ID")]
    pub id: Option<String>,
    #[serde(rename = "@validUntil")]
    pub valid_until: Option<DateTime<Utc>>,
    #[serde(rename = "@cacheDuration")]
    pub cache_duration: Option<usize>,
    #[serde(rename = "@protocolSupportEnumeration")]
    pub protocol_support_enumeration: Option<String>,
    #[serde(rename = "@errorURL")]
    pub error_url: Option<String>,
    #[serde(rename = "Extensions")]
    pub extensions: Option<Extensions>,
    #[serde(rename = "KeyDescriptor")]
    pub key_descriptors: Option<Vec<KeyDescriptor>>,
    #[serde(rename = "Organization")]
    pub organization: Option<Organization>,
    #[serde(rename = "ContactPerson")]
    pub contact_people: Option<Vec<ContactPerson>>,
    #[serde(rename = "ArtifactResolutionService")]
    pub artifact_resolution_service: Option<Vec<IndexedEndpoint>>,
    #[serde(rename = "SingleLogoutService")]
    pub single_logout_services: Option<Vec<Endpoint>>,
    #[serde(rename = "ManageNameIDService")]
    pub manage_name_id_services: Option<Vec<Endpoint>>,
    #[serde(rename = "NameIDFormat")]
    pub name_id_formats: Option<Vec<String>>,
    // ^-SSODescriptor
    #[serde(rename = "@AuthnRequestsSigned")]
    pub authn_requests_signed: Option<bool>,
    #[serde(rename = "@WantAssertionsSigned")]
    pub want_assertions_signed: Option<bool>,
    #[serde(rename = "AssertionConsumerService")]
    pub assertion_consumer_services: Vec<IndexedEndpoint>,
    #[serde(rename = "AttributeConsumingService")]
    pub attribute_consuming_services: Option<Vec<AttributeConsumingService>>,
}

impl ToXml for SpSsoDescriptor {
    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
        let valid_until = self
            .valid_until
            .map(|valid_until| valid_until.to_rfc3339_opts(SecondsFormat::Secs, true));
        let cache_duration = self
            .cache_duration
            .map(|cache_duration| cache_duration.to_string());
        let want_assertions_signed = self
            .want_assertions_signed
            .map(|want_assertions_signed| want_assertions_signed.to_string());
        let authn_requests_signed = self
            .authn_requests_signed
            .map(|authn_requests_signed| authn_requests_signed.to_string());

        writer
            .create_element(NAME)
            .with_attributes(self.id.as_deref().map(|v| ("ID", v)))
            .with_attributes(valid_until.as_deref().map(|v| ("validUntil", v)))
            .with_attributes(cache_duration.as_deref().map(|v| ("cacheDuration", v)))
            .with_attributes(
                self.protocol_support_enumeration
                    .as_deref()
                    .map(|v| ("protocolSupportEnumeration", v)),
            )
            .with_attributes(self.error_url.as_deref().map(|v| ("errorURL", v)))
            .with_attributes(
                want_assertions_signed
                    .as_deref()
                    .map(|v| ("WantAssertionsSigned", v)),
            )
            .with_attributes(
                authn_requests_signed
                    .as_deref()
                    .map(|v| ("AuthnRequestsSigned", v)),
            )
            .write_inner_content(|writer| {
                if let Some(extensions) = &self.extensions {
                    extensions.write_xml(writer)?;
                }

                if let Some(key_descriptors) = &self.key_descriptors {
                    for descriptor in key_descriptors {
                        descriptor.write_xml(writer)?;
                    }
                }

                if let Some(organization) = &self.organization {
                    organization.write_xml(writer)?;
                }

                if let Some(contact_people) = &self.contact_people {
                    for contact in contact_people {
                        contact.write_xml(writer)?;
                    }
                }

                if let Some(artifact_resolution_service) = &self.artifact_resolution_service {
                    for service in artifact_resolution_service {
                        service.write_xml(writer, "md:ArtifactResolutionService")?;
                    }
                }

                if let Some(single_logout_services) = &self.single_logout_services {
                    for service in single_logout_services {
                        service.write_xml(writer, "md:SingleLogoutService")?;
                    }
                }

                if let Some(manage_name_id_services) = &self.manage_name_id_services {
                    for service in manage_name_id_services {
                        service.write_xml(writer, "md:ManageNameIDService")?;
                    }
                }

                if let Some(name_id_formats) = &self.name_id_formats {
                    for format in name_id_formats {
                        writer
                            .create_element("md:NameIDFormat")
                            .write_text_content(BytesText::new(format))?;
                    }
                }

                for service in &self.assertion_consumer_services {
                    service.write_xml(writer, "md:AssertionConsumerService")?;
                }

                if let Some(attribute_consuming_services) = &self.attribute_consuming_services {
                    for service in attribute_consuming_services {
                        service.write_xml(writer)?;
                    }
                }
                Ok(())
            })?;
        Ok(())
    }
}