Truly independent web browser
LibWeb: Serialize wrapped JWKs in a new global object
Tim Ledbetter3154ecb0e861
diff --git a/Libraries/LibWeb/Bindings/NewGlobalObject.cpp b/Libraries/LibWeb/Bindings/NewGlobalObject.cppindex 4116e5a589c..833c6db2b61 100644--- a/Libraries/LibWeb/Bindings/NewGlobalObject.cpp+++ b/Libraries/LibWeb/Bindings/NewGlobalObject.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <LibJS/Runtime/JSONObject.h>#include <LibWeb/Bindings/NewGlobalObject.h>#include <LibWeb/HTML/StructuredSerialize.h>#include <LibWeb/WebIDL/ExceptionOrUtils.h>@@ -17,4 +18,14 @@ JS::Completion throw_copy_of_error_in_current_realm(JS::VM& vm, JS::Value error)return JS::throw_completion(TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] { return HTML::structured_deserialize(vm, serialized_error, realm); })));}+JS::ThrowCompletionOr<Utf16String> serialize_to_json_in_a_new_global_object(JS::VM& vm, Function<JS::Value(JS::Realm&)> const& create_value)+{+ auto json = TRY(run_in_a_new_global_object<Optional<Utf16String>>(vm, [&](JS::Realm& realm) {+ return JS::JSONObject::stringify_impl(vm, create_value(realm), JS::Value {}, JS::Value {});+ }));+ if (!json.has_value())+ return vm.throw_completion<JS::TypeError>("Result of stringifying value must not be undefined"_utf16);+ return json.release_value();+}+}diff --git a/Libraries/LibWeb/Bindings/NewGlobalObject.h b/Libraries/LibWeb/Bindings/NewGlobalObject.hindex e6eb760add7..c6a42682b86 100644--- a/Libraries/LibWeb/Bindings/NewGlobalObject.h+++ b/Libraries/LibWeb/Bindings/NewGlobalObject.h@@ -7,6 +7,7 @@#pragma once#include <AK/Function.h>+#include <AK/Utf16String.h>#include <LibJS/Forward.h>#include <LibJS/Runtime/Completion.h>#include <LibJS/Runtime/Realm.h>@@ -31,4 +32,6 @@ JS::ThrowCompletionOr<T> run_in_a_new_global_object(JS::VM& vm, Function<JS::Thrreturn result;}+JS::ThrowCompletionOr<Utf16String> serialize_to_json_in_a_new_global_object(JS::VM&, Function<JS::Value(JS::Realm&)> const& create_value);+}diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Libraries/LibWeb/Crypto/SubtleCrypto.cppindex a980c60d898..ead9b538327 100644--- a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp@@ -11,7 +11,6 @@#include <LibCrypto/Hash/HashManager.h>#include <LibGC/Heap.h>#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/JSONObject.h>#include <LibJS/Runtime/Object.h>#include <LibJS/Runtime/PrimitiveString.h>#include <LibJS/Runtime/ValueInlines.h>@@ -65,12 +64,7 @@ static JS::ThrowCompletionOr<ByteBuffer> export_key_result_to_bytes(JS::Realm& rif (result.has<ByteBuffer>())return move(result.get<ByteBuffer>());- auto key_object = Bindings::json_web_key_to_value(realm, result.get<JsonWebKey>());- auto maybe_json = JS::JSONObject::stringify_impl(realm.vm(), key_object, JS::Value {}, JS::Value {});- if (maybe_json.is_error())- return maybe_json.release_error();-- auto json = maybe_json.value()->to_well_formed_utf8();+ auto json = TRY(Bindings::json_web_key_to_json(realm.vm(), result.get<JsonWebKey>())).to_well_formed_utf8();return MUST(ByteBuffer::copy(json.bytes()));}diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.idl b/Libraries/LibWeb/Crypto/SubtleCrypto.idlindex c533715939a..efff0b4226e 100644--- a/Libraries/LibWeb/Crypto/SubtleCrypto.idl+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.idl@@ -15,7 +15,7 @@ dictionary RsaOtherPrimesInfo {};// https://wicg.github.io/webcrypto-modern-algos/#partial-JsonWebKey-dictionary-[GenerateToValue, GenerateFromJSON]+[GenerateToValue, GenerateFromJSON, GenerateToJSON]dictionary JsonWebKey {// The following fields are defined in Section 3.1 of JSON Web KeyDOMString kty;diff --git a/Meta/Generators/libweb_bindings/json_conversions.py b/Meta/Generators/libweb_bindings/json_conversions.pyindex 3ccc737dc70..a888b42e0ae 100644--- a/Meta/Generators/libweb_bindings/json_conversions.py+++ b/Meta/Generators/libweb_bindings/json_conversions.py@@ -6,6 +6,7 @@ from typing import TextIOfrom Generators.libweb_bindings.cpp_types import converter_function_namefrom Generators.libweb_bindings.includes import GeneratedIncludes+from Generators.libweb_bindings.to_js_value import to_value_function_namefrom Utils.utils import make_name_acceptable_cppfrom Utils.utils import title_case_to_snake_casefrom Utils.webidl_parser import Dictionary@@ -15,6 +16,10 @@ def from_json_function_name(dictionary: Dictionary) -> str:return f"convert_json_to_idl_value_for_{make_name_acceptable_cpp(title_case_to_snake_case(dictionary.name))}"+def to_json_function_name(dictionary: Dictionary) -> str:+ return f"{make_name_acceptable_cpp(title_case_to_snake_case(dictionary.name))}_to_json"++def write_dictionary_json_declarations(out: TextIO, dictionary: Dictionary, includes: GeneratedIncludes) -> None:if "GenerateFromJSON" in dictionary.extended_attributes:includes.add("AK/Utf16View.h")@@ -22,6 +27,14 @@ def write_dictionary_json_declarations(out: TextIO, dictionary: Dictionary, inclf"JS::ThrowCompletionOr<{dictionary.name}> {from_json_function_name(dictionary)}(JS::VM&, Utf16View);\n\n")+ if "GenerateToJSON" in dictionary.extended_attributes:+ if "GenerateToValue" not in dictionary.extended_attributes:+ raise RuntimeError(f"Dictionary '{dictionary.name}' has [GenerateToJSON] but not [GenerateToValue]")+ includes.add("AK/Utf16String.h")+ out.write(+ f"JS::ThrowCompletionOr<Utf16String> {to_json_function_name(dictionary)}(JS::VM&, {dictionary.name} const&);\n\n"+ )+def write_dictionary_json_conversions(out: TextIO, dictionary: Dictionary, includes: GeneratedIncludes) -> None:if "GenerateFromJSON" in dictionary.extended_attributes:@@ -35,5 +48,18 @@ def write_dictionary_json_conversions(out: TextIO, dictionary: Dictionary, inclu}});}}+"""+ )++ if "GenerateToJSON" in dictionary.extended_attributes:+ includes.add("LibWeb/Bindings/NewGlobalObject.h")+ out.write(+ f"""JS::ThrowCompletionOr<Utf16String> {to_json_function_name(dictionary)}(JS::VM& vm, {dictionary.name} const& dictionary)+{{+ return serialize_to_json_in_a_new_global_object(vm, [&](JS::Realm& realm) {{+ return {to_value_function_name(dictionary)}(realm, dictionary);+ }});+}}+""")diff --git a/Meta/Utils/webidl_parser.py b/Meta/Utils/webidl_parser.pyindex 2f30981438f..7fff5c43f4e 100644--- a/Meta/Utils/webidl_parser.py+++ b/Meta/Utils/webidl_parser.py@@ -36,6 +36,7 @@ ALLOWED_EXTENDED_ATTRIBUTES = frozenset("DirectGetter","FlyString","GenerateFromJSON",+ "GenerateToJSON","GenerateToValue","Global","HTMLConstructor",diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-wrapKey-jwk-new-global-object.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-wrapKey-jwk-new-global-object.txtnew file mode 100644index 00000000000..4715772132a--- /dev/null+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-wrapKey-jwk-new-global-object.txt@@ -0,0 +1,3 @@+No prototype changes: kty=oct alg=HS256 ext=true key_ops=["sign","verify"] k=AQID+Array.prototype.toJSON returns a string: kty=oct alg=HS256 ext=true key_ops=["sign","verify"] k=AQID+Object.prototype.toJSON replaces the key: kty=oct alg=HS256 ext=true key_ops=["sign","verify"] k=AQIDdiff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-wrapKey-jwk-new-global-object.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-wrapKey-jwk-new-global-object.htmlnew file mode 100644index 00000000000..f56c13ded16--- /dev/null+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-wrapKey-jwk-new-global-object.html@@ -0,0 +1,38 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const subtle = crypto.subtle;+ const wrapAlgorithm = { name: "AES-GCM", iv: new Uint8Array(12) };+ const wrappingKey = await subtle.importKey("raw", new Uint8Array(16), "AES-GCM", false, ["wrapKey", "decrypt"]);+ const key = await subtle.importKey("raw", new Uint8Array([1, 2, 3]), { name: "HMAC", hash: "SHA-256" }, true, ["sign", "verify"]);++ async function wrapWhile(description, setUp) {+ const tearDown = setUp();+ let wrapped;+ try {+ wrapped = await subtle.wrapKey("jwk", key, wrappingKey, wrapAlgorithm);+ } finally {+ tearDown();+ }+ const jwk = JSON.parse(new TextDecoder().decode(await subtle.decrypt(wrapAlgorithm, wrappingKey, wrapped)));+ println(`${description}: kty=${jwk.kty} alg=${jwk.alg} ext=${jwk.ext} key_ops=${JSON.stringify(jwk.key_ops)} k=${jwk.k}`);+ }++ await wrapWhile("No prototype changes", () => () => {});++ await wrapWhile("Array.prototype.toJSON returns a string", () => {+ Array.prototype.toJSON = function () {+ return "patched";+ };+ return () => delete Array.prototype.toJSON;+ });++ await wrapWhile("Object.prototype.toJSON replaces the key", () => {+ Object.prototype.toJSON = function () {+ return { kty: "patched" };+ };+ return () => delete Object.prototype.toJSON;+ });+ });+</script>