jwtiny
Minimal, type-safe JSON Web Token (JWT) validation for Rust.
jwtiny validates JWT tokens through a builder-pattern API that attempts to enforce correct validation order at compile time. Initially created to explore miniserde support for common JWT libraries, this ended up as a full library.
Warning: This is a learning project to get more familiar with Rust. If you spot any flaws, let me know. If you can make any use of this, let me know as well! π
Overview
JWTs (JSON Web Tokens) encode claims as JSON objects secured by digital signatures or message authentication codes. Validating them requires parsing Base64URL-encoded segments, verifying signatures with cryptographic keys, and checking temporal claims like expiration.
Common pitfalls include algorithm confusion attacks (accepting asymmetric algorithms when only symmetric keys are trusted), server-side request forgery (SSRF) via untrusted issuer URLs, and timing vulnerabilities in signature comparison.
jwtiny attempts to address these through a type-safe state machine: parsing yields a ParsedToken, issuer validation produces a TrustedToken, signature verification creates a VerifiedToken, and claims validation returns the final Token. Each stage must complete before the next begins, enforced by Rust's type system. The builder pattern configures all steps upfront, then executes them atomicallyβaiming to prevent partial validation and ensure cryptographic keys are only used after issuer checks complete.
Features
Per default, only hmac support is enabled. Everything else needs to be opt-in enabled as features:
| Feature | Feature | Description |
|---|---|---|
hmac |
always enabled | HMAC algorithms (HS256, HS384, HS512) |
rsa |
β | RSA algorithms (RS256, RS384, RS512) |
ecdsa |
β | ECDSA algorithms (ES256, ES384) |
aws-lc-rs |
β | Use aws-lc-rs backend instead of ring for RSA/ECDSA |
all-algorithms |
β | Enable all asymmetric algorithms (RSA + ECDSA) |
remote |
β | Remote JWKS over HTTPS (rustls). Provide an HTTP client. |
Quick Start
Add jwtiny to your Cargo.toml:
[]
= "0.0.0"
Note: Current version is
0.0.0(pre-release). Update to latest published version when available.
For asymmetric algorithms (RSA, ECDSA), enable features:
= { = "0.0.0", = ["rsa", "ecdsa"] }
Minimal example validating an HMAC-signed token:
use *;
let token = new
.ensure_issuer
.verify_signature
.validate_token
.run?;
println!;
Examples
HMAC Validation
For tokens signed with symmetric keys (HS256, HS384, HS512):
use *;
let token = new
.danger_skip_issuer_validation // Only if providing key directly
.verify_signature
.validate_token
.run?;
RSA Public Key Validation
Requires the rsa feature:
use *;
let token = new
.ensure_issuer
.verify_signature
.validate_token
.run?;
ECDSA Public Key Validation
Requires the ecdsa feature. Supports P-256 and P-384 curves:
use *;
let token = new
.ensure_issuer
.verify_signature
.validate_token
.run?;
JWKS Flow (Remote Key Fetching)
Requires the remote feature. Fetch public keys from a JWKS endpoint:
use *;
use HttpClient;
// Create an HTTP client function pointer
let http_client: HttpClient = ;
// Validate with automatic key resolution from JWKS
let token = new
.ensure_issuer
.verify_signature
.validate_token
.run_async
.await?;
Security note: Always validate the issuer before enabling JWKS fetching. Without issuer validation, an attacker can craft a token with an arbitrary iss claim, causing your application to fetch keys from attacker-controlled URLsβa classic SSRF vulnerability.
API Overview
The validation flow proceeds through distinct stages, each producing a new type:
// Stage 1: Parse the token string
let parsed = from_string?;
// Stage 2: Build the validation pipeline
let token = new
.ensure_issuer // Required: validate issuer (or use .danger_skip_issuer_validation())
.verify_signature // Required: verify signature
.validate_token // Optional: defaults to ValidationConfig::default() if omitted
.run?; // Execute all stages atomically
// Stage 3: Access validated claims
token.subject; // Option<&str>
token.issuer; // Option<&str>
token.claims; // &Claims
Issuer Validation
Always validate issuers when using JWKS to prevent SSRF attacks:
// β
Correct: Allowlist trusted issuers
.ensure_issuer
// For same-service tokens, explicitly skip
.danger_skip_issuer_validation
Signature Verification
Choose verification based on the algorithm family:
HMAC (symmetric keys) β always enabled:
with_secret_hs256
RSA (asymmetric keys) β requires rsa feature:
with_key
ECDSA (asymmetric keys) β requires ecdsa feature:
with_ecdsa_es256
Use algorithm-specific constructors (preferred) or pass an explicit AlgorithmPolicy.
Claims Validation
Configure temporal and claim-specific checks:
default
.require_audience // Validate `aud` claim
.max_age // Token must be < 1 hour old
.clock_skew // Allow 60s clock skew
.no_exp_validation // Skip expiration (dangerous)
.custom
Architecture
The library enforces a validation pipeline through type-level state transitions:
ParsedToken (parsed header and payload)
β .ensure_issuer()
βΌ
TrustedToken (issuer validated; internal type)
β .verify_signature()
βΌ
VerifiedToken (signature verified; internal type)
β .validate_token()
βΌ
ValidatedToken (claims validated; internal type)
β .run() / .run_async()
βΌ
Token (public API; safe to use)
Only the final Token type is exposed publicly. Intermediate types (TrustedToken, VerifiedToken, ValidatedToken) are internal, which helps prevent partial validation from escaping the builder.
Algorithm Confusion Prevention
Always restrict algorithms explicitly; an explicit policy is required. Prefer algorithm-specific constructors:
// β
Correct: Only allow the algorithm you trust
with_secret_hs256
// β Incorrect: missing explicit policy
// SignatureVerification::with_secret(b"secret")
SSRF Prevention
When using JWKS, validate issuers before fetching keys:
// β
Correct: Allowlist trusted issuers
.ensure_issuer
// β Incorrect: Attacker can make you fetch from any URL
.danger_skip_issuer_validation // Dangerous with JWKS!
"none" Algorithm Rejection
The "none" algorithm (unsigned tokens) is always rejected per RFC 8725:
from_string
// Returns: Error::NoneAlgorithmRejected
Timing Attack Protection
HMAC signature verification uses constant-time comparison via the constant_time_eq crate, which aims to mitigate timing-based key recovery attacks.
Cryptographic Backends
jwtiny supports two backends for RSA and ECDSA:
ring(default) β battle-tested cryptography libraryaws-lc-rsβ FIPS-validated AWS cryptography library
Select exactly one backend. The choice affects signature verification compatibility.
Using ring (default)
[]
= { = "0.0.0", = ["rsa", "ecdsa"] }
Using aws-lc-rs
[]
= { = "0.0.0", = ["rsa", "ecdsa", "aws-lc-rs"] }
Compatibility note: If you're verifying tokens signed by services using jsonwebtoken with the aws_lc_rs feature (e.g., jwkserve), use the aws-lc-rs feature to ensure compatibility.
Testing
jwtiny includes test coverage across algorithm families, edge cases, and integration scenarios.
Running Tests
# All features with default backend
# Specific algorithm features
# aws-lc-rs backend (for compatibility testing)
# Remote JWKS fetching
# Run specific test suite
Test Coverage
- Algorithm tests (
tests/algorithm_round_trips.rs): Round-trip signing and verification for HMAC, RSA, and ECDSA - Integration tests (
tests/jwkserve_integration.rs): End-to-end RS256 verification via JWKS (requires Docker) - Edge cases (
tests/edge_cases.rs): Token format validation, Base64URL edge cases, claims validation, algorithm confusion prevention - JWK support (
tests/jwk_support.rs): JWK metadata handling, key selection, RSA/ECDSA key extraction - JWT.io compatibility (
tests/jwtio_compatibility.rs): Verification of canonical JWT.io example tokens - Custom headers (
tests/custom_headers.rs): Header field preservation (kid,typ, custom fields), field order invariance, real-world header formats - Key formats (
tests/key_formats.rs): PKCS#8 DER, PKCS#1 DER, PEM format conversion, invalid/truncated key handling
Running Examples
License
MIT