Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,18 @@ http-body-util = "0.1.3"
hyper = { version = "1.6.0", features = ["full"] }
hyper-rustls = "0.27.5"
hyper-util = { version = "0.1.11", features = ["full"] }
jsonrpsee = { version = "0.24", features = ["server", "http-client", "macros", "client"] }
jsonrpsee = { version = "0.24", features = [
"server",
"http-client",
"macros",
"client",
] }
paste = "1.0.15"
rustls = { version = "0.23.25", features = ["ring"] }
serde_json = "1.0.140"
tokio = { version = "1.44.1", features = ["full"] }
tower = { version = "0.4.13", features = ["timeout"] }
tower-http = { version = "0.6.2", features = ["decompression-full"] }
tower-http = { version = "0.6.2", features = ["cors", "decompression-full"] }
tracing = "0.1.41"
tracing-subscriber = { version = "0.3.19", features = ["env-filter", "json"] }
metrics-exporter-prometheus = "0.16.2"
Expand All @@ -45,6 +50,7 @@ metrics-derive = "0.1.0"
metrics = "0.24.2"

[dev-dependencies]
test-case = "3"
ctor = "0.3.5"
alloy-primitives = "0.8.25"
reqwest = "0.12.15"
Expand Down
60 changes: 60 additions & 0 deletions src/any_or_value.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use std::str::FromStr;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnyOr<T> {
Any,
Specific(T),
}

impl<T> AnyOr<T>
where
T: Clone,
{
pub fn coalesce(items: &[AnyOr<T>]) -> AnyOr<Vec<T>> {
let mut ret = vec![];

for item in items {
match item {
AnyOr::Any => return AnyOr::Any,
AnyOr::Specific(v) => ret.push(v.clone()),
}
}

AnyOr::Specific(ret)
}
}

impl<T> FromStr for AnyOr<T>
where
T: FromStr,
{
type Err = <T as FromStr>::Err;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"*" => Ok(Self::Any),
s => s.parse().map(AnyOr::Specific),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use test_case::test_case;

#[test_case("*" => AnyOr::Any)]
#[test_case("123" => AnyOr::Specific(123))]
fn parsing(s: &str) -> AnyOr<i32> {
s.parse().unwrap()
}

#[test_case(&["*", "1", "2"] => AnyOr::Any)]
#[test_case(&["47", "2"] => AnyOr::Specific(vec![47, 2]))]
#[test_case(&["1", "*"] => AnyOr::Any)]
fn coalesce(items: &[&str]) -> AnyOr<Vec<i32>> {
let items: Vec<AnyOr<i32>> = items.iter().map(|s| s.parse().unwrap()).collect();

AnyOr::coalesce(items)
}
}
40 changes: 39 additions & 1 deletion src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::any_or_value::AnyOr;
use crate::auth::{AuthLayer, JwtAuthValidator};
use crate::metrics::ProxyMetrics;
use crate::proxy::ProxyLayer;
Expand All @@ -6,7 +7,7 @@ use alloy_rpc_types_engine::JwtSecret;
use clap::Parser;
use eyre::Context as _;
use eyre::{Result, eyre};
use http::{Request, Response, StatusCode};
use http::{HeaderName, HeaderValue, Method, Request, Response, StatusCode};
use http_body_util::Full;
use hyper::Uri;
use hyper::body::Bytes;
Expand All @@ -29,6 +30,7 @@ use std::path::PathBuf;
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::signal::unix::{SignalKind, signal};
use tower_http::cors::{Any, CorsLayer};
use tracing::level_filters::LevelFilter;
use tracing::{Level, Metadata};
use tracing::{error, info};
Expand Down Expand Up @@ -74,6 +76,24 @@ pub struct Cli {
#[clap(long, env, default_value_t = DEFAULT_HTTP_PORT)]
pub http_port: u16,

/// The allowed CORS origins.
///
/// Can be specific values or a '*' wildcard
#[clap(long = "cors.allow-origin")]
pub cors_allow_origin: Vec<AnyOr<HeaderValue>>,

/// The allowed CORS methods.
///
/// Can be specific values or a '*' wildcard
#[clap(long = "cors.allow-methods")]
pub cors_allow_methods: Vec<AnyOr<Method>>,

/// The allowed CORS headers
///
/// Can be specific values or a '*' wildcard
#[clap(long = "cors.allow-headers")]
pub cors_allow_headers: Vec<AnyOr<HeaderName>>,

/// Enable Prometheus metrics
#[arg(long, env, default_value = "false")]
pub metrics: bool,
Expand Down Expand Up @@ -347,6 +367,22 @@ impl Cli {
metrics: Arc<ProxyMetrics>,
) -> Result<ServerHandle> {
let module = RpcModule::new(());

let mut cors = CorsLayer::new();

match AnyOr::coalesce(&self.cors_allow_origin) {
AnyOr::Any => cors = cors.allow_origin(Any),
AnyOr::Specific(origins) => cors = cors.allow_origin(origins),
}
match AnyOr::coalesce(&self.cors_allow_methods) {
AnyOr::Any => cors = cors.allow_methods(Any),
AnyOr::Specific(methods) => cors = cors.allow_methods(methods),
}
match AnyOr::coalesce(&self.cors_allow_headers) {
AnyOr::Any => cors = cors.allow_headers(Any),
AnyOr::Specific(headers) => cors = cors.allow_headers(headers),
}

if let Some(secret) = jwt_secret {
let middleware = tower::ServiceBuilder::new()
.layer(AuthLayer::new(JwtAuthValidator::new(secret)))
Expand All @@ -355,6 +391,7 @@ impl Cli {
self.builder_targets.build()?,
metrics.clone(),
))
.layer(cors)
.layer(ProxyLayer::new(self.l2_targets.build()?, metrics.clone()));

let server = Server::builder()
Expand All @@ -373,6 +410,7 @@ impl Cli {
self.builder_targets.build()?,
metrics.clone(),
))
.layer(cors)
.layer(ProxyLayer::new(self.l2_targets.build()?, metrics.clone()));

let server = Server::builder()
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
use dotenvy as _;

pub mod any_or_value;
pub mod auth;
pub mod cli;
pub mod client;
Expand Down
Loading