samael-mdext 0.1.1

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

pub enum SubjectType<'a> {
    BaseId,
    NameId(&'a str),
    EncryptedId,
}

impl<'a> SubjectType<'a> {
    fn saml_element_name(&self) -> &'static str {
        match self {
            SubjectType::BaseId => "saml2:BaseID",
            SubjectType::NameId(_) => "saml2:NameID",
            SubjectType::EncryptedId => "saml2:EncryptedID",
        }
    }
}

impl<'a> ToXml for SubjectType<'a> {
    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
        let element = writer.create_element(self.saml_element_name());
        match self {
            SubjectType::NameId(content) => element.write_text_content(BytesText::new(content))?,
            _ => element.write_inner_content(|_| Ok(()))?,
        };
        Ok(())
    }
}

const NAME: &str = "saml2:Subject";
const SCHEMA: (&str, &str) = ("xmlns:saml2", "urn:oasis:names:tc:SAML:2.0:assertion");

#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct Subject {
    #[serde(rename = "NameID")]
    pub name_id: Option<SubjectNameID>,
    #[serde(rename = "SubjectConfirmation")]
    pub subject_confirmations: Option<Vec<SubjectConfirmation>>,
}

impl ToXml for Subject {
    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
        writer
            .create_element(NAME)
            .with_attribute(SCHEMA)
            .write_inner_content(|writer| {
                if let Some(name_id) = &self.name_id {
                    name_id.write_xml(writer)?;
                }
                if let Some(subject_confirmations) = &self.subject_confirmations {
                    for confirmation in subject_confirmations {
                        confirmation.write_xml(writer)?;
                    }
                }
                Ok(())
            })?;
        Ok(())
    }
}

#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct SubjectNameID {
    #[serde(rename = "@Format")]
    pub format: Option<String>,

    #[serde(rename = "$value")]
    pub value: String,
}

impl SubjectNameID {
    fn name() -> &'static str {
        "saml2:NameID"
    }
}

impl ToXml for SubjectNameID {
    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
        writer
            .create_element(SubjectNameID::name())
            .with_attributes(self.format.as_deref().map(|v| ("Format", v)))
            .write_text_content(BytesText::new(self.value.as_str()))?;
        Ok(())
    }
}

const SUBJECT_CONFIRMATION_NAME: &str = "saml2:SubjectConfirmation";

#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct SubjectConfirmation {
    #[serde(rename = "@Method")]
    pub method: Option<String>,
    #[serde(rename = "NameID")]
    pub name_id: Option<SubjectNameID>,
    #[serde(rename = "SubjectConfirmationData")]
    pub subject_confirmation_data: Option<SubjectConfirmationData>,
}

impl ToXml for SubjectConfirmation {
    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
        writer
            .create_element(SUBJECT_CONFIRMATION_NAME)
            .with_attributes(self.method.as_deref().map(|v| ("Method", v)))
            .write_inner_content(|writer| {
                if let Some(name_id) = &self.name_id {
                    name_id.write_xml(writer)?;
                }
                if let Some(subject_confirmation_data) = &self.subject_confirmation_data {
                    subject_confirmation_data.write_xml(writer)?;
                }
                Ok(())
            })?;
        Ok(())
    }
}

const SUBJECT_CONFIRMATION_DATA_NAME: &str = "saml2:SubjectConfirmationData";

#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct SubjectConfirmationData {
    #[serde(rename = "@NotBefore")]
    pub not_before: Option<chrono::DateTime<Utc>>,
    #[serde(rename = "@NotOnOrAfter")]
    pub not_on_or_after: Option<chrono::DateTime<Utc>>,
    #[serde(rename = "@Recipient")]
    pub recipient: Option<String>,
    #[serde(rename = "@InResponseTo")]
    pub in_response_to: Option<String>,
    #[serde(rename = "@Address")]
    pub address: Option<String>,
    #[serde(rename = "$value")]
    pub content: Option<String>,
}

impl ToXml for SubjectConfirmationData {
    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
        let not_before = self
            .not_before
            .map(|t| t.to_rfc3339_opts(SecondsFormat::Millis, true));
        let not_on_or_after = self
            .not_on_or_after
            .map(|t| t.to_rfc3339_opts(SecondsFormat::Millis, true));

        let element = writer
            .create_element(SUBJECT_CONFIRMATION_DATA_NAME)
            .with_attributes(not_before.as_deref().map(|v| ("NotBefore", v)))
            .with_attributes(not_on_or_after.as_deref().map(|v| ("NotOnOrAfter", v)))
            .with_attributes(self.recipient.as_deref().map(|v| ("Recipient", v)))
            .with_attributes(self.in_response_to.as_deref().map(|v| ("InResponseTo", v)))
            .with_attributes(self.address.as_deref().map(|v| ("Address", v)));

        match &self.content {
            Some(content) => element.write_text_content(BytesText::new(content))?,
            None => element.write_inner_content(|_| Ok(()))?,
        };
        Ok(())
    }
}