footing 0.4.1

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
//! Top-level immutable HTTP configuration and settings materialization.

use std::time::Duration;

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

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

use super::{
    policy::{
        CorsPolicy, DEFAULT_HTTP_TIMEOUT, HttpMiddlewareConfig, HttpRateLimitConfig,
        HttpRequestPolicy, RequestBodyLimitPolicy,
    },
    route_settings::HttpRequestPolicySettings,
    security::SecurityHeadersConfig,
    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, 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()),
            timeout: Some(DEFAULT_HTTP_TIMEOUT),
            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, 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,
            timeout: 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 response timeout, or `None` when disabled.
    /// Streaming response bodies are not covered by this deadline.
    pub const fn timeout(&self) -> Option<Duration> {
        self.timeout
    }

    #[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.
    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 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,
    #[serde(with = "crate::settings::human_duration::option")]
    /// Optional timeout applied to each request.
    /// Required when idempotency is enabled, and must be shorter than its processing TTL.
    pub timeout: Option<Duration>,
    /// Whether supported responses may be compressed.
    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(),
            timeout: Some(DEFAULT_HTTP_TIMEOUT),
            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 response deadline; `None` disables it.
    /// Streaming response bodies are outside this deadline. Idempotency requires
    /// a nonzero timeout shorter than its processing TTL.
    pub const fn with_timeout(mut self, timeout: Option<Duration>) -> Self {
        self.timeout = timeout;
        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 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, and the processing TTL must exceed the request timeout.
    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")
    }

    pub(crate) 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();
        issues.require(
            !self.idempotency.enabled || self.timeout.is_some(),
            format!("{path}.timeout"),
            "must be configured when idempotency is enabled",
        );
        if let Some(timeout) = self.timeout {
            issues.require(
                !timeout.is_zero(),
                format!("{path}.timeout"),
                "must be greater than zero",
            );
            if self.idempotency.enabled {
                issues.require(
                    self.idempotency.processing_ttl > timeout,
                    format!("{path}.idempotency.processing_ttl"),
                    "must be greater than the HTTP request timeout",
                );
            }
        }
        let cors = self.cors.build_at(&format!("{path}.cors"));
        let forwarded_headers = self
            .forwarded_headers
            .build_at(&format!("{path}.forwarded_headers"));
        let security_headers = self
            .security_headers
            .build_at(&format!("{path}.security_headers"));
        let rate_limit = self.rate_limit.build_at(&format!("{path}.rate_limit"));
        let idempotency = self.idempotency.build_at(&format!("{path}.idempotency"));
        let request_policy = self
            .request_policy
            .build_at(&format!("{path}.request_policy"));
        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?,
            timeout: self.timeout,
            compression: self.compression,
            rate_limit: rate_limit?,
            idempotency: idempotency?,
            request_policy: request_policy?,
        })
    }
}