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    /// Response carried a non-success SAML status code.
205    #[error("status not success: top={top}, second={second:?}")]
206    StatusNotSuccess {
207        /// Top-tier status code.
208        top: String,
209        /// Optional second-tier status code.
210        second: Option<String>,
211    },
212    /// A SAML message, assertion, session, or replay time bound is not satisfied.
213    #[error("SAML time window is invalid for {field}")]
214    TimeWindowInvalid {
215        /// SAML field or validation scope whose time window failed.
216        field: TimeWindowField,
217    },
218    /// Bearer subject confirmation requirements are not satisfied.
219    #[error("subject confirmation is not satisfied: {reason}")]
220    SubjectConfirmationInvalid {
221        /// Stable validation reason for callers and logs.
222        reason: SubjectConfirmationReason,
223    },
224    /// A duplicate SAML message or assertion key was detected.
225    #[error("replayed SAML message or assertion: {key}")]
226    ReplayDetected {
227        /// Replay cache key or duplicate identifier.
228        key: String,
229    },
230
231    // Signature / crypto validation.
232    /// Required signature is absent.
233    #[error("signature missing where required")]
234    SignatureMissing,
235    /// Required binding parameter is absent.
236    #[error("required binding parameter missing: {name}")]
237    MissingBindingParameter {
238        /// Binding parameter name.
239        name: &'static str,
240    },
241    /// Signature verification failed for a semantic SAML validation reason.
242    #[error("signature verification failed: {reason}")]
243    SignatureVerification {
244        /// Stable verification reason for callers and logs.
245        reason: SignatureVerificationReason,
246    },
247    /// Signed reference could not be resolved safely.
248    #[error("signed reference could not be resolved: {reason}")]
249    ReferenceResolution {
250        /// Stable reference-resolution reason for callers and logs.
251        reason: ReferenceResolutionReason,
252    },
253    /// Verified signed reference does not cover the consumed payload.
254    #[error("signed reference does not cover consumed payload")]
255    SignedReferenceMismatch,
256    /// Assertion-signature policy requires direct coverage of the consumed assertion.
257    #[error("consumed assertion is not directly covered by a trusted XML signature")]
258    AssertionSignatureRequired,
259
260    // Metadata / trust validation.
261    /// No trusted certificate could be selected for verification.
262    #[error("no trusted certificate could be selected for verification")]
263    NoTrustedCertificate,
264    /// Certificate embedded in the message does not match configured metadata.
265    #[error("certificate mismatch")]
266    CertificateMismatch,
267
268    // Legacy compatibility and lower-level operational variants.
269    /// Compatibility variant for issuer validation; prefer [`Self::IssuerMismatch`].
270    #[error("ERR_UNMATCH_ISSUER")]
271    UnmatchIssuer,
272    /// Compatibility variant for audience validation; prefer [`Self::AudienceMismatch`].
273    #[error("ERR_UNMATCH_AUDIENCE")]
274    UnmatchAudience,
275    /// Compatibility variant for destination validation; prefer [`Self::DestinationMismatch`].
276    #[error("ERR_UNMATCH_DESTINATION")]
277    UnmatchDestination,
278    /// Caller supplied a malformed request ID for response correlation.
279    ///
280    /// Prefer [`Self::InResponseToMismatch`] when a message value fails request
281    /// correlation.
282    #[error("ERR_INVALID_IN_RESPONSE_TO")]
283    InvalidInResponseTo,
284    /// Response status code is missing, empty, or could not be extracted.
285    #[error("ERR_UNDEFINED_STATUS")]
286    UndefinedStatus,
287    /// Compatibility variant for non-success status; prefer [`Self::StatusNotSuccess`].
288    #[error("ERR_FAILED_STATUS with top tier code: {top}, second tier code: {second}")]
289    FailedStatus {
290        /// Top-tier status code.
291        top: String,
292        /// Second-tier status code (empty when absent).
293        second: String,
294    },
295    /// Compatibility variant for elapsed session bounds; prefer [`Self::TimeWindowInvalid`].
296    #[error("ERR_EXPIRED_SESSION")]
297    ExpiredSession,
298    /// Compatibility variant for subject confirmation failures; prefer
299    /// [`Self::SubjectConfirmationInvalid`].
300    #[error("ERR_SUBJECT_UNCONFIRMED")]
301    SubjectUnconfirmed,
302    /// A signature-wrapping (XSW) attempt was detected.
303    #[error("ERR_POTENTIAL_WRAPPING_ATTACK")]
304    PotentialWrappingAttack,
305    /// Compatibility variant for missing binding signature parameters; prefer
306    /// [`Self::SignatureMissing`] or [`Self::MissingBindingParameter`].
307    #[error("ERR_MISSING_SIG_ALG")]
308    MissingSigAlg,
309    /// Compatibility variant for detached signature failures; prefer
310    /// [`Self::SignatureVerification`].
311    #[error("ERR_FAILED_MESSAGE_SIGNATURE_VERIFICATION")]
312    FailedMessageSignatureVerification,
313    /// Compatibility variant for XML-DSig failures; prefer [`Self::SignatureVerification`].
314    #[error("FAILED_TO_VERIFY_SIGNATURE")]
315    FailedToVerifySignature,
316    /// Compatibility variant for certificate mismatch; prefer [`Self::CertificateMismatch`].
317    #[error("ERROR_UNMATCH_CERTIFICATE_DECLARATION_IN_METADATA")]
318    UnmatchCertificate,
319    /// Compatibility variant for unsupported bindings; prefer [`Self::UnsupportedBinding`].
320    #[error("ERR_UNDEFINED_BINDING")]
321    UndefinedBinding,
322    /// Required metadata (endpoint/certificate) was missing.
323    #[error("missing metadata: {0}")]
324    MissingMetadata(String),
325    /// A required cryptographic key was missing.
326    #[error("missing key: {0}")]
327    MissingKey(String),
328    /// A delegated cryptographic operation failed.
329    #[error("crypto error: {0}")]
330    Crypto(String),
331}
332
333impl SamlError {
334    pub(crate) fn issuer_mismatch(expected: &str, actual: Option<&str>) -> Self {
335        Self::IssuerMismatch {
336            expected: expected.to_string(),
337            actual: actual.map(str::to_string),
338        }
339    }
340
341    pub(crate) fn destination_mismatch(expected: &str, actual: Option<&str>) -> Self {
342        Self::DestinationMismatch {
343            expected: expected.to_string(),
344            actual: actual.map(str::to_string),
345        }
346    }
347
348    pub(crate) fn in_response_to_mismatch(expected: Option<&str>, actual: Option<&str>) -> Self {
349        Self::InResponseToMismatch {
350            expected: expected.map(str::to_string),
351            actual: actual.map(str::to_string),
352        }
353    }
354}