use std::sync::atomic::Ordering;
use std::time::Duration;
use axum::body::Body;
use axum::extract::State;
use axum::http::{Request, StatusCode};
use axum::middleware::Next;
use axum::response::Response;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tracing::{debug, warn};
use crate::http::{constant_time_eq, current_window_epoch, is_admin_api_path, parse_csv_set};
use crate::http_runtime::HasRuntimeState;
use crate::http_security::extract_client_ip;
#[derive(Debug, Clone)]
pub struct AuthContext {
pub subject: Option<String>,
pub issuer: Option<String>,
pub provider: Option<String>,
pub token_id: Option<String>,
pub token_use: Option<String>,
pub tenant_id: Option<String>,
pub scopes: Vec<String>,
pub roles: Vec<String>,
}
pub fn has_admin_entitlement(ctx: &AuthContext) -> bool {
let admin_scope =
std::env::var("KRAB_AUTH_ADMIN_SCOPE").unwrap_or_else(|_| "admin".to_string());
let admin_role = std::env::var("KRAB_AUTH_ADMIN_ROLE").unwrap_or_else(|_| "admin".to_string());
ctx.scopes.iter().any(|s| s == &admin_scope) || ctx.roles.iter().any(|r| r == &admin_role)
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JwtClaims {
pub sub: Option<String>,
pub iss: Option<String>,
pub aud: Option<Value>,
pub exp: Option<i64>,
pub jti: Option<String>,
pub token_use: Option<String>,
pub tid: Option<String>,
pub tenant_id: Option<String>,
pub scope: Option<String>,
pub scp: Option<Value>,
pub roles: Option<Vec<String>>,
pub role: Option<String>,
#[serde(flatten)]
pub extra: std::collections::BTreeMap<String, Value>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct JwtProviderConfig {
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub issuer: Option<String>,
#[serde(default)]
pub audience: Option<String>,
#[serde(default)]
pub keys: std::collections::BTreeMap<String, String>,
#[serde(default)]
pub required_claims: std::collections::BTreeMap<String, Value>,
#[serde(default)]
pub jwks_url: Option<String>,
#[serde(default)]
pub key_not_after: std::collections::BTreeMap<String, String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct RoutePolicy {
pub prefix: String,
#[serde(default)]
pub all_scopes: Vec<String>,
#[serde(default)]
pub any_scopes: Vec<String>,
#[serde(default)]
pub all_roles: Vec<String>,
#[serde(default)]
pub any_roles: Vec<String>,
#[serde(default)]
pub allow_subjects: Vec<String>,
#[serde(default)]
pub require_tenant_match: bool,
}
fn parse_jwt_algorithm(alg: &str) -> Option<jsonwebtoken::Algorithm> {
match alg.trim().to_ascii_uppercase().as_str() {
"HS256" => Some(jsonwebtoken::Algorithm::HS256),
"HS384" => Some(jsonwebtoken::Algorithm::HS384),
"HS512" => Some(jsonwebtoken::Algorithm::HS512),
"RS256" => Some(jsonwebtoken::Algorithm::RS256),
"RS384" => Some(jsonwebtoken::Algorithm::RS384),
"RS512" => Some(jsonwebtoken::Algorithm::RS512),
"ES256" => Some(jsonwebtoken::Algorithm::ES256),
"ES384" => Some(jsonwebtoken::Algorithm::ES384),
"PS256" => Some(jsonwebtoken::Algorithm::PS256),
"PS384" => Some(jsonwebtoken::Algorithm::PS384),
"PS512" => Some(jsonwebtoken::Algorithm::PS512),
"EDDSA" => Some(jsonwebtoken::Algorithm::EdDSA),
_ => None,
}
}
fn is_hmac_algorithm(alg: &jsonwebtoken::Algorithm) -> bool {
matches!(
alg,
jsonwebtoken::Algorithm::HS256
| jsonwebtoken::Algorithm::HS384
| jsonwebtoken::Algorithm::HS512
)
}
fn configured_jwt_algorithms() -> Result<Vec<jsonwebtoken::Algorithm>, StatusCode> {
let raw = match std::env::var("KRAB_JWT_ALLOWED_ALGS") {
Ok(raw) => raw,
Err(_) => return Ok(vec![jsonwebtoken::Algorithm::HS256]),
};
let mut algorithms = Vec::new();
for alg in raw.split(',').map(str::trim).filter(|alg| !alg.is_empty()) {
let Some(parsed) = parse_jwt_algorithm(alg) else {
warn!(alg = %alg, "jwt_allowlist_contains_unsupported_algorithm");
continue;
};
if !algorithms.contains(&parsed) {
algorithms.push(parsed);
}
}
if algorithms.is_empty() {
warn!("KRAB_JWT_ALLOWED_ALGS resolved to an empty allowlist");
return Err(StatusCode::SERVICE_UNAVAILABLE);
}
let has_hmac = algorithms.iter().any(is_hmac_algorithm);
let has_asymmetric = algorithms.iter().any(|alg| !is_hmac_algorithm(alg));
if has_hmac && has_asymmetric {
warn!(
allowlist = %raw,
"KRAB_JWT_ALLOWED_ALGS mixes HMAC and asymmetric algorithm families; refusing to verify"
);
return Err(StatusCode::SERVICE_UNAVAILABLE);
}
Ok(algorithms)
}
pub fn jwt_algorithm_allowed(alg: &str, _environment: &crate::config::Environment) -> bool {
let Some(candidate) = parse_jwt_algorithm(alg) else {
return false;
};
configured_jwt_algorithms()
.map(|allowed| allowed.contains(&candidate))
.unwrap_or(false)
}
pub fn jwt_leeway_secs() -> u64 {
std::env::var("KRAB_JWT_LEEWAY_SECS")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(30)
}
pub fn load_rotation_keys() -> anyhow::Result<std::collections::BTreeMap<String, String>> {
if let Some(json) = crate::config::read_env_or_file("KRAB_JWT_KEYS_JSON")? {
let parsed = serde_json::from_str::<std::collections::BTreeMap<String, String>>(&json)?;
if !parsed.is_empty() {
return Ok(parsed);
}
}
let secret = crate::config::read_env_or_file("KRAB_JWT_SECRET")?;
let Some(secret) = secret else {
tracing::warn!(
"No JWT signing key configured; set KRAB_JWT_SECRET or KRAB_JWT_KEYS_JSON for jwt/oidc mode"
);
return Ok(std::collections::BTreeMap::new());
};
let mut keys = std::collections::BTreeMap::new();
keys.insert("default".to_string(), secret);
Ok(keys)
}
pub fn load_jwt_providers() -> anyhow::Result<Vec<JwtProviderConfig>> {
if let Some(raw) = crate::config::read_env_or_file("KRAB_JWT_PROVIDERS_JSON")? {
let mut providers = serde_json::from_str::<Vec<JwtProviderConfig>>(&raw)?;
providers.retain(|p| {
!p.keys.is_empty() || p.jwks_url.as_deref().is_some_and(|u| !u.trim().is_empty())
});
if !providers.is_empty() {
return Ok(providers);
}
}
let jwks_url = std::env::var("KRAB_OIDC_JWKS_URL")
.ok()
.filter(|url| !url.trim().is_empty());
let key_not_after = match std::env::var("KRAB_JWT_KEY_NOT_AFTER_JSON") {
Ok(raw) if !raw.trim().is_empty() => {
let parsed: std::collections::BTreeMap<String, Value> = serde_json::from_str(&raw)?;
parsed
.into_iter()
.map(|(kid, value)| {
let value = match value {
Value::String(s) => s,
other => other.to_string(),
};
(kid, value)
})
.collect()
}
_ => std::collections::BTreeMap::new(),
};
let keys = if jwks_url.is_some()
&& crate::config::read_env_or_file("KRAB_JWT_KEYS_JSON")?.is_none()
&& crate::config::read_env_or_file("KRAB_JWT_SECRET")?.is_none()
{
std::collections::BTreeMap::new()
} else {
load_rotation_keys()?
};
Ok(vec![JwtProviderConfig {
name: Some("default".to_string()),
issuer: std::env::var("KRAB_OIDC_ISSUER").ok(),
audience: std::env::var("KRAB_OIDC_AUDIENCE").ok(),
keys,
required_claims: std::collections::BTreeMap::new(),
jwks_url,
key_not_after,
}])
}
pub const MAX_KIDLESS_KEY_TRIALS: usize = 8;
pub fn require_kid() -> bool {
std::env::var("KRAB_JWT_REQUIRE_KID")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false)
}
pub fn select_key<'a>(
keys: &'a std::collections::BTreeMap<String, String>,
kid: Option<&str>,
) -> Option<&'a String> {
match kid {
Some(k) => keys.get(k),
None if require_kid() => None,
None => keys.get("default").or_else(|| keys.values().next()),
}
}
pub fn tenant_from_claims(claims: &JwtClaims) -> Option<String> {
claims
.tenant_id
.clone()
.or_else(|| claims.tid.clone())
.or_else(|| {
claims
.extra
.get("tenant_id")
.and_then(|v| v.as_str().map(ToString::to_string))
})
.or_else(|| {
claims
.extra
.get("tid")
.and_then(|v| v.as_str().map(ToString::to_string))
})
}
pub fn tenant_from_path(path: &str) -> Option<&str> {
let mut parts = path.split('/').filter(|p| !p.is_empty());
while let Some(segment) = parts.next() {
if segment == "tenants" {
return parts.next();
}
}
None
}
pub fn try_load_route_policies() -> Result<Vec<RoutePolicy>, serde_json::Error> {
match std::env::var("KRAB_AUTH_ROUTE_POLICIES_JSON") {
Ok(raw) => serde_json::from_str::<Vec<RoutePolicy>>(&raw),
Err(_) => Ok(Vec::new()),
}
}
pub fn load_route_policies() -> Vec<RoutePolicy> {
try_load_route_policies().unwrap_or_else(|error| {
tracing::error!(error = %error, "auth_route_policies_json_malformed");
Vec::new()
})
}
pub fn validate_provider_claims(
claims: &JwtClaims,
provider: &JwtProviderConfig,
) -> Result<(), StatusCode> {
if let Some(expected_issuer) = provider.issuer.as_deref() {
if claims.iss.as_deref() != Some(expected_issuer) {
return Err(StatusCode::UNAUTHORIZED);
}
}
if let Some(expected_audience) = provider.audience.as_ref() {
let aud_ok = match claims.aud.as_ref() {
Some(Value::String(aud)) => aud == expected_audience,
Some(Value::Array(values)) => values
.iter()
.any(|v| v.as_str() == Some(expected_audience.as_str())),
_ => false,
};
if !aud_ok {
return Err(StatusCode::UNAUTHORIZED);
}
}
if !provider.required_claims.is_empty() {
let claims_json = serde_json::to_value(claims).map_err(|_| StatusCode::UNAUTHORIZED)?;
let claims_obj = claims_json.as_object().ok_or(StatusCode::UNAUTHORIZED)?;
for (k, v) in &provider.required_claims {
let found = claims_obj
.get(k)
.or_else(|| claims.extra.get(k))
.ok_or(StatusCode::UNAUTHORIZED)?;
if found != v {
return Err(StatusCode::UNAUTHORIZED);
}
}
}
Ok(())
}
pub fn scopes_from_claims(claims: &JwtClaims) -> Vec<String> {
if let Some(scope) = &claims.scope {
return scope.split_whitespace().map(|s| s.to_string()).collect();
}
match claims.scp.as_ref() {
Some(Value::String(scope)) => scope.split_whitespace().map(|s| s.to_string()).collect(),
Some(Value::Array(values)) => values
.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect(),
_ => vec![],
}
}
pub fn roles_from_claims(claims: &JwtClaims) -> Vec<String> {
if let Some(roles) = &claims.roles {
return roles.clone();
}
if let Some(role) = &claims.role {
return vec![role.clone()];
}
vec![]
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum JwtAlgorithmFamily {
Hmac,
Rsa,
Ec,
Ed,
}
impl JwtAlgorithmFamily {
const ALL: [Self; 4] = [Self::Hmac, Self::Rsa, Self::Ec, Self::Ed];
pub(crate) fn of(algorithm: jsonwebtoken::Algorithm) -> Self {
match algorithm {
jsonwebtoken::Algorithm::HS256
| jsonwebtoken::Algorithm::HS384
| jsonwebtoken::Algorithm::HS512 => Self::Hmac,
jsonwebtoken::Algorithm::RS256
| jsonwebtoken::Algorithm::RS384
| jsonwebtoken::Algorithm::RS512
| jsonwebtoken::Algorithm::PS256
| jsonwebtoken::Algorithm::PS384
| jsonwebtoken::Algorithm::PS512 => Self::Rsa,
jsonwebtoken::Algorithm::ES256 | jsonwebtoken::Algorithm::ES384 => Self::Ec,
jsonwebtoken::Algorithm::EdDSA => Self::Ed,
}
}
fn representative(self) -> jsonwebtoken::Algorithm {
match self {
Self::Hmac => jsonwebtoken::Algorithm::HS256,
Self::Rsa => jsonwebtoken::Algorithm::RS256,
Self::Ec => jsonwebtoken::Algorithm::ES256,
Self::Ed => jsonwebtoken::Algorithm::EdDSA,
}
}
}
pub struct JwtVerifierCache {
providers: Vec<JwtProviderConfig>,
keys: std::collections::HashMap<(usize, String, JwtAlgorithmFamily), jsonwebtoken::DecodingKey>,
jwks: Vec<Option<std::sync::Arc<crate::jwks::JwksSource>>>,
retire_at: Vec<std::collections::HashMap<String, i64>>,
load_failed: bool,
background_refresh: std::sync::atomic::AtomicBool,
}
impl JwtVerifierCache {
pub fn from_env() -> Self {
match load_jwt_providers() {
Ok(providers) => Self::from_providers(providers),
Err(err) => {
warn!(error = %err, "jwt_provider_configuration_load_failed");
Self::failed()
}
}
}
fn failed() -> Self {
Self {
providers: Vec::new(),
keys: std::collections::HashMap::new(),
jwks: Vec::new(),
retire_at: Vec::new(),
load_failed: true,
background_refresh: std::sync::atomic::AtomicBool::new(false),
}
}
pub fn from_providers(providers: Vec<JwtProviderConfig>) -> Self {
Self::from_providers_with(providers, crate::jwks::JwksSettings::from_env())
}
pub(crate) fn from_providers_with(
providers: Vec<JwtProviderConfig>,
settings: crate::jwks::JwksSettings,
) -> Self {
let environment = crate::config::Environment::from_env();
let mut keys = std::collections::HashMap::new();
let mut jwks = Vec::with_capacity(providers.len());
let mut retire_at = Vec::with_capacity(providers.len());
for (provider_index, provider) in providers.iter().enumerate() {
let name = provider.name.as_deref().unwrap_or("provider");
for (kid, material) in &provider.keys {
for family in JwtAlgorithmFamily::ALL {
if let Ok(key) = decoding_key_for_algorithm(family.representative(), material) {
keys.insert((provider_index, kid.clone(), family), key);
}
}
}
match provider.jwks_url.as_deref().map(str::trim) {
Some(url) if !url.is_empty() => {
if !crate::jwks::url_allowed(url, &environment) {
tracing::error!(
provider = name,
url,
environment = %environment.as_str(),
"jwks_url_rejected_https_required_outside_dev"
);
return Self::failed();
}
match crate::jwks::JwksSource::new(url.to_string(), settings) {
Ok(source) => jwks.push(Some(std::sync::Arc::new(source))),
Err(error) => {
tracing::error!(
provider = name,
url,
%error,
"jwks_source_unusable_http_client_build_failed"
);
return Self::failed();
}
}
}
_ => jwks.push(None),
}
let mut retire = std::collections::HashMap::new();
for (kid, raw) in &provider.key_not_after {
let Some(at) = crate::jwks::parse_not_after(raw) else {
tracing::error!(
provider = name,
kid,
value = raw,
"jwt_key_not_after_unparseable"
);
return Self::failed();
};
retire.insert(kid.clone(), at);
}
retire_at.push(retire);
}
Self {
providers,
keys,
jwks,
retire_at,
load_failed: false,
background_refresh: std::sync::atomic::AtomicBool::new(false),
}
}
pub fn providers(&self) -> &[JwtProviderConfig] {
&self.providers
}
pub fn load_failed(&self) -> bool {
self.load_failed
}
pub fn uses_jwks(&self) -> bool {
self.jwks.iter().any(Option::is_some)
}
pub async fn prepare_for_kid(&self, kid: Option<&str>) {
let periodic = !self
.background_refresh
.load(std::sync::atomic::Ordering::Relaxed);
for source in self.jwks.iter().flatten() {
if let Some(Err(error)) = source.refresh_if_needed(kid, periodic).await {
warn!(url = %source.url(), %error, "jwks_fetch_failed");
}
}
}
pub async fn refresh_jwks(&self) {
for source in self.jwks.iter().flatten() {
if let Err(error) = source.refresh().await {
warn!(url = %source.url(), %error, "jwks_refresh_failed");
}
}
}
pub fn spawn_background_refresh(cache: &std::sync::Arc<Self>) {
if !cache.uses_jwks() {
return;
}
let Ok(handle) = tokio::runtime::Handle::try_current() else {
warn!(
refresh = "lazy_on_request_path",
"jwks_background_refresh_unavailable_outside_tokio_runtime"
);
return;
};
cache
.background_refresh
.store(true, std::sync::atomic::Ordering::Relaxed);
let interval = cache
.jwks
.iter()
.flatten()
.map(|s| s.settings().refresh_every)
.min()
.unwrap_or(std::time::Duration::from_secs(300));
let weak = std::sync::Arc::downgrade(cache);
handle.spawn(async move {
loop {
let Some(cache) = weak.upgrade() else {
return;
};
cache.refresh_jwks().await;
drop(cache);
tokio::time::sleep(interval).await;
}
});
}
fn decoding_key(
&self,
provider_index: usize,
kid: &str,
algorithm: jsonwebtoken::Algorithm,
) -> Option<jsonwebtoken::DecodingKey> {
let family = JwtAlgorithmFamily::of(algorithm);
if let Some(key) = self.keys.get(&(provider_index, kid.to_string(), family)) {
return Some(key.clone());
}
self.jwks.get(provider_index)?.as_ref()?.key(kid, family)
}
fn candidate_kids(&self, provider_index: usize, kid: Option<&str>) -> Vec<String> {
let provider = &self.providers[provider_index];
let remote = self.jwks.get(provider_index).and_then(Option::as_ref);
match kid {
Some(k) => {
let known =
provider.keys.contains_key(k) || remote.is_some_and(|source| source.has_kid(k));
if known {
vec![k.to_string()]
} else {
Vec::new()
}
}
None if require_kid() => Vec::new(),
None => {
let mut kids: Vec<String> = provider.keys.keys().cloned().collect();
if let Some(source) = remote {
kids.extend(source.kids());
}
if let Some(pos) = kids.iter().position(|k| k == "default") {
let default = kids.remove(pos);
kids.insert(0, default);
}
kids
}
}
}
fn is_retired(&self, provider_index: usize, kid: &str, now: i64) -> bool {
self.retire_at
.get(provider_index)
.and_then(|map| map.get(kid))
.is_some_and(|at| now >= *at)
}
fn remote_unavailable(&self, provider_index: usize) -> bool {
self.jwks
.get(provider_index)
.and_then(Option::as_ref)
.is_some_and(|source| !source.loaded())
}
}
fn decoding_key_for_algorithm(
algorithm: jsonwebtoken::Algorithm,
key_material: &str,
) -> anyhow::Result<jsonwebtoken::DecodingKey> {
match algorithm {
jsonwebtoken::Algorithm::HS256
| jsonwebtoken::Algorithm::HS384
| jsonwebtoken::Algorithm::HS512 => Ok(jsonwebtoken::DecodingKey::from_secret(
key_material.as_bytes(),
)),
jsonwebtoken::Algorithm::RS256
| jsonwebtoken::Algorithm::RS384
| jsonwebtoken::Algorithm::RS512
| jsonwebtoken::Algorithm::PS256
| jsonwebtoken::Algorithm::PS384
| jsonwebtoken::Algorithm::PS512 => Ok(jsonwebtoken::DecodingKey::from_rsa_pem(
key_material.as_bytes(),
)?),
jsonwebtoken::Algorithm::ES256 | jsonwebtoken::Algorithm::ES384 => Ok(
jsonwebtoken::DecodingKey::from_ec_pem(key_material.as_bytes())?,
),
jsonwebtoken::Algorithm::EdDSA => Ok(jsonwebtoken::DecodingKey::from_ed_pem(
key_material.as_bytes(),
)?),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthFailureReason {
MissingCredentials,
MalformedToken,
AlgorithmRejected,
UnknownKey,
KeyRetired,
InvalidSignature,
Expired,
ClaimsRejected,
RefreshTokenRejected,
PolicyDenied,
Revoked,
CredentialMismatch,
ProviderUnavailable,
Misconfigured,
}
impl AuthFailureReason {
pub const ALL: [Self; 14] = [
Self::MissingCredentials,
Self::MalformedToken,
Self::AlgorithmRejected,
Self::UnknownKey,
Self::KeyRetired,
Self::InvalidSignature,
Self::Expired,
Self::ClaimsRejected,
Self::RefreshTokenRejected,
Self::PolicyDenied,
Self::Revoked,
Self::CredentialMismatch,
Self::ProviderUnavailable,
Self::Misconfigured,
];
pub fn as_str(self) -> &'static str {
match self {
Self::MissingCredentials => "missing_credentials",
Self::MalformedToken => "malformed_token",
Self::AlgorithmRejected => "algorithm_rejected",
Self::UnknownKey => "unknown_key",
Self::KeyRetired => "key_retired",
Self::InvalidSignature => "invalid_signature",
Self::Expired => "expired",
Self::ClaimsRejected => "claims_rejected",
Self::RefreshTokenRejected => "refresh_token_rejected",
Self::PolicyDenied => "policy_denied",
Self::Revoked => "revoked",
Self::CredentialMismatch => "credential_mismatch",
Self::ProviderUnavailable => "provider_unavailable",
Self::Misconfigured => "misconfigured",
}
}
pub(crate) fn slot(self) -> usize {
Self::ALL
.iter()
.position(|r| *r == self)
.unwrap_or(Self::ALL.len() - 1)
}
fn specificity(self) -> u8 {
match self {
Self::Expired | Self::ClaimsRejected => 4,
Self::KeyRetired => 3,
Self::InvalidSignature => 2,
Self::UnknownKey => 1,
_ => 0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuthFailure {
pub status: StatusCode,
pub reason: AuthFailureReason,
}
impl AuthFailure {
fn new(status: StatusCode, reason: AuthFailureReason) -> Self {
Self { status, reason }
}
fn unauthorized(reason: AuthFailureReason) -> Self {
Self::new(StatusCode::UNAUTHORIZED, reason)
}
}
#[derive(Debug, Clone)]
pub struct AuthPolicy {
required_scopes: Vec<String>,
required_roles: Vec<String>,
admin_scope: String,
admin_role: String,
require_tenant_claim: bool,
require_tenant_match: bool,
route_policies: Result<Vec<RoutePolicy>, String>,
required_claims: Result<std::collections::BTreeMap<String, Value>, String>,
}
impl AuthPolicy {
pub fn from_env() -> Self {
let csv = |name: &str| {
std::env::var(name)
.ok()
.map(|v| parse_csv_set(&v))
.unwrap_or_default()
};
let route_policies = try_load_route_policies().map_err(|error| {
tracing::error!(error = %error, "auth_route_policies_json_malformed");
error.to_string()
});
let required_claims = match std::env::var("KRAB_AUTH_REQUIRED_CLAIMS_JSON") {
Ok(raw) => serde_json::from_str(&raw).map_err(|error| {
tracing::error!(error = %error, "auth_required_claims_json_malformed");
error.to_string()
}),
Err(_) => Ok(std::collections::BTreeMap::new()),
};
Self {
required_scopes: csv("KRAB_AUTH_REQUIRED_SCOPES"),
required_roles: csv("KRAB_AUTH_REQUIRED_ROLES"),
admin_scope: std::env::var("KRAB_AUTH_ADMIN_SCOPE")
.unwrap_or_else(|_| "admin".to_string()),
admin_role: std::env::var("KRAB_AUTH_ADMIN_ROLE")
.unwrap_or_else(|_| "admin".to_string()),
require_tenant_claim: crate::http::bool_env("KRAB_AUTH_REQUIRE_TENANT_CLAIM", false),
require_tenant_match: crate::http::bool_env("KRAB_AUTH_REQUIRE_TENANT_MATCH", true),
route_policies,
required_claims,
}
}
pub fn has_admin_entitlement(&self, ctx: &AuthContext) -> bool {
ctx.scopes.iter().any(|s| s == &self.admin_scope)
|| ctx.roles.iter().any(|r| r == &self.admin_role)
}
pub fn enforce(
&self,
path: &str,
claims: &JwtClaims,
tenant_id: Option<&str>,
scopes: &[String],
roles: &[String],
) -> Result<(), StatusCode> {
for scope in &self.required_scopes {
if !scopes.iter().any(|s| s == scope) {
return Err(StatusCode::UNAUTHORIZED);
}
}
for role in &self.required_roles {
if !roles.iter().any(|r| r == role) {
return Err(StatusCode::UNAUTHORIZED);
}
}
if is_admin_api_path(path)
&& !scopes.iter().any(|s| s == &self.admin_scope)
&& !roles.iter().any(|r| r == &self.admin_role)
{
return Err(StatusCode::UNAUTHORIZED);
}
if self.require_tenant_claim && tenant_id.is_none() {
return Err(StatusCode::UNAUTHORIZED);
}
if self.require_tenant_match {
if let Some(path_tenant) = tenant_from_path(path) {
if tenant_id != Some(path_tenant) {
return Err(StatusCode::UNAUTHORIZED);
}
}
}
let route_policies = self.route_policies.as_ref().map_err(|error| {
tracing::error!(
error = %error,
"auth_route_policies_json_malformed_failing_closed"
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
for policy in route_policies
.iter()
.filter(|p| path.starts_with(&p.prefix))
{
for scope in &policy.all_scopes {
if !scopes.iter().any(|s| s == scope) {
return Err(StatusCode::UNAUTHORIZED);
}
}
if !policy.any_scopes.is_empty()
&& !policy
.any_scopes
.iter()
.any(|s| scopes.iter().any(|actual| actual == s))
{
return Err(StatusCode::UNAUTHORIZED);
}
for role in &policy.all_roles {
if !roles.iter().any(|r| r == role) {
return Err(StatusCode::UNAUTHORIZED);
}
}
if !policy.any_roles.is_empty()
&& !policy
.any_roles
.iter()
.any(|r| roles.iter().any(|actual| actual == r))
{
return Err(StatusCode::UNAUTHORIZED);
}
if !policy.allow_subjects.is_empty() {
let subject = claims.sub.as_deref().ok_or(StatusCode::UNAUTHORIZED)?;
if !policy.allow_subjects.iter().any(|s| s == subject) {
return Err(StatusCode::UNAUTHORIZED);
}
}
if policy.require_tenant_match {
let path_tenant = tenant_from_path(path).ok_or(StatusCode::UNAUTHORIZED)?;
if tenant_id != Some(path_tenant) {
return Err(StatusCode::UNAUTHORIZED);
}
}
}
let required = self
.required_claims
.as_ref()
.map_err(|_| StatusCode::UNAUTHORIZED)?;
if !required.is_empty() {
let claims_json = serde_json::to_value(claims).map_err(|_| StatusCode::UNAUTHORIZED)?;
let claims_obj = claims_json.as_object().ok_or(StatusCode::UNAUTHORIZED)?;
for (k, v) in required {
let found = claims_obj
.get(k)
.or_else(|| claims.extra.get(k))
.ok_or(StatusCode::UNAUTHORIZED)?;
if found != v {
return Err(StatusCode::UNAUTHORIZED);
}
}
}
Ok(())
}
}
pub fn enforce_claim_policy(
path: &str,
claims: &JwtClaims,
tenant_id: Option<&str>,
scopes: &[String],
roles: &[String],
) -> Result<(), StatusCode> {
AuthPolicy::from_env().enforce(path, claims, tenant_id, scopes, roles)
}
pub fn authorize_with_static_bearer(req: &Request<Body>) -> Result<AuthContext, StatusCode> {
authorize_static_detailed(req).map_err(|failure| failure.status)
}
fn authorize_static_detailed(req: &Request<Body>) -> Result<AuthContext, AuthFailure> {
let unavailable = AuthFailure::new(
StatusCode::SERVICE_UNAVAILABLE,
AuthFailureReason::ProviderUnavailable,
);
let expected = match crate::config::read_env_or_file("KRAB_BEARER_TOKEN") {
Ok(Some(token)) if !token.trim().is_empty() => token,
Ok(_) => {
tracing::warn!("KRAB_BEARER_TOKEN is not configured for static auth mode");
return Err(unavailable);
}
Err(error) => {
tracing::warn!(%error, "KRAB_BEARER_TOKEN could not be read for static auth mode");
return Err(unavailable);
}
};
let expected = format!("Bearer {expected}");
let Some(presented) = req
.headers()
.get("authorization")
.and_then(|h| h.to_str().ok())
else {
return Err(AuthFailure::unauthorized(
AuthFailureReason::MissingCredentials,
));
};
if !constant_time_eq(presented.as_bytes(), expected.as_bytes()) {
return Err(AuthFailure::unauthorized(
AuthFailureReason::CredentialMismatch,
));
}
Ok(AuthContext {
subject: Some("static-token-client".to_string()),
issuer: Some("krab.static".to_string()),
provider: Some("static".to_string()),
token_id: None,
token_use: None,
tenant_id: None,
scopes: vec![],
roles: vec![],
})
}
pub fn authorize_with_jwt(req: &Request<Body>, path: &str) -> Result<AuthContext, StatusCode> {
let cache = JwtVerifierCache::from_env();
authorize_with_jwt_cached(req, path, &cache)
}
pub fn authorize_with_jwt_cached(
req: &Request<Body>,
path: &str,
cache: &JwtVerifierCache,
) -> Result<AuthContext, StatusCode> {
authorize_jwt_detailed(req, path, cache, &AuthPolicy::from_env())
.map_err(|failure| failure.status)
}
fn bearer_token(req: &Request<Body>) -> Option<&str> {
req.headers()
.get("authorization")
.and_then(|h| h.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
}
fn authorize_jwt_detailed(
req: &Request<Body>,
path: &str,
cache: &JwtVerifierCache,
policy: &AuthPolicy,
) -> Result<AuthContext, AuthFailure> {
let bearer = bearer_token(req).ok_or(AuthFailure::unauthorized(
AuthFailureReason::MissingCredentials,
))?;
let header = jsonwebtoken::decode_header(bearer)
.map_err(|_| AuthFailure::unauthorized(AuthFailureReason::MalformedToken))?;
let env = crate::config::Environment::from_env();
let alg = format!("{:?}", header.alg);
let allowed_algs = configured_jwt_algorithms()
.map_err(|status| AuthFailure::new(status, AuthFailureReason::Misconfigured))?;
if !allowed_algs.contains(&header.alg) || !jwt_algorithm_allowed(&alg, &env) {
warn!(
alg = ?header.alg,
environment = %env.as_str(),
"jwt_algorithm_rejected_by_hardening_profile"
);
return Err(AuthFailure::unauthorized(
AuthFailureReason::AlgorithmRejected,
));
}
if cache.load_failed() {
warn!("jwt_provider_configuration_unavailable_rejecting_request");
return Err(AuthFailure::new(
StatusCode::SERVICE_UNAVAILABLE,
AuthFailureReason::Misconfigured,
));
}
let mut validation = jsonwebtoken::Validation::new(header.alg);
validation.algorithms = allowed_algs.clone();
validation.validate_exp = true;
validation.validate_aud = false;
validation.leeway = jwt_leeway_secs();
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(i64::MAX);
let mut failure = AuthFailureReason::UnknownKey;
let mut note = |reason: AuthFailureReason| {
if reason.specificity() > failure.specificity() {
failure = reason;
}
};
let mut remote_unavailable = false;
let mut kidless_trials = 0usize;
let mut accepted: Option<(JwtClaims, String)> = None;
'providers: for (provider_index, provider) in cache.providers().iter().enumerate() {
let kids = cache.candidate_kids(provider_index, header.kid.as_deref());
if kids.is_empty() && cache.remote_unavailable(provider_index) {
remote_unavailable = true;
}
for selected_kid in &kids {
if cache.is_retired(provider_index, selected_kid, now) {
warn!(
provider = provider.name.as_deref().unwrap_or("provider"),
kid = %selected_kid,
"jwt_key_retired_rejecting_token"
);
note(AuthFailureReason::KeyRetired);
continue;
}
let Some(decoding_key) = cache.decoding_key(provider_index, selected_kid, header.alg)
else {
warn!(
provider = provider.name.as_deref().unwrap_or("provider"),
alg = ?header.alg,
"jwt_provider_key_material_invalid_for_algorithm"
);
continue;
};
if header.kid.is_none() {
if kidless_trials >= MAX_KIDLESS_KEY_TRIALS {
warn!(
max_trials = MAX_KIDLESS_KEY_TRIALS,
"jwt_kidless_key_trial_cap_reached"
);
break 'providers;
}
kidless_trials += 1;
}
let token_data =
match jsonwebtoken::decode::<JwtClaims>(bearer, &decoding_key, &validation) {
Ok(data) => data,
Err(error) => {
note(match error.kind() {
jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
AuthFailureReason::Expired
}
jsonwebtoken::errors::ErrorKind::InvalidSignature => {
AuthFailureReason::InvalidSignature
}
_ => AuthFailureReason::MalformedToken,
});
continue;
}
};
if validate_provider_claims(&token_data.claims, provider).is_err() {
note(AuthFailureReason::ClaimsRejected);
continue;
}
accepted = Some((
token_data.claims,
provider
.name
.clone()
.unwrap_or_else(|| "provider".to_string()),
));
break 'providers;
}
}
let Some((claims, provider_name)) = accepted else {
if failure == AuthFailureReason::UnknownKey && remote_unavailable {
return Err(AuthFailure::new(
StatusCode::SERVICE_UNAVAILABLE,
AuthFailureReason::ProviderUnavailable,
));
}
return Err(AuthFailure::unauthorized(failure));
};
if matches!(claims.token_use.as_deref(), Some("refresh")) {
warn!("refresh_token_presented_to_access_protected_route");
return Err(AuthFailure::unauthorized(
AuthFailureReason::RefreshTokenRejected,
));
}
let scopes = scopes_from_claims(&claims);
let roles = roles_from_claims(&claims);
let tenant_id = tenant_from_claims(&claims);
policy
.enforce(path, &claims, tenant_id.as_deref(), &scopes, &roles)
.map_err(|status| {
let reason = if status == StatusCode::INTERNAL_SERVER_ERROR {
AuthFailureReason::Misconfigured
} else {
AuthFailureReason::PolicyDenied
};
AuthFailure::new(status, reason)
})?;
Ok(AuthContext {
subject: claims.sub,
issuer: claims.iss,
provider: Some(provider_name),
token_id: claims.jti,
token_use: claims.token_use,
tenant_id,
scopes,
roles,
})
}
pub(crate) const FRAMEWORK_OPEN_PATHS: &[&str] = &["/health", "/ready"];
pub(crate) const LEGACY_APP_OPEN_PATHS: &[&str] = &[
"/",
"/contact",
"/api/contact",
"/api/v1/auth/login",
"/api/v1/auth/refresh",
"/api/v1/auth/revoke",
"/api/v1/auth/jwks",
"/api/v1/auth/capabilities",
"/api/v1/auth/status",
"/api/status",
"/data/dashboard",
"/rpc/version",
"/rpc/now",
"/asset-manifest.json",
"/blog/*",
"/pkg/*",
];
pub(crate) const METRICS_OPEN_PATHS: &[&str] = &["/metrics", "/metrics/prometheus"];
pub(crate) fn auth_open_path_patterns() -> Vec<String> {
let mut patterns: Vec<String> = match std::env::var("KRAB_AUTH_OPEN_PATHS") {
Ok(raw) => parse_csv_set(&raw),
Err(_) => {
let mut defaults: Vec<String> =
FRAMEWORK_OPEN_PATHS.iter().map(|s| s.to_string()).collect();
if crate::http::bool_env("KRAB_AUTH_LEGACY_OPEN_PATHS", true) {
warn!(
paths = ?LEGACY_APP_OPEN_PATHS,
removed_in = "0.7.0",
"auth_legacy_default_open_paths_in_use: these application routes are \
unauthenticated only because they are on the framework's default list; \
declare the ones this service serves with KRAB_AUTH_PUBLIC_PATHS or \
RuntimeState::with_public_paths, then set KRAB_AUTH_LEGACY_OPEN_PATHS=false"
);
defaults.extend(LEGACY_APP_OPEN_PATHS.iter().map(|s| s.to_string()));
}
defaults
}
};
if metrics_public() {
for path in METRICS_OPEN_PATHS {
let path = (*path).to_string();
if !patterns.contains(&path) {
patterns.push(path);
}
}
}
patterns
}
pub(crate) fn metrics_public() -> bool {
crate::http::bool_env("KRAB_METRICS_PUBLIC", false)
}
pub(crate) fn path_matches_patterns(path: &str, patterns: &[String]) -> bool {
patterns.iter().any(|pattern| {
if let Some(prefix) = pattern.strip_suffix('*') {
path.starts_with(prefix)
} else {
path == pattern
}
})
}
pub async fn auth_middleware<S>(
State(state): State<S>,
mut req: Request<Body>,
next: Next,
) -> Result<Response, StatusCode>
where
S: Clone + Send + Sync + 'static + HasRuntimeState,
{
let path = req.uri().path().to_string();
let runtime = state.runtime_state();
let open = path_matches_patterns(&path, &runtime.auth_open_paths);
let is_public = runtime.is_public_path(&path);
if open || is_public {
return Ok(next.run(req).await);
}
let client_ip = extract_client_ip(&req, runtime.trust_proxy_headers);
let auth_window_secs = runtime.auth_fail_window_secs;
let auth_window = current_window_epoch(auth_window_secs);
let auth_key = format!("auth:fail:{client_ip}:{auth_window}");
let kidless_bearer = bearer_token(&req)
.and_then(|token| jsonwebtoken::decode_header(token).ok())
.is_some_and(|header| header.kid.is_none());
let pre_check = if kidless_bearer {
runtime.store.get(&auth_key).await
} else {
Ok(None)
};
match pre_check {
Ok(Some(count))
if count
.trim()
.parse::<u64>()
.is_ok_and(|count| count > runtime.auth_fail_threshold) =>
{
debug!(
client_ip = %client_ip,
threshold = runtime.auth_fail_threshold,
"auth_failure_rate_limiter_rejected_before_verification"
);
return Err(StatusCode::TOO_MANY_REQUESTS);
}
Ok(_) => {}
Err(err) => {
debug!(
error = %err,
client_ip = %client_ip,
"auth_failure_budget_lookup_failed_verifying_anyway"
);
}
}
let mode = runtime.auth_mode.clone();
let authorized = if mode.eq_ignore_ascii_case("jwt") || mode.eq_ignore_ascii_case("oidc") {
let cache = &runtime.jwt_verifier_cache;
if cache.uses_jwks() {
let kid = bearer_token(&req)
.and_then(|token| jsonwebtoken::decode_header(token).ok())
.and_then(|header| header.kid);
cache.prepare_for_kid(kid.as_deref()).await;
}
authorize_jwt_detailed(&req, &path, cache, &runtime.auth_policy)
} else {
authorize_static_detailed(&req)
};
let authorized = match authorized {
Ok(ctx) => {
if let Some(token_id) = ctx.token_id.as_deref() {
let revoked_key = format!("auth:revoked:{token_id}");
match runtime.store.get(&revoked_key).await {
Ok(Some(_)) => {
warn!(token_id = %token_id, path = %path, "revoked_token_rejected");
Err(AuthFailure::unauthorized(AuthFailureReason::Revoked))
}
Ok(None) => Ok(ctx),
Err(err) => {
warn!(
error = %err,
token_id = %token_id,
"revocation_lookup_failed_failing_closed"
);
Err(AuthFailure::new(
StatusCode::SERVICE_UNAVAILABLE,
AuthFailureReason::ProviderUnavailable,
))
}
}
} else {
Ok(ctx)
}
}
Err(failure) => Err(failure),
};
match authorized {
Ok(ctx) => {
if is_admin_api_path(&path) && !runtime.auth_policy.has_admin_entitlement(&ctx) {
return Err(StatusCode::FORBIDDEN);
}
req.extensions_mut().insert(ctx);
Ok(next.run(req).await)
}
Err(AuthFailure {
status: code,
reason,
}) => {
runtime.auth_failures_total.fetch_add(1, Ordering::Relaxed);
runtime.auth_failure_reasons[reason.slot()].fetch_add(1, Ordering::Relaxed);
debug!(
reason = reason.as_str(),
status = code.as_u16(),
"auth_request_rejected"
);
if code != StatusCode::UNAUTHORIZED {
return Err(code);
}
let failures = match runtime
.store
.incr_with_ttl(&auth_key, 1, Duration::from_secs(auth_window_secs + 2))
.await
{
Ok(count) => count,
Err(err) => {
warn!(
error = %err,
client_ip = %client_ip,
"auth_failure_store_error_failing_closed"
);
return Err(StatusCode::SERVICE_UNAVAILABLE);
}
};
if failures > runtime.auth_fail_threshold {
warn!(
failures_in_window = failures,
window_seconds = auth_window_secs,
threshold = runtime.auth_fail_threshold,
limiter_scope = "per_ip_distributed_auth_failures",
client_ip = %client_ip,
"auth_failure_rate_limiter_triggered"
);
return Err(StatusCode::TOO_MANY_REQUESTS);
}
Err(code)
}
}
}
pub fn is_internal_service_path(path: &str) -> bool {
path.starts_with("/internal") || path.starts_with("/api/internal")
}
pub async fn service_auth_middleware<S>(
State(state): State<S>,
req: Request<Body>,
next: Next,
) -> Result<Response, StatusCode>
where
S: Clone + Send + Sync + 'static + HasRuntimeState,
{
let path = req.uri().path().to_string();
if !is_internal_service_path(&path) {
return Ok(next.run(req).await);
}
let expected_scope = state.runtime_state().service_auth_scope.clone();
let has_scope = req
.extensions()
.get::<AuthContext>()
.map(|ctx| ctx.scopes.iter().any(|scope| scope == &expected_scope))
.unwrap_or(false);
if !has_scope {
warn!(
path = %path,
required_scope = %expected_scope,
"service_auth_scope_validation_failed"
);
return Err(StatusCode::FORBIDDEN);
}
debug!(
path = %path,
required_scope = %expected_scope,
"service_auth_scope_validation_passed"
);
Ok(next.run(req).await)
}
#[cfg(test)]
mod open_path_tests {
use super::{
auth_open_path_patterns, path_matches_patterns, FRAMEWORK_OPEN_PATHS, LEGACY_APP_OPEN_PATHS,
};
use serial_test::serial;
fn reset_open_path_env() {
std::env::remove_var("KRAB_AUTH_OPEN_PATHS");
std::env::remove_var("KRAB_METRICS_PUBLIC");
std::env::remove_var("KRAB_AUTH_LEGACY_OPEN_PATHS");
}
#[test]
#[serial]
fn legacy_app_paths_can_be_dropped_ahead_of_0_7() {
reset_open_path_env();
std::env::set_var("KRAB_AUTH_LEGACY_OPEN_PATHS", "false");
let patterns = auth_open_path_patterns();
reset_open_path_env();
assert_eq!(
patterns,
FRAMEWORK_OPEN_PATHS
.iter()
.map(|s| s.to_string())
.collect::<Vec<_>>()
);
assert!(!path_matches_patterns("/", &patterns));
assert!(!path_matches_patterns("/contact", &patterns));
assert!(path_matches_patterns("/ready", &patterns));
}
#[test]
fn pattern_matching_supports_exact_and_prefix() {
let patterns: Vec<String> = vec!["/health".into(), "/blog/*".into()];
assert!(path_matches_patterns("/health", &patterns));
assert!(!path_matches_patterns("/healthz", &patterns));
assert!(path_matches_patterns("/blog/post-1", &patterns));
assert!(!path_matches_patterns("/metrics", &patterns));
}
#[test]
#[serial]
fn default_open_paths_exclude_metrics() {
reset_open_path_env();
let patterns = auth_open_path_patterns();
assert_eq!(
patterns,
FRAMEWORK_OPEN_PATHS
.iter()
.chain(LEGACY_APP_OPEN_PATHS)
.map(|s| s.to_string())
.collect::<Vec<_>>()
);
assert!(
!path_matches_patterns("/metrics", &patterns),
"metrics must not be anonymously readable without an explicit opt-in"
);
assert!(!path_matches_patterns("/metrics/prometheus", &patterns));
assert!(path_matches_patterns("/health", &patterns));
assert!(path_matches_patterns("/pkg/app_bg.wasm", &patterns));
assert!(!path_matches_patterns("/api/v1/users", &patterns));
}
#[test]
#[serial]
fn metrics_public_env_reopens_both_metrics_paths() {
reset_open_path_env();
std::env::set_var("KRAB_METRICS_PUBLIC", "true");
let patterns = auth_open_path_patterns();
reset_open_path_env();
assert!(path_matches_patterns("/metrics", &patterns));
assert!(path_matches_patterns("/metrics/prometheus", &patterns));
assert!(path_matches_patterns("/health", &patterns));
assert!(!path_matches_patterns("/api/v1/users", &patterns));
}
#[test]
#[serial]
fn metrics_public_env_applies_over_an_explicit_open_path_list() {
reset_open_path_env();
std::env::set_var("KRAB_AUTH_OPEN_PATHS", "/health,/ready");
std::env::set_var("KRAB_METRICS_PUBLIC", "1");
let patterns = auth_open_path_patterns();
reset_open_path_env();
assert!(path_matches_patterns("/health", &patterns));
assert!(
path_matches_patterns("/metrics", &patterns),
"the metrics flag must not be silently inert when KRAB_AUTH_OPEN_PATHS is set"
);
}
#[test]
#[serial]
fn operators_can_close_metrics_via_env() {
reset_open_path_env();
std::env::set_var("KRAB_AUTH_OPEN_PATHS", "/health,/ready");
let patterns = auth_open_path_patterns();
reset_open_path_env();
assert!(path_matches_patterns("/health", &patterns));
assert!(
!path_matches_patterns("/metrics", &patterns),
"an explicit open-path list must be able to close /metrics"
);
}
#[test]
#[serial]
fn empty_env_value_closes_every_default_open_path() {
reset_open_path_env();
std::env::set_var("KRAB_AUTH_OPEN_PATHS", "");
let patterns = auth_open_path_patterns();
reset_open_path_env();
assert!(patterns.is_empty());
assert!(!path_matches_patterns("/health", &patterns));
}
}
#[cfg(test)]
mod jwks_lazy_refresh_tests {
use super::{JwtProviderConfig, JwtVerifierCache};
use serde_json::{json, Value};
use serial_test::serial;
use std::sync::{Arc, Mutex};
use std::time::Duration;
const ED_X: &str = "tQCGXC6DpH3eQ7mQpTmUwz_UrjPnQ-X2ztczWt5Uyis";
fn jwk(kid: &str) -> Value {
json!({"kty": "OKP", "crv": "Ed25519", "kid": kid, "x": ED_X, "use": "sig"})
}
#[test]
#[serial]
fn without_a_runtime_key_sets_are_refreshed_on_the_request_path() {
let runtime = tokio::runtime::Runtime::new().unwrap();
let document = Arc::new(Mutex::new(json!({"keys": [jwk("k1")]})));
let served = document.clone();
let url = runtime.block_on(async move {
let app = axum::Router::new().route(
"/jwks",
axum::routing::get(move || {
let served = served.clone();
async move { axum::Json(served.lock().unwrap().clone()) }
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
format!("http://{addr}/jwks")
});
std::env::remove_var("KRAB_ENVIRONMENT");
let provider = JwtProviderConfig {
name: Some("idp".to_string()),
issuer: None,
audience: None,
keys: Default::default(),
required_claims: Default::default(),
jwks_url: Some(url),
key_not_after: Default::default(),
};
let cache = Arc::new(JwtVerifierCache::from_providers_with(
vec![provider],
crate::jwks::JwksSettings {
refresh_every: Duration::from_millis(200),
min_refetch: Duration::from_millis(50),
timeout: Duration::from_secs(2),
},
));
JwtVerifierCache::spawn_background_refresh(&cache);
let source = cache.jwks[0].clone().unwrap();
runtime.block_on(cache.prepare_for_kid(Some("k1")));
assert!(source.has_kid("k1"));
*document.lock().unwrap() = json!({"keys": [jwk("k2")]});
std::thread::sleep(Duration::from_millis(300));
runtime.block_on(cache.prepare_for_kid(Some("k1")));
assert!(
!source.has_kid("k1"),
"a key removed at the provider must stop verifying without a background task"
);
assert!(source.has_kid("k2"));
}
}