saml 0.0.1-alpha.1

Stateless, async-native SAML 2.0 toolkit with no libxml2/xmlsec C build chain
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Cross-check parsed AuthnRequest against SP metadata + caller-supplied
//! destination, producing the public [`ParsedAuthnRequest`].
//!
//! Implements RFC-004 §2.1 steps 4 (Issuer match), 5 (Destination check),
//! 5a + 7 (ACS resolution), 7a (binding consistency). Step 5a is performed at
//! parse time in [`super::request_parse`] (it depends only on the wire
//! ProtocolBinding URI, not on metadata); the rest live here.
//!
//! The key security property below is **echo prevention** on the ACS URL:
//! the SP-supplied `AssertionConsumerServiceURL` is *never* trusted directly.
//! It must match a URL already advertised in `SpDescriptor`, otherwise the
//! request is rejected with [`Error::UnregisteredAcs`]. The resolved endpoint
//! flows into [`ParsedAuthnRequest::assertion_consumer_service`] as an
//! [`SsoResponseEndpoint`] cloned from the descriptor — by construction it
//! can only be a registered URL, and by the type's invariants it can only
//! carry a POST or Artifact binding.

use std::time::SystemTime;

use crate::authn::request_parse::RawParsedAuthnRequest;
use crate::authn_context::RequestedAuthnContext;
use crate::binding::{SsoResponseBinding, SsoResponseEndpoint};
use crate::descriptor::sp::SpDescriptor;
use crate::error::Error;
use crate::nameid::NameIdFormat;

/// The validated AuthnRequest the IdP role hands back to its caller. Mirrors
/// RFC-004 §2 `ParsedAuthnRequest` verbatim.
#[derive(Debug, Clone)]
pub struct ParsedAuthnRequest {
    pub id: String,
    pub issuer: String,
    pub issue_instant: SystemTime,
    pub destination: Option<String>,
    /// Resolved ACS endpoint — always points at a registered SP endpoint
    /// (never the SP-supplied URL). RFC-004 §2.1 step 7 (echo-prevention).
    pub assertion_consumer_service: SsoResponseEndpoint,
    /// What binding the SP requested for the Response. Parser already
    /// narrowed to POST/Artifact (illegal Redirect/SOAP rejected at parse
    /// time). `None` means the AuthnRequest carried no `@ProtocolBinding`.
    pub protocol_binding: Option<SsoResponseBinding>,
    /// Raw selection from the request, kept for logging.
    pub assertion_consumer_service_selection: AcsSelection,
    pub force_authn: bool,
    pub is_passive: bool,
    pub requested_name_id_format: Option<NameIdFormat>,
    pub requested_authn_context: Option<RequestedAuthnContext>,
    /// RelayState forwarded from the binding layer (Redirect query string, or
    /// POST form). Optional. Set by the caller (sp/idp role), not here —
    /// `validate_authn_request` initializes this to `None`; the caller
    /// overwrites it after a successful validate.
    pub relay_state: Option<String>,
}

/// How the SP nominated its ACS endpoint on the wire. Retained on the
/// validated request for logging / metrics; resolution has already happened.
#[derive(Debug, Clone)]
pub enum AcsSelection {
    /// SP specified `AssertionConsumerServiceIndex`.
    Index(u16),
    /// SP specified `AssertionConsumerServiceURL`.
    Url(String),
    /// SP specified neither — IdP used SP metadata's default endpoint.
    Default,
}

/// Apply RFC-004 §2.1 steps 4, 5, 7, 7a to the raw parsed request.
///
/// `expected_destination` is the URL of the IdP SSO endpoint that received
/// the message; `sp_sso_endpoint_urls` is the IdP's own registered SSO
/// endpoint URL set (so this function can reject callers that pass a
/// destination not registered in their own metadata — the
/// "RFC-004 §2.1 step 5 caller-bug guard").
pub(crate) fn validate_authn_request(
    raw: RawParsedAuthnRequest,
    sp: &SpDescriptor,
    expected_destination: &str,
    sp_sso_endpoint_urls: &[String],
) -> Result<ParsedAuthnRequest, Error> {
    // Step 4: Issuer match.
    if raw.issuer != sp.entity_id {
        return Err(Error::IssuerMismatch {
            expected: sp.entity_id.clone(),
            got: Some(raw.issuer),
        });
    }

    // Step 5: Destination binding.
    //
    // First, the caller must have routed this AuthnRequest to an endpoint
    // they actually advertise in metadata. Treat the absence as an
    // InvalidConfiguration (caller bug, not wire-format issue).
    if !sp_sso_endpoint_urls
        .iter()
        .any(|u| u == expected_destination)
    {
        return Err(Error::InvalidConfiguration {
            reason: "expected_destination is not a registered SSO endpoint",
        });
    }
    // Second, if the AuthnRequest carries `@Destination`, it MUST match.
    // Absence is permitted (the spec marks Destination as optional on
    // AuthnRequest); presence is binding.
    if let Some(dest) = raw.destination.as_deref()
        && dest != expected_destination
    {
        return Err(Error::DestinationMismatch);
    }

    // Step 7: ACS resolution.
    //
    // The order — Index → URL → Default — mirrors the SAML 2.0 schema's
    // attribute precedence: when both Index and URL are supplied, the
    // schema is ambiguous and most IdPs (Okta, Auth0) honor Index. We never
    // reach the `URL` branch when an `Index` was supplied; the parser
    // surfaces both, but validation deliberately prefers the indirection
    // (an index can only point at a registered endpoint, so it is strictly
    // safer than a URL lookup).
    let unregistered = || Error::UnregisteredAcs {
        entity_id: sp.entity_id.clone(),
    };
    let (resolved, selection): (SsoResponseEndpoint, AcsSelection) =
        if let Some(index) = raw.assertion_consumer_service_index {
            let endpoint = sp
                .acs_endpoint_by_index(index)
                .cloned()
                .ok_or_else(unregistered)?;
            (endpoint, AcsSelection::Index(index))
        } else if let Some(url) = raw.assertion_consumer_service_url.as_deref() {
            let endpoint = sp
                .acs_endpoint_by_url(url)
                .cloned()
                .ok_or_else(unregistered)?;
            (endpoint, AcsSelection::Url(url.to_owned()))
        } else {
            let endpoint = sp.default_acs().cloned().ok_or_else(unregistered)?;
            (endpoint, AcsSelection::Default)
        };

    // Step 7a: binding consistency.
    //
    // If the SP requested a specific Response binding via `@ProtocolBinding`,
    // it must match the binding registered on the resolved ACS endpoint. We
    // already know the request value is a `SsoResponseBinding` (Redirect /
    // SOAP rejected at parse time), and the registry endpoint binding is
    // also a `SsoResponseBinding`, so the comparison is a direct equality
    // check.
    if let Some(requested) = raw.protocol_binding
        && requested != resolved.binding
    {
        return Err(Error::IllegalResponseBinding {
            requested: requested.as_binding(),
        });
    }

    Ok(ParsedAuthnRequest {
        id: raw.id,
        issuer: raw.issuer,
        issue_instant: raw.issue_instant,
        destination: raw.destination,
        assertion_consumer_service: resolved,
        protocol_binding: raw.protocol_binding,
        assertion_consumer_service_selection: selection,
        force_authn: raw.force_authn,
        is_passive: raw.is_passive,
        requested_name_id_format: raw.requested_name_id_format,
        requested_authn_context: raw.requested_authn_context,
        relay_state: None,
    })
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::authn::request_parse::parse_authn_request;
    use crate::binding::SsoResponseBinding;
    use crate::xml::parse::Document;

    /// Build an `SpDescriptor` directly via metadata XML (no encryption /
    /// signing certs needed for these tests — validation reads only the
    /// `entity_id` + ACS list).
    fn sp_with_acs_layout(acs_xml: &str) -> SpDescriptor {
        let xml = format!(
            r#"<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
                                     entityID="https://sp.example.com/saml">
              <md:SPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
                {acs_xml}
              </md:SPSSODescriptor>
            </md:EntityDescriptor>"#
        );
        SpDescriptor::from_metadata_xml(xml.as_bytes()).unwrap()
    }

    fn default_sp() -> SpDescriptor {
        sp_with_acs_layout(
            r#"<md:AssertionConsumerService index="0" isDefault="true"
                    Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
                    Location="https://sp.example.com/acs/post"/>
              <md:AssertionConsumerService index="1"
                    Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"
                    Location="https://sp.example.com/acs/artifact"/>"#,
        )
    }

    fn sso_urls() -> Vec<String> {
        vec!["https://idp.example.com/sso".to_string()]
    }

    fn raw_request(xml: &str) -> RawParsedAuthnRequest {
        let doc = Document::parse(xml.as_bytes()).unwrap();
        parse_authn_request(&doc).unwrap().0
    }

    const REQ_INDEX_0_POST: &str = r#"<samlp:AuthnRequest
            xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
            xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
            ID="_id" Version="2.0"
            IssueInstant="2026-05-26T12:34:56Z"
            Destination="https://idp.example.com/sso"
            AssertionConsumerServiceIndex="0"
            ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST">
          <saml:Issuer>https://sp.example.com/saml</saml:Issuer>
        </samlp:AuthnRequest>"#;

    #[test]
    fn happy_path_index_resolution() {
        let sp = default_sp();
        let parsed = validate_authn_request(
            raw_request(REQ_INDEX_0_POST),
            &sp,
            "https://idp.example.com/sso",
            &sso_urls(),
        )
        .expect("validate ok");

        assert_eq!(parsed.id, "_id");
        assert_eq!(parsed.issuer, "https://sp.example.com/saml");
        assert_eq!(
            parsed.assertion_consumer_service.url,
            "https://sp.example.com/acs/post"
        );
        assert_eq!(
            parsed.assertion_consumer_service.binding,
            SsoResponseBinding::HttpPost
        );
        match parsed.assertion_consumer_service_selection {
            AcsSelection::Index(0) => {}
            other => panic!("expected Index(0), got {other:?}"),
        }
        assert_eq!(parsed.protocol_binding, Some(SsoResponseBinding::HttpPost));
        assert!(parsed.relay_state.is_none());
    }

    #[test]
    fn happy_path_default_when_no_acs_attrs() {
        let xml = r#"<samlp:AuthnRequest
            xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
            xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
            ID="_id" Version="2.0"
            IssueInstant="2026-05-26T12:34:56Z"
            Destination="https://idp.example.com/sso">
          <saml:Issuer>https://sp.example.com/saml</saml:Issuer>
        </samlp:AuthnRequest>"#;
        let sp = default_sp();
        let parsed = validate_authn_request(
            raw_request(xml),
            &sp,
            "https://idp.example.com/sso",
            &sso_urls(),
        )
        .expect("validate ok");
        assert!(matches!(
            parsed.assertion_consumer_service_selection,
            AcsSelection::Default
        ));
        // Default ACS is the entry flagged isDefault="true".
        assert_eq!(
            parsed.assertion_consumer_service.url,
            "https://sp.example.com/acs/post"
        );
    }

    #[test]
    fn happy_path_url_resolution() {
        let xml = r#"<samlp:AuthnRequest
            xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
            xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
            ID="_id" Version="2.0"
            IssueInstant="2026-05-26T12:34:56Z"
            Destination="https://idp.example.com/sso"
            AssertionConsumerServiceURL="https://sp.example.com/acs/artifact">
          <saml:Issuer>https://sp.example.com/saml</saml:Issuer>
        </samlp:AuthnRequest>"#;
        let sp = default_sp();
        let parsed = validate_authn_request(
            raw_request(xml),
            &sp,
            "https://idp.example.com/sso",
            &sso_urls(),
        )
        .expect("validate ok");
        assert!(matches!(
            parsed.assertion_consumer_service_selection,
            AcsSelection::Url(ref u) if u == "https://sp.example.com/acs/artifact"
        ));
        assert_eq!(
            parsed.assertion_consumer_service.binding,
            SsoResponseBinding::HttpArtifact
        );
    }

    #[test]
    fn issuer_mismatch_is_structured_error() {
        let xml = r#"<samlp:AuthnRequest
            xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
            xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
            ID="_id" Version="2.0"
            IssueInstant="2026-05-26T12:34:56Z"
            Destination="https://idp.example.com/sso"
            AssertionConsumerServiceIndex="0">
          <saml:Issuer>https://other-sp.example.com/saml</saml:Issuer>
        </samlp:AuthnRequest>"#;
        let sp = default_sp();
        let err = validate_authn_request(
            raw_request(xml),
            &sp,
            "https://idp.example.com/sso",
            &sso_urls(),
        )
        .unwrap_err();
        match err {
            Error::IssuerMismatch { expected, got } => {
                assert_eq!(expected, "https://sp.example.com/saml");
                assert_eq!(got.as_deref(), Some("https://other-sp.example.com/saml"));
            }
            other => panic!("expected IssuerMismatch, got {other:?}"),
        }
    }

    #[test]
    fn destination_not_in_sso_list_is_invalid_configuration() {
        let sp = default_sp();
        let err = validate_authn_request(
            raw_request(REQ_INDEX_0_POST),
            &sp,
            "https://idp.example.com/sso", // request's @Destination
            // Empty: caller is asking us to validate against a destination
            // they don't actually advertise.
            &[],
        )
        .unwrap_err();
        match err {
            Error::InvalidConfiguration { reason } => {
                assert_eq!(
                    reason,
                    "expected_destination is not a registered SSO endpoint"
                );
            }
            other => panic!("expected InvalidConfiguration, got {other:?}"),
        }
    }

    #[test]
    fn destination_mismatch_with_request_attr() {
        let xml = r#"<samlp:AuthnRequest
            xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
            xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
            ID="_id" Version="2.0"
            IssueInstant="2026-05-26T12:34:56Z"
            Destination="https://idp.example.com/sso-other"
            AssertionConsumerServiceIndex="0">
          <saml:Issuer>https://sp.example.com/saml</saml:Issuer>
        </samlp:AuthnRequest>"#;
        let sp = default_sp();
        let err = validate_authn_request(
            raw_request(xml),
            &sp,
            "https://idp.example.com/sso",
            &sso_urls(),
        )
        .unwrap_err();
        match err {
            Error::DestinationMismatch => {}
            other => panic!("expected DestinationMismatch, got {other:?}"),
        }
    }

    #[test]
    fn destination_absent_on_request_is_accepted() {
        let xml = r#"<samlp:AuthnRequest
            xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
            xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
            ID="_id" Version="2.0"
            IssueInstant="2026-05-26T12:34:56Z"
            AssertionConsumerServiceIndex="0">
          <saml:Issuer>https://sp.example.com/saml</saml:Issuer>
        </samlp:AuthnRequest>"#;
        let sp = default_sp();
        let parsed = validate_authn_request(
            raw_request(xml),
            &sp,
            "https://idp.example.com/sso",
            &sso_urls(),
        )
        .expect("validate ok");
        assert!(parsed.destination.is_none());
    }

    #[test]
    fn acs_index_unknown_is_unregistered() {
        let xml = r#"<samlp:AuthnRequest
            xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
            xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
            ID="_id" Version="2.0"
            IssueInstant="2026-05-26T12:34:56Z"
            Destination="https://idp.example.com/sso"
            AssertionConsumerServiceIndex="42">
          <saml:Issuer>https://sp.example.com/saml</saml:Issuer>
        </samlp:AuthnRequest>"#;
        let sp = default_sp();
        let err = validate_authn_request(
            raw_request(xml),
            &sp,
            "https://idp.example.com/sso",
            &sso_urls(),
        )
        .unwrap_err();
        match err {
            Error::UnregisteredAcs { entity_id } => {
                assert_eq!(entity_id, "https://sp.example.com/saml");
            }
            other => panic!("expected UnregisteredAcs, got {other:?}"),
        }
    }

    #[test]
    fn acs_url_unknown_is_unregistered() {
        // Echo-attack defense: an SP claiming an off-list ACS URL must NOT
        // be honored. The validator's resolved endpoint is structurally
        // unable to point at a non-registered URL.
        let xml = r#"<samlp:AuthnRequest
            xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
            xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
            ID="_id" Version="2.0"
            IssueInstant="2026-05-26T12:34:56Z"
            Destination="https://idp.example.com/sso"
            AssertionConsumerServiceURL="https://attacker.example.com/exfil">
          <saml:Issuer>https://sp.example.com/saml</saml:Issuer>
        </samlp:AuthnRequest>"#;
        let sp = default_sp();
        let err = validate_authn_request(
            raw_request(xml),
            &sp,
            "https://idp.example.com/sso",
            &sso_urls(),
        )
        .unwrap_err();
        match err {
            Error::UnregisteredAcs { entity_id } => {
                assert_eq!(entity_id, "https://sp.example.com/saml");
            }
            other => panic!("expected UnregisteredAcs, got {other:?}"),
        }
    }

    #[test]
    fn protocol_binding_mismatch_against_resolved_acs() {
        // ProtocolBinding=Artifact, but Index=0 resolves to POST → error.
        let xml = r#"<samlp:AuthnRequest
            xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
            xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
            ID="_id" Version="2.0"
            IssueInstant="2026-05-26T12:34:56Z"
            Destination="https://idp.example.com/sso"
            AssertionConsumerServiceIndex="0"
            ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact">
          <saml:Issuer>https://sp.example.com/saml</saml:Issuer>
        </samlp:AuthnRequest>"#;
        let sp = default_sp();
        let err = validate_authn_request(
            raw_request(xml),
            &sp,
            "https://idp.example.com/sso",
            &sso_urls(),
        )
        .unwrap_err();
        match err {
            Error::IllegalResponseBinding { requested } => {
                assert_eq!(requested, crate::binding::Binding::HttpArtifact);
            }
            other => panic!("expected IllegalResponseBinding, got {other:?}"),
        }
    }

    #[test]
    fn no_default_acs_and_no_attrs_is_unregistered() {
        // An SP with no ACS endpoints at all is technically conformant to
        // the SAML schema (the role descriptor permits zero ACS entries),
        // but in practice means "I cannot receive Responses". Validating
        // an AuthnRequest that didn't pick an ACS must fail loudly rather
        // than the IdP silently choosing nothing.
        let sp = sp_with_acs_layout("");
        let xml = r#"<samlp:AuthnRequest
            xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
            xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
            ID="_id" Version="2.0"
            IssueInstant="2026-05-26T12:34:56Z"
            Destination="https://idp.example.com/sso">
          <saml:Issuer>https://sp.example.com/saml</saml:Issuer>
        </samlp:AuthnRequest>"#;
        let err = validate_authn_request(
            raw_request(xml),
            &sp,
            "https://idp.example.com/sso",
            &sso_urls(),
        )
        .unwrap_err();
        match err {
            Error::UnregisteredAcs { entity_id } => {
                assert_eq!(entity_id, "https://sp.example.com/saml");
            }
            other => panic!("expected UnregisteredAcs, got {other:?}"),
        }
    }

    #[test]
    fn protocol_binding_none_uses_resolved_acs_binding() {
        // No `@ProtocolBinding` on the wire → step 7a accepts; the resolved
        // ACS endpoint's binding is authoritative downstream.
        let xml = r#"<samlp:AuthnRequest
            xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
            xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
            ID="_id" Version="2.0"
            IssueInstant="2026-05-26T12:34:56Z"
            Destination="https://idp.example.com/sso"
            AssertionConsumerServiceIndex="1">
          <saml:Issuer>https://sp.example.com/saml</saml:Issuer>
        </samlp:AuthnRequest>"#;
        let sp = default_sp();
        let parsed = validate_authn_request(
            raw_request(xml),
            &sp,
            "https://idp.example.com/sso",
            &sso_urls(),
        )
        .unwrap();
        assert!(parsed.protocol_binding.is_none());
        assert_eq!(
            parsed.assertion_consumer_service.binding,
            SsoResponseBinding::HttpArtifact
        );
    }
}