soaprs-http 0.5.0

Transport-neutral HTTP contracts and policies for soaprs
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
//! Framework-independent endpoint policies.

use std::{num::NonZeroU32, num::NonZeroU64, time::Duration};

use http::{HeaderName, Method, Uri};
use soaprs_auth::AuthorizationName;
use soaprs_core::{SoapError, SoapResult};

/// Identity dimension used to derive a rate-limit key.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum RateLimitScope {
    /// One shared limit for the endpoint.
    Global,
    /// One limit per normalized client network address.
    #[default]
    ClientIp,
    /// One limit per authenticated principal.
    Principal,
    /// One limit per authenticated API key.
    ApiKey,
    /// An adapter or application supplies a named key resolver.
    Custom(AuthorizationName),
}

/// Declarative rate limit translated by an HTTP or rate-limiter adapter.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RateLimitPolicy {
    /// Maximum steady-state requests in the period.
    pub requests: NonZeroU32,
    /// Length of the rate-limit period.
    pub period: Duration,
    /// Optional additional burst capacity.
    pub burst: Option<NonZeroU32>,
    /// Dimension used to derive the limiter key.
    pub scope: RateLimitScope,
}

impl RateLimitPolicy {
    /// Creates a client-IP rate limit with a non-zero period.
    pub fn new(requests: NonZeroU32, period: Duration) -> SoapResult<Self> {
        if period.is_zero() {
            return Err(SoapError::validation(
                "rate-limit period must be greater than zero",
            ));
        }
        Ok(Self {
            requests,
            period,
            burst: None,
            scope: RateLimitScope::ClientIp,
        })
    }

    /// Selects the identity dimension used to derive a limiter key.
    #[must_use]
    pub fn scope(mut self, scope: RateLimitScope) -> Self {
        self.scope = scope;
        self
    }

    /// Adds explicit burst capacity above the steady-state limit.
    #[must_use]
    pub fn burst(mut self, burst: NonZeroU32) -> Self {
        self.burst = Some(burst);
        self
    }

    /// Validates invariants after direct public-field mutation.
    pub fn validate(&self) -> SoapResult<()> {
        if self.period.is_zero() {
            Err(SoapError::validation(
                "rate-limit period must be greater than zero",
            ))
        } else {
            Ok(())
        }
    }
}

/// Maximum accepted request body size.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BodyLimitPolicy {
    /// Maximum number of request body bytes before decoding.
    pub max_bytes: NonZeroU64,
}

impl BodyLimitPolicy {
    /// Creates a request body limit.
    pub const fn new(max_bytes: NonZeroU64) -> Self {
        Self { max_bytes }
    }
}

/// Whether cross-site request-forgery protection is required.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CsrfPolicy {
    /// No CSRF mechanism is required by endpoint metadata.
    #[default]
    Disabled,
    /// A CSRF adapter must validate the request.
    Required,
}

/// Allowed CORS origins.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AllowedOrigins {
    /// Any origin is allowed. This cannot be combined with credentials.
    Any,
    /// Only the exact normalized origins are allowed.
    Exact(Vec<Uri>),
}

/// Declarative cross-origin resource-sharing policy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CorsPolicy {
    /// Origins permitted by the resource.
    pub origins: AllowedOrigins,
    /// Methods permitted for cross-origin requests.
    pub methods: Vec<Method>,
    /// Request headers permitted by preflight responses.
    pub allow_headers: Vec<HeaderName>,
    /// Response headers exposed to browser code.
    pub expose_headers: Vec<HeaderName>,
    /// Whether credentialed browser requests are allowed.
    pub allow_credentials: bool,
    /// Optional browser preflight cache duration.
    pub max_age: Option<Duration>,
}

impl CorsPolicy {
    /// Creates a public CORS policy without credentials.
    pub fn any(methods: Vec<Method>) -> SoapResult<Self> {
        validate_methods(&methods)?;
        Ok(Self {
            origins: AllowedOrigins::Any,
            methods,
            allow_headers: Vec::new(),
            expose_headers: Vec::new(),
            allow_credentials: false,
            max_age: None,
        })
    }

    /// Creates an exact-origin CORS policy.
    pub fn exact<I, S>(origins: I, methods: Vec<Method>) -> SoapResult<Self>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        validate_methods(&methods)?;
        let origins = origins
            .into_iter()
            .map(|origin| validate_origin(origin.as_ref()))
            .collect::<SoapResult<Vec<_>>>()?;
        if origins.is_empty() {
            return Err(SoapError::validation("CORS origins cannot be empty"));
        }
        Ok(Self {
            origins: AllowedOrigins::Exact(origins),
            methods,
            allow_headers: Vec::new(),
            expose_headers: Vec::new(),
            allow_credentials: false,
            max_age: None,
        })
    }

    /// Allows browser credentials for an exact-origin policy.
    pub fn allow_credentials(mut self) -> SoapResult<Self> {
        if matches!(self.origins, AllowedOrigins::Any) {
            return Err(SoapError::validation(
                "credentialed CORS cannot allow every origin",
            ));
        }
        self.allow_credentials = true;
        Ok(self)
    }

    /// Sets headers accepted in cross-origin requests.
    #[must_use]
    pub fn allow_headers(mut self, headers: Vec<HeaderName>) -> Self {
        self.allow_headers = headers;
        self
    }

    /// Sets headers exposed to browser code.
    #[must_use]
    pub fn expose_headers(mut self, headers: Vec<HeaderName>) -> Self {
        self.expose_headers = headers;
        self
    }

    /// Sets a non-zero browser preflight cache duration.
    pub fn max_age(mut self, max_age: Duration) -> SoapResult<Self> {
        if max_age.is_zero() {
            return Err(SoapError::validation(
                "CORS max age must be greater than zero",
            ));
        }
        self.max_age = Some(max_age);
        Ok(self)
    }

    /// Validates invariants after direct public-field mutation.
    pub fn validate(&self) -> SoapResult<()> {
        validate_methods(&self.methods)?;
        match &self.origins {
            AllowedOrigins::Any if self.allow_credentials => {
                return Err(SoapError::validation(
                    "credentialed CORS cannot allow every origin",
                ));
            }
            AllowedOrigins::Exact(origins) if origins.is_empty() => {
                return Err(SoapError::validation("CORS origins cannot be empty"));
            }
            AllowedOrigins::Exact(origins) => {
                origins
                    .iter()
                    .try_for_each(|origin| validate_origin(&origin.to_string()).map(|_| ()))?;
            }
            AllowedOrigins::Any => {}
        }
        if self.max_age.is_some_and(|max_age| max_age.is_zero()) {
            return Err(SoapError::validation(
                "CORS max age must be greater than zero",
            ));
        }
        Ok(())
    }
}

fn validate_methods(methods: &[Method]) -> SoapResult<()> {
    if methods.is_empty() {
        Err(SoapError::validation("CORS methods cannot be empty"))
    } else {
        Ok(())
    }
}

fn validate_origin(origin: &str) -> SoapResult<Uri> {
    let uri = origin
        .parse::<Uri>()
        .map_err(|_| SoapError::validation(format!("invalid CORS origin `{origin}`")))?;
    let has_root_or_empty_path = uri.path().is_empty() || uri.path() == "/";
    if !matches!(uri.scheme_str(), Some("http" | "https"))
        || uri.authority().is_none()
        || uri
            .authority()
            .is_some_and(|authority| authority.as_str().contains('@'))
        || !has_root_or_empty_path
        || uri.query().is_some()
    {
        return Err(SoapError::validation(format!(
            "invalid CORS origin `{origin}`"
        )));
    }
    Ok(uri)
}

/// Browser frame embedding policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameOptions {
    /// The resource cannot be embedded in a frame.
    Deny,
    /// Only the same origin may embed the resource.
    SameOrigin,
}

/// Referrer information sent by compatible clients.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReferrerPolicy {
    /// Do not send referrer information.
    NoReferrer,
    /// Send origin only when crossing origins.
    StrictOriginWhenCrossOrigin,
}

/// HTTP Strict Transport Security declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HstsPolicy {
    /// Browser HSTS duration.
    pub max_age: Duration,
    /// Whether the policy covers subdomains.
    pub include_subdomains: bool,
    /// Whether the site requests browser preload registration.
    pub preload: bool,
}

impl HstsPolicy {
    /// Creates a non-zero HSTS policy.
    pub fn new(max_age: Duration) -> SoapResult<Self> {
        if max_age.is_zero() {
            return Err(SoapError::validation(
                "HSTS max age must be greater than zero",
            ));
        }
        Ok(Self {
            max_age,
            include_subdomains: false,
            preload: false,
        })
    }

    /// Applies HSTS to subdomains.
    #[must_use]
    pub const fn include_subdomains(mut self) -> Self {
        self.include_subdomains = true;
        self
    }

    /// Requests browser HSTS preload registration.
    #[must_use]
    pub const fn preload(mut self) -> Self {
        self.preload = true;
        self
    }
}

/// Security response-header policy translated by framework adapters.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecurityHeadersPolicy {
    /// Emit `X-Content-Type-Options: nosniff`.
    pub no_sniff: bool,
    /// Frame embedding restriction.
    pub frame_options: Option<FrameOptions>,
    /// Browser referrer policy.
    pub referrer_policy: Option<ReferrerPolicy>,
    /// Optional application-defined Content Security Policy.
    pub content_security_policy: Option<String>,
    /// Optional HTTPS-only HSTS policy.
    pub hsts: Option<HstsPolicy>,
}

impl SecurityHeadersPolicy {
    /// Returns conservative defaults that are safe for most API responses.
    pub const fn secure_defaults() -> Self {
        Self {
            no_sniff: true,
            frame_options: Some(FrameOptions::Deny),
            referrer_policy: Some(ReferrerPolicy::NoReferrer),
            content_security_policy: None,
            hsts: None,
        }
    }

    /// Sets an application-specific Content Security Policy without controls.
    pub fn content_security_policy(mut self, policy: impl Into<String>) -> SoapResult<Self> {
        let policy = policy.into();
        if policy.trim().is_empty() || policy.chars().any(char::is_control) {
            return Err(SoapError::validation(
                "content security policy is empty or contains control characters",
            ));
        }
        self.content_security_policy = Some(policy);
        Ok(self)
    }

    /// Enables HSTS. Applications should do this only when HTTPS is guaranteed.
    #[must_use]
    pub const fn hsts(mut self, policy: HstsPolicy) -> Self {
        self.hsts = Some(policy);
        self
    }

    /// Validates header values after direct public-field mutation.
    pub fn validate(&self) -> SoapResult<()> {
        if self
            .content_security_policy
            .as_ref()
            .is_some_and(|policy| policy.trim().is_empty() || policy.chars().any(char::is_control))
        {
            return Err(SoapError::validation(
                "content security policy is empty or contains control characters",
            ));
        }
        if self.hsts.is_some_and(|policy| policy.max_age.is_zero()) {
            return Err(SoapError::validation(
                "HSTS max age must be greater than zero",
            ));
        }
        Ok(())
    }
}

impl Default for SecurityHeadersPolicy {
    fn default() -> Self {
        Self::secure_defaults()
    }
}

/// HTTP response cache visibility.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CacheVisibility {
    /// Do not store the response.
    NoStore,
    /// Only private client caches may store the response.
    Private,
    /// Shared and private caches may store the response.
    Public,
}

/// Declarative HTTP response caching policy, distinct from application data caching.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResponseCachePolicy {
    /// Cache visibility.
    pub visibility: CacheVisibility,
    /// Optional freshness lifetime.
    pub max_age: Option<Duration>,
    /// Request headers that vary the selected representation.
    pub vary: Vec<HeaderName>,
}

impl ResponseCachePolicy {
    /// Prevents every compliant cache from storing the response.
    pub const fn no_store() -> Self {
        Self {
            visibility: CacheVisibility::NoStore,
            max_age: None,
            vary: Vec::new(),
        }
    }

    /// Creates a private response cache policy with non-zero freshness.
    pub fn private(max_age: Duration) -> SoapResult<Self> {
        Self::cacheable(CacheVisibility::Private, max_age)
    }

    /// Creates a shared response cache policy with non-zero freshness.
    pub fn public(max_age: Duration) -> SoapResult<Self> {
        Self::cacheable(CacheVisibility::Public, max_age)
    }

    fn cacheable(visibility: CacheVisibility, max_age: Duration) -> SoapResult<Self> {
        if max_age.is_zero() {
            return Err(SoapError::validation(
                "response cache max age must be greater than zero",
            ));
        }
        Ok(Self {
            visibility,
            max_age: Some(max_age),
            vary: Vec::new(),
        })
    }

    /// Sets request headers included in the cache key.
    #[must_use]
    pub fn vary(mut self, vary: Vec<HeaderName>) -> Self {
        self.vary = vary;
        self
    }

    /// Validates cache semantics after direct public-field mutation.
    pub fn validate(&self) -> SoapResult<()> {
        match (self.visibility, self.max_age) {
            (CacheVisibility::NoStore, Some(_)) => Err(SoapError::validation(
                "no-store response cache policy cannot declare max age",
            )),
            (CacheVisibility::Private | CacheVisibility::Public, None) => Err(
                SoapError::validation("cacheable response policy requires max age"),
            ),
            (_, Some(max_age)) if max_age.is_zero() => Err(SoapError::validation(
                "response cache max age must be greater than zero",
            )),
            _ => Ok(()),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{num::NonZeroU32, time::Duration};

    use http::Method;

    use soaprs_auth::AuthorizationPolicy;

    use super::{
        CacheVisibility, CorsPolicy, RateLimitPolicy, RateLimitScope, ResponseCachePolicy,
        SecurityHeadersPolicy,
    };

    #[test]
    fn authorization_names_and_lists_are_validated() {
        assert!(AuthorizationPolicy::strategy("jwt").is_ok());
        assert!(AuthorizationPolicy::optional_strategy("session").is_ok());
        assert!(AuthorizationPolicy::all_permissions(["orders:read", "orders:write"]).is_ok());
        assert!(AuthorizationPolicy::any_role(Vec::<String>::new()).is_err());
        assert!(AuthorizationPolicy::named("bad policy name").is_err());
        assert!(!AuthorizationPolicy::Optional.requires_identity());
        assert!(AuthorizationPolicy::Optional.authenticates_when_present());
        assert!(!AuthorizationPolicy::Optional.allows_public_response_cache());
    }

    #[test]
    fn rate_limits_include_scope_and_burst_without_choosing_storage() {
        let Some(requests) = NonZeroU32::new(100) else {
            panic!("non-zero fixture");
        };
        let result = RateLimitPolicy::new(requests, Duration::from_secs(60)).map(|policy| {
            policy
                .scope(RateLimitScope::Principal)
                .burst(NonZeroU32::MIN)
        });
        assert!(result.is_ok());
    }

    #[test]
    fn cors_rejects_wildcard_credentials_and_non_origins() {
        let wildcard = CorsPolicy::any(vec![Method::GET]);
        assert!(wildcard.and_then(CorsPolicy::allow_credentials).is_err());
        assert!(CorsPolicy::exact(["https://example.com"], vec![Method::GET]).is_ok());
        assert!(CorsPolicy::exact(["https://example.com/path"], vec![Method::GET]).is_err());
        assert!(CorsPolicy::exact(["ftp://example.com"], vec![Method::GET]).is_err());
        assert!(CorsPolicy::exact(["https://user@example.com"], vec![Method::GET]).is_err());
    }

    #[test]
    fn public_policy_fields_are_revalidated_before_registration() {
        let Some(requests) = NonZeroU32::new(10) else {
            panic!("non-zero fixture");
        };
        let Some(mut rate_limit) = RateLimitPolicy::new(requests, Duration::from_secs(1)).ok()
        else {
            panic!("valid rate limit");
        };
        rate_limit.period = Duration::ZERO;
        assert!(rate_limit.validate().is_err());

        let mut cors = CorsPolicy::any(vec![Method::GET]).unwrap_or_else(|error| {
            panic!("valid CORS fixture failed: {error}");
        });
        cors.allow_credentials = true;
        assert!(cors.validate().is_err());

        let mut cache = ResponseCachePolicy::no_store();
        cache.visibility = CacheVisibility::Public;
        assert!(cache.validate().is_err());

        let mut headers = SecurityHeadersPolicy::secure_defaults();
        headers.content_security_policy = Some("\r\ninjected: true".to_owned());
        assert!(headers.validate().is_err());
    }
}