use crate::auth::AuthContext;
use crate::tenant::resolver::TenantResolver;
use crate::tenant::types::{Tenant, TenantId};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GateDenial {
NotFound,
Forbidden,
Unauthenticated,
}
impl std::fmt::Display for GateDenial {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotFound => f.write_str("not found"),
Self::Forbidden => f.write_str("forbidden"),
Self::Unauthenticated => f.write_str("unauthenticated"),
}
}
}
impl std::error::Error for GateDenial {}
pub trait TenantTagged {
fn tenant_tag(&self) -> Option<TenantId>;
}
pub struct TenantGate {
tenant: Option<Tenant>,
}
impl TenantGate {
pub async fn from_auth(
resolver: &dyn TenantResolver,
auth: Option<&AuthContext>,
) -> Self {
let tenant = match auth {
None => None,
Some(ctx) if !ctx.is_authenticated() => None,
Some(ctx) => resolver.resolve(ctx).await.ok(),
};
Self { tenant }
}
pub fn anonymous() -> Self {
Self { tenant: None }
}
pub fn caller_tenant(&self) -> Option<&Tenant> {
self.tenant.as_ref()
}
pub fn is_anonymous(&self) -> bool {
self.tenant.is_none()
}
pub fn can_see(&self, resource_tag: Option<&TenantId>) -> bool {
match (self.tenant.as_ref(), resource_tag) {
(None, None) => true,
(None, Some(_)) => false,
(Some(_), None) => true,
(Some(t), Some(tag)) => t == tag,
}
}
pub fn can_write(&self, resource_tag: Option<&TenantId>) -> bool {
match (self.tenant.as_ref(), resource_tag) {
(None, _) => false,
(Some(_), None) => true,
(Some(t), Some(tag)) => t == tag,
}
}
pub fn authorize_read(&self, resource_tag: Option<&TenantId>) -> Result<(), GateDenial> {
if self.can_see(resource_tag) {
Ok(())
} else {
Err(GateDenial::NotFound)
}
}
pub fn authorize_write(&self, resource_tag: Option<&TenantId>) -> Result<(), GateDenial> {
if self.tenant.is_none() {
return Err(GateDenial::Unauthenticated);
}
if self.can_write(resource_tag) {
Ok(())
} else {
Err(GateDenial::Forbidden)
}
}
pub fn stamp(&self) -> Result<TenantId, GateDenial> {
self.tenant
.as_ref()
.map(TenantId::from)
.ok_or(GateDenial::Unauthenticated)
}
pub fn visible<R: TenantTagged>(&self, resource: &R) -> bool {
self.can_see(resource.tenant_tag().as_ref())
}
pub fn authorize_read_of<R: TenantTagged>(&self, resource: &R) -> Result<(), GateDenial> {
self.authorize_read(resource.tenant_tag().as_ref())
}
pub fn authorize_write_of<R: TenantTagged>(&self, resource: &R) -> Result<(), GateDenial> {
self.authorize_write(resource.tenant_tag().as_ref())
}
}
impl std::fmt::Debug for TenantGate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TenantGate")
.field(
"tenant",
&self.tenant.as_ref().map(Tenant::as_str).unwrap_or("<anonymous>"),
)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tenant::resolver::ClaimTenantResolver;
use serde_json::json;
fn ctx_with_tenant(user: &str, tenant: &str) -> AuthContext {
AuthContext::new(
user.to_string(),
"sess-1".to_string(),
vec![],
json!({"org_id": tenant}),
)
}
fn tag(s: &str) -> TenantId {
TenantId::try_new(s).unwrap()
}
async fn gate_for(auth: Option<&AuthContext>) -> TenantGate {
TenantGate::from_auth(&ClaimTenantResolver::new(), auth).await
}
#[tokio::test]
async fn anonymous_caller_sees_only_public_resources() {
let gate = gate_for(None).await;
assert!(gate.can_see(None));
assert!(!gate.can_see(Some(&tag("acme"))));
}
#[tokio::test]
async fn tenant_caller_sees_own_and_public() {
let ctx = ctx_with_tenant("alice", "acme");
let gate = gate_for(Some(&ctx)).await;
assert!(gate.can_see(None));
assert!(gate.can_see(Some(&tag("acme"))));
assert!(!gate.can_see(Some(&tag("neon"))));
}
#[tokio::test]
async fn anonymous_cannot_write_anything() {
let gate = gate_for(None).await;
assert!(!gate.can_write(None));
assert!(!gate.can_write(Some(&tag("acme"))));
}
#[tokio::test]
async fn tenant_writes_own_and_public_only() {
let ctx = ctx_with_tenant("alice", "acme");
let gate = gate_for(Some(&ctx)).await;
assert!(gate.can_write(None));
assert!(gate.can_write(Some(&tag("acme"))));
assert!(!gate.can_write(Some(&tag("neon"))));
}
#[tokio::test]
async fn read_denial_is_not_found() {
let ctx = ctx_with_tenant("alice", "acme");
let gate = gate_for(Some(&ctx)).await;
assert_eq!(
gate.authorize_read(Some(&tag("neon"))),
Err(GateDenial::NotFound)
);
assert_eq!(gate.authorize_read(Some(&tag("acme"))), Ok(()));
assert_eq!(gate.authorize_read(None), Ok(()));
}
#[tokio::test]
async fn write_denials_split_unauthenticated_vs_forbidden() {
let anon = gate_for(None).await;
assert_eq!(
anon.authorize_write(None),
Err(GateDenial::Unauthenticated)
);
let ctx = ctx_with_tenant("alice", "acme");
let gate = gate_for(Some(&ctx)).await;
assert_eq!(
gate.authorize_write(Some(&tag("neon"))),
Err(GateDenial::Forbidden)
);
assert_eq!(gate.authorize_write(Some(&tag("acme"))), Ok(()));
assert_eq!(gate.authorize_write(None), Ok(()));
}
#[tokio::test]
async fn stamp_returns_resolved_tenant_for_create() {
let ctx = ctx_with_tenant("alice", "acme");
let gate = gate_for(Some(&ctx)).await;
assert_eq!(gate.stamp().unwrap().as_str(), "acme");
let anon = gate_for(None).await;
assert_eq!(anon.stamp(), Err(GateDenial::Unauthenticated));
}
#[tokio::test]
async fn forged_ctx_with_claim_but_no_session_is_rejected_by_gate() {
let ctx = AuthContext::new(
"alice".into(),
String::new(), vec![],
json!({"org_id": "acme"}),
);
let gate = gate_for(Some(&ctx)).await;
assert!(gate.caller_tenant().is_none());
assert!(gate.is_anonymous());
}
#[tokio::test]
async fn unresolvable_caller_is_anonymous() {
let ctx = AuthContext::new(
"alice".into(),
"sess-1".into(),
vec![],
json!({}), );
let resolver = ClaimTenantResolver {
claim_key: "org_id".into(),
single_user_fallback: false,
};
let gate = TenantGate::from_auth(&resolver, Some(&ctx)).await;
assert!(gate.is_anonymous());
}
#[tokio::test]
async fn tenant_tagged_conveniences_mirror_predicates() {
struct Note {
tenant: Option<&'static str>,
}
impl TenantTagged for Note {
fn tenant_tag(&self) -> Option<TenantId> {
self.tenant.map(|t| TenantId::try_new(t).unwrap())
}
}
let ctx = ctx_with_tenant("alice", "acme");
let gate = gate_for(Some(&ctx)).await;
let own = Note { tenant: Some("acme") };
let foreign = Note { tenant: Some("neon") };
let public = Note { tenant: None };
assert!(gate.visible(&own));
assert!(gate.visible(&public));
assert!(!gate.visible(&foreign));
assert_eq!(gate.authorize_read_of(&own), Ok(()));
assert_eq!(gate.authorize_read_of(&foreign), Err(GateDenial::NotFound));
assert_eq!(gate.authorize_write_of(&own), Ok(()));
assert_eq!(
gate.authorize_write_of(&foreign),
Err(GateDenial::Forbidden)
);
}
#[tokio::test]
async fn debug_renders_tenant_or_anonymous() {
let ctx = ctx_with_tenant("alice", "acme");
let gate = gate_for(Some(&ctx)).await;
assert!(format!("{gate:?}").contains("acme"));
let anon = TenantGate::anonymous();
assert!(format!("{anon:?}").contains("<anonymous>"));
}
#[test]
fn gate_denial_display_matches_wire_vocabulary() {
assert_eq!(format!("{}", GateDenial::NotFound), "not found");
assert_eq!(format!("{}", GateDenial::Forbidden), "forbidden");
assert_eq!(
format!("{}", GateDenial::Unauthenticated),
"unauthenticated"
);
}
}