lean_ctx_ext/core/trust/
tenant_isolation.rs1use std::fmt;
5
6use super::identity::{IdentityContext, TenantId};
7
8pub trait TenantBoundary {
10 fn tenant_id(&self) -> &TenantId;
12}
13
14impl TenantBoundary for TenantId {
15 fn tenant_id(&self) -> &TenantId {
16 self
17 }
18}
19
20impl TenantBoundary for IdentityContext {
21 fn tenant_id(&self) -> &TenantId {
22 &self.tenant
23 }
24}
25
26#[derive(Clone, Debug, Eq, PartialEq)]
29pub struct CrossTenantLeak {
30 pub expected: TenantId,
32 pub actual: TenantId,
34}
35
36impl CrossTenantLeak {
37 #[must_use]
39 pub fn new(expected: TenantId, actual: TenantId) -> Self {
40 Self { expected, actual }
41 }
42}
43
44impl fmt::Display for CrossTenantLeak {
45 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
46 write!(
47 formatter,
48 "tenant boundary violation: expected {}, found {}",
49 self.expected, self.actual
50 )
51 }
52}
53
54impl std::error::Error for CrossTenantLeak {}
55
56#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
58pub struct IsolationCheck;
59
60impl IsolationCheck {
61 pub fn same_tenant<A: TenantBoundary + ?Sized, B: TenantBoundary + ?Sized>(
63 left: &A,
64 right: &B,
65 ) -> Result<(), CrossTenantLeak> {
66 assert_same_tenant(left, right)
67 }
68
69 pub fn all_same_tenant<T: TenantBoundary>(values: &[T]) -> Result<(), CrossTenantLeak> {
71 let Some(first) = values.first() else {
72 return Ok(());
73 };
74 for value in values.iter().skip(1) {
75 assert_same_tenant(first, value)?;
76 }
77 Ok(())
78 }
79
80 pub fn verify<A: TenantBoundary + ?Sized, B: TenantBoundary + ?Sized>(
82 left: &A,
83 right: &B,
84 ) -> Result<(), CrossTenantLeak> {
85 Self::same_tenant(left, right)
86 }
87}
88
89pub fn assert_same_tenant<A: TenantBoundary + ?Sized, B: TenantBoundary + ?Sized>(
91 left: &A,
92 right: &B,
93) -> Result<(), CrossTenantLeak> {
94 if left.tenant_id() == right.tenant_id() {
95 Ok(())
96 } else {
97 Err(CrossTenantLeak::new(
98 left.tenant_id().clone(),
99 right.tenant_id().clone(),
100 ))
101 }
102}