wami 0.17.1

Who Am I - Multicloud Identity, IAM, STS, and SSO operations library for Rust
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
//! OpenID Connect — the flows where a human is present.
//!
//! Authorization code with PKCE, refresh rotation, ID tokens, consent and
//! discovery, layered onto the same [`OAuthService`] that issues
//! `client_credentials` tokens. One keyset signs everything, so a relying party
//! that already verifies wami's access tokens verifies its ID tokens too.
//!
//! # The shape of the flow
//!
//! The host authenticates the user — wami does not; that is
//! [`crate::service::auth`]'s job or an upstream IdP's — and then:
//!
//! 1. [`OAuthService::authorize`] with the user it just authenticated. It
//!    returns either a code, or [`Authorization::ConsentRequired`] naming the
//!    scopes the user has not yet approved.
//! 2. On approval, [`OAuthService::grant_consent`], then `authorize` again.
//! 3. The host redirects to the client with the code.
//! 4. The client posts it back with its verifier, and
//!    [`OAuthService::exchange_code`] returns the tokens.
//!
//! # What is deliberately absent
//!
//! No `plain` PKCE, no implicit flow, and PKCE is not optional — the challenge
//! is a required field of [`AuthorizationRequest`] rather than an `Option`, so
//! a caller cannot forget it. Each of those has been the root of enough real
//! incidents that offering them, even behind a flag, would be offering a way to
//! get this wrong.

use async_trait::async_trait;
use chrono::Utc;
use std::sync::Arc;
use wami_core::error::{AmiError, Result};

use super::{OAuthService, OAuthStore};
use crate::store::traits::oauth::{OAuthAuthorizationStore, OAuthConsentStore, OAuthRefreshStore};
use crate::wami::oauth::{
    builder, oidc, AuthenticationEvent, AuthorizationCode, CodeChallenge, DiscoveryDocument,
    GrantType, OAuthClaims, OAuthClient, RefreshToken, UserConsent, UserInfo, UserProfile,
    AUTHORIZATION_CODE_LIFETIME, REFRESH_TOKEN_LIFETIME,
};
use crate::wami::sts::jwt::{TokenType, TypePolicy};

/// Combined bound for a store that can serve the user-facing flows.
pub trait OidcStore:
    OAuthStore + OAuthAuthorizationStore + OAuthRefreshStore + OAuthConsentStore
{
}
impl<T: OAuthStore + OAuthAuthorizationStore + OAuthRefreshStore + OAuthConsentStore> OidcStore
    for T
{
}

/// Where the profile claims in an ID token come from.
///
/// wami does not own your user directory, and pretending otherwise would mean
/// either duplicating it or restricting who can use this. The host answers
/// instead, for whatever a user is in its world.
///
/// A service without one still issues ID tokens; they carry `sub` and nothing
/// else, which is all `openid` on its own entitles a client to.
///
/// # Cache it
///
/// This is called on every mint — once per sign-in, and again on every refresh
/// for as long as the chain lives. An implementation that reaches across the
/// network each time puts that latency on the token endpoint's critical path.
/// Profile claims change rarely; cache them.
#[async_trait]
pub trait UserClaimsSource: Send + Sync {
    /// The profile of `user_name`, or `None` if there is nothing to release.
    async fn claims_for(&self, user_name: &str) -> Result<Option<UserProfile>>;
}

/// What the host asks for once it has authenticated a user.
#[derive(Debug, Clone)]
pub struct AuthorizationRequest {
    /// The client the user is signing in to.
    pub client_id: String,
    /// The user the host has just authenticated.
    pub user_name: String,
    /// Where the code will be delivered. Matched exactly against the client's
    /// registered set.
    pub redirect_uri: String,
    /// Scopes the client asked for.
    pub scopes: Vec<String>,
    /// The client's PKCE commitment. Not optional, by construction.
    pub challenge: CodeChallenge,
    /// The client's nonce, echoed into the ID token.
    pub nonce: Option<String>,
    /// What the host did to authenticate the user, if it wants to say.
    ///
    /// Produces `auth_time`, `acr` and `amr` in the ID token, and survives into
    /// the refresh chain so a later token reports the *original* sign-in.
    /// Omitting it omits those claims; nothing else changes.
    pub event: Option<AuthenticationEvent>,
    /// The client's opaque state, handed back untouched.
    ///
    /// wami does nothing with it, and cannot: `state` defends against CSRF by
    /// being compared at the *callback*, and wami never sees the callback — it
    /// has no browser session to bind to. The host must generate it, tie it to
    /// the user agent's session, and reject a callback whose `state` does not
    /// match. Passing it through here only saves the host from carrying it
    /// itself; it is not a check.
    pub state: Option<String>,
}

/// The outcome of an authorization request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Authorization {
    /// A code to deliver to `redirect_uri`.
    Code {
        /// The code.
        code: String,
        /// Where to deliver it — the one that was validated, not the one to
        /// re-read from the request.
        redirect_uri: String,
        /// The client's state, unchanged.
        state: Option<String>,
    },
    /// The user has not approved these scopes yet.
    ///
    /// The host shows them, and calls [`OAuthService::grant_consent`] if the
    /// user agrees. Returning this rather than granting silently is the whole
    /// point of consent.
    ConsentRequired {
        /// Which client is asking.
        client_id: String,
        /// The scopes still needing approval — the full set to display, not
        /// only the new ones, so the user sees what they are agreeing to.
        scopes: Vec<String>,
    },
}

/// A client redeeming an authorization code.
#[derive(Debug, Clone)]
pub struct CodeExchange {
    /// The client's identifier.
    pub client_id: String,
    /// The client's secret.
    pub client_secret: String,
    /// The code it received.
    pub code: String,
    /// The redirect URI the code was issued against.
    pub redirect_uri: String,
    /// The PKCE verifier behind the challenge it committed to.
    pub code_verifier: String,
}

/// The tokens returned by the user-facing grants.
///
/// Separate from [`TokenResponse`] because those grants return a refresh token
/// and, when `openid` was granted, an ID token — and because a client parsing
/// this must not silently accept a response missing them.
///
/// [`TokenResponse`]: crate::wami::oauth::TokenResponse
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct OidcTokens {
    /// The signed access token.
    pub access_token: String,
    /// Always `Bearer`.
    pub token_type: String,
    /// Access token lifetime in seconds.
    pub expires_in: i64,
    /// Granted scopes, space-delimited.
    pub scope: String,
    /// The refresh token. Single-use: the next refresh replaces it.
    pub refresh_token: String,
    /// The ID token, present when `openid` was granted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id_token: Option<String>,
}

impl<S: OidcStore> OAuthService<S> {
    /// Attach a source of profile claims for ID tokens and `/userinfo`.
    pub fn with_user_claims(mut self, claims: Arc<dyn UserClaimsSource>) -> Self {
        self.user_claims = Some(claims);
        self
    }

    /// Issue an authorization code for an authenticated user, or ask for
    /// consent.
    ///
    /// # Errors
    ///
    /// [`AmiError::AccessDenied`] if the client is unknown, disabled, or not
    /// registered for the `authorization_code` grant.
    /// [`AmiError::InvalidParameter`] if the redirect URI is not registered or
    /// a requested scope is outside the client's set.
    ///
    /// Both are returned *to the caller of this library* and must never be
    /// redirected to the client: sending an error to an unverified redirect URI
    /// is the vulnerability the check exists to prevent.
    pub async fn authorize(&self, request: AuthorizationRequest) -> Result<Authorization> {
        let client = self.enabled_client(&request.client_id).await?;

        if !client.allows_grant(GrantType::AuthorizationCode) {
            return Err(AmiError::AccessDenied {
                message: format!(
                    "client {} may not use the authorization_code grant",
                    request.client_id
                ),
            });
        }

        // Before anything else. Every later step assumes the code has somewhere
        // safe to go.
        oidc::validate_redirect_uri(&client, &request.redirect_uri)?;

        let granted = client.narrow_scopes(&request.scopes).map_err(|refused| {
            AmiError::InvalidParameter {
                message: format!(
                    "client {} is not entitled to scope {refused}",
                    request.client_id
                ),
            }
        })?;

        let approved = self
            .store
            .read()
            .await
            .get_consent(&request.client_id, &request.user_name)
            .await?
            .is_some_and(|c| c.covers(&granted));

        if !approved {
            return Ok(Authorization::ConsentRequired {
                client_id: request.client_id,
                scopes: granted,
            });
        }

        let code = AuthorizationCode {
            code: oidc::generate_opaque_value(),
            client_id: request.client_id,
            user_name: request.user_name,
            scopes: granted,
            redirect_uri: request.redirect_uri.clone(),
            challenge: Some(request.challenge),
            nonce: request.nonce,
            event: request.event,
            expires_at: Utc::now() + AUTHORIZATION_CODE_LIFETIME,
        };
        let issued = code.code.clone();
        self.store
            .write()
            .await
            .store_authorization_code(code)
            .await?;

        Ok(Authorization::Code {
            code: issued,
            redirect_uri: request.redirect_uri,
            state: request.state,
        })
    }

    /// Record a user's approval of a client's scopes.
    ///
    /// Widening an existing consent replaces it; the record is what the user
    /// last agreed to, not a log of every time they agreed.
    pub async fn grant_consent(
        &self,
        client_id: &str,
        user_name: &str,
        scopes: Vec<String>,
    ) -> Result<UserConsent> {
        let client = self.enabled_client(client_id).await?;
        let scopes =
            client
                .narrow_scopes(&scopes)
                .map_err(|refused| AmiError::InvalidParameter {
                    message: format!("client {client_id} is not entitled to scope {refused}"),
                })?;

        self.store
            .write()
            .await
            .record_consent(UserConsent {
                user_name: user_name.to_string(),
                client_id: client_id.to_string(),
                scopes,
                granted_at: Utc::now(),
            })
            .await
    }

    /// Withdraw a user's approval, and with it every refresh token it backed.
    ///
    /// Revoking the consent alone would leave the client holding a refresh
    /// token that keeps minting access tokens for a month — the user would have
    /// said no and nothing would have stopped.
    pub async fn withdraw_consent(&self, client_id: &str, user_name: &str) -> Result<bool> {
        let mut store = self.store.write().await;
        let withdrawn = store.revoke_consent(client_id, user_name).await?;
        store.revoke_refresh_chain(client_id, user_name).await?;
        Ok(withdrawn)
    }

    /// Redeem an authorization code.
    ///
    /// # Errors
    ///
    /// [`AmiError::AccessDenied`] for bad client credentials, and for an
    /// unknown, expired, replayed or mismatched code — all reported
    /// identically, because telling them apart tells an attacker which of their
    /// guesses was closest.
    ///
    /// # Not a transaction, on purpose
    ///
    /// The code is consumed in one store operation and the tokens are written
    /// in another. A process that dies between the two leaves the code spent
    /// and no tokens issued: the exchange fails and the user signs in again.
    /// That is the direction to fail in. The alternative ordering — mint first,
    /// consume after — turns the same crash into a code that stays redeemable
    /// after tokens were handed out, which is the replay this whole path exists
    /// to prevent. A store that can span both in a transaction is welcome to;
    /// nothing here depends on it.
    pub async fn exchange_code(&self, exchange: CodeExchange) -> Result<OidcTokens> {
        let client = self
            .validate_client(&exchange.client_id, &exchange.client_secret)
            .await?;

        // Consumed before it is checked, and unconditionally. A code that fails
        // any check below is spent regardless — leaving it redeemable would let
        // an attacker who holds a stolen code keep trying verifiers.
        let code = self
            .store
            .write()
            .await
            .consume_authorization_code(&exchange.code)
            .await?
            .ok_or_else(refused_code)?;

        if code.client_id != exchange.client_id
            || code.redirect_uri != exchange.redirect_uri
            || code.expires_at <= Utc::now()
        {
            return Err(refused_code());
        }

        // PKCE. A code with no challenge cannot be redeemed at all: the only
        // way to store one is through `authorize`, which requires a challenge,
        // so its absence means the record was written by something else.
        match &code.challenge {
            Some(challenge) if challenge.verify(&exchange.code_verifier) => {}
            _ => return Err(refused_code()),
        }

        self.mint(
            &client,
            &code.user_name,
            &code.scopes,
            code.nonce,
            code.event,
        )
        .await
    }

    /// Exchange a refresh token for a fresh set.
    ///
    /// The presented token is spent and a new one issued in its place. A token
    /// presented twice is treated as leaked: the whole chain for that user and
    /// client is revoked, so both the attacker and the legitimate client are
    /// forced back through sign-in. That is the point — a silent second use is
    /// indistinguishable from theft, and letting it pass makes rotation
    /// decorative.
    ///
    /// # Errors
    ///
    /// [`AmiError::AccessDenied`] for bad credentials, an unknown or expired
    /// token, or a reuse.
    pub async fn refresh_tokens(
        &self,
        client_id: &str,
        client_secret: &str,
        refresh_token: &str,
    ) -> Result<OidcTokens> {
        let client = self.validate_client(client_id, client_secret).await?;

        let existing = self
            .store
            .read()
            .await
            .get_refresh_token(refresh_token)
            .await?
            .ok_or_else(refused_refresh)?;

        if existing.client_id != client_id {
            return Err(refused_refresh());
        }

        let replacement = RefreshToken {
            token: oidc::generate_opaque_value(),
            client_id: client_id.to_string(),
            user_name: existing.user_name.clone(),
            scopes: existing.scopes.clone(),
            expires_at: Utc::now() + REFRESH_TOKEN_LIFETIME,
            used_at: None,
            replaced_by: None,
            event: existing.event.clone(),
        };
        let minted = replacement.token.clone();

        let spent = self
            .store
            .write()
            .await
            .rotate_refresh_token(refresh_token, replacement)
            .await?
            .ok_or_else(refused_refresh)?;

        // The store hands back the token it took. If it does not name our
        // replacement, we did not win the rotation, and nothing was minted.
        if spent.replaced_by.as_deref() != Some(minted.as_str()) {
            if spent.used_at.is_none() {
                // Merely expired. The user signs in again; nothing is wrong.
                return Err(refused_refresh());
            }
            self.store
                .write()
                .await
                .revoke_refresh_chain(client_id, &spent.user_name)
                .await?;
            return Err(AmiError::AccessDenied {
                message: "refresh token reuse detected; the chain has been revoked".to_string(),
            });
        }

        // No nonce on refresh. OIDC Core §12.2: a refreshed ID token "SHOULD
        // NOT have a nonce Claim, even when the ID Token issued at the time of
        // the original authentication contained nonce". The nonce belonged to
        // one sign-in; replaying it into a later token would defeat what the
        // relying party checks it for.
        self.mint(&client, &spent.user_name, &spent.scopes, None, spent.event)
            .await
    }

    /// Answer `/userinfo` for a bearer access token.
    ///
    /// # Errors
    ///
    /// [`AmiError::AccessDenied`] if the token is invalid, revoked, expired, or
    /// was not granted `openid` — a `client_credentials` token has no user
    /// behind it, and answering with the client as `sub` would be a lie.
    pub async fn user_info(&self, access_token: &str, audience: &str) -> Result<UserInfo> {
        let refused = || AmiError::AccessDenied {
            message: "invalid access token".to_string(),
        };

        let claims = self
            .keys
            .verify_claims_as::<OAuthClaims>(
                access_token,
                audience,
                TokenType::AccessToken,
                TypePolicy::Lenient,
            )
            .map_err(|_| refused())?;

        let scopes: Vec<String> = claims
            .scope
            .split_whitespace()
            .map(str::to_string)
            .collect();
        if !scopes.iter().any(|s| s == "openid") {
            return Err(refused());
        }

        let record = self
            .store
            .read()
            .await
            .get_oauth_token(&claims.jti)
            .await?
            .ok_or_else(refused)?;
        if !record.is_active_at(Utc::now()) {
            return Err(refused());
        }

        let profile = self.profile_of(&claims.sub).await?;
        Ok(oidc::build_user_info(&claims.sub, &scopes, &profile))
    }

    /// The provider metadata for this service, served from `base_url`.
    pub fn discovery(&self, base_url: &str) -> DiscoveryDocument {
        oidc::build_discovery_document(&self.issuer, base_url)
    }

    /// A registered, enabled client, or [`AmiError::AccessDenied`].
    async fn enabled_client(&self, client_id: &str) -> Result<OAuthClient> {
        let refused = || AmiError::AccessDenied {
            message: "unknown or disabled client".to_string(),
        };
        let client = self
            .store
            .read()
            .await
            .get_oauth_client(client_id)
            .await?
            .ok_or_else(refused)?;
        if !client.enabled {
            return Err(refused());
        }
        Ok(client)
    }

    /// What the host will release about a user, or nothing if it was not asked.
    async fn profile_of(&self, user_name: &str) -> Result<UserProfile> {
        match &self.user_claims {
            Some(source) => Ok(source.claims_for(user_name).await?.unwrap_or_default()),
            None => Ok(UserProfile::default()),
        }
    }

    /// Mint the access, refresh and (when `openid` is granted) ID tokens.
    ///
    /// One place, so the code and refresh paths cannot drift into issuing
    /// differently-shaped tokens.
    async fn mint(
        &self,
        client: &OAuthClient,
        user_name: &str,
        scopes: &[String],
        nonce: Option<String>,
        event: Option<AuthenticationEvent>,
    ) -> Result<OidcTokens> {
        let now = Utc::now();
        let signing_failed = |e: crate::wami::sts::jwt::JwtError| {
            AmiError::StoreError(format!("failed to sign: {e}"))
        };

        let claims =
            builder::build_user_claims(client, user_name, scopes, &self.issuer, now, self.lifetime);
        let access_token = self
            .keys
            .sign_claims_as(&claims, self.access_token_type())
            .map_err(signing_failed)?;

        let id_token = if scopes.iter().any(|s| s == "openid") {
            let profile = self.profile_of(user_name).await?;
            let id_claims = oidc::build_id_token_claims(
                oidc::IdTokenRequest {
                    user_name,
                    client_id: &client.client_id,
                    issuer: &self.issuer,
                    scopes,
                    profile: &profile,
                    nonce,
                    event: event.as_ref(),
                },
                now,
                self.lifetime,
            );
            Some(self.keys.sign_claims(&id_claims).map_err(signing_failed)?)
        } else {
            None
        };

        let refresh = RefreshToken {
            token: oidc::generate_opaque_value(),
            client_id: client.client_id.clone(),
            user_name: user_name.to_string(),
            scopes: scopes.to_vec(),
            expires_at: now + REFRESH_TOKEN_LIFETIME,
            used_at: None,
            replaced_by: None,
            event,
        };
        let refresh_token = refresh.token.clone();

        // Both recorded before either is handed out. A token the caller holds
        // but the store never saw could not be revoked.
        let mut store = self.store.write().await;
        store
            .record_oauth_token(builder::build_token_record(&claims, now))
            .await?;
        store.store_refresh_token(refresh).await?;

        Ok(OidcTokens {
            access_token,
            token_type: "Bearer".to_string(),
            expires_in: self.lifetime.num_seconds(),
            scope: scopes.join(" "),
            refresh_token,
            id_token,
        })
    }
}

/// One answer for every way a code exchange can fail.
fn refused_code() -> AmiError {
    AmiError::AccessDenied {
        message: "invalid authorization code".to_string(),
    }
}

/// One answer for every way a refresh can fail, reuse aside.
fn refused_refresh() -> AmiError {
    AmiError::AccessDenied {
        message: "invalid refresh token".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::memory::InMemoryOAuthStore;
    use crate::wami::oauth::{build_client, derive_s256_challenge, GrantRequest, IdTokenClaims};
    use crate::wami::sts::jwt::KeyManager;
    use tokio::sync::RwLock;

    const AUD: &str = "the-api";
    const REDIRECT: &str = "https://app.test/cb";
    const VERIFIER: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";

    struct Directory;

    #[async_trait]
    impl UserClaimsSource for Directory {
        async fn claims_for(&self, user_name: &str) -> Result<Option<UserProfile>> {
            Ok((user_name == "alice").then(|| UserProfile {
                name: Some("Alice Example".into()),
                email: Some("alice@example.test".into()),
            }))
        }
    }

    async fn service_with(
        grants: Vec<GrantType>,
        redirects: Vec<String>,
    ) -> OAuthService<InMemoryOAuthStore> {
        let service = OAuthService::new(
            Arc::new(RwLock::new(InMemoryOAuthStore::new())),
            Arc::new(KeyManager::generate()),
            "https://id.test".to_string(),
        )
        .with_user_claims(Arc::new(Directory));

        let client = build_client(
            "app".into(),
            "s3cret",
            "The App".into(),
            grants,
            vec![
                "openid".into(),
                "profile".into(),
                "email".into(),
                "reports:read".into(),
            ],
            AUD.to_string(),
            redirects,
        )
        .unwrap();
        service.register_client(client).await.unwrap();
        service
    }

    async fn service() -> OAuthService<InMemoryOAuthStore> {
        service_with(
            vec![GrantType::AuthorizationCode, GrantType::RefreshToken],
            vec![REDIRECT.to_string()],
        )
        .await
    }

    fn request(scopes: &[&str]) -> AuthorizationRequest {
        AuthorizationRequest {
            client_id: "app".into(),
            user_name: "alice".into(),
            redirect_uri: REDIRECT.into(),
            scopes: scopes.iter().map(|s| s.to_string()).collect(),
            challenge: CodeChallenge::s256(derive_s256_challenge(VERIFIER)),
            nonce: Some("n-0S6".into()),
            event: None,
            state: Some("xyz".into()),
        }
    }

    fn exchange(code: &str, verifier: &str) -> CodeExchange {
        CodeExchange {
            client_id: "app".into(),
            client_secret: "s3cret".into(),
            code: code.into(),
            redirect_uri: REDIRECT.into(),
            code_verifier: verifier.into(),
        }
    }

    /// Consent, then a code. The two steps every other test starts from.
    async fn a_code(service: &OAuthService<InMemoryOAuthStore>, scopes: &[&str]) -> String {
        service
            .grant_consent(
                "app",
                "alice",
                scopes.iter().map(|s| s.to_string()).collect(),
            )
            .await
            .unwrap();
        match service.authorize(request(scopes)).await.unwrap() {
            Authorization::Code { code, .. } => code,
            other => panic!("expected a code, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn a_user_who_has_not_consented_is_asked_before_any_code_exists() {
        let service = service().await;

        let outcome = service
            .authorize(request(&["openid", "email"]))
            .await
            .unwrap();
        assert_eq!(
            outcome,
            Authorization::ConsentRequired {
                client_id: "app".into(),
                scopes: vec!["openid".into(), "email".into()],
            }
        );

        // And nothing was stored — an unapproved request must not leave a code
        // lying around that something else could redeem.
        assert!(service
            .store
            .write()
            .await
            .consume_authorization_code("anything")
            .await
            .unwrap()
            .is_none());
    }

    #[tokio::test]
    async fn consent_that_does_not_cover_the_request_is_asked_for_again() {
        let service = service().await;
        service
            .grant_consent("app", "alice", vec!["openid".into()])
            .await
            .unwrap();

        let outcome = service
            .authorize(request(&["openid", "email"]))
            .await
            .unwrap();
        assert!(matches!(outcome, Authorization::ConsentRequired { .. }));

        // Widening it lets the same request through.
        service
            .grant_consent("app", "alice", vec!["openid".into(), "email".into()])
            .await
            .unwrap();
        let outcome = service
            .authorize(request(&["openid", "email"]))
            .await
            .unwrap();
        assert!(matches!(outcome, Authorization::Code { .. }));
    }

    #[tokio::test]
    async fn the_whole_flow_yields_an_id_token_addressed_to_the_client() {
        let service = service().await;
        let code = a_code(&service, &["openid", "profile", "email"]).await;

        let tokens = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();
        assert_eq!(tokens.token_type, "Bearer");
        assert_eq!(tokens.scope, "openid profile email");
        assert!(!tokens.refresh_token.is_empty());

        // The access token names the user, and is verified against the API's
        // audience.
        let access: OAuthClaims = service
            .keys
            .verify_claims(&tokens.access_token, AUD)
            .unwrap();
        assert_eq!(access.sub, "alice", "the user, not the client");
        assert_eq!(access.client_id, "app");

        // The ID token is verified against the *client's* audience, not the
        // API's — a resource server cannot accept it by accident.
        let id: IdTokenClaims = service
            .keys
            .verify_claims(tokens.id_token.as_ref().unwrap(), "app")
            .unwrap();
        assert_eq!(id.sub, "alice");
        assert_eq!(id.iss, "https://id.test");
        assert_eq!(id.nonce.as_deref(), Some("n-0S6"));
        assert_eq!(id.name.as_deref(), Some("Alice Example"));
        assert_eq!(id.email.as_deref(), Some("alice@example.test"));

        assert!(
            service
                .keys
                .verify_claims::<IdTokenClaims>(tokens.id_token.as_ref().unwrap(), AUD)
                .is_err(),
            "an ID token must not verify as an access token"
        );
    }

    #[tokio::test]
    async fn without_openid_there_is_no_id_token() {
        let service = service().await;
        let code = a_code(&service, &["reports:read"]).await;

        let tokens = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();
        assert_eq!(tokens.id_token, None);
        assert_eq!(tokens.scope, "reports:read");
    }

    #[tokio::test]
    async fn a_code_cannot_be_redeemed_twice() {
        let service = service().await;
        let code = a_code(&service, &["openid"]).await;

        assert!(service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .is_ok());
        let replay = service.exchange_code(exchange(&code, VERIFIER)).await;
        assert!(matches!(replay, Err(AmiError::AccessDenied { .. })));
    }

    #[tokio::test]
    async fn a_wrong_verifier_is_refused_and_burns_the_code() {
        // PKCE only helps if a failed attempt costs the attacker the code. If
        // the code survived, an intercepted one could be brute-forced.
        let service = service().await;
        let code = a_code(&service, &["openid"]).await;

        assert!(service
            .exchange_code(exchange(&code, "not-the-verifier"))
            .await
            .is_err());
        assert!(
            service
                .exchange_code(exchange(&code, VERIFIER))
                .await
                .is_err(),
            "the real client should no longer be able to redeem it either"
        );
    }

    #[tokio::test]
    async fn a_code_is_bound_to_the_redirect_uri_it_was_issued_against() {
        let service = service().await;
        let code = a_code(&service, &["openid"]).await;

        let mut elsewhere = exchange(&code, VERIFIER);
        elsewhere.redirect_uri = "https://app.test/other".into();
        assert!(matches!(
            service.exchange_code(elsewhere).await,
            Err(AmiError::AccessDenied { .. })
        ));
    }

    #[tokio::test]
    async fn an_unregistered_redirect_uri_never_produces_a_code() {
        let service = service().await;
        service
            .grant_consent("app", "alice", vec!["openid".into()])
            .await
            .unwrap();

        for hostile in [
            "https://app.test/cb.attacker.test",
            "https://app.test.attacker.test/cb",
            "http://app.test/cb",
        ] {
            let mut req = request(&["openid"]);
            req.redirect_uri = hostile.into();
            assert!(
                matches!(
                    service.authorize(req).await,
                    Err(AmiError::InvalidParameter { .. })
                ),
                "{hostile} was accepted"
            );
        }
    }

    #[tokio::test]
    async fn a_client_not_registered_for_the_grant_cannot_start_the_flow() {
        let service = service_with(
            vec![GrantType::ClientCredentials],
            vec![REDIRECT.to_string()],
        )
        .await;
        service
            .grant_consent("app", "alice", vec!["openid".into()])
            .await
            .unwrap();

        assert!(matches!(
            service.authorize(request(&["openid"])).await,
            Err(AmiError::AccessDenied { .. })
        ));
    }

    #[tokio::test]
    async fn a_scope_outside_the_client_set_is_refused_at_authorization() {
        let service = service().await;
        let mut req = request(&["openid"]);
        req.scopes = vec!["billing:write".into()];

        assert!(matches!(
            service.authorize(req).await,
            Err(AmiError::InvalidParameter { .. })
        ));
    }

    #[tokio::test]
    async fn an_expired_code_is_refused() {
        let service = service().await;
        let code = AuthorizationCode {
            code: "stale".into(),
            client_id: "app".into(),
            user_name: "alice".into(),
            scopes: vec!["openid".into()],
            redirect_uri: REDIRECT.into(),
            challenge: Some(CodeChallenge::s256(derive_s256_challenge(VERIFIER))),
            nonce: None,
            event: None,
            expires_at: Utc::now() - chrono::Duration::seconds(1),
        };
        service
            .store
            .write()
            .await
            .store_authorization_code(code)
            .await
            .unwrap();

        assert!(matches!(
            service.exchange_code(exchange("stale", VERIFIER)).await,
            Err(AmiError::AccessDenied { .. })
        ));
    }

    #[tokio::test]
    async fn a_code_belonging_to_another_client_cannot_be_redeemed() {
        let service = service().await;
        let other = build_client(
            "other".into(),
            "other-secret",
            "Other".into(),
            vec![GrantType::AuthorizationCode],
            vec!["openid".into()],
            AUD.to_string(),
            vec![REDIRECT.to_string()],
        )
        .unwrap();
        service.register_client(other).await.unwrap();

        let code = a_code(&service, &["openid"]).await;
        let mut stolen = exchange(&code, VERIFIER);
        stolen.client_id = "other".into();
        stolen.client_secret = "other-secret".into();

        assert!(matches!(
            service.exchange_code(stolen).await,
            Err(AmiError::AccessDenied { .. })
        ));
    }

    #[tokio::test]
    async fn wrong_client_credentials_never_reach_the_code() {
        let service = service().await;
        let code = a_code(&service, &["openid"]).await;

        let mut wrong = exchange(&code, VERIFIER);
        wrong.client_secret = "guessed".into();
        assert!(service.exchange_code(wrong).await.is_err());

        // The code survived: a failed *authentication* must not spend it, or
        // anyone could burn a code by guessing at the secret.
        assert!(service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .is_ok());
    }

    #[tokio::test]
    async fn a_refresh_token_works_once_and_yields_a_new_one() {
        let service = service().await;
        let code = a_code(&service, &["openid", "email"]).await;
        let first = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();

        let second = service
            .refresh_tokens("app", "s3cret", &first.refresh_token)
            .await
            .unwrap();
        assert_ne!(second.refresh_token, first.refresh_token, "it rotated");
        assert_eq!(second.scope, first.scope, "scopes carry over");

        let claims: OAuthClaims = service
            .keys
            .verify_claims(&second.access_token, AUD)
            .unwrap();
        assert_eq!(claims.sub, "alice");

        // A refreshed ID token carries no nonce: the original belonged to one
        // sign-in.
        let id: IdTokenClaims = service
            .keys
            .verify_claims(second.id_token.as_ref().unwrap(), "app")
            .unwrap();
        assert_eq!(id.nonce, None);
    }

    #[tokio::test]
    async fn reusing_a_refresh_token_revokes_the_whole_chain() {
        let service = service().await;
        let code = a_code(&service, &["openid"]).await;
        let first = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();
        let second = service
            .refresh_tokens("app", "s3cret", &first.refresh_token)
            .await
            .unwrap();

        // The attacker replays the token the legitimate client already spent.
        let err = service
            .refresh_tokens("app", "s3cret", &first.refresh_token)
            .await
            .unwrap_err();
        assert!(matches!(err, AmiError::AccessDenied { .. }));

        // And the legitimate client is locked out too. That is intended: we
        // cannot tell which of the two is the thief, so both sign in again.
        assert!(
            service
                .refresh_tokens("app", "s3cret", &second.refresh_token)
                .await
                .is_err(),
            "the chain should have been revoked"
        );
    }

    #[tokio::test]
    async fn an_unknown_or_foreign_refresh_token_is_refused() {
        let service = service().await;
        assert!(service
            .refresh_tokens("app", "s3cret", "never-issued")
            .await
            .is_err());

        let other = build_client(
            "other".into(),
            "other-secret",
            "Other".into(),
            vec![GrantType::RefreshToken],
            vec!["openid".into()],
            AUD.to_string(),
            vec![REDIRECT.to_string()],
        )
        .unwrap();
        service.register_client(other).await.unwrap();

        let code = a_code(&service, &["openid"]).await;
        let tokens = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();

        assert!(
            service
                .refresh_tokens("other", "other-secret", &tokens.refresh_token)
                .await
                .is_err(),
            "a refresh token is bound to the client it was issued to"
        );
    }

    #[tokio::test]
    async fn withdrawing_consent_stops_the_refresh_tokens_it_backed() {
        // Otherwise the user says no and the client keeps minting access tokens
        // for a month.
        let service = service().await;
        let code = a_code(&service, &["openid"]).await;
        let tokens = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();

        assert!(service.withdraw_consent("app", "alice").await.unwrap());
        assert!(service
            .refresh_tokens("app", "s3cret", &tokens.refresh_token)
            .await
            .is_err());

        // And the next authorization asks again.
        assert!(matches!(
            service.authorize(request(&["openid"])).await.unwrap(),
            Authorization::ConsentRequired { .. }
        ));
    }

    #[tokio::test]
    async fn userinfo_releases_only_what_the_scopes_granted() {
        let service = service().await;
        let code = a_code(&service, &["openid", "email"]).await;
        let tokens = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();

        let info = service.user_info(&tokens.access_token, AUD).await.unwrap();
        assert_eq!(info.sub, "alice");
        assert_eq!(info.email.as_deref(), Some("alice@example.test"));
        assert_eq!(info.name, None, "profile was not granted");
    }

    #[tokio::test]
    async fn userinfo_refuses_a_token_with_no_user_behind_it() {
        // A client_credentials token's subject is the client. Answering with it
        // as `sub` would tell the caller a person signed in when none did.
        let service = service_with(vec![GrantType::ClientCredentials], vec![]).await;
        let token = service
            .issue_token(GrantRequest::ClientCredentials {
                client_id: "app".into(),
                client_secret: "s3cret".into(),
                scope: vec!["reports:read".into()],
            })
            .await
            .unwrap();

        assert!(matches!(
            service.user_info(&token.access_token, AUD).await,
            Err(AmiError::AccessDenied { .. })
        ));
    }

    #[tokio::test]
    async fn userinfo_refuses_a_revoked_token() {
        let service = service().await;
        let code = a_code(&service, &["openid"]).await;
        let tokens = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();

        service.revoke_all_for_client("app").await.unwrap();
        assert!(service.user_info(&tokens.access_token, AUD).await.is_err());
        assert!(service.user_info("not-a-jwt", AUD).await.is_err());
    }

    #[tokio::test]
    async fn a_service_without_a_claims_source_releases_only_the_subject() {
        let service = OAuthService::new(
            Arc::new(RwLock::new(InMemoryOAuthStore::new())),
            Arc::new(KeyManager::generate()),
            "https://id.test".to_string(),
        );
        let client = build_client(
            "app".into(),
            "s3cret",
            "The App".into(),
            vec![GrantType::AuthorizationCode],
            vec!["openid".into(), "email".into()],
            AUD.to_string(),
            vec![REDIRECT.to_string()],
        )
        .unwrap();
        service.register_client(client).await.unwrap();

        let code = a_code(&service, &["openid", "email"]).await;
        let tokens = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();

        let info = service.user_info(&tokens.access_token, AUD).await.unwrap();
        assert_eq!(info.sub, "alice");
        assert_eq!(info.email, None, "there was nothing to ask");
    }

    #[tokio::test]
    async fn a_disabled_client_can_neither_authorize_nor_consent() {
        let service = service().await;
        service.disable_client("app").await.unwrap();

        assert!(matches!(
            service.authorize(request(&["openid"])).await,
            Err(AmiError::AccessDenied { .. })
        ));
        assert!(service
            .grant_consent("app", "alice", vec!["openid".into()])
            .await
            .is_err());
    }

    #[tokio::test]
    async fn a_user_cannot_consent_to_a_scope_the_client_never_had() {
        // Otherwise a host with a buggy consent screen could record approval
        // for something the client was never registered to ask for, and the
        // narrowing at authorization time would be the only thing left.
        let service = service().await;
        let err = service
            .grant_consent("app", "alice", vec!["billing:write".into()])
            .await
            .unwrap_err();
        assert!(matches!(err, AmiError::InvalidParameter { .. }));
    }

    #[tokio::test]
    async fn an_expired_refresh_token_is_refused_without_revoking_the_chain() {
        // Expiry is not a leak. Punishing it like one would sign every idle
        // user out of every other client they use.
        let service = service().await;
        let code = a_code(&service, &["openid"]).await;
        let live = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();

        let stale = RefreshToken {
            token: "stale".into(),
            client_id: "app".into(),
            user_name: "alice".into(),
            scopes: vec!["openid".into()],
            expires_at: Utc::now() - chrono::Duration::seconds(1),
            used_at: None,
            replaced_by: None,
            event: None,
        };
        service
            .store
            .write()
            .await
            .store_refresh_token(stale)
            .await
            .unwrap();

        let err = service
            .refresh_tokens("app", "s3cret", "stale")
            .await
            .unwrap_err();
        assert!(matches!(err, AmiError::AccessDenied { .. }));
        assert!(
            !err.to_string().contains("reuse"),
            "an expiry must not be reported as a leak: {err}"
        );

        assert!(
            service
                .refresh_tokens("app", "s3cret", &live.refresh_token)
                .await
                .is_ok(),
            "the user's live token should have survived"
        );
    }

    /// A sign-in the host reports: two hours ago, password plus a hardware key.
    fn an_event() -> AuthenticationEvent {
        AuthenticationEvent {
            at: Utc::now() - chrono::Duration::hours(2),
            acr: Some("urn:mace:incommon:iap:silver".into()),
            amr: vec!["pwd".into(), "hwk".into()],
        }
    }

    #[tokio::test]
    async fn the_id_token_reports_the_sign_in_the_host_described() {
        let service = service().await;
        let event = an_event();
        service
            .grant_consent("app", "alice", vec!["openid".into()])
            .await
            .unwrap();
        let mut req = request(&["openid"]);
        req.event = Some(event.clone());
        let code = match service.authorize(req).await.unwrap() {
            Authorization::Code { code, .. } => code,
            other => panic!("expected a code, got {other:?}"),
        };

        let tokens = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();
        let id: IdTokenClaims = service
            .keys
            .verify_claims(tokens.id_token.as_ref().unwrap(), "app")
            .unwrap();

        assert_eq!(id.auth_time, Some(event.at.timestamp()));
        assert_eq!(id.acr, event.acr);
        assert_eq!(id.amr, vec!["pwd", "hwk"]);
    }

    #[tokio::test]
    async fn a_refreshed_id_token_reports_the_original_sign_in_not_the_refresh() {
        // OIDC Core §12.2: auth_time "MUST represent the time of the original
        // authentication - not the time that the new ID token is issued". A
        // chain that recomputed it would silently reset the session age on
        // every refresh, defeating a relying party that enforces max_age.
        let service = service().await;
        let event = an_event();
        service
            .grant_consent("app", "alice", vec!["openid".into()])
            .await
            .unwrap();
        let mut req = request(&["openid"]);
        req.event = Some(event.clone());
        let code = match service.authorize(req).await.unwrap() {
            Authorization::Code { code, .. } => code,
            other => panic!("expected a code, got {other:?}"),
        };
        let first = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();

        let second = service
            .refresh_tokens("app", "s3cret", &first.refresh_token)
            .await
            .unwrap();
        let third = service
            .refresh_tokens("app", "s3cret", &second.refresh_token)
            .await
            .unwrap();

        for (which, tokens) in [("second", &second), ("third", &third)] {
            let id: IdTokenClaims = service
                .keys
                .verify_claims(tokens.id_token.as_ref().unwrap(), "app")
                .unwrap();
            assert_eq!(
                id.auth_time,
                Some(event.at.timestamp()),
                "{which} refresh moved auth_time"
            );
            assert_eq!(id.amr, vec!["pwd", "hwk"], "{which} refresh lost amr");
            assert_eq!(id.nonce, None, "{which} refresh must not echo the nonce");
        }
    }

    #[tokio::test]
    async fn a_host_that_says_nothing_gets_no_authentication_claims() {
        let service = service().await;
        let code = a_code(&service, &["openid"]).await;
        let tokens = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();

        let id: IdTokenClaims = service
            .keys
            .verify_claims(tokens.id_token.as_ref().unwrap(), "app")
            .unwrap();
        assert_eq!(id.auth_time, None);
        assert_eq!(id.acr, None);
        assert!(id.amr.is_empty());

        // And they are absent from the wire, not present as nulls.
        let json = serde_json::to_value(&id).unwrap();
        for absent in ["auth_time", "acr", "amr"] {
            assert!(json.get(absent).is_none(), "{absent} was serialised");
        }
    }

    #[tokio::test]
    async fn explicit_typing_labels_access_tokens_and_leaves_id_tokens_alone() {
        let service = service().await.with_explicit_typ();
        let code = a_code(&service, &["openid"]).await;
        let tokens = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();

        let access = jsonwebtoken::decode_header(&tokens.access_token).unwrap();
        assert_eq!(access.typ.as_deref(), Some("at+jwt"));

        // OIDC registers no typ for ID tokens, so they keep JWT — and that
        // difference is what makes the two impossible to confuse.
        let id = jsonwebtoken::decode_header(tokens.id_token.as_ref().unwrap()).unwrap();
        assert_eq!(id.typ.as_deref(), Some("JWT"));

        // Two independent barriers, checked one at a time. The audience: an
        // access token names the API, so it does not verify against the
        // client. And the label, isolated by asking with the *right* audience
        // — only the `typ` can refuse it here.
        assert!(
            service
                .keys
                .verify_claims::<IdTokenClaims>(&tokens.access_token, "app")
                .is_err(),
            "the audience alone should have refused it"
        );
        let by_label = service.keys.verify_claims_as::<IdTokenClaims>(
            &tokens.access_token,
            AUD,
            TokenType::Jwt,
            TypePolicy::Lenient,
        );
        assert!(
            matches!(
                by_label,
                Err(crate::wami::sts::jwt::JwtError::TokenTypeMismatch { .. })
            ),
            "the label alone should have refused it, got {by_label:?}"
        );
    }

    #[tokio::test]
    async fn turning_typing_on_does_not_invalidate_tokens_already_issued() {
        // The reason the switch is safe to flip in production: an access token
        // signed before the flip carries `typ: JWT`, and introspection and
        // /userinfo still accept it.
        let untyped = service().await;
        let code = a_code(&untyped, &["openid"]).await;
        let tokens = untyped
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();

        let typed = OAuthService::new(
            untyped.store.clone(),
            untyped.keys.clone(),
            "https://id.test".to_string(),
        )
        .with_user_claims(Arc::new(Directory))
        .with_explicit_typ();

        assert!(typed.user_info(&tokens.access_token, AUD).await.is_ok());
        assert!(
            typed
                .introspect_token(&tokens.access_token, AUD)
                .await
                .unwrap()
                .active
        );
    }

    #[tokio::test]
    async fn an_id_token_is_never_accepted_as_a_bearer_token() {
        let service = service().await.with_explicit_typ();
        let code = a_code(&service, &["openid"]).await;
        let tokens = service
            .exchange_code(exchange(&code, VERIFIER))
            .await
            .unwrap();
        let id_token = tokens.id_token.unwrap();

        // Two independent reasons it fails: the audience is the client, and
        // once typing is on the label is wrong too.
        assert!(service.user_info(&id_token, AUD).await.is_err());
        assert!(
            !service
                .introspect_token(&id_token, AUD)
                .await
                .unwrap()
                .active
        );
    }

    #[tokio::test]
    async fn discovery_reports_this_services_issuer() {
        let service = service().await;
        let doc = service.discovery("https://id.test");
        assert_eq!(doc.issuer, "https://id.test");
        assert_eq!(doc.authorization_endpoint, "https://id.test/authorize");
        assert_eq!(doc.code_challenge_methods_supported, vec!["S256"]);
    }
}