what-core 1.7.0

Core framework for What - an HTML-first web framework powered by Rust
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
//! Declarative collection authorization policies.
//!
//! Policies are declared per collection in `what.toml` `[collections.<name>]`
//! sections and govern who may create/read/update/delete records, plus record
//! ownership, tenant scoping, and field-level restrictions. Collections without
//! an explicit policy get an owner-protected default (create = "all",
//! update/delete = "owner", read = "all").
//!
//! Enforcement lives in the server handlers: [`CollectionPolicy::allows_create`]
//! / [`allows_mutation`](CollectionPolicy::allows_mutation) gate writes,
//! [`read_scope`](CollectionPolicy::read_scope) forces a WHERE clause on reads,
//! and [`stamp_owner`](CollectionPolicy::stamp_owner) / [`sanitize_input`] keep
//! server-managed fields trustworthy.

use crate::auth::UserContext;
use crate::config::CollectionPolicyConfig;
use crate::sessions::Session;
use crate::{Error, Result};
use serde_json::{Map, Value};
use std::collections::HashMap;

/// A single term in a rule (rules are an OR of terms).
#[derive(Debug, Clone, PartialEq)]
pub enum RuleTerm {
    /// Anyone, including anonymous visitors.
    All,
    /// Any authenticated user.
    User,
    /// The record's owner (mutations/reads only — invalid for create).
    Owner,
    /// No one.
    Nobody,
    /// A named role.
    Role(String),
}

impl std::fmt::Display for RuleTerm {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RuleTerm::All => write!(f, "all"),
            RuleTerm::User => write!(f, "user"),
            RuleTerm::Owner => write!(f, "owner"),
            RuleTerm::Nobody => write!(f, "none"),
            RuleTerm::Role(r) => write!(f, "{r}"),
        }
    }
}

/// An access rule — a disjunction (OR) of terms.
#[derive(Debug, Clone, PartialEq)]
pub struct Rule {
    terms: Vec<RuleTerm>,
}

impl Rule {
    /// Parse a rule expression like `"owner, admin"`. `ctx` is a dotted path
    /// (e.g. `collections.notes.update`) used in error messages. `allow_owner`
    /// is false for create rules (a record has no owner before it exists).
    pub fn parse(s: &str, ctx: &str, allow_owner: bool) -> Result<Rule> {
        let raw: Vec<String> = s
            .split(',')
            .map(|t| t.trim().to_string())
            .filter(|t| !t.is_empty())
            .collect();
        if raw.is_empty() {
            return Err(Error::Config(format!("{ctx}: empty rule")));
        }

        let mut terms = Vec::new();
        for word in &raw {
            let term = match word.as_str() {
                "all" => RuleTerm::All,
                "user" => RuleTerm::User,
                "none" => RuleTerm::Nobody,
                "owner" => {
                    if !allow_owner {
                        return Err(Error::Config(format!(
                            "{ctx}: \"owner\" is not valid for a create rule (a record has no owner until it is created)"
                        )));
                    }
                    RuleTerm::Owner
                }
                other => RuleTerm::Role(other.to_string()),
            };
            terms.push(term);
        }

        // Reserved words cannot be combined with anything else.
        if terms.contains(&RuleTerm::All) && terms.len() > 1 {
            return Err(Error::Config(format!(
                "{ctx}: \"all\" cannot be combined with other terms"
            )));
        }
        if terms.contains(&RuleTerm::Nobody) && terms.len() > 1 {
            return Err(Error::Config(format!(
                "{ctx}: \"none\" cannot be combined with other terms"
            )));
        }

        Ok(Rule { terms })
    }

    /// Rule that allows everyone.
    pub fn all() -> Rule {
        Rule { terms: vec![RuleTerm::All] }
    }

    /// Rule that allows only the record owner.
    pub fn owner() -> Rule {
        Rule { terms: vec![RuleTerm::Owner] }
    }

    /// True if this rule allows anyone unconditionally.
    pub fn is_all(&self) -> bool {
        self.terms == [RuleTerm::All]
    }

    /// True if any term references ownership.
    fn has_owner(&self) -> bool {
        self.terms.contains(&RuleTerm::Owner)
    }

    /// True if any non-owner term matches this actor (i.e. the actor may act on
    /// records regardless of ownership).
    fn non_owner_match(&self, actor: &Actor) -> bool {
        self.terms.iter().any(|t| match t {
            RuleTerm::All => true,
            RuleTerm::User => actor.authenticated,
            RuleTerm::Role(r) => actor.roles.iter().any(|ar| ar == r),
            RuleTerm::Owner | RuleTerm::Nobody => false,
        })
    }
}

impl std::fmt::Display for Rule {
    /// Render the rule as its config vocabulary (round-trips `Rule::parse`).
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let terms: Vec<String> = self.terms.iter().map(|t| t.to_string()).collect();
        write!(f, "{}", terms.join(", "))
    }
}

/// Ownership mode for a collection.
#[derive(Debug, Clone, PartialEq)]
pub enum OwnerMode {
    /// Stamp `_owner` on create.
    Auto,
    /// No ownership tracking.
    None,
}

impl std::fmt::Display for OwnerMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OwnerMode::Auto => write!(f, "auto"),
            OwnerMode::None => write!(f, "none"),
        }
    }
}

/// Result of a mutation authorization check.
#[derive(Debug, Clone, PartialEq)]
pub enum Decision {
    /// The mutation is allowed.
    Allow,
    /// Allowed only because the record predates ownership (implicit policy,
    /// unowned record) — callers should warn in dev mode.
    AllowLegacy,
    /// The mutation is denied.
    Deny,
}

/// The read scope to apply to a fetch for a collection.
#[derive(Debug, Clone, PartialEq)]
pub enum ReadScope {
    /// No restriction.
    All,
    /// No matching identity — return nothing.
    Deny,
    /// Filter expressions to AND into the query (each is the filter
    /// mini-language: comma = OR, `&` = AND).
    Filters(Vec<String>),
}

/// Which write a mutation performs.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MutationKind {
    Update,
    Delete,
}

/// A compiled collection policy.
#[derive(Debug, Clone)]
pub struct CollectionPolicy {
    pub owner_mode: OwnerMode,
    pub create: Rule,
    pub update: Rule,
    pub delete: Rule,
    pub read: Rule,
    pub filter: Option<String>,
    pub readonly_fields: Vec<String>,
    pub private_fields: Vec<String>,
    /// Whether this policy was explicitly declared (vs the implicit default).
    pub explicit: bool,
}

impl Default for CollectionPolicy {
    /// The implicit owner-protected default for undeclared collections.
    fn default() -> Self {
        CollectionPolicy {
            owner_mode: OwnerMode::Auto,
            create: Rule::all(),
            update: Rule::owner(),
            delete: Rule::owner(),
            read: Rule::all(),
            filter: None,
            readonly_fields: Vec::new(),
            private_fields: Vec::new(),
            explicit: false,
        }
    }
}

impl CollectionPolicy {
    /// Compile a raw config entry for collection `name`.
    fn compile(name: &str, cfg: &CollectionPolicyConfig) -> Result<Self> {
        let owner_mode = match cfg.owner.as_deref() {
            None | Some("auto") => OwnerMode::Auto,
            Some("none") => OwnerMode::None,
            Some(other) => {
                return Err(Error::Config(format!(
                    "collections.{name}.owner: expected \"auto\" or \"none\", got \"{other}\""
                )));
            }
        };

        let create = match &cfg.create {
            Some(s) => Rule::parse(s, &format!("collections.{name}.create"), false)?,
            None => Rule::all(),
        };
        let update = match &cfg.update {
            Some(s) => Rule::parse(s, &format!("collections.{name}.update"), true)?,
            None => Rule::owner(),
        };
        let delete = match &cfg.delete {
            Some(s) => Rule::parse(s, &format!("collections.{name}.delete"), true)?,
            None => Rule::owner(),
        };
        let read = match &cfg.read {
            Some(s) => Rule::parse(s, &format!("collections.{name}.read"), true)?,
            None => Rule::all(),
        };

        Ok(CollectionPolicy {
            owner_mode,
            create,
            update,
            delete,
            read,
            filter: cfg.filter.clone().filter(|f| !f.trim().is_empty()),
            readonly_fields: cfg.fields.readonly.clone(),
            private_fields: cfg.fields.private.clone(),
            explicit: true,
        })
    }

    fn mutation_rule(&self, kind: MutationKind) -> &Rule {
        match kind {
            MutationKind::Update => &self.update,
            MutationKind::Delete => &self.delete,
        }
    }

    /// Whether reads of this collection are restricted in any way.
    pub fn is_read_scoped(&self) -> bool {
        !self.read.is_all() || self.filter.is_some()
    }

    /// Authorize a create.
    pub fn allows_create(&self, actor: &Actor) -> bool {
        self.create.non_owner_match(actor)
    }

    /// Authorize an update/delete against the existing record.
    ///
    /// `resolved_filter` is the tenant filter with `#var#` already resolved; if
    /// present, the record must also satisfy it (otherwise a tenant could mutate
    /// another tenant's row by guessing its id).
    pub fn allows_mutation(
        &self,
        actor: &Actor,
        record: Option<&Value>,
        kind: MutationKind,
        resolved_filter: Option<&str>,
    ) -> Decision {
        // A missing record makes the mutation a safe no-op.
        let Some(record) = record else {
            return Decision::Allow;
        };

        // Tenant scope: the record must be inside the actor's tenant.
        if let Some(filter) = resolved_filter {
            if !record_matches_filter(record, filter) {
                return Decision::Deny;
            }
        }

        let rule = self.mutation_rule(kind);

        // Non-owner terms (all/user/role) grant access regardless of ownership.
        if rule.non_owner_match(actor) {
            return Decision::Allow;
        }

        if rule.has_owner() {
            let record_owner = record.get("_owner").and_then(|v| v.as_str());
            match record_owner {
                Some(owner) if actor.owner_keys().iter().any(|k| k == owner) => {
                    return Decision::Allow;
                }
                None => {
                    // Unowned record: legacy-modifiable only under the implicit
                    // default; explicit policies stay strict.
                    if !self.explicit {
                        return Decision::AllowLegacy;
                    }
                }
                Some(_) => {}
            }
        }

        Decision::Deny
    }

    /// Compute the read scope for `actor`. `filter_ctx` supplies `#var#` values
    /// (user/session) for the tenant filter.
    pub fn read_scope(&self, actor: &Actor, filter_ctx: &HashMap<String, Value>) -> ReadScope {
        let mut filters: Vec<String> = Vec::new();

        // Tenant filter (fail closed if any #var# is unresolved).
        if let Some(raw) = &self.filter {
            let resolved = crate::parser::replace_variables(raw, filter_ctx);
            if resolved.contains('#') {
                return ReadScope::Deny;
            }
            filters.push(resolved);
        }

        if self.read.is_all() {
            return if filters.is_empty() {
                ReadScope::All
            } else {
                ReadScope::Filters(filters)
            };
        }

        // A non-owner term (user/role) grants the full row-set (subject to the
        // tenant filter above).
        if self.read.non_owner_match(actor) {
            return if filters.is_empty() {
                ReadScope::All
            } else {
                ReadScope::Filters(filters)
            };
        }

        // Owner scope: restrict to the actor's own records.
        if self.read.has_owner() {
            let keys = actor.owner_keys();
            if keys.is_empty() {
                return ReadScope::Deny;
            }
            // Comma = OR in the filter mini-language.
            let owner_or = keys
                .iter()
                .map(|k| format!("_owner={k}"))
                .collect::<Vec<_>>()
                .join(",");
            filters.push(owner_or);
            return ReadScope::Filters(filters);
        }

        // No term matched (e.g. read = "none", or role rule with no match).
        ReadScope::Deny
    }

    /// The resolved tenant filter for mutation checks, or None.
    pub fn resolved_filter(&self, filter_ctx: &HashMap<String, Value>) -> Option<String> {
        let raw = self.filter.as_ref()?;
        let resolved = crate::parser::replace_variables(raw, filter_ctx);
        if resolved.contains('#') {
            // Unresolved — treat as "matches nothing" by returning a filter no
            // record satisfies. Callers use this only for mutation gating.
            return Some("_owner=\u{0}__unresolved__".to_string());
        }
        Some(resolved)
    }

    /// Stamp `_owner` into a new record's field map (create only).
    pub fn stamp_owner(&self, map: &mut Map<String, Value>, actor: &Actor) {
        if self.owner_mode == OwnerMode::None {
            return;
        }
        if let Some(key) = actor.primary_owner_key() {
            map.insert("_owner".to_string(), Value::String(key));
        }
    }

    /// Remove client-supplied values the server manages: the `_owner` field
    /// (never trust it from input) and any `fields.readonly`.
    pub fn sanitize_input(&self, map: &mut Map<String, Value>) {
        map.remove("_owner");
        for field in &self.readonly_fields {
            map.remove(field);
        }
    }
}

/// Registry of compiled collection policies, keyed by collection name.
#[derive(Debug, Clone)]
pub struct PolicyRegistry {
    map: HashMap<String, CollectionPolicy>,
    default_policy: CollectionPolicy,
}

impl PolicyRegistry {
    /// Compile all policies from config, failing loud on any semantic error.
    pub fn from_config(cfg: &HashMap<String, CollectionPolicyConfig>) -> Result<Self> {
        let mut map = HashMap::new();
        for (name, entry) in cfg {
            map.insert(name.clone(), CollectionPolicy::compile(name, entry)?);
        }
        Ok(PolicyRegistry {
            map,
            default_policy: CollectionPolicy::default(),
        })
    }

    /// An empty registry (all collections get the implicit default).
    pub fn empty() -> Self {
        PolicyRegistry {
            map: HashMap::new(),
            default_policy: CollectionPolicy::default(),
        }
    }

    /// Look up a collection's policy, falling back to the implicit default.
    pub fn get(&self, collection: &str) -> &CollectionPolicy {
        self.map.get(collection).unwrap_or(&self.default_policy)
    }

    /// Iterate over explicitly configured collections.
    pub fn configured(&self) -> impl Iterator<Item = (&str, &CollectionPolicy)> {
        self.map.iter().map(|(k, v)| (k.as_str(), v))
    }

    /// Whether reads of this collection are scoped (used to scrub base context).
    pub fn is_read_scoped(&self, collection: &str) -> bool {
        self.get(collection).is_read_scoped()
    }
}

/// The acting principal for a request.
#[derive(Debug, Clone)]
pub struct Actor {
    pub authenticated: bool,
    pub user_sub: Option<String>,
    pub roles: Vec<String>,
    /// `session:<hash>` owner key for anonymous ownership.
    pub session_key: Option<String>,
}

impl Actor {
    /// An anonymous actor (no session, no auth).
    pub fn anonymous() -> Actor {
        Actor {
            authenticated: false,
            user_sub: None,
            roles: Vec::new(),
            session_key: None,
        }
    }

    /// Build an actor from the request's user context and session.
    pub fn from_parts(user: &UserContext, session: Option<&Session>) -> Actor {
        let user_sub = if user.authenticated {
            match user.sub() {
                // Filter mini-language metacharacters would corrupt owner
                // filters — skip the user key and let session ownership stand.
                Some(s) if s.contains([',', '&', '=', '<', '>']) => {
                    tracing::warn!(
                        target: "what::policy",
                        "user sub contains filter metacharacters; skipping user ownership key"
                    );
                    None
                }
                other => other,
            }
        } else {
            None
        };
        let session_key = session.map(|s| format!("session:{}", &s.id[..s.id.len().min(32)]));
        Actor {
            authenticated: user.authenticated,
            user_sub,
            roles: if user.authenticated { user.roles() } else { Vec::new() },
            session_key,
        }
    }

    /// All owner keys this actor can claim (`user:<sub>` and/or `session:<hash>`).
    pub fn owner_keys(&self) -> Vec<String> {
        let mut keys = Vec::new();
        if let Some(sub) = &self.user_sub {
            keys.push(format!("user:{sub}"));
        }
        if let Some(sk) = &self.session_key {
            keys.push(sk.clone());
        }
        keys
    }

    /// The key used to stamp new records: the user key if authenticated, else
    /// the session key.
    pub fn primary_owner_key(&self) -> Option<String> {
        if let Some(sub) = &self.user_sub {
            return Some(format!("user:{sub}"));
        }
        self.session_key.clone()
    }
}

/// Strip `fields.private` from a JSON array of records (or a single record).
pub fn strip_private_fields(items: &mut Value, private: &[String]) {
    if private.is_empty() {
        return;
    }
    match items {
        Value::Array(arr) => {
            for item in arr.iter_mut() {
                if let Value::Object(map) = item {
                    for f in private {
                        map.remove(f);
                    }
                }
            }
        }
        Value::Object(map) => {
            for f in private {
                map.remove(f);
            }
        }
        _ => {}
    }
}

/// Scrub the base template context (built from the entire store): drop any
/// read-scoped collection entirely (fetch directives re-add it scoped) and
/// strip private fields from the rest. Collections with the implicit default
/// (read = "all", no private fields) are untouched.
pub fn scrub_base_context(reg: &PolicyRegistry, ctx: &mut HashMap<String, Value>) {
    for (name, policy) in reg.configured() {
        if policy.is_read_scoped() {
            ctx.remove(name);
        } else if !policy.private_fields.is_empty() {
            if let Some(v) = ctx.get_mut(name) {
                strip_private_fields(v, &policy.private_fields);
            }
        }
    }
}

/// Evaluate a record against a filter expression, mirroring the SQL builder's
/// semantics exactly (comma = OR groups, `&` = AND within a group, ops
/// `>= <= > < =`). Used to enforce tenant scoping on mutations by id.
pub fn record_matches_filter(record: &Value, filter_expr: &str) -> bool {
    let obj = match record {
        Value::Object(m) => m,
        _ => return false,
    };

    // OR across comma-separated groups.
    for group in filter_expr.split(',') {
        if group.trim().is_empty() {
            continue;
        }
        let mut group_ok = true;
        for cond in group.split('&') {
            let cond = cond.trim();
            if cond.is_empty() {
                continue;
            }
            if !eval_condition(obj, cond) {
                group_ok = false;
                break;
            }
        }
        if group_ok {
            return true;
        }
    }
    false
}

fn eval_condition(obj: &Map<String, Value>, cond: &str) -> bool {
    // Order matters: check two-char ops before single-char.
    for (op, is_ge, is_le, is_gt, is_lt, is_eq) in [
        (">=", true, false, false, false, false),
        ("<=", false, true, false, false, false),
        (">", false, false, true, false, false),
        ("<", false, false, false, true, false),
        ("=", false, false, false, false, true),
    ] {
        if let Some((field, val)) = cond.split_once(op) {
            let field = field.trim();
            let val = val.trim();
            let actual = obj.get(field);
            let actual_str = actual.map(value_to_string).unwrap_or_default();

            // Try numeric comparison first, fall back to string.
            let (an, vn) = (actual_str.parse::<f64>(), val.parse::<f64>());
            return if let (Ok(a), Ok(v)) = (an, vn) {
                if is_ge {
                    a >= v
                } else if is_le {
                    a <= v
                } else if is_gt {
                    a > v
                } else if is_lt {
                    a < v
                } else {
                    a == v
                }
            } else if is_eq {
                actual_str == val
            } else if is_ge {
                actual_str >= val.to_string()
            } else if is_le {
                actual_str <= val.to_string()
            } else if is_gt {
                actual_str > val.to_string()
            } else {
                actual_str < val.to_string()
            };
        }
    }
    false
}

fn value_to_string(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        Value::Number(n) => n.to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Null => String::new(),
        other => other.to_string(),
    }
}

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

    fn cfg(f: impl FnOnce(&mut CollectionPolicyConfig)) -> CollectionPolicyConfig {
        let mut c = CollectionPolicyConfig::default();
        f(&mut c);
        c
    }

    fn user_actor(sub: &str, roles: &[&str]) -> Actor {
        Actor {
            authenticated: true,
            user_sub: Some(sub.to_string()),
            roles: roles.iter().map(|s| s.to_string()).collect(),
            session_key: None,
        }
    }

    fn session_actor(id: &str) -> Actor {
        Actor {
            authenticated: false,
            user_sub: None,
            roles: Vec::new(),
            session_key: Some(format!("session:{id}")),
        }
    }

    #[test]
    fn rule_parse_basic() {
        assert!(Rule::parse("all", "x", true).unwrap().is_all());
        assert_eq!(
            Rule::parse("owner, admin", "x", true).unwrap().terms,
            vec![RuleTerm::Owner, RuleTerm::Role("admin".into())]
        );
        assert_eq!(
            Rule::parse("editor,admin", "x", false).unwrap().terms,
            vec![RuleTerm::Role("editor".into()), RuleTerm::Role("admin".into())]
        );
    }

    #[test]
    fn rule_parse_failures() {
        assert!(Rule::parse("owner", "collections.x.create", false).is_err());
        assert!(Rule::parse("all, admin", "x", true).is_err());
        assert!(Rule::parse("none, user", "x", true).is_err());
        assert!(Rule::parse("", "x", true).is_err());
    }

    #[test]
    fn default_policy_is_owner_protected() {
        let p = CollectionPolicy::default();
        assert!(p.create.is_all());
        assert_eq!(p.update, Rule::owner());
        assert_eq!(p.delete, Rule::owner());
        assert!(p.read.is_all());
        assert!(!p.explicit);
        assert!(!p.is_read_scoped());
    }

    #[test]
    fn create_authorization() {
        let p = CollectionPolicy::compile("notes", &cfg(|c| c.create = Some("user".into()))).unwrap();
        assert!(!p.allows_create(&Actor::anonymous()));
        assert!(p.allows_create(&user_actor("alice", &[])));

        let roles = CollectionPolicy::compile("a", &cfg(|c| c.create = Some("editor".into()))).unwrap();
        assert!(!roles.allows_create(&user_actor("bob", &[])));
        assert!(roles.allows_create(&user_actor("bob", &["editor"])));
    }

    #[test]
    fn update_owner_matching() {
        let p = CollectionPolicy::default(); // update = owner, implicit
        let rec = json!({"_owner": "user:alice", "title": "x"});
        assert_eq!(
            p.allows_mutation(&user_actor("alice", &[]), Some(&rec), MutationKind::Update, None),
            Decision::Allow
        );
        assert_eq!(
            p.allows_mutation(&user_actor("bob", &[]), Some(&rec), MutationKind::Update, None),
            Decision::Deny
        );
    }

    #[test]
    fn legacy_unowned_record() {
        let implicit = CollectionPolicy::default();
        let rec = json!({"title": "no owner"});
        assert_eq!(
            implicit.allows_mutation(&Actor::anonymous(), Some(&rec), MutationKind::Delete, None),
            Decision::AllowLegacy
        );

        // Explicit policy stays strict.
        let explicit = CollectionPolicy::compile("n", &cfg(|c| c.update = Some("owner".into()))).unwrap();
        assert_eq!(
            explicit.allows_mutation(&session_actor("abc"), Some(&rec), MutationKind::Update, None),
            Decision::Deny
        );
    }

    #[test]
    fn missing_record_is_safe_noop() {
        let p = CollectionPolicy::default();
        assert_eq!(
            p.allows_mutation(&Actor::anonymous(), None, MutationKind::Delete, None),
            Decision::Allow
        );
    }

    #[test]
    fn role_delete_rule() {
        let p = CollectionPolicy::compile("n", &cfg(|c| c.delete = Some("owner, admin".into()))).unwrap();
        let rec = json!({"_owner": "user:alice"});
        // Non-owner admin passes.
        assert_eq!(
            p.allows_mutation(&user_actor("carol", &["admin"]), Some(&rec), MutationKind::Delete, None),
            Decision::Allow
        );
        // Non-owner non-admin denied.
        assert_eq!(
            p.allows_mutation(&user_actor("carol", &[]), Some(&rec), MutationKind::Delete, None),
            Decision::Deny
        );
    }

    #[test]
    fn tenant_filter_gates_mutation() {
        let p = CollectionPolicy::compile("n", &cfg(|c| {
            c.filter = Some("org=acme".into());
            c.update = Some("user".into());
        })).unwrap();
        let mine = json!({"org": "acme"});
        let theirs = json!({"org": "other"});
        assert_eq!(
            p.allows_mutation(&user_actor("a", &[]), Some(&mine), MutationKind::Update, Some("org=acme")),
            Decision::Allow
        );
        assert_eq!(
            p.allows_mutation(&user_actor("a", &[]), Some(&theirs), MutationKind::Update, Some("org=acme")),
            Decision::Deny
        );
    }

    #[test]
    fn read_scope_permutations() {
        let empty = HashMap::new();

        // read = all
        assert_eq!(CollectionPolicy::default().read_scope(&Actor::anonymous(), &empty), ReadScope::All);

        // read = owner, has session
        let owner_read = CollectionPolicy::compile("n", &cfg(|c| c.read = Some("owner".into()))).unwrap();
        match owner_read.read_scope(&session_actor("abc"), &empty) {
            ReadScope::Filters(f) => assert_eq!(f, vec!["_owner=session:abc".to_string()]),
            other => panic!("expected filters, got {other:?}"),
        }

        // read = owner, no identity → deny
        assert_eq!(owner_read.read_scope(&Actor::anonymous(), &empty), ReadScope::Deny);

        // read = user, authenticated → all
        let user_read = CollectionPolicy::compile("n", &cfg(|c| c.read = Some("user".into()))).unwrap();
        assert_eq!(user_read.read_scope(&user_actor("a", &[]), &empty), ReadScope::All);
        assert_eq!(user_read.read_scope(&Actor::anonymous(), &empty), ReadScope::Deny);
    }

    #[test]
    fn read_scope_tenant_filter() {
        let mut ctx = HashMap::new();
        ctx.insert("user".to_string(), json!({"org_id": "acme"}));
        let p = CollectionPolicy::compile("n", &cfg(|c| c.filter = Some("org_id=#user.org_id#".into()))).unwrap();
        match p.read_scope(&user_actor("a", &[]), &ctx) {
            ReadScope::Filters(f) => assert_eq!(f, vec!["org_id=acme".to_string()]),
            other => panic!("expected filters, got {other:?}"),
        }
        // Unresolved var → deny.
        assert_eq!(p.read_scope(&user_actor("a", &[]), &HashMap::new()), ReadScope::Deny);
    }

    #[test]
    fn owner_and_tenant_combine() {
        let mut ctx = HashMap::new();
        ctx.insert("user".to_string(), json!({"org_id": "acme"}));
        let p = CollectionPolicy::compile("n", &cfg(|c| {
            c.read = Some("owner".into());
            c.filter = Some("org_id=#user.org_id#".into());
        })).unwrap();
        let actor = user_actor("alice", &[]);
        match p.read_scope(&actor, &ctx) {
            ReadScope::Filters(f) => {
                assert_eq!(f, vec!["org_id=acme".to_string(), "_owner=user:alice".to_string()]);
            }
            other => panic!("expected filters, got {other:?}"),
        }
    }

    #[test]
    fn stamp_and_sanitize() {
        let p = CollectionPolicy::compile("n", &cfg(|c| c.fields.readonly = vec!["price".into()])).unwrap();
        let mut map = Map::new();
        map.insert("title".into(), json!("hi"));
        map.insert("_owner".into(), json!("user:evil")); // spoof attempt
        map.insert("price".into(), json!("0")); // readonly
        p.sanitize_input(&mut map);
        assert!(!map.contains_key("_owner"));
        assert!(!map.contains_key("price"));

        p.stamp_owner(&mut map, &user_actor("alice", &[]));
        assert_eq!(map.get("_owner"), Some(&json!("user:alice")));
    }

    #[test]
    fn owner_mode_none_skips_stamp() {
        let p = CollectionPolicy::compile("n", &cfg(|c| c.owner = Some("none".into()))).unwrap();
        let mut map = Map::new();
        p.stamp_owner(&mut map, &user_actor("alice", &[]));
        assert!(!map.contains_key("_owner"));
    }

    #[test]
    fn actor_owner_keys() {
        let both = Actor {
            authenticated: true,
            user_sub: Some("alice".into()),
            roles: vec![],
            session_key: Some("session:abc".into()),
        };
        assert_eq!(both.owner_keys(), vec!["user:alice", "session:abc"]);
        assert_eq!(both.primary_owner_key(), Some("user:alice".into()));
        assert_eq!(session_actor("abc").primary_owner_key(), Some("session:abc".into()));
    }

    #[test]
    fn record_matches_filter_parity() {
        let rec = json!({"org": "acme", "count": 5});
        assert!(record_matches_filter(&rec, "org=acme"));
        assert!(!record_matches_filter(&rec, "org=other"));
        assert!(record_matches_filter(&rec, "count>=5"));
        assert!(record_matches_filter(&rec, "count>3"));
        assert!(!record_matches_filter(&rec, "count>5"));
        // OR groups
        assert!(record_matches_filter(&rec, "org=other,org=acme"));
        // AND within group
        assert!(record_matches_filter(&rec, "org=acme&count=5"));
        assert!(!record_matches_filter(&rec, "org=acme&count=9"));
    }

    #[test]
    fn strip_private() {
        let mut items = json!([{"email": "a@x.com", "name": "A"}, {"email": "b@x.com", "name": "B"}]);
        strip_private_fields(&mut items, &["email".to_string()]);
        assert_eq!(items, json!([{"name": "A"}, {"name": "B"}]));
    }

    #[test]
    fn registry_defaults_and_lookup() {
        let mut cfg_map = HashMap::new();
        cfg_map.insert("notes".to_string(), cfg(|c| c.read = Some("owner".into())));
        let reg = PolicyRegistry::from_config(&cfg_map).unwrap();
        assert!(reg.get("notes").explicit);
        assert!(reg.is_read_scoped("notes"));
        // Unknown collection → implicit default.
        assert!(!reg.get("other").explicit);
        assert!(!reg.is_read_scoped("other"));
    }

    #[test]
    fn registry_fails_loud() {
        let mut cfg_map = HashMap::new();
        cfg_map.insert("bad".to_string(), cfg(|c| c.create = Some("owner".into())));
        assert!(PolicyRegistry::from_config(&cfg_map).is_err());
    }

    #[test]
    fn scrub_base_context_drops_scoped() {
        let mut cfg_map = HashMap::new();
        cfg_map.insert("secret".to_string(), cfg(|c| c.read = Some("owner".into())));
        cfg_map.insert("public".to_string(), cfg(|c| c.fields.private = vec!["ssn".into()]));
        let reg = PolicyRegistry::from_config(&cfg_map).unwrap();

        let mut ctx = HashMap::new();
        ctx.insert("secret".to_string(), json!([{"x": 1}]));
        ctx.insert("public".to_string(), json!([{"name": "A", "ssn": "123"}]));
        ctx.insert("open".to_string(), json!([{"y": 2}]));

        scrub_base_context(&reg, &mut ctx);
        assert!(!ctx.contains_key("secret"));
        assert_eq!(ctx.get("public"), Some(&json!([{"name": "A"}])));
        assert_eq!(ctx.get("open"), Some(&json!([{"y": 2}])));
    }
}