Expand description
§ReqKey Rust SDK
The official Rust SDK for ReqKey API key validation, credit metering, consumer rate limits, and correlated API traffic analytics.
The crate has one shared async core, a blocking client for synchronous applications, and optional integrations for Axum, Actix Web, Rocket, and Warp. Framework features are disabled unless selected, so the core client does not pull a web framework into your dependency graph.
Website: reqkey.com · Documentation: reqkey.com/docs
§Status
This crate starts at 0.1.0 and is prepared for its first crates.io release.
Its request contract and middleware behavior are based on ReqKey Python SDK
0.2.1. See Python compatibility for the
feature-by-feature comparison and intentional Rust differences.
§Supported integrations
| Application | Cargo feature | Integration |
|---|---|---|
| Tokio, Hyper, custom HTTP stacks | core/default | Client and shared middleware::Middleware |
| Synchronous scripts/workers | blocking (default) | SyncClient |
| Axum 0.8 | axum | Tower ReqKeyLayer |
| Actix Web 4 | actix-web | ReqKeyMiddleware transform |
| Rocket 0.5 | rocket | ReqKeyGuard + ReqKeyFairing |
| Warp 0.4 | warp | ReqKeyFilter + WarpRequest::record |
All network I/O uses Reqwest. Async operations run on Tokio, as do the supported async web frameworks.
§Installation
The default build uses Rustls and includes both async and blocking clients:
[dependencies]
reqkey = "0.1"Async-only core:
[dependencies]
reqkey = { version = "0.1", default-features = false, features = ["rustls-tls"] }Axum:
[dependencies]
reqkey = { version = "0.1", features = ["axum"] }Actix Web:
[dependencies]
reqkey = { version = "0.1", features = ["actix-web"] }Rocket:
[dependencies]
reqkey = { version = "0.1", features = ["rocket"] }Warp:
[dependencies]
reqkey = { version = "0.1", features = ["warp"] }Every integration:
[dependencies]
reqkey = { version = "0.1", features = ["full"] }To use the platform TLS implementation instead of Rustls:
[dependencies]
reqkey = { version = "0.1", default-features = false, features = ["native-tls"] }The minimum supported Rust version is 1.88. This matches the current Actix Web 4 line; core-only users also receive the same declared MSRV.
§Direct async client
Set the server-side project credential:
export REQKEY_PROJECT_KEY="your_project_key"Then validate a consumer key and atomically deduct credits:
use reqkey::Client;
#[tokio::main]
async fn main() -> reqkey::Result<()> {
let client = Client::from_env()?;
let decision = client
.verify("consumer_key_...")
.api_id("api_payments")
.credits(2)
.resource("/payments")
.send()
.await?;
if decision.allowed() {
println!("remaining: {:?}", decision.credits_remaining);
}
Ok(())
}REQKEY_ROOT_KEY and ClientBuilder::root_key are retained as backward-
compatible aliases. Never configure both project and root keys.
§Direct analytics
use reqkey::IngestEvent;
let event = IngestEvent::builder()
.request_id("request_from_validation")
.api_id("api_payments")
.method("POST")
.endpoint("/payments")
.path("/payments")
.status_code(201)
.latency_ms(18)
.api_key("consumer_key_...")
.consumer_name("Acme")
.build()?;
client.ingest(&event).await?;At least one of request_id or api_id is required. Request and response
bodies are limited to 1,000 Unicode characters. The builder also supports:
client_ip,user_agent, anduser_idconsumer_name,api_key, andconsumer_id- query parameters and filtered request/response headers
- request and response bodies
- an ISO-8601 timestamp
§Blocking client
The default blocking feature provides the same request contract without an
async runtime:
use reqkey::SyncClient;
fn verify() -> reqkey::Result<()> {
let client = SyncClient::from_env()?;
let decision = client
.verify("consumer_key_...")
.api_id("api_payments")
.credits(1)
.send()?;
println!("allowed: {}", decision.allowed());
Ok(())
}Do not call SyncClient on an async executor thread. Use Client, or move
blocking work to tokio::task::spawn_blocking.
§Shared middleware configuration
Every framework adapter uses the same engine and builder:
use reqkey::{Client, middleware::{
FailureMode, KeyLocation, KeyScheme, Middleware, MiddlewareConfig, Mode,
}};
let client = Client::from_env()?;
let config = MiddlewareConfig::builder("api_payments")
.mode(Mode::Both)
.enabled(true)
.key_location(KeyLocation::header("X-StartupName-Key"))
.key_scheme(KeyScheme::Raw)
.credit_cost(1)
.exclude_path("/health")
.exclude_path("/docs/*")
.failure_mode(FailureMode::Closed)
.build()?;
let middleware = Middleware::new(client, config);§Request lifecycle
In Mode::Both, the engine:
- bypasses configured methods and exact/prefix-excluded paths;
- extracts the key and calls
/key/validatewith API, credits, and resource; - awaits
/ingestbefore returning a 401/402/403/429 denial; - exposes a successful
VerificationResultto the endpoint; - runs the endpoint;
- awaits correlated
/ingestwith response status and selected metadata; - releases the completed response.
Ingestion is intentionally inside the request lifecycle. The SDK does not start a process-local background task that can disappear during shutdown.
§Modes
Mode::Validate: validate and charge only; never ingest.Mode::Ingest: never require or validate a consumer key; record by API ID.Mode::Both: validate, charge, and ingest a correlated event.
Denied traffic is recorded by default only in Both. Disable this with
ingest_denied_requests(false).
§Key extraction
// Recommended custom header.
let _ = MiddlewareConfig::builder("api")
.key_location(KeyLocation::header("X-StartupName-Key"))
.build()?;
// Authorization: Bearer <key>.
let _ = MiddlewareConfig::builder("api")
.key_location(KeyLocation::header("Authorization"))
.key_scheme(KeyScheme::Bearer)
.build()?;
// Compatibility options. Raw values only.
let _ = MiddlewareConfig::builder("api")
.key_location(KeyLocation::query("api_key"))
.build()?;
let _ = MiddlewareConfig::builder("api")
.key_location(KeyLocation::cookie("startup_key"))
.build()?;Query keys are supported for compatibility but are discouraged because URLs
are commonly retained in browser, proxy, and access logs. When query capture
is enabled, the SDK removes the configured query key from both path and
queryParams while still sending it in the dedicated apiKey identity field.
For another trusted source, use consumer_key_resolver. Resolvers receive a
framework-neutral RequestContext, so configuration is portable between
adapters.
§Dynamic credit costs and route selection
let config = MiddlewareConfig::builder("api_payments")
.credit_cost_resolver(|request| {
Ok(if request.method == http::Method::POST && request.path == "/images" {
5
} else {
1
})
})
.should_protect(|request| request.path.starts_with("/api/"))
.path_resolver(|request| Ok(request.path.clone()))
.build()?;Rust resolvers are synchronous because they inspect already-extracted request metadata and should not perform I/O. Put application I/O in the endpoint. This avoids boxed async callbacks in the hot middleware path.
§Axum
The Axum adapter is a native Tower layer. Add it to a router, route group, or individual route:
use axum::{extract::Extension, routing::post, Router};
use reqkey::{
axum::ReqKeyLayer,
middleware::{Middleware, MiddlewareConfig},
Client, VerificationResult,
};
let client = Client::from_env()?;
let config = MiddlewareConfig::builder("api_payments")
.exclude_path("/health")
.build()?;
let layer = ReqKeyLayer::new(Middleware::new(client, config));
let app = Router::new()
.route("/payments", post(create_payment))
.layer(layer);Handlers extract Extension<VerificationResult> after successful validation.
In fail-open mode they can instead/also extract
Extension<reqkey::middleware::ReqKeyFailure>.
Axum safely captures a textual response body only when its exact size is known, it is no larger than 4,004 bytes, and it is not compressed. The event still has status, headers, and latency when capture is skipped.
§Actix Web
use actix_web::App;
use reqkey::{
actix_web::ReqKeyMiddleware,
middleware::{Middleware, MiddlewareConfig},
Client,
};
let client = Client::from_env()?;
let config = MiddlewareConfig::builder("api_payments").build()?;
let middleware = Middleware::new(client, config);
let app = App::new().wrap(ReqKeyMiddleware::new(middleware));Views access the decision through HttpMessage::extensions():
let decision = request.extensions().get::<VerificationResult>();The Actix transform records status, filtered headers, latency, validation
state, and identity. It deliberately does not consume generic/streaming
MessageBody values for response-body capture.
§Rocket
Rocket request fairings cannot short-circuit routing, so protected routes use an idiomatic request guard. A response fairing adds headers and analytics:
use reqkey::{
rocket::{default_catchers, ReqKeyFairing, ReqKeyGuard},
middleware::{Middleware, MiddlewareConfig},
Client,
};
#[rocket::post("/payments")]
fn payment(reqkey: ReqKeyGuard) -> String {
format!("remaining={:?}", reqkey.decision()
.and_then(|decision| decision.credits_remaining))
}
let client = Client::from_env().expect("REQKEY_PROJECT_KEY");
let config = MiddlewareConfig::builder("api_payments").build().unwrap();
rocket::build()
.attach(ReqKeyFairing::new(Middleware::new(client, config)))
.register("/api", default_catchers())
.mount("/api", rocket::routes![payment])Registering default_catchers() preserves ReqKey’s JSON error body, custom
message, status, and Retry-After. Register it only on the protected mount
scope if other routes have their own 401/402/403/429/503 catchers. Rocket
response bodies are not consumed for analytics.
§Warp
Warp has composable filters rather than an after-response middleware hook. The
ReqKey filter returns a handle; wrap the reply with record to add headers and
await analytics:
use std::convert::Infallible;
use reqkey::{
warp::{recover, ReqKeyFilter, WarpRequest},
middleware::{Middleware, MiddlewareConfig},
Client,
};
use warp::Filter;
let client = Client::from_env().expect("REQKEY_PROJECT_KEY");
let config = MiddlewareConfig::builder("api_payments").build().unwrap();
let reqkey = ReqKeyFilter::new(Middleware::new(client, config));
warp::path("payments")
.and(reqkey.filter())
.and_then(|guard: WarpRequest| async move {
Ok::<_, Infallible>(guard.record("created").await)
})
.recover(recover)If a handler omits WarpRequest::record, validation still occurs, but response
analytics and ReqKey response headers do not. This explicit wrapper is the
closest reliable equivalent to post-response middleware in Warp. Response
bodies are not inspected.
§Plain HTTP and custom frameworks
Use Client directly when only key validation is needed. To reuse the complete
middleware policy with Hyper or another stack, translate its types into
RequestContext, call Middleware::authorize, run the endpoint only for
AuthorizationOutcome::Authorized/Bypass, then call Middleware::record
with ResponseContext.
use http::{HeaderMap, Method};
use reqkey::middleware::{
AuthorizationOutcome, Middleware, RequestContext, ResponseContext,
};
let request = RequestContext::new(Method::GET, "/reports")
.with_query("page=2")
.with_headers(headers)
.with_client_ip("203.0.113.4");
match engine.authorize(request).await {
AuthorizationOutcome::Bypass => { /* run normally */ }
AuthorizationOutcome::Denied(denial) => {
// Return denial.status_code, denial.headers(), and denial.json_body().
}
AuthorizationOutcome::Authorized(authorized) => {
// Run the handler, then:
engine.record(authorized, ResponseContext::new(200)).await;
}
}§Configuration reference
| Builder option | Default | Purpose |
|---|---|---|
MiddlewareConfig::builder(api_id) | required | ReqKey API protected/observed. |
mode | Both | Validate, Ingest, or correlated Both. |
enabled | true | Bypass all ReqKey work when false. |
key_location | Header("X-API-Key") | Header, query parameter, or cookie. |
key_scheme | Raw | Raw or Bearer syntax; Bearer is header-only. |
consumer_key_resolver | — | Custom extraction from RequestContext. |
credit_cost | 1 | Static non-negative (u64) usage cost. |
credit_cost_resolver | — | Per-request cost callback. |
exclude_path | empty | Exact path or trailing-* prefix pattern. |
skip_methods | OPTIONS | Methods bypassing validation and analytics. |
should_protect | — | Additional request selection predicate. |
request_id_resolver | — | Correlation for ingest-only mode. |
path_resolver | request path | Normalized endpoint/resource. |
consumer_name_resolver | — | Optional analytics display name. |
client_ip_resolver | framework peer | Trusted proxy override. |
on_error | tracing only | Safe validation/ingestion failure callback. |
ingest_denied_requests | true | Record denials in Both. |
failure_mode | Closed | Return 503 or continue when ReqKey fails. |
error_message | built in | Override one stable denial message. |
capture_query_params | false | Capture safe query values and path query. |
capture_request_headers | false | Capture filtered request headers. |
capture_response_headers | false | Capture filtered response headers. |
capture_request_body | false | Plain/custom integrations only. |
capture_response_body | false | Adapter-dependent safe textual capture. |
capture_client_ip | false | Capture peer/resolved IP. |
capture_user_agent | true | Capture user agent. |
exclude_header | sensitive defaults | Add a case-insensitive redaction. |
Client settings use Client::builder() or SyncClient::builder():
| Client option | Default | Purpose |
|---|---|---|
project_key | required | Server-side Bearer credential. |
root_key | — | Backward-compatible alias; mutually exclusive. |
base_url | https://api.reqkey.com | ReqKey origin/private deployment. |
timeout | 2 seconds | Per validation or ingestion operation. |
http_client | SDK-created | Inject a configured Reqwest client. |
§Analytics privacy
Default middleware events include API ID, method, normalized endpoint, status,
latency, user agent, extracted consumer key in the dedicated apiKey identity
field, and the validation request ID when available.
Query parameters, headers, bodies, and client IPs are opt-in. The following headers are always filtered case-insensitively:
AuthorizationCookieandSet-CookieProxy-AuthorizationX-API-Key- the configured consumer-key header/location name
- every name added with
exclude_header
Framework middleware never consumes incoming request bodies because doing so
can interfere with application extractors and streaming. A custom/plain
integration may explicitly supply a body with RequestContext::with_request_body.
Client-IP capture prefers the framework peer address. Only when it is absent
does the shared engine inspect common proxy headers. Use client_ip_resolver
when a trusted proxy overwrites a specific header; otherwise forwarding values
can be spoofed by callers.
§Response state and headers
Successful validation exposes VerificationResult through each framework’s
native request state:
- Axum:
Extension<VerificationResult> - Actix Web:
request.extensions().get::<VerificationResult>() - Rocket:
ReqKeyGuard::decision() - Warp:
WarpRequest::decision()
Fail-open errors use the equivalent ReqKeyFailure state. Responses include,
when available:
X-ReqKey-Request-IDX-ReqKey-Credits-LimitX-ReqKey-Credits-RemainingX-ReqKey-Validation-Time-Ms
Cross-origin browser JavaScript needs these names in its CORS expose_headers
configuration if it must read them.
§Errors and availability
Direct clients return reqkey::Error:
Configuration: invalid local configuration/input;Timeout: the configured operation timeout elapsed;Transport: DNS, connection, or protocol transport failure;Authentication: ReqKey returned 401 for the project credential;Api: non-JSON, unexpected shape/status, or a non-decision API response.
HTTP 200/402/403/429 validation responses are normalized into
VerificationResult; access denial is data, not a transport error.
Middleware fails closed by default and returns 503 when ReqKey cannot make a
decision. FailureMode::Open runs the endpoint but never turns an explicit
invalid, exhausted, forbidden, or rate-limited decision into an allow.
Validation is not automatically retried because it can deduct credits. Safe
retries require server-side idempotency. Ingestion failures never replace the
application response; they are emitted with tracing and delivered to
on_error if configured.
The callback receives MiddlewareErrorEvent containing only operation, error,
method, path, request ID, and status. It intentionally excludes keys,
credentials, headers, query parameters, and bodies. Panics in the callback are
caught and logged.
§Examples
Runnable examples are under the examples directory:
cargo run --example plain_async
cargo run --example plain_blocking
cargo run --features axum --example axum
cargo run --features actix-web --example actix_web
cargo run --features rocket --example rocket
cargo run --features warp --example warp§Development and testing
rustup component add rustfmt clippy
cargo fmt --all -- --check
cargo check --no-default-features
cargo test
cargo test --all-features
cargo clippy --all-targets --all-features -- -D warnings
RUSTDOCFLAGS="-D warnings" cargo doc --all-features --no-deps
cargo package --allow-dirtyTests use a local mock HTTP server and never require live ReqKey credentials. The all-features suite covers the core client, shared policy, Axum layer, Actix transform, Rocket guard/fairing, and Warp filter/reply wrapper.
§Publishing to crates.io
The crate name, metadata, source include list, license, README, feature flags,
MSRV, and docs.rs configuration are already present in Cargo.toml. Before a
release:
- Confirm the
reqkeyname and your publisher access withcargo searchand the crates.io owner settings. - Update
versioninCargo.tomland add the release toCHANGELOG.md. - Run every development command above from a clean checkout.
- Inspect
cargo package --listand the generated.cratearchive. - Run
cargo publish --dry-run. - Authenticate with
cargo login, then runcargo publish. - Tag the same version (for example
v0.1.0) and publish GitHub release notes.
Do not publish with placeholder repository URLs or before the public
Req-Key/reqkey-rust repository exists. crates.io releases are immutable; a
mistake requires yanking and releasing a new version.
§License
MIT. See the license file.
Modules§
- actix_
web actix-web - Actix Web 4 middleware integration.
- axum
axum - Axum 0.8 middleware integration.
- middleware
- Framework-independent request validation and analytics policy.
- rocket
rocket - Rocket 0.5 request-guard and response-fairing integration.
- warp
warp - Warp 0.4 composable filter integration.
Structs§
- Client
- Asynchronous ReqKey API client.
- Client
Builder - Builder for the asynchronous
Client. - Ingest
Event - Request/response analytics event accepted by
/ingest. - Ingest
Event Builder - Builder for
IngestEvent. - Sync
Client blocking - Synchronous ReqKey client for non-async applications.
- Sync
Client Builder blocking - Builder for the synchronous
SyncClient. - Sync
Verify blocking - Fluent validation request produced by
SyncClient::verify. - Verification
Result - The normalized result of
/key/validate. - Verify
- Fluent validation request produced by
Client::verify.
Enums§
- Error
- Errors returned by the ReqKey SDK.
- Operation
- A ReqKey operation, used in transport errors and middleware notifications.
- Verification
Reason - Stable SDK-level categories for a key-validation decision.
Constants§
- VERSION
- Current SDK version sent in the ReqKey user agent.
Type Aliases§
- Result
- Result alias used throughout the SDK.