Skip to main content

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/// ```rust
86/// # use tablo_core::{NoForm, Resource, ResourceDef, Tenancy, TenantId, lens};
87/// # #[derive(Debug, Clone, toasty::Model)]
88/// # struct Post { #[key] #[auto] id: uuid::Uuid, tenant_id: TenantId }
89/// # #[derive(Debug, Clone, toasty::Model)]
90/// # struct Comment {
91/// #     #[key] #[auto] id: uuid::Uuid,
92/// #     post_id: uuid::Uuid,
93/// #     #[belongs_to(key = post_id, references = id)]
94/// #     post: toasty::Deferred<Post>,
95/// # }
96/// # struct PostResource;
97/// # impl Resource for PostResource { type Model = Post; type Form = NoForm<Post>; }
98/// # struct CommentResource;
99/// # impl Resource for CommentResource { type Model = Comment; type Form = NoForm<Comment>; }
100/// let posts: ResourceDef<PostResource> =
101///     ResourceDef::new().tenancy(Tenancy::column(lens!(Post.tenant_id)));
102///
103/// let comments: ResourceDef<CommentResource> =
104///     ResourceDef::new().tenancy(Tenancy::via(Comment::fields().post().tenant_id()));
105/// ```
106///
107/// A scoped resource answers 403 to a request with no tenant, in every handler,
108/// instead of serving unscoped rows or writing rows with no tenant.
109pub struct Tenancy<M> {
110    scope: Scope,
111    _model: std::marker::PhantomData<fn() -> M>,
112}
113
114/// The model field a [`Tenancy::column`] stamps and filters on.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub(crate) struct TenantField {
117    /// The field's index in its model.
118    pub(crate) index: usize,
119    /// The field's name, which is also its form key.
120    pub(crate) name: String,
121}
122
123/// `<lens> = tenant` for one tenant.
124type TenantFilter = Box<dyn Fn(uuid::Uuid) -> Expr<bool> + Send + Sync>;
125
126enum Scope {
127    None,
128    /// The model's own column, resolved when declared: its field, or `None`
129    /// when the lens names none.
130    Column {
131        filter: TenantFilter,
132        field: Option<TenantField>,
133    },
134    Via {
135        filter: TenantFilter,
136        /// Whether the lens is one field of the model: a `via` over its own
137        /// column stamps nothing, so the mount refuses it in favor of
138        /// [`Tenancy::column`](Self::column).
139        single: bool,
140        /// The model field the lens's first step names: the relation whose
141        /// foreign key the form must write through a relationship field.
142        hop: Option<usize>,
143    },
144}
145
146impl<M: toasty::schema::Model + 'static> Tenancy<M> {
147    fn scoped(scope: Scope) -> Self {
148        Self {
149            scope,
150            _model: std::marker::PhantomData,
151        }
152    }
153
154    /// Rows belong to no tenant: the resource is served as
155    /// [`query`](crate::resource::Resource::query) states it, to every
156    /// request. The default.
157    pub fn none() -> Self {
158        Self::scoped(Scope::None)
159    }
160
161    /// Rows carry their tenant in one [`TenantId`] column of their own model,
162    /// `TenantId` or `Option<TenantId>`.
163    ///
164    /// The framework filters every loader on it and stamps the request's
165    /// tenant into it on create, so the record form must not claim it.
166    /// Mounting the panel refuses a lens that is not a single field of the
167    /// model.
168    pub fn column<T>(lens: impl Into<Path<M, T>>) -> Self
169    where
170        T: TenantColumn,
171        M: Send + Sync,
172    {
173        let lens = lens.into();
174        let field = model::field::<M>(&ModelPath::of(&lens))
175            .ok()
176            .map(|field| TenantField {
177                index: field.index,
178                name: field.name,
179            });
180        Self::scoped(Scope::Column {
181            filter: Box::new(move |tenant| lens.clone().eq(T::from_tenant(tenant))),
182            field,
183        })
184    }
185
186    /// Rows inherit their tenant through a relation: `lens` reaches the parent's [`TenantId`]
187    /// column, as `Comment::fields().post().tenant_id()` does.
188    ///
189    /// The framework filters every loader on it. It stamps nothing on create:
190    /// a row's tenant is its parent's. The lens starts at a `belongs_to`
191    /// relation, and mounting the panel requires the form to write that
192    /// relation's foreign key through a relationship field over a tenant-scoped
193    /// resource, whose key the framework re-checks against that resource's
194    /// tenant-scoped query inside the write.
195    pub fn via<T>(lens: impl Into<Path<M, T>>) -> Self
196    where
197        T: TenantColumn,
198        M: Send + Sync,
199    {
200        let lens = lens.into();
201        let path = ModelPath::of(&lens);
202        let hop = path.steps().first().copied();
203        let single = model::field::<M>(&path).is_ok();
204        Self::scoped(Scope::Via {
205            filter: Box::new(move |tenant| lens.clone().eq(T::from_tenant(tenant))),
206            single,
207            hop,
208        })
209    }
210
211    /// Whether the rows belong to a tenant, so every handler requires one.
212    pub fn is_scoped(&self) -> bool {
213        !matches!(self.scope, Scope::None)
214    }
215
216    /// `<lens> = tenant`, or `None` for an unscoped resource.
217    pub(crate) fn filter(&self, tenant: uuid::Uuid) -> Option<Expr<bool>> {
218        match &self.scope {
219            Scope::None => None,
220            Scope::Column { filter, .. } | Scope::Via { filter, .. } => Some(filter(tenant)),
221        }
222    }
223
224    /// Whether a [`via`](Self::via) tenancy names one field of the model,
225    /// which [`Tenancy::column`](Self::column) owns. `None` for any other
226    /// tenancy.
227    pub(crate) fn via_is_single(&self) -> Option<bool> {
228        match &self.scope {
229            Scope::Via { single, .. } => Some(*single),
230            Scope::None | Scope::Column { .. } => None,
231        }
232    }
233
234    /// The model field a [`via`](Self::via) lens steps through first.
235    pub(crate) fn via_hop(&self) -> Option<usize> {
236        match &self.scope {
237            Scope::Via { hop, .. } => *hop,
238            Scope::None | Scope::Column { .. } => None,
239        }
240    }
241
242    /// The model's own tenant column for a [`column`](Self::column) tenancy,
243    /// or the mistake of a lens that names none.
244    pub(crate) fn column_field(&self) -> Option<Result<&TenantField, DeclarationErrorKind>> {
245        match &self.scope {
246            Scope::Column { field, .. } => Some(
247                field
248                    .as_ref()
249                    .ok_or(DeclarationErrorKind::TenancyColumnNotAField),
250            ),
251            Scope::None | Scope::Via { .. } => None,
252        }
253    }
254}
255
256impl<M: toasty::schema::Model + 'static> Default for Tenancy<M> {
257    fn default() -> Self {
258        Self::none()
259    }
260}
261
262#[cfg(test)]
263mod tests;