use std::sync::Arc;
use async_trait::async_trait;
use serde_json::{Map, Value};
use super::linking::{CredentialClass, CredentialLink};
use super::principal::{Issuer, Principal};
use crate::auth::{AuthContext, SessionValidator, PRINCIPAL_CLAIM};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Presentation {
Bearer {
token: String,
},
ApiKey {
key: String,
},
Cookie {
header: String,
},
SignedChallenge {
scheme: String,
key_id: String,
challenge: String,
signature: String,
},
}
impl Presentation {
pub fn kind_label(&self) -> &str {
match self {
Self::Bearer { .. } => "bearer",
Self::ApiKey { .. } => "apikey",
Self::Cookie { .. } => "cookie",
Self::SignedChallenge { scheme, .. } => scheme,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthnRejection {
Unsupported {
authenticator: String,
presented: String,
},
Malformed(String),
Expired,
SignatureInvalid,
UnknownCredential,
Revoked,
Backend(String),
}
impl std::fmt::Display for AuthnRejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Unsupported {
authenticator,
presented,
} => write!(
f,
"authenticator `{authenticator}` does not handle `{presented}` material"
),
Self::Malformed(why) => write!(f, "malformed credential: {why}"),
Self::Expired => f.write_str("credential expired"),
Self::SignatureInvalid => f.write_str("credential signature did not verify"),
Self::UnknownCredential => f.write_str("unknown credential"),
Self::Revoked => f.write_str("credential revoked"),
Self::Backend(why) => write!(f, "authenticator backend error: {why}"),
}
}
}
impl std::error::Error for AuthnRejection {}
impl AuthnRejection {
pub fn unsupported(authenticator: impl Into<String>, presented: &Presentation) -> Self {
Self::Unsupported {
authenticator: authenticator.into(),
presented: presented.kind_label().to_string(),
}
}
pub fn is_unsupported(&self) -> bool {
matches!(self, Self::Unsupported { .. })
}
pub fn is_backend_failure(&self) -> bool {
matches!(self, Self::Backend(_))
}
}
#[derive(Debug, Clone)]
pub struct Authenticated {
principal: Principal,
session_id: String,
roles: Vec<String>,
claims: Value,
}
impl Authenticated {
pub fn new(
principal: Principal,
session_id: impl Into<String>,
roles: Vec<String>,
claims: Value,
) -> Self {
Self {
principal,
session_id: session_id.into(),
roles,
claims,
}
}
pub fn principal(&self) -> &Principal {
&self.principal
}
pub fn session_id(&self) -> &str {
&self.session_id
}
pub fn roles(&self) -> &[String] {
&self.roles
}
pub fn claims(&self) -> &Value {
&self.claims
}
pub fn into_auth_context(self) -> AuthContext {
let Self {
principal,
session_id,
roles,
claims,
} = self;
let mut metadata: Map<String, Value> = match claims {
Value::Object(m) => m,
Value::Null => Map::new(),
other => {
let mut m = Map::new();
m.insert("claims".to_string(), other);
m
}
};
metadata.insert(
PRINCIPAL_CLAIM.to_string(),
Value::String(principal.to_string()),
);
AuthContext::new(
principal.as_legacy_user_id(),
session_id,
roles,
Value::Object(metadata),
)
}
}
#[async_trait]
pub trait Authenticator: Send + Sync + 'static {
fn name(&self) -> &str;
fn accepts(&self, presentation: &Presentation) -> bool;
async fn authenticate(
&self,
presentation: &Presentation,
) -> Result<Authenticated, AuthnRejection>;
}
#[derive(Clone, Default)]
pub struct AuthenticatorChain {
authenticators: Vec<Arc<dyn Authenticator>>,
}
impl std::fmt::Debug for AuthenticatorChain {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AuthenticatorChain")
.field("authenticators", &self.names())
.finish()
}
}
impl AuthenticatorChain {
pub fn new() -> Self {
Self::default()
}
pub fn with(mut self, authenticator: Arc<dyn Authenticator>) -> Self {
self.authenticators.push(authenticator);
self
}
pub fn try_with(self, authenticator: Arc<dyn Authenticator>) -> Result<Self, String> {
if self.names().contains(&authenticator.name()) {
return Err(authenticator.name().to_string());
}
Ok(self.with(authenticator))
}
pub fn names(&self) -> Vec<&str> {
self.authenticators.iter().map(|a| a.name()).collect()
}
pub fn is_empty(&self) -> bool {
self.authenticators.is_empty()
}
pub async fn authenticate(
&self,
presentation: &Presentation,
) -> Result<Authenticated, AuthnRejection> {
let mut last = AuthnRejection::unsupported("<empty chain>", presentation);
for authenticator in &self.authenticators {
if !authenticator.accepts(presentation) {
continue;
}
match authenticator.authenticate(presentation).await {
Ok(ok) => return Ok(ok),
Err(e) if e.is_unsupported() => last = e,
Err(e) => return Err(e),
}
}
Err(last)
}
}
#[async_trait]
impl SessionValidator for AuthenticatorChain {
async fn validate(&self, cookie_value: &str) -> Option<AuthContext> {
let as_cookie = Presentation::Cookie {
header: cookie_value.to_string(),
};
match self.authenticate(&as_cookie).await {
Ok(ok) => return Some(ok.into_auth_context()),
Err(e) if !e.is_unsupported() => return None,
Err(_) => {}
}
let as_bearer = Presentation::Bearer {
token: cookie_value.trim().to_string(),
};
self.authenticate(&as_bearer)
.await
.ok()
.map(Authenticated::into_auth_context)
}
}
#[derive(Debug, Clone)]
pub struct VerifiedClaims {
pub subject: String,
pub roles: Vec<String>,
pub claims: Value,
}
#[async_trait]
pub trait TokenVerifier: Send + Sync + 'static {
fn issuer(&self) -> Issuer;
async fn verify(&self, token: &str) -> Result<VerifiedClaims, AuthnRejection>;
}
pub struct BearerJwtAuthenticator<V: TokenVerifier> {
name: String,
verifier: V,
}
impl<V: TokenVerifier> BearerJwtAuthenticator<V> {
pub fn new(name: impl Into<String>, verifier: V) -> Self {
Self {
name: name.into(),
verifier,
}
}
}
#[async_trait]
impl<V: TokenVerifier> Authenticator for BearerJwtAuthenticator<V> {
fn name(&self) -> &str {
&self.name
}
fn accepts(&self, presentation: &Presentation) -> bool {
matches!(presentation, Presentation::Bearer { .. })
}
async fn authenticate(
&self,
presentation: &Presentation,
) -> Result<Authenticated, AuthnRejection> {
let Presentation::Bearer { token } = presentation else {
return Err(AuthnRejection::unsupported(&self.name, presentation));
};
let verified = self.verifier.verify(token).await?;
let principal = Principal::new(self.verifier.issuer(), verified.subject.clone())
.map_err(|e| AuthnRejection::Malformed(e.to_string()))?;
Ok(Authenticated::new(
principal,
String::new(),
verified.roles,
verified.claims,
))
}
}
pub type ApiKeyDigest = Arc<dyn Fn(&str) -> String + Send + Sync>;
pub struct ApiKeyAuthenticator {
name: String,
links: Arc<dyn CredentialLink>,
digest: ApiKeyDigest,
}
impl ApiKeyAuthenticator {
pub fn new(name: impl Into<String>, links: Arc<dyn CredentialLink>, digest: ApiKeyDigest) -> Self {
Self {
name: name.into(),
links,
digest,
}
}
pub fn plaintext(name: impl Into<String>, links: Arc<dyn CredentialLink>) -> Self {
Self::new(name, links, Arc::new(|k: &str| k.to_string()))
}
}
#[async_trait]
impl Authenticator for ApiKeyAuthenticator {
fn name(&self) -> &str {
&self.name
}
fn accepts(&self, presentation: &Presentation) -> bool {
matches!(
presentation,
Presentation::ApiKey { .. } | Presentation::Bearer { .. }
)
}
async fn authenticate(
&self,
presentation: &Presentation,
) -> Result<Authenticated, AuthnRejection> {
let raw = match presentation {
Presentation::ApiKey { key } => key,
Presentation::Bearer { token } => token,
_ => return Err(AuthnRejection::unsupported(&self.name, presentation)),
};
if raw.is_empty() {
return Err(AuthnRejection::Malformed("empty api key".into()));
}
let locator = (self.digest)(raw);
let link = self
.links
.resolve(CredentialClass::ApiKey, &locator)
.await
.map_err(|e| AuthnRejection::Backend(e.to_string()))?
.ok_or(AuthnRejection::UnknownCredential)?;
if link.is_revoked() {
return Err(AuthnRejection::Revoked);
}
if link.is_expired_at(chrono::Utc::now()) {
return Err(AuthnRejection::Expired);
}
Ok(Authenticated::new(
link.principal().clone(),
String::new(),
link.roles().to_vec(),
link.claims().clone(),
))
}
}
pub struct CookieAuthenticator {
name: String,
cookie_name: String,
inner: Arc<dyn Authenticator>,
allow_bare_token: bool,
}
impl CookieAuthenticator {
pub fn new(
name: impl Into<String>,
cookie_name: impl Into<String>,
inner: Arc<dyn Authenticator>,
) -> Self {
Self {
name: name.into(),
cookie_name: cookie_name.into(),
inner,
allow_bare_token: true,
}
}
pub fn strict(mut self) -> Self {
self.allow_bare_token = false;
self
}
fn extract<'a>(&self, header: &'a str) -> Option<&'a str> {
if !header.contains('=') {
return self.allow_bare_token.then(|| header.trim());
}
for pair in header.split(';') {
let pair = pair.trim();
if let Some(rest) = pair.strip_prefix(&self.cookie_name) {
if let Some(val) = rest.strip_prefix('=') {
return Some(val.trim());
}
}
}
None
}
}
#[async_trait]
impl Authenticator for CookieAuthenticator {
fn name(&self) -> &str {
&self.name
}
fn accepts(&self, presentation: &Presentation) -> bool {
matches!(presentation, Presentation::Cookie { .. })
}
async fn authenticate(
&self,
presentation: &Presentation,
) -> Result<Authenticated, AuthnRejection> {
let Presentation::Cookie { header } = presentation else {
return Err(AuthnRejection::unsupported(&self.name, presentation));
};
let token = self.extract(header).ok_or_else(|| {
AuthnRejection::Malformed(format!("no `{}` cookie in header", self.cookie_name))
})?;
if token.is_empty() {
return Err(AuthnRejection::Malformed(format!(
"`{}` cookie is empty",
self.cookie_name
)));
}
let inner = Presentation::Bearer {
token: token.to_string(),
};
match self.inner.authenticate(&inner).await {
Err(e) if e.is_unsupported() => {
Err(AuthnRejection::unsupported(&self.name, presentation))
}
other => other,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::identity::linking::{InMemoryCredentialLink, LinkedCredential};
const UUID: &str = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
struct FakeIdp;
#[async_trait]
impl TokenVerifier for FakeIdp {
fn issuer(&self) -> Issuer {
Issuer::Idp
}
async fn verify(&self, token: &str) -> Result<VerifiedClaims, AuthnRejection> {
match token {
"good" => Ok(VerifiedClaims {
subject: UUID.to_string(),
roles: vec!["user".into()],
claims: serde_json::json!({"org_id": "acme"}),
}),
"stale" => Err(AuthnRejection::Expired),
"notauuid" => Ok(VerifiedClaims {
subject: "alice".to_string(),
roles: vec![],
claims: Value::Null,
}),
_ => Err(AuthnRejection::SignatureInvalid),
}
}
}
fn bearer(t: &str) -> Presentation {
Presentation::Bearer {
token: t.to_string(),
}
}
#[tokio::test]
async fn bearer_authenticator_produces_a_verified_principal() {
let a = BearerJwtAuthenticator::new("idp-bearer", FakeIdp);
let ok = a.authenticate(&bearer("good")).await.unwrap();
assert_eq!(ok.principal().to_string(), format!("idp:{UUID}"));
assert_eq!(ok.roles(), ["user"]);
}
#[tokio::test]
async fn bearer_authenticator_rejects_with_typed_errors() {
let a = BearerJwtAuthenticator::new("idp-bearer", FakeIdp);
assert_eq!(
a.authenticate(&bearer("stale")).await.unwrap_err(),
AuthnRejection::Expired
);
assert_eq!(
a.authenticate(&bearer("forged")).await.unwrap_err(),
AuthnRejection::SignatureInvalid
);
assert!(matches!(
a.authenticate(&bearer("notauuid")).await.unwrap_err(),
AuthnRejection::Malformed(_)
));
assert!(a
.authenticate(&Presentation::ApiKey { key: "x".into() })
.await
.unwrap_err()
.is_unsupported());
}
async fn links_with_key() -> Arc<InMemoryCredentialLink> {
let links = Arc::new(InMemoryCredentialLink::new());
let p: Principal = format!("idp:{UUID}").parse().unwrap();
links
.link(
LinkedCredential::new(CredentialClass::ApiKey, "digest-of-k1", p)
.with_roles(vec!["service".into()]),
)
.await
.unwrap();
links
}
#[tokio::test]
async fn api_key_authenticator_resolves_and_rejects() {
let links = links_with_key().await;
let a = ApiKeyAuthenticator::new(
"apikey",
links.clone(),
Arc::new(|k: &str| format!("digest-of-{k}")),
);
let ok = a
.authenticate(&Presentation::ApiKey { key: "k1".into() })
.await
.unwrap();
assert_eq!(ok.principal().to_string(), format!("idp:{UUID}"));
assert_eq!(ok.roles(), ["service"]);
assert_eq!(
a.authenticate(&Presentation::ApiKey { key: "nope".into() })
.await
.unwrap_err(),
AuthnRejection::UnknownCredential
);
assert!(matches!(
a.authenticate(&Presentation::ApiKey { key: "".into() })
.await
.unwrap_err(),
AuthnRejection::Malformed(_)
));
}
#[tokio::test]
async fn api_key_authenticator_honours_revocation_and_expiry() {
let links = Arc::new(InMemoryCredentialLink::new());
let p: Principal = format!("idp:{UUID}").parse().unwrap();
links
.link(LinkedCredential::new(CredentialClass::ApiKey, "dead", p.clone()).revoked())
.await
.unwrap();
links
.link(
LinkedCredential::new(CredentialClass::ApiKey, "old", p)
.expiring_at(chrono::Utc::now() - chrono::Duration::hours(1)),
)
.await
.unwrap();
let a = ApiKeyAuthenticator::plaintext("apikey", links);
assert_eq!(
a.authenticate(&Presentation::ApiKey { key: "dead".into() })
.await
.unwrap_err(),
AuthnRejection::Revoked
);
assert_eq!(
a.authenticate(&Presentation::ApiKey { key: "old".into() })
.await
.unwrap_err(),
AuthnRejection::Expired
);
}
#[tokio::test]
async fn cookie_authenticator_unwraps_and_delegates() {
let inner = Arc::new(BearerJwtAuthenticator::new("idp-bearer", FakeIdp));
let a = CookieAuthenticator::new("idp-cookie", "access_token", inner);
let ok = a
.authenticate(&Presentation::Cookie {
header: "theme=dark; access_token=good; other=1".into(),
})
.await
.unwrap();
assert_eq!(ok.principal().to_string(), format!("idp:{UUID}"));
let ok = a
.authenticate(&Presentation::Cookie {
header: "good".into(),
})
.await
.unwrap();
assert_eq!(ok.principal().to_string(), format!("idp:{UUID}"));
assert!(matches!(
a.authenticate(&Presentation::Cookie {
header: "theme=dark".into()
})
.await
.unwrap_err(),
AuthnRejection::Malformed(_)
));
assert_eq!(
a.authenticate(&Presentation::Cookie {
header: "access_token=stale".into()
})
.await
.unwrap_err(),
AuthnRejection::Expired
);
}
#[tokio::test]
async fn cookie_extraction_does_not_match_a_suffix_cookie() {
let inner = Arc::new(BearerJwtAuthenticator::new("idp-bearer", FakeIdp));
let a = CookieAuthenticator::new("idp-cookie", "access_token", inner);
let err = a
.authenticate(&Presentation::Cookie {
header: "xaccess_token=good".into(),
})
.await
.unwrap_err();
assert!(matches!(err, AuthnRejection::Malformed(_)), "{err:?}");
}
#[tokio::test]
async fn chain_short_circuits_on_a_real_failure() {
let links = links_with_key().await;
let chain = AuthenticatorChain::new()
.with(Arc::new(BearerJwtAuthenticator::new("idp-bearer", FakeIdp)))
.with(Arc::new(ApiKeyAuthenticator::plaintext("apikey", links)));
assert_eq!(chain.names(), ["idp-bearer", "apikey"]);
assert_eq!(
chain.authenticate(&bearer("stale")).await.unwrap_err(),
AuthnRejection::Expired
);
}
#[tokio::test]
async fn empty_chain_reports_unsupported_not_success() {
let chain = AuthenticatorChain::new();
assert!(chain.is_empty());
assert!(chain
.authenticate(&bearer("good"))
.await
.unwrap_err()
.is_unsupported());
assert!(chain.validate("anything").await.is_none());
}
#[tokio::test]
async fn chain_is_a_session_validator() {
let chain = AuthenticatorChain::new().with(Arc::new(CookieAuthenticator::new(
"idp-cookie",
"access_token",
Arc::new(BearerJwtAuthenticator::new("idp-bearer", FakeIdp)),
)));
let ctx = chain.validate("access_token=good").await.unwrap();
assert_eq!(ctx.user_id, UUID);
assert_eq!(
ctx.principal().map(|p| p.to_string()),
Some(format!("idp:{UUID}"))
);
assert!(chain.validate("access_token=forged").await.is_none());
}
}