Skip to content

Commit

Permalink
feat:add opt CORS
Browse files Browse the repository at this point in the history
  • Loading branch information
Marsyew committed Mar 5, 2024
1 parent 5b53180 commit 58d8e4f
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ members = [".", "libs/cli", "libs/libwish", "tools/whepfrom", "tools/whipinto"]
[dependencies]
http-body-util = "0.1.0"
axum = { version = "0.7.4", features = ["multipart", "tracing"] }
tower-http = { version = "0.5.2", features = ["fs", "auth", "trace"] }
tower-http = { version = "0.5.2", features = ["fs", "auth", "trace","cors"] }

# TODO
# There have error, Next commit can't work with obs studio
Expand Down
13 changes: 13 additions & 0 deletions config-dist.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,16 @@ urls = [
# Default: info
# Values: off, error, warn, info, debug, trace
# level = "warn"

[http]
listen = "[::]:7777"
cors = false

#[http]
#cors = false
#access-control-allow-origin = none
#cors = true
#all request headers allowed.
#all methods allowed.
#all origins allowed.
#all headers exposed.
37 changes: 37 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use webrtc::{
ice_transport::{ice_credential_type::RTCIceCredentialType, ice_server::RTCIceServer},
Error,
};
use toml::Value;
use tower_http::cors::CorsLayer;

#[derive(Debug, Default, Clone, Deserialize, Serialize)]
pub struct Config {
Expand All @@ -16,6 +18,7 @@ pub struct Config {
pub auth: Auth,
#[serde(default = "default_log")]
pub log: Log,
pub enable_cors: bool,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Auth {
Expand Down Expand Up @@ -157,6 +160,7 @@ impl Config {
listen: default_listen(),
auth: Default::default(),
log: default_log(),
enable_cors: true,
}
}
}
Expand All @@ -170,3 +174,36 @@ impl Config {
Ok(())
}
}


pub fn cors_layer() -> CorsLayer {
let config_cors = fs::read_to_string("config-dist.toml")
.unwrap_or_else(|_| {
eprintln!("Unable to read config-dist.toml");
String::from(r#"
[http]
listen = "[::]:7777"
cors = false
"#)
});
let config: Value = match toml::from_str(&config_cors) {
Ok(parsed_config) => parsed_config,
Err(_) => {
eprintln!("Failed to parse config file");
toml::from_str(r#"
[http]
listen = "[::]:7777"
cors = false
"#).expect("Failed to parse default config")
}
};
let enable_cors = config["http"]["cors"].as_bool()
.unwrap_or(false);

if enable_cors {
CorsLayer::permissive()
} else {
let origins = [];
CorsLayer::new().allow_origin(origins)
}
}
5 changes: 4 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use crate::auth::ManyValidate;
use crate::config::Config;
use crate::dto::req::{ChangeResource, SelectLayer};
use crate::result::Result;
use config::IceServer;
use config::{IceServer,cors_layer};
use path::manager::Manager;
#[cfg(not(debug_assertions))]
use {http::header, rust_embed::RustEmbed};
Expand Down Expand Up @@ -79,6 +79,7 @@ async fn main() {
config: cfg.clone(),
};
let auth_layer = ValidateRequestHeaderLayer::custom(ManyValidate::new(cfg.auth));
let cors = cors_layer();
let app = Router::new()
.route("/whip/:id", post(whip))
.route("/whep/:id", post(whep))
Expand All @@ -95,6 +96,7 @@ async fn main() {
.layer(auth_layer)
.route("/metrics", get(metrics))
.with_state(app_state)
.layer(cors)
.layer(axum::middleware::from_fn(print_request_response))
.layer(
TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {
Expand Down Expand Up @@ -370,3 +372,4 @@ fn string_encoder(s: &impl ToString) -> String {
let s = serde_json::to_string(&s.to_string()).unwrap();
s[1..s.len() - 1].to_string()
}

0 comments on commit 58d8e4f

Please sign in to comment.