gamlastan 0.9.0

SAML 2.0 library - types, XML, crypto, metadata, bindings, security, profiles
Documentation
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
481
482
483
484
485
//! Metadata validation and endpoint resolution.
//!
//! The type system captures the metadata shape, but runtime validation still
//! checks required endpoint lists, forbidden `ResponseLocation` attributes on
//! some services, protocol support declarations, and entityID constraints.
//!
//! Endpoint helpers implement the default and binding-preference selection rules
//! used by SAML profiles.

use crate::metadata::error::MetadataError;
use crate::metadata::types::endpoint::{Endpoint, IndexedEndpoint};
use crate::metadata::types::entity_descriptor::EntityDescriptor;
use crate::metadata::types::idp::IdpSsoDescriptor;
use crate::metadata::types::sp::SpSsoDescriptor;

/// Metadata validator configuration.
pub struct MetadataValidator {
    /// Whether to require at least one SSO service for IdP descriptors.
    pub require_sso_service: bool,
    /// Whether to require at least one ACS for SP descriptors.
    pub require_acs: bool,
}

impl Default for MetadataValidator {
    fn default() -> Self {
        MetadataValidator {
            require_sso_service: true,
            require_acs: true,
        }
    }
}

impl MetadataValidator {
    /// Create a new validator with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Validate an EntityDescriptor.
    pub fn validate(&self, entity: &EntityDescriptor) -> Result<(), MetadataError> {
        // Check entity ID constraints
        if entity.entity_id.is_empty() {
            return Err(MetadataError::SchemaViolation(
                "EntityDescriptor entityID must not be empty".to_string(),
            ));
        }
        if entity.entity_id.len() > 1024 {
            return Err(MetadataError::SchemaViolation(format!(
                "EntityDescriptor entityID exceeds 1024 characters: {} chars",
                entity.entity_id.len()
            )));
        }

        // Validate IdP descriptors
        for idp in entity.idp_sso_descriptors() {
            self.validate_idp(idp)?;
        }

        // Validate SP descriptors
        for sp in entity.sp_sso_descriptors() {
            self.validate_sp(sp)?;
        }

        Ok(())
    }

    /// Validate an IDPSSODescriptor.
    fn validate_idp(&self, idp: &IdpSsoDescriptor) -> Result<(), MetadataError> {
        // SingleSignOnService is required (1..n)
        if self.require_sso_service && idp.single_sign_on_services.is_empty() {
            return Err(MetadataError::MissingRequiredEndpoint(
                "IDPSSODescriptor must have at least one SingleSignOnService".to_string(),
            ));
        }

        // SingleSignOnService MUST NOT have ResponseLocation
        for sso in &idp.single_sign_on_services {
            if sso.response_location.is_some() {
                return Err(MetadataError::SchemaViolation(
                    "SingleSignOnService MUST NOT have ResponseLocation".to_string(),
                ));
            }
        }

        // NameIDMappingService MUST NOT have ResponseLocation
        for nidms in &idp.name_id_mapping_services {
            if nidms.response_location.is_some() {
                return Err(MetadataError::SchemaViolation(
                    "NameIDMappingService MUST NOT have ResponseLocation".to_string(),
                ));
            }
        }

        // ArtifactResolutionService MUST NOT have ResponseLocation
        for ars in &idp.sso_base.artifact_resolution_services {
            if ars.endpoint.response_location.is_some() {
                return Err(MetadataError::SchemaViolation(
                    "ArtifactResolutionService MUST NOT have ResponseLocation".to_string(),
                ));
            }
        }

        // protocolSupportEnumeration is required
        if idp.sso_base.base.protocol_support_enumeration.is_empty() {
            return Err(MetadataError::SchemaViolation(
                "RoleDescriptor must specify at least one supported protocol".to_string(),
            ));
        }

        Ok(())
    }

    /// Validate an SPSSODescriptor.
    fn validate_sp(&self, sp: &SpSsoDescriptor) -> Result<(), MetadataError> {
        // AssertionConsumerService is required (1..n)
        if self.require_acs && sp.assertion_consumer_services.is_empty() {
            return Err(MetadataError::MissingRequiredEndpoint(
                "SPSSODescriptor must have at least one AssertionConsumerService".to_string(),
            ));
        }

        // ArtifactResolutionService MUST NOT have ResponseLocation
        for ars in &sp.sso_base.artifact_resolution_services {
            if ars.endpoint.response_location.is_some() {
                return Err(MetadataError::SchemaViolation(
                    "ArtifactResolutionService MUST NOT have ResponseLocation".to_string(),
                ));
            }
        }

        // protocolSupportEnumeration is required
        if sp.sso_base.base.protocol_support_enumeration.is_empty() {
            return Err(MetadataError::SchemaViolation(
                "RoleDescriptor must specify at least one supported protocol".to_string(),
            ));
        }

        Ok(())
    }
}

/// Resolve the default endpoint from a list of indexed endpoints.
///
/// Per the SAML metadata spec:
/// 1. The endpoint with isDefault=true, if any
/// 2. The first endpoint with isDefault unset (not explicitly false)
/// 3. The endpoint with the lowest index
pub fn resolve_default_indexed_endpoint(endpoints: &[IndexedEndpoint]) -> Option<&IndexedEndpoint> {
    if endpoints.is_empty() {
        return None;
    }

    // 1. Look for isDefault=true
    if let Some(ep) = endpoints.iter().find(|e| e.is_default == Some(true)) {
        return Some(ep);
    }

    // 2. Look for isDefault unset (None, not Some(false))
    if let Some(ep) = endpoints.iter().find(|e| e.is_default.is_none()) {
        return Some(ep);
    }

    // 3. Lowest index
    endpoints.iter().min_by_key(|e| e.index)
}

/// Resolve an endpoint by binding URI from a list of endpoints.
pub fn resolve_endpoint_by_binding<'a>(
    endpoints: &'a [Endpoint],
    binding: &str,
) -> Option<&'a Endpoint> {
    endpoints.iter().find(|e| e.binding == binding)
}

/// Resolve an indexed endpoint by binding URI.
pub fn resolve_indexed_endpoint_by_binding<'a>(
    endpoints: &'a [IndexedEndpoint],
    binding: &str,
) -> Option<&'a IndexedEndpoint> {
    endpoints.iter().find(|e| e.endpoint.binding == binding)
}

/// Negotiate an endpoint from an ordered list of binding preferences.
///
/// Returns the endpoint for the first preference that the peer supports
/// (mirrors pysaml2's `pick_binding` / `preferred_binding` behavior).
/// Returns `None` if no preferred binding is offered; callers may then fall
/// back to `endpoints.first()` if any binding is acceptable.
pub fn negotiate_endpoint_by_preference<'a>(
    endpoints: &'a [Endpoint],
    binding_preferences: &[&str],
) -> Option<&'a Endpoint> {
    binding_preferences
        .iter()
        .find_map(|binding| resolve_endpoint_by_binding(endpoints, binding))
}

/// Negotiate an indexed endpoint from an ordered list of binding preferences.
pub fn negotiate_indexed_endpoint_by_preference<'a>(
    endpoints: &'a [IndexedEndpoint],
    binding_preferences: &[&str],
) -> Option<&'a IndexedEndpoint> {
    binding_preferences
        .iter()
        .find_map(|binding| resolve_indexed_endpoint_by_binding(endpoints, binding))
}

/// Default binding preference orders per service, mirroring pysaml2's
/// `preferred_binding` configuration defaults.
pub mod binding_preferences {
    const HTTP_REDIRECT: &str = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect";
    const HTTP_POST: &str = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
    const HTTP_ARTIFACT: &str = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact";
    const SOAP: &str = "urn:oasis:names:tc:SAML:2.0:bindings:SOAP";

    /// SingleSignOnService preference order.
    pub const SINGLE_SIGN_ON: &[&str] = &[HTTP_REDIRECT, HTTP_POST, HTTP_ARTIFACT];

    /// AssertionConsumerService preference order.
    pub const ASSERTION_CONSUMER: &[&str] = &[HTTP_POST, HTTP_REDIRECT, HTTP_ARTIFACT];

    /// SingleLogoutService preference order.
    pub const SINGLE_LOGOUT: &[&str] = &[SOAP, HTTP_REDIRECT, HTTP_POST, HTTP_ARTIFACT];

    /// ManageNameIDService preference order.
    pub const MANAGE_NAME_ID: &[&str] = &[SOAP, HTTP_REDIRECT, HTTP_POST, HTTP_ARTIFACT];

    /// ArtifactResolutionService preference order.
    pub const ARTIFACT_RESOLUTION: &[&str] = &[SOAP];

    /// NameIDMappingService / AttributeService / AuthnQueryService /
    /// AuthzService preference order (back-channel only).
    pub const BACK_CHANNEL_QUERY: &[&str] = &[SOAP];
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metadata::types::endpoint::{Endpoint, IndexedEndpoint};
    use crate::metadata::types::entity_descriptor::{EntityDescriptor, EntityRoles};
    use crate::metadata::types::role_descriptor::{RoleDescriptorBase, SsoDescriptorBase};

    #[test]
    fn test_negotiate_endpoint_by_preference() {
        let endpoints = vec![
            Endpoint::new(
                "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
                "https://idp.example.com/sso/post",
            ),
            Endpoint::new(
                "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
                "https://idp.example.com/sso/redirect",
            ),
        ];

        // Default SSO preference order picks Redirect first
        let ep = negotiate_endpoint_by_preference(&endpoints, binding_preferences::SINGLE_SIGN_ON)
            .unwrap();
        assert!(ep.location.contains("redirect"));

        // SLO order prefers SOAP, falls through to Redirect
        let ep = negotiate_endpoint_by_preference(&endpoints, binding_preferences::SINGLE_LOGOUT)
            .unwrap();
        assert!(ep.location.contains("redirect"));

        // No match when only unsupported bindings preferred
        assert!(negotiate_endpoint_by_preference(
            &endpoints,
            binding_preferences::ARTIFACT_RESOLUTION
        )
        .is_none());
    }

    #[test]
    fn test_negotiate_indexed_endpoint_by_preference() {
        let endpoints = vec![IndexedEndpoint::new(
            Endpoint::new(
                "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
                "https://sp.example.com/acs",
            ),
            0,
        )];
        let ep = negotiate_indexed_endpoint_by_preference(
            &endpoints,
            binding_preferences::ASSERTION_CONSUMER,
        )
        .unwrap();
        assert!(ep.endpoint.location.contains("acs"));
    }

    fn make_sso_base() -> SsoDescriptorBase {
        SsoDescriptorBase {
            base: RoleDescriptorBase::new(vec!["urn:oasis:names:tc:SAML:2.0:protocol".to_string()]),
            artifact_resolution_services: vec![],
            single_logout_services: vec![],
            manage_name_id_services: vec![],
            name_id_formats: vec![],
        }
    }

    #[test]
    fn test_validate_empty_entity_id() {
        let entity = EntityDescriptor {
            entity_id: String::new(),
            id: None,
            valid_until: None,
            cache_duration: None,
            has_signature: false,
            extensions: None,
            roles: EntityRoles::Roles {
                idp_sso: vec![],
                sp_sso: vec![],
                authn_authority: vec![],
                attr_authority: vec![],
                pdp: vec![],
            },
            organization: None,
            contact_persons: vec![],
            additional_metadata_locations: vec![],
        };
        let v = MetadataValidator::new();
        assert!(v.validate(&entity).is_err());
    }

    #[test]
    fn test_validate_idp_missing_sso() {
        let entity = EntityDescriptor {
            entity_id: "https://idp.example.com".to_string(),
            id: None,
            valid_until: None,
            cache_duration: None,
            has_signature: false,
            extensions: None,
            roles: EntityRoles::Roles {
                idp_sso: vec![IdpSsoDescriptor {
                    sso_base: make_sso_base(),
                    want_authn_requests_signed: None,
                    single_sign_on_services: vec![], // Missing!
                    name_id_mapping_services: vec![],
                    assertion_id_request_services: vec![],
                    attribute_profiles: vec![],
                    attributes: vec![],
                }],
                sp_sso: vec![],
                authn_authority: vec![],
                attr_authority: vec![],
                pdp: vec![],
            },
            organization: None,
            contact_persons: vec![],
            additional_metadata_locations: vec![],
        };
        let v = MetadataValidator::new();
        let err = v.validate(&entity).unwrap_err();
        assert!(err.to_string().contains("SingleSignOnService"));
    }

    #[test]
    fn test_validate_idp_sso_response_location_rejected() {
        let entity = EntityDescriptor {
            entity_id: "https://idp.example.com".to_string(),
            id: None,
            valid_until: None,
            cache_duration: None,
            has_signature: false,
            extensions: None,
            roles: EntityRoles::Roles {
                idp_sso: vec![IdpSsoDescriptor {
                    sso_base: make_sso_base(),
                    want_authn_requests_signed: None,
                    single_sign_on_services: vec![Endpoint::with_response_location(
                        "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
                        "https://idp.example.com/sso",
                        "https://idp.example.com/sso-response", // Not allowed!
                    )],
                    name_id_mapping_services: vec![],
                    assertion_id_request_services: vec![],
                    attribute_profiles: vec![],
                    attributes: vec![],
                }],
                sp_sso: vec![],
                authn_authority: vec![],
                attr_authority: vec![],
                pdp: vec![],
            },
            organization: None,
            contact_persons: vec![],
            additional_metadata_locations: vec![],
        };
        let v = MetadataValidator::new();
        let err = v.validate(&entity).unwrap_err();
        assert!(err.to_string().contains("ResponseLocation"));
    }

    #[test]
    fn test_validate_sp_missing_acs() {
        let entity = EntityDescriptor {
            entity_id: "https://sp.example.com".to_string(),
            id: None,
            valid_until: None,
            cache_duration: None,
            has_signature: false,
            extensions: None,
            roles: EntityRoles::Roles {
                idp_sso: vec![],
                sp_sso: vec![SpSsoDescriptor {
                    sso_base: make_sso_base(),
                    authn_requests_signed: None,
                    want_assertions_signed: None,
                    assertion_consumer_services: vec![], // Missing!
                    attribute_consuming_services: vec![],
                }],
                authn_authority: vec![],
                attr_authority: vec![],
                pdp: vec![],
            },
            organization: None,
            contact_persons: vec![],
            additional_metadata_locations: vec![],
        };
        let v = MetadataValidator::new();
        let err = v.validate(&entity).unwrap_err();
        assert!(err.to_string().contains("AssertionConsumerService"));
    }

    #[test]
    fn test_resolve_default_indexed_endpoint() {
        let eps = vec![
            IndexedEndpoint::new(Endpoint::new("urn:binding:1", "https://example.com/1"), 0),
            IndexedEndpoint::new_default(
                Endpoint::new("urn:binding:2", "https://example.com/2"),
                1,
            ),
        ];
        let default = resolve_default_indexed_endpoint(&eps).unwrap();
        assert_eq!(default.index, 1); // isDefault=true wins
    }

    #[test]
    fn test_resolve_default_indexed_endpoint_none_set() {
        let eps = vec![
            IndexedEndpoint {
                endpoint: Endpoint::new("urn:binding:1", "https://example.com/1"),
                index: 2,
                is_default: None,
            },
            IndexedEndpoint {
                endpoint: Endpoint::new("urn:binding:2", "https://example.com/2"),
                index: 0,
                is_default: None,
            },
        ];
        // First with is_default=None wins (index 2 comes first in iteration)
        let default = resolve_default_indexed_endpoint(&eps).unwrap();
        assert_eq!(default.index, 2);
    }

    #[test]
    fn test_resolve_endpoint_by_binding() {
        let eps = vec![
            Endpoint::new(
                "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
                "https://idp.example.com/sso/redirect",
            ),
            Endpoint::new(
                "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
                "https://idp.example.com/sso/post",
            ),
        ];
        let ep =
            resolve_endpoint_by_binding(&eps, "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")
                .unwrap();
        assert_eq!(ep.location, "https://idp.example.com/sso/post");
    }

    #[test]
    fn test_resolve_endpoint_by_binding_not_found() {
        let eps = vec![Endpoint::new(
            "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
            "https://idp.example.com/sso",
        )];
        let ep = resolve_endpoint_by_binding(&eps, "urn:oasis:names:tc:SAML:2.0:bindings:SOAP");
        assert!(ep.is_none());
    }
}