use std::future::Future;
use std::sync::Arc;
#[derive(Clone, Copy)]
pub struct AuthzRequest<'a> {
pub credential: Option<&'a str>,
pub action: &'static str,
pub port: Option<u16>,
pub space: Option<&'a str>,
pub scope: Option<&'a str>,
pub params: &'a [(&'a str, &'a str)],
}
impl std::fmt::Debug for AuthzRequest<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AuthzRequest")
.field("credential", &self.credential.map(|_| "<redacted>"))
.field("action", &self.action)
.field("port", &self.port)
.field("space", &self.space)
.field("scope", &self.scope)
.field("params", &self.params)
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthzDecision {
Allow { principal: Option<String> },
Deny { reason: &'static str },
}
impl AuthzDecision {
#[must_use]
pub fn allow() -> Self {
Self::Allow { principal: None }
}
#[must_use]
pub fn is_allowed(&self) -> bool {
matches!(self, Self::Allow { .. })
}
}
pub mod actions {
pub const SYSTEM_READ: &str = "system.read";
pub const SYSTEM_WRITE: &str = "system.write";
pub const IMPOSTER_READ: &str = "imposter.read";
pub const IMPOSTER_WRITE: &str = "imposter.write";
pub const IMPOSTER_DELETE: &str = "imposter.delete";
pub const IMPOSTER_VERIFY: &str = "imposter.verify";
pub const EVENTS_READ: &str = "events.read";
pub const INTERCEPT_READ: &str = "intercept.read";
pub const INTERCEPT_WRITE: &str = "intercept.write";
}
pub trait AdminAuthorizer: Send + Sync {
fn authorize(&self, req: AuthzRequest<'_>) -> AuthzDecision;
}
#[derive(Debug, Default, Clone, Copy)]
pub struct AllowAll;
impl AdminAuthorizer for AllowAll {
fn authorize(&self, _req: AuthzRequest<'_>) -> AuthzDecision {
AuthzDecision::allow()
}
}
pub type SharedAdminAuthorizer = Arc<dyn AdminAuthorizer>;
tokio::task_local! {
static PRINCIPAL: Option<String>;
}
pub async fn with_principal_scope<F: Future>(principal: Option<String>, fut: F) -> F::Output {
PRINCIPAL.scope(principal, fut).await
}
#[must_use]
pub fn current_principal() -> Option<String> {
PRINCIPAL.try_with(Clone::clone).ok().flatten()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn allow_helper_carries_no_principal() {
assert_eq!(
AuthzDecision::allow(),
AuthzDecision::Allow { principal: None }
);
}
#[test]
fn deny_is_not_allowed() {
assert!(!AuthzDecision::Deny { reason: "nope" }.is_allowed());
assert!(AuthzDecision::allow().is_allowed());
assert!(
AuthzDecision::Allow {
principal: Some("alice".into())
}
.is_allowed()
);
}
#[test]
fn allow_all_admits_every_action() {
let a = AllowAll;
for action in [
actions::IMPOSTER_WRITE,
actions::SYSTEM_READ,
actions::IMPOSTER_DELETE,
] {
let decision = a.authorize(AuthzRequest {
credential: None,
action,
port: None,
space: None,
scope: None,
params: &[],
});
assert_eq!(decision, AuthzDecision::allow());
}
}
#[test]
fn debug_redacts_the_admin_credential() {
let req = AuthzRequest {
credential: Some("super-secret-token"),
action: actions::IMPOSTER_WRITE,
port: Some(4545),
space: None,
scope: None,
params: &[],
};
let rendered = format!("{req:?}");
assert!(
!rendered.contains("super-secret-token"),
"the credential leaked into Debug: {rendered}"
);
assert!(rendered.contains("<redacted>"), "got: {rendered}");
let anon = AuthzRequest {
credential: None,
..req
};
assert!(format!("{anon:?}").contains("credential: None"));
}
#[test]
fn action_strings_are_distinct() {
let all = [
actions::SYSTEM_READ,
actions::SYSTEM_WRITE,
actions::IMPOSTER_READ,
actions::IMPOSTER_WRITE,
actions::IMPOSTER_DELETE,
actions::IMPOSTER_VERIFY,
actions::EVENTS_READ,
actions::INTERCEPT_READ,
actions::INTERCEPT_WRITE,
];
let unique: std::collections::BTreeSet<_> = all.iter().collect();
assert_eq!(unique.len(), all.len(), "action constants must be distinct");
}
}