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>),
#[cfg_attr(not(feature = "tenancy"), allow(dead_code))]
Superuser,
}
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::Codenames(codenames) => check_codenames(codenames, caller, pool).await,
other => other.check_caller(caller),
}
}
fn check_caller(&self, caller: Option<&Caller>) -> Outcome {
match (self, caller) {
(Self::Anonymous, _) => Outcome::Allow,
(Self::SignedIn | Self::Superuser | Self::Codenames(_), None) => {
Outcome::Unauthenticated
}
(Self::SignedIn, Some(_)) => Outcome::Allow,
(Self::Superuser, Some(c)) if c.is_superuser => Outcome::Allow,
_ => Outcome::Forbidden,
}
}
}
#[cfg(feature = "admin")]
#[derive(Clone, Debug)]
pub struct RouteAccess(Gate);
#[cfg(feature = "admin")]
impl RouteAccess {
#[must_use]
pub fn allow_anonymous() -> Self {
Self(Gate::Anonymous)
}
#[cfg(feature = "tenancy")]
#[must_use]
pub fn superuser() -> Self {
Self(Gate::Superuser)
}
pub(crate) fn guard(self, router: axum::Router) -> axum::Router {
if self.0 == Gate::Anonymous {
return router;
}
let gate = std::sync::Arc::new(self.0);
router.route_layer(axum::middleware::from_fn_with_state(gate, check_route))
}
}
#[cfg(feature = "admin")]
async fn check_route(
axum::extract::State(gate): axum::extract::State<std::sync::Arc<Gate>>,
req: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
let (parts, body) = req.into_parts();
let outcome = match Caller::on_fixed(&parts) {
Ok(caller) => gate.check_caller(caller.as_ref()),
Err(refused) => refused,
};
match outcome.refusal() {
Some(resp) => resp,
None => {
next.run(axum::extract::Request::from_parts(parts, body))
.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),
}
impl Outcome {
pub(crate) fn refusal(self) -> Option<axum::response::Response> {
use axum::http::StatusCode;
use axum::response::IntoResponse as _;
Some(match self {
Self::Allow => return None,
Self::Unauthenticated => {
(StatusCode::UNAUTHORIZED, "authentication required").into_response()
}
Self::Forbidden => (StatusCode::FORBIDDEN, "permission denied").into_response(),
Self::Unavailable(e) => {
tracing::error!(target: "rustango::access", error = %e, "permission read failed");
(StatusCode::SERVICE_UNAVAILABLE, "service unavailable").into_response()
}
})
}
}
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",
);
}
}