Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(csp): convert violation event dictionaries and validate native getters
ldm05a836809ed21
diff --git a/moli-renderer-v8/src/content_security_policy.rs b/moli-renderer-v8/src/content_security_policy.rsindex 0b6bcb7d8..fec0df178 100644--- a/moli-renderer-v8/src/content_security_policy.rs+++ b/moli-renderer-v8/src/content_security_policy.rs@@ -68,7 +68,11 @@ pub(crate) enum ContentSecurityPolicyRedirectStatus {FollowedRedirect,}-#[derive(Clone, Copy, Debug, Eq, PartialEq)]+#[derive(Clone, Copy, Debug, Eq, PartialEq, crate::webidl::WebIdlEnum)]+#[webidl(+ name = "SecurityPolicyViolationEventDisposition",+ rename_all = "kebab-case"+)]pub(crate) enum ContentSecurityPolicyDisposition {Enforce,Report,@@ -193,7 +197,7 @@ pub(crate) struct ContentSecurityPolicyViolationEventFields<'a> {data_properties,enumerable)]-struct ContentSecurityPolicyViolationEventDeclaration<'scope> {+pub(crate) struct ContentSecurityPolicyViolationEventDeclaration<'scope> {#[webapi(data_property = "documentURI")]document_uri: v8::Local<'scope, v8::String>,referrer: v8::Local<'scope, v8::String>,@@ -205,9 +209,9 @@ struct ContentSecurityPolicyViolationEventDeclaration<'scope> {disposition: v8::Local<'scope, v8::String>,source_file: v8::Local<'scope, v8::String>,sample: v8::Local<'scope, v8::String>,- line_number: i32,- column_number: i32,- status_code: i32,+ line_number: u32,+ column_number: u32,+ status_code: u16,}impl<'a> ContentSecurityPolicyViolationEventFields<'a> {@@ -236,22 +240,16 @@ pub(crate) fn create_security_policy_violation_event<'s>(let declaration = security_policy_violation_event_declaration(scope, fields)?;let event = crate::context_bootstrap::new_event_state(scope);initialize_event_object(scope, event, "securitypolicyviolation", true, false);+ event.set(+ scope,+ crate::util::v8str(scope, "composed").into(),+ v8::Boolean::new(scope, true).into(),+ )?;declaration.initialize(scope, event).ok()?;mark_event_trusted(scope, event);crate::context_bootstrap::new_event_wrapper(scope, event)}-pub(crate) fn initialize_security_policy_violation_event<'s>(- scope: &mut v8::PinScope<'s, '_>,- event: v8::Local<'s, v8::Object>,- fields: &ContentSecurityPolicyViolationEventFields<'_>,-) -> bool {- let event = crate::context_bootstrap::event_backing(scope, event);- security_policy_violation_event_declaration(scope, fields)- .and_then(|declaration| declaration.initialize(scope, event).ok())- .is_some()-}-fn security_policy_violation_event_declaration<'s>(scope: &mut v8::PinScope<'s, '_>,fields: &ContentSecurityPolicyViolationEventFields<'_>,@@ -275,9 +273,11 @@ fn security_policy_violation_event_declaration<'s>(disposition,source_file,sample,- line_number: fields.line_number,- column_number: fields.column_number,- status_code: fields.status_code,+ // Native locations use zero when unavailable. Synthetic events enter+ // this shared state with their already converted unsigned IDL values.+ line_number: fields.line_number.try_into().unwrap_or_default(),+ column_number: fields.column_number.try_into().unwrap_or_default(),+ status_code: fields.status_code.try_into().unwrap_or_default(),})}diff --git a/moli-renderer-v8/src/context_bootstrap/event_template.rs b/moli-renderer-v8/src/context_bootstrap/event_template.rsindex bdb533017..c26cc03f2 100644--- a/moli-renderer-v8/src/context_bootstrap/event_template.rs+++ b/moli-renderer-v8/src/context_bootstrap/event_template.rs@@ -1,3 +1,4 @@+use super::events::event_value_attribute_getter;use super::{event_document::{document_create_event_callback, document_has_focus_callback},event_legacy::{@@ -28,7 +29,7 @@ use super::{};use crate::web_api_interfaces;use crate::{native_bridge::document, window_host};-use moli_webapi_declare::WebApiFunctionTemplate;+use moli_webapi_declare::{WebApiFunctionTemplate, WebApiFunctionTemplateDeclaration};#[derive(WebApiFunctionTemplate)]#[webapi(interface = web_api_interfaces::Event, enumerable, receiver)]@@ -316,6 +317,46 @@ struct DocumentEventTemplateMethodsDeclaration {get_selection: (),}+#[derive(WebApiFunctionTemplate)]+#[webapi(interface = web_api_interfaces::SecurityPolicyViolationEvent, enumerable, receiver)]+struct SecurityPolicyViolationEventTemplateAccessorsDeclaration {+ #[webapi(accessor_property = "documentURI", getter = event_value_attribute_getter, data = crate::util::v8str(scope, "documentURI"))]+ document_uri: (),++ #[webapi(accessor_property = "referrer", getter = event_value_attribute_getter, data = crate::util::v8str(scope, "referrer"))]+ referrer: (),++ #[webapi(accessor_property = "blockedURI", getter = event_value_attribute_getter, data = crate::util::v8str(scope, "blockedURI"))]+ blocked_uri: (),++ #[webapi(accessor_property = "effectiveDirective", getter = event_value_attribute_getter, data = crate::util::v8str(scope, "effectiveDirective"))]+ effective_directive: (),++ #[webapi(accessor_property = "violatedDirective", getter = event_value_attribute_getter, data = crate::util::v8str(scope, "violatedDirective"))]+ violated_directive: (),++ #[webapi(accessor_property = "originalPolicy", getter = event_value_attribute_getter, data = crate::util::v8str(scope, "originalPolicy"))]+ original_policy: (),++ #[webapi(accessor_property = "sourceFile", getter = event_value_attribute_getter, data = crate::util::v8str(scope, "sourceFile"))]+ source_file: (),++ #[webapi(accessor_property = "sample", getter = event_value_attribute_getter, data = crate::util::v8str(scope, "sample"))]+ sample: (),++ #[webapi(accessor_property = "disposition", getter = event_value_attribute_getter, data = crate::util::v8str(scope, "disposition"))]+ disposition: (),++ #[webapi(accessor_property = "statusCode", getter = event_value_attribute_getter, data = crate::util::v8str(scope, "statusCode"))]+ status_code: (),++ #[webapi(accessor_property = "lineNumber", getter = event_value_attribute_getter, data = crate::util::v8str(scope, "lineNumber"))]+ line_number: (),++ #[webapi(accessor_property = "columnNumber", getter = event_value_attribute_getter, data = crate::util::v8str(scope, "columnNumber"))]+ column_number: (),+}+fn install_event_base_bindings<'s>(scope: &mut v8::PinScope<'s, '_, ()>,template: v8::Local<'s, v8::FunctionTemplate>,@@ -325,6 +366,52 @@ fn install_event_base_bindings<'s>(EventBaseTemplateMethodsDeclaration::initialize_prototype_template(scope, proto);}+struct EventTemplateDeclaration {+ attributes: &'static [&'static str],+ install: for<'s, 'p> fn(&mut v8::PinScope<'s, 'p, ()>, v8::Local<'s, v8::FunctionTemplate>),+}++impl EventTemplateDeclaration {+ fn new<D: WebApiFunctionTemplateDeclaration>() -> Self {+ Self {+ attributes: D::PROTOTYPE_ATTRIBUTE_NAMES,+ install: install_declaration::<D>,+ }+ }+}++fn install_declaration<'s, D: WebApiFunctionTemplateDeclaration>(+ scope: &mut v8::PinScope<'s, '_, ()>,+ template: v8::Local<'s, v8::FunctionTemplate>,+) {+ D::initialize_template(scope, template);+ let prototype = template.prototype_template(scope);+ D::initialize_prototype_template(scope, prototype);+}++fn event_template_declaration(interface: &str) -> Option<EventTemplateDeclaration> {+ match interface {+ "SecurityPolicyViolationEvent" => Some(EventTemplateDeclaration::new::<+ SecurityPolicyViolationEventTemplateAccessorsDeclaration,+ >()),+ _ => None,+ }+}++pub(super) fn event_has_prototype_attribute(interface: &str, property: &str) -> bool {+ let mut interface = Some(interface);+ while let Some(name) = interface {+ if event_template_declaration(name)+ .is_some_and(|declaration| declaration.attributes.contains(&property))+ {+ return true;+ }+ interface =+ web_api_interfaces::descriptor(name).and_then(|descriptor| descriptor.parent_name());+ }+ false+}+pub(super) fn install_event_template_bindings<'s>(scope: &mut v8::PinScope<'s, '_, ()>,template: v8::Local<'s, v8::FunctionTemplate>,@@ -336,6 +423,11 @@ pub(super) fn install_event_template_bindings<'s>(super::events::install_value_event_template_bindings(scope, template, spec.interface.name());super::events::install_device_event_template_bindings(scope, template, spec.interface.name());+ if let Some(declaration) = event_template_declaration(spec.interface.name()) {+ (declaration.install)(scope, template);+ return;+ }+match spec.interface.name() {"UIEvent" => {let proto = template.prototype_template(scope);diff --git a/moli-renderer-v8/src/context_bootstrap/events.rs b/moli-renderer-v8/src/context_bootstrap/events.rsindex fb70a84bb..9b8dff138 100644--- a/moli-renderer-v8/src/context_bootstrap/events.rs+++ b/moli-renderer-v8/src/context_bootstrap/events.rs@@ -476,3 +476,5 @@ pub(crate) use wrappers::{event_attribute, event_bool_attribute, event_private_value, initialize_event_wrapper,new_event_state, new_event_wrapper, set_event_private_value,};++pub(in crate::context_bootstrap) use wrappers::event_value_attribute_getter;diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses.rsindex 5ba707a78..3d00ba4c7 100644--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs@@ -11,6 +11,7 @@ mod constructor;mod data;mod keyboard;mod pointer;+mod security_policy;pub(in crate::context_bootstrap::events) use basic::initialize_text_event;pub(in crate::context_bootstrap) use constructor::build_event_subclass_template;diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/constructor.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/constructor.rsindex 15f7326d9..b4ee43c24 100644--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/constructor.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/constructor.rs@@ -50,9 +50,23 @@ fn event_subclass_constructor_callback<'s>(} else {None};- let (bubbles, cancelable, composed) = storage_event_init+ let security_policy_init = if kind == EventSubclassKind::SecurityPolicyViolationEvent {+ let Some(init) = security_policy::parse_security_policy_violation_event_init(scope, &args)+ else {+ return;+ };+ Some(init)+ } else {+ None+ };+ let (bubbles, cancelable, composed) = security_policy_init.as_ref()- .map(data::StorageEventInitMembers::event_flags)+ .map(security_policy::SecurityPolicyViolationEventInit::event_flags)+ .or_else(|| {+ storage_event_init+ .as_ref()+ .map(data::StorageEventInitMembers::event_flags)+ }).unwrap_or_else(|| read_event_init(scope, &args));initialize_event_object_with_type(scope, event, event_type, bubbles, cancelable);@@ -137,9 +151,9 @@ fn event_subclass_constructor_callback<'s>(}}EventSubclassKind::SecurityPolicyViolationEvent => {- if !data::initialize_security_policy_violation_event(scope, event, init) {- return;- }+ security_policy_init+ .expect("SecurityPolicyViolationEvent init is parsed")+ .initialize(scope, event);}EventSubclassKind::NavigationCurrentEntryChangeEvent => {if !data::initialize_navigation_current_entry_change_event(scope, event, init) {diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rsindex 499839284..233428328 100644--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs@@ -249,35 +249,6 @@ struct PromiseRejectionEventInitMembers<'s> {reason: Option<v8::Local<'s, v8::Value>>,}-#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "SecurityPolicyViolationEventInit")]-struct SecurityPolicyViolationEventInitMembers {- #[webidl(name = "documentURI", default = "")]- document_uri: String,- #[webidl(default = "")]- referrer: String,- #[webidl(name = "blockedURI", default = "")]- blocked_uri: String,- #[webidl(name = "violatedDirective", default = "")]- violated_directive: String,- #[webidl(name = "effectiveDirective", default = "")]- effective_directive: String,- #[webidl(name = "originalPolicy", default = "")]- original_policy: String,- #[webidl(default = "enforce")]- disposition: String,- #[webidl(name = "sourceFile", default = "")]- source_file: String,- #[webidl(default = "")]- sample: String,- #[webidl(name = "statusCode", converter = "unsigned_short", default = 0)]- status_code: u16,- #[webidl(name = "lineNumber", converter = "long", default = 0)]- line_number: i32,- #[webidl(name = "columnNumber", converter = "long", default = 0)]- column_number: i32,-}-#[derive(WebApiObject)]#[webapi(plain, data_properties, enumerable)]struct NavigationCurrentEntryChangeEventInitDeclaration<'scope> {@@ -672,71 +643,6 @@ pub(in crate::context_bootstrap::events::subclasses) fn initialize_promise_rejectrue}-pub(in crate::context_bootstrap::events::subclasses) fn initialize_security_policy_violation_event<- 's,->(- scope: &mut v8::PinScope<'s, '_>,- event: v8::Local<'s, v8::Object>,- init: Option<v8::Local<'s, v8::Object>>,-) -> bool {- let parsed = match init {- Some(init) => {- match webidl::parse_dictionary_object::<SecurityPolicyViolationEventInitMembers>(- scope, init,- ) {- Ok(parsed) => parsed,- Err(error) => {- webidl::throw_error(scope, &error);- return false;- }- }- }- None => SecurityPolicyViolationEventInitMembers {- document_uri: String::new(),- referrer: String::new(),- blocked_uri: String::new(),- violated_directive: String::new(),- effective_directive: String::new(),- original_policy: String::new(),- disposition: "enforce".to_owned(),- source_file: String::new(),- sample: String::new(),- status_code: 0,- line_number: 0,- column_number: 0,- },- };- let disposition = match parsed.disposition.as_str() {- "enforce" => crate::content_security_policy::ContentSecurityPolicyDisposition::Enforce,- "report" => crate::content_security_policy::ContentSecurityPolicyDisposition::Report,- _ => {- throw_type_error(- scope,- "Failed to construct 'SecurityPolicyViolationEvent': disposition is not a valid SecurityPolicyViolationEventDisposition.",- );- return false;- }- };- crate::content_security_policy::initialize_security_policy_violation_event(- scope,- event,- &crate::content_security_policy::ContentSecurityPolicyViolationEventFields {- document_uri: &parsed.document_uri,- referrer: &parsed.referrer,- blocked_uri: &parsed.blocked_uri,- effective_directive: &parsed.effective_directive,- violated_directive: &parsed.violated_directive,- original_policy: &parsed.original_policy,- disposition,- source_file: &parsed.source_file,- sample: &parsed.sample,- line_number: parsed.line_number,- column_number: parsed.column_number,- status_code: i32::from(parsed.status_code),- },- )-}-pub(in crate::context_bootstrap::events::subclasses) fn initialize_navigation_current_entry_change_event<'s,>(diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/security_policy.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/security_policy.rsnew file mode 100644index 000000000..480d4f880--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/security_policy.rs@@ -0,0 +1,127 @@+use crate::content_security_policy::{+ ContentSecurityPolicyDisposition, ContentSecurityPolicyViolationEventDeclaration,+};+use crate::util::{v8_string, v8_string_from_utf16_units};+use crate::webidl;++// Convert EventInit first, then the derived members in lexical order. Keep+// DOMString code units distinct from the four USVString URL fields.+#[derive(webidl::WebIdlDictionary)]+#[webidl(prefix = "SecurityPolicyViolationEventInit")]+pub(super) struct SecurityPolicyViolationEventInit {+ #[webidl(default = false)]+ bubbles: bool,+ #[webidl(default = false)]+ cancelable: bool,+ #[webidl(default = false)]+ composed: bool,+ #[webidl(name = "blockedURI", default = "", converter = "usv_string")]+ blocked_uri: String,+ #[webidl(name = "columnNumber", default = 0)]+ column_number: u32,+ #[webidl(converter = "enum", default = ContentSecurityPolicyDisposition::Enforce)]+ disposition: ContentSecurityPolicyDisposition,+ #[webidl(name = "documentURI", default = "", converter = "usv_string")]+ document_uri: String,+ #[webidl(name = "effectiveDirective", default = webidl::DomString16(Vec::new()), converter = "raw")]+ effective_directive: webidl::DomString16,+ #[webidl(name = "lineNumber", default = 0)]+ line_number: u32,+ #[webidl(name = "originalPolicy", default = webidl::DomString16(Vec::new()), converter = "raw")]+ original_policy: webidl::DomString16,+ #[webidl(default = "", converter = "usv_string")]+ referrer: String,+ #[webidl(default = webidl::DomString16(Vec::new()), converter = "raw")]+ sample: webidl::DomString16,+ #[webidl(name = "sourceFile", default = "", converter = "usv_string")]+ source_file: String,+ #[webidl(name = "statusCode", converter = "unsigned_short", default = 0)]+ status_code: u16,+ #[webidl(name = "violatedDirective", default = webidl::DomString16(Vec::new()), converter = "raw")]+ violated_directive: webidl::DomString16,+}++impl Default for SecurityPolicyViolationEventInit {+ fn default() -> Self {+ Self {+ bubbles: false,+ cancelable: false,+ composed: false,+ blocked_uri: String::new(),+ column_number: 0,+ disposition: ContentSecurityPolicyDisposition::Enforce,+ document_uri: String::new(),+ effective_directive: webidl::DomString16(Vec::new()),+ line_number: 0,+ original_policy: webidl::DomString16(Vec::new()),+ referrer: String::new(),+ sample: webidl::DomString16(Vec::new()),+ source_file: String::new(),+ status_code: 0,+ violated_directive: webidl::DomString16(Vec::new()),+ }+ }+}++pub(super) fn parse_security_policy_violation_event_init<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: &v8::FunctionCallbackArguments<'s>,+) -> Option<SecurityPolicyViolationEventInit> {+ let parsed = webidl::dictionary_arg(+ args,+ 1,+ webidl::Context::argument("SecurityPolicyViolationEvent", 2),+ )+ .and_then(|object| match object {+ Some(object) => webidl::parse_dictionary_object(scope, object),+ None => Ok(SecurityPolicyViolationEventInit::default()),+ });+ match parsed {+ Ok(init) => Some(init),+ Err(error) => {+ webidl::throw_error(scope, &error);+ None+ }+ }+}++impl SecurityPolicyViolationEventInit {+ pub(super) fn event_flags(&self) -> (bool, bool, bool) {+ (self.bubbles, self.cancelable, self.composed)+ }++ pub(super) fn initialize<'s>(+ self,+ scope: &mut v8::PinScope<'s, '_>,+ event: v8::Local<'s, v8::Object>,+ ) {+ let document_uri = v8_string(scope, &self.document_uri).expect("USVString documentURI");+ let referrer = v8_string(scope, &self.referrer).expect("USVString referrer");+ let blocked_uri = v8_string(scope, &self.blocked_uri).expect("USVString blockedURI");+ let effective_directive = v8_string_from_utf16_units(scope, &self.effective_directive.0)+ .expect("DOMString effectiveDirective");+ let violated_directive = v8_string_from_utf16_units(scope, &self.violated_directive.0)+ .expect("DOMString violatedDirective");+ let original_policy = v8_string_from_utf16_units(scope, &self.original_policy.0)+ .expect("DOMString originalPolicy");+ let disposition = v8_string(scope, self.disposition.as_str()).expect("disposition enum");+ let source_file = v8_string(scope, &self.source_file).expect("USVString sourceFile");+ let sample = v8_string_from_utf16_units(scope, &self.sample.0).expect("DOMString sample");+ ContentSecurityPolicyViolationEventDeclaration::new(+ document_uri,+ referrer,+ blocked_uri,+ effective_directive,+ violated_directive,+ original_policy,+ disposition,+ source_file,+ sample,+ self.line_number,+ self.column_number,+ self.status_code,+ )+ .initialize(scope, event)+ .expect("SecurityPolicyViolationEvent state should initialize");+ }+}diff --git a/moli-renderer-v8/src/context_bootstrap/events/wrappers.rs b/moli-renderer-v8/src/context_bootstrap/events/wrappers.rsindex 8f6acba35..3e57f6ea8 100644--- a/moli-renderer-v8/src/context_bootstrap/events/wrappers.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/wrappers.rs@@ -122,7 +122,10 @@ pub(crate) fn initialize_event_wrapper<'s>(let property = names.get_index(scope, index)?;if property.strict_equals(trusted_key.into()) {super::base::define_event_is_trusted_accessor(scope, wrapper);- } else {+ } else if !crate::context_bootstrap::event_template::event_has_prototype_attribute(+ interface,+ &property.to_rust_string_lossy(scope),+ ) {let attributes = state.get_property_attributes(scope, property)?;bind_attribute(scope, getters, wrapper, property, attributes)?;}@@ -237,6 +240,14 @@ fn event_attribute_getter<'s, const PROJECTION: u8>(}}+pub(in crate::context_bootstrap) fn event_value_attribute_getter<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ rv: v8::ReturnValue<'_, v8::Value>,+) {+ event_attribute_getter::<0>(scope, args, rv);+}+pub(super) fn event_attribute_in_wrapper<'s>(scope: &mut v8::PinScope<'s, '_>,wrapper: v8::Local<'s, v8::Object>,diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/script_security.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/script_security.rsindex ff2c2a515..be8c3563a 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/script_security.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/script_security.rs@@ -63,7 +63,7 @@ fn security_policy_violation_event_constructor_applies_init_defaults() {assert_eq!(result,- r#"{"defaults":["","","","","","","enforce","","",0,0,0],"initialized":{"type":"custom","documentURI":"https://example.test/document","referrer":"https://example.test/referrer","blockedURI":"https://example.test/blocked","violatedDirective":"default-src","effectiveDirective":"script-src","originalPolicy":"default-src 'none'","disposition":"report","sourceFile":"https://example.test/source.js","sample":"sample","statusCode":1,"lineNumber":-2,"columnNumber":3,"trusted":false,"instance":true}}"#+ r#"{"defaults":["","","","","","","enforce","","",0,0,0],"initialized":{"type":"custom","documentURI":"https://example.test/document","referrer":"https://example.test/referrer","blockedURI":"https://example.test/blocked","violatedDirective":"default-src","effectiveDirective":"script-src","originalPolicy":"default-src 'none'","disposition":"report","sourceFile":"https://example.test/source.js","sample":"sample","statusCode":1,"lineNumber":4294967294,"columnNumber":3,"trusted":false,"instance":true}}"#);}#[test]@@ -433,6 +433,7 @@ fn document_csp_violation_event_survives_mutated_event_globals() {.eval(r#"(() => {+ const getBlockedURI = Object.getOwnPropertyDescriptor(SecurityPolicyViolationEvent.prototype, "blockedURI").get;self.Event = null;Object.defineProperty(SecurityPolicyViolationEvent.prototype, "blockedURI", {value: "prototype-blocked-uri",@@ -449,7 +450,11 @@ fn document_csp_violation_event_survives_mutated_event_globals() {self.addEventListener("securitypolicyviolation", event => {events.push({type: event.type,- blockedURI: event.blockedURI,+ blockedURI: getBlockedURI.call(event),+ publicBlockedURI: event.blockedURI,+ bubbles: event.bubbles,+ cancelable: event.cancelable,+ composed: event.composed,effectiveDirective: event.effectiveDirective,disposition: event.disposition,instance: event instanceof SecurityPolicyViolationEvent@@ -478,7 +483,7 @@ fn document_csp_violation_event_survives_mutated_event_globals() {assert_eq!(vm.eval("JSON.stringify(globalThis.__mutatedEventCspResult)").expect("queued CSP event should survive mutated event globals"),- r#"{"thrown":"CompileError","events":[{"type":"securitypolicyviolation","blockedURI":"wasm-eval","effectiveDirective":"script-src","disposition":"enforce","instance":true}]}"#+ r#"{"thrown":"CompileError","events":[{"type":"securitypolicyviolation","blockedURI":"wasm-eval","publicBlockedURI":"prototype-blocked-uri","bubbles":true,"cancelable":false,"composed":true,"effectiveDirective":"script-src","disposition":"enforce","instance":true}]}"#);}#[test]diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rsindex 8c476d857..4dab1d786 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs@@ -44,6 +44,7 @@ mod pointer_lock;mod popup_hyperlinks;mod promise_rejection;mod security_policy;+mod security_policy_event_init;mod service_worker_drain;mod session_description;mod simple_handler_object;diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy_event_core.js b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy_event_core.jsnew file mode 100644index 000000000..de1eabacd--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy_event_core.js@@ -0,0 +1,126 @@+(realms) => {+ const rows = [], errors = [];+ const record = (label, checks, observed = null) => rows.push({label, checks, observed});+ const attempt = (label, run) => { try { run(); } catch (error) { errors.push({label, error: String(error.stack || error)}); } };+ const units = text => Array.from({length: text.length}, (_, i) => text.charCodeAt(i));+ const scalar = text => text.toWellFormed();+ const unsigned = (value, bits) => { const n = Number(value); if (!Number.isFinite(n) || n === 0) return 0; const modulus = 2 ** bits; return ((Math.trunc(n) % modulus) + modulus) % modulus; };+ const urls = ['blockedURI', 'documentURI', 'referrer', 'sourceFile'];+ const strings = ['effectiveDirective', 'originalPolicy', 'sample', 'violatedDirective'];+ const numbers = ['columnNumber', 'lineNumber', 'statusCode'];+ const fields = [...urls, ...strings, ...numbers, 'disposition'];+ const keys = ['bubbles', 'cancelable', 'composed', 'blockedURI', 'columnNumber', 'disposition', 'documentURI', 'effectiveDirective', 'lineNumber', 'originalPolicy', 'referrer', 'sample', 'sourceFile', 'statusCode', 'violatedDirective'];+ for (const [r, realm] of realms.entries()) {+ const Ctor = realm.SecurityPolicyViolationEvent, prefix = `${r}/SecurityPolicyViolationEvent`;+ attempt(prefix + '/metadata', () => {+ const e = new Ctor('violation');+ record(prefix + '/constructor', {name: Ctor.name === 'SecurityPolicyViolationEvent', length: Ctor.length === 1, parent: Object.getPrototypeOf(Ctor.prototype) === realm.Event.prototype, instance: e instanceof realm.Event});+ for (const field of fields) {+ const d = Object.getOwnPropertyDescriptor(Ctor.prototype, field);+ record(prefix + '/descriptor-' + field, {getter: typeof d?.get === 'function', name: d?.get?.name === 'get ' + field, length: d?.get?.length === 0, enumerable: d?.enumerable === true, configurable: d?.configurable === true, setter: d?.set === undefined, own: !Object.hasOwn(e, field)});+ }+ });+ for (const [i, init] of [undefined, null, {}, [], function() {}, new Date(0)].entries()) attempt(prefix + '/default-' + i, () => {+ const e = new Ctor('violation', init);+ record(prefix + '/default-' + i, {strings: [...urls, ...strings].every(f => e[f] === ''), numbers: numbers.every(f => e[f] === 0), disposition: e.disposition === 'enforce', flags: !e.bubbles && !e.cancelable && !e.composed});+ });+ for (const [i, value] of [1, '', false, Symbol('init'), 1n].entries()) attempt(prefix + '/dictionary-' + i, () => {+ let error; try { new Ctor('x', value); } catch (e) { error = e; }+ record(prefix + '/dictionary-' + i, {typeError: error instanceof realm.TypeError}, error?.name || 'returned');+ });+ const values = [undefined, null, '', 'plain', '\uD800', '\uDC00', '\uD83D\uDE80', 'x\uD800y', '\0', true, false, -3, 3.5, NaN, Infinity, 1n, ['a', 'b']];+ for (const field of [...urls, ...strings]) {+ for (const [i, value] of values.entries()) attempt(prefix + '/string-' + field + '-' + i, () => {+ const raw = value === undefined ? '' : String(value), expected = urls.includes(field) ? scalar(raw) : raw;+ const actual = new Ctor('x', {[field]: value})[field];+ record(prefix + '/string-' + field + '-' + i, {value: actual === expected}, units(actual));+ });+ attempt(prefix + '/coercion-' + field, () => {+ const trace = [], input = {[Symbol.toPrimitive](hint) { trace.push(hint); return '\uD800'; }};+ const actual = new Ctor('x', {[field]: input})[field];+ record(prefix + '/coercion-' + field, {value: actual === (urls.includes(field) ? '\uFFFD' : '\uD800'), hint: trace.length === 1 && trace[0] === 'string'}, {trace, units: units(actual)});+ let error; try { new Ctor('x', {[field]: Symbol('text')}); } catch (e) { error = e; }+ record(prefix + '/symbol-' + field, {typeError: error instanceof realm.TypeError});+ });+ }+ for (const field of numbers) {+ const bits = field === 'statusCode' ? 16 : 32;+ for (const [i, value] of [undefined, null, 0, -0, -1, -3.5, 3.5, 65535, 65536, 2147483648, 4294967295, 4294967296, 4294967297, NaN, Infinity, -Infinity, true, false, '65537', 'NaN', {valueOf() { return -1; }}].entries()) attempt(prefix + '/number-' + field + '-' + i, () => {+ const expected = value === undefined ? 0 : unsigned(value, bits), actual = new Ctor('x', {[field]: value})[field];+ record(prefix + '/number-' + field + '-' + i, {value: actual === expected, positiveZero: !Object.is(actual, -0)}, actual);+ });+ for (const [i, value] of [Symbol('number'), 1n].entries()) attempt(prefix + '/invalid-number-' + field + '-' + i, () => {+ let error; try { new Ctor('x', {[field]: value}); } catch (e) { error = e; }+ record(prefix + '/invalid-number-' + field + '-' + i, {typeError: error instanceof realm.TypeError});+ });+ attempt(prefix + '/number-hint-' + field, () => {+ const trace = [], value = {[Symbol.toPrimitive](hint) { trace.push(hint); return -1; }};+ const actual = new Ctor('x', {[field]: value})[field];+ record(prefix + '/number-hint-' + field, {value: actual === 2 ** bits - 1, hint: trace.length === 1 && trace[0] === 'number'}, {actual, trace});+ });+ }+ for (const [i, value] of ['enforce', 'report', undefined, 'Enforce', '', 'report-only', null, false, 1, Symbol('enum'), 1n, ['report'], {toString() { return 'enforce'; }}].entries()) attempt(prefix + '/enum-' + i, () => {+ let e, error; try { e = new Ctor('x', {disposition: value}); } catch (caught) { error = caught; }+ const valid = [0, 1, 2, 11, 12].includes(i);+ record(prefix + '/enum-' + i, valid ? {value: e?.disposition === (value === undefined ? 'enforce' : String(value))} : {typeError: error instanceof realm.TypeError}, e?.disposition || error?.name || 'returned');+ });+ attempt(prefix + '/order', () => {+ const trace = [];+ new Ctor('x', new Proxy({}, {get(_, key) { trace.push(key); }}));+ record(prefix + '/order', {order: JSON.stringify(trace) === JSON.stringify(keys)}, trace);+ for (const [i, key] of keys.entries()) {+ const sentinel = {}, reads = []; let error;+ try { new Ctor('x', new Proxy({}, {get(_, k) { reads.push(k); if (k === key) throw sentinel; }})); } catch (e) { error = e; }+ record(prefix + '/throw-get-' + key, {identity: error === sentinel, order: JSON.stringify(reads) === JSON.stringify(keys.slice(0, i + 1))}, reads);+ }+ for (const field of [...urls, ...strings, ...numbers, 'disposition']) {+ const sentinel = {}, reads = []; let error;+ try { new Ctor('x', new Proxy({}, {get(_, key) { reads.push(key); return key === field ? {[Symbol.toPrimitive]() { throw sentinel; }} : undefined; }})); } catch (e) { error = e; }+ record(prefix + '/throw-convert-' + field, {identity: error === sentinel, order: JSON.stringify(reads) === JSON.stringify(keys.slice(0, keys.indexOf(field) + 1))}, reads);+ }+ const reads = []; let error;+ try { new Ctor('x', new Proxy({}, {get(_, key) { reads.push(key); return key === 'disposition' ? 'invalid' : undefined; }})); } catch (e) { error = e; }+ record(prefix + '/invalid-enum-stops', {typeError: error instanceof realm.TypeError, order: JSON.stringify(reads) === JSON.stringify(keys.slice(0, keys.indexOf('disposition') + 1))}, reads);+ const init = Object.create({sample: '\uD800', blockedURI: '\uD800', lineNumber: -1});+ init.bubbles = 1; init.cancelable = {}; init.composed = 'yes';+ const event = new Ctor('x', init);+ record(prefix + '/inherited', {sample: event.sample === '\uD800', blockedURI: event.blockedURI === '\uFFFD', line: event.lineNumber === 4294967295, flags: event.bubbles && event.cancelable && event.composed}, {sample: units(event.sample), blockedURI: units(event.blockedURI), line: event.lineNumber});+ });+ attempt(prefix + '/construct', () => {+ let call, missing; try { Ctor('x'); } catch (e) { call = e; } try { new Ctor(); } catch (e) { missing = e; }+ record(prefix + '/required', {call: call instanceof realm.TypeError, missing: missing instanceof realm.TypeError});+ const trace = [], type = {[Symbol.toPrimitive](hint) { trace.push('type:' + hint); return '\uD800'; }};+ const e = new Ctor(type, new Proxy({}, {get(_, key) { trace.push(key); }}));+ record(prefix + '/type-first', {type: e.type === '\uD800', order: JSON.stringify(trace) === JSON.stringify(['type:string', ...keys])}, trace);+ const sentinel = {}, reads = []; let error;+ try { new Ctor({toString() { throw sentinel; }}, new Proxy({}, {get(_, key) { reads.push(key); }})); } catch (e) { error = e; }+ record(prefix + '/type-throw', {identity: error === sentinel, reads: reads.length === 0});+ class Derived extends Ctor {}+ const d = new Derived('x', {sample: '\uD800', lineNumber: -1});+ record(prefix + '/subclass', {identity: d instanceof Derived && d instanceof Ctor, sample: d.sample === '\uD800', line: d.lineNumber === 4294967295}, {sample: units(d.sample), line: d.lineNumber});+ function Alternate() {} Alternate.prototype = Object.create(Ctor.prototype);+ const alternate = Reflect.construct(Ctor, ['x', {sample: '\uD800'}], Alternate);+ record(prefix + '/new-target', {prototype: Object.getPrototypeOf(alternate) === Alternate.prototype, sample: alternate.sample === '\uD800'}, units(alternate.sample));+ });+ for (const field of fields) attempt(prefix + '/receiver-' + field, () => {+ const getter = Object.getOwnPropertyDescriptor(Ctor.prototype, field)?.get;+ if (!getter) { record(prefix + '/receiver-' + field, {getter: false}); return; }+ const genuine = new Ctor('x'), revoked = Proxy.revocable(genuine, {}); revoked.revoke();+ for (const [i, value] of [null, undefined, {}, Object.create(Ctor.prototype), Object.create(genuine), new realm.Event('x'), new Proxy(genuine, {}), revoked.proxy].entries()) {+ let error; try { getter.call(value); } catch (e) { error = e; }+ record(prefix + '/receiver-' + field + '-' + i, {typeError: error instanceof realm.TypeError});+ }+ let traps = 0; const proxy = new Proxy(genuine, {get() { traps++; throw 'get'; }, getPrototypeOf() { traps++; throw 'prototype'; }}); let error;+ try { getter.call(proxy); } catch (e) { error = e; }+ record(prefix + '/receiver-traps-' + field, {typeError: error instanceof realm.TypeError, traps: traps === 0});+ for (const [j, other] of realms.entries()) {+ const value = urls.includes(field) || strings.includes(field) ? '\uD800' : field === 'disposition' ? 'report' : -1;+ const event = new other.SecurityPolicyViolationEvent('x', {[field]: value});+ const expected = urls.includes(field) ? '\uFFFD' : strings.includes(field) ? '\uD800' : field === 'disposition' ? 'report' : field === 'statusCode' ? 65535 : 4294967295;+ const actual = getter.call(event);+ record(prefix + '/foreign-getter-' + field + '-' + j, {value: actual === expected}, typeof actual === 'string' ? units(actual) : actual);+ }+ });+ }+ return {rows, errors};+}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy_event_init.js b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy_event_init.jsnew file mode 100644index 000000000..487273711--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy_event_init.js@@ -0,0 +1,5 @@+(() => {+ const result = globalThis.__cspEventProbe([window, document.getElementById('child').contentWindow]);+ globalThis.__uiEventResults = result;+ return result.errors.length === 0 && result.rows.every(row => Object.values(row.checks).every(value => value === true));+})()diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy_event_init.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy_event_init.rsnew file mode 100644index 000000000..0296c76ba--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy_event_init.rs@@ -0,0 +1,64 @@+use super::service_worker_drain::drain_service_worker_test_turn;+use super::*;++#[tokio::test]+async fn security_policy_events_convert_dictionaries_and_validate_native_receivers() {+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(+ "https://security-policy-events.test/",+ &loader,+ );+ vm.eval(+ r#"+ if (!document.documentElement) document.appendChild(document.createElement('html'));+ if (!document.body) document.documentElement.appendChild(document.createElement('body'));+ const frame = document.body.appendChild(document.createElement('iframe'));+ frame.id = 'child'; frame.srcdoc = '<head></head><body></body>'; void frame.contentWindow;+ 'ready'+ "#,+ )+ .unwrap();+ assert!(+ vm.run_one_child_frame_task_executor_turn(+ ChildFrameSemanticTurnKind::RealmMaterialization,+ &loader+ )+ .await+ .unwrap()+ );+ vm.drain_ready_page_task_executor_turns_for_setup(&loader, 128)+ .await+ .unwrap();+ let source = format!(+ "globalThis.__cspEventProbe = {}; {}",+ include_str!("security_policy_event_core.js"),+ include_str!("security_policy_event_init.js")+ );+ assert_eq!(vm.eval(&source).unwrap(), "true", "{}",+ vm.eval("JSON.stringify({errors:__uiEventResults.errors,failures:__uiEventResults.rows.filter(row=>Object.values(row.checks).some(value=>value!==true))})").unwrap());+}++#[tokio::test]+async fn worker_security_policy_events_use_the_same_converted_payload_and_native_brands() {+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();+ let (mut vm, browser_context_runtime) =+ new_service_worker_page_test_vm_with_loader_and_browser_context_runtime(+ "https://worker-security-policy-events.test/",+ &loader,+ );+ let source = format!(+ "globalThis.__cspEventProbe = {}; ({}).then(value => globalThis.__cspWorker = value, error => globalThis.__cspWorker = String(error));",+ include_str!("security_policy_event_core.js"),+ include_str!("security_policy_event_worker.js")+ );+ vm.eval(&source).unwrap();+ tokio::time::timeout(std::time::Duration::from_secs(10), async {+ while vm.eval("globalThis.__cspWorker !== undefined").unwrap() != "true" {+ drain_service_worker_test_turn(&mut vm, &browser_context_runtime, &loader).await;+ }+ })+ .await+ .expect("worker SecurityPolicyViolationEvent probe should settle");+ assert_eq!(vm.eval("globalThis.__cspWorker").unwrap(), "true", "{}",+ vm.eval("JSON.stringify({errors:__uiEventResults.errors,failures:__uiEventResults.rows.filter(row=>Object.values(row.checks).some(value=>value!==true))})").unwrap());+}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy_event_worker.js b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy_event_worker.jsnew file mode 100644index 000000000..0db532eae--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy_event_worker.js@@ -0,0 +1,10 @@+(async () => {+ const source = 'globalThis.__cspEventProbe = ' + globalThis.__cspEventProbe.toString() + '; postMessage(__cspEventProbe([self]));';+ const url = URL.createObjectURL(new Blob([source], {type: 'text/javascript'}));+ const worker = new Worker(url);+ let result;+ try { result = await new Promise((resolve, reject) => { worker.onmessage = e => resolve(e.data); worker.onerror = e => reject(new Error(e.message)); }); }+ finally { worker.terminate(); URL.revokeObjectURL(url); }+ globalThis.__uiEventResults = result;+ return result.errors.length === 0 && result.rows.every(row => Object.values(row.checks).every(value => value === true));+})()diff --git a/moli-renderer-v8/src/worker/thread/tests/modules.rs b/moli-renderer-v8/src/worker/thread/tests/modules.rsindex 4db311763..a2b4e63f2 100644--- a/moli-renderer-v8/src/worker/thread/tests/modules.rs+++ b/moli-renderer-v8/src/worker/thread/tests/modules.rs@@ -205,6 +205,7 @@ async fn worker_csp_violation_event_survives_mutated_event_globals() {let mut handle = spawn_test_worker_with_options(WorkerSpawnOptions::new(r#"+ const getBlockedURI = Object.getOwnPropertyDescriptor(SecurityPolicyViolationEvent.prototype, "blockedURI").get;self.Event = null;Object.defineProperty(SecurityPolicyViolationEvent.prototype, "blockedURI", {value: "prototype-blocked-uri",@@ -215,7 +216,11 @@ async fn worker_csp_violation_event_survives_mutated_event_globals() {addEventListener("securitypolicyviolation", event => {events.push({type: event.type,- blockedURI: event.blockedURI,+ blockedURI: getBlockedURI.call(event),+ publicBlockedURI: event.blockedURI,+ bubbles: event.bubbles,+ cancelable: event.cancelable,+ composed: event.composed,effectiveDirective: event.effectiveDirective,disposition: event.disposition,instance: event instanceof SecurityPolicyViolationEvent@@ -245,7 +250,7 @@ async fn worker_csp_violation_event_survives_mutated_event_globals() {.expect("channel closed");assert_eq!(expect_post_json(msg),- r#"{"events":[{"type":"securitypolicyviolation","blockedURI":"data","effectiveDirective":"script-src","disposition":"enforce","instance":true}],"name":"NetworkError","ran":false}"#+ r#"{"events":[{"type":"securitypolicyviolation","blockedURI":"data","publicBlockedURI":"prototype-blocked-uri","bubbles":true,"cancelable":false,"composed":true,"effectiveDirective":"script-src","disposition":"enforce","instance":true}],"name":"NetworkError","ran":false}"#);}