actixutils

Reusable middleware, extractors, and framework-agnostic building blocks for Actix Web 4: JWT authentication, cookie sessions, rate limiting, idempotency, request coalescing, pagination, request IDs, per-request timeouts, trusted-proxy client-IP resolution, bitmask permission checks, timing-attack mitigation, and event-publishing context propagation.

This project is pre-1.0 and still changing. Ideas for features and optimizations are welcome.

This documents the crate as it exists in src/. For a short introduction and install instructions, start with the README.

Crate layout

The crate is split into three top-level modules, by whether an item depends on actix-web:

Module Contains
extractors Types implementing FromRequest: Jwt<T>, Session<T>, ReadSession<T>, Filters, ClientIp
middleware Types implementing Transform: the full middleware suite
locals Framework-agnostic pieces: claim structs, signing/validation traits, IdempotencyStore, ProxyConfig, task-local state

Plus a standalone pubkey module for serving an RSA public key (see below).

The most commonly used items are re-exported at the crate root:

ClientIp and every middleware type are not re-exported at the root; import them through actixutils::extractors and actixutils::middleware.

Feature flags

Flag Enables
jwt The Jwt<T> extractor, HS256Signer, RS256Signer/RS256Validator, and the identity/authority helper functions (pulls in jsonwebtoken)

jwt is not enabled by default. Everything else is available without a flag, including middleware::Auth<T> (it only needs some Validate<T> implementation), sessions, rate limiting, idempotency, coalescing, timeouts, client IP, pagination, request IDs, and Context/ReadContext.

ferrumec is a regular dependency, not an optional one. Its Store and EventStream traits appear in the public API, so applications that use sessions, rate limiting, or ReadContext should depend on ferrumec (0.5) directly.

Quick start

Requires the jwt feature.

use actix_web::{web, App, HttpResponse, HttpServer};
use actixutils::{HS256Signer, Identity, Jwt, Validate};
use std::sync::Arc;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let signer = Arc::new(HS256Signer::new(
        "my-app".to_string(),
        "super-secret-key".to_string(),
    ));

    HttpServer::new(move || {
        App::new()
            .app_data(signer.clone() as Arc<dyn Validate<Identity>>)
            .route("/protected", web::get().to(protected))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

async fn protected(auth: Jwt<Identity>) -> HttpResponse {
    HttpResponse::Ok().json(&auth.0)
}

The extractor looks up exactly Arc<dyn Validate<T>> in app data. Registering it with web::Data::from(...) stores a different type (Data<dyn Validate<T>>) that the extractor will not find, and every request would fail with 500.

JWT authentication

Two independent ways to require a valid JWT, sharing the same signer or validator:

Signers and validators (all feature jwt):

Validation requires the token’s aud claim to match the audience passed to the validator, and enforces exp.

Claim structs (locals):

middleware::{identity, authority} are Next-style functions for actix_web::middleware::from_fn. identity requires a valid Identity; authority(bit) requires a valid Authority whose role has that bit set (401 if the token is bad, 403 if the bit is missing).

pubkey::configure serves a PEM key at GET /.well-known/public-key.pem, read at call time from the validate.key environment variable. It panics if the variable is unset. The name contains a dot, which most shells will not let you export; set it with env 'validate.key=...' ./app or your process manager. This is handy for RS256 downstream services that fetch the issuer’s public key.

Stores

The crate ships no storage backends. Two trait families are involved:

Trait Defined in Used by
Store<K, V> ferrumec RateLimiter<T> (Store<T::Id, VecDeque<Instant>>), SessionMiddleware<T> and RequiredSession<T> (Store<Uuid, T>)
IdempotencyStore actixutils::locals Idempotency<S>

ferrumec::Store<K, V> is an #[async_trait] with four methods, get, set, delete and clear, each returning Result<_, Box<dyn Error>>. You implement it once per backend (in-memory, Redis, a database table) and reuse it. A HashMap behind a lock is enough for a single process.

IdempotencyStore is a separate, TTL-aware trait (acquire, get, complete, release) with its own associated Error type. It is not a Store.

Sessions

Cookie-based, server-side sessions are split across two modules:

The cookie set by SessionMiddleware has Path=/ and HttpOnly; there is no Secure or SameSite attribute.

Handlers that use Session<T> or ReadSession<T> get a 500 if no session middleware ran for the request.

Middleware suite

Middleware What it does
Auth<T> Validates a Bearer JWT (header or access_token cookie) and stores claims in request extensions
ResponseEqualizer Pads every response to a minimum duration (optionally plus random jitter), mitigating timing side-channels on auth/lookup endpoints
RateLimiter<T> Sliding-window per-identity rate limiting; keys on any extractor implementing locals::rate_limiter::GetId; backed by a caller-supplied ferrumec::Store
Idempotency<S> Caches responses by an Idempotency-Key header to prevent duplicate mutations on retried requests; pluggable IdempotencyStore
Singleflight<K, KeyFn> Request coalescing: concurrent requests that map to the same key share a single execution of the wrapped service
TimeoutMiddleware Fails a request with 504 Gateway Timeout if it exceeds a fixed duration
ClientIpMiddleware Resolves the real client IP from X-Forwarded-For, honouring a configured set of trusted proxy networks; exposed via the ClientIp extractor
PathParams Merges matched path parameters into Filters, overlaying them on the query string
RequestId / RequestIdStr Generates a UUIDv4 per request, records it in the tracing span, stores it in extensions, and returns it as X-Request-Id
Context / ReadContext<T> Builds a per-request event-publishing context from the request ID and an identity’s UUID
Pagination / PaginationMiddleware Parses ?page=&limit= into a task-local, readable anywhere via Pagination::get()
SessionMiddleware<T> / RequiredSession<T> Cookie-based server-side sessions (see above)
AttachLocal<T> / SetLocal Generic helper: extracts a T up front, then runs the rest of the request inside T::scope(...), the mechanism PaginationMiddleware-style task-locals are built on
identity / authority(bit) from_fn guards for a valid Identity / an Authority with a given permission bit (feature jwt)

Continue with the middleware overview, the tutorial, or the examples.

Two traits called GetId

Testing

middleware::test_session (compiled only under #[cfg(test)]) contains an in-memory ferrumec::Store<Uuid, T> and integration tests exercising Session<T> / SessionMiddleware end to end, which makes it a useful reference for writing your own store. middleware::test_coalesce holds the Singleflight tests.

Several rustdoc examples use the jwt feature, so run the full suite with:

cargo test --all-features

License

MIT (see Cargo.toml).