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    /// Assertion session `SessionNotOnOrAfter`.
97    SessionNotOnOrAfter,
98    /// Assertion `Conditions` NotBefore/NotOnOrAfter window.
99    Conditions,
100    /// Replay cache retention window could not be computed or has elapsed.
101    ReplayExpiration,
102}
103
104impl fmt::Display for TimeWindowField {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        match self {
107            Self::SessionNotOnOrAfter => f.write_str("SessionNotOnOrAfter"),
108            Self::Conditions => f.write_str("Conditions"),
109            Self::ReplayExpiration => f.write_str("ReplayExpiration"),
110        }
111    }
112}
113
114/// Errors produced by the SAML-RS library.
115///
116/// Variants are grouped by validation category:
117///
118/// - wire and XML decoding failures;
119/// - SAML protocol validation failures;
120/// - signature, signed-reference, and delegated crypto failures;
121/// - metadata and trust selection failures;
122/// - configuration, unsupported binding, and compatibility failures.
123///
124/// This enum is `#[non_exhaustive]`; downstream callers should include a
125/// fallback arm when matching.
126#[derive(Debug, thiserror::Error)]
127#[non_exhaustive]
128pub enum SamlError {
129    // Wire / XML errors.
130    /// Raw DEFLATE (de)compression failed.
131    #[error("deflate error: {0}")]
132    Deflate(#[from] std::io::Error),
133    /// Base64 decoding failed.
134    #[error("base64 decode error: {0}")]
135    Base64(#[from] base64::DecodeError),
136    /// Malformed or unexpected XML.
137    #[error("xml error: {0}")]
138    Xml(String),
139    /// Input failed validation.
140    #[error("invalid input: {0}")]
141    Invalid(String),
142    /// Inbound XML does not satisfy the SAML 2.0 protocol QName or version profile.
143    #[error("SAML protocol profile violation: {0}")]
144    ProtocolProfile(String),
145
146    // Unsupported profiles and bindings.
147    /// Functionality not yet implemented in the current milestone.
148    #[error("unsupported: {0}")]
149    Unsupported(String),
150    /// Requested binding is not supported by this API path.
151    #[error("unsupported binding: {binding:?}")]
152    UnsupportedBinding {
153        /// Binding that reached an unsupported profile path.
154        binding: Binding,
155    },
156
157    // SAML protocol validation.
158    /// Issuer in the message does not match the expected peer entity ID.
159    #[error("issuer mismatch: expected {expected}, got {actual:?}")]
160    IssuerMismatch {
161        /// Expected peer entity ID.
162        expected: String,
163        /// Actual issuer value extracted from the message, when available.
164        actual: Option<String>,
165    },
166    /// Response `Destination` does not match the expected recipient URL.
167    #[error("destination mismatch: expected {expected}, got {actual:?}")]
168    DestinationMismatch {
169        /// Expected recipient URL.
170        expected: String,
171        /// Actual destination value extracted from the message, when available.
172        actual: Option<String>,
173    },
174    /// `InResponseTo` does not match the expected request ID.
175    #[error("inResponseTo mismatch: expected {expected:?}, got {actual:?}")]
176    InResponseToMismatch {
177        /// Expected request ID. `None` means no request correlation was expected.
178        expected: Option<String>,
179        /// Actual `InResponseTo` value extracted from the message, when available.
180        actual: Option<String>,
181    },
182    /// RelayState does not match the pending message correlation state.
183    #[error("relay state mismatch")]
184    RelayStateMismatch {
185        /// Expected RelayState presence and value.
186        expected: RelayStateParam,
187        /// Actual RelayState presence and value.
188        actual: RelayStateParam,
189    },
190    /// `<Audience>` does not include the expected Service Provider entity ID.
191    #[error("audience restriction not satisfied: expected {expected}")]
192    AudienceMismatch {
193        /// Expected SP entity ID.
194        expected: String,
195    },
196    /// Response carried a non-success SAML status code.
197    #[error("status not success: top={top}, second={second:?}")]
198    StatusNotSuccess {
199        /// Top-tier status code.
200        top: String,
201        /// Optional second-tier status code.
202        second: Option<String>,
203    },
204    /// Assertion or session time bounds are not satisfied.
205    #[error("SAML time window is invalid for {field}")]
206    TimeWindowInvalid {
207        /// SAML field or validation scope whose time window failed.
208        field: TimeWindowField,
209    },
210    /// Bearer subject confirmation requirements are not satisfied.
211    #[error("subject confirmation is not satisfied: {reason}")]
212    SubjectConfirmationInvalid {
213        /// Stable validation reason for callers and logs.
214        reason: SubjectConfirmationReason,
215    },
216    /// A duplicate SAML message or assertion key was detected.
217    #[error("replayed SAML message or assertion: {key}")]
218    ReplayDetected {
219        /// Replay cache key or duplicate identifier.
220        key: String,
221    },
222
223    // Signature / crypto validation.
224    /// Required signature is absent.
225    #[error("signature missing where required")]
226    SignatureMissing,
227    /// Required binding parameter is absent.
228    #[error("required binding parameter missing: {name}")]
229    MissingBindingParameter {
230        /// Binding parameter name.
231        name: &'static str,
232    },
233    /// Signature verification failed for a semantic SAML validation reason.
234    #[error("signature verification failed: {reason}")]
235    SignatureVerification {
236        /// Stable verification reason for callers and logs.
237        reason: SignatureVerificationReason,
238    },
239    /// Signed reference could not be resolved safely.
240    #[error("signed reference could not be resolved: {reason}")]
241    ReferenceResolution {
242        /// Stable reference-resolution reason for callers and logs.
243        reason: ReferenceResolutionReason,
244    },
245    /// Verified signed reference does not cover the consumed payload.
246    #[error("signed reference does not cover consumed payload")]
247    SignedReferenceMismatch,
248    /// Assertion-signature policy requires direct coverage of the consumed assertion.
249    #[error("consumed assertion is not directly covered by a trusted XML signature")]
250    AssertionSignatureRequired,
251
252    // Metadata / trust validation.
253    /// No trusted certificate could be selected for verification.
254    #[error("no trusted certificate could be selected for verification")]
255    NoTrustedCertificate,
256    /// Certificate embedded in the message does not match configured metadata.
257    #[error("certificate mismatch")]
258    CertificateMismatch,
259
260    // Legacy compatibility and lower-level operational variants.
261    /// Compatibility variant for issuer validation; prefer [`Self::IssuerMismatch`].
262    #[error("ERR_UNMATCH_ISSUER")]
263    UnmatchIssuer,
264    /// Compatibility variant for audience validation; prefer [`Self::AudienceMismatch`].
265    #[error("ERR_UNMATCH_AUDIENCE")]
266    UnmatchAudience,
267    /// Compatibility variant for destination validation; prefer [`Self::DestinationMismatch`].
268    #[error("ERR_UNMATCH_DESTINATION")]
269    UnmatchDestination,
270    /// Caller supplied a malformed request ID for response correlation.
271    ///
272    /// Prefer [`Self::InResponseToMismatch`] when a message value fails request
273    /// correlation.
274    #[error("ERR_INVALID_IN_RESPONSE_TO")]
275    InvalidInResponseTo,
276    /// Response status code is missing, empty, or could not be extracted.
277    #[error("ERR_UNDEFINED_STATUS")]
278    UndefinedStatus,
279    /// Compatibility variant for non-success status; prefer [`Self::StatusNotSuccess`].
280    #[error("ERR_FAILED_STATUS with top tier code: {top}, second tier code: {second}")]
281    FailedStatus {
282        /// Top-tier status code.
283        top: String,
284        /// Second-tier status code (empty when absent).
285        second: String,
286    },
287    /// Compatibility variant for elapsed session bounds; prefer [`Self::TimeWindowInvalid`].
288    #[error("ERR_EXPIRED_SESSION")]
289    ExpiredSession,
290    /// Compatibility variant for subject confirmation failures; prefer
291    /// [`Self::SubjectConfirmationInvalid`].
292    #[error("ERR_SUBJECT_UNCONFIRMED")]
293    SubjectUnconfirmed,
294    /// A signature-wrapping (XSW) attempt was detected.
295    #[error("ERR_POTENTIAL_WRAPPING_ATTACK")]
296    PotentialWrappingAttack,
297    /// Compatibility variant for missing binding signature parameters; prefer
298    /// [`Self::SignatureMissing`] or [`Self::MissingBindingParameter`].
299    #[error("ERR_MISSING_SIG_ALG")]
300    MissingSigAlg,
301    /// Compatibility variant for detached signature failures; prefer
302    /// [`Self::SignatureVerification`].
303    #[error("ERR_FAILED_MESSAGE_SIGNATURE_VERIFICATION")]
304    FailedMessageSignatureVerification,
305    /// Compatibility variant for XML-DSig failures; prefer [`Self::SignatureVerification`].
306    #[error("FAILED_TO_VERIFY_SIGNATURE")]
307    FailedToVerifySignature,
308    /// Compatibility variant for certificate mismatch; prefer [`Self::CertificateMismatch`].
309    #[error("ERROR_UNMATCH_CERTIFICATE_DECLARATION_IN_METADATA")]
310    UnmatchCertificate,
311    /// Compatibility variant for unsupported bindings; prefer [`Self::UnsupportedBinding`].
312    #[error("ERR_UNDEFINED_BINDING")]
313    UndefinedBinding,
314    /// Required metadata (endpoint/certificate) was missing.
315    #[error("missing metadata: {0}")]
316    MissingMetadata(String),
317    /// A required cryptographic key was missing.
318    #[error("missing key: {0}")]
319    MissingKey(String),
320    /// A delegated cryptographic operation failed.
321    #[error("crypto error: {0}")]
322    Crypto(String),
323}
324
325impl SamlError {
326    pub(crate) fn issuer_mismatch(expected: &str, actual: Option<&str>) -> Self {
327        Self::IssuerMismatch {
328            expected: expected.to_string(),
329            actual: actual.map(str::to_string),
330        }
331    }
332
333    pub(crate) fn destination_mismatch(expected: &str, actual: Option<&str>) -> Self {
334        Self::DestinationMismatch {
335            expected: expected.to_string(),
336            actual: actual.map(str::to_string),
337        }
338    }
339
340    pub(crate) fn in_response_to_mismatch(expected: Option<&str>, actual: Option<&str>) -> Self {
341        Self::InResponseToMismatch {
342            expected: expected.map(str::to_string),
343            actual: actual.map(str::to_string),
344        }
345    }
346}