cheers-server 0.8.36

Origin-side surface for cheers — secret-key minter, symmetric codecs, UserStore/RefreshStore, refresh rotation, RevocationWriter, and the SessionAuthority facade.
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
//! The [`McpAuthority`] origin facade for minting MCP-call tokens.
//!
//! Composes the moving parts the doc lays out in `.yah/docs/working/
//! mcp-auth-and-ownership.md` §Mint flows:
//!
//! - [`PasetoV4SecretMinter::mint_mcp`](crate::codec::PasetoV4SecretMinter::mint_mcp)
//!   — the signing primitive (R020-T15, v4.public over Ed25519).
//! - [`GrantStore`](crate::grants::GrantStore) — per-(principal, aud) grant
//!   entries; empty result = no entitlement = mint rejected (composition rule
//!   (5)).
//! - [`BundleStore`](crate::bundles::BundleStore) +
//!   [`expand_scopes`](crate::bundles::expand_scopes) — bundle expansion at
//!   mint time (R020-F5, rule (2)).
//! - [`validate_grant`] — composition rule (4) defence in depth: a bundle
//!   that smuggles a service-only scope into a user grant is caught here
//!   before signing.
//! - [`OwnershipStore`](crate::ownership::OwnershipStore) — the `owns` claim
//!   source of truth, read at mint time and baked into the token (R020-F4 /
//!   W159 §Layer 2).
//!
//! Mirrors the [`SessionAuthority`](crate::session::SessionAuthority) shape:
//! generic over the capability set so the assembled deployment is visible in
//! the type, and the absence of a verifier here keeps mint power confined to
//! this crate (the edge holds
//! [`PasetoV4PublicVerifier`](cheers_verify::PasetoV4PublicVerifier), never a
//! minter).

use cheers_core::{
    validate_grant, Actor, AuthStrength, CodecError, Error, GrantError, McpClaims, Owns,
    PrincipalId, PrincipalKind, Scope, StoreError,
};

use crate::bundles::{expand_scopes, BundleExpansionError, BundleStore};
use crate::codec::PasetoV4SecretMinter;
use crate::grants::GrantStore;
use crate::ownership::{OwnershipRow, OwnershipStore};
use crate::session::generate_jti;

/// TTL defaults for an MCP-call token.
///
/// Short by design — per `.yah/docs/working/mcp-auth-and-ownership.md` §TTLs,
/// the 5–15 minute access window is also the propagation bound for
/// revocations and ownership-table edits when no `ownership_version`
/// freshness backstop is in play.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct McpPolicy {
    /// Per-call access-token lifetime in seconds.
    pub access_ttl_seconds: i64,
}

impl McpPolicy {
    /// 10 minutes — middle of the doc's 5–15 min range.
    pub const DEFAULT_ACCESS_TTL_SECONDS: i64 = 10 * 60;

    pub fn new(access_ttl_seconds: i64) -> Self {
        Self { access_ttl_seconds }
    }

    pub fn with_access_ttl(mut self, seconds: i64) -> Self {
        self.access_ttl_seconds = seconds;
        self
    }
}

impl Default for McpPolicy {
    fn default() -> Self {
        Self {
            access_ttl_seconds: Self::DEFAULT_ACCESS_TTL_SECONDS,
        }
    }
}

/// A freshly-minted MCP-call token plus the [`McpClaims`] it carries.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct MintedMcpToken {
    /// The signed `v4.public.*` token string.
    pub token: String,
    /// The claims embedded in `token`, including the freshly minted `jti`.
    pub claims: McpClaims,
}

/// Why a mint attempt failed before (or after) the signing step.
///
/// Typed so the HTTP layer (R020-T17 routes) can map specific failures to the
/// right status code: `AudNotEntitled` → 403, `GrantMisconfigured` → 500
/// (server-side data bug), `Store` → 503, `Codec` → 500.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum McpMintError {
    /// Composition rule (5) — the principal holds no grant for the requested
    /// `aud`. Per-call rejection, returned before any signing happens.
    #[error("no entitlement: principal '{principal}' has no grant for aud '{aud}'")]
    AudNotEntitled { principal: String, aud: String },
    /// RFC 8693 — a requested scope on a token-exchange is not in the
    /// intersection of both principals' grants for this `aud`. Per the doc
    /// (`§Mint flows` → token exchange), the whole exchange is rejected —
    /// `invalid_scope`, not a partial token. Maps to HTTP 400 `invalid_scope`.
    #[error("requested scope '{scope}' is not granted by both principals for aud '{aud}'")]
    InvalidScope { scope: Scope, aud: String },
    /// The caller passed the wrong principal kind for this mint path — e.g.
    /// `mint_user_fresh` invoked with `svc:` or `camp:` in the `sub` slot.
    /// A programmer-error, not a user-input rejection: surface 500, not 403.
    #[error("mint path expects {expected} principal; got {got}")]
    WrongPrincipalKind {
        expected: PrincipalKind,
        got: PrincipalKind,
    },
    /// Composition rule (4) defence in depth — bundle expansion produced a
    /// service-only scope for a non-service principal. Indicates a
    /// misconfigured bundle or a grant that should have been rejected at the
    /// grant API; surface as 500.
    #[error(transparent)]
    GrantMisconfigured(#[from] GrantError),
    /// Bundle expansion failed (unknown bundle / store error inside
    /// expansion).
    #[error(transparent)]
    BundleExpansion(#[from] BundleExpansionError),
    /// Underlying store failure (grants / ownership).
    #[error(transparent)]
    Store(#[from] StoreError),
    /// Signing failure inside the codec layer.
    #[error(transparent)]
    Codec(#[from] CodecError),
}

impl From<McpMintError> for Error {
    fn from(e: McpMintError) -> Self {
        match e {
            McpMintError::Store(s) => Error::Store(s),
            McpMintError::Codec(c) => Error::Codec(c),
            McpMintError::BundleExpansion(BundleExpansionError::Store(s)) => Error::Store(s),
            // Structured rejections (AudNotEntitled, WrongPrincipalKind,
            // GrantMisconfigured, BundleExpansion::Unknown) carry a message
            // that's safe to surface; route them through InvalidInput so a
            // caller that doesn't pattern-match on McpMintError still gets a
            // sensible umbrella error.
            other => Error::InvalidInput(other.to_string()),
        }
    }
}

/// Origin facade: everything that can *mint* an MCP-call token.
///
/// Holds the four origin-tier capabilities for the MCP boundary — a
/// [`PasetoV4SecretMinter`], a [`BundleStore`], a [`GrantStore`], and an
/// [`OwnershipStore`] — plus the cheers issuer URL and an [`McpPolicy`].
/// Generic (not `dyn`) so the assembled capability set is visible in the
/// type. The matching edge-side verifier is
/// [`PasetoV4PublicVerifier`](cheers_verify::PasetoV4PublicVerifier) +
/// `verify_mcp_at`; the verify-only consumer (kamaji) never depends on
/// this crate.
pub struct McpAuthority<B, G, O> {
    minter: PasetoV4SecretMinter,
    bundles: B,
    grants: G,
    ownership: O,
    iss: String,
    /// `kid` stamped into every minted token's PASETO footer (R592-B7 wire
    /// convention) — identifies which published key `minter` signs with, so
    /// an edge verifier's JWKS/footer lookup can find the matching pubkey.
    kid: String,
    policy: McpPolicy,
}

impl<B, G, O> McpAuthority<B, G, O>
where
    B: BundleStore,
    G: GrantStore,
    O: OwnershipStore,
{
    /// Assemble an authority with the [default policy](McpPolicy::default).
    ///
    /// `kid` is the footer identifier published alongside `minter`'s public
    /// key (e.g. in cheers's JWKS) — every token this authority mints carries
    /// it so a verifier can select the right key.
    pub fn new(
        minter: PasetoV4SecretMinter,
        bundles: B,
        grants: G,
        ownership: O,
        iss: impl Into<String>,
        kid: impl Into<String>,
    ) -> Self {
        Self {
            minter,
            bundles,
            grants,
            ownership,
            iss: iss.into(),
            kid: kid.into(),
            policy: McpPolicy::default(),
        }
    }

    /// Override the TTL policy.
    pub fn with_policy(mut self, policy: McpPolicy) -> Self {
        self.policy = policy;
        self
    }

    pub fn policy(&self) -> &McpPolicy {
        &self.policy
    }

    pub fn issuer(&self) -> &str {
        &self.iss
    }

    /// **Mint path 1** — user-initiated, passkey-fresh (R020-F6).
    ///
    /// Returns a token bearing
    /// `{sub: user:<U>, act?, camp_id?, scope: [...], owns: {...}, auth_strength: "user-fresh"}`.
    /// Required inputs:
    ///
    /// - `user`: the authenticated user's principal (kind MUST be
    ///   [`PrincipalKind::User`]).
    /// - `actor`: the optional `act` claim (RFC 8693) — the agent acting on
    ///   the user's behalf. The agent is never the primary `sub`.
    /// - `camp_id`: when set, both populates the `camp_id` claim and is the
    ///   key used to look up the `owns` claim (rows held by
    ///   `camp:<camp_id>`).
    /// - `aud`: the target resource URI for this call. Per composition rule
    ///   (5) the principal MUST hold at least one grant entry for `aud` — an
    ///   empty grant list returns [`McpMintError::AudNotEntitled`] before
    ///   any signing happens.
    /// - `now`: unix seconds. `iat = now`, `exp = now + policy.access_ttl`.
    ///
    /// The pipeline: grants → [`expand_scopes`] → [`validate_grant`] per
    /// scope (rule (4) defence) → ownership lookup → sign with `mint_mcp`.
    pub async fn mint_user_fresh(
        &self,
        user: PrincipalId,
        actor: Option<Actor>,
        camp_id: Option<String>,
        aud: impl Into<String>,
        now: i64,
    ) -> Result<MintedMcpToken, McpMintError> {
        if user.kind != PrincipalKind::User {
            return Err(McpMintError::WrongPrincipalKind {
                expected: PrincipalKind::User,
                got: user.kind,
            });
        }
        let aud = aud.into();

        let entries = self.grants.list_for(&user, &aud).await?;
        if entries.is_empty() {
            return Err(McpMintError::AudNotEntitled {
                principal: user.to_string(),
                aud,
            });
        }

        let scopes = expand_scopes(&self.bundles, &entries).await?;
        for s in &scopes {
            validate_grant(user.kind, *s)?;
        }

        let owns = match &camp_id {
            Some(id) => {
                let camp_principal = PrincipalId::camp(id);
                let rows = self.ownership.list_for_principal(&camp_principal).await?;
                rows_to_owns(&rows)
            }
            None => Owns::default(),
        };

        let mut claims = McpClaims::new(
            self.iss.clone(),
            aud,
            user,
            now,
            now + self.policy.access_ttl_seconds,
            generate_jti(),
            scopes,
        )
        .with_auth_strength(AuthStrength::UserFresh);
        if let Some(a) = actor {
            claims = claims.with_act(a);
        }
        if let Some(c) = camp_id {
            claims = claims.with_camp_id(c);
        }
        if !owns.is_empty() {
            claims = claims.with_owns(owns);
        }

        let token = self.minter.mint_mcp(&claims, &self.kid)?;
        Ok(MintedMcpToken { token, claims })
    }

    /// **Mint path 2** — bootstrapped camp, autonomous (R020-F7).
    ///
    /// For yubaba-hosted camps operating without a live user session: the
    /// camp's bootstrap credential authenticates upstream of this call, and
    /// the verified camp principal is what arrives here. Returns a token
    /// bearing
    /// `{sub: camp:<C>, camp_id: <C>, scope: [...], owns: {...}, auth_strength: "bootstrap"}`
    /// — note **no `act` claim** on this path, the camp itself is the
    /// principal (not a user acted-on-by an agent).
    ///
    /// Required inputs:
    ///
    /// - `camp`: the authenticated camp's principal (kind MUST be
    ///   [`PrincipalKind::Camp`]). `camp_id` on the resulting claim is the
    ///   bare id (sans `camp:` prefix), so a consumer doesn't have to re-
    ///   parse `sub` to learn it.
    /// - `aud`: the target resource URI for this call. Per composition rule
    ///   (5) the camp MUST hold at least one grant entry for `aud` — an empty
    ///   grant list returns [`McpMintError::AudNotEntitled`] before signing.
    /// - `now`: unix seconds. `iat = now`, `exp = now + policy.access_ttl`.
    ///
    /// Same pipeline as [`mint_user_fresh`](Self::mint_user_fresh): grants →
    /// [`expand_scopes`] → [`validate_grant`] per scope (rule (4) defence —
    /// catches a bundle that smuggles `ownership:write` into a camp grant) →
    /// ownership lookup → sign with `mint_mcp`.
    pub async fn mint_bootstrap(
        &self,
        camp: PrincipalId,
        aud: impl Into<String>,
        now: i64,
    ) -> Result<MintedMcpToken, McpMintError> {
        if camp.kind != PrincipalKind::Camp {
            return Err(McpMintError::WrongPrincipalKind {
                expected: PrincipalKind::Camp,
                got: camp.kind,
            });
        }
        let aud = aud.into();

        let entries = self.grants.list_for(&camp, &aud).await?;
        if entries.is_empty() {
            return Err(McpMintError::AudNotEntitled {
                principal: camp.to_string(),
                aud,
            });
        }

        let scopes = expand_scopes(&self.bundles, &entries).await?;
        for s in &scopes {
            validate_grant(camp.kind, *s)?;
        }

        let rows = self.ownership.list_for_principal(&camp).await?;
        let owns = rows_to_owns(&rows);

        let camp_id = camp.id.clone();
        let mut claims = McpClaims::new(
            self.iss.clone(),
            aud,
            camp,
            now,
            now + self.policy.access_ttl_seconds,
            generate_jti(),
            scopes,
        )
        .with_camp_id(camp_id)
        .with_auth_strength(AuthStrength::Bootstrap);
        if !owns.is_empty() {
            claims = claims.with_owns(owns);
        }

        let token = self.minter.mint_mcp(&claims, &self.kid)?;
        Ok(MintedMcpToken { token, claims })
    }

    /// **Mint path 3** — RFC 8693 token-exchange (R020-F8).
    ///
    /// The ONLY path that crosses principals: a multi-player camp daemon
    /// (`subject_token` = camp bootstrap credential) presents a human's
    /// session token (`actor_token` = user's session) and asks for a token
    /// attributed to the *human*, with the camp as call context. The result
    /// looks like a `mint_user_fresh` token — same `auth_strength=user-fresh`
    /// because the user authenticated locally — but the camp's grants
    /// constrain it.
    ///
    /// Inputs (already-verified principals — credential checks live at the
    /// HTTP `/token` endpoint, same way passkey assertion sits upstream of
    /// [`mint_user_fresh`](Self::mint_user_fresh)):
    ///
    /// - `user`: the verified user from `actor_token` (kind MUST be
    ///   [`PrincipalKind::User`]).
    /// - `camp`: the verified camp from `subject_token` (kind MUST be
    ///   [`PrincipalKind::Camp`]).
    /// - `actor`: the optional `act` claim — the agent variant acting on the
    ///   user's behalf (RFC 8693).
    /// - `aud`: target resource URI. BOTH principals must hold a grant for
    ///   it (composition rule (5) applies per side).
    /// - `requested_scope`: the scopes the exchange asks for. EVERY entry
    ///   must be in the intersection of the user's expanded-grant scopes AND
    ///   the camp's expanded-grant scopes for this aud. A requested scope
    ///   outside the intersection rejects the whole exchange with
    ///   [`McpMintError::InvalidScope`] — no partial token (RFC 8693 / doc
    ///   §Mint flows).
    /// - `now`: unix seconds. `iat = now`, `exp = now + policy.access_ttl`.
    ///
    /// Result claim:
    /// `{sub: user:<U>, act: {sub: agent:<V>}?, camp_id: <C>, scope: [...requested...], owns: {...}, auth_strength: "user-fresh"}`.
    /// `owns` is the CAMP's ownership (not the user's) — the call is scoped
    /// to the camp's resources. Audit (R020-F13) captures both legs from the
    /// resulting claim plus the endpoint's request context.
    pub async fn mint_token_exchange(
        &self,
        user: PrincipalId,
        camp: PrincipalId,
        actor: Option<Actor>,
        aud: impl Into<String>,
        requested_scope: Vec<Scope>,
        now: i64,
    ) -> Result<MintedMcpToken, McpMintError> {
        if user.kind != PrincipalKind::User {
            return Err(McpMintError::WrongPrincipalKind {
                expected: PrincipalKind::User,
                got: user.kind,
            });
        }
        if camp.kind != PrincipalKind::Camp {
            return Err(McpMintError::WrongPrincipalKind {
                expected: PrincipalKind::Camp,
                got: camp.kind,
            });
        }
        let aud = aud.into();

        // (1) User side — composition rule (5) per side.
        let user_entries = self.grants.list_for(&user, &aud).await?;
        if user_entries.is_empty() {
            return Err(McpMintError::AudNotEntitled {
                principal: user.to_string(),
                aud,
            });
        }
        let user_scopes = expand_scopes(&self.bundles, &user_entries).await?;
        for s in &user_scopes {
            validate_grant(user.kind, *s)?;
        }

        // (2) Camp side — same rule (5) check. Even though the result is
        //     user-attributed, the camp must also be entitled to the
        //     audience.
        let camp_entries = self.grants.list_for(&camp, &aud).await?;
        if camp_entries.is_empty() {
            return Err(McpMintError::AudNotEntitled {
                principal: camp.to_string(),
                aud,
            });
        }
        let camp_scopes = expand_scopes(&self.bundles, &camp_entries).await?;
        for s in &camp_scopes {
            validate_grant(camp.kind, *s)?;
        }

        // (3) RFC 8693 — every requested scope must be in BOTH principals'
        //     expanded grants. Any miss → reject the WHOLE exchange (not a
        //     partial token).
        for s in &requested_scope {
            if !user_scopes.contains(s) || !camp_scopes.contains(s) {
                return Err(McpMintError::InvalidScope {
                    scope: *s,
                    aud: aud.clone(),
                });
            }
        }

        // (4) `owns` comes from the CAMP — the camp is the resource context,
        //     even though `sub` is the user.
        let rows = self.ownership.list_for_principal(&camp).await?;
        let owns = rows_to_owns(&rows);

        let camp_id = camp.id.clone();
        let mut claims = McpClaims::new(
            self.iss.clone(),
            aud,
            user,
            now,
            now + self.policy.access_ttl_seconds,
            generate_jti(),
            requested_scope,
        )
        .with_camp_id(camp_id)
        .with_auth_strength(AuthStrength::UserFresh);
        if let Some(a) = actor {
            claims = claims.with_act(a);
        }
        if !owns.is_empty() {
            claims = claims.with_owns(owns);
        }

        let token = self.minter.mint_mcp(&claims, &self.kid)?;
        Ok(MintedMcpToken { token, claims })
    }
}

/// Convert ownership rows into the [`Owns`] claim shape. Revoked rows are
/// filtered out (the store already excludes them, but a belt-and-braces
/// check keeps the wire shape from leaking stale entries if the store
/// contract evolves). Unknown resource kinds spill into
/// [`Owns::extra`](cheers_core::Owns).
///
/// Duplicate `(kind, resource_id)` pairs collapse to one entry — ownership
/// is set-membership, and while `POST /ownership` is idempotent for
/// identical live rows, historical duplicates (or the residual
/// concurrent-write race) may still exist in a store. The claim shape must
/// not amplify them onto every minted token.
fn rows_to_owns(rows: &[OwnershipRow]) -> Owns {
    fn push_unique(list: &mut Vec<String>, id: &str) {
        if !list.iter().any(|existing| existing == id) {
            list.push(id.to_owned());
        }
    }
    let mut o = Owns::default();
    for r in rows {
        if r.is_revoked() {
            continue;
        }
        match r.resource_kind.as_str() {
            "service" => push_unique(&mut o.service, &r.resource_id),
            "arch_doc" => push_unique(&mut o.arch_doc, &r.resource_id),
            "node" => push_unique(&mut o.node, &r.resource_id),
            other => push_unique(
                o.extra.entry(other.to_owned()).or_default(),
                &r.resource_id,
            ),
        }
    }
    o
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bundles::{BundleName, MemoryBundleStore, ScopeOrBundle};
    use crate::codec::PasetoV4SecretMinter;
    use crate::grants::MemoryGrantStore;
    use crate::ownership::{NewOwnership, OwnershipRow, OwnershipStore};
    use async_trait::async_trait;
    use cheers_core::{Scope, StoreError};
    use cheers_verify::PasetoV4PublicVerifier;
    use std::sync::Mutex;

    // ---- in-memory OwnershipStore (test-only) ------------------------------
    //
    // cheers-sqlx ships the persistent impls; cheers-server tests only need
    // a process-local one. Lives here rather than in ownership.rs because
    // F4 deliberately kept that module impl-free for the trait surface.

    #[derive(Default)]
    struct MemOwnershipStore {
        rows: Mutex<Vec<OwnershipRow>>,
        next_id: Mutex<u64>,
    }

    impl MemOwnershipStore {
        fn new() -> Self {
            Self::default()
        }
    }

    #[async_trait]
    impl OwnershipStore for MemOwnershipStore {
        async fn insert(
            &self,
            ownership: &NewOwnership,
            now: i64,
        ) -> Result<OwnershipRow, StoreError> {
            let mut id_g = self.next_id.lock().unwrap();
            *id_g += 1;
            let id = format!("row-{}", *id_g);
            drop(id_g);
            let row = OwnershipRow::new(
                id,
                ownership.principal_id.clone(),
                ownership.resource_kind.clone(),
                ownership.resource_id.clone(),
                ownership.relationship.clone(),
                ownership.granted_by.clone(),
                ownership.on_behalf_of.clone(),
                now,
                None,
            );
            self.rows.lock().unwrap().push(row.clone());
            Ok(row)
        }

        async fn get(&self, id: &str) -> Result<Option<OwnershipRow>, StoreError> {
            Ok(self.rows.lock().unwrap().iter().find(|r| r.id == id).cloned())
        }

        async fn revoke_by_id(&self, id: &str, now: i64) -> Result<(), StoreError> {
            let mut g = self.rows.lock().unwrap();
            let row = g
                .iter_mut()
                .find(|r| r.id == id)
                .ok_or(StoreError::NotFound)?;
            if row.revoked_at.is_none() {
                row.revoked_at = Some(now);
            }
            Ok(())
        }

        async fn revoke_by_on_behalf_of(
            &self,
            user: &PrincipalId,
            now: i64,
        ) -> Result<u64, StoreError> {
            let mut count = 0u64;
            for r in self.rows.lock().unwrap().iter_mut() {
                if r.revoked_at.is_none() && r.on_behalf_of.as_ref() == Some(user) {
                    r.revoked_at = Some(now);
                    count += 1;
                }
            }
            Ok(count)
        }

        async fn list_for_principal(
            &self,
            principal: &PrincipalId,
        ) -> Result<Vec<OwnershipRow>, StoreError> {
            Ok(self
                .rows
                .lock()
                .unwrap()
                .iter()
                .filter(|r| r.revoked_at.is_none() && r.principal_id == *principal)
                .cloned()
                .collect())
        }

        async fn list_for_resource(
            &self,
            resource_kind: &str,
            resource_id: &str,
        ) -> Result<Vec<OwnershipRow>, StoreError> {
            Ok(self
                .rows
                .lock()
                .unwrap()
                .iter()
                .filter(|r| {
                    r.revoked_at.is_none()
                        && r.resource_kind == resource_kind
                        && r.resource_id == resource_id
                })
                .cloned()
                .collect())
        }
    }

    // ---- assembly ----------------------------------------------------------

    /// `kid` this test rig's authority stamps into every mint — tests that
    /// verify a minted token must pass the same value to `verify_mcp_at`.
    const RIG_KID: &str = "mcp-authority-test-kid-1";

    fn rig() -> (
        McpAuthority<MemoryBundleStore, MemoryGrantStore, MemOwnershipStore>,
        PasetoV4PublicVerifier,
    ) {
        let (minter, verifier) = PasetoV4SecretMinter::generate().unwrap();
        let bundles = MemoryBundleStore::with_defaults();
        let grants = MemoryGrantStore::new();
        let ownership = MemOwnershipStore::new();
        let authority = McpAuthority::new(
            minter,
            bundles,
            grants,
            ownership,
            "https://cheers.example",
            RIG_KID,
        );
        (authority, verifier)
    }

    fn put_simple_grant(authority: &McpAuthority<MemoryBundleStore, MemoryGrantStore, MemOwnershipStore>, principal: PrincipalId, aud: &str, entries: Vec<ScopeOrBundle>) {
        authority.grants.put(principal, aud, entries);
    }

    // ---- McpPolicy ---------------------------------------------------------

    #[test]
    fn mcp_policy_default_is_ten_minutes() {
        let p = McpPolicy::default();
        assert_eq!(p.access_ttl_seconds, 10 * 60);
        let p = McpPolicy::new(300);
        assert_eq!(p.access_ttl_seconds, 300);
        let p = McpPolicy::default().with_access_ttl(5 * 60);
        assert_eq!(p.access_ttl_seconds, 5 * 60);
    }

    // ---- mint_user_fresh: success paths ------------------------------------

    #[test]
    fn mint_user_fresh_signs_token_verifiable_at_edge() {
        let (authority, verifier) = rig();
        let user = PrincipalId::user("alice");
        let aud = "https://kamaji.camp.example";
        put_simple_grant(
            &authority,
            user.clone(),
            aud,
            vec![ScopeOrBundle::Scope(Scope::CloudDeploy), ScopeOrBundle::Scope(Scope::CloudRead)],
        );

        pollster::block_on(async {
            let minted = authority
                .mint_user_fresh(user.clone(), None, None, aud, 1_000)
                .await
                .unwrap();

            // Token starts with v4.public — the doc-pinned envelope.
            assert!(minted.token.starts_with("v4.public."));
            // auth_strength is user-fresh on this path.
            assert_eq!(minted.claims.auth_strength, Some(AuthStrength::UserFresh));
            // jti is non-empty + iat/exp respect the default TTL (10 min).
            assert!(!minted.claims.jti.is_empty());
            assert_eq!(minted.claims.iat, 1_000);
            assert_eq!(
                minted.claims.exp,
                1_000 + McpPolicy::DEFAULT_ACCESS_TTL_SECONDS
            );
            // Edge verifies the freshly minted token under the public key.
            let back = verifier.verify_mcp_at(&minted.token, 1_100, RIG_KID).unwrap();
            assert_eq!(back, minted.claims);
            assert_eq!(back.sub, user);
            assert_eq!(back.scope, vec![Scope::CloudDeploy, Scope::CloudRead]);
        });
    }

    #[test]
    fn mint_user_fresh_expands_bundles_at_mint_time() {
        // A grant of `{"bundle":"deploy-admin"}` lands on the wire as the
        // literal scope list (rule (2)). Edit the bundle, re-mint, see the
        // change without rewriting the grant.
        let (authority, _verifier) = rig();
        let user = PrincipalId::user("bob");
        let aud = "https://kamaji.example";
        put_simple_grant(
            &authority,
            user.clone(),
            aud,
            vec![ScopeOrBundle::Bundle(BundleName::new("deploy-admin"))],
        );

        pollster::block_on(async {
            let first = authority
                .mint_user_fresh(user.clone(), None, None, aud, 1_000)
                .await
                .unwrap();
            assert!(first.claims.scope.contains(&Scope::CloudDestroy));

            // Edit the bundle: drop CloudDestroy. Grant is untouched.
            authority
                .bundles
                .put(
                    &BundleName::new("deploy-admin"),
                    &[Scope::CloudRead, Scope::CloudDeploy],
                )
                .await
                .unwrap();

            let second = authority
                .mint_user_fresh(user, None, None, aud, 1_100)
                .await
                .unwrap();
            assert!(!second.claims.scope.contains(&Scope::CloudDestroy));
            assert_eq!(second.claims.scope, vec![Scope::CloudRead, Scope::CloudDeploy]);
        });
    }

    #[test]
    fn mint_user_fresh_populates_act_camp_id_and_owns() {
        let (authority, verifier) = rig();
        let user = PrincipalId::user("carol");
        let camp_id = "camp-xyz";
        let aud = "https://aud.example";
        put_simple_grant(
            &authority,
            user.clone(),
            aud,
            vec![ScopeOrBundle::Scope(Scope::CampRead)],
        );
        // Seed two owned resources under the camp principal.
        pollster::block_on(async {
            let svc = NewOwnership::new(
                PrincipalId::camp(camp_id),
                "service",
                "svc-a",
                "owns",
                PrincipalId::service("yubaba"),
                Some(user.clone()),
            )
            .unwrap();
            authority.ownership.insert(&svc, 500).await.unwrap();

            let doc = NewOwnership::new(
                PrincipalId::camp(camp_id),
                "arch_doc",
                "doc-1",
                "owns",
                PrincipalId::service("yubaba"),
                Some(user.clone()),
            )
            .unwrap();
            authority.ownership.insert(&doc, 500).await.unwrap();

            let minted = authority
                .mint_user_fresh(
                    user.clone(),
                    Some(Actor::new(PrincipalId::service("agent-claude"))),
                    Some(camp_id.to_owned()),
                    aud,
                    1_000,
                )
                .await
                .unwrap();

            assert_eq!(
                minted.claims.act.as_ref().unwrap().sub,
                PrincipalId::service("agent-claude")
            );
            assert_eq!(minted.claims.camp_id.as_deref(), Some(camp_id));
            assert_eq!(minted.claims.owns.service, vec!["svc-a".to_string()]);
            assert_eq!(minted.claims.owns.arch_doc, vec!["doc-1".to_string()]);

            // Edge accepts it.
            let back = verifier.verify_mcp_at(&minted.token, 1_100, RIG_KID).unwrap();
            assert_eq!(back, minted.claims);
        });
    }

    #[test]
    fn mint_user_fresh_omits_owns_when_camp_owns_nothing() {
        // No ownership rows + camp_id present → owns is empty/omitted on the
        // wire. The claim skip_serializing_if guards this; the test pins it.
        let (authority, _verifier) = rig();
        let user = PrincipalId::user("dan");
        let aud = "https://aud.example";
        put_simple_grant(
            &authority,
            user.clone(),
            aud,
            vec![ScopeOrBundle::Scope(Scope::CampRead)],
        );

        pollster::block_on(async {
            let minted = authority
                .mint_user_fresh(user, None, Some("camp-empty".into()), aud, 1_000)
                .await
                .unwrap();
            assert!(minted.claims.owns.is_empty());
            let json = serde_json::to_string(&minted.claims).unwrap();
            assert!(!json.contains("\"owns\""), "empty owns must omit: {json}");
        });
    }

    // ---- mint_user_fresh: rejection paths ----------------------------------

    #[test]
    fn mint_user_fresh_rejects_unentitled_aud() {
        let (authority, _verifier) = rig();
        let user = PrincipalId::user("eve");
        // No grant placed for any aud.
        pollster::block_on(async {
            let err = authority
                .mint_user_fresh(user, None, None, "https://aud.example", 1_000)
                .await
                .unwrap_err();
            match err {
                McpMintError::AudNotEntitled { principal, aud } => {
                    assert_eq!(principal, "user:eve");
                    assert_eq!(aud, "https://aud.example");
                }
                other => panic!("expected AudNotEntitled, got {other:?}"),
            }
        });
    }

    #[test]
    fn mint_user_fresh_rejects_non_user_principal() {
        let (authority, _verifier) = rig();
        pollster::block_on(async {
            let err = authority
                .mint_user_fresh(
                    PrincipalId::service("yubaba"),
                    None,
                    None,
                    "https://aud.example",
                    1_000,
                )
                .await
                .unwrap_err();
            match err {
                McpMintError::WrongPrincipalKind { expected, got } => {
                    assert_eq!(expected, PrincipalKind::User);
                    assert_eq!(got, PrincipalKind::Service);
                }
                other => panic!("expected WrongPrincipalKind, got {other:?}"),
            }
        });
    }

    #[test]
    fn mint_user_fresh_rejects_service_only_scope_smuggled_via_bundle() {
        // Defence in depth for composition rule (4): if a bundle granted to
        // a User principal contains ownership:write, the mint path catches
        // it via validate_grant BEFORE signing — the misconfigured bundle
        // never becomes a mintable token.
        let (authority, _verifier) = rig();
        let user = PrincipalId::user("mallory");
        let aud = "https://aud.example";

        pollster::block_on(async {
            authority
                .bundles
                .put(
                    &BundleName::new("dangerous"),
                    &[Scope::CampRead, Scope::OwnershipWrite],
                )
                .await
                .unwrap();
            authority.grants.put(
                user.clone(),
                aud,
                vec![ScopeOrBundle::Bundle(BundleName::new("dangerous"))],
            );

            let err = authority
                .mint_user_fresh(user, None, None, aud, 1_000)
                .await
                .unwrap_err();
            match err {
                McpMintError::GrantMisconfigured(GrantError::ServiceOnlyScope { scope, kind }) => {
                    assert_eq!(scope, Scope::OwnershipWrite);
                    assert_eq!(kind, PrincipalKind::User);
                }
                other => panic!("expected GrantMisconfigured(ServiceOnlyScope), got {other:?}"),
            }
        });
    }

    // ---- mint_bootstrap: success paths -------------------------------------

    #[test]
    fn mint_bootstrap_signs_token_verifiable_at_edge() {
        let (authority, verifier) = rig();
        let camp = PrincipalId::camp("c-xyz");
        let aud = "https://kamaji.camp.example";
        put_simple_grant(
            &authority,
            camp.clone(),
            aud,
            vec![
                ScopeOrBundle::Scope(Scope::CloudDeploy),
                ScopeOrBundle::Scope(Scope::CloudRead),
            ],
        );

        pollster::block_on(async {
            let minted = authority
                .mint_bootstrap(camp.clone(), aud, 1_000)
                .await
                .unwrap();

            // Same v4.public envelope as mint path 1.
            assert!(minted.token.starts_with("v4.public."));
            // auth_strength is bootstrap on this path.
            assert_eq!(minted.claims.auth_strength, Some(AuthStrength::Bootstrap));
            // sub is the camp principal; camp_id is the bare id (no prefix) so
            // a consumer doesn't have to re-parse sub.
            assert_eq!(minted.claims.sub, camp);
            assert_eq!(minted.claims.camp_id.as_deref(), Some("c-xyz"));
            // No act claim — bootstrap is the camp acting as itself, not a
            // user acted-on-by an agent.
            assert!(minted.claims.act.is_none());
            assert!(!minted.claims.jti.is_empty());
            assert_eq!(minted.claims.iat, 1_000);
            assert_eq!(
                minted.claims.exp,
                1_000 + McpPolicy::DEFAULT_ACCESS_TTL_SECONDS
            );

            // Edge verifies the freshly minted token under the public key —
            // no per-call cheers round trip.
            let back = verifier.verify_mcp_at(&minted.token, 1_100, RIG_KID).unwrap();
            assert_eq!(back, minted.claims);
            assert_eq!(back.scope, vec![Scope::CloudDeploy, Scope::CloudRead]);
        });
    }

    #[test]
    fn mint_bootstrap_owns_reflects_ownership_table_state() {
        let (authority, _verifier) = rig();
        let camp = PrincipalId::camp("c-with-owns");
        let user = PrincipalId::user("u-on-behalf");
        let aud = "https://aud.example";
        put_simple_grant(
            &authority,
            camp.clone(),
            aud,
            vec![ScopeOrBundle::Scope(Scope::CampRead)],
        );

        pollster::block_on(async {
            // Seed two owned resources under the camp principal — the camp is
            // the holder, the user is the human on whose behalf the grant
            // happened (W159 §audit / on_behalf_of).
            let svc = NewOwnership::new(
                camp.clone(),
                "service",
                "svc-a",
                "owns",
                PrincipalId::service("yubaba"),
                Some(user.clone()),
            )
            .unwrap();
            authority.ownership.insert(&svc, 500).await.unwrap();

            let doc = NewOwnership::new(
                camp.clone(),
                "arch_doc",
                "doc-1",
                "owns",
                PrincipalId::service("yubaba"),
                Some(user.clone()),
            )
            .unwrap();
            authority.ownership.insert(&doc, 500).await.unwrap();

            let minted = authority
                .mint_bootstrap(camp.clone(), aud, 1_000)
                .await
                .unwrap();

            assert_eq!(minted.claims.owns.service, vec!["svc-a".to_string()]);
            assert_eq!(minted.claims.owns.arch_doc, vec!["doc-1".to_string()]);
        });
    }

    #[test]
    fn rows_to_owns_dedups_duplicate_resource_ids() {
        // Historical duplicate rows (pre-idempotent-create stores, or the
        // residual concurrent-write race) must collapse to one entry per
        // (kind, resource_id) — the owns claim is set-membership.
        let camp = PrincipalId::camp("c-dup");
        let svc = PrincipalId::service("yubaba");
        let mk = |id: &str, kind: &str, rid: &str| {
            OwnershipRow::new(
                id.to_owned(),
                camp.clone(),
                kind.to_owned(),
                rid.to_owned(),
                "owns".to_owned(),
                svc.clone(),
                None,
                500,
                None,
            )
        };
        let rows = vec![
            mk("row-1", "service", "svc-a"),
            mk("row-2", "service", "svc-a"), // duplicate
            mk("row-3", "service", "svc-b"),
            mk("row-4", "node", "aa11"),
            mk("row-5", "node", "aa11"), // duplicate
            mk("row-6", "pond", "p-1"),
            mk("row-7", "pond", "p-1"), // duplicate in the extra spill
        ];

        let owns = rows_to_owns(&rows);
        assert_eq!(owns.service, vec!["svc-a".to_string(), "svc-b".to_string()]);
        assert_eq!(owns.node, vec!["aa11".to_string()]);
        assert_eq!(
            owns.extra.get("pond"),
            Some(&vec!["p-1".to_string()])
        );
    }

    #[test]
    fn mint_bootstrap_omits_owns_when_camp_owns_nothing() {
        // No ownership rows → owns is empty and omitted on the wire. Same
        // skip_serializing_if guard as mint path 1, pinned independently here
        // because the bootstrap mint path always sets camp_id (a token whose
        // sub is `camp:<C>` is always scoped to that camp).
        let (authority, _verifier) = rig();
        let camp = PrincipalId::camp("c-empty");
        let aud = "https://aud.example";
        put_simple_grant(
            &authority,
            camp.clone(),
            aud,
            vec![ScopeOrBundle::Scope(Scope::CampRead)],
        );

        pollster::block_on(async {
            let minted = authority
                .mint_bootstrap(camp, aud, 1_000)
                .await
                .unwrap();
            assert!(minted.claims.owns.is_empty());
            let json = serde_json::to_string(&minted.claims).unwrap();
            assert!(!json.contains("\"owns\""), "empty owns must omit: {json}");
            // camp_id is still present even when owns is empty.
            assert!(json.contains("\"camp_id\":\"c-empty\""), "camp_id must remain: {json}");
        });
    }

    #[test]
    fn mint_bootstrap_expands_bundles_at_mint_time() {
        // Same propagation property as F5/F6: a bundle edit shows up on the
        // next mint without rewriting the camp's grant.
        let (authority, _verifier) = rig();
        let camp = PrincipalId::camp("c-deploy");
        let aud = "https://aud.example";
        put_simple_grant(
            &authority,
            camp.clone(),
            aud,
            vec![ScopeOrBundle::Bundle(BundleName::new("deploy-admin"))],
        );

        pollster::block_on(async {
            let first = authority
                .mint_bootstrap(camp.clone(), aud, 1_000)
                .await
                .unwrap();
            assert!(first.claims.scope.contains(&Scope::CloudDestroy));

            authority
                .bundles
                .put(
                    &BundleName::new("deploy-admin"),
                    &[Scope::CloudRead, Scope::CloudDeploy],
                )
                .await
                .unwrap();

            let second = authority
                .mint_bootstrap(camp, aud, 1_100)
                .await
                .unwrap();
            assert!(!second.claims.scope.contains(&Scope::CloudDestroy));
            assert_eq!(second.claims.scope, vec![Scope::CloudRead, Scope::CloudDeploy]);
        });
    }

    // ---- mint_bootstrap: rejection paths -----------------------------------

    #[test]
    fn mint_bootstrap_rejects_non_camp_principal() {
        let (authority, _verifier) = rig();
        pollster::block_on(async {
            // A user principal handed to the bootstrap path is a programmer
            // error — surfaces WrongPrincipalKind, not a 403.
            let err = authority
                .mint_bootstrap(
                    PrincipalId::user("alice"),
                    "https://aud.example",
                    1_000,
                )
                .await
                .unwrap_err();
            match err {
                McpMintError::WrongPrincipalKind { expected, got } => {
                    assert_eq!(expected, PrincipalKind::Camp);
                    assert_eq!(got, PrincipalKind::User);
                }
                other => panic!("expected WrongPrincipalKind, got {other:?}"),
            }

            // Same for a service principal.
            let err = authority
                .mint_bootstrap(
                    PrincipalId::service("yubaba"),
                    "https://aud.example",
                    1_000,
                )
                .await
                .unwrap_err();
            match err {
                McpMintError::WrongPrincipalKind { expected, got } => {
                    assert_eq!(expected, PrincipalKind::Camp);
                    assert_eq!(got, PrincipalKind::Service);
                }
                other => panic!("expected WrongPrincipalKind, got {other:?}"),
            }
        });
    }

    #[test]
    fn mint_bootstrap_rejects_unentitled_aud() {
        let (authority, _verifier) = rig();
        let camp = PrincipalId::camp("c-no-grants");
        // No grant placed for any aud — composition rule (5).
        pollster::block_on(async {
            let err = authority
                .mint_bootstrap(camp, "https://aud.example", 1_000)
                .await
                .unwrap_err();
            match err {
                McpMintError::AudNotEntitled { principal, aud } => {
                    assert_eq!(principal, "camp:c-no-grants");
                    assert_eq!(aud, "https://aud.example");
                }
                other => panic!("expected AudNotEntitled, got {other:?}"),
            }
        });
    }

    #[test]
    fn mint_bootstrap_rejects_service_only_scope_smuggled_via_bundle() {
        // Composition rule (4) — `ownership:write` and `audit:write` are
        // grantable to kind=service ONLY. A bundle granted to a camp
        // principal that expands to a service-only scope is rejected by
        // validate_grant BEFORE signing, mirroring F6's defence in depth on
        // the user path.
        let (authority, _verifier) = rig();
        let camp = PrincipalId::camp("c-sneaky");
        let aud = "https://aud.example";

        pollster::block_on(async {
            authority
                .bundles
                .put(
                    &BundleName::new("dangerous"),
                    &[Scope::CampRead, Scope::OwnershipWrite],
                )
                .await
                .unwrap();
            authority.grants.put(
                camp.clone(),
                aud,
                vec![ScopeOrBundle::Bundle(BundleName::new("dangerous"))],
            );

            let err = authority
                .mint_bootstrap(camp, aud, 1_000)
                .await
                .unwrap_err();
            match err {
                McpMintError::GrantMisconfigured(GrantError::ServiceOnlyScope { scope, kind }) => {
                    assert_eq!(scope, Scope::OwnershipWrite);
                    assert_eq!(kind, PrincipalKind::Camp);
                }
                other => panic!("expected GrantMisconfigured(ServiceOnlyScope), got {other:?}"),
            }
        });
    }

    // ---- mint_token_exchange: success paths --------------------------------

    #[test]
    fn mint_token_exchange_attributes_to_user_with_camp_as_context() {
        let (authority, verifier) = rig();
        let user = PrincipalId::user("alice");
        let camp = PrincipalId::camp("c-multi");
        let aud = "https://kamaji.camp.example";

        // User holds CloudDeploy + CloudRead for this aud; camp holds the
        // same. Requested scope is a subset.
        put_simple_grant(
            &authority,
            user.clone(),
            aud,
            vec![
                ScopeOrBundle::Scope(Scope::CloudDeploy),
                ScopeOrBundle::Scope(Scope::CloudRead),
            ],
        );
        put_simple_grant(
            &authority,
            camp.clone(),
            aud,
            vec![
                ScopeOrBundle::Scope(Scope::CloudDeploy),
                ScopeOrBundle::Scope(Scope::CloudRead),
            ],
        );

        // Camp owns a service — owns claim must come from the camp.
        pollster::block_on(async {
            let svc = NewOwnership::new(
                camp.clone(),
                "service",
                "svc-prod",
                "owns",
                PrincipalId::service("yubaba"),
                Some(user.clone()),
            )
            .unwrap();
            authority.ownership.insert(&svc, 500).await.unwrap();

            let minted = authority
                .mint_token_exchange(
                    user.clone(),
                    camp.clone(),
                    Some(Actor::new(PrincipalId::service("agent-claude"))),
                    aud,
                    vec![Scope::CloudDeploy],
                    1_000,
                )
                .await
                .unwrap();

            assert!(minted.token.starts_with("v4.public."));
            // sub is the USER, not the camp — exchange attributes to the
            // human even though the camp is the bearer at the HTTP layer.
            assert_eq!(minted.claims.sub, user);
            // camp_id carries the camp context (bare id, no prefix).
            assert_eq!(minted.claims.camp_id.as_deref(), Some("c-multi"));
            // act carries the agent variant.
            assert_eq!(
                minted.claims.act.as_ref().unwrap().sub,
                PrincipalId::service("agent-claude"),
            );
            // user-fresh — the user authenticated locally.
            assert_eq!(minted.claims.auth_strength, Some(AuthStrength::UserFresh));
            // Result scope is the requested scope (verified in intersection).
            assert_eq!(minted.claims.scope, vec![Scope::CloudDeploy]);
            // owns comes from the CAMP, not the user.
            assert_eq!(minted.claims.owns.service, vec!["svc-prod".to_string()]);
            // jti present, iat/exp respect policy.
            assert!(!minted.claims.jti.is_empty());
            assert_eq!(minted.claims.iat, 1_000);
            assert_eq!(
                minted.claims.exp,
                1_000 + McpPolicy::DEFAULT_ACCESS_TTL_SECONDS
            );
            // Edge verifies.
            let back = verifier.verify_mcp_at(&minted.token, 1_100, RIG_KID).unwrap();
            assert_eq!(back, minted.claims);
        });
    }

    #[test]
    fn mint_token_exchange_intersection_drops_scope_one_side_lacks() {
        // Verify intersection by removing a scope from one side and observing
        // it's rejected at the requested-scope check — proves the camp's
        // grants actually narrow the user's, not just rubber-stamp the
        // request.
        let (authority, _verifier) = rig();
        let user = PrincipalId::user("bob");
        let camp = PrincipalId::camp("c-narrow");
        let aud = "https://aud.example";

        // User has both; camp has only CloudRead.
        put_simple_grant(
            &authority,
            user.clone(),
            aud,
            vec![
                ScopeOrBundle::Scope(Scope::CloudDeploy),
                ScopeOrBundle::Scope(Scope::CloudRead),
            ],
        );
        put_simple_grant(
            &authority,
            camp.clone(),
            aud,
            vec![ScopeOrBundle::Scope(Scope::CloudRead)],
        );

        pollster::block_on(async {
            // Requesting CloudRead alone succeeds — in both.
            let minted = authority
                .mint_token_exchange(
                    user.clone(),
                    camp.clone(),
                    None,
                    aud,
                    vec![Scope::CloudRead],
                    1_000,
                )
                .await
                .unwrap();
            assert_eq!(minted.claims.scope, vec![Scope::CloudRead]);

            // Requesting CloudDeploy fails — camp lacks it. The whole
            // exchange rejects (not a partial token).
            let err = authority
                .mint_token_exchange(
                    user,
                    camp,
                    None,
                    aud,
                    vec![Scope::CloudRead, Scope::CloudDeploy],
                    1_000,
                )
                .await
                .unwrap_err();
            match err {
                McpMintError::InvalidScope { scope, aud: a } => {
                    assert_eq!(scope, Scope::CloudDeploy);
                    assert_eq!(a, aud);
                }
                other => panic!("expected InvalidScope, got {other:?}"),
            }
        });
    }

    #[test]
    fn mint_token_exchange_rejects_scope_user_lacks() {
        // Mirror case: camp has it, user doesn't. Same all-or-nothing reject.
        let (authority, _verifier) = rig();
        let user = PrincipalId::user("carol");
        let camp = PrincipalId::camp("c-wide");
        let aud = "https://aud.example";

        put_simple_grant(
            &authority,
            user.clone(),
            aud,
            vec![ScopeOrBundle::Scope(Scope::CloudRead)],
        );
        put_simple_grant(
            &authority,
            camp.clone(),
            aud,
            vec![
                ScopeOrBundle::Scope(Scope::CloudRead),
                ScopeOrBundle::Scope(Scope::CloudDeploy),
            ],
        );

        pollster::block_on(async {
            let err = authority
                .mint_token_exchange(
                    user,
                    camp,
                    None,
                    aud,
                    vec![Scope::CloudDeploy],
                    1_000,
                )
                .await
                .unwrap_err();
            match err {
                McpMintError::InvalidScope { scope, aud: _ } => {
                    assert_eq!(scope, Scope::CloudDeploy);
                }
                other => panic!("expected InvalidScope, got {other:?}"),
            }
        });
    }

    // ---- mint_token_exchange: rejection paths ------------------------------

    #[test]
    fn mint_token_exchange_rejects_wrong_user_kind() {
        let (authority, _verifier) = rig();
        pollster::block_on(async {
            let err = authority
                .mint_token_exchange(
                    PrincipalId::camp("c-as-user"),
                    PrincipalId::camp("c"),
                    None,
                    "https://aud.example",
                    vec![],
                    1_000,
                )
                .await
                .unwrap_err();
            match err {
                McpMintError::WrongPrincipalKind { expected, got } => {
                    assert_eq!(expected, PrincipalKind::User);
                    assert_eq!(got, PrincipalKind::Camp);
                }
                other => panic!("expected WrongPrincipalKind, got {other:?}"),
            }
        });
    }

    #[test]
    fn mint_token_exchange_rejects_wrong_camp_kind() {
        let (authority, _verifier) = rig();
        pollster::block_on(async {
            let err = authority
                .mint_token_exchange(
                    PrincipalId::user("alice"),
                    PrincipalId::service("yubaba"),
                    None,
                    "https://aud.example",
                    vec![],
                    1_000,
                )
                .await
                .unwrap_err();
            match err {
                McpMintError::WrongPrincipalKind { expected, got } => {
                    assert_eq!(expected, PrincipalKind::Camp);
                    assert_eq!(got, PrincipalKind::Service);
                }
                other => panic!("expected WrongPrincipalKind, got {other:?}"),
            }
        });
    }

    #[test]
    fn mint_token_exchange_rejects_unentitled_user() {
        let (authority, _verifier) = rig();
        let user = PrincipalId::user("eve");
        let camp = PrincipalId::camp("c");
        let aud = "https://aud.example";
        // Camp has a grant, user doesn't — must reject on the user side.
        put_simple_grant(
            &authority,
            camp.clone(),
            aud,
            vec![ScopeOrBundle::Scope(Scope::CloudRead)],
        );

        pollster::block_on(async {
            let err = authority
                .mint_token_exchange(user, camp, None, aud, vec![Scope::CloudRead], 1_000)
                .await
                .unwrap_err();
            match err {
                McpMintError::AudNotEntitled { principal, aud: _ } => {
                    assert_eq!(principal, "user:eve");
                }
                other => panic!("expected AudNotEntitled, got {other:?}"),
            }
        });
    }

    #[test]
    fn mint_token_exchange_rejects_unentitled_camp() {
        // Mirror: user has a grant, camp doesn't. Composition rule (5)
        // applies per side, so the camp's empty grant list rejects.
        let (authority, _verifier) = rig();
        let user = PrincipalId::user("frank");
        let camp = PrincipalId::camp("c-no-grants");
        let aud = "https://aud.example";
        put_simple_grant(
            &authority,
            user.clone(),
            aud,
            vec![ScopeOrBundle::Scope(Scope::CloudRead)],
        );

        pollster::block_on(async {
            let err = authority
                .mint_token_exchange(user, camp, None, aud, vec![Scope::CloudRead], 1_000)
                .await
                .unwrap_err();
            match err {
                McpMintError::AudNotEntitled { principal, aud: _ } => {
                    assert_eq!(principal, "camp:c-no-grants");
                }
                other => panic!("expected AudNotEntitled, got {other:?}"),
            }
        });
    }

    #[test]
    fn mint_token_exchange_catches_service_only_scope_smuggled_via_camp_bundle() {
        // Defence in depth — composition rule (4) — even on the exchange
        // path: a camp bundle that expands to OwnershipWrite is caught by
        // validate_grant(Camp, scope) BEFORE intersection is computed.
        let (authority, _verifier) = rig();
        let user = PrincipalId::user("g");
        let camp = PrincipalId::camp("c-sneaky");
        let aud = "https://aud.example";

        pollster::block_on(async {
            authority
                .bundles
                .put(
                    &BundleName::new("dangerous"),
                    &[Scope::CampRead, Scope::OwnershipWrite],
                )
                .await
                .unwrap();
            put_simple_grant(
                &authority,
                user.clone(),
                aud,
                vec![ScopeOrBundle::Scope(Scope::CampRead)],
            );
            put_simple_grant(
                &authority,
                camp,
                aud,
                vec![ScopeOrBundle::Bundle(BundleName::new("dangerous"))],
            );

            let err = authority
                .mint_token_exchange(
                    user,
                    PrincipalId::camp("c-sneaky"),
                    None,
                    aud,
                    vec![Scope::CampRead],
                    1_000,
                )
                .await
                .unwrap_err();
            match err {
                McpMintError::GrantMisconfigured(GrantError::ServiceOnlyScope { scope, kind }) => {
                    assert_eq!(scope, Scope::OwnershipWrite);
                    assert_eq!(kind, PrincipalKind::Camp);
                }
                other => panic!("expected GrantMisconfigured(ServiceOnlyScope), got {other:?}"),
            }
        });
    }

    // ---- McpMintError → Error conversion -----------------------------------

    #[test]
    fn mcp_mint_error_converts_to_umbrella_error() {
        let e: Error = McpMintError::AudNotEntitled {
            principal: "user:x".into(),
            aud: "a".into(),
        }
        .into();
        match e {
            Error::InvalidInput(msg) => assert!(msg.contains("aud")),
            other => panic!("expected InvalidInput, got {other:?}"),
        }

        let e: Error = McpMintError::Store(StoreError::Conflict).into();
        assert!(matches!(e, Error::Store(StoreError::Conflict)));

        let e: Error = McpMintError::Codec(CodecError::Malformed).into();
        assert!(matches!(e, Error::Codec(CodecError::Malformed)));
    }
}