axiam-sdk 1.2.2

Official Rust client SDK for AXIAM IAM
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
//! CIBA — client-initiated backchannel authentication, CONTRACT.md §33
//! (contract 1.58; CIBA Core 1.0, poll and ping modes).
//!
//! A client that already knows whom it wants to authenticate asks AXIAM to
//! authenticate that user **on another device**; AXIAM notifies the user, who
//! approves or refuses on the console. The client then collects the tokens at
//! the token endpoint — by polling, or once after AXIAM *pings* it.
//!
//! Four operations on [`AxiamClient`]:
//!
//! | Operation | What it does |
//! |---|---|
//! | [`AxiamClient::ciba_initiate`] | `POST /oauth2/bc-authorize`. **Never retried.** |
//! | [`AxiamClient::ciba_poll`] | one token request with `grant_type=urn:openid:params:grant-type:ciba` |
//! | [`AxiamClient::ciba_await`] | polls to a terminal outcome, honouring `interval` and `slow_down` |
//! | [`AxiamClient::ciba_handle_ping`] | verifies a ping's bearer and returns its `auth_req_id`; no I/O |
//!
//! Two things a caller must not read into a success:
//!
//! * **A successful `ciba_initiate` proves nothing about the user** (§33.3
//!   rule 4). AXIAM answers a hint that names nobody, a locked user and a real
//!   one identically, and the only signal that a user did not answer is
//!   `expired_token`. Nothing here reports that a user "exists" or "was
//!   notified".
//! * **A ping says the request was decided, never how** (§33.2). Call
//!   `ciba_poll` after answering the ping; the outcome — tokens,
//!   `access_denied` or `expired_token` — comes from the token endpoint.
//!
//! The client always authenticates, by the credential this SDK was built with
//! (`client_secret_post`, or the §6.1 client certificate for a
//! `tls_client_auth` client); a client built with neither is refused locally.
//! `auth_req_id`, `client_notification_token` and the signing key are
//! [`Sensitive`] (§33.5).

use crate::time::{Duration, Instant};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use jsonwebtoken::{Algorithm, EncodingKey, Header};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use uuid::Uuid;

use super::discovery::OidcConfiguration;
use super::exchange::{OidcTokenSet, TokenResponseWire, oauth2_error_or_fallback};
use crate::client::AxiamClient;
use crate::error::AxiamError;
use crate::management::error::local_refusal;
use crate::sensitive::Sensitive;

/// `grant_type` of the CIBA token request (CIBA Core §10.1).
pub const CIBA_GRANT_TYPE: &str = "urn:openid:params:grant-type:ciba";

/// The interval used when the initiate response carries none (§33.7 rule 2).
pub const DEFAULT_CIBA_INTERVAL_SECS: u64 = 5;

/// Seconds added to the interval per `slow_down`, permanently (§33.7 rule 3).
pub const CIBA_SLOW_DOWN_INCREMENT_SECS: u64 = 5;

/// The lifetime of a signed request this SDK mints: five minutes, inside the
/// server's sixty-minute bound on `exp - nbf` (§33.2).
pub const SIGNED_REQUEST_LIFETIME_SECS: i64 = 300;

// ---------------------------------------------------------------------------
// Request and response types
// ---------------------------------------------------------------------------

/// Whom to authenticate: **exactly one** hint (§33.2). A sum type, so sending
/// both, or neither, cannot be written. `login_hint_token` is not offered.
#[derive(Debug, Clone)]
pub enum CibaUserHint {
    /// A username, then an e-mail address, within the tenant.
    LoginHint(String),
    /// An ID token this deployment issued to this client.
    IdTokenHint(String),
}

/// How the client receives the outcome, as it registered.
#[derive(Debug, Clone)]
pub enum CibaDelivery {
    /// The client polls the token endpoint.
    Poll,
    /// AXIAM pings the client's registered notification endpoint, presenting
    /// this token as a bearer; the client then polls once.
    Ping {
        /// The bearer AXIAM presents at the ping; keep it to check the ping
        /// with [`AxiamClient::ciba_handle_ping`]. Never returned by AXIAM.
        client_notification_token: Sensitive<String>,
    },
}

/// The signature algorithms a signed request may use (§33.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CibaSigningAlg {
    /// RSASSA-PSS with SHA-256.
    Ps256,
    /// ECDSA on P-256 with SHA-256.
    Es256,
    /// Ed25519.
    EdDsa,
}

impl CibaSigningAlg {
    fn jose(self) -> Algorithm {
        match self {
            CibaSigningAlg::Ps256 => Algorithm::PS256,
            CibaSigningAlg::Es256 => Algorithm::ES256,
            CibaSigningAlg::EdDsa => Algorithm::EdDSA,
        }
    }
}

/// The key and algorithm for the signed request form (§33.2, CIBA Core
/// §7.1.1). Both are the caller's: there is no default for either, and the
/// SDK signs under exactly the algorithm given — the one the client
/// registered as `backchannel_authentication_request_signing_alg`.
///
/// The key is held only as a signing key; `Debug` shows the algorithm and
/// `kid`, never the key.
#[derive(Clone)]
pub struct CibaRequestSigner {
    alg: CibaSigningAlg,
    key: Sensitive<RequestKey>,
    kid: Option<String>,
}

/// What signs. ES256 and PS256 are signed by `ring`, never by `jsonwebtoken`'s
/// RustCrypto backend, and a caller's private key must not meet that backend:
/// its P-256 scalar arithmetic runs on `crypto-bigint` 0.5.5, whose
/// constant-time defects are RUSTSEC-2026-0387, and it signs RSA with the `rsa`
/// crate, whose private-key operations are not constant time
/// (RUSTSEC-2023-0071, the Marvin attack). EdDSA keeps `jsonwebtoken`.
#[derive(Clone)]
enum RequestKey {
    Jwt(EncodingKey),
    #[cfg(not(target_arch = "wasm32"))]
    Es256(Arc<ring::signature::EcdsaKeyPair>),
    #[cfg(not(target_arch = "wasm32"))]
    Ps256(Arc<ring::signature::RsaKeyPair>),
}

impl std::fmt::Debug for CibaRequestSigner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CibaRequestSigner")
            .field("alg", &self.alg)
            .field("kid", &self.kid)
            .field("key", &self.key)
            .finish()
    }
}

impl CibaRequestSigner {
    /// A signer from a PEM private key (PKCS#8 for EdDSA and ES256; PKCS#1 or
    /// PKCS#8 for PS256) and the algorithm it signs under.
    ///
    /// ES256 and PS256 are signed by `ring`. ES256 takes a PKCS#8 `PRIVATE KEY`
    /// PEM only; the PS256 RSA key must be one `ring` signs with: 2048 to 8192
    /// bits, a multiple of 512 bits. Neither is available in the browser
    /// (wasm32) build, which refuses both.
    ///
    /// # Errors
    /// A local `ValidationError`, before any request, when the PEM is not a
    /// key, or not a key that signs under `alg`.
    pub fn from_pem(
        alg: CibaSigningAlg,
        pem: &Sensitive<Vec<u8>>,
        kid: Option<String>,
    ) -> Result<Self, AxiamError> {
        let refuse = || {
            local_refusal(
                "ciba_initiate",
                "signing_key",
                "the key is not a private key that signs under the given algorithm (CONTRACT.md §33.2)",
            )
        };
        let key = match alg {
            CibaSigningAlg::EdDsa => EncodingKey::from_ed_pem(pem.expose())
                .map(RequestKey::Jwt)
                .map_err(|_| refuse())?,
            #[cfg(not(target_arch = "wasm32"))]
            CibaSigningAlg::Es256 => {
                let der = pkcs8_der_from_pem(pem.expose()).ok_or_else(refuse)?;
                let pair = ring::signature::EcdsaKeyPair::from_pkcs8(
                    &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
                    &der,
                    &ring::rand::SystemRandom::new(),
                )
                .map_err(|_| refuse())?;
                RequestKey::Es256(Arc::new(pair))
            }
            #[cfg(target_arch = "wasm32")]
            CibaSigningAlg::Es256 => {
                return Err(local_refusal(
                    "ciba_initiate",
                    "signing_key",
                    "ES256 request signing is not available in the browser build (CONTRACT.md §33.2)",
                ));
            }
            #[cfg(not(target_arch = "wasm32"))]
            CibaSigningAlg::Ps256 => {
                // PKCS#8 `PRIVATE KEY` or PKCS#1 `RSA PRIVATE KEY`, as
                // `EncodingKey::from_rsa_pem` took.
                let parsed = if let Some(der) = pkcs8_der_from_pem(pem.expose()) {
                    ring::signature::RsaKeyPair::from_pkcs8(&der)
                } else {
                    let der = pkcs1_der_from_pem(pem.expose()).ok_or_else(refuse)?;
                    ring::signature::RsaKeyPair::from_der(&der)
                };
                let pair = parsed.map_err(|e| match e.to_string().as_str() {
                    "TooSmall" | "TooLarge" | "PrivateModulusLenNotMultipleOf512Bits" => {
                        local_refusal(
                            "ciba_initiate",
                            "signing_key",
                            "a PS256 key must be 2048 to 8192 bits, a multiple of 512 bits: the RSA sizes ring signs with (CONTRACT.md §33.2)",
                        )
                    }
                    _ => refuse(),
                })?;
                RequestKey::Ps256(Arc::new(pair))
            }
            #[cfg(target_arch = "wasm32")]
            CibaSigningAlg::Ps256 => {
                return Err(local_refusal(
                    "ciba_initiate",
                    "signing_key",
                    "PS256 request signing is not available in the browser build (CONTRACT.md §33.2)",
                ));
            }
        };
        // A key that parses is not yet a key for this algorithm: prove it signs.
        match &key {
            RequestKey::Jwt(k) => {
                jsonwebtoken::crypto::sign(b"axiam-ciba-probe", k, alg.jose())
                    .map_err(|_| refuse())?;
            }
            #[cfg(not(target_arch = "wasm32"))]
            RequestKey::Es256(pair) => {
                es256_sign(pair, b"axiam-ciba-probe").ok_or_else(refuse)?;
            }
            #[cfg(not(target_arch = "wasm32"))]
            RequestKey::Ps256(pair) => {
                ps256_sign(pair, b"axiam-ciba-probe").ok_or_else(refuse)?;
            }
        }
        Ok(Self {
            alg,
            key: Sensitive::new(key),
            kid,
        })
    }

    /// The algorithm this signer uses.
    pub fn alg(&self) -> CibaSigningAlg {
        self.alg
    }

    /// The `ring` RSA key pair, when this signer holds one (PS256, native).
    #[cfg(all(test, not(target_arch = "wasm32")))]
    fn ring_rsa(&self) -> Option<&ring::signature::RsaKeyPair> {
        match self.key.expose() {
            RequestKey::Ps256(pair) => Some(pair),
            RequestKey::Jwt(_) | RequestKey::Es256(_) => None,
        }
    }
}

/// Arguments to [`AxiamClient::ciba_initiate`] (§33.2 `CibaInitiateRequest`).
///
/// `binding_message` and `login_hint` can be personal data: the SDK never logs
/// them. `user_code`, `login_hint_token` and `request_uri` are not members —
/// AXIAM refuses each (§33.3 rule 3).
#[derive(Debug, Clone)]
pub struct CibaInitiateParams {
    /// Space-separated; must include `openid`.
    pub scope: String,
    /// Whom to authenticate.
    pub hint: CibaUserHint,
    /// Shown to the user on the approval page — what lets them tell the
    /// request they started from one an attacker did. Required for a `fapi2`
    /// client.
    pub binding_message: Option<String>,
    /// The requested lifetime, 30–600 s (absent: 300).
    pub requested_expiry: Option<u32>,
    /// Space-separated authentication context classes.
    pub acr_values: Option<String>,
    /// RFC 8707 resource indicator.
    pub resource: Option<String>,
    /// Poll or ping, as registered.
    pub delivery: CibaDelivery,
    /// `Some` sends the request as one signed JWT (`request`) — required of a
    /// client that registered a signing algorithm, refused from one that did
    /// not.
    pub signer: Option<CibaRequestSigner>,
    /// Tenant UUID for the `tenant_id` query parameter (§12.1 note 2).
    pub tenant_id: Option<Uuid>,
    /// A pre-fetched discovery document.
    pub configuration: Option<OidcConfiguration>,
}

impl CibaInitiateParams {
    /// A poll-mode, unsigned request for `scope` and `hint`.
    pub fn new(scope: impl Into<String>, hint: CibaUserHint) -> Self {
        Self {
            scope: scope.into(),
            hint,
            binding_message: None,
            requested_expiry: None,
            acr_values: None,
            resource: None,
            delivery: CibaDelivery::Poll,
            signer: None,
            tenant_id: None,
            configuration: None,
        }
    }
}

/// `CibaInitiateResponse` (§33.2).
#[derive(Debug, Clone)]
pub struct CibaInitiateResponse {
    /// The request's id at the token endpoint — a bearer credential for the
    /// grant (§33.5). Never parse or length-check it.
    pub auth_req_id: Sensitive<String>,
    /// The request's lifetime, seconds — authoritative (§33.7 rule 4).
    pub expires_in: u64,
    /// The minimum seconds between token requests; the response's value, or
    /// [`DEFAULT_CIBA_INTERVAL_SECS`] when it was absent or zero.
    pub interval: u64,
    /// When the response was received; `ciba_await`'s deadline is this plus
    /// `expires_in`.
    pub received_at: Instant,
}

#[derive(Deserialize)]
struct CibaInitiateResponseWire {
    auth_req_id: String,
    expires_in: u64,
    #[serde(default)]
    interval: Option<u64>,
}

/// Arguments to [`AxiamClient::ciba_poll`].
#[derive(Debug, Clone)]
pub struct CibaPollParams {
    /// The `auth_req_id` from [`CibaInitiateResponse`] or a ping.
    pub auth_req_id: Sensitive<String>,
    /// Tenant UUID for the `tenant_id` query parameter.
    pub tenant_id: Option<Uuid>,
    /// A pre-fetched discovery document.
    pub configuration: Option<OidcConfiguration>,
}

/// The clock [`AxiamClient::ciba_await`] waits on — injectable so its
/// schedule is testable without sleeping (§33.8 tests 6 and 7).
pub trait CibaClock: Send + Sync {
    /// The current instant.
    fn now(&self) -> Instant;
    /// Wait `duration`.
    fn sleep(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
}

/// The real clock: `Instant::now` and `tokio::time::sleep`.
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemCibaClock;

impl CibaClock for SystemCibaClock {
    fn now(&self) -> Instant {
        Instant::now()
    }
    fn sleep(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
        Box::pin(tokio::time::sleep(duration))
    }
}

/// Arguments to [`AxiamClient::ciba_await`].
#[derive(Clone, Default)]
pub struct CibaAwaitParams {
    /// Tenant UUID for the `tenant_id` query parameter.
    pub tenant_id: Option<Uuid>,
    /// A pre-fetched discovery document.
    pub configuration: Option<OidcConfiguration>,
    /// The clock to wait on; `None` is [`SystemCibaClock`].
    pub clock: Option<Arc<dyn CibaClock>>,
}

impl std::fmt::Debug for CibaAwaitParams {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CibaAwaitParams")
            .field("tenant_id", &self.tenant_id)
            .field(
                "configuration",
                &self.configuration.as_ref().map(|c| &c.issuer),
            )
            .field("clock", &self.clock.as_ref().map(|_| "<clock>"))
            .finish()
    }
}

// ---------------------------------------------------------------------------
// The polling schedule (§33.7), as a value type
// ---------------------------------------------------------------------------

/// What one poll answer means for the loop (§33.3 rule 6, §33.7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Step {
    /// `authorization_pending` — keep polling at the current interval.
    Pending,
    /// `slow_down` — add 5 s to the interval, for good.
    SlowDown,
    /// A transport failure, a `408`, a `429` or a `5xx` (whatever its body)
    /// that outlived §16's retries — not terminal; wait one interval (§33.7
    /// rule 5, contract 1.59 P8, P9).
    Transient,
    /// Anything else is the answer: `access_denied`, `expired_token`,
    /// `invalid_grant`, a `4xx` without an `error` member, the call refused
    /// locally — and **any failure after a `2xx`** (a body that does not
    /// decode, an ID token that does not validate or whose key cannot be
    /// fetched), because the redemption is spent (§33.7 rule 7, P9).
    Terminal,
}

/// A failed [`AxiamClient::ciba_poll`], with what it means for the loop.
struct PollFailure {
    err: AxiamError,
    step: Step,
}

impl PollFailure {
    fn terminal(err: AxiamError) -> Self {
        Self {
            err,
            step: Step::Terminal,
        }
    }
}

/// The step a decisive (not retried) non-`2xx` answer means.
fn decisive_step(err: &AxiamError, status: u16) -> Step {
    match err.oauth_error_code() {
        Some("authorization_pending") => Step::Pending,
        Some("slow_down") => Step::SlowDown,
        // §33.3 rule 13: a 429's body is `rate_limit_exceeded`, never terminal
        // for a poll; P9: a `408` and a `429` are transient, whatever they say.
        Some("rate_limit_exceeded") => Step::Transient,
        _ if status == 408 || status == 429 => Step::Transient,
        _ => Step::Terminal,
    }
}

// ---------------------------------------------------------------------------
// The four operations
// ---------------------------------------------------------------------------

/// The client's credential for these calls: client_secret_post, or the client
/// certificate the transport presents (`tls_client_auth`).
struct ClientAuth {
    client_id: String,
    client_secret: Option<String>,
}

impl AxiamClient {
    fn ciba_client_auth(&self, operation: &str) -> Result<ClientAuth, AxiamError> {
        let client_id = self.oidc_client_id_or_err()?.to_string();
        let client_secret = self.oidc_client_secret().map(|s| s.expose().clone());
        if client_secret.is_none() && !self.presents_client_certificate() {
            return Err(AxiamError::auth(format!(
                "{operation} requires client authentication: a CIBA client is never public — \
                 build the client with .oidc_client_secret(...) or a §6.1 client certificate \
                 (CONTRACT.md §33.1)"
            )));
        }
        Ok(ClientAuth {
            client_id,
            client_secret,
        })
    }

    /// `POST /oauth2/bc-authorize` (CIBA Core §7, CONTRACT.md §33.1) — ask AXIAM
    /// to authenticate a user on another device.
    ///
    /// **Never retried** — not on a transport error, a `5xx` or a `429`
    /// (§33.7 rule 1): every accepted call stores a request and may notify a
    /// person. On a lost answer, let it expire and ask again deliberately.
    ///
    /// A success proves nothing about the user (§33.3 rule 4); see the module
    /// documentation.
    ///
    /// # Errors
    /// * a local [`AxiamError::Auth`] when the client has no credential;
    /// * a local `ValidationError` for a ping-mode request without a
    ///   `client_notification_token`;
    /// * the server's refusals as [`crate::OAuthProtocolError`]s — for
    ///   example `invalid_binding_message`, whose `error_description` is the
    ///   server's.
    pub async fn ciba_initiate(
        &self,
        params: CibaInitiateParams,
    ) -> Result<CibaInitiateResponse, AxiamError> {
        self.ensure_open()?;
        let auth = self.ciba_client_auth("ciba_initiate")?;
        if let CibaDelivery::Ping {
            client_notification_token,
        } = &params.delivery
            && client_notification_token.expose().is_empty()
        {
            return Err(local_refusal(
                "ciba_initiate",
                "client_notification_token",
                "a ping-mode request needs a client_notification_token: without one AXIAM has nothing to ping with (CONTRACT.md §33.8)",
            ));
        }
        let configuration = match params.configuration.clone() {
            Some(c) => c,
            None => self.oidc_discover().await?,
        };
        let tenant_id = self.resolve_oidc_tenant_id(params.tenant_id).await?;
        let endpoint = self
            .mtls_preferred_opt(
                &configuration,
                |a| a.backchannel_authentication_endpoint.as_deref(),
                configuration.backchannel_authentication_endpoint.as_deref(),
            )?
            .ok_or_else(|| {
                AxiamError::auth(
                    "the authorization server's discovery document advertises no \
                     backchannel_authentication_endpoint: this server does not support CIBA \
                     (CONTRACT.md §33.1)",
                )
            })?;
        let url = self.oidc_endpoint_url(endpoint, tenant_id)?;

        let mut form: Vec<(&'static str, Sensitive<String>)> =
            vec![("client_id", Sensitive::new(auth.client_id.clone()))];
        if let Some(secret) = &auth.client_secret {
            form.push(("client_secret", Sensitive::new(secret.clone())));
        }
        match &params.signer {
            Some(signer) => {
                let request =
                    signed_request(&params, signer, &auth.client_id, &configuration.issuer)?;
                form.push(("request", request));
            }
            None => form.extend(plain_members(&params)),
        }
        let body: Vec<(&str, &str)> = form
            .iter()
            .map(|(k, v)| (*k, v.expose().as_str()))
            .collect();

        let response = self
            .idp_form_post(url)
            .form(&body)
            .send()
            .await
            .map_err(|e| AxiamError::network(format!("ciba_initiate request failed: {e}")))?;
        if !response.status().is_success() {
            return Err(oauth2_error_or_fallback(response).await);
        }
        let wire: CibaInitiateResponseWire = response.json().await.map_err(|e| {
            AxiamError::network(format!("failed to parse the ciba_initiate response: {e}"))
        })?;
        Ok(CibaInitiateResponse {
            auth_req_id: Sensitive::new(wire.auth_req_id),
            expires_in: wire.expires_in,
            interval: wire
                .interval
                .filter(|i| *i > 0)
                .unwrap_or(DEFAULT_CIBA_INTERVAL_SECS),
            received_at: Instant::now(),
        })
    }

    /// `POST /oauth2/token` with `grant_type=urn:openid:params:grant-type:ciba`
    /// (CIBA Core §10.1, CONTRACT.md §33.1) — **one** token request.
    ///
    /// The answers of §33.3 rule 6 surface as [`AxiamError::Auth`] carrying a
    /// [`crate::OAuthProtocolError`]: `authorization_pending` and `slow_down`
    /// (non-terminal), `access_denied` and `expired_token` (terminal and
    /// distinct — [`AxiamError::is_access_denied`],
    /// [`AxiamError::is_expired_token`]), `invalid_grant`.
    ///
    /// Retried per §16 on a transport failure, a bodiless `408` or `429`, and
    /// a `5xx` **whatever its body** — AXIAM answers an internal failure
    /// `500 {"error":"server_error"}` — which then surfaces as a
    /// `NetworkError`, never as that `OAuthProtocolError` (§33.7 rule 5,
    /// contract 1.59 P8). **Store the returned tokens before anything else**:
    /// a request is redeemed once, and a second `ciba_poll` for it is
    /// `invalid_grant` (§33.7 rule 7).
    ///
    /// A bare `ciba_poll` has no deadline of its own and keeps §16's bounded
    /// budget; [`Self::ciba_await`]'s polls are bounded by the request's
    /// deadline (§33.7 rule 5, §34.2 P10, contract 1.60).
    pub async fn ciba_poll(&self, params: CibaPollParams) -> Result<OidcTokenSet, AxiamError> {
        self.ciba_poll_step(params, None).await.map_err(|f| f.err)
    }

    /// [`Self::ciba_poll`], keeping what a failure means for
    /// [`Self::ciba_await`]'s loop. `bound`, when set, is `ciba_await`'s
    /// deadline and clock: a §16 retry here never waits past the deadline and
    /// no request follows it (`expired_token` is then the outcome).
    async fn ciba_poll_step(
        &self,
        params: CibaPollParams,
        bound: Option<(Instant, &dyn CibaClock)>,
    ) -> Result<OidcTokenSet, PollFailure> {
        use crate::retry::{
            Attempt, RetryBound, RetryRunner, Sleeper, ThreadRngJitter, TokioSleeper,
            parse_retry_after,
        };
        self.ensure_open().map_err(PollFailure::terminal)?;
        let auth = self
            .ciba_client_auth("ciba_poll")
            .map_err(PollFailure::terminal)?;
        let configuration = match params.configuration {
            Some(c) => c,
            None => self.oidc_discover().await.map_err(PollFailure::terminal)?,
        };
        let tenant_id = self
            .resolve_oidc_tenant_id(params.tenant_id)
            .await
            .map_err(PollFailure::terminal)?;
        let endpoint = self
            .mtls_preferred(
                &configuration,
                |a| a.token_endpoint.as_deref(),
                &configuration.token_endpoint,
            )
            .map_err(PollFailure::terminal)?;
        let url = self
            .oidc_endpoint_url(endpoint, tenant_id)
            .map_err(PollFailure::terminal)?;
        let mut form: Vec<(&str, &str)> = vec![
            ("grant_type", CIBA_GRANT_TYPE),
            ("auth_req_id", params.auth_req_id.expose().as_str()),
            ("client_id", auth.client_id.as_str()),
        ];
        if let Some(secret) = &auth.client_secret {
            form.push(("client_secret", secret.as_str()));
        }
        let runner = RetryRunner {
            enabled: self.retry_enabled(),
            operation: "ciba_poll",
            telemetry: self.telemetry(),
            jitter: &ThreadRngJitter,
            sleeper: &TokioSleeper,
        };
        let (url, form) = (&url, &form);
        // The retry's waits are served on the loop's injected clock.
        struct ClockSleeper<'c>(&'c dyn CibaClock);
        impl Sleeper for ClockSleeper<'_> {
            fn sleep(&self, d: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
                self.0.sleep(d)
            }
        }
        let bound_sleeper = bound.map(|(_, clock)| ClockSleeper(clock));
        let bound_now = bound.map(|(_, clock)| move || clock.now());
        let retry_bound = match (bound, &bound_sleeper, &bound_now) {
            (Some((deadline, _)), Some(sleeper), Some(now)) => Some(RetryBound {
                deadline,
                now,
                sleeper,
            }),
            _ => None,
        };
        let wire: TokenResponseWire = runner
            .run_until(retry_bound.as_ref(), |_| async move {
                let response = self
                    .idp_form_post(url.clone())
                    .form(form)
                    .send()
                    .await
                    .map_err(|e| {
                        Attempt::bare(AxiamError::network(format!(
                            "ciba_poll request failed: {e}"
                        )))
                    })?;
                if !response.status().is_success() {
                    let retry_after = response
                        .headers()
                        .get(reqwest::header::RETRY_AFTER)
                        .and_then(|v| v.to_str().ok())
                        .and_then(parse_retry_after);
                    let status = response.status().as_u16();
                    // P8: on this operation a 5xx is transient whatever its
                    // body, so it maps by status (§2) rather than by `error`.
                    if status >= 500 {
                        let text = response.text().await.unwrap_or_default();
                        let err = AxiamError::from_http_status(status, text);
                        return Err(Attempt { err, retry_after });
                    }
                    let err = oauth2_error_or_fallback(response).await;
                    // The protocol answers (`authorization_pending`, …) are
                    // decisive, and so is any other 4xx but a bodiless 408 /
                    // 429.
                    if err.oauth_error_code().is_some()
                        || !crate::retry::status_is_retryable(status)
                    {
                        let step = decisive_step(&err, status);
                        return Ok(Err(PollFailure { err, step }));
                    }
                    return Err(Attempt { err, retry_after });
                }
                // §33.7 rule 7: consume the 200 before anything else — and a
                // body that does not parse is not retried, since the server
                // may already have redeemed the request: it is terminal.
                Ok(response.json::<TokenResponseWire>().await.map_err(|e| {
                    PollFailure::terminal(AxiamError::network(format!(
                        "failed to parse the ciba_poll response: {e}"
                    )))
                }))
            })
            .await
            .map_err(|ended| {
                if ended.at_deadline {
                    // The retry's wait ended at the deadline: no request
                    // follows it, and the request has expired (§33.7 rule 4).
                    return PollFailure::terminal(expired_token());
                }
                // What outlived §16's retries is a transport failure, a 5xx or
                // a bodiless 408 / 429: transient for the loop.
                PollFailure {
                    err: ended.err,
                    step: Step::Transient,
                }
            })??;
        // After the 2xx: a failure here — the ID token, or the key fetch its
        // validation needs — is terminal; the redemption is spent (P9).
        self.to_token_set(wire, &configuration, None)
            .await
            .map_err(PollFailure::terminal)
    }

    /// Poll for `initiated`'s outcome until it is decided or expires (§33.1,
    /// §33.7). Surfaces nothing to the user — AXIAM notified them.
    ///
    /// * The first poll waits one `interval`; polling earlier only earns
    ///   `slow_down` and a longer wait.
    /// * `slow_down` adds [`CIBA_SLOW_DOWN_INCREMENT_SECS`] to the interval,
    ///   cumulatively and permanently; `authorization_pending` never lowers it.
    /// * A transport failure, a `408`, a `429` or a `5xx` (whatever its body)
    ///   is not terminal: the loop waits the interval and polls again.
    /// * Anything else ends the loop: a `4xx` without an `error` member, and
    ///   any failure **after** a `200` — a body that does not decode, an ID
    ///   token that does not validate or whose key cannot be fetched. The
    ///   redemption is spent, so polling again could only answer
    ///   `invalid_grant` (§33.7 rule 7, contract 1.59 P9); such tokens are
    ///   not returned (§12.4), and the application starts a new request.
    /// * Polling stops at `received_at + expires_in`, even if the server has
    ///   not said `expired_token`; the same `expired_token` is then raised
    ///   locally. That includes a §16 retry inside a poll: its wait (a
    ///   `Retry-After` is a minimum wait) is capped at the deadline and
    ///   served on the injected clock, and when the wait ends there no request
    ///   follows (§34.2 P10, contract 1.60).
    ///
    /// Returns the token set without adopting it as this client's credential
    /// — the posture of `device_login` and `login_client_credentials`. In
    /// **ping** mode, do not call this: call [`Self::ciba_poll`] once from
    /// the ping handler, and fall back to this loop only once half of
    /// `expires_in` has passed without a ping (§33.7 rule 6).
    pub async fn ciba_await(
        &self,
        initiated: &CibaInitiateResponse,
        params: CibaAwaitParams,
    ) -> Result<OidcTokenSet, AxiamError> {
        let clock: Arc<dyn CibaClock> = params
            .clock
            .clone()
            .unwrap_or_else(|| Arc::new(SystemCibaClock));
        let configuration = match params.configuration {
            Some(c) => c,
            None => self.oidc_discover().await?,
        };
        let deadline = initiated.received_at + Duration::from_secs(initiated.expires_in);
        let mut interval = if initiated.interval == 0 {
            DEFAULT_CIBA_INTERVAL_SECS
        } else {
            initiated.interval
        };
        loop {
            let wait = Duration::from_secs(interval);
            if clock.now() + wait >= deadline {
                return Err(expired_token());
            }
            clock.sleep(wait).await;
            match self
                .ciba_poll_step(
                    CibaPollParams {
                        auth_req_id: initiated.auth_req_id.clone(),
                        tenant_id: params.tenant_id,
                        configuration: Some(configuration.clone()),
                    },
                    Some((deadline, clock.as_ref())),
                )
                .await
            {
                Ok(tokens) => return Ok(tokens),
                Err(PollFailure { err, step }) => match step {
                    Step::Pending | Step::Transient => continue,
                    Step::SlowDown => interval += CIBA_SLOW_DOWN_INCREMENT_SECS,
                    Step::Terminal => return Err(err),
                },
            }
        }
    }

    /// Check a ping AXIAM delivered to your notification endpoint and return
    /// the `auth_req_id` it names (CIBA Core §10.2, CONTRACT.md §33.1). **No
    /// I/O.**
    ///
    /// `headers` are the request's headers as `(name, value)` pairs, in any
    /// framework's shape; `body` its raw body; `expected_token` the
    /// `client_notification_token` you sent with the request.
    ///
    /// 1. Exactly one `Authorization` header, `Bearer` (any case), one space,
    ///    and the token — compared in constant time. Otherwise
    ///    [`AxiamError::Auth`], whose message names no value.
    /// 2. A JSON object with a non-empty string `auth_req_id`; any other
    ///    member is ignored. Otherwise a local `ValidationError`.
    ///
    /// It neither answers the HTTP request nor calls the token endpoint:
    /// answer `204` as soon as this returns, **then** [`Self::ciba_poll`] —
    /// AXIAM retries a ping that is not answered quickly. Nor does it check
    /// that the `auth_req_id` is one you issued: the token endpoint answers
    /// `invalid_grant` for any other.
    pub fn ciba_handle_ping<'a>(
        &self,
        headers: impl IntoIterator<Item = (&'a str, &'a [u8])>,
        body: &[u8],
        expected_token: &Sensitive<String>,
    ) -> Result<Sensitive<String>, AxiamError> {
        use subtle::ConstantTimeEq;
        let refused = || {
            AxiamError::auth(
                "ciba ping refused: the Authorization header is not the expected bearer \
                 (CONTRACT.md §33.1)",
            )
        };
        let mut authorization = headers
            .into_iter()
            .filter(|(name, _)| name.eq_ignore_ascii_case("authorization"))
            .map(|(_, value)| value);
        let (Some(value), None) = (authorization.next(), authorization.next()) else {
            return Err(refused());
        };
        let Some(space) = value.iter().position(|b| *b == b' ') else {
            return Err(refused());
        };
        let (scheme, token) = (&value[..space], &value[space + 1..]);
        if !scheme.eq_ignore_ascii_case(b"bearer") || token.is_empty() {
            return Err(refused());
        }
        let expected = expected_token.expose().as_bytes();
        if expected.is_empty() || !bool::from(token.ct_eq(expected)) {
            return Err(refused());
        }
        let parsed: Value = serde_json::from_slice(body)
            .map_err(|_| local_refusal("ciba_handle_ping", "body", "the ping body is not JSON"))?;
        match parsed.get("auth_req_id") {
            Some(Value::String(id)) if !id.is_empty() && parsed.is_object() => {
                Ok(Sensitive::new(id.clone()))
            }
            _ => Err(local_refusal(
                "ciba_handle_ping",
                "auth_req_id",
                "the ping body carries no non-empty auth_req_id string",
            )),
        }
    }
}

impl AxiamError {
    /// Whether this is the `access_denied` answer — at a CIBA or device poll,
    /// the user refused (§33.4).
    pub fn is_access_denied(&self) -> bool {
        self.oauth_error_code() == Some("access_denied")
    }

    /// Whether this is the `expired_token` answer — at a CIBA or device poll,
    /// nobody decided in time; raised locally too when `ciba_await` reaches
    /// its deadline (§33.4, §33.7 rule 4).
    pub fn is_expired_token(&self) -> bool {
        self.oauth_error_code() == Some("expired_token")
    }
}

/// The local `expired_token` outcome of §33.7 rule 4.
fn expired_token() -> AxiamError {
    AxiamError::oauth_protocol_error(
        "expired_token",
        "the CIBA request expired before it was decided (client-side deadline from \
         expires_in; CONTRACT.md §33.7 rule 4)",
    )
}

/// The plain form's authentication-request members, exactly those set.
fn plain_members(params: &CibaInitiateParams) -> Vec<(&'static str, Sensitive<String>)> {
    let mut out = vec![("scope", Sensitive::new(params.scope.clone()))];
    match &params.hint {
        CibaUserHint::LoginHint(h) => out.push(("login_hint", Sensitive::new(h.clone()))),
        CibaUserHint::IdTokenHint(h) => out.push(("id_token_hint", Sensitive::new(h.clone()))),
    }
    if let Some(m) = &params.binding_message {
        out.push(("binding_message", Sensitive::new(m.clone())));
    }
    if let Some(e) = params.requested_expiry {
        out.push(("requested_expiry", Sensitive::new(e.to_string())));
    }
    if let Some(a) = &params.acr_values {
        out.push(("acr_values", Sensitive::new(a.clone())));
    }
    if let Some(r) = &params.resource {
        out.push(("resource", Sensitive::new(r.clone())));
    }
    if let CibaDelivery::Ping {
        client_notification_token,
    } = &params.delivery
    {
        out.push((
            "client_notification_token",
            client_notification_token.clone(),
        ));
    }
    out
}

#[derive(Serialize)]
struct SignedClaims<'a> {
    iss: &'a str,
    aud: &'a str,
    iat: i64,
    nbf: i64,
    exp: i64,
    jti: String,
    #[serde(flatten)]
    members: serde_json::Map<String, Value>,
}

/// The DER inside a `-----BEGIN {label}-----` PEM. Both the base64 text (a copy
/// of the key) and the decoded DER are wiped on drop.
#[cfg(not(target_arch = "wasm32"))]
fn der_from_pem(pem: &[u8], label: &str) -> Option<zeroize::Zeroizing<Vec<u8>>> {
    use base64::Engine as _;
    use zeroize::Zeroizing;
    let text = std::str::from_utf8(pem).ok()?;
    let body = text
        .trim()
        .strip_prefix(&format!("-----BEGIN {label}-----"))?
        .strip_suffix(&format!("-----END {label}-----"))?;
    let compact: Zeroizing<String> = Zeroizing::new(body.split_whitespace().collect());
    base64::engine::general_purpose::STANDARD
        .decode(compact.as_bytes())
        .ok()
        .map(Zeroizing::new)
}

/// The PKCS#8 DER of a `PRIVATE KEY` PEM.
#[cfg(not(target_arch = "wasm32"))]
fn pkcs8_der_from_pem(pem: &[u8]) -> Option<zeroize::Zeroizing<Vec<u8>>> {
    der_from_pem(pem, "PRIVATE KEY")
}

/// The PKCS#1 `RSAPrivateKey` DER of an `RSA PRIVATE KEY` PEM.
#[cfg(not(target_arch = "wasm32"))]
fn pkcs1_der_from_pem(pem: &[u8]) -> Option<zeroize::Zeroizing<Vec<u8>>> {
    der_from_pem(pem, "RSA PRIVATE KEY")
}

/// PS256 (RSASSA-PSS, SHA-256, modulus-length bytes) over `message`, by
/// `ring`. Randomised salt.
#[cfg(not(target_arch = "wasm32"))]
fn ps256_sign(pair: &ring::signature::RsaKeyPair, message: &[u8]) -> Option<Vec<u8>> {
    let mut signature = vec![0; pair.public().modulus_len()];
    pair.sign(
        &ring::signature::RSA_PSS_SHA256,
        &ring::rand::SystemRandom::new(),
        message,
        &mut signature,
    )
    .ok()?;
    Some(signature)
}

/// ES256 (`r || s`, 64 bytes) over `message`, by `ring`. Randomised nonce.
#[cfg(not(target_arch = "wasm32"))]
fn es256_sign(pair: &ring::signature::EcdsaKeyPair, message: &[u8]) -> Option<Vec<u8>> {
    pair.sign(&ring::rand::SystemRandom::new(), message)
        .ok()
        .map(|s| s.as_ref().to_vec())
}

/// A compact JWS (RFC 7515) over `header` and `claims`, its signature computed
/// by `sign` over the signing input.
#[cfg(not(target_arch = "wasm32"))]
fn ring_jws<C: Serialize>(
    header: &Header,
    claims: &C,
    sign: impl FnOnce(&[u8]) -> Option<Vec<u8>>,
) -> Option<String> {
    use base64::Engine as _;
    let b64 = &base64::engine::general_purpose::URL_SAFE_NO_PAD;
    let input = format!(
        "{}.{}",
        b64.encode(serde_json::to_vec(header).ok()?),
        b64.encode(serde_json::to_vec(claims).ok()?)
    );
    let signature = sign(input.as_bytes())?;
    Some(format!("{input}.{}", b64.encode(signature)))
}

/// The CIBA Core §7.1.1 signed request: every member inside the JWT, plus
/// `iss`, `aud`, `iat`, `nbf`, `exp` and a fresh `jti`.
fn signed_request(
    params: &CibaInitiateParams,
    signer: &CibaRequestSigner,
    client_id: &str,
    issuer: &str,
) -> Result<Sensitive<String>, AxiamError> {
    let now = crate::time::SystemTime::now()
        .duration_since(crate::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    let mut members = serde_json::Map::new();
    for (k, v) in plain_members(params) {
        let value = if k == "requested_expiry" {
            // A number inside the JWT (CIBA Core §7.1), a string on the form.
            json!(params.requested_expiry)
        } else {
            Value::String(v.expose().clone())
        };
        members.insert(k.to_string(), value);
    }
    let claims = SignedClaims {
        iss: client_id,
        aud: issuer,
        iat: now,
        nbf: now,
        exp: now + SIGNED_REQUEST_LIFETIME_SECS,
        jti: Uuid::new_v4().simple().to_string(),
        members,
    };
    let mut header = Header::new(signer.alg.jose());
    header.kid = signer.kid.clone();
    let signed = match signer.key.expose() {
        RequestKey::Jwt(key) => jsonwebtoken::encode(&header, &claims, key).ok(),
        #[cfg(not(target_arch = "wasm32"))]
        RequestKey::Es256(pair) => ring_jws(&header, &claims, |m| es256_sign(pair, m)),
        #[cfg(not(target_arch = "wasm32"))]
        RequestKey::Ps256(pair) => ring_jws(&header, &claims, |m| ps256_sign(pair, m)),
    };
    signed.map(Sensitive::new).ok_or_else(|| {
        local_refusal(
            "ciba_initiate",
            "signing_key",
            "the signed request could not be signed with the given key",
        )
    })
}

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

    #[test]
    fn the_classification_follows_section_33_3_rule_6() {
        let cases = [
            ("authorization_pending", Step::Pending),
            ("slow_down", Step::SlowDown),
            ("rate_limit_exceeded", Step::Transient),
            ("access_denied", Step::Terminal),
            ("expired_token", Step::Terminal),
            ("invalid_grant", Step::Terminal),
            ("something_new", Step::Terminal),
        ];
        for (code, step) in cases {
            assert_eq!(
                decisive_step(&AxiamError::oauth_protocol_error(code, "d"), 400),
                step,
                "{code}"
            );
        }
        // P9: a 408 and a 429 are transient whatever they carry; a 4xx
        // without an `error` member is decisive.
        let unknown = AxiamError::oauth_protocol_error("something_new", "d");
        assert_eq!(decisive_step(&unknown, 429), Step::Transient);
        assert_eq!(decisive_step(&unknown, 408), Step::Transient);
        assert_eq!(
            decisive_step(&AxiamError::from_http_status(400, "x"), 400),
            Step::Terminal
        );
        assert_eq!(
            decisive_step(&AxiamError::from_http_status(404, "x"), 404),
            Step::Terminal
        );
    }

    #[test]
    fn the_two_terminal_outcomes_are_told_apart() {
        let denied = AxiamError::oauth_protocol_error("access_denied", "no");
        let expired = AxiamError::oauth_protocol_error("expired_token", "late");
        assert!(denied.is_access_denied() && !denied.is_expired_token());
        assert!(expired.is_expired_token() && !expired.is_access_denied());
    }

    /// A fresh P-256 PKCS#8 PEM, generated here: no key literal.
    #[cfg(not(target_arch = "wasm32"))]
    fn p256_pem() -> (String, Vec<u8>) {
        use base64::Engine as _;
        let der = ring::signature::EcdsaKeyPair::generate_pkcs8(
            &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
            &ring::rand::SystemRandom::new(),
        )
        .expect("generate");
        let body = base64::engine::general_purpose::STANDARD.encode(der.as_ref());
        let pem = format!("-----BEGIN PRIVATE KEY-----\n{body}\n-----END PRIVATE KEY-----\n");
        (pem, der.as_ref().to_vec())
    }

    // RUSTSEC-2026-0387: a caller's ES256 key is never used by `jsonwebtoken`'s
    // RustCrypto backend, whose `p256` runs its scalar arithmetic on
    // `crypto-bigint` 0.5.5. The signer is `ring`'s, and the test pins that
    // through the nonce: RFC 6979 (what that backend does) signs one message to
    // one signature, ring draws a fresh nonce, so two signatures differ.
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn the_es256_signer_is_rings_not_rust_cryptos() {
        let (pem, _) = p256_pem();
        let signer = CibaRequestSigner::from_pem(
            CibaSigningAlg::Es256,
            &Sensitive::new(pem.clone().into_bytes()),
            None,
        )
        .expect("a P-256 key");
        let RequestKey::Es256(pair) = signer.key.expose() else {
            panic!("an ES256 signer must hold the ring key pair");
        };
        let message = b"the same message, signed twice";
        let (a, b) = (
            es256_sign(pair, message).expect("sign"),
            es256_sign(pair, message).expect("sign"),
        );
        assert_ne!(a, b, "ring's randomised nonce: two signatures differ");
        assert_eq!(a.len(), 64, "r || s, as JWS ES256 wants");

        // The discriminator: the RustCrypto signer is deterministic here, so
        // this assertion would pass for it and the one above would not.
        let rc = EncodingKey::from_ec_pem(pem.as_bytes()).expect("parses");
        let (c, d) = (
            jsonwebtoken::crypto::sign(message, &rc, Algorithm::ES256).expect("sign"),
            jsonwebtoken::crypto::sign(message, &rc, Algorithm::ES256).expect("sign"),
        );
        assert_eq!(c, d, "RFC 6979: the RustCrypto signer is deterministic");
    }

    // The ring-signed request is a valid ES256 JWS: it verifies under the
    // key's public half with `jsonwebtoken`, which only verifies here.
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn a_ring_signed_request_verifies_as_es256() {
        use ring::signature::KeyPair as _;
        let (pem, der) = p256_pem();
        let public = ring::signature::EcdsaKeyPair::from_pkcs8(
            &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
            &der,
            &ring::rand::SystemRandom::new(),
        )
        .expect("parses")
        .public_key()
        .as_ref()
        .to_vec();
        let signer = CibaRequestSigner::from_pem(
            CibaSigningAlg::Es256,
            &Sensitive::new(pem.into_bytes()),
            Some("k1".into()),
        )
        .expect("a P-256 key");
        let RequestKey::Es256(pair) = signer.key.expose() else {
            panic!("ring key pair");
        };
        let mut header = Header::new(Algorithm::ES256);
        header.kid = Some("k1".into());
        let jws = ring_jws(&header, &json!({"iss": "c", "aud": "i"}), |m| {
            es256_sign(pair, m)
        })
        .expect("signs");

        // Uncompressed point 0x04 || x || y -> the JWK's x and y.
        use base64::Engine as _;
        let b64 = &base64::engine::general_purpose::URL_SAFE_NO_PAD;
        let (x, y) = (b64.encode(&public[1..33]), b64.encode(&public[33..65]));
        let key = jsonwebtoken::DecodingKey::from_ec_components(&x, &y).expect("jwk");
        let mut validation = jsonwebtoken::Validation::new(Algorithm::ES256);
        validation.set_audience(&["i"]);
        validation.set_required_spec_claims::<&str>(&[]);
        let claims = jsonwebtoken::decode::<Value>(&jws, &key, &validation).expect("verifies");
        assert_eq!(claims.claims["iss"], "c");
        assert_eq!(claims.header.kid.as_deref(), Some("k1"));
    }

    /// Runs the `openssl` CLI with `args`, `stdin` piped in; its stdout.
    #[cfg(not(target_arch = "wasm32"))]
    fn openssl(args: &[&str], stdin: &[u8]) -> Vec<u8> {
        use std::io::Write as _;
        use std::process::{Command, Stdio};
        let mut child = Command::new("openssl")
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("the openssl CLI generates the test RSA keys");
        child
            .stdin
            .take()
            .expect("stdin")
            .write_all(stdin)
            .expect("write");
        let out = child.wait_with_output().expect("openssl");
        assert!(
            out.status.success(),
            "openssl {args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        out.stdout
    }

    /// A fresh RSA key of `bits`, generated here by the `openssl` CLI (ring
    /// cannot generate RSA keys, and rcgen can only through aws-lc-rs): no key
    /// literal. Its PKCS#8 `PRIVATE KEY` PEM, its PKCS#1 `RSA PRIVATE KEY` PEM,
    /// and its SPKI `PUBLIC KEY` PEM.
    #[cfg(not(target_arch = "wasm32"))]
    fn rsa_pems(bits: u32) -> (String, String, String) {
        let pkcs8 = openssl(
            &[
                "genpkey",
                "-algorithm",
                "RSA",
                "-pkeyopt",
                &format!("rsa_keygen_bits:{bits}"),
            ],
            b"",
        );
        let pkcs1 = openssl(&["pkey", "-traditional"], &pkcs8);
        let public = openssl(&["pkey", "-pubout"], &pkcs8);
        let text = |b: Vec<u8>| String::from_utf8(b).expect("PEM is text");
        (text(pkcs8), text(pkcs1), text(public))
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn ps256_signer(pem: &str) -> Result<CibaRequestSigner, AxiamError> {
        CibaRequestSigner::from_pem(
            CibaSigningAlg::Ps256,
            &Sensitive::new(pem.as_bytes().to_vec()),
            Some("k1".into()),
        )
    }

    // A ring-signed PS256 request is a valid PS256 JWS, from either PEM form
    // `EncodingKey::from_rsa_pem` took: it verifies under the key's public
    // half with `jsonwebtoken`, which only verifies here (a public-key
    // operation).
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn a_ring_signed_request_verifies_as_ps256_from_pkcs8_and_pkcs1() {
        let (pkcs8, pkcs1, public) = rsa_pems(2048);
        assert!(pkcs8.starts_with("-----BEGIN PRIVATE KEY-----"));
        assert!(pkcs1.starts_with("-----BEGIN RSA PRIVATE KEY-----"));
        let key = jsonwebtoken::DecodingKey::from_rsa_pem(public.as_bytes()).expect("public");
        let mut validation = jsonwebtoken::Validation::new(Algorithm::PS256);
        validation.set_audience(&["https://issuer.example"]);
        validation.set_required_spec_claims(&["exp", "nbf", "aud", "iss"]);
        let params = CibaInitiateParams::new("openid", CibaUserHint::LoginHint("alice".into()));
        for pem in [&pkcs8, &pkcs1] {
            let signer = ps256_signer(pem).expect("an RSA key");
            let jws = signed_request(&params, &signer, "client-1", "https://issuer.example")
                .expect("signs");
            let token = jsonwebtoken::decode::<Value>(jws.expose(), &key, &validation)
                .expect("verifies as PS256");
            assert_eq!(token.header.alg, Algorithm::PS256);
            assert_eq!(token.header.kid.as_deref(), Some("k1"));
            assert_eq!(token.claims["iss"], "client-1");
            assert_eq!(token.claims["login_hint"], "alice");
        }
    }

    /// RUSTSEC-2023-0071: a caller's RSA key never reaches `jsonwebtoken`'s
    /// RustCrypto backend, whose `rsa` crate's private-key operations are not
    /// constant time. The signer is `ring`'s.
    ///
    /// The discriminator is the key the signer holds, read through the
    /// `#[cfg(test)]` accessor `ring_rsa`, not the signature: PSS draws a fresh
    /// salt in both backends, so no output property (unlike ES256's RFC 6979
    /// nonce) tells them apart. The accessor returns the `ring` key pair only
    /// for `RequestKey::Ps256`, and `signed_request` signs with exactly that
    /// variant's pair, so `Some` here means the request is signed by `ring`.
    /// The held pair is shown to be the caller's key (its signature verifies
    /// under the caller's public key), and an EdDSA signer reads `None`, so the
    /// accessor discriminates rather than always answering `Some`.
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn the_ps256_signer_is_rings_not_rust_cryptos() {
        let (pkcs8, pkcs1, public) = rsa_pems(2048);
        let key = jsonwebtoken::DecodingKey::from_rsa_pem(public.as_bytes()).expect("public");
        for pem in [&pkcs8, &pkcs1] {
            let signer = ps256_signer(pem).expect("an RSA key");
            let pair = signer
                .ring_rsa()
                .expect("a PS256 signer must hold the ring key pair");
            assert_eq!(
                pair.public().modulus_len(),
                256,
                "the caller's 2048-bit key"
            );
            let message = b"signed by the held ring pair";
            let signature = ps256_sign(pair, message).expect("sign");
            use base64::Engine as _;
            let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(signature);
            assert!(
                jsonwebtoken::crypto::verify(&b64, message, &key, Algorithm::PS256)
                    .expect("verify"),
                "the held ring pair is the caller's key"
            );
        }

        let ed = ring::signature::Ed25519KeyPair::generate_pkcs8(&ring::rand::SystemRandom::new())
            .expect("generate");
        use base64::Engine as _;
        let ed_pem = format!(
            "-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----\n",
            base64::engine::general_purpose::STANDARD.encode(ed.as_ref())
        );
        let eddsa = CibaRequestSigner::from_pem(
            CibaSigningAlg::EdDsa,
            &Sensitive::new(ed_pem.into_bytes()),
            None,
        )
        .expect("an Ed25519 key");
        assert!(eddsa.ring_rsa().is_none(), "EdDSA keeps jsonwebtoken");
    }

    // ring signs RSA from 2048 bits; a 1024-bit key, which `jsonwebtoken`
    // took, is refused locally, saying why.
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn a_ps256_key_under_2048_bits_is_refused_saying_why() {
        let (pkcs8, pkcs1, _) = rsa_pems(1024);
        for pem in [&pkcs8, &pkcs1] {
            let err = ps256_signer(pem).expect_err("too small for ring");
            let text = err.to_string();
            assert!(
                text.contains("a PS256 key must be 2048 to 8192 bits"),
                "{text}"
            );
        }
    }
}