Skip to main content

hyperlane_plugin_cors/
impl.rs

1use super::*;
2
3/// Debug formatting for [`AllowOrigin`].
4impl Debug for AllowOrigin {
5    /// Formats the [`AllowOrigin`] policy without requiring `Debug` on closures.
6    ///
7    /// # Arguments
8    ///
9    /// - `&mut Formatter<'_>` - Output formatter.
10    ///
11    /// # Returns
12    ///
13    /// - `fmt::Result` - Formatting outcome.
14    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15        match self {
16            Self::Any => f.write_str(DEBUG_ALLOW_ORIGIN_ANY),
17            Self::Exact(set) => f.debug_tuple(DEBUG_ALLOW_ORIGIN_EXACT).field(set).finish(),
18            Self::Suffix(list) => f
19                .debug_tuple(DEBUG_ALLOW_ORIGIN_SUFFIX)
20                .field(list)
21                .finish(),
22            Self::Custom(_) => f.write_str(DEBUG_ALLOW_ORIGIN_CUSTOM),
23        }
24    }
25}
26
27/// Inherent helpers for [`AllowOrigin`].
28impl AllowOrigin {
29    /// Constructs an `O(1)` exact-origin allowlist (stored lowercased for case-insensitive matching).
30    ///
31    /// # Arguments
32    ///
33    /// - `I` - Iterator of allowed origin strings (for example `"https://app.example.com"`).
34    ///
35    /// # Returns
36    ///
37    /// - `Self` - Exact-match allowlist policy.
38    pub fn exact<I, S>(origins: I) -> Self
39    where
40        I: IntoIterator<Item = S>,
41        S: AsRef<str>,
42    {
43        let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
44        for origin in origins {
45            let normalized: String = origin.as_ref().trim().to_ascii_lowercase();
46            if !normalized.is_empty() {
47                set.insert(normalized);
48            }
49        }
50        Self::Exact(set)
51    }
52
53    /// Constructs a host suffix matcher (for example `[".example.com"]`).
54    ///
55    /// # Arguments
56    ///
57    /// - `I` - Iterator of allowed domain suffixes.
58    ///
59    /// # Returns
60    ///
61    /// - `Self` - Suffix-match policy.
62    pub fn suffix<I, S>(suffixes: I) -> Self
63    where
64        I: IntoIterator<Item = S>,
65        S: AsRef<str>,
66    {
67        let list: Vec<String> = suffixes
68            .into_iter()
69            .map(|item: S| item.as_ref().trim().to_ascii_lowercase())
70            .filter(|item: &String| !item.is_empty())
71            .collect();
72        Self::Suffix(list)
73    }
74
75    /// Constructs a custom predicate-based origin matcher.
76    ///
77    /// # Arguments
78    ///
79    /// - `F` - Thread-safe predicate receiving the raw `Origin` header value.
80    ///
81    /// # Returns
82    ///
83    /// - `Self` - Predicate policy.
84    pub fn custom<F>(predicate: F) -> Self
85    where
86        F: Fn(&str) -> bool + Send + Sync + 'static,
87    {
88        Self::Custom(Arc::new(predicate))
89    }
90
91    /// Reports whether `origin` is permitted by this policy.
92    ///
93    /// # Arguments
94    ///
95    /// - `&str` - Incoming `Origin` header value.
96    ///
97    /// # Returns
98    ///
99    /// - `bool` - `true` when `origin` is allowed.
100    #[inline]
101    pub fn is_allowed(&self, origin: &str) -> bool {
102        let trimmed: &str = origin.trim();
103        if trimmed.is_empty() {
104            return false;
105        }
106        match self {
107            Self::Any => true,
108            Self::Exact(set) => {
109                if set.contains(trimmed) {
110                    return true;
111                }
112                let bytes: &[u8] = trimmed.as_bytes();
113                if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
114                    return false;
115                }
116                if bytes.len() <= ORIGIN_LOWER_STACK_CAP {
117                    let mut stack: [u8; ORIGIN_LOWER_STACK_CAP] = [0u8; ORIGIN_LOWER_STACK_CAP];
118                    let mut i: usize = 0;
119                    while i < bytes.len() {
120                        stack[i] = bytes[i].to_ascii_lowercase();
121                        i += 1;
122                    }
123                    if let Ok(lower) = from_utf8(&stack[..bytes.len()]) {
124                        return set.contains(lower);
125                    }
126                }
127                set.contains(&trimmed.to_ascii_lowercase())
128            }
129            Self::Suffix(suffixes) => {
130                let host: &str = extract_origin_host(trimmed);
131                if host.is_empty() {
132                    return false;
133                }
134                suffixes.iter().any(|suffix: &String| {
135                    if let Some(bare) = suffix.strip_prefix('.') {
136                        host.eq_ignore_ascii_case(bare)
137                            || ends_with_ignore_ascii_case(host, suffix.as_str())
138                    } else {
139                        host.eq_ignore_ascii_case(suffix.as_str())
140                    }
141                })
142            }
143            Self::Custom(matcher) => matcher(trimmed),
144        }
145    }
146}
147
148/// Default construction for [`CorsConfig`].
149impl Default for CorsConfig {
150    /// Constructs a conservative default [`CorsConfig`] allowing any origin without credentials.
151    fn default() -> Self {
152        Self {
153            allow_origin: AllowOrigin::Any,
154            allow_methods: DEFAULT_ALLOWED_METHODS
155                .iter()
156                .map(|method: &&str| (*method).to_owned())
157                .collect(),
158            allow_headers: DEFAULT_ALLOWED_HEADERS
159                .iter()
160                .map(|header: &&str| (*header).to_owned())
161                .collect(),
162            expose_headers: Vec::new(),
163            allow_credentials: false,
164            max_age_secs: Some(DEFAULT_CORS_MAX_AGE_SECS),
165            allow_private_network: false,
166        }
167    }
168}
169
170/// Inherent builders and presets for [`CorsConfig`].
171impl CorsConfig {
172    /// Builds a permissive development policy allowing any origin, method, and header.
173    ///
174    /// # Returns
175    ///
176    /// - `Self` - Permissive CORS configuration.
177    pub fn permissive() -> Self {
178        Self {
179            allow_origin: AllowOrigin::Any,
180            allow_methods: DEFAULT_ALLOWED_METHODS
181                .iter()
182                .map(|method: &&str| (*method).to_owned())
183                .collect(),
184            allow_headers: vec![CORS_WILDCARD.to_owned()],
185            expose_headers: Vec::new(),
186            allow_credentials: false,
187            max_age_secs: Some(DEFAULT_CORS_MAX_AGE_SECS),
188            allow_private_network: false,
189        }
190    }
191
192    /// Builds a strict allowlist policy accepting only the specified origins.
193    ///
194    /// # Arguments
195    ///
196    /// - `I` - Iterator of exact origin strings.
197    ///
198    /// # Returns
199    ///
200    /// - `Self` - Strict CORS configuration.
201    pub fn strict<I, S>(origins: I) -> Self
202    where
203        I: IntoIterator<Item = S>,
204        S: AsRef<str>,
205    {
206        Self::default().with_allow_origin(AllowOrigin::exact(origins))
207    }
208
209    /// Sets the [`AllowOrigin`] policy.
210    ///
211    /// # Arguments
212    ///
213    /// - `AllowOrigin` - Desired origin matching policy.
214    ///
215    /// # Returns
216    ///
217    /// - `Self` - Updated configuration.
218    pub fn with_allow_origin(mut self, allow_origin: AllowOrigin) -> Self {
219        self.set_allow_origin(allow_origin);
220        self
221    }
222
223    /// Sets the allowed HTTP methods for preflight responses.
224    ///
225    /// # Arguments
226    ///
227    /// - `I` - Iterator of HTTP method names.
228    ///
229    /// # Returns
230    ///
231    /// - `Self` - Updated configuration.
232    pub fn with_allow_methods<I, S>(mut self, methods: I) -> Self
233    where
234        I: IntoIterator<Item = S>,
235        S: Into<String>,
236    {
237        self.set_allow_methods(methods.into_iter().map(Into::into).collect());
238        self
239    }
240
241    /// Sets the allowed request headers for preflight responses.
242    ///
243    /// # Arguments
244    ///
245    /// - `I` - Iterator of header names.
246    ///
247    /// # Returns
248    ///
249    /// - `Self` - Updated configuration.
250    pub fn with_allow_headers<I, S>(mut self, headers: I) -> Self
251    where
252        I: IntoIterator<Item = S>,
253        S: Into<String>,
254    {
255        self.set_allow_headers(headers.into_iter().map(Into::into).collect());
256        self
257    }
258
259    /// Sets the response headers exposed to cross-origin clients.
260    ///
261    /// # Arguments
262    ///
263    /// - `I` - Iterator of exposed header names.
264    ///
265    /// # Returns
266    ///
267    /// - `Self` - Updated configuration.
268    pub fn with_expose_headers<I, S>(mut self, headers: I) -> Self
269    where
270        I: IntoIterator<Item = S>,
271        S: Into<String>,
272    {
273        self.set_expose_headers(headers.into_iter().map(Into::into).collect());
274        self
275    }
276
277    /// Enables or disables `Access-Control-Allow-Credentials: true`.
278    ///
279    /// # Arguments
280    ///
281    /// - `bool` - Whether credentials may be sent cross-origin.
282    ///
283    /// # Returns
284    ///
285    /// - `Self` - Updated configuration.
286    pub fn with_allow_credentials(mut self, allow_credentials: bool) -> Self {
287        self.set_allow_credentials(allow_credentials);
288        self
289    }
290
291    /// Configures the `Access-Control-Max-Age` cache duration in seconds.
292    ///
293    /// # Arguments
294    ///
295    /// - `Option<u64>` - Optional cache lifetime in seconds.
296    ///
297    /// # Returns
298    ///
299    /// - `Self` - Updated configuration.
300    pub fn with_max_age_secs(mut self, max_age_secs: Option<u64>) -> Self {
301        self.set_max_age_secs(max_age_secs);
302        self
303    }
304
305    /// Enables or disables `Access-Control-Allow-Private-Network: true` responses.
306    ///
307    /// # Arguments
308    ///
309    /// - `bool` - Whether private-network preflight requests are approved.
310    ///
311    /// # Returns
312    ///
313    /// - `Self` - Updated configuration.
314    pub fn with_allow_private_network(mut self, allow_private_network: bool) -> Self {
315        self.set_allow_private_network(allow_private_network);
316        self
317    }
318}
319
320/// Inherent implementation of [`CompiledCors`].
321impl CompiledCors {
322    /// Precompiles a [`CorsConfig`] into zero-allocation header values.
323    ///
324    /// # Arguments
325    ///
326    /// - `CorsConfig` - Source CORS configuration.
327    ///
328    /// # Returns
329    ///
330    /// - `Self` - Precompiled policy ready for hot-path request evaluation.
331    pub fn compile(config: CorsConfig) -> Self {
332        let exact_small: Option<Box<[String]>> = match config.get_allow_origin() {
333            AllowOrigin::Exact(set) if set.len() <= CORS_SMALL_EXACT_LIMIT => {
334                let items: Vec<String> = set.iter().cloned().collect();
335                Some(items.into_boxed_slice())
336            }
337            _ => None,
338        };
339        let is_any_wildcard: bool = matches!(config.get_allow_origin(), AllowOrigin::Any)
340            && !config.get_allow_credentials();
341        let raw_methods: String = config.get_allow_methods().join(COMMA_SPACE);
342        let methods_header: String = if is_valid_cors_header_value(&raw_methods) {
343            raw_methods
344        } else {
345            String::new()
346        };
347        let mirror_headers: bool = should_mirror_request_headers(config.get_allow_headers());
348        let headers_header: Option<String> = if mirror_headers {
349            None
350        } else {
351            let joined: String = config.get_allow_headers().join(COMMA_SPACE);
352            if is_valid_cors_header_value(&joined) {
353                Some(joined)
354            } else {
355                None
356            }
357        };
358        let expose_header: Option<String> = if config.get_expose_headers().is_empty() {
359            None
360        } else {
361            let joined: String = config.get_expose_headers().join(COMMA_SPACE);
362            if is_valid_cors_header_value(&joined) {
363                Some(joined)
364            } else {
365                None
366            }
367        };
368        let max_age_header: Option<String> = config
369            .try_get_max_age_secs()
370            .map(|secs: u64| secs.to_string());
371        let vary_origin: bool = !is_any_wildcard;
372        let mut preflight_lines: Vec<u8> = Vec::with_capacity(256);
373        if config.get_allow_credentials() {
374            preflight_lines.extend_from_slice(ACCESS_CONTROL_ALLOW_CREDENTIALS.as_bytes());
375            preflight_lines.extend_from_slice(PREFLIGHT_WIRE_COLON_SPACE);
376            preflight_lines.extend_from_slice(HEADER_VALUE_TRUE.as_bytes());
377            preflight_lines.extend_from_slice(PREFLIGHT_WIRE_CRLF);
378        }
379        if !methods_header.is_empty() {
380            preflight_lines.extend_from_slice(ACCESS_CONTROL_ALLOW_METHODS.as_bytes());
381            preflight_lines.extend_from_slice(PREFLIGHT_WIRE_COLON_SPACE);
382            preflight_lines.extend_from_slice(methods_header.as_bytes());
383            preflight_lines.extend_from_slice(PREFLIGHT_WIRE_CRLF);
384        }
385        if let Some(ref fixed_headers) = headers_header {
386            preflight_lines.extend_from_slice(ACCESS_CONTROL_ALLOW_HEADERS.as_bytes());
387            preflight_lines.extend_from_slice(PREFLIGHT_WIRE_COLON_SPACE);
388            preflight_lines.extend_from_slice(fixed_headers.as_bytes());
389            preflight_lines.extend_from_slice(PREFLIGHT_WIRE_CRLF);
390        }
391        if let Some(ref max_age) = max_age_header {
392            preflight_lines.extend_from_slice(ACCESS_CONTROL_MAX_AGE.as_bytes());
393            preflight_lines.extend_from_slice(PREFLIGHT_WIRE_COLON_SPACE);
394            preflight_lines.extend_from_slice(max_age.as_bytes());
395            preflight_lines.extend_from_slice(PREFLIGHT_WIRE_CRLF);
396        }
397        preflight_lines.extend_from_slice(VARY.as_bytes());
398        preflight_lines.extend_from_slice(PREFLIGHT_WIRE_COLON_SPACE);
399        let preflight_vary: &str = if vary_origin {
400            VARY_PREFLIGHT_WITH_ORIGIN
401        } else {
402            VARY_PREFLIGHT_WITHOUT_ORIGIN
403        };
404        preflight_lines.extend_from_slice(preflight_vary.as_bytes());
405        preflight_lines.extend_from_slice(PREFLIGHT_WIRE_CRLF);
406        Self {
407            config,
408            exact_small,
409            is_any_wildcard,
410            methods_header,
411            mirror_headers,
412            headers_header,
413            expose_header,
414            max_age_header,
415            preflight_static_lines: preflight_lines.into_boxed_slice(),
416            vary_origin,
417        }
418    }
419
420    /// Returns the source [`CorsConfig`].
421    ///
422    /// # Returns
423    ///
424    /// - `&CorsConfig` - Active CORS configuration.
425    #[inline(always)]
426    pub fn get_config(&self) -> &CorsConfig {
427        &self.config
428    }
429
430    /// Resolves the `Access-Control-Allow-Origin` header value for an incoming `Origin`.
431    ///
432    /// Never returns `"*"` when `allow_credentials` is `true`, satisfying the Fetch specification.
433    ///
434    /// # Arguments
435    ///
436    /// - `&'a str` - Incoming `Origin` header value.
437    ///
438    /// # Returns
439    ///
440    /// - `Option<&'a str>` - Header value to emit, or `None` when the origin is rejected.
441    #[inline]
442    pub fn resolve_origin<'a>(&self, origin: &'a str) -> Option<&'a str> {
443        let Self {
444            config,
445            exact_small,
446            is_any_wildcard,
447            ..
448        } = self;
449        let trimmed: &'a str = origin.trim();
450        if trimmed.is_empty() {
451            return None;
452        }
453        if *is_any_wildcard {
454            return Some(CORS_WILDCARD);
455        }
456        if let Some(small) = exact_small {
457            let t_len: usize = trimmed.len();
458            for allowed in small.iter() {
459                if allowed.len() == t_len && allowed.eq_ignore_ascii_case(trimmed) {
460                    return Some(trimmed);
461                }
462            }
463            return None;
464        }
465        if !config.get_allow_origin().is_allowed(trimmed) {
466            return None;
467        }
468        Some(trimmed)
469    }
470
471    /// Applies CORS headers to `ctx`, returning `true` when `ctx` was answered as a preflight request.
472    ///
473    /// # Arguments
474    ///
475    /// - `&mut Context` - Incoming request and outgoing response context.
476    ///
477    /// # Returns
478    ///
479    /// - `bool` - `true` when a preflight `OPTIONS` response was populated and ready to send.
480    pub fn apply_request(&self, ctx: &mut Context) -> bool {
481        let Self {
482            config,
483            methods_header,
484            mirror_headers,
485            headers_header,
486            expose_header,
487            max_age_header,
488            vary_origin,
489            ..
490        } = self;
491        let allow_credentials: bool = config.get_allow_credentials();
492        let Some(origin) = request_header_back(ctx.get_request(), ORIGIN) else {
493            return false;
494        };
495        let Some(allow_origin_val) = self.resolve_origin(origin) else {
496            return false;
497        };
498        let is_wildcard: bool = allow_origin_val == CORS_WILDCARD;
499        let mut origin_stack: [u8; ORIGIN_LOWER_STACK_CAP] = [0u8; ORIGIN_LOWER_STACK_CAP];
500        let mut origin_stack_len: usize = 0;
501        let mut origin_heap: Option<String> = None;
502        if !is_wildcard {
503            let raw_bytes: &[u8] = allow_origin_val.as_bytes();
504            if raw_bytes.len() <= ORIGIN_LOWER_STACK_CAP {
505                origin_stack[..raw_bytes.len()].copy_from_slice(raw_bytes);
506                origin_stack_len = raw_bytes.len();
507            } else {
508                origin_heap = Some(allow_origin_val.to_owned());
509            }
510        }
511        let req: &Request = ctx.get_request();
512        let is_preflight: bool = req.get_method().is_options()
513            && req
514                .get_headers()
515                .contains_key(ACCESS_CONTROL_REQUEST_METHOD);
516        let req_headers: Option<String> = if is_preflight && *mirror_headers {
517            request_header_back(req, ACCESS_CONTROL_REQUEST_HEADERS).map(str::to_owned)
518        } else {
519            None
520        };
521        let wants_private_net: bool = is_preflight
522            && config.get_allow_private_network()
523            && request_header_back(req, ACCESS_CONTROL_REQUEST_PRIVATE_NETWORK)
524                .is_some_and(|val: &str| val.trim().eq_ignore_ascii_case(HEADER_VALUE_TRUE));
525        let allow_origin_str: &str = if is_wildcard {
526            CORS_WILDCARD
527        } else if let Some(ref owned) = origin_heap {
528            owned.as_str()
529        } else {
530            from_utf8(&origin_stack[..origin_stack_len]).unwrap_or_default()
531        };
532        let response: &mut Response = ctx.get_mut_response();
533        if response.get_headers().is_empty() {
534            if is_preflight {
535                if is_wildcard || is_valid_cors_header_value(allow_origin_str) {
536                    response.set_header(ACCESS_CONTROL_ALLOW_ORIGIN, allow_origin_str);
537                }
538                if allow_credentials {
539                    response.set_header(ACCESS_CONTROL_ALLOW_CREDENTIALS, HEADER_VALUE_TRUE);
540                }
541                if !methods_header.is_empty() {
542                    response.set_header(ACCESS_CONTROL_ALLOW_METHODS, methods_header.as_str());
543                }
544                if let Some(fixed_headers) = headers_header {
545                    response.set_header(ACCESS_CONTROL_ALLOW_HEADERS, fixed_headers.as_str());
546                } else if let Some(requested) = req_headers
547                    && is_valid_cors_header_value(&requested)
548                {
549                    response.set_header(ACCESS_CONTROL_ALLOW_HEADERS, requested.as_str());
550                }
551                if let Some(max_age) = max_age_header {
552                    response.set_header(ACCESS_CONTROL_MAX_AGE, max_age.as_str());
553                }
554                if wants_private_net {
555                    response.set_header(ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK, HEADER_VALUE_TRUE);
556                }
557                let preflight_vary: &str = if *vary_origin {
558                    VARY_PREFLIGHT_WITH_ORIGIN
559                } else {
560                    VARY_PREFLIGHT_WITHOUT_ORIGIN
561                };
562                response.set_header(VARY, preflight_vary);
563                response
564                    .set_status_code(HttpStatus::NoContent.code())
565                    .set_body(&[] as &[u8]);
566                return true;
567            }
568            let mut batch: [(&str, &str); 4] = [("", ""); 4];
569            let mut batch_len: usize = 0;
570            if is_wildcard || is_valid_cors_header_value(allow_origin_str) {
571                batch[batch_len] = (ACCESS_CONTROL_ALLOW_ORIGIN, allow_origin_str);
572                batch_len += 1;
573            }
574            if allow_credentials {
575                batch[batch_len] = (ACCESS_CONTROL_ALLOW_CREDENTIALS, HEADER_VALUE_TRUE);
576                batch_len += 1;
577            }
578            if *vary_origin {
579                batch[batch_len] = (VARY, VARY_ORIGIN);
580                batch_len += 1;
581            }
582            if let Some(expose) = expose_header {
583                batch[batch_len] = (ACCESS_CONTROL_EXPOSE_HEADERS, expose.as_str());
584                batch_len += 1;
585            }
586            response.set_headers_batch(&batch[..batch_len]);
587            return false;
588        }
589        response.set_header(ACCESS_CONTROL_ALLOW_ORIGIN, allow_origin_str);
590        if allow_credentials {
591            response.set_header(ACCESS_CONTROL_ALLOW_CREDENTIALS, HEADER_VALUE_TRUE);
592        }
593        if is_preflight {
594            if !methods_header.is_empty() {
595                response.set_header(ACCESS_CONTROL_ALLOW_METHODS, methods_header);
596            }
597            if let Some(fixed_headers) = headers_header {
598                response.set_header(ACCESS_CONTROL_ALLOW_HEADERS, fixed_headers);
599            } else if let Some(requested) = req_headers {
600                response.set_header(ACCESS_CONTROL_ALLOW_HEADERS, requested);
601            }
602            if let Some(max_age) = max_age_header {
603                response.set_header(ACCESS_CONTROL_MAX_AGE, max_age);
604            }
605            if wants_private_net {
606                response.set_header(ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK, HEADER_VALUE_TRUE);
607            }
608            if !response.has_header(VARY) {
609                let preflight_vary: &str = if *vary_origin {
610                    VARY_PREFLIGHT_WITH_ORIGIN
611                } else {
612                    VARY_PREFLIGHT_WITHOUT_ORIGIN
613                };
614                response.set_header(VARY, preflight_vary);
615            } else {
616                if *vary_origin {
617                    merge_vary_header(response, VARY_ORIGIN);
618                }
619                merge_vary_header(response, VARY_PREFLIGHT_METHOD);
620                merge_vary_header(response, VARY_PREFLIGHT_HEADERS);
621            }
622            response
623                .set_status_code(HttpStatus::NoContent.code())
624                .set_body(&[] as &[u8]);
625            return true;
626        }
627        if *vary_origin {
628            merge_vary_header(response, VARY_ORIGIN);
629        }
630        if let Some(expose) = expose_header {
631            response.set_header(ACCESS_CONTROL_EXPOSE_HEADERS, expose);
632        }
633        false
634    }
635
636    /// Re-applies CORS headers on the response path if a route cleared response headers.
637    ///
638    /// # Arguments
639    ///
640    /// - `&mut Context` - Active request/response context.
641    #[inline]
642    pub fn ensure_response_headers(&self, ctx: &mut Context) {
643        if ctx.get_response().has_header(ACCESS_CONTROL_ALLOW_ORIGIN) {
644            return;
645        }
646        let Self {
647            config,
648            expose_header,
649            vary_origin,
650            ..
651        } = self;
652        let allow_credentials: bool = config.get_allow_credentials();
653        let Some(origin) = request_header_back(ctx.get_request(), ORIGIN) else {
654            return;
655        };
656        let Some(allow_origin_val) = self.resolve_origin(origin) else {
657            return;
658        };
659        let is_wildcard: bool = allow_origin_val == CORS_WILDCARD;
660        let mut origin_stack: [u8; ORIGIN_LOWER_STACK_CAP] = [0u8; ORIGIN_LOWER_STACK_CAP];
661        let mut origin_stack_len: usize = 0;
662        let mut origin_heap: Option<String> = None;
663        if !is_wildcard {
664            let raw_bytes: &[u8] = allow_origin_val.as_bytes();
665            if raw_bytes.len() <= ORIGIN_LOWER_STACK_CAP {
666                origin_stack[..raw_bytes.len()].copy_from_slice(raw_bytes);
667                origin_stack_len = raw_bytes.len();
668            } else {
669                origin_heap = Some(allow_origin_val.to_owned());
670            }
671        }
672        let allow_origin_str: &str = if is_wildcard {
673            CORS_WILDCARD
674        } else if let Some(ref owned) = origin_heap {
675            owned.as_str()
676        } else {
677            from_utf8(&origin_stack[..origin_stack_len]).unwrap_or_default()
678        };
679        let response: &mut Response = ctx.get_mut_response();
680        if response.get_headers().is_empty() {
681            let mut batch: [(&str, &str); 4] = [("", ""); 4];
682            let mut batch_len: usize = 0;
683            if is_wildcard || is_valid_cors_header_value(allow_origin_str) {
684                batch[batch_len] = (ACCESS_CONTROL_ALLOW_ORIGIN, allow_origin_str);
685                batch_len += 1;
686            }
687            if *vary_origin {
688                batch[batch_len] = (VARY, VARY_ORIGIN);
689                batch_len += 1;
690            }
691            if allow_credentials {
692                batch[batch_len] = (ACCESS_CONTROL_ALLOW_CREDENTIALS, HEADER_VALUE_TRUE);
693                batch_len += 1;
694            }
695            if let Some(expose) = expose_header {
696                batch[batch_len] = (ACCESS_CONTROL_EXPOSE_HEADERS, expose.as_str());
697                batch_len += 1;
698            }
699            response.set_headers_batch(&batch[..batch_len]);
700            return;
701        }
702        response.set_header(ACCESS_CONTROL_ALLOW_ORIGIN, allow_origin_str);
703        if *vary_origin {
704            merge_vary_header(response, VARY_ORIGIN);
705        }
706        if allow_credentials {
707            response.set_header(ACCESS_CONTROL_ALLOW_CREDENTIALS, HEADER_VALUE_TRUE);
708        }
709        if let Some(expose) = expose_header {
710            response.set_header(ACCESS_CONTROL_EXPOSE_HEADERS, expose);
711        }
712    }
713
714    /// Attempts to write a zero-allocation HTTP/1.1 `204 No Content` preflight wire response directly into `stream`.
715    ///
716    /// # Arguments
717    ///
718    /// - `&mut Stream` - Connection stream.
719    /// - `&Context` - Incoming request context.
720    ///
721    /// # Returns
722    ///
723    /// - `Option<bool>` - `Some(true)` if preflight was sent, `Some(false)` if not applicable to fast wire path, `None` if no preflight.
724    pub(crate) async fn try_send_fast_preflight(
725        &self,
726        stream: &mut Stream,
727        ctx: &Context,
728    ) -> Option<bool> {
729        let Self {
730            config,
731            mirror_headers,
732            preflight_static_lines,
733            ..
734        } = self;
735        let req: &Request = ctx.get_request();
736        if !req.get_method().is_options()
737            || !req.get_version().is_http1_1()
738            || !ctx.get_response().get_headers().is_empty()
739            || !req
740                .get_headers()
741                .contains_key(ACCESS_CONTROL_REQUEST_METHOD)
742        {
743            return None;
744        }
745        let origin: &str = request_header_back(req, ORIGIN)?;
746        let allow_origin_val: &str = self.resolve_origin(origin)?;
747        if allow_origin_val != CORS_WILDCARD && !is_valid_cors_header_value(allow_origin_val) {
748            return Some(false);
749        }
750        let mirrored_headers: Option<&str> = if *mirror_headers {
751            request_header_back(req, ACCESS_CONTROL_REQUEST_HEADERS)
752                .filter(|v: &&str| is_valid_cors_header_value(v))
753        } else {
754            None
755        };
756        let wants_private_net: bool = config.get_allow_private_network()
757            && request_header_back(req, ACCESS_CONTROL_REQUEST_PRIVATE_NETWORK)
758                .is_some_and(|val: &str| val.trim().eq_ignore_ascii_case(HEADER_VALUE_TRUE));
759        let mut total_len: usize = PREFLIGHT_WIRE_STATUS_ORIGIN.len()
760            + allow_origin_val.len()
761            + PREFLIGHT_WIRE_CRLF.len()
762            + preflight_static_lines.len()
763            + PREFLIGHT_WIRE_CRLF.len();
764        if let Some(mh) = mirrored_headers {
765            total_len += PREFLIGHT_WIRE_ALLOW_HEADERS.len() + mh.len() + PREFLIGHT_WIRE_CRLF.len();
766        }
767        if wants_private_net {
768            total_len += PREFLIGHT_WIRE_PRIVATE_NET.len();
769        }
770        if total_len <= PREFLIGHT_WIRE_STACK_CAP {
771            let mut stack: [u8; PREFLIGHT_WIRE_STACK_CAP] = [0u8; PREFLIGHT_WIRE_STACK_CAP];
772            let mut pos: usize = 0;
773            stack[pos..pos + PREFLIGHT_WIRE_STATUS_ORIGIN.len()]
774                .copy_from_slice(PREFLIGHT_WIRE_STATUS_ORIGIN);
775            pos += PREFLIGHT_WIRE_STATUS_ORIGIN.len();
776            let orig_b: &[u8] = allow_origin_val.as_bytes();
777            stack[pos..pos + orig_b.len()].copy_from_slice(orig_b);
778            pos += orig_b.len();
779            stack[pos..pos + PREFLIGHT_WIRE_CRLF.len()].copy_from_slice(PREFLIGHT_WIRE_CRLF);
780            pos += PREFLIGHT_WIRE_CRLF.len();
781            stack[pos..pos + preflight_static_lines.len()].copy_from_slice(preflight_static_lines);
782            pos += preflight_static_lines.len();
783            if let Some(mh) = mirrored_headers {
784                stack[pos..pos + PREFLIGHT_WIRE_ALLOW_HEADERS.len()]
785                    .copy_from_slice(PREFLIGHT_WIRE_ALLOW_HEADERS);
786                pos += PREFLIGHT_WIRE_ALLOW_HEADERS.len();
787                let mh_b: &[u8] = mh.as_bytes();
788                stack[pos..pos + mh_b.len()].copy_from_slice(mh_b);
789                pos += mh_b.len();
790                stack[pos..pos + PREFLIGHT_WIRE_CRLF.len()].copy_from_slice(PREFLIGHT_WIRE_CRLF);
791                pos += PREFLIGHT_WIRE_CRLF.len();
792            }
793            if wants_private_net {
794                stack[pos..pos + PREFLIGHT_WIRE_PRIVATE_NET.len()]
795                    .copy_from_slice(PREFLIGHT_WIRE_PRIVATE_NET);
796                pos += PREFLIGHT_WIRE_PRIVATE_NET.len();
797            }
798            stack[pos..pos + PREFLIGHT_WIRE_CRLF.len()].copy_from_slice(PREFLIGHT_WIRE_CRLF);
799            pos += PREFLIGHT_WIRE_CRLF.len();
800            let _: Result<(), ResponseError> = stream.try_send(&stack[..pos]).await;
801            return Some(true);
802        }
803        let mut wire: Vec<u8> = Vec::with_capacity(total_len);
804        wire.extend_from_slice(PREFLIGHT_WIRE_STATUS_ORIGIN);
805        wire.extend_from_slice(allow_origin_val.as_bytes());
806        wire.extend_from_slice(PREFLIGHT_WIRE_CRLF);
807        wire.extend_from_slice(preflight_static_lines);
808        if let Some(mh) = mirrored_headers {
809            wire.extend_from_slice(PREFLIGHT_WIRE_ALLOW_HEADERS);
810            wire.extend_from_slice(mh.as_bytes());
811            wire.extend_from_slice(PREFLIGHT_WIRE_CRLF);
812        }
813        if wants_private_net {
814            wire.extend_from_slice(PREFLIGHT_WIRE_PRIVATE_NET);
815        }
816        wire.extend_from_slice(PREFLIGHT_WIRE_CRLF);
817        let _: Result<(), ResponseError> = stream.try_send(&wire).await;
818        Some(true)
819    }
820}
821
822/// Inherent implementation of [`CorsPlugin`].
823impl CorsPlugin {
824    /// Initializes the global [`CorsPlugin`] once with `config`.
825    ///
826    /// # Arguments
827    ///
828    /// - `CorsConfig` - CORS policy configuration.
829    ///
830    /// # Returns
831    ///
832    /// - `&'static Self` - Reference to the initialized global plugin.
833    pub fn init(config: CorsConfig) -> &'static Self {
834        CORS_PLUGIN.get_or_init(|| Self {
835            compiled: CompiledCors::compile(config),
836        })
837    }
838
839    /// Returns the initialized global [`CorsPlugin`], if [`CorsPlugin::init`] was called.
840    ///
841    /// # Returns
842    ///
843    /// - `Option<&'static Self>` - Global plugin reference, or `None`.
844    #[inline(always)]
845    pub fn get() -> Option<&'static Self> {
846        CORS_PLUGIN.get()
847    }
848
849    /// Returns the precompiled [`CompiledCors`] engine.
850    ///
851    /// # Returns
852    ///
853    /// - `&CompiledCors` - Precompiled CORS policy.
854    #[inline(always)]
855    pub fn get_compiled(&self) -> &CompiledCors {
856        &self.compiled
857    }
858}
859
860/// Implements [`ServerHook`] for [`CorsRequestHook`].
861impl ServerHook for CorsRequestHook {
862    /// Constructs a per-request [`CorsRequestHook`].
863    ///
864    /// # Arguments
865    ///
866    /// - `&mut Stream` - Connection stream.
867    /// - `&mut Context` - Request context.
868    ///
869    /// # Returns
870    ///
871    /// - `Self` - Hook instance.
872    #[inline(always)]
873    async fn new(_: &mut Stream, _: &mut Context) -> Self {
874        Self
875    }
876
877    /// Applies CORS headers and short-circuits preflight `OPTIONS` requests with `204 No Content`.
878    ///
879    /// # Arguments
880    ///
881    /// - `Self` - Hook instance.
882    /// - `&mut Stream` - Connection stream.
883    /// - `&mut Context` - Request context.
884    ///
885    /// # Returns
886    ///
887    /// - `Status` - `Status::Reject` after sending a preflight response; `Status::Continue` otherwise.
888    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
889        let Some(plugin) = CorsPlugin::get() else {
890            return Status::Continue;
891        };
892        let compiled: &CompiledCors = plugin.get_compiled();
893        if compiled.try_send_fast_preflight(stream, ctx).await == Some(true) {
894            return Status::Reject;
895        }
896        if compiled.apply_request(ctx) {
897            let _: Result<(), ResponseError> = ctx.try_send_response(stream).await;
898            return Status::Reject;
899        }
900        Status::Continue
901    }
902}
903
904/// Implements [`ServerHook`] for [`CorsResponseHook`].
905impl ServerHook for CorsResponseHook {
906    /// Constructs a per-response [`CorsResponseHook`].
907    ///
908    /// # Arguments
909    ///
910    /// - `&mut Stream` - Connection stream.
911    /// - `&mut Context` - Request context.
912    ///
913    /// # Returns
914    ///
915    /// - `Self` - Hook instance.
916    #[inline(always)]
917    async fn new(_: &mut Stream, _: &mut Context) -> Self {
918        Self
919    }
920
921    /// Ensures CORS headers remain present on the response before transmission.
922    ///
923    /// # Arguments
924    ///
925    /// - `Self` - Hook instance.
926    /// - `&mut Stream` - Connection stream.
927    /// - `&mut Context` - Request context.
928    ///
929    /// # Returns
930    ///
931    /// - `Status` - Always `Status::Continue`.
932    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
933        let Some(plugin) = CorsPlugin::get() else {
934            return Status::Continue;
935        };
936        plugin.get_compiled().ensure_response_headers(ctx);
937        Status::Continue
938    }
939}