Commit Graph

12124 Commits

Author SHA1 Message Date
Simon Wülker
99ca170ed7 script: Fully initialize ResizeObserverEntry fields (#40036)
A `ResizeObserverEntry` stores of three different lists of size values:
* border box sizes (`border-box`)
* content box sizes (`content-box`)
* content box sizes, in integral device pixels
(`device-pixel-content-box`)

Currently, servo only stores content box sizes and leaves the other two
empty:

205b049fcd/components/script/dom/resizeobserver.rs (L155-L163)

It's worth noting that the `device-pixel-content-box` observation type
is not supported yet, so the only size reported will be a zero-sized
rectangle.


205b049fcd/components/script/dom/resizeobserver.rs (L328-L329)



Testing: New web platform tests start to pass
Fixes https://github.com/servo/servo/issues/38811
Part of #39790

---------

Signed-off-by: Simon Wülker <simon.wuelker@arcor.de>
Co-authored-by: Josh Matthews <josh@joshmatthews.net>
2025-10-21 00:03:23 +00:00
Tim van der Lippe
93e58de734 Implement document preloaded resources (#39794)
This aligns the request object more with the specification,
since the spec now has a `traversable_for_user_prompts` and
a separate field for the client. Before, they were present
in the same enum.

In doing so, new structs are added that are all required in
the new spec. With this we can add support for preloaded
resources in this client, which are only populated when
we have an applicable Global.

Since the spec moved things around a bit, it now has a
dedicated method to populate the client from the request.

Unfortunately none of the WPT preload tests pass, since
the requests are received out-of-order. The specification
requires us to wait for that to settle, but I haven't figured
out yet how to do that. Given that this PR is already quite
large, opted to do that in a follow-up.

Part of #35035

Signed-off-by: Tim van der Lippe <tvanderlippe@gmail.com>
2025-10-20 13:29:55 +00:00
shuppy
3fd9ebb849 script: Make file picker selection flow asynchronous (#39893)
Previously the `<input type=file>` would wait synchronously for file
selection
results from the embedder. This change moves that synchronous wait to
the
`FileManager` worker thread. The main benefit is that script is not
blocked waiting
for the embedder. The synchronous wait on the worker thread is not a
large issue
because it is run from a thread pool, though a later change could also
remove
that synchronous wait.

In addition, the API surface for file selection changes a bit as there
is now a `dismiss`
method which differentiates between selecting no file and not making a
choice at
all.

Testing: Covered by exiting WPT, WebDriver conformance, and unit tests.

---------

Signed-off-by: delan azabani <dazabani@igalia.com>
Signed-off-by: Martin Robinson <mrobinson@igalia.com>
Co-authored-by: Martin Robinson <mrobinson@igalia.com>
2025-10-20 07:33:11 +00:00
Martin Robinson
148ce3e9c7 constellation: Always include the WebViewId in Pipeline specific messages (#39974)
It would be useful for  the Constellation is ever going to store data
per-WebView for the purposes of making cleanup and resource management
easier. If that's ever going to happen the `WebView` needs to be passed
with all messages that need it. This change makes it so that messages to
the Constellation that require a Pipeline also carry a WebViewId. This
eliminates one way in which message handling might go wrong.

This avoids making the Constelaltion look up the `WebViewId` for many
messages
that it receives.

Testing: This should not change observable behavior, so should be
covered by existing tests.

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
2025-10-18 14:23:24 +00:00
Martin Robinson
c776475b3b Remove Servo's wrapper around rand (#39979)
This wrapper was added in order to eliminate the number of file
descriptors used accessing `/dev/urandom`, but these days `osrandom` and
by proxy `rand` will try to use `getrandom` on Linux and similar system
APIs on other platforms [^1].

This is a trial balloon for removing the wrapper, since almost all
modern Linux systems have `getrandom`  (available since Linux
3.17).

[^1]: https://docs.rs/getrandom/0.3.4/getrandom/#supported-targets

Testing: Should not change observable behavior (only in random ways), so
should
be covered by WPT tests.

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
2025-10-18 13:54:20 +00:00
Martin Robinson
1872fca726 script: Trigger a rendering update when calling IntersectionObserver.observe (#39967)
Observers should trigger an observation when they are installed, but
this can only happen if a rendering update happens. This change makes
sure that a rendering opportunity is triggered. This isn't discused in
the specification because we only triggering rendering updates when
necessary for performance reasons.

Testing: This fixes a timeout in
`/intersection-observer/cross-origin-tall-iframe.sub.html`.
Fixes #39831.

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
2025-10-18 07:48:03 +00:00
Simon Wülker
a417dc5f23 xpath: Don't panic in node name test when namespace prefix is unknown (#39952)
We don't need to care about namespace prefixes in name tests because
they are already resolved to namespaces at this point.

The old implementation was also masking a few other small bugs which
I've fixed here. When the namespace resolver doesn't give us any results
then we should not lookup the namespace on the node itself. In XPath,
namespaces on html elements in html documents are compared a in a
relaxed way, and we were previously also using the relaxed comparison
mode on non-html elements in html documents (like svg).

Testing: Existing tests continue to pass (and the web platform tests
contain numerous namespace tests which cover this behaviour)
Fixes https://github.com/servo/servo/issues/39939
Part of #34527

Signed-off-by: Simon Wülker <simon.wuelker@arcor.de>
2025-10-18 07:14:37 +00:00
Simon Wülker
201364060c xpath: Infer result type when reusing result value (#39958)
When the provided xpath result type is `XPathResult.ANY_TYPE` then we
need to infer the result type from the result value. Previously we were
doing this in the XPathResult constructor, but that isn't being called
when we reuse a result. Instead, we move the inferring to right after we
evaluate an expression.

Testing: This change adds a new test
Fixes https://github.com/servo/servo/issues/39955
Part of #34527

---------

Signed-off-by: Simon Wülker <simon.wuelker@arcor.de>
2025-10-18 04:01:52 +00:00
Josh Matthews
94bcef54b8 script: Mark document as unsalvageable if unclosed websockets present. (#39940)
Our implementation of
https://html.spec.whatwg.org/multipage/#unloading-document-cleanup-steps
is incomplete and doesn't consider the existence of websockets. This
change corrects that, and adds a little bit more structure to the
current document unloading implementation.

Testing: New passing tests.
Fixes: #39872

Signed-off-by: Josh Matthews <josh@joshmatthews.net>
2025-10-18 01:54:35 +00:00
Philipp Albrecht
72f6e72fbe Integrate fetch into WebSocket implementation (#36616)
# Description

For the initial WebSocket handshake, we need to create a proper
handshake request and `fetch()` it. Creating this handshake request
begins in `WebSocketMethods::Constructor()`, which sends the partially
prepared `RequestBuilder` over to `components/net/resource_thread.rs`.
There we handle the incoming `CoreResourceMsg::Fetch` message and finish
creating the handshake request in
`components/net/websocket_loader.rs::create_handshake_request()`.
Finally we fetch the request by calling
`components/net/fetch/methods.rs::fetch()`.

`fetch()` eventually calls `http_network_fetch()`. This is where the
"actual fetching" of the request takes place on a network level, which
means we need to handle WebSocket handshake requests differently than
non-WebSocket requests. I mostly moved the existing code, which uses
`tungstenite`, with some type massaging (thanks again, @jdm, for helping
me out here!). This included converting from tungstenite types to
Servo's net types (request/response).

# The tricky bits

In order to fetch the handshake request via
`components/net/fetch/methods.rs::fetch()`, we need to convert the
request URL's scheme from ws(s) to http(s). Then, we need to "undo" this
conversion again when doing CSP checks (i.e. http(s) back to ws(s)). To
avoid having this "undoing" logic in a bunch of places we introduced
`Request::original_url()`, holding the URL before the scheme conversion
took place. Unfortunately this only gets as so far. There are still some
places, where we need to explicitly check and/or convert the URL scheme
(e.g. retroactively upgrading to a secure scheme).

# Related

* https://websockets.spec.whatwg.org/#concept-websocket-establish
* https://fetch.spec.whatwg.org/#http-network-fetch
* https://github.com/w3c/webappsec-csp/issues/532

---

Fixes: #35028

---------

Signed-off-by: pylbrecht <pylbrecht@mailbox.org>
2025-10-18 01:53:37 +00:00
Simon Wülker
01641b2374 xpath: let absolute path expressions begin at the root node (#39965)
Testing: This change adds a test
Fixes #39964
Part of https://github.com/servo/servo/issues/34527

---------

Signed-off-by: Simon Wülker <simon.wuelker@arcor.de>
2025-10-17 18:11:53 +00:00
Martin Robinson
a9b9c899ed script: Delay screenshots until the first rendering update after fonts.ready (#39963)
This fixes a regression (likely from #39583) that made the result of
many font loading
tests intermittent. The issues here is that the count of fonts loading
is decremented synchronously in the `FontContext`, but the notification
to the `ScriptThread` happens asynchronously. In between the time the
decrement happens and the `ScriptThread` is notified, a rendering update
could happen which could mark a screenshot as ready to take too soon.

The solution here is to wait until the `fonts.ready` promise is
resolved, which is guaranteed to fire after all fonts have loaded. In
addition, a rendering update is queued after this happens. This means
that the screenshot will wait until that final rendering update to be
ready.

This should remove the flakiness of font load tests.

Testing: This should fix many flaky tests.
Fixes: #39953.
Fixes: #39951.
Fixes #38956.
Fixes #39408.
Fixes #39429.
Fixes #39592.
Fixes #39636.
Fixes #39650.
Fixes #39666.
Fixes #39667.
Fixes #39706.
Fixes #39750.
Fixes #39801.
Fixes #39853.
Fixes #39881.
Fixes #39950.

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
2025-10-17 17:48:19 +00:00
Martin Robinson
f004e69cd9 compositor: Remove the CompositorMsg::TouchEventProcessed message (#39811)
The renderer needs needs to know when touch events processing has
finished in the DOM in order to properly handle them. This was
previously done using the `CompositorMsg::TouchEventProcessed` message.
This message is now redudant with the general-purpose
`EmbedderMsg::InputEventHandled` message.

This change removes the former message and instead, has the
`TouchHandler` keep a `HashMap` of pending touch events which is uses to
finish their processing when they come back from script. The goal here
is reduce the number of messages sent and to keep the complexity of
touch handling more centered in the `TouchHandler`.

Testing: This should not change observable behavior, so is covered by
existing tests.

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
2025-10-17 13:51:04 +00:00
Gregory Terzian
1af34ca483 script: prevent panic when opening an auxiliary using a window with a closed browsing context(iframe) (#39922)
When one unbinds an iframe from the tree, its browsing context is
destroyed, however if script keeps a reference to the window, it can
still try to open an auxiliary, resulting in a crash because the
constellation has already removed the browsing context. This adds a
non-intermittent test for the problem, and addresses it in a seemingly
ad-hoc way by checking whether the browsing context has already been
discarded, and if so doing an early return, as part of the window open
steps.

Testing: Added a crash test in the mozilla wpt folder.
Fixes: https://github.com/servo/servo/issues/39716

---------

Signed-off-by: gterzian <2792687+gterzian@users.noreply.github.com>
2025-10-17 12:05:08 +00:00
Gregory Terzian
631a2b1268 constellation: add source browsing context info in forwarded post message (#39833)
For cross-document messaging, when the constellation forwards the
message, it can add the source browsing context and ancestry info to the
message. This saves a round-trip back to the constellation from script
later, and also allows for messages to be delivered when the source
pipeline is closed by the time of delivery(but not by the time of
forwarding by the constellation).

Testing: Updated various tests in
`/html/semantics/embedded-content/the-iframe-element/` WPT: from
TIMEOUT(because message was not delivered) or intermittent CRASH(because
the source pipeline would be closed by the time of attempted delivery.)
to FAIL.
Fixes: https://github.com/servo/servo/issues/39748

---------

Signed-off-by: gterzian <2792687+gterzian@users.noreply.github.com>
2025-10-17 11:20:53 +00:00
spuradage
113472e171 chore: remove repetitive word in comment (#39948)
remove repetitive word in comment

Signed-off-by: spuradage <spuradage@outlook.com>
2025-10-17 08:48:23 +00:00
Martin Robinson
7829650566 script: Make remaining JavaScript evaluation result serialization functions safe (#39924)
Pass in `SafeJSContext` to the rest of the JavaScript evaluation result
serialization functions in order to make them safe. Surrounded remaining
unsafe code with `unsafe {}` blocks to silence Rust compiler warnings.
Avoid calling a couple calls to `FromJSValConvertible::from_jsval` by
using the builtin `JSVal` methods.

Testing: This does not change behavior so is covered by existing tests.

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
2025-10-16 18:55:23 +00:00
Kingsley Yung
3adb685e5b script: Correct block size in bits of SHA algorithms (#39918)
The block size in bits of SHA-1, SHA-256, SHA-384 and SHA-512 should be
512, 512, 1024 and 1024, respectively, according to the specification
[FIPS-198-1](http://csrc.nist.gov/publications/fips/fips198-1/FIPS-198-1_final.pdf).

Testing: Pass some WPT tests that were expected to fail.

---------

Signed-off-by: Kingsley Yung <kingsley@kkoyung.dev>
2025-10-16 09:34:18 +00:00
Ashwin Naren
f4cd655fc2 webcrypto: Add JWK export for HMAC keys (#39806)
Finish up the work started by #39059.

---------

Signed-off-by: Ashwin Naren <arihant2math@gmail.com>
Co-authored-by: Kingsley Yung <kingsley@kkoyung.dev>
2025-10-16 04:34:10 +00:00
Euclid Ye
8971f69143 webdriver: Deserialize WebWindow and report error correctly for script execution (#39885)
We were relying on `fn WebdriverWindow` to report `NoSuchWindow` during
script execution, regardless of the fact that it is never `Fallible`. I
was really hoping to refactor this to return `Fallible` to reduce one
RTT of IPC, but there is no easy way to convert between DOM exception
56b806b129/components/script_bindings/error.rs (L15)
and JavaScriptEvaluationError
56b806b129/components/shared/embedder/lib.rs (L1092).

We also migrate `element.rs` to `script_argument_extraction.rs` to
reflect the true purpose of the file.

Testing: 10 new subtests passing.

---------

Signed-off-by: Euclid Ye <yezhizhenjiakang@gmail.com>
2025-10-16 03:26:27 +00:00
Josh Matthews
8476a783ab script: Do not force push history handling. (#39896)
Steps 12 and 13 of
https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate
contains logic to update the provided history handling mode when
navigating, but there is no else clause in the specification. This
change removes the logic in Servo that falls back to "push" mode if
neither step is executed.

Testing: New WPT test added.
Fixes: #39818

Signed-off-by: Josh Matthews <josh@joshmatthews.net>
2025-10-15 13:16:14 +00:00
Josh Matthews
383ef76dea script: Ensure scheduled timers account for suspension offset. (#39880)
When pages go into the bfcache, rendering engines record when the page
is suspended. As part of
https://html.spec.whatwg.org/multipage/browsing-the-web.html#reactivate-a-document,
any outstanding timers need to have their duration offset by the time
since the page was suspended. We used the correct offset when scheduling
new timers in a page that has been reactivated, but the wrong offset
when dealing with outstanding timers.

Testing: Lots of WPT tests that either pass or no longer timeout.
Fixes: #39545

Signed-off-by: Josh Matthews <josh@joshmatthews.net>
2025-10-15 13:14:16 +00:00
Kingsley Yung
f3b000bf30 script: Simplify dictionary conversion in SubtleCrypto (#39894)
WebCrypto API implementation involves a lot of conversion between JS
values and many different WebIDL dictionaries. We currently have two
helper functions, `value_from_js_object` and
`boxed_value_from_js_object`, to convert JS values into different WebIDL
dictionaries.

These two helper functions use `T::new`, where `T` is the WebIDL
dictionary type, to convert the values. Since `T::new` does not belong
to any trait, to make the helper functions work with different WebIDL
dictionaries as generics, we currently define the `DictionaryFromJSVal`
trait to wrap the `new` function. However, it is inconvenient to
implement the trait for each involved WebIDL dictionary.

The patch changes the conversion process to use `safe_from_jsval` from
the `SafeFromJSValConvertible` trait, instead of the `T::new` function.
Codegen has already implemented the underlying trait
`FromJSValConvertible` for those WebIDL dictionaries. We don't need to
manually implement it for each involved WebIDL dictionary. Hence, we can
make our `SubtleCrypto` implementation simpler.

Testing: Refactoring. Existing WPT tests suffice.

---------

Signed-off-by: Kingsley Yung <kingsley@kkoyung.dev>
2025-10-15 11:46:24 +00:00
minghuaw
975eb988e6 script: Fix script string transfered to mozjs with wrong encoding (#39799)
The current implementation would transfer the script string to `mozjs`
without telling `mozjs` that the string is UTF-8 encoded, causing
problems when the script carries Chinese characters. This PR fixes this
by using a correct API `mozjs::jsapi::JS_NewStringCopyUTF8N`. Also
changed `TrustedXxx::data()` to return a `&DOMString` to reduce one
unnecessary cloning when transferring script string to `mozjs`

Testing: Manual testing. Would like to ask for community ideas on
introducing new test covering this

---------

Signed-off-by: minghuaw <michael.wu1107@gmail.com>
2025-10-15 07:42:11 +00:00
shuppy
0d57fcb3e6 libservo: Merge file selection dialog into EmbedderControls (#39859)
in #39709, we introduced a single “form control” or “embedder control”
delegate that requests the embedder’s input for &lt;select> and
&lt;input type="color"> elements.

this patch partially merges &lt;input type="file"> elements into that
new system, and renames “form controls” to “embedder controls” for
consistency.

internally we continue to use a separate code path where the embedder
directly communicates with the file manager thread. subsequent work will
make the messages asynchronous via the constellation and script thread,
like other embedder controls.

Testing: this is currently tricky to write an automated test for; we
expect to write a WebDriver test for this once we make the communication
asynchronous

---------

Signed-off-by: delan azabani <dazabani@igalia.com>
Signed-off-by: Martin Robinson <mrobinson@igalia.com>
Co-authored-by: Martin Robinson <mrobinson@igalia.com>
2025-10-15 06:12:19 +00:00
Simon Wülker
0ffa1c628d script: Throw in HTMLInputElement::stepUp when step attribute is "any" (#39874)
This change aligns our implementations of `stepUp` and `stepDown` closer
with the specification.

Testing: This change rewrites and extends existing web platform tests.

---------

Signed-off-by: Simon Wülker <simon.wuelker@arcor.de>
2025-10-15 05:53:38 +00:00
Kingsley Yung
82c0b2fe4a script: Access internal slot of CryptoKey from HMAC Operations (#39863)
After the PR #39814 being merged, we can access the `[[algorithm]]`
internal slot of a `CryptoKey` directly in Rust, without doing a JS
object conversion.

This patch leverages this feature to simplify HMAC operation steps that
access the `[[algorithm]]` internal slot of `CryptoKey`.

Testing: Refactoring. Existing WPT tests suffice.

Signed-off-by: Kingsley Yung <kingsley@kkoyung.dev>
2025-10-14 18:11:42 +00:00
Euclid Ye
4665363c58 webdriver: Incoporate script execution arm into the rest match block (#39854)
Previously, we had a separate match block for script execution. The
motivation was to avoid runtime error due to persistent RefCell
immutable borrow, caused by mozjs mutation.

This PR merge blocks into one. This avoids wildcard match, helping us
identify arms that were never matched, which normally causes error.

Testing: Manually tested. This is one of two ways to avoid panic.

Signed-off-by: Euclid Ye <yezhizhenjiakang@gmail.com>
2025-10-14 12:43:14 +00:00
Simon Wülker
6cc0bfd6fd script: Convert less between string types in range-related methods of HTMLInputElement (#39846)
The current code has snippets like
`self.convert_string_to_number(&DOMString::from(attr.summarize().value))`
in various places.

The snippet wants to take the value of an attribute and parse it as a
number. In theory this is an easy problem, the attribute internally
stores a `AttrValue` (which can be treated as `str`) and the conversion
code wants a `str` - no conversions or copies necessary!

But the reality of what happens is less ideal:
`attr.summarize` allocates a `AttrInfo` containing owned copies of the
attributes namespace, name and value. The name and value are also
converted from the `AttrValue` to a `DOMString` and then back to a
`String` in the process. And then we take the value field from
`AttrInfo` and create a new DOMString from it, passing that to
`self.self.convert_string_to_number` - which ends up internally calling
`str()` on it.

All in all this is not a big issue, because this code doesn't run often.
But it's also not hard to fix, and we end up with cleaner code in the
process.

Signed-off-by: Simon Wülker <simon.wuelker@arcor.de>
2025-10-14 08:24:30 +00:00
shuppy
b88007c14b libservo: Allow Servo to hide embedder controls (#39763)
In some situations, web content may need to hide embedder controls. For
example, when focus shifts when a `<select>` box is open or when the
element showing the control is removed from the DOM. This change adds a
new API to hide embedder controls when that happens.

Testing: This change adds a new API test.

Signed-off-by: Delan Azabani <dazabani@igalia.com>
Co-authored-by: Martin Robinson <mrobinson@igalia.com>
2025-10-14 07:56:33 +00:00
Simon Wülker
a5b30e206f script: Remove RefCell around document.animations (#39845)
We never mutate this field.

Signed-off-by: Simon Wülker <simon.wuelker@arcor.de>
2025-10-14 00:00:12 +00:00
Simon Wülker
66bfb87f7f script: Pass CanGc to input-related methods that interact with SpiderMonkey (#39844)
Testing: Compile-time annotations only, no testing required.

Signed-off-by: Simon Wülker <simon.wuelker@arcor.de>
2025-10-13 23:59:37 +00:00
Gae24
6353999184 script: replace load_whole_resource with async fetch when constructing a worker (#39671)
Testing: no behaviour changes in tests result should happen
Fixes: #39621

---------

Signed-off-by: Gae24 <96017547+Gae24@users.noreply.github.com>
2025-10-13 21:11:45 +00:00
Simon Wülker
84d30339b5 xpath: Cast query result to desired type (#39764)
When running an XPath query, users supply a target result type (eg
`XPathResult.NUMBER_TYPE`). When this type does match the return value
of the query, then we need to convert to it.

See
https://searchfox.org/firefox-main/rev/ab5bf2401717970560597083d6ac72915bde2d89/dom/xslt/xpath/XPathResult.cpp#160
for the relevant part in gecko.

Testing: This change adds a test
Part of #34527

---------

Signed-off-by: Simon Wülker <simon.wuelker@arcor.de>
2025-10-13 13:20:55 +00:00
Andrei Volykhin
08cc8bc991 canvas: Reset origin clean flag on reset the context to its default state (#39768)
The canvas `origin clean` flag for 2D rendering context should be reset
on the reset the context to its default state.

See
https://html.spec.whatwg.org/multipage/#security-with-canvas-elements
    
The following operations are resetting the `origin clean` flag:
- reset() method
  https://html.spec.whatwg.org/multipage/#dom-context-2d-reset
- canvas (output bitmap) dimensions change

https://html.spec.whatwg.org/multipage/#concept-canvas-set-bitmap-dimensions
    
Testing: Improvements in the following tests
- html/semantics/embedded-content/the-canvas-element/security.reset.*
- html/semantics/embedded-content/the-canvas-element/security.resize.*

Signed-off-by: Andrei Volykhin <andrei.volykhin@gmail.com>
2025-10-13 12:11:03 +00:00
Kingsley Yung
1eb0f2cd86 script: Allow zero length in deriveBits operation of HKDF and PBKDF2 (#39829)
The WebCrypto API specification was updated
(https://github.com/w3c/webcrypto/pull/380) to allow zero length in
deriveBits operation of HKDF and PBKDF2. This patch updates our
implementation accordingly.

Testing: Pass some WPT tests that were expected to fail.

Signed-off-by: Kingsley Yung <kingsley@kkoyung.dev>
2025-10-13 11:25:58 +00:00
Kingsley Yung
af334c84c9 script: Register "get key length" operation for AES-KW (#39827)
We have already implemented the "get key length" operation for AES-KW in
`components/script/dom/subtlecrypto/aes_operation.rs`. Registering it to
`registeredAlgorithms` in the algorithm normalization makes it
functional.

Testing: Pass some WPT tests that were expected to fail.

Signed-off-by: Kingsley Yung <kingsley@kkoyung.dev>
2025-10-13 06:36:39 +00:00
Kingsley Yung
5af91c39d5 script: Change type of [[algorithm]] internal slot of CryptoKey (#39814)
CryptoKey interface has an internal slot named [[algorithm]], which
store a WebIDL dictionary [1]. CryptoKey also stores a cached ECMAScript
Object associated with the [[algorithm]] internal slot, and returns this
object when the interface member `algorithm` is called [2].

In our current implementation, when we create a new `CryptoKey`, we need
to manually construct an ECMAScript Object for the [[algorithm]]
internal slot, and provide it to `CryptoKey::new`. Then, the provided
object directly is stored in `CryptoKey`.

There are several issues with this design.

- `CryptoKey::new` accepts arbitrary ECMAScript Object via a
`HandleObject` value. It basically relies on the caller to provide a
correct object.
- When we want to access the dictionary members of the [[algorithm]]
internal slot, we need to first convert the ECMAScript Object back to a
WebIDL dictionary. Although we have a separate field in the `CryptoKey`
struct to store the `name` member of the dictionary for convenience, it
is still not easy to access other members.

This patch makes the following change: Instead of storing an ECMAScript
Object provided by the caller and a separate name for convenience, we
store (our "subtle" struct of) WebIDL dictionary type in Rust, generated
by codegen, in the [[algorithm]] internal slot. Moreover, the cached
ECMAScript Object associated with the [[algorithm]] internal slot is
constructed from the [[algorithm]] internal slot internally, and we
store it in the [[algorithm_cached]] internal slot.

The benefits of this new design are:

- The caller can directly provide the WebIDL dictionary in Rust to
`CryptoKey`, without manually creating an ECMAScript Object.
- When we want to access the [[algorithm]] internal slot, we don't need
to do a ECMAScript-Object-to-dictionary conversion.
- The Rust type system with an implementation of the
`SafeToJSValConversion` trait can guarantee the cached ECMAScript Object
associated with the [[algorithm]] internal slot is in good shape.

[1] https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-algorithm
[2] https://w3c.github.io/webcrypto/#dom-cryptokey-algorithm

Testing: Refatoring. No behavioral change. Existing WPT test suffices.

Signed-off-by: Kingsley Yung <kingsley@kkoyung.dev>
2025-10-12 16:10:34 +00:00
Tim van der Lippe
9042b68d70 Add policy container to all requests (#39775)
In preparation of adding a client to a request, we first need to add a
policy container to all requests. Some where missing and relying on
fallbacks (that need to be removed).

For worklets this adds the appropriate policy container from the
containing global, but since that's still behind a pref, no tests are
affected.

For font contexts I tried to pass through the relevant information, but
it is a tad too much. Once fontcontext knows more information about its
containing global (as the TODO also points to referrer), we should clean
this up.

Part of #35035

Signed-off-by: Tim van der Lippe <tvanderlippe@gmail.com>
2025-10-12 12:13:19 +00:00
Martin Robinson
b9b2111f34 libservo: Notify the embedder when an input event can't be sent to a Pipeline (#39810)
The `WebViewDelegate::notify_input_event_handled` method is called for
the
embedder when an input event's processing has finished within Servo.
This allows the embedder to chain the event up to parent widgets or do
some kind of post-processing such as the implementation of overridable
keybindings.

This change makes it so that this method is called even when an input
event cannot successfully be sent to a pipeline. This could happen when
an event is handled during navigation or perhaps during shutdown. In any
case, Servo should *always* tell the embedder when the event is done
processing so that they don't get eaten by the Servo widget.

Testing: This is very difficult to test as it only happens in very
specific
time-sensitive sitautions.

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
2025-10-12 09:26:38 +00:00
Simon Wülker
e1c418d8b2 XPath: Flatten the AST to make it more flexible (#39800)
The current XPath AST is tightly tied to the parser grammar. To address
issues like https://github.com/servo/servo/issues/39739, we'll want to
do optimization passes on the AST in the future, which requires relaxing
it's structure first.

This PR moves the AST structure into a separate module and flattens it
into a shape where most expressions are variants of the core
`Expression` enum.

This also has the nice side effect of being a net reduction in LoC and
making the AST *significantly* easier to read.

I think the difference between the old and new structure is best
explained by example.
One of our unit tests parses `concat('hello', ' ', 'world')`, and the
current AST looks like this:

```rust
Expr::Path(PathExpr {
    is_absolute: false,
    is_descendant: false,
    steps: vec![StepExpr::Filter(FilterExpr {
        primary: PrimaryExpr::Function(CoreFunction::Concat(vec![
            Expr::Path(PathExpr {
                is_absolute: false,
                is_descendant: false,
                steps: vec![StepExpr::Filter(FilterExpr {
                    primary: PrimaryExpr::Literal(Literal::String(
                        "hello".to_string(),
                    )),
                    predicates: PredicateListExpr { predicates: vec![] },
                })],
            }),
            Expr::Path(PathExpr {
                is_absolute: false,
                is_descendant: false,
                steps: vec![StepExpr::Filter(FilterExpr {
                    primary: PrimaryExpr::Literal(Literal::String(" ".to_string())),
                    predicates: PredicateListExpr { predicates: vec![] },
                })],
            }),
            Expr::Path(PathExpr {
                is_absolute: false,
                is_descendant: false,
                steps: vec![StepExpr::Filter(FilterExpr {
                    primary: PrimaryExpr::Literal(Literal::String(
                        "world".to_string(),
                    )),
                    predicates: PredicateListExpr { predicates: vec![] },
                })],
            }),
        ])),
        predicates: PredicateListExpr { predicates: vec![] },
    })],
}),
```
After this change, the AST looks like this:
```rust
Expression::Function(CoreFunction::Concat(vec![
    Expression::Literal(Literal::String("hello".to_string())),
    Expression::Literal(Literal::String(" ".to_string())),
    Expression::Literal(Literal::String("world".to_string())),
])),
```

Testing:  No behaviour change intended, covered by existing tests.
Part of #34527

---------

Signed-off-by: Simon Wülker <simon.wuelker@arcor.de>
2025-10-12 08:17:40 +00:00
Kingsley Yung
71442b3186 script: Migrate deriveBits/get key length operation to use new normalization (#39805)
Refactoring of the algorithm normalization in #39431 introduces a new
algorithm normalization procedure to replace the existing one, and we
continue the migration here. This patch is the last piece of this
migration.

In this patch:

- The `SubtleCrypto.deriveKey` and `SubtleCrypto.deriveBits` method are
migrated from using existing `normalize_algorithm_for_derive_bits`,
`normalize_algorithm_for_import_key` and
`normalize_algorithm_for_get_key_length` functions to using the new
`normalize_algorithm` function.
- The custom types `DeriveBitsAlgorithm`, `ImportKeyAlgorithm` and
`GetKeyLengthAlgorithm` used by `normalize_algorithm_for_derive_bits`,
`normalize_algorithm_for_import_key` and
`normalize_algorithm_for_get_key_length` are removed.
- The custom type `DigestAlgorithm` is also removed.
- The `SubtleHkdfParams::derive_bits` function is moved to sub-module
`hkdf_operation`.
- The `Subtlepkdf2Params::derive_bits` function is moved to sub-module
`pbkdf2_operation`.
- The `SubtleHmacImportParams::get_key_length` function is moved to
sub-module `hmac_operation`.
- The `get_key_length_for_aes` function is moved to sub-module
`aes_operation`.
- The `import_key_aes`, `import_key_hkdf`, `import_key_hmac` and
`import_key_pbkdf2` are removed since they are no longer in use.

Testing: Refactoring. Existing WPT tests suffice.
Fixes: Part of #39368

Signed-off-by: Kingsley Yung <kingsley@kkoyung.dev>
2025-10-12 07:55:50 +00:00
shram-laabh
1c24269ee6 Adding message argument in WrongDocument Error (#39773)
*This pull request address one of the action item of [*Provide messages
in JS errors*](https://github.com/servo/servo/issues/39053) i.e. it adds
message argument in WrongDocument Error *

Testing: *This PR is tested using CLI ./mach test-unit -p libservo
--jobs=3*
Fixes: [*Provide messages in JS
errors*](https://github.com/servo/servo/issues/39053)

---------

Signed-off-by: Ankur Gupta <ankur.gupta6519@gmail.com>
2025-10-12 03:12:15 +00:00
Kingsley Yung
e3aaf7445d script: Migrate wrapKey/unwrapKey operation to use new normalization (#39780)
Refactoring of the algorithm normalization in #39431 introduces a new
algorithm normalization procedure to replace the existing one, and we
continue the migration here.

In this patch:

- The `SubtleCrypto.wrapKey` and `SubtleCrypto.unwrapKey` method is
migrated from using existing `normalize_algorithm_for_key_wrap` function
to using the new `normalize_algorithm` function.
- `SubtleCrypto::wrap_key_aes_kw` and `SubtleCrypto::unwrap_key_aes_kw`
are moved to the sub-module `aes_operation`.
- The custom type `KeyWrapAlgorithm` used by
`normalize_algorithm_for_key_wrap` is also removed.
- The following algorithm that had been copied to `aes_operation`
sub-module are removed in this patch since they are no longer used.
  - `SubtleCrypto::encrypt_decrypt_aes_ctr`
  - `SubtleCrypto::encrypt_aes_gcm`
  - `SubtleCrypto::decrypt_aes_gcm`
  - `SubtleCrypto::export_aes_aes`

Testing: Refactoring. Existing WPT tests suffice.
Fixes: Part of #39368

Signed-off-by: Kingsley Yung <kingsley@kkoyung.dev>
2025-10-11 12:49:06 +00:00
Martin Robinson
3721fbd0fe script: Combine all Event flags into a single bitflags (#39740)
This makes the management of flags conceptually simpler and reduces the
number of instance variables in the `Event` data structure.

Testing: This should not change behavior so should be covered by
existing tests.

---------

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
2025-10-11 10:27:23 +00:00
araya
6880af31f6 fonts: Do not fall back to non-Japanese fonts for Han in Japanese language documents (#39608)
## Motivations

This PR improves fallback font algorithm for Japanese documents on macos
and Linux.

For Japanese documents, we generally use a same font for
Hiragana/Katakana/Kanji(Han).
Since their is a fallback algorithm to render serif fonts for
`Script::Han`in current implementation, it gives unnatural reading
experience for Japanese users.

## Changes
To achieve above, 
- added `lang` field to `FallbackFontSelectionOptions` struct
- pass `_x_lang` from text_run in layout component

## Screenshots
rendering https://ja.wikipedia.org/wiki/Servo

<table>
<thead>
<tr>
<th>before fixed</th>
<th>after fixed</th>

</tr>
</thead>
<tbody>
<tr>
<td>
<!-- before fixed -->
<img width="545" height="168" alt="CleanShot 2025-10-01 at 23 08 24"
src="https://github.com/user-attachments/assets/9ad7ccb0-729a-49ad-b8ce-88b1d78a2705"
/>



</td>
<td>
<!-- after fixed -->

<img width="474" height="139" alt="CleanShot 2025-10-01 at 23 07 16"
src="https://github.com/user-attachments/assets/010e8052-5a10-48e1-8367-ff29a5632d0f"
/>


</td>

</tr>
</tbody>
</table>

---------

Signed-off-by: araya <araya@araya.dev>
2025-10-11 09:07:14 +00:00
Simon Wülker
de7e776e28 script: Restrict allowed node types for XPath context node (#39751)
See
https://searchfox.org/firefox-main/rev/b30a9b734819436853abf4eba6d768037514b3f6/dom/xslt/xpath/XPathExpression.cpp#115
for the equivalent code in firefox. Chrome also throws the same error.

Testing: This change adds a test
Part of #34527

---------

Signed-off-by: Simon Wülker <simon.wuelker@arcor.de>
2025-10-11 08:28:01 +00:00
Kingsley Yung
c950f8cdf4 script: Migrate importKey operation to use new normalization (#39760)
Refactoring of the algorithm normalization in #39431 introduces a new
algorithm normalization procedure to replace the existing one, and we
continue the migration here.

In this patch:

- The `SubtleCrypto.importKey` method is migrated from using existing
`normalize_algorithm_for_import_key` function to using the new
`normalize_algorithm` function.
- The `import_key_aes`, `import_key_hkdf`, `import_key_hmac` and
`import_key_pbkdf2` are copied to the `aes_operation`, `hkdf_operation`,
`hmac_operation`, `pbkdf2_operation` submodules, according to their
types of cryptographic algorithms.
- The above `import_key_xxx` methods are supposed to move the
submodules, but they are copied without removal in this patch. It is
because they are used by the `wrapKey` and `unwrapKey` operations which
have not migrated at this moment. Once `wrapKey` and `unwrapKey` are
migrated, they can be removed.
- The custom type `ImportKeyAlgorithm` and
`normalize_algorithm_for_import_key` are supposed to be removed, but
they are not removed at this moment since they are used by the `wrapKey`
and `unwrapKey` operations which have not migrated. Once `wrapKey` and
`unwrapKey` are migrated, they can be removed.

Remarks: According to the spec, the `SubtleCrypto.exportKey` method does
not use the algorithm normalization. However, we move the "export"
counterpart of the above `import_key_xxx` functions all together. So,
some refactoring is also made to the `ExportKey` method.

Testing: Refactoring. Existing WPT tests suffice.
Fixes: Part of #39368

Signed-off-by: Kingsley Yung <kingsley@kkoyung.dev>
2025-10-10 22:56:28 +00:00
Martin Robinson
a7d9142978 libservo: Improve JavaScript evaluation error name and documentation (#39770)
Testing: this just changes a type name and adds documentation, so
doesn't need new tests.

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
2025-10-10 16:41:25 +00:00
Martin Robinson
35d4b1e937 script: Combine WebDriverJSError with JavaScriptEvaluationError and add the stack (#39647)
This change merges the WebDriver only `WebDriverJSError` with the API
`JavaScriptEvaluationError` and also allows passing `ErrorInfo`
information through to the API layer when possible. In addition, the
stack is added to `ErrorInfo` (but only in situations when evaluating
JavaScript code for WebDriver or via the API for performance reasons).

These changes allow much more useful error output when script execution
fails via WebDriver. Now the error message and source file line numbers
are printed by the test executor.

Testing: These changes should be reflected in the testing output.

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
2025-10-10 11:34:42 +00:00