skilj-core 0.1.1

The engine behind skilj: event storage, DCB consistency checks, projections and the plugin API for event and command types. Most applications use it through the skilj crate.
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
//! `Role`, `RoleAccessMapping`, `AccessToken` (and its four variants);
//! `CreateRole`, `RevokeRole`, `GrantRoleAccessMapping`,
//! `RevokeRoleAccessMapping`, `TokenRevocation`; actor resolution
//! (`ReadAccess`/`WriteAccess`/`AdminAccess`/`SensitiveDataAccess`/
//! `Superadmin`) and the JWT-to-Role identity resolution entry point. See
//! docs/architecture.md ยง3.2 and [ยง6](../../../docs/architecture.md#idp-trust-configuration) (JWKS/JWT verification lives here,
//! behind the `jsonwebtoken` crate).

use crate::error::SkiljRejection;
use crate::event_store::BoundedContext;

// Real JWKS fetching and JWT signature verification (step 1 of the
// identity resolution note above `entity Role`) now live below
// (`IdpConfig`/`SigningAlgorithm`/`JwksCache`/`verify_and_extract_subject`)
// - genuine I/O, so unlike every pure function in this module they
// aren't tested by construction alone; see their own doc comments and
// docs/architecture.md ยง6 for the concrete design the spec's own "black
// box" text left this document to fill in. The four actors
// (`ReadAccess`/`WriteAccess`/`AdminAccess`/`SensitiveDataAccess`)
// and `Superadmin` have no resolution function of their own to add
// beyond that: each is a predicate over an already-resolved
// `RoleAccessMapping`/`Role` (see `actor ReadAccess` etc. in the spec),
// and every rule elsewhere in this crate that faces one already inlines
// exactly that predicate as its own `requires` checks - there is no
// separate obligation for the actor declarations themselves to
// propagate, only each surface's own still-deferred `surface-actor`
// obligation (the GraphQL-scaffolding gap every test file in this crate
// already defers for the same reason).
// `EventReadToken`/`ExternalEventToken`/`DirectCreationToken`/
// `CommandToken`/`Role`/`RoleAccessMapping` below are first, partial cuts
// - see their own doc comments - added while propagating tests for the
// EventFetch/ExternalEventIngestion/DirectEventCreation/CommandTrigger/
// AccessManagement surfaces (docs/architecture.md ยง9's pilot and its
// follow-ups). The base `AccessToken` shape (`secret`/`created_at`/
// `revoked_at`, plus `id` on `EventReadToken`) and the `AccessToken` sum
// type itself, `create_external_event_token`/`create_direct_creation_token`/
// `create_command_token`/`create_event_read_token`, and `revoke_token` were
// added next, propagating EventTypeAdminOperations/
// CommandTypeAdminOperations/TokenRevocation - the token lifecycle's
// minting and revocation halves, completing `AccessToken`'s entity shape.
// `resolve_role_by_external_subject` was added last - the one pure
// fragment of JWT-to-Role identity resolution (see its own doc comment
// for why the JWT/JWKS verification itself stays unmodelled).

/// See `entity Role`'s `status` field/transition graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RoleStatus {
    /// In force.
    Active,
    /// Revoked; it grants nothing.
    Revoked,
}

/// See `entity Role`. `access_mappings` (a relationship projection, not a
/// stored field - the same treatment `EventType`'s `*_tokens` get) is
/// omitted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Role {
    /// The role's id.
    pub id: String,
    /// The identity at the IdP this role belongs to: a verified JWT's subject
    /// claim is matched against it.
    pub external_subject: String,
    /// A display name.
    pub name: String,
    /// Whether it is a superadmin: it may add bounded contexts and manage
    /// every role and grant, independently of its own grants.
    pub superadmin: bool,
    /// Whether it is in force.
    pub status: RoleStatus,
    /// When it was created.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// When it was revoked; `None` while active.
    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// See `enum AccessLevel`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AccessLevel {
    /// May read events, commands and projections.
    Read,
    /// May also submit commands.
    Write,
    /// May also register types, mint tokens and administer the bounded
    /// context.
    Admin,
}

/// See `entity RoleAccessMapping`. Reuses `RoleStatus` for its own
/// `status` - the spec declares both as the identical `active | revoked`
/// shape, and nothing here needs to tell "a revoked Role" apart from "a
/// revoked grant" by type alone (each already lives on its own struct).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RoleAccessMapping {
    /// The role granted.
    pub role: Role,
    /// The bounded context it is granted on.
    pub bounded_context: BoundedContext,
    /// What it may do there.
    pub level: AccessLevel,
    /// Whether it may read every subject's sensitive fields, not only its own.
    pub can_read_sensitive: bool,
    /// Orthogonal to `level`, exactly as `can_read_sensitive` is: `None`
    /// (the default for every mapping today) means unrestricted within
    /// `bounded_context`, identical to this grant's own behaviour before
    /// this field existed. `Some(v)` restricts this grant to projection
    /// instances whose own derived "owner" value equals `v`, for a
    /// projection that declares an owner-tag dimension (see
    /// `plugin::Projection::OWNER_TAG_KEY`) - a projection with no such
    /// declaration is unaffected by this field regardless of its value.
    /// No validation on the value itself, the same unchecked
    /// pass-through `can_read_sensitive`'s boolean already gets. See
    /// `projections::query_projection`'s own enforcement and
    /// specs/skilj.allium's `owner_scope_satisfied`.
    pub scope: Option<String>,
    /// Whether the grant is in force.
    pub status: RoleStatus,
    /// When it was granted.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// When it was revoked; `None` while active.
    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// See `entity PrivateFieldGrant`. One Role letting another read the
/// private fields of a record it is itself the default reader of - the
/// only entity the private-field mechanism needs (see `value PrivateField`
/// in the spec). Self-service, unlike every other grant in this module:
/// made by the ordinary caller who already holds the thing being shared,
/// needing no admin/superadmin anywhere, and revocable only by that same
/// caller (see `revoke_private_field_access`).
///
/// `id` is a Rust/DB-only addressing detail the spec entity itself
/// doesn't name - `RevokePrivateFieldAccess`'s own `grant` parameter has
/// to unambiguously identify one grant among however many a
/// `(grantor, grantee)` pair may have accumulated over time (unlike
/// `RoleAccessMapping`, there is no "at most one active" uniqueness
/// constraint here - a grantor may grant the same grantee several
/// different records, or re-grant after revoking), so a synthetic id is
/// the same practical elaboration `AccessToken`'s own `id` already is,
/// not a new domain fact.
///
/// `event_sequence`/`command_id` stand in for the spec's own `event:
/// Event?`/`command: Command?` - a deliberate Rust/DB elaboration, not a
/// narrower domain fact: every real use of the record a per-record grant
/// names is an identity comparison alone (`render_event`/`render_command`'s
/// own `matches_this_record` closure - "does this grant name exactly the
/// record being read", never any of that record's own fields), so
/// carrying `Event.sequence`/`Command.id` is exactly as capable as
/// embedding the whole value and needs no extra load to reconstruct one
/// at read time - the same trade-off `CommandAuthorised.consistency_tags`
/// already made in an earlier pass (docs/architecture.md's own write-up).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrivateFieldGrant {
    /// The grant's id.
    pub id: String,
    /// The bounded context of the shared record.
    pub bounded_context: BoundedContext,
    /// The role sharing its private fields.
    pub grantor: Role,
    /// The role they are shared with.
    pub grantee: Role,
    /// At most one of the two is ever set - see the invariant
    /// `PrivateFieldGrantNamesAtMostOneRecord` in the spec. Both `None` is
    /// a blanket grant: every record of any type `grantor` is itself the
    /// default private reader of, present and future alike, re-derived at
    /// every read rather than trusted from grant time (see
    /// `event_store::is_default_private_reader`'s own doc comment).
    pub event_sequence: Option<i64>,
    /// The `Command::id` of the one command shared; see `event_sequence`.
    pub command_id: Option<String>,
    /// Whether the grant is in force.
    pub status: TokenStatus,
    /// When it was granted.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// When it was revoked; `None` while active.
    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// See `entity AccessToken`'s `status` field/transition graph. Reused by
/// `PrivateFieldGrant` too - both are the identical `active | revoked`
/// shape, the same "no need for a third type to tell them apart"
/// reasoning `RoleAccessMapping` reusing `RoleStatus` already gives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TokenStatus {
    /// Accepted.
    Active,
    /// Revoked; refused from then on.
    Revoked,
}

/// See `variant EventReadToken` in the spec. Now carries the full
/// `entity AccessToken` base shape - `id` included, promoted from the
/// earlier EventFetch-only cut (nothing in EventFetch's own rules reads
/// it, but `RevokeToken` and its `AccessToken` sum type below need every
/// variant to carry the same base fields uniformly).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventReadToken {
    /// The token's id: the part before the `.` in a bearer credential.
    pub id: String,
    /// The token's secret: the part after the `.`.
    pub secret: String,
    /// Whether it is accepted.
    pub status: TokenStatus,
    /// When it was minted.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// When it was revoked; `None` while active.
    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
    /// The event type it reads.
    pub event_type: crate::event_store::EventType,
    /// Cross-tenant read fix (docs/architecture.md's own write-up of
    /// these passes) - the REST track's own counterpart to
    /// `RoleAccessMapping.scope`, set at minting time
    /// (`create_event_read_token`) by whichever admin issues this token,
    /// independent of that admin's own `access_mapping.scope`: an
    /// unscoped staff admin can mint a company-scoped token. Same
    /// null-is-unrestricted semantics, checked by
    /// `event_store::event_owner_scope_satisfied` in
    /// `fetch_events`/`consume_events`.
    pub scope: Option<String>,
    /// See `variant EventReadToken.start_from` - decided once at minting
    /// time (`create_event_read_token`), consulted once, by
    /// `event_store::consume_events`, on this token's own first
    /// `ConsumeEvents` call alone. Never absent: the spec's own
    /// `start_from ?? beginning` default substitution happens inside
    /// `create_event_read_token` rather than being carried as an
    /// `Option` here, the same "the entity itself never stores the
    /// absence" treatment `consume_events`' own resolved `mode` binding
    /// already gives `AckMode`.
    pub start_from: EventReadStartPosition,
    /// See `EventReadToken.start_at_sequence` in the spec. Populated iff
    /// `start_from = AtSequence` - `create_event_read_token`'s own
    /// `requires` guards are what hold that true, not a type-level
    /// enforcement here (the same "construction, not a restating
    /// invariant" register the spec's own doc comment on this exact
    /// point uses).
    pub start_at_sequence: Option<i64>,
    /// See `EventReadToken.start_at_time` in the spec - `start_at_sequence`'s
    /// own sibling, populated iff `start_from = AtTime`.
    pub start_at_time: Option<chrono::DateTime<chrono::Utc>>,
}

/// See `variant EventReadToken.start_from`. `Beginning` unless a minting
/// admin names `Latest` explicitly (`create_event_read_token`) - the
/// spec-backed counterpart to `plugin::CrossContextRouteStartFrom`,
/// which exists because `CrossContextRoute` has no spec entity of its
/// own to carry this one (docs/architecture.md ยง36's "no spec entity"
/// note) - the two are deliberately separate types, not a shared one,
/// since nothing here depends on the plugin module or vice versa.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EventReadStartPosition {
    /// From the first event of its type.
    Beginning,
    /// From events committed after the first read; earlier ones are skipped.
    Latest,
    /// See `EventReadToken.start_at_sequence` - the value this variant
    /// reads is carried on the token itself, not on this tag.
    AtSequence,
    /// See `EventReadToken.start_at_time` - same treatment as
    /// `AtSequence` above.
    AtTime,
}

/// See `variant ExternalEventToken`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExternalEventToken {
    /// The token's id: the part before the `.` in a bearer credential.
    pub id: String,
    /// The token's secret: the part after the `.`.
    pub secret: String,
    /// Whether it is accepted.
    pub status: TokenStatus,
    /// When it was minted.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// When it was revoked; `None` while active.
    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
    /// The event type it creates.
    pub event_type: crate::event_store::EventType,
    /// Cross-tenant write fix (docs/architecture.md's own write-up of
    /// these passes) - `EventReadToken.scope`'s own write-side
    /// counterpart: set at minting time (`create_external_event_token`)
    /// by whichever admin issues this token, independent of that
    /// admin's own `access_mapping.scope`. Same null-is-unrestricted
    /// semantics, checked by `event_store::owner_scope_satisfied` in
    /// `create_external_event` - a token naming a scope may create
    /// events only for the owner it names.
    pub scope: Option<String>,
}

/// See `variant DirectCreationToken`. Same shape as `ExternalEventToken`
/// above, `scope` included.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectCreationToken {
    /// The token's id: the part before the `.` in a bearer credential.
    pub id: String,
    /// The token's secret: the part after the `.`.
    pub secret: String,
    /// Whether it is accepted.
    pub status: TokenStatus,
    /// When it was minted.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// When it was revoked; `None` while active.
    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
    /// The event type it creates.
    pub event_type: crate::event_store::EventType,
    /// The one owner it may create events for; `None` for any.
    pub scope: Option<String>,
}

/// See `variant CommandToken`. Same shape as `ExternalEventToken`/
/// `DirectCreationToken` above, scoped to a `CommandType` instead of an
/// `EventType`, `scope` included - checked by
/// `event_store::owner_scope_satisfied` in `authorise_command_trigger`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandToken {
    /// The token's id: the part before the `.` in a bearer credential.
    pub id: String,
    /// The token's secret: the part after the `.`.
    pub secret: String,
    /// Whether it is accepted.
    pub status: TokenStatus,
    /// When it was minted.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// When it was revoked; `None` while active.
    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
    /// The command type it submits.
    pub command_type: crate::event_store::CommandType,
    /// The one owner it may submit commands for; `None` for any.
    pub scope: Option<String>,
}

/// See `entity AccessToken`'s `purpose` field - a Rust sum type over the
/// four variants stands in for it directly, the same "the enum variant
/// tag is the purpose" treatment `Event.origin`/`EventOrigin` gets, so
/// there is no separate `purpose` field to carry: matching on this enum
/// already tells the four apart. Exists for `RevokeToken`, the one rule
/// that operates on "any `AccessToken`" polymorphically rather than on one
/// concrete variant.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AccessToken {
    /// Lets an external system create one event type.
    ExternalEventToken(ExternalEventToken),
    /// Lets a caller create one event type without a command.
    DirectCreationToken(DirectCreationToken),
    /// Lets a REST caller submit one command type.
    CommandToken(CommandToken),
    /// Lets a REST caller read one event type.
    EventReadToken(EventReadToken),
}

impl AccessToken {
    fn status(&self) -> TokenStatus {
        match self {
            AccessToken::ExternalEventToken(t) => t.status,
            AccessToken::DirectCreationToken(t) => t.status,
            AccessToken::CommandToken(t) => t.status,
            AccessToken::EventReadToken(t) => t.status,
        }
    }

    /// `token_scope` from `rule RevokeToken`: `token.command_type.bounded_context`
    /// for a `CommandToken`, `token.event_type.bounded_context` for the
    /// other three.
    fn scope(&self) -> &BoundedContext {
        match self {
            AccessToken::ExternalEventToken(t) => &t.event_type.bounded_context,
            AccessToken::DirectCreationToken(t) => &t.event_type.bounded_context,
            AccessToken::CommandToken(t) => &t.command_type.bounded_context,
            AccessToken::EventReadToken(t) => &t.event_type.bounded_context,
        }
    }

    /// The token's own owner scope (`None` = unrestricted) - not to be
    /// confused with [`scope`](Self::scope) above, which is `RevokeToken`'s
    /// bounded-context `token_scope`.
    fn owner_scope(&self) -> Option<&str> {
        match self {
            AccessToken::ExternalEventToken(t) => t.scope.as_deref(),
            AccessToken::DirectCreationToken(t) => t.scope.as_deref(),
            AccessToken::CommandToken(t) => t.scope.as_deref(),
            AccessToken::EventReadToken(t) => t.scope.as_deref(),
        }
    }
}

/// Library-level errors this module's own rules reject for - an
/// enumerable, closed set, unlike a bounded context's own
/// `CommandDecision::Rejected` (see crate::error and
/// docs/architecture.md ยง4.1).
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// This Role is not active.
    #[error("this Role is not active")]
    RoleNotActive,

    /// This RoleAccessMapping is not active.
    #[error("this RoleAccessMapping is not active")]
    GrantNotActive,

    /// This grant's access level is too low for this action.
    #[error("this grant's access level is too low for this action")]
    InsufficientAccessLevel,

    /// This RoleAccessMapping is scoped to a different bounded context.
    #[error("this RoleAccessMapping is scoped to a different bounded context")]
    GrantBoundedContextMismatch,

    /// Cross-tenant read/write fix (docs/architecture.md's own write-up
    /// of these passes): a grant/token names a `scope`, the record's own
    /// type declares an owner dimension, and the record's own derived
    /// owner either differs from `scope` or is not yet established -
    /// fail-closed, the same "affirmatively provable, not merely
    /// un-contradicted" framing every caller of this variant shares. A
    /// single-record surface (`projections::query_projection`,
    /// `event_store::inspect_event`, `event_store::authorise_command_submission`/
    /// `authorise_command_trigger`/`create_external_event`/`create_direct_event`,
    /// the write side always having exactly one record to authorise
    /// rather than a range) rejects outright with this; multi-record read
    /// surfaces (`event_store::query_events`/`count_events`/
    /// `deliver_to_subscriptions`/`fetch_events`/`consume_events`) never
    /// construct it at all - a record that fails this check is filtered
    /// out of the result, not a reason to fail the whole call.
    #[error("this grant is scoped to a value that does not match this record's own owner")]
    GrantScopeMismatch,

    /// `projections::query_projection`'s own whole-instance team gate
    /// (issue #17, docs/architecture.md's own write-up of this
    /// pass): a projection declares `Projection::TEAM_ONLY` and the
    /// querying `access_mapping.role.name` doesn't match it. Kept
    /// distinct from `GrantScopeMismatch` above even though both reject
    /// a `query_projection` call - that one is about tenant ownership of
    /// one instance, this one is about team membership to query the
    /// projection at all, and the two are independent, composable checks
    /// (a projection may declare both). `ProjectionQuery` is GraphQL-only,
    /// so unlike `GrantScopeMismatch` this never needed a
    /// `skilj-rest::error::status_for` arm - `to_graphql_error` renders
    /// any `SkiljRejection` generically via `code()`/`message()`.
    #[error("this grant's Role is not on the team this projection requires to query it")]
    NotOnRequiredTeam,

    /// The private-field mechanism's own grant-time check: `event =
    /// null or is_default_private_reader(event, access_mapping)` (and the
    /// `command` sibling) from `rule GrantPrivateFieldAccessForEvent`/
    /// `GrantPrivateFieldAccessForCommand`. Only ever constructed for a
    /// per-record grant - a blanket one (naming neither) names nothing to
    /// check yet, and is trusted at grant time, re-derived at every read
    /// instead (see `event_store::is_default_private_reader`'s own doc
    /// comment).
    #[error("the caller is not this record's own default private reader")]
    NotDefaultPrivateReader,

    /// `rule RevokePrivateFieldAccess`'s own guard: only the `Role` that
    /// made a `PrivateFieldGrant` may end it - not the grantee, and not an
    /// admin. The self-service counterpart to every other grant in this
    /// module needing a superadmin/admin to revoke it.
    #[error("only the Role that made this PrivateFieldGrant may revoke it")]
    NotGrantor,

    /// This PrivateFieldGrant is not active.
    #[error("this PrivateFieldGrant is not active")]
    PrivateFieldGrantNotActive,

    /// A named `event`/`command` belongs to a different bounded context
    /// than the grantor's own `access_mapping` - the `PrivateFieldGrant`
    /// counterpart to `GrantBoundedContextMismatch` above, kept distinct
    /// since the message names the right entity.
    #[error("this record does not belong to the grantor's own bounded context")]
    PrivateFieldRecordWrongBoundedContext,

    /// This AccessToken is not active.
    #[error("this AccessToken is not active")]
    TokenNotActive,

    /// Only an active superadmin Role may perform this action.
    #[error("only an active superadmin Role may perform this action")]
    NotSuperadmin,

    /// No active Role's external_subject matches this JWT's subject claim.
    #[error("no active Role's external_subject matches this JWT's subject claim")]
    UnrecognisedSubject,

    /// This external_subject is already claimed by another active Role.
    #[error("this external_subject is already claimed by another active Role")]
    ExternalSubjectAlreadyClaimed,

    /// This Role already holds an active RoleAccessMapping for this bounded context.
    #[error("this Role already holds an active RoleAccessMapping for this bounded context")]
    DuplicateActiveMapping,

    #[error("the presented JWT is malformed: {0}")]
    /// The presented JWT is malformed.
    MalformedJwt(String),

    /// The presented JWT has no key id (kid) header, so no JWKS entry can verify it.
    #[error("the presented JWT has no key id (kid) header, so no JWKS entry can verify it")]
    JwtMissingKeyId,

    #[error(
        "the presented JWT's key id (kid) doesn't match any key in the trusted IdP's JWKS, \
         even after a refetch"
    )]
    /// The JWT's key id matches no key in the IdP's JWKS, even after a
    /// refetch.
    UnknownSigningKey,

    #[error("the presented JWT failed verification: {0}")]
    /// The JWT failed verification: signature, issuer, audience or time.
    JwtVerificationFailed(String),

    #[error("the presented JWT's verified claims have no {0} claim to trust as the subject")]
    /// The verified claims lack the configured subject claim.
    MissingSubjectClaim(String),

    #[error("fetching the trusted IdP's JWKS failed: {0}")]
    /// Fetching the IdP's JWKS failed.
    JwksFetchFailed(String),

    /// `rule CreateEventReadToken`'s first `start_at_sequence`/
    /// `start_at_time` guard: `start_from` (after its own `?? beginning`
    /// default) resolves to `at_sequence`, but `start_at_sequence` is
    /// absent, or `start_at_time` is present alongside it.
    #[error("start_from = at_sequence requires start_at_sequence and forbids start_at_time")]
    StartAtSequenceMismatch,

    /// Same guard's `at_time` counterpart.
    #[error("start_from = at_time requires start_at_time and forbids start_at_sequence")]
    StartAtTimeMismatch,

    /// Same guard's `beginning`/`latest` counterpart - neither of these
    /// two takes a value, so naming one anyway is refused rather than
    /// silently ignored (see `create_event_read_token`'s own doc
    /// comment).
    #[error("start_from = beginning or latest forbids both start_at_sequence and start_at_time")]
    StartAtValueNotAllowed,

    /// The four token-minting rules and `RevokeToken`: a scoped admin grant
    /// may only mint or revoke tokens within its own scope
    /// (docs/architecture.md ยง92).
    #[error(
        "this admin grant is scoped, so a token it mints or revokes must have the same \
         scope (a minted one may omit it to inherit that scope)"
    )]
    TokenScopeBeyondGrant,
}

impl SkiljRejection for Error {
    fn code(&self) -> &str {
        match self {
            Error::RoleNotActive => "role_not_active",
            Error::GrantNotActive => "grant_not_active",
            Error::InsufficientAccessLevel => "insufficient_access_level",
            Error::GrantBoundedContextMismatch => "grant_bounded_context_mismatch",
            Error::GrantScopeMismatch => "grant_scope_mismatch",
            Error::TokenScopeBeyondGrant => "token_scope_beyond_grant",
            Error::NotOnRequiredTeam => "not_on_required_team",
            Error::NotDefaultPrivateReader => "not_default_private_reader",
            Error::NotGrantor => "not_grantor",
            Error::PrivateFieldGrantNotActive => "private_field_grant_not_active",
            Error::PrivateFieldRecordWrongBoundedContext => {
                "private_field_record_wrong_bounded_context"
            }
            Error::TokenNotActive => "token_not_active",
            Error::NotSuperadmin => "not_superadmin",
            Error::UnrecognisedSubject => "unrecognised_subject",
            Error::ExternalSubjectAlreadyClaimed => "external_subject_already_claimed",
            Error::DuplicateActiveMapping => "duplicate_active_mapping",
            Error::MalformedJwt(_) => "malformed_jwt",
            Error::JwtMissingKeyId => "jwt_missing_key_id",
            Error::UnknownSigningKey => "unknown_signing_key",
            Error::JwtVerificationFailed(_) => "jwt_verification_failed",
            Error::MissingSubjectClaim(_) => "missing_subject_claim",
            Error::JwksFetchFailed(_) => "jwks_fetch_failed",
            Error::StartAtSequenceMismatch => "start_at_sequence_mismatch",
            Error::StartAtTimeMismatch => "start_at_time_mismatch",
            Error::StartAtValueNotAllowed => "start_at_value_not_allowed",
        }
    }

    fn message(&self) -> String {
        self.to_string()
    }
}

/// Cross-tenant read fix (docs/architecture.md's own write-up of these
/// passes) - `snapshot_query::inspect_snapshot_field`'s own enforcement,
/// the identical single-record, fail-closed shape
/// `projections::query_projection`'s inline `access_mapping.scope`-vs-
/// instance-owner check already has (kept as its own tiny function here,
/// rather than inlined the same way, only because `inspectSnapshot` has
/// no other pure-function layer of its own for it to join - `event_owner_scope_satisfied`/
/// `command_owner_scope_satisfied` are functions in their own right for
/// the opposite reason, several call sites each). Holds when `scope` is
/// `None` (unrestricted - every caller's behaviour before `scope`
/// existed), or `owner` is `Some` and equal to it. Does not hold - fails
/// closed - when `scope` is `Some` and `owner` is either a different
/// value or `None` (not yet established): the identical "affirmatively
/// provable, not merely un-contradicted" stance every sibling in this
/// pass already takes.
pub fn scope_matches_owner(owner: Option<&str>, scope: Option<&str>) -> bool {
    match scope {
        None => true,
        Some(scope) => owner == Some(scope),
    }
}

/// The one `Role.name` equality test "does this Role belong to the
/// required team" ever comes down to, shared by two independently-arrived-at
/// call sites that both needed it: `event_store::entitled_to_read_private_field`'s
/// `PrivateFieldKind::Team` arm (a `PrivateField`'s own declared `team`)
/// and `projections::query_projection`'s `team_only` check
/// (`Projection::TEAM_ONLY`, issue #17). Kept as one function
/// specifically so a future change to what "matching a team" means
/// (case-insensitive names, multiple teams per Role, team hierarchies)
/// has exactly one definition to update rather than two that could drift
/// apart. Vacuously true when `required` is `None` - no team named, no
/// membership to hold.
pub fn role_matches_required_team(role: &Role, required: Option<&str>) -> bool {
    match required {
        None => true,
        Some(name) => role.name == name,
    }
}

/// Reused by `bootstrap::add_bounded_context`/
/// `bootstrap::list_bounded_contexts` (both `facing caller: Superadmin`,
/// the same actor every rule in this module already checks this way),
/// and by `skilj-graphql`'s superadmin-only resolvers, which check it
/// before any lookup (docs/architecture.md ยง139).
pub fn require_active_superadmin(caller: &Role) -> crate::error::Result<()> {
    if caller.status != RoleStatus::Active {
        return Err(Error::RoleNotActive.into());
    }
    if !caller.superadmin {
        return Err(Error::NotSuperadmin.into());
    }
    Ok(())
}

/// A deployment's trust configuration for exactly one external IdP - see
/// the identity resolution note above `entity Role` and docs/
/// [architecture.md ยง6](../../../docs/architecture.md#idp-trust-configuration). Runtime/library configuration, not domain state,
/// the same register the spec's own note gives the in-memory event
/// cache's startup warm-up count: nothing in the domain reads or writes
/// these values, they only parameterise `verify_and_extract_subject`
/// below.
#[derive(Debug, Clone)]
pub struct IdpConfig {
    /// Where the IdP publishes its signing keys.
    pub jwks_endpoint: reqwest::Url,
    /// The `iss` a JWT must carry.
    pub issuer: String,
    /// The algorithm a JWT must be signed with.
    pub signing_algorithm: SigningAlgorithm,
    /// The `aud` values a JWT must carry (at least one of) to be accepted:
    /// this deployment's own client id(s) at the IdP. Required, never
    /// empty. An IdP issues tokens to every application registered with
    /// it, all under the same `issuer` and signing keys, so without this
    /// check a token issued to any *other* application at the same IdP
    /// would be accepted here as its user (docs/architecture.md ยง81).
    pub audiences: Vec<String>,
    /// Defaults to `"sub"`, the standard JWT subject claim - the one
    /// degree of freedom the spec's own note leaves step 2 ("SkilJ
    /// trusts the subject claim of a verified JWT... configurable" per
    /// the identity resolution note's closing paragraph).
    pub subject_claim: String,
}

impl IdpConfig {
    /// `audience` is the `aud` value the IdP puts in tokens issued for
    /// this deployment (usually its client id there); see
    /// [`audiences`](Self::audiences). More can be accepted with
    /// [`with_additional_audience`](Self::with_additional_audience).
    pub fn new(
        jwks_endpoint: reqwest::Url,
        issuer: impl Into<String>,
        audience: impl Into<String>,
        signing_algorithm: SigningAlgorithm,
    ) -> Self {
        Self {
            jwks_endpoint,
            issuer: issuer.into(),
            signing_algorithm,
            audiences: vec![audience.into()],
            subject_claim: "sub".to_string(),
        }
    }

    /// Also accept tokens whose `aud` is `audience` - for a deployment
    /// reached through more than one client registration at the same IdP
    /// (a web app and a CLI, say).
    pub fn with_additional_audience(mut self, audience: impl Into<String>) -> Self {
        self.audiences.push(audience.into());
        self
    }

    /// Trusts `claim` as the subject instead of `sub`.
    pub fn with_subject_claim(mut self, claim: impl Into<String>) -> Self {
        self.subject_claim = claim.into();
        self
    }
}

/// The signing algorithms `IdpConfig` accepts - asymmetric only.
/// `jsonwebtoken::Algorithm` also offers HMAC variants, deliberately not
/// wrapped here: an HMAC signature is verified with the same secret it
/// was signed with, which would mean this process and the external IdP
/// sharing a symmetric secret - a trust shape the spec's own "SkilJ does
/// not authenticate GraphQL callers itself; it delegates to a trusted
/// external identity provider" framing doesn't fit. SkilJ only ever
/// verifies a JWT an external IdP already signed with its own private
/// key.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SigningAlgorithm {
    /// RSA PKCS#1 v1.5 with SHA-256.
    Rs256,
    /// RSA PKCS#1 v1.5 with SHA-384.
    Rs384,
    /// RSA PKCS#1 v1.5 with SHA-512.
    Rs512,
    /// ECDSA on P-256 with SHA-256.
    Es256,
    /// ECDSA on P-384 with SHA-384.
    Es384,
}

impl SigningAlgorithm {
    fn to_jsonwebtoken(self) -> jsonwebtoken::Algorithm {
        match self {
            SigningAlgorithm::Rs256 => jsonwebtoken::Algorithm::RS256,
            SigningAlgorithm::Rs384 => jsonwebtoken::Algorithm::RS384,
            SigningAlgorithm::Rs512 => jsonwebtoken::Algorithm::RS512,
            SigningAlgorithm::Es256 => jsonwebtoken::Algorithm::ES256,
            SigningAlgorithm::Es384 => jsonwebtoken::Algorithm::ES384,
        }
    }
}

/// Caches an IdP's JWKS (JSON Web Key Set), keyed by each key's own
/// `kid` - see [docs/architecture.md ยง6](../../../docs/architecture.md#idp-trust-configuration) for why this is reactive-refresh
/// rather than a background-timer poll: a JWT whose `kid` isn't already
/// cached triggers exactly one refetch of the whole set before giving
/// up, rather than a task refreshing on a schedule nothing here needs to
/// manage the lifecycle of. `min_refetch_interval` (a few seconds', not
/// configurable - an internal safety margin, not a tuning knob) is what
/// keeps a caller presenting JWTs with garbage `kid` values from cheaply
/// forcing a refetch on every single request.
///
/// One `JwksCache` per `IdpConfig`, held for the process's lifetime
/// (`Skilj` holds one, built once in `.build()`) - never reconstructed
/// per request, so its cached keys and refetch timer persist exactly the
/// way this design depends on.
pub struct JwksCache {
    client: reqwest::Client,
    /// Bounds each JWKS fetch end to end (connect, send, read). The
    /// refetch runs while holding `last_refetch`, so an unbounded fetch
    /// against an IdP endpoint that accepted the connection and then
    /// stalled held that lock forever: every later cache miss - including
    /// the refetch a real key rotation needs - queued behind it, and no
    /// JWT signed with a new key could be verified again until restart
    /// (docs/architecture.md ยง82).
    fetch_timeout: std::time::Duration,
    jwks_endpoint: reqwest::Url,
    min_refetch_interval: std::time::Duration,
    keys: tokio::sync::RwLock<std::collections::HashMap<String, jsonwebtoken::DecodingKey>>,
    /// Held across the whole refetch, not just the timestamp update, so
    /// concurrent misses queue behind one in-flight fetch and then see
    /// its result - see `key_for`.
    last_refetch: tokio::sync::Mutex<Option<std::time::Instant>>,
}

impl JwksCache {
    /// How long one JWKS fetch may take before it fails with
    /// `JwksFetchFailed`.
    pub const DEFAULT_FETCH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

    /// Overrides [`DEFAULT_FETCH_TIMEOUT`](Self::DEFAULT_FETCH_TIMEOUT).
    pub fn with_fetch_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.fetch_timeout = timeout;
        self
    }

    /// A cache for the JWKS at `jwks_endpoint`, empty until the first JWT is
    /// verified.
    pub fn new(jwks_endpoint: reqwest::Url) -> Self {
        Self {
            client: reqwest::Client::new(),
            fetch_timeout: Self::DEFAULT_FETCH_TIMEOUT,
            jwks_endpoint,
            min_refetch_interval: std::time::Duration::from_secs(5),
            keys: tokio::sync::RwLock::new(std::collections::HashMap::new()),
            last_refetch: tokio::sync::Mutex::new(None),
        }
    }

    /// The cached `DecodingKey` for `kid`, refetching the whole JWKS
    /// document once first when it isn't already cached and the minimum
    /// refetch interval has elapsed since the last attempt (whether or
    /// not that attempt found the key being looked for now) - `None`
    /// either way it still can't be found, which
    /// `verify_and_extract_subject` below turns into
    /// `Error::UnknownSigningKey`.
    ///
    /// Single-flight: the refetch runs while holding `last_refetch`, and
    /// the cache is checked again once that lock is acquired. A caller
    /// that missed while another caller's fetch was in flight therefore
    /// waits for it and finds the key, rather than seeing a refetch "too
    /// recent" and being rejected - which used to 401 every concurrent
    /// request on a cold start or an IdP key rotation.
    async fn key_for(&self, kid: &str) -> crate::error::Result<Option<jsonwebtoken::DecodingKey>> {
        if let Some(key) = self.keys.read().await.get(kid) {
            return Ok(Some(key.clone()));
        }

        let mut last_refetch = self.last_refetch.lock().await;
        if let Some(key) = self.keys.read().await.get(kid) {
            return Ok(Some(key.clone()));
        }
        let now = std::time::Instant::now();
        if last_refetch.is_some_and(|last| now.duration_since(last) < self.min_refetch_interval) {
            return Ok(None);
        }
        *last_refetch = Some(now);

        self.refetch().await?;
        Ok(self.keys.read().await.get(kid).cloned())
    }

    #[tracing::instrument(skip_all, fields(jwks_endpoint = %self.jwks_endpoint))]
    async fn refetch(&self) -> crate::error::Result<()> {
        let jwks: jsonwebtoken::jwk::JwkSet = self
            .client
            .get(self.jwks_endpoint.clone())
            .timeout(self.fetch_timeout)
            .send()
            .await
            .map_err(|e| Error::JwksFetchFailed(e.to_string()))?
            .json()
            .await
            .map_err(|e| Error::JwksFetchFailed(e.to_string()))?;

        let mut keys = self.keys.write().await;
        keys.clear();
        for jwk in &jwks.keys {
            let (Some(kid), Ok(decoding_key)) = (
                jwk.common.key_id.clone(),
                jsonwebtoken::DecodingKey::from_jwk(jwk),
            ) else {
                continue;
            };
            keys.insert(kid, decoding_key);
        }
        Ok(())
    }
}

/// Step 1 of the identity resolution note above `entity Role`: verifies
/// `jwt`'s signature against `config`'s trusted IdP (fetching/caching its
/// JWKS via `cache` as needed), then step 2, pulling out - and trusting -
/// only `config.subject_claim`. Everything else in the JWT's claims is
/// read by nobody: `jsonwebtoken::decode` verifies the signature,
/// `issuer`, audience, algorithm, `exp` and `nbf`, but claims are
/// decoded into a generic JSON map rather than a fixed struct, since
/// `subject_claim` is configurable rather than always `"sub"`.
///
/// Genuine I/O (JWKS fetch on a cache miss), so - unlike every function
/// above in this module - not a pure function `skilj-core`'s own test
/// suite exercises via plain unit tests; see this crate's `tests/`
/// directory for its own JWKS-serving test harness instead. Called by
/// `skilj-graphql`'s auth extractor, once per request that presents a
/// bearer JWT; its output is what `resolve_role_by_external_subject`
/// below takes as `verified_subject`.
pub async fn verify_and_extract_subject(
    jwt: &str,
    config: &IdpConfig,
    cache: &JwksCache,
) -> crate::error::Result<String> {
    verify_jwt(jwt, config, cache).await.map(|v| v.subject)
}

/// What [`verify_jwt`] trusts from a verified JWT.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedJwt {
    /// `config.subject_claim`'s value.
    pub subject: String,
    /// The last moment this token is still accepted: its `exp` plus the
    /// same leeway verification allows. A connection authenticated once
    /// and kept open (a GraphQL websocket) must stop being served by then
    /// (docs/architecture.md ยง135).
    pub valid_until: std::time::SystemTime,
}

/// [`verify_and_extract_subject`], also returning when the token expires.
pub async fn verify_jwt(
    jwt: &str,
    config: &IdpConfig,
    cache: &JwksCache,
) -> crate::error::Result<VerifiedJwt> {
    let header =
        jsonwebtoken::decode_header(jwt).map_err(|e| Error::MalformedJwt(e.to_string()))?;
    let kid = header.kid.ok_or(Error::JwtMissingKeyId)?;
    let Some(decoding_key) = cache.key_for(&kid).await? else {
        return Err(Error::UnknownSigningKey.into());
    };

    let mut validation = jsonwebtoken::Validation::new(config.signing_algorithm.to_jsonwebtoken());
    validation.set_issuer(&[&config.issuer]);
    // Audience is required, not optional: `IdpConfig::audiences` is
    // never empty, and a token with no `aud` at all is refused rather
    // than let through (`jsonwebtoken` otherwise only checks `aud` when
    // the token carries one). This used to be `validate_aud = false`,
    // after `Validation::new`'s own default (check against *no*
    // configured audience, rejecting every real OIDC token) broke a real
    // IdP - which accepted any token the same IdP issued to any other
    // application (docs/architecture.md ยง81).
    validation.set_audience(&config.audiences);
    validation.set_required_spec_claims(&["exp", "iss", "aud"]);
    // `nbf` is optional, but when a token carries one it isn't valid
    // before then (RFC 7519 ยง4.1.5). `jsonwebtoken` skips the check by
    // default; it uses the same leeway as `exp` (docs/architecture.md ยง111).
    validation.validate_nbf = true;

    let token_data = jsonwebtoken::decode::<serde_json::Map<String, serde_json::Value>>(
        jwt,
        &decoding_key,
        &validation,
    )
    .map_err(|e| Error::JwtVerificationFailed(e.to_string()))?;

    let subject = token_data
        .claims
        .get(&config.subject_claim)
        .and_then(|v| v.as_str())
        .map(str::to_string)
        .ok_or_else(|| Error::MissingSubjectClaim(config.subject_claim.clone()))?;
    // `exp` is a required claim and `decode` has already checked it is a
    // number in the future (within leeway), so this only reads it back.
    let exp = token_data
        .claims
        .get("exp")
        .and_then(|v| v.as_f64())
        .ok_or_else(|| Error::JwtVerificationFailed("exp is not a number".to_string()))?;
    // Clamped so an absurd `exp` can't overflow `SystemTime` (year 2106
    // is as good as never for a connection).
    let valid_until = std::time::UNIX_EPOCH
        + std::time::Duration::from_secs(exp.clamp(0.0, u32::MAX as f64) as u64)
        + std::time::Duration::from_secs(validation.leeway);
    Ok(VerifiedJwt {
        subject,
        valid_until,
    })
}

/// See the GraphQL identity resolution note above `entity Role`, step 3:
/// "That claim value resolves to the one active Role whose
/// external_subject matches it". The one pure part of the JWT-to-Role
/// resolution pipeline - step 1, verifying the presented JWT's signature
/// against the trusted IdP's JWKS, is a black box this engine doesn't own
/// ("a black box here, the same register as `protect_sensitive_fields`
/// and `generate_token_secret`" per the spec's own text), so it stays a
/// caller-supplied `verified_subject: &str` rather than something this
/// function fetches or verifies itself - the caller has already done
/// that and is handing over the JWT's trusted subject claim, nothing
/// else from it (step 2: "SkilJ trusts the subject claim of a verified
/// JWT, and nothing else in it"). `existing_roles` is every `Role` this
/// engine currently knows of, the same full-snapshot treatment
/// `create_role`'s own `existing_roles` gets below.
/// `UniqueActiveExternalSubject` is what makes "the one" well defined -
/// at most one active `Role` can ever match.
pub fn resolve_role_by_external_subject<'a>(
    verified_subject: &str,
    existing_roles: &'a [Role],
) -> crate::error::Result<&'a Role> {
    existing_roles
        .iter()
        .find(|r| r.status == RoleStatus::Active && r.external_subject == verified_subject)
        .ok_or_else(|| Error::UnrecognisedSubject.into())
}

/// See `rule CreateRole`. `id` is the value the caller's own
/// `generate_token_id()` already produced - not this function's to
/// generate, the same caller-supplied-black-box-output treatment
/// `next_sequence` gets elsewhere in this codebase (`generate_token_id`
/// is real, in `crate::shared`, a plain UUIDv4). `existing_roles` is
/// every `Role` this engine currently knows of, for the
/// `UniqueActiveExternalSubject` check - a full-snapshot parameter, the
/// same shape `consistency_boundary_and_matching_events` takes `Event`s
/// in, since there's no single key to look this existential check up by.
pub fn create_role(
    caller: &Role,
    name: String,
    superadmin: bool,
    external_subject: String,
    existing_roles: &[Role],
    id: String,
    now: chrono::DateTime<chrono::Utc>,
) -> crate::error::Result<Role> {
    require_active_superadmin(caller)?;
    if existing_roles
        .iter()
        .any(|r| r.external_subject == external_subject && r.status == RoleStatus::Active)
    {
        return Err(Error::ExternalSubjectAlreadyClaimed.into());
    }

    Ok(Role {
        id,
        external_subject,
        name,
        superadmin,
        status: RoleStatus::Active,
        created_at: now,
        revoked_at: None,
    })
}

/// See `rule RevokeRole`. `active_mappings` is `role.access_mappings
/// where status = active` as already looked up by the caller - the same
/// "relationship projection resolved by the caller" treatment
/// `Role.access_mappings` gets everywhere else (see the doc comment on
/// `Role`). Returns the revoked `Role` and every mapping it just
/// cascaded the revocation to - together they *are*
/// `RevokedRoleImpliesMappingsRevoked`, established in the same
/// transaction rather than checked after the fact.
pub fn revoke_role(
    caller: &Role,
    role: &Role,
    active_mappings: &[RoleAccessMapping],
    now: chrono::DateTime<chrono::Utc>,
) -> crate::error::Result<(Role, Vec<RoleAccessMapping>)> {
    require_active_superadmin(caller)?;
    if role.status != RoleStatus::Active {
        return Err(Error::RoleNotActive.into());
    }

    let revoked_role = Role {
        status: RoleStatus::Revoked,
        revoked_at: Some(now),
        ..role.clone()
    };
    let revoked_mappings = active_mappings
        .iter()
        .cloned()
        .map(|m| RoleAccessMapping {
            status: RoleStatus::Revoked,
            revoked_at: Some(now),
            ..m
        })
        .collect();

    Ok((revoked_role, revoked_mappings))
}

/// See `rule GrantRoleAccessMapping`. `existing_mappings` is every
/// `RoleAccessMapping` this engine currently knows of, for the `not
/// exists RoleAccessMapping{role, bounded_context, status: active}`
/// check - same full-snapshot treatment as `create_role`'s
/// `existing_roles`.
#[allow(clippy::too_many_arguments)]
pub fn grant_role_access_mapping(
    caller: &Role,
    role: &Role,
    bounded_context: &BoundedContext,
    level: AccessLevel,
    can_read_sensitive: bool,
    scope: Option<String>,
    existing_mappings: &[RoleAccessMapping],
    now: chrono::DateTime<chrono::Utc>,
) -> crate::error::Result<RoleAccessMapping> {
    require_active_superadmin(caller)?;
    if role.status != RoleStatus::Active {
        return Err(Error::RoleNotActive.into());
    }
    if bounded_context.status != crate::event_store::BoundedContextStatus::Active {
        return Err(crate::event_store::Error::BoundedContextArchived.into());
    }
    if existing_mappings.iter().any(|m| {
        &m.role == role && &m.bounded_context == bounded_context && m.status == RoleStatus::Active
    }) {
        return Err(Error::DuplicateActiveMapping.into());
    }

    Ok(RoleAccessMapping {
        role: role.clone(),
        bounded_context: bounded_context.clone(),
        level,
        can_read_sensitive,
        scope,
        status: RoleStatus::Active,
        created_at: now,
        revoked_at: None,
    })
}

/// See `rule RevokeRoleAccessMapping`.
pub fn revoke_role_access_mapping(
    caller: &Role,
    access_mapping: &RoleAccessMapping,
    now: chrono::DateTime<chrono::Utc>,
) -> crate::error::Result<RoleAccessMapping> {
    require_active_superadmin(caller)?;
    if access_mapping.status != RoleStatus::Active {
        return Err(Error::GrantNotActive.into());
    }

    Ok(RoleAccessMapping {
        status: RoleStatus::Revoked,
        revoked_at: Some(now),
        ..access_mapping.clone()
    })
}

/// See `rule GrantPrivateFieldAccessForEvent`. `id` is the caller's own
/// `generate_token_id()` output, not this function's to generate - the
/// same treatment `create_role`'s `id`/every `create_*_token` function's
/// `id` already gets. `event: None` mints a blanket grant; `Some` a
/// per-record one, checked against `is_default_private_reader` below.
pub fn grant_private_field_access_for_event(
    access_mapping: &RoleAccessMapping,
    grantee: &Role,
    event: Option<&crate::event_store::Event>,
    id: String,
    now: chrono::DateTime<chrono::Utc>,
) -> crate::error::Result<PrivateFieldGrant> {
    if access_mapping.status != RoleStatus::Active {
        return Err(Error::GrantNotActive.into());
    }
    if grantee.status != RoleStatus::Active {
        return Err(Error::RoleNotActive.into());
    }
    if let Some(event) = event {
        if !event
            .bounded_context
            .same_as(&access_mapping.bounded_context)
        {
            return Err(Error::PrivateFieldRecordWrongBoundedContext.into());
        }
        if !crate::event_store::is_default_private_reader(event, &access_mapping.role) {
            return Err(Error::NotDefaultPrivateReader.into());
        }
    }
    Ok(PrivateFieldGrant {
        id,
        bounded_context: access_mapping.bounded_context.clone(),
        grantor: access_mapping.role.clone(),
        grantee: grantee.clone(),
        event_sequence: event.map(|e| e.sequence),
        command_id: None,
        status: TokenStatus::Active,
        created_at: now,
        revoked_at: None,
    })
}

/// See `rule GrantPrivateFieldAccessForCommand` - same shape and
/// reasoning as `grant_private_field_access_for_event` above, checked
/// against a `Command` instead of an `Event`.
pub fn grant_private_field_access_for_command(
    access_mapping: &RoleAccessMapping,
    grantee: &Role,
    command: Option<&crate::event_store::Command>,
    id: String,
    now: chrono::DateTime<chrono::Utc>,
) -> crate::error::Result<PrivateFieldGrant> {
    if access_mapping.status != RoleStatus::Active {
        return Err(Error::GrantNotActive.into());
    }
    if grantee.status != RoleStatus::Active {
        return Err(Error::RoleNotActive.into());
    }
    if let Some(command) = command {
        if !command
            .bounded_context
            .same_as(&access_mapping.bounded_context)
        {
            return Err(Error::PrivateFieldRecordWrongBoundedContext.into());
        }
        if !crate::event_store::is_default_private_reader(command, &access_mapping.role) {
            return Err(Error::NotDefaultPrivateReader.into());
        }
    }
    Ok(PrivateFieldGrant {
        id,
        bounded_context: access_mapping.bounded_context.clone(),
        grantor: access_mapping.role.clone(),
        grantee: grantee.clone(),
        event_sequence: None,
        command_id: command.map(|c| c.id.clone()),
        status: TokenStatus::Active,
        created_at: now,
        revoked_at: None,
    })
}

/// See `rule RevokePrivateFieldAccess`. Only the Role that made a grant
/// may end it - not the grantee, and not an admin (`Error::NotGrantor`) -
/// the self-service counterpart to `revoke_role_access_mapping`'s own
/// superadmin-only guard just below.
pub fn revoke_private_field_access(
    access_mapping: &RoleAccessMapping,
    grant: &PrivateFieldGrant,
    now: chrono::DateTime<chrono::Utc>,
) -> crate::error::Result<PrivateFieldGrant> {
    if access_mapping.status != RoleStatus::Active {
        return Err(Error::GrantNotActive.into());
    }
    if access_mapping.role != grant.grantor {
        return Err(Error::NotGrantor.into());
    }
    if grant.status != TokenStatus::Active {
        return Err(Error::PrivateFieldGrantNotActive.into());
    }
    Ok(PrivateFieldGrant {
        status: TokenStatus::Revoked,
        revoked_at: Some(now),
        ..grant.clone()
    })
}

/// See `rule ListPrivateFieldGrants`. `all_grants_in_context` is the
/// caller's own already-loaded snapshot - this bounded context's rows
/// alone, the same "pure function, I/O resolved before the call" split
/// every other rule in this crate follows - filtered here down to
/// `grantor`'s own (or, when `grantor` is omitted, the caller's own).
/// Naming a *different* grantor requires `access_mapping.level = admin`;
/// naming none, or naming oneself, needs no particular level - reading
/// back one's own decisions needs no grant beyond having made them.
/// Revoked grants are included, not filtered out - see the rule's own
/// `@guidance` for why.
pub fn list_private_field_grants(
    access_mapping: &RoleAccessMapping,
    grantor: Option<&Role>,
    all_grants_in_context: &[PrivateFieldGrant],
) -> crate::error::Result<Vec<PrivateFieldGrant>> {
    if access_mapping.status != RoleStatus::Active {
        return Err(Error::GrantNotActive.into());
    }
    let subject = match grantor {
        None => &access_mapping.role,
        Some(named) if named == &access_mapping.role => named,
        Some(named) if access_mapping.level == AccessLevel::Admin => named,
        Some(_) => return Err(Error::InsufficientAccessLevel.into()),
    };
    Ok(all_grants_in_context
        .iter()
        .filter(|g| &g.grantor == subject)
        .cloned()
        .collect())
}

/// One now-inactive `RoleAccessMapping`, identified the same way a live
/// `EventSubscription` connection already scopes itself - `role_id` plus
/// `bounded_context` name, never the full entity. `RevocationBroadcaster`'s
/// own publish payload.
#[derive(Debug, Clone)]
pub struct RevokedMapping {
    /// The role whose grant was revoked.
    pub role_id: String,
    /// The bounded context it was revoked on.
    pub bounded_context: String,
}

/// `EventSubscription`'s own second broadcast channel, alongside
/// `event_store::EventBroadcaster` - drift audit finding #4 (2026-08-20,
/// see project memory `skilj-drift-audit-2026-08-20`). Fixes
/// `RevocationClosesTheConnection`'s real gap: the per-delivered-event
/// re-check `resolvers::event_subscription` already did only ever ran
/// when an event happened to arrive, so a subscription in a bounded
/// context that had gone quiet stayed open indefinitely after its own
/// grant was revoked - exactly the scenario that guarantee's own spec
/// text exists to rule out ("the caller would wait on it indefinitely
/// believing itself current"). This is the push half of the fix: every
/// site that revokes a `RoleAccessMapping` - `revoke_role_and_mappings`'s
/// own cascade and `revoke_active_role_access_mapping` directly, both in
/// `skilj-graphql/src/resolvers/access_management.rs` - publishes here
/// right after the revocation is durably committed, and both subscription
/// resolvers `tokio::select!` against it alongside their own
/// `EventBroadcaster` receiver, closing the instant a notification names
/// their own `(role_id, bounded_context)` rather than waiting for the
/// next matching event. The identical "same choke point, one shared
/// process-wide instance, silently-ignored `SendError` when nobody's
/// listening" shape `EventBroadcaster` already establishes - see its own
/// doc comment, not repeated here.
///
/// Revocations are rare and low-volume compared to events, so unlike
/// `EventBroadcaster`'s own `capacity` this has no builder-configurable
/// knob - a fixed, generous capacity is enough headroom that a lagged
/// receiver is already an exceptional case, handled defensively (a direct
/// database re-check, not assumed-still-active) rather than tuned around.
#[derive(Clone)]
pub struct RevocationBroadcaster {
    sender: tokio::sync::broadcast::Sender<RevokedMapping>,
    instance_id: String,
}

impl RevocationBroadcaster {
    /// A broadcaster no one listens to yet.
    pub fn new() -> Self {
        let (sender, _receiver) = tokio::sync::broadcast::channel(256);
        Self {
            sender,
            instance_id: crate::shared::generate_token_id(),
        }
    }

    /// See `EventBroadcaster::instance_id`'s own doc comment - identical
    /// role, for `db::notify_revocation`/this instance's cross-instance
    /// dispatch loop instead of `db::notify_event_appended`/the
    /// `EventBroadcaster` one.
    pub fn instance_id(&self) -> &str {
        &self.instance_id
    }

    /// A fresh, independent receiver - one call per live GraphQL
    /// subscription, the same as `EventBroadcaster::subscribe`.
    pub fn subscribe(&self) -> tokio::sync::broadcast::Receiver<RevokedMapping> {
        self.sender.subscribe()
    }

    /// Called once per revoked `RoleAccessMapping`, right after that
    /// revocation is durably committed - see this type's own doc comment
    /// for the two real call sites. A `SendError` (zero receivers
    /// currently subscribed) is the expected steady state, not a
    /// failure - identical reasoning to `EventBroadcaster::publish`.
    pub fn publish(&self, revoked: RevokedMapping) {
        let _ = self.sender.send(revoked);
    }
}

impl Default for RevocationBroadcaster {
    fn default() -> Self {
        Self::new()
    }
}

/// `access_mapping.status = active`/`access_mapping.level = admin` -
/// shared by every `Create*Token` rule below and by `revoke_token`, all
/// four of which require this exact pair (see
/// `EventTypeAdminOperations`/`CommandTypeAdminOperations`/
/// `TokenRevocation`'s own `facing access_mapping: AdminAccess`).
fn require_active_admin(access_mapping: &RoleAccessMapping) -> crate::error::Result<()> {
    if access_mapping.status != RoleStatus::Active {
        return Err(Error::GrantNotActive.into());
    }
    if access_mapping.level != AccessLevel::Admin {
        return Err(Error::InsufficientAccessLevel.into());
    }
    Ok(())
}

/// The scope a token minted under `access_mapping` gets, for all four
/// token-minting rules (docs/architecture.md ยง92). An unscoped grant mints
/// whatever `requested` names, narrowing included - the ordinary staff
/// case. A scoped grant is confined to its own scope and can't mint its
/// way out of it: omitted, the token inherits the grant's scope; naming
/// the same scope is fine; naming another, or none, is refused.
fn scope_for_minted_token(
    access_mapping: &RoleAccessMapping,
    requested: Option<String>,
) -> crate::error::Result<Option<String>> {
    match (access_mapping.scope.as_deref(), requested) {
        (None, requested) => Ok(requested),
        (Some(own), None) => Ok(Some(own.to_string())),
        (Some(own), Some(requested)) if requested == own => Ok(Some(requested)),
        (Some(_), Some(_)) => Err(Error::TokenScopeBeyondGrant.into()),
    }
}

/// See `rule CreateExternalEventToken`. `id`/`secret` are the caller's own
/// `generate_token_id()`/`generate_token_secret()` output - not this
/// function's to generate, the same treatment `create_role`'s `id` gets
/// (see its own doc comment; both are real, in `crate::shared`). `scope`
/// is carried through unvalidated - `ExternalEventToken.scope`'s own doc
/// comment, and `create_event_read_token`'s below for the full
/// "independent of the minting admin's own scope" reasoning, shared by
/// all four token-minting functions alike.
pub fn create_external_event_token(
    access_mapping: &RoleAccessMapping,
    event_type: &crate::event_store::EventType,
    id: String,
    secret: String,
    scope: Option<String>,
    now: chrono::DateTime<chrono::Utc>,
) -> crate::error::Result<ExternalEventToken> {
    require_active_admin(access_mapping)?;
    let scope = scope_for_minted_token(access_mapping, scope)?;
    if !access_mapping
        .bounded_context
        .same_as(&event_type.bounded_context)
    {
        return Err(Error::GrantBoundedContextMismatch.into());
    }

    Ok(ExternalEventToken {
        id,
        secret,
        status: TokenStatus::Active,
        created_at: now,
        revoked_at: None,
        event_type: event_type.clone(),
        scope,
    })
}

/// See `rule CreateDirectCreationToken`. Same shape and reasoning as
/// `create_external_event_token` above.
pub fn create_direct_creation_token(
    access_mapping: &RoleAccessMapping,
    event_type: &crate::event_store::EventType,
    id: String,
    secret: String,
    scope: Option<String>,
    now: chrono::DateTime<chrono::Utc>,
) -> crate::error::Result<DirectCreationToken> {
    require_active_admin(access_mapping)?;
    let scope = scope_for_minted_token(access_mapping, scope)?;
    if !access_mapping
        .bounded_context
        .same_as(&event_type.bounded_context)
    {
        return Err(Error::GrantBoundedContextMismatch.into());
    }

    Ok(DirectCreationToken {
        id,
        secret,
        status: TokenStatus::Active,
        created_at: now,
        revoked_at: None,
        event_type: event_type.clone(),
        scope,
    })
}

/// See `rule CreateEventReadToken`. Same shape and reasoning as
/// `create_external_event_token` above, plus `scope` -
/// `EventReadToken.scope`'s own doc comment - carried through
/// unvalidated, the same "no validation on this value" treatment
/// `RoleAccessMapping.scope` already gets from `grant_role_access_mapping`.
/// It is the minted token's own scope, independent of the minting
/// admin's own `access_mapping.scope`: the grant authorising this call
/// (and every other token-minting call in this module) is checked for
/// level and bounded context alone, and has no bearing on what may be
/// named here - an admin holding an unscoped staff grant may mint a
/// company-scoped token, and that is the ordinary case, not an oversight.
///
/// `start_from` is the one parameter this function doesn't share with
/// its three siblings above - see `EventReadToken.start_from`'s own doc
/// comment for what it means. `None` (the caller omitted it, the spec's
/// own `start_from?`) resolves to `Beginning` here, the rule's own
/// `start_from ?? beginning` default substitution - the entity itself
/// never stores the absence, only the resolved value.
///
/// `start_at_sequence`/`start_at_time` are `AtSequence`/`AtTime`'s own
/// values (`EventReadToken.start_at_sequence`/`.start_at_time`'s own doc
/// comments) - the rule's three guards, checked here in the same order
/// the spec states them: `AtSequence` demands `start_at_sequence` and
/// forbids `start_at_time`, `AtTime` demands the reverse, and
/// `Beginning`/`Latest` forbid both. A caller that names one without its
/// value, or with the other one's, is refused outright
/// (`StartAtSequenceMismatch`/`StartAtTimeMismatch`/`StartAtValueNotAllowed`)
/// rather than silently resolved to some default - see those guards' own
/// doc comment in the spec for why.
#[allow(clippy::too_many_arguments)]
pub fn create_event_read_token(
    access_mapping: &RoleAccessMapping,
    event_type: &crate::event_store::EventType,
    id: String,
    secret: String,
    scope: Option<String>,
    start_from: Option<EventReadStartPosition>,
    start_at_sequence: Option<i64>,
    start_at_time: Option<chrono::DateTime<chrono::Utc>>,
    now: chrono::DateTime<chrono::Utc>,
) -> crate::error::Result<EventReadToken> {
    require_active_admin(access_mapping)?;
    let scope = scope_for_minted_token(access_mapping, scope)?;
    if !access_mapping
        .bounded_context
        .same_as(&event_type.bounded_context)
    {
        return Err(Error::GrantBoundedContextMismatch.into());
    }

    let resolved_start_from = start_from.unwrap_or(EventReadStartPosition::Beginning);
    match resolved_start_from {
        EventReadStartPosition::AtSequence => {
            if start_at_sequence.is_none() || start_at_time.is_some() {
                return Err(Error::StartAtSequenceMismatch.into());
            }
        }
        EventReadStartPosition::AtTime => {
            if start_at_time.is_none() || start_at_sequence.is_some() {
                return Err(Error::StartAtTimeMismatch.into());
            }
        }
        EventReadStartPosition::Beginning | EventReadStartPosition::Latest => {
            if start_at_sequence.is_some() || start_at_time.is_some() {
                return Err(Error::StartAtValueNotAllowed.into());
            }
        }
    }

    Ok(EventReadToken {
        id,
        secret,
        status: TokenStatus::Active,
        created_at: now,
        revoked_at: None,
        event_type: event_type.clone(),
        scope,
        start_from: resolved_start_from,
        start_at_sequence,
        start_at_time,
    })
}

/// See `rule CreateCommandToken`. Same shape and reasoning as
/// `create_external_event_token` above, scoped to a `CommandType` instead
/// of an `EventType`.
pub fn create_command_token(
    access_mapping: &RoleAccessMapping,
    command_type: &crate::event_store::CommandType,
    id: String,
    secret: String,
    scope: Option<String>,
    now: chrono::DateTime<chrono::Utc>,
) -> crate::error::Result<CommandToken> {
    require_active_admin(access_mapping)?;
    let scope = scope_for_minted_token(access_mapping, scope)?;
    if !access_mapping
        .bounded_context
        .same_as(&command_type.bounded_context)
    {
        return Err(Error::GrantBoundedContextMismatch.into());
    }

    Ok(CommandToken {
        id,
        secret,
        status: TokenStatus::Active,
        created_at: now,
        revoked_at: None,
        command_type: command_type.clone(),
        scope,
    })
}

/// See `rule RevokeToken`. One function for all four `AccessToken`
/// variants, matching the spec's own "one revocation rule for every
/// variant" framing - `token_scope` is `AccessToken::scope`, the only
/// place the variants differ here.
pub fn revoke_token(
    access_mapping: &RoleAccessMapping,
    token: &AccessToken,
    now: chrono::DateTime<chrono::Utc>,
) -> crate::error::Result<AccessToken> {
    require_active_admin(access_mapping)?;
    if !access_mapping.bounded_context.same_as(token.scope()) {
        return Err(Error::GrantBoundedContextMismatch.into());
    }
    // docs/architecture.md ยง92: a scoped admin's reach over tokens is its
    // own scope, for revoking as for minting - it can't revoke (cut off)
    // another owner's credentials, or an unrestricted staff one.
    if access_mapping
        .scope
        .as_deref()
        .is_some_and(|own| token.owner_scope() != Some(own))
    {
        return Err(Error::TokenScopeBeyondGrant.into());
    }
    if token.status() != TokenStatus::Active {
        return Err(Error::TokenNotActive.into());
    }

    Ok(match token.clone() {
        AccessToken::ExternalEventToken(t) => AccessToken::ExternalEventToken(ExternalEventToken {
            status: TokenStatus::Revoked,
            revoked_at: Some(now),
            ..t
        }),
        AccessToken::DirectCreationToken(t) => {
            AccessToken::DirectCreationToken(DirectCreationToken {
                status: TokenStatus::Revoked,
                revoked_at: Some(now),
                ..t
            })
        }
        AccessToken::CommandToken(t) => AccessToken::CommandToken(CommandToken {
            status: TokenStatus::Revoked,
            revoked_at: Some(now),
            ..t
        }),
        AccessToken::EventReadToken(t) => AccessToken::EventReadToken(EventReadToken {
            status: TokenStatus::Revoked,
            revoked_at: Some(now),
            ..t
        }),
    })
}