Skip to main content

saml_rs/
error.rs

1//! Error types for `saml-rs`.
2//!
3//! [`SamlError`] is non-exhaustive. Callers should include a fallback match arm
4//! so new semantic SAML validation failures can be added without breaking
5//! source compatibility.
6
7use crate::constants::Binding;
8use crate::model::RelayStateParam;
9use std::fmt;
10
11/// Reason a required SAML signature verification failed.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum SignatureVerificationReason {
15    /// Enveloped XML-DSig verification failed.
16    XmlSignature,
17    /// HTTP-Redirect or SimpleSign detached message signature verification failed.
18    DetachedMessageSignature,
19    /// Detached signature input could not be correlated with consumed RelayState.
20    RelayStateCorrelation,
21    /// Signed reference digest verification failed.
22    ReferenceDigest,
23}
24
25impl fmt::Display for SignatureVerificationReason {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            Self::XmlSignature => f.write_str("xml signature"),
29            Self::DetachedMessageSignature => f.write_str("detached message signature"),
30            Self::RelayStateCorrelation => f.write_str("relay state correlation"),
31            Self::ReferenceDigest => f.write_str("reference digest"),
32        }
33    }
34}
35
36/// Reason a signed XML reference could not be resolved safely.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38#[non_exhaustive]
39pub enum ReferenceResolutionReason {
40    /// Reference URI points outside the same XML document.
41    ExternalReference,
42    /// Reference URI syntax is not supported by the SAML verifier.
43    UnsupportedReferenceUri,
44    /// Signature contained no references to validate.
45    MissingSignatureReference,
46    /// Same-document reference did not resolve to an XML node.
47    UnresolvedReference,
48}
49
50impl fmt::Display for ReferenceResolutionReason {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Self::ExternalReference => f.write_str("external reference"),
54            Self::UnsupportedReferenceUri => f.write_str("unsupported reference URI"),
55            Self::MissingSignatureReference => f.write_str("missing signature reference"),
56            Self::UnresolvedReference => f.write_str("unresolved reference"),
57        }
58    }
59}
60
61/// Bearer subject confirmation validation failure reason.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63#[non_exhaustive]
64pub enum SubjectConfirmationReason {
65    /// SubjectConfirmation `Method` was missing or was not bearer.
66    InvalidMethod,
67    /// SubjectConfirmationData omitted `NotOnOrAfter`.
68    MissingNotOnOrAfter,
69    /// SubjectConfirmationData `NotOnOrAfter` time bounds were not satisfied.
70    TimeWindowInvalid,
71    /// SubjectConfirmationData `Recipient` did not match the ACS URL.
72    RecipientMismatch,
73    /// SubjectConfirmationData `InResponseTo` did not match the request ID.
74    InResponseToMismatch,
75    /// No bearer SubjectConfirmation satisfied the validation requirements.
76    MissingBearerConfirmation,
77}
78
79impl fmt::Display for SubjectConfirmationReason {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        match self {
82            Self::InvalidMethod => f.write_str("method"),
83            Self::MissingNotOnOrAfter => f.write_str("missing NotOnOrAfter"),
84            Self::TimeWindowInvalid => f.write_str("time window"),
85            Self::RecipientMismatch => f.write_str("recipient"),
86            Self::InResponseToMismatch => f.write_str("InResponseTo"),
87            Self::MissingBearerConfirmation => f.write_str("missing bearer confirmation"),
88        }
89    }
90}
91
92/// SAML time-bound field whose validation failed.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94#[non_exhaustive]
95pub enum TimeWindowField {
96    /// Expiration derived from the typed IdP issuance lifetime could not be
97    /// represented for the current issue instant.
98    IdpIssuanceExpiration,
99    /// LogoutRequest `NotOnOrAfter`.
100    LogoutRequestNotOnOrAfter,
101    /// Assertion session `SessionNotOnOrAfter`.
102    SessionNotOnOrAfter,
103    /// Assertion `Conditions` NotBefore/NotOnOrAfter window.
104    Conditions,
105    /// Replay cache retention window could not be computed or has elapsed.
106    ReplayExpiration,
107}
108
109impl fmt::Display for TimeWindowField {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        match self {
112            Self::IdpIssuanceExpiration => f.write_str("IdP issuance expiration"),
113            Self::LogoutRequestNotOnOrAfter => f.write_str("LogoutRequest@NotOnOrAfter"),
114            Self::SessionNotOnOrAfter => f.write_str("SessionNotOnOrAfter"),
115            Self::Conditions => f.write_str("Conditions"),
116            Self::ReplayExpiration => f.write_str("ReplayExpiration"),
117        }
118    }
119}
120
121/// Errors produced by the SAML-RS library.
122///
123/// Variants are grouped by validation category:
124///
125/// - wire and XML decoding failures;
126/// - SAML protocol validation failures;
127/// - signature, signed-reference, and delegated crypto failures;
128/// - metadata and trust selection failures;
129/// - configuration, unsupported binding, and compatibility failures.
130///
131/// This enum is `#[non_exhaustive]`; downstream callers should include a
132/// fallback arm when matching.
133#[derive(Debug, thiserror::Error)]
134#[non_exhaustive]
135pub enum SamlError {
136    // Wire / XML errors.
137    /// Raw DEFLATE (de)compression failed.
138    #[error("deflate error: {0}")]
139    Deflate(#[from] std::io::Error),
140    /// Base64 decoding failed.
141    #[error("base64 decode error: {0}")]
142    Base64(#[from] base64::DecodeError),
143    /// Malformed or unexpected XML.
144    #[error("xml error: {0}")]
145    Xml(String),
146    /// Input failed validation.
147    #[error("invalid input: {0}")]
148    Invalid(String),
149    /// XML violates SAML protocol requirements such as QName, version, required
150    /// attributes, or their lexical forms.
151    #[error("SAML protocol profile violation: {0}")]
152    ProtocolProfile(String),
153
154    // Unsupported profiles and bindings.
155    /// Functionality not yet implemented in the current milestone.
156    #[error("unsupported: {0}")]
157    Unsupported(String),
158    /// Requested binding is not supported by this API path.
159    #[error("unsupported binding: {binding:?}")]
160    UnsupportedBinding {
161        /// Binding that reached an unsupported profile path.
162        binding: Binding,
163    },
164
165    // SAML protocol validation.
166    /// Issuer in the message does not match the expected peer entity ID.
167    #[error("issuer mismatch: expected {expected}, got {actual:?}")]
168    IssuerMismatch {
169        /// Expected peer entity ID.
170        expected: String,
171        /// Actual issuer value extracted from the message, when available.
172        actual: Option<String>,
173    },
174    /// Response `Destination` does not match the expected recipient URL.
175    #[error("destination mismatch: expected {expected}, got {actual:?}")]
176    DestinationMismatch {
177        /// Expected recipient URL.
178        expected: String,
179        /// Actual destination value extracted from the message, when available.
180        actual: Option<String>,
181    },
182    /// `InResponseTo` does not match the expected request ID.
183    #[error("inResponseTo mismatch: expected {expected:?}, got {actual:?}")]
184    InResponseToMismatch {
185        /// Expected request ID. `None` means no request correlation was expected.
186        expected: Option<String>,
187        /// Actual `InResponseTo` value extracted from the message, when available.
188        actual: Option<String>,
189    },
190    /// RelayState does not match the pending message correlation state.
191    #[error("relay state mismatch")]
192    RelayStateMismatch {
193        /// Expected RelayState presence and value.
194        expected: RelayStateParam,
195        /// Actual RelayState presence and value.
196        actual: RelayStateParam,
197    },
198    /// `<Audience>` does not include the expected Service Provider entity ID.
199    #[error("audience restriction not satisfied: expected {expected}")]
200    AudienceMismatch {
201        /// Expected SP entity ID.
202        expected: String,
203    },
204    /// A `<Conditions>` child is not one this service provider can evaluate.
205    #[error("assertion condition is not understood: {element}")]
206    UnrecognizedCondition {
207        /// Local name of the unrecognized condition element.
208        element: String,
209    },
210    /// Assertions in one response do not share one principal.
211    ///
212    /// The comparison is `NameID` value, `Format`, `NameQualifier`, and
213    /// `SPNameQualifier`. An omitted `Format` is unspecified.
214    #[error("assertions do not refer to one principal")]
215    PrincipalMismatch,
216    /// Response carried a non-success SAML status code.
217    #[error("status not success: top={top}, second={second:?}")]
218    StatusNotSuccess {
219        /// Top-tier status code.
220        top: String,
221        /// Optional second-tier status code.
222        second: Option<String>,
223    },
224    /// A SAML message, assertion, session, or replay time bound is not satisfied.
225    #[error("SAML time window is invalid for {field}")]
226    TimeWindowInvalid {
227        /// SAML field or validation scope whose time window failed.
228        field: TimeWindowField,
229    },
230    /// Bearer subject confirmation requirements are not satisfied.
231    #[error("subject confirmation is not satisfied: {reason}")]
232    SubjectConfirmationInvalid {
233        /// Stable validation reason for callers and logs.
234        reason: SubjectConfirmationReason,
235    },
236    /// A later assertion matches an outstanding logout that is still before
237    /// `NotOnOrAfter`.
238    #[error("assertion matches an outstanding logout")]
239    AssertionMatchesOutstandingLogout,
240    /// A duplicate SAML message or assertion key was detected.
241    #[error("replayed SAML message or assertion: {key}")]
242    ReplayDetected {
243        /// Replay cache key or duplicate identifier.
244        key: String,
245    },
246
247    // Signature / crypto validation.
248    /// Required signature is absent.
249    #[error("signature missing where required")]
250    SignatureMissing,
251    /// Required binding parameter is absent.
252    #[error("required binding parameter missing: {name}")]
253    MissingBindingParameter {
254        /// Binding parameter name.
255        name: &'static str,
256    },
257    /// Signature verification failed for a semantic SAML validation reason.
258    #[error("signature verification failed: {reason}")]
259    SignatureVerification {
260        /// Stable verification reason for callers and logs.
261        reason: SignatureVerificationReason,
262    },
263    /// Signed reference could not be resolved safely.
264    #[error("signed reference could not be resolved: {reason}")]
265    ReferenceResolution {
266        /// Stable reference-resolution reason for callers and logs.
267        reason: ReferenceResolutionReason,
268    },
269    /// Verified signed reference does not cover the consumed payload.
270    #[error("signed reference does not cover consumed payload")]
271    SignedReferenceMismatch,
272    /// Assertion-signature policy requires direct coverage of the consumed assertion.
273    #[error("consumed assertion is not directly covered by a trusted XML signature")]
274    AssertionSignatureRequired,
275
276    /// An embedded XML signature selected an algorithm outside the strict SAML profile.
277    #[error("embedded XML signature algorithm is not allowed")]
278    AlgorithmUnsupported,
279
280    // Metadata / trust validation.
281    /// No trusted certificate could be selected for verification.
282    #[error("no trusted certificate could be selected for verification")]
283    NoTrustedCertificate,
284    /// Certificate embedded in the message does not match configured metadata.
285    #[error("certificate mismatch")]
286    CertificateMismatch,
287
288    // Legacy compatibility and lower-level operational variants.
289    /// Compatibility variant for issuer validation; prefer [`Self::IssuerMismatch`].
290    #[error("ERR_UNMATCH_ISSUER")]
291    UnmatchIssuer,
292    /// Compatibility variant for audience validation; prefer [`Self::AudienceMismatch`].
293    #[error("ERR_UNMATCH_AUDIENCE")]
294    UnmatchAudience,
295    /// Compatibility variant for destination validation; prefer [`Self::DestinationMismatch`].
296    #[error("ERR_UNMATCH_DESTINATION")]
297    UnmatchDestination,
298    /// Caller supplied a malformed request ID for response correlation.
299    ///
300    /// Prefer [`Self::InResponseToMismatch`] when a message value fails request
301    /// correlation.
302    #[error("ERR_INVALID_IN_RESPONSE_TO")]
303    InvalidInResponseTo,
304    /// Response status code is missing, empty, or could not be extracted.
305    #[error("ERR_UNDEFINED_STATUS")]
306    UndefinedStatus,
307    /// Compatibility variant for non-success status; prefer [`Self::StatusNotSuccess`].
308    #[error("ERR_FAILED_STATUS with top tier code: {top}, second tier code: {second}")]
309    FailedStatus {
310        /// Top-tier status code.
311        top: String,
312        /// Second-tier status code (empty when absent).
313        second: String,
314    },
315    /// Compatibility variant for elapsed session bounds; prefer [`Self::TimeWindowInvalid`].
316    #[error("ERR_EXPIRED_SESSION")]
317    ExpiredSession,
318    /// Compatibility variant for subject confirmation failures; prefer
319    /// [`Self::SubjectConfirmationInvalid`].
320    #[error("ERR_SUBJECT_UNCONFIRMED")]
321    SubjectUnconfirmed,
322    /// A signature-wrapping (XSW) attempt was detected.
323    #[error("ERR_POTENTIAL_WRAPPING_ATTACK")]
324    PotentialWrappingAttack,
325    /// Compatibility variant for missing binding signature parameters; prefer
326    /// [`Self::SignatureMissing`] or [`Self::MissingBindingParameter`].
327    #[error("ERR_MISSING_SIG_ALG")]
328    MissingSigAlg,
329    /// Compatibility variant for detached signature failures; prefer
330    /// [`Self::SignatureVerification`].
331    #[error("ERR_FAILED_MESSAGE_SIGNATURE_VERIFICATION")]
332    FailedMessageSignatureVerification,
333    /// Compatibility variant for XML-DSig failures; prefer [`Self::SignatureVerification`].
334    #[error("FAILED_TO_VERIFY_SIGNATURE")]
335    FailedToVerifySignature,
336    /// Compatibility variant for certificate mismatch; prefer [`Self::CertificateMismatch`].
337    #[error("ERROR_UNMATCH_CERTIFICATE_DECLARATION_IN_METADATA")]
338    UnmatchCertificate,
339    /// Compatibility variant for unsupported bindings; prefer [`Self::UnsupportedBinding`].
340    #[error("ERR_UNDEFINED_BINDING")]
341    UndefinedBinding,
342    /// Required metadata (endpoint/certificate) was missing.
343    #[error("missing metadata: {0}")]
344    MissingMetadata(String),
345    /// A required cryptographic key was missing.
346    #[error("missing key: {0}")]
347    MissingKey(String),
348    /// A delegated cryptographic operation failed.
349    #[error("crypto error: {0}")]
350    Crypto(String),
351}
352
353impl SamlError {
354    pub(crate) fn issuer_mismatch(expected: &str, actual: Option<&str>) -> Self {
355        Self::IssuerMismatch {
356            expected: expected.to_string(),
357            actual: actual.map(str::to_string),
358        }
359    }
360
361    pub(crate) fn destination_mismatch(expected: &str, actual: Option<&str>) -> Self {
362        Self::DestinationMismatch {
363            expected: expected.to_string(),
364            actual: actual.map(str::to_string),
365        }
366    }
367
368    pub(crate) fn in_response_to_mismatch(expected: Option<&str>, actual: Option<&str>) -> Self {
369        Self::InResponseToMismatch {
370            expected: expected.map(str::to_string),
371            actual: actual.map(str::to_string),
372        }
373    }
374}