diff --git a/moli-renderer-v8/src/context_bootstrap/observer_template.rs b/moli-renderer-v8/src/context_bootstrap/observer_template.rs index 7b5d5dd3c89..4a1ca50806c 100644 --- a/moli-renderer-v8/src/context_bootstrap/observer_template.rs +++ b/moli-renderer-v8/src/context_bootstrap/observer_template.rs @@ -141,6 +141,10 @@ pub(super) fn install_observer_template_bindings<'s>( let proto = template.prototype_template(scope); super::reporting_observer::ReportingObserverPrototypeDeclaration::initialize_prototype_template(scope, proto); } + "ReportBody" => { + let proto = template.prototype_template(scope); + super::reporting_observer::records::ReportBodyPrototypeDeclaration::initialize_prototype_template(scope, proto); + } "PerformanceObserver" => { let proto = template.prototype_template(scope); PerformanceObserverTemplateMethodsDeclaration::initialize_prototype_template( diff --git a/moli-renderer-v8/src/context_bootstrap/reporting_observer.rs b/moli-renderer-v8/src/context_bootstrap/reporting_observer.rs index 6432ee7cad2..e3a84ba67bc 100644 --- a/moli-renderer-v8/src/context_bootstrap/reporting_observer.rs +++ b/moli-renderer-v8/src/context_bootstrap/reporting_observer.rs @@ -1,6 +1,6 @@ //! Reporting observers share the native callback residence and browser task //! scheduler. Reports in the global buffer are immutable serialized snapshots; -//! each observer receives separate application-visible dictionaries. +//! each observer receives separate application-visible records. use crate::common_runtime::{ CallbackRegistrationId, CallbackRegistrationKind, CallbackResidence, CommonRuntimeState, @@ -13,6 +13,8 @@ use crate::web_api_interfaces; use crate::webidl; use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject, web_api_object_target}; +pub(super) mod records; + const CALLBACK_ID: &str = "__moliReportingCallbackRegistrationId"; const CALLBACK: &str = "__moliReportingObserverCallback"; const CALLBACK_RELEVANT: &str = "__moliReportingObserverCallbackRelevant"; @@ -22,7 +24,6 @@ const BUFFERED: &str = "__moliReportingObserverBuffered"; const PENDING: &str = "__moliReportingObserverPending"; const REPORT_BUFFER: &str = "__moliReportingObserverReportBuffer"; const REPORT_TYPE: &str = "__moliReportingObserverReportType"; -const REPORT_JSON: &str = "__moliReportingObserverReportJson"; #[derive(WebApiObject)] #[webapi(interface = web_api_interfaces::ReportingObserver)] @@ -192,14 +193,9 @@ pub(crate) fn notify_report( body: serde_json::Value, ) { let report = crate::util::new_null_prototype_object(scope); + records::initialize_snapshot(scope, report, url, &body); let kind = v8_string(scope, report_type).expect("report type should allocate"); - let json = v8_string( - scope, - &serde_json::json!({"type":report_type,"url":url,"body":body}).to_string(), - ) - .expect("report should serialize"); set_private_value(scope, report, REPORT_TYPE, kind.into()); - set_private_value(scope, report, REPORT_JSON, json.into()); for observer in registered(scope) { add_report(scope, observer, report); } @@ -430,12 +426,8 @@ fn expose_reports<'s>( records.get_index(scope, index).expect("dense report queue"), ) .expect("internal report is an object"); - let json = v8::Local::::try_from( - get_private_value(scope, report, REPORT_JSON).expect("internal report JSON"), - ) - .expect("serialized report is a string"); - let exposed = v8::json::parse(scope, json).expect("native report JSON should parse"); - append(scope, reports, exposed); + let exposed = records::expose(scope, report); + append(scope, reports, exposed.into()); } reports } diff --git a/moli-renderer-v8/src/context_bootstrap/reporting_observer/records.rs b/moli-renderer-v8/src/context_bootstrap/reporting_observer/records.rs new file mode 100644 index 00000000000..a00668269a8 --- /dev/null +++ b/moli-renderer-v8/src/context_bootstrap/reporting_observer/records.rs @@ -0,0 +1,169 @@ +//! Chromium's legacy Report surface has a shared prototype without a global +//! constructor. The stored payload remains an immutable native JSON snapshot. +use super::*; + +const REPORT_PROTOTYPE: &str = "__moliReportingReportPrototype"; +const REPORT_URL: &str = "__moliReportingReportUrl"; +const REPORT_BODY: &str = "__moliReportingReportBody"; +const BODY_JSON: &str = "__moliReportingBodyJson"; + +#[derive(WebApiObject)] +#[webapi(interface = web_api_interfaces::Report)] +struct ReportDeclaration<'s> { + #[webapi(prototype)] + prototype: v8::Local<'s, v8::Object>, + #[webapi(slot = BODY_JSON)] + body_snapshot: v8::Local<'s, v8::String>, + #[webapi(slot = REPORT_TYPE)] + kind: v8::Local<'s, v8::Value>, + #[webapi(slot = REPORT_URL)] + url: v8::Local<'s, v8::Value>, + #[webapi(slot = REPORT_BODY)] + body: v8::Local<'s, v8::Value>, +} + +#[derive(WebApiObject)] +#[webapi(interface = web_api_interfaces::ReportBody)] +struct ReportBodyDeclaration<'s> { + #[webapi(slot = BODY_JSON)] + snapshot: v8::Local<'s, v8::String>, +} + +#[derive(WebApiFunctionTemplate)] +#[webapi( + interface = web_api_interfaces::Report, + enumerable, + prototype_to_string_tag = "Report" +)] +struct ReportPrototypeDeclaration { + #[webapi(accessor_property = "type", getter = slot_getter, data = v8_string(scope, REPORT_TYPE).unwrap())] + kind: (), + #[webapi(accessor_property, getter = slot_getter, data = v8_string(scope, REPORT_URL).unwrap())] + url: (), + #[webapi(accessor_property, getter = slot_getter, data = v8_string(scope, REPORT_BODY).unwrap())] + body: (), + #[webapi(method = "toJSON", length = 0, callback = report_to_json)] + to_json: (), +} + +#[derive(WebApiObject)] +#[webapi(plain, data_properties, enumerable, no_dynamic_constructor)] +struct ReportSnapshotDeclaration<'s> { + r#type: v8::Local<'s, v8::Value>, + url: v8::Local<'s, v8::Value>, + body: v8::Local<'s, v8::Value>, +} + +#[derive(WebApiFunctionTemplate)] +#[webapi(interface = web_api_interfaces::ReportBody, enumerable)] +pub(in crate::context_bootstrap) struct ReportBodyPrototypeDeclaration { + #[webapi(method = "toJSON", length = 0, callback = body_to_json)] + to_json: (), +} + +pub(super) fn initialize_snapshot( + scope: &mut v8::PinScope<'_, '_>, + record: v8::Local<'_, v8::Object>, + url: &str, + body: &serde_json::Value, +) { + let url = v8_string(scope, url).expect("report URL should allocate"); + let body = v8_string(scope, &body.to_string()).expect("report body should serialize"); + set_private_value(scope, record, REPORT_URL, url.into()); + set_private_value(scope, record, BODY_JSON, body.into()); +} + +fn report_prototype<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Object> { + let global = scope.get_current_context().global(scope); + if let Some(value) = get_private_value(scope, global, REPORT_PROTOTYPE) { + return v8::Local::::try_from(value).expect("Report prototype is an object"); + } + let template = v8::ObjectTemplate::new(scope); + ReportPrototypeDeclaration::initialize_prototype_template(scope, template); + let prototype = template + .new_instance(scope) + .expect("Report prototype should allocate"); + set_private_value(scope, global, REPORT_PROTOTYPE, prototype.into()); + prototype +} + +fn snapshot<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, + slot: &str, +) -> v8::Local<'s, v8::Value> { + let json = v8::Local::::try_from( + get_private_value(scope, object, slot).expect("native report snapshot"), + ) + .expect("report snapshot is a string"); + v8::json::parse(scope, json).expect("native report JSON should parse") +} + +pub(super) fn expose<'s>( + scope: &mut v8::PinScope<'s, '_>, + record: v8::Local<'s, v8::Object>, +) -> v8::Local<'s, v8::Object> { + let kind = get_private_value(scope, record, REPORT_TYPE).expect("native report type"); + let url = get_private_value(scope, record, REPORT_URL).expect("native report URL"); + let body_json = v8::Local::::try_from( + get_private_value(scope, record, BODY_JSON).expect("native report body JSON"), + ) + .expect("report body JSON is a string"); + let kind_name = kind.to_rust_string_lossy(scope); + let body = if matches!(kind_name.as_str(), "coep" | "dip") { + ReportBodyDeclaration::new(body_json) + .bind(scope) + .expect("native ReportBody should bind") + .into() + } else { + // Synthetic diagnostic report families have arbitrary dictionary data; + // keep those payloads as independent ordinary records for each consumer. + snapshot(scope, record, BODY_JSON) + }; + let prototype = report_prototype(scope); + let object = v8::Object::new(scope); + // Report has no global constructor. Initialize the explicit prototype + // directly instead of resolving an author-defined global Report property. + ReportDeclaration::new(prototype, body_json, kind, url, body) + .initialize(scope, object) + .expect("native Report should initialize"); + object +} + +fn slot_getter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + let receiver = web_api_object_target(scope, args.this()).expect("branded Report receiver"); + let slot = args.data().to_rust_string_lossy(scope); + rv.set(get_private_value(scope, receiver, &slot).expect("native Report attribute")); +} + +fn report_to_json<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + let receiver = web_api_object_target(scope, args.this()).expect("branded Report receiver"); + let kind = get_private_value(scope, receiver, REPORT_TYPE).expect("native Report type"); + let url = get_private_value(scope, receiver, REPORT_URL).expect("native Report URL"); + let body = snapshot(scope, receiver, BODY_JSON); + let snapshot = ReportSnapshotDeclaration { + r#type: kind, + url, + body, + } + .bind(scope) + .expect("Report snapshot should bind"); + rv.set(snapshot.into()); +} + +fn body_to_json<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + let receiver = web_api_object_target(scope, args.this()).expect("branded ReportBody receiver"); + rv.set(snapshot(scope, receiver, BODY_JSON)); +} diff --git a/moli-renderer-v8/src/script_vm/tests/reporting_observer.rs b/moli-renderer-v8/src/script_vm/tests/reporting_observer.rs index 14413c0762c..682ca3efe3d 100644 --- a/moli-renderer-v8/src/script_vm/tests/reporting_observer.rs +++ b/moli-renderer-v8/src/script_vm/tests/reporting_observer.rs @@ -143,7 +143,7 @@ fn reporting_observer_converts_callback_and_returned_records_in_the_consumer_rea globalThis.other=frame.contentWindow;globalThis.calls=[]; globalThis.observer=new ReportingObserver(other.Function('reports,self',` parent.calls.push([reports instanceof Array, - Object.getPrototypeOf(reports[0])===Object.prototype, + Object.getPrototypeOf(Object.getPrototypeOf(reports[0]))===Object.prototype&&Object.prototype.toString.call(reports[0])==='[object Report]', Object.getPrototypeOf(reports[0].body)===Object.prototype, this===self,reports[0].body.value]); `)); @@ -163,7 +163,7 @@ fn reporting_observer_converts_callback_and_returned_records_in_the_consumer_rea r#"(() => { const records=other.ReportingObserver.prototype.takeRecords.call(observer); return JSON.stringify([records instanceof other.Array, - Object.getPrototypeOf(records[0])===other.Object.prototype, + Object.getPrototypeOf(Object.getPrototypeOf(records[0]))===other.Object.prototype&&Object.prototype.toString.call(records[0])==='[object Report]', Object.getPrototypeOf(records[0].body)===other.Object.prototype, records[0].body.value,observer.takeRecords().length]); })()"# @@ -230,3 +230,49 @@ fn reporting_observer_callback_and_owner_realm_retirement_suppresses_pending_del drain_reporting_tasks(&mut vm); assert_eq!(vm.eval("calls").unwrap(), "0"); } + +#[test] +fn reporting_records_use_hidden_native_prototypes_and_immutable_json_snapshots() { + let mut vm = new_storage_page_task_executor_test_vm("https://reporting-records.test/"); + vm.eval("document.body.innerHTML='';globalThis.other=child.contentWindow;globalThis.observer=new ReportingObserver(()=>{});observer.observe();").unwrap(); + let context = &vm.current_main_world().unwrap().context as *const _; + vm.with_context_scope_by_ptr_and_checkpoint_for_test(context,|scope,_|{ + crate::context_bootstrap::notify_reporting_observers(scope,"coep","https://reporting-records.test/",serde_json::json!({"type":"corp","blockedURL":"https://remote.test/image","destination":"","disposition":"enforce"})); + Ok(()) + }).unwrap(); + assert_eq!(vm.eval(r#"(() => { + if(typeof Report!=='undefined'||typeof other.Report!=='undefined')return 'global Report'; + let constructorLookups=0; + Object.defineProperty(other,'Report',{configurable:true,get(){constructorLookups++;throw Error('public Report getter');}}); + const record=other.ReportingObserver.prototype.takeRecords.call(observer)[0]; + delete other.Report; + if(constructorLookups!==0)return 'constructor lookup'; + const proto=Object.getPrototypeOf(record);const body=record.body; + if(Reflect.ownKeys(record).length!==0||Reflect.ownKeys(body).length!==0)return 'own properties'; + if(Object.getPrototypeOf(proto)!==other.Object.prototype||Object.hasOwn(proto,'constructor'))return 'Report prototype'; + if(Object.prototype.toString.call(record)!=='[object Report]'||Object.prototype.toString.call(body)!=='[object ReportBody]')return 'tags'; + if(Object.getPrototypeOf(body)!==other.ReportBody.prototype)return 'body prototype'; + const descriptor=Object.getOwnPropertyDescriptor(proto,'type'); + if(!descriptor.enumerable||!descriptor.configurable||descriptor.set!==undefined)return 'readonly attribute'; + if(record.type!=='coep'||record.url!=='https://reporting-records.test/')return 'attributes'; + const serialize=proto.toJSON;const serializeBody=other.ReportBody.prototype.toJSON; + const expected={type:'corp',blockedURL:'https://remote.test/image',destination:'',disposition:'enforce'}; + const first=serialize.call(record);first.body.blockedURL='changed'; + if(serialize.call(record).body.blockedURL!==expected.blockedURL)return 'shared snapshot'; + if(serializeBody.call(body).blockedURL!==expected.blockedURL)return 'body snapshot'; + Object.defineProperties(record,{type:{get(){throw Error('public type getter')}},body:{get(){throw Error('public body getter')}},url:{value:'https://forged.test/'}}); + const snapshot=serialize.call(record); + if(Object.keys(snapshot).join(',')!=='type,url,body')return 'snapshot keys'; + if(snapshot.type!=='coep'||snapshot.url!=='https://reporting-records.test/'||snapshot.body.blockedURL!==expected.blockedURL)return 'public override'; + if(Object.getPrototypeOf(snapshot)!==other.Object.prototype||Object.getPrototypeOf(snapshot.body)!==other.Object.prototype)return 'snapshot realm'; + for(const [real,method] of [[record,serialize],[body,serializeBody]]){ + let traps=0;const proxy=new Proxy(real,{get(){traps++;throw Error('proxy get')}}); + for(const fake of [{},Object.create(real),proxy]){ + try{method.call(fake);return 'accepted forged receiver';} + catch(error){if(!(error instanceof other.TypeError)||error instanceof TypeError)return 'error realm';} + } + if(traps!==0)return 'proxy traps'; + } + return 'true'; + })()"#).unwrap(),"true"); +} diff --git a/moli-webapi/src/interfaces.rs b/moli-webapi/src/interfaces.rs index 613b44f668f..57e04d4aaf3 100644 --- a/moli-webapi/src/interfaces.rs +++ b/moli-webapi/src/interfaces.rs @@ -102,6 +102,7 @@ interfaces! { PerformanceEventTiming: PerformanceEntry; PerformancePaintTiming: PerformanceEntry; PerformanceServerTiming; + Report; ReportBody; ReportingObserver; SpeechSynthesisErrorEvent: SpeechSynthesisEvent;