#![forbid(unsafe_code)]
#![deny(missing_docs)]
use std::collections::BTreeSet;
pub mod jwt;
pub use jwt::JwtAuthenticator;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Principal {
pub subject: String,
pub tenant: Option<String>,
pub permissions: BTreeSet<String>,
}
impl Principal {
#[must_use]
pub fn anonymous() -> Self {
Self::default()
}
pub fn new<I, P>(subject: impl Into<String>, permissions: I) -> Self
where
I: IntoIterator<Item = P>,
P: Into<String>,
{
Self {
subject: subject.into(),
tenant: None,
permissions: permissions.into_iter().map(Into::into).collect(),
}
}
pub fn in_tenant<I, P>(
subject: impl Into<String>,
tenant: impl Into<String>,
permissions: I,
) -> Self
where
I: IntoIterator<Item = P>,
P: Into<String>,
{
Self {
subject: subject.into(),
tenant: Some(tenant.into()),
permissions: permissions.into_iter().map(Into::into).collect(),
}
}
#[must_use]
pub fn has(&self, permission: &str) -> bool {
self.permissions.contains(permission)
}
#[must_use]
pub fn owns(&self, resource_tenant: &str) -> bool {
self.tenant.as_deref() == Some(resource_tenant)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AuthError {
MissingCredentials,
InvalidToken,
Forbidden,
}
impl std::fmt::Display for AuthError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
AuthError::MissingCredentials => "missing bearer credentials",
AuthError::InvalidToken => "invalid bearer token",
AuthError::Forbidden => "forbidden",
})
}
}
impl std::error::Error for AuthError {}
pub trait Authenticator: Send + Sync {
fn authenticate(&self, bearer: &str) -> Result<Principal, AuthError>;
}
#[derive(Clone, Default)]
pub struct TokenAuthenticator {
tokens: std::collections::HashMap<[u8; 32], Principal>,
}
fn token_digest(token: &str) -> [u8; 32] {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(token.as_bytes());
hasher.finalize().into()
}
impl TokenAuthenticator {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_token(mut self, token: impl Into<String>, principal: Principal) -> Self {
self.tokens.insert(token_digest(&token.into()), principal);
self
}
pub fn insert(&mut self, token: impl Into<String>, principal: Principal) {
self.tokens.insert(token_digest(&token.into()), principal);
}
#[must_use]
pub fn len(&self) -> usize {
self.tokens.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.tokens.is_empty()
}
}
impl Authenticator for TokenAuthenticator {
fn authenticate(&self, bearer: &str) -> Result<Principal, AuthError> {
if bearer.is_empty() {
return Err(AuthError::MissingCredentials);
}
self.tokens
.get(&token_digest(bearer))
.cloned()
.ok_or(AuthError::InvalidToken)
}
}
#[derive(Clone, Default)]
pub struct ApiKeyAuthenticator {
keys: std::collections::HashMap<[u8; 32], Principal>,
}
impl ApiKeyAuthenticator {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_key(mut self, key: impl AsRef<str>, principal: Principal) -> Self {
self.keys.insert(token_digest(key.as_ref()), principal);
self
}
pub fn insert(&mut self, key: impl AsRef<str>, principal: Principal) {
self.keys.insert(token_digest(key.as_ref()), principal);
}
pub fn revoke(&mut self, key: impl AsRef<str>) -> bool {
self.keys.remove(&token_digest(key.as_ref())).is_some()
}
#[must_use]
pub fn len(&self) -> usize {
self.keys.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.keys.is_empty()
}
}
impl Authenticator for ApiKeyAuthenticator {
fn authenticate(&self, key: &str) -> Result<Principal, AuthError> {
if key.is_empty() {
return Err(AuthError::MissingCredentials);
}
self.keys
.get(&token_digest(key))
.cloned()
.ok_or(AuthError::InvalidToken)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn principal_ownership_and_permissions() {
let p = Principal::in_tenant("alice", "acme", ["notes.read"]);
assert!(p.has("notes.read"));
assert!(p.owns("acme"));
assert!(!p.owns("globex"));
assert!(!Principal::new("svc", ["notes.read"]).owns("acme"));
assert!(!Principal::anonymous().owns("acme"));
}
#[test]
fn token_authenticator_denies_by_default() {
let auth = TokenAuthenticator::new().with_token(
"s3cr3t",
Principal::in_tenant("alice", "acme", ["notes.read"]),
);
assert_eq!(auth.authenticate("s3cr3t").unwrap().subject, "alice");
assert_eq!(auth.authenticate("nope"), Err(AuthError::InvalidToken));
assert_eq!(auth.authenticate(""), Err(AuthError::MissingCredentials));
assert!(TokenAuthenticator::new().authenticate("anything").is_err());
}
#[test]
fn api_key_authenticates_to_principal_with_scopes() {
let auth = ApiKeyAuthenticator::new().with_key(
"sk_live_abc123",
Principal::in_tenant("svc-billing", "acme", ["invoices.read", "invoices.write"]),
);
let principal = auth.authenticate("sk_live_abc123").expect("valid key");
assert_eq!(principal.subject, "svc-billing");
assert!(principal.owns("acme"));
assert!(principal.has("invoices.read"));
assert!(principal.has("invoices.write"));
}
#[test]
fn api_key_denies_unknown_empty_and_revoked() {
let mut auth = ApiKeyAuthenticator::new()
.with_key("sk_live_abc123", Principal::new("svc", ["invoices.read"]));
assert_eq!(
auth.authenticate("sk_live_nope"),
Err(AuthError::InvalidToken)
);
assert_eq!(auth.authenticate(""), Err(AuthError::MissingCredentials));
assert!(ApiKeyAuthenticator::new().authenticate("anything").is_err());
assert!(auth.authenticate("sk_live_abc123").is_ok());
assert!(auth.revoke("sk_live_abc123"));
assert_eq!(
auth.authenticate("sk_live_abc123"),
Err(AuthError::InvalidToken)
);
assert_eq!(auth.len(), 0);
assert!(!auth.revoke("sk_live_never"));
}
}