use axum::extract::{Request, State};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use seiva_identity::Principal;
use crate::problem::Problem;
use crate::request_id::RequestIdExt;
pub trait PrincipalExt {
fn require_owns(&self, resource_tenant: &str) -> Result<(), Problem>;
}
impl PrincipalExt for Principal {
fn require_owns(&self, resource_tenant: &str) -> Result<(), Problem> {
if self.owns(resource_tenant) {
Ok(())
} else {
Err(Problem::forbidden(
"caller does not own the requested resource",
))
}
}
}
#[must_use = "a Scoped value must be unwrapped with `owned_by` — dropping it skips the ownership check"]
pub struct Scoped<T> {
tenant: String,
value: T,
}
impl<T> Scoped<T> {
pub fn new(tenant: impl Into<String>, value: T) -> Self {
Self {
tenant: tenant.into(),
value,
}
}
#[must_use]
pub fn tenant(&self) -> &str {
&self.tenant
}
pub fn owned_by(self, principal: &Principal) -> Result<T, Problem> {
if principal.owns(&self.tenant) {
Ok(self.value)
} else {
Err(Problem::forbidden(
"caller does not own the requested resource",
))
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct RequiredPermission(pub &'static str);
pub async fn permission_guard(
State(required): State<RequiredPermission>,
request: Request,
next: Next,
) -> Response {
if required.0.is_empty() {
return next.run(request).await;
}
let principal = request
.extensions()
.get::<Principal>()
.cloned()
.unwrap_or_else(Principal::anonymous);
if principal.has(required.0) {
return next.run(request).await;
}
let request_id = request.extensions().request_id();
Problem::forbidden(format!("permission `{}` is required", required.0))
.with_instance(request.uri().path().to_owned())
.with_request_id_opt(request_id)
.into_response()
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::StatusCode;
#[test]
fn tenant_scoped_principal_owns_only_its_own_tenant() {
let p = Principal::in_tenant("alice", "acme", ["notes.read"]);
assert!(p.owns("acme"));
assert!(!p.owns("globex"));
assert!(p.has("notes.read"));
assert_eq!(p.tenant.as_deref(), Some("acme"));
}
#[test]
fn tenantless_and_anonymous_principals_own_nothing() {
assert!(!Principal::new("svc", ["notes.read"]).owns("acme"));
assert!(!Principal::anonymous().owns("acme"));
}
#[test]
fn require_owns_allows_same_tenant_and_forbids_cross_tenant() {
let p = Principal::in_tenant("alice", "acme", ["notes.read"]);
assert!(p.require_owns("acme").is_ok());
let denied = p.require_owns("globex").unwrap_err();
assert_eq!(denied.status, StatusCode::FORBIDDEN);
}
#[test]
fn scoped_unwraps_only_for_the_owning_tenant() {
let owner = Principal::in_tenant("alice", "acme", ["notes.read"]);
let scoped = Scoped::new("acme", "secret-note");
assert_eq!(scoped.tenant(), "acme");
assert_eq!(scoped.owned_by(&owner).unwrap(), "secret-note");
}
#[test]
fn scoped_forbids_a_cross_tenant_caller() {
let intruder = Principal::in_tenant("mallory", "globex", ["notes.read"]);
let scoped = Scoped::new("acme", "secret-note");
let denied = scoped.owned_by(&intruder).unwrap_err();
assert_eq!(denied.status, StatusCode::FORBIDDEN);
}
#[test]
fn scoped_forbids_a_tenantless_or_anonymous_caller() {
assert!(Scoped::new("acme", 1)
.owned_by(&Principal::new("svc", ["notes.read"]))
.is_err());
assert!(Scoped::new("acme", 1)
.owned_by(&Principal::anonymous())
.is_err());
}
}