Skip to main content

tablo_core/panel/
gate.rs

1//! The panel gate: auth and tenant enforcement plus the prefix-derived URLs
2//! every handler builds on.
3
4use std::sync::Arc;
5
6use topcoat::{Result, context::Cx};
7
8pub(crate) use crate::auth::panel_prefix;
9use crate::{
10    panel::url::RETURN_PARAM,
11    resource::{Mounted, Resource, mounted, require_mounted},
12};
13
14/// Rejects tenant-scoped requests without a tenant, never serving unscoped rows.
15pub(crate) fn enforce_tenant<R: Resource>(cx: &Cx, resource: &Mounted<R>) -> Result<()> {
16    if resource.tenancy.is_scoped() {
17        crate::tenancy::require_tenant(cx)?;
18    }
19    Ok(())
20}
21
22/// Signs in and scopes the request for `R`, answering `R` as the request's panel mounted it.
23pub(crate) fn gate<R: Resource>(cx: &Cx) -> Result<Arc<Mounted<R>>> {
24    crate::auth::guard(cx)?;
25    let resource = require_mounted::<R>(cx)?;
26    enforce_tenant(cx, &resource)?;
27    Ok(resource)
28}
29
30/// Whether the current request may open `R`'s list: the request's panel mounts `R`, and
31/// sign-in, tenant scope, and [`Ability::ViewAny`](crate::Ability::ViewAny) allow it.
32pub fn can_list<R: Resource>(cx: &Cx) -> bool {
33    crate::auth::guard(cx).is_ok()
34        && mounted::<R>(cx).is_some_and(|resource| {
35            enforce_tenant(cx, &resource).is_ok() && resource.can(cx, crate::Ability::ViewAny)
36        })
37}
38
39/// Whether the current request may view `R`'s `field`: the request's panel mounts `R`, and no
40/// [`ResourceDef::field_access`](crate::ResourceDef::field_access) rule over the model hides the
41/// field from it. The panel's own pages mask a hidden field; a
42/// [`RecordPage`](crate::RecordPage) shows one only after asking this.
43///
44/// A `field` that is no root field of the model, `lens!(Post.author.name)` say, answers `false`.
45pub fn can_view_field<R: Resource, T>(
46    cx: &Cx,
47    field: impl Into<toasty::stmt::Path<R::Model, T>>,
48) -> bool {
49    let path = crate::toasty_compat::model::ModelPath::of(&field.into());
50    let Ok(field) = crate::toasty_compat::model::field::<R::Model>(&path) else {
51        return false;
52    };
53    mounted::<R>(cx).is_some_and(|resource| !resource.field_mask(cx).hidden().contains(&field.name))
54}
55
56/// Whether the current request may open the page `P`: the request's panel mounts `P`, and sign-in
57/// and [`PageDef::access`](crate::PageDef::access) allow it, the checks the page's `GET` makes.
58///
59/// A form a page renders posts to an app route, which [`PageDef::access`](crate::PageDef::access)
60/// does not cover; the route asks `can_open::<P>(cx)` itself.
61pub fn can_open<P: crate::Page>(cx: &Cx) -> bool {
62    crate::auth::guard(cx).is_ok()
63        && super::pages::mounted_page::<P>(cx).is_some_and(|page| page.admits(cx))
64}
65
66/// Returns the validated `?return=` target under the panel prefix, else `None`.
67pub(crate) fn return_target(cx: &Cx) -> Option<String> {
68    let query = topcoat::router::request::uri(cx).query()?;
69    let prefix = panel_prefix(cx);
70    form_urlencoded::parse(query.as_bytes())
71        .find(|(key, _)| key == RETURN_PARAM)
72        .and_then(|(_, value)| crate::auth::safe_next(&value).map(str::to_string))
73        .filter(|target| !has_dot_segment(target))
74        .filter(|target| {
75            target
76                .strip_prefix(prefix.as_str())
77                .is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?']))
78        })
79}
80
81/// Whether `target`'s path holds a `.` or `..` segment, spelled raw or with
82/// `%2e`.
83fn has_dot_segment(target: &str) -> bool {
84    let path = target.split(['?', '#']).next().unwrap_or_default();
85    path.split('/').any(|segment| {
86        let segment = segment.to_ascii_lowercase().replace("%2e", ".");
87        segment == "." || segment == ".."
88    })
89}
90
91/// The validated `?return=` target, else `list_url`.
92pub(crate) fn landing_url(cx: &Cx, list_url: &str) -> String {
93    return_target(cx).unwrap_or_else(|| list_url.to_string())
94}
95
96#[cfg(test)]
97mod tests;