use std::sync::Arc;
use axum::extract::{Request, State};
use axum::http::StatusCode;
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde_json::json;
use crate::routes::AppState;
pub(crate) const DEFAULT_TENANT: &str = "default";
#[derive(Debug, Clone)]
pub(crate) struct TenantContext {
tenant: String,
}
impl TenantContext {
pub(crate) fn new(tenant: String) -> Self {
Self { tenant }
}
pub(crate) fn tenant(&self) -> &str {
&self.tenant
}
pub(crate) fn scope(&self, id: &str) -> String {
scope_id(&self.tenant, id)
}
pub(crate) fn unscope<'a>(&self, internal_id: &'a str) -> Option<&'a str> {
strip_owned(&self.tenant, internal_id)
}
pub(crate) fn owns(&self, internal_id: &str) -> bool {
self.unscope(internal_id).is_some()
}
}
pub(crate) fn scope_id(tenant: &str, id: &str) -> String {
if tenant == DEFAULT_TENANT {
id.to_string()
} else {
format!("{tenant}/{id}")
}
}
pub(crate) fn strip_owned<'a>(tenant: &str, internal_id: &'a str) -> Option<&'a str> {
if tenant == DEFAULT_TENANT {
if internal_id.contains('/') {
None
} else {
Some(internal_id)
}
} else {
internal_id
.strip_prefix(tenant)
.and_then(|rest| rest.strip_prefix('/'))
}
}
pub(crate) fn tenant_of_internal(internal_id: &str) -> &str {
match internal_id.split_once('/') {
Some((tenant, _)) => tenant,
None => DEFAULT_TENANT,
}
}
pub(crate) async fn require_api_key(
State(state): State<Arc<AppState>>,
mut request: Request,
next: Next,
) -> Response {
let tenant = if state.config.auth_enabled() {
let provided = request
.headers()
.get("x-api-key")
.and_then(|v| v.to_str().ok());
match provided.and_then(|key| state.config.tenant_for_key(key)) {
Some(tenant) => tenant.to_string(),
None => {
return (
StatusCode::UNAUTHORIZED,
Json(json!({
"error": "unauthorized",
"message": "a valid `X-Api-Key` header is required",
})),
)
.into_response();
}
}
} else {
DEFAULT_TENANT.to_string()
};
request.extensions_mut().insert(TenantContext::new(tenant));
next.run(request).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_tenant_is_unprefixed() {
assert_eq!(scope_id(DEFAULT_TENANT, "t1"), "t1");
assert_eq!(scope_id("acme", "t1"), "acme/t1");
}
#[test]
fn strip_owned_respects_tenant_boundaries() {
assert_eq!(strip_owned("acme", "acme/t1"), Some("t1"));
assert_eq!(strip_owned("acme", "globex/t1"), None);
assert_eq!(strip_owned("acme", "t1"), None);
assert_eq!(strip_owned(DEFAULT_TENANT, "t1"), Some("t1"));
assert_eq!(strip_owned(DEFAULT_TENANT, "acme/t1"), None);
assert_eq!(strip_owned("acm", "acme/t1"), None);
}
#[test]
fn tenant_of_internal_reads_the_prefix() {
assert_eq!(tenant_of_internal("acme/t1"), "acme");
assert_eq!(tenant_of_internal("t1"), DEFAULT_TENANT);
}
}