Skip to content

The headless browser for AI agents and web scraping

Validate file uploads in their owning realm

SGavrl0d8a200574f4
diff --git a/crates/obscura-cdp/src/domains/dom.rs b/crates/obscura-cdp/src/domains/dom.rs
index dc477e8d..4142d2a3 100644
--- a/crates/obscura-cdp/src/domains/dom.rs
+++ b/crates/obscura-cdp/src/domains/dom.rs
@@ -106,6 +106,23 @@ fn resolve_node_id(page: &mut Page, params: &Value) -> Result<u64, String> {
Err("nodeId, backendNodeId, or objectId required".to_string())
}
+async fn run_file_input_command(page: &mut Page, function: &str, object_id: Option<&str>,
+ specs: Value, validate_only: bool) -> Result<(), String> {
+ let specs = serde_json::to_string(&specs).map_err(|error| error.to_string())?;
+ let command = format!("function() {{ return ({function}).call(this, {specs}, {validate_only}); }}");
+ let result = page.call_function_on_for_cdp_with_timeout(&command, object_id,
+ &[], true, false, 30_000).await?;
+ if result.thrown {
+ return Err(format!("Could not set input files: {}", result.description));
+ }
+ match result.value.as_ref().and_then(Value::as_str) {
+ Some("ok") => Ok(()),
+ Some("missing") => Err("Could not find node with given id".into()),
+ Some("invalid") => Err("Node is not a file input element".into()),
+ _ => Err("Could not set files on the input element".into()),
+ }
+}
+
/// Standard base64 (with padding). Used to ferry file bytes to the JS layer for
/// DOM.setFileInputFiles without pulling in a dependency.
fn encode_base64(input: &[u8]) -> String {
@@ -429,12 +446,39 @@ pub async fn handle(
if !page.context.allow_file_access {
return Err("DOM.setFileInputFiles is disabled. Restart with `obscura serve --allow-file-access` to enable local file uploads.".to_string());
}
- let node_id = resolve_node_id(page, params)?;
- let paths: Vec<String> = params
- .get("files")
- .and_then(|v| v.as_array())
- .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
- .unwrap_or_default();
+ let files = params.get("files").and_then(Value::as_array)
+ .ok_or("DOM.setFileInputFiles requires a files array")?;
+ let paths: Vec<&str> = files.iter().map(|file| file.as_str()
+ .ok_or_else(|| "DOM.setFileInputFiles requires string file paths".to_string()))
+ .collect::<Result<_, _>>()?;
+ // Keep remote handles intact: a child-frame node's numeric id
+ // belongs to its own DOM, not the page's root DOM.
+ let (object_id, receiver) = if params.get("nodeId").is_some()
+ || params.get("backendNodeId").is_some() {
+ let node_id = params.get("nodeId").or_else(|| params.get("backendNodeId"))
+ .and_then(Value::as_u64).ok_or("valid nodeId or backendNodeId required")?;
+ let exists = u32::try_from(node_id).ok().and_then(|id| {
+ page.with_dom(|dom| dom.get_node(NodeId::new(id)).is_some())
+ }).unwrap_or(false);
+ if !exists { return Err("Could not find node with given id".into()); }
+ (None, format!("globalThis._wrap({node_id})"))
+ } else {
+ let object_id = params.get("objectId").and_then(Value::as_str)
+ .ok_or("nodeId, backendNodeId, or objectId required")?;
+ (Some(object_id), "this".to_string())
+ };
+ let function = format!(
+ "function(specs, validateOnly) {{\
+ var el = {receiver};\
+ if (!el || !el.nodeType) return 'missing';\
+ var owner = el.ownerDocument && el.ownerDocument.defaultView || globalThis;\
+ if (typeof owner.__obscura_setInputFiles !== 'function')\
+ throw new Error('File input helper unavailable');\
+ return owner.__obscura_setInputFiles(el, specs, validateOnly) === true\
+ ? 'ok' : (validateOnly ? 'invalid' : 'failed');\
+ }}"
+ );
+ run_file_input_command(page, &function, object_id, json!([]), true).await?;
let mut specs = Vec::with_capacity(paths.len());
for p in &paths {
@@ -448,13 +492,7 @@ pub async fn handle(
specs.push(json!({ "name": name, "type": guess_mime(p), "b64": encode_base64(&bytes) }));
}
- let specs_json = serde_json::to_string(&specs).unwrap_or_else(|_| "[]".to_string());
- let code = format!(
- "(function() {{ var el = globalThis._wrap && globalThis._wrap({0}); \
- if (el && globalThis.__obscura_setInputFiles) {{ globalThis.__obscura_setInputFiles(el, {1}); return true; }} return false; }})()",
- node_id, specs_json
- );
- let _ = page.evaluate(&code);
+ run_file_input_command(page, &function, object_id, json!(specs), false).await?;
Ok(json!({}))
}
"getBoxModel" => {
diff --git a/crates/obscura-cdp/tests/file_upload_integrity.rs b/crates/obscura-cdp/tests/file_upload_integrity.rs
new file mode 100644
index 00000000..385bc12f
--- /dev/null
+++ b/crates/obscura-cdp/tests/file_upload_integrity.rs
@@ -0,0 +1,128 @@
+use std::time::Duration;
+
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use tokio::net::TcpListener;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+type Ws = tokio_tungstenite::WebSocketStream<
+ tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
+
+async fn call(ws: &mut Ws, id: u64, method: &str, params: Value,
+ session: Option<&str>) -> Value {
+ let mut command = json!({"id":id, "method":method, "params":params});
+ if let Some(session) = session { command["sessionId"] = json!(session); }
+ ws.send(Message::Text(command.to_string().into())).await.unwrap();
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
+ loop {
+ let frame = tokio::time::timeout_at(deadline, ws.next()).await
+ .unwrap_or_else(|_| panic!("timeout waiting for {method}"))
+ .expect("connection closed").unwrap();
+ let Message::Text(text) = frame else { continue };
+ let reply: Value = serde_json::from_str(&text).unwrap();
+ if reply["id"].as_u64() == Some(id) { return reply; }
+ }
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn file_uploads_validate_before_reading_and_preserve_frame_identity() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ drop(listener);
+ let path = std::env::temp_dir().join(format!("obscura-upload-integrity-{}.bin", std::process::id()));
+ std::fs::write(&path, [0_u8, 128, 255, 13, 10]).unwrap();
+ let missing = path.with_extension("missing");
+ let name = path.file_name().unwrap().to_str().unwrap().to_string();
+ tokio::task::LocalSet::new().run_until(async {
+ tokio::task::spawn_local(async move {
+ obscura_cdp::server::start_with_host_and_security(
+ port, "127.0.0.1", None, false, None, true, None).await.unwrap();
+ });
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
+ let (mut ws, _) = loop {
+ match connect_async(format!("ws://127.0.0.1:{port}/devtools/browser")).await {
+ Ok(connection) => break connection,
+ Err(error) => {
+ assert!(tokio::time::Instant::now() < deadline, "server did not start: {error}");
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ }
+ };
+ let created = call(&mut ws, 1, "Target.createTarget", json!({"url":"about:blank"}), None).await;
+ let target = created["result"]["targetId"].as_str().expect("target id");
+ let session = format!("{target}-session");
+ let sid = Some(session.as_str());
+ let html = "<input id=f type=file multiple><input id=s type=file>\
+ <input id=t type=text><div id=d></div>\
+ <iframe srcdoc=\"<input id=child type=file>\"></iframe>";
+ let navigated = call(&mut ws, 2, "Page.navigate",
+ json!({"url":format!("data:text/html,{html}"), "waitUntil":"load"}), sid).await;
+ assert!(navigated.get("error").is_none(), "{navigated}");
+ let mut nodes = Vec::new();
+ for (index, selector) in ["#f", "#s", "#t", "#d"].into_iter().enumerate() {
+ let reply = call(&mut ws, 3 + index as u64, "DOM.querySelector",
+ json!({"selector":selector}), sid).await;
+ nodes.push(reply["result"]["nodeId"].as_u64().expect("node id"));
+ }
+ let selected = call(&mut ws, 7, "DOM.setFileInputFiles",
+ json!({"backendNodeId":nodes[0], "files":[path, path]}), sid).await;
+ assert!(selected.get("error").is_none(), "{selected}");
+ for (index, (node, expected)) in [
+ (999_999, "Could not find node"), (nodes[2], "not a file input"),
+ (nodes[3], "not a file input"),
+ ].into_iter().enumerate() {
+ let reply = call(&mut ws, 8 + index as u64, "DOM.setFileInputFiles",
+ json!({"nodeId":node, "files":[missing]}), sid).await;
+ let message = reply["error"]["message"].as_str().expect("target error");
+ assert!(message.contains(expected), "{reply}");
+ assert!(!message.contains("cannot read"), "read paths before validating: {reply}");
+ }
+ for (index, files) in [json!(null), json!("invalid"), json!([42]), json!([null])]
+ .into_iter().enumerate() {
+ let reply = call(&mut ws, 11 + index as u64, "DOM.setFileInputFiles",
+ json!({"nodeId":nodes[0], "files":files}), sid).await;
+ assert!(reply.get("error").is_some(), "{reply}");
+ }
+ let omitted = call(&mut ws, 15, "DOM.setFileInputFiles",
+ json!({"nodeId":nodes[0]}), sid).await;
+ assert!(omitted.get("error").is_some(), "{omitted}");
+ let state = call(&mut ws, 16, "Runtime.evaluate",
+ json!({"expression":"document.getElementById('f').files.length", "returnByValue":true}), sid).await;
+ assert_eq!(state["result"]["result"]["value"].as_f64(), Some(2.0), "{state}");
+
+ let single = call(&mut ws, 17, "DOM.setFileInputFiles",
+ json!({"nodeId":nodes[1], "files":[path, path]}), sid).await;
+ assert!(single.get("error").is_none(), "{single}");
+ let state = call(&mut ws, 18, "Runtime.evaluate",
+ json!({"expression":"document.getElementById('s').files.length", "returnByValue":true}), sid).await;
+ assert_eq!(state["result"]["result"]["value"].as_f64(), Some(1.0), "{state}");
+
+ let remote = call(&mut ws, 19, "Runtime.evaluate",
+ json!({"expression":"document.querySelector('iframe').contentDocument.getElementById('child')"}), sid).await;
+ let object = remote["result"]["result"]["objectId"].as_str().expect("child node handle");
+ let child = call(&mut ws, 20, "DOM.setFileInputFiles",
+ json!({"objectId":object, "files":[path]}), sid).await;
+ assert!(child.get("error").is_none(), "{child}");
+ let state = call(&mut ws, 21, "Runtime.evaluate", json!({
+ "expression":"(async () => {const f=document.querySelector('iframe').contentDocument.getElementById('child').files[0];return [f.name,Array.from(new Uint8Array(await f.arrayBuffer()))]})()",
+ "awaitPromise":true, "returnByValue":true,
+ }), sid).await;
+ assert_eq!(state["result"]["result"]["value"], json!([name, [0,128,255,13,10]]), "{state}");
+
+ call(&mut ws, 22, "Runtime.evaluate", json!({
+ "expression":"(() => {const original=__obscura_setInputFiles;globalThis.__obscura_setInputFiles=(el,specs,dry)=>dry ? original(el,specs,true) : false})()",
+ }), sid).await;
+ let rejected = call(&mut ws, 23, "DOM.setFileInputFiles",
+ json!({"nodeId":nodes[0], "files":[path]}), sid).await;
+ assert!(rejected["error"]["message"].as_str().unwrap().contains("Could not set files"), "{rejected}");
+ for (index, mut params) in [json!({"nodeId":null}), json!({"backendNodeId":"invalid"})]
+ .into_iter().enumerate() {
+ params["objectId"] = json!(object);
+ params["files"] = json!([missing]);
+ let reply = call(&mut ws, 24 + index as u64, "DOM.setFileInputFiles", params, sid).await;
+ assert!(reply["error"]["message"].as_str().unwrap().contains("valid nodeId"), "{reply}");
+ }
+ ws.close(None).await.unwrap();
+ }).await;
+ std::fs::remove_file(path).unwrap();
+}
diff --git a/crates/obscura-cdp/tests/integration.rs b/crates/obscura-cdp/tests/integration.rs
index 3c45da5a..46480f35 100644
--- a/crates/obscura-cdp/tests/integration.rs
+++ b/crates/obscura-cdp/tests/integration.rs
@@ -41,6 +41,7 @@ integration_tests!(
execution_context_ownership,
execution_context_pruned_on_navigation,
file_navigation_gate,
+ file_upload_integrity,
form_submit_method_bypasses_listener,
iframe_event_dispatch,
input_activation_author_accessors,
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 18f542cb..a80ba7dc 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -11961,14 +11961,15 @@ function _emptyFileList() { return _makeFileList([]); }
// Rust side. Real File objects (backed by the bytes) are created so page code can
// read them via FileReader or upload them via fetch/FormData, then input+change
// fire as a genuine selection would (issue #359).
-globalThis.__obscura_setInputFiles = function(el, specs) {
- const files = (specs || []).map((s) => {
- let bytes;
- try {
- const bin = atob(s.b64 || "");
- bytes = new Uint8Array(bin.length);
- for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
- } catch (_e) { bytes = new Uint8Array(0); }
+globalThis.__obscura_setInputFiles = function(el, specs, validateOnly = false) {
+ if (!el || _cache.get(el._nid) !== el || !(el instanceof HTMLInputElement)
+ || (el.getAttribute('type') || '').toLowerCase() !== 'file') return false;
+ if (validateOnly) return true;
+ const selected = el.hasAttribute('multiple') ? (specs || []) : (specs || []).slice(0, 1);
+ const files = selected.map((s) => {
+ const bin = atob(s.b64 || "");
+ const bytes = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return new File([bytes], s.name || "", { type: s.type || "" });
});
el._files = _makeFileList(files);
@@ -11977,8 +11978,9 @@ globalThis.__obscura_setInputFiles = function(el, specs) {
// trusted events; upload flows that gate their change handler on
// event.isTrusted (common in frameworks and anti-bot code) ignore untrusted
// ones, which would silently break the exact case this feature targets.
- try { el.dispatchEvent(globalThis.__obscura_markTrusted(new Event("input", { bubbles: true }))); } catch (_e) {}
- try { el.dispatchEvent(globalThis.__obscura_markTrusted(new Event("change", { bubbles: true }))); } catch (_e) {}
+ el.dispatchEvent(globalThis.__obscura_markTrusted(new Event("input", { bubbles: true })));
+ el.dispatchEvent(globalThis.__obscura_markTrusted(new Event("change", { bubbles: true })));
+ return true;
};
globalThis.Event = class Event {
constructor(t,o={}) { if (arguments.length < 1) throw new TypeError("Failed to construct 'Event': 1 argument required, but only 0 present."); this.type=String(t);this.bubbles=!!o.bubbles;this.cancelable=!!o.cancelable;this.composed=!!o.composed;this.defaultPrevented=false;this.target=null;this.currentTarget=null;this.eventPhase=0;this.timeStamp=performance.now();this._dispatching=false;this._propagationStopped=false;this._immediatePropagationStopped=false; }
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 6d108e9c..a938a654 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -4606,6 +4606,34 @@ impl Default for ObscuraJsRuntime {
#[cfg(test)]
mod tests {
+ #[test]
+ fn file_input_validation_is_nonmutating_and_selection_honors_multiple() {
+ let mut rt = setup_runtime("<input id=single type=file><input id=multi type=file multiple><div id=wrong></div>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const single = document.getElementById('single');
+ const multi = document.getElementById('multi');
+ const specs = [{name:'one',b64:'AID/'},{name:'two',b64:'BAU='}];
+ const events = [];
+ for (const type of ['input','change']) {
+ single.addEventListener(type, event => events.push([type,event.isTrusted]));
+ }
+ const selected = __obscura_setInputFiles(single, specs);
+ const previous = single.files;
+ const validation = __obscura_setInputFiles(single, [], true);
+ const preserved = single.files === previous;
+ __obscura_setInputFiles(multi, specs);
+ const counts = [single.files.length, multi.files.length];
+ const invalid = __obscura_setInputFiles(document.getElementById('wrong'), specs);
+ const forged = __obscura_setInputFiles(Object.create(HTMLInputElement.prototype), specs);
+ __obscura_setInputFiles(single, []);
+ return {selected,validation,preserved,counts,invalid,forged,events,empty:single.files.length};
+ })()"#).unwrap(), serde_json::json!({
+ "selected":true, "validation":true, "preserved":true, "counts":[1,2],
+ "invalid":false, "forged":false,
+ "events":[["input",true],["change",true],["input",true],["change",true]], "empty":0,
+ }));
+ }
+
#[test]
fn table_rows_are_live_ordered_readonly_collections() {
let mut rt = setup_runtime("<html><body></body></html>");
diff --git a/docs/Architecture-overview.md b/docs/Architecture-overview.md
index ea46e47a..b1399fe3 100644
--- a/docs/Architecture-overview.md
+++ b/docs/Architecture-overview.md
@@ -132,6 +132,13 @@ for Playwright frame locators or iframe screenshot fidelity.
`obscura-js/js/bootstrap.js` provides the browser globals: `document`, `window`, `navigator`, `location`, observers, fetch, indexedDB, etc.
+`DOM.setFileInputFiles` requires the existing `--allow-file-access` opt-in,
+validates the target and file-path array before reading local files, and reports
+selection failures as CDP errors. Remote handles retain their owning frame
+rather than being reduced to root-DOM node numbers. The owning realm creates
+the File objects and emits trusted input/change events; non-multiple inputs
+select only the first file. In-memory DataTransfer payloads remain a separate API.
+
The noninteractive dialog defaults dismiss `confirm()` (`false`), cancel
`prompt()` (`null`), and let `alert()` return without blocking. These functions
do not emit client-controlled CDP dialogs. `Page.handleJavaScriptDialog`