Skip to main content

Crate reqkey

Crate reqkey 

Source
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

ApplicationCargo featureIntegration
Tokio, Hyper, custom HTTP stackscore/defaultClient and shared middleware::Middleware
Synchronous scripts/workersblocking (default)SyncClient
Axum 0.8axumTower ReqKeyLayer
Actix Web 4actix-webReqKeyMiddleware transform
Rocket 0.5rocketReqKeyGuard + ReqKeyFairing
Warp 0.4warpReqKeyFilter + 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, and user_id
  • consumer_name, api_key, and consumer_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:

  1. bypasses configured methods and exact/prefix-excluded paths;
  2. extracts the key and calls /key/validate with API, credits, and resource;
  3. awaits /ingest before returning a 401/402/403/429 denial;
  4. exposes a successful VerificationResult to the endpoint;
  5. runs the endpoint;
  6. awaits correlated /ingest with response status and selected metadata;
  7. 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 optionDefaultPurpose
MiddlewareConfig::builder(api_id)requiredReqKey API protected/observed.
modeBothValidate, Ingest, or correlated Both.
enabledtrueBypass all ReqKey work when false.
key_locationHeader("X-API-Key")Header, query parameter, or cookie.
key_schemeRawRaw or Bearer syntax; Bearer is header-only.
consumer_key_resolverCustom extraction from RequestContext.
credit_cost1Static non-negative (u64) usage cost.
credit_cost_resolverPer-request cost callback.
exclude_pathemptyExact path or trailing-* prefix pattern.
skip_methodsOPTIONSMethods bypassing validation and analytics.
should_protectAdditional request selection predicate.
request_id_resolverCorrelation for ingest-only mode.
path_resolverrequest pathNormalized endpoint/resource.
consumer_name_resolverOptional analytics display name.
client_ip_resolverframework peerTrusted proxy override.
on_errortracing onlySafe validation/ingestion failure callback.
ingest_denied_requeststrueRecord denials in Both.
failure_modeClosedReturn 503 or continue when ReqKey fails.
error_messagebuilt inOverride one stable denial message.
capture_query_paramsfalseCapture safe query values and path query.
capture_request_headersfalseCapture filtered request headers.
capture_response_headersfalseCapture filtered response headers.
capture_request_bodyfalsePlain/custom integrations only.
capture_response_bodyfalseAdapter-dependent safe textual capture.
capture_client_ipfalseCapture peer/resolved IP.
capture_user_agenttrueCapture user agent.
exclude_headersensitive defaultsAdd a case-insensitive redaction.

Client settings use Client::builder() or SyncClient::builder():

Client optionDefaultPurpose
project_keyrequiredServer-side Bearer credential.
root_keyBackward-compatible alias; mutually exclusive.
base_urlhttps://api.reqkey.comReqKey origin/private deployment.
timeout2 secondsPer validation or ingestion operation.
http_clientSDK-createdInject 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:

  • Authorization
  • Cookie and Set-Cookie
  • Proxy-Authorization
  • X-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-ID
  • X-ReqKey-Credits-Limit
  • X-ReqKey-Credits-Remaining
  • X-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-dirty

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:

  1. Confirm the reqkey name and your publisher access with cargo search and the crates.io owner settings.
  2. Update version in Cargo.toml and add the release to CHANGELOG.md.
  3. Run every development command above from a clean checkout.
  4. Inspect cargo package --list and the generated .crate archive.
  5. Run cargo publish --dry-run.
  6. Authenticate with cargo login, then run cargo publish.
  7. 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_webactix-web
Actix Web 4 middleware integration.
axumaxum
Axum 0.8 middleware integration.
middleware
Framework-independent request validation and analytics policy.
rocketrocket
Rocket 0.5 request-guard and response-fairing integration.
warpwarp
Warp 0.4 composable filter integration.

Structs§

Client
Asynchronous ReqKey API client.
ClientBuilder
Builder for the asynchronous Client.
IngestEvent
Request/response analytics event accepted by /ingest.
IngestEventBuilder
Builder for IngestEvent.
SyncClientblocking
Synchronous ReqKey client for non-async applications.
SyncClientBuilderblocking
Builder for the synchronous SyncClient.
SyncVerifyblocking
Fluent validation request produced by SyncClient::verify.
VerificationResult
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.
VerificationReason
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.