saml-rs 0.2.0

Pure-Rust SAML 2.0 Service Provider and Identity Provider support.
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
use core::marker::PhantomData;

use super::bindings::{LogoutBinding, SsoRequestBinding, SsoResponseBinding};
use super::endpoints::AcsEndpoint;
use super::outbound::Outbound;
use crate::config::EntityId;
use crate::constants::Binding;
use crate::error::SamlError;
use crate::model::{
    AuthnRequest, EndpointUrl, LogoutRequest, MessageId, RelayStateParam, SamlInstant,
};

mod sealed {
    pub trait Sealed {}
}

/// Message marker support for typed pending state.
#[doc(hidden)]
pub trait PendingMessage: sealed::Sealed {
    /// Private storage for protocol-specific pending fields.
    type Details: Clone + core::fmt::Debug + PartialEq + Eq;
    /// Binding type used for outbound request dispatch.
    type RequestBinding: Copy + core::fmt::Debug + PartialEq + Eq;
    /// Binding type expected for the correlated response.
    type ResponseBinding: Copy + core::fmt::Debug + PartialEq + Eq;
}

/// Protocol-specific pending AuthnRequest details.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthnPendingDetails {
    request_binding: Option<SsoRequestBinding>,
    response_binding: SsoResponseBinding,
    acs: AcsEndpoint,
}

/// Protocol-specific pending LogoutRequest details.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogoutPendingDetails {
    binding: LogoutBinding,
}

impl sealed::Sealed for AuthnRequest {}

impl PendingMessage for AuthnRequest {
    type Details = AuthnPendingDetails;
    type RequestBinding = SsoRequestBinding;
    type ResponseBinding = SsoResponseBinding;
}

impl sealed::Sealed for LogoutRequest {}

impl PendingMessage for LogoutRequest {
    type Details = LogoutPendingDetails;
    type RequestBinding = LogoutBinding;
    type ResponseBinding = LogoutBinding;
}

/// Persistable correlation snapshot for a pending SAML message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingSnapshot<Message: PendingMessage> {
    /// Correlation ID.
    pub id: String,
    /// Exact RelayState state.
    pub relay_state: RelayStateParam,
    /// Peer entity ID.
    pub peer_entity_id: String,
    /// Expected response binding keyword.
    pub expected_binding: String,
    /// Selected request binding keyword, if tracked.
    pub request_binding: Option<String>,
    /// Selected ACS URL for AuthnRequest snapshots.
    ///
    /// LogoutRequest snapshots leave this empty and [`PendingLogoutRequest::from_snapshot`]
    /// ignores it.
    pub acs_url: String,
    /// Selected ACS binding keyword for AuthnRequest snapshots.
    ///
    /// LogoutRequest snapshots leave this empty and [`PendingLogoutRequest::from_snapshot`]
    /// ignores it.
    pub acs_binding: String,
    /// Selected ACS index for AuthnRequest snapshots, if any.
    ///
    /// LogoutRequest snapshots leave this unset and [`PendingLogoutRequest::from_snapshot`]
    /// ignores it.
    pub acs_index: Option<u16>,
    /// Whether the selected AuthnRequest ACS was default.
    ///
    /// LogoutRequest snapshots leave this false and [`PendingLogoutRequest::from_snapshot`]
    /// ignores it.
    pub acs_is_default: bool,
    /// Issue instant, if recorded.
    pub issued_at: Option<SamlInstant>,
    /// Expiration instant, if recorded.
    pub expires_at: Option<SamlInstant>,
    _message: PhantomData<Message>,
}

impl PendingSnapshot<AuthnRequest> {
    /// Build an AuthnRequest snapshot from persistence fields.
    ///
    /// Snapshots store correlation data without copying keys or peer metadata.
    ///
    /// # Examples
    ///
    /// ```
    /// use saml_rs::{AuthnRequest, PendingSnapshot, RelayStateParam};
    ///
    /// let snapshot = PendingSnapshot::<AuthnRequest>::authn_request(
    ///     "_request123",
    ///     RelayStateParam::absent(),
    ///     "https://idp.example.com/metadata",
    ///     "post",
    ///     "https://sp.example.com/acs",
    ///     "post",
    /// );
    ///
    /// assert_eq!(snapshot.peer_entity_id, "https://idp.example.com/metadata");
    /// assert_eq!(snapshot.acs_url, "https://sp.example.com/acs");
    /// ```
    pub fn authn_request(
        id: impl Into<String>,
        relay_state: RelayStateParam,
        peer_entity_id: impl Into<String>,
        expected_binding: impl Into<String>,
        acs_url: impl Into<String>,
        acs_binding: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            relay_state,
            peer_entity_id: peer_entity_id.into(),
            expected_binding: expected_binding.into(),
            request_binding: None,
            acs_url: acs_url.into(),
            acs_binding: acs_binding.into(),
            acs_index: None,
            acs_is_default: false,
            issued_at: None,
            expires_at: None,
            _message: PhantomData,
        }
    }
}

impl PendingSnapshot<LogoutRequest> {
    /// Build a LogoutRequest snapshot from persistence fields.
    ///
    /// ACS fields are AuthnRequest-only and are intentionally left empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use saml_rs::{LogoutBinding, LogoutRequest, PendingSnapshot, RelayStateParam};
    ///
    /// let snapshot = PendingSnapshot::<LogoutRequest>::logout_request(
    ///     "_logout123",
    ///     RelayStateParam::absent(),
    ///     "https://idp.example.com/metadata",
    ///     LogoutBinding::Post,
    /// );
    ///
    /// assert_eq!(snapshot.expected_binding, "post");
    /// assert!(snapshot.acs_url.is_empty());
    /// ```
    pub fn logout_request(
        id: impl Into<String>,
        relay_state: RelayStateParam,
        peer_entity_id: impl Into<String>,
        binding: LogoutBinding,
    ) -> Self {
        Self {
            id: id.into(),
            relay_state,
            peer_entity_id: peer_entity_id.into(),
            expected_binding: binding.as_binding().short_name().to_string(),
            request_binding: Some(binding.as_binding().short_name().to_string()),
            acs_url: String::new(),
            acs_binding: String::new(),
            acs_index: None,
            acs_is_default: false,
            issued_at: None,
            expires_at: None,
            _message: PhantomData,
        }
    }
}

/// Pending SAML message correlation state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pending<Message: PendingMessage> {
    id: MessageId,
    relay_state: RelayStateParam,
    details: Message::Details,
    peer_entity_id: EntityId,
    issued_at: Option<SamlInstant>,
    expires_at: Option<SamlInstant>,
    _message: PhantomData<Message>,
}

/// Pending AuthnRequest correlation state.
pub type PendingAuthnRequest = Pending<AuthnRequest>;

/// Pending LogoutRequest correlation state.
pub type PendingLogoutRequest = Pending<LogoutRequest>;

impl<Message: PendingMessage> Pending<Message> {
    fn validate_common(
        relay_state: &RelayStateParam,
        peer_entity_id: &EntityId,
    ) -> Result<(), SamlError> {
        relay_state.validate()?;
        EntityId::try_new(peer_entity_id.as_str().to_string())?;
        Ok(())
    }

    fn validate_snapshot_timing(
        issued_at: &Option<SamlInstant>,
        expires_at: &Option<SamlInstant>,
    ) -> Result<(), SamlError> {
        if expires_at.is_some() && issued_at.is_none() {
            return Err(SamlError::Invalid(
                "pending snapshot expiration requires an issue instant".into(),
            ));
        }
        Ok(())
    }

    /// Record an issue instant.
    pub fn with_issue_instant(mut self, issued_at: SamlInstant) -> Self {
        self.issued_at = Some(issued_at);
        self
    }

    /// Record an expiration instant.
    pub fn with_expiration(mut self, expires_at: SamlInstant) -> Self {
        self.expires_at = Some(expires_at);
        self
    }

    /// SAML protocol message ID.
    pub fn id(&self) -> &MessageId {
        &self.id
    }

    /// RelayState state.
    pub fn relay_state(&self) -> &RelayStateParam {
        &self.relay_state
    }

    /// Peer entity ID.
    pub fn peer_entity_id(&self) -> &EntityId {
        &self.peer_entity_id
    }

    /// Issue instant, if recorded.
    pub fn issued_at(&self) -> Option<&SamlInstant> {
        self.issued_at.as_ref()
    }

    /// Expiration instant, if recorded.
    pub fn expires_at(&self) -> Option<&SamlInstant> {
        self.expires_at.as_ref()
    }
}

impl Pending<AuthnRequest> {
    /// Create pending AuthnRequest state without storing keys or metadata.
    ///
    /// # Errors
    ///
    /// Returns [`SamlError::Invalid`] when the RelayState state is malformed,
    /// the IdP entity ID is empty, or the selected ACS binding does not match
    /// the expected response binding.
    pub fn try_new(
        request_id: MessageId,
        relay_state: RelayStateParam,
        acs: AcsEndpoint,
        response_binding: SsoResponseBinding,
        idp_entity_id: EntityId,
    ) -> Result<Self, SamlError> {
        Self::validate_common(&relay_state, &idp_entity_id)?;
        if acs.binding() != response_binding {
            return Err(SamlError::Invalid(
                "ACS binding must match expected response binding".into(),
            ));
        }
        Ok(Self {
            id: request_id,
            relay_state,
            details: AuthnPendingDetails {
                request_binding: None,
                response_binding,
                acs,
            },
            peer_entity_id: idp_entity_id,
            issued_at: None,
            expires_at: None,
            _message: PhantomData,
        })
    }

    /// Record the outbound AuthnRequest binding selected for dispatch.
    pub fn with_request_binding(mut self, request_binding: SsoRequestBinding) -> Self {
        self.details.request_binding = Some(request_binding);
        self
    }

    /// Reconstruct pending AuthnRequest state from a snapshot.
    ///
    /// # Errors
    ///
    /// Returns [`SamlError`] when any snapshot field is malformed or
    /// inconsistent.
    ///
    /// # Examples
    ///
    /// ```
    /// use saml_rs::{AuthnRequest, Pending, PendingSnapshot, RelayStateParam};
    ///
    /// let snapshot = PendingSnapshot::<AuthnRequest>::authn_request(
    ///     "_request123",
    ///     RelayStateParam::absent(),
    ///     "https://idp.example.com/metadata",
    ///     "post",
    ///     "https://sp.example.com/acs",
    ///     "post",
    /// );
    /// let pending = Pending::<AuthnRequest>::from_snapshot(snapshot)?;
    ///
    /// assert_eq!(pending.idp_entity_id().as_str(), "https://idp.example.com/metadata");
    /// # Ok::<(), saml_rs::SamlError>(())
    /// ```
    pub fn from_snapshot(snapshot: PendingSnapshot<AuthnRequest>) -> Result<Self, SamlError> {
        snapshot.relay_state.validate()?;
        Self::validate_snapshot_timing(&snapshot.issued_at, &snapshot.expires_at)?;
        let request_id = MessageId::try_new(snapshot.id)?;
        let idp_entity_id = EntityId::try_new(snapshot.peer_entity_id)?;
        let response_binding =
            sso_response_binding_from_snapshot_value(&snapshot.expected_binding)?;
        let acs_binding = sso_response_binding_from_snapshot_value(&snapshot.acs_binding)?;
        let mut acs = AcsEndpoint::new(acs_binding, EndpointUrl::try_new(snapshot.acs_url)?)
            .with_default_flag(snapshot.acs_is_default);
        if let Some(index) = snapshot.acs_index {
            acs = acs.with_index(index);
        }
        let request_binding = snapshot
            .request_binding
            .as_deref()
            .map(sso_request_binding_from_snapshot_value)
            .transpose()?;
        let mut pending = Self::try_new(
            request_id,
            snapshot.relay_state,
            acs,
            response_binding,
            idp_entity_id,
        )?;
        pending.details.request_binding = request_binding;
        pending.issued_at = snapshot.issued_at;
        pending.expires_at = snapshot.expires_at;
        Ok(pending)
    }

    /// Build a persistable snapshot.
    pub fn snapshot(&self) -> PendingSnapshot<AuthnRequest> {
        let mut snapshot = PendingSnapshot::authn_request(
            self.id.as_str(),
            self.relay_state.clone(),
            self.peer_entity_id.as_str(),
            self.details.response_binding.as_binding().short_name(),
            self.details.acs.location().as_str(),
            self.details.acs.binding().as_binding().short_name(),
        );
        snapshot.request_binding = self
            .details
            .request_binding
            .map(|binding| binding.as_binding().short_name().to_string());
        snapshot.acs_index = self.details.acs.index();
        snapshot.acs_is_default = self.details.acs.is_default();
        snapshot.issued_at = self.issued_at.clone();
        snapshot.expires_at = self.expires_at.clone();
        snapshot
    }

    /// Request ID.
    pub fn request_id(&self) -> &MessageId {
        &self.id
    }

    /// Request binding, when tracked.
    pub fn request_binding(&self) -> Option<SsoRequestBinding> {
        self.details.request_binding
    }

    /// Expected response binding.
    pub fn response_binding(&self) -> SsoResponseBinding {
        self.details.response_binding
    }

    /// Selected ACS endpoint.
    pub fn acs(&self) -> &AcsEndpoint {
        &self.details.acs
    }

    /// Selected IdP entity ID.
    pub fn idp_entity_id(&self) -> &EntityId {
        &self.peer_entity_id
    }
}

impl Pending<LogoutRequest> {
    /// Create pending LogoutRequest state without storing keys or metadata.
    ///
    /// # Errors
    ///
    /// Returns [`SamlError::Invalid`] when RelayState or peer entity ID are malformed.
    pub fn try_new(
        request_id: MessageId,
        relay_state: RelayStateParam,
        binding: LogoutBinding,
        peer_entity_id: EntityId,
    ) -> Result<Self, SamlError> {
        Self::validate_common(&relay_state, &peer_entity_id)?;
        Ok(Self {
            id: request_id,
            relay_state,
            details: LogoutPendingDetails { binding },
            peer_entity_id,
            issued_at: None,
            expires_at: None,
            _message: PhantomData,
        })
    }

    /// Reconstruct pending LogoutRequest state from a snapshot.
    ///
    /// AuthnRequest-only ACS snapshot fields are ignored.
    ///
    /// # Errors
    ///
    /// Returns [`SamlError`] when any snapshot field is malformed or
    /// inconsistent.
    ///
    /// # Examples
    ///
    /// ```
    /// use saml_rs::{LogoutBinding, LogoutRequest, Pending, PendingSnapshot, RelayStateParam};
    ///
    /// let snapshot = PendingSnapshot::<LogoutRequest>::logout_request(
    ///     "_logout123",
    ///     RelayStateParam::absent(),
    ///     "https://idp.example.com/metadata",
    ///     LogoutBinding::Post,
    /// );
    /// let pending = Pending::<LogoutRequest>::from_snapshot(snapshot)?;
    ///
    /// assert_eq!(pending.peer_entity_id().as_str(), "https://idp.example.com/metadata");
    /// # Ok::<(), saml_rs::SamlError>(())
    /// ```
    pub fn from_snapshot(snapshot: PendingSnapshot<LogoutRequest>) -> Result<Self, SamlError> {
        snapshot.relay_state.validate()?;
        Self::validate_snapshot_timing(&snapshot.issued_at, &snapshot.expires_at)?;
        let request_id = MessageId::try_new(snapshot.id)?;
        let peer_entity_id = EntityId::try_new(snapshot.peer_entity_id)?;
        let response_binding = logout_binding_from_snapshot_value(&snapshot.expected_binding)?;
        let request_binding = snapshot
            .request_binding
            .as_deref()
            .map(logout_binding_from_snapshot_value)
            .transpose()?
            .unwrap_or(response_binding);
        if request_binding != response_binding {
            return Err(SamlError::Invalid(
                "logout request and response bindings must match".into(),
            ));
        }
        let mut pending = Self::try_new(
            request_id,
            snapshot.relay_state,
            response_binding,
            peer_entity_id,
        )?;
        pending.issued_at = snapshot.issued_at;
        pending.expires_at = snapshot.expires_at;
        Ok(pending)
    }

    /// Build a persistable snapshot.
    pub fn snapshot(&self) -> PendingSnapshot<LogoutRequest> {
        let mut snapshot = PendingSnapshot::logout_request(
            self.id.as_str(),
            self.relay_state.clone(),
            self.peer_entity_id.as_str(),
            self.details.binding,
        );
        snapshot.issued_at = self.issued_at.clone();
        snapshot.expires_at = self.expires_at.clone();
        snapshot
    }

    /// Logout request binding selected for dispatch.
    pub fn request_binding(&self) -> LogoutBinding {
        self.details.binding
    }

    /// Expected logout response binding.
    pub fn response_binding(&self) -> LogoutBinding {
        self.details.binding
    }
}

fn sso_response_binding_from_snapshot_value(value: &str) -> Result<SsoResponseBinding, SamlError> {
    let binding = Binding::from_short_name(value)
        .or_else(|| Binding::from_urn(value))
        .ok_or(SamlError::UndefinedBinding)?;
    SsoResponseBinding::try_from(binding)
}

fn sso_request_binding_from_snapshot_value(value: &str) -> Result<SsoRequestBinding, SamlError> {
    let binding = Binding::from_short_name(value)
        .or_else(|| Binding::from_urn(value))
        .ok_or(SamlError::UndefinedBinding)?;
    SsoRequestBinding::try_from(binding)
}

fn logout_binding_from_snapshot_value(value: &str) -> Result<LogoutBinding, SamlError> {
    let binding = Binding::from_short_name(value)
        .or_else(|| Binding::from_urn(value))
        .ok_or(SamlError::UndefinedBinding)?;
    LogoutBinding::try_from(binding)
}

/// Started browser flow with pending state and outbound browser action.
#[derive(Debug, Clone)]
pub struct Started<Message: PendingMessage> {
    /// Pending correlation state.
    pub pending: Pending<Message>,
    /// Outbound browser action.
    pub outbound: Outbound<Message>,
}