footing 0.1.5

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
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
//! Validated CORS and route-aware HTTP request policies.

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

use crate::http::{
    IdempotencyConfig, IdempotencyRequestPolicy, RateLimitConfig, RateLimitKeySource,
    RateLimitRequestPolicy,
};
use axum::{
    extract::MatchedPath,
    http::{
        HeaderName, HeaderValue, Method, Request,
        header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE},
    },
};

use super::{error::HttpLayerError, security::SecurityHeadersConfig};
use crate::http::trusted_proxy::ForwardedHeadersPolicy;

/// Default HTTP timeout.
pub const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
/// Default HTTP request body limit.
pub const DEFAULT_HTTP_REQUEST_BODY_LIMIT: usize = 2 * 1024 * 1024;
/// Default HSTS maximum age.
pub const DEFAULT_HSTS_MAX_AGE: Duration = Duration::from_secs(31_536_000);

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Policy controlling CORS.
pub enum CorsPolicy {
    /// The capability is disabled.
    Disabled,
    /// Indicates permissive.
    Permissive,
    /// Indicates restricted.
    Restricted(CorsConfig),
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Validated configuration for restricted CORS.
pub struct CorsConfig {
    pub(super) allowed_origins: Vec<HeaderValue>,
    pub(super) allowed_methods: Vec<Method>,
    pub(super) allowed_headers: Vec<HeaderName>,
    pub(super) exposed_headers: Vec<HeaderName>,
    pub(super) allow_credentials: bool,
    pub(super) max_age: Option<Duration>,
}

impl CorsConfig {
    pub(super) fn new(allowed_origins: impl IntoIterator<Item = HeaderValue>) -> Self {
        Self {
            allowed_origins: allowed_origins.into_iter().collect(),
            allowed_methods: vec![
                Method::GET,
                Method::POST,
                Method::PUT,
                Method::PATCH,
                Method::DELETE,
            ],
            allowed_headers: default_cors_allowed_headers(),
            exposed_headers: default_cors_exposed_headers(),
            allow_credentials: false,
            max_age: Some(Duration::from_secs(10 * 60)),
        }
    }

    pub(super) fn from_origin_strs(
        origins: impl IntoIterator<Item = impl AsRef<str>>,
    ) -> Result<Self, axum::http::header::InvalidHeaderValue> {
        let origins = origins
            .into_iter()
            .map(|origin| HeaderValue::from_str(origin.as_ref().trim()))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(Self::new(origins))
    }

    pub(super) fn allow_methods(mut self, methods: impl IntoIterator<Item = Method>) -> Self {
        self.allowed_methods = methods.into_iter().collect();
        self
    }

    pub(super) fn allow_headers(mut self, headers: impl IntoIterator<Item = HeaderName>) -> Self {
        self.allowed_headers = headers.into_iter().collect();
        self
    }

    pub(super) fn expose_headers(mut self, headers: impl IntoIterator<Item = HeaderName>) -> Self {
        self.exposed_headers = headers.into_iter().collect();
        self
    }

    pub(super) const fn allow_credentials(mut self, allow_credentials: bool) -> Self {
        self.allow_credentials = allow_credentials;
        self
    }

    pub(super) const fn max_age(mut self, max_age: Option<Duration>) -> Self {
        self.max_age = max_age;
        self
    }

    #[must_use]
    /// Returns the allowed origins.
    pub fn allowed_origins(&self) -> &[HeaderValue] {
        &self.allowed_origins
    }

    #[must_use]
    /// Returns the allowed methods.
    pub fn allowed_methods(&self) -> &[Method] {
        &self.allowed_methods
    }

    #[must_use]
    /// Returns the allowed headers.
    pub fn allowed_headers(&self) -> &[HeaderName] {
        &self.allowed_headers
    }

    #[must_use]
    /// Returns the exposed headers.
    pub fn exposed_headers(&self) -> &[HeaderName] {
        &self.exposed_headers
    }

    #[must_use]
    /// Returns the credentials allowed.
    pub const fn credentials_allowed(&self) -> bool {
        self.allow_credentials
    }

    #[must_use]
    /// Returns the maximum age value.
    pub const fn max_age_value(&self) -> Option<Duration> {
        self.max_age
    }

    pub(super) fn validate(&self) -> Result<(), HttpLayerError> {
        if self.allowed_origins.is_empty()
            || self
                .allowed_origins
                .iter()
                .any(|origin| origin.as_bytes().is_empty())
        {
            return Err(HttpLayerError::CorsAllowedOriginsEmpty);
        }

        if self.allow_credentials
            && self
                .allowed_origins
                .iter()
                .any(|origin| origin.as_bytes() == b"*")
        {
            return Err(HttpLayerError::CorsWildcardOriginWithCredentials);
        }

        Ok(())
    }
}

#[derive(Debug, Clone)]
#[non_exhaustive]
/// Immutable HTTP policy produced by [`crate::http::HttpFoundationSettings::build`].
///
/// Runtime stores and telemetry are injected separately through
/// [`crate::http::HttpFoundationBuilder`].
pub struct HttpLayerConfig {
    pub(super) request_context: bool,
    pub(super) forwarded_headers: ForwardedHeadersPolicy,
    pub(super) trace: bool,
    pub(super) cors: CorsPolicy,
    pub(super) security_headers: Option<SecurityHeadersConfig>,
    pub(super) timeout: Option<Duration>,
    pub(super) request_body_limit: Option<NonZeroUsize>,
    pub(super) compression: bool,
    pub(super) rate_limit: Option<HttpRateLimitConfig>,
    pub(super) idempotency: Option<IdempotencyConfig>,
    pub(super) request_policy: HttpRequestPolicy,
}

#[derive(Debug, Clone)]
#[non_exhaustive]
/// Validated HTTP rate-limit policy.
pub struct HttpRateLimitConfig {
    pub(super) limiter: RateLimitConfig,
    pub(super) key_source: RateLimitKeySource,
}

impl HttpRateLimitConfig {
    #[must_use]
    /// Creates a policy from validated limiter configuration and a key source.
    pub const fn new(limiter: RateLimitConfig, key_source: RateLimitKeySource) -> Self {
        Self {
            limiter,
            key_source,
        }
    }

    #[must_use]
    /// Returns the token-bucket configuration.
    pub const fn limiter(&self) -> RateLimitConfig {
        self.limiter
    }

    #[must_use]
    /// Returns the request key source.
    pub const fn key_source(&self) -> &RateLimitKeySource {
        &self.key_source
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Policy controlling request body limit.
pub enum RequestBodyLimitPolicy {
    /// The capability is disabled.
    Disabled,
    /// Enforces a non-zero byte limit.
    Bytes(NonZeroUsize),
}

impl RequestBodyLimitPolicy {
    /// Creates a non-zero byte limit.
    pub fn bytes(value: usize) -> Result<Self, HttpLayerError> {
        NonZeroUsize::new(value)
            .map(Self::Bytes)
            .ok_or(HttpLayerError::InvalidRequestBodyLimit)
    }

    /// Creates a policy from an optional byte limit.
    pub fn from_optional(value: Option<usize>) -> Result<Self, HttpLayerError> {
        match value {
            Some(value) => Self::bytes(value),
            None => Ok(Self::Disabled),
        }
    }

    #[must_use]
    /// Returns this value as optional.
    pub const fn as_optional(self) -> Option<usize> {
        match self {
            Self::Disabled => None,
            Self::Bytes(value) => Some(value.get()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Policy controlling HTTP request.
pub struct HttpRequestPolicy {
    default_rate_limit: RateLimitRequestPolicy,
    default_idempotency: IdempotencyRequestPolicy,
    default_request_body_limit: RequestBodyLimitPolicy,
    rules: Vec<HttpRouteRule>,
}

impl Default for HttpRequestPolicy {
    fn default() -> Self {
        Self {
            default_rate_limit: RateLimitRequestPolicy::Enabled,
            default_idempotency: IdempotencyRequestPolicy::HeaderOptional,
            default_request_body_limit: RequestBodyLimitPolicy::Disabled,
            rules: Vec::new(),
        }
    }
}

impl HttpRequestPolicy {
    #[must_use]
    /// Creates disabled.
    pub fn disabled() -> Self {
        Self {
            default_rate_limit: RateLimitRequestPolicy::Disabled,
            default_idempotency: IdempotencyRequestPolicy::Disabled,
            default_request_body_limit: RequestBodyLimitPolicy::Disabled,
            rules: Vec::new(),
        }
    }

    #[must_use]
    /// Configures default rate limit and returns the updated value.
    pub const fn with_default_rate_limit(mut self, policy: RateLimitRequestPolicy) -> Self {
        self.default_rate_limit = policy;
        self
    }

    #[must_use]
    /// Configures default idempotency and returns the updated value.
    pub const fn with_default_idempotency(mut self, policy: IdempotencyRequestPolicy) -> Self {
        self.default_idempotency = policy;
        self
    }

    #[must_use]
    /// Configures default request body limit and returns the updated value.
    pub const fn with_default_request_body_limit(mut self, policy: RequestBodyLimitPolicy) -> Self {
        self.default_request_body_limit = policy;
        self
    }

    #[must_use]
    /// Configures rule and returns the updated value.
    pub fn with_rule(mut self, rule: HttpRouteRule) -> Self {
        self.rules.push(rule);
        self
    }

    #[must_use]
    /// Configures rules and returns the updated value.
    pub fn with_rules(mut self, rules: impl IntoIterator<Item = HttpRouteRule>) -> Self {
        self.rules.extend(rules);
        self
    }

    #[must_use]
    /// Returns the rules.
    pub fn rules(&self) -> &[HttpRouteRule] {
        &self.rules
    }

    #[must_use]
    /// Returns the default rate limit.
    pub const fn default_rate_limit(&self) -> RateLimitRequestPolicy {
        self.default_rate_limit
    }

    #[must_use]
    /// Returns the default idempotency.
    pub const fn default_idempotency(&self) -> IdempotencyRequestPolicy {
        self.default_idempotency
    }

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

    #[must_use]
    /// Returns the policy for.
    pub fn policy_for<B>(&self, request: &Request<B>) -> EffectiveHttpRequestPolicy {
        let mut policy = EffectiveHttpRequestPolicy {
            rate_limit: self.default_rate_limit,
            idempotency: self.default_idempotency,
            request_body_limit: self.default_request_body_limit,
        };

        for rule in &self.rules {
            if !rule.matches(request) {
                continue;
            }
            if let Some(rate_limit) = rule.rate_limit {
                policy.rate_limit = rate_limit;
            }
            if let Some(idempotency) = rule.idempotency {
                policy.idempotency = idempotency;
            }
            if let Some(request_body_limit) = rule.request_body_limit {
                policy.request_body_limit = request_body_limit;
            }
        }

        policy
    }

    #[must_use]
    /// Returns whether this value has request body limit overrides.
    pub fn has_request_body_limit_overrides(&self) -> bool {
        !matches!(
            self.default_request_body_limit,
            RequestBodyLimitPolicy::Disabled
        ) || self
            .rules
            .iter()
            .any(|rule| rule.request_body_limit.is_some())
    }

    pub(super) fn request_body_limit_for<B>(
        &self,
        request: &Request<B>,
        fallback: RequestBodyLimitPolicy,
    ) -> RequestBodyLimitPolicy {
        let mut policy = match self.default_request_body_limit {
            RequestBodyLimitPolicy::Disabled => fallback,
            configured => configured,
        };

        for rule in &self.rules {
            if rule.matches(request)
                && let Some(configured) = rule.request_body_limit
            {
                policy = configured;
            }
        }

        policy
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Represents HTTP route rule.
pub struct HttpRouteRule {
    pub(super) matcher: RouteMatcher,
    pub(super) methods: Vec<Method>,
    pub(super) rate_limit: Option<RateLimitRequestPolicy>,
    pub(super) idempotency: Option<IdempotencyRequestPolicy>,
    pub(super) request_body_limit: Option<RequestBodyLimitPolicy>,
}

impl HttpRouteRule {
    #[must_use]
    /// Creates any.
    pub fn any() -> Self {
        Self::new(RouteMatcher::any())
    }

    /// Creates exact.
    pub fn exact(path: impl Into<String>) -> Result<Self, HttpLayerError> {
        RouteMatcher::exact(path).map(Self::new)
    }

    /// Creates prefix.
    pub fn prefix(prefix: impl Into<String>) -> Result<Self, HttpLayerError> {
        RouteMatcher::prefix(prefix).map(Self::new)
    }

    /// Creates raw prefix.
    pub fn raw_prefix(prefix: impl Into<String>) -> Result<Self, HttpLayerError> {
        RouteMatcher::raw_prefix(prefix).map(Self::new)
    }

    #[must_use]
    /// Creates a new instance.
    pub fn new(matcher: RouteMatcher) -> Self {
        Self {
            matcher,
            methods: Vec::new(),
            rate_limit: None,
            idempotency: None,
            request_body_limit: None,
        }
    }

    #[must_use]
    /// Returns the methods.
    pub fn methods(mut self, methods: impl IntoIterator<Item = Method>) -> Self {
        self.methods = methods.into_iter().collect();
        self
    }

    #[must_use]
    /// Returns the rate limit.
    pub const fn rate_limit(mut self, policy: RateLimitRequestPolicy) -> Self {
        self.rate_limit = Some(policy);
        self
    }

    #[must_use]
    /// Returns the idempotency.
    pub const fn idempotency(mut self, policy: IdempotencyRequestPolicy) -> Self {
        self.idempotency = Some(policy);
        self
    }

    #[must_use]
    /// Returns the request body limit.
    pub const fn request_body_limit(mut self, policy: RequestBodyLimitPolicy) -> Self {
        self.request_body_limit = Some(policy);
        self
    }

    #[must_use]
    /// Returns the matcher.
    pub const fn matcher(&self) -> &RouteMatcher {
        &self.matcher
    }

    #[must_use]
    /// Returns the methods slice.
    pub fn methods_slice(&self) -> &[Method] {
        &self.methods
    }

    fn matches<B>(&self, request: &Request<B>) -> bool {
        (self.methods.is_empty() || self.methods.iter().any(|method| method == request.method()))
            && self.matcher.matches(request_path(request))
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Validated route matcher.
pub struct RouteMatcher(pub(super) RouteMatcherKind);

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum RouteMatcherKind {
    Any,
    Exact(String),
    Prefix(String),
    RawPrefix(String),
}

impl RouteMatcher {
    #[must_use]
    /// Matches every route.
    pub const fn any() -> Self {
        Self(RouteMatcherKind::Any)
    }

    /// Matches one exact absolute path.
    pub fn exact(path: impl Into<String>) -> Result<Self, HttpLayerError> {
        Self::path(RouteMatcherKind::Exact, path)
    }

    /// Matches an absolute path on segment boundaries.
    pub fn prefix(path: impl Into<String>) -> Result<Self, HttpLayerError> {
        Self::path(RouteMatcherKind::Prefix, path)
    }

    /// Matches an absolute path using raw string-prefix semantics.
    pub fn raw_prefix(path: impl Into<String>) -> Result<Self, HttpLayerError> {
        Self::path(RouteMatcherKind::RawPrefix, path)
    }

    fn path(
        constructor: impl FnOnce(String) -> RouteMatcherKind,
        path: impl Into<String>,
    ) -> Result<Self, HttpLayerError> {
        let path = path.into();
        if !path.starts_with('/') {
            return Err(HttpLayerError::InvalidRouteMatcher);
        }
        Ok(Self(constructor(path)))
    }

    #[must_use]
    /// Returns whether this value matches the value.
    pub fn matches(&self, path: &str) -> bool {
        match &self.0 {
            RouteMatcherKind::Any => true,
            RouteMatcherKind::Exact(expected) => path == expected,
            RouteMatcherKind::Prefix(prefix) => path_matches_segment_prefix(path, prefix),
            RouteMatcherKind::RawPrefix(prefix) => path.starts_with(prefix),
        }
    }
}

fn path_matches_segment_prefix(path: &str, prefix: &str) -> bool {
    if path == prefix {
        return true;
    }
    let Some(rest) = path.strip_prefix(prefix) else {
        return false;
    };
    prefix.ends_with('/') || rest.starts_with('/')
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Policy controlling effective HTTP request.
pub struct EffectiveHttpRequestPolicy {
    rate_limit: RateLimitRequestPolicy,
    idempotency: IdempotencyRequestPolicy,
    request_body_limit: RequestBodyLimitPolicy,
}

impl EffectiveHttpRequestPolicy {
    #[must_use]
    /// Returns the rate limit.
    pub const fn rate_limit(self) -> RateLimitRequestPolicy {
        self.rate_limit
    }

    #[must_use]
    /// Returns the idempotency.
    pub const fn idempotency(self) -> IdempotencyRequestPolicy {
        self.idempotency
    }

    #[must_use]
    /// Returns the request body limit.
    pub const fn request_body_limit(self) -> RequestBodyLimitPolicy {
        self.request_body_limit
    }
}

fn request_path<B>(request: &Request<B>) -> &str {
    request
        .extensions()
        .get::<MatchedPath>()
        .map(MatchedPath::as_str)
        .unwrap_or_else(|| request.uri().path())
}

fn default_cors_allowed_headers() -> Vec<HeaderName> {
    vec![
        ACCEPT,
        AUTHORIZATION,
        CONTENT_TYPE,
        HeaderName::from_static("x-request-id"),
        HeaderName::from_static("traceparent"),
    ]
}

fn default_cors_exposed_headers() -> Vec<HeaderName> {
    vec![HeaderName::from_static("x-request-id")]
}