Skip to content

The headless browser for AI agents and web scraping

fix(obscura-js): CORS-check intermediate redirect hops + preflight status order (#973)

Andrey Mnatsakanov05846def8641
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index ddb3d918..a4c25e3d 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -2888,6 +2888,15 @@ async fn op_fetch_url(
deno_error::JsErrorBox::generic(format!("CORS preflight failed: {}", e))
})?;
+ // Fetch spec: the preflight response's status must be an ok status
+ // before its CORS headers are consulted (#973).
+ if !preflight.status().is_success() {
+ return Err(deno_error::JsErrorBox::generic(format!(
+ "CORS preflight returned HTTP {}",
+ preflight.status()
+ )));
+ }
+
let allowed_origin = preflight
.headers()
.get("access-control-allow-origin")
@@ -2905,12 +2914,6 @@ async fn op_fetch_url(
page_origin, allowed_origin
)));
}
- if !preflight.status().is_success() {
- return Err(deno_error::JsErrorBox::generic(format!(
- "CORS preflight returned HTTP {}",
- preflight.status()
- )));
- }
let allowed_methods = parse_cors_header_list(
preflight.headers(),
@@ -3063,6 +3066,33 @@ async fn op_fetch_url(
break resp;
}
+ // Fetch spec: the CORS check applies to every response in cors mode,
+ // not only the final one. A cross-origin redirect response must be
+ // authorized before it is followed (#973).
+ if mode == "cors" && current_is_cross_origin {
+ let allowed = resp
+ .headers()
+ .get("access-control-allow-origin")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("");
+ let allow_credentials = resp
+ .headers()
+ .get("access-control-allow-credentials")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("");
+ if !cors_response_allows(credentials, &page_origin, allowed, allow_credentials) {
+ return Ok(serde_json::json!({
+ "status": 0, "body": "", "url": current_url, "headers": {},
+ "corsBlocked": true,
+ "corsError": format!(
+ "CORS error: cross-origin redirect from '{}' not allowed by Access-Control-Allow-Origin '{}'",
+ current_url, allowed
+ ),
+ })
+ .to_string());
+ }
+ }
+
let location_header = resp
.headers()
.get(reqwest::header::LOCATION)
@@ -3335,6 +3365,31 @@ async fn stealth_fetch_all(
if !(300..400).contains(&r.status) {
break (r.status, r.headers, r.body);
}
+ // Cross-origin redirect responses must pass the CORS check too, before
+ // the redirect is followed (#973).
+ if mode == "cors" && current_is_cross_origin {
+ let allowed = r
+ .headers
+ .get("access-control-allow-origin")
+ .map(String::as_str)
+ .unwrap_or("");
+ let allow_credentials = r
+ .headers
+ .get("access-control-allow-credentials")
+ .map(String::as_str)
+ .unwrap_or("");
+ if !cors_response_allows(credentials, &page_origin, allowed, allow_credentials) {
+ return Ok(serde_json::json!({
+ "status": 0, "body": "", "url": current_url, "headers": {},
+ "corsBlocked": true,
+ "corsError": format!(
+ "CORS error: cross-origin redirect from '{}' not allowed by Access-Control-Allow-Origin '{}'",
+ current_url, allowed
+ ),
+ })
+ .to_string());
+ }
+ }
let Some(location) = r.headers.get("location").cloned() else {
break (r.status, r.headers, r.body);
};
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index d342f952..a1d4557b 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -17332,6 +17332,77 @@ mod tests {
redirect_runtime_for_origin(&format!("http://{source_address}"))
}
+ // A redirector (cross-origin to the page) whose 302 carries no
+ // Access-Control-Allow-Origin, pointing at its own /final which does allow.
+ // Returns the runtime (page on a distinct origin) and the redirector base.
+ fn cross_origin_intermediate_redirect_runtime() -> (ObscuraJsRuntime, String) {
+ let redirector = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let redirector_address = redirector.local_addr().unwrap();
+ std::thread::spawn(move || {
+ use std::io::{Read as _, Write as _};
+ for _ in 0..2 {
+ let Ok((mut stream, _)) = redirector.accept() else {
+ break;
+ };
+ let mut buffer = [0u8; 1024];
+ let _ = stream.read(&mut buffer);
+ let request = String::from_utf8_lossy(&buffer);
+ let response = if request.contains("/final") {
+ "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"
+ .to_string()
+ } else {
+ // 302 WITHOUT Access-Control-Allow-Origin.
+ "HTTP/1.1 302 Found\r\nLocation: /final\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
+ .to_string()
+ };
+ let _ = stream.write_all(response.as_bytes());
+ }
+ });
+
+ // The page lives on a distinct origin, so the fetch is cross-origin.
+ let page = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let page_address = page.local_addr().unwrap();
+ drop(page);
+
+ (
+ redirect_runtime_for_origin(&format!("http://{page_address}")),
+ format!("http://{redirector_address}"),
+ )
+ }
+
+ // #973: in cors mode, a cross-origin redirect response that lacks
+ // Access-Control-Allow-Origin must be rejected before it is followed, even
+ // if the final destination would authorize the request.
+ #[tokio::test(flavor = "current_thread")]
+ async fn cors_mode_blocks_unauthorized_cross_origin_redirect_hop() {
+ let (mut rt, redirector) = cross_origin_intermediate_redirect_runtime();
+ let result = rt
+ .call_function_on_for_cdp(
+ &format!(
+ r#"async () => {{
+ try {{
+ await fetch("{redirector}/start", {{ mode: "cors" }});
+ return "allowed";
+ }} catch (e) {{
+ return "blocked";
+ }}
+ }}"#
+ ),
+ None,
+ &[],
+ true,
+ true,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ result.value.unwrap(),
+ serde_json::json!("blocked"),
+ "a cross-origin redirect without Access-Control-Allow-Origin must be blocked in cors mode"
+ );
+ }
+
/// HTTP-redirect fetch returns a network error as soon as the
/// redirect count *reaches* 20, and only increments it afterwards. So
/// the twentieth hop must still succeed: