entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
//! `WebAuthn` error type.
//!
//! Mirrors the private-enum + public-struct + `is_*` query pattern used
//! by [`AuthError`](crate::provider::AuthError) and every other error type
//! in this crate. Variants cover the categories called out in the
//! `WebAuthn` rollout plan: configuration, challenge state mismatch,
//! attestation verification failure, origin / RP-ID mismatch, unknown
//! credential, sign-count rollback, missing user-verification, and a
//! catch-all `Internal` for upstream library errors.
//!
//! # Security
//!
//! Error messages are safe for logging and never contain secret material
//! (challenges, signatures, credential public keys, PRF output). Detail
//! strings are caller-provided and the caller is responsible for ensuring
//! they too are non-sensitive.
//!
//! Note: missing PRF support is **not** an error — it is a flag returned
//! to the caller from the registration / authentication ceremony. A
//! registered passkey without PRF is still a fully valid authentication
//! factor; only the single-tap vault-unlock path is unavailable. See the
//! plan §2.2 for the prefer-not-require rationale.

use core::fmt;

// ---------------------------------------------------------------------------
// Error kind (private)
// ---------------------------------------------------------------------------

/// The category of `WebAuthn` failure that occurred.
///
/// Private — callers inspect errors through the query methods on
/// [`WebAuthnError`].
#[derive(Debug, Clone, PartialEq, Eq)]
enum WebAuthnErrorKind {
    /// The relying-party configuration is invalid (missing `rp_id`, empty
    /// origin list, malformed origin URL, etc.).
    InvalidConfiguration(String),
    /// The ceremony state (registration or authentication) does not match
    /// the response — challenge tampering, replay across ceremonies, or
    /// state crossover between users.
    ChallengeMismatch,
    /// Attestation signature, certificate chain, or authenticator-data
    /// verification failed.
    AttestationFailed(String),
    /// The asserted origin is not in the relying party's allowlist.
    OriginMismatch,
    /// The RP-ID hash in the authenticator data does not match the
    /// configured relying party.
    RpIdMismatch,
    /// The asserted credential ID is unknown to the configured store.
    CredentialNotFound,
    /// The new sign-count is less than or equal to the stored value —
    /// either a cloned authenticator or a replayed assertion.
    SignCountRollback,
    /// The authenticator did not assert user-verified (UV) when the
    /// ceremony required it. Spec: `flags.uv == 0` when policy demands UV.
    UserVerificationFailed,
    /// Catch-all for upstream library failures and unforeseen edge cases.
    Internal(String),
}

// ---------------------------------------------------------------------------
// Public error type
// ---------------------------------------------------------------------------

/// Top-level `WebAuthn` error.
///
/// Error messages are safe for logging and never contain secret material.
/// Inspect the category via the `is_*()` query methods and retrieve any
/// attached detail string via [`detail()`](WebAuthnError::detail).
///
/// # Security
///
/// Variants such as [`is_credential_not_found`](WebAuthnError::is_credential_not_found)
/// and [`is_challenge_mismatch`](WebAuthnError::is_challenge_mismatch) are
/// deliberately separate because they expose useful telemetry to operators.
/// Callers that surface errors over an unauthenticated wire should map
/// every `WebAuthn` failure to a single opaque "authentication failed"
/// response to prevent credential enumeration.
#[derive(Debug, Clone, PartialEq, Eq)]
#[doc(alias = "webauthn_error")]
pub struct WebAuthnError {
    kind: WebAuthnErrorKind,
}

// -- Constructors (crate-internal) ----------------------------------------

impl WebAuthnError {
    const fn new(kind: WebAuthnErrorKind) -> Self {
        Self { kind }
    }

    /// The relying-party configuration is invalid.
    pub fn invalid_configuration(detail: impl Into<String>) -> Self {
        Self::new(WebAuthnErrorKind::InvalidConfiguration(detail.into()))
    }

    /// The ceremony state does not match the client response.
    #[must_use]
    pub fn challenge_mismatch() -> Self {
        Self::new(WebAuthnErrorKind::ChallengeMismatch)
    }

    /// Attestation verification failed.
    pub fn attestation_failed(detail: impl Into<String>) -> Self {
        Self::new(WebAuthnErrorKind::AttestationFailed(detail.into()))
    }

    /// The asserted origin is not in the relying-party allowlist.
    #[must_use]
    pub fn origin_mismatch() -> Self {
        Self::new(WebAuthnErrorKind::OriginMismatch)
    }

    /// The RP-ID hash does not match the configured relying party.
    #[must_use]
    pub fn rp_id_mismatch() -> Self {
        Self::new(WebAuthnErrorKind::RpIdMismatch)
    }

    /// The asserted credential ID is unknown.
    #[must_use]
    pub fn credential_not_found() -> Self {
        Self::new(WebAuthnErrorKind::CredentialNotFound)
    }

    /// The new sign-count is at or below the stored value.
    #[must_use]
    pub fn sign_count_rollback() -> Self {
        Self::new(WebAuthnErrorKind::SignCountRollback)
    }

    /// User-verification was required but not asserted.
    #[must_use]
    pub fn user_verification_failed() -> Self {
        Self::new(WebAuthnErrorKind::UserVerificationFailed)
    }

    /// Catch-all for upstream-library / internal failures.
    pub fn internal(detail: impl Into<String>) -> Self {
        Self::new(WebAuthnErrorKind::Internal(detail.into()))
    }
}

// -- Query methods --------------------------------------------------------

impl WebAuthnError {
    /// Returns `true` if the relying-party configuration is invalid.
    #[must_use]
    #[inline]
    pub fn is_invalid_configuration(&self) -> bool {
        matches!(self.kind, WebAuthnErrorKind::InvalidConfiguration(_))
    }

    /// Returns `true` if the ceremony state does not match the response.
    #[must_use]
    #[inline]
    pub fn is_challenge_mismatch(&self) -> bool {
        self.kind == WebAuthnErrorKind::ChallengeMismatch
    }

    /// Returns `true` if attestation verification failed.
    #[must_use]
    #[inline]
    pub fn is_attestation_failed(&self) -> bool {
        matches!(self.kind, WebAuthnErrorKind::AttestationFailed(_))
    }

    /// Returns `true` if the asserted origin is not in the RP allowlist.
    #[must_use]
    #[inline]
    pub fn is_origin_mismatch(&self) -> bool {
        self.kind == WebAuthnErrorKind::OriginMismatch
    }

    /// Returns `true` if the RP-ID hash does not match.
    #[must_use]
    #[inline]
    pub fn is_rp_id_mismatch(&self) -> bool {
        self.kind == WebAuthnErrorKind::RpIdMismatch
    }

    /// Returns `true` if the asserted credential ID is unknown.
    #[must_use]
    #[inline]
    pub fn is_credential_not_found(&self) -> bool {
        self.kind == WebAuthnErrorKind::CredentialNotFound
    }

    /// Returns `true` if the new sign-count is at or below the stored value.
    #[must_use]
    #[inline]
    pub fn is_sign_count_rollback(&self) -> bool {
        self.kind == WebAuthnErrorKind::SignCountRollback
    }

    /// Returns `true` if user-verification was required but not asserted.
    #[must_use]
    #[inline]
    pub fn is_user_verification_failed(&self) -> bool {
        self.kind == WebAuthnErrorKind::UserVerificationFailed
    }

    /// Returns `true` if an upstream library or internal failure occurred.
    #[must_use]
    #[inline]
    pub fn is_internal(&self) -> bool {
        matches!(self.kind, WebAuthnErrorKind::Internal(_))
    }

    /// Returns the detail string for variants that carry one, or `None`
    /// for the unit variants.
    #[must_use]
    #[inline]
    pub fn detail(&self) -> Option<&str> {
        match &self.kind {
            WebAuthnErrorKind::InvalidConfiguration(d)
            | WebAuthnErrorKind::AttestationFailed(d)
            | WebAuthnErrorKind::Internal(d) => Some(d),
            WebAuthnErrorKind::ChallengeMismatch
            | WebAuthnErrorKind::OriginMismatch
            | WebAuthnErrorKind::RpIdMismatch
            | WebAuthnErrorKind::CredentialNotFound
            | WebAuthnErrorKind::SignCountRollback
            | WebAuthnErrorKind::UserVerificationFailed => None,
        }
    }
}

impl fmt::Display for WebAuthnError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            WebAuthnErrorKind::InvalidConfiguration(detail) => {
                f.write_str("webauthn: invalid configuration: ")?;
                f.write_str(detail)
            }
            WebAuthnErrorKind::ChallengeMismatch => {
                f.write_str("webauthn: challenge state does not match response")
            }
            WebAuthnErrorKind::AttestationFailed(detail) => {
                f.write_str("webauthn: attestation failed: ")?;
                f.write_str(detail)
            }
            WebAuthnErrorKind::OriginMismatch => {
                f.write_str("webauthn: origin not in relying-party allowlist")
            }
            WebAuthnErrorKind::RpIdMismatch => f.write_str("webauthn: rp-id hash mismatch"),
            WebAuthnErrorKind::CredentialNotFound => f.write_str("webauthn: credential not found"),
            WebAuthnErrorKind::SignCountRollback => {
                f.write_str("webauthn: sign-count rollback rejected")
            }
            WebAuthnErrorKind::UserVerificationFailed => {
                f.write_str("webauthn: user-verification required but not asserted")
            }
            WebAuthnErrorKind::Internal(detail) => {
                f.write_str("webauthn: internal error: ")?;
                f.write_str(detail)
            }
        }
    }
}

impl std::error::Error for WebAuthnError {}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn invalid_configuration_display_and_query() {
        let err = WebAuthnError::invalid_configuration("missing rp_id");
        assert_eq!(
            err.to_string(),
            "webauthn: invalid configuration: missing rp_id"
        );
        assert!(err.is_invalid_configuration());
        assert_eq!(err.detail(), Some("missing rp_id"));
    }

    #[test]
    fn challenge_mismatch_display_and_query() {
        let err = WebAuthnError::challenge_mismatch();
        assert_eq!(
            err.to_string(),
            "webauthn: challenge state does not match response"
        );
        assert!(err.is_challenge_mismatch());
        assert_eq!(err.detail(), None);
    }

    #[test]
    fn attestation_failed_display_and_query() {
        let err = WebAuthnError::attestation_failed("bad signature");
        assert_eq!(
            err.to_string(),
            "webauthn: attestation failed: bad signature"
        );
        assert!(err.is_attestation_failed());
        assert_eq!(err.detail(), Some("bad signature"));
    }

    #[test]
    fn origin_mismatch_display_and_query() {
        let err = WebAuthnError::origin_mismatch();
        assert_eq!(
            err.to_string(),
            "webauthn: origin not in relying-party allowlist"
        );
        assert!(err.is_origin_mismatch());
        assert_eq!(err.detail(), None);
    }

    #[test]
    fn rp_id_mismatch_display_and_query() {
        let err = WebAuthnError::rp_id_mismatch();
        assert_eq!(err.to_string(), "webauthn: rp-id hash mismatch");
        assert!(err.is_rp_id_mismatch());
        assert_eq!(err.detail(), None);
    }

    #[test]
    fn credential_not_found_display_and_query() {
        let err = WebAuthnError::credential_not_found();
        assert_eq!(err.to_string(), "webauthn: credential not found");
        assert!(err.is_credential_not_found());
        assert_eq!(err.detail(), None);
    }

    #[test]
    fn sign_count_rollback_display_and_query() {
        let err = WebAuthnError::sign_count_rollback();
        assert_eq!(err.to_string(), "webauthn: sign-count rollback rejected");
        assert!(err.is_sign_count_rollback());
        assert_eq!(err.detail(), None);
    }

    #[test]
    fn user_verification_failed_display_and_query() {
        let err = WebAuthnError::user_verification_failed();
        assert_eq!(
            err.to_string(),
            "webauthn: user-verification required but not asserted"
        );
        assert!(err.is_user_verification_failed());
        assert_eq!(err.detail(), None);
    }

    #[test]
    fn internal_display_and_query() {
        let err = WebAuthnError::internal("upstream parsed a nan");
        assert_eq!(
            err.to_string(),
            "webauthn: internal error: upstream parsed a nan"
        );
        assert!(err.is_internal());
        assert_eq!(err.detail(), Some("upstream parsed a nan"));
    }

    #[test]
    fn error_implements_std_error() {
        let errors: Vec<Box<dyn std::error::Error>> = vec![
            Box::new(WebAuthnError::invalid_configuration("x")),
            Box::new(WebAuthnError::challenge_mismatch()),
            Box::new(WebAuthnError::attestation_failed("x")),
            Box::new(WebAuthnError::origin_mismatch()),
            Box::new(WebAuthnError::rp_id_mismatch()),
            Box::new(WebAuthnError::credential_not_found()),
            Box::new(WebAuthnError::sign_count_rollback()),
            Box::new(WebAuthnError::user_verification_failed()),
            Box::new(WebAuthnError::internal("x")),
        ];
        for err in &errors {
            assert!(err.source().is_none(), "source() should be None for: {err}");
            let _ = err.to_string();
        }
    }

    #[test]
    fn query_methods_are_exclusive() {
        let cases: Vec<(WebAuthnError, &str)> = vec![
            (
                WebAuthnError::invalid_configuration("c"),
                "invalid_configuration",
            ),
            (WebAuthnError::challenge_mismatch(), "challenge_mismatch"),
            (WebAuthnError::attestation_failed("c"), "attestation_failed"),
            (WebAuthnError::origin_mismatch(), "origin_mismatch"),
            (WebAuthnError::rp_id_mismatch(), "rp_id_mismatch"),
            (
                WebAuthnError::credential_not_found(),
                "credential_not_found",
            ),
            (WebAuthnError::sign_count_rollback(), "sign_count_rollback"),
            (
                WebAuthnError::user_verification_failed(),
                "user_verification_failed",
            ),
            (WebAuthnError::internal("c"), "internal"),
        ];
        for (err, expected) in &cases {
            let hits: Vec<&str> = [
                err.is_invalid_configuration()
                    .then_some("invalid_configuration"),
                err.is_challenge_mismatch().then_some("challenge_mismatch"),
                err.is_attestation_failed().then_some("attestation_failed"),
                err.is_origin_mismatch().then_some("origin_mismatch"),
                err.is_rp_id_mismatch().then_some("rp_id_mismatch"),
                err.is_credential_not_found()
                    .then_some("credential_not_found"),
                err.is_sign_count_rollback()
                    .then_some("sign_count_rollback"),
                err.is_user_verification_failed()
                    .then_some("user_verification_failed"),
                err.is_internal().then_some("internal"),
            ]
            .into_iter()
            .flatten()
            .collect();
            assert_eq!(
                hits,
                vec![*expected],
                "expected exactly one query match for {expected}, got {hits:?}",
            );
        }
    }

    #[test]
    fn partial_eq_distinguishes_payload_strings() {
        assert_eq!(
            WebAuthnError::attestation_failed("a"),
            WebAuthnError::attestation_failed("a")
        );
        assert_ne!(
            WebAuthnError::attestation_failed("a"),
            WebAuthnError::attestation_failed("b")
        );
        assert_ne!(
            WebAuthnError::origin_mismatch(),
            WebAuthnError::rp_id_mismatch()
        );
    }
}