diff --git a/rust/src/audit/CWE-942/PermissiveCors.qhelp b/rust/src/audit/CWE-942/PermissiveCors.qhelp new file mode 100644 index 00000000..768700b3 --- /dev/null +++ b/rust/src/audit/CWE-942/PermissiveCors.qhelp @@ -0,0 +1,55 @@ + + + + +

+Cross-Origin Resource Sharing (CORS) lets a server relax the browser's same-origin policy by +naming the origins that are allowed to read its responses in the +Access-Control-Allow-Origin response header. A policy that allows any origin, for +example by sending Access-Control-Allow-Origin: *, reflecting the request origin, or +using a framework's "allow any origin" or "permissive" CORS configuration, lets every website +read the responses of this service from a victim's browser. +

+

+This is harmless for truly public, unauthenticated data, but it exposes any sensitive data the +service returns (now or in the future), including data served to clients on a local or private +network that the attacker cannot reach directly. +

+

+This query recognizes, among others: allow_any_origin() (warp, actix-cors), +Cors::permissive() (actix-cors), CorsLayer::permissive(), +CorsLayer::very_permissive() and allow_origin with Any, +"*", AllowOrigin::any() or AllowOrigin::mirror_request() +(tower-http), AllowedOrigins::all() (rocket_cors), +AccessControlAllowOrigin::Any (iron / hyper 0.10), and setting the +Access-Control-Allow-Origin header to "*" directly. +

+
+ + +

+Allow only an explicit list of trusted origins. If the endpoint really serves only public data +that every website may read, the alert can be dismissed. +

+
+ + +

+In the following example, an axum application uses a tower-http CorsLayer that +allows the wildcard origin, so any website can read the JSON responses: +

+ +

+The fix is to allow only the trusted front-end origin: +

+ +
+ + +
  • MDN: Cross-Origin Resource Sharing (CORS).
  • +
  • OWASP: Testing Cross Origin Resource Sharing.
  • +
  • Common Weakness Enumeration: CWE-942.
  • +
    +
    diff --git a/rust/src/audit/CWE-942/PermissiveCors.ql b/rust/src/audit/CWE-942/PermissiveCors.ql new file mode 100644 index 00000000..156b7eb6 --- /dev/null +++ b/rust/src/audit/CWE-942/PermissiveCors.ql @@ -0,0 +1,201 @@ +/** + * @name Permissive CORS configuration + * @description Allowing any origin to read cross-origin responses lets an + * arbitrary website read data served to a victim's browser. + * @kind problem + * @problem.severity warning + * @security-severity 2.5 + * @sub-severity low + * @precision very-low + * @id githubsecuritylab/audit/rust/permissive-cors + * @tags security + * experimental + * audit + * external/cwe/cwe-942 + */ + +import rust +import codeql.rust.dataflow.DataFlow + +/** Holds if `e` is a string literal whose value is `value`. */ +bindingset[value] +private predicate isStringLiteral(Expr e, string value) { + e.(StringLiteralExpr).getTextValue() = "\"" + value + "\"" +} + +/** + * Holds if `c` builds a header value from its argument, such as `HeaderValue::from_static("*")`. + */ +private predicate isHeaderValueConstructor(CallExpr c) { + isPathCall(c, "HeaderValue", + ["from_static", "from_str", "from_bytes", "from_maybe_shared", "try_from"]) + or + isPathCall(c, "String", "from") + or + isPathCall(c, "AllowOrigin", "exact") +} + +/** + * Gets an expression that the value of `e` is taken from: the receiver of a method call, the + * argument of a constructor of a header value, a referenced or `?`-operand expression, or a reaching + * assignment to a local variable read by `e`. + * + * This handles wrappers such as `"*".parse::().unwrap()`, + * `HeaderValue::from_static("*")` and `let origin = "*"; ... origin`. Other arguments are not + * followed: in `origin.parse::().expect("*")` the `"*"` is only a message. + */ +private Expr getAnInnerExpr(Expr e) { + result = e.(MethodCallExpr).getReceiver() + or + isHeaderValueConstructor(e) and result = e.(CallExpr).getArgList().getAnArg() + or + result = e.(RefExpr).getExpr() + or + result = e.(TryExpr).getExpr() + or + exists(Variable v, DataFlow::ExprNode source, DataFlow::ExprNode target | + e = v.getAnAccess() and + target.asExpr() = e and + source.asExpr() = result and + source.asExpr() != e and + DataFlow::localFlow(source, target) + ) +} + +/** Holds if `p` is a path whose final segment is `name` (for example `Any` or `cors::Any`). */ +bindingset[name] +private predicate pathEndsWith(Path p, string name) { p.getText() = name } + +/** + * Holds if `p` is a path whose final segment is `name` and whose qualifier + * ends in `qualifier` (for example `CorsLayer::permissive`). + */ +bindingset[qualifier, name] +private predicate qualifiedPathEndsWith(Path p, string qualifier, string name) { + p.getText() = name and + p.getQualifier().getText() = qualifier +} + +/** Holds if `c` is a call to a function at a path ending in `qualifier::name`. */ +bindingset[qualifier, name] +private predicate isPathCall(CallExpr c, string qualifier, string name) { + qualifiedPathEndsWith(c.getFunction().(PathExpr).getPath(), qualifier, name) +} + +/** Holds if `e` is (or is derived from) a value denoting the wildcard CORS origin. */ +private predicate isWildcardOriginValue(Expr e) { + isStringLiteral(e, "*") + or + // `tower_http::cors::Any`, `salvo::cors::Any` + pathEndsWith(e.(PathExpr).getPath(), "Any") + or + // `tower_http::cors::AllowOrigin::any()`, `AllowOrigin::mirror_request()` + isPathCall(e, "AllowOrigin", ["any", "mirror_request"]) + or + isWildcardOriginValue(getAnInnerExpr(e)) +} + +/** + * Holds if `e` names the `Access-Control-Allow-Origin` header, either directly + * or via a header-name constructor such as `HeaderName::from_static(...)`. + */ +private predicate isAllowOriginHeaderName(Expr e) { + e.(StringLiteralExpr).getTextValue().toLowerCase() = "\"access-control-allow-origin\"" + or + pathEndsWith(e.(PathExpr).getPath(), "ACCESS_CONTROL_ALLOW_ORIGIN") + or + isAllowOriginHeaderName(e.(RefExpr).getExpr()) + or + exists(CallExpr c | c = e | + isPathCall(c, "HeaderName", ["from_static", "from_lowercase", "from_bytes", "from_str"]) and + isAllowOriginHeaderName(c.getArgList().getArg(0)) + ) + or + exists(MethodCallExpr c | + c = e and + c.getIdentifier().getText() in ["unwrap", "expect"] and + isAllowOriginHeaderName(c.getReceiver()) + ) + or + isAllowOriginHeaderName(e.(TryExpr).getExpr()) +} + +/** + * Holds if `call` sets a header on a response, a header map or a header layer: `insert`, `append` + * and `header` style methods, and functions such as `Header::new` and `warp::reply::with::header`. + * A call that only receives a header name and a value, such as a comparison helper, does not. + */ +private predicate isHeaderWriter(Expr call) { + call.(MethodCallExpr).getIdentifier().getText() = + ["insert", "append", "header", "insert_header", "append_header", "add_header", "set_header"] + or + call.(CallExpr).getFunction().(PathExpr).getPath().getText() = + ["header", "with_header", "overriding", "if_not_present", "appending"] + or + isPathCall(call, "Header", "new") +} + +/** + * Holds if `name` and `value` are an adjacent header name/value pair, either + * consecutive arguments of a call that sets a header (for example + * `headers.insert(name, value)` or `with_header(reply, name, value)`) or a + * 2-tuple `(name, value)`. + */ +private predicate isHeaderPair(Expr pair, Expr name, Expr value) { + isHeaderWriter(pair) and + exists(ArgList args, int i | + args = pair.(MethodCallExpr).getArgList() or args = pair.(CallExpr).getArgList() + | + name = args.getArg(i) and + value = args.getArg(i + 1) + ) + or + pair.(TupleExpr).getNumberOfFields() = 2 and + name = pair.(TupleExpr).getField(0) and + value = pair.(TupleExpr).getField(1) +} + +/** + * Holds if `e` configures a CORS policy (or sets a CORS response header) that + * allows any origin, described by `description`. + */ +predicate isPermissiveCors(Expr e, string description) { + // warp: `warp::cors().allow_any_origin()`; actix-cors: `Cors::default().allow_any_origin()` + e.(MethodCallExpr).getIdentifier().getText() = "allow_any_origin" and + e.(MethodCallExpr).getArgList().getNumberOfArgs() = 0 and + description = "This CORS policy allows any origin" + or + // tower-http / salvo: `.allow_origin(Any)`, `.allow_origin("*".parse().unwrap())` + e.(MethodCallExpr).getIdentifier().getText() = "allow_origin" and + isWildcardOriginValue(e.(MethodCallExpr).getArgList().getArg(0)) and + description = "This CORS policy allows any origin" + or + // actix-cors: `Cors::permissive()`; tower-http: `CorsLayer::permissive()` / `very_permissive()` + ( + isPathCall(e, "Cors", "permissive") + or + isPathCall(e, "CorsLayer", ["permissive", "very_permissive"]) + or + // rocket_cors: `AllowedOrigins::all()` + isPathCall(e, "AllowedOrigins", "all") + ) and + description = "This CORS policy allows any origin" + or + // iron / hyper 0.10: `AccessControlAllowOrigin::Any` + qualifiedPathEndsWith(e.(PathExpr).getPath(), "AccessControlAllowOrigin", "Any") and + description = "This Access-Control-Allow-Origin header allows any origin" + or + // raw header: `headers.insert(ACCESS_CONTROL_ALLOW_ORIGIN, "*")`, `("Access-Control-Allow-Origin", "*")` + exists(Expr name, Expr value | + isHeaderPair(e, name, value) and + isAllowOriginHeaderName(name) and + isWildcardOriginValue(value) + ) and + description = "This Access-Control-Allow-Origin header allows any origin" +} + +from Expr e, string description +where isPermissiveCors(e, description) +select e, + description + + ". Review whether the responses of this service contain sensitive or credentialed data." diff --git a/rust/src/audit/CWE-942/PermissiveCorsBad.rs b/rust/src/audit/CWE-942/PermissiveCorsBad.rs new file mode 100644 index 00000000..8e53b37f --- /dev/null +++ b/rust/src/audit/CWE-942/PermissiveCorsBad.rs @@ -0,0 +1,9 @@ +use axum::{http::HeaderValue, routing::get, Router}; +use tower_http::cors::CorsLayer; + +fn app() -> Router { + Router::new().route("/json", get(|| async { "{}" })).layer( + // BAD: any website can read responses from this service + CorsLayer::new().allow_origin("*".parse::().unwrap()), + ) +} diff --git a/rust/src/audit/CWE-942/PermissiveCorsGood.rs b/rust/src/audit/CWE-942/PermissiveCorsGood.rs new file mode 100644 index 00000000..7559b341 --- /dev/null +++ b/rust/src/audit/CWE-942/PermissiveCorsGood.rs @@ -0,0 +1,9 @@ +use axum::{http::HeaderValue, routing::get, Router}; +use tower_http::cors::CorsLayer; + +fn app() -> Router { + Router::new().route("/json", get(|| async { "{}" })).layer( + // GOOD: only the trusted front-end origin can read responses + CorsLayer::new().allow_origin("https://app.example.com".parse::().unwrap()), + ) +} diff --git a/rust/test/audit/CWE-942/PermissiveCors/PermissiveCors.expected b/rust/test/audit/CWE-942/PermissiveCors/PermissiveCors.expected new file mode 100644 index 00000000..f01cd5c9 --- /dev/null +++ b/rust/test/audit/CWE-942/PermissiveCors/PermissiveCors.expected @@ -0,0 +1,22 @@ +| main.rs:11:20:12:31 | ... .allow_any_origin() | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:27:19:27:79 | ...::header(...) | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:62:27:62:55 | ...::Any | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:99:13:100:66 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:108:20:108:79 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:114:20:114:53 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:120:20:120:59 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:126:20:126:68 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:132:20:132:79 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:139:20:139:88 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:147:20:147:88 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:161:20:161:42 | ...::permissive(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:167:20:167:47 | ...::very_permissive(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:172:9:172:90 | headers.insert(...) | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:177:11:177:52 | TupleExpr | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:216:9:219:9 | headers.insert(...) | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:225:9:228:9 | headers.insert(...) | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:235:9:238:9 | headers.insert(...) | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:280:28:280:63 | TupleExpr | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:293:23:293:56 | ... .allow_any_origin() | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:294:34:294:51 | ...::permissive(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | +| main.rs:318:30:318:50 | ...::all(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. | diff --git a/rust/test/audit/CWE-942/PermissiveCors/PermissiveCors.qlref b/rust/test/audit/CWE-942/PermissiveCors/PermissiveCors.qlref new file mode 100644 index 00000000..e9f39ddc --- /dev/null +++ b/rust/test/audit/CWE-942/PermissiveCors/PermissiveCors.qlref @@ -0,0 +1 @@ +query: audit/CWE-942/PermissiveCors.ql diff --git a/rust/test/audit/CWE-942/PermissiveCors/main.rs b/rust/test/audit/CWE-942/PermissiveCors/main.rs new file mode 100644 index 00000000..5f297ff7 --- /dev/null +++ b/rust/test/audit/CWE-942/PermissiveCors/main.rs @@ -0,0 +1,331 @@ +// Test cases for `rust/permissive-cors` (CWE-942). +// +// The third-party crates referenced here (warp, iron, tower-http, axum, +// actix-web, actix-cors, rocket, rocket_cors) are not fetched for this test, +// so the query must recognize the permissive CORS patterns syntactically. + +mod warp_cors { + use warp::Filter; + + pub async fn bad() { + let cors = warp::cors() + .allow_any_origin() // $ Alert + .allow_methods(vec!["GET", "POST"]) + .allow_headers(vec!["Content-Type", "Authorization"]); + + let route = warp::path("example") + .and(warp::get()) + .map(|| "Hello, CORS!") + .with(cors); + + warp::serve(route).run(([127, 0, 0, 1], 3030)).await; + } + + pub async fn bad_raw_header() { + let route = warp::path("example") + .map(|| "Hello, CORS!") + .with(warp::reply::with::header("Access-Control-Allow-Origin", "*")); // $ Alert + warp::serve(route).run(([127, 0, 0, 1], 3031)).await; + } + + pub async fn good() { + let cors = warp::cors() + .allow_origin("https://trusted.example.com") + .allow_methods(vec!["GET", "POST"]); + + let route = warp::path("example") + .map(|| "Hello, CORS!") + .with(cors); + + warp::serve(route).run(([127, 0, 0, 1], 3032)).await; + } + + pub async fn good_raw_header() { + let route = warp::path("example") + .map(|| "Hello, CORS!") + .with(warp::reply::with::header( + "Access-Control-Allow-Origin", + "https://trusted.example.com", + )); + warp::serve(route).run(([127, 0, 0, 1], 3033)).await; + } +} + +mod iron_cors { + use iron::headers::AccessControlAllowOrigin; + use iron::prelude::*; + use iron::status; + + pub fn bad() { + Iron::new(|_: &mut Request| { + let mut r = Response::with((status::Ok, "Hello World!")); + r.headers.set(AccessControlAllowOrigin::Any); // $ Alert + Ok(r) + }) + .http("localhost:8080") + .unwrap(); + } + + pub fn good() { + Iron::new(|_: &mut Request| { + let mut r = Response::with((status::Ok, "Hello World!")); + r.headers.set(AccessControlAllowOrigin::Value( + "https://trusted.example.com".to_owned(), + )); + Ok(r) + }) + .http("localhost:8081") + .unwrap(); + } +} + +mod tower_http_cors { + use std::str::FromStr; + + use axum::{ + http::{header, HeaderMap, HeaderValue, Method}, + response::IntoResponse, + routing::get, + Json, Router, + }; + use tower_http::cors::{self, AllowOrigin, Any, CorsLayer}; + + async fn json() -> impl IntoResponse { + Json(vec!["one", "two", "three"]) + } + + pub fn bad_parsed_wildcard() -> Router { + Router::new().route("/json", get(json)).layer( + CorsLayer::new() + .allow_origin("*".parse::().unwrap()) // $ Alert + .allow_methods([Method::GET]), + ) + } + + pub fn bad_from_static_wildcard() -> Router { + Router::new() + .route("/json", get(json)) + .layer(CorsLayer::new().allow_origin(HeaderValue::from_static("*"))) // $ Alert + } + + pub fn bad_any() -> Router { + Router::new() + .route("/json", get(json)) + .layer(CorsLayer::new().allow_origin(Any)) // $ Alert + } + + pub fn bad_qualified_any() -> Router { + Router::new() + .route("/json", get(json)) + .layer(CorsLayer::new().allow_origin(cors::Any)) // $ Alert + } + + pub fn bad_allow_origin_any() -> Router { + Router::new() + .route("/json", get(json)) + .layer(CorsLayer::new().allow_origin(AllowOrigin::any())) // $ Alert + } + + pub fn bad_mirror_request() -> Router { + Router::new() + .route("/json", get(json)) + .layer(CorsLayer::new().allow_origin(AllowOrigin::mirror_request())) // $ Alert + } + + pub fn bad_wildcard_variable() -> Router { + let origin = "*"; + Router::new() + .route("/json", get(json)) + .layer(CorsLayer::new().allow_origin(origin.parse::().unwrap())) // $ Alert + } + + pub fn bad_reassigned_wildcard_variable() -> Router { + let mut origin = "https://trusted.example.com"; + origin = "*"; + Router::new() + .route("/json", get(json)) + .layer(CorsLayer::new().allow_origin(origin.parse::().unwrap())) // $ Alert + } + + pub fn good_reassigned_trusted_variable() -> Router { + let mut origin = "*"; + origin = "https://trusted.example.com"; + Router::new() + .route("/json", get(json)) + .layer(CorsLayer::new().allow_origin(origin.parse::().unwrap())) + } + + pub fn bad_permissive() -> Router { + Router::new() + .route("/json", get(json)) + .layer(CorsLayer::permissive()) // $ Alert + } + + pub fn bad_very_permissive() -> Router { + Router::new() + .route("/json", get(json)) + .layer(CorsLayer::very_permissive()) // $ Alert + } + + pub async fn bad_raw_header_map() -> impl IntoResponse { + let mut headers = HeaderMap::new(); + headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*")); // $ Alert + (headers, "Hello") + } + + pub async fn bad_raw_header_tuple() -> impl IntoResponse { + ([(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")], "Hello") // $ Alert + } + + pub fn good_exact_origin() -> Router { + Router::new().route("/json", get(json)).layer( + CorsLayer::new() + .allow_origin("https://trusted.example.com".parse::().unwrap()) + .allow_methods([Method::GET]) + .allow_headers(Any), + ) + } + + pub fn good_origin_list() -> Router { + Router::new().route("/json", get(json)).layer( + CorsLayer::new().allow_origin(AllowOrigin::list([ + HeaderValue::from_static("https://a.example.com"), + HeaderValue::from_static("https://b.example.com"), + ])), + ) + } + + pub fn good_any_methods_only() -> Router { + Router::new() + .route("/json", get(json)) + .layer(CorsLayer::new().allow_methods(Any).allow_headers(Any)) + } + + pub async fn good_raw_header_map() -> impl IntoResponse { + let mut headers = HeaderMap::new(); + headers.insert( + header::ACCESS_CONTROL_ALLOW_ORIGIN, + HeaderValue::from_static("https://trusted.example.com"), + ); + headers.insert(header::ACCESS_CONTROL_ALLOW_METHODS, HeaderValue::from_static("*")); + (headers, "Hello") + } + + pub async fn bad_raw_header_name_constructor() -> impl IntoResponse { + let mut headers = HeaderMap::new(); + headers.insert( + header::HeaderName::from_static("access-control-allow-origin"), + HeaderValue::from_static("*"), + ); // $ Alert + (headers, "Hello") + } + + pub async fn bad_raw_header_name_constructor_unwrap() -> impl IntoResponse { + let mut headers = HeaderMap::new(); + headers.insert( + header::HeaderName::from_str("access-control-allow-origin").unwrap(), + HeaderValue::from_static("*"), + ); // $ Alert + (headers, "Hello") + } + + pub async fn bad_raw_header_name_constructor_try( + ) -> Result> { + let mut headers = HeaderMap::new(); + headers.insert( + header::HeaderName::from_str("access-control-allow-origin")?, + HeaderValue::from_static("*"), + ); // $ Alert + Ok((headers, "Hello")) + } + + fn check(value: Option<&HeaderValue>, expected: &str) -> bool { + value.map_or(false, |v| v == expected) + } + + fn has_header(headers: &HeaderMap, name: &str, expected: &str) -> bool { + headers.get(name).map_or(false, |v| v == expected) + } + + // Reading (rather than setting) the header must not be reported. + pub fn good_read_header(headers: &HeaderMap) { + assert_eq!(headers.get(header::ACCESS_CONTROL_ALLOW_ORIGIN).unwrap(), "*"); + assert!(check(headers.get(header::ACCESS_CONTROL_ALLOW_ORIGIN), "*")); + } + + // A helper that is given a header name and a value, and only compares them, does not set a header. + pub fn good_header_comparison_helper(headers: &HeaderMap) -> bool { + has_header(headers, "Access-Control-Allow-Origin", "*") + } + + // The wildcard is only the message of `expect`: the origin itself is an exact one. + pub fn good_wildcard_only_in_expect_message() -> Router { + Router::new().route("/json", get(json)).layer( + CorsLayer::new() + .allow_origin("https://trusted.example.com".parse::().expect("*")), + ) + } +} + +mod actix_cors_example { + use actix_cors::Cors; + use actix_web::{web, App, HttpResponse, HttpServer}; + + async fn index() -> HttpResponse { + HttpResponse::Ok().body("Hello") + } + + async fn bad_insert_header() -> HttpResponse { + HttpResponse::Ok() + .insert_header(("Access-Control-Allow-Origin", "*")) // $ Alert + .body("Hello") + } + + async fn good_insert_header() -> HttpResponse { + HttpResponse::Ok() + .insert_header(("access-control-allow-origin", "https://trusted.example.com")) + .insert_header(("X-Custom", "*")) + .body("Hello") + } + + pub async fn run() -> std::io::Result<()> { + HttpServer::new(|| { + let bad = Cors::default().allow_any_origin(); // $ Alert + let bad_permissive = Cors::permissive(); // $ Alert + let good = Cors::default() + .allowed_origin("https://trusted.example.com") + .allow_any_method() + .allow_any_header(); + App::new() + .wrap(bad) + .wrap(bad_permissive) + .wrap(good) + .route("/", web::get().to(index)) + .route("/bad", web::get().to(bad_insert_header)) + .route("/good", web::get().to(good_insert_header)) + }) + .bind(("127.0.0.1", 8080))? + .run() + .await + } +} + +mod rocket_cors_example { + use rocket_cors::{AllowedOrigins, CorsOptions}; + + pub fn bad() -> CorsOptions { + CorsOptions { + allowed_origins: AllowedOrigins::all(), // $ Alert + ..Default::default() + } + } + + pub fn good() -> CorsOptions { + CorsOptions { + allowed_origins: AllowedOrigins::some_exact(&["https://trusted.example.com"]), + ..Default::default() + } + } +} + +fn main() {}