samael 0.0.21

A SAML2 library for Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use crate::metadata::{
    AffiliationDescriptor, AttributeAuthorityDescriptors, AuthnAuthorityDescriptors, ContactPerson,
    IdpSsoDescriptor, Organization, PdpDescriptors, RoleDescriptor, SpSsoDescriptor,
};
use crate::signature::Signature;
use chrono::prelude::*;
use quick_xml::events::{BytesDecl, BytesEnd, BytesStart, BytesText, Event};
use quick_xml::Writer;
use serde::Deserialize;
use std::collections::VecDeque;
use std::io::Cursor;
use std::str::FromStr;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum Error {
    #[error("Failed to deserialize SAML response: {:?}", source)]
    ParseError {
        #[from]
        source: quick_xml::DeError,
    },
}

#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum EntityDescriptorType {
    #[serde(rename = "EntitiesDescriptor")]
    EntitiesDescriptor(EntitiesDescriptor),
    #[serde(rename = "EntityDescriptor")]
    EntityDescriptor(EntityDescriptor),
}

impl EntityDescriptorType {
    pub fn iter(&self) -> EntityDescriptorIterator {
        EntityDescriptorIterator::new(self)
    }
}

impl FromStr for EntityDescriptorType {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(quick_xml::de::from_str(s)?)
    }
}

impl TryFrom<EntityDescriptorType> for Event<'_> {
    type Error = Box<dyn std::error::Error>;

    fn try_from(value: EntityDescriptorType) -> Result<Self, Self::Error> {
        (&value).try_into()
    }
}

impl TryFrom<&EntityDescriptorType> for Event<'_> {
    type Error = Box<dyn std::error::Error>;

    fn try_from(value: &EntityDescriptorType) -> Result<Self, Self::Error> {
        let mut write_buf = Vec::new();
        let mut writer = Writer::new(Cursor::new(&mut write_buf));
        writer.write_event(Event::Decl(BytesDecl::new("1.0", Some("UTF-8"), None)))?;

        let event: Event<'_> = match value {
            EntityDescriptorType::EntitiesDescriptor(descriptor) => descriptor.try_into()?,
            EntityDescriptorType::EntityDescriptor(descriptor) => descriptor.try_into()?,
        };
        writer.write_event(event)?;

        Ok(Event::Text(BytesText::from_escaped(String::from_utf8(
            write_buf,
        )?)))
    }
}

const ENTITIES_DESCRIPTOR_NAME: &str = "md:EntitiesDescriptor";

#[derive(Clone, Debug, Deserialize, Default, Hash, Eq, PartialEq, Ord, PartialOrd)]
#[serde(rename = "md:EntitiesDescriptor")]
pub struct EntitiesDescriptor {
    #[serde(rename = "@ID")]
    pub id: Option<String>,
    #[serde(rename = "@Name")]
    pub name: Option<String>,
    #[serde(rename = "@validUntil")]
    pub valid_until: Option<DateTime<Utc>>,
    #[serde(rename = "@cacheDuration")]
    pub cache_duration: Option<String>,
    #[serde(rename = "Signature")]
    pub signature: Option<Signature>,
    #[serde(default, rename = "$value")]
    pub descriptors: Vec<EntityDescriptorType>,
}

impl FromStr for EntitiesDescriptor {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(quick_xml::de::from_str(s)?)
    }
}

impl TryFrom<EntitiesDescriptor> for Event<'_> {
    type Error = Box<dyn std::error::Error>;

    fn try_from(value: EntitiesDescriptor) -> Result<Self, Self::Error> {
        (&value).try_into()
    }
}

impl TryFrom<&EntitiesDescriptor> for Event<'_> {
    type Error = Box<dyn std::error::Error>;

    fn try_from(value: &EntitiesDescriptor) -> Result<Self, Self::Error> {
        let mut write_buf = Vec::new();
        let mut writer = Writer::new(Cursor::new(&mut write_buf));
        writer.write_event(Event::Decl(BytesDecl::new("1.0", Some("UTF-8"), None)))?;

        let mut root = BytesStart::new(ENTITIES_DESCRIPTOR_NAME);
        root.push_attribute(("xmlns:md", "urn:oasis:names:tc:SAML:2.0:metadata"));
        root.push_attribute((
            "xmlns:alg",
            "urn:oasis:names:tc:SAML:2.0:metadata:algsupport",
        ));
        root.push_attribute(("xmlns:mdui", "urn:oasis:names:tc:SAML:metadata:ui"));
        root.push_attribute(("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"));

        if let Some(id) = &value.id {
            root.push_attribute(("ID", id.as_ref()))
        }

        if let Some(name) = &value.name {
            root.push_attribute(("Name", name.as_ref()))
        }

        if let Some(valid_until) = &value.valid_until {
            root.push_attribute((
                "validUntil",
                valid_until
                    .to_rfc3339_opts(SecondsFormat::Secs, true)
                    .as_ref(),
            ))
        }

        if let Some(cache_duration) = &value.cache_duration {
            root.push_attribute(("cacheDuration", cache_duration.as_ref()));
        }

        writer.write_event(Event::Start(root))?;
        for descriptor in &value.descriptors {
            let event: Event<'_> = descriptor.try_into()?;
            writer.write_event(event)?;
        }

        writer.write_event(Event::End(BytesEnd::new(ENTITIES_DESCRIPTOR_NAME)))?;

        Ok(Event::Text(BytesText::from_escaped(String::from_utf8(
            write_buf,
        )?)))
    }
}

const ENTITY_DESCRIPTOR_NAME: &str = "md:EntityDescriptor";

#[derive(Clone, Debug, Deserialize, Default, Hash, Eq, PartialEq, Ord, PartialOrd)]
#[serde(rename = "md:EntityDescriptor")]
pub struct EntityDescriptor {
    #[serde(rename = "@entityID")]
    pub entity_id: Option<String>,
    #[serde(rename = "@ID")]
    pub id: Option<String>,
    #[serde(rename = "Signature")]
    pub signature: Option<Signature>,
    #[serde(rename = "@validUntil")]
    pub valid_until: Option<DateTime<Utc>>,
    #[serde(rename = "@cacheDuration")]
    pub cache_duration: Option<String>,
    #[serde(rename = "RoleDescriptor")]
    pub role_descriptors: Option<Vec<RoleDescriptor>>,
    #[serde(rename = "IDPSSODescriptor")]
    pub idp_sso_descriptors: Option<Vec<IdpSsoDescriptor>>,
    #[serde(rename = "SPSSODescriptor")]
    pub sp_sso_descriptors: Option<Vec<SpSsoDescriptor>>,
    #[serde(rename = "AuthnAuthorityDescriptor")]
    pub authn_authority_descriptors: Option<Vec<AuthnAuthorityDescriptors>>,
    #[serde(rename = "AttributeAuthorityDescriptor")]
    pub attribute_authority_descriptors: Option<Vec<AttributeAuthorityDescriptors>>,
    #[serde(rename = "PDPDescriptor")]
    pub pdp_descriptors: Option<Vec<PdpDescriptors>>,
    #[serde(rename = "AffiliationDescriptor")]
    pub affiliation_descriptors: Option<AffiliationDescriptor>,
    #[serde(rename = "ContactPerson", default)]
    pub contact_person: Option<Vec<ContactPerson>>,
    #[serde(rename = "Organization")]
    pub organization: Option<Organization>,
}

impl FromStr for EntityDescriptor {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(quick_xml::de::from_str(s)?)
    }
}

impl TryFrom<EntityDescriptor> for Event<'_> {
    type Error = Box<dyn std::error::Error>;

    fn try_from(value: EntityDescriptor) -> Result<Self, Self::Error> {
        (&value).try_into()
    }
}

impl TryFrom<&EntityDescriptor> for Event<'_> {
    type Error = Box<dyn std::error::Error>;

    fn try_from(value: &EntityDescriptor) -> Result<Self, Self::Error> {
        let mut write_buf = Vec::new();
        let mut writer = Writer::new(Cursor::new(&mut write_buf));
        writer.write_event(Event::Decl(BytesDecl::new("1.0", Some("UTF-8"), None)))?;

        let mut root = BytesStart::new(ENTITY_DESCRIPTOR_NAME);
        root.push_attribute(("xmlns:md", "urn:oasis:names:tc:SAML:2.0:metadata"));
        root.push_attribute(("xmlns:saml", "urn:oasis:names:tc:SAML:2.0:assertion"));
        root.push_attribute(("xmlns:mdrpi", "urn:oasis:names:tc:SAML:metadata:rpi"));
        root.push_attribute(("xmlns:mdattr", "urn:oasis:names:tc:SAML:metadata:attribute"));
        root.push_attribute(("xmlns:mdui", "urn:oasis:names:tc:SAML:metadata:ui"));
        root.push_attribute(("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"));
        root.push_attribute((
            "xmlns:idpdisc",
            "urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol",
        ));

        if let Some(entity_id) = &value.entity_id {
            root.push_attribute(("entityID", entity_id.as_ref()))
        }
        if let Some(valid_until) = &value.valid_until {
            root.push_attribute((
                "validUntil",
                valid_until
                    .to_rfc3339_opts(SecondsFormat::Secs, true)
                    .as_ref(),
            ))
        }
        if let Some(cache_duration) = &value.cache_duration {
            root.push_attribute(("cacheDuration", cache_duration.as_ref()));
        }

        writer.write_event(Event::Start(root))?;
        for descriptor in value.sp_sso_descriptors.as_ref().unwrap_or(&vec![]) {
            let event: Event<'_> = descriptor.try_into()?;
            writer.write_event(event)?;
        }

        for descriptor in value.idp_sso_descriptors.as_ref().unwrap_or(&vec![]) {
            let event: Event<'_> = descriptor.try_into()?;
            writer.write_event(event)?;
        }

        if let Some(organization) = &value.organization {
            let event: Event<'_> = organization.try_into()?;
            writer.write_event(event)?;
        }

        if let Some(contact_persons) = &value.contact_person {
            for contact_person in contact_persons {
                let event: Event<'_> = contact_person.try_into()?;
                writer.write_event(event)?;
            }
        }

        writer.write_event(Event::End(BytesEnd::new(ENTITY_DESCRIPTOR_NAME)))?;

        Ok(Event::Text(BytesText::from_escaped(String::from_utf8(
            write_buf,
        )?)))
    }
}

#[derive(Clone)]
pub struct EntityDescriptorIterator<'a> {
    queue: VecDeque<&'a EntityDescriptorType>,
}

impl<'a> EntityDescriptorIterator<'a> {
    pub fn new(root: &'a EntityDescriptorType) -> Self {
        let mut queue = VecDeque::new();
        queue.push_back(root);
        EntityDescriptorIterator { queue }
    }
}

impl<'a> Iterator for EntityDescriptorIterator<'a> {
    type Item = &'a EntityDescriptor;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(current) = self.queue.pop_front() {
            match current {
                EntityDescriptorType::EntitiesDescriptor(entities_descriptor) => {
                    for descriptor in &entities_descriptor.descriptors {
                        self.queue.push_back(descriptor);
                    }
                }
                EntityDescriptorType::EntityDescriptor(entity_descriptor) => {
                    return Some(entity_descriptor);
                }
            }
        }
        None
    }
}

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

    use super::{EntitiesDescriptor, EntityDescriptor, EntityDescriptorType};

    #[test]
    fn test_sp_entity_descriptor() {
        let input_xml = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/test_vectors/sp_metadata.xml"
        ));
        println!("{}", &input_xml);
        let entity_descriptor: EntityDescriptor = input_xml
            .parse()
            .expect("Failed to parse sp_metadata.xml into an EntityDescriptor");
        let output_xml = entity_descriptor
            .to_string()
            .expect("Failed to convert EntityDescriptor to xml");
        let reparsed_entity_descriptor: EntityDescriptor = output_xml
            .parse()
            .expect("Failed to parse EntityDescriptor");

        assert_eq!(reparsed_entity_descriptor, entity_descriptor);
    }

    #[test]
    fn test_idp_entity_descriptor() {
        let input_xml = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/test_vectors/idp_metadata.xml"
        ));
        let entity_descriptor: EntityDescriptor = input_xml
            .parse()
            .expect("Failed to parse idp_metadata.xml into an EntityDescriptor");
        let output_xml = entity_descriptor
            .to_string()
            .expect("Failed to convert EntityDescriptor to xml");
        let reparsed_entity_descriptor: EntityDescriptor = output_xml
            .parse()
            .expect("Failed to parse EntityDescriptor");

        assert_eq!(reparsed_entity_descriptor, entity_descriptor);
    }

    #[test]
    fn test_idp_entities_descriptor() {
        let input_xml = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/test_vectors/idp_metadata_nested.xml"
        ));
        let entities_descriptor: EntitiesDescriptor = input_xml
            .parse()
            .expect("Failed to parse idp_metadata_nested.xml into an EntitiesDescriptor");
        let output_xml = entities_descriptor
            .to_string()
            .expect("Failed to convert EntitiesDescriptor to xml");
        let reparsed_entities_descriptor: EntitiesDescriptor = output_xml
            .parse()
            .expect("Failed to parse EntitiesDescriptor");

        assert_eq!(2, reparsed_entities_descriptor.descriptors.len());
        assert_eq!(reparsed_entities_descriptor, entities_descriptor);
    }

    #[test]
    fn test_idp_entity_descriptor_type() {
        let input_xml = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/test_vectors/idp_metadata.xml"
        ));
        let entity_descriptor_type: EntityDescriptorType = input_xml
            .parse()
            .expect("Failed to parse idp_metadata.xml into an EntityDescriptorType");
        let output_xml = entity_descriptor_type
            .to_string()
            .expect("Failed to convert EntityDescriptorType to xml");
        let reparsed_entity_descriptor_type: EntityDescriptorType = output_xml
            .parse()
            .expect("Failed to parse EntityDescriptorType");

        assert_eq!(reparsed_entity_descriptor_type, entity_descriptor_type);

        let expected_entity_descriptor: EntityDescriptor = input_xml
            .parse()
            .expect("Failed to parse idp_metadata.xml into an EntityDescriptor");
        let entity_descriptor = entity_descriptor_type
            .iter()
            .next()
            .expect("Failed to take first EntityDescriptor from EntityDescriptorType");

        assert_eq!(&expected_entity_descriptor, entity_descriptor);
    }

    #[test]
    fn test_idp_entity_descriptor_type_nested() {
        let input_xml = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/test_vectors/idp_metadata_nested.xml"
        ));
        let entity_descriptor_type: EntityDescriptorType = input_xml
            .parse()
            .expect("Failed to parse idp_metadata_nested.xml into an EntityDescriptorType");
        let output_xml = entity_descriptor_type
            .to_string()
            .expect("Failed to convert EntityDescriptorType to xml");
        let reparsed_entity_descriptor_type: EntityDescriptorType = output_xml
            .parse()
            .expect("Failed to parse EntityDescriptorType");

        assert_eq!(reparsed_entity_descriptor_type, entity_descriptor_type);

        let input_xml = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/test_vectors/idp_metadata.xml"
        ));
        let expected_entity_descriptor: EntityDescriptor = input_xml
            .parse()
            .expect("Failed to parse idp_metadata.xml into an EntityDescriptor");
        let entity_descriptor = entity_descriptor_type
            .iter()
            .next()
            .expect("Failed to take first EntityDescriptor from EntityDescriptorType");
        println!("{entity_descriptor:#?}");

        assert_eq!(&expected_entity_descriptor, entity_descriptor);
    }
}

#[cfg(test)]
mod contact_person_tests {
    use super::*;

    #[test]
    fn deserialize_multiple_contact_persons() {
        let xml = r#"<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="https://test.example.org">
  <ContactPerson contactType="technical">
    <GivenName>Test</GivenName>
  </ContactPerson>
  <ContactPerson contactType="support">
    <GivenName>Test2</GivenName>
  </ContactPerson>
</EntityDescriptor>"#;

        let ed: EntityDescriptor = quick_xml::de::from_str(xml).unwrap();
        let contacts = ed.contact_person.expect("contact_person should be Some");
        assert_eq!(contacts.len(), 2);
    }
}

#[cfg(test)]
mod contact_person_ns_tests {
    use super::*;

    #[test]
    fn deserialize_contact_person_with_namespaced_attribute() {
        let xml = r#"<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="https://test.example.org">
  <ContactPerson contactType="technical">
    <GivenName>Test</GivenName>
  </ContactPerson>
  <ContactPerson xmlns:remd="http://refeds.org/metadata" contactType="other" remd:contactType="http://refeds.org/metadata/contactType/security">
    <GivenName>Test2</GivenName>
  </ContactPerson>
</EntityDescriptor>"#;

        let ed: EntityDescriptor = quick_xml::de::from_str(xml).unwrap();
        let contacts = ed.contact_person.expect("contact_person should be Some");
        assert_eq!(contacts.len(), 2);
    }
}