use async_trait::async_trait;
use std::collections::BTreeMap;
use std::sync::Arc;
use crate::model::{ClientCredentialRequest, ClientCredentialResponse, ClientId, OAuthError};
#[cfg(feature = "internal-auth")]
mod internal;
#[cfg(feature = "external-auth")]
mod jwt;
#[cfg(feature = "internal-auth")]
#[cfg_attr(docsrs, doc(cfg(feature = "internal-auth")))]
pub use internal::{InternalAuth, InternalAuthBuilder};
#[cfg(feature = "external-auth")]
#[cfg_attr(docsrs, doc(cfg(feature = "external-auth")))]
pub use jwt::{JwtAuthenticator, JwtConfig};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Scope {
ReadAll,
ReadBl,
ReadTargets,
ReadVenObjects,
WritePrograms,
WriteEvents,
WriteReports,
WriteSubscriptions,
WriteVens,
}
impl Scope {
pub const fn as_str(self) -> &'static str {
match self {
Scope::ReadAll => "read_all",
Scope::ReadBl => "read_bl",
Scope::ReadTargets => "read_targets",
Scope::ReadVenObjects => "read_ven_objects",
Scope::WritePrograms => "write_programs",
Scope::WriteEvents => "write_events",
Scope::WriteReports => "write_reports",
Scope::WriteSubscriptions => "write_subscriptions",
Scope::WriteVens => "write_vens",
}
}
pub const ALL: [Scope; 9] = [
Scope::ReadAll,
Scope::ReadBl,
Scope::ReadTargets,
Scope::ReadVenObjects,
Scope::WritePrograms,
Scope::WriteEvents,
Scope::WriteReports,
Scope::WriteSubscriptions,
Scope::WriteVens,
];
pub const BUSINESS_LOGIC: [Scope; 7] = [
Scope::ReadAll,
Scope::ReadBl,
Scope::WritePrograms,
Scope::WriteEvents,
Scope::WriteSubscriptions,
Scope::WriteVens,
Scope::WriteReports,
];
pub const VEN: [Scope; 5] = [
Scope::ReadTargets,
Scope::ReadVenObjects,
Scope::WriteReports,
Scope::WriteSubscriptions,
Scope::WriteVens,
];
}
impl core::str::FromStr for Scope {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Scope::ALL.into_iter().find(|c| c.as_str() == s).ok_or(())
}
}
impl core::fmt::Display for Scope {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Scopes(Vec<Scope>);
impl Scopes {
pub fn none() -> Self {
Self::default()
}
pub fn new(scopes: impl IntoIterator<Item = Scope>) -> Self {
let mut v: Vec<Scope> = scopes.into_iter().collect();
v.sort();
v.dedup();
Self(v)
}
pub fn parse(s: &str) -> Self {
Self::new(s.split_whitespace().filter_map(|t| t.parse().ok()))
}
pub fn contains(&self, scope: Scope) -> bool {
self.0.binary_search(&scope).is_ok()
}
pub fn contains_any(&self, scopes: &[Scope]) -> bool {
scopes.iter().any(|s| self.contains(*s))
}
pub fn as_slice(&self) -> &[Scope] {
&self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn to_scope_string(&self) -> String {
self.0
.iter()
.map(|s| s.as_str())
.collect::<Vec<_>>()
.join(" ")
}
pub fn is_business_logic(&self) -> bool {
self.contains_any(&[Scope::ReadAll, Scope::WritePrograms, Scope::WriteEvents])
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Principal {
pub client_id: Option<ClientId>,
pub scopes: Scopes,
}
impl Principal {
pub fn anonymous() -> Self {
Self {
client_id: None,
scopes: Scopes::none(),
}
}
pub fn is_business_logic(&self) -> bool {
self.scopes.is_business_logic()
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum AuthError {
#[error("no bearer token was presented")]
Missing,
#[error("the presented credential is not valid")]
Invalid,
#[error("the presented credential has expired")]
Expired,
#[error("the authorization service is unavailable: {0}")]
Unavailable(String),
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum TokenError {
#[error(
"this VTN does not issue tokens; use GET /auth/server to find the authorization service"
)]
NotIssuing,
#[error("{}", .0.error_description.as_deref().unwrap_or("the token request was refused"))]
Refused(OAuthError),
#[error("the token endpoint is temporarily unavailable: {0}")]
Unavailable(String),
}
#[async_trait]
pub trait Authenticator: Send + Sync + 'static {
async fn authenticate(&self, bearer: Option<&str>) -> Result<Principal, AuthError>;
fn token_url(&self) -> String;
fn allows_anonymous(&self) -> bool {
false
}
fn issues_tokens(&self) -> bool {
false
}
async fn issue_token(
&self,
_request: &ClientCredentialRequest,
) -> Result<ClientCredentialResponse, TokenError> {
Err(TokenError::NotIssuing)
}
}
pub type SharedAuthenticator = Arc<dyn Authenticator>;
#[derive(Debug, Clone)]
pub struct AnonymousAuth {
token_url: String,
}
impl AnonymousAuth {
pub fn new(token_url: impl Into<String>) -> Self {
Self {
token_url: token_url.into(),
}
}
}
#[async_trait]
impl Authenticator for AnonymousAuth {
async fn authenticate(&self, _bearer: Option<&str>) -> Result<Principal, AuthError> {
Ok(Principal::anonymous())
}
fn token_url(&self) -> String {
self.token_url.clone()
}
fn allows_anonymous(&self) -> bool {
true
}
}
#[derive(Debug, Default)]
pub struct StaticTokenAuth {
tokens: BTreeMap<String, Principal>,
token_url: String,
allow_anonymous: bool,
}
impl StaticTokenAuth {
pub fn new(token_url: impl Into<String>) -> Self {
Self {
tokens: BTreeMap::new(),
token_url: token_url.into(),
allow_anonymous: false,
}
}
pub fn with_business_logic(mut self, token: impl Into<String>, client_id: ClientId) -> Self {
self.tokens.insert(
token.into(),
Principal {
client_id: Some(client_id),
scopes: Scopes::new(Scope::BUSINESS_LOGIC),
},
);
self
}
pub fn with_ven(mut self, token: impl Into<String>, client_id: ClientId) -> Self {
self.tokens.insert(
token.into(),
Principal {
client_id: Some(client_id),
scopes: Scopes::new(Scope::VEN),
},
);
self
}
pub fn with_token(
mut self,
token: impl Into<String>,
client_id: ClientId,
scopes: Scopes,
) -> Self {
self.tokens.insert(
token.into(),
Principal {
client_id: Some(client_id),
scopes,
},
);
self
}
pub fn allowing_anonymous(mut self) -> Self {
self.allow_anonymous = true;
self
}
}
pub(crate) fn constant_time_eq(a: &str, b: &str) -> bool {
let (a, b) = (a.as_bytes(), b.as_bytes());
if a.len() != b.len() {
return false;
}
a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
#[async_trait]
impl Authenticator for StaticTokenAuth {
async fn authenticate(&self, bearer: Option<&str>) -> Result<Principal, AuthError> {
let Some(token) = bearer else {
return if self.allow_anonymous {
Ok(Principal::anonymous())
} else {
Err(AuthError::Missing)
};
};
self.tokens
.iter()
.fold(None, |found, (known, principal)| {
if constant_time_eq(known, token) {
Some(principal)
} else {
found
}
})
.cloned()
.ok_or(AuthError::Invalid)
}
fn token_url(&self) -> String {
self.token_url.clone()
}
fn allows_anonymous(&self) -> bool {
self.allow_anonymous
}
}
pub fn bearer_from_header(value: Option<&str>) -> Option<&str> {
let value = value?;
let (scheme, token) = value.split_once(' ')?;
scheme
.eq_ignore_ascii_case("Bearer")
.then_some(token.trim())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scope_strings_round_trip() {
for s in Scope::ALL {
assert_eq!(s.as_str().parse::<Scope>().unwrap(), s);
}
}
#[test]
fn unknown_scopes_are_ignored_not_fatal() {
let s = Scopes::parse("read_all openid profile write_events");
assert!(s.contains(Scope::ReadAll));
assert!(s.contains(Scope::WriteEvents));
assert_eq!(s.as_slice().len(), 2);
}
#[test]
fn the_role_falls_out_of_the_scopes() {
assert!(Scopes::new(Scope::BUSINESS_LOGIC).is_business_logic());
assert!(!Scopes::new(Scope::VEN).is_business_logic());
assert!(!Scopes::none().is_business_logic());
}
#[test]
fn read_bl_alone_is_not_business_logic() {
let only_read_bl = Scopes::new([Scope::ReadBl]);
assert!(!only_read_bl.is_business_logic());
assert!(only_read_bl.contains(Scope::ReadBl));
assert!(Scopes::new([Scope::ReadAll, Scope::ReadBl]).is_business_logic());
}
#[test]
fn bearer_extraction_is_case_insensitive_about_the_scheme() {
assert_eq!(bearer_from_header(Some("Bearer abc")), Some("abc"));
assert_eq!(bearer_from_header(Some("bearer abc")), Some("abc"));
assert_eq!(bearer_from_header(Some("Basic abc")), None);
assert_eq!(bearer_from_header(None), None);
}
#[tokio::test]
async fn static_tokens_resolve_to_principals() {
let auth = StaticTokenAuth::new("https://vtn/auth/token")
.with_business_logic("bl-token", ClientId::new("bl").unwrap())
.with_ven("ven-token", ClientId::new("ven-1").unwrap());
let bl = auth.authenticate(Some("bl-token")).await.unwrap();
assert!(bl.is_business_logic());
let ven = auth.authenticate(Some("ven-token")).await.unwrap();
assert!(!ven.is_business_logic());
assert_eq!(ven.client_id.unwrap().as_str(), "ven-1");
assert_eq!(
auth.authenticate(Some("nope")).await.unwrap_err(),
AuthError::Invalid
);
assert_eq!(
auth.authenticate(None).await.unwrap_err(),
AuthError::Missing
);
}
#[tokio::test]
async fn an_anonymous_vtn_admits_everyone_without_scopes() {
let auth = AnonymousAuth::new("https://vtn/auth/token");
let p = auth.authenticate(None).await.unwrap();
assert!(p.client_id.is_none());
assert!(p.scopes.is_empty(), "an anonymous reader can never write");
}
#[test]
fn token_comparison_does_not_short_circuit() {
assert!(constant_time_eq("abcdef", "abcdef"));
assert!(!constant_time_eq("abcdef", "abcdeg"));
assert!(!constant_time_eq("abc", "abcdef"));
}
}