skilj-core 0.0.4

SkilJ's domain engine: entities, rules, the plugin API, and persistence. Zero web-framework dependency - see docs/architecture.md §3.
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
//! `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 (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)]
pub enum RoleStatus {
    Active,
    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 {
    pub id: String,
    pub external_subject: String,
    pub name: String,
    pub superadmin: bool,
    pub status: RoleStatus,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// See `enum AccessLevel`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccessLevel {
    Read,
    Write,
    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 {
    pub role: Role,
    pub bounded_context: BoundedContext,
    pub level: AccessLevel,
    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>,
    pub status: RoleStatus,
    pub created_at: chrono::DateTime<chrono::Utc>,
    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 {
    pub id: String,
    pub bounded_context: BoundedContext,
    pub grantor: Role,
    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>,
    pub command_id: Option<String>,
    pub status: TokenStatus,
    pub created_at: chrono::DateTime<chrono::Utc>,
    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)]
pub enum TokenStatus {
    Active,
    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 {
    pub id: String,
    pub secret: String,
    pub status: TokenStatus,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
    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 ExternalEventToken`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExternalEventToken {
    pub id: String,
    pub secret: String,
    pub status: TokenStatus,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
    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 {
    pub id: String,
    pub secret: String,
    pub status: TokenStatus,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
    pub event_type: crate::event_store::EventType,
    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 {
    pub id: String,
    pub secret: String,
    pub status: TokenStatus,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
    pub command_type: crate::event_store::CommandType,
    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)]
pub enum AccessToken {
    ExternalEventToken(ExternalEventToken),
    DirectCreationToken(DirectCreationToken),
    CommandToken(CommandToken),
    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,
        }
    }
}

/// 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 {
    #[error("this Role is not active")]
    RoleNotActive,

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

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

    #[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
    /// (Codeberg 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,

    #[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,

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

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

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

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

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

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

    #[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"
    )]
    UnknownSigningKey,

    #[error("the presented JWT failed verification: {0}")]
    JwtVerificationFailed(String),

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

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

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::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",
        }
    }

    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`, Codeberg 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,
    }
}

/// `pub(crate)`: 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).
pub(crate) 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. 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 {
    pub jwks_endpoint: reqwest::Url,
    pub issuer: String,
    pub signing_algorithm: SigningAlgorithm,
    /// 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 {
    pub fn new(
        jwks_endpoint: reqwest::Url,
        issuer: impl Into<String>,
        signing_algorithm: SigningAlgorithm,
    ) -> Self {
        Self {
            jwks_endpoint,
            issuer: issuer.into(),
            signing_algorithm,
            subject_claim: "sub".to_string(),
        }
    }

    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)]
pub enum SigningAlgorithm {
    Rs256,
    Rs384,
    Rs512,
    Es256,
    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 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,
    jwks_endpoint: reqwest::Url,
    min_refetch_interval: std::time::Duration,
    keys: tokio::sync::RwLock<std::collections::HashMap<String, jsonwebtoken::DecodingKey>>,
    last_refetch: tokio::sync::RwLock<Option<std::time::Instant>>,
}

impl JwksCache {
    pub fn new(jwks_endpoint: reqwest::Url) -> Self {
        Self {
            client: reqwest::Client::new(),
            jwks_endpoint,
            min_refetch_interval: std::time::Duration::from_secs(5),
            keys: tokio::sync::RwLock::new(std::collections::HashMap::new()),
            last_refetch: tokio::sync::RwLock::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`.
    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.write().await;
            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())
            .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` and algorithm, 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> {
    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]);
    // `IdpConfig` has no audience field at all - deliberately, per this
    // function's own doc comment above ("nothing else from it" but the
    // subject claim). `jsonwebtoken::Validation::new`'s own default is
    // `validate_aud: true` with no configured value, which rejects any
    // token carrying an `aud` claim outright rather than skipping the
    // check - and every spec-compliant OIDC ID token carries one. Found
    // against a real external IdP (self-hosted Dex, skilj-helpdesk):
    // signature and issuer verified correctly, then every real token
    // rejected with InvalidAudience regardless of its actual audience
    // value. The local JWKS/JWT test fixtures elsewhere in this
    // workspace never carry an `aud` claim, so they never exercised
    // this path.
    validation.validate_aud = false;

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

    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()).into())
}

/// 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 != 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 != 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 {
    pub role_id: String,
    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 {
    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(())
}

/// 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)?;
    if access_mapping.bounded_context != 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)?;
    if access_mapping.bounded_context != 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.
pub fn create_event_read_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<EventReadToken> {
    require_active_admin(access_mapping)?;
    if access_mapping.bounded_context != event_type.bounded_context {
        return Err(Error::GrantBoundedContextMismatch.into());
    }

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

/// 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)?;
    if access_mapping.bounded_context != 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 != token.scope() {
        return Err(Error::GrantBoundedContextMismatch.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
        }),
    })
}