issuerd-server 0.1.3

HTTP server bootstrap, middleware, TLS and OIDC endpoints for the Issuerd IAM server
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
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2026 Dmitry Andreev. <da@issuerd.org>
//
// Account console REST API: profile, credentials, sessions, consents, and linked accounts.

use std::sync::Arc;
use std::time::Duration;

use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use issuerd_auth_flow::{
    built_in::{federated_password_provider, set_user_password, verify_password_hash},
    totp,
};
use issuerd_core::{
    typestate::{AccountSessionGuard, RealmBound},
    BrokerIdpSettings, ClientIdentifier, Credential, CredentialId, CredentialType, DisplayName,
    Email, IssuerdError, Pagination, PasswordPolicyError, Realm, RealmId, SessionId, User, UserId,
    Username, ACTION_TOKEN_PURPOSE_BROKER_LINK,
};
use issuerd_token::action_tokens::{action_token_claims, issue_action_token};
use tracing::{debug, error, instrument, warn};

use super::required_actions::send_verification_email;
use crate::{
    middleware::{proxy_ip::ClientIp, realm::ResolvedRealm},
    state::ServerState,
};

#[derive(Debug, serde::Serialize, utoipa::ToSchema)]
pub struct AccountMeResponse {
    pub id: String,
    pub username: String,
    pub email: Option<String>,
    pub first_name: Option<String>,
    pub last_name: Option<String>,
    pub email_verified: bool,
    pub enabled: bool,
    pub roles: Vec<String>,
}

#[derive(Debug, serde::Serialize, utoipa::ToSchema)]
pub struct AccountSession {
    pub id: String,
    pub ip_address: String,
    pub started: String,
    pub last_session_refresh: String,
    pub clients: Vec<String>,
}

/// Serde helper for tri-state optional fields: absent = `None` (leave
/// unchanged), explicit `null` = `Some(None)` (clear), value = `Some(Some(v))`.
/// With `#[serde(default)]` the function runs only when the field is present.
mod double_option {
    use serde::{Deserialize, Deserializer};

    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
    where
        D: Deserializer<'de>,
        T: Deserialize<'de>,
    {
        Ok(Some(Option::<T>::deserialize(deserializer)?))
    }
}

/// Profile update body: a field that is absent stays unchanged, an explicit
/// `null` clears it (first/last name and email only โ€” username is never
/// cleared).
#[derive(Debug, serde::Deserialize, utoipa::ToSchema)]
pub struct UpdateMeRequest {
    #[serde(default, deserialize_with = "double_option::deserialize")]
    pub first_name: Option<Option<String>>,
    #[serde(default, deserialize_with = "double_option::deserialize")]
    pub last_name: Option<Option<String>>,
    #[serde(default, deserialize_with = "double_option::deserialize")]
    pub email: Option<Option<String>>,
    #[serde(default)]
    pub username: Option<String>,
}

#[derive(Debug, serde::Deserialize, utoipa::ToSchema)]
pub struct ChangePasswordRequest {
    pub current_password: String,
    pub new_password: String,
}

/// Response of the TOTP enrollment start endpoint: the base32 secret, the
/// `otpauth://` provisioning URI, and the same URI rendered as an inline SVG
/// QR code (generated locally โ€” the secret never leaves the server).
#[derive(Debug, serde::Serialize, utoipa::ToSchema)]
pub struct TotpStartResponse {
    pub secret: String,
    #[serde(rename = "otpauthUrl")]
    pub otpauth_url: String,
    #[serde(rename = "qrSvg")]
    pub qr_svg: String,
}

#[derive(Debug, serde::Deserialize, utoipa::ToSchema)]
pub struct TotpVerifyRequest {
    pub code: String,
}

#[derive(Debug, serde::Serialize, utoipa::ToSchema)]
pub struct AccountCredentialsResponse {
    pub password: bool,
    pub totp: bool,
    pub webauthn: bool,
}

#[derive(Debug, serde::Serialize, utoipa::ToSchema)]
pub struct AccountConsentResponse {
    pub client_id: String,
    pub granted_scopes: Vec<String>,
    pub created_at: String,
    pub last_updated_at: String,
}

#[utoipa::path(
    get,
    path = "/realms/{realm}/account/api/me",
    tag = "Account",
    summary = "Get the authenticated user's profile",
    operation_id = "account_get_me",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    responses(
        (status = 200, description = "Account profile", body = AccountMeResponse),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers))]
pub async fn account_me_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    let user = match load_user(&state, &guard).await {
        Ok(u) => u,
        Err(resp) => return resp,
    };
    match build_me_response(&state, &guard.realm_id, &user).await {
        Ok(me) => Json(me).into_response(),
        Err(resp) => resp,
    }
}

#[utoipa::path(
    get,
    path = "/realms/{realm}/account/api/sessions",
    tag = "Account",
    summary = "List the authenticated user's sessions",
    operation_id = "account_list_sessions",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    responses(
        (status = 200, description = "Active sessions", body = Vec<AccountSession>),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers))]
pub async fn account_sessions_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    let sessions = match state
        .storage
        .list_sessions(&guard.realm_id, Some(guard.user_id), &Pagination::default())
        .await
    {
        Ok(s) => s,
        Err(_) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({"error": "failed to list sessions"})),
            )
                .into_response()
        }
    };

    let result: Vec<AccountSession> = sessions
        .into_iter()
        .map(|s| AccountSession {
            id: s.id.0,
            ip_address: s.ip_address.to_string(),
            started: s.started.to_rfc3339(),
            last_session_refresh: s.last_session_refresh.to_rfc3339(),
            clients: s.clients.into_iter().map(|c| c.client_id.0).collect(),
        })
        .collect();

    Json(result).into_response()
}

#[utoipa::path(
    post,
    path = "/realms/{realm}/account/api/sessions/{id}/logout",
    tag = "Account",
    summary = "Log out (delete) one of the user's own sessions",
    operation_id = "account_logout_session",
    params(
        ("realm" = String, Path, description = "Realm name"),
        ("id" = String, Path, description = "Session or credential id"),
    ),
    responses(
        (status = 204, description = "Session deleted (idempotent)"),
        (status = 400, description = "Bad request", body = crate::openapi::AccountErrorResponse),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers, _realm, session_id))]
pub async fn account_logout_session_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
    // The realm segment is resolved by middleware; only the session id is used.
    Path((_realm, session_id)): Path<(String, String)>,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    let sid = match SessionId::new(session_id.clone()) {
        Ok(id) => id,
        Err(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": "invalid session id"})),
            )
                .into_response()
        }
    };

    // Verify the session belongs to the current user. A storage error must
    // fail closed: skipping the ownership check would let a caller delete
    // another user's session during a backend outage (P3-15).
    let session = match state.storage.get_user_session(&guard.realm_id, &sid).await {
        Ok(Some(session)) => {
            if session.user_id != guard.user_id {
                return (
                    StatusCode::FORBIDDEN,
                    Json(serde_json::json!({"error": "cannot logout another user's session"})),
                )
                    .into_response();
            }
            session
        }
        Ok(None) => {
            // Already gone โ€” logout is idempotent, nothing to delete.
            return StatusCode::NO_CONTENT.into_response();
        }
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account logout: failed to load session");
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({"error": "failed to load session"})),
            )
                .into_response();
        }
    };

    if let Err(e) = state.storage.delete_user_session(&guard.realm_id, &sid).await {
        error!(realm = %guard.realm_id, error = %e, "account logout: failed to delete session");
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({"error": "failed to delete session"})),
        )
            .into_response();
    }
    crate::session_cache::invalidate_session(&state, &guard.realm_id, &sid).await;
    // Back-channel logout: notify clients with a `backchannel_logout_uri`
    // (fire-and-forget).
    if let Ok(Some(realm)) = state.storage.get_realm(&guard.realm_id).await {
        state.logout_notifier.notify_session_destroyed(&realm, &session).await;
    }
    StatusCode::NO_CONTENT.into_response()
}

#[utoipa::path(
    put,
    path = "/realms/{realm}/account/api/me",
    tag = "Account",
    summary = "Update the authenticated user's profile",
    operation_id = "account_update_me",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    request_body = UpdateMeRequest,
    responses(
        (status = 200, description = "Updated account profile", body = AccountMeResponse),
        (status = 400, description = "Bad request", body = crate::openapi::AccountErrorResponse),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers, body))]
pub async fn account_update_me_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
    Json(body): Json<UpdateMeRequest>,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };
    let realm_model = match load_realm(&state, &guard).await {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let mut user = match load_user(&state, &guard).await {
        Ok(u) => u,
        Err(resp) => return resp,
    };

    // Resending the current username is a no-op, not a change attempt.
    if let Some(new_username) = body.username {
        if new_username != user.username.as_str() {
            if !realm_model.edit_username_allowed {
                return bad_request("username changes are not allowed in this realm");
            }
            match Username::new(new_username) {
                Ok(username) => user.username = username,
                Err(e) => return bad_request(&e.to_string()),
            }
        }
    }

    if let Some(first_name) = body.first_name {
        match parse_optional_name(first_name) {
            Ok(name) => user.first_name = name,
            Err(msg) => return bad_request(&msg),
        }
    }
    if let Some(last_name) = body.last_name {
        match parse_optional_name(last_name) {
            Ok(name) => user.last_name = name,
            Err(msg) => return bad_request(&msg),
        }
    }

    let mut send_verification = false;
    if let Some(email) = body.email {
        match apply_email_change(&state, &guard, &realm_model, &mut user, email).await {
            Ok(v) => send_verification = v,
            Err(resp) => return resp,
        }
    }

    if let Err(e) = state.storage.update_user(&guard.realm_id, &user).await {
        // Username uniqueness on rename is enforced by the storage backend.
        if matches!(e, IssuerdError::Conflict)
            || matches!(&e, IssuerdError::InvalidRequest(m) if m.contains("username already exists"))
        {
            return bad_request("username already in use");
        }
        error!(realm = %guard.realm_id, error = %e, "account update me: failed to update user");
        return internal_error("failed to update user");
    }
    issuerd_cluster::invalidate::invalidate_user_claims(
        state.cache.as_ref(),
        &guard.realm_id,
        &user.id,
    )
    .await;

    // Deliver after persisting so the VERIFY_EMAIL assignment survives a
    // delivery failure (the user can retrigger it from the login flow).
    if send_verification {
        if let Err(e) = send_verification_email(
            &state,
            &realm_model,
            realm_model.name.as_ref(),
            &user,
            None,
            None,
        )
        .await
        {
            error!(realm = %guard.realm_id, error = %e, "account update me: verification email failed");
        }
    }

    match build_me_response(&state, &guard.realm_id, &user).await {
        Ok(me) => Json(me).into_response(),
        Err(resp) => resp,
    }
}

#[utoipa::path(
    post,
    path = "/realms/{realm}/account/api/credentials/password",
    tag = "Account",
    summary = "Change the account password (verifies the current one, enforces the realm policy)",
    operation_id = "account_change_password",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    request_body = ChangePasswordRequest,
    responses(
        (status = 204, description = "Password changed"),
        (status = 400, description = "Bad request", body = crate::openapi::AccountErrorResponse),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers, body, ip))]
pub async fn account_change_password_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    axum::extract::Extension(ClientIp(ip)): axum::extract::Extension<ClientIp>,
    headers: axum::http::HeaderMap,
    Json(body): Json<ChangePasswordRequest>,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };
    let realm_model = match load_realm(&state, &guard).await {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let user = match load_user(&state, &guard).await {
        Ok(u) => u,
        Err(resp) => return resp,
    };

    // Federated user with a live provider: the external directory is the
    // source of truth for both the current-password check and the write.
    let federation = match federated_password_provider(
        state.storage.as_ref(),
        state.federation_manager.as_ref(),
        &guard.realm_id,
        &guard.user_id,
    )
    .await
    {
        Ok(v) => v,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account change password: federation lookup failed");
            return internal_error("failed to resolve federation provider");
        }
    };
    if let Some((provider, username)) = federation {
        let current_ok = match provider.validate_password(&username, &body.current_password).await {
            Ok(v) => v,
            Err(e) => {
                error!(realm = %guard.realm_id, error = %e, "account change password: federation validation failed");
                return internal_error("failed to verify current password");
            }
        };
        if !current_ok {
            warn!(realm = %guard.realm_id, username = %issuerd_core::utils::sanitize_log_str(user.username.as_str()), ip = %ip, "account change password: wrong current password");
            return bad_request("current password is incorrect");
        }
        if let Err(policy_err) = realm_model.password_policy.validate(&body.new_password, &user) {
            return policy_error_response(policy_err);
        }
        return match provider.update_password(&username, &body.new_password).await {
            Ok(()) => {
                // Drop stale local credentials: login only consults them when
                // the provider errors, where they would act as a dormant
                // fallback password.
                match state
                    .storage
                    .get_credentials(&guard.realm_id, &guard.user_id, CredentialType::Password)
                    .await
                {
                    Ok(stale) => {
                        for cred in stale {
                            if let Err(e) = state
                                .storage
                                .delete_credential(&guard.realm_id, &guard.user_id, &cred.id)
                                .await
                            {
                                warn!(realm = %guard.realm_id, error = %e, "account change password: stale credential cleanup failed");
                            }
                        }
                    }
                    Err(e) => {
                        warn!(realm = %guard.realm_id, error = %e, "account change password: stale credential cleanup failed");
                    }
                }
                StatusCode::NO_CONTENT.into_response()
            }
            Err(issuerd_core::FederationError::NotSupported) => bad_request(
                "the external directory for this account does not accept password changes",
            ),
            Err(e) => {
                error!(realm = %guard.realm_id, error = %e, "account change password: directory write failed");
                internal_error("failed to update password")
            }
        };
    }

    let credentials = match state
        .storage
        .get_credentials(&guard.realm_id, &guard.user_id, CredentialType::Password)
        .await
    {
        Ok(c) => c,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account change password: load failed");
            return internal_error("failed to load credentials");
        }
    };
    // Identical message whether the account has no password credential or the
    // current password does not match โ€” the response must not reveal which.
    let current_ok = credentials.iter().any(|c| verify_password_hash(&body.current_password, c));
    if !current_ok {
        warn!(realm = %guard.realm_id, username = %issuerd_core::utils::sanitize_log_str(user.username.as_str()), ip = %ip, "account change password: wrong current password");
        return bad_request("current password is incorrect");
    }

    // Policy gate before any stored credential is touched.
    if let Err(policy_err) = realm_model.password_policy.validate(&body.new_password, &user) {
        return policy_error_response(policy_err);
    }

    match set_user_password(
        state.storage.as_ref(),
        &guard.realm_id,
        &guard.user_id,
        &body.new_password,
        realm_model.password_policy.history_size,
        false,
    )
    .await
    {
        Ok(()) => StatusCode::NO_CONTENT.into_response(),
        Err(e) => {
            let msg = e.to_string();
            // set_user_password enforces password history; a reuse rejection
            // surfaces in the same 400 + policyViolations shape.
            if msg.contains("password_history") {
                let violations = vec![issuerd_core::PasswordPolicyViolation {
                    code: "password_history".to_string(),
                    message: msg.clone(),
                }];
                return (
                    StatusCode::BAD_REQUEST,
                    Json(serde_json::json!({"error": msg, "policyViolations": violations})),
                )
                    .into_response();
            }
            error!(realm = %guard.realm_id, error = %e, "account change password: failed");
            internal_error("failed to update password")
        }
    }
}

/// Cache TTL for a pending TOTP enrollment secret.
const TOTP_ENROLL_TTL_SECS: u64 = 600;

/// Cache key holding a user's not-yet-verified enrollment secret.
fn totp_enrollment_key(realm_id: &RealmId, user_id: &UserId) -> String {
    format!("totp-enroll:{realm_id}:{user_id}")
}

#[utoipa::path(
    post,
    path = "/realms/{realm}/account/api/credentials/totp/start",
    tag = "Account",
    summary = "Start TOTP enrollment (returns secret + otpauth URL + QR SVG)",
    operation_id = "account_totp_start",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    responses(
        (status = 200, description = "Pending enrollment", body = TotpStartResponse),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers))]
pub async fn account_totp_start_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };
    let realm_model = match load_realm(&state, &guard).await {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let user = match load_user(&state, &guard).await {
        Ok(u) => u,
        Err(resp) => return resp,
    };

    let secret = totp::generate_secret();
    let key = totp_enrollment_key(&guard.realm_id, &guard.user_id);
    if let Err(e) = state
        .cache
        .set(
            &key,
            secret.clone().into_bytes(),
            Some(Duration::from_secs(TOTP_ENROLL_TTL_SECS)),
        )
        .await
    {
        error!(realm = %guard.realm_id, error = %e, "account TOTP start: cache write failed");
        return internal_error("failed to start authenticator enrollment");
    }

    let issuer = realm_model
        .display_name
        .as_ref()
        .map(|d| d.as_str())
        .unwrap_or(realm_model.name.as_str());
    let otpauth_url =
        totp::otpauth_url(issuer, user.username.as_str(), &secret, &realm_model.otp_policy);
    let qr_svg = match crate::qr::qr_svg(&otpauth_url) {
        Ok(svg) => svg,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account TOTP start: QR render failed");
            return internal_error("failed to render QR code");
        }
    };

    Json(TotpStartResponse {
        secret,
        otpauth_url,
        qr_svg,
    })
    .into_response()
}

#[utoipa::path(
    post,
    path = "/realms/{realm}/account/api/credentials/totp/verify",
    tag = "Account",
    summary = "Verify a TOTP code and persist the authenticator credential",
    operation_id = "account_totp_verify",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    request_body = TotpVerifyRequest,
    responses(
        (status = 204, description = "TOTP credential created"),
        (status = 400, description = "Bad request", body = crate::openapi::AccountErrorResponse),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers, body))]
pub async fn account_totp_verify_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
    Json(body): Json<TotpVerifyRequest>,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };
    let realm_model = match load_realm(&state, &guard).await {
        Ok(r) => r,
        Err(resp) => return resp,
    };

    let key = totp_enrollment_key(&guard.realm_id, &guard.user_id);
    // A wrong code must NOT consume the pending secret โ€” the user may simply
    // have mistyped, and deleting here would force a restart of enrollment.
    let secret = match state.cache.get(&key).await {
        Ok(Some(bytes)) => match String::from_utf8(bytes) {
            Ok(s) => s,
            Err(_) => return internal_error("corrupt enrollment state"),
        },
        Ok(None) => return bad_request("enrollment not started or expired"),
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account TOTP verify: cache read failed");
            return internal_error("failed to load enrollment state");
        }
    };

    let now = issuerd_core::utils::now_secs();
    let Some(matched_step) = totp::verify(&secret, &body.code, now, &realm_model.otp_policy, None)
    else {
        return bad_request("invalid code");
    };

    let cred = Credential {
        id: CredentialId::new(issuerd_core::utils::generate_id()).unwrap(),
        credential_type: CredentialType::Totp,
        user_label: None,
        created_date: chrono::Utc::now(),
        secret_data: secret.into_bytes(),
        credential_data: serde_json::json!({
            "algorithm": realm_model.otp_policy.algorithm,
            "digits": realm_model.otp_policy.digits,
            "period": realm_model.otp_policy.period_secs,
            "last_used_step": matched_step,
        }),
        priority: 0,
    };
    if let Err(e) = state.storage.create_credential(&guard.realm_id, &guard.user_id, &cred).await {
        error!(realm = %guard.realm_id, error = %e, "account TOTP verify: store failed");
        return internal_error("failed to store authenticator");
    }
    // Enrollment consumed โ€” clear the pending secret. A cleanup failure is
    // harmless (the entry expires on its own), so only log it.
    if let Err(e) = state.cache.delete(&key).await {
        warn!(realm = %guard.realm_id, error = %e, "account TOTP verify: cleanup failed");
    }
    StatusCode::NO_CONTENT.into_response()
}

#[utoipa::path(
    delete,
    path = "/realms/{realm}/account/api/credentials/totp",
    tag = "Account",
    summary = "Delete the account's TOTP credential",
    operation_id = "account_totp_delete",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    responses(
        (status = 204, description = "TOTP credential deleted (idempotent)"),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers))]
pub async fn account_totp_delete_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    // Idempotent: 204 whether or not a TOTP credential existed.
    let credentials = match state
        .storage
        .get_credentials(&guard.realm_id, &guard.user_id, CredentialType::Totp)
        .await
    {
        Ok(c) => c,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account TOTP delete: load failed");
            return internal_error("failed to load credentials");
        }
    };
    for cred in credentials {
        if let Err(e) =
            state.storage.delete_credential(&guard.realm_id, &guard.user_id, &cred.id).await
        {
            error!(realm = %guard.realm_id, error = %e, "account TOTP delete: failed");
            return internal_error("failed to delete authenticator");
        }
    }
    StatusCode::NO_CONTENT.into_response()
}

// --- WebAuthn / passkey management -----------------------------------------

/// Cache TTL for an in-flight passkey registration ceremony.
const WEBAUTHN_REG_TTL_SECS: u64 = 600;

/// Cache key holding a user's in-flight passkey registration state.
fn webauthn_registration_key(realm_id: &RealmId, user_id: &UserId) -> String {
    format!("webauthn-reg:{realm_id}:{user_id}")
}

#[derive(Debug, serde::Deserialize, utoipa::ToSchema)]
pub struct WebAuthnRegisterFinishRequest {
    /// Optional user-facing label ("Work laptop") stored on the credential.
    #[serde(default)]
    pub label: Option<String>,
    /// The serialized `PublicKeyCredential` produced by the browser ceremony.
    pub credential: serde_json::Value,
}

#[derive(Debug, serde::Serialize, utoipa::ToSchema)]
pub struct AccountPasskeyResponse {
    pub id: String,
    pub label: String,
    #[serde(rename = "createdAt")]
    pub created_at: String,
}

/// Build the relying-party instance for the configured issuer, logging and
/// returning `None` on failure. The issuer is validated at boot, so a failure
/// here indicates a configuration regression.
fn webauthn_rp(state: &ServerState, realm: &Realm) -> Option<webauthn_rs::prelude::Webauthn> {
    let (rp_id, rp_origin) =
        match issuerd_auth_flow::webauthn::relying_party_from_issuer(&state.config.issuer_url) {
            Ok(v) => v,
            Err(e) => {
                error!(error = %e, "account WebAuthn: invalid relying-party configuration");
                return None;
            }
        };
    let rp_name = realm.display_name.as_ref().map(|d| d.as_str()).unwrap_or(realm.name.as_str());
    match issuerd_auth_flow::webauthn::build_webauthn(&rp_id, &rp_origin, rp_name) {
        Ok(w) => Some(w),
        Err(e) => {
            error!(error = %e, "account WebAuthn: failed to build relying party");
            None
        }
    }
}

/// Ceremony display name: "First Last" when present, else the username.
fn passkey_display_name(user: &User) -> String {
    match (&user.first_name, &user.last_name) {
        (Some(first), Some(last)) => format!("{first} {last}"),
        (Some(first), None) => first.to_string(),
        (None, Some(last)) => last.to_string(),
        (None, None) => user.username.to_string(),
    }
}

#[utoipa::path(
    post,
    path = "/realms/{realm}/account/api/webauthn/register/start",
    tag = "Account",
    summary = "Start a passkey registration ceremony",
    operation_id = "account_webauthn_register_start",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    responses(
        (status = 200, description = "WebAuthn creation options (PublicKeyCredentialCreationOptions JSON)", body = serde_json::Value),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers))]
pub async fn account_webauthn_register_start_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };
    let realm_model = match load_realm(&state, &guard).await {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let user = match load_user(&state, &guard).await {
        Ok(u) => u,
        Err(resp) => return resp,
    };
    let Some(webauthn) = webauthn_rp(&state, &realm_model) else {
        return internal_error("invalid relying-party configuration");
    };

    // Exclude already-registered passkeys so the browser refuses duplicates.
    let existing = match state
        .storage
        .get_credentials(&guard.realm_id, &guard.user_id, CredentialType::WebAuthn)
        .await
    {
        Ok(c) => c,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account WebAuthn start: load failed");
            return internal_error("failed to load credentials");
        }
    };
    let mut exclude = Vec::with_capacity(existing.len());
    for cred in &existing {
        match issuerd_auth_flow::webauthn::passkey_from_bytes(&cred.secret_data) {
            Ok(passkey) => exclude.push(passkey.cred_id().clone()),
            Err(e) => {
                warn!(realm = %guard.realm_id, error = %e, "account WebAuthn start: skipping undecodable passkey");
            }
        }
    }

    let display_name = passkey_display_name(&user);
    let (ccr, reg_state) = match webauthn.start_passkey_registration(
        issuerd_auth_flow::webauthn::user_handle(&guard.user_id),
        user.username.as_str(),
        &display_name,
        Some(exclude),
    ) {
        Ok(v) => v,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account WebAuthn start: ceremony init failed");
            return internal_error("failed to start passkey registration");
        }
    };

    let state_bytes = match serde_json::to_vec(&reg_state) {
        Ok(b) => b,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account WebAuthn start: state serialization failed");
            return internal_error("failed to start passkey registration");
        }
    };
    let key = webauthn_registration_key(&guard.realm_id, &guard.user_id);
    if let Err(e) = state
        .cache
        .set(&key, state_bytes, Some(Duration::from_secs(WEBAUTHN_REG_TTL_SECS)))
        .await
    {
        error!(realm = %guard.realm_id, error = %e, "account WebAuthn start: cache write failed");
        return internal_error("failed to start passkey registration");
    }

    Json(ccr.public_key).into_response()
}

#[utoipa::path(
    post,
    path = "/realms/{realm}/account/api/webauthn/register/finish",
    tag = "Account",
    summary = "Finish a passkey registration ceremony and store the credential",
    operation_id = "account_webauthn_register_finish",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    request_body = WebAuthnRegisterFinishRequest,
    responses(
        (status = 204, description = "Passkey registered"),
        (status = 400, description = "Bad request", body = crate::openapi::AccountErrorResponse),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers, body))]
pub async fn account_webauthn_register_finish_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
    Json(body): Json<WebAuthnRegisterFinishRequest>,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };
    let realm_model = match load_realm(&state, &guard).await {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let Some(webauthn) = webauthn_rp(&state, &realm_model) else {
        return internal_error("invalid relying-party configuration");
    };

    let key = webauthn_registration_key(&guard.realm_id, &guard.user_id);
    // A failed finish keeps the pending state: the user may retry the
    // ceremony (e.g. after cancelling the browser prompt) until the TTL
    // expires.
    let state_bytes = match state.cache.get(&key).await {
        Ok(Some(b)) => b,
        Ok(None) => return bad_request("registration not started or expired"),
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account WebAuthn finish: cache read failed");
            return internal_error("failed to load registration state");
        }
    };
    let reg_state: webauthn_rs::prelude::PasskeyRegistration = match serde_json::from_slice(
        &state_bytes,
    ) {
        Ok(s) => s,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account WebAuthn finish: corrupt state");
            return internal_error("corrupt registration state");
        }
    };
    let credential: webauthn_rs::prelude::RegisterPublicKeyCredential =
        match serde_json::from_value(body.credential) {
            Ok(c) => c,
            Err(_) => return bad_request("malformed credential"),
        };
    let passkey = match webauthn.finish_passkey_registration(&credential, &reg_state) {
        Ok(p) => p,
        Err(e) => {
            warn!(realm = %guard.realm_id, error = %e, "account WebAuthn finish: passkey verification failed");
            return bad_request("passkey verification failed");
        }
    };

    let label = body
        .label
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string);
    let secret_data = match issuerd_auth_flow::webauthn::passkey_to_bytes(&passkey) {
        Ok(b) => b,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account WebAuthn finish: serialization failed");
            return internal_error("failed to store passkey");
        }
    };
    let cred = Credential {
        id: CredentialId::new(issuerd_core::utils::generate_id()).unwrap(),
        credential_type: CredentialType::WebAuthn,
        user_label: label,
        created_date: chrono::Utc::now(),
        secret_data,
        credential_data: serde_json::json!({
            "cred_id": base64::Engine::encode(
                &base64::engine::general_purpose::URL_SAFE_NO_PAD,
                &**passkey.cred_id(),
            ),
        }),
        priority: 0,
    };
    if let Err(e) = state.storage.create_credential(&guard.realm_id, &guard.user_id, &cred).await {
        error!(realm = %guard.realm_id, error = %e, "account WebAuthn finish: store failed");
        return internal_error("failed to store passkey");
    }
    // Registration consumed โ€” clear the pending state. A cleanup failure is
    // harmless (the entry expires on its own), so only log it.
    if let Err(e) = state.cache.delete(&key).await {
        warn!(realm = %guard.realm_id, error = %e, "account WebAuthn finish: cleanup failed");
    }
    StatusCode::NO_CONTENT.into_response()
}

#[utoipa::path(
    get,
    path = "/realms/{realm}/account/api/webauthn/credentials",
    tag = "Account",
    summary = "List the account's registered passkeys",
    operation_id = "account_webauthn_list_credentials",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    responses(
        (status = 200, description = "Registered passkeys", body = Vec<AccountPasskeyResponse>),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers))]
pub async fn account_webauthn_credentials_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    let credentials = match state
        .storage
        .get_credentials(&guard.realm_id, &guard.user_id, CredentialType::WebAuthn)
        .await
    {
        Ok(c) => c,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account WebAuthn list: load failed");
            return internal_error("failed to load credentials");
        }
    };
    let result: Vec<AccountPasskeyResponse> = credentials
        .iter()
        .map(|cred| AccountPasskeyResponse {
            id: cred.id.0.clone(),
            label: cred.user_label.clone().unwrap_or_default(),
            created_at: cred.created_date.to_rfc3339(),
        })
        .collect();
    Json(result).into_response()
}

#[utoipa::path(
    delete,
    path = "/realms/{realm}/account/api/webauthn/credentials/{id}",
    tag = "Account",
    summary = "Delete one of the account's passkeys",
    operation_id = "account_webauthn_delete_credential",
    params(
        ("realm" = String, Path, description = "Realm name"),
        ("id" = String, Path, description = "Session or credential id"),
    ),
    responses(
        (status = 204, description = "Passkey deleted (idempotent; only WebAuthn credentials are deletable)"),
        (status = 400, description = "Bad request", body = crate::openapi::AccountErrorResponse),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers, _realm, credential_id))]
pub async fn account_webauthn_delete_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
    // The realm segment is resolved by middleware; only the credential id is used.
    Path((_realm, credential_id)): Path<(String, String)>,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    let cred_id = match CredentialId::new(credential_id) {
        Ok(id) => id,
        Err(e) => return bad_request(&e.to_string()),
    };
    let credentials = match state
        .storage
        .get_credentials(&guard.realm_id, &guard.user_id, CredentialType::WebAuthn)
        .await
    {
        Ok(c) => c,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account WebAuthn delete: load failed");
            return internal_error("failed to load credentials");
        }
    };
    // Only WebAuthn credentials of this user are deletable through this
    // endpoint; anything else (including unknown ids) is an idempotent 204.
    if let Some(cred) = credentials.iter().find(|c| c.id == cred_id) {
        if let Err(e) =
            state.storage.delete_credential(&guard.realm_id, &guard.user_id, &cred.id).await
        {
            error!(realm = %guard.realm_id, error = %e, "account WebAuthn delete: failed");
            return internal_error("failed to delete passkey");
        }
    }
    StatusCode::NO_CONTENT.into_response()
}

#[utoipa::path(
    get,
    path = "/realms/{realm}/account/api/credentials",
    tag = "Account",
    summary = "Presence flags for the account's enrolled credentials",
    operation_id = "account_get_credentials",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    responses(
        (status = 200, description = "Credential presence flags", body = AccountCredentialsResponse),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers))]
pub async fn account_credentials_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    let password = match has_credential(&state, &guard, CredentialType::Password).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };
    // Federated users keep their password in the external directory; report
    // it as set when the linked provider accepts password writes so the
    // account console offers the change form.
    let password = if password {
        true
    } else {
        matches!(
            federated_password_provider(
                state.storage.as_ref(),
                state.federation_manager.as_ref(),
                &guard.realm_id,
                &guard.user_id,
            )
            .await,
            Ok(Some((provider, _))) if provider.supports_password_update()
        )
    };
    let totp = match has_credential(&state, &guard, CredentialType::Totp).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };
    let webauthn = match has_credential(&state, &guard, CredentialType::WebAuthn).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };
    let webauthn_passwordless =
        match has_credential(&state, &guard, CredentialType::WebAuthnPasswordless).await {
            Ok(v) => v,
            Err(resp) => return resp,
        };

    Json(AccountCredentialsResponse {
        password,
        totp,
        webauthn: webauthn || webauthn_passwordless,
    })
    .into_response()
}

#[utoipa::path(
    get,
    path = "/realms/{realm}/account/api/consents",
    tag = "Account",
    summary = "List the account's granted consents",
    operation_id = "account_list_consents",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    responses(
        (status = 200, description = "Granted consents", body = Vec<AccountConsentResponse>),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers))]
pub async fn account_consents_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    let consents = match state.storage.get_consents(&guard.realm_id, &guard.user_id).await {
        Ok(c) => c,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account consents: failed to list");
            return internal_error("failed to list consents");
        }
    };

    let mut result = Vec::new();
    for consent in consents {
        // The consent stores the internal client UUID; the API exposes the
        // human client_id string. Skip consents whose client row vanished.
        let client = match state.storage.get_client(&guard.realm_id, &consent.client_id).await {
            Ok(Some(c)) => c,
            Ok(None) => continue,
            Err(e) => {
                error!(realm = %guard.realm_id, error = %e, "account consents: resolve failed");
                return internal_error("failed to resolve consent client");
            }
        };
        result.push(AccountConsentResponse {
            client_id: client.client_id.to_string(),
            granted_scopes: consent.granted_scopes.to_vec(),
            created_at: consent.created_at.to_rfc3339(),
            last_updated_at: consent.last_updated_at.to_rfc3339(),
        });
    }
    Json(result).into_response()
}

#[utoipa::path(
    delete,
    path = "/realms/{realm}/account/api/consents/{client_id}",
    tag = "Account",
    summary = "Revoke the account's consent for a client",
    operation_id = "account_delete_consent",
    params(
        ("realm" = String, Path, description = "Realm name"),
        ("client_id" = String, Path, description = "Human client_id string"),
    ),
    responses(
        (status = 204, description = "Consent revoked (idempotent)"),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
        (status = 404, description = "Not found", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers))]
pub async fn account_delete_consent_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
    // The realm segment is resolved by middleware; only the client id is used.
    Path((_realm, client_id)): Path<(String, String)>,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    // The path param is the human client_id string, not the internal UUID.
    let identifier = match ClientIdentifier::new(client_id) {
        Ok(id) => id,
        Err(e) => return bad_request(&e.to_string()),
    };
    let client = match state.storage.get_client_by_client_id(&guard.realm_id, &identifier).await {
        Ok(Some(c)) => c,
        Ok(None) => return error_response(StatusCode::NOT_FOUND, "client not found"),
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "account delete consent: load failed");
            return internal_error("failed to load client");
        }
    };

    // Deleting a missing consent is a no-op in every backend, so revocation
    // is idempotent: 204 whether or not a consent row existed.
    if let Err(e) = state.storage.delete_consent(&guard.realm_id, &guard.user_id, &client.id).await
    {
        error!(realm = %guard.realm_id, error = %e, "account delete consent: failed");
        return internal_error("failed to delete consent");
    }
    StatusCode::NO_CONTENT.into_response()
}

// ---------------------------------------------------------------------------
// Linked accounts (identity brokering)
// ---------------------------------------------------------------------------

#[derive(Debug, serde::Serialize, utoipa::ToSchema)]
pub struct LinkedAccountResponse {
    pub alias: String,
    pub provider_id: String,
    pub display_name: String,
    pub external_username: Option<String>,
    pub created_at: String,
}

#[derive(Debug, serde::Serialize, utoipa::ToSchema)]
pub struct LinkAccountResponse {
    pub redirect_url: String,
}

/// `GET /realms/{realm}/account/api/linked-accounts` โ€” the user's IdP links,
/// joined with the provider configuration for display purposes.
#[utoipa::path(
    get,
    path = "/realms/{realm}/account/api/linked-accounts",
    tag = "Account",
    summary = "List the account's linked external identities",
    operation_id = "account_list_linked_accounts",
    params(
        ("realm" = String, Path, description = "Realm name"),
    ),
    responses(
        (status = 200, description = "Linked accounts", body = Vec<LinkedAccountResponse>),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers))]
pub async fn account_linked_accounts_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    let links = match state
        .storage
        .list_identity_provider_links(&guard.realm_id, &guard.user_id)
        .await
    {
        Ok(l) => l,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "linked accounts: failed to list");
            return internal_error("failed to list linked accounts");
        }
    };
    let idps = match state.storage.list_identity_providers(&guard.realm_id).await {
        Ok(l) => l,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "linked accounts: failed to list IdPs");
            return internal_error("failed to list identity providers");
        }
    };

    let result = links
        .into_iter()
        .map(|link| {
            // A link can outlive its IdP config row only until the cascade
            // delete runs; if it is gone, fall back to the bare alias.
            let (provider_id, display_name) =
                match idps.iter().find(|i| i.alias.as_ref() == link.provider_alias) {
                    Some(cfg) => (
                        cfg.provider_id.as_str().to_string(),
                        BrokerIdpSettings::new(cfg).display_name(),
                    ),
                    None => (String::new(), link.provider_alias.clone()),
                };
            LinkedAccountResponse {
                alias: link.provider_alias.clone(),
                provider_id,
                display_name,
                external_username: link.external_username.clone(),
                created_at: link.created_at.to_rfc3339(),
            }
        })
        .collect::<Vec<_>>();
    Json(result).into_response()
}

/// `POST /realms/{realm}/account/api/linked-accounts/{alias}` โ€” start the
/// linking ceremony: returns the broker login URL carrying a short-lived
/// `link` action token that binds the callback to this authenticated user.
#[utoipa::path(
    post,
    path = "/realms/{realm}/account/api/linked-accounts/{alias}",
    tag = "Account",
    summary = "Start the IdP account-linking ceremony (returns the broker redirect URL)",
    operation_id = "account_link_identity",
    params(
        ("realm" = String, Path, description = "Realm name"),
        ("alias" = String, Path, description = "Identity provider alias"),
    ),
    responses(
        (status = 200, description = "Link ceremony start", body = LinkAccountResponse),
        (status = 400, description = "Bad request", body = crate::openapi::AccountErrorResponse),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
        (status = 404, description = "Not found", body = crate::openapi::AccountErrorResponse),
        (status = 409, description = "Conflict", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers))]
pub async fn account_link_identity_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
    // The realm segment is resolved by middleware; only the alias is used.
    Path((_realm, alias)): Path<(String, String)>,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };
    // extract_auth has already rejected a missing realm segment.
    let realm_name = realm.as_deref().unwrap_or_default();

    if let Err(e) = issuerd_core::Alias::new(alias.clone()) {
        return bad_request(&e.to_string());
    }
    let idp = match state.storage.get_identity_provider_by_alias(&guard.realm_id, &alias).await {
        Ok(Some(i)) => i,
        Ok(None) => return error_response(StatusCode::NOT_FOUND, "identity provider not found"),
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "link account: IdP load failed");
            return internal_error("failed to load identity provider");
        }
    };
    if !idp.enabled || !BrokerIdpSettings::new(&idp).is_broker_provider() {
        return bad_request("identity provider is not available for linking");
    }

    // One link per (user, alias); re-linking is a delete-then-link cycle.
    match state
        .storage
        .get_identity_provider_link_for_user(&guard.realm_id, &guard.user_id, &alias)
        .await
    {
        Ok(Some(_)) => {
            return error_response(StatusCode::CONFLICT, "identity provider already linked")
        }
        Ok(None) => {}
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "link account: link check failed");
            return internal_error("failed to check existing link");
        }
    }

    // The link token is deliberately NOT single-use: the guard is the
    // BrokerState entry plus the issuerd_session cookie match at the callback, so
    // a browser restart during the ceremony does not strand the user.
    let claims = action_token_claims(
        &guard.user_id,
        &guard.realm_id,
        ACTION_TOKEN_PURPOSE_BROKER_LINK,
        super::broker::LINK_TOKEN_TTL_SECS,
    );
    let token = match issue_action_token(state.crypto.as_ref(), &claims).await {
        Ok(t) => t,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "link account: token issue failed");
            return internal_error("failed to issue link token");
        }
    };
    Json(LinkAccountResponse {
        redirect_url: format!("/realms/{realm_name}/broker/{alias}/login?link={token}"),
    })
    .into_response()
}

/// `DELETE /realms/{realm}/account/api/linked-accounts/{alias}` โ€” unlink.
/// Idempotent (204 whether or not the link existed), but refuses to remove
/// the account's last sign-in method.
#[utoipa::path(
    delete,
    path = "/realms/{realm}/account/api/linked-accounts/{alias}",
    tag = "Account",
    summary = "Unlink an external identity (refuses to remove the last sign-in method)",
    operation_id = "account_unlink_identity",
    params(
        ("realm" = String, Path, description = "Realm name"),
        ("alias" = String, Path, description = "Identity provider alias"),
    ),
    responses(
        (status = 204, description = "Unlinked (idempotent)"),
        (status = 400, description = "Bad request", body = crate::openapi::AccountErrorResponse),
        (status = 401, description = "Missing or invalid access token", body = crate::openapi::AccountErrorResponse),
    ),
    security(("bearer_auth" = [])),
)]
#[instrument(skip(state, headers))]
pub async fn account_unlink_identity_handler(
    State(state): State<Arc<ServerState>>,
    axum::extract::Extension(ResolvedRealm(realm)): axum::extract::Extension<ResolvedRealm>,
    headers: axum::http::HeaderMap,
    // The realm segment is resolved by middleware; only the alias is used.
    Path((_realm, alias)): Path<(String, String)>,
) -> Response {
    let guard = match extract_auth(&state, &realm, &headers).await {
        Ok(v) => v,
        Err(resp) => return resp,
    };

    let links = match state
        .storage
        .list_identity_provider_links(&guard.realm_id, &guard.user_id)
        .await
    {
        Ok(l) => l,
        Err(e) => {
            error!(realm = %guard.realm_id, error = %e, "unlink account: failed to list");
            return internal_error("failed to list linked accounts");
        }
    };
    if !links.iter().any(|l| l.provider_alias == alias) {
        return StatusCode::NO_CONTENT.into_response();
    }

    // Last sign-in method guard: without a password credential, unlinking the
    // only IdP link would leave the account with no way to sign in at all.
    if links.len() == 1 {
        match has_credential(&state, &guard, CredentialType::Password).await {
            Ok(true) => {}
            Ok(false) => {
                return bad_request("cannot unlink the only sign-in method; set a password first")
            }
            Err(resp) => return resp,
        }
    }

    if let Err(e) = state
        .storage
        .delete_identity_provider_link(&guard.realm_id, &guard.user_id, &alias)
        .await
    {
        error!(realm = %guard.realm_id, error = %e, "unlink account: delete failed");
        return internal_error("failed to unlink identity provider");
    }
    StatusCode::NO_CONTENT.into_response()
}

fn error_response(status: StatusCode, message: &str) -> Response {
    (status, Json(serde_json::json!({"error": message}))).into_response()
}

fn bad_request(message: &str) -> Response {
    error_response(StatusCode::BAD_REQUEST, message)
}

fn internal_error(message: &str) -> Response {
    error_response(StatusCode::INTERNAL_SERVER_ERROR, message)
}

/// 400 with the machine-readable violation list the account console renders.
fn policy_error_response(err: PasswordPolicyError) -> Response {
    (
        StatusCode::BAD_REQUEST,
        Json(serde_json::json!({
            "error": err.to_string(),
            "policyViolations": err.violations,
        })),
    )
        .into_response()
}

/// Load the authenticated user, mapping storage failures to error responses.
#[allow(clippy::result_large_err)]
async fn load_user(
    state: &Arc<ServerState>,
    guard: &AccountSessionGuard,
) -> Result<User, Response> {
    state
        .storage
        .get_user(&guard.realm_id, &guard.user_id)
        .await
        .map_err(|e| {
            error!(realm = %guard.realm_id, error = %e, "account API: failed to load user");
            internal_error("failed to load user")
        })?
        .ok_or_else(|| error_response(StatusCode::NOT_FOUND, "user not found"))
}

/// Load the realm the guard is bound to (login flags, password policy).
#[allow(clippy::result_large_err)]
async fn load_realm(
    state: &Arc<ServerState>,
    guard: &AccountSessionGuard,
) -> Result<Realm, Response> {
    state
        .storage
        .get_realm(&guard.realm_id)
        .await
        .map_err(|e| {
            error!(realm = %guard.realm_id, error = %e, "account API: failed to load realm");
            internal_error("failed to load realm")
        })?
        .ok_or_else(|| error_response(StatusCode::NOT_FOUND, "realm not found"))
}

/// Resolve the user's realm-role names and build the `me` response object.
/// Shared by GET and PUT so both return the identical shape.
#[allow(clippy::result_large_err)]
async fn build_me_response(
    state: &Arc<ServerState>,
    realm_id: &RealmId,
    user: &User,
) -> Result<AccountMeResponse, Response> {
    let role_ids = state.storage.list_user_realm_roles(realm_id, &user.id).await.map_err(|e| {
        error!(realm = %realm_id, error = %e, "account me: failed to list roles");
        internal_error("failed to list roles")
    })?;
    let mut roles = vec![];
    for role_id in &role_ids {
        if let Ok(Some(role)) = state.storage.get_role(realm_id, role_id).await {
            roles.push(role.name.to_string());
        }
    }
    Ok(AccountMeResponse {
        id: user.id.0.clone(),
        username: user.username.to_string(),
        email: user.email.as_ref().map(|e| e.to_string()),
        first_name: user.first_name.as_ref().map(|n| n.to_string()),
        last_name: user.last_name.as_ref().map(|n| n.to_string()),
        email_verified: user.email_verified,
        enabled: user.enabled,
        roles,
    })
}

/// `true` when the user has at least one credential of the given type.
/// Password-history credentials use a custom type and are never counted here.
#[allow(clippy::result_large_err)]
async fn has_credential(
    state: &Arc<ServerState>,
    guard: &AccountSessionGuard,
    cred_type: CredentialType,
) -> Result<bool, Response> {
    state
        .storage
        .get_credentials(&guard.realm_id, &guard.user_id, cred_type)
        .await
        .map(|creds| !creds.is_empty())
        .map_err(|e| {
            error!(realm = %guard.realm_id, error = %e, "account credentials: load failed");
            internal_error("failed to load credentials")
        })
}

/// Validate an optional display-name update: explicit null clears the field,
/// a value is validated through the `DisplayName` newtype. The `Err` variant
/// carries the validation message for the 400 response.
fn parse_optional_name(value: Option<String>) -> Result<Option<DisplayName>, String> {
    value.map(|v| DisplayName::new(v).map_err(|e| e.to_string())).transpose()
}

/// Apply an email change to `user`, enforcing uniqueness and verification
/// rules. Returns `true` when a verification email must be sent after the
/// update has been persisted.
#[allow(clippy::result_large_err)]
async fn apply_email_change(
    state: &Arc<ServerState>,
    guard: &AccountSessionGuard,
    realm: &Realm,
    user: &mut User,
    new_email: Option<String>,
) -> Result<bool, Response> {
    let new_email: Option<Email> = match new_email {
        Some(v) => Some(Email::new(v).map_err(|e| bad_request(&e.to_string()))?),
        None => None,
    };
    let changed = new_email.as_ref().map(|e| e.as_str()) != user.email.as_ref().map(|e| e.as_str());
    if !changed {
        return Ok(false);
    }
    if let Some(email) = &new_email {
        // Email uniqueness is not enforced by the storage backends, so it is
        // checked here unless the realm explicitly allows duplicate emails.
        if !realm.duplicate_emails_allowed {
            let existing = state
                .storage
                .get_user_by_email(&guard.realm_id, email.as_str())
                .await
                .map_err(|e| {
                    error!(realm = %guard.realm_id, error = %e, "account update me: email lookup failed");
                    internal_error("failed to update user")
                })?;
            if existing.is_some_and(|other| other.id != user.id) {
                return Err(bad_request("email already in use"));
            }
        }
    }
    user.email = new_email;
    // Any email change invalidates the previous verification.
    user.email_verified = false;
    if user.email.is_none() || !realm.verify_email_enabled {
        return Ok(false);
    }
    if !user.required_actions.iter().any(|a| a == "VERIFY_EMAIL") {
        user.required_actions.push("VERIFY_EMAIL".to_string());
    }
    Ok(true)
}

/// Peek at the JWT payload's `exp` claim without validating the token. Used
/// only to pick the log level for an already-rejected token โ€” never for an
/// authorization decision.
fn token_is_expired(token: &str) -> bool {
    let Some(payload) = token.split('.').nth(1) else {
        return false;
    };
    let Ok(bytes) =
        base64::Engine::decode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, payload)
    else {
        return false;
    };
    let Ok(claims) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
        return false;
    };
    claims
        .get("exp")
        .and_then(serde_json::Value::as_i64)
        .is_some_and(|exp| exp < chrono::Utc::now().timestamp())
}

#[allow(clippy::result_large_err)]
async fn extract_auth(
    state: &Arc<ServerState>,
    realm: &Option<String>,
    headers: &axum::http::HeaderMap,
) -> Result<AccountSessionGuard, Response> {
    let realm_name = match realm.as_deref() {
        Some(r) => r,
        None => {
            return Err((
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": "missing realm"})),
            )
                .into_response())
        }
    };

    // The URL carries the realm name and token issuers embed the realm name;
    // storage is keyed by realm id, which differs for admin-created
    // (UUID-id) realms.
    let realm = match state.resolve_realm(realm_name).await {
        Ok(Some(realm)) => realm,
        _ => {
            return Err((
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": "invalid realm"})),
            )
                .into_response())
        }
    };
    let realm_id = realm.id.clone();

    let token = headers
        .get(axum::http::header::AUTHORIZATION)
        .and_then(|h| h.to_str().ok())
        .and_then(|s| s.strip_prefix("Bearer "))
        .ok_or_else(|| {
            (StatusCode::UNAUTHORIZED, Json(serde_json::json!({"error": "invalid_token"})))
                .into_response()
        })?;

    let validated = state.token_service.validate_access_token(token).map_err(|e| {
        // A routinely expired token is client noise (the SPA refreshes and
        // retries); anything else (bad signature, wrong issuer, malformed)
        // is security-relevant and stays at WARN.
        if token_is_expired(token) {
            debug!(realm = %realm_id, error = %e, "account API authentication failed: token expired");
        } else {
            warn!(realm = %realm_id, error = %e, "account API authentication failed");
        }
        (StatusCode::UNAUTHORIZED, Json(serde_json::json!({"error": "invalid_token"})))
            .into_response()
    })?;

    // Verify the token's issuer belongs to this realm. The issuer embeds the
    // realm name.
    let token_realm =
        issuerd_core::typestate::extract_realm_from_issuer(validated.claims.iss.as_str());
    if token_realm != Some(realm.name.as_str()) {
        return Err((
            StatusCode::UNAUTHORIZED,
            Json(serde_json::json!({"error": "invalid_token"})),
        )
            .into_response());
    }

    // The account API honors the same token-validity gates as userinfo:
    // explicit revocation (RFC 7009), backing-session existence (logout and
    // admin revocation take effect immediately), and realm `not_before`.
    // Without them a logged-out or revoked token kept working here until
    // expiry โ€” including for the mutating endpoints (email change, TOTP and
    // passkey deletion).
    let (_issuer_realm, session) =
        match super::oidc::enforce_token_validity(state, token, &validated.claims).await {
            Ok(ctx) => ctx,
            Err(resp) => return Err(resp),
        };

    // Bearer-only API: a DPoP-bound token (`cnf.jkt`) must be presented with
    // a proof (RFC 9449 ยง7.1), which this API does not accept โ€” reject the
    // downgrade instead of letting a stolen proof-bound token authenticate
    // as plain Bearer.
    if validated.claims.cnf.is_some() {
        return Err((
            StatusCode::UNAUTHORIZED,
            Json(serde_json::json!({"error": "invalid_token"})),
        )
            .into_response());
    }

    // Wrap the validated user id in a realm-bound value and then produce the
    // compile-time proof required by account handlers. A token
    // minted for a pairwise client carries an irreversible `sub` โ€” resolve
    // the real user through the token's session (the account-console client
    // is public by default, so this only matters when an admin opts a
    // first-party client into pairwise).
    let user_id =
        match super::oidc::resolve_token_user(state, &realm_id, &validated.claims, session).await {
            Some(user) => user.id,
            None => validated.claims.sub,
        };
    let bound = RealmBound::new(realm_id, user_id);
    Ok(AccountSessionGuard::bind(bound))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{config::ServerConfig, state::ServerState};

    async fn test_state() -> Arc<ServerState> {
        let cfg = ServerConfig::default();
        Arc::new(ServerState::from_config(&cfg).await.unwrap())
    }

    fn master_realm() -> axum::extract::Extension<ResolvedRealm> {
        axum::extract::Extension(ResolvedRealm(Some("master".to_string())))
    }

    #[tokio::test]
    async fn account_me_requires_auth() {
        let response = account_me_handler(
            State(test_state().await),
            master_realm(),
            axum::http::HeaderMap::new(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn account_update_me_requires_auth() {
        let response = account_update_me_handler(
            State(test_state().await),
            master_realm(),
            axum::http::HeaderMap::new(),
            Json(UpdateMeRequest {
                first_name: None,
                last_name: None,
                email: None,
                username: None,
            }),
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn account_change_password_requires_auth() {
        let response = account_change_password_handler(
            State(test_state().await),
            master_realm(),
            axum::extract::Extension(ClientIp("127.0.0.1".parse().unwrap())),
            axum::http::HeaderMap::new(),
            Json(ChangePasswordRequest {
                current_password: "old".to_string(),
                new_password: "new".to_string(),
            }),
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn account_credentials_requires_auth() {
        let response = account_credentials_handler(
            State(test_state().await),
            master_realm(),
            axum::http::HeaderMap::new(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn account_consents_requires_auth() {
        let response = account_consents_handler(
            State(test_state().await),
            master_realm(),
            axum::http::HeaderMap::new(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn account_delete_consent_requires_auth() {
        let response = account_delete_consent_handler(
            State(test_state().await),
            master_realm(),
            axum::http::HeaderMap::new(),
            Path(("master".to_string(), "some-client".to_string())),
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn account_webauthn_register_start_requires_auth() {
        let response = account_webauthn_register_start_handler(
            State(test_state().await),
            master_realm(),
            axum::http::HeaderMap::new(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn account_webauthn_register_finish_requires_auth() {
        let response = account_webauthn_register_finish_handler(
            State(test_state().await),
            master_realm(),
            axum::http::HeaderMap::new(),
            Json(WebAuthnRegisterFinishRequest {
                label: None,
                credential: serde_json::json!({}),
            }),
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn account_webauthn_credentials_requires_auth() {
        let response = account_webauthn_credentials_handler(
            State(test_state().await),
            master_realm(),
            axum::http::HeaderMap::new(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn account_webauthn_delete_requires_auth() {
        let response = account_webauthn_delete_handler(
            State(test_state().await),
            master_realm(),
            axum::http::HeaderMap::new(),
            Path(("master".to_string(), "some-credential".to_string())),
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn update_me_request_distinguishes_absent_from_explicit_null() {
        let parsed: UpdateMeRequest = serde_json::from_str("{}").unwrap();
        assert!(parsed.first_name.is_none());
        assert!(parsed.last_name.is_none());
        assert!(parsed.email.is_none());
        assert!(parsed.username.is_none());

        let parsed: UpdateMeRequest = serde_json::from_str(
            r#"{"first_name": null, "email": "a@example.com", "username": "newname"}"#,
        )
        .unwrap();
        assert_eq!(parsed.first_name, Some(None));
        assert!(parsed.last_name.is_none());
        assert_eq!(parsed.email, Some(Some("a@example.com".to_string())));
        assert_eq!(parsed.username, Some("newname".to_string()));
    }

    #[test]
    fn parse_optional_name_maps_clear_value_and_validation() {
        assert_eq!(parse_optional_name(None).unwrap(), None);
        assert_eq!(
            parse_optional_name(Some("Ada".to_string())).unwrap(),
            Some(DisplayName::new("Ada").unwrap())
        );
        // Empty values are rejected by the newtype with a message for the 400.
        assert!(!parse_optional_name(Some(String::new())).unwrap_err().is_empty());
    }

    #[test]
    fn account_credentials_response_serializes_contract_shape() {
        let json = serde_json::to_value(AccountCredentialsResponse {
            password: true,
            totp: false,
            webauthn: true,
        })
        .unwrap();
        assert_eq!(json, serde_json::json!({"password": true, "totp": false, "webauthn": true}));
    }

    #[test]
    fn account_consent_response_serializes_contract_shape() {
        let json = serde_json::to_value(AccountConsentResponse {
            client_id: "my-client".to_string(),
            granted_scopes: vec!["openid".to_string(), "profile".to_string()],
            created_at: "2026-01-01T00:00:00+00:00".to_string(),
            last_updated_at: "2026-01-02T00:00:00+00:00".to_string(),
        })
        .unwrap();
        assert_eq!(
            json,
            serde_json::json!({
                "client_id": "my-client",
                "granted_scopes": ["openid", "profile"],
                "created_at": "2026-01-01T00:00:00+00:00",
                "last_updated_at": "2026-01-02T00:00:00+00:00",
            })
        );
    }

    /// Password-grant an access token for the master `admin` user.
    async fn password_grant_token(state: &Arc<ServerState>) -> String {
        let resp = crate::routes::oidc::token_handler(
            State(state.clone()),
            axum::extract::Extension(ResolvedRealm(Some("master".to_string()))),
            axum::extract::Extension(ClientIp("127.0.0.1".parse().unwrap())),
            axum::http::HeaderMap::new(),
            "grant_type=password&username=admin&password=admin&client_id=admin-cli&scope=openid"
                .to_string(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        json["access_token"].as_str().unwrap().to_string()
    }

    async fn account_me_with_token(state: &Arc<ServerState>, access_token: &str) -> Response {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert("authorization", format!("Bearer {access_token}").parse().unwrap());
        account_me_handler(
            State(state.clone()),
            axum::extract::Extension(ResolvedRealm(Some("master".to_string()))),
            headers,
        )
        .await
    }

    #[tokio::test]
    async fn account_me_accepts_token_with_live_session() {
        let state = test_state().await;
        let access_token = password_grant_token(&state).await;
        let resp = account_me_with_token(&state, &access_token).await;
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn account_me_rejects_token_of_deleted_session() {
        let state = test_state().await;
        let access_token = password_grant_token(&state).await;

        // Logout / admin revocation deletes the backing session; the account
        // API must reject the token immediately, like userinfo does.
        let validated = state.token_service.validate_access_token(&access_token).unwrap();
        let sid = validated.claims.sid.clone().unwrap();
        state
            .storage
            .delete_user_session(&RealmId::new("master").unwrap(), &sid)
            .await
            .unwrap();

        let resp = account_me_with_token(&state, &access_token).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn account_me_rejects_explicitly_revoked_token() {
        let state = test_state().await;
        let access_token = password_grant_token(&state).await;

        // RFC 7009 revocation records the raw token in the revocation list.
        state
            .cache
            .set(
                &format!("revoked:{access_token}"),
                b"1".to_vec(),
                Some(std::time::Duration::from_secs(300)),
            )
            .await
            .unwrap();

        let resp = account_me_with_token(&state, &access_token).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn account_me_rejects_token_issued_before_realm_not_before() {
        let state = test_state().await;
        let access_token = password_grant_token(&state).await;

        // Push the realm's not_before cutoff past the token's iat. The realm
        // was already resolved (and cached) by the grant, so drop the
        // name-lookup cache entry after the direct storage mutation.
        let mut realm = state
            .storage
            .get_realm(&RealmId::new("master").unwrap())
            .await
            .unwrap()
            .unwrap();
        realm.not_before = chrono::Utc::now().timestamp() + 60;
        state.storage.update_realm(&realm).await.unwrap();
        state
            .cache
            .delete(&issuerd_cluster::cache_keys::realm_by_name("master"))
            .await
            .unwrap();

        let resp = account_me_with_token(&state, &access_token).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn account_me_rejects_dpop_bound_token_presented_as_bearer() {
        let state = test_state().await;
        let realm_id = RealmId::new("master").unwrap();
        let realm = state.storage.get_realm(&realm_id).await.unwrap().unwrap();
        let user = state.storage.get_user_by_username(&realm_id, "admin").await.unwrap().unwrap();
        let client = state
            .storage
            .get_client_by_client_id(&realm_id, &ClientIdentifier::new("admin-cli").unwrap())
            .await
            .unwrap()
            .unwrap();

        // A live session backs the token, so the cnf gate is the only
        // possible rejection cause.
        let session_id = SessionId::new(issuerd_core::utils::generate_id()).unwrap();
        let session = issuerd_core::UserSession {
            id: session_id.clone(),
            realm_id: realm_id.clone(),
            user_id: user.id.clone(),
            login_username: user.username.clone(),
            auth_method: issuerd_core::AuthMethod::Password,
            remember_me: false,
            offline: false,
            ip_address: "127.0.0.1".parse().unwrap(),
            started: chrono::Utc::now(),
            last_session_refresh: chrono::Utc::now(),
            auth_time: chrono::Utc::now(),
            impersonator: None,
            clients: vec![],
        };
        state.storage.create_user_session(&realm_id, &session).await.unwrap();

        // Mint a DPoP-bound token (cnf.jkt) for the live session.
        let overlay = crate::dpop::bind_cnf_overlay(None, Some("test-jkt"));
        let token = state
            .token_manager
            .issue_access_token_with_roles(
                &user,
                &client,
                &realm,
                &["openid".to_string()],
                &session_id,
                None,
                None,
                overlay,
            )
            .await
            .unwrap();

        // Presented as plain Bearer without a proof, the bound token must be
        // rejected (RFC 9449 ยง7.1) instead of silently downgraded.
        let resp = account_me_with_token(&state, &token.token).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }
}