oauth-as 0.9.0

An embeddable OAuth 2.1 Authorization Server library: spec-mirroring types (RFC 6749, RFC 8628, RFC 7636), a full device-authorization-grant state machine, and a storage trait the host implements. Deliberately host-agnostic with a tiny dependency set; nothing is allocated until the host constructs an AuthorizationServer, so an embedding host pays zero memory until its config enables the feature.
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (C) 2026 Matthew Jackson

//! The host seams this library cannot fill for itself: an AUDIT EVENT channel and a RATE LIMITING
//! decision point, plus the one slot ([`Hooks`]) the server carries for both of them and for the
//! client secret verifier ([`crate::client::SecretVerifier`]).
//!
//! # Why these live here and not in the host's own code
//!
//! Both answer questions only the library can ask and only the host can answer.
//!
//! - OBSERVATION. This crate revokes a whole token family when it detects authorization code
//!   replay (RFC 9700 section 4.1.1) or refresh token reuse (OAuth 2.1 draft section 6.1, RFC 9700
//!   section 4.14.2). Those are the crate's most serious security behaviours and their entire
//!   value is that somebody NOTICES: a revocation that appears in no log is an incident nobody
//!   investigates. Nothing outside the library can see either event, because the evidence (a
//!   consumed code presented twice, a spent refresh record presented again) exists only inside the
//!   grant machinery.
//! - THROTTLING. RFC 8628 section 5.1 makes the device user code's entropy adequate only IN
//!   COMBINATION WITH rate limiting of code entry. The library knows an attempt happened and
//!   whether it failed; it does NOT know the caller, the IP, the session or the user, because it
//!   never sees a request. So the library asks and reports, and the host counts and decides.
//!
//!   That reasoning explains why this is a SEAM. It never justified shipping the seam EMPTY, and
//!   as of 0.9.0 the crate does not: [`crate::rate_limit::FixedWindowRateLimiter`] is a counter a
//!   host installs in one line, with defaults derived from the section 5.1 arithmetic. It is a
//!   floor rather than a ceiling (it is per process, so on a multi-node deployment the effective
//!   limit is multiplied by the node count); its module docs say plainly what it cannot do.
//!
//! # Zero cost until enabled
//!
//! The crate doc promises a host that never turns something on pays nothing for it, and this
//! module is built to keep that promise structurally rather than by intention:
//!
//! - [`Hooks`] is ONE pointer wide: three seams behind three trait objects would be 48 bytes on
//!   every [`crate::server::AuthorizationServer`] value, paid by every host, so the three live
//!   inside a boxed struct that is not allocated at all until something is installed.
//! - [`Hooks::emit`] takes a CLOSURE, not an [`Event`]. With no sink installed the closure is
//!   never called, so the event is never built: no allocation, no formatting, no vtable dispatch,
//!   just one null check on a pointer that is already in cache. `tests/events.rs` measures exactly
//!   that with a counting allocator and with a closure that panics if it is ever run.
//! - Events are delivered SYNCHRONOUSLY, on the calling task. This crate has no background task by
//!   design (see the crate docs) and does not gain one here; a host that wants buffering owns a
//!   channel and writes three lines of [`EventSink`].
//!
//! # What events may carry, and what they may never carry
//!
//! Security finding C13 hand-wrote `Debug` on every type in this crate that holds a credential, so
//! that a host's `tracing::debug!(?request)` could not become a plaintext credential leak. An event
//! channel is a second way out of the process for the same values, and it goes to the same logs,
//! so it is held to the same rule: NO access token, NO refresh token, NO authorization code, NO
//! device code, NO user code, NO client secret, NO PKCE verifier. `tests/events.rs` scans the
//! [`Event`] declaration and fails if a field named after one of those appears.
//!
//! What events DO carry is what an incident response needs to act:
//!
//! - `client_id`, which RFC 6749 section 2.2 states is not a secret.
//! - the `subject`, where there is one. This is the host's own user identifier, which the host
//!   already put into this crate; it is not a credential (holding it authenticates nobody), though
//!   a host in a privacy-regulated setting may want to treat it as personal data in its logs.
//! - the `family_id` of a refresh chain. This one is worth justifying, because it is the only
//!   opaque server-minted string in the whole set. It is SAFE to log because it is not a
//!   credential in any sense the protocol recognises: it is accepted at no endpoint, it appears in
//!   no request and no response, it is never given to a client, and possessing it lets nobody
//!   obtain, refresh or introspect a token. Its only power is to NAME a set of records in the
//!   host's own store, which is precisely the correlation an operator needs to answer "what else
//!   did this compromised grant issue" and to call [`crate::store::Storage::revoke_token_family`]
//!   by hand. The alternative, logging the tokens themselves, is the leak this rule exists to
//!   prevent; the alternative of logging nothing makes the revocation untraceable.

use crate::client::SecretVerifier;
use crate::error::ErrorCode;
use crate::grant::GrantType;
use crate::registration::RegistrationPolicy;
use crate::scope::ScopeSet;
use crate::token::TokenTypeHint;

/// Why a client failed to authenticate (RFC 6749 section 5.2 `invalid_client`).
///
/// The WIRE collapses all of these into one `invalid_client`, deliberately, so an attacker cannot
/// probe which client ids exist. The AUDIT channel separates them just as deliberately: the host
/// is not the attacker, and "a thousand unknown client ids" and "a thousand wrong secrets for one
/// real client" are different incidents with different responses.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ClientAuthFailure {
    /// No registration exists for the presented `client_id`.
    UnknownClient,
    /// The registration exists and the presented credential did not verify (or none was presented
    /// for a confidential client, or one was presented for a public one).
    SecretMismatch,
    /// The host's own [`RateLimiter`] refused the attempt before it was evaluated.
    RateLimited,
    /// The registration is dynamic (RFC 7591) and its `client_secret_expires_at` has passed, so the
    /// secret is no longer a credential however correct it is.
    ///
    /// Separated from [`ClientAuthFailure::SecretMismatch`] because the response differs and the
    /// urgency differs. This is not an attack: it is a client that missed a rotation window this
    /// server announced when it registered them, and the fix is to re-register rather than to
    /// investigate. A run of these after a rotation deadline is expected; a run of them before one
    /// means the deployment's clock or its issued lifetimes are wrong.
    SecretExpired,
    /// The registration authenticates with RFC 8705 mutual TLS and NO certificate reached
    /// this crate. Worth separating from a mismatch: in practice it usually means the TLS
    /// terminator is not configured to request, verify or forward a client certificate, which
    /// is an operational fault affecting every mutual-TLS client at once rather than an
    /// attack on one of them.
    #[cfg(feature = "mtls")]
    NoCertificatePresented,
    /// A certificate was presented and did not match the registration (RFC 8705 section 2.1
    /// subject values, or section 2.2 thumbprints). This one IS the attack shape: a caller
    /// holding some valid certificate trying to be a client it is not.
    #[cfg(feature = "mtls")]
    CertificateMismatch,
    /// The registration exists and an RFC 7523 client assertion was presented that did not verify:
    /// a bad signature, an `alg` the registration does not use, an audience naming another server,
    /// an expired assertion, or a `jti` that had already been spent.
    ///
    /// Separated from [`ClientAuthFailure::SecretMismatch`] because the responses differ. A run of
    /// wrong secrets is credential stuffing; a run of REPLAYED assertions is somebody who has
    /// captured a client's traffic, which is a different incident and a much worse one.
    #[cfg(feature = "client_assertion")]
    AssertionInvalid,
}

/// The OPERATOR's sentence, never the client's. Everything here is what the wire deliberately
/// refuses to distinguish (see the type's docs), so these strings must not reach a response body.
impl std::fmt::Display for ClientAuthFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            ClientAuthFailure::UnknownClient => "no registration for that client_id",
            ClientAuthFailure::SecretMismatch => "the presented client credential did not verify",
            ClientAuthFailure::RateLimited => "the host's rate limiter refused the attempt",
            ClientAuthFailure::SecretExpired => {
                "the registration's client_secret_expires_at has passed"
            }
            #[cfg(feature = "mtls")]
            ClientAuthFailure::NoCertificatePresented => {
                "the registration authenticates with mutual TLS and no certificate was presented"
            }
            #[cfg(feature = "mtls")]
            ClientAuthFailure::CertificateMismatch => {
                "the presented certificate is not one this registration authenticates with"
            }
            #[cfg(feature = "client_assertion")]
            ClientAuthFailure::AssertionInvalid => "the client assertion did not verify",
        })
    }
}

/// It is the `Err` payload of `crate::mtls::authenticate_via_mtls`, so a host handling that with
/// `?` or collecting it into a `Box<dyn Error>` needs this, exactly as `DpopFailure` and
/// `AssertionFailure` do for theirs. (Plain text rather than intra-doc links: those two types are
/// behind features this one is not, so a link would dangle in a default build.)
impl std::error::Error for ClientAuthFailure {}

/// Something the authorization server did, or refused to do, worth recording.
///
/// Every field borrows: an event costs no allocation to build, which is what lets a host with a
/// sink installed pay only for what its sink chooses to keep. See the module docs for the rule on
/// what may and may not appear here.
///
/// `#[non_exhaustive]`: later releases will add events (RFC 7591 registration, DPoP proof failures)
/// and adding one must not be a breaking change for a host that matched on this.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Event<'a> {
    /// A client failed to authenticate at a token-plane endpoint.
    ClientAuthenticationFailed {
        /// The `client_id` presented, which may not name any registration.
        client_id: &'a str,
        /// Which of the two indistinguishable-on-the-wire failures this actually was.
        failure: ClientAuthFailure,
    },
    /// An access token was issued (and possibly a refresh token with it).
    TokenIssued {
        /// The client the grant was issued to.
        client_id: &'a str,
        /// Which grant produced it.
        grant_type: GrantType,
        /// The resource owner, absent for `client_credentials` (RFC 6749 section 4.4 has none).
        subject: Option<&'a str>,
        /// The granted scope, borrowed rather than rendered: a sink that does not want it pays
        /// nothing, and one that does can format it itself.
        scope: &'a ScopeSet,
        /// The refresh chain this issuance belongs to, when it has one. See the module docs for
        /// why this identifier is safe to log.
        family_id: Option<&'a str>,
        /// Whether a refresh token was issued alongside the access token.
        refresh_issued: bool,
    },
    /// A grant request was refused, with the RFC 6749 section 5.2 code the client was told.
    GrantRefused {
        /// The client that asked.
        client_id: &'a str,
        /// The grant it asked for.
        grant_type: GrantType,
        /// The error code that went back on the wire.
        error: ErrorCode,
    },
    /// A user approved a device grant at the host's verification UI (RFC 8628 section 3.3).
    DeviceGrantApproved {
        /// The device's client.
        client_id: &'a str,
        /// The user who approved it.
        subject: &'a str,
    },
    /// A user refused a device grant, which the device will next see as `access_denied`.
    DeviceGrantDenied {
        /// The device's client.
        client_id: &'a str,
    },
    /// EVIDENCE OF COMPROMISE. An authorization code was presented after it had already been
    /// redeemed (RFC 6749 section 4.1.2, RFC 9700 section 4.1.1). The server has refused the
    /// replay and revoked what the code minted; a code is a value that leaks into logs, `Referer`
    /// headers and browser history, so a replay means either a leak or an attack in progress.
    AuthorizationCodeReplayDetected {
        /// The client the code was issued to.
        client_id: &'a str,
        /// The refresh family that was revoked, when the code's chain was still reachable.
        family_id: Option<&'a str>,
        /// Whether the refresh family was actually revoked (a chain already swept leaves nothing to
        /// kill, and a store that refuses the revocation kills nothing either).
        tokens_revoked: bool,
        /// Whether ANY step of the compromise response failed to persist: the family revocation,
        /// the fallback deletion of the access token the code minted, or the write that puts the
        /// consumed code record back so the NEXT replay is still detectable.
        ///
        /// This exists because the wire cannot carry the news. A replayed code is answered
        /// `invalid_grant` however badly the store is behaving, since the party being answered is
        /// whoever holds the leaked code, so this event is the ONLY signal a deployment gets that a
        /// code was replayed and the only place the truth about what was done can be told. An event
        /// that overstates the containment is worse than no event: it is what an operator reads
        /// while deciding not to investigate.
        ///
        /// `true` means credentials the server intended to destroy may still be live. Treat it as
        /// an incident that needs a human, not as a storage warning.
        containment_failed: bool,
    },
    /// EVIDENCE OF COMPROMISE, and the most serious event here. A superseded refresh token was
    /// presented, which means two parties hold it (OAuth 2.1 draft section 6.1, RFC 9700 section
    /// 4.14.2). The whole family has been revoked, which also logs out the legitimate client, so
    /// this is an event a host will be asked about.
    RefreshTokenReuseDetected {
        /// The client that presented the spent token.
        client_id: &'a str,
        /// The revoked family. See the module docs for why this is safe to log.
        family_id: &'a str,
        /// How many records the family revocation removed.
        records_revoked: u64,
    },
    /// A token was revoked through the RFC 7009 endpoint.
    TokenRevoked {
        /// The client that revoked it (section 2.1 requires it to be the owner).
        client_id: &'a str,
        /// Which kind was removed.
        token_type: TokenTypeHint,
        /// The presented token IS revoked; this says whether the RFC 7009 section 2.1 SHOULD that
        /// follows it succeeded. Revoking a refresh token also invalidates the access tokens of the
        /// same grant, and that cascade is deliberately non-fatal: turning a completed revocation
        /// into an error would tell an honest client nothing happened when the token it named is
        /// already gone. Non-fatal is not the same as unreported, and `true` here means the
        /// client's access tokens from that grant are still live for up to one access token TTL.
        ///
        /// Always `false` for an access token: there is no grant-wide cascade to attempt.
        cascade_failed: bool,
    },
    /// A resource owner WITHDREW a consent, and everything issued under it was revoked.
    ///
    /// The one event in this set a USER causes rather than a client, and it is worth recording for
    /// the same reason the two compromise events are: the cascade logs a client out of an account
    /// it was in the middle of working with, so a host will be asked what happened.
    /// `records_revoked` is how many tokens, codes and approved device grants the withdrawal
    /// actually removed, which is what distinguishes "the user ended a live session" from "the
    /// user revoked something that had already expired".
    #[cfg(feature = "consent")]
    ConsentWithdrawn {
        /// The client that may no longer act for this user.
        client_id: &'a str,
        /// The user who withdrew it.
        subject: &'a str,
        /// How many records the cascade removed.
        records_revoked: u64,
    },
    /// A client registered itself through RFC 7591 dynamic client registration.
    ///
    /// Worth watching even in a deployment that meant to enable this: RFC 7591 section 5 is
    /// explicit that an open registration endpoint lets anyone create clients, so the RATE of this
    /// event is the signal that an abuse policy is not holding. Carries no credential, so neither
    /// the issued client secret nor the registration access token reaches the host's logs.
    ClientRegistered {
        /// The identifier the server minted.
        client_id: &'a str,
    },
    /// A registration was rewritten through RFC 7592 section 2.2.
    ///
    /// An update can change the redirect URIs, which is the whole of where this client's
    /// authorization codes may be delivered, so it deserves the same attention as the original
    /// registration.
    ClientRegistrationUpdated {
        /// The registration that changed.
        client_id: &'a str,
    },
    /// A registration was deleted through RFC 7592 section 2.3, taking with it every token,
    /// refresh chain and outstanding authorization code it held.
    ClientRegistrationDeleted {
        /// The registration that is now gone.
        client_id: &'a str,
    },
}

/// Where events go. The host implements this; the library never logs anything itself.
///
/// `on_event` is called SYNCHRONOUSLY, inside the request the host is already driving, and it takes
/// `&self` so the sink is shared. Two consequences a host should design for: a slow sink slows the
/// token endpoint, and a panicking sink panics the request. A host doing anything expensive should
/// push onto a channel here and do the work elsewhere; this crate will not own that thread.
pub trait EventSink: Send + Sync {
    /// Record one event. Must not panic and should not block.
    fn on_event(&self, event: Event<'_>);
}

/// Something a caller is attempting that a host may want to throttle.
///
/// Deliberately carries no credential: not the user code being tried (RFC 8628 section 6.1 makes
/// it the credential a human types) and not the secret. It also cannot carry an IP or a session,
/// because this library never sees a request; a host correlates using its own request context,
/// which it still holds at the moment it calls into the server.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Attempt<'a> {
    /// A client is authenticating at a token-plane endpoint. The `client_id` is included because
    /// RFC 6749 section 2.2 makes it explicitly not a secret, so a limiter may key on it.
    ClientAuthentication {
        /// The presented identifier, which may name no registration.
        client_id: &'a str,
    },
    /// A user code was entered at the host's verification UI
    /// ([`crate::server::AuthorizationServer::approve_device`] /
    /// [`crate::server::AuthorizationServer::deny_device`]). This is the attempt RFC 8628 section
    /// 5.1 requires a deployment to rate limit.
    DeviceUserCodeEntry,
}

/// What a [`RateLimiter`] decided.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RateLimitDecision {
    /// Proceed.
    Allow,
    /// Refuse without evaluating the credential.
    Deny,
}

/// How an attempt turned out, reported back so a limiter can count FAILURES rather than traffic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AttemptOutcome {
    /// The credential verified / the code matched a live grant.
    Succeeded,
    /// It did not. This is the signal a guessing attack produces.
    Failed,
}

/// The host's throttle. THIS LIBRARY DOES NOT RATE LIMIT ANYTHING, and cannot: it never sees a
/// request, so it has no caller, no IP, no session and no user to count against.
///
/// RFC 8628 section 5.1 is explicit that the device user code's entropy is sufficient only in
/// combination with rate limiting of user code entry, so for any deployment offering the device
/// grant this is not optional in practice, only optional in the type system.
///
/// A HOST DOES NOT HAVE TO WRITE ONE. [`crate::rate_limit::FixedWindowRateLimiter`] is an
/// implementation this crate ships, in memory, with no new dependency and with defaults derived
/// from the section 5.1 arithmetic. Implement this trait yourself when you have something the
/// library does not: a request IP, a session, a user, or a store shared across nodes.
pub trait RateLimiter: Send + Sync {
    /// Decide whether `attempt` may proceed. Called BEFORE any credential is evaluated, so a
    /// `Deny` costs the attacker a lookup and tells them nothing.
    fn check(&self, attempt: Attempt<'_>) -> RateLimitDecision;

    /// Report how an allowed attempt turned out. Defaults to doing nothing, so a host that only
    /// wants a hard ceiling implements one method.
    fn record(&self, attempt: Attempt<'_>, outcome: AttemptOutcome) {
        let _ = (attempt, outcome);
    }
}

/// The installed seams. Boxed as a unit (see [`Hooks`]) so that installing none of them allocates
/// anything at all.
#[derive(Default)]
struct Installed {
    events: Option<Box<dyn EventSink>>,
    rate_limiter: Option<Box<dyn RateLimiter>>,
    secret_verifier: Option<Box<dyn SecretVerifier>>,
    registration_policy: Option<Box<dyn RegistrationPolicy>>,
    #[cfg(feature = "jar")]
    request_object_keys: Option<Box<dyn crate::par::RequestObjectKeys>>,
    /// The host's ES256 backend for VERIFICATION (RFC 9449 DPoP proofs, RFC 9101 request objects,
    /// RFC 7523 client assertions). `Arc` rather than `Box` because it is also what a host hands
    /// to [`crate::signer_conformance`] and may share with its own resource-server half.
    #[cfg(feature = "jwt")]
    es256_verifier: Option<std::sync::Arc<dyn crate::jwt::Es256Verifier>>,
}

/// The server's slot for the host seams: exactly one pointer wide, and null until the host
/// installs something.
///
/// This shape is the design decision the module docs argue for. Holding three `Option<Box<dyn _>>`
/// fields directly on [`crate::server::AuthorizationServer`] would add 48 bytes to every server
/// value in every deployment, including every deployment that installs nothing, and
/// `tests/allocation.rs` holds that type to a size budget precisely so a convenience like that
/// cannot be paid for silently.
#[derive(Default)]
pub struct Hooks(Option<Box<Installed>>);

impl Hooks {
    /// An empty slot: nothing installed, nothing allocated.
    pub fn new() -> Self {
        Hooks(None)
    }

    fn installed(&mut self) -> &mut Installed {
        // The one allocation this module can make, and only on a host's explicit install call.
        self.0.get_or_insert_with(Default::default)
    }

    /// Install the audit sink, replacing any previous one.
    pub fn install_event_sink(&mut self, sink: Box<dyn EventSink>) {
        self.installed().events = Some(sink);
    }

    /// Install the rate limiter, replacing any previous one.
    pub fn install_rate_limiter(&mut self, limiter: Box<dyn RateLimiter>) {
        self.installed().rate_limiter = Some(limiter);
    }

    /// Install the client secret verifier, replacing any previous one.
    pub fn install_secret_verifier(&mut self, verifier: Box<dyn SecretVerifier>) {
        self.installed().secret_verifier = Some(verifier);
    }

    /// Install the RFC 7591 registration policy, replacing any previous one.
    pub fn install_registration_policy(&mut self, policy: Box<dyn RegistrationPolicy>) {
        self.installed().registration_policy = Some(policy);
    }

    /// Install the RFC 9101 request object verification keys, replacing any previous source.
    #[cfg(feature = "jar")]
    pub fn install_request_object_keys(&mut self, keys: Box<dyn crate::par::RequestObjectKeys>) {
        self.installed().request_object_keys = Some(keys);
    }

    /// Install the ES256 backend used to VERIFY signatures, replacing any previous one.
    #[cfg(feature = "jwt")]
    pub fn install_es256_verifier(
        &mut self,
        verifier: std::sync::Arc<dyn crate::jwt::Es256Verifier>,
    ) {
        self.installed().es256_verifier = Some(verifier);
    }

    /// The installed ES256 verifier, or `None`.
    ///
    /// `None` is NOT read as "accept anything": every caller refuses instead. Callers inside this
    /// crate reach the verifier through a private resolver on `AuthorizationServer`, which is what
    /// applies the `jwt-p256` fallback; this method reports only what the HOST installed, so that
    /// fallback lives in exactly one place.
    #[cfg(feature = "jwt")]
    pub fn es256_verifier(&self) -> Option<&std::sync::Arc<dyn crate::jwt::Es256Verifier>> {
        match &self.0 {
            Some(installed) => installed.es256_verifier.as_ref(),
            None => None,
        }
    }

    /// The installed RFC 9101 request object key source.
    ///
    /// `None` is NOT read as "accept anything", for the same reason as
    /// [`Hooks::registration_policy`] and the opposite of the [`RateLimiter`] default: a server
    /// that cannot check a signature must refuse the request, because "cannot check" must never
    /// read as "checked out".
    #[cfg(feature = "jar")]
    pub fn request_object_keys(&self) -> Option<&dyn crate::par::RequestObjectKeys> {
        match &self.0 {
            Some(installed) => installed.request_object_keys.as_deref(),
            None => None,
        }
    }

    /// Whether an event sink is installed.
    ///
    /// Call sites use this to decide whether to CLONE a value that is about to be consumed and
    /// would otherwise be unavailable by the time the event can honestly be emitted (a client id
    /// moved into a grant record, say). An unobserved host takes the `false` branch and pays
    /// nothing; an observed one pays one small clone for the record it asked for.
    pub fn is_observed(&self) -> bool {
        match &self.0 {
            Some(installed) => installed.events.is_some(),
            None => false,
        }
    }

    /// Emit an event, building it ONLY if a sink is installed.
    ///
    /// The closure is the whole point: see the module docs. With no sink this compiles down to a
    /// null check and a return.
    pub fn emit<'a, F>(&self, event: F)
    where
        F: FnOnce() -> Event<'a>,
    {
        if let Some(installed) = &self.0 {
            if let Some(sink) = &installed.events {
                sink.on_event(event());
            }
        }
    }

    /// Ask the host's limiter whether `attempt` may proceed. With none installed the answer is
    /// [`RateLimitDecision::Allow`]: a library with no notion of a caller has no business
    /// inventing a throttling policy, and failing closed here would break every host that has not
    /// yet written one.
    ///
    /// "Allow" is therefore the answer for a host that installed nothing, and RFC 8628 section 5.1
    /// says that host is running an under-protected verification endpoint. Install
    /// [`crate::rate_limit::FixedWindowRateLimiter`] if you have nothing better.
    pub fn check(&self, attempt: Attempt<'_>) -> RateLimitDecision {
        match &self.0 {
            Some(installed) => match &installed.rate_limiter {
                Some(limiter) => limiter.check(attempt),
                None => RateLimitDecision::Allow,
            },
            None => RateLimitDecision::Allow,
        }
    }

    /// Report an outcome to the host's limiter, if any.
    pub fn record(&self, attempt: Attempt<'_>, outcome: AttemptOutcome) {
        if let Some(installed) = &self.0 {
            if let Some(limiter) = &installed.rate_limiter {
                limiter.record(attempt, outcome);
            }
        }
    }

    /// The installed client secret verifier, for [`crate::client::ClientAuth::verify_with`].
    pub fn secret_verifier(&self) -> Option<&dyn SecretVerifier> {
        match &self.0 {
            Some(installed) => installed.secret_verifier.as_deref(),
            None => None,
        }
    }

    /// The installed RFC 7591 registration policy.
    ///
    /// `None` means the host installed none, and that is NOT read as "allow": see
    /// [`RegistrationPolicy`]. It is the opposite of the [`RateLimiter`] default above, and
    /// deliberately so. An absent limiter means the host has not written a throttling policy yet,
    /// and refusing every request would break a host that never asked for throttling. An absent
    /// registration policy means the host turned on an endpoint that mints clients and said
    /// nothing about who may use it, and RFC 7591 section 5 is explicit about what an open one
    /// costs.
    pub fn registration_policy(&self) -> Option<&dyn RegistrationPolicy> {
        match &self.0 {
            Some(installed) => installed.registration_policy.as_deref(),
            None => None,
        }
    }
}

#[cfg(test)]
#[path = "tests/events.rs"]
mod tests;