trustee-api 0.11.1

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

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

use axum::{
    body::Body,
    extract::{Query, State},
    http::{header, StatusCode},
    response::{IntoResponse, Json, Redirect, Response},
};
use axum_extra::extract::cookie::{Cookie, SameSite};
use pep::oidc_client::OidcClient;
use pep::oidc_resource_server::ResourceServerClient;
use pep::oidc::pkce_cookie::PkceCookieManager;
use pep::session_manager::WebSessionManager;
use pep::{DevConfig, JwtClaims, JwtValidationOptions, OidcClientConfig};
use serde::Deserialize;
use time::Duration as TimeDuration;

use cedar_policy::{Context, Entities, EntityUid, Request};
use std::str::FromStr;

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// Authentication configuration parsed from `[oidc]` and `[dev]` TOML sections.
#[derive(Debug, Clone)]
pub struct AuthConfig {
    /// OIDC provider issuer URL
    pub issuer_url: String,
    /// OAuth2 client ID
    pub client_id: String,
    /// OAuth2 client secret (None → public client, PKCE only)
    pub client_secret: Option<String>,
    /// Redirect URI for OIDC callback
    pub redirect_uri: String,
    /// OAuth2 scopes
    pub scope: String,
    /// Token cookie name
    pub cookie_name: String,
    /// Development mode configuration
    pub dev_config: DevConfig,
    /// JWT validation options
    pub validation_options: JwtValidationOptions,
    /// Secret for signing PKCE state cookies
    pub pkce_cookie_secret: String,
}

impl AuthConfig {
    /// Parse auth config from the merged trustee TOML string.
    ///
    /// Reads `[oidc]` and `[dev]` sections. If neither is present, returns None
    /// (auth disabled — all endpoints open).
    pub fn from_toml(config_toml: &str) -> Option<Self> {
        let table: toml::Table = toml::from_str(config_toml).ok()?;

        // Check for dev mode
        let dev_config = table.get("dev").and_then(|d| d.as_table()).map(|d| {
            DevConfig {
                local_dev_mode: d.get("local_dev_mode").and_then(|v| v.as_bool()).unwrap_or(false),
                local_dev_email: d.get("local_dev_email").and_then(|v| v.as_str()).map(String::from),
                local_dev_name: d.get("local_dev_name").and_then(|v| v.as_str()).map(String::from),
                local_dev_username: d.get("local_dev_username").and_then(|v| v.as_str()).map(String::from),
            }
        });

        // Dev mode without OIDC — return early with dev-only config
        if let Some(ref dc) = dev_config {
            if dc.local_dev_mode {
                // Try to get OIDC config too (for login endpoint), but it's optional in dev mode
                let oidc = Self::parse_oidc_section(&table);
                return Some(Self {
                    issuer_url: oidc.as_ref().map(|o| o.0.clone()).unwrap_or_else(|| "https://auth.example.com".into()),
                    client_id: oidc.as_ref().map(|o| o.1.clone()).unwrap_or_else(|| "trustee".into()),
                    client_secret: oidc.as_ref().and_then(|o| o.2.clone()),
                    redirect_uri: oidc.as_ref().map(|o| o.3.clone()).unwrap_or_else(|| "http://localhost:3000/auth/callback".into()),
                    scope: oidc.as_ref().map(|o| o.4.clone()).unwrap_or_else(|| "openid profile email".into()),
                    cookie_name: "trustee_token".into(),
                    dev_config: dc.clone(),
                    validation_options: JwtValidationOptions::default(),
                    pkce_cookie_secret: oidc.as_ref().map(|o| o.6.clone()).unwrap_or_else(|| "trustee-default-pkce-secret-change-me".into()),
                });
            }
        }

        // Production mode — requires [oidc] section
        let (issuer_url, client_id, client_secret, redirect_uri, scope, validation_options, pkce_secret) =
            Self::parse_oidc_section(&table)?;

        Some(Self {
            issuer_url,
            client_id,
            client_secret,
            redirect_uri,
            scope,
            cookie_name: "trustee_token".into(),
            dev_config: dev_config.unwrap_or_default(),
            validation_options,
            pkce_cookie_secret: pkce_secret,
        })
    }

    /// Parse the `[oidc]` section from a TOML table.
    /// Returns (issuer_url, client_id, client_secret, redirect_uri, scope, validation_options, pkce_secret).
    fn parse_oidc_section(
        table: &toml::Table,
    ) -> Option<(String, String, Option<String>, String, String, JwtValidationOptions, String)> {
        let oidc = table.get("oidc")?.as_table()?;

        let issuer_url = oidc.get("issuer_url")?.as_str()?.to_string();
        let client_id = oidc.get("client_id")?.as_str()?.to_string();
        let client_secret = oidc.get("client_secret").and_then(|v| v.as_str()).map(String::from);
        let redirect_uri = oidc
            .get("redirect_uri")
            .or_else(|| oidc.get("redirect_url")) // backward compat
            .and_then(|v| v.as_str())
            .unwrap_or("http://localhost:3000/auth/callback")
            .to_string();
        let scope = oidc
            .get("scope")
            .and_then(|v| v.as_str())
            .unwrap_or("openid profile email")
            .to_string();

        let mut validation_options = JwtValidationOptions::default();
        if let Some(skip) = oidc.get("skip_issuer_validation").and_then(|v| v.as_bool()) {
            validation_options.skip_issuer_validation = skip;
        }
        if let Some(skip) = oidc.get("skip_audience_validation").and_then(|v| v.as_bool()) {
            validation_options.skip_audience_validation = skip;
        }
        validation_options.expected_audience = oidc
            .get("expected_audience")
            .and_then(|v| v.as_str())
            .map(String::from);

        let pkce_secret = oidc
            .get("pkce_cookie_secret")
            .and_then(|v| v.as_str())
            .unwrap_or("trustee-default-pkce-secret-change-me")
            .to_string();

        Some((issuer_url, client_id, client_secret, redirect_uri, scope, validation_options, pkce_secret))
    }

    /// Build OIDC client configuration for PEP's OidcClient.
    pub fn oidc_client_config(&self) -> OidcClientConfig {
        OidcClientConfig {
            issuer_url: self.issuer_url.clone(),
            client_id: self.client_id.clone(),
            client_secret: self.client_secret.clone(),
            redirect_uri: self.redirect_uri.clone(),
            scope: self.scope.clone(),
            code_challenge_method: "S256".to_string(),
        }
    }
}

/// Shared authentication state, stored in ServerState.
#[derive(Clone)]
pub struct AuthState {
    /// OIDC client for login flow (authorization code + PKCE)
    pub oidc_client: OidcClient,
    /// Resource server client for JWT validation (lazy-initialized)
    pub resource_server: ResourceServerClient,
    /// OIDC client configuration
    pub client_config: OidcClientConfig,
    /// Auth configuration
    pub config: AuthConfig,
    /// Stateless PKCE cookie manager
    pub pkce_manager: PkceCookieManager,
    /// Web session manager (cookie session_id → server-side token with auto-refresh)
    pub session_manager: Arc<WebSessionManager>,
    /// Cedar authorizer for ABAC authorization (None = Cedar disabled)
    pub cedar_authorizer: Option<Arc<pep::cedar::CedarAuthorizer>>,
}

impl AuthState {
    /// Create new auth state from configuration.
    pub fn new(config: AuthConfig) -> Self {
        Self::with_cedar(config, None)
    }

    /// Create new auth state with optional Cedar authorizer.
    pub fn with_cedar(config: AuthConfig, cedar_authorizer: Option<Arc<pep::cedar::CedarAuthorizer>>) -> Self {
        let pkce_manager = PkceCookieManager::new(
            config.pkce_cookie_secret.as_bytes(),
            "trustee_pkce_state",
            StdDuration::from_secs(600),
        );

        let session_manager = Arc::new(WebSessionManager::new(
            OidcClient::new(),
            config.issuer_url.clone(),
            config.client_id.clone(),
            config.client_secret.clone(),
            config.scope.clone(),
        ));

        Self {
            oidc_client: OidcClient::new(),
            resource_server: ResourceServerClient::new(),
            client_config: config.oidc_client_config(),
            pkce_manager,
            session_manager,
            config,
            cedar_authorizer,
        }
    }

    /// Check if development mode is enabled.
    pub fn is_dev_mode(&self) -> bool {
        self.config.dev_config.local_dev_mode
    }

    /// Validate a JWT token using PEP's ResourceServerClient.
    pub async fn validate_token(&self, token: &str) -> anyhow::Result<JwtClaims> {
        let mut claims = self
            .resource_server
            .validate_jwt_with_options(
                token,
                &self.config.issuer_url,
                &self.config.client_id,
                &self.config.validation_options,
            )
            .await
            .map_err(|e| anyhow::anyhow!("Token validation failed: {}", e))?;

        // Enrich with userinfo for role/groups (cached, no-op if already present)
        // 2de5d1eb: this used to be `let _ =` — a silent role-less principal
        // that Cedar then fail-closed DENIED with `matched policies: []` and
        // zero diagnosis. Enrichment failure must SCREAM.
        if let Err(e) = self
            .resource_server
            .enrich_claims_with_userinfo(&mut claims, token, &self.config.issuer_url, None)
            .await
        {
            tracing::error!(
                "userinfo enrichment FAILED for sub {}: {} — principal carries NO role/groups; \
                 with Cedar enabled every request will be DENIED until enrichment succeeds",
                claims.sub,
                e
            );
        }

        // PEP only merges groups/role from userinfo. If name/email are missing
        // (Kanidm JWTs only contain sub), fetch them from userinfo directly.
        if claims.name.is_none() || claims.email.is_none() {
            self.fill_userinfo_fields(&mut claims, token).await;
        }

        Ok(claims)
    }

    /// Fetch name/email/preferred_username from the OIDC userinfo endpoint
    /// and fill in any that are missing from the JWT claims.
    async fn fill_userinfo_fields(&self, claims: &mut JwtClaims, token: &str) {
        // Derive userinfo URL from issuer
        // For Kanidm: issuer_url is the discovery endpoint,
        // userinfo is at {issuer_url}/userinfo
        let userinfo_url = format!("{}/userinfo", self.config.issuer_url.trim_end_matches('/'));

        let client = reqwest::Client::new();
        let resp = client
            .get(&userinfo_url)
            .header("Authorization", format!("Bearer {}", token))
            .header("Accept", "application/json")
            .send()
            .await;

        let Ok(resp) = resp else {
            tracing::debug!("Userinfo request failed for name/email enrichment");
            return;
        };

        if !resp.status().is_success() {
            tracing::debug!("Userinfo returned {} for name/email enrichment", resp.status());
            return;
        }

        let Ok(userinfo): Result<serde_json::Map<String, serde_json::Value>, _> = resp.json().await else {
            return;
        };

        tracing::debug!("Userinfo keys: {:?}", userinfo.keys().collect::<Vec<_>>());

        if claims.name.is_none() {
            if let Some(name) = userinfo.get("name").and_then(|v| v.as_str()) {
                claims.name = Some(name.to_string());
            }
        }
        if claims.email.is_none() {
            if let Some(email) = userinfo.get("email").and_then(|v| v.as_str()) {
                claims.email = Some(email.to_string());
            }
        }
        if claims.preferred_username.is_none() {
            if let Some(uname) = userinfo.get("preferred_username").and_then(|v| v.as_str()) {
                claims.preferred_username = Some(uname.to_string());
            }
        }
    }

    /// Check Cedar authorization for the authenticated user.
    ///
    /// Returns Ok(()) if allowed (or if Cedar is not configured).
    /// Returns Err(()) if denied — caller should return 403 Forbidden.
    fn check_cedar_authorized(&self, claims: &JwtClaims, action: &str) -> Result<(), ()> {
        let Some(ref authorizer) = self.cedar_authorizer else {
            return Ok(()); // Cedar not configured — allow
        };

        // Build principal entity from JWT claims
        let principal_entity = match pep::cedar::build_principal_entity(claims) {
            Ok(e) => e,
            Err(e) => {
                tracing::error!("Cedar: failed to build principal entity: {}", e);
                return Err(());
            }
        };

        // Build entities set with principal + TrusteeApp resource
        let mut entities_vec = vec![principal_entity];

        // Add a TrusteeApp entity as the resource
        let app_uid = match EntityUid::from_str(r#"TrusteeApp::"default""#) {
            Ok(uid) => uid,
            Err(e) => {
                tracing::error!("Cedar: failed to build TrusteeApp uid: {}", e);
                return Err(());
            }
        };
        let app_entity = match cedar_policy::Entity::new(
            app_uid,
            std::collections::HashMap::new(),
            std::collections::HashSet::new(),
        ) {
            Ok(e) => e,
            Err(e) => {
                tracing::error!("Cedar: failed to build TrusteeApp entity: {}", e);
                return Err(());
            }
        };
        entities_vec.push(app_entity);

        let entities = match Entities::from_entities(entities_vec, None) {
            Ok(e) => e,
            Err(e) => {
                tracing::error!("Cedar: failed to build entities set: {}", e);
                return Err(());
            }
        };

        // Build the Cedar authorization request
        let principal_uid = match pep::cedar::build_principal_uid(claims) {
            Ok(uid) => uid,
            Err(e) => {
                tracing::error!("Cedar: failed to build principal uid: {}", e);
                return Err(());
            }
        };

        let action_uid = match EntityUid::from_str(&format!("Action::\"{action}\"")) {
            Ok(uid) => uid,
            Err(e) => {
                tracing::error!("Cedar: failed to build action uid: {}", e);
                return Err(());
            }
        };

        let resource_uid = match EntityUid::from_str(r#"TrusteeApp::"default""#) {
            Ok(uid) => uid,
            Err(e) => {
                tracing::error!("Cedar: failed to build resource uid: {}", e);
                return Err(());
            }
        };

        let request = match Request::new(principal_uid, action_uid, resource_uid, Context::empty(), None) {
            Ok(r) => r,
            Err(e) => {
                tracing::error!("Cedar: failed to build request: {}", e);
                return Err(());
            }
        };

        let response = authorizer.is_allowed_with_entities(&request, &entities);

        if response.allowed() {
            tracing::debug!(
                "Cedar: authorized user {} (sub={})",
                claims.email.as_deref().unwrap_or("unknown"),
                claims.sub
            );
            Ok(())
        } else {
            tracing::warn!(
                "Cedar: DENIED user {} (sub={}) — matched policies: {:?}, errors: {:?}",
                claims.email.as_deref().unwrap_or("unknown"),
                claims.sub,
                response.matched_policies(),
                response.errors()
            );
            Err(())
        }
    }
}

// ---------------------------------------------------------------------------
// Auth checking — called by protected route handlers
// ---------------------------------------------------------------------------

/// Cedar action names (P2, nghr 645809c3).
///
/// Keep in sync with `policies/trustee_schema.cedarschema` — the schema and
/// the embedded policy ship atomically with these constants; a filesystem
/// policy override referencing removed actions will deny everything (loud,
/// by design).
pub mod actions {
    pub const LIST_MODELS: &str = "ListModels";
    pub const LIST_SESSIONS: &str = "ListSessions";
    pub const VIEW_SESSION: &str = "ViewSession";
    pub const VIEW_HISTORY: &str = "ViewHistory";
    pub const CREATE_SESSION: &str = "CreateSession";
    pub const COMMAND_SESSION: &str = "CommandSession";
    pub const CANCEL_SESSION: &str = "CancelSession";
    pub const HANDOFF_SESSION: &str = "HandoffSession";
    pub const RESUME_SESSION: &str = "ResumeSession";
    pub const UPDATE_SESSION: &str = "UpdateSession";
    pub const DELETE_SESSION: &str = "DeleteSession";
    pub const VIEW_MCP_CREDENTIALS: &str = "ViewMcpCredentials";
    pub const UPDATE_MCP_CREDENTIALS: &str = "UpdateMcpCredentials";
}

/// Principal kind (16D). `Agent` iff the enriched `role` claim contains
/// "agent" — the exact value mapped by Kanidm's `pdt-api-agents` group
/// (role vocabulary: admin | user | service | agent, facts doc 42977cb7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrincipalKind {
    Human,
    Agent,
}

impl PrincipalKind {
    /// Classify from the primary role. Anything that is not exactly
    /// "agent" is Human — fail-toward-human keeps the default posture
    /// identical to pre-16D behavior.
    pub fn from_role(role: Option<&str>) -> Self {
        match role {
            Some("agent") => Self::Agent,
            _ => Self::Human,
        }
    }
}

/// Extract the primary role from enriched JWT claims.
///
/// PEP merges userinfo into `extra` (flattened claims). Kanidm delivers
/// `role` as a STRING or an ARRAY (pep 366e8ed lesson) — accept both,
/// first value wins.
fn claim_role(claims: &JwtClaims) -> Option<String> {
    match claims.extra.get("role") {
        Some(serde_json::Value::String(s)) => Some(s.clone()),
        Some(serde_json::Value::Array(arr)) => arr
            .iter()
            .filter_map(|v| v.as_str())
            .next()
            .map(|s| s.to_string()),
        _ => None,
    }
}

/// Authenticated user info extracted from the token.
#[derive(Debug, Clone)]
pub struct AuthUser {
    pub sub: String,
    pub email: Option<String>,
    pub name: Option<String>,
    pub username: Option<String>,
    pub is_dev: bool,
    /// Primary role from enriched claims (16D).
    pub role: Option<String>,
    /// Principal classification (16D): Agent iff role == "agent".
    pub kind: PrincipalKind,
}

impl From<JwtClaims> for AuthUser {
    fn from(claims: JwtClaims) -> Self {
        let role = claim_role(&claims);
        let kind = PrincipalKind::from_role(role.as_deref());
        Self {
            sub: claims.sub,
            email: claims.email,
            name: claims.name,
            username: claims.preferred_username,
            is_dev: false,
            role,
            kind,
        }
    }
}

/// Cookie max-age for session cookies (1 hour, matching the server-side idle timeout).
const SESSION_COOKIE_MAX_AGE: StdDuration = StdDuration::from_secs(3600);

/// PINNED (16D) + AGENT CARVE-OUT (16E): user_key for JWT principals.
///
/// Humans: `preferred_username` first, falling back to `sub`. NEVER email —
/// email is rebindable in Kanidm and would silently re-home a principal's
/// namespace.
///
/// Agents: `sub` — ALWAYS. Exchanged agent tokens carry no
/// `preferred_username` today, but a future scope change (e.g. adding
/// `profile` to the exchange) would add it and silently re-home every
/// agent's namespace — the exact migration bug class 0.10→0.11 inflicted on
/// humans. Agents are pinned to `sub` for the lifetime of the namespace.
///
/// MIGRATION NOTE (humans): the 16D rule changed the key for existing JWT
/// humans (they were keyed by `sub` before 0.11.0). Kanidm humans have a
/// `preferred_username`, so their namespace hash changes on first login —
/// pre-web-production history under the old hash is orphaned, not deleted.
fn jwt_user_key(claims: &JwtClaims) -> String {
    if PrincipalKind::from_role(claim_role(claims).as_deref()) == PrincipalKind::Agent {
        return claims.sub.clone();
    }
    match claims.preferred_username.as_deref() {
        Some(u) if !u.trim().is_empty() => u.trim().to_string(),
        _ => {
            tracing::debug!(
                "user_key: preferred_username missing/empty for sub {} — falling back to sub",
                claims.sub
            );
            claims.sub.clone()
        }
    }
}

/// Extract a user key from a dev-mode token string.
///
/// Two formats (BOTH gated by `local_dev_mode` at every call site):
/// - `dev:agent:<name>` → `agent-{name}` (16D: agent namespace in dev —
///   unblocks per-user cache + THQ E2E without Kanidm accounts; distinct
///   prefix so dev agents can never collide with dev humans)
/// - `dev:email:name:username` → `dev:{email}` (dev humans, legacy)
fn dev_user_key(token: &str) -> Option<String> {
    if let Some(name) = token.strip_prefix("dev:agent:") {
        let name = name.trim();
        if name.is_empty() || name.contains(':') {
            return None;
        }
        return Some(format!("agent-{name}"));
    }
    let parts: Vec<&str> = token.splitn(4, ':').collect();
    if parts.len() >= 4 {
        Some(format!("dev:{}", parts[1]))
    } else {
        None
    }
}

/// Pure decision core of [`check_dispatch_admin`] — unit-testable without an IdP.
pub(crate) fn dispatch_allowed(kind: PrincipalKind, role: Option<&str>) -> bool {
    kind == PrincipalKind::Human && role == Some("admin")
}

/// 16F: admin gate for the per-agent dispatch surface (`/xagent/{name}`).
///
/// The OUTER dispatch must be performed by a HUMAN ADMIN: agents may never
/// dispatch agents, and `service` is read-only by design. The impersonated
/// INNER request is separately authenticated and Cedar-gated AS THE AGENT
/// (per-action matrix), so this gate answers exactly one question: "may this
/// principal dispatch agent-users at all".
///
/// Open mode (no auth configured) allows dispatch, consistent with the
/// posture check_auth already applies. Dev-mode human tokens carry no role
/// and are therefore rejected — dispatch testing requires a real admin JWT.
pub async fn check_dispatch_admin(
    auth: &Option<Arc<AuthState>>,
    headers: &axum::http::HeaderMap,
) -> Result<(), StatusCode> {
    let Some(auth) = auth.as_ref() else {
        return Ok(()); // open mode — same posture as check_auth
    };
    let Some(token) = headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .map(|s| s.to_string())
    else {
        return Err(StatusCode::UNAUTHORIZED);
    };
    if token.starts_with("dev:") {
        tracing::warn!("xagent dispatch rejected: dev tokens cannot dispatch agents");
        return Err(StatusCode::FORBIDDEN);
    }
    let claims = auth
        .validate_token(&token)
        .await
        .map_err(|e| {
            tracing::warn!("xagent dispatch: caller token validation failed: {}", e);
            StatusCode::UNAUTHORIZED
        })?;
    let user = AuthUser::from(claims);
    if !dispatch_allowed(user.kind, user.role.as_deref()) {
        tracing::warn!(
            "xagent dispatch rejected: principal kind={:?} role={:?} — admin required",
            user.kind,
            user.role
        );
        return Err(StatusCode::FORBIDDEN);
    }
    Ok(())
}

impl AuthState {
    /// 16F: exchange an agent-user's Kanidm service token for a short-lived
    /// access token carrying `role=agent`, usable as the impersonated Bearer
    /// on the inner dispatch. Same grant the MCP credentials use (verified
    /// RFC 8693 shape); enrichment in `validate_token` resolves the role.
    ///
    /// `issuer_url` MUST be the service-account issuer: Kanidm binds token
    /// exchange to the client origin — the `[oidc]` auth issuer host serves
    /// logins but rejects exchange with `invalid_request`, while the
    /// `[mcp.credentials.*]` service issuer (see
    /// `ServerState::service_issuer`) accepts it (verified live 2026-08-30:
    /// same token, 200 vs 400).
    pub async fn exchange_agent_token(
        &self,
        issuer_url: &str,
        service_token: &str,
    ) -> Result<(String, u64), StatusCode> {
        let tr = self
            .oidc_client
            .exchange_token(
                issuer_url,
                &self.config.client_id,
                None, // public client — no secret (Kanidm rejects one)
                service_token,
                &self.config.client_id,
                Some("openid groups"),
            )
            .await
            .map_err(|e| {
                tracing::error!(
                    "xagent dispatch: agent token exchange FAILED at {issuer_url}: {} — impersonation unavailable",
                    e
                );
                StatusCode::BAD_GATEWAY
            })?;
        Ok((tr.access_token, tr.expires_in.unwrap_or(900)))
    }
}

/// Check authentication for a protected endpoint.
///
/// Returns `Ok((None, user_key))` if auth is not configured (open mode), or if
/// a valid token is present without needing cookie renewal. Returns
/// `Ok((Some(cookie), user_key))` if auth succeeded and the caller should
/// include the given `Set-Cookie` header value in the response (rolling session).
/// Returns `Err(StatusCode)` if auth is configured but no valid token is found.
///
/// The returned `user_key` is the identity string used for session isolation
/// (JWT principals: `preferred_username || sub` — PINNED, see [`jwt_user_key`];
/// `dev:{email}` for dev-mode humans, `agent-{name}` for `dev:agent:` tokens,
/// `"default"` when auth is not configured). This avoids the need for handlers
/// to call `resolve_user_key()` which would re-validate the JWT a second time.
///
/// Token sources (in order):
/// 1. `Authorization: Bearer <token>` header (raw JWT — validated directly)
/// 2. `trustee_token=<session_id>` cookie (looked up in WebSessionManager,
///    auto-refreshed if near expiry)
///
/// Dev mode tokens use the format `dev:email:name:username`.
pub async fn check_auth(
    auth: &Option<Arc<AuthState>>,
    headers: &axum::http::HeaderMap,
    action: &str,
) -> Result<(Option<String>, String), StatusCode> {
    let Some(auth) = auth.as_ref() else {
        return Ok((None, "default".to_string())); // Auth not configured — allow
    };

    // 1. Try Bearer header first (raw JWT — e.g. from API clients, Torpi proxy)
    if let Some(token) = headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .map(|s| s.to_string())
    {
        // Dev mode token — only accepted when dev mode is currently enabled
        if token.starts_with("dev:") {
            if !auth.config.dev_config.local_dev_mode {
                tracing::warn!("Dev token presented but dev mode is disabled — rejecting");
                return Err(StatusCode::UNAUTHORIZED);
            }
            return match dev_user_key(&token) {
                Some(key) => Ok((None, key)),
                None => Err(StatusCode::UNAUTHORIZED),
            };
        }

        return match auth.validate_token(&token).await {
            Ok(claims) => {
                if auth.check_cedar_authorized(&claims, action).is_err() {
                    return Err(StatusCode::FORBIDDEN);
                }
                Ok((None, jwt_user_key(&claims)))
            }
            Err(e) => {
                tracing::warn!("Bearer token validation failed: {}", e);
                Err(StatusCode::UNAUTHORIZED)
            }
        };
    }

    // 2. Try cookie (session_id → WebSessionManager → access token with auto-refresh)
    let session_id = headers
        .get(header::COOKIE)
        .and_then(|v| v.to_str().ok())
        .and_then(|cookies| extract_token_from_cookies(cookies, &auth.config.cookie_name));

    let Some(session_id) = session_id else {
        tracing::warn!("No auth token found in request");
        return Err(StatusCode::UNAUTHORIZED);
    };

    // Dev mode token in cookie — only accepted when dev mode is currently enabled
    if session_id.starts_with("dev:") {
        if !auth.config.dev_config.local_dev_mode {
            tracing::warn!("Dev cookie presented but dev mode is disabled — rejecting");
            return Err(StatusCode::UNAUTHORIZED);
        }
        return match dev_user_key(&session_id) {
            Some(key) => Ok((None, key)),
            None => Err(StatusCode::UNAUTHORIZED),
        };
    }

    // Session-based: look up via WebSessionManager (auto-refreshes)
    match auth.session_manager.get_token(&session_id).await {
        Ok(access_token) => match auth.validate_token(&access_token).await {
            Ok(claims) => {
                // Cedar authorization check
                if auth.check_cedar_authorized(&claims, action).is_err() {
                    return Err(StatusCode::FORBIDDEN);
                }
                // Roll the cookie — reset max-age so active users stay logged in
                let secure = auth.client_config.redirect_uri.starts_with("https");
                let cookie = create_auth_cookie(
                    &auth.config.cookie_name,
                    &session_id,
                    SESSION_COOKIE_MAX_AGE,
                    secure,
                );
                Ok((Some(cookie.to_string()), jwt_user_key(&claims)))
            }
            Err(e) => {
                // Token was returned but JWT validation failed (e.g. ExpiredSignature
                // due to clock skew). Force-refresh and retry once.
                tracing::warn!("Session token validation failed: {} — attempting force-refresh", e);
                match auth.session_manager.force_refresh(&session_id).await {
                    Ok(new_token) => match auth.validate_token(&new_token).await {
                        Ok(claims) => {
                            // Cedar authorization check
                            if auth.check_cedar_authorized(&claims, action).is_err() {
                                return Err(StatusCode::FORBIDDEN);
                            }
                            let secure = auth.client_config.redirect_uri.starts_with("https");
                            let cookie = create_auth_cookie(
                                &auth.config.cookie_name,
                                &session_id,
                                SESSION_COOKIE_MAX_AGE,
                                secure,
                            );
                            Ok((Some(cookie.to_string()), jwt_user_key(&claims)))
                        }
                        Err(e2) => {
                            tracing::warn!("Session token still invalid after force-refresh: {}", e2);
                            Err(StatusCode::UNAUTHORIZED)
                        }
                    },
                    Err(e2) => {
                        tracing::warn!("Force-refresh failed: {}", e2);
                        Err(StatusCode::UNAUTHORIZED)
                    }
                }
            }
        },
        Err(e) => {
            tracing::warn!("Session lookup/refresh failed: {}", e);
            Err(StatusCode::UNAUTHORIZED)
        }
    }
}

/// Extract a valid access token from the request (for use by handlers that
/// need the token itself, not just auth checking).
///
/// Resolves session_id cookies to actual access tokens via WebSessionManager.
/// Bearer headers are returned as-is.
async fn resolve_access_token(
    auth: &AuthState,
    headers: &axum::http::HeaderMap,
) -> Result<String, StatusCode> {
    // Bearer header — return as-is
    if let Some(token) = headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .map(|s| s.to_string())
    {
        return Ok(token);
    }

    // Cookie — resolve session_id → access_token
    let session_id = headers
        .get(header::COOKIE)
        .and_then(|v| v.to_str().ok())
        .and_then(|cookies| extract_token_from_cookies(cookies, &auth.config.cookie_name));

    match session_id {
        Some(sid) if sid.starts_with("dev:") => {
            if !auth.config.dev_config.local_dev_mode {
                tracing::warn!("Dev cookie in resolve_access_token but dev mode is disabled — rejecting");
                Err(StatusCode::UNAUTHORIZED)
            } else {
                Ok(sid)
            }
        }
        Some(sid) => auth.session_manager.get_token(&sid).await.map_err(|e| {
            tracing::warn!("Failed to resolve session token: {}", e);
            StatusCode::UNAUTHORIZED
        }),
        None => Err(StatusCode::UNAUTHORIZED),
    }
}

/// Extract token value from a cookie header string.
fn extract_token_from_cookies(cookie_header: &str, cookie_name: &str) -> Option<String> {
    for cookie in cookie_header.split(';') {
        let cookie = cookie.trim();
        if let Some(value) = cookie.strip_prefix(&format!("{}=", cookie_name)) {
            return Some(value.to_string());
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Auth routes: /auth/login, /auth/callback, /auth/me, /auth/logout
// ---------------------------------------------------------------------------

/// Build the auth routes as a nested Router.
pub fn auth_routes() -> axum::Router<crate::ServerState> {
    axum::Router::new()
        .route("/login", axum::routing::get(login_handler))
        .route("/callback", axum::routing::get(callback_handler))
        .route("/me", axum::routing::get(me_handler))
        .route("/logout", axum::routing::post(logout_handler))
        .route("/mcp/login", axum::routing::get(mcp_login_handler))
        .route("/mcp/callback", axum::routing::get(mcp_callback_handler))
        .route("/mcp/status", axum::routing::get(mcp_status_handler))
        .route("/mcp/logout", axum::routing::post(mcp_logout_handler))
}

/// Query parameters for OIDC callback.
#[derive(Debug, Deserialize)]
pub struct CallbackQuery {
    pub code: Option<String>,
    pub state: Option<String>,
    pub error: Option<String>,
    pub error_description: Option<String>,
}

/// GET /auth/login — initiate OIDC login with PKCE, or create dev session.
async fn login_handler(
    State(state): State<crate::ServerState>,
) -> Result<Response, AuthError> {
    let auth = state.auth.as_ref().ok_or(AuthError::AuthNotConfigured)?;

    // Dev mode — create synthetic session
    if auth.is_dev_mode() {
        tracing::info!("Dev mode: creating dev session");
        let dev = &auth.config.dev_config;
        let dev_token = format!(
            "dev:{}:{}:{}",
            dev.local_dev_email.as_deref().unwrap_or("dev@localhost"),
            dev.local_dev_name.as_deref().unwrap_or("Dev User"),
            dev.local_dev_username.as_deref().unwrap_or("dev")
        );
        let cookie = create_auth_cookie(&auth.config.cookie_name, &dev_token, StdDuration::from_secs(86400), false);
        return Ok(Response::builder()
            .status(StatusCode::FOUND)
            .header(header::LOCATION, "/")
            .header(header::SET_COOKIE, cookie.to_string())
            .body(Body::empty())
            .unwrap());
    }

    // Production — redirect to IdP with PKCE
    let pkce_session = auth.pkce_manager.create();
    let challenge = OidcClient::generate_code_challenge(&pkce_session.verifier);

    let auth_url = auth
        .oidc_client
        .build_authorization_url(&auth.client_config, &pkce_session.state, Some(&challenge))
        .await
        .map_err(|e| AuthError::OidcError(e.to_string()))?;

    // Set PKCE state cookie (HttpOnly, SameSite=Lax)
    // Secure flag follows the redirect_uri scheme — HTTP localhost/LAN must not
    // set Secure or the browser drops the cookie and PKCE state is lost.
    let secure = auth.client_config.redirect_uri.starts_with("https");
    let pkce_cookie = Cookie::build((
        auth.pkce_manager.cookie_name().to_string(),
        pkce_session.cookie_value,
    ))
        .path("/")
        .http_only(true)
        .same_site(SameSite::Lax)
        .secure(secure)
        .max_age(TimeDuration::seconds(auth.pkce_manager.ttl().as_secs() as i64))
        .build();

    Ok(Response::builder()
        .status(StatusCode::TEMPORARY_REDIRECT)
        .header(header::LOCATION, &auth_url)
        .header(header::SET_COOKIE, pkce_cookie.to_string())
        .body(Body::empty())
        .unwrap())
}

/// GET /auth/callback — exchange authorization code for tokens, set cookie.
async fn callback_handler(
    State(state): State<crate::ServerState>,
    Query(query): Query<CallbackQuery>,
    headers: axum::http::HeaderMap,
) -> Result<Response, AuthError> {
    let auth = state.auth.as_ref().ok_or(AuthError::AuthNotConfigured)?;

    // Check for errors from IdP
    if let Some(error) = query.error {
        let desc = query.error_description.unwrap_or_default();
        tracing::error!("OIDC error: {} - {}", error, desc);
        return Ok(Redirect::temporary(&format!(
            "/?error={}&error_description={}",
            urlencoding::encode(&error),
            urlencoding::encode(&desc)
        ))
        .into_response());
    }

    let code = query.code.ok_or(AuthError::MissingCode)?;
    let oauth_state = query.state.ok_or(AuthError::MissingState)?;

    // Retrieve PKCE cookie
    let cookie_header = headers
        .get(header::COOKIE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    let pkce_value = extract_token_from_cookies(cookie_header, auth.pkce_manager.cookie_name())
        .ok_or(AuthError::InvalidState)?;

    // Verify PKCE cookie (HMAC + expiry + state match)
    let verifier = auth
        .pkce_manager
        .verify(&pkce_value, &oauth_state)
        .ok_or(AuthError::InvalidState)?;

    // Exchange code for tokens
    tracing::info!("Exchanging authorization code for tokens");
    let token_response = auth
        .oidc_client
        .exchange_code_for_tokens(&auth.client_config, &code, Some(&verifier))
        .await
        .map_err(|e| AuthError::TokenExchangeFailed(e.to_string()))?;

    let session_id = auth
        .session_manager
        .create_session(&token_response)
        .await
        .map_err(|e| AuthError::TokenExchangeFailed(format!("Session creation failed: {}", e)))?;

    // Cookie lifetime matches server-side idle timeout (1 hour).
    // The cookie is rolled on every successful request via check_auth().
    let max_age = SESSION_COOKIE_MAX_AGE;

    // Set auth cookie — Secure only when redirect_uri is HTTPS
    let secure = auth.client_config.redirect_uri.starts_with("https");
    let cookie = create_auth_cookie(&auth.config.cookie_name, &session_id, max_age, secure);

    // Clear PKCE cookie (single-use)
    let clear_pkce = Cookie::build((auth.pkce_manager.cookie_name().to_string(), ""))
        .path("/")
        .http_only(true)
        .same_site(SameSite::Lax)
        .max_age(TimeDuration::seconds(-1))
        .build();

    tracing::info!("Authentication successful, redirecting to /");

    Ok(Response::builder()
        .status(StatusCode::FOUND)
        .header(header::LOCATION, "/")
        .header(header::SET_COOKIE, cookie.to_string())
        .header(header::SET_COOKIE, clear_pkce.to_string())
        .body(Body::empty())
        .unwrap())
}

/// GET /auth/me — return current user info.
async fn me_handler(
    State(state): State<crate::ServerState>,
    headers: axum::http::HeaderMap,
) -> Response {
    let Some(ref auth) = state.auth else {
        // Auth not configured — always authenticated (no auth required)
        return axum::Json(serde_json::json!({
            "authenticated": true,
            "auth_enabled": false
        }))
        .into_response();
    };

    let cookie_header = headers
        .get(header::COOKIE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    // Also try Authorization: Bearer header
    let bearer = headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .map(String::from);

    let token = bearer.clone().or_else(|| extract_token_from_cookies(cookie_header, &auth.config.cookie_name));

    let Some(cookie_value) = token else {
        return axum::Json(serde_json::json!({
            "authenticated": false,
            "auth_enabled": true
        }))
        .into_response();
    };

    // Dev mode token (stored directly in cookie, no session manager)
    // Only report as authenticated when dev mode is currently enabled
    if cookie_value.starts_with("dev:") && auth.config.dev_config.local_dev_mode {
        let parts: Vec<&str> = cookie_value.splitn(4, ':').collect();
        if parts.len() >= 4 {
            return axum::Json(serde_json::json!({
                "authenticated": true,
                "auth_enabled": true,
                "email": parts[1],
                "name": parts[2],
                "username": parts[3],
                "dev_mode": true
            }))
            .into_response();
        }
    }

    // Bearer header = raw JWT; Cookie value = session_id → resolve to access token
    let access_token = if bearer.is_some() {
        // Already have the raw token from Bearer header
        cookie_value
    } else {
        // Cookie value is a session_id — resolve via WebSessionManager
        match auth.session_manager.get_token(&cookie_value).await {
            Ok(token) => token,
            Err(e) => {
                tracing::debug!("Session token resolution failed for /auth/me: {}", e);
                return axum::Json(serde_json::json!({
                    "authenticated": false,
                    "auth_enabled": true
                }))
                .into_response();
            }
        }
    };

    // Real JWT — validate and return claims
    match auth.validate_token(&access_token).await {
        Ok(claims) => axum::Json(serde_json::json!({
            "authenticated": true,
            "auth_enabled": true,
            "sub": claims.sub,
            "email": claims.email,
            "name": claims.name,
            "username": claims.preferred_username,
            "dev_mode": false
        }))
        .into_response(),
        Err(e) => {
            tracing::debug!("Token validation failed for /auth/me: {}", e);
            axum::Json(serde_json::json!({
                "authenticated": false,
                "auth_enabled": true
            }))
            .into_response()
        }
    }
}

/// POST /auth/logout — destroy session and clear auth cookie.
async fn logout_handler(
    State(state): State<crate::ServerState>,
    headers: axum::http::HeaderMap,
) -> Response {
    let cookie_name = state
        .auth
        .as_ref()
        .map(|a| a.config.cookie_name.as_str())
        .unwrap_or("trustee_token");

    // Destroy the session on the server side
    if let Some(ref auth) = state.auth {
        if let Some(cookie_header) = headers.get(header::COOKIE).and_then(|v| v.to_str().ok()) {
            if let Some(session_id) = extract_token_from_cookies(cookie_header, cookie_name) {
                if !session_id.starts_with("dev:") {
                    let _ = auth.session_manager.destroy_session(&session_id);
                }
            }
        }
    }

    let cookie = Cookie::build((cookie_name.to_string(), ""))
        .path("/")
        .http_only(true)
        .same_site(SameSite::Lax)
        .max_age(TimeDuration::seconds(-1))
        .build();

    Response::builder()
        .status(StatusCode::FOUND)
        .header(header::LOCATION, "/")
        .header(header::SET_COOKIE, cookie.to_string())
        .body(Body::empty())
        .unwrap()
}

// ---------------------------------------------------------------------------
// MCP auth routes: /auth/mcp/login, /callback, /status, /logout (C2)
// ---------------------------------------------------------------------------

/// Query parameters for MCP login initiation.
#[derive(Debug, Deserialize)]
pub struct McpLoginQuery {
    pub cred: String,
}

/// Query parameters for MCP OIDC callback.
#[derive(Debug, Deserialize)]
pub struct McpCallbackQuery {
    pub code: Option<String>,
    pub state: Option<String>,
    pub error: Option<String>,
    pub error_description: Option<String>,
}

/// GET /auth/mcp/login?cred=<name> — initiate per-server OIDC PKCE login.
///
/// Reads the credential config from the session's config_toml, verifies it's
/// `type = "web-interactive"`, then redirects to the OIDC provider.
async fn mcp_login_handler(
    State(state): State<crate::ServerState>,
    Query(query): Query<McpLoginQuery>,
    headers: axum::http::HeaderMap,
) -> Result<Response, AuthError> {
    // Require authentication — user must be logged into trustee-web
    let (_cookie, _user_key) = crate::auth::check_auth(
        &state.auth,
        &headers,
        crate::auth::actions::UPDATE_MCP_CREDENTIALS,
    )
    .await
    .map_err(|_| AuthError::AuthNotConfigured)?;

    let auth = state.auth.as_ref().ok_or(AuthError::AuthNotConfigured)?;

    // Parse MCP credential config from session's config_toml
    let cred_config = load_mcp_credential(&state, &query.cred).await?;

    let (issuer_url, client_id, client_secret, scope) = match &cred_config {
        McpCredentialInfo::WebInteractive {
            issuer_url,
            client_id,
            client_secret,
            scope,
        } => (issuer_url.clone(), client_id.clone(), client_secret.clone(), scope.clone()),
        _ => {
            return Ok(Redirect::temporary(&format!(
                "/?mcp_error={}",
                urlencoding::encode(&format!("Credential '{}' is not web-interactive type", query.cred))
            ))
            .into_response());
        }
    };

    // Build PKCE pair using a separate PkceCookieManager for MCP
    let oidc_client = OidcClient::new();
    let verifier = OidcClient::generate_code_verifier();
    let challenge = OidcClient::generate_code_challenge(&verifier);
    let oauth_state = OidcClient::generate_state();

    // Build OidcClientConfig for the MCP credential's OIDC client
    let mcp_redirect_uri = format!(
        "{}/auth/mcp/callback",
        auth.client_config.redirect_uri.trim_end_matches('/').trim_end_matches("/auth/callback")
    );

    let mcp_client_config = OidcClientConfig {
        issuer_url: issuer_url.clone(),
        client_id: client_id.clone(),
        client_secret: client_secret.clone(),
        redirect_uri: mcp_redirect_uri.clone(),
        scope: scope.clone(),
        code_challenge_method: "S256".to_string(),
    };

    // Build authorization URL
    let auth_url = oidc_client
        .build_authorization_url(&mcp_client_config, &oauth_state, Some(&challenge))
        .await
        .map_err(|e| AuthError::OidcError(e.to_string()))?;

    // Store PKCE state + credential name in the in-memory map
    mcp_pkce().insert(oauth_state.clone(), verifier.clone(), query.cred.clone()).await;

    tracing::info!(
        "Initiating MCP browser login for credential '{}' (issuer={})",
        query.cred, issuer_url
    );

    Ok(Response::builder()
        .status(StatusCode::TEMPORARY_REDIRECT)
        .header(header::LOCATION, &auth_url)
        .body(Body::empty())
        .unwrap())
}

/// GET /auth/mcp/callback — handle MCP OIDC callback, store tokens.
async fn mcp_callback_handler(
    State(state): State<crate::ServerState>,
    Query(query): Query<McpCallbackQuery>,
    headers: axum::http::HeaderMap,
) -> Result<Response, AuthError> {
    let auth = state.auth.as_ref().ok_or(AuthError::AuthNotConfigured)?;

    // Check for errors from IdP
    if let Some(error) = query.error {
        let desc = query.error_description.unwrap_or_default();
        tracing::error!("MCP OIDC error: {} - {}", error, desc);
        return Ok(Redirect::temporary(&format!(
            "/?mcp_error={}&error_description={}",
            urlencoding::encode(&error),
            urlencoding::encode(&desc)
        ))
        .into_response());
    }

    let code = query.code.ok_or(AuthError::MissingCode)?;
    let oauth_state = query.state.ok_or(AuthError::MissingState)?;

    // Look up PKCE verifier + credential name from in-memory store
    let pkce_data = mcp_pkce().take(&oauth_state).await
        .ok_or(AuthError::InvalidState)?;

    let verifier = pkce_data.verifier;
    let cred_name = &pkce_data.cred_name;

    // Parse the MCP credential config to get OIDC settings for token exchange
    let cred_config = load_mcp_credential(&state, cred_name).await?;

    let (issuer_url, client_id, client_secret, scope) = match &cred_config {
        McpCredentialInfo::WebInteractive {
            issuer_url,
            client_id,
            client_secret,
            scope,
        } => (issuer_url.clone(), client_id.clone(), client_secret.clone(), scope.clone()),
        _ => {
            return Ok(Redirect::temporary(&format!(
                "/?mcp_error={}",
                urlencoding::encode("Credential is not web-interactive type")
            ))
            .into_response());
        }
    };

    // Build redirect URI (must match what was used in login)
    let mcp_redirect_uri = format!(
        "{}/auth/mcp/callback",
        auth.client_config.redirect_uri.trim_end_matches('/').trim_end_matches("/auth/callback")
    );

    let mcp_client_config = OidcClientConfig {
        issuer_url: issuer_url.clone(),
        client_id: client_id.clone(),
        client_secret: client_secret.clone(),
        redirect_uri: mcp_redirect_uri,
        scope: scope.clone(),
        code_challenge_method: "S256".to_string(),
    };

    // Exchange code for tokens
    tracing::info!("Exchanging MCP authorization code for tokens (credential={})", cred_name);
    let oidc_client = OidcClient::new();
    let token_response = oidc_client
        .exchange_code_for_tokens(&mcp_client_config, &code, Some(&verifier))
        .await
        .map_err(|e| AuthError::TokenExchangeFailed(e.to_string()))?;

    // Compute expires_at
    let expires_at = {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let expires_epoch = now + token_response.expires_in.unwrap_or(900);
        let days = expires_epoch / 86400;
        let rem = expires_epoch % 86400;
        let h = rem / 3600;
        let m = (rem % 3600) / 60;
        let s = rem % 60;
        let z = days as i64 + 719468;
        let era = if z >= 0 { z } else { z - 146096 } / 146097;
        let doe = (z - era * 146097) as u64;
        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
        let y = yoe as i64 + era * 400;
        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
        let mp = (5 * doy + 2) / 153;
        let d = doy - (153 * mp + 2) / 5 + 1;
        let mon = if mp < 10 { mp + 3 } else { mp - 9 };
        let yr = if mon <= 2 { y + 1 } else { y };
        format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", yr, mon, d, h, m, s)
    };

    // Store via FileTokenStore (same as `trustee mcp auth`)
    use pep::{FileTokenStore, StoredToken, TokenStore};

    let stored = StoredToken::new(
        &token_response.access_token,
        token_response.refresh_token.clone(),
        "Bearer",
        &expires_at,
        token_response.scope.clone(),
    );

    let agent_name = state.config_toml.as_ref().and_then(|t| {
        toml::from_str::<toml::Value>(t).ok()
            .and_then(|v| v.get("agent").and_then(|a| a.get("name")).and_then(|n| n.as_str()).map(String::from))
    }).unwrap_or_else(|| "trustee".to_string());
    let token_store = FileTokenStore::new(&agent_name);

    if let Err(e) = token_store.save(cred_name, &stored) {
        tracing::error!("Failed to store MCP token: {}", e);
        return Ok(Redirect::temporary(&format!(
            "/?mcp_error={}",
            urlencoding::encode(&format!("Failed to store token: {}", e))
        ))
        .into_response());
    }

    tracing::info!(
        "MCP authentication successful for credential '{}' (expires {})",
        cred_name, expires_at
    );

    Ok(Response::builder()
        .status(StatusCode::FOUND)
        .header(header::LOCATION, format!("/?mcp_connected={}", urlencoding::encode(cred_name)))
        .body(Body::empty())
        .unwrap())
}

/// GET /auth/mcp/status — return connection status for all MCP credentials.
async fn mcp_status_handler(
    State(state): State<crate::ServerState>,
    headers: axum::http::HeaderMap,
) -> Response {
    use pep::{FileTokenStore, TokenStore};

    // Require auth
    let (_cookie, user_key) = match crate::auth::check_auth(
        &state.auth,
        &headers,
        crate::auth::actions::VIEW_MCP_CREDENTIALS,
    )
    .await
    {
        Ok(result) => result,
        Err(code) => return (code, Json(serde_json::json!({"error": "Unauthorized"}))).into_response(),
    };

    // Parse MCP config from session
    let config_toml = {
        let (_sid, session_arc, _, _) = state.ensure_active_session(&user_key).await;
        let session = session_arc.lock().await;
        match &session.config_toml {
            Some(t) => t.clone(),
            None => return (StatusCode::INTERNAL_SERVER_ERROR, "Config not loaded").into_response(),
        }
    };

    let mcp_config: toml::Value = match toml::from_str(&config_toml) {
        Ok(v) => v,
        Err(_) => return Json(serde_json::json!([])).into_response(),
    };

    let agent_name = {
        let (_sid, session_arc, _, _) = state.ensure_active_session(&user_key).await;
        let session = session_arc.lock().await;
        session.agent_name.clone()
    };
    let token_store = FileTokenStore::new(&agent_name);

    // Build server → credential mapping
    let servers = mcp_config
        .get("mcp")
        .and_then(|m| m.get("servers"))
        .and_then(|s| s.as_array());
    let credentials = mcp_config
        .get("mcp")
        .and_then(|m| m.get("credentials"))
        .and_then(|c| c.as_table());

    let mut cred_servers: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();
    if let Some(servers) = servers {
        for server in servers {
            let name = server.get("name").and_then(|n| n.as_str()).unwrap_or("");
            let cred_ref = server.get("credentials").and_then(|c| c.as_str()).unwrap_or("");
            if !cred_ref.is_empty() {
                cred_servers
                    .entry(cred_ref.to_string())
                    .or_default()
                    .push(name.to_string());
            }
        }
    }

    let mut result = Vec::new();

    if let Some(creds) = credentials {
        for (cred_name, cred_config) in creds {
            let cred_type = cred_config.get("type").and_then(|t| t.as_str()).unwrap_or("unknown");
            let servers_using = cred_servers.get(cred_name).cloned().unwrap_or_default();

            if cred_type == "web-session" {
                // Session credentials are always "connected" if auth is enabled
                let connected = state.auth.is_some();
                result.push(serde_json::json!({
                    "credential": cred_name,
                    "type": cred_type,
                    "connected": connected,
                    "servers": servers_using,
                }));
            } else if cred_type == "service-account" {
                // Long-lived service token, exchanged lazily (RFC 8693) by the
                // agent at runtime. "Connected" = the service_token resolved to
                // a non-empty value in this (already ${VAR}-substituted) config.
                let token = cred_config
                    .get("service_token")
                    .and_then(|t| t.as_str())
                    .unwrap_or("");
                result.push(serde_json::json!({
                    "credential": cred_name,
                    "type": cred_type,
                    "connected": !token.is_empty(),
                    "servers": servers_using,
                }));
            } else if cred_type == "static" {
                // Static token — connected when it resolved non-empty.
                let token = cred_config
                    .get("token")
                    .and_then(|t| t.as_str())
                    .unwrap_or("");
                result.push(serde_json::json!({
                    "credential": cred_name,
                    "type": cred_type,
                    "connected": !token.is_empty(),
                    "servers": servers_using,
                }));
            } else if cred_type == "web-interactive" || cred_type == "interactive" {
                // Check token store
                let status = match token_store.load(cred_name) {
                    Ok(Some(token)) => {
                        let expired = token.is_expired();
                        serde_json::json!({
                            "credential": cred_name,
                            "type": cred_type,
                            "connected": !expired,
                            "expires_at": token.expires_at,
                            "servers": servers_using,
                        })
                    }
                    _ => serde_json::json!({
                        "credential": cred_name,
                        "type": cred_type,
                        "connected": false,
                        "servers": servers_using,
                    }),
                };
                result.push(status);
            }
        }
    }

    Json(serde_json::Value::Array(result)).into_response()
}

/// POST /auth/mcp/logout?cred=<name> — remove stored MCP tokens.
async fn mcp_logout_handler(
    State(state): State<crate::ServerState>,
    Query(query): Query<McpLoginQuery>,
    headers: axum::http::HeaderMap,
) -> Response {
    use pep::{FileTokenStore, TokenStore};

    // Require auth
    let (_cookie, user_key) = match crate::auth::check_auth(
        &state.auth,
        &headers,
        crate::auth::actions::UPDATE_MCP_CREDENTIALS,
    )
    .await
    {
        Ok(result) => result,
        Err(code) => return (code, Json(serde_json::json!({"error": "Unauthorized"}))).into_response(),
    };

    let agent_name = {
        let (_sid, session_arc, _, _) = state.ensure_active_session(&user_key).await;
        let session = session_arc.lock().await;
        session.agent_name.clone()
    };
    let token_store = FileTokenStore::new(&agent_name);

    match token_store.delete(&query.cred) {
        Ok(()) => {
            tracing::info!("Removed MCP credentials for '{}'", query.cred);
            Json(serde_json::json!({"success": true})).into_response()
        }
        Err(e) => {
            tracing::error!("Failed to remove MCP credentials: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({"error": e.to_string()})),
            )
                .into_response()
        }
    }
}

// ---------------------------------------------------------------------------
// MCP auth helpers
// ---------------------------------------------------------------------------

/// In-memory store for MCP PKCE state (state token → verifier + credential name).
/// Entries expire after 10 minutes. Not persisted across restarts.
struct McpPkceStore {
    entries: tokio::sync::Mutex<std::collections::HashMap<String, McpPkceEntry>>,
}

struct McpPkceEntry {
    verifier: String,
    cred_name: String,
    created_at: std::time::Instant,
}

impl McpPkceStore {
    fn new() -> Self {
        Self {
            entries: tokio::sync::Mutex::new(std::collections::HashMap::new()),
        }
    }

    /// Insert a PKCE entry. Cleans up entries older than 10 minutes.
    async fn insert(&self, state: String, verifier: String, cred_name: String) {
        let mut map = self.entries.lock().await;
        // Cleanup expired entries (older than 10 min)
        let cutoff = std::time::Instant::now() - std::time::Duration::from_secs(600);
        map.retain(|_, v| v.created_at > cutoff);
        map.insert(state, McpPkceEntry {
            verifier,
            cred_name,
            created_at: std::time::Instant::now(),
        });
    }

    /// Take and remove a PKCE entry (single-use).
    async fn take(&self, state: &str) -> Option<McpPkceEntry> {
        let mut map = self.entries.lock().await;
        map.remove(state)
    }
}

/// Global singleton PKCE store for MCP browser logins.
static MCP_PKCE: std::sync::OnceLock<McpPkceStore> = std::sync::OnceLock::new();

/// Get or initialize the global MCP PKCE store.
fn mcp_pkce() -> &'static McpPkceStore {
    MCP_PKCE.get_or_init(McpPkceStore::new)
}

/// Simplified MCP credential info (parsed from TOML).
enum McpCredentialInfo {
    WebInteractive {
        issuer_url: String,
        client_id: String,
        client_secret: Option<String>,
        scope: String,
    },
    Other(String),
}

/// Load a specific MCP credential from the session's config_toml.
async fn load_mcp_credential(
    state: &crate::ServerState,
    cred_name: &str,
) -> Result<McpCredentialInfo, AuthError> {
    let config_toml = state
        .config_toml
        .clone()
        .ok_or(AuthError::AuthNotConfigured)?;

    let config: toml::Value = toml::from_str(&config_toml)
        .map_err(|e| AuthError::OidcError(format!("Config parse error: {}", e)))?;

    let cred = config
        .get("mcp")
        .and_then(|m| m.get("credentials"))
        .and_then(|c| c.as_table())
        .and_then(|c| c.get(cred_name))
        .ok_or_else(|| AuthError::OidcError(format!("Credential '{}' not found", cred_name)))?;

    let cred_type = cred.get("type").and_then(|t| t.as_str()).unwrap_or("unknown");

    match cred_type {
        "web-interactive" => {
            let issuer_url = cred
                .get("issuer_url")
                .and_then(|v| v.as_str())
                .ok_or_else(|| AuthError::OidcError("Missing issuer_url".into()))?
                .to_string();
            let client_id = cred
                .get("client_id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| AuthError::OidcError("Missing client_id".into()))?
                .to_string();
            let client_secret = cred
                .get("client_secret")
                .and_then(|v| v.as_str())
                .map(String::from);
            let scope = cred
                .get("scope")
                .and_then(|v| v.as_str())
                .unwrap_or("openid profile email")
                .to_string();

            Ok(McpCredentialInfo::WebInteractive {
                issuer_url,
                client_id,
                client_secret,
                scope,
            })
        }
        other => Ok(McpCredentialInfo::Other(other.to_string())),
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Create an HttpOnly auth cookie.
fn create_auth_cookie(name: &str, value: &str, max_age: StdDuration, secure: bool) -> Cookie<'static> {
    Cookie::build((name.to_string(), value.to_string()))
        .path("/")
        .http_only(true)
        .same_site(SameSite::Lax)
        .secure(secure)
        .max_age(TimeDuration::seconds(max_age.as_secs() as i64))
        .build()
}

// ---------------------------------------------------------------------------
// Error handling
// ---------------------------------------------------------------------------

/// Authentication errors.
#[derive(Debug)]
pub enum AuthError {
    MissingCode,
    MissingState,
    InvalidState,
    OidcError(String),
    TokenExchangeFailed(String),
    AuthNotConfigured,
}

impl IntoResponse for AuthError {
    fn into_response(self) -> Response {
        let (_status, msg) = match self {
            AuthError::MissingCode => (StatusCode::BAD_REQUEST, "Missing authorization code"),
            AuthError::MissingState => (StatusCode::BAD_REQUEST, "Missing state parameter"),
            AuthError::InvalidState => (StatusCode::BAD_REQUEST, "Invalid or expired state"),
            AuthError::OidcError(_) => (StatusCode::SERVICE_UNAVAILABLE, "Authentication service error"),
            AuthError::TokenExchangeFailed(_) => (StatusCode::BAD_REQUEST, "Token exchange failed"),
            AuthError::AuthNotConfigured => (StatusCode::NOT_IMPLEMENTED, "Authentication not configured"),
        };
        Redirect::temporary(&format!("/?error={}", urlencoding::encode(msg))).into_response()
    }
}

#[cfg(test)]
mod principal_tests {
    use super::*;
    use pep::oidc::types::JwtClaims;
    use std::collections::HashMap;

    fn claims_with_role(role: serde_json::Value) -> JwtClaims {
        let mut c = JwtClaims::default();
        c.sub = "sub-uuid".to_string();
        c.preferred_username = Some("farzan".to_string());
        c.extra.insert("role".to_string(), role);
        c
    }

    // -- dev_user_key (16D dev:agent namespace) ------------------------------

    #[test]
    fn dev_agent_token_yields_agent_namespaced_key() {
        assert_eq!(
            dev_user_key("dev:agent:farzan"),
            Some("agent-farzan".to_string())
        );
        assert_eq!(
            dev_user_key("dev:agent:paydar"),
            Some("agent-paydar".to_string())
        );
    }

    #[test]
    fn dev_agent_token_rejects_empty_and_colon_names() {
        assert_eq!(dev_user_key("dev:agent:"), None);
        assert_eq!(dev_user_key("dev:agent:  "), None);
        assert_eq!(
            dev_user_key("dev:agent:a:b"),
            None,
            "name must not contain ':'"
        );
    }

    #[test]
    fn dev_human_token_format_unchanged() {
        assert_eq!(
            dev_user_key("dev:a@b.c:Some Name:someuser"),
            Some("dev:a@b.c".to_string())
        );
        assert_eq!(dev_user_key("dev:only:two"), None);
    }

    // -- claim_role / PrincipalKind (string OR array role) --------------------

    #[test]
    fn role_as_string_classifies_agent() {
        let c = claims_with_role(serde_json::json!("agent"));
        assert_eq!(claim_role(&c).as_deref(), Some("agent"));
        assert_eq!(AuthUser::from(c).kind, PrincipalKind::Agent);
    }

    #[test]
    fn role_as_array_takes_first_value() {
        // Kanidm may deliver role as an array (pep 366e8ed lesson).
        let c = claims_with_role(serde_json::json!(["agent", "other"]));
        assert_eq!(claim_role(&c).as_deref(), Some("agent"));
        assert_eq!(AuthUser::from(c).kind, PrincipalKind::Agent);
    }

    #[test]
    fn non_agent_roles_classify_human() {
        for role in ["user", "admin", "service"] {
            let c = claims_with_role(serde_json::json!(role));
            assert_eq!(claim_role(&c).as_deref(), Some(role));
            assert_eq!(AuthUser::from(c).kind, PrincipalKind::Human, "role={role}");
        }
    }

    #[test]
    fn missing_or_nonstring_role_classifies_human() {
        let mut c = JwtClaims::default();
        c.sub = "sub-uuid".to_string();
        assert_eq!(claim_role(&c), None);
        assert_eq!(AuthUser::from(c.clone()).kind, PrincipalKind::Human);
        c.extra.insert("role".to_string(), serde_json::json!(42));
        assert_eq!(claim_role(&c), None, "non-string non-array role ignored");
    }

    // -- jwt_user_key (PINNED: preferred_username || sub, never email) --------

    #[test]
    fn user_key_prefers_preferred_username() {
        let mut c = JwtClaims::default();
        c.sub = "sub-uuid".to_string();
        c.preferred_username = Some("farzan".to_string());
        c.email = Some("rebindable@example.com".to_string());
        assert_eq!(jwt_user_key(&c), "farzan", "email must never be the key");
    }

    #[test]
    fn user_key_falls_back_to_sub_on_blank_username() {
        let mut c = JwtClaims::default();
        c.sub = "sub-uuid".to_string();
        c.preferred_username = Some("   ".to_string());
        assert_eq!(jwt_user_key(&c), "sub-uuid");
        c.preferred_username = None;
        assert_eq!(jwt_user_key(&c), "sub-uuid");
    }

    #[test]
    fn user_key_agent_pinned_to_sub_even_with_username() {
        // 16E: agent principals NEVER use preferred_username — a future
        // token-scope change must not re-home agent namespaces.
        let mut c = claims_with_role(serde_json::json!("agent"));
        c.sub = "agent-sub-uuid".to_string();
        c.preferred_username = Some("farzan".to_string());
        assert_eq!(jwt_user_key(&c), "agent-sub-uuid");
    }

    #[test]
    fn authuser_carries_role_and_kind() {
        let c = claims_with_role(serde_json::json!("agent"));
        let u = AuthUser::from(c);
        assert_eq!(u.role.as_deref(), Some("agent"));
        assert_eq!(u.kind, PrincipalKind::Agent);
        assert_eq!(u.username.as_deref(), Some("farzan"));
    }
}

#[cfg(test)]
mod cedar_p2_tests {
    use super::*;
    use cedar_policy::{Context, Entities, EntityUid, Request};
    use pep::cedar::{CedarAuthorizer, CedarConfig};
    use std::collections::HashMap;

    const POLICY: &str = include_str!("../policies/trustee_default.cedar");
    const SCHEMA: &str = include_str!("../policies/trustee_schema.cedarschema");

    async fn authorizer() -> CedarAuthorizer {
        // Unique per call: tests run concurrently and must not share files.
        static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        let dir = std::env::temp_dir().join(format!("trustee-cedar-p2-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("temp dir");
        let policy_path = dir.join("trustee_default.cedar");
        let schema_path = dir.join("trustee_schema.cedarschema");
        std::fs::write(&policy_path, POLICY).expect("write policy");
        std::fs::write(&schema_path, SCHEMA).expect("write schema");
        let cfg = CedarConfig {
            policy_path,
            schema_path: Some(schema_path),
            entities_path: None,
            default_decision: pep::cedar::DefaultDecision::Deny,
            validate_on_load: true,
            policy_store_url: None,
            policy_store_token: None,
            embedded_policy: Some(POLICY),
            embedded_schema: Some(SCHEMA),
        };
        CedarAuthorizer::new_with_policy_store(cfg)
            .await
            .expect("Cedar init from shipped sources")
    }

    fn claims_with_role(role: Option<&str>) -> JwtClaims {
        let mut c = JwtClaims::default();
        c.sub = "test-sub".to_string();
        if let Some(r) = role {
            c.extra.insert("role".to_string(), serde_json::json!(r));
        }
        c
    }

    /// Mirrors check_cedar_authorized's request construction exactly.
    async fn allowed(auth: &CedarAuthorizer, role: Option<&str>, action: &str) -> bool {
        let claims = claims_with_role(role);
        let principal_entity = pep::cedar::build_principal_entity(&claims).unwrap();
        let app_entity = cedar_policy::Entity::new(
            EntityUid::from_str(r#"TrusteeApp::"default""#).unwrap(),
            HashMap::new(),
            std::collections::HashSet::new(),
        )
        .unwrap();
        let entities = Entities::from_entities(vec![principal_entity, app_entity], None).unwrap();
        let request = Request::new(
            pep::cedar::build_principal_uid(&claims).unwrap(),
            EntityUid::from_str(&format!("Action::\"{action}\"")).unwrap(),
            EntityUid::from_str(r#"TrusteeApp::"default""#).unwrap(),
            Context::empty(),
            None,
        )
        .unwrap();
        auth.is_allowed_with_entities(&request, &entities).allowed()
    }

    #[tokio::test]
    async fn admin_allowed_including_destructive() {
        let auth = authorizer().await;
        for action in [
            actions::VIEW_SESSION,
            actions::COMMAND_SESSION,
            actions::DELETE_SESSION,
            actions::UPDATE_MCP_CREDENTIALS,
        ] {
            assert!(
                allowed(&auth, Some("admin"), action).await,
                "admin {action}"
            );
        }
    }

    #[tokio::test]
    async fn user_full_session_management() {
        let auth = authorizer().await;
        for action in [
            actions::CREATE_SESSION,
            actions::COMMAND_SESSION,
            actions::DELETE_SESSION,
            actions::VIEW_HISTORY,
            actions::UPDATE_MCP_CREDENTIALS,
        ] {
            assert!(allowed(&auth, Some("user"), action).await, "user {action}");
        }
    }

    #[tokio::test]
    async fn agent_working_set_but_delete_denied() {
        let auth = authorizer().await;
        for action in [
            actions::CREATE_SESSION,
            actions::COMMAND_SESSION,
            actions::CANCEL_SESSION,
            actions::RESUME_SESSION,
            actions::VIEW_HISTORY,
            actions::UPDATE_MCP_CREDENTIALS,
        ] {
            assert!(
                allowed(&auth, Some("agent"), action).await,
                "agent {action}"
            );
        }
        assert!(
            !allowed(&auth, Some("agent"), actions::DELETE_SESSION).await,
            "agent must NOT delete sessions (fail-closed start; revisit at task F)"
        );
    }

    #[tokio::test]
    async fn service_read_only() {
        let auth = authorizer().await;
        for action in [
            actions::VIEW_SESSION,
            actions::LIST_SESSIONS,
            actions::VIEW_HISTORY,
        ] {
            assert!(allowed(&auth, Some("service"), action).await, "service {action}");
        }
        for action in [actions::COMMAND_SESSION, actions::DELETE_SESSION] {
            assert!(
                !allowed(&auth, Some("service"), action).await,
                "service {action} denied"
            );
        }
    }

    #[tokio::test]
    async fn missing_or_unknown_role_denied_everything() {
        let auth = authorizer().await;
        for role in [None, Some("intern"), Some("Admin")] {
            assert!(
                !allowed(&auth, role, actions::VIEW_SESSION).await,
                "role={role:?} must be denied (fail-closed default)"
            );
        }
    }

    #[test]
    fn boot_decision_is_fail_closed() {
        assert!(crate::cedar_boot_decision(true, false, false).is_err());
        assert!(crate::cedar_boot_decision(true, false, true).is_ok());
        assert!(crate::cedar_boot_decision(true, true, false).is_ok());
        assert!(crate::cedar_boot_decision(false, false, false).is_ok());
    }
}