diff --git a/moli-core/tests/fetch_behaviors/location_origin.rs b/moli-core/tests/fetch_behaviors/location_origin.rs index b762e0f0326..6edbc205ab5 100644 --- a/moli-core/tests/fetch_behaviors/location_origin.rs +++ b/moli-core/tests/fetch_behaviors/location_origin.rs @@ -18,7 +18,27 @@ async fn serve(mut socket: tokio::net::TcpStream) -> Result<()> { .context("request target")?; let url = url::Url::parse(&format!("http://fixture{path}"))?; const REPORT: &str = include_str!("../fixtures/location-origin-report.js"); + const STORAGE_REPORT: &str = include_str!("../fixtures/storage-origin-report.js"); let (mime, body) = match url.path() { + "/storage-report.js" => ("text/javascript", STORAGE_REPORT.to_owned()), + "/storage-report" => ( + "text/html", + format!( + r#""# + ), + ), "/origin-report.js" => ("text/javascript", REPORT.to_owned()), "/origin-report" => ( "text/html", @@ -41,8 +61,7 @@ async fn serve(mut socket: tokio::net::TcpStream) -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread")] -async fn location_origin_serializes_the_url_without_changing_document_security() -> Result<()> { +async fn run_origin_surface_fixture(fixture: &str, expected_observations: usize) -> Result<()> { let local = tokio::net::TcpListener::bind("127.0.0.1:0").await?; let remote = tokio::net::TcpListener::bind("127.0.0.1:0").await?; let origins = [ @@ -74,7 +93,7 @@ async fn location_origin_serializes_the_url_without_changing_document_security() let script = format!( "(globalThis.originTestOrigins={}, {})", serde_json::to_string(&origins)?, - include_str!("../fixtures/location-url-origin.js") + fixture ); let result = page .evaluate_runtime_expression_with_await_async(&script, true) @@ -82,7 +101,10 @@ async fn location_origin_serializes_the_url_without_changing_document_security() let observed: serde_json::Value = serde_json::from_str(result["value"].as_str().context("Location origin result")?)?; assert_eq!(observed["errors"], serde_json::json!([])); - assert_eq!(observed["observations"].as_array().unwrap().len(), 15); + assert_eq!( + observed["observations"].as_array().unwrap().len(), + expected_observations + ); Ok::<_, anyhow::Error>(()) }) .await; @@ -90,3 +112,13 @@ async fn location_origin_serializes_the_url_without_changing_document_security() server.await??; result? } + +#[tokio::test(flavor = "multi_thread")] +async fn location_origin_serializes_the_url_without_changing_document_security() -> Result<()> { + run_origin_surface_fixture(include_str!("../fixtures/location-url-origin.js"), 15).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn popup_storage_getters_enforce_receiver_and_document_origin_checks() -> Result<()> { + run_origin_surface_fixture(include_str!("../fixtures/popup-storage-origin.js"), 10).await +} diff --git a/moli-core/tests/fixtures/popup-storage-origin.js b/moli-core/tests/fixtures/popup-storage-origin.js new file mode 100644 index 00000000000..9596e8b74de --- /dev/null +++ b/moli-core/tests/fixtures/popup-storage-origin.js @@ -0,0 +1,81 @@ +(async () => { + const [home, other] = globalThis.originTestOrigins || globalThis.__fetchOrigins; + const inspect = (0, eval)(await (await fetch(home + '/storage-report.js')).text()); + const keys = ['localStorage', 'sessionStorage']; + const getters = keys.map(name => Object.getOwnPropertyDescriptor(self, name).get); + const errors = [], observations = []; + const check = (name, report, child) => { + const expectedAccess = report.origin === 'null' ? 'SecurityError' : 'accessible'; + const expectedGetter = report.origin === 'null' ? 'SecurityError' : 'same'; + const borrowed = getters.map(getter => { + try { getter.call(child); return 'accessible'; } catch (error) { return error.name; } + }); + observations.push({name, report, borrowed}); + for (const key of keys) { + const value = report.storage[key]; + if (JSON.stringify(value.descriptor) !== JSON.stringify(['function', 'undefined', true, true, false]) || + value.access !== expectedAccess || value.ownGetter !== expectedGetter || value.forged !== 'TypeError') { + errors.push({name, key, value, expectedAccess, expectedGetter}); + } + } + const expectedBorrowed = report.origin === home ? 'accessible' : 'SecurityError'; + if (borrowed.some(value => value !== expectedBorrowed)) errors.push({name, borrowed, expectedBorrowed}); + }; + const cases = [ + ['popup HTTP', {}, home], + ['CSP sandbox popup', {csp: 'sandbox allow-scripts'}, 'null'], + ['CSP same-origin popup', {csp: 'sandbox allow-scripts allow-same-origin'}, home], + ['cross-origin popup', {remote: true}, other], + ['inherited sandbox popup', {sandbox: 'allow-scripts allow-popups'}, 'null'], + ['escaped sandbox popup', {sandbox: 'allow-scripts allow-popups allow-popups-to-escape-sandbox'}, home], + ['CSP sandbox iframe', {frame: true, csp: 'sandbox allow-scripts'}, 'null'], + ['same-origin iframe', {frame: true}, home], + ]; + for (const [name, options, expectedOrigin] of cases) { + const token = 'storage-' + observations.length; + const url = new URL('/storage-report', options.remote ? other : home); + url.searchParams.set('token', token); + if (options.csp) url.searchParams.set('csp', options.csp); + if (options.sandbox) url.searchParams.set('launch', '1'); + let popup, frame, reportedWindow, listener, timer; + try { + const event = await new Promise((resolve, reject) => { + listener = event => { if (event.data && event.data.token === token) resolve(event); }; + addEventListener('message', listener); + timer = setTimeout(() => reject(new Error('child did not report')), 5000); + if (options.frame || options.sandbox) { + frame = document.createElement('iframe'); + if (options.sandbox) frame.setAttribute('sandbox', options.sandbox); + frame.src = url.href; document.body.append(frame); + } else { + popup = open(url.href, '_blank'); + // Seed both caches in the initial same-origin Document. A later + // sandboxed response must still deny access to its Storage getters. + for (const key of keys) popup[key]; + } + }); + reportedWindow = event.source; + if (event.data.origin !== expectedOrigin || event.origin !== expectedOrigin) errors.push({name, origin: event.data.origin, messageOrigin: event.origin, expectedOrigin}); + check(name, event.data, reportedWindow); + } catch (error) { + observations.push({name, error: String(error)}); errors.push({name, error: String(error)}); + } finally { + clearTimeout(timer); removeEventListener('message', listener); + if (options.sandbox && reportedWindow) reportedWindow.close(); + if (popup) popup.close(); + if (frame) frame.remove(); + } + } + const blank = open(); + try { check('initial popup', inspect(blank, 'initial'), blank); } finally { blank.close(); } + // Closing is queued: the current task must still see the same Storage objects. + const closing = open(); + const cached = keys.map(key => closing[key]); + closing.close(); + const retained = keys.map((key, index) => { + try { return closing[key] === cached[index]; } catch (error) { return error.name; } + }); + observations.push({name: 'queued popup close', retained}); + if (!closing.closed || retained.some(value => value !== true)) errors.push({name: 'queued popup close', retained}); + return JSON.stringify({errors, observations}); +})() diff --git a/moli-core/tests/fixtures/storage-origin-report.js b/moli-core/tests/fixtures/storage-origin-report.js new file mode 100644 index 00000000000..fe8ef575bba --- /dev/null +++ b/moli-core/tests/fixtures/storage-origin-report.js @@ -0,0 +1,17 @@ +(function inspectStorage(target, token) { + const read = callback => { + try { return callback(); } catch (error) { return error.name; } + }; + const storage = {}; + for (const name of ['localStorage', 'sessionStorage']) { + const descriptor = Object.getOwnPropertyDescriptor(target, name); + storage[name] = { + descriptor: descriptor && [typeof descriptor.get, typeof descriptor.set, + descriptor.enumerable, descriptor.configurable, 'value' in descriptor], + access: read(() => { target[name].getItem('storage-origin-' + token); return 'accessible'; }), + ownGetter: read(() => descriptor.get.call(target) === target[name] ? 'same' : 'different'), + forged: read(() => { descriptor.get.call({}); return 'accepted'; }), + }; + } + return {token, origin: target.origin, storage}; +})