auth-framework 0.6.0-rc47

A comprehensive, production-ready authentication and authorization framework for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
//! OAuth 2.0 API Endpoints
//!
//! Handles OAuth 2.0 authorization code flow (RFC 6749), token exchange,
//! token revocation (RFC 7009), and client metadata retrieval.

use crate::api::{ApiResponse, ApiState, extract_bearer_token, validate_api_token};
use crate::oauth2_server::AuthorizationRequest;
// Re-export canonical types for consumers that imported them from api::oauth2
pub use crate::oauth2_server::{
    AuthorizationRequest as AuthorizeRequest, TokenRequest, TokenResponse,
};
use axum::{
    Json,
    extract::{Path, Query, State},
    http::{HeaderMap, StatusCode},
    response::{IntoResponse, Redirect},
};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use url::Url;
use uuid::Uuid;

/// Compare two redirect URIs using parsed URL normalization (RFC 6749 §3.1.2.3).
///
/// Normalization handles scheme/host case, default-port elision, and path
/// normalization so that trivial textual differences don't cause mismatches.
fn redirect_uri_matches(candidate: &str, registered: &str) -> bool {
    match (Url::parse(candidate), Url::parse(registered)) {
        (Ok(a), Ok(b)) => {
            // RFC 6749 §3.1.2: redirect URIs MUST NOT contain a fragment component.
            if a.fragment().is_some() || b.fragment().is_some() {
                return false;
            }

            a.scheme() == b.scheme()
                && a.host_str() == b.host_str()
                && a.port_or_known_default() == b.port_or_known_default()
                && a.path() == b.path()
                && a.query() == b.query()
        }
        // If either side isn't a valid URL, fall back to exact string match
        // so we don't silently accept garbage.
        _ => candidate == registered,
    }
}

/// OAuth error response per [RFC 6749 §5.2](https://datatracker.ietf.org/doc/html/rfc6749#section-5.2).
///
/// Use the constructor + chaining helpers to avoid specifying all four fields
/// every time:
///
/// # Example
/// ```rust
/// use auth_framework::api::oauth2::OAuthError;
///
/// let err = OAuthError::new("invalid_request")
///     .description("missing redirect_uri")
///     .state("abc");
/// assert_eq!(err.error, "invalid_request");
/// assert_eq!(err.error_description.as_deref(), Some("missing redirect_uri"));
/// ```
#[derive(Debug, Serialize)]
pub struct OAuthError {
    pub error: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_uri: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
}

impl OAuthError {
    /// Create a new error with the given error code (e.g. `"invalid_request"`).
    pub fn new(error: impl Into<String>) -> Self {
        Self {
            error: error.into(),
            error_description: None,
            error_uri: None,
            state: None,
        }
    }

    /// Set the human-readable error description.
    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.error_description = Some(desc.into());
        self
    }

    /// Set the `state` parameter (echoed back from the authorization request).
    pub fn state(mut self, state: impl Into<String>) -> Self {
        self.state = Some(state.into());
        self
    }

    /// Set the `state` parameter from an `Option`.
    pub fn maybe_state(mut self, state: Option<String>) -> Self {
        self.state = state;
        self
    }

    /// Set the error URI pointing to a page with more information.
    pub fn error_uri(mut self, uri: impl Into<String>) -> Self {
        self.error_uri = Some(uri.into());
        self
    }
}

/// Registered OAuth 2.0 client metadata.
///
/// Stored in KV at `oauth2_client:{client_id}` and returned by
/// [`get_client_info`].
///
/// # Example
/// ```rust
/// use auth_framework::api::oauth2::ClientInfo;
///
/// let info = ClientInfo {
///     client_id: "abc".into(),
///     name: "My App".into(),
///     description: "A demo app".into(),
///     redirect_uris: vec!["https://example.com/cb".into()],
///     scopes: vec!["openid".into()],
/// };
/// assert_eq!(info.client_id, "abc");
/// ```
#[derive(Debug, Serialize, Deserialize)]
pub struct ClientInfo {
    pub client_id: String,
    pub name: String,
    pub description: String,
    pub redirect_uris: Vec<String>,
    pub scopes: Vec<String>,
}

/// OAuth 2.0 token revocation request per [RFC 7009](https://datatracker.ietf.org/doc/html/rfc7009).
///
/// # Example
/// ```rust
/// use auth_framework::api::oauth2::RevokeRequest;
///
/// let req: RevokeRequest = serde_json::from_str(r#"{"token":"abc"}"#).unwrap();
/// assert_eq!(req.token, "abc");
/// assert!(req.token_type_hint.is_none());
/// ```
#[derive(Debug, Deserialize)]
pub struct RevokeRequest {
    pub token: String,
    #[serde(default)]
    pub token_type_hint: Option<String>, // "access_token" or "refresh_token"
}

/// OpenID Connect UserInfo response.
///
/// Contains claims about the authenticated user, filtered by the scopes
/// granted to the access token.
///
/// # Example
/// ```rust
/// use auth_framework::api::oauth2::UserInfoResponse;
///
/// let info = UserInfoResponse {
///     sub: "user-1".into(),
///     name: Some("Alice".into()),
///     email: None,
///     picture: None,
///     updated_at: None,
/// };
/// assert_eq!(info.sub, "user-1");
/// ```
#[derive(Debug, Serialize)]
pub struct UserInfoResponse {
    pub sub: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub picture: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<i64>,
}

/// GET /oauth/authorize
/// OAuth 2.0 authorization endpoint — validates the client and redirect_uri, generates
/// an authorization code, and redirects the user-agent back to the client (RFC 6749 §4.1.2).
///
/// SECURITY: The caller must supply their access token as `Authorization: Bearer <token>`.
/// The authenticated user's identity is recorded in the authorization code so it can be
/// used when the client exchanges the code for tokens.  Issuing codes without a verified
/// user identity would allow any party that knows a valid client_id to obtain tokens.
pub async fn authorize(
    State(state): State<ApiState>,
    headers: HeaderMap,
    Query(params): Query<AuthorizationRequest>,
) -> impl IntoResponse {
    if params.response_type != "code" {
        let error = OAuthError::new("unsupported_response_type")
            .description("Only 'code' response type is supported")
            .maybe_state(params.state);
        return (StatusCode::BAD_REQUEST, Json(error)).into_response();
    }

    if params.client_id.is_empty() {
        let error = OAuthError::new("invalid_request")
            .description("client_id is required")
            .maybe_state(params.state);
        return (StatusCode::BAD_REQUEST, Json(error)).into_response();
    }

    if params.redirect_uri.is_empty() {
        let error = OAuthError::new("invalid_request")
            .description("redirect_uri is required")
            .maybe_state(params.state);
        return (StatusCode::BAD_REQUEST, Json(error)).into_response();
    }

    // SECURITY: Require the resource owner to be authenticated before issuing codes.
    // The user must supply their Bearer access token.  Without this check, any caller
    // that knows a registered client_id could obtain a code and exchange it for tokens.
    let user_id = {
        let token_str = match extract_bearer_token(&headers) {
            Some(t) => t,
            None => {
                let error = OAuthError::new("unauthorized_client")
                    .description(
                        "User authentication required: supply your access token as \
                         'Authorization: Bearer <token>'",
                    )
                    .maybe_state(params.state);
                return (StatusCode::UNAUTHORIZED, Json(error)).into_response();
            }
        };
        match validate_api_token(&state.auth_framework, &token_str).await {
            Ok(auth_token) => auth_token.user_id,
            Err(_) => {
                let error = OAuthError::new("unauthorized_client")
                    .description("Invalid or expired user access token")
                    .maybe_state(params.state);
                return (StatusCode::UNAUTHORIZED, Json(error)).into_response();
            }
        }
    };

    // SECURITY: Validate client_id and verify the redirect_uri is pre-registered.
    // Redirecting to an unregistered URI would let an attacker steal the authorization code.
    let client_key = format!("oauth2_client:{}", params.client_id);
    let granted_scope = match state.auth_framework.storage().get_kv(&client_key).await {
        Ok(Some(data)) => {
            let client_data: serde_json::Value = serde_json::from_slice(&data).unwrap_or_default();
            let registered_uris: Vec<String> = client_data["redirect_uris"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(String::from))
                        .collect()
                })
                .unwrap_or_default();

            if !registered_uris
                .iter()
                .any(|r| redirect_uri_matches(&params.redirect_uri, r))
            {
                tracing::warn!(
                    client_id = %params.client_id,
                    redirect_uri = %params.redirect_uri,
                    "OAuth authorize: redirect_uri not registered for client"
                );
                let error = OAuthError::new("invalid_request")
                    .description("redirect_uri is not registered for this client")
                    .maybe_state(params.state);
                return (StatusCode::BAD_REQUEST, Json(error)).into_response();
            }

            // S8: Public clients (no client_secret) MUST provide a PKCE code_challenge.
            let is_public_client = client_data
                .get("client_secret")
                .and_then(|v| v.as_str())
                .is_none_or(|s| s.is_empty());
            if is_public_client && params.code_challenge.is_none() {
                let error = OAuthError::new("invalid_request")
                    .description("Public clients must use PKCE: code_challenge is required")
                    .maybe_state(params.state);
                return (StatusCode::BAD_REQUEST, Json(error)).into_response();
            }

            // A client can be granted only the scopes it is registered for.
            match effective_scope(&client_data, params.scope.as_deref()) {
                Ok(scope) => scope,
                Err(description) => {
                    let error = OAuthError::new("invalid_scope")
                        .description(description)
                        .maybe_state(params.state);
                    return (StatusCode::BAD_REQUEST, Json(error)).into_response();
                }
            }
        }
        Ok(None) => {
            tracing::warn!(client_id = %params.client_id, "OAuth authorize: unknown client_id");
            let error = OAuthError::new("invalid_client")
                .description("Unknown client_id")
                .maybe_state(params.state);
            return (StatusCode::BAD_REQUEST, Json(error)).into_response();
        }
        Err(e) => {
            tracing::error!(
                client_id = %params.client_id,
                error = %e,
                "OAuth authorize: storage error looking up client"
            );
            let error = OAuthError::new("server_error")
                .description("Authorization server error")
                .maybe_state(params.state);
            return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
        }
    };

    let auth_code = format!("ac_{}", uuid::Uuid::new_v4().to_string().replace("-", ""));

    // RFC 8707: Validate resource indicators if present.
    if let Some(ref resources) = params.resource
        && let Err(e) =
            crate::server::oauth::resource_indicators::validate_resource_indicators(resources)
    {
        let error = OAuthError::new("invalid_target")
            .description(e.to_string())
            .maybe_state(params.state);
        return (StatusCode::BAD_REQUEST, Json(error)).into_response();
    }

    let code_data = serde_json::json!({
        "client_id": params.client_id,
        "redirect_uri": params.redirect_uri,
        "scope": granted_scope,
        "state": params.state.clone(),
        "code_challenge": params.code_challenge,
        "code_challenge_method": params.code_challenge_method,
        "user_id": user_id,
        "resource": params.resource,
        "created_at": chrono::Utc::now().to_rfc3339(),
        "expires_at": (chrono::Utc::now() + chrono::Duration::minutes(10)).to_rfc3339(),
        "used": false,
    });

    let storage_key = format!("oauth2_code:{}", auth_code);
    let code_data_str = match serde_json::to_string(&code_data) {
        Ok(s) => s,
        Err(e) => {
            tracing::error!("Failed to serialize OAuth authorization code data: {:?}", e);
            let error =
                OAuthError::new("server_error").description("Authorization server internal error");
            return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
        }
    };

    if let Err(e) = state
        .auth_framework
        .storage()
        .store_kv(
            &storage_key,
            code_data_str.as_bytes(),
            Some(std::time::Duration::from_secs(600)),
        )
        .await
    {
        tracing::error!("Failed to store OAuth authorization code: {:?}", e);
        let error = OAuthError::new("server_error")
            .description("Authorization server error")
            .maybe_state(params.state);
        return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
    }

    // SECURITY: URL-encode the state value to prevent parameter injection.
    // A raw state like "&extra=injected" would append unintended query parameters.
    let encoded_state: Option<String> = params.state.as_deref().map(|st| {
        st.bytes()
            .flat_map(|b| {
                if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
                    vec![b as char]
                } else {
                    format!("%{:02X}", b).chars().collect()
                }
            })
            .collect()
    });

    let mut redirect_url = params.redirect_uri;
    redirect_url.push_str(&format!("?code={}", auth_code));
    if let Some(ref st) = encoded_state {
        redirect_url.push_str(&format!("&state={}", st));
    }

    tracing::info!(
        client_id = %params.client_id,
        user_id = %user_id,
        "OAuth authorization code issued"
    );
    Redirect::to(&redirect_url).into_response()
}

/// POST /oauth/token — exchange an authorization code or refresh token for
/// an access token (RFC 6749 §4.1.3, §6).
///
/// Supported grant types:
/// - `authorization_code` — requires `code`, `client_id`, and optionally `code_verifier`
/// - `refresh_token` — requires `refresh_token`
///
/// # Example
/// ```rust,ignore
/// // POST /oauth/token {"grant_type":"authorization_code","code":"ac_...","client_id":"..."}
/// let response = token(State(api_state), Json(token_request)).await;
/// assert!(response.success);
/// ```
pub async fn token(
    State(state): State<ApiState>,
    Json(req): Json<TokenRequest>,
) -> ApiResponse<TokenResponse> {
    match req.grant_type.as_str() {
        "authorization_code" => handle_authorization_code_grant(state, req).await,
        "refresh_token" => handle_refresh_token_grant(state, req).await,
        _ => ApiResponse::error_typed(
            "unsupported_grant_type",
            "Supported grant types: authorization_code, refresh_token",
        ),
    }
}

async fn handle_authorization_code_grant(
    state: ApiState,
    req: TokenRequest,
) -> ApiResponse<TokenResponse> {
    let code = match req.code {
        Some(c) => c,
        None => {
            return ApiResponse::validation_error_typed(
                "code is required for authorization_code grant",
            );
        }
    };

    let client_id = match req.client_id {
        Some(c) => c,
        None => return ApiResponse::validation_error_typed("client_id is required"),
    };

    // Authenticate the client BEFORE the code is looked at, so a failed
    // authentication neither reveals anything about the code nor consumes it.
    let client_kind =
        match authenticate_token_client(&state, &client_id, req.client_secret.as_deref()).await {
            Ok(kind) => kind,
            Err(refusal) => return *refusal,
        };

    let consumed_key = format!("oauth2_code_consumed:{}", code);
    let storage_key = format!("oauth2_code:{}", code);
    let code_data = match state.auth_framework.storage().get_kv(&storage_key).await {
        Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
            Ok(json) => json,
            Err(e) => {
                tracing::error!("Failed to parse stored authorization code data: {:?}", e);
                return ApiResponse::error_typed("invalid_grant", "Invalid authorization code");
            }
        },
        Ok(None) => {
            return ApiResponse::error_typed(
                "invalid_grant",
                "Authorization code not found or expired",
            );
        }
        Err(e) => {
            tracing::error!("Failed to retrieve authorization code: {:?}", e);
            return ApiResponse::error_typed(
                "server_error",
                "Failed to validate authorization code",
            );
        }
    };

    // Claim the code: of any number of simultaneous redemptions exactly one proceeds (atomic
    // set-if-absent). The marker is only written for a code that exists, so presenting
    // made-up codes stores nothing.
    match state
        .auth_framework
        .storage()
        .store_kv_if_absent(
            &consumed_key,
            b"1",
            Some(std::time::Duration::from_secs(600)),
        )
        .await
    {
        Ok(true) => {}
        Ok(false) => {
            return ApiResponse::error_typed("invalid_grant", "Authorization code already used");
        }
        Err(e) => {
            tracing::error!("Failed to claim authorization code: {:?}", e);
            return ApiResponse::error_typed(
                "server_error",
                "Failed to process authorization code",
            );
        }
    }

    // A code issued to a different client is refused and left intact (with its
    // consumed marker released), so presenting someone else's code cannot burn it.
    if code_data["client_id"].as_str() != Some(&client_id) {
        if let Err(e) = state
            .auth_framework
            .storage()
            .delete_kv(&consumed_key)
            .await
        {
            tracing::warn!("Failed to release code consumed marker: {:?}", e);
        }
        return ApiResponse::error_typed("invalid_grant", "client_id mismatch");
    }

    // Immediately delete the code to prevent reuse (single-use enforcement).
    if let Err(e) = state.auth_framework.storage().delete_kv(&storage_key).await {
        tracing::error!("Failed to delete authorization code from storage: {:?}", e);
        return ApiResponse::error_typed("server_error", "Failed to process authorization code");
    }

    // Validate redirect_uri if provided
    if let Some(redirect_uri) = &req.redirect_uri {
        let stored_uri = code_data["redirect_uri"].as_str().unwrap_or_default();
        if !redirect_uri_matches(redirect_uri, stored_uri) {
            return ApiResponse::error_typed("invalid_grant", "redirect_uri mismatch");
        }
    }

    // Check if PKCE was used in authorization - if so, code_verifier is required
    let stored_challenge = code_data["code_challenge"].as_str();
    let challenge_method = code_data["code_challenge_method"]
        .as_str()
        .unwrap_or("plain");

    if let Some(stored) = stored_challenge {
        // PKCE was used in authorization, so code_verifier is required
        let code_verifier = match &req.code_verifier {
            Some(verifier) => verifier,
            None => {
                return ApiResponse::error_typed(
                    "invalid_request",
                    "code_verifier is required when PKCE challenge was provided",
                );
            }
        };

        let computed_challenge = match challenge_method {
            "S256" => {
                let mut hasher = Sha256::new();
                hasher.update(code_verifier.as_bytes());
                URL_SAFE_NO_PAD.encode(hasher.finalize())
            }
            "plain" => code_verifier.clone(),
            _ => {
                return ApiResponse::error_typed(
                    "invalid_request",
                    "Unsupported code_challenge_method",
                );
            }
        };

        if computed_challenge != stored {
            return ApiResponse::error_typed("invalid_grant", "PKCE verification failed");
        }
    } else if req.code_verifier.is_some() {
        // code_verifier provided but no challenge was used - this is suspicious
        return ApiResponse::error_typed(
            "invalid_request",
            "code_verifier provided but no PKCE challenge was used in authorization",
        );
    } else if client_kind == ClientKind::Public {
        // S8: Public clients (registered without a secret) MUST use PKCE.
        // Whether a client is public comes from its registration, not from whether
        // the request happens to carry a secret.
        return ApiResponse::error_typed(
            "invalid_request",
            "Public clients must use PKCE: provide code_challenge in authorization and code_verifier in token request",
        );
    }

    // Code was already atomically deleted above (delete-first approach).
    // No need to mark as used — the code is permanently consumed.

    // RFC 8707: Validate resource indicators on the token request.
    let authz_resources: Vec<String> = code_data["resource"]
        .as_array()
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    if let Some(ref token_resources) = req.resource {
        if let Err(e) =
            crate::server::oauth::resource_indicators::validate_resource_indicators(token_resources)
        {
            return ApiResponse::error_typed("invalid_target", e.to_string());
        }
        if let Err(e) = crate::server::oauth::resource_indicators::validate_token_resource_subset(
            token_resources,
            &authz_resources,
        ) {
            return ApiResponse::error_typed("invalid_target", e.to_string());
        }
    }

    // Create access and refresh tokens
    //
    // The granted scope never exceeds what the client is registered for, whatever the
    // code carries (e.g. a code issued before scopes were enforced).
    let client_record = match load_client_record(&state, &client_id).await {
        Ok(Some(record)) => record,
        Ok(None) => return ApiResponse::error_typed("invalid_client", "Unknown client"),
        Err(refused) => return *refused,
    };
    let allowed = allowed_scopes(&client_record);
    let scopes: Vec<String> = code_data["scope"]
        .as_str()
        .unwrap_or("openid profile email")
        .split_whitespace()
        .filter(|s| allowed.iter().any(|a| a == s))
        .map(|s| s.to_string())
        .collect();
    if scopes.is_empty() {
        return ApiResponse::error_typed(
            "invalid_scope",
            "No granted scope is allowed for this client",
        );
    }
    let scope = scopes.join(" ");

    // Use the user_id that was recorded in the authorization code when the resource owner
    // authenticated via the /oauth/authorize endpoint.  This ensures tokens are bound to the
    // actual user rather than a fabricated identifier derived from the client_id.
    let user_id = match code_data["user_id"].as_str() {
        Some(uid) if !uid.is_empty() => uid.to_string(),
        _ => {
            tracing::error!("Authorization code missing user_id field");
            return ApiResponse::error_typed("server_error", "Malformed authorization code");
        }
    };

    let token = match state
        .auth_framework
        .token_manager()
        .create_client_auth_token(&user_id, scopes.clone(), "oauth2", &client_id, None)
    {
        Ok(token) => token,
        Err(e) => {
            tracing::error!("Failed to create access token: {:?}", e);
            return ApiResponse::error_typed("server_error", "Failed to create access token");
        }
    };

    // Persist a storage-backed refresh token so the refresh grant can validate and rotate it.
    let refresh_token_value = uuid::Uuid::new_v4().to_string().replace("-", "");
    let refresh_data = serde_json::json!({
        "user_id": user_id,
        "client_id": client_id,
        "scopes": scope,
    });
    let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_value);
    if let Err(e) = state
        .auth_framework
        .storage()
        .store_kv(
            &refresh_key,
            serde_json::to_string(&refresh_data)
                .unwrap_or_default()
                .as_bytes(),
            Some(std::time::Duration::from_secs(30 * 24 * 3600)),
        )
        .await
    {
        tracing::warn!("Failed to store refresh token: {:?}", e);
    }

    let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
    let response = TokenResponse {
        access_token: token.access_token,
        token_type: "Bearer".to_string(),
        expires_in,
        refresh_token: Some(refresh_token_value),
        scope: Some(scope.to_string()),
        id_token: None,
    };

    tracing::info!("OAuth2 tokens issued for client: {}", client_id);
    ApiResponse::success(response)
}

/// A boxed error response (keeps the `Err` variant of the client-check helpers small).
fn refusal(code: &str, message: &str) -> Box<ApiResponse<TokenResponse>> {
    Box::new(ApiResponse::error_typed(code, message))
}

/// Load a registered client's record from `oauth2_client:{client_id}`.
async fn load_client_record(
    state: &ApiState,
    client_id: &str,
) -> std::result::Result<Option<serde_json::Value>, Box<ApiResponse<TokenResponse>>> {
    let key = format!("oauth2_client:{client_id}");
    match state.auth_framework.storage().get_kv(&key).await {
        Ok(Some(data)) => serde_json::from_slice(&data).map(Some).map_err(|e| {
            tracing::error!("Unreadable client record for {client_id}: {e}");
            refusal("server_error", "Failed to validate client")
        }),
        Ok(None) => Ok(None),
        Err(e) => {
            tracing::error!("Failed to load client {client_id}: {e:?}");
            Err(refusal("server_error", "Failed to validate client"))
        }
    }
}

/// Scopes granted to clients that were registered without any scope information.
const DEFAULT_CLIENT_SCOPES: [&str; 3] = ["openid", "profile", "email"];

/// The scopes a client may be granted: those it was registered for (the `scope` string
/// and/or the `scopes` list). A record that names neither key predates scope registration
/// and gets the OpenID defaults; a record that names a key but yields no scope (empty, or
/// of an unexpected type) is granted nothing.
fn allowed_scopes(record: &serde_json::Value) -> Vec<String> {
    if record.get("scope").is_none_or(|v| v.is_null())
        && record.get("scopes").is_none_or(|v| v.is_null())
    {
        return DEFAULT_CLIENT_SCOPES
            .iter()
            .map(|s| s.to_string())
            .collect();
    }
    let mut allowed: Vec<String> = Vec::new();
    if let Some(s) = record["scope"].as_str() {
        allowed.extend(s.split_whitespace().map(String::from));
    }
    if let Some(list) = record["scopes"].as_array() {
        for item in list.iter().filter_map(|v| v.as_str()) {
            allowed.extend(item.split_whitespace().map(String::from));
        }
    }
    allowed.sort();
    allowed.dedup();
    allowed
}

/// The scope to grant for a request: the requested scopes if every one is allowed
/// (RFC 6749 section 3.3), otherwise `Err(invalid_scope description)`. With no scope
/// requested, the client gets everything it is registered for.
fn effective_scope(
    record: &serde_json::Value,
    requested: Option<&str>,
) -> std::result::Result<String, String> {
    let allowed = allowed_scopes(record);
    let requested: Vec<&str> = requested
        .map(|s| s.split_whitespace().collect())
        .unwrap_or_default();
    if requested.is_empty() {
        return if allowed.is_empty() {
            Err("this client is not registered for any scope".to_string())
        } else {
            Ok(allowed.join(" "))
        };
    }
    if let Some(bad) = requested.iter().find(|s| !allowed.iter().any(|a| a == **s)) {
        let shown: String = bad.chars().take(64).collect();
        return Err(format!("scope '{shown}' is not allowed for this client"));
    }
    let mut granted: Vec<&str> = Vec::with_capacity(requested.len());
    for s in requested {
        if !granted.contains(&s) {
            granted.push(s);
        }
    }
    Ok(granted.join(" "))
}

/// The client secret of a client record; `None` for a public client.
fn client_secret_of(record: &serde_json::Value) -> Option<&str> {
    record["client_secret"].as_str().filter(|s| !s.is_empty())
}

/// How a client identified itself at the token endpoint.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ClientKind {
    /// Registered without a secret: identified by `client_id` alone (PKCE is mandatory).
    Public,
    /// Registered with a secret and authenticated with it.
    Confidential,
}

/// Authenticate the client of an authorization-code exchange (RFC 6749 section 3.2.1).
///
/// The client must be registered (`oauth2_client:{id}`). A client whose record holds a
/// non-empty `client_secret` is confidential and MUST present exactly that secret
/// (constant-time compare); a missing or wrong secret is `invalid_client`. Whether a
/// client is public is decided by its registration, never by what the request carries.
async fn authenticate_token_client(
    state: &ApiState,
    client_id: &str,
    presented_secret: Option<&str>,
) -> std::result::Result<ClientKind, Box<ApiResponse<TokenResponse>>> {
    let Some(record) = load_client_record(state, client_id).await? else {
        return Err(refusal("invalid_client", "Unknown client"));
    };
    match client_secret_of(&record) {
        None => Ok(ClientKind::Public),
        Some(stored) => {
            let authenticated = presented_secret.is_some_and(|presented| {
                crate::security::timing_protection::constant_time_string_compare(presented, stored)
            });
            if authenticated {
                Ok(ClientKind::Confidential)
            } else {
                Err(refusal("invalid_client", "Client authentication failed"))
            }
        }
    }
}

/// RFC 6749 §6 / §10.4: a refresh token issued to `stored_client` is
/// redeemable only by that client.
///
/// * A **confidential** client (its record holds a secret) must authenticate,
///   and the client that authenticated must be `stored_client`:
///   missing/invalid credentials are `invalid_client`, a different (validly
///   authenticated) client is `invalid_grant`.
/// * A **public** client must present a `client_id` equal to `stored_client`:
///   missing or different is `invalid_grant`.
///
/// There is no "check it only if it is present" path, and a token whose
/// client is no longer registered fails closed.
async fn authorize_refresh_client(
    state: &ApiState,
    stored_client: &str,
    presented_id: Option<&str>,
    presented_secret: Option<&str>,
) -> std::result::Result<(), Box<ApiResponse<TokenResponse>>> {
    let not_issued_to_you = || {
        refusal(
            "invalid_grant",
            "Refresh token was not issued to this client",
        )
    };

    let Some(stored_record) = load_client_record(state, stored_client).await? else {
        return Err(refusal(
            "invalid_grant",
            "Refresh token was issued to a client that is no longer registered",
        ));
    };

    if client_secret_of(&stored_record).is_none() {
        // Public client: it identifies itself, nothing more.
        return match presented_id {
            Some(id) if id == stored_client => Ok(()),
            _ => Err(not_issued_to_you()),
        };
    }

    // Confidential client: authenticate whoever is asking against THEIR record.
    let (Some(presented_id), Some(presented_secret)) = (presented_id, presented_secret) else {
        return Err(refusal(
            "invalid_client",
            "Client authentication is required",
        ));
    };
    let presented_record = if presented_id == stored_client {
        Some(stored_record)
    } else {
        load_client_record(state, presented_id).await?
    };
    let authenticated = presented_record
        .as_ref()
        .and_then(client_secret_of)
        .is_some_and(|secret| {
            crate::security::timing_protection::constant_time_string_compare(
                presented_secret,
                secret,
            )
        });
    if !authenticated {
        return Err(refusal("invalid_client", "Client authentication failed"));
    }
    if presented_id != stored_client {
        return Err(not_issued_to_you());
    }
    Ok(())
}

async fn handle_refresh_token_grant(
    state: ApiState,
    req: TokenRequest,
) -> ApiResponse<TokenResponse> {
    let refresh_token_str = match req.refresh_token {
        Some(t) => t,
        None => return ApiResponse::validation_error_typed("refresh_token is required"),
    };

    // A revoked refresh token must not mint new access tokens, regardless of
    // whether its own storage entry has been deleted yet (see `revoke`). Fail
    // closed on a storage error here -- matching the equivalent check in
    // `api/auth.rs`'s refresh handler -- rather than treating "couldn't check"
    // as "not revoked".
    let revoked_key = format!("oauth2_revoked_token:{}", refresh_token_str);
    match state.auth_framework.storage().get_kv(&revoked_key).await {
        Ok(Some(_)) => {
            return ApiResponse::error_typed("invalid_grant", "Refresh token has been revoked");
        }
        Ok(None) => {} // Not revoked -- proceed
        Err(e) => {
            tracing::error!("Refresh token revocation check failed: {:?}", e);
            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
        }
    }

    let consumed_key = format!("oauth2_refresh_consumed:{}", refresh_token_str);

    // Validate the refresh token against persistent storage.
    let refresh_key = format!("oauth2_refresh_token:{}", refresh_token_str);
    let stored = match state.auth_framework.storage().get_kv(&refresh_key).await {
        Ok(Some(data)) => match serde_json::from_slice::<serde_json::Value>(&data) {
            Ok(v) => v,
            Err(_) => return ApiResponse::error_typed("invalid_grant", "Invalid refresh token"),
        },
        Ok(None) => {
            return ApiResponse::error_typed("invalid_grant", "Refresh token not found or expired");
        }
        Err(e) => {
            tracing::error!("Failed to retrieve refresh token: {:?}", e);
            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
        }
    };

    // Claim the token: of any number of simultaneous redemptions exactly one proceeds (atomic
    // set-if-absent). The marker is only written for a token that exists.
    match state
        .auth_framework
        .storage()
        .store_kv_if_absent(
            &consumed_key,
            b"1",
            Some(std::time::Duration::from_secs(600)),
        )
        .await
    {
        Ok(true) => {}
        Ok(false) => {
            return ApiResponse::error_typed("invalid_grant", "Refresh token already consumed");
        }
        Err(e) => {
            tracing::error!("Failed to claim refresh token: {:?}", e);
            return ApiResponse::error_typed("server_error", "Failed to validate refresh token");
        }
    }

    let user_id = match stored["user_id"].as_str() {
        Some(u) => u.to_string(),
        None => return ApiResponse::error_typed("invalid_grant", "Malformed refresh token data"),
    };
    let client_id = match &stored["client_id"] {
        serde_json::Value::Null => None,
        serde_json::Value::String(s) => Some(s.clone()),
        // A client_id of some other type cannot be checked: fail closed
        // instead of silently skipping the binding.
        _ => return ApiResponse::error_typed("invalid_grant", "Malformed refresh token data"),
    };

    // A token issued to a client is redeemable only by that client. A refused
    // attempt releases the consumed marker set above, so merely seeing a
    // refresh token (and presenting it wrongly) cannot burn it.
    if let Some(stored_client) = client_id.as_deref()
        && let Err(refusal) = authorize_refresh_client(
            &state,
            stored_client,
            req.client_id.as_deref(),
            req.client_secret.as_deref(),
        )
        .await
    {
        if let Err(e) = state
            .auth_framework
            .storage()
            .delete_kv(&consumed_key)
            .await
        {
            tracing::warn!("Failed to release refresh consumed marker: {:?}", e);
        }
        return *refusal;
    }

    let mut scopes: Vec<String> = stored["scopes"]
        .as_str()
        .unwrap_or("openid profile email")
        .split_whitespace()
        .map(|s| s.to_string())
        .collect();
    // A refreshed token never exceeds what the client is registered for NOW, whatever the
    // stored record carries (older records, or a registration narrowed since).
    if let Some(client) = stored["client_id"].as_str() {
        let record = match load_client_record(&state, client).await {
            Ok(Some(record)) => record,
            Ok(None) => {
                let _ = state
                    .auth_framework
                    .storage()
                    .delete_kv(&consumed_key)
                    .await;
                return ApiResponse::error_typed("invalid_client", "Unknown client");
            }
            Err(refused) => {
                let _ = state
                    .auth_framework
                    .storage()
                    .delete_kv(&consumed_key)
                    .await;
                return *refused;
            }
        };
        let allowed = allowed_scopes(&record);
        scopes.retain(|s| allowed.iter().any(|a| a == s));
        if scopes.is_empty() {
            let _ = state
                .auth_framework
                .storage()
                .delete_kv(&consumed_key)
                .await;
            return ApiResponse::error_typed(
                "invalid_scope",
                "No granted scope is allowed for this client",
            );
        }
    }
    let scope = scopes.join(" ");

    let minted = match client_id.as_deref() {
        Some(client) => state
            .auth_framework
            .token_manager()
            .create_client_auth_token(&user_id, scopes, "oauth2", client, None),
        // A stored refresh record without a client (written by an older version) still came
        // from an OAuth grant: its access token is delegated, never a user session.
        None => state
            .auth_framework
            .token_manager()
            .create_client_auth_token(&user_id, scopes, "oauth2", "unknown-client", None),
    };
    let token = match minted {
        Ok(t) => t,
        Err(e) => {
            tracing::error!("Failed to create access token on refresh: {:?}", e);
            return ApiResponse::error_typed("server_error", "Failed to issue access token");
        }
    };

    // Issue a new refresh token (rotation).
    // Store the new token BEFORE deleting the old one to avoid data loss on failure.
    let new_refresh_token = uuid::Uuid::new_v4().to_string().replace("-", "");
    let new_refresh_data = serde_json::json!({
        "user_id": user_id,
        "client_id": client_id,
        "scopes": scope,
    });
    let new_refresh_key = format!("oauth2_refresh_token:{}", new_refresh_token);
    if let Err(e) = state
        .auth_framework
        .storage()
        .store_kv(
            &new_refresh_key,
            serde_json::to_string(&new_refresh_data)
                .unwrap_or_default()
                .as_bytes(),
            Some(std::time::Duration::from_secs(30 * 24 * 3600)),
        )
        .await
    {
        tracing::error!("Failed to store new refresh token: {:?}", e);
        return ApiResponse::error_typed("server_error", "Failed to issue refresh token");
    }

    // Now that the new token is safely stored, delete the old one (single-use enforcement).
    if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
        tracing::warn!(
            "Failed to delete old refresh token during rotation: {:?}",
            e
        );
    }

    let expires_in = (token.expires_at - token.issued_at).num_seconds().max(0) as u64;
    let response = TokenResponse {
        access_token: token.access_token,
        token_type: "Bearer".to_string(),
        expires_in,
        refresh_token: Some(new_refresh_token),
        scope: Some(scope),
        id_token: None,
    };

    tracing::info!("OAuth2 token refreshed for user: {}", user_id);
    ApiResponse::success(response)
}

/// POST /api/v1/oauth/revoke — revoke an access or refresh token.
///
/// Stores a revocation marker in KV (`oauth2_revoked_token:{token}`,
/// TTL'd to the refresh token's own 30-day lifetime -- not just the 7
/// days access-token revocation needs -- since this one marker has to
/// outlive whichever token type was actually revoked) and, for JWT
/// tokens, also stores a JTI-based marker (`revoked_token:{jti}`) so
/// that all authenticated endpoints reject the token immediately. If
/// the token is a refresh token, also deletes its `oauth2_refresh_token:`
/// storage entry outright -- `handle_refresh_token_grant` also checks
/// the revocation marker directly (failing closed on a storage error
/// there), so revocation is effective for the marker's full TTL even if
/// the delete itself fails.
///
/// # Example
/// ```rust,ignore
/// let resp = revoke(State(state), Json(RevokeRequest {
///     token: "access_token_value".into(),
///     token_type_hint: Some("access_token".into()),
/// })).await;
/// assert!(resp.success);
/// ```
pub async fn revoke(
    State(state): State<ApiState>,
    Json(req): Json<RevokeRequest>,
) -> ApiResponse<serde_json::Value> {
    // The token becomes part of a storage key: bound its size.
    if req.token.is_empty() || req.token.len() > 8192 {
        return ApiResponse::error_typed("invalid_request", "Invalid token");
    }

    // Store the revoked token in a blacklist for immediate invalidation.
    // Key by the raw token value so the userinfo endpoint can check it too.
    let revoked_token_key = format!("oauth2_revoked_token:{}", req.token);
    let revoked_data = serde_json::json!({
        "token": req.token,
        "revoked_at": chrono::Utc::now().to_rfc3339(),
        "token_type_hint": req.token_type_hint
    });

    if let Err(e) = state
        .auth_framework
        .storage()
        .store_kv(
            &revoked_token_key,
            serde_json::to_string(&revoked_data)
                .unwrap_or_default()
                .as_bytes(),
            // 30 days: must outlive the longest-lived token type this
            // endpoint can revoke (the refresh token's own 30-day TTL),
            // not just the 7 days an access token's JWT markers need --
            // otherwise a revoked refresh token whose delete somehow
            // failed would become usable again once this marker expired.
            Some(std::time::Duration::from_secs(86400 * 30)),
        )
        .await
    {
        tracing::error!("Failed to store revoked token: {:?}", e);
        return ApiResponse::error_typed("server_error", "Failed to revoke token");
    }

    // If this is a refresh token, delete its storage entry outright so it
    // can no longer be used to mint new access tokens. A no-op (and not an
    // error) if `req.token` isn't a refresh token at all -- the key simply
    // won't exist.
    let refresh_key = format!("oauth2_refresh_token:{}", req.token);
    if let Err(e) = state.auth_framework.storage().delete_kv(&refresh_key).await {
        tracing::warn!("Failed to delete refresh token on revoke: {:?}", e);
    }

    // If the token is a JWT, also store revoked_token:{jti} so the authentication
    // middleware (validate_api_token in api/mod.rs) blocks it on all protected
    // endpoints. Without this step, the revocation would only be visible to the
    // userinfo endpoint, leaving all other authenticated routes unprotected.
    if let Ok(claims) = state
        .auth_framework
        .token_manager()
        .validate_jwt_token(&req.token)
    {
        let now = chrono::Utc::now().timestamp();
        let remaining_secs = (claims.exp - now + 60).max(60) as u64;
        let jti_key = format!("revoked_token:{}", claims.jti);
        if let Err(e) = state
            .auth_framework
            .storage()
            .store_kv(
                &jti_key,
                b"1",
                Some(std::time::Duration::from_secs(remaining_secs)),
            )
            .await
        {
            tracing::warn!("Failed to store JWT JTI revocation entry: {:?}", e);
        } else {
            tracing::info!("JWT token revoked via jti: {}", claims.jti);
        }
    }

    tracing::info!(
        "OAuth2 token revoked: {}",
        &req.token[..10.min(req.token.len())]
    );

    ApiResponse::success(serde_json::json!({
        "message": "Token revoked successfully"
    }))
}

/// GET /api/v1/oauth/userinfo — return claims about the authenticated user.
///
/// The caller must supply a valid Bearer access token. If the token has been
/// revoked, an `invalid_token` error is returned. Email is included only
/// when the `email` scope is present in the token.
///
/// # Example
/// ```rust,ignore
/// // GET /api/v1/oauth/userinfo  Authorization: Bearer <token>
/// let resp = userinfo(State(state), headers).await;
/// assert_eq!(resp.data.unwrap().sub, "user-1");
/// ```
pub async fn userinfo(
    State(state): State<ApiState>,
    headers: HeaderMap,
) -> ApiResponse<UserInfoResponse> {
    // Extract and validate access token
    let token = match extract_bearer_token(&headers) {
        Some(t) => t,
        None => {
            return ApiResponse::error_typed("invalid_token", "Authorization header required");
        }
    };

    // Check if token is revoked first
    let revoked_token_key = format!("oauth2_revoked_token:{}", token);
    if let Ok(Some(_)) = state
        .auth_framework
        .storage()
        .get_kv(&revoked_token_key)
        .await
    {
        return ApiResponse::error_typed("invalid_token", "Token has been revoked");
    }

    // Validate the access token
    let claims = match state.auth_framework.validate_delegated_jwt(&token).await {
        Ok(c) => c,
        Err(_) => {
            return ApiResponse::error_typed("invalid_token", "Access token is invalid");
        }
    };

    // Get user profile
    let user_profile = match state.auth_framework.get_user_profile(&claims.sub).await {
        Ok(profile) => profile,
        Err(e) => {
            tracing::error!("Failed to get user profile: {:?}", e);
            return ApiResponse::error_typed("server_error", "Failed to retrieve user information");
        }
    };

    let userinfo = UserInfoResponse {
        sub: claims.sub.clone(),
        name: user_profile.username.clone(),
        // Only include email if the token's scopes include "email"
        email: if claims.scope.split_whitespace().any(|s| s == "email") {
            user_profile.email.clone()
        } else {
            None
        },
        picture: user_profile.picture.clone(),
        updated_at: Some(chrono::Utc::now().timestamp()),
    };

    tracing::info!("OAuth2 UserInfo requested for user: {}", claims.sub);
    ApiResponse::success(userinfo)
}

/// GET /oauth/clients/{client_id} — return the stored metadata for a
/// registered OAuth 2.0 client.
///
/// # Example
/// ```rust,ignore
/// let resp = get_client_info(State(state), Path("my-client-id".into())).await;
/// ```
pub async fn get_client_info(
    State(state): State<ApiState>,
    Path(client_id): Path<String>,
) -> impl IntoResponse {
    let client_key = format!("oauth2_client:{}", client_id);
    match state.auth_framework.storage().get_kv(&client_key).await {
        Ok(Some(data)) => match serde_json::from_slice::<ClientInfo>(&data) {
            Ok(client) => (
                StatusCode::OK,
                Json(serde_json::json!({ "success": true, "data": client })),
            )
                .into_response(),
            Err(e) => {
                tracing::error!(client_id = %client_id, error = %e, "Failed to deserialize client record");
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(serde_json::json!({
                        "success": false,
                        "error": "server_error",
                        "message": "Failed to read client record"
                    })),
                )
                    .into_response()
            }
        },
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "success": false,
                "error": "invalid_client",
                "message": "Unknown client_id"
            })),
        )
            .into_response(),
        Err(e) => {
            tracing::error!(client_id = %client_id, error = %e, "Storage error looking up client");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({
                    "success": false,
                    "error": "server_error",
                    "message": "Authorization server error"
                })),
            )
                .into_response()
        }
    }
}

// ---------------------------------------------------------------------------
// OpenID Connect Discovery (RFC 8414 / OpenID Connect Discovery 1.0)
// ---------------------------------------------------------------------------

/// OpenID Connect Discovery endpoint (RFC 8414 / OpenID Connect Discovery 1.0).
///
/// Returns server authorization metadata so clients can auto-configure
/// (issuer, endpoints, supported grants, signing algorithms, etc.).
///
/// # Example
/// ```rust,ignore
/// // GET /.well-known/openid-configuration
/// let (status, Json(config)) = openid_configuration(State(state)).await;
/// assert_eq!(status, StatusCode::OK);
/// ```
pub async fn openid_configuration(State(state): State<ApiState>) -> impl IntoResponse {
    let issuer = {
        let configured = state.auth_framework.config().issuer.clone();
        if configured.is_empty() {
            "https://auth.example.com".to_string()
        } else {
            configured
        }
    };

    let config = serde_json::json!({
        "issuer": issuer,
        "authorization_endpoint": format!("{}/api/v1/oauth/authorize", issuer),
        "token_endpoint": format!("{}/api/v1/oauth/token", issuer),
        "userinfo_endpoint": format!("{}/api/v1/oauth/userinfo", issuer),
        "revocation_endpoint": format!("{}/api/v1/oauth/revoke", issuer),
        "introspection_endpoint": format!("{}/api/v1/oauth/introspect", issuer),
        "jwks_uri": format!("{}/api/v1/.well-known/jwks.json", issuer),
        "end_session_endpoint": format!("{}/api/v1/oauth/end_session", issuer),
        "pushed_authorization_request_endpoint": format!("{}/api/v1/oauth/par", issuer),
        "registration_endpoint": format!("{}/api/v1/oauth/register", issuer),
        "response_types_supported": ["code"],
        "grant_types_supported": [
            "authorization_code",
            "refresh_token"
        ],
        "subject_types_supported": ["public"],
        "id_token_signing_alg_values_supported": ["HS256"],
        "token_endpoint_auth_methods_supported": [
            "client_secret_basic",
            "client_secret_post"
        ],
        "code_challenge_methods_supported": ["S256"],
        "scopes_supported": ["openid", "profile", "email"]
    });

    (StatusCode::OK, Json(config))
}

// ---------------------------------------------------------------------------
// JWKS endpoint (RFC 7517)
// ---------------------------------------------------------------------------

/// JSON Web Key Set (JWKS) endpoint ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)).
///
/// Returns the public keys used to verify tokens. Currently returns an
/// empty key set because HS256 (symmetric) signing is used; clients
/// should use the introspection endpoint for token validation.
///
/// # Example
/// ```rust,ignore
/// // GET /.well-known/jwks.json
/// let (status, Json(jwks)) = jwks(State(state)).await;
/// assert!(jwks["keys"].as_array().unwrap().is_empty());
/// ```
pub async fn jwks(State(_state): State<ApiState>) -> impl IntoResponse {
    (StatusCode::OK, Json(serde_json::json!({ "keys": [] })))
}

// ---------------------------------------------------------------------------
// OIDC RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0)
// ---------------------------------------------------------------------------

/// Request parameters for OpenID Connect RP-Initiated Logout.
///
/// # Example
/// ```rust
/// use auth_framework::api::oauth2::EndSessionRequest;
///
/// let req: EndSessionRequest = serde_json::from_str(
///     r#"{"id_token_hint":"eyJ...","state":"xyz"}"#
/// ).unwrap();
/// assert!(req.post_logout_redirect_uri.is_none());
/// ```
#[derive(Debug, Deserialize)]
pub struct EndSessionRequest {
    pub id_token_hint: Option<String>,
    pub post_logout_redirect_uri: Option<String>,
    pub state: Option<String>,
}

/// OIDC RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0).
///
/// Revokes the token from `id_token_hint` (if valid) and, when a
/// registered `post_logout_redirect_uri` is provided, redirects the
/// user-agent there.
///
/// # Example
/// ```rust,ignore
/// // GET /oauth/end_session?id_token_hint=eyJ...&state=xyz
/// let resp = end_session(State(state), Query(params)).await;
/// ```
pub async fn end_session(
    State(state): State<ApiState>,
    Query(params): Query<EndSessionRequest>,
) -> impl IntoResponse {
    // If an id_token_hint is provided, revoke it
    if let Some(ref token) = params.id_token_hint
        && let Ok(claims) = state
            .auth_framework
            .token_manager()
            .validate_jwt_token(token)
    {
        let revoked_key = format!("oauth2_revoked_token:{}", token);
        if let Err(e) = state
            .auth_framework
            .storage()
            .store_kv(
                &revoked_key,
                b"revoked",
                Some(std::time::Duration::from_secs(86400 * 7)),
            )
            .await
        {
            tracing::warn!("Failed to revoke token during OIDC end_session: {}", e);
        }
        // the marker every bearer-token validation path reads
        if let Err(e) = state
            .auth_framework
            .storage()
            .store_kv(
                &format!("revoked_token:{}", claims.jti),
                b"revoked",
                Some(std::time::Duration::from_secs(
                    (claims.exp - chrono::Utc::now().timestamp()).max(60) as u64,
                )),
            )
            .await
        {
            tracing::warn!(
                "Failed to record jti revocation during OIDC end_session: {}",
                e
            );
        }
        tracing::info!("OIDC end_session: revoked token for user {}", claims.sub);
    }

    // Redirect to post_logout_redirect_uri only if it matches a registered URI for the
    // client identified by id_token_hint.  Without this check an attacker could craft a
    // link that redirects users to an arbitrary URL (open redirect / phishing).
    if let Some(ref redirect_uri) = params.post_logout_redirect_uri {
        // Look up the client's registered redirect URIs via the id_token_hint's `azp` or `aud` claim.
        let allowed = if let Some(ref token) = params.id_token_hint {
            // Try to extract client_id from the token (azp > aud)
            let client_id = state
                .auth_framework
                .token_manager()
                .validate_jwt_token(token)
                .ok()
                .and_then(|claims| {
                    // client_id claim identifies the OAuth client
                    if let Some(ref cid) = claims.client_id
                        && !cid.is_empty()
                    {
                        return Some(cid.clone());
                    }
                    // Fallback: aud may contain the client_id
                    if !claims.aud.is_empty() {
                        Some(claims.aud.clone())
                    } else {
                        None
                    }
                });
            if let Some(cid) = client_id {
                let client_key = format!("oauth2_client:{}", cid);
                match state.auth_framework.storage().get_kv(&client_key).await {
                    Ok(Some(data)) => {
                        let client: serde_json::Value =
                            serde_json::from_slice(&data).unwrap_or_default();
                        let uris: Vec<String> = client["redirect_uris"]
                            .as_array()
                            .map(|a| {
                                a.iter()
                                    .filter_map(|v| v.as_str().map(String::from))
                                    .collect()
                            })
                            .unwrap_or_default();
                        uris.iter().any(|r| redirect_uri_matches(redirect_uri, r))
                    }
                    _ => false,
                }
            } else {
                false
            }
        } else {
            false
        };

        if allowed {
            if let Ok(mut parsed) = Url::parse(redirect_uri) {
                if let Some(ref st) = params.state {
                    parsed.query_pairs_mut().append_pair("state", st);
                }
                return Redirect::to(parsed.as_str()).into_response();
            }
        } else {
            tracing::warn!(
                "end_session: post_logout_redirect_uri rejected — not registered for the client"
            );
        }
    }

    // No redirect — return a simple JSON acknowledgement
    (
        StatusCode::OK,
        Json(serde_json::json!({ "status": "logged_out" })),
    )
        .into_response()
}

// ---------------------------------------------------------------------------
// Dynamic Client Registration (RFC 7591)
// ---------------------------------------------------------------------------

/// Dynamic client registration request per [RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591).
///
/// # Example
/// ```rust
/// use auth_framework::api::oauth2::ClientRegistrationRequest;
///
/// let req: ClientRegistrationRequest = serde_json::from_str(
///     r#"{"redirect_uris":["https://example.com/cb"]}"#
/// ).unwrap();
/// assert_eq!(req.redirect_uris.len(), 1);
/// ```
#[derive(Debug, Deserialize)]
pub struct ClientRegistrationRequest {
    pub redirect_uris: Vec<String>,
    #[serde(default)]
    pub client_name: Option<String>,
    #[serde(default)]
    pub token_endpoint_auth_method: Option<String>,
    #[serde(default)]
    pub grant_types: Option<Vec<String>>,
    #[serde(default)]
    pub response_types: Option<Vec<String>>,
    #[serde(default)]
    pub scope: Option<String>,
}

/// POST /oauth/register — dynamically register a new OAuth 2.0 client
/// ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)).
///
/// Requires a valid Bearer token with `admin` role, or an Initial Access
/// Token stored in KV at `oauth2_initial_access_token`. Unauthenticated
/// callers are rejected to prevent resource exhaustion.
///
/// # Example
/// ```rust,ignore
/// let resp = register_client(
///     State(state),
///     headers,   // with Authorization: Bearer <admin-token>
///     Json(ClientRegistrationRequest {
///         redirect_uris: vec!["https://example.com/cb".into()],
///         client_name: Some("My App".into()),
///         ..Default::default()
///     }),
/// ).await;
/// ```
pub async fn register_client(
    State(state): State<ApiState>,
    headers: HeaderMap,
    Json(req): Json<ClientRegistrationRequest>,
) -> impl IntoResponse {
    // RFC 7591 §1.2: require authentication via Bearer token
    let token_str = match extract_bearer_token(&headers) {
        Some(t) => t,
        None => {
            return (
                StatusCode::UNAUTHORIZED,
                Json(serde_json::json!({
                    "error": "invalid_token",
                    "error_description": "A valid Bearer token is required for dynamic client registration"
                })),
            )
                .into_response();
        }
    };

    // Option 1: check if this is the pre-configured Initial Access Token
    let is_initial_access_token = match state
        .auth_framework
        .storage()
        .get_kv("oauth2_initial_access_token")
        .await
    {
        Ok(Some(stored)) => {
            let stored_str = String::from_utf8_lossy(&stored);
            subtle::ConstantTimeEq::ct_eq(token_str.as_bytes(), stored_str.trim().as_bytes()).into()
        }
        _ => false,
    };

    // Option 2: validate as a normal JWT and check for admin role
    let is_admin = if !is_initial_access_token {
        match validate_api_token(&state.auth_framework, &token_str).await {
            Ok(auth_token) => auth_token.roles.contains("admin"),
            Err(_) => false,
        }
    } else {
        false
    };

    if !is_initial_access_token && !is_admin {
        return (
            StatusCode::FORBIDDEN,
            Json(serde_json::json!({
                "error": "insufficient_scope",
                "error_description": "Dynamic client registration requires admin privileges or a valid Initial Access Token"
            })),
        )
            .into_response();
    }
    // Validate all redirect_uris are well-formed URLs with safe schemes
    for uri in &req.redirect_uris {
        match Url::parse(uri) {
            Ok(parsed) => {
                match parsed.scheme() {
                    "https" => {}
                    "http" => {
                        // Allow plain HTTP only for loopback addresses (development)
                        if !matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")) {
                            return (
                                StatusCode::BAD_REQUEST,
                                Json(serde_json::json!({
                                    "error": "invalid_redirect_uri",
                                    "error_description": format!("Non-loopback HTTP redirect_uri not allowed: {}", uri)
                                })),
                            )
                                .into_response();
                        }
                    }
                    scheme => {
                        return (
                            StatusCode::BAD_REQUEST,
                            Json(serde_json::json!({
                                "error": "invalid_redirect_uri",
                                "error_description": format!("Disallowed URI scheme '{}' in redirect_uri: {}", scheme, uri)
                            })),
                        )
                            .into_response();
                    }
                }
            }
            Err(_) => {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(serde_json::json!({
                        "error": "invalid_redirect_uri",
                        "error_description": format!("Invalid redirect_uri: {}", uri)
                    })),
                )
                    .into_response();
            }
        }
    }

    if req.redirect_uris.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({
                "error": "invalid_client_metadata",
                "error_description": "At least one redirect_uri is required"
            })),
        )
            .into_response();
    }

    let client_id = Uuid::new_v4().to_string();
    let client_secret = Uuid::new_v4().to_string();

    let client_data = serde_json::json!({
        "client_id": client_id,
        "client_secret": client_secret,
        "client_name": req.client_name,
        "redirect_uris": req.redirect_uris,
        "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
        "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
        "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
        "scope": req.scope.as_deref().unwrap_or("openid"),
    });

    let key = format!("oauth2_client:{}", client_id);
    if let Err(e) = state
        .auth_framework
        .storage()
        .store_kv(&key, client_data.to_string().as_bytes(), None)
        .await
    {
        tracing::error!("Failed to store client registration: {}", e);
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({
                "error": "server_error",
                "error_description": "Failed to register client"
            })),
        )
            .into_response();
    }

    tracing::info!("Dynamic client registered: client_id={}", client_id);

    (
        StatusCode::CREATED,
        Json(serde_json::json!({
            "client_id": client_id,
            "client_secret": client_secret,
            "client_name": req.client_name,
            "redirect_uris": req.redirect_uris,
            "token_endpoint_auth_method": req.token_endpoint_auth_method.as_deref().unwrap_or("client_secret_basic"),
            "grant_types": req.grant_types.as_deref().unwrap_or(&["authorization_code".to_string()]),
            "response_types": req.response_types.as_deref().unwrap_or(&["code".to_string()]),
            "scope": req.scope.as_deref().unwrap_or("openid"),
        })),
    )
        .into_response()
}

// ---------------------------------------------------------------------------
// /users/me — alias for the authenticated user's profile
// ---------------------------------------------------------------------------

/// GET /users/me — returns the authenticated user's profile.
///
/// Convenience alias that delegates to [`userinfo`].
///
/// # Example
/// ```rust,ignore
/// // GET /users/me  Authorization: Bearer <token>
/// let resp = users_me(state, headers).await;
/// ```
pub async fn users_me(state: State<ApiState>, headers: HeaderMap) -> impl IntoResponse {
    // Delegate to the existing userinfo handler
    userinfo(state, headers).await
}