The headless browser for AI agents and web scraping
Merge branch 'main' into fix/751-blob-object-url
SGavrld0cf0188dc6d
diff --cc crates/obscura-js/src/runtime.rsindex 2033d5dc,e9398b19..87139250--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@@ -3703,86 -4835,393 +4835,473 @@@ mod tests);}- // #751 — the accepted case above only asserts the `blob:` scheme, which the- // old `blob:obscura/<base36>` form also satisfied. Pin the shape itself:- // Chrome mints `blob:<document origin>/<v4 UUID>`, so a URL that names the- // engine, or carries a token no UUID parser accepts, is a regression even- // though it still starts with `blob:`.#[test]- fn a_blob_url_is_chrome_shaped() {+ fn native_metadata_does_not_retain_removed_methods() {let mut rt = setup_runtime("<html><body></body></html>");+ let value = rt.execute_runtime_script("<removed-native-method>", r#"(() => {+ const fn = AudioBuffer.prototype.copyToChannel;+ if (Function.prototype.toString.call(fn) !== 'function copyToChannel() { [native code] }') {+ throw new Error('Live method lost its native source');+ }+ delete AudioBuffer.prototype.copyToChannel;+ return fn;+ })()"#.into()).unwrap();+ let weak = deno_core::v8::Weak::new(rt.runtime().v8_isolate(), &value);+ rt.collect_garbage();+ assert!(!weak.is_empty(), "a caller-held method must remain live");+ drop(value);+ rt.collect_garbage();+ assert!(weak.is_empty(), "native-source metadata must not own a removed method");+ }- assert_eq!(- rt.evaluate(+ #[test]+ fn native_metadata_does_not_retain_removed_accessors() {+ let mut rt = setup_runtime("<html><body></body></html>");+ let value = rt.execute_runtime_script("<removed-native-accessor>", r#"(() => {+ const fn = Object.getOwnPropertyDescriptor(MouseEvent.prototype, 'x').get;+ if (Function.prototype.toString.call(fn) !== 'function get x() { [native code] }') {+ throw new Error('Live accessor lost its native source');+ }+ delete MouseEvent.prototype.x;+ return fn;+ })()"#.into()).unwrap();+ let weak = deno_core::v8::Weak::new(rt.runtime().v8_isolate(), &value);+ rt.collect_garbage();+ assert!(!weak.is_empty(), "a caller-held accessor must remain live");+ drop(value);+ rt.collect_garbage();+ assert!(weak.is_empty(), "native-source metadata must not own a removed accessor");+ }++ #[test]+ fn native_source_survives_page_replacement_of_weak_collection_methods() {+ let mut rt = setup_runtime("<html><body></body></html>");+ assert_eq!(rt.evaluate_script(r#"(() => {+ const method = AudioBuffer.prototype.copyToChannel;+ const getter = Object.getOwnPropertyDescriptor(MouseEvent.prototype, 'x').get;+ const fail = () => { throw new Error('Page collection method called'); };+ WeakSet.prototype.has = WeakSet.prototype.add = fail;+ WeakMap.prototype.has = WeakMap.prototype.get = WeakMap.prototype.set = fail;+ return [method.toString(), getter.toString()];+ })()"#).unwrap(), serde_json::json!([+ "function copyToChannel() { [native code] }",+ "function get x() { [native code] }",+ ]));+ }++ // #1013: removeAttribute('id') must update the id_index so getElementById no+ // longer returns the (still-attached) element.+ #[test]+ fn get_element_by_id_reflects_remove_attribute() {+ let mut rt = setup_runtime("<html><body><div id='test'>x</div></body></html>");+ assert_eq!(+ rt.evaluate("document.getElementById('test') !== null")+ .unwrap(),+ serde_json::json!(true),+ "the element should be found before its id is removed"+ );+ rt.evaluate("document.getElementById('test').removeAttribute('id')")+ .unwrap();+ assert_eq!(+ rt.evaluate("document.getElementById('test') === null")+ .unwrap(),+ serde_json::json!(true),+ "getElementById must not return an element whose id was removed"+ );+ }++ #[cfg(feature = "render")]+ #[test]+ fn page_transport_keeps_render_resources_cache_only_across_document_resets() {+ let standalone = ObscuraJsRuntime::new();+ assert!(+ standalone.render_resource_sync_loading_enabled(),+ "standalone render runtimes keep the compatibility loader"+ );+ standalone.set_dom(parse_html("<html><body></body></html>"));+ assert!(standalone.render_resource_sync_loading_enabled());++ let rt = ObscuraJsRuntime::new();+ rt.set_http_client(std::sync::Arc::new(obscura_net::ObscuraHttpClient::new()));+ assert!(+ !rt.render_resource_sync_loading_enabled(),+ "installing a page transport must switch the cache to cache-only"+ );+ rt.set_dom(parse_html(+ "<html><body><img src=\"https://example.test/a.png\"></body></html>",+ ));+ assert!(+ !rt.render_resource_sync_loading_enabled(),+ "set_dom rebuilds the cache and must keep it cache-only"+ );+ assert!(rt.take_dom().is_some());+ assert!(+ !rt.render_resource_sync_loading_enabled(),+ "take_dom rebuilds the cache and must keep it cache-only"+ );+ }++ #[cfg(feature = "render")]+ #[test]+ fn renderer_resource_transport_preserves_file_subresource_policy() {+ let file = "file:///tmp/obscura-render-resource.svg";+ assert!(page_render_resource_url_allowed(+ "file:///tmp/obscura-page.html",+ file+ ));+ assert!(!page_render_resource_url_allowed(+ "https://example.test/page",+ file+ ));+ assert!(page_render_resource_url_allowed(+ "https://example.test/page",+ "https://assets.test/image.svg"+ ));+ }++ #[cfg(feature = "render")]+ #[test]+ fn render_resource_in_flight_set_has_a_page_wide_bound() {+ let rt = ObscuraJsRuntime::new();+ let requests = (0..(MAX_PENDING_RENDER_RESOURCES + 4))+ .map(|index| (format!("https://assets.test/{index}.png"), None, false))+ .collect();++ assert_eq!(+ rt.mark_render_resources_in_flight(requests).len(),+ MAX_PENDING_RENDER_RESOURCES+ );+ assert!(+ rt.mark_render_resources_in_flight(vec![(+ "https://assets.test/extra.png".to_string(),+ None,+ false,+ )])+ .is_empty()+ );+ }++ /// A load that answers after the document was retired (abort is not a+ /// join) must neither seed the surviving runtime nor clear a same-URL+ /// request of the document that replaced it.+ #[cfg(feature = "render")]+ #[tokio::test(flavor = "current_thread")]+ async fn late_channel_answer_of_a_retired_document_is_discarded() {+ let url = "https://example.test/a.svg".to_string();+ let mut rt = ObscuraJsRuntime::new();+ rt.set_http_client(std::sync::Arc::new(obscura_net::ObscuraHttpClient::new()));+ rt.set_dom(parse_html(&format!(+ "<html><body><img src=\"{url}\"></body></html>"+ )));+ rt.set_url("https://example.test/page");+ let body = std::sync::Arc::<[u8]>::from(+ br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"></svg>"##+ .as_slice(),+ );+ let answer = |generation, tx: &tokio::sync::mpsc::UnboundedSender<_>| {+ tx.send(crate::ops::RenderResourceLoad {+ generation,+ url: url.clone(),+ profile: None,+ is_font: false,+ response: Some(crate::ops::RenderResourceResponse {+ url: url.clone(),+ status: 200,+ headers: Default::default(),+ body: body.clone(),+ }),+ })+ };+ // The old document's load holds the sender it was started with.+ let old_tx = rt.state.borrow().render_resource_tx.clone();+ let generation = rt.document_generation();+ rt.mark_render_resources_in_flight(vec![(url.clone(), None, false)]);+ rt.abandon_render_resources();+ assert!(!rt.has_pending_render_resources());+ assert!(+ answer(generation, &old_tx).is_err(),+ "retired channel is closed"+ );+ assert_eq!(rt.apply_render_resource_results(), 0);+ assert!(+ !rt.render_resource_is_known(&url),+ "late bytes must not seed the runtime"+ );++ // The same runtime requests the URL again; a stale-generation answer+ // that somehow reaches the live channel is fenced too.+ let requests = rt.mark_render_resources_in_flight(vec![(url.clone(), None, false)]);+ assert_eq!(requests.len(), 1);+ let live_tx = rt.state.borrow().render_resource_tx.clone();+ assert!(answer(generation.wrapping_sub(1), &live_tx).is_ok());+ assert_eq!(rt.apply_render_resource_results(), 0);+ assert!(+ rt.has_pending_render_resources(),+ "stale answer must not clear the live request"+ );+ assert!(!rt.render_resource_is_known(&url));+ assert!(answer(generation, &live_tx).is_ok());+ assert_eq!(rt.apply_render_resource_results(), 1);+ assert!(!rt.has_pending_render_resources());+ assert!(rt.render_resource_is_known(&url));+ }++ /// A runtime with only the stealth client installed has a page transport+ /// (`has_page_transport`, cache-only renderer) and must load through it.+ #[cfg(all(feature = "render", feature = "stealth"))]+ #[tokio::test(flavor = "current_thread")]+ async fn stealth_only_transport_starts_render_resource_loads() {+ let url = "http://127.0.0.1:9/a.svg".to_string();+ let mut rt = ObscuraJsRuntime::new();+ rt.set_stealth_client(std::sync::Arc::new(+ obscura_net::StealthHttpClient::with_proxy(+ std::sync::Arc::new(obscura_net::CookieJar::new()),+ None,+ true,+ ),+ ));+ assert!(rt.has_page_transport());+ assert!(!rt.render_resource_sync_loading_enabled());+ rt.set_dom(parse_html(&format!(+ "<html><body><img src=\"{url}\"></body></html>"+ )));+ rt.set_url("http://127.0.0.1:9/page");+ let requests = rt.mark_render_resources_in_flight(vec![(url.clone(), None, false)]);+ assert_eq!(+ rt.start_render_resource_loads(requests),+ 1,+ "stealth client is a transport"+ );+ assert!(rt.has_pending_render_resources());+ // The unreachable origin answers with a failed load, which settles it.+ for _ in 0..200 {+ if rt.apply_render_resource_results() > 0 || !rt.has_pending_render_resources() {+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;+ }+ assert!(+ !rt.has_pending_render_resources(),+ "the load must finish through the stealth client"+ );+ assert!(rt.render_resource_is_known(&url));+ }++ #[cfg(feature = "render")]+ #[test]+ fn live_form_values_paint_without_mutating_content_attributes() {+ let mut rt = setup_runtime(+ "<!doctype html><html><body><input id=field value=initial><input id=box type=checkbox></body></html>",+ );+ rt.set_viewport(320.0, 120.0);+ let before = rt+ .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap();+ let prepared_address =+ rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize;+ rt.evaluate("document.getElementById('field').value = 'changed'")+ .unwrap();+ assert_eq!(+ rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize,+ prepared_address,+ "live text values must not discard unchanged layout"+ );+ let changed_value = rt+ .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap();+ assert_ne!(before, changed_value, "live text value must affect pixels");+ rt.evaluate("document.getElementById('box').indeterminate = true")+ .unwrap();+ assert_eq!(+ rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize,+ prepared_address,+ "indeterminate paint state must not discard unchanged layout"+ );+ let indeterminate = rt+ .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap();+ assert_ne!(+ changed_value, indeterminate,+ "indeterminate state must affect pixels"+ );+ rt.evaluate("document.getElementById('box').indeterminate = false")+ .unwrap();+ rt.evaluate("document.getElementById('box').checked = true")+ .unwrap();+ let after = rt+ .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap();+ assert_ne!(changed_value, after, "checked state must affect pixels");+ assert_eq!(rt.evaluate("[document.getElementById('field').value, document.getElementById('field').getAttribute('value'), document.getElementById('box').getAttribute('checked'), document.querySelectorAll(':checked').length]").unwrap(), serde_json::json!(["changed", "initial", null, 1]));+ rt.evaluate("(document.getElementById('field').value = 'initial', document.getElementById('box').checked = false)").unwrap();+ assert_eq!(+ before,+ rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap()+ );+ rt.evaluate("document.getElementById('field').value = ''")+ .unwrap();+ assert_eq!(+ rt.evaluate("document.getElementById('field').value")+ .unwrap(),+ serde_json::json!("")+ );+ assert_ne!(+ before,+ rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap(),+ "empty current value must override a nonempty default"+ );+ }++ #[test]+ fn cloned_controls_keep_current_value_and_checked_state() {+ let mut rt = setup_runtime(+ "<html><body><div id=group><input id=field value=default><input id=box type=checkbox></div></body></html>",+ );+ let result = rt.evaluate("(() => {const field=document.getElementById('field'), box=document.getElementById('box');field.value='current';box.checked=true;box.indeterminate=true;const clone=document.getElementById('group').cloneNode(true);return [clone.children[0].value,clone.children[0].getAttribute('value'),clone.children[1].checked,clone.children[1].indeterminate];})()").unwrap();+ assert_eq!(+ result,+ serde_json::json!(["current", "default", true, false])+ );+ }++ #[cfg(feature = "render")]+ #[test]+ fn form_reset_restores_default_input_state_and_pixels() {+ let mut rt = setup_runtime(+ "<html><body><form id=form><input id=field value=default><input id=box type=checkbox checked></form></body></html>",+ );+ rt.set_viewport(320.0, 120.0);+ let before = rt+ .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap();+ rt.evaluate("const field=document.getElementById('field'),box=document.getElementById('box');field.value='typed';box.checked=false;box.indeterminate=true").unwrap();+ assert_ne!(+ before,+ rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap()+ );+ rt.evaluate("document.getElementById('form').reset()")+ .unwrap();+ assert_eq!(+ rt.evaluate("[field.value,field.getAttribute('value'),box.checked,box.indeterminate,box.hasAttribute('checked')]").unwrap(),+ serde_json::json!(["default", "default", true, false, true])+ );+ assert_eq!(+ before,+ rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap()+ );+ }++ // SEC-503 / #820 — createObjectURL must reject non-Blob input (an object+ // that merely has a .text() method, e.g. Response) with a TypeError, as+ // Chrome does; a real Blob is still accepted.+ #[test]+ fn create_object_url_rejects_non_blob_input() {+ let mut rt = setup_runtime("<html><body></body></html>");++ // A real Blob is accepted and yields a blob: URL.+ let ok = rt+ .evaluate("URL.createObjectURL(new Blob(['hello'])).startsWith('blob:')")+ .unwrap();+ assert_eq!(ok, serde_json::json!(true), "a real Blob must be accepted");++ // A non-Blob object with only .text() must be rejected.+ let rejected = rt+ .evaluate(+ "(function(){ try { URL.createObjectURL({ text: () => Promise.resolve('x') }); return false; }\+ catch (e) { return !!(e && e.name === 'TypeError'); } })()",+ )+ .unwrap();+ assert_eq!(+ rejected,+ serde_json::json!(true),+ "createObjectURL must throw TypeError for non-Blob input"+ );+ }+++ // #751 — the accepted case above only asserts the `blob:` scheme, which the++ // old `blob:obscura/<base36>` form also satisfied. Pin the shape itself:++ // Chrome mints `blob:<document origin>/<v4 UUID>`, so a URL that names the++ // engine, or carries a token no UUID parser accepts, is a regression even++ // though it still starts with `blob:`.++ #[test]++ fn a_blob_url_is_chrome_shaped() {++ let mut rt = setup_runtime("<html><body></body></html>");++++ assert_eq!(++ rt.evaluate(+ r#"(() => {+ const url = URL.createObjectURL(new Blob(["x"]));+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;+ const second = URL.createObjectURL(new Blob(["y"]));+ const threw = argument => {+ try {+ argument === undefined ? URL.createObjectURL() : URL.createObjectURL(argument);+ return "did not throw";+ } catch (error) {+ return error instanceof TypeError ? error.message : String(error);+ }+ };+ return {+ origin: url.slice(0, "blob:http://example.com/".length),+ uuid: uuid.test(url.slice("blob:http://example.com/".length)),+ names_the_engine: /obscura|fake/.test(url),+ unique: url !== second,+ no_argument: threw(undefined),+ string: threw("nope"),+ number: threw(7),+ null_value: threw(null),+ file_is_a_blob: URL.createObjectURL(new File(["x"], "a.txt")).startsWith("blob:http://example.com/"),+ };+ })()"#,+ )+ .unwrap(),+ serde_json::json!({+ "origin": "blob:http://example.com/",+ "uuid": true,+ "names_the_engine": false,+ "unique": true,+ "no_argument": "Failed to execute 'createObjectURL' on 'URL': 1 argument required, but only 0 present.",+ "string": "Failed to execute 'createObjectURL' on 'URL': parameter 1 is not of type 'Blob'.",+ "number": "Failed to execute 'createObjectURL' on 'URL': parameter 1 is not of type 'Blob'.",+ "null_value": "Failed to execute 'createObjectURL' on 'URL': parameter 1 is not of type 'Blob'.",+ "file_is_a_blob": true,+ })+ );+ }++ // #751 — the source has to be in the store by the time createObjectURL+ // returns. Blob-URL Worker construction is synchronous in a real browser,+ // so an async `blob.text().then()` store races the Worker constructor and+ // the Worker falls through to fetch() and fails; revocation then has to+ // remove it again rather than leaving the entry readable.+ #[test]+ fn a_blob_url_is_stored_synchronously_and_revocation_removes_it() {+ let mut rt = setup_runtime("<html><body></body></html>");++ assert_eq!(+ rt.evaluate(+ r#"(() => {+ const url = URL.createObjectURL(new Blob(["self.onmessage = () => {};"]));+ const stored = globalThis.__blobStore[url];+ URL.revokeObjectURL(url);+ return {+ stored_synchronously: stored === "self.onmessage = () => {};",+ revoked: globalThis.__blobStore[url] === undefined,+ };+ })()"#,+ )+ .unwrap(),+ serde_json::json!({+ "stored_synchronously": true,+ "revoked": true,+ })+ );+ }+// SEC-301 / SEC-302 / #792 — the profile setters must embed values safely.// set_platform must not allow a backslash-before-quote to break out of the// JS string literal (injection), and set_user_agent must not silently fail