use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use http::HeaderMap;
use jsonwebtoken::{Algorithm, DecodingKey, Validation};
use serde_json::{Map, Value};
use tokio::sync::Mutex;
#[cfg(feature = "axum")]
pub mod axum;
pub const IDENTITY_HEADER: &str = "x-jiayang-identity";
const MAX_AGE_SECONDS: u64 = 300;
const COOLDOWN_SECONDS: u64 = 10;
const RETRY_SECONDS: u64 = 1;
const FETCH_TIMEOUT: Duration = Duration::from_secs(3);
const MAX_JWKS_BYTES: usize = 1 << 20;
const MIN_RSA_BITS: usize = 2048;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("unauthorized: {0}")]
pub struct Unauthorized(pub &'static str);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
User,
Service,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct User {
pub kind: Kind,
pub sub: String,
pub email: Option<String>,
pub role: String,
pub workspace_id: String,
pub agent_name: Option<String>,
}
impl User {
pub fn is_agent(&self) -> bool {
self.agent_name.is_some()
}
}
const AGENT_PREFIX: &str = "agent:";
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("forbidden: this needs {0}")]
pub struct Forbidden(pub Role);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Role {
Viewer,
Editor,
Owner,
}
impl Role {
fn parse(value: &str) -> Option<Self> {
match value {
"viewer" => Some(Self::Viewer),
"editor" => Some(Self::Editor),
"owner" => Some(Self::Owner),
_ => None,
}
}
}
impl std::fmt::Display for Role {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Viewer => "viewer",
Self::Editor => "editor",
Self::Owner => "owner",
})
}
}
impl User {
pub fn has_role(&self, least: Role) -> bool {
Role::parse(&self.role).is_some_and(|has| has >= least)
}
pub fn require_role(&self, least: Role) -> Result<(), Forbidden> {
if self.has_role(least) { Ok(()) } else { Err(Forbidden(least)) }
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Provider {
Stripe,
Github,
Slack,
Shopify,
StandardWebhooks,
HmacSha256,
}
impl Provider {
pub const ALL: [Self; 6] =
[Self::Stripe, Self::Github, Self::Slack, Self::Shopify, Self::StandardWebhooks, Self::HmacSha256];
pub const fn name(self) -> &'static str {
match self {
Self::Stripe => "stripe",
Self::Github => "github",
Self::Slack => "slack",
Self::Shopify => "shopify",
Self::StandardWebhooks => "standard_webhooks",
Self::HmacSha256 => "hmac_sha256",
}
}
pub fn from_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|provider| provider.name() == name)
}
}
impl std::fmt::Display for Provider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Webhook {
pub provider: Provider,
pub pattern: String,
pub delivery: Option<String>,
pub signed_at: Option<u64>,
pub workspace_id: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Config {
pub app_id: String,
pub issuer: String,
pub jwks_url: String,
pub dev: bool,
}
impl Config {
pub fn from_env() -> Result<Self, Unauthorized> {
Self::from_vars(|name| std::env::var(name).ok())
}
fn from_vars(var: impl Fn(&str) -> Option<String>) -> Result<Self, Unauthorized> {
let text = |name| var(name).unwrap_or_default();
Self {
app_id: text("JIAYANG_APP_ID"),
issuer: text("JIAYANG_IDENTITY_ISSUER"),
jwks_url: text("JIAYANG_JWKS_URL"),
dev: var("JIAYANG_DEV").as_deref() == Some("1"),
}
.checked()
}
fn checked(self) -> Result<Self, Unauthorized> {
if self.app_id.is_empty() || self.issuer.is_empty() || self.jwks_url.is_empty() {
return Err(Unauthorized("JIAYANG_APP_ID, JIAYANG_IDENTITY_ISSUER and JIAYANG_JWKS_URL must be set"));
}
if !origin_allowed(&self.issuer, &self.jwks_url, self.dev) {
return Err(Unauthorized(
"JIAYANG_IDENTITY_ISSUER and JIAYANG_JWKS_URL must use https, except under jiayang dev (JIAYANG_DEV=1, on this machine)",
));
}
Ok(self)
}
}
fn origin_allowed(issuer: &str, jwks_url: &str, dev: bool) -> bool {
if is_https(issuer) && is_https(jwks_url) {
return true;
}
dev && on_this_machine(issuer, false) && on_this_machine(jwks_url, true)
}
fn is_https(url: &str) -> bool {
url.get(..8).is_some_and(|scheme| scheme.eq_ignore_ascii_case("https://"))
}
fn on_this_machine(raw: &str, or_docker_host: bool) -> bool {
if raw.chars().any(|c| c == '\\' || c == '@' || c.is_whitespace()) {
return false;
}
let Ok(url) = reqwest::Url::parse(raw) else { return false };
if url.scheme() != "http" || !url.username().is_empty() || url.password().is_some() {
return false;
}
let host = written_host(raw);
if url.host_str() != Some(host.as_str()) {
return false;
}
match host.as_str() {
"127.0.0.1" | "localhost" | "[::1]" => true,
"host.docker.internal" => or_docker_host,
_ => false,
}
}
fn written_host(raw: &str) -> String {
let after = raw.split_once("//").map_or("", |(_, rest)| rest);
let authority = after.split(['/', '?', '#']).next().unwrap_or("").to_ascii_lowercase();
match authority.find(']') {
Some(end) if authority.starts_with('[') => authority[..=end].to_owned(),
_ => authority.split(':').next().unwrap_or("").to_owned(),
}
}
pub type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;
pub type FetchFuture = Pin<Box<dyn Future<Output = Result<Vec<u8>, String>> + Send>>;
pub type Fetch = Arc<dyn Fn(String) -> FetchFuture + Send + Sync>;
fn system_clock() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
#[derive(Clone)]
pub struct Verifier {
config: Config,
keys: Arc<KeySet>,
now: Clock,
}
impl Verifier {
pub fn new(config: Config) -> Result<Self, Unauthorized> {
let config = config.checked()?;
let keys = Arc::new(KeySet::new(&config.jwks_url));
Ok(Self { config, keys, now: Arc::new(system_clock) })
}
pub fn from_env() -> Result<Self, Unauthorized> {
Self::new(Config::from_env()?)
}
pub fn with_clock(mut self, now: Clock) -> Self {
self.now = now;
self
}
pub fn with_key_set(mut self, keys: KeySet) -> Self {
self.keys = Arc::new(keys);
self
}
pub async fn require_user(&self, headers: &HeaderMap) -> Result<User, Unauthorized> {
self.verify(token_in(headers)?).await
}
pub async fn verify(&self, token: &str) -> Result<User, Unauthorized> {
const INVALID: Unauthorized = Unauthorized("invalid identity token");
let claims = self.claims(token, &self.config.app_id).await?;
let text = |name: &str| claims.get(name).and_then(Value::as_str);
if text("aud").is_none() {
return Err(INVALID);
}
let kind = match text("kind") {
Some("user") => Kind::User,
Some("service") => Kind::Service,
_ => return Err(INVALID),
};
let sub = text("sub").filter(|s| !s.is_empty()).ok_or(INVALID)?;
let email = match kind {
Kind::User => Some(text("email").ok_or(INVALID)?.to_owned()),
Kind::Service => None,
};
let role = text("role").ok_or(INVALID)?;
let workspace_id = text("wid").ok_or(INVALID)?;
let agent_name = match (kind, sub.strip_prefix(AGENT_PREFIX)) {
(Kind::Service, Some(id)) => {
let name = text("agent_name").filter(|n| !n.is_empty() && !id.is_empty()).ok_or(INVALID)?;
Some(name.to_owned())
}
_ => None,
};
Ok(User {
kind,
sub: sub.to_owned(),
email,
role: role.to_owned(),
workspace_id: workspace_id.to_owned(),
agent_name,
})
}
pub async fn require_webhook(&self, headers: &HeaderMap, providers: &[Provider]) -> Result<Webhook, Unauthorized> {
self.verify_webhook(token_in(headers)?, providers).await
}
pub async fn verify_webhook(&self, token: &str, providers: &[Provider]) -> Result<Webhook, Unauthorized> {
const INVALID: Unauthorized = Unauthorized("invalid webhook token");
if providers.is_empty() {
return Err(Unauthorized("no provider named"));
}
let claims = self.claims(token, &format!("{WEBHOOK_AUDIENCE}{}", self.config.app_id)).await?;
let text = |name: &str| claims.get(name).and_then(Value::as_str);
if text("aud").is_none() || text("kind") != Some("webhook") || text("sub").is_none_or(str::is_empty) {
return Err(INVALID);
}
let workspace_id = text("wid").ok_or(INVALID)?;
let provider = text("provider")
.and_then(Provider::from_name)
.filter(|provider| providers.contains(provider))
.ok_or(Unauthorized("not a webhook this route takes"))?;
let pattern = text("pattern").filter(|p| !p.is_empty()).ok_or(INVALID)?;
let delivery = match claims.get("delivery") {
None => None,
Some(Value::String(delivery)) if !delivery.is_empty() => Some(delivery.clone()),
Some(_) => return Err(INVALID),
};
let signed_at = claims.get("signed_at").map(|value| whole_seconds(value).ok_or(INVALID)).transpose()?;
Ok(Webhook {
provider,
pattern: pattern.to_owned(),
delivery,
signed_at,
workspace_id: workspace_id.to_owned(),
})
}
async fn claims(&self, token: &str, audience: &str) -> Result<Map<String, Value>, Unauthorized> {
const INVALID: Unauthorized = Unauthorized("invalid identity token");
let header = jsonwebtoken::decode_header(token).map_err(|_| INVALID)?;
if header.alg != Algorithm::RS256 {
return Err(INVALID);
}
let kid = header.kid.ok_or(INVALID)?;
let key = self.keys.key(&kid).await?;
let mut validation = Validation::new(Algorithm::RS256);
validation.set_audience(&[audience]);
validation.set_issuer(&[&self.config.issuer]);
validation.set_required_spec_claims(&["iss", "aud", "sub"]);
validation.validate_exp = false;
validation.validate_nbf = false;
validation.leeway = 0;
let claims = jsonwebtoken::decode::<Map<String, Value>>(token, &key, &validation).map_err(|_| INVALID)?.claims;
if claims
.keys()
.any(|name| name != &name.to_ascii_lowercase() && CLAIM_NAMES.contains(&name.to_ascii_lowercase().as_str()))
{
return Err(INVALID);
}
let now = (self.now)();
let time = |name: &str| claims.get(name).map(|v| v.as_u64().ok_or(INVALID)).transpose();
time("iat")?.ok_or(INVALID)?;
let (exp, nbf) = (time("exp")?.ok_or(INVALID)?, time("nbf")?);
if now >= exp || nbf.is_some_and(|nbf| now < nbf) {
return Err(INVALID);
}
Ok(claims)
}
}
fn token_in(headers: &HeaderMap) -> Result<&str, Unauthorized> {
if headers.get_all(IDENTITY_HEADER).iter().nth(1).is_some() {
return Err(Unauthorized("invalid identity token"));
}
headers
.get(IDENTITY_HEADER)
.and_then(|v| v.to_str().ok())
.filter(|t| !t.is_empty())
.ok_or(Unauthorized("no identity token"))
}
const WEBHOOK_AUDIENCE: &str = "webhook:";
const MAX_EXACT: u64 = (1 << 53) - 1;
fn whole_seconds(value: &Value) -> Option<u64> {
let seconds = match value.as_u64() {
Some(seconds) => seconds,
None => {
let seconds = value.as_f64()?;
if seconds < 0.0 || seconds.fract() != 0.0 || seconds > MAX_EXACT as f64 {
return None;
}
seconds as u64
}
};
(seconds <= MAX_EXACT).then_some(seconds)
}
const CLAIM_NAMES: [&str; 16] = [
"iss",
"aud",
"sub",
"exp",
"iat",
"nbf",
"jti",
"kind",
"email",
"role",
"wid",
"provider",
"pattern",
"delivery",
"signed_at",
"agent_name",
];
pub struct KeySet {
url: String,
fetch: Fetch,
now: Clock,
fetching: Mutex<Option<u64>>,
keys: std::sync::RwLock<Cached>,
}
#[derive(Default)]
struct Cached {
keys: HashMap<String, DecodingKey>,
fetched_at: Option<u64>,
}
impl Cached {
fn lookup(&self, kid: &str, now: u64) -> (Option<DecodingKey>, bool) {
let fresh = self.fetched_at.is_some_and(|at| now.saturating_sub(at) < MAX_AGE_SECONDS);
(self.keys.get(kid).cloned(), fresh)
}
}
impl KeySet {
pub fn new(url: &str) -> Self {
Self::with_fetch(url, Arc::new(http_fetch), Arc::new(system_clock))
}
pub fn with_fetch(url: &str, fetch: Fetch, now: Clock) -> Self {
Self {
url: url.to_owned(),
fetch,
now,
fetching: Mutex::new(None),
keys: std::sync::RwLock::new(Cached::default()),
}
}
fn lookup(&self, kid: &str, now: u64) -> (Option<DecodingKey>, bool) {
self.keys.read().map(|c| c.lookup(kid, now)).unwrap_or((None, false))
}
pub async fn key(&self, kid: &str) -> Result<DecodingKey, Unauthorized> {
if let (Some(key), true) = self.lookup(kid, (self.now)()) {
return Ok(key);
}
let mut tried = self.fetching.lock().await;
let now = (self.now)();
let (mut key, mut fresh) = self.lookup(kid, now);
let wait = if fresh { COOLDOWN_SECONDS } else { RETRY_SECONDS };
if (!fresh || key.is_none()) && tried.is_none_or(|at| now.saturating_sub(at) >= wait) {
*tried = Some(now);
let fetched = (self.fetch)(self.url.clone()).await.and_then(|body| parse_jwks(&body));
if let Ok(mut cached) = self.keys.write() {
match fetched {
Ok(keys) => *cached = Cached { keys, fetched_at: Some(now) },
Err(_) if !fresh => *cached = Cached::default(),
Err(_) => {}
}
}
(key, fresh) = self.lookup(kid, now);
}
if !fresh {
return Err(Unauthorized("couldn't fetch the identity keys"));
}
key.ok_or(Unauthorized("unknown signing key"))
}
}
fn http_fetch(url: String) -> FetchFuture {
Box::pin(async move {
let client = client().map_err(|e| e.to_string())?;
let mut res = client.get(&url).send().await.map_err(|e| e.to_string())?;
if res.status() != reqwest::StatusCode::OK {
return Err(format!("JWKS answered {}", res.status()));
}
let mut body = Vec::new();
while let Some(chunk) = res.chunk().await.map_err(|e| e.to_string())? {
body.extend_from_slice(&chunk);
if body.len() > MAX_JWKS_BYTES {
return Err("JWKS too large".into());
}
}
Ok(body)
})
}
fn client() -> reqwest::Result<reqwest::Client> {
let with = |roots: &[reqwest::Certificate]| {
roots
.iter()
.fold(reqwest::Client::builder(), |builder, root| builder.add_root_certificate(root.clone()))
.timeout(FETCH_TIMEOUT)
.redirect(reqwest::redirect::Policy::none())
.build()
};
let roots = roots_from_env();
with(&roots).or_else(|_| {
let usable: Vec<_> = roots.iter().filter(|root| with(std::slice::from_ref(root)).is_ok()).cloned().collect();
with(&usable)
})
}
fn roots_from_env() -> Vec<reqwest::Certificate> {
let Some(path) = std::env::var_os("SSL_CERT_FILE") else { return Vec::new() };
std::fs::read(path).ok().and_then(|pem| reqwest::Certificate::from_pem_bundle(&pem).ok()).unwrap_or_default()
}
fn parse_jwks(body: &[u8]) -> Result<HashMap<String, DecodingKey>, String> {
let doc: Value = serde_json::from_slice(body).map_err(|e| e.to_string())?;
let mut keys = HashMap::new();
for jwk in doc.get("keys").and_then(Value::as_array).into_iter().flatten() {
let text = |name: &str| jwk.get(name).and_then(Value::as_str);
let (Some("RSA"), Some(kid), Some(n), Some(e)) = (text("kty"), text("kid"), text("n"), text("e")) else {
continue;
};
if text("use").is_some_and(|u| u != "sig") || text("alg").is_some_and(|a| a != "RS256") {
continue;
}
let Ok(modulus) = URL_SAFE_NO_PAD.decode(n.trim_end_matches('=')) else { continue };
let bits = modulus
.iter()
.position(|b| *b != 0)
.map_or(0, |i| (modulus.len() - i) * 8 - modulus[i].leading_zeros() as usize);
if bits < MIN_RSA_BITS {
continue;
}
if let Ok(key) = DecodingKey::from_rsa_components(n, e) {
keys.insert(kid.to_owned(), key);
}
}
Ok(keys)
}
#[cfg(test)]
mod role_tests {
use super::{Kind, Role, User};
fn who(role: &str) -> User {
User {
kind: Kind::User,
sub: "u1".into(),
email: Some("a@example.com".into()),
role: role.into(),
workspace_id: "w1".into(),
agent_name: None,
}
}
#[test]
fn an_owner_can_do_what_an_editor_can() {
let ladder: [(&str, &[Role], &[Role]); 3] = [
("viewer", &[Role::Viewer], &[Role::Editor, Role::Owner]),
("editor", &[Role::Viewer, Role::Editor], &[Role::Owner]),
("owner", &[Role::Viewer, Role::Editor, Role::Owner], &[]),
];
for (role, allowed, refused) in ladder {
for least in allowed {
assert!(who(role).has_role(*least), "{role} should be at least {least}");
}
for least in refused {
assert!(!who(role).has_role(*least), "{role} should not be {least}");
}
}
}
#[test]
fn a_role_this_version_doesnt_know_allows_nothing() {
for unknown in ["superuser", "", "OWNER", "admin"] {
assert!(!who(unknown).has_role(Role::Viewer), "{unknown} allowed something");
}
}
#[test]
fn require_role_says_which_one() {
assert!(who("owner").require_role(Role::Editor).is_ok());
let refused = who("viewer").require_role(Role::Editor).expect_err("a viewer is not an editor");
assert_eq!(refused.to_string(), "forbidden: this needs editor");
}
}
#[cfg(test)]
mod origin_tests {
#![allow(clippy::unwrap_used, clippy::expect_used)] use super::Config;
use serde_json::Value;
fn vectors() -> Value {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../testdata/vectors.json");
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}
fn from(v: &Value, issuer: &str, jwks_url: &str, dev: Option<&str>) -> Result<Config, super::Unauthorized> {
let app = v["config"]["app_id"].as_str().unwrap();
Config::from_vars(|name| match name {
"JIAYANG_APP_ID" => Some(app.to_owned()),
"JIAYANG_IDENTITY_ISSUER" => Some(issuer.to_owned()),
"JIAYANG_JWKS_URL" => Some(jwks_url.to_owned()),
"JIAYANG_DEV" => dev.map(str::to_owned),
_ => None,
})
}
#[test]
fn takes_exactly_the_origins_marked_ok() {
let v = vectors();
for case in v["origins"].as_array().unwrap() {
let name = case["name"].as_str().unwrap();
let read =
from(&v, case["issuer"].as_str().unwrap(), case["jwks_url"].as_str().unwrap(), case["dev"].as_str());
match (case["ok"].as_bool().unwrap(), read) {
(true, Err(err)) => panic!("{name}: refused: {err}"),
(false, Ok(config)) => panic!("{name}: taken as {config:?}"),
(false, Err(err)) => assert!(err.to_string().contains("JIAYANG_DEV=1"), "{name}: {err}"),
(true, Ok(_)) => {}
}
}
}
#[test]
fn refuses_jiayang_dev_without_jiayang_dev() {
let v = vectors();
let (issuer, jwks_url) = (v["dev"]["issuer"].as_str().unwrap(), v["dev"]["jwks_url"].as_str().unwrap());
assert!(from(&v, issuer, jwks_url, None).is_err());
assert!(from(&v, issuer, jwks_url, Some("1")).unwrap().dev);
}
}