use axum::http::request::Parts;
use crate::sql::Pool;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) enum Gate {
#[default]
Undecided,
Anonymous,
#[cfg_attr(
not(all(feature = "tenancy", feature = "template_views")),
allow(dead_code)
)]
SignedIn,
#[cfg_attr(not(feature = "admin"), allow(dead_code))]
Codenames(Vec<String>),
}
impl Gate {
#[cfg_attr(
not(all(feature = "tenancy", feature = "template_views")),
allow(dead_code)
)]
pub(crate) async fn check(&self, caller: Option<&Caller>, pool: &Pool) -> Outcome {
match self {
Self::Anonymous => Outcome::Allow,
Self::Undecided => Outcome::Forbidden,
Self::SignedIn if caller.is_some() => Outcome::Allow,
Self::SignedIn => Outcome::Unauthenticated,
Self::Codenames(codenames) => check_codenames(codenames, caller, pool).await,
}
}
}
pub(crate) struct Caller {
#[cfg_attr(not(feature = "tenancy"), allow(dead_code))]
pub(crate) id: i64,
#[cfg_attr(not(feature = "tenancy"), allow(dead_code))]
pub(crate) is_superuser: bool,
}
impl Caller {
fn authenticated(parts: &Parts) -> Option<Self> {
#[cfg(feature = "tenancy")]
if let Some(u) = parts
.extensions
.get::<crate::tenancy::middleware::AuthenticatedUser>()
{
return Some(Self {
id: u.id,
is_superuser: u.is_superuser,
});
}
let _ = parts;
None
}
#[cfg_attr(not(feature = "admin"), allow(dead_code))]
pub(crate) fn on_fixed(parts: &Parts) -> Result<Option<Self>, Outcome> {
let caller = Self::authenticated(parts);
#[cfg(feature = "tenancy")]
{
let principal = crate::tenancy::Principal::from_parts(parts);
let tenant_bound = principal.as_ref().is_some_and(|p| p.tenant.is_some())
|| crate::object_permissions::credential_tenant(parts).is_some()
|| routed_to_tenant(&parts.extensions);
if (caller.is_some() || principal.is_some()) && tenant_bound {
return Err(Outcome::Forbidden);
}
}
Ok(caller)
}
#[cfg(feature = "tenancy")]
pub(crate) fn on_tenant(
parts: &Parts,
org: &crate::tenancy::Org,
) -> Result<Option<Self>, Outcome> {
match Binding::of(parts, org) {
Binding::Foreign | Binding::Untenanted => Err(Outcome::Forbidden),
Binding::Fits => Ok(Self::authenticated(parts)),
}
}
}
#[cfg(feature = "tenancy")]
#[must_use]
pub(crate) fn routed_to_tenant(ext: &axum::http::Extensions) -> bool {
use crate::tenancy::RequestTenant;
ext.get::<crate::tenancy::request_tenant::DispatchedOrg>()
.is_some()
|| crate::extractors::MountedTenantContext::of(ext).is_some()
|| RequestTenant::get(ext).is_some_and(|t| *t != RequestTenant::Global)
}
#[derive(Debug)]
pub(crate) enum Outcome {
Allow,
#[cfg_attr(not(feature = "tenancy"), allow(dead_code))]
Unauthenticated,
Forbidden,
#[cfg_attr(not(feature = "tenancy"), allow(dead_code))]
Unavailable(String),
}
pub(crate) async fn check_codenames(
codenames: &[String],
caller: Option<&Caller>,
pool: &Pool,
) -> Outcome {
#[cfg(feature = "tenancy")]
{
let Some(caller) = caller else {
return Outcome::Unauthenticated;
};
if caller.is_superuser {
return Outcome::Allow;
}
for cn in codenames {
match crate::tenancy::permissions::has_perm_pool(caller.id, cn, pool).await {
Ok(true) => {}
Ok(false) => return Outcome::Forbidden,
Err(e) => return Outcome::Unavailable(e.to_string()),
}
}
Outcome::Allow
}
#[cfg(not(feature = "tenancy"))]
{
let _ = (codenames, caller, pool);
Outcome::Forbidden
}
}
pub(crate) fn require_decided(surface: &str, table: &str, routes: &[(&str, &Gate)], fix: &str) {
let open: Vec<&str> = routes
.iter()
.filter(|(_, g)| **g == Gate::Undecided)
.map(|(action, _)| *action)
.collect();
assert!(
open.is_empty(),
"{surface} `{table}`: {open:?} would serve any caller, and nothing says that is \
intended; {fix}"
);
assert!(
!routes
.iter()
.any(|(_, g)| matches!(g, Gate::Codenames(c) if c.is_empty())),
"{surface} `{table}`: an empty codename list would let any signed-in user in; \
name the codenames, or call `.login_required()` if that is intended"
);
let needs_users = routes
.iter()
.any(|(_, g)| matches!(g, Gate::SignedIn | Gate::Codenames(_)));
assert!(
cfg!(feature = "tenancy") || !needs_users,
"{surface} `{table}`: permission codenames need the `tenancy` feature; on a \
single-database app {fix}"
);
}
#[cfg(feature = "tenancy")]
pub(crate) enum Binding {
Foreign,
Untenanted,
Fits,
}
#[cfg(feature = "tenancy")]
impl Binding {
#[must_use]
pub(crate) fn of(parts: &Parts, org: &crate::tenancy::Org) -> Self {
let routed = crate::tenancy::TenantSlug::of(org);
let other_org =
crate::object_permissions::credential_tenant(parts).is_some_and(|c| Some(c) != routed);
match crate::tenancy::Principal::from_parts(parts).map(|p| p.tenant) {
Some(Some(t)) if t != org.slug || other_org => Self::Foreign,
Some(None) => Self::Untenanted,
_ => Self::Fits,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "[\"delete\"] would serve any caller")]
fn an_undecided_route_refuses_to_mount() {
require_decided(
"DeleteView",
"post",
&[("delete", &Gate::Undecided)],
"say who",
);
}
#[test]
fn a_decided_surface_mounts() {
require_decided("ListView", "post", &[("list", &Gate::Anonymous)], "x");
}
#[test]
#[should_panic(expected = "call `.login_required()`")]
fn empty_codenames_refuse_to_mount() {
require_decided(
"ListView",
"post",
&[("GET", &Gate::Codenames(Vec::new()))],
"x",
);
}
#[cfg(not(feature = "tenancy"))]
#[test]
#[should_panic(expected = "need the `tenancy` feature")]
fn codenames_need_tenancy() {
require_decided(
"ViewSet",
"post",
&[("list", &Gate::Codenames(vec!["post.view".into()]))],
"x",
);
}
}