blob: ee9d4a401e60dd74565bb0551089aa2fe269b970 [file]
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Minimal JWT issuer/verifier for the shard-0 HTTP listener.
//!
//! Ported from the legacy server implementation's `JwtManager`, reduced
//! to the issue + verify half: no revoked-token persistence. Self-issued HS256
//! is the common path; with `[[http.jwt.trusted_issuers]]` configured, `decode`
//! also verifies external RS256/EC tokens against the issuer's JWKS
//! ([`super::jwks`]) and maps them onto the configured iggy username.
//! The refresh-token route re-issues by composing `decode_for_refresh` (verify
//! plus a refusal of trusted-issuer tokens) with `generate` at the handler.
//! Refresh leaves the original token usable until it expires, the account
//! revision changes, or its source personal access token is revoked or expires.
//! The claim set (`JwtClaims`) is
//! the legacy one plus `user_created_at`, which names the account a
//! self-issued token was issued to, `access_revision`, which a password change
//! or a revocation moves past, and `token_id` for a token exchanged from a
//! personal access token. The `IggyError -> HTTP` grading is reused verbatim so
//! error bodies stay identical to the legacy server.
use std::collections::HashMap;
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use configs::http::{HttpJwtConfig, TrustedIssuerConfig};
use iggy_binary_protocol::requests::users::login_register::CredentialProof;
use iggy_common::{IggyDuration, IggyError, IggyExpiry, IggyTimestamp, UserId};
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use server_common::crypto;
use tracing::{debug, error, info, warn};
use uuid::Uuid;
use super::jwks::JwksClient;
/// Length window for the random secret minted when no secret is configured.
/// Matches the legacy server so both behave identically on an empty secret.
const GENERATED_SECRET_LEN: Range<usize> = 32..64;
/// BLAKE3 `derive_key` context for turning the cluster PSK into the HS256
/// signing key when no JWT secret is configured in cluster mode. A distinct
/// context string keeps this key cryptographically independent from the
/// replica-auth MAC subkey derived from the same PSK. Deliberate coupling:
/// with this fallback a PSK compromise also yields the token-signing key, and
/// rotating the PSK invalidates all bearers; operators who want the domains
/// decoupled configure an explicit `http.jwt` secret, which always wins.
///
/// Frozen string: it is KDF domain separation, not a label. Editing it derives
/// a different signing key and invalidates every bearer issued before the
/// change.
const JWT_KEY_CONTEXT: &str = "apache-iggy server http-jwt v1 psk->hs256-key";
/// Expiry stamp used for a non-expiring token: far enough out to never trip
/// `exp` validation, small enough to fit `u32`. Mirrors the legacy server.
const NEVER_EXPIRE_SECS: u32 = 1_000_000_000;
/// Fixed-lifetime issuer/verifier for HTTP bearer tokens on shard 0.
pub struct JwtManager {
algorithm: Algorithm,
issuer: String,
audience: String,
access_token_expiry: IggyExpiry,
not_before: IggyDuration,
encoding_key: EncodingKey,
decoding_key: DecodingKey,
validation: Validation,
jwks_client: JwksClient,
/// Trusted external issuers keyed by normalized issuer URL. Empty unless
/// `[[http.jwt.trusted_issuers]]` is configured, in which case `decode`
/// takes the JWKS verification path for tokens from these issuers.
trusted_issuers: HashMap<String, Arc<TrustedIssuer>>,
}
#[derive(Debug)]
pub(in crate::http) struct TrustedIssuer {
pub config: TrustedIssuerConfig,
warned_account: AtomicBool,
}
impl TrustedIssuer {
pub fn warn_invalid_account(&self) {
if !self.warned_account.swap(true, Ordering::Relaxed) {
warn!(
issuer = %self.config.issuer,
username = %self.config.username,
"refusing trusted issuer tokens: configured user is missing, inactive or root"
);
}
}
}
impl JwtManager {
/// Build the manager from the `[http.jwt]` config, normalizing an
/// unconfigured secret the same way the legacy server does (mint a random
/// ephemeral secret, or mirror whichever half is set) and loading any
/// configured trusted issuers (keyed by normalized issuer URL).
///
/// `cluster_psk`, when present, replaces the random-mint fallback with a
/// key derived from the cluster shared secret, so every node verifies
/// every node's bearers - the invariant follower-to-primary forwarding
/// depends on. A configured secret always wins over it.
///
/// # Errors
///
/// Returns [`IggyError`] if the configured algorithm is unsupported or a
/// secret cannot be turned into an encoding/decoding key.
pub fn build(config: &HttpJwtConfig, cluster_psk: Option<&str>) -> Result<Self, IggyError> {
let config = normalize_secrets(config.clone(), cluster_psk);
let algorithm = config.get_algorithm()?;
let encoding_key = config.get_encoding_key()?;
let decoding_key = config.get_decoding_key()?;
let mut validation = Validation::new(algorithm);
validation.set_issuer(&config.valid_issuers);
validation.set_audience(&config.valid_audiences);
validation.leeway = u64::from(config.clock_skew.as_secs());
// The issuer always stamps `nbf`, so enforce it: a token presented
// before its not-before instant (beyond `leeway`) is rejected.
// `jsonwebtoken` leaves `validate_nbf` off by default, so this is
// explicit; the claim is always present, so it only ever tightens.
validation.validate_nbf = true;
// Reject missing fields at startup instead of failing token verification
// at first use. Root mappings are refused per request, by user id.
for issuer_config in config.trusted_issuers.iter().flatten() {
if issuer_config.issuer.is_empty() {
error!("trusted issuer configured with an empty issuer URL");
return Err(IggyError::InvalidConfiguration);
}
if issuer_config.audience.is_empty() {
error!(
issuer = %issuer_config.issuer,
"trusted issuer configured with an empty audience"
);
return Err(IggyError::InvalidConfiguration);
}
if issuer_config.jwks_url.is_empty() {
error!(
issuer = %issuer_config.issuer,
"trusted issuer configured with an empty jwks_url"
);
return Err(IggyError::InvalidConfiguration);
}
if issuer_config.username.is_empty() {
error!(
issuer = %issuer_config.issuer,
"trusted issuer configured without a username, the key that replaced user_id"
);
return Err(IggyError::InvalidConfiguration);
}
}
let trusted_issuers = config
.trusted_issuers
.iter()
.flatten()
.map(|issuer_config| {
(
normalize_issuer_url(&issuer_config.issuer),
Arc::new(TrustedIssuer {
config: issuer_config.clone(),
warned_account: AtomicBool::new(false),
}),
)
})
.collect();
Ok(Self {
algorithm,
issuer: config.issuer,
audience: config.audience,
access_token_expiry: config.access_token_expiry,
not_before: config.not_before,
encoding_key,
decoding_key,
validation,
jwks_client: JwksClient::default(),
trusted_issuers,
})
}
/// Issue a signed access token for the account `user_id` carrying what
/// `credential` proved, a unique `jti` plus issued-at / not-before / expiry
/// stamps derived from the config. The expiry never passes
/// `expires_at_secs`, the expiry of the personal access token the token was
/// exchanged from.
///
/// # Errors
///
/// Returns [`IggyError::CannotGenerateJwt`] if signing fails.
pub fn generate(
&self,
user_id: UserId,
credential: CredentialProof,
cluster_uid: u128,
expires_at_secs: u64,
) -> Result<GeneratedToken, IggyError> {
let header = Header::new(self.algorithm);
let iat = IggyTimestamp::now().to_secs();
let expiry_secs = match self.access_token_expiry {
IggyExpiry::NeverExpire => NEVER_EXPIRE_SECS,
IggyExpiry::ServerDefault => 0,
IggyExpiry::ExpireDuration(duration) => duration.as_secs(),
};
let exp = (iat + u64::from(expiry_secs)).min(expires_at_secs);
let nbf = iat + u64::from(self.not_before.as_secs());
let claims = JwtClaims {
jti: Uuid::now_v7().to_string(),
sub: user_id.to_string(),
aud: Audience::from(self.audience.clone()),
iss: self.issuer.clone(),
iat,
exp,
nbf,
user_created_at: Some(credential.user_created_at),
access_revision: Some(credential.access_revision),
token_id: (credential.token_id != 0).then_some(credential.token_id),
};
let claims = SelfIssuedClaims {
claims,
cluster_uid: Uuid::from_u128(cluster_uid),
};
let access_token = encode(&header, &claims, &self.encoding_key)
.map_err(|_| IggyError::CannotGenerateJwt)?;
Ok(GeneratedToken {
user_id,
access_token,
access_token_expiry: exp,
})
}
/// Verify a token's signature and registered claims, returning its `jti`
/// (what a session table keys on), its `exp` and the account it acts as.
///
/// With no trusted issuers this is the self-issued HS256 verify and the
/// returned future resolves without awaiting. When the token's issuer
/// matches a configured trusted issuer, verification instead uses the
/// issuer's JWKS key (awaiting the fetch on a cache miss) and the subject
/// is the configured iggy username, not the external subject.
///
/// # Errors
///
/// Returns [`IggyError::Unauthenticated`] if the token is malformed,
/// expired, or fails issuer/audience/signature validation.
pub async fn decode(&self, token: &str) -> Result<VerifiedToken, IggyError> {
// With no trusted issuers this is the original self-issued verifier,
// resolving without ever awaiting.
if self.trusted_issuers.is_empty() {
return self.decode_self_issued(token);
}
// Try the self-issued verify first. Self-issued is always HS* (config
// validation refuses anything else), so a token signed by an issuer's
// key fails here either at the algorithm check, when its header names a
// non-HMAC alg, or at the signature check, when the header claims HS*
// but the signature was not made with the local secret. Either way an
// external token can never be accepted as self-issued; a valid
// self-issued token returns here and the classification below only runs
// once it has failed.
if let Ok(verified) = self.decode_self_issued(token) {
return Ok(verified);
}
// Self-issued verify failed. Classify the token by its (untrusted) issuer
// claim; if it names a trusted issuer, verify it against that issuer's
// JWKS key. Everything read here is re-checked under that key below.
let Ok(insecure) = jsonwebtoken::dangerous::insecure_decode::<JwtClaims>(token) else {
debug!("token is not self-issued and cannot be parsed to classify its issuer");
return Err(IggyError::Unauthenticated);
};
let normalized_iss = normalize_issuer_url(&insecure.claims.iss);
let Some(issuer) = self.trusted_issuers.get(&normalized_iss) else {
debug!(
issuer = %insecure.claims.iss,
"token issuer matches no trusted issuer and failed self-issued verify"
);
return Err(IggyError::Unauthenticated);
};
let config = &issuer.config;
// `insecure.header` is parsed from the same header segment `decode_header`
// reads, so reuse it for `alg` and `kid` instead of parsing twice.
let Some(kid) = insecure.header.kid.as_deref() else {
debug!(
issuer = %config.issuer,
"trusted-issuer token has no `kid` header for JWKS key lookup"
);
return Err(IggyError::Unauthenticated);
};
let decoding_key = match self
.jwks_client
.get_key(&config.issuer, &config.jwks_url, kid)
.await
{
Ok(key) => key,
Err(error) => {
// Fail closed but loud: a broken `jwks_url` or a rotated-away
// `kid` otherwise surfaces only as an opaque 401.
warn!(
%error,
issuer = %config.issuer,
kid,
"cannot resolve JWKS key for trusted-issuer token"
);
return Err(IggyError::Unauthenticated);
}
};
// The algorithm is taken from the token header (e.g. RS256), not the
// self-issued HS256; issuer and audience are pinned to the config, and
// the timing checks mirror the self-issued path (enforce `nbf`, honor
// the configured clock skew).
let mut validation = Validation::new(insecure.header.alg);
validation.set_issuer(std::slice::from_ref(&config.issuer));
validation.set_audience(std::slice::from_ref(&config.audience));
validation.validate_nbf = true;
validation.leeway = self.validation.leeway;
let claims = decode::<JwtClaims>(token, &decoding_key, &validation)
.map(|data| data.claims)
.map_err(|error| {
error!(%error, "trusted-issuer JWT verification failed");
IggyError::Unauthenticated
})?;
// The raw external `sub` is discarded (no auto-provisioning): every
// token from this issuer acts as the configured iggy user.
Ok(VerifiedToken {
jti: claims.jti,
exp: claims.exp,
subject: TokenSubject::TrustedIssuer(Arc::clone(issuer)),
})
}
/// Verify a token for the refresh route and return the account it names,
/// refusing any token minted by a trusted external issuer: those carry
/// their own lifecycle (the issuer controls their `exp`), so exchanging one
/// for a self-issued token would mint a bearer that outlives the external
/// grant. Mirrors the legacy `JwtManager::refresh_token` reject.
///
/// # Errors
///
/// Returns [`IggyError::InvalidAccessToken`] for a trusted-issuer token, or
/// whatever [`Self::decode`] returns for an otherwise invalid one.
pub async fn decode_for_refresh(
&self,
token: &str,
) -> Result<(UserId, CredentialProof, u128), IggyError> {
match self.decode(token).await?.subject {
TokenSubject::Account {
user_id,
credential,
cluster_uid,
} => Ok((user_id, credential, cluster_uid)),
TokenSubject::TrustedIssuer(issuer) => {
debug!(username = %issuer.config.username, "refusing to refresh a trusted-issuer token");
Err(IggyError::InvalidAccessToken)
}
}
}
/// Self-issued HS256 verify against the configured secret and validation.
/// The synchronous common path shared by the fast path and by every
/// trusted-issuer classification miss.
fn decode_self_issued(&self, token: &str) -> Result<VerifiedToken, IggyError> {
let SelfIssuedClaims {
claims,
cluster_uid,
} = decode::<SelfIssuedClaims>(token, &self.decoding_key, &self.validation)
.map(|data| data.claims)
.map_err(|_| IggyError::Unauthenticated)?;
let user_id = claims.sub.parse().map_err(|_| IggyError::Unauthenticated)?;
// Missing only on a token from a server that did not stamp them yet.
let user_created_at = claims.user_created_at.ok_or(IggyError::Unauthenticated)?;
let access_revision = claims
.access_revision
.filter(|&revision| revision != 0)
.ok_or(IggyError::Unauthenticated)?;
Ok(VerifiedToken {
jti: claims.jti,
exp: claims.exp,
subject: TokenSubject::Account {
user_id,
cluster_uid: cluster_uid.as_u128(),
credential: CredentialProof {
user_created_at,
access_revision,
token_id: claims.token_id.unwrap_or_default(),
},
},
})
}
}
/// Normalize an issuer URL by lowercasing scheme and host while preserving path
/// case, so trusted-issuer lookup is case-insensitive on the parts that are
/// (`https://Example.COM/PATH` -> `https://example.com/PATH`).
fn normalize_issuer_url(url: &str) -> String {
match url.split_once("://") {
Some((scheme, rest)) => {
let scheme = scheme.to_lowercase();
let (host, path) = rest.find('/').map_or((rest, ""), |idx| rest.split_at(idx));
format!("{}://{}{}", scheme, host.to_lowercase(), path)
}
None => url.trim_end_matches('/').to_lowercase(),
}
}
/// Fill in an unconfigured JWT secret exactly like the legacy HTTP server:
/// both empty -> one random ephemeral secret; one empty -> mirror the other;
/// both set but different -> warn (they must match).
fn normalize_secrets(mut config: HttpJwtConfig, cluster_psk: Option<&str>) -> HttpJwtConfig {
match (
config.encoding_secret.is_empty(),
config.decoding_secret.is_empty(),
) {
(true, true) => {
if let Some(psk) = cluster_psk {
// Cluster-wide deterministic key: hex of the derived 256-bit
// subkey, so every node signs and verifies identically and a
// follower-forwarded bearer is valid on the primary. Hex (not
// raw bytes) because the secret travels the same String path
// a configured secret does.
let derived = blake3::derive_key(JWT_KEY_CONTEXT, psk.as_bytes());
let secret = blake3::Hash::from_bytes(derived).to_hex().to_string();
info!(
"JWT secrets are not configured - derived a cluster-wide secret from cluster.auth.shared_secret; tokens are valid on every node and rotate with the PSK"
);
config.encoding_secret.clone_from(&secret);
config.decoding_secret = secret;
return config;
}
let secret = crypto::generate_secret(GENERATED_SECRET_LEN);
let redacted: String = secret.chars().take(3).collect();
warn!(
"JWT encoding and decoding secrets are not configured - generated a random secret: {redacted}***. JWT tokens will be invalidated on server restart. Set 'encoding_secret' and 'decoding_secret' in the config to use persistent secrets."
);
config.encoding_secret.clone_from(&secret);
config.decoding_secret = secret;
}
(true, false) => {
warn!(
"JWT encoding secret is not configured but decoding secret is set - using decoding secret for both. Set 'encoding_secret' in the config to avoid this warning."
);
config.encoding_secret = config.decoding_secret.clone();
}
(false, true) => {
warn!(
"JWT decoding secret is not configured but encoding secret is set - using encoding secret for both. Set 'decoding_secret' in the config to avoid this warning."
);
config.decoding_secret = config.encoding_secret.clone();
}
(false, false) => {
if config.encoding_secret != config.decoding_secret {
warn!(
"JWT encoding and decoding secrets are different but self-issued tokens are signed and verified with one shared secret (algorithm is {}) - both secrets must be identical.",
config.algorithm
);
}
}
}
config
}
#[derive(Debug, Clone)]
pub(in crate::http) enum Audience {
Single(String),
Multiple(Vec<String>),
}
impl From<String> for Audience {
fn from(aud: String) -> Self {
Self::Single(aud)
}
}
impl Serialize for Audience {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Single(aud) => serializer.serialize_str(aud),
Self::Multiple(auds) => auds.serialize(serializer),
}
}
}
impl<'de> Deserialize<'de> for Audience {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct AudienceVisitor;
impl<'de> serde::de::Visitor<'de> for AudienceVisitor {
type Value = Audience;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a string or an array of strings")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(Audience::Single(value.to_string()))
}
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(Audience::Single(value))
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let mut auds = Vec::new();
while let Some(aud) = seq.next_element::<String>()? {
auds.push(aud);
}
Ok(Audience::Multiple(auds))
}
}
deserializer.deserialize_any(AudienceVisitor)
}
}
#[derive(Debug, Serialize, Deserialize)]
struct SelfIssuedClaims {
#[serde(flatten)]
claims: JwtClaims,
cluster_uid: Uuid,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
struct JwtClaims {
pub jti: String,
pub iss: String,
pub aud: Audience,
pub sub: String,
pub iat: u64,
pub exp: u64,
pub nbf: u64,
/// `created_at` (micros) of the account the token was issued to. A user
/// delete frees its id for the next create, so the id in `sub` alone
/// cannot tell that account from a newer one. Every self-issued token sets
/// it. Only a trusted-issuer token leaves it `None`, and `decode` maps
/// that token onto the configured username instead.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user_created_at: Option<u64>,
/// The account's access revision when the token was issued. A password
/// change or a revocation moves the account past it, which refuses every
/// token issued before. Every self-issued token sets it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub access_revision: Option<u64>,
/// The op that created the personal access token this token was exchanged
/// from, which must stay live and unexpired for the token to work.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token_id: Option<u64>,
}
/// A token that passed [`JwtManager::decode`].
#[derive(Debug)]
pub(in crate::http) struct VerifiedToken {
pub jti: String,
pub exp: u64,
pub subject: TokenSubject,
}
/// The account a verified token acts as.
#[derive(Debug)]
pub(in crate::http) enum TokenSubject {
/// A self-issued token names the account it was issued to and what the
/// credential it was issued for proved.
Account {
user_id: UserId,
credential: CredentialProof,
cluster_uid: u128,
},
/// A trusted-issuer token acts as the user its issuer config names, looked
/// up per request, so a later account that takes a deleted user's id does
/// not inherit the issuer.
TrustedIssuer(Arc<TrustedIssuer>),
}
#[derive(Debug)]
pub(in crate::http) struct GeneratedToken {
pub user_id: UserId,
pub access_token: String,
pub access_token_expiry: u64,
}
#[cfg(test)]
mod tests {
use super::*;
/// A default config (HS256, matching issuer/audience, empty secrets ->
/// one ephemeral secret shared by encode and decode) with the two
/// timing knobs overridden.
fn config(not_before: &str, clock_skew: &str) -> HttpJwtConfig {
HttpJwtConfig {
not_before: not_before.parse().expect("valid duration"),
clock_skew: clock_skew.parse().expect("valid duration"),
..HttpJwtConfig::default()
}
}
const CLUSTER_UID: u128 = u128::MAX - 1;
const USER_ID: UserId = 7;
const USER_CREATED_AT_MICROS: u64 = 1_700_000_000_000_000;
const ACCESS_REVISION: u64 = 12;
const TOKEN_ID: u64 = 34;
fn issue(manager: &JwtManager) -> GeneratedToken {
manager
.generate(
USER_ID,
CredentialProof::account(USER_CREATED_AT_MICROS, ACCESS_REVISION),
CLUSTER_UID,
u64::MAX,
)
.expect("issues")
}
fn claims_of(manager: &JwtManager, token: &str) -> SelfIssuedClaims {
decode::<SelfIssuedClaims>(token, &manager.decoding_key, &manager.validation)
.expect("valid now")
.claims
}
// The default config has no trusted issuers, so `decode` takes the
// synchronous self-issued path; any executor can drive the ready future.
#[tokio::test]
async fn token_presented_before_its_nbf_is_rejected() {
// not_before well past the leeway window, so the freshly issued token
// is not yet valid and decode must reject it.
let manager = JwtManager::build(&config("3600 s", "5 s"), None).expect("builds");
let token = issue(&manager);
assert!(
manager.decode(&token.access_token).await.is_err(),
"a token presented before its nbf must be rejected"
);
}
#[tokio::test]
async fn token_at_its_nbf_is_accepted() {
// Default not_before (0s) => nbf == iat, so the token is valid now and
// enabling nbf validation does not reject a normally issued token.
let manager = JwtManager::build(&config("0 s", "5 s"), None).expect("builds");
let token = issue(&manager);
assert!(
manager.decode(&token.access_token).await.is_ok(),
"a token at its nbf must be accepted"
);
}
#[tokio::test]
async fn given_issued_token_when_decoded_should_name_the_account_it_was_issued_to() {
let manager = JwtManager::build(&config("0 s", "5 s"), None).expect("builds");
let verified = manager
.decode(&issue(&manager).access_token)
.await
.expect("valid now");
assert!(
matches!(
verified.subject,
TokenSubject::Account { user_id: USER_ID, credential, cluster_uid: CLUSTER_UID }
if credential == CredentialProof::account(USER_CREATED_AT_MICROS, ACCESS_REVISION)
),
"unexpected subject {:?}",
verified.subject
);
}
#[tokio::test]
async fn given_token_exchanged_from_personal_access_token_when_decoded_should_name_both_proofs()
{
let manager = JwtManager::build(&config("0 s", "5 s"), None).expect("builds");
let credential = CredentialProof {
user_created_at: USER_CREATED_AT_MICROS,
access_revision: ACCESS_REVISION,
token_id: TOKEN_ID,
};
let token = manager
.generate(USER_ID, credential, CLUSTER_UID, u64::MAX)
.expect("issues");
let verified = manager
.decode(&token.access_token)
.await
.expect("valid now");
assert!(
matches!(
verified.subject,
TokenSubject::Account { user_id: USER_ID, credential: decoded, cluster_uid: CLUSTER_UID } if decoded == credential
),
"unexpected subject {:?}",
verified.subject
);
}
#[test]
fn given_source_token_expiring_first_when_issuing_should_cap_the_expiry() {
let manager = JwtManager::build(
&HttpJwtConfig {
access_token_expiry: IggyExpiry::NeverExpire,
..config("0 s", "5 s")
},
None,
)
.expect("builds");
let source_expiry = IggyTimestamp::now().to_secs() + 60;
let token = manager
.generate(
USER_ID,
CredentialProof::token(USER_CREATED_AT_MICROS, TOKEN_ID),
CLUSTER_UID,
source_expiry,
)
.expect("issues");
assert_eq!(token.access_token_expiry, source_expiry);
assert_eq!(
claims_of(&manager, &token.access_token).claims.exp,
source_expiry
);
}
#[tokio::test]
async fn given_self_issued_token_without_cluster_uid_when_decoded_should_reject() {
let manager = JwtManager::build(&config("0 s", "5 s"), None).unwrap();
let claims = claims_of(&manager, &issue(&manager).access_token).claims;
let token = encode(
&Header::new(manager.algorithm),
&claims,
&manager.encoding_key,
)
.unwrap();
assert!(matches!(
manager.decode(&token).await,
Err(IggyError::Unauthenticated)
));
}
#[tokio::test]
async fn given_self_issued_token_without_access_revision_when_decoded_should_reject() {
let manager = JwtManager::build(&config("0 s", "5 s"), None).expect("builds");
for revision in [None, Some(0)] {
let mut claims = claims_of(&manager, &issue(&manager).access_token);
// A token from before tokens named a revision, signed with the live key.
claims.claims.access_revision = revision;
let token = encode(
&Header::new(manager.algorithm),
&claims,
&manager.encoding_key,
)
.expect("signs");
assert!(
manager.decode(&token).await.is_err(),
"a validly signed token with revision {revision:?} must be refused"
);
}
}
#[tokio::test]
async fn given_self_issued_token_without_account_stamp_when_decoded_should_reject() {
let manager = JwtManager::build(&config("0 s", "5 s"), None).expect("builds");
let mut claims = claims_of(&manager, &issue(&manager).access_token);
// A token from before tokens named their account, signed with the live key.
claims.claims.user_created_at = None;
let token = encode(
&Header::new(manager.algorithm),
&claims,
&manager.encoding_key,
)
.expect("signs");
assert!(
manager.decode(&token).await.is_err(),
"a validly signed token that names no account must be refused"
);
}
#[test]
fn build_rejects_trusted_issuer_with_empty_username() {
let jwt = HttpJwtConfig {
trusted_issuers: Some(vec![TrustedIssuerConfig {
issuer: "https://external.example".to_string(),
audience: "iggy".to_string(),
jwks_url: "https://external.example/.well-known/jwks.json".to_string(),
username: String::new(),
}]),
..HttpJwtConfig::default()
};
match JwtManager::build(&jwt, None) {
Err(IggyError::InvalidConfiguration) => {}
Err(other) => panic!("expected InvalidConfiguration, got {other:?}"),
Ok(_) => panic!("build must reject a trusted issuer with an empty username"),
}
}
#[test]
fn build_rejects_trusted_issuer_with_empty_issuer() {
let jwt = HttpJwtConfig {
trusted_issuers: Some(vec![TrustedIssuerConfig {
issuer: String::new(),
audience: "iggy".to_string(),
jwks_url: "https://external.example/.well-known/jwks.json".to_string(),
username: "service".to_string(),
}]),
..HttpJwtConfig::default()
};
match JwtManager::build(&jwt, None) {
Err(IggyError::InvalidConfiguration) => {}
Err(other) => panic!("expected InvalidConfiguration, got {other:?}"),
Ok(_) => panic!("build must reject a trusted issuer with an empty issuer"),
}
}
#[test]
fn build_rejects_trusted_issuer_with_empty_audience() {
let jwt = HttpJwtConfig {
trusted_issuers: Some(vec![TrustedIssuerConfig {
issuer: "https://external.example".to_string(),
audience: String::new(),
jwks_url: "https://external.example/jwks".to_string(),
username: "service".to_string(),
}]),
..HttpJwtConfig::default()
};
match JwtManager::build(&jwt, None) {
Err(IggyError::InvalidConfiguration) => {}
Err(other) => panic!("expected InvalidConfiguration, got {other:?}"),
Ok(_) => panic!("build must reject a trusted issuer with an empty audience"),
}
}
#[test]
fn build_rejects_trusted_issuer_with_empty_jwks_url() {
let jwt = HttpJwtConfig {
trusted_issuers: Some(vec![TrustedIssuerConfig {
issuer: "https://external.example".to_string(),
audience: "iggy".to_string(),
jwks_url: String::new(),
username: "service".to_string(),
}]),
..HttpJwtConfig::default()
};
match JwtManager::build(&jwt, None) {
Err(IggyError::InvalidConfiguration) => {}
Err(other) => panic!("expected InvalidConfiguration, got {other:?}"),
Ok(_) => panic!("build must reject a trusted issuer with an empty jwks_url"),
}
}
#[test]
fn normalize_issuer_url_lowercases_scheme_and_host_preserving_path() {
assert_eq!(
normalize_issuer_url("HTTPS://Example.COM/PATH"),
"https://example.com/PATH"
);
}
#[test]
fn normalize_issuer_url_no_path() {
assert_eq!(
normalize_issuer_url("HTTPS://Example.COM"),
"https://example.com"
);
}
#[test]
fn normalize_issuer_url_no_scheme_trims_trailing_slash() {
assert_eq!(normalize_issuer_url("Example.COM/"), "example.com");
}
#[test]
fn normalize_issuer_url_already_normalized_is_stable() {
assert_eq!(
normalize_issuer_url("https://example.com/path"),
"https://example.com/path"
);
}
}