cf-gears-toolkit-security 0.11.0

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

/// A scalar value for scope filtering.
///
/// Used in [`ScopeFilter`] predicates to represent typed values.
/// JSON conversion happens at the PDP/PEP boundary (see the PEP compiler),
/// not inside the security model.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum ScopeValue {
    /// UUID value (tenant IDs, resource IDs, etc.)
    Uuid(Uuid),
    /// String value (status, GTS type IDs, etc.)
    String(String),
    /// Integer value.
    Int(i64),
    /// Boolean value.
    Bool(bool),
}

impl ScopeValue {
    /// Try to extract a UUID from this value.
    ///
    /// Returns `Some` for `ScopeValue::Uuid` directly, and for
    /// `ScopeValue::String` if the string is a valid UUID.
    #[must_use]
    pub fn as_uuid(&self) -> Option<Uuid> {
        match self {
            Self::Uuid(u) => Some(*u),
            Self::String(s) => Uuid::parse_str(s).ok(),
            Self::Int(_) | Self::Bool(_) => None,
        }
    }
}

impl fmt::Display for ScopeValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Uuid(u) => write!(f, "{u}"),
            Self::String(s) => write!(f, "{s}"),
            Self::Int(n) => write!(f, "{n}"),
            Self::Bool(b) => write!(f, "{b}"),
        }
    }
}

impl From<Uuid> for ScopeValue {
    #[inline]
    fn from(u: Uuid) -> Self {
        Self::Uuid(u)
    }
}

impl From<&Uuid> for ScopeValue {
    #[inline]
    fn from(u: &Uuid) -> Self {
        Self::Uuid(*u)
    }
}

impl From<String> for ScopeValue {
    #[inline]
    fn from(s: String) -> Self {
        Self::String(s)
    }
}

impl From<&str> for ScopeValue {
    #[inline]
    fn from(s: &str) -> Self {
        Self::String(s.to_owned())
    }
}

impl From<i64> for ScopeValue {
    #[inline]
    fn from(n: i64) -> Self {
        Self::Int(n)
    }
}

impl From<bool> for ScopeValue {
    #[inline]
    fn from(b: bool) -> Self {
        Self::Bool(b)
    }
}

/// Well-known authorization property names.
///
/// These constants are shared between the PEP compiler and the ORM condition
/// builder (`ScopableEntity::resolve_property()`), ensuring a single source of
/// truth for property names.
pub mod pep_properties {
    /// Tenant-ownership property. Typically maps to the `tenant_id` column.
    pub const OWNER_TENANT_ID: &str = "owner_tenant_id";

    /// Resource identity property. Typically maps to the primary key column.
    pub const RESOURCE_ID: &str = "id";

    /// Owner (user) identity property. Typically maps to an `owner_id` column.
    pub const OWNER_ID: &str = "owner_id";
}

/// A single scope filter — a typed predicate on a named resource property.
///
/// The property name (e.g., `"owner_tenant_id"`, `"id"`) is an authorization
/// concept. Mapping to DB columns is done by `ScopableEntity::resolve_property()`.
///
/// Variants mirror the predicate types from the PDP response:
/// - [`ScopeFilter::Eq`] — equality (`property = value`)
/// - [`ScopeFilter::In`] — set membership (`property IN (values)`)
/// - [`ScopeFilter::InGroup`] — group membership subquery
/// - [`ScopeFilter::InGroupSubtree`] — group subtree subquery
/// - [`ScopeFilter::InTenantSubtree`] — tenant subtree subquery on `tenant_closure`
///
/// `#[non_exhaustive]`: this mirrors the PDP's predicate set, which has already
/// grown to five variants and will grow again. Without it, every new predicate
/// is a breaking change for every downstream `match`. With it, a consumer must
/// write a wildcard arm — and **that arm must fail closed**: a filter this build
/// does not understand is a restriction it cannot apply, so treating it as
/// "nothing to do" silently drops a narrowing term and widens the grant.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScopeFilter {
    /// Equality: `property = value`.
    Eq(EqScopeFilter),
    /// Set membership: `property IN (values)`.
    In(InScopeFilter),
    /// Group membership: `property IN (SELECT resource_id FROM membership WHERE group_id IN (group_ids))`.
    InGroup(InGroupScopeFilter),
    /// Group subtree: `property IN (SELECT resource_id FROM membership WHERE group_id IN (SELECT descendant_id FROM closure WHERE ancestor_id IN (ancestor_ids)))`.
    InGroupSubtree(InGroupSubtreeScopeFilter),
    /// Tenant subtree: `property IN (SELECT descendant_id FROM tenant_closure WHERE ancestor_id = root_tenant_id)`.
    InTenantSubtree(InTenantSubtreeScopeFilter),
}

/// Equality scope filter: `property = value`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct EqScopeFilter {
    /// Authorization property name (e.g., `pep_properties::OWNER_TENANT_ID`).
    property: String,
    /// The value to match.
    value: ScopeValue,
}

/// Set membership scope filter: `property IN (values)`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InScopeFilter {
    /// Authorization property name (e.g., `pep_properties::OWNER_TENANT_ID`).
    property: String,
    /// The set of values to match against.
    values: Vec<ScopeValue>,
}

impl EqScopeFilter {
    /// Create an equality scope filter.
    #[must_use]
    pub fn new(property: impl Into<String>, value: impl Into<ScopeValue>) -> Self {
        Self {
            property: property.into(),
            value: value.into(),
        }
    }

    /// The authorization property name.
    #[inline]
    #[must_use]
    pub fn property(&self) -> &str {
        &self.property
    }

    /// The filter value.
    #[inline]
    #[must_use]
    pub fn value(&self) -> &ScopeValue {
        &self.value
    }
}

impl InScopeFilter {
    /// Create a set membership scope filter.
    #[must_use]
    pub fn new(property: impl Into<String>, values: Vec<ScopeValue>) -> Self {
        Self {
            property: property.into(),
            values,
        }
    }

    /// Create from an iterator of convertible values.
    #[must_use]
    pub fn from_values<V: Into<ScopeValue>>(
        property: impl Into<String>,
        values: impl IntoIterator<Item = V>,
    ) -> Self {
        Self {
            property: property.into(),
            values: values.into_iter().map(Into::into).collect(),
        }
    }

    /// The authorization property name.
    #[inline]
    #[must_use]
    pub fn property(&self) -> &str {
        &self.property
    }

    /// The filter values.
    #[inline]
    #[must_use]
    pub fn values(&self) -> &[ScopeValue] {
        &self.values
    }
}

/// Group membership scope filter.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InGroupScopeFilter {
    property: String,
    group_ids: Vec<ScopeValue>,
}

impl InGroupScopeFilter {
    /// Create a group membership scope filter.
    #[must_use]
    pub fn new(property: impl Into<String>, group_ids: Vec<ScopeValue>) -> Self {
        Self {
            property: property.into(),
            group_ids,
        }
    }

    /// The authorization property name.
    #[inline]
    #[must_use]
    pub fn property(&self) -> &str {
        &self.property
    }

    /// The group IDs.
    #[inline]
    #[must_use]
    pub fn group_ids(&self) -> &[ScopeValue] {
        &self.group_ids
    }
}

/// Group subtree scope filter.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InGroupSubtreeScopeFilter {
    property: String,
    ancestor_ids: Vec<ScopeValue>,
}

impl InGroupSubtreeScopeFilter {
    /// Create a group subtree scope filter.
    #[must_use]
    pub fn new(property: impl Into<String>, ancestor_ids: Vec<ScopeValue>) -> Self {
        Self {
            property: property.into(),
            ancestor_ids,
        }
    }

    /// The authorization property name.
    #[inline]
    #[must_use]
    pub fn property(&self) -> &str {
        &self.property
    }

    /// The ancestor group IDs.
    #[inline]
    #[must_use]
    pub fn ancestor_ids(&self) -> &[ScopeValue] {
        &self.ancestor_ids
    }
}

/// Tenant subtree scope filter — clamps a property to descendants of a single
/// root tenant via the `tenant_closure` table.
///
/// Compiles to (with `respect_barriers = true`, the default, and an empty
/// `descendant_status`):
/// `property IN (SELECT descendant_id FROM tenant_closure
///   WHERE ancestor_id = root_tenant_id AND barrier = 0)`
///
/// With `respect_barriers = false`:
/// `property IN (SELECT descendant_id FROM tenant_closure
///   WHERE ancestor_id = root_tenant_id)`
///
/// With a non-empty `descendant_status` (each value is the canonical
/// SMALLINT for a tenant status — see
/// `tenant_resolver_sdk::TenantStatus::as_smallint`):
/// `... AND descendant_status IN (...)`
///
/// **Heads-up for `tenants`-style entities:** When a property resolves
/// to the `tenants` row's own primary key (via `pep_properties::RESOURCE_ID`),
/// the entity must declare the `id` column as a resolvable secured
/// property. Entities marked with `#[secure(no_resource, ...)]` will
/// fail-closed at scope resolution time.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InTenantSubtreeScopeFilter {
    property: String,
    root_tenant_id: ScopeValue,
    respect_barriers: bool,
    descendant_status: Vec<ScopeValue>,
}

impl InTenantSubtreeScopeFilter {
    /// Create a tenant subtree scope filter that respects barriers with no
    /// status filter.
    ///
    /// Equivalent to
    /// `with_respect_barriers(property, root_tenant_id, true)`.
    #[must_use]
    pub fn new(property: impl Into<String>, root_tenant_id: impl Into<ScopeValue>) -> Self {
        Self::with_respect_barriers(property, root_tenant_id, true)
    }

    /// Create a tenant subtree scope filter with explicit barrier handling
    /// and no status filter.
    #[must_use]
    pub fn with_respect_barriers(
        property: impl Into<String>,
        root_tenant_id: impl Into<ScopeValue>,
        respect_barriers: bool,
    ) -> Self {
        Self::with_descendant_status(property, root_tenant_id, respect_barriers, Vec::new())
    }

    /// Create a tenant subtree scope filter with explicit barrier handling
    /// and a (possibly empty) status filter on the descendants. An empty
    /// list is equivalent to "no status filter".
    #[must_use]
    pub fn with_descendant_status(
        property: impl Into<String>,
        root_tenant_id: impl Into<ScopeValue>,
        respect_barriers: bool,
        descendant_status: Vec<ScopeValue>,
    ) -> Self {
        Self {
            property: property.into(),
            root_tenant_id: root_tenant_id.into(),
            respect_barriers,
            descendant_status,
        }
    }

    /// The authorization property name.
    #[inline]
    #[must_use]
    pub fn property(&self) -> &str {
        &self.property
    }

    /// The single root tenant ID at which the subtree is anchored.
    #[inline]
    #[must_use]
    pub fn root_tenant_id(&self) -> &ScopeValue {
        &self.root_tenant_id
    }

    /// Whether the SQL compilation should clamp the closure subquery
    /// with `AND barrier = 0` (i.e. stop at self-managed boundaries).
    #[inline]
    #[must_use]
    pub fn respect_barriers(&self) -> bool {
        self.respect_barriers
    }

    /// Status filter applied to the descendants reached via the closure.
    ///
    /// Empty slice means "no status filter"; otherwise the SQL adds
    /// `AND descendant_status IN (...)` to the closure subquery. Values
    /// are expected to be SMALLINT-encoded statuses
    /// (see `tenant_resolver_sdk::TenantStatus::as_smallint`).
    #[inline]
    #[must_use]
    pub fn descendant_status(&self) -> &[ScopeValue] {
        &self.descendant_status
    }
}

impl ScopeFilter {
    /// Create an equality filter (`property = value`).
    #[must_use]
    pub fn eq(property: impl Into<String>, value: impl Into<ScopeValue>) -> Self {
        Self::Eq(EqScopeFilter::new(property, value))
    }

    /// Create a set membership filter (`property IN (values)`).
    #[must_use]
    pub fn r#in(property: impl Into<String>, values: Vec<ScopeValue>) -> Self {
        Self::In(InScopeFilter::new(property, values))
    }

    /// Create a set membership filter from UUID values (convenience).
    #[must_use]
    pub fn in_uuids(property: impl Into<String>, uuids: Vec<Uuid>) -> Self {
        Self::In(InScopeFilter::new(
            property,
            uuids.into_iter().map(ScopeValue::Uuid).collect(),
        ))
    }

    /// Create a group membership filter.
    #[must_use]
    pub fn in_group(property: impl Into<String>, group_ids: Vec<ScopeValue>) -> Self {
        Self::InGroup(InGroupScopeFilter::new(property, group_ids))
    }

    /// Create a group subtree filter.
    #[must_use]
    pub fn in_group_subtree(property: impl Into<String>, ancestor_ids: Vec<ScopeValue>) -> Self {
        Self::InGroupSubtree(InGroupSubtreeScopeFilter::new(property, ancestor_ids))
    }

    /// Create a tenant subtree filter rooted at a single ancestor tenant.
    ///
    /// `descendant_status` is a (possibly empty) list of SMALLINT-encoded
    /// tenant statuses (see `tenant_resolver_sdk::TenantStatus::as_smallint`);
    /// when non-empty, the SQL adds `AND descendant_status IN (...)` to
    /// the closure subquery. Pass `Vec::new()` for "no status filter".
    #[must_use]
    pub fn in_tenant_subtree(
        property: impl Into<String>,
        root_tenant_id: impl Into<ScopeValue>,
        respect_barriers: bool,
        descendant_status: Vec<ScopeValue>,
    ) -> Self {
        Self::InTenantSubtree(InTenantSubtreeScopeFilter::with_descendant_status(
            property,
            root_tenant_id,
            respect_barriers,
            descendant_status,
        ))
    }

    /// The authorization property name.
    #[must_use]
    pub fn property(&self) -> &str {
        match self {
            Self::Eq(f) => f.property(),
            Self::In(f) => f.property(),
            Self::InGroup(f) => f.property(),
            Self::InGroupSubtree(f) => f.property(),
            Self::InTenantSubtree(f) => f.property(),
        }
    }

    /// Collect direct-match values as a slice-like view for iteration.
    ///
    /// For `Eq`, returns a single-element slice; for `In`, returns the values slice.
    /// For `InGroup`/`InGroupSubtree`/`InTenantSubtree`, returns empty — those
    /// are subquery parameters, not resource property values. The actual
    /// matching happens in SQL via [`secure::scope_to_condition`].
    ///
    /// **Write-path limitation:** Because `InTenantSubtree` returns an empty
    /// slice here, in-memory helpers such as [`AccessScope::contains_uuid`] and
    /// [`AccessScope::all_uuid_values_for`] always return negative/empty results
    /// for this filter variant. Secure-insert paths that validate scope membership
    /// via these helpers cannot use `InTenantSubtree` as a substitute for
    /// `allow_all()` without an additional DB-backed tenant-membership check.
    #[must_use]
    pub fn values(&self) -> ScopeFilterValues<'_> {
        match self {
            Self::Eq(f) => ScopeFilterValues::Single(&f.value),
            Self::In(f) => ScopeFilterValues::Multiple(&f.values),
            Self::InGroup(_) | Self::InGroupSubtree(_) | Self::InTenantSubtree(_) => {
                ScopeFilterValues::Multiple(&[])
            }
        }
    }

    /// Whether this filter can be decided from its values alone.
    ///
    /// `false` for the three subquery variants, whose matching happens in SQL.
    /// [`ScopeFilter::values`] returns an empty view for those, which is
    /// indistinguishable from an `In` filter that genuinely has no values — so
    /// a caller deciding membership in memory reads "no match" for a filter
    /// that does grant access.
    ///
    /// Check this first: a filter that is not representable in memory has to be
    /// resolved against the database, not treated as a negative.
    #[must_use]
    pub fn is_representable_in_memory(&self) -> bool {
        match self {
            Self::Eq(_) | Self::In(_) => true,
            Self::InGroup(_) | Self::InGroupSubtree(_) | Self::InTenantSubtree(_) => false,
        }
    }

    /// Extract filter values as UUIDs, skipping non-UUID entries.
    ///
    /// Useful when the caller knows the property holds UUID values
    /// (e.g., `owner_tenant_id`, `id`).
    #[must_use]
    pub fn uuid_values(&self) -> Vec<Uuid> {
        self.values()
            .iter()
            .filter_map(ScopeValue::as_uuid)
            .collect()
    }
}

/// Iterator adapter for [`ScopeFilter::values()`].
///
/// Provides a uniform way to iterate over filter values regardless of
/// whether the filter is `Eq` (single value) or `In` (multiple values).
#[derive(Clone, Debug)]
pub enum ScopeFilterValues<'a> {
    /// Single value from an `Eq` filter.
    Single(&'a ScopeValue),
    /// Multiple values from an `In` filter.
    Multiple(&'a [ScopeValue]),
}

impl<'a> ScopeFilterValues<'a> {
    /// Returns an iterator over the values.
    #[must_use]
    pub fn iter(&self) -> ScopeFilterValuesIter<'a> {
        match self {
            Self::Single(v) => ScopeFilterValuesIter(ScopeFilterValuesIterInner::Single(Some(v))),
            Self::Multiple(vs) => {
                ScopeFilterValuesIter(ScopeFilterValuesIterInner::Multiple(vs.iter()))
            }
        }
    }

    /// Returns `true` if any value matches the given predicate.
    #[must_use]
    pub fn contains(&self, value: &ScopeValue) -> bool {
        self.iter().any(|v| v == value)
    }
}

impl<'a> IntoIterator for ScopeFilterValues<'a> {
    type Item = &'a ScopeValue;
    type IntoIter = ScopeFilterValuesIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a> IntoIterator for &ScopeFilterValues<'a> {
    type Item = &'a ScopeValue;
    type IntoIter = ScopeFilterValuesIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Iterator over [`ScopeFilterValues`].
#[derive(Debug, Clone)]
pub struct ScopeFilterValuesIter<'a>(ScopeFilterValuesIterInner<'a>);

/// How [`ScopeFilterValuesIter`] is actually yielding values.
///
/// Private on purpose: as public variants this put `std::slice::Iter` into the
/// crate's API, pinning an implementation detail into the contract that a
/// change of backing collection would then break.
#[derive(Debug, Clone)]
enum ScopeFilterValuesIterInner<'a> {
    /// Yields a single value.
    Single(Option<&'a ScopeValue>),
    /// Yields from a slice.
    Multiple(std::slice::Iter<'a, ScopeValue>),
}

impl<'a> Iterator for ScopeFilterValuesIter<'a> {
    type Item = &'a ScopeValue;

    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.0 {
            ScopeFilterValuesIterInner::Single(v) => v.take(),
            ScopeFilterValuesIterInner::Multiple(iter) => iter.next(),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match &self.0 {
            ScopeFilterValuesIterInner::Single(v) => {
                let n = usize::from(v.is_some());
                (n, Some(n))
            }
            ScopeFilterValuesIterInner::Multiple(iter) => iter.size_hint(),
        }
    }
}

impl ExactSizeIterator for ScopeFilterValuesIter<'_> {}

/// A conjunction (AND) of scope filters — one access path.
///
/// All filters within a constraint must match simultaneously for a row
/// to be accessible via this path.
#[derive(Clone, Debug, PartialEq)]
pub struct ScopeConstraint {
    filters: Vec<ScopeFilter>,
}

/// A [`ScopeConstraint`] was built with no filters.
///
/// A constraint is a conjunction, so an empty one is an AND over nothing: it
/// matches every row. As one disjunct of an [`AccessScope`] that makes the whole
/// scope allow-all, while `is_unconstrained()` and `is_deny_all()` both still
/// answer `false` — so the scope looks constrained to every caller that asks.
/// `toolkit-db` compiled exactly this shape to an unconditional `WHERE true`.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
#[error("a scope constraint must carry at least one filter; an empty one matches every row")]
pub struct EmptyScopeConstraint;

impl ScopeConstraint {
    /// Create a new scope constraint from a non-empty list of filters.
    ///
    /// # Errors
    ///
    /// Returns [`EmptyScopeConstraint`] if `filters` is empty. Rejecting here is
    /// what keeps a predicate-free constraint from reaching a consumer at all:
    /// the policy compiler builds one of these from whatever predicates a PDP
    /// returned, and a decision that produced none would otherwise widen into
    /// an allow-all grant instead of failing closed.
    pub fn try_new(filters: Vec<ScopeFilter>) -> Result<Self, EmptyScopeConstraint> {
        if filters.is_empty() {
            return Err(EmptyScopeConstraint);
        }
        Ok(Self { filters })
    }

    /// Create a new scope constraint from a list of filters known to be
    /// non-empty.
    ///
    /// # Panics
    ///
    /// Panics if `filters` is empty. Prefer [`ScopeConstraint::try_new`]
    /// wherever the list is derived from input rather than written out in
    /// place; this exists for literals and test fixtures, where an empty list
    /// is a bug in the caller rather than a condition to handle.
    #[must_use]
    pub fn new(filters: Vec<ScopeFilter>) -> Self {
        assert!(
            !filters.is_empty(),
            "a scope constraint must carry at least one filter; an empty one matches every row"
        );
        Self { filters }
    }

    /// The filters in this constraint (AND-ed together).
    #[inline]
    #[must_use]
    pub fn filters(&self) -> &[ScopeFilter] {
        &self.filters
    }

    /// Returns `true` if this constraint has no filters.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.filters.is_empty()
    }
}

/// A disjunction (OR) of scope constraints defining what data is accessible.
///
/// Each constraint is an independent access path (OR-ed). Filters within a
/// constraint are AND-ed. An unconstrained scope bypasses row-level filtering.
///
/// # Examples
///
/// ```
/// use toolkit_security::access_scope::{AccessScope, ScopeConstraint, ScopeFilter, pep_properties};
/// use uuid::Uuid;
///
/// // deny-all (default)
/// let scope = AccessScope::deny_all();
/// assert!(scope.is_deny_all());
///
/// // single tenant
/// let tid = Uuid::new_v4();
/// let scope = AccessScope::for_tenant(tid);
/// assert!(!scope.is_deny_all());
/// assert!(scope.contains_uuid(pep_properties::OWNER_TENANT_ID, tid));
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct AccessScope {
    constraints: Vec<ScopeConstraint>,
    unconstrained: bool,
}

impl Default for AccessScope {
    /// Default is deny-all: no constraints and not unconstrained.
    fn default() -> Self {
        Self::deny_all()
    }
}

impl AccessScope {
    // ── Constructors ────────────────────────────────────────────────

    /// Create an access scope from a list of constraints (OR-ed).
    #[must_use]
    pub fn from_constraints(constraints: Vec<ScopeConstraint>) -> Self {
        Self {
            constraints,
            unconstrained: false,
        }
    }

    /// Create an access scope with a single constraint.
    #[must_use]
    pub fn single(constraint: ScopeConstraint) -> Self {
        Self::from_constraints(vec![constraint])
    }

    /// Create an "allow all" (unconstrained) scope.
    ///
    /// This represents a legitimate PDP decision with no row-level filtering.
    /// Not a bypass — it's a valid authorization outcome.
    #[must_use]
    pub fn allow_all() -> Self {
        Self {
            constraints: Vec::new(),
            unconstrained: true,
        }
    }

    /// Create a "deny all" scope (no access).
    #[must_use]
    pub fn deny_all() -> Self {
        Self {
            constraints: Vec::new(),
            unconstrained: false,
        }
    }

    // ── Convenience constructors ────────────────────────────────────

    /// Create a scope for a set of tenant IDs.
    #[must_use]
    pub fn for_tenants(ids: Vec<Uuid>) -> Self {
        Self::single(ScopeConstraint::new(vec![ScopeFilter::in_uuids(
            pep_properties::OWNER_TENANT_ID,
            ids,
        )]))
    }

    /// Create a scope for a single tenant ID.
    #[must_use]
    pub fn for_tenant(id: Uuid) -> Self {
        Self::for_tenants(vec![id])
    }

    /// Create a scope for a set of resource IDs.
    #[must_use]
    pub fn for_resources(ids: Vec<Uuid>) -> Self {
        Self::single(ScopeConstraint::new(vec![ScopeFilter::in_uuids(
            pep_properties::RESOURCE_ID,
            ids,
        )]))
    }

    /// Create a scope for a single resource ID.
    #[must_use]
    pub fn for_resource(id: Uuid) -> Self {
        Self::for_resources(vec![id])
    }

    // ── Accessors ───────────────────────────────────────────────────

    /// The constraints in this scope (OR-ed).
    #[inline]
    #[must_use]
    pub fn constraints(&self) -> &[ScopeConstraint] {
        &self.constraints
    }

    /// Returns `true` if this scope is unconstrained (allow-all).
    #[inline]
    #[must_use]
    pub fn is_unconstrained(&self) -> bool {
        self.unconstrained
    }

    /// Returns `true` if this scope denies all access.
    ///
    /// A scope is deny-all when it is not unconstrained and has no constraints.
    #[must_use]
    pub fn is_deny_all(&self) -> bool {
        !self.unconstrained && self.constraints.is_empty()
    }

    /// Collect all values for a given property across all constraints.
    ///
    /// **Reports on the constraint list only.** An allow-all scope has no
    /// constraints, so this returns an empty `Vec` for it — which means "no
    /// constraint names this property", never "this scope permits nothing".
    /// An allow-all scope permits every value, and no finite list can say so.
    /// Check [`AccessScope::is_unconstrained`] before reading anything into an
    /// empty result.
    #[must_use]
    pub fn all_values_for(&self, property: &str) -> Vec<&ScopeValue> {
        let mut result = Vec::new();
        for constraint in &self.constraints {
            for filter in constraint.filters() {
                if filter.property() == property {
                    result.extend(filter.values());
                }
            }
        }
        result
    }

    /// Collect all UUID values for a given property across all constraints.
    ///
    /// Convenience wrapper — skips non-UUID values.
    ///
    /// **Reports on the constraint list only**, with the same caveat as
    /// [`AccessScope::all_values_for`]: empty on an allow-all scope, which
    /// permits everything rather than nothing.
    #[must_use]
    pub fn all_uuid_values_for(&self, property: &str) -> Vec<Uuid> {
        let mut result = Vec::new();
        for constraint in &self.constraints {
            for filter in constraint.filters() {
                if filter.property() == property {
                    result.extend(filter.uuid_values());
                }
            }
        }
        result
    }

    /// Whether any filter, in any constraint, names `property` with this UUID.
    ///
    /// Matches both `ScopeValue::Uuid` and `ScopeValue::String` variants so
    /// that UUID-as-string values are treated consistently with
    /// [`AccessScope::all_uuid_values_for`], which also parses strings via
    /// [`ScopeValue::as_uuid`].
    ///
    /// # This is not an authorization decision
    ///
    /// It searches filter *values*. It does not evaluate a constraint, which is
    /// a conjunction: for a grant of `[owner_tenant_id = A AND owner_id = Alice]`
    /// this answers `true` for `(owner_tenant_id, A)` even when the row in
    /// question belongs to Bob. A `true` here means "the scope mentions this
    /// value somewhere", nothing more.
    ///
    /// It also reports on the constraint list alone, so an allow-all scope —
    /// which has no constraints — answers `false` for a value it permits, and
    /// a subquery filter (`InGroup`, `InGroupSubtree`, `InTenantSubtree`)
    /// exposes no in-memory values at all, so it answers `false` for a grant
    /// that does apply.
    ///
    /// Authorize a write by passing the scope to the insert and letting
    /// `SecureORM` evaluate it — `validate_insert_scope` ANDs across the filters
    /// of a constraint and ORs across constraints, which is the whole decision.
    ///
    /// Not marked `#[deprecated]` yet: the workspace builds with `-D warnings`,
    /// so the attribute would break the build at all of its current call sites
    /// at once. It goes on once the three gear gates
    /// (resource-group, ledger, pricing) have moved to `SecureORM`.
    #[must_use]
    pub fn contains_uuid(&self, property: &str, id: Uuid) -> bool {
        self.constraints.iter().any(|c| {
            c.filters().iter().any(|f| {
                f.property() == property && f.values().iter().any(|v| v.as_uuid() == Some(id))
            })
        })
    }

    /// Check if any constraint references the given property.
    ///
    /// **Reports on the constraint list only**: an allow-all scope has no
    /// constraints and so answers `false`, which is not a statement about what
    /// it permits. Check [`AccessScope::is_unconstrained`] first.
    #[must_use]
    pub fn has_property(&self, property: &str) -> bool {
        self.constraints
            .iter()
            .any(|c| c.filters().iter().any(|f| f.property() == property))
    }

    /// Create a new scope retaining only `owner_tenant_id` filters.
    ///
    /// Useful for entities declared with `no_owner` (e.g., messages, reactions),
    /// where `owner_id` constraints cannot be resolved and would cause fail-closed
    /// deny-all behaviour.
    ///
    /// - Unconstrained scopes become deny-all (fail-closed).
    /// - Constraints that contain no `owner_tenant_id` filter are dropped entirely.
    /// - If all constraints are dropped, the result is deny-all.
    ///
    /// # This widens the grant, by design — check that you want it
    ///
    /// Filters on other properties are **removed from surviving constraints**,
    /// and a constraint is a conjunction, so dropping one of its terms admits
    /// everything that term excluded. `[owner_tenant_id = T, id IN (r1)]`
    /// becomes `owner_tenant_id = T`: one resource turned into the whole tenant.
    ///
    /// That is correct for the case this exists for — re-targeting a scope at a
    /// *different* entity, one with no `owner_id`/`id` column of its own, where
    /// the removed terms never applied to the rows being filtered. It is wrong
    /// if you are narrowing a scope for the same entity, and the resulting
    /// scope must not be the only thing authorizing the access: mini-chat, for
    /// example, checks the parent chat against the full scope first and only
    /// then uses `tenant_only()` for its messages.
    #[must_use]
    pub fn tenant_only(&self) -> Self {
        self.retain_properties(&[pep_properties::OWNER_TENANT_ID])
    }

    /// Create a new scope retaining only `owner_tenant_id` and `owner_id` filters.
    ///
    /// Useful for entities that have both tenant and owner columns but no
    /// resource-level constraints (e.g., reactions scoped to the acting user).
    ///
    /// - Unconstrained scopes become deny-all (fail-closed).
    /// - Constraints that contain neither retained property are dropped.
    /// - Filters on other properties are **removed from surviving
    ///   constraints**, which widens them — see the warning on
    ///   [`AccessScope::tenant_only`]; it applies here in full.
    /// - If all constraints are dropped, the result is deny-all.
    #[must_use]
    pub fn tenant_and_owner(&self) -> Self {
        self.retain_properties(&[pep_properties::OWNER_TENANT_ID, pep_properties::OWNER_ID])
    }

    /// Create a new scope that guarantees an `owner_id` equality filter
    /// matching exactly the supplied `owner_id` is present in every constraint.
    ///
    /// **Intersection semantics**: if a constraint already contains an
    /// `owner_id` filter, the supplied value must be among its values —
    /// otherwise the constraint is dropped. When it matches, the filter is
    /// narrowed to exactly that single value.
    ///
    /// - **Unconstrained** → single constraint with only the `owner_id` filter.
    /// - **Deny-all** → stays deny-all.
    /// - **No existing owner filter** → `owner_id` is injected.
    /// - **Existing owner filter containing `owner_id`** → narrowed to `Eq`.
    /// - **Existing owner filter NOT containing `owner_id`** → constraint dropped
    ///   (constraints use OR semantics, so dropping one narrows access; dropping
    ///   all yields deny-all).
    ///
    /// Use this as a defence-in-depth measure for user-owned resources when
    /// the PDP may not always return `owner_id` constraints or may return a
    /// broader set than the current subject.
    #[must_use]
    pub fn ensure_owner(&self, owner_id: Uuid) -> Self {
        if self.is_deny_all() {
            return Self::deny_all();
        }

        let owner_filter = ScopeFilter::eq(pep_properties::OWNER_ID, owner_id);

        if self.unconstrained {
            return Self::single(ScopeConstraint::new(vec![owner_filter]));
        }

        let constraints = self
            .constraints
            .iter()
            .filter_map(|c| {
                let owner_filters: Vec<&ScopeFilter> = c
                    .filters()
                    .iter()
                    .filter(|f| f.property() == pep_properties::OWNER_ID)
                    .collect();

                if owner_filters.is_empty() {
                    let mut filters = c.filters().to_vec();
                    filters.push(owner_filter.clone());
                    return Some(ScopeConstraint::new(filters));
                }

                // Intersection semantics: ALL owner_id predicates must contain
                // the supplied owner_id, otherwise the constraint is dropped.
                let all_match = owner_filters
                    .iter()
                    .all(|f| f.values().iter().any(|v| v.as_uuid() == Some(owner_id)));
                if !all_match {
                    return None;
                }

                // Fast path: single Eq already matches → constraint unchanged.
                if owner_filters.len() == 1 && matches!(owner_filters[0], ScopeFilter::Eq(_)) {
                    return Some(c.clone());
                }

                // Replace all owner_id filters with a single Eq.
                let mut filters: Vec<ScopeFilter> = c
                    .filters()
                    .iter()
                    .filter(|f| f.property() != pep_properties::OWNER_ID)
                    .cloned()
                    .collect();
                filters.push(owner_filter.clone());
                Some(ScopeConstraint::new(filters))
            })
            .collect();

        Self::from_constraints(constraints)
    }

    /// Internal helper: build a new scope keeping only filters whose property
    /// is in the given whitelist.
    fn retain_properties(&self, properties: &[&str]) -> Self {
        if self.unconstrained {
            return Self::deny_all();
        }

        let constraints = self
            .constraints
            .iter()
            .filter_map(|c| {
                let kept: Vec<ScopeFilter> = c
                    .filters()
                    .iter()
                    .filter(|f| properties.contains(&f.property()))
                    .cloned()
                    .collect();

                if kept.is_empty() {
                    None
                } else {
                    Some(ScopeConstraint::new(kept))
                }
            })
            .collect();

        Self::from_constraints(constraints)
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use uuid::Uuid;

    const T1: &str = "11111111-1111-1111-1111-111111111111";
    const T2: &str = "22222222-2222-2222-2222-222222222222";

    fn uid(s: &str) -> Uuid {
        Uuid::parse_str(s).unwrap()
    }

    // --- ScopeFilter::Eq ---

    #[test]
    fn scope_filter_eq_exposes_exactly_one_value() {
        let f = ScopeFilter::eq(pep_properties::OWNER_TENANT_ID, uid(T1));
        assert_eq!(f.property(), pep_properties::OWNER_TENANT_ID);
        assert!(matches!(f, ScopeFilter::Eq(_)));

        // The behaviour worth pinning is what an `Eq` filter yields, not that
        // the constructor stored what it was handed: exactly one value, and one
        // that parses back to the UUID it was built from.
        assert_eq!(f.values().iter().count(), 1);
        assert_eq!(f.uuid_values(), vec![uid(T1)]);
    }

    #[test]
    fn all_values_for_works_with_eq() {
        let scope = AccessScope::single(ScopeConstraint::new(vec![ScopeFilter::eq(
            pep_properties::OWNER_TENANT_ID,
            uid(T1),
        )]));
        assert_eq!(
            scope.all_uuid_values_for(pep_properties::OWNER_TENANT_ID),
            &[uid(T1)]
        );
    }

    #[test]
    fn all_values_for_works_with_mixed_eq_and_in() {
        let scope = AccessScope::from_constraints(vec![
            ScopeConstraint::new(vec![ScopeFilter::eq(
                pep_properties::OWNER_TENANT_ID,
                uid(T1),
            )]),
            ScopeConstraint::new(vec![ScopeFilter::in_uuids(
                pep_properties::OWNER_TENANT_ID,
                vec![uid(T2)],
            )]),
        ]);
        let values = scope.all_uuid_values_for(pep_properties::OWNER_TENANT_ID);
        assert_eq!(values, &[uid(T1), uid(T2)]);
    }

    #[test]
    fn contains_uuid_works_with_eq() {
        let scope = AccessScope::single(ScopeConstraint::new(vec![ScopeFilter::eq(
            pep_properties::OWNER_TENANT_ID,
            uid(T1),
        )]));
        assert!(scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
        assert!(!scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T2)));
    }

    #[test]
    fn a_subquery_filter_reports_that_it_cannot_be_decided_in_memory() {
        // An empty value view means two different things, and only this
        // predicate separates them: an `In` filter with no values genuinely
        // matches nothing, while a subquery filter matches whatever the
        // database says and simply cannot answer here.
        let empty_in = ScopeFilter::r#in(pep_properties::OWNER_TENANT_ID, vec![]);
        assert_eq!(empty_in.values().iter().count(), 0);
        assert!(
            empty_in.is_representable_in_memory(),
            "an In filter with no values is a real, decidable negative"
        );

        for subquery in [
            ScopeFilter::in_group(pep_properties::RESOURCE_ID, vec![ScopeValue::Uuid(uid(T1))]),
            ScopeFilter::in_group_subtree(
                pep_properties::RESOURCE_ID,
                vec![ScopeValue::Uuid(uid(T1))],
            ),
        ] {
            assert_eq!(subquery.values().iter().count(), 0);
            assert!(
                !subquery.is_representable_in_memory(),
                "a subquery filter's empty value view is not a negative"
            );
        }
    }

    #[test]
    fn contains_uuid_matches_a_uuid_held_as_a_string() {
        // The same id can sit in a scope as either `Uuid` or the `String` of its
        // text, and the two are not equal under `PartialEq`. `contains_uuid`
        // parses through `as_uuid`, so it answers on identity rather than on
        // representation.
        let as_text = AccessScope::single(ScopeConstraint::new(vec![ScopeFilter::eq(
            pep_properties::OWNER_TENANT_ID,
            ScopeValue::String(uid(T1).to_string()),
        )]));
        assert!(as_text.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
        assert!(!as_text.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T2)));

        let typed = AccessScope::single(ScopeConstraint::new(vec![ScopeFilter::eq(
            pep_properties::OWNER_TENANT_ID,
            uid(T1),
        )]));
        assert!(typed.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
    }

    #[test]
    fn contains_uuid_is_false_for_a_subquery_filter() {
        // `InGroup` resolves in SQL and exposes no values in memory, so this
        // answers "no" for a grant that does apply — one of the reasons it is
        // not an authorization decision.
        let scope = AccessScope::single(ScopeConstraint::new(vec![ScopeFilter::in_group(
            pep_properties::RESOURCE_ID,
            vec![ScopeValue::Uuid(uid(T1))],
        )]));
        assert!(!scope.contains_uuid(pep_properties::RESOURCE_ID, uid(T1)));
    }

    #[test]
    fn contains_uuid_does_not_evaluate_the_conjunction() {
        // The reason this is deprecated: a constraint is an AND, and this
        // reports on a single filter. The grant is "tenant T1 *and* owner T2",
        // yet the tenant alone answers true — which is why a caller must not
        // read it as permission.
        let scope = AccessScope::single(ScopeConstraint::new(vec![
            ScopeFilter::eq(pep_properties::OWNER_TENANT_ID, uid(T1)),
            ScopeFilter::eq(pep_properties::OWNER_ID, uid(T2)),
        ]));

        assert!(scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
        assert!(
            !scope.contains_uuid(pep_properties::OWNER_ID, uid(T1)),
            "guard: T1 is the tenant, not the owner"
        );
    }

    #[test]
    fn an_allow_all_scope_permits_everything_it_reports_no_constraint_for() {
        // The distinction the `contains_*` family cannot express on its own: an
        // allow-all scope holds no constraints, so every one of them answers
        // "no" for a value the scope in fact permits.
        let scope = AccessScope::allow_all();

        assert!(!scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
        assert!(!scope.has_property(pep_properties::OWNER_TENANT_ID));
        assert!(
            scope
                .all_uuid_values_for(pep_properties::OWNER_TENANT_ID)
                .is_empty()
        );

        // `is_unconstrained` is the only accessor that tells the two apart, and
        // it is what a caller must consult — a deny-all scope reports exactly
        // the same emptiness while permitting nothing.
        assert!(scope.is_unconstrained());
        assert!(!AccessScope::deny_all().is_unconstrained());
    }

    #[test]
    fn an_empty_constraint_is_refused() {
        // An AND over no filters is TRUE, so this shape is an allow-all
        // disjunct -- while the scope carrying it still reports itself as
        // neither unconstrained nor deny-all, so nothing downstream sees that
        // it grants everything.
        assert_eq!(
            ScopeConstraint::try_new(vec![]).unwrap_err(),
            EmptyScopeConstraint
        );

        assert!(
            ScopeConstraint::try_new(vec![ScopeFilter::eq(
                pep_properties::OWNER_TENANT_ID,
                uid(T1)
            )])
            .is_ok(),
            "one filter is enough to narrow"
        );
    }

    #[test]
    #[should_panic(expected = "must carry at least one filter")]
    fn the_infallible_constructor_refuses_an_empty_list_too() {
        // `new` is for literals, where an empty list is a bug in the caller
        // rather than a condition to handle -- but it must not quietly produce
        // the allow-all shape either.
        drop(ScopeConstraint::new(vec![]));
    }

    #[test]
    fn a_deny_all_scope_permits_nothing() {
        let scope = AccessScope::deny_all();
        assert!(scope.is_deny_all());
        assert!(!scope.is_unconstrained());
        assert!(!scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
    }

    // --- tenant_only ---

    #[test]
    fn tenant_only_strips_owner_id() {
        let scope = AccessScope::single(ScopeConstraint::new(vec![
            ScopeFilter::eq(pep_properties::OWNER_TENANT_ID, uid(T1)),
            ScopeFilter::eq(pep_properties::OWNER_ID, uid(T2)),
        ]));

        let tenant_scope = scope.tenant_only();
        assert!(tenant_scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
        assert!(!tenant_scope.has_property(pep_properties::OWNER_ID));
    }

    #[test]
    fn tenant_only_widens_a_resource_scoped_grant_to_the_whole_tenant() {
        // Pinning the sharp edge rather than the happy path: removing a term
        // from a conjunction admits everything that term excluded. This is what
        // makes `tenant_only()` safe only when re-targeting the scope at an
        // entity the removed terms never applied to -- and unsafe as the sole
        // authorization for the same entity.
        let scope = AccessScope::single(ScopeConstraint::new(vec![
            ScopeFilter::eq(pep_properties::OWNER_TENANT_ID, uid(T1)),
            ScopeFilter::eq(pep_properties::RESOURCE_ID, uid(T2)),
        ]));

        let tenant_scope = scope.tenant_only();
        assert!(
            !tenant_scope.has_property(pep_properties::RESOURCE_ID),
            "the resource narrowing is gone, so this grant now covers the tenant"
        );
        assert!(tenant_scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
    }

    #[test]
    fn tenant_only_unconstrained_becomes_deny_all() {
        let scope = AccessScope::allow_all();
        let tenant_scope = scope.tenant_only();
        assert!(tenant_scope.is_deny_all());
    }

    #[test]
    fn tenant_only_deny_all_when_no_tenant_filters() {
        let scope = AccessScope::single(ScopeConstraint::new(vec![ScopeFilter::eq(
            pep_properties::OWNER_ID,
            uid(T1),
        )]));

        let tenant_scope = scope.tenant_only();
        assert!(tenant_scope.is_deny_all());
    }

    #[test]
    fn tenant_only_on_deny_all_stays_deny_all() {
        let scope = AccessScope::deny_all();
        let tenant_scope = scope.tenant_only();
        assert!(tenant_scope.is_deny_all());
    }

    // --- tenant_and_owner ---

    #[test]
    fn tenant_and_owner_keeps_both_properties() {
        let scope = AccessScope::single(ScopeConstraint::new(vec![
            ScopeFilter::eq(pep_properties::OWNER_TENANT_ID, uid(T1)),
            ScopeFilter::eq(pep_properties::OWNER_ID, uid(T2)),
            ScopeFilter::eq(pep_properties::RESOURCE_ID, uid(T1)),
        ]));

        let narrowed = scope.tenant_and_owner();
        assert!(narrowed.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
        assert!(narrowed.contains_uuid(pep_properties::OWNER_ID, uid(T2)));
        assert!(!narrowed.has_property(pep_properties::RESOURCE_ID));
    }

    #[test]
    fn tenant_and_owner_unconstrained_becomes_deny_all() {
        let scope = AccessScope::allow_all();
        assert!(scope.tenant_and_owner().is_deny_all());
    }

    #[test]
    fn tenant_and_owner_deny_all_when_no_matching_filters() {
        let scope = AccessScope::single(ScopeConstraint::new(vec![ScopeFilter::eq(
            pep_properties::RESOURCE_ID,
            uid(T1),
        )]));
        assert!(scope.tenant_and_owner().is_deny_all());
    }

    // --- ensure_owner ---

    #[test]
    fn ensure_owner_adds_owner_when_missing() {
        let scope = AccessScope::for_tenant(uid(T1));
        let owner_id = uid(T2);

        let scoped = scope.ensure_owner(owner_id);
        assert!(scoped.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
        assert!(scoped.contains_uuid(pep_properties::OWNER_ID, owner_id));
    }

    #[test]
    fn ensure_owner_keeps_existing_owner() {
        let existing_owner = uid(T2);
        let scope = AccessScope::single(ScopeConstraint::new(vec![
            ScopeFilter::eq(pep_properties::OWNER_TENANT_ID, uid(T1)),
            ScopeFilter::eq(pep_properties::OWNER_ID, existing_owner),
        ]));

        let scoped = scope.ensure_owner(existing_owner);
        assert_eq!(
            scoped.all_uuid_values_for(pep_properties::OWNER_ID),
            &[existing_owner]
        );
    }

    #[test]
    fn ensure_owner_on_unconstrained_creates_owner_scope() {
        let scope = AccessScope::allow_all();
        let owner_id = uid(T1);

        let scoped = scope.ensure_owner(owner_id);
        assert!(!scoped.is_unconstrained());
        assert!(scoped.contains_uuid(pep_properties::OWNER_ID, owner_id));
    }

    #[test]
    fn ensure_owner_on_deny_all_stays_deny_all() {
        let scope = AccessScope::deny_all();
        let scoped = scope.ensure_owner(uid(T1));
        assert!(scoped.is_deny_all());
    }

    #[test]
    fn ensure_owner_narrows_existing_owner_to_subject() {
        let user_a = uid(T1);
        let user_b = uid(T2);
        let scope = AccessScope::single(ScopeConstraint::new(vec![
            ScopeFilter::eq(pep_properties::OWNER_TENANT_ID, uid(T1)),
            ScopeFilter::in_uuids(pep_properties::OWNER_ID, vec![user_a, user_b]),
        ]));

        let scoped = scope.ensure_owner(user_a);
        assert_eq!(
            scoped.all_uuid_values_for(pep_properties::OWNER_ID),
            &[user_a],
            "Must narrow to exactly the subject's owner_id"
        );
        assert!(scoped.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
    }

    #[test]
    fn ensure_owner_drops_constraint_when_subject_not_in_pdp() {
        let user_x = uid(T1);
        let user_y = uid(T2);
        let scope = AccessScope::single(ScopeConstraint::new(vec![
            ScopeFilter::eq(pep_properties::OWNER_TENANT_ID, uid(T1)),
            ScopeFilter::eq(pep_properties::OWNER_ID, user_x),
        ]));

        let scoped = scope.ensure_owner(user_y);
        assert!(
            scoped.is_deny_all(),
            "Must be deny-all when subject not in PDP's owner set"
        );
    }

    #[test]
    fn ensure_owner_checks_all_owner_filters_in_constraint() {
        let alice = uid(T1);
        let bob = uid(T2);
        // Contrived: two owner_id filters in one constraint.
        // alice is in the first but not the second → must be dropped.
        let scope = AccessScope::single(ScopeConstraint::new(vec![
            ScopeFilter::in_uuids(pep_properties::OWNER_ID, vec![alice, bob]),
            ScopeFilter::in_uuids(pep_properties::OWNER_ID, vec![bob]),
        ]));

        let scoped = scope.ensure_owner(alice);
        assert!(
            scoped.is_deny_all(),
            "Must deny when subject is missing from any owner_id filter"
        );

        // bob is in both → should pass and narrow to Eq.
        let scoped = scope.ensure_owner(bob);
        assert!(!scoped.is_deny_all());
        assert_eq!(
            scoped.all_uuid_values_for(pep_properties::OWNER_ID),
            &[bob],
            "Must narrow to single Eq for the matching owner"
        );
    }

    #[test]
    fn ensure_owner_multi_constraint_keeps_only_matching() {
        let alice = uid(T1);
        let bob = uid(T2);
        let tenant = uid(T1);

        // Constraint 1: tenant + alice → matches alice
        let c1 = ScopeConstraint::new(vec![
            ScopeFilter::eq(pep_properties::OWNER_TENANT_ID, tenant),
            ScopeFilter::eq(pep_properties::OWNER_ID, alice),
        ]);
        // Constraint 2: tenant + bob → does NOT match alice
        let c2 = ScopeConstraint::new(vec![
            ScopeFilter::eq(pep_properties::OWNER_TENANT_ID, tenant),
            ScopeFilter::eq(pep_properties::OWNER_ID, bob),
        ]);

        let scope = AccessScope::from_constraints(vec![c1, c2]);
        let scoped = scope.ensure_owner(alice);

        assert!(
            !scoped.is_deny_all(),
            "Must not be deny-all - one constraint matches"
        );
        assert_eq!(
            scoped.all_uuid_values_for(pep_properties::OWNER_ID),
            &[alice],
            "Must keep only the constraint matching alice"
        );
        assert!(
            scoped.contains_uuid(pep_properties::OWNER_TENANT_ID, tenant),
            "Tenant filter must be preserved"
        );
    }

    // --- ScopeFilter::InGroup ---

    #[test]
    fn scope_filter_in_group_constructor() {
        let f = ScopeFilter::in_group(
            pep_properties::OWNER_TENANT_ID,
            vec![ScopeValue::Uuid(uid(T1))],
        );
        assert_eq!(f.property(), pep_properties::OWNER_TENANT_ID);
        assert!(matches!(f, ScopeFilter::InGroup(_)));
        assert_eq!(f.values().iter().count(), 0);
    }

    // --- ScopeFilter::InGroupSubtree ---

    #[test]
    fn scope_filter_in_group_subtree_constructor() {
        let f = ScopeFilter::in_group_subtree(
            pep_properties::OWNER_TENANT_ID,
            vec![ScopeValue::Uuid(uid(T1))],
        );
        assert_eq!(f.property(), pep_properties::OWNER_TENANT_ID);
        assert!(matches!(f, ScopeFilter::InGroupSubtree(_)));
        assert_eq!(f.values().iter().count(), 0);
    }

    #[test]
    fn in_group_scope_contains_uuid_returns_false() {
        let scope = AccessScope::single(ScopeConstraint::new(vec![ScopeFilter::in_group(
            pep_properties::OWNER_TENANT_ID,
            vec![ScopeValue::Uuid(uid(T1))],
        )]));
        assert!(!scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
    }

    #[test]
    fn in_group_subtree_scope_contains_uuid_returns_false() {
        let scope = AccessScope::single(ScopeConstraint::new(vec![ScopeFilter::in_group_subtree(
            pep_properties::OWNER_TENANT_ID,
            vec![ScopeValue::Uuid(uid(T1))],
        )]));
        assert!(!scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
    }

    // --- ScopeFilter::InTenantSubtree ---

    #[test]
    fn scope_filter_in_tenant_subtree_constructor_defaults_to_respect() {
        let f = ScopeFilter::in_tenant_subtree(
            pep_properties::RESOURCE_ID,
            ScopeValue::Uuid(uid(T1)),
            true,
            Vec::new(),
        );
        assert_eq!(f.property(), pep_properties::RESOURCE_ID);
        assert!(matches!(f, ScopeFilter::InTenantSubtree(_)));
        assert_eq!(f.values().iter().count(), 0);
        match &f {
            ScopeFilter::InTenantSubtree(sf) => {
                assert!(sf.respect_barriers());
                assert!(sf.descendant_status().is_empty());
            }
            other => panic!("unexpected variant: {other:?}"),
        }
    }

    #[test]
    fn in_tenant_subtree_scope_contains_uuid_returns_false() {
        let scope =
            AccessScope::single(ScopeConstraint::new(vec![ScopeFilter::in_tenant_subtree(
                pep_properties::RESOURCE_ID,
                ScopeValue::Uuid(uid(T1)),
                true,
                Vec::new(),
            )]));
        assert!(!scope.contains_uuid(pep_properties::RESOURCE_ID, uid(T1)));
    }

    #[test]
    fn in_tenant_subtree_scope_filter_carries_descendant_status() {
        let filter =
            ScopeFilter::InTenantSubtree(InTenantSubtreeScopeFilter::with_descendant_status(
                pep_properties::OWNER_TENANT_ID,
                ScopeValue::Uuid(uid(T1)),
                true,
                vec![ScopeValue::Int(1), ScopeValue::Int(2)],
            ));

        // The status list must survive into the filter...
        let ScopeFilter::InTenantSubtree(inner) = &filter else {
            panic!("constructed as InTenantSubtree");
        };
        assert_eq!(
            inner.descendant_status(),
            &[ScopeValue::Int(1), ScopeValue::Int(2)]
        );

        // ...while `values()` stays empty, because this variant resolves as a
        // subquery in SQL and exposes nothing to match against in memory. That
        // pairing is what the filter promises; reading the field back alone
        // would pass even if the variant started leaking values.
        assert_eq!(filter.values().iter().count(), 0);
        assert!(!filter.is_representable_in_memory());
    }

    #[test]
    fn in_tenant_subtree_scope_filter_exposes_property_and_root() {
        let f =
            InTenantSubtreeScopeFilter::new(pep_properties::RESOURCE_ID, ScopeValue::Uuid(uid(T1)));
        assert_eq!(f.property(), pep_properties::RESOURCE_ID);
        assert_eq!(f.root_tenant_id(), &ScopeValue::Uuid(uid(T1)));
        assert!(f.respect_barriers());
    }

    #[test]
    fn in_tenant_subtree_scope_filter_ignore_barriers_constructor() {
        let f = InTenantSubtreeScopeFilter::with_respect_barriers(
            pep_properties::OWNER_TENANT_ID,
            ScopeValue::Uuid(uid(T1)),
            false,
        );
        assert!(!f.respect_barriers());
    }

    // `tenant_tables_constants_are_stable` used to live here, comparing each
    // constant to the literal it was defined as a few hundred lines above --
    // which can only fail if someone edits one and forgets the other. The
    // constants themselves have since moved to `toolkit-db`, next to the code
    // that emits SQL against those tables.

    // --- contains_uuid string matching ---

    #[test]
    fn contains_uuid_matches_string_variant() {
        let scope = AccessScope::single(ScopeConstraint::new(vec![ScopeFilter::eq(
            pep_properties::OWNER_TENANT_ID,
            ScopeValue::String(T1.to_owned()),
        )]));
        assert!(scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
        assert!(!scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T2)));
    }

    #[test]
    fn contains_uuid_does_not_match_invalid_string() {
        let scope = AccessScope::single(ScopeConstraint::new(vec![ScopeFilter::eq(
            pep_properties::OWNER_TENANT_ID,
            ScopeValue::String("not-a-uuid".to_owned()),
        )]));
        assert!(!scope.contains_uuid(pep_properties::OWNER_TENANT_ID, uid(T1)));
    }
}