reddb-io-server 1.7.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
//! Managed policy guardrail (#646).
//!
//! Companion to [`super::managed_config::ManagedConfigGate`]. Guards
//! mutations of IAM policy documents that the operator has marked
//! `managed=true` in [`super::registry::ConfigRegistry`] under a
//! `resource_type` of [`RESOURCE_TYPE_POLICY`].
//!
//! The gate sits in front of the four ordinary policy-mutation paths
//! (`put_policy`, `delete_policy`, `attach_policy`, `detach_policy`).
//! Given the policy id the caller is about to mutate, plus the
//! operation kind, it looks the id up in the registry and:
//!
//! * If no entry matches, or the matched entry is **not** managed,
//!   returns [`ManagedPolicyDecision::PassThrough`] — ordinary IAM
//!   rules govern the mutation (criterion #1 baseline: ordinary
//!   policies remain mutable per ordinary policy).
//!
//! * If the matched entry is managed, enforces two layers in order:
//!     1. **Structural eligibility** — caller must be both system-owned
//!        and platform-scoped (the operator-principal shape). Otherwise
//!        [`ManagedPolicyDecision::Deny`] with
//!        [`DenyReason::NotStructurallyEligible`]. This is the layer
//!        that blocks ordinary allow-all admins from rewriting,
//!        dropping, or re-attaching a managed policy (criterion #2).
//!     2. **Policy permission** — caller must satisfy
//!        [`AuthStore::check_policy_authz`] against the operation's
//!        action and the entry's `required_resource`. Otherwise
//!        [`ManagedPolicyDecision::Deny`] with
//!        [`DenyReason::PolicyDenied`] (criterion #4: structurally
//!        eligible caller still needs policy permission).
//!
//! Because the `managed=true` bit lives in the registry — not in the
//! submitted Policy document — re-submitting a Policy JSON that omits
//! any "managed" hint cannot flip the entry off; the gate consults the
//! registry per call (criterion #3).
//!
//! Every Deny carries the matched entry id, version, op-derived action,
//! and required resource so the Control Event Ledger / audit hook can
//! persist the evidence (criterion #5). The matched action/resource
//! string mirrors what `check_policy_authz` would have evaluated, so an
//! investigator can replay the decision.

use super::policies::{EvalContext, ResourceRef};
use super::registry::{ConfigRegistry, ConfigRegistryEntry, EvidenceRequirement};
use super::store::AuthStore;
use super::UserId;

/// Resource-type tag a registry entry must carry to govern a policy id.
/// Entries of any other `resource_type` are ignored by this gate even if
/// their id collides with a policy id — those entries describe other
/// governance surfaces (config keys, vault paths, audit) and must not
/// silently gate policy mutations.
pub const RESOURCE_TYPE_POLICY: &str = "policy";

/// Which mutation the caller is attempting on a (possibly-managed)
/// policy id. The gate uses this to derive the policy action it asks
/// the IAM evaluator about.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PolicyOp {
    /// `put_policy` — install or replace the document.
    Put,
    /// `delete_policy` — remove the document and its attachments.
    Drop,
    /// `attach_policy` — bind the policy to a user or group.
    Attach,
    /// `detach_policy` — unbind the policy from a user or group.
    Detach,
}

impl PolicyOp {
    /// IAM action verb the gate evaluates for this op against the
    /// managed policy's `required_resource`. Matches the verbs already
    /// in `ACTION_ALLOWLIST` (see `policies.rs`).
    pub fn action(self) -> &'static str {
        match self {
            Self::Put => "policy:put",
            Self::Drop => "policy:drop",
            Self::Attach => "policy:attach",
            Self::Detach => "policy:detach",
        }
    }
}

/// Outcome of a managed-policy mutation check.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ManagedPolicyDecision {
    /// Policy id is not governed by a managed registry entry. Caller
    /// should proceed with ordinary IAM checks.
    PassThrough { policy_id: String, op: PolicyOp },
    /// Policy is managed and the caller satisfied both the structural
    /// and policy gates. Caller may proceed; the returned evidence
    /// requirement tells the Control Event Ledger how much detail to
    /// persist.
    Allow {
        entry_id: String,
        entry_version: u64,
        op: PolicyOp,
        matched_action: String,
        matched_resource: String,
        evidence: EvidenceRequirement,
    },
    /// Policy is managed and the caller failed one of the gates.
    /// Carries enough metadata for Control Event / audit emission.
    Deny {
        entry_id: String,
        entry_version: u64,
        op: PolicyOp,
        matched_action: String,
        matched_resource: String,
        reason: DenyReason,
    },
}

/// Why a managed policy mutation was denied. Designed for Control Event
/// payloads: the variant tells operators what *kind* of guard tripped,
/// and the structured fields let them see which eligibility flag was
/// false.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DenyReason {
    /// Caller is not the operator-principal shape required by managed
    /// guardrails (must be both system-owned and platform-scoped).
    NotStructurallyEligible {
        is_system_owned: bool,
        is_platform_scoped: bool,
    },
    /// Caller is structurally eligible but the policy evaluator rejected
    /// the op-derived action / required-resource pair (either explicit
    /// Deny or DefaultDeny).
    PolicyDenied,
}

impl std::fmt::Display for DenyReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotStructurallyEligible {
                is_system_owned,
                is_platform_scoped,
            } => write!(
                f,
                "caller is not structurally eligible for managed policy \
                 (system_owned={is_system_owned}, platform_scoped={is_platform_scoped})"
            ),
            Self::PolicyDenied => {
                write!(f, "managed policy required IAM permission was denied")
            }
        }
    }
}

impl ManagedPolicyDecision {
    /// Convenience: did this decision permit the mutation (PassThrough
    /// or Allow)?
    pub fn permitted(&self) -> bool {
        matches!(self, Self::PassThrough { .. } | Self::Allow { .. })
    }
}

/// Stateless guard wrapping a [`ConfigRegistry`] reference.
pub struct ManagedPolicyGate<'a> {
    registry: &'a ConfigRegistry,
}

impl<'a> ManagedPolicyGate<'a> {
    pub fn new(registry: &'a ConfigRegistry) -> Self {
        Self { registry }
    }

    /// Evaluate `op` on `policy_id` for `actor`. Returns one of the
    /// three [`ManagedPolicyDecision`] variants — see the module docs
    /// for the decision rules.
    pub fn check_mutation(
        &self,
        auth: &AuthStore,
        actor: &UserId,
        ctx: &EvalContext,
        policy_id: &str,
        op: PolicyOp,
    ) -> ManagedPolicyDecision {
        let Some(entry) = self.lookup_governing_entry(policy_id) else {
            return ManagedPolicyDecision::PassThrough {
                policy_id: policy_id.to_string(),
                op,
            };
        };
        if !entry.managed {
            return ManagedPolicyDecision::PassThrough {
                policy_id: policy_id.to_string(),
                op,
            };
        }

        let (kind, name) = split_required_resource(&entry.required_resource, policy_id);
        let matched_resource = format!("{kind}:{name}");
        let matched_action = op.action().to_string();

        if !(ctx.principal_is_system_owned && ctx.principal_is_platform_scoped) {
            return ManagedPolicyDecision::Deny {
                entry_id: entry.id.clone(),
                entry_version: entry.version,
                op,
                matched_action,
                matched_resource,
                reason: DenyReason::NotStructurallyEligible {
                    is_system_owned: ctx.principal_is_system_owned,
                    is_platform_scoped: ctx.principal_is_platform_scoped,
                },
            };
        }

        let resource = ResourceRef::new(kind, name);
        if !auth.check_policy_authz(actor, op.action(), &resource, ctx) {
            return ManagedPolicyDecision::Deny {
                entry_id: entry.id.clone(),
                entry_version: entry.version,
                op,
                matched_action,
                matched_resource,
                reason: DenyReason::PolicyDenied,
            };
        }

        ManagedPolicyDecision::Allow {
            entry_id: entry.id,
            entry_version: entry.version,
            op,
            matched_action,
            matched_resource,
            evidence: entry.evidence_requirement,
        }
    }

    /// Registry entry governing `policy_id` — exact id match against an
    /// entry whose `resource_type` is [`RESOURCE_TYPE_POLICY`]. There is
    /// no namespace fallback for policies (unlike config keys): policy
    /// ids are flat, not dotted, so a "most-specific" walk has nothing
    /// to climb.
    fn lookup_governing_entry(&self, policy_id: &str) -> Option<ConfigRegistryEntry> {
        let e = self.registry.get_active(policy_id)?;
        if e.resource_type == RESOURCE_TYPE_POLICY {
            Some(e)
        } else {
            None
        }
    }
}

/// Split `"kind:name"` from a registry entry's `required_resource`.
/// Falls back to `("policy", policy_id)` when the colon is absent so
/// older entries that just stored a bare policy id still produce a
/// well-formed [`ResourceRef`] aligned with the policy id under
/// evaluation.
fn split_required_resource<'a>(s: &'a str, policy_id: &'a str) -> (&'a str, &'a str) {
    match s.split_once(':') {
        Some((k, n)) if !k.is_empty() => (k, n),
        _ => ("policy", policy_id),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::policies::Policy;
    use crate::auth::registry::{ConfigRegistryDraft, Mutability, Sensitivity};
    use crate::auth::store::PrincipalRef;
    use crate::auth::{AuthConfig, Role};
    use std::sync::Arc;

    fn store() -> Arc<AuthStore> {
        Arc::new(AuthStore::new(AuthConfig::default()))
    }

    fn registry_admin_ctx() -> EvalContext {
        EvalContext {
            principal_tenant: None,
            current_tenant: None,
            peer_ip: None,
            mfa_present: false,
            now_ms: 1_700_000_000_000,
            principal_is_admin_role: true,
            principal_is_system_owned: false,
            principal_is_platform_scoped: true,
        }
    }

    fn allow_all_registry(id: &str) -> Policy {
        Policy::from_json_str(&format!(
            r#"{{
                "id": "{id}",
                "version": 1,
                "statements": [{{
                    "effect": "allow",
                    "actions": ["red.registry:*"],
                    "resources": ["registry:*"]
                }}]
            }}"#
        ))
        .unwrap()
    }

    fn allow_all_policies(id: &str) -> Policy {
        Policy::from_json_str(&format!(
            r#"{{
                "id": "{id}",
                "version": 1,
                "statements": [{{
                    "effect": "allow",
                    "actions": ["policy:*"],
                    "resources": ["*"]
                }}]
            }}"#
        ))
        .unwrap()
    }

    fn allow_policy_action(id: &str, action: &str, resource_glob: &str) -> Policy {
        Policy::from_json_str(&format!(
            r#"{{
                "id": "{id}",
                "version": 1,
                "statements": [{{
                    "effect": "allow",
                    "actions": ["{action}"],
                    "resources": ["{resource_glob}"]
                }}]
            }}"#
        ))
        .unwrap()
    }

    fn deny_policy_action(id: &str, action: &str, resource_glob: &str) -> Policy {
        Policy::from_json_str(&format!(
            r#"{{
                "id": "{id}",
                "version": 1,
                "statements": [{{
                    "effect": "deny",
                    "actions": ["{action}"],
                    "resources": ["{resource_glob}"]
                }}]
            }}"#
        ))
        .unwrap()
    }

    fn seed_registry_admin(store: &Arc<AuthStore>) -> UserId {
        store.create_user("seeder", "p", Role::Admin).unwrap();
        let uid = UserId::platform("seeder");
        store.put_policy(allow_all_registry("p-reg-allow")).unwrap();
        store
            .attach_policy(PrincipalRef::User(uid.clone()), "p-reg-allow")
            .unwrap();
        uid
    }

    fn managed_policy_draft(id: &str) -> ConfigRegistryDraft {
        ConfigRegistryDraft {
            id: id.to_string(),
            resource_type: RESOURCE_TYPE_POLICY.into(),
            schema: "iam-policy/v1".into(),
            mutability: Mutability::MutableViaGovernance,
            sensitivity: Sensitivity::Internal,
            managed: true,
            // For policy ops the gate derives the action from PolicyOp;
            // `required_action` is recorded for completeness but is not
            // what the evaluator is asked about.
            required_action: "policy:*".into(),
            required_resource: format!("policy:{id}"),
            evidence_requirement: EvidenceRequirement::Metadata,
        }
    }

    fn unmanaged_policy_draft(id: &str) -> ConfigRegistryDraft {
        let mut d = managed_policy_draft(id);
        d.managed = false;
        d
    }

    // ---- acceptance #1 ---------------------------------------------------

    #[test]
    fn policy_can_be_installed_as_managed_through_registry() {
        // Governance path is `ConfigRegistry::register` — gated by
        // `red.registry:register` on `registry:<id>`. The same surface
        // that pins managed configs also pins managed policies.
        let store = store();
        let seeder = seed_registry_admin(&store);
        let reg = ConfigRegistry::new();
        let entry = reg
            .register(
                &store,
                &seeder,
                &registry_admin_ctx(),
                managed_policy_draft("p-baseline-readonly"),
                1_000,
            )
            .expect("register");
        assert!(entry.managed);
        assert_eq!(entry.resource_type, RESOURCE_TYPE_POLICY);

        // Sanity: an unmanaged sibling registers with managed=false.
        let other = reg
            .register(
                &store,
                &seeder,
                &registry_admin_ctx(),
                unmanaged_policy_draft("p-tenant-custom"),
                1_000,
            )
            .unwrap();
        assert!(!other.managed);
    }

    // ---- acceptance #2 ---------------------------------------------------

    #[test]
    fn ordinary_allow_all_user_cannot_put_drop_attach_or_detach_managed_policy() {
        // alice@platform has `policy:*` on `*` — would normally let her
        // do anything to any policy. The managed gate must block all
        // four ops because she lacks the operator structural shape.
        let store = store();
        let seeder = seed_registry_admin(&store);
        store.create_user("alice", "p", Role::Admin).unwrap();
        let alice = UserId::platform("alice");
        store
            .put_policy(allow_all_policies("p-alice-allow"))
            .unwrap();
        store
            .attach_policy(PrincipalRef::User(alice.clone()), "p-alice-allow")
            .unwrap();

        let reg = ConfigRegistry::new();
        reg.register(
            &store,
            &seeder,
            &registry_admin_ctx(),
            managed_policy_draft("p-baseline-readonly"),
            1_000,
        )
        .unwrap();

        let gate = ManagedPolicyGate::new(&reg);
        let ctx = EvalContext {
            principal_tenant: None,
            current_tenant: None,
            peer_ip: None,
            mfa_present: false,
            now_ms: 1_700_000_000_001,
            principal_is_admin_role: true,
            principal_is_system_owned: false, // <-- the key gate
            principal_is_platform_scoped: true,
        };
        for op in [
            PolicyOp::Put,
            PolicyOp::Drop,
            PolicyOp::Attach,
            PolicyOp::Detach,
        ] {
            let decision = gate.check_mutation(&store, &alice, &ctx, "p-baseline-readonly", op);
            match decision {
                ManagedPolicyDecision::Deny {
                    entry_id,
                    matched_action,
                    matched_resource,
                    reason,
                    op: got_op,
                    ..
                } => {
                    assert_eq!(entry_id, "p-baseline-readonly");
                    assert_eq!(got_op, op);
                    assert_eq!(matched_action, op.action());
                    assert_eq!(matched_resource, "policy:p-baseline-readonly");
                    assert!(
                        matches!(
                            reason,
                            DenyReason::NotStructurallyEligible {
                                is_system_owned: false,
                                is_platform_scoped: true
                            }
                        ),
                        "op={op:?} got {reason:?}"
                    );
                }
                other => panic!("expected Deny for {op:?}, got {other:?}"),
            }
        }
    }

    // ---- acceptance #3 ---------------------------------------------------

    #[test]
    fn re_putting_managed_policy_without_managed_metadata_still_blocked() {
        // The "managed" bit lives in the registry, not in the policy
        // document. A caller who rewrites the policy JSON to omit any
        // managed hint must NOT thereby unlock the policy: the gate is
        // consulted per call against the registry entry, which still
        // says managed=true.
        let store = store();
        let seeder = seed_registry_admin(&store);
        store.create_user("alice", "p", Role::Admin).unwrap();
        let alice = UserId::platform("alice");
        store
            .put_policy(allow_all_policies("p-alice-allow"))
            .unwrap();
        store
            .attach_policy(PrincipalRef::User(alice.clone()), "p-alice-allow")
            .unwrap();

        let reg = ConfigRegistry::new();
        reg.register(
            &store,
            &seeder,
            &registry_admin_ctx(),
            managed_policy_draft("p-baseline-readonly"),
            1_000,
        )
        .unwrap();

        let gate = ManagedPolicyGate::new(&reg);
        let ctx = EvalContext {
            principal_tenant: None,
            current_tenant: None,
            peer_ip: None,
            mfa_present: false,
            now_ms: 1_700_000_000_002,
            principal_is_admin_role: true,
            principal_is_system_owned: false,
            principal_is_platform_scoped: true,
        };

        // First attempt — straightforward put — blocked.
        let d1 = gate.check_mutation(&store, &alice, &ctx, "p-baseline-readonly", PolicyOp::Put);
        assert!(matches!(d1, ManagedPolicyDecision::Deny { .. }), "{d1:?}");

        // Second attempt — caller "submits" a stripped policy doc; the
        // gate result is identical because it only consults the
        // registry. The registry entry stays managed at v1; no
        // supersede happened.
        let d2 = gate.check_mutation(&store, &alice, &ctx, "p-baseline-readonly", PolicyOp::Put);
        assert!(matches!(d2, ManagedPolicyDecision::Deny { .. }), "{d2:?}");

        assert_eq!(reg.get_active("p-baseline-readonly").unwrap().version, 1);
        assert!(reg.get_active("p-baseline-readonly").unwrap().managed);
    }

    // ---- acceptance #4 ---------------------------------------------------

    #[test]
    fn structurally_eligible_caller_with_matching_policy_is_allowed() {
        let store = store();
        let seeder = seed_registry_admin(&store);
        store
            .create_system_user("ops", "p", Role::Admin, None)
            .expect("create system-owned user");
        let ops = UserId::platform("ops");
        // Grant ops `policy:*` on the managed policy resource.
        store
            .put_policy(allow_policy_action(
                "p-ops-policy",
                "policy:*",
                "policy:p-baseline-readonly",
            ))
            .unwrap();
        store
            .attach_policy(PrincipalRef::User(ops.clone()), "p-ops-policy")
            .unwrap();

        let reg = ConfigRegistry::new();
        reg.register(
            &store,
            &seeder,
            &registry_admin_ctx(),
            managed_policy_draft("p-baseline-readonly"),
            1_000,
        )
        .unwrap();

        let gate = ManagedPolicyGate::new(&reg);
        let ctx = EvalContext {
            principal_tenant: None,
            current_tenant: None,
            peer_ip: None,
            mfa_present: false,
            now_ms: 1_700_000_000_003,
            principal_is_admin_role: true,
            principal_is_system_owned: true,
            principal_is_platform_scoped: true,
        };
        for op in [
            PolicyOp::Put,
            PolicyOp::Drop,
            PolicyOp::Attach,
            PolicyOp::Detach,
        ] {
            let decision = gate.check_mutation(&store, &ops, &ctx, "p-baseline-readonly", op);
            assert!(
                matches!(decision, ManagedPolicyDecision::Allow { .. }),
                "op={op:?} got {decision:?}"
            );
            assert!(decision.permitted());
        }
    }

    #[test]
    fn structurally_eligible_caller_without_matching_policy_is_policy_denied() {
        // Operator shape is right, but no allow grants the per-op
        // action on the managed policy — DefaultDeny falls out of the
        // evaluator.
        let store = store();
        let seeder = seed_registry_admin(&store);
        store
            .create_system_user("ops", "p", Role::Write, None)
            .unwrap();
        let ops = UserId::platform("ops");
        // Unrelated policy so the evaluator goes through IAM rather
        // than short-circuiting on "no policies".
        store
            .put_policy(
                Policy::from_json_str(
                    r#"{"id":"p-unrelated","version":1,"statements":[{"effect":"allow","actions":["select"],"resources":["table:public.x"]}]}"#,
                )
                .unwrap(),
            )
            .unwrap();
        store
            .attach_policy(PrincipalRef::User(ops.clone()), "p-unrelated")
            .unwrap();

        let reg = ConfigRegistry::new();
        reg.register(
            &store,
            &seeder,
            &registry_admin_ctx(),
            managed_policy_draft("p-baseline-readonly"),
            1_000,
        )
        .unwrap();

        let gate = ManagedPolicyGate::new(&reg);
        let ctx = EvalContext {
            principal_tenant: None,
            current_tenant: None,
            peer_ip: None,
            mfa_present: false,
            now_ms: 1_700_000_000_004,
            principal_is_admin_role: false,
            principal_is_system_owned: true,
            principal_is_platform_scoped: true,
        };
        let decision =
            gate.check_mutation(&store, &ops, &ctx, "p-baseline-readonly", PolicyOp::Put);
        match decision {
            ManagedPolicyDecision::Deny { reason, .. } => {
                assert!(matches!(reason, DenyReason::PolicyDenied), "got {reason:?}");
            }
            other => panic!("expected Deny(PolicyDenied), got {other:?}"),
        }
    }

    #[test]
    fn explicit_deny_overrides_structural_allow() {
        // System-owned operator with a broad policy-* allow *and* an
        // explicit deny on the managed policy resource — deny wins
        // (policy-first, per #644).
        let store = store();
        let seeder = seed_registry_admin(&store);
        store
            .create_system_user("ops", "p", Role::Admin, None)
            .unwrap();
        let ops = UserId::platform("ops");
        store.put_policy(allow_all_policies("p-allow")).unwrap();
        store
            .put_policy(deny_policy_action(
                "p-deny",
                "policy:put",
                "policy:p-baseline-readonly",
            ))
            .unwrap();
        store
            .attach_policy(PrincipalRef::User(ops.clone()), "p-allow")
            .unwrap();
        store
            .attach_policy(PrincipalRef::User(ops.clone()), "p-deny")
            .unwrap();

        let reg = ConfigRegistry::new();
        reg.register(
            &store,
            &seeder,
            &registry_admin_ctx(),
            managed_policy_draft("p-baseline-readonly"),
            1_000,
        )
        .unwrap();

        let gate = ManagedPolicyGate::new(&reg);
        let ctx = EvalContext {
            principal_tenant: None,
            current_tenant: None,
            peer_ip: None,
            mfa_present: false,
            now_ms: 1_700_000_000_005,
            principal_is_admin_role: true,
            principal_is_system_owned: true,
            principal_is_platform_scoped: true,
        };
        // The put op is explicitly denied → PolicyDenied even for the
        // structurally-eligible operator.
        let decision =
            gate.check_mutation(&store, &ops, &ctx, "p-baseline-readonly", PolicyOp::Put);
        match decision {
            ManagedPolicyDecision::Deny { reason, .. } => {
                assert!(matches!(reason, DenyReason::PolicyDenied), "got {reason:?}");
            }
            other => panic!("expected Deny(PolicyDenied), got {other:?}"),
        }
        // A different op (drop) is not covered by the deny, so the
        // broad allow still wins.
        let drop_decision =
            gate.check_mutation(&store, &ops, &ctx, "p-baseline-readonly", PolicyOp::Drop);
        assert!(
            matches!(drop_decision, ManagedPolicyDecision::Allow { .. }),
            "got {drop_decision:?}"
        );
    }

    // ---- acceptance #5 ---------------------------------------------------

    #[test]
    fn deny_carries_resource_and_reason_for_audit_hook() {
        // The Deny payload must give the audit hook / Control Event
        // integration enough detail to reconstruct what was attempted
        // and why it failed.
        let store = store();
        let seeder = seed_registry_admin(&store);
        store.create_user("alice", "p", Role::Admin).unwrap();
        let alice = UserId::platform("alice");

        let reg = ConfigRegistry::new();
        let mut draft = managed_policy_draft("p-tenant-isolation");
        draft.evidence_requirement = EvidenceRequirement::Full;
        reg.register(&store, &seeder, &registry_admin_ctx(), draft, 1_000)
            .unwrap();

        let gate = ManagedPolicyGate::new(&reg);
        let ctx = EvalContext {
            principal_tenant: None,
            current_tenant: None,
            peer_ip: None,
            mfa_present: false,
            now_ms: 1_700_000_000_006,
            principal_is_admin_role: true,
            principal_is_system_owned: false,
            principal_is_platform_scoped: true,
        };
        let decision =
            gate.check_mutation(&store, &alice, &ctx, "p-tenant-isolation", PolicyOp::Attach);
        match decision {
            ManagedPolicyDecision::Deny {
                entry_id,
                entry_version,
                op,
                matched_action,
                matched_resource,
                reason,
            } => {
                assert_eq!(entry_id, "p-tenant-isolation");
                assert_eq!(entry_version, 1);
                assert_eq!(op, PolicyOp::Attach);
                assert_eq!(matched_action, "policy:attach");
                assert_eq!(matched_resource, "policy:p-tenant-isolation");
                let rendered = reason.to_string();
                assert!(
                    rendered.contains("structurally eligible"),
                    "reason should be audit-renderable: {rendered}"
                );
            }
            other => panic!("expected Deny, got {other:?}"),
        }
    }

    // ---- passthrough / resource-type discipline -------------------------

    #[test]
    fn unmanaged_policy_passes_through() {
        // Registry has an entry but managed=false — the gate must not
        // interfere with ordinary IAM rules.
        let store = store();
        let seeder = seed_registry_admin(&store);
        let reg = ConfigRegistry::new();
        reg.register(
            &store,
            &seeder,
            &registry_admin_ctx(),
            unmanaged_policy_draft("p-tenant-custom"),
            1_000,
        )
        .unwrap();

        let gate = ManagedPolicyGate::new(&reg);
        let alice = UserId::platform("alice");
        let d = gate.check_mutation(
            &store,
            &alice,
            &EvalContext::default(),
            "p-tenant-custom",
            PolicyOp::Put,
        );
        assert!(matches!(d, ManagedPolicyDecision::PassThrough { .. }));
        assert!(d.permitted());
    }

    #[test]
    fn unknown_policy_passes_through() {
        let store = store();
        let _ = seed_registry_admin(&store);
        let reg = ConfigRegistry::new();
        let gate = ManagedPolicyGate::new(&reg);
        let alice = UserId::platform("alice");
        let d = gate.check_mutation(
            &store,
            &alice,
            &EvalContext::default(),
            "p-anything",
            PolicyOp::Drop,
        );
        assert!(matches!(d, ManagedPolicyDecision::PassThrough { .. }));
    }

    #[test]
    fn entry_with_unrelated_resource_type_does_not_gate_policy_mutations() {
        // Pin the contract: a registry entry whose `resource_type` is
        // not `policy` (e.g. `config_key` reusing a name that collides
        // with a policy id) must not silently fire the policy gate.
        let store = store();
        let seeder = seed_registry_admin(&store);
        let reg = ConfigRegistry::new();
        let mut d = managed_policy_draft("p-baseline-readonly");
        d.resource_type = "config_key".into();
        reg.register(&store, &seeder, &registry_admin_ctx(), d, 1_000)
            .unwrap();

        let gate = ManagedPolicyGate::new(&reg);
        let alice = UserId::platform("alice");
        let dec = gate.check_mutation(
            &store,
            &alice,
            &EvalContext::default(),
            "p-baseline-readonly",
            PolicyOp::Put,
        );
        assert!(
            matches!(dec, ManagedPolicyDecision::PassThrough { .. }),
            "got {dec:?}"
        );
    }

    // ---- #647 system-owned guardrail integration: tenant-scope half ----
    //
    // Acceptance #4 for #647 asks that tenant-scoped and platform-scoped
    // system-owned users be tested *separately*. The Allow-path test
    // (`structurally_eligible_caller_with_matching_policy_is_allowed`)
    // already pins the platform-scoped operator. A tenant-scoped
    // system-owned user is *not* a platform-scoped operator — the gate
    // requires both flags — so even with `policy:*` granted the gate
    // must Deny on `NotStructurallyEligible` and never reach the policy
    // evaluator. Pins acceptance #3 too: system-owned alone is not
    // enough; platform scope is part of the operator-principal shape.

    #[test]
    fn tenant_scoped_system_owned_user_is_structurally_ineligible_for_managed_policy() {
        let store = store();
        let seeder = seed_registry_admin(&store);
        store
            .create_system_user("ops", "p", Role::Admin, Some("acme"))
            .expect("create tenant-scoped system-owned user");
        let ops_acme = UserId::scoped("acme", "ops");
        // Grant the broadest possible policy permission — proves the
        // Deny below is structural, not policy-evaluator fallout.
        store
            .put_policy(allow_all_policies("p-ops-acme-allow"))
            .unwrap();
        store
            .attach_policy(PrincipalRef::User(ops_acme.clone()), "p-ops-acme-allow")
            .unwrap();

        let reg = ConfigRegistry::new();
        reg.register(
            &store,
            &seeder,
            &registry_admin_ctx(),
            managed_policy_draft("p-baseline-readonly"),
            1_000,
        )
        .unwrap();

        let gate = ManagedPolicyGate::new(&reg);
        // Mirror the runtime EvalContext shape for a tenant-scoped
        // system-owned user — system_owned=true (the user record says
        // so) AND platform_scoped=false (tenant.is_some()).
        let ctx = EvalContext {
            principal_tenant: Some("acme".into()),
            current_tenant: Some("acme".into()),
            peer_ip: None,
            mfa_present: false,
            now_ms: 1_700_000_000_100,
            principal_is_admin_role: true,
            principal_is_system_owned: true,
            principal_is_platform_scoped: false,
        };

        for op in [
            PolicyOp::Put,
            PolicyOp::Drop,
            PolicyOp::Attach,
            PolicyOp::Detach,
        ] {
            let decision = gate.check_mutation(&store, &ops_acme, &ctx, "p-baseline-readonly", op);
            match decision {
                ManagedPolicyDecision::Deny {
                    reason:
                        DenyReason::NotStructurallyEligible {
                            is_system_owned,
                            is_platform_scoped,
                        },
                    op: got_op,
                    ..
                } => {
                    assert_eq!(got_op, op);
                    assert!(is_system_owned, "system_owned flag should propagate");
                    assert!(
                        !is_platform_scoped,
                        "tenant-scoped principal must report platform_scoped=false"
                    );
                }
                other => panic!("expected NotStructurallyEligible Deny for {op:?}, got {other:?}"),
            }
        }
    }

    #[test]
    fn split_required_resource_handles_bare_string() {
        assert_eq!(
            split_required_resource("policy:p-baseline", "p-baseline"),
            ("policy", "p-baseline")
        );
        // Bare string with no colon falls back to (policy, policy_id),
        // not the bare value, so the resource always aligns with the
        // policy id under evaluation.
        assert_eq!(
            split_required_resource("p-anything-else", "p-baseline"),
            ("policy", "p-baseline")
        );
    }
}