tablo_core/tenancy.rs
1//! Scopes resources to the request tenant.
2//!
3//! [`tenant_id`] answers the request's tenant: the signed-in user's
4//! [`membership`](crate::membership) unless a server-set `Tenant` request extension or a `Tenant`
5//! scoped value overrides it, so app middleware and `Router::handle` tests can set it
6//! deliberately. No request header supplies a tenant: learning another tenant's UUID does not make
7//! anyone that tenant.
8
9use toasty::stmt::{Expr, Path};
10use topcoat::context::{Cx, try_app_context, try_request_context};
11
12use crate::{
13 DeclarationErrorKind,
14 toasty_compat::model::{self, ModelPath},
15};
16
17mod tenant_id;
18
19pub use tenant_id::{TenantColumn, TenantId};
20
21/// One tenant a user may act for: its id, and the name the tenant switcher
22/// shows. A [`PanelUser`](crate::auth::PanelUser) lists its memberships in
23/// [`tenants`](crate::auth::PanelUser::tenants).
24#[derive(Debug, Clone, PartialEq, Eq, Hash)]
25pub struct Membership {
26 pub tenant: uuid::Uuid,
27 pub name: String,
28}
29
30impl Membership {
31 /// The membership of `tenant`, shown as `name`.
32 pub fn new(tenant: uuid::Uuid, name: impl Into<String>) -> Self {
33 Self {
34 tenant,
35 name: name.into(),
36 }
37 }
38}
39
40/// Request-scoped tenant identifier.
41///
42/// App code may put it on the `Cx` with `cx.with(Tenant(id))`, and server code
43/// and tests may carry it as a request extension; either wins over the signed-in
44/// user's tenant.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46pub struct Tenant(pub uuid::Uuid);
47
48/// The tenant the request acts for, if any.
49///
50/// Checks a `Tenant` request extension first (a server-set override — the
51/// deliberate seam app middleware and `Router::handle` tests use), then a
52/// `Tenant` scoped value app code put on the `Cx`, then the signed-in user's
53/// [`membership`](crate::membership). No request header is consulted.
54pub fn tenant_id(cx: &Cx) -> Option<uuid::Uuid> {
55 if let Some(parts) = try_request_context::<http::request::Parts>(cx)
56 && let Some(t) = parts.extensions.get::<Tenant>()
57 {
58 return Some(t.0);
59 }
60 if let Some(t) = try_request_context::<Tenant>(cx) {
61 return Some(t.0);
62 }
63 let TenantSource(session) = try_app_context::<TenantSource>(cx)?;
64 session(cx)
65}
66
67/// Finds the tenant the request's session acts for; the first panel mounted on a router installs
68/// it in the app context.
69pub(crate) struct TenantSource(pub(crate) fn(&Cx) -> Option<uuid::Uuid>);
70
71/// Requires a tenant, returning an error if missing (for tenancy-gated resources).
72///
73/// # Errors
74///
75/// 403 when the request acts for no tenant.
76pub fn require_tenant(cx: &Cx) -> Result<uuid::Uuid, topcoat::Error> {
77 tenant_id(cx).ok_or_else(|| topcoat::router::error::forbidden().into())
78}
79
80/// How a resource's rows belong to a tenant.
81///
82/// A resource declares one with [`ResourceDef::tenancy`](crate::ResourceDef::tenancy). A
83/// scoped tenancy names, by lens, the [`TenantId`] column each row is filtered on:
84///
85/// ```text
86/// ResourceDef::new().tenancy(Tenancy::column(Post::fields().tenant_id()))
87///
88/// ResourceDef::new().tenancy(Tenancy::via(Comment::fields().post().tenant_id()))
89/// ```
90///
91/// A scoped resource answers 403 to a request with no tenant, in every handler,
92/// instead of serving unscoped rows or writing rows with no tenant.
93pub struct Tenancy<M> {
94 scope: Scope,
95 _model: std::marker::PhantomData<fn() -> M>,
96}
97
98/// The model field a [`Tenancy::column`] stamps and filters on.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub(crate) struct TenantField {
101 /// The field's index in its model.
102 pub(crate) index: usize,
103 /// The field's name, which is also its form key.
104 pub(crate) name: String,
105}
106
107/// `<lens> = tenant` for one tenant.
108type TenantFilter = Box<dyn Fn(uuid::Uuid) -> Expr<bool> + Send + Sync>;
109
110enum Scope {
111 None,
112 /// The model's own column, resolved when declared: its field, or `None`
113 /// when the lens names none.
114 Column {
115 filter: TenantFilter,
116 field: Option<TenantField>,
117 },
118 Via {
119 filter: TenantFilter,
120 /// Whether the lens is one field of the model: a `via` over its own
121 /// column stamps nothing, so the mount refuses it in favor of
122 /// [`Tenancy::column`](Self::column).
123 single: bool,
124 /// The model field the lens's first step names: the relation whose
125 /// foreign key the form must write through a relationship field.
126 hop: Option<usize>,
127 },
128}
129
130impl<M: toasty::schema::Model + 'static> Tenancy<M> {
131 fn scoped(scope: Scope) -> Self {
132 Self {
133 scope,
134 _model: std::marker::PhantomData,
135 }
136 }
137
138 /// Rows belong to no tenant: the resource is served as
139 /// [`query`](crate::resource::Resource::query) states it, to every
140 /// request. The default.
141 pub fn none() -> Self {
142 Self::scoped(Scope::None)
143 }
144
145 /// Rows carry their tenant in one [`TenantId`] column of their own model,
146 /// `TenantId` or `Option<TenantId>`.
147 ///
148 /// The framework filters every loader on it and stamps the request's
149 /// tenant into it on create, so the record form must not claim it.
150 /// Mounting the panel refuses a lens that is not a single field of the
151 /// model.
152 pub fn column<T>(lens: impl Into<Path<M, T>>) -> Self
153 where
154 T: TenantColumn,
155 M: Send + Sync,
156 {
157 let lens = lens.into();
158 let field = model::field::<M>(&ModelPath::of(&lens))
159 .ok()
160 .map(|field| TenantField {
161 index: field.index,
162 name: field.name,
163 });
164 Self::scoped(Scope::Column {
165 filter: Box::new(move |tenant| lens.clone().eq(T::from_tenant(tenant))),
166 field,
167 })
168 }
169
170 /// Rows inherit their tenant through a relation: `lens` reaches the parent's [`TenantId`]
171 /// column, as `Comment::fields().post().tenant_id()` does.
172 ///
173 /// The framework filters every loader on it. It stamps nothing on create:
174 /// a row's tenant is its parent's. The lens starts at a `belongs_to`
175 /// relation, and mounting the panel requires the form to write that
176 /// relation's foreign key through a relationship field over a tenant-scoped
177 /// resource, whose key the framework re-checks against that resource's
178 /// tenant-scoped query inside the write.
179 pub fn via<T>(lens: impl Into<Path<M, T>>) -> Self
180 where
181 T: TenantColumn,
182 M: Send + Sync,
183 {
184 let lens = lens.into();
185 let path = ModelPath::of(&lens);
186 let hop = path.steps().first().copied();
187 let single = model::field::<M>(&path).is_ok();
188 Self::scoped(Scope::Via {
189 filter: Box::new(move |tenant| lens.clone().eq(T::from_tenant(tenant))),
190 single,
191 hop,
192 })
193 }
194
195 /// Whether the rows belong to a tenant, so every handler requires one.
196 pub fn is_scoped(&self) -> bool {
197 !matches!(self.scope, Scope::None)
198 }
199
200 /// `<lens> = tenant`, or `None` for an unscoped resource.
201 pub(crate) fn filter(&self, tenant: uuid::Uuid) -> Option<Expr<bool>> {
202 match &self.scope {
203 Scope::None => None,
204 Scope::Column { filter, .. } | Scope::Via { filter, .. } => Some(filter(tenant)),
205 }
206 }
207
208 /// Whether a [`via`](Self::via) tenancy names one field of the model,
209 /// which [`Tenancy::column`](Self::column) owns. `None` for any other
210 /// tenancy.
211 pub(crate) fn via_is_single(&self) -> Option<bool> {
212 match &self.scope {
213 Scope::Via { single, .. } => Some(*single),
214 Scope::None | Scope::Column { .. } => None,
215 }
216 }
217
218 /// The model field a [`via`](Self::via) lens steps through first.
219 pub(crate) fn via_hop(&self) -> Option<usize> {
220 match &self.scope {
221 Scope::Via { hop, .. } => *hop,
222 Scope::None | Scope::Column { .. } => None,
223 }
224 }
225
226 /// The model's own tenant column for a [`column`](Self::column) tenancy,
227 /// or the mistake of a lens that names none.
228 pub(crate) fn column_field(&self) -> Option<Result<&TenantField, DeclarationErrorKind>> {
229 match &self.scope {
230 Scope::Column { field, .. } => Some(
231 field
232 .as_ref()
233 .ok_or(DeclarationErrorKind::TenancyColumnNotAField),
234 ),
235 Scope::None | Scope::Via { .. } => None,
236 }
237 }
238}
239
240impl<M: toasty::schema::Model + 'static> Default for Tenancy<M> {
241 fn default() -> Self {
242 Self::none()
243 }
244}
245
246#[cfg(test)]
247mod tests;