use std::convert::Infallible;
use std::sync::Arc;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use seiva_identity::Principal;
use seiva_ports::Scope;
use crate::idempotency::IdempotencyKey;
#[derive(Debug, Clone)]
pub struct Ctx {
principal: Arc<Principal>,
method: String,
path: String,
idempotency_key: Option<IdempotencyKey>,
}
impl Ctx {
#[must_use]
pub fn new(principal: Principal) -> Self {
Self::from_shared(Arc::new(principal))
}
#[must_use]
pub(crate) fn from_shared(principal: Arc<Principal>) -> Self {
Self {
principal,
method: String::new(),
path: String::new(),
idempotency_key: None,
}
}
#[must_use]
pub fn with_request(
mut self,
method: impl Into<String>,
path: impl Into<String>,
idempotency_key: Option<IdempotencyKey>,
) -> Self {
self.method = method.into();
self.path = path.into();
self.idempotency_key = idempotency_key;
self
}
#[must_use]
pub fn principal(&self) -> &Principal {
self.principal.as_ref()
}
#[must_use]
pub fn tenant(&self) -> Option<&str> {
self.principal.tenant.as_deref()
}
#[must_use]
pub fn subject(&self) -> &str {
&self.principal.subject
}
#[must_use]
pub fn scope(&self) -> Option<Scope> {
self.principal.tenant.as_deref().and_then(Scope::tenant)
}
#[must_use]
pub fn has(&self, permission: &str) -> bool {
self.principal.has(permission)
}
#[must_use]
pub fn method(&self) -> &str {
&self.method
}
#[must_use]
pub fn path(&self) -> &str {
&self.path
}
#[must_use]
pub fn idempotency_key(&self) -> Option<&IdempotencyKey> {
self.idempotency_key.as_ref()
}
}
impl<S: Sync> FromRequestParts<S> for Ctx {
type Rejection = Infallible;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let principal = parts
.extensions
.get::<Arc<Principal>>()
.cloned()
.unwrap_or_else(|| Arc::new(Principal::anonymous()));
let idempotency_key = parts
.headers
.get(crate::idempotency::IDEMPOTENCY_HEADER)
.and_then(|v| v.to_str().ok())
.and_then(|raw| IdempotencyKey::parse(raw).ok());
Ok(Ctx::from_shared(principal).with_request(
parts.method.as_str().to_owned(),
parts.uri.path().to_owned(),
idempotency_key,
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use seiva_ports::Scope;
#[test]
fn a_tenant_bound_caller_scopes_to_its_tenant() {
let ctx = Ctx::new(Principal::in_tenant("u1", "acme", ["orders:write"]));
match ctx.scope() {
Some(Scope::Tenant(t)) => assert_eq!(t.as_str(), "acme"),
other => panic!("expected Some(Scope::Tenant(acme)), got {other:?}"),
}
}
#[test]
fn a_tenant_less_caller_fails_closed_not_global() {
let authn = Ctx::new(Principal::new("u1", ["orders:write"]));
assert_eq!(authn.scope(), None, "tenant-less must not map to a scope");
let anon = Ctx::new(Principal::anonymous());
assert_eq!(anon.scope(), None, "anonymous must not map to a scope");
}
}