footing 0.6.2

Feature-gated foundations for Rust backend services
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
//! Top-level immutable HTTP configuration and settings materialization.

use std::{num::NonZeroUsize, time::Duration};

use axum::http::HeaderValue;
use serde::{Deserialize, Serialize};

use crate::{
    http::{
        IdempotencyConfig, IdempotencyRequestPolicy, SecurityHeadersConfig,
        trusted_proxy::ForwardedHeadersPolicy,
    },
    settings::{SettingsIssues, SettingsValidationError, field_path},
};

use super::{
    policy::{
        CorsPolicy, HttpMiddlewareConfig, HttpRateLimitConfig, HttpRequestPolicy,
        RequestBodyLimitPolicy, ResponseTimeout,
    },
    route_settings::HttpRequestPolicySettings,
    settings::{
        CorsSettings, ForwardedHeadersSettings, HttpIdempotencySettings, HttpRateLimitSettings,
        SecurityHeadersSettings,
    },
};

const DOCUMENTATION_CSP: &str = concat!(
    "default-src 'none'; script-src 'self'; connect-src 'self'; ",
    "style-src 'self' 'unsafe-inline'; img-src 'self' data:; ",
    "font-src 'self'; worker-src 'self' blob:; base-uri 'none'; ",
    "object-src 'none'; frame-ancestors 'none'",
);

impl HttpMiddlewareConfig {
    #[must_use]
    /// Creates the default stack configuration for JSON APIs.
    ///
    /// Enables request context, tracing, gzip compression, API security headers,
    /// a 30-second response timeout and a 2 MiB request body limit. Forwarded
    /// headers are untrusted; CORS, concurrency limiting, rate limiting and
    /// idempotency are disabled.
    /// Authentication and authorization hooks must be installed explicitly.
    ///
    /// This is also [`Self::default`]. Customize these defaults through
    /// [`HttpMiddlewareSettings`]; use [`Self::documentation`] for browser docs
    /// whose OAuth popups cannot use the API's strict opener policy.
    pub fn standard() -> Self {
        Self {
            request_context: true,
            forwarded_headers: ForwardedHeadersPolicy::never(),
            trace: true,
            cors: CorsPolicy::Disabled,
            security_headers: Some(SecurityHeadersConfig::api_defaults()),
            max_concurrent_requests: None,
            compression: true,
            rate_limit: None,
            idempotency: None,
            request_policy: HttpRequestPolicy::default(),
        }
    }

    #[must_use]
    /// Creates a stack with all optional middleware and body limits disabled.
    ///
    /// Use when the application supplies its own middleware or for focused
    /// tests. No request context, tracing, security headers, timeout, compression,
    /// CORS, concurrency limiting, rate limiting or idempotency is installed.
    /// Forwarded headers remain untrusted. Prefer [`Self::standard`] for ordinary
    /// API routes.
    pub fn minimal() -> Self {
        Self {
            request_context: false,
            forwarded_headers: ForwardedHeadersPolicy::never(),
            trace: false,
            cors: CorsPolicy::Disabled,
            security_headers: None,
            max_concurrent_requests: None,
            compression: false,
            rate_limit: None,
            idempotency: None,
            request_policy: HttpRequestPolicy::disabled(),
        }
    }

    /// Creates a stack configuration for locally hosted ReDoc and RapiDoc pages.
    ///
    /// Keeps [`Self::standard`]'s request handling, but omits COOP so popup OAuth
    /// can return to its opener. Its CSP allows same-origin scripts and requests,
    /// runtime styles, data images and Blob workers; inline scripts and framing
    /// remain blocked. Assets, API requests and OAuth token requests on other
    /// origins need a custom CSP via [`HttpMiddlewareSettings::documentation`].
    ///
    /// Apply this stack to the documentation router and [`Self::standard`] to
    /// the API router, then merge them. Outer middleware and reverse proxies must
    /// preserve these headers. Authentication remains application policy.
    #[must_use]
    pub fn documentation() -> Self {
        Self {
            security_headers: Some(
                SecurityHeadersConfig::api_defaults()
                    .with_cross_origin_opener_policy(None)
                    .with_content_security_policy(Some(HeaderValue::from_static(
                        DOCUMENTATION_CSP,
                    ))),
            ),
            ..Self::standard()
        }
    }

    #[must_use]
    /// Whether the stack attaches request IDs and [`crate::http::RequestContext`].
    pub const fn request_context_enabled(&self) -> bool {
        self.request_context
    }

    #[must_use]
    /// Whether any forwarded-header trust policy is configured.
    pub fn forwarded_headers_enabled(&self) -> bool {
        !self.forwarded_headers.is_disabled()
    }

    #[must_use]
    /// Returns the policy deciding which peers may supply client IP headers.
    pub const fn forwarded_headers_policy(&self) -> &ForwardedHeadersPolicy {
        &self.forwarded_headers
    }

    #[must_use]
    /// Whether HTTP request and response tracing is enabled.
    pub const fn trace_enabled(&self) -> bool {
        self.trace
    }

    #[must_use]
    /// Returns the cross-origin request policy; disabled by default.
    pub const fn cors(&self) -> &CorsPolicy {
        &self.cors
    }

    #[must_use]
    /// Returns the response security headers, or `None` when disabled.
    pub const fn security_headers(&self) -> Option<&SecurityHeadersConfig> {
        self.security_headers.as_ref()
    }

    #[must_use]
    /// Returns the default response timeout, or `None` when disabled.
    /// Matching route rules can override this deadline.
    /// Expiry returns a `503` [`crate::http::ApiProblem`] with code `response_timeout`
    /// and any existing request context identifiers. Streaming response bodies
    /// are not covered by this deadline.
    pub const fn timeout(&self) -> Option<Duration> {
        self.request_policy.default_timeout().duration()
    }

    /// Returns the maximum number of requests simultaneously producing responses.
    ///
    /// `None` disables the limit. A built stack and its clones share one process-local
    /// budget, including when applied to several routers. Streaming response bodies
    /// do not hold capacity. See [`HttpMiddlewareSettings::max_concurrent_requests`].
    #[must_use]
    pub const fn max_concurrent_requests(&self) -> Option<NonZeroUsize> {
        self.max_concurrent_requests
    }

    #[must_use]
    /// Returns the default request body limit from the request policy.
    pub const fn request_body_limit(&self) -> Option<usize> {
        self.request_policy
            .default_request_body_limit()
            .as_optional()
    }

    #[must_use]
    /// Returns the request body limit policy.
    pub const fn request_body_limit_policy(&self) -> RequestBodyLimitPolicy {
        self.request_policy.default_request_body_limit()
    }

    #[must_use]
    /// Whether eligible responses may be gzip-compressed.
    /// See [`HttpMiddlewareSettings::compression`] for response exclusions.
    pub const fn compression_enabled(&self) -> bool {
        self.compression
    }

    #[must_use]
    /// Returns the global rate-limit configuration, or `None` when disabled.
    pub const fn rate_limit(&self) -> Option<&HttpRateLimitConfig> {
        self.rate_limit.as_ref()
    }

    #[must_use]
    /// Returns the idempotency configuration, or `None` when disabled.
    pub const fn idempotency(&self) -> Option<&IdempotencyConfig> {
        self.idempotency.as_ref()
    }

    #[must_use]
    /// Returns default and route-specific timeout, body-limit, rate-limit and idempotency policies.
    pub const fn request_policy(&self) -> &HttpRequestPolicy {
        &self.request_policy
    }
}

impl Default for HttpMiddlewareConfig {
    fn default() -> Self {
        Self::standard()
    }
}

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for HTTP middleware.
///
/// [`Self::new`] and [`Self::default`] start with [`HttpMiddlewareConfig::standard`]
/// behavior. [`Self::documentation`] starts with the browser documentation preset.
/// Missing serialized fields use API defaults; unknown fields are rejected.
/// Modify settings, call [`Self::build`] to validate them, then supply runtime
/// stores and authentication hooks through [`super::HttpMiddlewareStack::builder`].
pub struct HttpMiddlewareSettings {
    /// Whether request identifiers and context are attached to requests.
    pub request_context: bool,
    /// Whether HTTP tracing middleware is enabled.
    pub trace: bool,
    /// Forwarded-header trust configuration.
    pub forwarded_headers: ForwardedHeadersSettings,
    /// Cross-origin resource sharing configuration.
    pub cors: CorsSettings,
    /// Security response header configuration.
    pub security_headers: SecurityHeadersSettings,
    /// Optional process-local limit on requests simultaneously producing responses.
    ///
    /// Disabled by default. Must be between `1` and [`tokio::sync::Semaphore::MAX_PERMITS`].
    /// The assembled stack and its clones share capacity across all routers to which
    /// they are applied; independently built stacks have separate budgets.
    ///
    /// At capacity, a request immediately receives a `503` [`crate::http::ApiProblem`]
    /// with code `request_overloaded` and any existing request context. Requests never
    /// queue. Admission precedes authentication, authorization, rate limiting and
    /// idempotency reservation. Capacity is released when a response is produced or
    /// processing is cancelled, including on timeout; streaming response bodies and
    /// detached work are outside the budget.
    pub max_concurrent_requests: Option<usize>,
    /// Whether eligible responses may be gzip-compressed.
    ///
    /// Responses with a strong `ETag` retain their original bytes and validator.
    /// This preserves application `If-Match` and `If-Range` semantics: a strong
    /// validator cannot be reused for compressed bytes or silently weakened.
    /// Use a weak `ETag` when automatic compression is desired. Existing
    /// `Content-Encoding` values and their response bodies are preserved.
    /// A response with a `Cache-Control: no-transform` directive also retains
    /// its original bytes. Directives are case-insensitive and all
    /// `Cache-Control` fields are checked.
    /// HEAD responses retain their metadata when their body size hint has a
    /// zero lower bound, including header-only responses and unknown-size
    /// streams. HEAD responses with a nonzero body lower bound remain eligible.
    pub compression: bool,
    /// Global rate-limit configuration.
    pub rate_limit: HttpRateLimitSettings,
    /// Global idempotency configuration.
    pub idempotency: HttpIdempotencySettings,
    /// Default and route-specific request policies.
    pub request_policy: HttpRequestPolicySettings,
}

impl Default for HttpMiddlewareSettings {
    fn default() -> Self {
        Self {
            request_context: true,
            trace: true,
            forwarded_headers: ForwardedHeadersSettings::default(),
            cors: CorsSettings::default(),
            security_headers: SecurityHeadersSettings::default(),
            max_concurrent_requests: None,
            compression: true,
            rate_limit: HttpRateLimitSettings::default(),
            idempotency: HttpIdempotencySettings::default(),
            request_policy: HttpRequestPolicySettings::default(),
        }
    }
}

impl HttpMiddlewareSettings {
    #[must_use]
    /// Starts with the API defaults described by [`HttpMiddlewareConfig::standard`].
    /// Call [`Self::build`] after applying overrides.
    pub fn new() -> Self {
        Self::default()
    }

    /// Starts with the same defaults as [`HttpMiddlewareConfig::documentation`].
    ///
    /// The security-header settings remain editable. For example, extend
    /// `security_headers.content_security_policy` with trusted API or OAuth token
    /// origins before [`Self::build`]. Replacing all security-header settings
    /// with API defaults also restores strict COOP and breaks popup OAuth.
    #[must_use]
    pub fn documentation() -> Self {
        Self {
            security_headers: SecurityHeadersSettings {
                cross_origin_opener_policy: None,
                content_security_policy: Some(DOCUMENTATION_CSP.to_owned()),
                ..SecurityHeadersSettings::default()
            },
            ..Self::default()
        }
    }

    #[must_use]
    /// Configures request context and returns the updated value.
    pub const fn with_request_context(mut self, request_context: bool) -> Self {
        self.request_context = request_context;
        self
    }

    #[must_use]
    /// Configures trace and returns the updated value.
    pub const fn with_trace(mut self, trace: bool) -> Self {
        self.trace = trace;
        self
    }

    #[must_use]
    /// Configures which trusted peers may supply forwarded client IP headers.
    /// Forwarded headers are ignored by default.
    pub fn with_forwarded_headers(mut self, forwarded_headers: ForwardedHeadersSettings) -> Self {
        self.forwarded_headers = forwarded_headers;
        self
    }

    #[must_use]
    /// Configures CORS and returns the updated value.
    pub fn with_cors(mut self, cors: CorsSettings) -> Self {
        self.cors = cors;
        self
    }

    #[must_use]
    /// Configures security headers and returns the updated value.
    pub fn with_security_headers(mut self, security_headers: SecurityHeadersSettings) -> Self {
        self.security_headers = security_headers;
        self
    }

    #[must_use]
    /// Sets the request policy's default response deadline; `None` disables it.
    /// Calling `with_request_policy` afterwards replaces this default as well.
    ///
    /// Expiry returns a `503` [`crate::http::ApiProblem`] with code `response_timeout`
    /// and any existing request context identifiers. Streaming response bodies
    /// are outside this deadline. Each effective policy permitting idempotency
    /// requires a nonzero timeout shorter than its processing TTL.
    pub const fn with_timeout(mut self, timeout: Option<Duration>) -> Self {
        self.request_policy.default_timeout = match timeout {
            Some(duration) => ResponseTimeout::After(duration),
            None => ResponseTimeout::Disabled,
        };
        self
    }

    /// Sets the shared request concurrency limit; `None` disables it.
    ///
    /// See [`Self::max_concurrent_requests`] for admission and cancellation semantics.
    #[must_use]
    pub const fn with_max_concurrent_requests(mut self, limit: Option<usize>) -> Self {
        self.max_concurrent_requests = limit;
        self
    }

    #[must_use]
    /// Sets the request policy's default body limit; `None` disables it.
    /// Calling `with_request_policy` afterwards replaces this value as well.
    pub const fn with_request_body_limit(mut self, request_body_limit: Option<usize>) -> Self {
        self.request_policy.default_request_body_limit = match request_body_limit {
            Some(bytes) => super::route_settings::RequestBodyLimitSettings::Bytes(bytes),
            None => super::route_settings::RequestBodyLimitSettings::Disabled,
        };
        self
    }

    #[must_use]
    /// Configures [`Self::compression`] and returns the updated value.
    pub const fn with_compression(mut self, compression: bool) -> Self {
        self.compression = compression;
        self
    }

    #[must_use]
    /// Configures global rate limiting. When enabled, the stack builder also
    /// needs a rate-limit store; identity-based keys require an authentication hook.
    pub fn with_rate_limit(mut self, rate_limit: HttpRateLimitSettings) -> Self {
        self.rate_limit = rate_limit;
        self
    }

    #[must_use]
    /// Configures idempotency. When enabled, the stack builder also needs an
    /// idempotency store. Every default or route policy permitting idempotency
    /// must have a finite response timeout shorter than the processing TTL.
    pub fn with_idempotency(mut self, idempotency: HttpIdempotencySettings) -> Self {
        self.idempotency = idempotency;
        self
    }

    #[must_use]
    /// Configures request policy and returns the updated value.
    pub fn with_request_policy(mut self, request_policy: HttpRequestPolicySettings) -> Self {
        self.request_policy = request_policy;
        self
    }

    /// Builds immutable HTTP configuration after validating every setting.
    pub fn build(self) -> Result<HttpMiddlewareConfig, SettingsValidationError> {
        self.build_at("http")
    }

    /// Validates all HTTP middleware settings.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        self.validate_at("http")
    }

    /// Validates settings using their location in the application configuration.
    ///
    /// `path` prefixes every reported field. An empty path reports fields at the
    /// document root; the supplied path is otherwise used unchanged.
    pub fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        self.build_at(path).map(|_| ())
    }

    fn build_at(&self, path: &str) -> Result<HttpMiddlewareConfig, SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        if let Some(limit) = self.max_concurrent_requests {
            issues.require(
                (1..=tokio::sync::Semaphore::MAX_PERMITS).contains(&limit),
                field_path(path, "max_concurrent_requests"),
                "must be greater than zero and fit the supported concurrency range",
            );
        }
        let cors = self.cors.build_at(&field_path(path, "cors"));
        let forwarded_headers = self
            .forwarded_headers
            .build_at(&field_path(path, "forwarded_headers"));
        let security_headers = self
            .security_headers
            .build_at(&field_path(path, "security_headers"));
        let rate_limit = self.rate_limit.build_at(&field_path(path, "rate_limit"));
        let idempotency = self.idempotency.build_at(&field_path(path, "idempotency"));
        let request_policy = self
            .request_policy
            .build_at(&field_path(path, "request_policy"));
        if self.idempotency.enabled
            && let Ok(policy) = &request_policy
        {
            for (index, effective) in std::iter::once((None, policy.policy_with_rule(None))).chain(
                policy
                    .rules()
                    .iter()
                    .enumerate()
                    .map(|(index, rule)| (Some(index), policy.policy_with_rule(Some(rule)))),
            ) {
                if effective.idempotency() == IdempotencyRequestPolicy::Disabled {
                    continue;
                }
                let timeout_path = match index {
                    Some(index) => format!("request_policy.rules.{index}.timeout"),
                    None => "request_policy.default_timeout".to_owned(),
                };
                issues.require(
                    effective.timeout().duration().is_some_and(|timeout| timeout < self.idempotency.processing_ttl),
                    field_path(path, &timeout_path),
                    "must be enabled and shorter than idempotency.processing_ttl when this policy permits idempotency",
                );
            }
        }
        for result in [
            cors.as_ref().map(|_| ()),
            forwarded_headers.as_ref().map(|_| ()),
            security_headers.as_ref().map(|_| ()),
            rate_limit.as_ref().map(|_| ()),
            idempotency.as_ref().map(|_| ()),
            request_policy.as_ref().map(|_| ()),
        ] {
            if let Err(error) = result {
                issues.extend(error.clone());
            }
        }
        issues.into_result()?;
        Ok(HttpMiddlewareConfig {
            request_context: self.request_context,
            forwarded_headers: forwarded_headers?,
            trace: self.trace,
            cors: cors?,
            security_headers: security_headers?,
            max_concurrent_requests: self.max_concurrent_requests.and_then(NonZeroUsize::new),
            compression: self.compression,
            rate_limit: rate_limit?,
            idempotency: idempotency?,
            request_policy: request_policy?,
        })
    }
}