oauth-as 0.9.2

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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (C) 2026 Matthew Jackson

//! RFC 9126 pushed authorization requests (PAR) and RFC 9101 JWT-secured authorization requests
//! (JAR). Compiled ONLY under the off-by-default `par` and `jar` cargo features; with both off
//! this module does not exist and nothing else in the crate changes.
//!
//! # What these buy
//!
//! In a plain OAuth 2.1 authorization request every parameter travels through the user agent as
//! query text: the browser, its extensions, its history, its `Referer` headers and any proxy in
//! front of it can all read the request, and anything that can rewrite the URL can change it
//! before this server ever sees it. The two mechanisms here close that in different ways, and a
//! deployment may use either or both:
//!
//! - PAR (RFC 9126) moves the parameters off the browser entirely. The client POSTs them to a
//!   back-channel endpoint, authenticating exactly as it would at the token endpoint, and receives
//!   an opaque `request_uri` handle. Only the handle traverses the browser, and it is single use
//!   and short lived, so an intermediary sees nothing and can substitute nothing.
//! - JAR (RFC 9101) leaves the parameters in the browser but SIGNS them. An intermediary can still
//!   read the request; it can no longer alter it without the signature failing.
//!
//! # The two rules that decide whether either is worth anything
//!
//! 1. SINGLE USE, enforced by storage. A `request_uri` is consumed with
//!    [`crate::store::Storage::take_pushed_authorization_request`], the same atomic
//!    remove-and-return primitive that makes authorization codes and refresh tokens single use.
//!    RFC 9126 section 4 says a client MUST use a `request_uri` once and section 7.3 asks the
//!    server to enforce it; a read-then-delete implementation of the trait method reintroduces the
//!    replay under concurrency, which is why the trait says what it says.
//! 2. THE ALGORITHM COMES FROM THE REGISTRATION, never from the token. A JOSE header is written by
//!    whoever wrote the token, so trusting its `alg` is the classic JWS algorithm confusion attack
//!    (RFC 8725 sections 3.1 and 3.2, which RFC 9101 section 6.2 requires be applied here). This
//!    module compares the presented `alg` against the one registered for the client and refuses
//!    anything else; `none` can never match, because [`RequestObjectAlg`] has no variant that
//!    spells it and no constructor that could produce one.
//!
//! # What is deliberately NOT implemented
//!
//! - RFC 9101 section 5.2's fetched `request_uri` (the AS retrieving a request object over HTTPS
//!   from a client-supplied URL). This library never makes outbound network calls, and RFC 9101
//!   section 10.4.1 describes exactly why an AS that does is a DDoS amplifier. The only
//!   `request_uri` values this server accepts are the ones it minted itself at its own PAR
//!   endpoint (RFC 9126 section 2.2's URN form).
//! - RFC 9101 section 6.1 encrypted (JWE) request objects. A five-part JWT is refused with
//!   `invalid_request_object` rather than silently treated as unsigned.

#[cfg(feature = "jar")]
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
#[cfg(feature = "jar")]
use base64::Engine as _;
#[cfg(feature = "par")]
use serde::{Deserialize, Serialize};

use crate::authorization::{
    AuthorizationError, AuthorizationRequest, ValidatedAuthorizationRequest,
};
use crate::client::ClientId;
use crate::error::{ErrorCode, ErrorResponse};
use crate::server::{AuthorizationServer, Clock};
use crate::store::Storage;

// --------------------------------------------------------------------------- RFC 9126 PAR

/// The `pushed_at` a record written before 0.9.1 gets when it is read back.
///
/// The epoch, because it is the fail-closed answer: every barrier is recorded after it, so a
/// record with no stated push instant is REFUSED by a standing revocation rather than admitted by
/// one. See the field's own documentation.
#[cfg(feature = "par")]
fn pushed_at_default() -> std::time::SystemTime {
    std::time::SystemTime::UNIX_EPOCH
}

/// The shortest handle lifetime this server will offer, whatever the host configured.
///
/// RFC 9126 section 2.2 makes `expires_in` a POSITIVE integer, and a sub-second
/// [`ParConfig::request_uri_ttl`] reports zero — a handle a conforming client abandons without
/// using. One second is the smallest value that can be reported truthfully. It is a clamp rather
/// than a rejection for the reason [`crate::server::ServerConfig::user_code_length`] clamps: a
/// misconfiguration must not become a runtime failure in front of a user.
#[cfg(feature = "par")]
pub const MIN_REQUEST_URI_TTL: std::time::Duration = std::time::Duration::from_secs(1);

/// The URN prefix RFC 9126 section 2.2 offers for a minted `request_uri`, registered in its
/// section 9.3. The RFC leaves the format to the server, so this is a choice rather than a
/// requirement; it is the choice every interoperability profile in practice expects, and it names
/// the value as a reference to server-side data rather than as something fetchable.
#[cfg(feature = "par")]
pub const REQUEST_URI_PREFIX: &str = "urn:ietf:params:oauth:request_uri:";

/// How many random bytes go into a `request_uri`. RFC 9126 section 7.1 defers to RFC 9101 section
/// 10.2 clause (d) on entropy: the handle is a capability URL, so guessing one is impersonating
/// the client that pushed it. 32 bytes is 256 bits, the same draw as every other artifact this
/// crate mints.
#[cfg(feature = "par")]
const REQUEST_URI_ENTROPY_BYTES: usize = 32;

/// RFC 9126 configuration. `None` on [`crate::server::ServerConfig::par`] means PAR is OFF: no
/// endpoint is advertised and [`AuthorizationServer::pushed_authorization_request`] refuses.
#[cfg(feature = "par")]
#[derive(Debug, Clone, PartialEq, Eq)]
/// `#[non_exhaustive]`, for the reason [`crate::server::ServerConfig`] carries it, and stated
/// plainly because this type is the exception to that finding rather than an instance of it: no
/// field here is feature gated TODAY. It is a configuration struct hanging off `ServerConfig`, it
/// is where every future RFC 9126 policy knob will land, and a host that learns the rule from the
/// parent config is entitled to it from the child. Construct with [`ParConfig::new`] and override
/// what the deployment needs.
#[non_exhaustive]
pub struct ParConfig {
    /// RFC 9126 section 5 `pushed_authorization_request_endpoint`. `None` derives
    /// `{issuer}/par`.
    pub pushed_authorization_request_endpoint: Option<String>,
    /// How long a minted `request_uri` stays usable.
    ///
    /// RFC 9126 section 2.2 leaves this to the server and gives 5 to 600 seconds as the typical
    /// range. The default here is 60 seconds, which is a redirect round trip with room to spare:
    /// the handle exists only to get the user agent from the client to this server's authorization
    /// endpoint, and everything the handle protects (the `code_challenge` above all) is worth less
    /// the shorter it is guessable for.
    pub request_uri_ttl: std::time::Duration,
    /// RFC 9126 section 5 `require_pushed_authorization_requests`. When true, this server refuses
    /// any authorization request whose parameters arrived in the query
    /// ([`AuthorizationServer::validate_authorization_request`] answers `invalid_request`), which
    /// is the section 4 policy statement that PAR is the only way in.
    pub require_pushed_authorization_requests: bool,
}

#[cfg(feature = "par")]
impl Default for ParConfig {
    fn default() -> Self {
        ParConfig::new()
    }
}

#[cfg(feature = "par")]
impl ParConfig {
    /// PAR offered, not required, with the 60 second handle lifetime described on
    /// [`ParConfig::request_uri_ttl`].
    pub fn new() -> Self {
        ParConfig {
            pushed_authorization_request_endpoint: None,
            request_uri_ttl: std::time::Duration::from_secs(60),
            require_pushed_authorization_requests: false,
        }
    }

    /// The advertised endpoint for `issuer`.
    pub fn endpoint(&self, issuer: &str) -> String {
        match &self.pushed_authorization_request_endpoint {
            Some(url) => url.clone(),
            None => format!("{}/par", issuer.trim_end_matches('/')),
        }
    }
}

/// The RFC 9126 section 2.2 success response body. The endpoint answers `201 Created`, which the
/// RFC states rather than suggests; see [`PushedAuthorizationResponse::http_status`].
/// `Debug` is HAND-WRITTEN (below) and does not print the `request_uri`. The stored RECORD has
/// been hand-redacted since it was written, for the reason stated there -- the handle is a
/// capability for as long as it is live (RFC 9126 section 7.1) -- and this type, which hands that
/// same handle to the client, was left deriving until 0.9.2. The handle carries a fully validated
/// authorization request including its redirect URI; a leaked live one is redeemable.
#[cfg(feature = "par")]
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PushedAuthorizationResponse {
    /// The single-use handle the client puts in its authorization request.
    pub request_uri: String,
    /// The handle's lifetime in seconds (a positive integer, per section 2.2).
    pub expires_in: u64,
}

/// Hand-written so the `request_uri` never prints. `expires_in` prints in full: a lifetime is not
/// a credential and is the diagnostic an operator is usually after.
#[cfg(feature = "par")]
impl std::fmt::Debug for PushedAuthorizationResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PushedAuthorizationResponse")
            .field("request_uri", &"[redacted]")
            .field("expires_in", &self.expires_in)
            .finish()
    }
}

#[cfg(feature = "par")]
impl PushedAuthorizationResponse {
    /// `201`. RFC 9126 section 2.2 says the server MUST generate the request URI and provide it
    /// "with a 201 HTTP status code", so this is not the 200 the rest of this crate's endpoints
    /// use and a host must not substitute one.
    pub fn http_status(&self) -> u16 {
        201
    }
}

/// A pushed authorization request as the host persists it, keyed by `request_uri`.
///
/// The fields are the authorization request parameters this server understands, rather than an
/// opaque bag of whatever was posted. That is deliberate: the endpoint validates the pushed
/// request at push time (RFC 9126 section 2.1 step 3), so a parameter this server cannot act on
/// cannot have been validated, and storing it would only let it reappear at the authorization
/// endpoint unexamined. A parameter added to the authorization request is therefore added
/// here as well, and the compiler says so; RFC 9396 `authorization_details`, which this
/// comment used to name as the obvious next one, is now one of them.
///
/// `Debug` is hand-written for the same reason as [`crate::authorization::AuthorizationCodeRecord`]'s:
/// the `request_uri` is a capability handle for as long as it is live (RFC 9126 section 7.1), so it
/// must not reach a host's logs through `{:?}`.
#[cfg(feature = "par")]
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
/// `#[non_exhaustive]`: `rar` adds one field and `consent` adds two, and the doc above commits this
/// record to gaining a field for every parameter the authorization request gains, which makes it
/// the type in this crate most certain to keep changing shape. It round-trips through a
/// `Storage` implementor by serde exactly as the token records do, so persisting it is unaffected;
/// [`PushedAuthorizationRequest::new`] is the path for building one directly.
#[non_exhaustive]
pub struct PushedAuthorizationRequest {
    /// The handle, and the storage key.
    pub request_uri: String,
    /// The client that pushed it. RFC 9126 section 2.2: the value MUST be bound to this client,
    /// and section 7.5 is the attack that binding prevents.
    pub client_id: ClientId,
    /// `response_type`, as pushed.
    pub response_type: Option<String>,
    /// `redirect_uri`, as pushed.
    pub redirect_uri: Option<String>,
    /// `scope`, as pushed.
    pub scope: Option<String>,
    /// `state`, as pushed.
    pub state: Option<String>,
    /// `code_challenge`, as pushed (RFC 7636 section 4.3).
    pub code_challenge: Option<String>,
    /// `code_challenge_method`, as pushed.
    pub code_challenge_method: Option<String>,
    /// RFC 8707 `resource` indicators, as pushed, in wire order.
    pub resource: Vec<String>,
    /// RFC 9396 `authorization_details`, as pushed: the raw JSON array.
    ///
    /// Stored, and not merely validated at push time, because this record IS the request
    /// the authorization endpoint later reads (section 2.1 step 3 validates it here, and
    /// RFC 9101 section 6.3 says the endpoint MUST use only the pushed parameters). A
    /// parameter validated at push time and then dropped would be a parameter the client
    /// was told was acceptable and then silently did not get, which is exactly the drop
    /// RFC 9396 section 5 exists to prevent.
    #[cfg(feature = "rar")]
    pub authorization_details: Option<String>,
    /// RFC 9470 section 4 `acr_values`, as pushed.
    #[cfg(feature = "consent")]
    pub acr_values: Option<String>,
    /// RFC 9470 section 4 `max_age`, as pushed: the raw seconds text, parsed by the same
    /// validation the query path uses so a malformed value is refused HERE, at push time, which
    /// is what RFC 9126 section 2.1 means by processing the request as if it had been sent
    /// directly to the authorization endpoint.
    ///
    /// Stored for the reason `authorization_details` above is: this record IS the request the
    /// authorization endpoint later reads. Dropping these two did not merely lose a preference,
    /// it disabled RFC 9470 step-up for every PAR deployment, so a client answering an
    /// `insufficient_user_authentication` challenge with `max_age=0` got a code minted against
    /// the session it was told to replace.
    #[cfg(feature = "consent")]
    pub max_age: Option<String>,
    /// The instant this request was PUSHED.
    ///
    /// A pushed request is not yet a grant, but it is a thing a client authored, and a
    /// [`crate::store::RevocationBarrier::Client`] is compared against this so that a request
    /// pushed before an RFC 7592 deletion is refused while one pushed by a re-provisioned client
    /// is served. `expires_at` cannot stand in for it: the TTL is short but non-zero, so a request
    /// pushed just before the deletion still has a deadline in the future and would be admitted.
    ///
    /// `#[serde(default)]`, and the default is the epoch, which is the FAIL-CLOSED direction.
    /// This field is new in 0.9.1, so a record a 0.9.0 node wrote — or is still writing, during a
    /// rolling upgrade — carries no such key, and without a default the read fails outright and
    /// the endpoint answers `server_error`. With it, the record deserializes and dates from before
    /// every barrier, so a standing revocation REFUSES it rather than admitting it. A far-future
    /// default would deserialize just as happily and admit every one of them, which is the
    /// resurrection this field exists to stop. There is deliberately NO backfill migration: a
    /// backfill cannot reach a 0.9.0 node still writing field-less payloads during a rolling
    /// upgrade, which is the window that matters, so the serde default covers strictly more than
    /// one would.
    #[serde(default = "pushed_at_default")]
    pub pushed_at: std::time::SystemTime,
    /// When the handle dies. RFC 9126 section 4: an expired `request_uri` MUST be rejected.
    pub expires_at: std::time::SystemTime,
}

#[cfg(feature = "par")]
impl std::fmt::Debug for PushedAuthorizationRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut out = f.debug_struct("PushedAuthorizationRequest");
        // `pushed_at` prints for the reason `PushedAuthorizationRequest::new` spells out below: it
        // is the instant a `crate::store::RevocationBarrier::Client` is compared against, a record
        // left at the epoch is refused for as long as any client barrier stands, and the endpoint
        // then blames a client deletion that never happened. That is "a silent per-client outage if
        // nobody says so", and an operator diagnosing it reaches for `{:?}` first. It is not a
        // credential; `request_uri` is the credential here and stays redacted.
        out.field("request_uri", &"[redacted]")
            .field("pushed_at", &self.pushed_at)
            .field("client_id", &self.client_id)
            .field("response_type", &self.response_type)
            .field("redirect_uri", &self.redirect_uri)
            .field("scope", &self.scope)
            .field("state", &self.state)
            .field("code_challenge", &self.code_challenge)
            .field("code_challenge_method", &self.code_challenge_method)
            .field("resource", &self.resource);
        #[cfg(feature = "rar")]
        out.field("authorization_details", &self.authorization_details);
        #[cfg(feature = "consent")]
        out.field("acr_values", &self.acr_values)
            .field("max_age", &self.max_age);
        out.field("expires_at", &self.expires_at).finish()
    }
}

#[cfg(feature = "par")]
impl PushedAuthorizationRequest {
    /// The record with nothing pushed but three of the four things that are not authorization
    /// parameters at all: the handle, the client RFC 9126 section 2.2 binds it to, and the
    /// section 4 expiry that makes it die.
    ///
    /// THE FOURTH IS `pushed_at`, AND A CALLER USING THIS CONSTRUCTOR MUST SET IT. It is not an
    /// argument here because it is not a parameter a client sends; it is the instant a
    /// [`crate::store::RevocationBarrier::Client`] compares this record against, and this
    /// constructor leaves it at the epoch, which predates every barrier that could ever be
    /// recorded. A record left that way is REFUSED by `put_pushed_authorization_request` for as
    /// long as any client barrier stands, and the endpoint answers "this client was deleted while
    /// its request was being pushed" about a client that was not deleted. That is the fail-closed
    /// direction and it is the right default, but it is a silent per-client outage if nobody says
    /// so — which nothing did until the 0.9.1 audit, in the doc that is the manual for exactly
    /// this.
    ///
    /// Every OTHER field is a pushed parameter, every one of them is legitimately absent from a
    /// real request, and they are all public, so a caller assigns exactly what the client sent and
    /// leaves the rest as the `None` that says the client sent nothing. Filling them from arguments
    /// instead would mean a positional list of ten parameters, nine of them `Option` (`resource` is
    /// a `Vec`), which is how a `redirect_uri` ends up in the `scope` slot.
    pub fn new(
        request_uri: impl Into<String>,
        client_id: ClientId,
        expires_at: std::time::SystemTime,
    ) -> Self {
        PushedAuthorizationRequest {
            // FAIL-CLOSED, as the other hand-built records are: a request assembled without
            // saying when it was pushed must not outrank a standing revocation.
            pushed_at: std::time::SystemTime::UNIX_EPOCH,
            request_uri: request_uri.into(),
            client_id,
            response_type: None,
            redirect_uri: None,
            scope: None,
            state: None,
            code_challenge: None,
            code_challenge_method: None,
            resource: Vec::new(),
            #[cfg(feature = "rar")]
            authorization_details: None,
            #[cfg(feature = "consent")]
            acr_values: None,
            #[cfg(feature = "consent")]
            max_age: None,
            expires_at,
        }
    }

    /// The stored parameters as an authorization request, borrowing rather than copying: this is
    /// what the authorization endpoint validates, and it should cost no more than reading the
    /// record already did.
    pub fn as_request(&self) -> AuthorizationRequest<'_> {
        AuthorizationRequest {
            response_type: self.response_type.as_deref().map(Into::into),
            client_id: Some(self.client_id.as_str().into()),
            redirect_uri: self.redirect_uri.as_deref().map(Into::into),
            scope: self.scope.as_deref().map(Into::into),
            state: self.state.as_deref().map(Into::into),
            code_challenge: self.code_challenge.as_deref().map(Into::into),
            code_challenge_method: self.code_challenge_method.as_deref().map(Into::into),
            resource: self.resource.iter().map(|r| r.as_str().into()).collect(),
            #[cfg(feature = "rar")]
            authorization_details: self.authorization_details.as_deref().map(Into::into),
            // The FIELD is not feature gated (see `AuthorizationRequest`, which states why: a
            // build without `rar` has to see the parameter in order to refuse it). This RECORD's
            // member still is, because such a build never stores one: the push that carried it
            // was refused before a handle existed.
            #[cfg(not(feature = "rar"))]
            authorization_details: None,
            #[cfg(feature = "consent")]
            acr_values: self.acr_values.as_deref().map(Into::into),
            #[cfg(feature = "consent")]
            max_age: self.max_age.as_deref().map(Into::into),
        }
    }
}

// --------------------------------------------------------------------------- RFC 9101 JAR

/// The signing algorithms this server will verify a request object with, in the spelling RFC 8414
/// / RFC 9101 section 4 `request_object_signing_alg_values_supported` uses.
///
/// ES256 and nothing else, for the reason `Cargo.toml` gives for the RFC 9068 signer: this crate
/// carries one curve and no JOSE framework, and an algorithm list is a menu of things an attacker
/// may ask for. `none` is absent and unreachable: see [`RequestObjectAlg`].
#[cfg(feature = "jar")]
pub const REQUEST_OBJECT_SIGNING_ALGS: &[&str] = &["ES256"];

/// The RFC 9101 section 9.4.1 media type for a request object, used as the JOSE `typ` header
/// parameter that RFC 9101 section 10.8 recommends for a new deployment.
#[cfg(feature = "jar")]
pub const REQUEST_OBJECT_TYP: &str = "oauth-authz-req+jwt";

/// RFC 9101 configuration. `None` on [`crate::server::ServerConfig::jar`] means signed request
/// objects are OFF: nothing is advertised and a `request` parameter is refused.
#[cfg(feature = "jar")]
#[derive(Debug, Clone, PartialEq, Eq)]
/// `#[non_exhaustive]` on the same argument as [`ParConfig`] next door, and with the same
/// admission: nothing here is feature gated today, and this is the config family being made
/// uniform rather than a variance being contained. It grew a second field within one release of
/// that note being written, which is the argument making itself. [`JarConfig::new`] and `Default`
/// both give the accepted-not-required policy with the default lifetime ceiling.
#[non_exhaustive]
pub struct JarConfig {
    /// RFC 9101 section 10.5 `require_signed_request_object`. When true, this server refuses any
    /// authorization request that is not a signed request object, which is what stops an attacker
    /// stripping the signature and falling back to a plain RFC 6749 request (the downgrade that
    /// section names).
    pub require_signed_request_object: bool,
    /// The longest remaining life this server will honour on a request object, measured from now to
    /// its `exp`. Default five minutes.
    ///
    /// A request object is a BEARER CREDENTIAL that travels in a browser query string, so it lands
    /// in history, in `Referer`, and in every proxy log on the path. Anyone who reads one can
    /// re-drive `/authorize` with it until it dies, which makes "when does it die" the only thing
    /// standing between a captured URL and an indefinite replay.
    ///
    /// RFC 9101 does not set this. It does not require `exp` at all, and section 9.1 registers it
    /// without a requirement level, so the lifetime is implementer discretion. What the RFC does
    /// say, in section 10.2(d) about request object URIs, is that "a general guidance for the
    /// validity time would be less than a minute", which is the spec's own view of how long one of
    /// these should live. Five minutes is that guidance loosened to survive ordinary clock skew and
    /// a user who is slow to land on the page, and it is a ceiling rather than a lifetime: an
    /// object asking for less gets less.
    ///
    /// Set it larger if a deployment genuinely needs it, and know what is being bought with it.
    pub max_request_object_lifetime: std::time::Duration,
}

#[cfg(feature = "jar")]
impl JarConfig {
    /// Signed request objects accepted, not required, with the default lifetime ceiling.
    pub fn new() -> Self {
        JarConfig::default()
    }
}

/// Written out rather than derived, and the reason is the whole point of the field: a derived
/// `Default` gives `Duration::ZERO` for the ceiling, and a zero ceiling refuses every request
/// object ever presented. A default that silently turns the feature off would be discovered by a
/// host at runtime, on a flow that used to work.
#[cfg(feature = "jar")]
impl Default for JarConfig {
    fn default() -> Self {
        JarConfig {
            require_signed_request_object: false,
            max_request_object_lifetime: std::time::Duration::from_secs(300),
        }
    }
}

/// A signature algorithm a client may register for its request objects.
///
/// A one-variant enum on purpose. The value that matters is the one that is NOT here: RFC 9101
/// section 10.5 requires `alg: none` to be rejected, and the cheapest way to guarantee that is a
/// type in which "none" cannot be spelled, so no configuration mistake and no future edit to a
/// string comparison can reintroduce it.
#[cfg(feature = "jar")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RequestObjectAlg {
    /// ECDSA using P-256 and SHA-256 (RFC 7518 section 3.4).
    Es256,
}

#[cfg(feature = "jar")]
impl RequestObjectAlg {
    /// The registered JOSE `alg` spelling.
    pub fn as_str(self) -> &'static str {
        match self {
            RequestObjectAlg::Es256 => "ES256",
        }
    }
}

/// A public key was not usable as a request object verification key. Carries no key material.
///
/// The payload is sealed and read through [`RequestObjectKeyError::detail`], matching
/// [`crate::token_exchange::UnknownTokenTypeIdentifier`]: both are one-payload rejections, both
/// are readable, and neither can be forged by a caller.
#[cfg(feature = "jar")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestObjectKeyError(String);

#[cfg(feature = "jar")]
impl RequestObjectKeyError {
    /// Why the key was refused, as a sentence.
    ///
    /// A `&'static`-shaped description of the CONDITION, never any part of the key: the variants
    /// this type is built from name a decoding or a width failure, and the type's own docs commit
    /// to carrying no key material.
    pub fn detail(&self) -> &str {
        &self.0
    }
}

#[cfg(feature = "jar")]
impl std::fmt::Display for RequestObjectKeyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "request object key error: {}", self.0)
    }
}

#[cfg(feature = "jar")]
impl std::error::Error for RequestObjectKeyError {}

/// What a client registered to sign its request objects with: one algorithm and one public key.
///
/// Both halves are the REGISTRATION's, never the token's. RFC 9101 section 6.2 requires the
/// signature to be validated "using a key associated with the client and the algorithm specified
/// in the `alg` Header Parameter", with RFC 8725 sections 3.1 and 3.2 applied, and the only
/// reading of those together that is not an algorithm confusion attack is: take the algorithm the
/// client registered, and refuse the token if its header names anything else.
#[cfg(feature = "jar")]
#[derive(Clone, PartialEq, Eq)]
pub struct RegisteredRequestObjectKey {
    alg: RequestObjectAlg,
    kid: Option<String>,
    /// The public key, in the ONE shape this crate's [`crate::jwt::Es256Verifier`] seam takes.
    ///
    /// It was an uncompressed SEC 1 point (`0x04 || x || y`) through 0.9.0, alongside a PRIVATE
    /// second copy of ES256 verification in this file that knew how to read one. The seam collapsed
    /// both into the single implementation behind `crate::jwt`, which is the point: two verifiers
    /// behind two independent code paths is how a codebase ends up with an algorithm confusion bug
    /// in whichever half nobody reviewed, and this crate has already had to unify `CLOCK_SKEW_LEEWAY`
    /// and a hex digit table for the same reason.
    ///
    /// ONE CONSEQUENCE, stated because it is a real change rather than a refactor: the "is this
    /// point actually on P-256" check no longer happens at REGISTRATION, because this crate no
    /// longer contains an elliptic curve. It moved into the installed verifier, per request, where
    /// [`crate::jwt::Es256Verifier`] states it as a MUST and names what it is for (an
    /// invalid-curve attack is what a missing on-curve check buys). What the constructors below
    /// still catch at registration time is every encoding mistake (a trimmed coordinate, a wrong
    /// length, non-base64url), which is what a host actually gets wrong when it copies a JWK out
    /// of its client table.
    ///
    /// WHO ESTABLISHES IT, precisely, because "it still fails closed" is a claim and claims in
    /// this crate are meant to be checkable. For the built-in `jwt-p256` backend it is
    /// established: `p256`'s `from_sec1_bytes` rejects a point that is not on the curve, so an
    /// off-curve coordinate pair cannot verify anything. For a HOST verifier it is the host's
    /// contract to meet and nothing in this crate checks it: [`crate::signer_conformance`] does
    /// not currently present an off-curve key, so a green run there does not cover this clause.
    /// A host whose backend hands raw coordinates to a library that skips point validation should
    /// test that clause itself until the harness carries it.
    key: crate::jwt::PublicJwk,
}

#[cfg(feature = "jar")]
impl std::fmt::Debug for RegisteredRequestObjectKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RegisteredRequestObjectKey")
            .field("alg", &self.alg)
            .field("kid", &self.kid)
            .finish()
    }
}

#[cfg(feature = "jar")]
impl RegisteredRequestObjectKey {
    /// Register an ES256 key from the `x` and `y` members of a client's RFC 7517 JWK, exactly as
    /// they appear there (base64url, unpadded, 32 bytes each).
    pub fn es256_from_jwk_coordinates(
        kid: Option<String>,
        x: &str,
        y: &str,
    ) -> Result<Self, RequestObjectKeyError> {
        let x = URL_SAFE_NO_PAD
            .decode(x)
            .map_err(|_| RequestObjectKeyError("x is not base64url".into()))?;
        let y = URL_SAFE_NO_PAD
            .decode(y)
            .map_err(|_| RequestObjectKeyError("y is not base64url".into()))?;
        // The width check is `public_jwk`'s, in ONE place, so that the two constructors cannot
        // drift apart on what a coordinate is.
        //
        // Re-encoded from the DECODED bytes rather than passed through, so that the two
        // constructors cannot disagree about what they accepted: whatever `x` and `y` spelled, what
        // is stored is the canonical unpadded base64url of exactly 32 bytes.
        Ok(RegisteredRequestObjectKey {
            alg: RequestObjectAlg::Es256,
            kid,
            key: public_jwk(&x, &y)?,
        })
    }

    /// Register an ES256 key from an uncompressed SEC 1 point (65 bytes, `0x04 || x || y`).
    pub fn es256_from_sec1(
        kid: Option<String>,
        sec1: &[u8],
    ) -> Result<Self, RequestObjectKeyError> {
        if sec1.len() != 65 {
            return Err(RequestObjectKeyError(
                "an uncompressed P-256 point is exactly 65 bytes".into(),
            ));
        }
        // The leading byte is checked because it is the one thing that says which SEC 1 encoding
        // this is: 0x02 and 0x03 are the COMPRESSED forms, which are 33 bytes and so cannot arrive
        // here, but 0x00 or 0x04 written by hand from a truncated buffer can. A host handing in 65
        // bytes that do not start 0x04 has not handed in the point it thinks it has.
        if sec1[0] != 0x04 {
            return Err(RequestObjectKeyError(
                "an uncompressed P-256 point begins with 0x04".into(),
            ));
        }
        Ok(RegisteredRequestObjectKey {
            alg: RequestObjectAlg::Es256,
            kid,
            key: public_jwk(&sec1[1..33], &sec1[33..])?,
        })
    }

    /// The registered algorithm. This, not the token header, decides.
    pub fn alg(&self) -> RequestObjectAlg {
        self.alg
    }

    /// The registered `kid`, when the client named one.
    pub fn kid(&self) -> Option<&str> {
        self.kid.as_deref()
    }
}

/// Where the request object verification keys come from: the host answers "what did this client
/// register".
///
/// This is a SEAM rather than a field on [`crate::client::Client`], and the reason is stated
/// plainly because it is a temporary one. RFC 7523 `private_key_jwt` client authentication needs
/// the same thing (a public key per client), so client-registered key material belongs on the
/// registration once that lands, and this trait should then be re-pointed at it rather than
/// duplicated. Until then, a host installs one of these with
/// [`AuthorizationServer::with_request_object_keys`] and answers from wherever it already keeps
/// client keys.
///
/// With none installed, a `request` parameter is refused: a server that cannot check a signature
/// must never treat the request as if it had checked one.
#[cfg(feature = "jar")]
pub trait RequestObjectKeys: Send + Sync {
    /// The key `client_id` registered for signing request objects, or `None` if it registered
    /// none (in which case it may not use JAR at all).
    fn registered_key(&self, client_id: &ClientId) -> Option<RegisteredRequestObjectKey>;
}

/// The authorization request parameters carried as claims of a verified request object.
///
/// Only the parameters this server acts on are extracted. RFC 9101 section 4 lets a request object
/// carry any extension parameter, and RFC 6749 section 3.1 requires unknown ones to be ignored,
/// which is what not extracting them means here.
#[cfg(feature = "jar")]
#[derive(Debug)]
struct RequestObjectClaims {
    client_id: String,
    response_type: Option<String>,
    redirect_uri: Option<String>,
    scope: Option<String>,
    state: Option<String>,
    code_challenge: Option<String>,
    code_challenge_method: Option<String>,
    resource: Vec<String>,
    #[cfg(feature = "rar")]
    authorization_details: Option<String>,
    #[cfg(feature = "consent")]
    acr_values: Option<String>,
    #[cfg(feature = "consent")]
    max_age: Option<String>,
}

#[cfg(feature = "jar")]
impl RequestObjectClaims {
    fn as_request(&self) -> AuthorizationRequest<'_> {
        AuthorizationRequest {
            response_type: self.response_type.as_deref().map(Into::into),
            client_id: Some(self.client_id.as_str().into()),
            redirect_uri: self.redirect_uri.as_deref().map(Into::into),
            scope: self.scope.as_deref().map(Into::into),
            state: self.state.as_deref().map(Into::into),
            code_challenge: self.code_challenge.as_deref().map(Into::into),
            code_challenge_method: self.code_challenge_method.as_deref().map(Into::into),
            resource: self.resource.iter().map(|r| r.as_str().into()).collect(),
            #[cfg(feature = "rar")]
            authorization_details: self.authorization_details.as_deref().map(Into::into),
            // The FIELD is not feature gated (see `AuthorizationRequest`, which states why: a
            // build without `rar` has to see the parameter in order to refuse it). This CLAIM SET
            // still is, and never carries one in such a build: `verified_request_object` refuses
            // an object whose claims contain `authorization_details` before it builds this.
            #[cfg(not(feature = "rar"))]
            authorization_details: None,
            #[cfg(feature = "consent")]
            acr_values: self.acr_values.as_deref().map(Into::into),
            #[cfg(feature = "consent")]
            max_age: self.max_age.as_deref().map(Into::into),
        }
    }
}

/// One base64url (unpadded) segment of a JWS compact serialization.
///
/// `refusal` is the WHOLE description rather than the name of the segment, and it is
/// `&'static str`, so the refusal borrows a constant instead of formatting one. There are exactly
/// three call sites and three sentences (below), and this is the authorization endpoint: nothing
/// has authenticated at this point, so the caller chooses how many of these it asks for.
#[cfg(feature = "jar")]
fn decode_segment(segment: &str, refusal: &'static str) -> Result<Vec<u8>, ErrorResponse> {
    URL_SAFE_NO_PAD
        .decode(segment)
        .map_err(|_| ErrorResponse::new(ErrorCode::InvalidRequestObject).with_description(refusal))
}

/// The three refusals [`decode_segment`] can produce, spelled out so the call sites read as they
/// did when the sentence was built from the segment's name.
#[cfg(feature = "jar")]
const HEADER_NOT_BASE64URL: &str = "the header is not base64url";
#[cfg(feature = "jar")]
const PAYLOAD_NOT_BASE64URL: &str = "the payload is not base64url";
#[cfg(feature = "jar")]
const SIGNATURE_NOT_BASE64URL: &str = "the signature is not base64url";

/// One [`crate::jwt::PublicJwk`] from two 32-byte coordinates.
///
/// THE SEAM NOTE THAT USED TO BE HERE IS DISCHARGED. Through 0.9.0 this file carried its own
/// private `verify_es256` over `p256::ecdsa::VerifyingKey`, a second copy of the same twenty lines
/// that `src/jwt.rs` held for RFC 7523 client assertions and RFC 9449 DPoP proofs, with a comment
/// promising it would become a call to them. It now is one: this function converts the registered
/// key into the shape the [`crate::jwt::Es256Verifier`] seam takes, and the verification itself
/// happens in the single implementation behind that trait.
#[cfg(feature = "jar")]
fn public_jwk(x: &[u8], y: &[u8]) -> Result<crate::jwt::PublicJwk, RequestObjectKeyError> {
    // RFC 7518 section 6.2.1.2 fixes both coordinates at the curve's full byte length, so a
    // trimmed leading zero is a different (and unusable) key rather than the same one.
    if x.len() != 32 || y.len() != 32 {
        return Err(RequestObjectKeyError(
            "a P-256 coordinate is exactly 32 bytes".into(),
        ));
    }
    crate::jwt::PublicJwk::from_coordinates(&URL_SAFE_NO_PAD.encode(x), &URL_SAFE_NO_PAD.encode(y))
        .map_err(|_| RequestObjectKeyError("a P-256 coordinate is exactly 32 bytes".into()))
}

/// Read one claim that RFC 9101 section 4 requires to be a JSON string.
#[cfg(feature = "jar")]
fn string_claim(
    claims: &serde_json::Map<String, serde_json::Value>,
    name: &str,
) -> Result<Option<String>, ErrorResponse> {
    match claims.get(name) {
        None => Ok(None),
        Some(serde_json::Value::String(s)) => Ok(Some(s.clone())),
        // Section 4: "Parameter names and string values MUST be included as JSON strings". A
        // number or an object here is not a request parameter that could ever have been sent in a
        // query string, so coercing it would be inventing a request the client did not make.
        Some(_) => Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
            .with_description(format!("the {name} claim must be a JSON string"))),
    }
}

// ------------------------------------------------------------------- the server-side endpoints

impl<S: Storage, C: Clock> AuthorizationServer<S, C> {
    /// RFC 9126 section 2: the pushed authorization request endpoint.
    ///
    /// `parameters` is the form body exactly as it arrived, so that this can apply section 2.1
    /// step 2 (a pushed request carrying `request_uri` is refused) and section 3 (a `request`
    /// parameter is a signed request object) rather than making the host decide either. Parameters
    /// this server does not know are ignored, per RFC 6749 section 3.1.
    ///
    /// The client authenticates exactly as at the token endpoint (section 2.1 step 1), and the
    /// pushed request is fully validated here (step 3): client, exact-match redirect URI, PKCE
    /// S256, scope inside the registration, RFC 8707 resource indicators. That is the whole point
    /// of the back channel. A client learns its request is malformed from a JSON error it can read
    /// rather than from a browser redirect it cannot.
    ///
    /// Errors follow RFC 9126 section 2.3: the token endpoint's RFC 6749 section 5.2 shape, with
    /// `invalid_request` standing in for the authorization errors section 4.1.2.1 refuses to
    /// redirect (a missing or mismatching redirect URI above all).
    #[cfg(feature = "par")]
    pub async fn pushed_authorization_request(
        &self,
        client_id: &ClientId,
        client_secret: Option<&str>,
        parameters: &[(&str, &str)],
    ) -> Result<PushedAuthorizationResponse, ErrorResponse> {
        self.pushed_authorization_request_with_credential(
            client_id,
            &crate::server::ClientCredential::secret(client_secret),
            parameters,
        )
        .await
    }

    /// [`AuthorizationServer::pushed_authorization_request`] for a client presenting any credential
    /// this server accepts at the token endpoint, not just a shared secret.
    ///
    /// RFC 9126 section 2.1 step 1 says the client authenticates here "in the same way as at the
    /// token endpoint", so an RFC 7523 `private_key_jwt` client that the token endpoint accepts
    /// must be accepted here too; a PAR endpoint that only understood `client_secret_basic` would
    /// lock exactly the deployments that most want PAR (FAPI 2.0 requires both) out of it. This
    /// mirrors `device_authorization_with_credential` and
    /// `introspection_response_with_credential`, for the same reason and with the same shape.
    #[cfg(feature = "par")]
    pub async fn pushed_authorization_request_with_credential(
        &self,
        client_id: &ClientId,
        credential: &crate::server::ClientCredential<'_>,
        parameters: &[(&str, &str)],
    ) -> Result<PushedAuthorizationResponse, ErrorResponse> {
        // Read before authenticating: a server that is not offering PAR should say so whatever the
        // credential was, and should not become a client-credential oracle for a feature it does
        // not run.
        if self.config().par.is_none() {
            return Err(ErrorResponse::new(ErrorCode::InvalidRequest)
                .with_description("this server does not offer pushed authorization requests"));
        }

        // STAMPED BEFORE THE REGISTRATION IS READ, and that ordering is the whole point.
        //
        // `pushed_at` is what a [`crate::store::RevocationBarrier::Client`] is compared against,
        // so it must date from BEFORE the read the write derives from. Taking it after
        // `authenticate_client` — one `get_client` round trip, a secret verification, and on the
        // RFC 7523 path a JWT verify plus a `claim_replay_id` write, followed by a SECOND
        // `get_client` inside `validate_direct_authorization_request` — would date the push later
        // than a `delete_client` landing in that window, so the comparison would ADMIT the write
        // and mint a handle for a registration that no longer exists. The refusal below would
        // then fire only for the sliver between building the record and taking the store lock,
        // rather than for the window its own comment names.
        //
        // Same defect, same fix, as `client_credentials_token`: found by auditing the 0.9.1 fix
        // that made barriers compare instants at all. Refusing on identity alone had closed it
        // for free.
        let pushed_at = self.now();

        // 1. Client authentication, "in the same way as at the token endpoint" (section 2.1).
        let client = self.authenticate_client(client_id, credential).await?;

        // 2. Section 2.1: `request_uri` MUST NOT be provided here. Chaining one handle to another
        //    would let a client (or an attacker who captured a handle) re-push somebody else's
        //    request under its own identity.
        if parameters.iter().any(|(name, _)| *name == "request_uri") {
            return Err(ErrorResponse::new(ErrorCode::InvalidRequest)
                .with_description("request_uri must not be pushed (RFC 9126 s2.1)"));
        }

        // Section 3: the parameters may instead arrive inside a signed request object, in which
        // case they are the ONLY source; anything alongside it in the form body is client
        // authentication and nothing else.
        #[cfg(feature = "jar")]
        if let Some((_, object)) = parameters.iter().find(|(name, _)| *name == "request") {
            let claims = self.verified_request_object(&client.client_id, object)?;
            return self
                .store_pushed_request(&client.client_id, &claims.as_request(), pushed_at)
                .await;
        }

        // RFC 9101 SECTION 10.5, ON THE PUSHED PATH TOO. `require_signed_request_object` says this
        // server will not act on an authorization request that is not signed, and a request pushed
        // as plain form parameters is exactly that. Enforcing it only at the authorization endpoint
        // would leave PAR as the door the policy does not cover, which is the same shape as the
        // RFC 9126 gate this file just gained one level up: a policy that holds on one entry point
        // and not the other is a policy the deployment does not have.
        //
        // Refused HERE rather than when the handle is redeemed, because a handle minted from an
        // unsigned request is a handle that can never be spent, and answering that at push time
        // tells the client which request was wrong while it still has it in hand.
        #[cfg(feature = "jar")]
        if matches!(&self.config().jar, Some(jar) if jar.require_signed_request_object) {
            return Err(ErrorResponse::new(ErrorCode::InvalidRequest).with_description(
                "this server acts only on signed request objects (RFC 9101 s10.5), and this push \
                 carried none",
            ));
        }

        let request = AuthorizationRequest::from_pairs(parameters.iter().copied());
        self.store_pushed_request(&client.client_id, &request, pushed_at)
            .await
    }

    /// Validate a pushed request and mint its handle. Split out so that the form-body path and the
    /// signed-request-object path cannot drift apart.
    #[cfg(feature = "par")]
    async fn store_pushed_request(
        &self,
        authenticated: &ClientId,
        request: &AuthorizationRequest<'_>,
        pushed_at: std::time::SystemTime,
    ) -> Result<PushedAuthorizationResponse, ErrorResponse> {
        // A client may push only its OWN request. RFC 9126 section 2.1 makes `client_id` a
        // required parameter here with its ordinary meaning, and section 3 step 3 states the rule
        // explicitly for the request-object form: the authenticated client and the request's
        // client must be the same. Without this, an authenticated client could lodge a request
        // that names a victim client and hand the handle to the browser.
        match request.client_id.as_deref() {
            Some(pushed) if pushed == authenticated.as_str() => {}
            Some(_) => {
                return Err(
                    ErrorResponse::new(ErrorCode::InvalidRequest).with_description(
                        "client_id does not match the authenticated client (RFC 9126 s2.1)",
                    ),
                )
            }
            None => {
                return Err(ErrorResponse::new(ErrorCode::InvalidRequest)
                    .with_description("client_id is required (RFC 9126 s2.1)"))
            }
        }

        // Section 2.1 step 3: the same validation the authorization endpoint performs, reused
        // rather than reimplemented. Two copies of this drift, and the copy that drifts is the one
        // an attacker uses.
        //
        // The two-shape authorization error (RFC 6749 section 4.1.2.1) collapses to one JSON body
        // here, because there is no user agent to redirect: section 2.3 says so and gives
        // `invalid_request` as the default for the non-redirectable half.
        self.validate_direct_authorization_request(request)
            .await
            .map_err(|e| match e {
                AuthorizationError::Direct(error) => error,
                AuthorizationError::Redirect(redirect) => redirect.error,
            })?;

        // CLAMPED, not trusted. `request_uri_ttl` is a plain public field with no validating
        // constructor, and RFC 9126 section 2.2 says `expires_in` is a POSITIVE integer — which a
        // sub-second `Duration` is not: it reports `0`, a handle a conforming client treats as
        // already dead. `Duration::ZERO` is worse, because `expires_at` then equals `now` and the
        // handle is refused on its first presentation while the push itself answered `201`. The
        // host sees a successful push and a flow that cannot proceed, with nothing pointing at the
        // TTL.
        //
        // Clamped rather than rejected, for the same reason `ServerConfig::user_code_length`
        // clamps: a misconfiguration must not become a runtime failure at the one moment a user is
        // standing in front of a device.
        let ttl = match &self.config().par {
            Some(par) => par.request_uri_ttl.max(MIN_REQUEST_URI_TTL),
            // Unreachable through the public endpoint, which checks this first; answered rather
            // than panicked because a library must not take a host's process down over its own
            // configuration.
            None => {
                return Err(ErrorResponse::new(ErrorCode::InvalidRequest)
                    .with_description("this server does not offer pushed authorization requests"))
            }
        };
        let now = self.now();
        // FALLIBLE, not `expect`. This draw is reachable from an ordinary PAR request, and every
        // other fallible step on this path — the store write below, the client authentication
        // above — answers `server_error` rather than taking the host's process down. A library
        // that panics inside a host's request handler is worse than one that refuses: under
        // `panic = "abort"` the whole server dies, and the diagnostic is a panic message rather
        // than the host's own error channel. `getrandom` fails for reasons a deployment really
        // meets — fd exhaustion, a seccomp filter without `getrandom(2)`, an uninitialised
        // early-boot pool.
        let request_uri = match crate::server::try_random_hex(REQUEST_URI_ENTROPY_BYTES) {
            Some(hex) => format!("{REQUEST_URI_PREFIX}{hex}"),
            None => return Err(ErrorResponse::new(ErrorCode::ServerError)),
        };
        let expires_at = crate::server::saturating_deadline(now, ttl);
        let record = PushedAuthorizationRequest {
            // Read at request ENTRY, above `authenticate_client`, not here. See the comment there:
            // a barrier recorded between the two must refuse this write, and it can only do so if
            // the instant predates the read the write is derived from. `expires_at` below is
            // deliberately still measured from the write, because the TTL is a promise about how
            // long the handle lives, not about when the client authored it.
            pushed_at,
            request_uri: request_uri.clone(),
            client_id: authenticated.clone(),
            response_type: request.response_type.as_deref().map(str::to_string),
            redirect_uri: request.redirect_uri.as_deref().map(str::to_string),
            scope: request.scope.as_deref().map(str::to_string),
            state: request.state.as_deref().map(str::to_string),
            code_challenge: request.code_challenge.as_deref().map(str::to_string),
            code_challenge_method: request.code_challenge_method.as_deref().map(str::to_string),
            resource: request.resource.iter().map(|r| r.to_string()).collect(),
            #[cfg(feature = "rar")]
            authorization_details: request.authorization_details.as_deref().map(str::to_string),
            #[cfg(feature = "consent")]
            acr_values: request.acr_values.as_deref().map(str::to_string),
            #[cfg(feature = "consent")]
            max_age: request.max_age.as_deref().map(str::to_string),
            expires_at,
        };
        // A REFUSAL HERE IS NOT AN ERROR TO REPORT AS ONE. `authenticate_client` succeeded a
        // moment ago, so reaching this line with a barrier in the way means the registration was
        // deleted between that check and this write. The client genuinely no longer exists, and
        // `invalid_client` is the truthful answer rather than the `server_error` a storage failure
        // would deserve.
        let stored = self
            .store()
            .put_pushed_authorization_request(record)
            .await
            .map_err(|e| {
                let _ = e;
                ErrorResponse::new(ErrorCode::ServerError)
            })?;
        if stored.is_refused() {
            return Err(ErrorResponse::new(ErrorCode::InvalidClient)
                .with_description("this client was deleted while its request was being pushed"));
        }
        Ok(PushedAuthorizationResponse {
            request_uri,
            // Derived from the deadline actually recorded, not from the configured TTL. The two
            // can disagree: `saturating_deadline` clamps near the platform ceiling, and a client
            // told a lifetime longer than the record's would hold a handle it believes is live
            // after the store has stopped honouring it.
            expires_in: expires_at
                .duration_since(now)
                .unwrap_or(MIN_REQUEST_URI_TTL)
                .as_secs(),
        })
    }

    /// The authorization endpoint for a request that arrived as `client_id` plus `request_uri`
    /// (RFC 9126 section 4).
    ///
    /// Every OTHER query parameter is ignored, and this signature is how that is enforced: they
    /// are not accepted, so there is no code path in which one of them could win. RFC 9101
    /// section 6.3, which RFC 9126 section 4 builds on, is explicit that the server MUST only use
    /// the parameters from the reference "even if the same parameter is provided in the query
    /// parameter". A client that duplicates `scope` in the query gets the pushed `scope`; an
    /// attacker who appends one gets the same.
    ///
    /// The handle is consumed atomically, so a second use of it fails however many requests are in
    /// flight (RFC 9126 section 4 and section 7.3).
    #[cfg(feature = "par")]
    pub async fn validate_pushed_authorization_request(
        &self,
        client_id: &str,
        request_uri: &str,
    ) -> Result<ValidatedAuthorizationRequest, AuthorizationError> {
        // Errors here are DIRECT, never a redirect: the redirect URI lives inside the record that
        // has not been read yet (or does not exist), and RFC 6749 section 4.1.2.1 forbids
        // redirecting to a URI the server has not validated. That is the whole reason the two
        // error shapes exist.
        // `&'static str`: every refusal below names a condition, never a value out of the
        // request, so the description is always a constant and never needs copying.
        let direct = |code: ErrorCode, why: &'static str| {
            AuthorizationError::Direct(ErrorResponse::new(code).with_description(why))
        };

        let record = self
            .store()
            .take_pushed_authorization_request(request_uri)
            .await
            .map_err(|e| {
                let _ = e;
                AuthorizationError::Direct(ErrorResponse::new(ErrorCode::ServerError))
            })?
            .ok_or_else(|| {
                // Unknown, already used, or swept. One answer for all three: an attacker probing
                // handles learns nothing from the difference, and a client that reloaded its
                // browser learns the same thing either way.
                direct(
                    ErrorCode::InvalidRequestUri,
                    "unknown, expired or already used request_uri",
                )
            })?;

        // RFC 9126 section 2.2: the handle is bound to the client that pushed it, and section 7.5
        // (request URI swapping) is the attack. The record goes BACK, exactly as a cross-client
        // authorization code does in `server.rs`: burning a live handle for a request that was
        // never entitled to it is a denial of service handed to whoever asks.
        if record.client_id.as_str() != client_id {
            // NOT fire-and-forget, and word for word the argument the authorization code path in
            // `server.rs` gives for the same situation. If this write fails, a LIVE pushed request
            // belonging to an honest client has just been destroyed by a stranger's request, and
            // answering `invalid_request_uri` would report that as the ordinary refusal it is not:
            // the honest client would arrive a moment later, be told `invalid_request_uri` as
            // well, and nobody would ever connect the two. `server_error` is the truthful answer
            // and it is the only place this failure can surface, because the party in front of us
            // is not the one who was harmed.
            //
            // It reveals nothing a probe can use: reaching this branch at all requires a real
            // handle, and the difference between the two answers is a store failure the caller
            // cannot provoke.
            // A REFUSAL IS THE RIGHT OUTCOME AND NOT AN ERROR. It means `delete_client` cascaded
            // this client away while the record was out of the store, so the handle SHOULD stay
            // gone: putting it back would resurrect a pushed request belonging to a registration
            // that no longer exists, which is the rule in `oauth_as::store`'s module docs. The
            // stranger in front of us is answered `invalid_request_uri` either way, so there is
            // nothing to report differently on the wire.
            let _restored = self
                .store()
                .put_pushed_authorization_request(record)
                .await
                .map_err(|e| {
                    let _ = e;
                    AuthorizationError::Direct(ErrorResponse::new(ErrorCode::ServerError))
                })?;
            return Err(direct(
                ErrorCode::InvalidRequestUri,
                "request_uri was not issued to this client",
            ));
        }

        // Section 4: an expired request_uri MUST be rejected. Not put back: it can never become
        // valid again, so retaining it would only leave a guessable string in the store.
        if self.now() >= record.expires_at {
            return Err(direct(
                ErrorCode::InvalidRequestUri,
                "request_uri has expired",
            ));
        }

        // Section 4 again: validated as any other authorization request would be. The pushed
        // request was validated at push time too, and doing it twice is the answer section 7.4
        // asks for, since the client's policy may have changed in between (a redirect URI removed,
        // a scope withdrawn, the client deleted outright).
        self.validate_direct_authorization_request(&record.as_request())
            .await
    }

    /// The authorization endpoint for a request that arrived as `client_id` plus a signed
    /// `request` object (RFC 9101 sections 5.1 and 6).
    ///
    /// As with [`AuthorizationServer::validate_pushed_authorization_request`], the query
    /// parameters that a client may have duplicated alongside the object are not accepted here at
    /// all: RFC 9101 section 6.3 requires the server to use only the object's own parameters, and
    /// the surest way to honour that is to have no other parameters in hand.
    #[cfg(feature = "jar")]
    pub async fn validate_signed_authorization_request(
        &self,
        client_id: &str,
        request_object: &str,
    ) -> Result<ValidatedAuthorizationRequest, AuthorizationError> {
        // RFC 9126 SECTION 5, AND THE GATE THAT WAS NOT HERE.
        //
        // `require_pushed_authorization_requests` means this server "accepts authorization request
        // data only via PAR". The gate lived solely in `validate_authorization_request`, whose
        // comment explained that it is the query-parameter door and that `par.rs` reaches
        // validation directly "having already established that the request was pushed or signed".
        // That conflated two switches which buy different things:
        //
        //   `require_signed_request_object` buys INTEGRITY for a request that travels the browser.
        //   `require_pushed_authorization_requests` buys that the request NEVER TRAVELS THE BROWSER,
        //   and that it was lodged by an AUTHENTICATED client behind an atomically single-use,
        //   expiring handle.
        //
        // A signed request object has the first property and neither of the other two. So a
        // deployment that set the PAR flag, and also enabled JAR for a client, still accepted
        // authorization request data through the browser: it was refused at the plain-query door
        // and waved through this one. Refused here on the same terms as there.
        #[cfg(feature = "par")]
        if matches!(&self.config().par, Some(par) if par.require_pushed_authorization_requests) {
            return Err(AuthorizationError::Direct(
                ErrorResponse::new(ErrorCode::InvalidRequest).with_description(
                    "this server accepts authorization request data only via PAR (RFC 9126 s4)",
                ),
            ));
        }
        let claims = self
            .verified_request_object(&ClientId::new(client_id), request_object)
            .map_err(AuthorizationError::Direct)?;
        self.validate_direct_authorization_request(&claims.as_request())
            .await
    }

    /// Verify a JWS-signed request object and extract its authorization request parameters
    /// (RFC 9101 section 6.2 and section 6.3).
    ///
    /// `client_id` is the client the request CLAIMS to be, taken from the authenticated client at
    /// the PAR endpoint or from the `client_id` query parameter at the authorization endpoint
    /// (RFC 9101 section 5 makes it REQUIRED there). It selects the verification key, and section
    /// 6.3 then requires the object's own `client_id` claim to be the same value: selecting the
    /// key by the claimed identity is safe precisely because the signature check that follows is
    /// what proves the identity.
    #[cfg(feature = "jar")]
    fn verified_request_object(
        &self,
        client_id: &ClientId,
        request_object: &str,
    ) -> Result<RequestObjectClaims, ErrorResponse> {
        if self.config().jar.is_none() {
            // RFC 9101 section 7 registers `request_not_supported` for exactly this.
            return Err(ErrorResponse::new(ErrorCode::RequestNotSupported)
                .with_description("this server does not accept signed request objects"));
        }
        let keys = self.hooks().request_object_keys().ok_or_else(|| {
            // A server with no key source cannot check a signature, and "cannot check" must never
            // read as "checked out".
            ErrorResponse::new(ErrorCode::InvalidRequestObject)
                .with_description("no request object verification keys are installed")
        })?;
        let registered = keys.registered_key(client_id).ok_or_else(|| {
            ErrorResponse::new(ErrorCode::InvalidRequestObject)
                .with_description("the client registered no request object key")
        })?;
        // The SAME refusal shape, one seam along: with no ES256 backend installed this server
        // cannot check the signature, and a server that cannot check a signature must never behave
        // as though it had checked one. Resolved before any segment is decoded, so an unverifiable
        // request object costs an unauthenticated caller nothing but the lookup.
        let verifier = self.es256_verifier().ok_or_else(|| {
            ErrorResponse::new(ErrorCode::InvalidRequestObject)
                .with_description("no ES256 verifier is installed")
        })?;

        // RFC 7515 section 3.1 compact serialization: exactly three parts. A five-part token is a
        // JWE, which RFC 9101 section 6.1 defines and this server does not implement; refusing it
        // by shape is what stops it being read as an unsigned JWS.
        let mut parts = request_object.split('.');
        let (header_b64, payload_b64, signature_b64) =
            match (parts.next(), parts.next(), parts.next(), parts.next()) {
                (Some(h), Some(p), Some(s), None) => (h, p, s),
                _ => {
                    return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                        .with_description("not a three part JWS compact serialization"))
                }
            };

        let header: serde_json::Value =
            serde_json::from_slice(&decode_segment(header_b64, HEADER_NOT_BASE64URL)?).map_err(
                |_| {
                    ErrorResponse::new(ErrorCode::InvalidRequestObject)
                        .with_description("the header is not JSON")
                },
            )?;
        let alg = header
            .get("alg")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| {
                ErrorResponse::new(ErrorCode::InvalidRequestObject)
                    .with_description("the header has no alg")
            })?;

        // RFC 7515 section 4.1.11 `crit`. Same rule as `CompactJws::reject_unknown_crit`, spelled
        // out here because this path parses the header by hand (it must read `alg` and `kid`
        // BEFORE choosing a verifier, so it cannot go through `CompactJws::parse` first). The two
        // must stay in agreement; if this path ever moves onto `CompactJws`, delete this and call
        // that.
        //
        // A JWS whose header names an extension the recipient does
        // not understand is INVALID, unconditionally: the point of the member is that the producer
        // is saying "this one changes the meaning, refuse me if you cannot process it". This
        // verifier implements NO extensions, so any `crit` at all is a refusal, and the empty
        // array is a refusal too because the section forbids it ("MUST NOT be used ... with an
        // empty list").
        //
        // Checked BEFORE `alg`, and before any signature work, for the same reason `alg` is checked
        // before the signature: a header that says the recipient cannot process this object is
        // answered without spending an ECDSA verification on it.
        match header.get("crit") {
            None => {}
            Some(serde_json::Value::Array(names)) => {
                return Err(
                    ErrorResponse::new(ErrorCode::InvalidRequestObject).with_description(
                        if names.is_empty() {
                            "the header has an empty crit, which RFC 7515 s4.1.11 forbids"
                                .to_string()
                        } else {
                            "the header's crit names an extension this server does not implement"
                                .to_string()
                        },
                    ),
                )
            }
            Some(_) => {
                return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                    .with_description("the header's crit is not an array"))
            }
        }

        // THE algorithm check. The registration decides; the header only gets to agree with it.
        // This is what makes `alg: none` and every other substitution (RFC 8725 sections 3.1 and
        // 3.2) a refusal rather than a verification path, and it is the reason `alg` is compared
        // BEFORE any signature work is attempted.
        if alg != registered.alg.as_str() {
            return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                .with_description("alg does not match the algorithm registered for this client"));
        }

        // RFC 9101 section 6.2: "If a kid Header Parameter is present, the key identified MUST be
        // the key used and MUST be a key associated with the client."
        if let Some(presented) = header.get("kid").and_then(serde_json::Value::as_str) {
            match registered.kid() {
                Some(kid) if kid == presented => {}
                _ => {
                    return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                        .with_description(
                            "kid does not identify a key registered for this client",
                        ))
                }
            }
        }

        // RFC 9101 section 10.8 (cross-JWT confusion), applying RFC 8725 section 3.11. A request
        // object is not the only JWT this issuer's clients hold, and a JWT minted for another
        // purpose must not be usable as an authorization request. `typ` is optional (requiring it
        // would break clients that predate the media type), but a `typ` that names something else
        // is a token that was made for something else.
        if let Some(typ) = header.get("typ").and_then(serde_json::Value::as_str) {
            if typ != REQUEST_OBJECT_TYP && typ != "JWT" && typ != "jwt" {
                return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                    .with_description("typ names a JWT that is not a request object"));
            }
        }

        let signature = decode_segment(signature_b64, SIGNATURE_NOT_BASE64URL)?;
        // The JWS Signing Input is the ASCII of "header.payload" (RFC 7515 section 5.2 step 8),
        // taken from the ORIGINAL text rather than re-encoded: re-encoding would verify a
        // normalisation of the token instead of the token, which is how a signature check gets
        // decoupled from what it is supposed to be checking.
        let signing_input = &request_object.as_bytes()[..header_b64.len() + 1 + payload_b64.len()];
        if !verifier.verify(&registered.key, signing_input, &signature) {
            return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                .with_description("the signature did not verify"));
        }

        // Only now is anything in the payload worth reading.
        let payload: serde_json::Value =
            serde_json::from_slice(&decode_segment(payload_b64, PAYLOAD_NOT_BASE64URL)?).map_err(
                |_| {
                    ErrorResponse::new(ErrorCode::InvalidRequestObject)
                        .with_description("the payload is not JSON")
                },
            )?;
        let claims = payload.as_object().ok_or_else(|| {
            ErrorResponse::new(ErrorCode::InvalidRequestObject)
                .with_description("the payload is not a JSON object")
        })?;

        // RFC 9101 section 4: "request and request_uri parameters MUST NOT be included in Request
        // Objects". A nested reference would be a request that never terminates, and at the PAR
        // endpoint it would smuggle past the section 2.1 refusal of `request_uri`.
        for forbidden in ["request", "request_uri"] {
            if claims.contains_key(forbidden) {
                return Err(
                    ErrorResponse::new(ErrorCode::InvalidRequestObject).with_description(
                        "a request object must not carry request or request_uri (RFC 9101 s4)",
                    ),
                );
            }
        }

        // Section 6.3: the two client ids MUST be identical.
        match string_claim(claims, "client_id")? {
            Some(claimed) if claimed == client_id.as_str() => {}
            _ => return Err(
                ErrorResponse::new(ErrorCode::InvalidRequestObject).with_description(
                    "the client_id claim does not match the request's client_id (RFC 9101 s6.3)",
                ),
            ),
        }

        // RFC 9101 section 4 says a signed request object SHOULD carry `aud` naming this server's
        // issuer identifier. When it does, it is checked: an object addressed to a different
        // authorization server, replayed here by whoever intercepted it, is the mix-up that `aud`
        // exists to stop. When it does not, the object is still accepted, because SHOULD is not
        // MUST and refusing would break conforming clients.
        if let Some(aud) = payload.get("aud") {
            let issuer = self.issuer_identifier();
            let addressed_here = match aud {
                serde_json::Value::String(one) => one == issuer,
                serde_json::Value::Array(many) => many
                    .iter()
                    .any(|v| v.as_str().map(|s| s == issuer).unwrap_or(false)),
                _ => false,
            };
            if !addressed_here {
                return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                    .with_description("aud does not name this authorization server"));
            }
        }

        // RFC 7519 section 4.1.4 / 4.1.5, AND THE THREE WAYS THIS USED TO FAIL OPEN.
        //
        // A request object is a bearer credential that travels in a browser query string, so it
        // lands in history, in `Referer` and in proxy logs. Its `exp` is the only thing between a
        // captured URL and an indefinite replay, and all three of the following let that check be
        // skipped rather than failed:
        //
        //   1. NO `exp` AT ALL. The old code honoured a lifetime "if one was carried", so an object
        //      without one authorized its exact request forever. RFC 9101 does not require `exp`
        //      and section 9.1 registers it with no requirement level, so this is implementer
        //      discretion rather than a rule to follow; the discretion is exercised the same way
        //      `client-assertion` already exercises it for a missing `jti`, and for the reason
        //      written there: an untrackable bearer credential is one anybody who saw the request
        //      can send again. Section 10.2(d)'s own guidance for a request object URI is "less
        //      than a minute", so a spec-shaped object is short lived by intent.
        //   2. A MALFORMED `exp`, which was WORSE than a missing one and is the reason this block
        //      was rewritten. The old code read the claim with `as_u64()` inside an `if let`, so a
        //      string, a fraction, a negative or exponent notation all produced `None` and the
        //      branch simply did not run. The client wrote an expiry, a reviewer reading the object
        //      sees an expiry, and the server ignored it. "We could not check this" must never read
        //      as "checked out".
        //   3. AN UNBOUNDED `exp`. An object may not name its own replay window: a year out is an
        //      immortal credential with a lifetime claim stapled to it. `max_request_object_lifetime`
        //      is the ceiling and the object gets the lesser of the two.
        //
        // The claim is a NumericDate per RFC 7519 section 2: "a JSON numeric value", and the
        // section says it "intentionally allows non-integer values". So 1.5 and 1.7e9 are LEGAL
        // spellings that must be honoured, and only a NON-NUMBER is malformed. The old code read
        // these with `as_u64`, which answers `None` for every legal non-integer spelling and every
        // illegal one alike, and then treated both as "the claim is absent".
        let numeric_date = |name: &str| -> Result<Option<f64>, ErrorResponse> {
            match payload.get(name) {
                None => Ok(None),
                Some(v) => v.as_f64().map(Some).ok_or_else(|| {
                    ErrorResponse::new(ErrorCode::InvalidRequestObject).with_description(format!(
                        "the request object's {name} is not a NumericDate (RFC 7519 s2)"
                    ))
                }),
            }
        };
        let now_secs = crate::server::unix_seconds(self.now()).ok_or_else(|| {
            ErrorResponse::new(ErrorCode::ServerError)
                .with_description("the server clock is outside the representable range")
        })? as f64;
        let exp = numeric_date("exp")?.ok_or_else(|| {
            ErrorResponse::new(ErrorCode::InvalidRequestObject).with_description(
                "the request object has no exp, so it would authorize its request for as long as \
                 the client's key stays registered",
            )
        })?;
        if now_secs >= exp {
            return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                .with_description("the request object has expired"));
        }
        let ceiling = self
            .config()
            .jar
            .as_ref()
            .map(|j| j.max_request_object_lifetime)
            .unwrap_or_else(|| std::time::Duration::from_secs(300));
        if exp - now_secs > ceiling.as_secs() as f64 {
            return Err(
                ErrorResponse::new(ErrorCode::InvalidRequestObject).with_description(
                    "the request object's remaining lifetime exceeds what this server accepts",
                ),
            );
        }
        // `nbf` reads the same way. It can only ever REFUSE an object that is otherwise fine, so a
        // malformed one failing closed costs a legitimate client nothing that sending a valid claim
        // would not have cost it. The leeway is the crate's single definition of clock skew rather
        // than a second one invented here, which is the drift `skew.rs` exists to have ended.
        if let Some(nbf) = numeric_date("nbf")? {
            if now_secs + crate::skew::CLOCK_SKEW_LEEWAY.as_secs() as f64 <= nbf {
                return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                    .with_description("the request object is not yet valid"));
            }
        }

        // RFC 9396 section 5, in the build that supports NO authorization detail type at all: the
        // parameter is REFUSED rather than ignored. Without `rar` the claim below does not exist,
        // so the object's `authorization_details` would be dropped on the floor and the client
        // would receive a code, and then a token, that says nothing about the permission it asked
        // for and believes it obtained. Section 5 makes refusing that a MUST, and a REQUEST OBJECT
        // is the worst place to ignore it: the client SIGNED these parameters, and RFC 9101
        // section 6.3 requires this server to use the object's parameters and no others. Same
        // posture as `request_not_supported` above for an object this server will not process at
        // all: say so, rather than proceed as though the parameter had not been sent.
        #[cfg(not(feature = "rar"))]
        if claims.contains_key("authorization_details") {
            return Err(ErrorResponse::new(ErrorCode::InvalidAuthorizationDetails)
                .with_description("this server does not support authorization_details"));
        }

        // RFC 8707 section 2 allows `resource` more than once, which in a JSON claim set is an
        // array; a single indicator stays a plain string.
        let resource = match claims.get("resource") {
            None => Vec::new(),
            Some(serde_json::Value::String(one)) => vec![one.clone()],
            Some(serde_json::Value::Array(many)) => {
                let mut out = Vec::with_capacity(many.len());
                for value in many {
                    match value.as_str() {
                        Some(s) => out.push(s.to_string()),
                        None => {
                            return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                                .with_description(
                                    "every resource claim entry must be a JSON string",
                                ))
                        }
                    }
                }
                out
            }
            Some(_) => {
                return Err(
                    ErrorResponse::new(ErrorCode::InvalidRequestObject).with_description(
                        "the resource claim must be a string or an array of strings",
                    ),
                )
            }
        };

        Ok(RequestObjectClaims {
            client_id: client_id.as_str().to_string(),
            response_type: string_claim(claims, "response_type")?,
            redirect_uri: string_claim(claims, "redirect_uri")?,
            scope: string_claim(claims, "scope")?,
            state: string_claim(claims, "state")?,
            code_challenge: string_claim(claims, "code_challenge")?,
            code_challenge_method: string_claim(claims, "code_challenge_method")?,
            resource,
            // RFC 9396 s2 makes `authorization_details` a JSON ARRAY, and inside a request
            // object it stays one: RFC 9101 s4 requires request parameters to be JSON
            // strings but exempts values that are themselves JSON, and a client that had to
            // string-escape its array here would produce something no other endpoint
            // accepts. It is re-serialized to the compact text the rest of this crate
            // parses, so the request object and the query string reach exactly the same
            // validation rather than two nearly identical ones.
            #[cfg(feature = "rar")]
            authorization_details: match claims.get("authorization_details") {
                None => None,
                Some(value @ serde_json::Value::Array(_)) => Some(value.to_string()),
                Some(_) => {
                    return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                        .with_description("the authorization_details claim must be a JSON array"))
                }
            },
            // RFC 9470 s4, from INSIDE the signature. A client answering a step-up challenge puts
            // these in the request object (RFC 9101 s4), and s6.3 requires the server to use only
            // the object's parameters "even if the same parameter is provided in the query
            // parameter". Reading the query for these two instead meant trusting the one part of
            // a JAR request an intermediary can still rewrite, on a request whose entire purpose
            // is that it cannot be.
            #[cfg(feature = "consent")]
            acr_values: string_claim(claims, "acr_values")?,
            // `max_age` is the one exception to the JSON-string rule above, and OpenID Connect
            // Core section 6.1's own worked example is why: it shows `"max_age": 86400`, a JSON
            // NUMBER, in a request object. Refusing that would refuse the conforming client this
            // parameter exists for, so a non-negative integer is accepted and normalised to the
            // decimal text the rest of this crate parses. A fractional or negative number is not
            // "the number of seconds" (OpenID Connect Core s3.1.2.1) and is refused.
            #[cfg(feature = "consent")]
            max_age: match claims.get("max_age") {
                None => None,
                Some(serde_json::Value::String(s)) => Some(s.clone()),
                Some(serde_json::Value::Number(n)) => match n.as_u64() {
                    Some(secs) => Some(secs.to_string()),
                    None => {
                        return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                            .with_description(
                                "the max_age claim must be a non-negative number of seconds",
                            ))
                    }
                },
                Some(_) => {
                    return Err(ErrorResponse::new(ErrorCode::InvalidRequestObject)
                        .with_description("the max_age claim must be a JSON string or number"))
                }
            },
        })
    }
}

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