samael-mdext 0.1.1

samael with unreleased fixes for SAML metadata extensions and XML escaping
use crate::metadata::UiInfo;
use crate::traits::ToXml;
use quick_xml::events::BytesText;
use quick_xml::Writer;
use serde::de::{self, MapAccess, Visitor};
use serde::{Deserialize, Deserializer};
use std::fmt;
use std::io::{self, Write};

const NAME: &str = "md:Extensions";
const SCOPE_NAME: &str = "shibmd:Scope";
const SHIBMD_NS: &str = "urn:mace:shibboleth:metadata:1.0";

#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct Extensions {
    pub ui_info: Option<UiInfo>,
    pub scopes: Vec<Scope>,
}

impl<'de> Deserialize<'de> for Extensions {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ExtensionsVisitor;

        impl<'de> Visitor<'de> for ExtensionsVisitor {
            type Value = Extensions;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("Extensions element")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut extensions = Extensions::default();

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "UIInfo" => extensions.ui_info = Some(map.next_value()?),
                        "Scope" => extensions.scopes.push(map.next_value()?),
                        _ => {
                            map.next_value::<de::IgnoredAny>()?;
                        }
                    }
                }

                Ok(extensions)
            }
        }

        deserializer.deserialize_map(ExtensionsVisitor)
    }
}

impl ToXml for Extensions {
    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
        if self.ui_info.is_none() && self.scopes.is_empty() {
            return Ok(());
        }

        let shibmd_ns = (!self.scopes.is_empty()).then_some(("xmlns:shibmd", SHIBMD_NS));

        writer
            .create_element(NAME)
            .with_attributes(shibmd_ns)
            .write_inner_content(|writer| {
                for scope in &self.scopes {
                    scope.write_xml(writer)?;
                }

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

                Ok(())
            })?;

        Ok(())
    }
}

/// A `shibmd:Scope` element naming a domain the entity may assert in scoped attributes
#[derive(Clone, Debug, Deserialize, Default, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct Scope {
    #[serde(rename = "@regexp", default)]
    pub regexp: bool,
    #[serde(rename = "$value")]
    pub value: String,
}

impl ToXml for Scope {
    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
        writer
            .create_element(SCOPE_NAME)
            .with_attribute(("regexp", if self.regexp { "true" } else { "false" }))
            .write_text_content(BytesText::new(&self.value))?;

        Ok(())
    }
}

#[cfg(test)]
mod scope_tests {
    use crate::metadata::EntityDescriptor;
    use crate::traits::ToXml;

    #[test]
    fn test_idp_entity_descriptor_with_scopes() {
        let xml = r#"<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:mdui="urn:oasis:names:tc:SAML:metadata:ui" xmlns:shibmd="urn:mace:shibboleth:metadata:1.0" entityID="https://idp.example.org/idp">
  <md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
    <md:Extensions>
      <shibmd:Scope regexp="false">example.org</shibmd:Scope>
      <mdui:UIInfo>
        <mdui:DisplayName xml:lang="en">Example University</mdui:DisplayName>
      </mdui:UIInfo>
      <shibmd:Scope regexp="true">^.+\.example\.org$</shibmd:Scope>
      <shibmd:Scope>example.edu</shibmd:Scope>
    </md:Extensions>
    <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://idp.example.org/SSO"/>
  </md:IDPSSODescriptor>
</md:EntityDescriptor>"#;

        let entity_descriptor: EntityDescriptor = xml.parse().unwrap();
        let extensions = entity_descriptor
            .idp_sso_descriptors
            .as_ref()
            .and_then(|descriptors| descriptors[0].extensions.as_ref())
            .expect("extensions should be Some");
        let scopes: Vec<(bool, &str)> = extensions
            .scopes
            .iter()
            .map(|scope| (scope.regexp, scope.value.as_str()))
            .collect();
        assert_eq!(
            scopes,
            vec![
                (false, "example.org"),
                (true, r"^.+\.example\.org$"),
                (false, "example.edu"),
            ]
        );
        assert!(extensions.ui_info.is_some());

        let output_xml = entity_descriptor.to_string().unwrap();
        assert!(output_xml.contains(r#"xmlns:shibmd="urn:mace:shibboleth:metadata:1.0""#));
        assert!(output_xml.contains(r#"<shibmd:Scope regexp="true">"#));

        let reparsed_entity_descriptor: EntityDescriptor = output_xml.parse().unwrap();
        assert_eq!(reparsed_entity_descriptor, entity_descriptor);
    }
}