reqkey 0.1.0

Official Rust SDK for ReqKey API key validation, credit metering, and analytics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
# 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](https://reqkey.com) ·
**Documentation:** [reqkey.com/docs](https://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](docs/PYTHON_COMPATIBILITY.md) 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:

```toml
[dependencies]
reqkey = "0.1"
```

Async-only core:

```toml
[dependencies]
reqkey = { version = "0.1", default-features = false, features = ["rustls-tls"] }
```

Axum:

```toml
[dependencies]
reqkey = { version = "0.1", features = ["axum"] }
```

Actix Web:

```toml
[dependencies]
reqkey = { version = "0.1", features = ["actix-web"] }
```

Rocket:

```toml
[dependencies]
reqkey = { version = "0.1", features = ["rocket"] }
```

Warp:

```toml
[dependencies]
reqkey = { version = "0.1", features = ["warp"] }
```

Every integration:

```toml
[dependencies]
reqkey = { version = "0.1", features = ["full"] }
```

To use the platform TLS implementation instead of Rustls:

```toml
[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:

```bash
export REQKEY_PROJECT_KEY="your_project_key"
```

Then validate a consumer key and atomically deduct credits:

```rust,no_run
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

```rust,no_run
# async fn example(client: &reqkey::Client) -> reqkey::Result<()> {
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?;
# Ok(())
# }
```

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:

```rust,no_run
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:

```rust,no_run
use reqkey::{Client, middleware::{
    FailureMode, KeyLocation, KeyScheme, Middleware, MiddlewareConfig, Mode,
}};

# fn build() -> reqkey::Result<Middleware> {
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);
# Ok(middleware)
# }
```

### 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

```rust,no_run
# use reqkey::middleware::{KeyLocation, KeyScheme, MiddlewareConfig};
# fn example() -> reqkey::Result<()> {
// 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()?;
# Ok(())
# }
```

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

```rust,no_run
# use reqkey::middleware::MiddlewareConfig;
# fn example() -> reqkey::Result<()> {
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()?;
# let _ = config;
# Ok(())
# }
```

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:

```rust,ignore
use axum::{extract::Extension, routing::post, Router};
use reqkey::{
    axum::ReqKeyLayer,
    middleware::{Middleware, MiddlewareConfig},
    Client, VerificationResult,
};

# async fn create_payment(Extension(decision): Extension<VerificationResult>) -> String {
#     format!("remaining={:?}", decision.credits_remaining)
# }
# fn app() -> reqkey::Result<Router> {
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);
# Ok(app)
# }
```

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

```rust,ignore
use actix_web::App;
use reqkey::{
    actix_web::ReqKeyMiddleware,
    middleware::{Middleware, MiddlewareConfig},
    Client,
};

# fn app() -> reqkey::Result<()> {
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));
# let _ = app;
# Ok(())
# }
```

Views access the decision through `HttpMessage::extensions()`:

```rust,ignore
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:

```rust,ignore
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))
}

# fn app() -> rocket::Rocket<rocket::Build> {
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:

```rust,ignore
use std::convert::Infallible;
use reqkey::{
    warp::{recover, ReqKeyFilter, WarpRequest},
    middleware::{Middleware, MiddlewareConfig},
    Client,
};
use warp::Filter;

# fn routes() -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {
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`.

```rust,no_run
use http::{HeaderMap, Method};
use reqkey::middleware::{
    AuthorizationOutcome, Middleware, RequestContext, ResponseContext,
};

# async fn handle(engine: Middleware, headers: HeaderMap) {
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:

- `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](https://github.com/Req-Key/reqkey-rust/tree/main/examples):

```bash
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

```bash
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](https://github.com/Req-Key/reqkey-rust/blob/main/LICENSE).