miden_node_utils/cors.rs
1use std::time::Duration;
2
3use http::HeaderName;
4use tonic::Status;
5use tower_http::cors::{AllowOrigin, CorsLayer};
6
7// CORS headers
8const DEFAULT_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60);
9const DEFAULT_EXPOSED_HEADERS: [HeaderName; 3] =
10 [Status::GRPC_STATUS, Status::GRPC_MESSAGE, Status::GRPC_STATUS_DETAILS];
11const DEFAULT_ALLOW_HEADERS: [HeaderName; 4] = [
12 HeaderName::from_static("x-grpc-web"),
13 http::header::CONTENT_TYPE,
14 HeaderName::from_static("x-user-agent"),
15 HeaderName::from_static("grpc-timeout"),
16];
17
18/// Enables CORS support. This is required for gRPC-web support.
19///
20/// The following implementation is based on the one in tonic-web that was deprecated
21/// in favor of letting the user configure the CORS layer. Reference:
22/// <https://github.com/hyperium/tonic/pull/1982/files>
23///
24/// # Configuration
25///
26/// The following configuration is used:
27///
28/// - `allow_origin`: Mirrors the request origin.
29/// - `allow_credentials`: Sets the `access-control-allow-credentials` header.
30/// - `max_age`: Sets the `access-control-max-age` header to 24 hours.
31/// - `expose_headers`: Sets the `access-control-expose-headers` header to the following headers:
32/// - `Status::GRPC_STATUS`
33/// - `Status::GRPC_MESSAGE`
34/// - `Status::GRPC_STATUS_DETAILS`
35/// - `allow_headers`: Sets the `access-control-allow-headers` header to the following headers:
36/// - `HeaderName::from_static("x-grpc-web")`
37/// - `http::header::CONTENT_TYPE`
38/// - `HeaderName::from_static("x-user-agent")`
39/// - `HeaderName::from_static("grpc-timeout")`
40pub fn cors_for_grpc_web_layer() -> CorsLayer {
41 CorsLayer::new()
42 .allow_origin(AllowOrigin::mirror_request())
43 .allow_credentials(true)
44 .max_age(DEFAULT_MAX_AGE)
45 .expose_headers(DEFAULT_EXPOSED_HEADERS)
46 .allow_headers(DEFAULT_ALLOW_HEADERS)
47}