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:
[]
= "0.1"
Async-only core:
[]
= { = "0.1", = false, = ["rustls-tls"] }
Axum:
[]
= { = "0.1", = ["axum"] }
Actix Web:
[]
= { = "0.1", = ["actix-web"] }
Rocket:
[]
= { = "0.1", = ["rocket"] }
Warp:
[]
= { = "0.1", = ["warp"] }
Every integration:
[]
= { = "0.1", = ["full"] }
To use the platform TLS implementation instead of Rustls:
[]
= { = "0.1", = false, = ["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:
Then validate a consumer key and atomically deduct credits:
use Client;
async
REQKEY_ROOT_KEY and ClientBuilder::root_key are retained as backward-
compatible aliases. Never configure both project and root keys.
Direct analytics
# async
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 SyncClient;
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 ;
#
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
# use ;
#
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
# use MiddlewareConfig;
#
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 ;
use ;
# async
#
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 App;
use ;
#
Views access the decision through HttpMessage::extensions():
let decision = request.extensions.;
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 ;
#
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 Infallible;
use ;
use Filter;
# + Clone
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 ;
use ;
# async
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:
Development and testing
RUSTDOCFLAGS="-D warnings"
Tests 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.