use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use base64::engine::general_purpose::STANDARD;
use base64::Engine as _;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
const DEFAULT_INTROSPECTION: &str = "https://api.sylphx.com/v1/oauth/introspect";
const MAX_TOKEN_BYTES: usize = 4096;
const MAX_CACHE_TTL: Duration = Duration::from_secs(60);
const MAX_CACHE_ENTRIES: usize = 10_000;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reply {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Grant {
pub subject: String,
pub client_id: String,
pub scopes: Vec<String>,
pub expires_at: i64,
pub issued_at: i64,
}
impl Grant {
pub fn has(&self, scope: &str) -> bool {
self.scopes.iter().any(|s| s == scope)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rejection {
Inactive,
Audience,
Issuer,
TokenType,
Expired,
Subject,
Malformed,
}
impl std::fmt::Display for Rejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Rejection::Inactive => "the token is not active",
Rejection::Audience => "the token is not for this resource",
Rejection::Issuer => "the token was not issued by the expected authorization server",
Rejection::TokenType => "the token type is not accepted",
Rejection::Expired => "the token is expired",
Rejection::Subject => "the token has no subject",
Rejection::Malformed => "the introspection answer is malformed",
})
}
}
pub fn grant_from_introspection(
body: &Value,
resource: &str,
issuer: &str,
now: i64,
) -> Result<Grant, Rejection> {
let obj = body.as_object().ok_or(Rejection::Malformed)?;
if obj.get("active").and_then(Value::as_bool) != Some(true) {
return Err(Rejection::Inactive);
}
let str_of = |k: &str| obj.get(k).and_then(Value::as_str).unwrap_or("");
let aud_ok = match obj.get("aud") {
Some(Value::String(s)) => s == resource,
Some(Value::Array(a)) => a.iter().any(|v| v.as_str() == Some(resource)),
_ => false,
};
if !aud_ok {
return Err(Rejection::Audience);
}
if str_of("iss") != issuer {
return Err(Rejection::Issuer);
}
if !str_of("token_type").eq_ignore_ascii_case("bearer") {
return Err(Rejection::TokenType);
}
let exp = obj.get("exp").and_then(Value::as_i64).unwrap_or(0);
if exp <= now {
return Err(Rejection::Expired);
}
let sub = str_of("sub");
if sub.is_empty() {
return Err(Rejection::Subject);
}
Ok(Grant {
subject: sub.to_string(),
client_id: str_of("client_id").to_string(),
scopes: str_of("scope")
.split_whitespace()
.map(String::from)
.collect(),
expires_at: exp,
issued_at: obj.get("iat").and_then(Value::as_i64).unwrap_or(0),
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Challenge {
kind: Kind,
metadata_url: String,
scope: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Kind {
NoCredentials,
InvalidToken(&'static str),
InvalidRequest,
InsufficientScope(Vec<String>),
Unavailable,
}
fn clean(v: &str) -> String {
v.chars()
.filter(|c| *c != '"' && *c != '\\' && !c.is_control())
.collect()
}
impl Challenge {
pub fn status(&self) -> u16 {
match self.kind {
Kind::NoCredentials | Kind::InvalidToken(_) => 401,
Kind::InvalidRequest => 400,
Kind::InsufficientScope(_) => 403,
Kind::Unavailable => 503,
}
}
pub fn www_authenticate(&self) -> String {
let meta = format!("resource_metadata=\"{}\"", clean(&self.metadata_url));
let scope = if self.scope.is_empty() {
String::new()
} else {
format!(", scope=\"{}\"", clean(&self.scope))
};
match &self.kind {
Kind::NoCredentials => format!("Bearer {meta}{scope}"),
Kind::InvalidToken(d) => {
format!("Bearer error=\"invalid_token\", error_description=\"{}\", {meta}{scope}", clean(d))
}
Kind::InvalidRequest => format!(
"Bearer error=\"invalid_request\", error_description=\"malformed Authorization header\", {meta}"
),
Kind::InsufficientScope(needed) => format!(
"Bearer error=\"insufficient_scope\", scope=\"{}\", {meta}",
clean(&needed.join(" "))
),
Kind::Unavailable => String::new(),
}
}
pub fn reply(&self) -> Reply {
let (error, description) = match &self.kind {
Kind::NoCredentials => ("invalid_request", "authentication required"),
Kind::InvalidToken(d) => ("invalid_token", *d),
Kind::InvalidRequest => ("invalid_request", "malformed Authorization header"),
Kind::InsufficientScope(_) => (
"insufficient_scope",
"the token lacks a scope this operation needs",
),
Kind::Unavailable => ("temporarily_unavailable", ""),
};
let body = if self.kind == Kind::Unavailable {
json!({ "error": error })
} else {
json!({ "error": error, "error_description": description })
};
let mut headers = vec![("content-type".to_string(), "application/json".to_string())];
if self.kind == Kind::Unavailable {
headers.push(("retry-after".into(), "5".into()));
} else {
headers.push(("www-authenticate".into(), self.www_authenticate()));
}
Reply {
status: self.status(),
headers,
body: body.to_string(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigError(String);
impl std::fmt::Display for ConfigError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "resource configuration: {}", self.0)
}
}
impl std::error::Error for ConfigError {}
fn cfg(m: impl Into<String>) -> ConfigError {
ConfigError(m.into())
}
fn check_url(what: &str, raw: &str) -> Result<reqwest::Url, ConfigError> {
let url =
reqwest::Url::parse(raw).map_err(|_| cfg(format!("{what} is not an absolute URL")))?;
let host = url
.host_str()
.ok_or_else(|| cfg(format!("{what} has no host")))?;
let loopback = matches!(host, "localhost" | "127.0.0.1" | "[::1]");
match url.scheme() {
"https" => {}
"http" if loopback => {}
_ => {
return Err(cfg(format!(
"{what} must be https (http only for localhost)"
)))
}
}
if url.fragment().is_some() {
return Err(cfg(format!("{what} must not have a fragment")));
}
Ok(url)
}
pub struct ProtectedResourceBuilder {
resource: String,
issuer: String,
scopes: Vec<String>,
name: Option<String>,
credentials: Option<(String, String)>,
endpoint: String,
ttl: Duration,
timeout: Duration,
}
impl ProtectedResourceBuilder {
pub fn scopes_supported<I, S>(mut self, scopes: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.scopes = scopes.into_iter().map(Into::into).collect();
self
}
pub fn resource_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn client_credentials(mut self, id: impl Into<String>, secret: impl Into<String>) -> Self {
self.credentials = Some((id.into(), secret.into()));
self
}
pub fn introspection_endpoint(mut self, url: impl Into<String>) -> Self {
self.endpoint = url.into();
self
}
pub fn cache_ttl(mut self, ttl: Duration) -> Self {
self.ttl = ttl;
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn build(self) -> Result<ProtectedResource, ConfigError> {
let res = check_url("resource", &self.resource)?;
if res.query().is_some() {
return Err(cfg("resource must not have a query"));
}
let iss = check_url("authorization server", &self.issuer)?;
if iss.query().is_some() {
return Err(cfg("authorization server must not have a query"));
}
check_url("introspection endpoint", &self.endpoint)?;
let (id, secret) = self
.credentials
.ok_or_else(|| cfg("client credentials are required"))?;
if id.is_empty() || secret.is_empty() {
return Err(cfg("client id and secret must not be empty"));
}
let http = reqwest::Client::builder()
.timeout(self.timeout)
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|e| cfg(format!("http client: {e}")))?;
let origin = res.origin().ascii_serialization();
let path = res.path();
let metadata_path = if path.is_empty() || path == "/" {
"/.well-known/oauth-protected-resource".to_string()
} else {
format!("/.well-known/oauth-protected-resource{path}")
};
Ok(ProtectedResource {
resource: self.resource,
issuer: self.issuer.trim_end_matches('/').to_string(),
scopes: self.scopes,
name: self.name,
id,
secret,
endpoint: self.endpoint,
ttl: self.ttl.min(MAX_CACHE_TTL),
metadata_url: format!("{origin}{metadata_path}"),
metadata_path,
http,
cache: Mutex::new(HashMap::new()),
})
}
}
pub struct ProtectedResource {
resource: String,
issuer: String,
scopes: Vec<String>,
name: Option<String>,
id: String,
secret: String,
endpoint: String,
ttl: Duration,
metadata_path: String,
metadata_url: String,
http: reqwest::Client,
cache: Mutex<HashMap<[u8; 32], (Grant, Instant)>>,
}
impl std::fmt::Debug for ProtectedResource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ProtectedResource")
.field("resource", &self.resource)
.field("issuer", &self.issuer)
.field("client_id", &self.id)
.field("client_secret", &"<redacted>")
.finish_non_exhaustive()
}
}
fn now_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
enum Presented<'a> {
Bearer(&'a str),
OtherScheme,
Malformed,
}
fn parse_bearer(header: &str) -> Presented<'_> {
let (scheme, rest) = header.split_once(' ').unwrap_or((header, ""));
if !scheme.eq_ignore_ascii_case("bearer") {
return Presented::OtherScheme;
}
if rest.is_empty()
|| rest.len() > MAX_TOKEN_BYTES
|| rest.chars().any(|c| c.is_whitespace() || c.is_control())
{
return Presented::Malformed;
}
Presented::Bearer(rest)
}
fn form_encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
impl ProtectedResource {
pub fn builder(
resource: impl Into<String>,
authorization_server: impl Into<String>,
) -> ProtectedResourceBuilder {
ProtectedResourceBuilder {
resource: resource.into(),
issuer: authorization_server.into(),
scopes: Vec::new(),
name: None,
credentials: None,
endpoint: DEFAULT_INTROSPECTION.into(),
ttl: Duration::from_secs(30),
timeout: Duration::from_secs(5),
}
}
pub fn from_env() -> Result<Self, ConfigError> {
let get = |k: &str| std::env::var(k).map_err(|_| cfg(format!("{k} is not set")));
let mut b = Self::builder(get("SYLPHX_RESOURCE_URI")?, get("SYLPHX_AUTH_ISSUER")?)
.client_credentials(
get("SYLPHX_RESOURCE_CLIENT_ID")?,
get("SYLPHX_RESOURCE_CLIENT_SECRET")?,
);
if let Ok(s) = std::env::var("SYLPHX_RESOURCE_SCOPES") {
b = b.scopes_supported(s.split_whitespace().map(String::from));
}
if let Ok(u) = std::env::var("SYLPHX_INTROSPECTION_URL") {
b = b.introspection_endpoint(u);
}
b.build()
}
pub fn metadata(&self) -> Value {
let mut doc = json!({
"resource": self.resource,
"authorization_servers": [self.issuer],
"scopes_supported": self.scopes,
"bearer_methods_supported": ["header"],
});
if let Some(n) = &self.name {
doc["resource_name"] = json!(n);
}
doc
}
pub fn metadata_path(&self) -> String {
self.metadata_path.clone()
}
pub fn metadata_url(&self) -> String {
self.metadata_url.clone()
}
pub fn metadata_response(&self) -> Reply {
Reply {
status: 200,
headers: vec![
("content-type".into(), "application/json".into()),
("cache-control".into(), "public, max-age=300".into()),
],
body: self.metadata().to_string(),
}
}
fn challenge(&self, kind: Kind, scope: &[&str]) -> Challenge {
let scope = if scope.is_empty() {
self.scopes.join(" ")
} else {
scope.join(" ")
};
Challenge {
kind,
metadata_url: self.metadata_url.clone(),
scope,
}
}
pub async fn authenticate(
&self,
authorization_header: Option<&str>,
) -> Result<Grant, Challenge> {
self.authenticate_for(authorization_header, &[]).await
}
async fn authenticate_for(
&self,
authorization_header: Option<&str>,
needed: &[&str],
) -> Result<Grant, Challenge> {
let Some(header) = authorization_header else {
return Err(self.challenge(Kind::NoCredentials, needed));
};
let token = match parse_bearer(header) {
Presented::Bearer(token) => token,
Presented::OtherScheme => return Err(self.challenge(Kind::NoCredentials, needed)),
Presented::Malformed => return Err(self.challenge(Kind::InvalidRequest, needed)),
};
let key: [u8; 32] = Sha256::digest(token.as_bytes()).into();
if !self.ttl.is_zero() {
let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some((grant, until)) = cache.get(&key) {
if Instant::now() < *until && grant.expires_at > now_secs() {
return Ok(grant.clone());
}
cache.remove(&key);
}
}
let answer = self
.introspect(token)
.await
.map_err(|_| self.challenge(Kind::Unavailable, &[]))?;
let now = now_secs();
match grant_from_introspection(&answer, &self.resource, &self.issuer, now) {
Ok(grant) => {
if !self.ttl.is_zero() {
let life = self
.ttl
.min(Duration::from_secs((grant.expires_at - now).max(0) as u64));
let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
if cache.len() >= MAX_CACHE_ENTRIES {
let t = Instant::now();
cache.retain(|_, (_, until)| *until > t);
if cache.len() >= MAX_CACHE_ENTRIES {
cache.clear();
}
}
cache.insert(key, (grant.clone(), Instant::now() + life));
}
Ok(grant)
}
Err(r) => Err(self.challenge(
Kind::InvalidToken(match r {
Rejection::Expired => "the access token expired",
Rejection::Audience => "the access token is not for this resource",
Rejection::TokenType => "sender-constrained tokens are not accepted",
_ => "the access token is invalid",
}),
needed,
)),
}
}
pub fn require(&self, grant: &Grant, needed: &[&str]) -> Result<(), Challenge> {
if needed.iter().all(|s| grant.has(s)) {
Ok(())
} else {
Err(self.challenge(
Kind::InsufficientScope(needed.iter().map(|s| s.to_string()).collect()),
needed,
))
}
}
pub async fn authorize(
&self,
authorization_header: Option<&str>,
needed: &[&str],
) -> Result<Grant, Challenge> {
let grant = self.authenticate_for(authorization_header, needed).await?;
self.require(&grant, needed)?;
Ok(grant)
}
async fn introspect(&self, token: &str) -> Result<Value, ()> {
let basic = STANDARD.encode(format!("{}:{}", self.id, self.secret));
let resp = self
.http
.post(&self.endpoint)
.header("authorization", format!("Basic {basic}"))
.header("content-type", "application/x-www-form-urlencoded")
.header("accept", "application/json")
.body(format!("token={}", form_encode(token)))
.send()
.await
.map_err(|_| ())?;
if resp.status().as_u16() != 200 {
return Err(());
}
resp.json::<Value>().await.map_err(|_| ())
}
}