tako-rs-plugins 2.0.0

Internal plugin and concrete-middleware implementations for tako-rs. Use the `tako-rs` umbrella crate instead.
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
#![cfg_attr(docsrs, doc(cfg(feature = "plugins")))]
//! Cross-Origin Resource Sharing (CORS) plugin for handling cross-origin HTTP requests.
//!
//! This module provides comprehensive CORS support for Tako web applications, enabling
//! secure cross-origin resource sharing between different domains. The plugin handles
//! preflight OPTIONS requests, validates origins against configured policies, and adds
//! appropriate CORS headers to responses. It supports configurable origins, methods,
//! headers, credentials, and cache control for flexible cross-origin access policies.
//!
//! The CORS plugin can be applied at both router-level (all routes) and route-level
//! (specific routes), allowing fine-grained control over CORS policies.
//!
//! # Examples
//!
//! ```rust
//! use tako::plugins::cors::{CorsPlugin, CorsBuilder};
//! use tako::plugins::TakoPlugin;
//! use tako::router::Router;
//! use http::Method;
//!
//! async fn api_handler(_req: tako::types::Request) -> &'static str {
//!     "API response"
//! }
//!
//! async fn public_handler(_req: tako::types::Request) -> &'static str {
//!     "Public response"
//! }
//!
//! let mut router = Router::new();
//!
//! // Router-level: Basic CORS setup allowing all origins (applied to all routes)
//! let global_cors = CorsBuilder::new().build();
//! router.plugin(global_cors);
//!
//! // Route-level: Restrictive CORS for specific API endpoint
//! let api_route = router.route(Method::GET, "/api/data", api_handler);
//! let api_cors = CorsBuilder::new()
//!     .allow_origin("https://app.example.com")
//!     .allow_origin("https://admin.example.com")
//!     .allow_methods(&[Method::GET, Method::POST, Method::PUT])
//!     .allow_credentials(true)
//!     .max_age_secs(86400)
//!     .build();
//! api_route.plugin(api_cors);
//!
//! // Another route without CORS restrictions (uses global if set)
//! router.route(Method::GET, "/public", public_handler);
//! ```

use std::fmt;
use std::sync::Arc;

use anyhow::Result;
use http::HeaderName;
use http::HeaderValue;
use http::Method;
use http::StatusCode;
use http::header::ACCESS_CONTROL_ALLOW_CREDENTIALS;
use http::header::ACCESS_CONTROL_ALLOW_HEADERS;
use http::header::ACCESS_CONTROL_ALLOW_METHODS;
use http::header::ACCESS_CONTROL_ALLOW_ORIGIN;
use http::header::ACCESS_CONTROL_MAX_AGE;
use http::header::ACCESS_CONTROL_REQUEST_HEADERS;
use http::header::ACCESS_CONTROL_REQUEST_METHOD;
use http::header::ORIGIN;
use http::header::VARY;
use tako_rs_core::body::TakoBody;
use tako_rs_core::middleware::Next;
use tako_rs_core::plugins::TakoPlugin;
use tako_rs_core::responder::Responder;
use tako_rs_core::router::Router;
use tako_rs_core::types::Request;
use tako_rs_core::types::Response;

/// Origin matching mode.
#[derive(Clone)]
pub enum OriginMatcher {
  /// Exact match (current default).
  Exact(String),
  /// Suffix match — `acme.example.com` matches origin `https://api.acme.example.com`.
  Suffix(String),
  /// Custom predicate. Receives the verbatim `Origin` header value.
  Custom(Arc<dyn Fn(&str) -> bool + Send + Sync + 'static>),
}

impl OriginMatcher {
  fn matches(&self, origin: &str) -> bool {
    match self {
      Self::Exact(s) => s == origin,
      Self::Suffix(s) => {
        // PPL-20: parse the host with `url::Url` instead of the prior
        // `split('/').nth(2).split(':')` chain, which mishandled
        // trailing slashes (Origin headers should not have them, but
        // browsers occasionally do), IPv6 literals like
        // `https://[::1]:8443` (the `split(':')` would chop the literal
        // mid-address), and userinfo like `https://user@example.com`
        // (the host would have leaked the userinfo prefix).
        let host = url::Url::parse(origin)
          .ok()
          .and_then(|u| u.host_str().map(str::to_owned))
          .unwrap_or_default();
        if host.is_empty() {
          return false;
        }
        host == *s.as_str() || host.ends_with(&format!(".{s}"))
      }
      Self::Custom(f) => f(origin),
    }
  }
}

impl<S: Into<String>> From<S> for OriginMatcher {
  fn from(value: S) -> Self {
    Self::Exact(value.into())
  }
}

/// CORS policy configuration settings for cross-origin request handling.
///
/// `Config` defines the Cross-Origin Resource Sharing policy including allowed origins,
/// HTTP methods, headers, credential handling, and preflight cache duration. The
/// configuration determines which cross-origin requests are permitted and what headers
/// are added to responses to enable secure cross-origin communication.
///
/// # Examples
///
/// ```rust
/// use tako::plugins::cors::Config;
/// use http::{Method, HeaderName};
///
/// let config = Config {
///     origins: vec!["https://app.example.com".to_string()],
///     methods: vec![Method::GET, Method::POST],
///     headers: vec![HeaderName::from_static("x-api-key")],
///     allow_credentials: true,
///     max_age_secs: Some(3600),
/// };
/// ```
#[derive(Clone)]
pub struct Config {
  /// Exact origin allow-list (legacy). For wider matching, use [`Self::origin_matchers`].
  pub origins: Vec<String>,
  /// Suffix / regex / custom origin matchers (additive on top of `origins`).
  pub origin_matchers: Vec<OriginMatcher>,
  /// List of allowed HTTP methods for cross-origin requests.
  pub methods: Vec<Method>,
  /// List of allowed request headers for cross-origin requests.
  pub headers: Vec<HeaderName>,
  /// Whether to allow credentials (cookies, authorization headers) in cross-origin requests.
  pub allow_credentials: bool,
  /// Maximum age in seconds for preflight request caching by browsers.
  pub max_age_secs: Option<u32>,
  /// Send `Access-Control-Allow-Private-Network: true` in preflight responses
  /// when the client signals `Access-Control-Request-Private-Network: true`.
  /// Required for browsers to allow public→private requests post Chrome 104.
  pub allow_private_network: bool,
}

impl Default for Config {
  /// Provides permissive default CORS configuration suitable for development.
  fn default() -> Self {
    Self {
      origins: Vec::new(),
      origin_matchers: Vec::new(),
      methods: vec![
        Method::GET,
        Method::POST,
        Method::PUT,
        Method::PATCH,
        Method::DELETE,
        Method::OPTIONS,
      ],
      headers: Vec::new(),
      allow_credentials: false,
      max_age_secs: Some(3600),
      allow_private_network: false,
    }
  }
}

impl Config {
  /// Validates the CORS configuration against the Fetch spec's hard rules.
  ///
  /// Returns an error if the configuration would produce a header combination that
  /// browsers reject (e.g. `Access-Control-Allow-Origin: *` together with
  /// `Access-Control-Allow-Credentials: true`).
  pub fn validate(&self) -> Result<(), CorsConfigError> {
    if self.allow_credentials && self.origins.is_empty() && self.origin_matchers.is_empty() {
      return Err(CorsConfigError::CredentialsWithWildcardOrigin);
    }
    Ok(())
  }

  fn origin_allowed(&self, origin: &str) -> bool {
    self.origins.iter().any(|p| p == origin)
      || self.origin_matchers.iter().any(|m| m.matches(origin))
  }
}

/// Errors produced when constructing an invalid [`CorsPlugin`] configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CorsConfigError {
  /// `allow_credentials = true` was combined with no explicit origins, which would
  /// produce `Access-Control-Allow-Origin: *` alongside `Access-Control-Allow-Credentials: true`.
  /// Browsers reject this combination per the Fetch spec.
  CredentialsWithWildcardOrigin,
}

impl fmt::Display for CorsConfigError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::CredentialsWithWildcardOrigin => f.write_str(
        "CORS misconfiguration: allow_credentials = true requires at least one explicit \
         allowed origin; reflecting `*` together with credentials is rejected by browsers",
      ),
    }
  }
}

impl std::error::Error for CorsConfigError {}

/// Builder for configuring CORS policies with a fluent API.
///
/// `CorsBuilder` provides a convenient way to construct CORS configurations using
/// method chaining. It starts with sensible defaults and allows selective customization
/// of origins, methods, headers, and other CORS policy aspects. The builder pattern
/// ensures all configuration is explicit while maintaining ease of use.
///
/// # Examples
///
/// ```rust
/// use tako::plugins::cors::CorsBuilder;
/// use http::{Method, HeaderName};
///
/// // Development setup - permissive CORS
/// let dev_cors = CorsBuilder::new()
///     .allow_credentials(false)
///     .build();
///
/// // Production setup - restrictive CORS
/// let prod_cors = CorsBuilder::new()
///     .allow_origin("https://app.mysite.com")
///     .allow_origin("https://admin.mysite.com")
///     .allow_methods(&[Method::GET, Method::POST])
///     .allow_headers(&[HeaderName::from_static("authorization")])
///     .allow_credentials(true)
///     .max_age_secs(86400)
///     .build();
/// ```
#[must_use]
pub struct CorsBuilder(Config);

impl Default for CorsBuilder {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

impl CorsBuilder {
  /// Creates a new CORS configuration builder with default settings.
  #[inline]
  pub fn new() -> Self {
    Self(Config::default())
  }

  /// Adds an allowed origin to the CORS policy.
  #[inline]
  pub fn allow_origin(mut self, o: impl Into<String>) -> Self {
    self.0.origins.push(o.into());
    self
  }

  /// Sets the allowed HTTP methods for cross-origin requests.
  #[inline]
  pub fn allow_methods(mut self, m: &[Method]) -> Self {
    self.0.methods = m.to_vec();
    self
  }

  /// Sets the allowed request headers for cross-origin requests.
  #[inline]
  pub fn allow_headers(mut self, h: &[HeaderName]) -> Self {
    self.0.headers = h.to_vec();
    self
  }

  /// Enables or disables credential sharing in cross-origin requests.
  #[inline]
  pub fn allow_credentials(mut self, allow: bool) -> Self {
    self.0.allow_credentials = allow;
    self
  }

  /// Sets the maximum age for preflight request caching.
  #[inline]
  pub fn max_age_secs(mut self, secs: u32) -> Self {
    self.0.max_age_secs = Some(secs);
    self
  }

  /// Adds a suffix-style origin match (e.g. `example.com` accepts every
  /// subdomain). Combine with [`Self::allow_origin`] for hybrid policies.
  #[inline]
  pub fn allow_origin_suffix(mut self, suffix: impl Into<String>) -> Self {
    self
      .0
      .origin_matchers
      .push(OriginMatcher::Suffix(suffix.into()));
    self
  }

  /// Plug a custom origin predicate.
  #[inline]
  pub fn allow_origin_predicate<F>(mut self, f: F) -> Self
  where
    F: Fn(&str) -> bool + Send + Sync + 'static,
  {
    self
      .0
      .origin_matchers
      .push(OriginMatcher::Custom(Arc::new(f)));
    self
  }

  /// Enables Private Network Access (Chrome PNA) preflight handling.
  #[inline]
  pub fn allow_private_network(mut self, yes: bool) -> Self {
    self.0.allow_private_network = yes;
    self
  }

  /// Builds the CORS plugin with the configured settings.
  ///
  /// # Panics
  ///
  /// Panics if [`Config::validate`] fails — typically when `allow_credentials = true`
  /// is combined with an empty origin list. Use [`CorsBuilder::try_build`] to handle
  /// the error explicitly.
  #[inline]
  pub fn build(self) -> CorsPlugin {
    self.try_build().expect("invalid CORS configuration")
  }

  /// Builds the CORS plugin, returning an error on invalid configuration instead of panicking.
  #[inline]
  pub fn try_build(self) -> Result<CorsPlugin, CorsConfigError> {
    self.0.validate()?;
    Ok(CorsPlugin { cfg: self.0 })
  }
}

/// CORS plugin for handling cross-origin resource sharing in Tako applications.
///
/// `CorsPlugin` implements the `TakoPlugin` trait to provide comprehensive CORS support
/// including preflight request handling, origin validation, and response header
/// management. It automatically handles OPTIONS preflight requests and adds appropriate
/// CORS headers to all responses based on the configured policy.
///
/// # Examples
///
/// ```rust
/// use tako::plugins::cors::{CorsPlugin, CorsBuilder};
/// use tako::plugins::TakoPlugin;
/// use tako::router::Router;
/// use http::Method;
///
/// // Basic setup with default permissive policy
/// let cors = CorsPlugin::default();
/// let mut router = Router::new();
/// router.plugin(cors);
///
/// // Custom restrictive policy for production
/// let prod_cors = CorsBuilder::new()
///     .allow_origin("https://myapp.com")
///     .allow_methods(&[Method::GET, Method::POST])
///     .allow_credentials(true)
///     .build();
/// router.plugin(prod_cors);
/// ```
#[derive(Clone)]
#[doc(alias = "cors")]
pub struct CorsPlugin {
  cfg: Config,
}

impl Default for CorsPlugin {
  /// Creates a CORS plugin with permissive default configuration.
  fn default() -> Self {
    Self {
      cfg: Config::default(),
    }
  }
}

impl TakoPlugin for CorsPlugin {
  /// Returns the plugin name for identification and debugging.
  fn name(&self) -> &'static str {
    "CorsPlugin"
  }

  /// Sets up the CORS plugin by registering middleware with the router.
  fn setup(&self, router: &Router) -> Result<()> {
    let cfg = self.cfg.clone();
    router.middleware(move |req, next| {
      let cfg = cfg.clone();
      async move { handle_cors(req, next, cfg).await }
    });
    Ok(())
  }
}

/// Handles CORS processing for incoming requests including preflight and actual requests.
async fn handle_cors(req: Request, next: Next, cfg: Config) -> impl Responder {
  let origin = req.headers().get(ORIGIN).cloned();
  let request_headers = req.headers().get(ACCESS_CONTROL_REQUEST_HEADERS).cloned();
  let pna_request = req
    .headers()
    .get("access-control-request-private-network")
    .and_then(|v| v.to_str().ok())
    .is_some_and(|v| v.eq_ignore_ascii_case("true"));

  // PPL-13: only short-circuit OPTIONS when it is an *actual* CORS preflight
  // (per Fetch spec: `Origin` + `Access-Control-Request-Method` headers).
  // The previous unconditional 204 intercepted legitimate non-CORS OPTIONS
  // handlers — capability discovery, `OPTIONS *` server-wide queries — and
  // returned an empty 204 with no `Allow` header in place of the handler's
  // response.
  let is_preflight = req.method() == Method::OPTIONS
    && origin.is_some()
    && req.headers().contains_key(ACCESS_CONTROL_REQUEST_METHOD);
  if is_preflight {
    let mut resp = http::Response::builder()
      .status(StatusCode::NO_CONTENT)
      .body(TakoBody::empty())
      .expect("valid CORS preflight response");
    add_cors_headers(
      &cfg,
      origin,
      request_headers.as_ref(),
      pna_request,
      &mut resp,
    );
    return resp.into_response();
  }

  let mut resp = next.run(req).await;
  add_cors_headers(&cfg, origin, request_headers.as_ref(), false, &mut resp);
  resp.into_response()
}

/// Adds CORS headers to HTTP responses based on configuration and request origin.
fn add_cors_headers(
  cfg: &Config,
  origin: Option<HeaderValue>,
  request_headers: Option<&HeaderValue>,
  pna_request: bool,
  resp: &mut Response,
) {
  // Origin validation and Access-Control-Allow-Origin header.
  //
  // Invariant guarded by `Config::validate`: when `allow_credentials = true`,
  // at least one origin or matcher is configured — so `*` is never emitted
  // alongside credentials.
  //
  // PPL-14:
  //  (a) `o.to_str().unwrap_or_default()` previously silenced invalid-byte
  //      Origin headers to empty-string, which then `origin_allowed("")`
  //      false'd, which silently emitted no header — attacker-malformed
  //      Origin hid the rejection from logs/metrics. Detect and bail
  //      cleanly instead.
  //  (b) `HeaderValue::from_str(&allow_origin).expect(...)` panicked if a
  //      mirrored origin contained CRLF/NUL (Origin reflection injection
  //      surface). Map the error to a silent bail so a malformed origin
  //      cannot crash the request task.
  let allow_anything = cfg.origins.is_empty() && cfg.origin_matchers.is_empty();
  let (allow_origin, mirrored_origin) = if allow_anything {
    ("*".to_string(), false)
  } else if let Some(o) = &origin {
    let Ok(s) = o.to_str() else {
      // Non-ASCII / control-byte Origin — bail cleanly.
      return;
    };
    if cfg.origin_allowed(s) {
      (s.to_string(), true)
    } else {
      return;
    }
  } else {
    return;
  };

  // Use the fallible API and bail on construction failure. The reflected
  // origin string is largely caller-controlled; even after the allow-list
  // check it may contain unexpected bytes if a custom matcher passes them.
  let Ok(value) = HeaderValue::from_str(&allow_origin) else {
    return;
  };
  resp
    .headers_mut()
    .insert(ACCESS_CONTROL_ALLOW_ORIGIN, value);

  // When the response varies on the request Origin (i.e. we mirrored it back),
  // shared caches must key on Origin to avoid cross-origin response leakage.
  if mirrored_origin {
    resp
      .headers_mut()
      .append(VARY, HeaderValue::from_static("Origin"));
  }

  // Access-Control-Allow-Methods header
  let methods = if cfg.methods.is_empty() {
    None
  } else {
    Some(
      cfg
        .methods
        .iter()
        .map(http::Method::as_str)
        .collect::<Vec<_>>()
        .join(","),
    )
  };
  if let Some(v) = methods
    && let Ok(hv) = HeaderValue::from_str(&v)
  {
    resp.headers_mut().insert(ACCESS_CONTROL_ALLOW_METHODS, hv);
  }

  // Access-Control-Allow-Headers header.
  //
  // `*` is invalid in any "Allow-*" header when `Access-Control-Allow-Credentials: true`
  // (Fetch spec). Two strategies when no explicit list is configured:
  //   - credentials disallowed: emit `*` (browsers accept it).
  //   - credentials allowed: reflect the request's `Access-Control-Request-Headers`
  //     so the preflight succeeds without a footgun.
  if cfg.headers.is_empty() {
    if cfg.allow_credentials {
      // Security best-practice: with `Access-Control-Allow-Credentials: true`
      // the allow-list should be an explicit, server-controlled set. The
      // pre-flight `Access-Control-Request-Headers` value is attacker-
      // influenced; reflecting it blindly lets a compromised origin probe
      // any header against the credentialed endpoint. Emit a one-time
      // warning and continue with the legacy reflection for BC — apps
      // should set explicit `headers(...)` to silence this.
      static WARNED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
      let () = WARNED.get_or_init(|| {
        tracing::warn!(
          "CORS reflects `Access-Control-Request-Headers` while `allow_credentials=true` and no explicit `headers(...)` list is configured — set an explicit allow-list to harden the preflight policy",
        );
      });
      if let Some(req_h) = request_headers {
        resp
          .headers_mut()
          .insert(ACCESS_CONTROL_ALLOW_HEADERS, req_h.clone());
        resp.headers_mut().append(
          VARY,
          HeaderValue::from_static("Access-Control-Request-Headers"),
        );
      }
      // No `Access-Control-Request-Headers` to reflect → emit nothing.
    } else {
      resp
        .headers_mut()
        .insert(ACCESS_CONTROL_ALLOW_HEADERS, HeaderValue::from_static("*"));
    }
  } else {
    let h = cfg
      .headers
      .iter()
      .map(http::HeaderName::as_str)
      .collect::<Vec<_>>()
      .join(",");
    if let Ok(hv) = HeaderValue::from_str(&h) {
      resp.headers_mut().insert(ACCESS_CONTROL_ALLOW_HEADERS, hv);
    }
  }

  // Access-Control-Allow-Credentials header
  if cfg.allow_credentials {
    resp.headers_mut().insert(
      ACCESS_CONTROL_ALLOW_CREDENTIALS,
      HeaderValue::from_static("true"),
    );
  }

  // Access-Control-Max-Age header
  if let Some(secs) = cfg.max_age_secs
    && let Ok(hv) = HeaderValue::from_str(&secs.to_string())
  {
    resp.headers_mut().insert(ACCESS_CONTROL_MAX_AGE, hv);
  }

  // Private Network Access (PNA) — emit only on preflight responses where
  // the client signaled the request bit. Doing so on regular responses is a
  // spec violation.
  if cfg.allow_private_network && pna_request {
    resp.headers_mut().insert(
      "access-control-allow-private-network",
      HeaderValue::from_static("true"),
    );
  }
}