boatramp-types 0.2.12

Shared, wasm-clean wire types + routing/config logic for boatramp (used by the server, CLI, and the edge Worker so the wire format and routing can't drift)
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
//! Control-plane **authorization** vocabulary and RBAC policy.
//!
//! This is the wasm-clean, pure core of authorization: the `action × resource`
//! right vocabulary, the request → required-[`Right`] mapping (the analogue of
//! the old `required_scope`), the RBAC [`AuthzPolicy`] (roles → right
//! templates) with its built-in default, and the pure [`RightSet::allows`]
//! decision. The COSE/Cedar engine (`boatramp_core::cose` + `::cedar`) reuses these types
//! and mirrors [`RightSet::allows`]; keeping the semantics
//! here means the server, CLI, and tests can't drift from the token format.
//!
//! No IO, no async, no authz-engine dependency — so it compiles to the edge target
//! and is exhaustively unit-testable.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

/// What a principal may *do* to a resource. [`Action::Admin`] is the superuser
/// action: holding it on a resource satisfies any other action there.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Action {
    /// Read/list (GET endpoints).
    Read,
    /// Mutate configuration (site config, aliases, domain verification, cache).
    Write,
    /// Ship content: create + activate deployments, upload blobs.
    Deploy,
    /// Full control of the resource (implies read/write/deploy).
    Admin,
}

/// A class of control-plane resource a [`Right`] governs. Two are **target-scoped**:
/// [`Resource::Site`] (target = `"<project>/<site>"`, the 0.2.0 project-qualified
/// form) and [`Resource::Project`] (target = `"<project>"`, governing the project's
/// **own** resources — functions, compute, workflows, and the project entity itself).
/// The rest are global.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Resource {
    /// A single site (`target` = `"<project>/<site>"`): deployments, config, aliases, …
    Site,
    /// A project (`target` = `"<project>"`): its functions, compute, workflows, and
    /// project-level config/CRUD. The owning + tenant boundary above a site.
    Project,
    /// Content-addressed blob uploads (`PUT /api/blobs/<hash>`).
    Blobs,
    /// API token management (`/api/tokens`).
    Tokens,
    /// TLS certificate status (`/api/certs`).
    Certs,
    /// Cache invalidation (`/api/cache/invalidate`).
    Cache,
    /// Node/system operations: metrics, prune, scrub, site listing.
    System,
}

impl Resource {
    /// Every resource variant — used to expand the `admin` role to "all rights".
    pub const ALL: [Self; 7] = [
        Self::Site,
        Self::Project,
        Self::Blobs,
        Self::Tokens,
        Self::Certs,
        Self::Cache,
        Self::System,
    ];

    /// The serde term for this resource (matches `rename_all`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Site => "site",
            Self::Project => "project",
            Self::Blobs => "blobs",
            Self::Tokens => "tokens",
            Self::Certs => "certs",
            Self::Cache => "cache",
            Self::System => "system",
        }
    }
}

impl Action {
    /// The serde term for this action (matches `rename_all`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Read => "read",
            Self::Write => "write",
            Self::Deploy => "deploy",
            Self::Admin => "admin",
        }
    }
}

impl std::fmt::Display for Resource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::fmt::Display for Action {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A single grant or requirement: an `action` on a `resource`, optionally scoped
/// to a `target` (a site name for [`Resource::Site`]). A `target` of `None` on a
/// *granted* right is a wildcard ("all targets"); a required right for a site
/// always carries `Some(site)`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Right {
    /// The resource class this right governs.
    pub resource: Resource,
    /// The site name for [`Resource::Site`]; `None` (wildcard/global) otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    /// The permitted action.
    pub action: Action,
}

impl Right {
    /// Construct a right.
    pub fn new(resource: Resource, target: Option<String>, action: Action) -> Self {
        Self {
            resource,
            target,
            action,
        }
    }

    /// The target term: the site name, or `*` for a wildcard/global right.
    pub fn target_term(&self) -> &str {
        self.target.as_deref().unwrap_or("*")
    }

    /// Whether holding `self` (a *granted* right) satisfies a `required` right:
    /// same resource, the granted action matches or is [`Action::Admin`], and the
    /// granted target is a wildcard (`None`/`*`) or equals the required target.
    pub fn satisfies(&self, required: &Self) -> bool {
        self.resource == required.resource
            && (self.action == required.action || self.action == Action::Admin)
            && target_matches(self.target.as_deref(), required.target.as_deref())
    }

    /// Map an HTTP `method` + request `path` to the single right it requires, or
    /// `None` for endpoints not gated by a right (the OIDC→token exchange).
    ///
    /// This is the authoritative request→right table. Unknown
    /// `/api/sites/<s>/…` subpaths fall through to the most restrictive
    /// `system · admin` so a narrow token can never reach an unmapped action.
    pub fn required(method: &str, path: &str) -> Option<Self> {
        let m = method.to_ascii_uppercase();
        let get = m == "GET";

        // Self-service endpoints gated only by holding *some* valid token, not a
        // right: the OIDC→token exchange (carries an IdP JWT) and `whoami`
        // (a principal reading its own identity). The handlers verify the token.
        if path == "/api/auth/exchange" || path == "/api/auth/whoami" {
            return None;
        }

        // Mesh join: the joiner presents a single-use *join
        // token* (verified by the handler), not an admin bearer — so this exact
        // path is unauthenticated at the RBAC layer. Note the `==`: the sibling
        // `/api/cluster/join-token` (minting) stays admin-scoped via the default.
        if path == "/api/cluster/join" {
            return None;
        }

        // First-token bootstrap: the caller presents a single-use, operator-set
        // *bootstrap secret* (verified by the handler), not an admin bearer — so
        // this exact path is unauthenticated at the RBAC layer. Note the `==`: the
        // sibling `/api/tokens` (minting) stays admin-scoped via the default below.
        if path == "/api/tokens/bootstrap" {
            return None;
        }

        // Content blobs are content-addressed (not site-specific); uploading is
        // a deploy-grade action.
        if path.starts_with("/api/blobs/") {
            return Some(Self::new(Resource::Blobs, None, Action::Deploy));
        }

        // Attaching a host **without** an ownership proof (`domain add
        // --unverified`) is an admin-only override: it asserts ownership of an
        // arbitrary hostname, so a site-scoped publisher must never reach it
        // (that would let them claim someone else's domain). Gate it at
        // `system·admin` explicitly, above the per-site branch that would
        // otherwise map it to the site-write right.
        if m == "POST" && path.contains("/domains/") && path.ends_with("/attach-unverified") {
            return Some(Self::new(Resource::System, None, Action::Admin));
        }

        // Project-scoped endpoints: `/api/projects/<proj>/<rest...>` (0.2.0). Parsed
        // through the shared `project_api_path` so this and the request-scoping
        // middleware agree on the tenant segment.
        if let Some((proj, sub)) = project_api_path(path) {
            if proj.is_empty() {
                // `/api/projects/` (trailing slash) or a malformed `//…` — listing.
                return Some(Self::new(Resource::System, None, Action::Read));
            }
            let sub: Vec<&str> = sub.split('/').filter(|s| !s.is_empty()).collect();
            return Some(match sub.split_first() {
                // The project entity itself: read, or manage (admin).
                None => Self::new(
                    Resource::Project,
                    Some(proj.to_string()),
                    if get { Action::Read } else { Action::Admin },
                ),
                // A site within the project: `.../sites/<site>/<site-sub...>`.
                Some((&"sites", tail)) => {
                    let site = tail.first().copied().unwrap_or("");
                    if site.is_empty() {
                        return Some(Self::new(
                            Resource::Project,
                            Some(proj.to_string()),
                            Action::Read,
                        ));
                    }
                    let site_sub: Vec<&str> = tail.iter().skip(1).copied().collect();
                    match site_subpath_action(&m, get, &site_sub) {
                        Some(a) => Self::new(Resource::Site, Some(format!("{proj}/{site}")), a),
                        // Unknown subpath — deny-safe.
                        None => Self::new(Resource::System, None, Action::Admin),
                    }
                }
                // Project-owned resources (functions/compute/workflows/config/…):
                // read with `Project·Read`, mutate with `Project·Deploy`.
                Some(_) => Self::new(
                    Resource::Project,
                    Some(proj.to_string()),
                    if get { Action::Read } else { Action::Deploy },
                ),
            });
        }

        // Legacy per-site endpoints: `/api/sites/<site>/<sub...>`. The site lives in
        // the `default` project post-migration, so the target is project-qualified.
        if let Some(rest) = path.strip_prefix("/api/sites/") {
            let mut segs = rest.split('/');
            let site = segs.next().unwrap_or("");
            if site.is_empty() {
                // `/api/sites/` (trailing slash) — listing.
                return Some(Self::new(Resource::System, None, Action::Read));
            }
            let target = Some(format!("{}/{site}", crate::project::DEFAULT_PROJECT));
            let sub: Vec<&str> = segs.filter(|s| !s.is_empty()).collect();
            let action = site_subpath_action(&m, get, &sub);
            return Some(match action {
                Some(a) => Self::new(Resource::Site, target, a),
                // Unknown subpath — deny-safe.
                None => Self::new(Resource::System, None, Action::Admin),
            });
        }

        // Exact, non-site endpoints.
        let default_project = crate::project::DEFAULT_PROJECT.to_string();
        let right = match path {
            "/api/sites" => Self::new(Resource::System, None, Action::Read),
            // Listing projects is a node-level read; creating one is a node-admin act
            // (only `/api/projects` exactly — a specific project is handled above).
            "/api/projects" => {
                let action = if get { Action::Read } else { Action::Admin };
                Self::new(Resource::System, None, action)
            }
            // Functions (FA-1/FA-2) are **project-owned** (0.2.0): read the view with
            // `project·read`, mutate (deploy a version, alias, rollback, delete) with
            // `project·deploy`, scoped to the default project for the legacy path.
            p if p == "/api/functions" || p.starts_with("/api/functions/") => {
                let action = if get { Action::Read } else { Action::Deploy };
                Self::new(Resource::Project, Some(default_project.clone()), action)
            }
            // Workflows (FA-6) are project-owned too; same shape as `/api/functions`.
            p if p == "/api/workflows" || p.starts_with("/api/workflows/") => {
                let action = if get { Action::Read } else { Action::Deploy };
                Self::new(Resource::Project, Some(default_project.clone()), action)
            }
            // Compute workloads (project-owned): read/deploy within the default project.
            p if p == "/api/compute" || p.starts_with("/api/compute/") => {
                let action = if get { Action::Read } else { Action::Deploy };
                Self::new(Resource::Project, Some(default_project.clone()), action)
            }
            // GraphQL administration — subgraph registration, the operation safelist,
            // and the composed supergraph — is project-owned (0.2.0), the same as
            // functions/compute/workflows: read the surface with `project·read`, mutate
            // it with `project·deploy`, scoped to the default project for this global
            // path (the project-scoped `/api/projects/<proj>/graphql/…` form is handled
            // above).
            p if p == "/api/graphql" || p.starts_with("/api/graphql/") => {
                let action = if get { Action::Read } else { Action::Deploy };
                Self::new(Resource::Project, Some(default_project.clone()), action)
            }
            "/api/blobs" => Self::new(Resource::Blobs, None, Action::Deploy),
            "/api/certs" => Self::new(Resource::Certs, None, Action::Read),
            "/api/cache/invalidate" => Self::new(Resource::Cache, None, Action::Write),
            "/api/metrics" => Self::new(Resource::System, None, Action::Read),
            "/api/prune" | "/api/scrub" => Self::new(Resource::System, None, Action::Admin),
            p if p == "/api/tokens" || p.starts_with("/api/tokens/") => {
                Self::new(Resource::Tokens, None, Action::Admin)
            }
            p if p == "/api/authz/policy" || p.starts_with("/api/authz/") => {
                Self::new(Resource::System, None, Action::Admin)
            }
            // Any other `/api/*` path: deny-safe (must hold system·admin).
            _ => Self::new(Resource::System, None, Action::Admin),
        };
        Some(right)
    }
}

/// The action a per-site subpath requires, or `None` if the subpath is unknown.
fn site_subpath_action(method: &str, get: bool, sub: &[&str]) -> Option<Action> {
    match sub.first().copied() {
        // `deployments`, `deployments/<id>`, `deployments/<id>/activate`.
        Some("deployments") => {
            let activate = sub.last() == Some(&"activate");
            if activate || method == "POST" {
                Some(Action::Deploy) // activate, or create a deployment
            } else if get {
                Some(Action::Read)
            } else {
                None
            }
        }
        Some("current") if get => Some(Action::Read),
        Some("config") => {
            if get {
                Some(Action::Read)
            } else if method == "PUT" {
                Some(Action::Write)
            } else {
                None
            }
        }
        // `domains/<host>/verification[/check]`, `domain-verifications`.
        Some("domains") => {
            let check = sub.last() == Some(&"check"); // a status check (POST, but read-grade)
            if get || check {
                Some(Action::Read)
            } else if method == "POST" || method == "DELETE" {
                Some(Action::Write)
            } else {
                None
            }
        }
        Some("domain-verifications") if get => Some(Action::Read),
        Some("aliases") => {
            if get {
                Some(Action::Read)
            } else if method == "PUT" || method == "DELETE" {
                Some(Action::Write)
            } else {
                None
            }
        }
        // `_boatramp/handlers`, `_boatramp/logs` (per-site observability, read);
        // `_boatramp/dlq` purge/redrive is a destructive site-scoped write.
        Some("_boatramp") => {
            if get {
                Some(Action::Read)
            } else if method == "POST" && sub.get(1) == Some(&"dlq") {
                Some(Action::Write)
            } else {
                None
            }
        }
        _ => None,
    }
}

/// The project segment of a `"<project>/<site>"` target (the part before the first
/// `/`), or the whole string when it carries no `/` (a bare project target).
pub fn project_of(target: &str) -> &str {
    target.split_once('/').map_or(target, |(p, _)| p)
}

/// Split an `/api/projects/<proj>/<sub…>` request path into its tenant project
/// segment and the remaining sub-path, or `None` when the path is not
/// project-scoped. `proj` is the first path segment after the prefix (possibly
/// empty for a malformed `//…` or a trailing-slash `/api/projects/`); `sub` is
/// everything after the first `/` (empty for the bare `/api/projects/<proj>` entity
/// path).
///
/// Both the request-scoping middleware (`project_scope::scope_of`) and
/// [`Right::required`] resolve the tenant through this one function, so the two can
/// never disagree on which project a request targets — a confused-deputy hazard if
/// they parsed it differently (each still applies its own policy to an empty
/// segment: the middleware carries the default tenant, `Right::required` treats it
/// as the listing/System right; both fail closed).
pub fn project_api_path(path: &str) -> Option<(&str, &str)> {
    let rest = path.strip_prefix("/api/projects/")?;
    Some(rest.split_once('/').unwrap_or((rest, "")))
}

/// Whether a granted target covers a required target:
/// - `None` — the global wildcard (an untargeted grant), covers everything;
/// - `"<project>/*"` — a project wildcard, covers any `"<project>/<site>"` (the
///   required target's project segment must equal `<project>`);
/// - anything else — an exact string match.
///
/// A grant target of the literal string `"*"` is **not** a global wildcard: the
/// wildcard is the *absence* of a target (`None`), so a `"*"` target matches only
/// a resource literally named `*`. This keeps the pure oracle faithful to the
/// Cedar authorizer, which likewise matches `"*"` as a literal set member — and a
/// resource named `*` cannot be created (`validate_resource_name` rejects it).
fn target_matches(granted: Option<&str>, required: Option<&str>) -> bool {
    match granted {
        None => true,
        Some(g) => match g.strip_suffix("/*") {
            Some(project) => required.is_some_and(|r| project_of(r) == project),
            None => required == Some(g),
        },
    }
}

/// A set of granted [`Right`]s with the pure authorization decision. This is the
/// pure-Rust reference decision: the differential oracle the Cedar authorizer is
/// tested against, and used by issuance code that needs to reason about a role's
/// effective rights.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RightSet {
    rights: Vec<Right>,
}

impl RightSet {
    /// An empty set (grants nothing).
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a right (de-duplicated).
    pub fn insert(&mut self, right: Right) {
        if !self.rights.contains(&right) {
            self.rights.push(right);
        }
    }

    /// Whether any held right satisfies `required`.
    pub fn allows(&self, required: &Right) -> bool {
        self.rights.iter().any(|g| g.satisfies(required))
    }

    /// Whether the set grants nothing.
    pub fn is_empty(&self) -> bool {
        self.rights.is_empty()
    }

    /// The held rights.
    pub fn rights(&self) -> &[Right] {
        &self.rights
    }
}

impl FromIterator<Right> for RightSet {
    fn from_iter<I: IntoIterator<Item = Right>>(iter: I) -> Self {
        let mut set = Self::new();
        for r in iter {
            set.insert(r);
        }
        set
    }
}

/// What a target-scoped role's grant target names.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetKind {
    /// A per-site role: target is `"<project>/<site>"`.
    Site,
    /// A per-project role: target is a bare `"<project>"`.
    Project,
}

/// A role granted to a principal: a role `name` from the [`AuthzPolicy`], plus an
/// optional `target` for target-scoped roles — a `"<project>/<site>"` for a site
/// role, or a bare `"<project>"` for a project role.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GrantedRole {
    /// The role name (a key in [`AuthzPolicy::roles`]).
    pub name: String,
    /// The site this instance is scoped to, for target-scoped roles.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
}

impl GrantedRole {
    /// A global role (no target).
    pub fn global(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            target: None,
        }
    }

    /// A target-scoped role (e.g. `publisher` on a site).
    pub fn scoped(name: impl Into<String>, target: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            target: Some(target.into()),
        }
    }

    /// Parse a role spec: `"<role>"` (global) or `"<role>:<target>"`
    /// (target-scoped). Used by the CLI `--role`, the API token-create body, and
    /// the OIDC claim→roles mapping, so they agree on the format.
    pub fn parse(spec: &str) -> Self {
        match spec.split_once(':') {
            Some((name, target)) if !target.trim().is_empty() => {
                Self::scoped(name.trim(), target.trim())
            }
            _ => Self::global(spec.trim()),
        }
    }
}

/// How a [`RightTemplate`] derives its target when expanding a role.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetScope {
    /// Wildcard/global: the expanded right has `target = None`.
    AnyTarget,
    /// Bind to the granted role instance's target verbatim (a site role's
    /// `"<project>/<site>"`, or a project role's `"<project>"`).
    RoleTarget,
    /// A **project role** granting a per-site right over *every* site in its project:
    /// the granted target is a bare project name `"<project>"` and the expanded right
    /// gets the project-wildcard target `"<project>/*"`, which
    /// [`target_matches`](Right::satisfies) treats as covering any `"<project>/<site>"`.
    ProjectWildcard,
}

impl TargetScope {
    /// Whether this scope binds a target (so its role is target-scoped).
    pub fn is_targeted(self) -> bool {
        matches!(self, Self::RoleTarget | Self::ProjectWildcard)
    }
}

/// One right a role grants, before binding to a concrete target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RightTemplate {
    /// The resource the right governs.
    pub resource: Resource,
    /// The action granted.
    pub action: Action,
    /// How the target is derived when the role is expanded.
    pub scope: TargetScope,
}

impl RightTemplate {
    /// A global right template (`AnyTarget`).
    pub fn any(resource: Resource, action: Action) -> Self {
        Self {
            resource,
            action,
            scope: TargetScope::AnyTarget,
        }
    }

    /// A target-scoped right template (`RoleTarget`).
    pub fn scoped(resource: Resource, action: Action) -> Self {
        Self {
            resource,
            action,
            scope: TargetScope::RoleTarget,
        }
    }

    /// A project-wildcard right template (`ProjectWildcard`): a per-site right a
    /// project role confers over every site in the project.
    pub fn project_wildcard(resource: Resource, action: Action) -> Self {
        Self {
            resource,
            action,
            scope: TargetScope::ProjectWildcard,
        }
    }
}

/// The RBAC policy: roles → the rights they grant. Stored at KV `authz/policy`
/// (schema v1); when absent the server uses [`AuthzPolicy::default_policy`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AuthzPolicy {
    /// Pinned schema discriminant (`v1`).
    #[serde(default = "crate::schema_version")]
    pub version: u32,
    /// Role name → the right templates it grants.
    pub roles: BTreeMap<String, Vec<RightTemplate>>,
}

impl Default for AuthzPolicy {
    fn default() -> Self {
        Self::default_policy()
    }
}

impl AuthzPolicy {
    /// The built-in default policy: `admin`, `publisher`,
    /// `deployer`, `viewer`, `operator`.
    pub fn default_policy() -> Self {
        let mut roles: BTreeMap<String, Vec<RightTemplate>> = BTreeMap::new();

        // admin — every (resource, action). Expanded as one Admin right per
        // resource with a wildcard target.
        roles.insert(
            "admin".to_string(),
            Resource::ALL
                .iter()
                .map(|&r| RightTemplate::any(r, Action::Admin))
                .collect(),
        );

        // publisher (site) — full control of its site + blob uploads.
        roles.insert(
            "publisher".to_string(),
            vec![
                RightTemplate::scoped(Resource::Site, Action::Read),
                RightTemplate::scoped(Resource::Site, Action::Write),
                RightTemplate::scoped(Resource::Site, Action::Deploy),
                RightTemplate::any(Resource::Blobs, Action::Deploy),
            ],
        );

        // deployer (site) — ship + read, but not edit config.
        roles.insert(
            "deployer".to_string(),
            vec![
                RightTemplate::scoped(Resource::Site, Action::Read),
                RightTemplate::scoped(Resource::Site, Action::Deploy),
                RightTemplate::any(Resource::Blobs, Action::Deploy),
            ],
        );

        // viewer (site) — read-only on its site.
        roles.insert(
            "viewer".to_string(),
            vec![RightTemplate::scoped(Resource::Site, Action::Read)],
        );

        // operator — node-level read + cache control, no site access.
        roles.insert(
            "operator".to_string(),
            vec![
                RightTemplate::any(Resource::System, Action::Read),
                RightTemplate::any(Resource::Certs, Action::Read),
                RightTemplate::any(Resource::Cache, Action::Write),
            ],
        );

        // project-admin (project) — full control of the project: its own resources
        // (functions/compute/workflows/config, via `Project·Admin`) AND every site in
        // it (`Site·Admin` over the project wildcard) + blob uploads.
        roles.insert(
            "project_admin".to_string(),
            vec![
                RightTemplate::scoped(Resource::Project, Action::Admin),
                RightTemplate::project_wildcard(Resource::Site, Action::Admin),
                RightTemplate::any(Resource::Blobs, Action::Deploy),
            ],
        );

        // project-publisher (project) — ship + configure any site in the project and
        // manage its functions/compute (write + deploy + read), but not admin the
        // project entity (no membership/role changes).
        roles.insert(
            "project_publisher".to_string(),
            vec![
                RightTemplate::scoped(Resource::Project, Action::Read),
                RightTemplate::scoped(Resource::Project, Action::Write),
                RightTemplate::scoped(Resource::Project, Action::Deploy),
                RightTemplate::project_wildcard(Resource::Site, Action::Read),
                RightTemplate::project_wildcard(Resource::Site, Action::Write),
                RightTemplate::project_wildcard(Resource::Site, Action::Deploy),
                RightTemplate::any(Resource::Blobs, Action::Deploy),
            ],
        );

        // project-viewer (project) — read-only across the whole project.
        roles.insert(
            "project_viewer".to_string(),
            vec![
                RightTemplate::scoped(Resource::Project, Action::Read),
                RightTemplate::project_wildcard(Resource::Site, Action::Read),
            ],
        );

        Self {
            version: crate::SCHEMA_VERSION,
            roles,
        }
    }

    /// Whether `role` is target-scoped (any of its templates binds the target).
    pub fn role_takes_target(&self, role: &str) -> bool {
        self.roles
            .get(role)
            .is_some_and(|ts| ts.iter().any(|t| t.scope.is_targeted()))
    }

    /// What kind of target a role's grant carries: a per-site `"<project>/<site>"`
    /// ([`TargetKind::Site`], a role with a Site `RoleTarget` template) or a bare
    /// `"<project>"` ([`TargetKind::Project`], a role with a `ProjectWildcard` or a
    /// non-Site `RoleTarget` template). `None` for a global role. Used to normalize a
    /// legacy site-only grant to the `default` project ([`normalize_grants`]).
    ///
    /// [`normalize_grants`]: Self::normalize_grants
    pub fn role_target_kind(&self, role: &str) -> Option<TargetKind> {
        let templates = self.roles.get(role)?;
        let mut site = false;
        let mut project = false;
        for t in templates {
            match t.scope {
                TargetScope::RoleTarget if t.resource == Resource::Site => site = true,
                TargetScope::RoleTarget => project = true,
                TargetScope::ProjectWildcard => project = true,
                TargetScope::AnyTarget => {}
            }
        }
        // A Site `RoleTarget` role is per-site; a project role (ProjectWildcard, or a
        // `RoleTarget` on the Project resource) is per-project.
        if site {
            Some(TargetKind::Site)
        } else if project {
            Some(TargetKind::Project)
        } else {
            None
        }
    }

    /// Normalize legacy grants for 0.2.0: a **site** role granted a bare target with
    /// no project segment (a pre-project token, e.g. `publisher:blog`) is read as the
    /// `default` project (`publisher:default/blog`). Project and global roles, and any
    /// already-qualified `"<project>/<site>"` target, pass through unchanged. Run once
    /// at token→roles ingestion, before either [`rights_for`](Self::rights_for) or the
    /// Cedar authorizer, so both decide on the same normalized grants.
    pub fn normalize_grants(&self, roles: &[GrantedRole]) -> Vec<GrantedRole> {
        roles
            .iter()
            .map(|g| match (&g.target, self.role_target_kind(&g.name)) {
                (Some(t), Some(TargetKind::Site)) if !t.contains('/') => {
                    GrantedRole::scoped(&g.name, format!("{}/{t}", crate::project::DEFAULT_PROJECT))
                }
                _ => g.clone(),
            })
            .collect()
    }

    /// Expand a principal's granted roles into the concrete [`RightSet`] they
    /// confer under this policy. A target-scoped template on a role granted
    /// without a target contributes nothing (defensive). This is the pure RBAC
    /// expansion the Cedar authorizer reproduces as a policy set. Callers pass
    /// grants already normalized by [`normalize_grants`](Self::normalize_grants).
    pub fn rights_for(&self, roles: &[GrantedRole]) -> RightSet {
        let mut set = RightSet::new();
        for granted in roles {
            let Some(templates) = self.roles.get(&granted.name) else {
                continue;
            };
            for t in templates {
                let target = match t.scope {
                    TargetScope::AnyTarget => None,
                    TargetScope::RoleTarget => match &granted.target {
                        Some(x) => Some(x.clone()),
                        None => continue,
                    },
                    // A project role's per-site right covers every site in its
                    // project: expand the bare project target to `"<project>/*"`.
                    TargetScope::ProjectWildcard => match &granted.target {
                        Some(x) => Some(format!("{x}/*")),
                        None => continue,
                    },
                };
                set.insert(Right::new(t.resource, target, t.action));
            }
        }
        set
    }
}

/// KV key for the RBAC policy document (`authz/policy`); absent ⇒ the built-in
/// [`AuthzPolicy::default_policy`].
pub const POLICY_KEY: &str = "authz/policy";

/// KV key prefix for revocation markers — presence of `authz/revoked/<id>`
/// means the token with authority revocation id `<id>` (and its attenuations)
/// is revoked.
pub const REVOKED_PREFIX: &str = "authz/revoked/";

/// KV key prefix for issued-token metadata (`authz/tokens/<id>`). The token
/// itself is never stored — only this metadata, for `token ls`.
pub const TOKEN_META_PREFIX: &str = "authz/tokens/";

/// The revocation-marker key for an authority revocation id.
pub fn revoked_key(revocation_id: &str) -> String {
    format!("{REVOKED_PREFIX}{revocation_id}")
}

/// KV key prefix for extra trusted **root anchors** added by `auth rotate-root`
/// (`auth/root/{alg:hex}`). Each is a `TokenPublicKey` trusted alongside the
/// configured primary root during a make-before-break root rotation.
pub const ROOT_ANCHOR_PREFIX: &str = "auth/root/";

/// The root-anchor key trusting `pubkey` (an `alg:hex`-encoded `TokenPublicKey`).
pub fn root_anchor_key(pubkey: &str) -> String {
    format!("{ROOT_ANCHOR_PREFIX}{pubkey}")
}

/// The metadata key for an issued token (keyed by its authority revocation id).
pub fn token_meta_key(id: &str) -> String {
    format!("{TOKEN_META_PREFIX}{id}")
}

/// The single-use marker key for a redeemed first-token bootstrap secret
/// (keyed by the secret's SHA-256 hex).
pub fn bootstrap_key(secret_hash: &str) -> String {
    format!("authz/bootstrap/{secret_hash}")
}

/// Metadata for an issued token (`authz/tokens/<id>`). The token itself is
/// shown once at creation and never stored; this is what `token ls` reports and
/// what `token rm` needs to find the revocation id. Schema v1.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenMeta {
    /// Pinned schema discriminant (`v1`).
    #[serde(default = "crate::schema_version")]
    pub version: u32,
    /// Human label for the token.
    pub label: String,
    /// The roles the token grants.
    pub roles: Vec<GrantedRole>,
    /// Unix timestamp (seconds) of creation.
    pub created_at: u64,
    /// Unix timestamp (seconds) of expiry, if the token carries a TTL.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<u64>,
    /// The authority revocation id (hex) — also the `authz/tokens/<id>` key and
    /// the argument to `token rm`.
    pub revocation_id: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn admin_satisfies_every_action_on_its_resource() {
        let admin_site = Right::new(Resource::Site, None, Action::Admin);
        for action in [Action::Read, Action::Write, Action::Deploy, Action::Admin] {
            let required = Right::new(Resource::Site, Some("blog".into()), action);
            assert!(
                admin_site.satisfies(&required),
                "admin must satisfy {action:?}"
            );
        }
        // …but not a different resource.
        assert!(!admin_site.satisfies(&Right::new(Resource::Tokens, None, Action::Read)));
    }

    #[test]
    fn target_scoping_is_exact_unless_wildcard() {
        let blog = Right::new(Resource::Site, Some("blog".into()), Action::Write);
        assert!(blog.satisfies(&Right::new(
            Resource::Site,
            Some("blog".into()),
            Action::Write
        )));
        assert!(!blog.satisfies(&Right::new(
            Resource::Site,
            Some("api".into()),
            Action::Write
        )));
        // A wildcard grant covers any site.
        let any = Right::new(Resource::Site, None, Action::Write);
        assert!(any.satisfies(&Right::new(
            Resource::Site,
            Some("api".into()),
            Action::Write
        )));
    }

    #[test]
    fn distinct_actions_do_not_imply_each_other() {
        let write = Right::new(Resource::Site, Some("blog".into()), Action::Write);
        let deploy_req = Right::new(Resource::Site, Some("blog".into()), Action::Deploy);
        assert!(
            !write.satisfies(&deploy_req),
            "write must not imply deploy (only admin does)"
        );
    }

    /// Every row of the request→right table.
    #[test]
    fn required_right_table() {
        let cases: &[(&str, &str, Option<Right>)] = &[
            ("POST", "/api/auth/exchange", None),
            ("GET", "/api/auth/whoami", None),
            // Minting a mesh join token is admin-scoped (deny-safe default for
            // `/api/cluster/*`) — an operator issues it.
            (
                "POST",
                "/api/cluster/join-token",
                Some(Right::new(Resource::System, None, Action::Admin)),
            ),
            // Presenting a join token to join is gated by the token itself, not
            // an admin bearer (the handler verifies it) — exact-path `None`.
            ("POST", "/api/cluster/join", None),
            // Rotating this node's mesh key is an operator action → admin-scoped.
            (
                "POST",
                "/api/cluster/rotate-key",
                Some(Right::new(Resource::System, None, Action::Admin)),
            ),
            // Revoking a node from the mesh is an operator action → admin-scoped.
            (
                "POST",
                "/api/cluster/revoke",
                Some(Right::new(Resource::System, None, Action::Admin)),
            ),
            (
                "PUT",
                "/api/blobs/abc123",
                Some(Right::new(Resource::Blobs, None, Action::Deploy)),
            ),
            (
                "GET",
                "/api/sites",
                Some(Right::new(Resource::System, None, Action::Read)),
            ),
            (
                "POST",
                "/api/sites/blog/deployments",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Deploy,
                )),
            ),
            (
                "GET",
                "/api/sites/blog/deployments",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Read,
                )),
            ),
            (
                "GET",
                "/api/sites/blog/deployments/d1",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Read,
                )),
            ),
            (
                "POST",
                "/api/sites/blog/deployments/d1/activate",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Deploy,
                )),
            ),
            (
                "GET",
                "/api/sites/blog/current",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Read,
                )),
            ),
            (
                "GET",
                "/api/sites/blog/config",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Read,
                )),
            ),
            (
                "PUT",
                "/api/sites/blog/config",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Write,
                )),
            ),
            (
                "GET",
                "/api/sites/blog/domains/x.example.com/verification",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Read,
                )),
            ),
            (
                "POST",
                "/api/sites/blog/domains/x.example.com/verification",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Write,
                )),
            ),
            (
                "DELETE",
                "/api/sites/blog/domains/x.example.com/verification",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Write,
                )),
            ),
            (
                "POST",
                "/api/sites/blog/domains/x.example.com/verification/check",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Read,
                )),
            ),
            (
                "GET",
                "/api/sites/blog/domain-verifications",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Read,
                )),
            ),
            (
                "PUT",
                "/api/sites/blog/aliases/www",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Write,
                )),
            ),
            (
                "GET",
                "/api/sites/blog/aliases",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Read,
                )),
            ),
            (
                "GET",
                "/api/sites/blog/_boatramp/handlers",
                Some(Right::new(
                    Resource::Site,
                    Some("default/blog".into()),
                    Action::Read,
                )),
            ),
            (
                "POST",
                "/api/tokens",
                Some(Right::new(Resource::Tokens, None, Action::Admin)),
            ),
            (
                "DELETE",
                "/api/tokens/t1",
                Some(Right::new(Resource::Tokens, None, Action::Admin)),
            ),
            (
                "GET",
                "/api/prune",
                Some(Right::new(Resource::System, None, Action::Admin)),
            ),
            (
                "POST",
                "/api/scrub",
                Some(Right::new(Resource::System, None, Action::Admin)),
            ),
            (
                "GET",
                "/api/certs",
                Some(Right::new(Resource::Certs, None, Action::Read)),
            ),
            (
                "POST",
                "/api/cache/invalidate",
                Some(Right::new(Resource::Cache, None, Action::Write)),
            ),
            (
                "GET",
                "/api/metrics",
                Some(Right::new(Resource::System, None, Action::Read)),
            ),
            // GraphQL administration is project-owned (default project for the global
            // path): read the surface with `project·read`, mutate it with
            // `project·deploy` — the same shape as functions/compute/workflows.
            (
                "GET",
                "/api/graphql/supergraph",
                Some(Right::new(
                    Resource::Project,
                    Some("default".into()),
                    Action::Read,
                )),
            ),
            (
                "PUT",
                "/api/graphql/subgraphs/catalog",
                Some(Right::new(
                    Resource::Project,
                    Some("default".into()),
                    Action::Deploy,
                )),
            ),
            (
                "POST",
                "/api/graphql/safelist",
                Some(Right::new(
                    Resource::Project,
                    Some("default".into()),
                    Action::Deploy,
                )),
            ),
        ];
        for (method, path, expected) in cases {
            assert_eq!(
                &Right::required(method, path),
                expected,
                "required({method}, {path})"
            );
        }
    }

    #[test]
    fn unknown_site_subpath_is_deny_safe() {
        // An unmapped subpath must require system·admin, not the site's action.
        assert_eq!(
            Right::required("PATCH", "/api/sites/blog/frobnicate"),
            Some(Right::new(Resource::System, None, Action::Admin))
        );
    }

    #[test]
    fn attach_unverified_is_admin_only() {
        // Attaching a host without a proof (`domain add --unverified`) must need
        // system·admin — a site-write right must NOT satisfy it, so a scoped
        // publisher can't claim an arbitrary host.
        let required = Right::required(
            "POST",
            "/api/sites/blog/domains/evil.example.com/attach-unverified",
        )
        .expect("route is gated");
        assert_eq!(required, Right::new(Resource::System, None, Action::Admin));
        // A publisher's site-write right does not satisfy the admin gate.
        let site_write = Right::new(Resource::Site, Some("blog".into()), Action::Write);
        assert!(!site_write.satisfies(&required));
        // A system-admin right does.
        assert!(Right::new(Resource::System, None, Action::Admin).satisfies(&required));
    }

    #[test]
    fn default_policy_publisher_can_deploy_and_write_its_site_only() {
        let policy = AuthzPolicy::default_policy();
        let rights = policy.rights_for(&[GrantedRole::scoped("publisher", "blog")]);
        // Can read/write/deploy blog + upload blobs…
        assert!(rights.allows(&Right::new(
            Resource::Site,
            Some("blog".into()),
            Action::Deploy
        )));
        assert!(rights.allows(&Right::new(
            Resource::Site,
            Some("blog".into()),
            Action::Write
        )));
        assert!(rights.allows(&Right::new(Resource::Blobs, None, Action::Deploy)));
        // …but not another site, nor token management.
        assert!(!rights.allows(&Right::new(
            Resource::Site,
            Some("api".into()),
            Action::Read
        )));
        assert!(!rights.allows(&Right::new(Resource::Tokens, None, Action::Admin)));
    }

    #[test]
    fn default_policy_deployer_cannot_edit_config() {
        let policy = AuthzPolicy::default_policy();
        let rights = policy.rights_for(&[GrantedRole::scoped("deployer", "blog")]);
        assert!(rights.allows(&Right::new(
            Resource::Site,
            Some("blog".into()),
            Action::Deploy
        )));
        assert!(rights.allows(&Right::new(
            Resource::Site,
            Some("blog".into()),
            Action::Read
        )));
        assert!(
            !rights.allows(&Right::new(
                Resource::Site,
                Some("blog".into()),
                Action::Write
            )),
            "deployer must not edit config"
        );
    }

    #[test]
    fn default_policy_admin_can_do_anything() {
        let policy = AuthzPolicy::default_policy();
        let rights = policy.rights_for(&[GrantedRole::global("admin")]);
        for resource in Resource::ALL {
            for action in [Action::Read, Action::Write, Action::Deploy, Action::Admin] {
                let target = matches!(resource, Resource::Site).then(|| "any".to_string());
                assert!(
                    rights.allows(&Right::new(resource, target, action)),
                    "admin must allow {resource:?}·{action:?}"
                );
            }
        }
    }

    #[test]
    fn site_role_without_target_grants_nothing_site_scoped() {
        let policy = AuthzPolicy::default_policy();
        // `publisher` granted globally (no target) — the site templates are
        // RoleTarget, so they contribute nothing; only the AnyTarget blobs right.
        let rights = policy.rights_for(&[GrantedRole::global("publisher")]);
        assert!(rights.allows(&Right::new(Resource::Blobs, None, Action::Deploy)));
        assert!(!rights.allows(&Right::new(
            Resource::Site,
            Some("blog".into()),
            Action::Read
        )));
    }

    #[test]
    fn role_takes_target_classifies_roles() {
        let policy = AuthzPolicy::default_policy();
        assert!(policy.role_takes_target("publisher"));
        assert!(policy.role_takes_target("viewer"));
        assert!(!policy.role_takes_target("admin"));
        assert!(!policy.role_takes_target("operator"));
    }

    #[test]
    fn policy_round_trips_through_json() {
        let policy = AuthzPolicy::default_policy();
        let json = serde_json::to_string(&policy).unwrap();
        let back: AuthzPolicy = serde_json::from_str(&json).unwrap();
        assert_eq!(policy, back);
        assert_eq!(back.version, crate::SCHEMA_VERSION);
    }

    #[test]
    fn unknown_role_is_ignored() {
        let policy = AuthzPolicy::default_policy();
        let rights = policy.rights_for(&[GrantedRole::global("nonesuch")]);
        assert!(rights.is_empty());
    }

    // ---- 0.2.0 project scoping ---------------------------------------------

    #[test]
    fn legacy_site_grant_normalizes_to_default_project() {
        let policy = AuthzPolicy::default_policy();
        // A pre-project token `publisher:blog` reads as the default project.
        let n = policy.normalize_grants(&[GrantedRole::scoped("publisher", "blog")]);
        assert_eq!(n, vec![GrantedRole::scoped("publisher", "default/blog")]);
        // An already-qualified site grant, a project grant, and a global grant pass
        // through untouched (a project name must NOT gain a `default/` prefix).
        let untouched = [
            GrantedRole::scoped("publisher", "acme/blog"),
            GrantedRole::scoped("project_admin", "acme"),
            GrantedRole::global("admin"),
        ];
        assert_eq!(policy.normalize_grants(&untouched), untouched);
    }

    #[test]
    fn project_admin_covers_its_project_but_not_another() {
        let policy = AuthzPolicy::default_policy();
        let rights = policy.rights_for(&[GrantedRole::scoped("project_admin", "acme")]);
        // Every site in acme, at every action.
        for action in [Action::Read, Action::Write, Action::Deploy, Action::Admin] {
            assert!(
                rights.allows(&Right::new(
                    Resource::Site,
                    Some("acme/blog".into()),
                    action
                )),
                "project-admin:acme covers acme/blog·{action:?}"
            );
        }
        // The project's own resources (functions/compute via Project).
        assert!(rights.allows(&Right::new(
            Resource::Project,
            Some("acme".into()),
            Action::Deploy
        )));
        assert!(rights.allows(&Right::new(
            Resource::Project,
            Some("acme".into()),
            Action::Admin
        )));
        // But NOT another project's sites or project resource — the tenant boundary.
        assert!(!rights.allows(&Right::new(
            Resource::Site,
            Some("shop/blog".into()),
            Action::Read
        )));
        assert!(!rights.allows(&Right::new(
            Resource::Project,
            Some("shop".into()),
            Action::Read
        )));
        // A bare/global site target is not covered by a project-scoped grant.
        assert!(!rights.allows(&Right::new(
            Resource::Site,
            Some("blog".into()),
            Action::Read
        )));
    }

    #[test]
    fn project_viewer_is_read_only_across_the_project() {
        let policy = AuthzPolicy::default_policy();
        let rights = policy.rights_for(&[GrantedRole::scoped("project_viewer", "acme")]);
        assert!(rights.allows(&Right::new(
            Resource::Site,
            Some("acme/blog".into()),
            Action::Read
        )));
        assert!(rights.allows(&Right::new(
            Resource::Project,
            Some("acme".into()),
            Action::Read
        )));
        // No writes/deploys anywhere.
        assert!(!rights.allows(&Right::new(
            Resource::Site,
            Some("acme/blog".into()),
            Action::Write
        )));
        assert!(!rights.allows(&Right::new(
            Resource::Project,
            Some("acme".into()),
            Action::Deploy
        )));
    }

    #[test]
    fn project_publisher_ships_but_cannot_admin_the_project() {
        let policy = AuthzPolicy::default_policy();
        let rights = policy.rights_for(&[GrantedRole::scoped("project_publisher", "acme")]);
        assert!(rights.allows(&Right::new(
            Resource::Site,
            Some("acme/blog".into()),
            Action::Deploy
        )));
        assert!(rights.allows(&Right::new(
            Resource::Project,
            Some("acme".into()),
            Action::Deploy
        )));
        assert!(rights.allows(&Right::new(Resource::Blobs, None, Action::Deploy)));
        // Admin of the project entity (membership/roles) is reserved for project-admin.
        assert!(!rights.allows(&Right::new(
            Resource::Project,
            Some("acme".into()),
            Action::Admin
        )));
    }

    #[test]
    fn required_maps_project_paths() {
        // A site within a project.
        assert_eq!(
            Right::required("POST", "/api/projects/acme/sites/blog/deployments"),
            Some(Right::new(
                Resource::Site,
                Some("acme/blog".into()),
                Action::Deploy
            ))
        );
        // A project-owned resource (a function): read vs mutate.
        assert_eq!(
            Right::required("GET", "/api/projects/acme/functions/resize"),
            Some(Right::new(
                Resource::Project,
                Some("acme".into()),
                Action::Read
            ))
        );
        assert_eq!(
            Right::required("POST", "/api/projects/acme/functions/resize/versions"),
            Some(Right::new(
                Resource::Project,
                Some("acme".into()),
                Action::Deploy
            ))
        );
        // The project entity itself.
        assert_eq!(
            Right::required("DELETE", "/api/projects/acme"),
            Some(Right::new(
                Resource::Project,
                Some("acme".into()),
                Action::Admin
            ))
        );
        // Listing/creating projects is node-level.
        assert_eq!(
            Right::required("GET", "/api/projects"),
            Some(Right::new(Resource::System, None, Action::Read))
        );
        assert_eq!(
            Right::required("POST", "/api/projects"),
            Some(Right::new(Resource::System, None, Action::Admin))
        );
        // Legacy top-level functions map to the default project now.
        assert_eq!(
            Right::required("GET", "/api/functions"),
            Some(Right::new(
                Resource::Project,
                Some("default".into()),
                Action::Read
            ))
        );
    }
}