Skip to content

Truly independent web browser

LibWeb: Serialize CryptoKeys from Rust

Shannon Booth9b7a78f52760
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
new file mode 100644
index 00000000000..f4ff3cee4da
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
@@ -0,0 +1,327 @@
+/*
+ * Copyright (c) 2023, stelar7 <[email protected]>
+ * Copyright (c) 2024, Andrew Kaster <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The serialization steps of CryptoKey, https://w3c.github.io/webcrypto/#cryptokey-interface, which LibWeb implements in
+//! C++ (Libraries/LibWeb/Crypto/CryptoKey.cpp).
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, Object, RawNativeFunctionResult, Realm};
+
+use crate::bindings::{Exception, WebIdlResult};
+use crate::html::structured_serialize::cpp::{
+ DecodedBytes, SerializationType, StructuredSerializeReader, StructuredSerializeWriter,
+};
+
+/// The fields of a CryptoKey, as Libraries/LibWeb/Crypto/CryptoKey.cpp hands them over and creates a key from. A key
+/// that it hands over owns its strings for the receiver, and borrows its bytes from the key for the call.
+#[repr(C)]
+struct RawFields<'a> {
+ /// Crypto::KeyType, in the order of Bindings::KeyType.
+ r#type: u8,
+ extractable: bool,
+ algorithm_type: u8,
+ algorithm_name: usize,
+ modulus_length: u32,
+ public_exponent: ak::Span<'a, u8>,
+ hash: usize,
+ named_curve: usize,
+ length: u32,
+ /// Bindings::KeyUsage.
+ usages: ak::Span<'a, u8>,
+ handle_tag: u8,
+ handle_buffers: [ak::Span<'a, u8>; MAX_HANDLE_BUFFERS],
+ handle_buffer_count: usize,
+ has_ec_parameters: bool,
+ ec_parameters: ak::Span<'a, u32>,
+ has_ec_public_key: bool,
+}
+
+unsafe extern "C" {
+ fn web_crypto_key_with_fields(
+ key: *mut c_void,
+ state: *mut c_void,
+ steps: unsafe extern "C" fn(state: *mut c_void, fields: *const RawFields<'_>),
+ );
+ fn web_crypto_key_create(
+ realm: *mut c_void,
+ fields: &RawFields<'_>,
+ out_key: &mut *mut c_void,
+ ) -> RawNativeFunctionResult;
+}
+
+const MAX_HANDLE_BUFFERS: usize = 8;
+
+/// The identifiers by which a storage record holds a key type, in the order of Bindings::KeyType.
+const KEY_TYPES: [&[u8]; 3] = [b"public", b"private", b"secret"];
+
+/// The identifiers by which a storage record holds a key usage, in the order of Bindings::KeyUsage.
+const KEY_USAGES: [&[u8]; 12] = [
+ b"encrypt",
+ b"decrypt",
+ b"sign",
+ b"verify",
+ b"deriveKey",
+ b"deriveBits",
+ b"wrapKey",
+ b"unwrapKey",
+ b"encapsulateKey",
+ b"encapsulateBits",
+ b"decapsulateKey",
+ b"decapsulateBits",
+];
+
+/// The types of a serialized algorithm, which are part of the stable storage serialization format.
+const ALGORITHM_KEY: u8 = 0;
+const ALGORITHM_RSA: u8 = 1;
+const ALGORITHM_RSA_HASHED: u8 = 2;
+const ALGORITHM_EC: u8 = 3;
+const ALGORITHM_AES: u8 = 4;
+const ALGORITHM_HMAC: u8 = 5;
+const ALGORITHM_KMAC: u8 = 6;
+
+/// The tags of a serialized handle, Crypto::HandleTag, which are part of the stable storage serialization format.
+const HANDLE_EC_PRIVATE_KEY: u8 = 4;
+
+/// The number of buffers of the handle of each tag, Crypto::HandleTag. An EC private key has one, then optionally its
+/// parameters and its public key, whose two buffers follow.
+const HANDLE_BUFFER_COUNTS: [usize; 11] = [1, 2, 8, 2, 1, 1, 3, 1, 3, 1, 1];
+
+fn data_clone_error(message: &[u8]) -> Exception {
+ Exception::Dom("DataCloneError", Utf16String::from_ascii(message))
+}
+
+fn encode_identifier(serialized: StructuredSerializeWriter, identifier: &[u8]) {
+ serialized.encode_utf16_string(&Utf16String::from_ascii(identifier));
+}
+
+/// The index of the identifier that a storage record holds.
+fn decode_identifier(
+ serialized: StructuredSerializeReader,
+ identifiers: &[&[u8]],
+ unknown_message: &[u8],
+) -> WebIdlResult<u8> {
+ let identifier = serialized.decode_utf16_string()?;
+ identifiers
+ .iter()
+ .position(|candidate| identifier == Utf16String::from_ascii(candidate))
+ .map(|index| u8::try_from(index).expect("an identifier list is short"))
+ .ok_or_else(|| data_clone_error(unknown_message))
+}
+
+/// Runs the serialization steps of the CryptoKey, given the record.
+pub(crate) fn serialization_steps(key: Gc<Object>, serialized: StructuredSerializeWriter) {
+ unsafe extern "C" fn steps(state: *mut c_void, fields: *const RawFields<'_>) {
+ // SAFETY: The state is the writer that serialization_steps() lends, and the fields live for the call.
+ let (serialized, fields) = unsafe { (*state.cast::<StructuredSerializeWriter>(), &*fields) };
+ write_fields(serialized, fields);
+ }
+ let mut state = serialized;
+ // SAFETY: The object is a live CryptoKey, and the state lives for the call.
+ unsafe { web_crypto_key_with_fields(key.as_ptr().cast(), (&raw mut state).cast(), steps) };
+}
+
+fn write_fields(serialized: StructuredSerializeWriter, value: &RawFields<'_>) {
+ let for_storage = serialized.serialization_type() == SerializationType::Storage;
+ // SAFETY: LibWeb hands over the strings.
+ let (algorithm_name, hash, named_curve) = unsafe {
+ (
+ Utf16String::from_raw_owned(value.algorithm_name),
+ Utf16String::from_raw_owned(value.hash),
+ Utf16String::from_raw_owned(value.named_curve),
+ )
+ };
+
+ // 1. Set serialized.[[Type]] to the [[type]] internal slot of value.
+ if for_storage {
+ encode_identifier(serialized, KEY_TYPES[usize::from(value.r#type)]);
+ } else {
+ serialized.encode_i32(i32::from(value.r#type));
+ }
+
+ // 2. Set serialized.[[Extractable]] to the [[extractable]] internal slot of value.
+ serialized.encode_bool(value.extractable);
+
+ // 3. Set serialized.[[Algorithm]] to the sub-serialization of the [[algorithm]] internal slot of value.
+ serialized.encode_u8(value.algorithm_type);
+ serialized.encode_utf16_string(&algorithm_name);
+ match value.algorithm_type {
+ ALGORITHM_RSA | ALGORITHM_RSA_HASHED => {
+ serialized.encode_u32(value.modulus_length);
+ serialized.encode_bytes(value.public_exponent.as_slice());
+ if value.algorithm_type == ALGORITHM_RSA_HASHED {
+ serialized.encode_utf16_string(&hash);
+ }
+ }
+ ALGORITHM_EC => serialized.encode_utf16_string(&named_curve),
+ ALGORITHM_AES => serialized.encode_u16(u16::try_from(value.length).expect("an AES key has a 16-bit length")),
+ ALGORITHM_HMAC => {
+ serialized.encode_utf16_string(&hash);
+ serialized.encode_u32(value.length);
+ }
+ ALGORITHM_KMAC => serialized.encode_u32(value.length),
+ ALGORITHM_KEY => {}
+ _ => unreachable!("LibWeb hands over the type of an algorithm that a record holds"),
+ }
+
+ // 4. Set serialized.[[Usages]] to the sub-serialization of the [[usages]] internal slot of value.
+ let usages = value.usages.as_slice();
+ serialized.encode_u64(usages.len() as u64);
+ for &usage in usages {
+ if for_storage {
+ encode_identifier(serialized, KEY_USAGES[usize::from(usage)]);
+ } else {
+ serialized.encode_u8(usage);
+ }
+ }
+
+ // 5. Set serialized.[[Handle]] to the [[handle]] internal slot of value.
+ serialized.encode_u8(value.handle_tag);
+ let buffers = &value.handle_buffers[..value.handle_buffer_count];
+ if value.handle_tag != HANDLE_EC_PRIVATE_KEY {
+ for buffer in buffers {
+ serialized.encode_bytes(buffer.as_slice());
+ }
+ return;
+ }
+ serialized.encode_bytes(buffers[0].as_slice());
+ serialized.encode_bool(value.has_ec_parameters);
+ if value.has_ec_parameters {
+ let parameters = value.ec_parameters.as_slice();
+ serialized.encode_u64(parameters.len() as u64);
+ for &parameter in parameters {
+ serialized.encode_u32(parameter);
+ }
+ }
+ serialized.encode_bool(value.has_ec_public_key);
+ if value.has_ec_public_key {
+ serialized.encode_bytes(buffers[1].as_slice());
+ serialized.encode_bytes(buffers[2].as_slice());
+ }
+}
+
+/// Runs the deserialization steps of CryptoKey, which create the key in the realm from what they read.
+pub(crate) fn deserialization_steps(
+ realm: Gc<Realm>,
+ serialized: StructuredSerializeReader,
+) -> WebIdlResult<Gc<Object>> {
+ let for_storage = serialized.serialization_type() == SerializationType::Storage;
+
+ // 1. Initialize the [[type]] internal slot of value to serialized.[[Type]].
+ let r#type = if for_storage {
+ decode_identifier(serialized, &KEY_TYPES, b"Unknown structured serialize key type")?
+ } else {
+ u8::try_from(serialized.decode_i32()?)
+ .ok()
+ .filter(|&r#type| usize::from(r#type) < KEY_TYPES.len())
+ .ok_or_else(|| data_clone_error(b"Invalid structured serialize key type"))?
+ };
+
+ // 2. Initialize the [[extractable]] internal slot of value to serialized.[[Extractable]].
+ let extractable = serialized.decode_bool()?;
+
+ // 3. Initialize the [[algorithm]] internal slot of value to the sub-deserialization of serialized.[[Algorithm]].
+ let algorithm_type = serialized.decode_u8()?;
+ if algorithm_type > ALGORITHM_KMAC {
+ return Err(data_clone_error(b"Invalid CryptoKey algorithm"));
+ }
+ let algorithm_name = serialized.decode_utf16_string()?;
+ let (mut modulus_length, mut public_exponent, mut hash, mut named_curve, mut length) =
+ (0, None, Utf16String::default(), Utf16String::default(), 0);
+ match algorithm_type {
+ ALGORITHM_RSA | ALGORITHM_RSA_HASHED => {
+ modulus_length = serialized.decode_u32()?;
+ public_exponent = Some(serialized.decode_byte_buffer()?);
+ if algorithm_type == ALGORITHM_RSA_HASHED {
+ hash = serialized.decode_utf16_string()?;
+ }
+ }
+ ALGORITHM_EC => named_curve = serialized.decode_utf16_string()?,
+ ALGORITHM_AES => length = u32::from(serialized.decode_u16()?),
+ ALGORITHM_HMAC => {
+ hash = serialized.decode_utf16_string()?;
+ length = serialized.decode_u32()?;
+ }
+ ALGORITHM_KMAC => length = serialized.decode_u32()?,
+ ALGORITHM_KEY => {}
+ _ => unreachable!("the type is that of an algorithm, as checked above"),
+ }
+
+ // 4. Initialize the [[usages]] internal slot of value to the sub-deserialization of serialized.[[Usages]].
+ let usage_count = serialized.decode_u64()?;
+ let mut usages = Vec::new();
+ for _ in 0..usage_count {
+ let usage = if for_storage {
+ decode_identifier(serialized, &KEY_USAGES, b"Unknown structured serialize key usage")?
+ } else {
+ Some(serialized.decode_u8()?)
+ .filter(|&usage| usize::from(usage) < KEY_USAGES.len())
+ .ok_or_else(|| data_clone_error(b"Invalid structured serialize key usage"))?
+ };
+ usages.push(usage);
+ }
+
+ // 5. Initialize the [[handle]] internal slot of value to serialized.[[Handle]].
+ let handle_tag = serialized.decode_u8()?;
+ let Some(&buffer_count) = HANDLE_BUFFER_COUNTS.get(usize::from(handle_tag)) else {
+ return Err(data_clone_error(b"Invalid CryptoKey handle tag"));
+ };
+ let mut buffers: Vec<DecodedBytes> = Vec::new();
+ let (mut has_ec_parameters, mut ec_parameters, mut has_ec_public_key) = (false, Vec::new(), false);
+ if handle_tag == HANDLE_EC_PRIVATE_KEY {
+ buffers.push(serialized.decode_byte_buffer()?);
+ has_ec_parameters = serialized.decode_bool()?;
+ if has_ec_parameters {
+ let parameter_count = serialized.decode_u64()?;
+ for _ in 0..parameter_count {
+ ec_parameters.push(serialized.decode_u32()?);
+ }
+ }
+ has_ec_public_key = serialized.decode_bool()?;
+ if has_ec_public_key {
+ buffers.push(serialized.decode_byte_buffer()?);
+ buffers.push(serialized.decode_byte_buffer()?);
+ }
+ } else {
+ for _ in 0..buffer_count {
+ buffers.push(serialized.decode_byte_buffer()?);
+ }
+ }
+
+ let mut handle_buffers = [ak::Span::default(); MAX_HANDLE_BUFFERS];
+ for (span, buffer) in handle_buffers.iter_mut().zip(&buffers) {
+ *span = ak::Span::new(buffer.bytes());
+ }
+ let fields = RawFields {
+ r#type,
+ extractable,
+ algorithm_type,
+ algorithm_name: algorithm_name.raw_identity(),
+ modulus_length,
+ public_exponent: public_exponent
+ .as_ref()
+ .map_or_else(ak::Span::default, |bytes| ak::Span::new(bytes.bytes())),
+ hash: hash.raw_identity(),
+ named_curve: named_curve.raw_identity(),
+ length,
+ usages: ak::Span::new(&usages),
+ handle_tag,
+ handle_buffers,
+ handle_buffer_count: buffers.len(),
+ has_ec_parameters,
+ ec_parameters: ak::Span::new(&ec_parameters),
+ has_ec_public_key,
+ };
+ let mut key = core::ptr::null_mut();
+ // SAFETY: The realm is live, and the call borrows the fields.
+ unsafe { web_crypto_key_create(realm.as_ptr().cast(), &fields, &mut key) }.into_completion()?;
+ // SAFETY: LibWeb returns a live object.
+ Ok(unsafe { Gc::from_non_null(NonNull::new(key.cast()).expect("LibWeb creates the key")) })
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/mod.rs
new file mode 100644
index 00000000000..c0cb8026a83
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/mod.rs
@@ -0,0 +1,9 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The serialization steps of the serializable interfaces of the Web Cryptography API, which LibWeb implements in C++.
+
+pub(crate) mod crypto_key;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
index d0aa44cdb5e..89b64a8fb65 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
@@ -25,6 +25,7 @@ unsafe extern "C" {
fn web_structured_serialize_writer_encode_u8(writer: *mut c_void, value: u8);
fn web_structured_serialize_writer_encode_bool(writer: *mut c_void, value: bool);
fn web_structured_serialize_writer_encode_i32(writer: *mut c_void, value: i32);
+ fn web_structured_serialize_writer_encode_u16(writer: *mut c_void, value: u16);
fn web_structured_serialize_writer_encode_u32(writer: *mut c_void, value: u32);
fn web_structured_serialize_writer_encode_u64(writer: *mut c_void, value: u64);
fn web_structured_serialize_writer_encode_f64(writer: *mut c_void, value: f64);
@@ -62,6 +63,11 @@ unsafe extern "C" {
realm: *mut c_void,
value: &mut i32,
) -> RawNativeFunctionResult;
+ fn web_structured_serialize_reader_decode_u16(
+ reader: *mut c_void,
+ realm: *mut c_void,
+ value: &mut u16,
+ ) -> RawNativeFunctionResult;
fn web_structured_serialize_reader_decode_u32(
reader: *mut c_void,
realm: *mut c_void,
@@ -98,6 +104,7 @@ unsafe extern "C" {
realm: *mut c_void,
buffer: &mut *mut c_void,
) -> RawNativeFunctionResult;
+ fn web_structured_serialize_byte_buffer_data(buffer: *mut c_void) -> *const u8;
fn web_structured_serialize_byte_buffer_size(buffer: *mut c_void) -> usize;
fn web_structured_serialize_array_buffer_from_byte_buffer(
realm: *mut c_void,
@@ -278,6 +285,11 @@ impl DecodedBytes {
unsafe { web_structured_serialize_byte_buffer_size(self.0.as_ptr()) }
}
+ pub(crate) fn bytes(&self) -> &[u8] {
+ // SAFETY: This owns the buffer, whose bytes live as long as it does.
+ unsafe { ak::slice_from_raw_parts(web_structured_serialize_byte_buffer_data(self.0.as_ptr()), self.len()) }
+ }
+
/// A new ArrayBuffer in the realm, which takes over the bytes.
pub(crate) fn into_array_buffer(self, realm: Gc<Realm>, is_shared: ArrayBufferShared) -> Gc<ArrayBuffer> {
let buffer = ManuallyDrop::new(self);
@@ -340,6 +352,11 @@ impl StructuredSerializeWriter {
unsafe { web_structured_serialize_writer_encode_i32(self.as_raw(), value) };
}
+ pub(crate) fn encode_u16(self, value: u16) {
+ // SAFETY: The writer is lent.
+ unsafe { web_structured_serialize_writer_encode_u16(self.as_raw(), value) };
+ }
+
pub(crate) fn encode_u32(self, value: u32) {
// SAFETY: The writer is lent.
unsafe { web_structured_serialize_writer_encode_u32(self.as_raw(), value) };
@@ -518,6 +535,13 @@ impl StructuredSerializeReader {
Ok(value)
}
+ pub(crate) fn decode_u16(self) -> WebIdlResult<u16> {
+ let mut value = 0;
+ // SAFETY: The reader is lent, and the realm is live.
+ completion(unsafe { web_structured_serialize_reader_decode_u16(self.as_raw(), self.realm_raw(), &mut value) })?;
+ Ok(value)
+ }
+
pub(crate) fn decode_u32(self) -> WebIdlResult<u32> {
let mut value = 0;
// SAFETY: The reader is lent, and the realm is live.
@@ -862,6 +886,8 @@ pub(crate) enum SerializableSteps {
DOMException,
/// The steps of QuotaExceededError, which run in crate::webidl::quota_exceeded_error.
QuotaExceededError,
+ /// The steps of CryptoKey, which run in crate::crypto::crypto_key.
+ CryptoKey,
/// The steps of an interface implemented in C++, which C++ runs.
Cpp,
}
@@ -872,7 +898,8 @@ pub(crate) fn serializable_steps(interface_name: u16) -> SerializableSteps {
0 => SerializableSteps::Rust,
1 => SerializableSteps::DOMException,
2 => SerializableSteps::QuotaExceededError,
- 3 => SerializableSteps::Cpp,
+ 3 => SerializableSteps::CryptoKey,
+ 4 => SerializableSteps::Cpp,
steps => unreachable!("LibWeb names no serializable steps {steps}"),
}
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
index 1556045707c..f33c9bb2afa 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
@@ -28,6 +28,7 @@ use libjs_rust::api::{
};
use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::crypto::crypto_key;
use crate::html::structured_serialize::cpp::{
DeserializationMemory, OwnedDeserializationMemory, OwnedSerializedTransferRecord, OwnedStructuredSerializeWriter,
SerializableSteps, SerializationMemory, SerializationType, SerializedTransferRecord, StructuredSerializeReader,
@@ -852,6 +853,7 @@ impl Serializer<'_> {
SerializableSteps::QuotaExceededError => {
quota_exceeded_error::serialization_steps(&QuotaExceededErrorFields::of(object), serialized);
}
+ SerializableSteps::CryptoKey => crypto_key::serialization_steps(object, serialized),
SerializableSteps::Rust | SerializableSteps::Cpp => {
let realm = self.realm.unwrap_or_else(|| object.shape().realm());
serialization_steps(
@@ -1369,8 +1371,8 @@ impl Deserializer<'_, '_> {
}
// NB: The deserialization steps of an interface implemented in Rust, and those that run here for
- // DOMException and QuotaExceededError, create the new instance from what they read, so they run
- // here, at the position in memory that the instance has.
+ // DOMException, QuotaExceededError and CryptoKey, create the new instance from what they read, so
+ // they run here, at the position in memory that the instance has.
let steps = serializable_steps(interface_name);
if steps != SerializableSteps::Cpp {
if version.is_some_and(|version| version != serializable_payload_version()) {
@@ -1390,6 +1392,9 @@ impl Deserializer<'_, '_> {
let fields = quota_exceeded_error::deserialization_steps(self.serialized)?;
Value::from_object(quota_exceeded_error::create(realm, &fields))
}
+ SerializableSteps::CryptoKey => {
+ Value::from_object(crypto_key::deserialization_steps(realm, self.serialized)?)
+ }
_ => deserialize_rust_platform_object(interface_name, self.serialized, self.memory)?,
};
self.memory.set(memory_index, value);
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index 1bffb0cb593..34b63ea3682 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -53,6 +53,8 @@ pub(crate) mod canvas_2d;
reason = "the bindings call every attribute and operation as one that can throw"
)]
pub(crate) mod compression;
+#[cfg(not(test))]
+pub(crate) mod crypto;
#[cfg_attr(
not(web_idl_bindings),
allow(dead_code, reason = "only the generated bindings use the dictionaries")
diff --git a/Libraries/LibWeb/Crypto/CryptoKey.cpp b/Libraries/LibWeb/Crypto/CryptoKey.cpp
index b5b0d81d9b2..68ed4cc7741 100644
--- a/Libraries/LibWeb/Crypto/CryptoKey.cpp
+++ b/Libraries/LibWeb/Crypto/CryptoKey.cpp
@@ -9,29 +9,22 @@
#include <AK/NeverDestroyed.h>
#include <LibGC/Heap.h>
#include <LibGC/WeakInlines.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/TypedArray.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/CryptoKey.h>
+#include <LibWeb/Bindings/RustSerialization.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/Crypto/CryptoKey.h>
#include <LibWeb/Crypto/CryptoKeySerializationTags.h>
-#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
namespace Web::Crypto {
namespace {
-WebIDL::ExceptionOr<HandleTag> decode_handle_tag(HTML::StructuredSerializeReader& decoder, JS::Realm& realm)
-{
- auto tag = TRY(HTML::decode_or_throw_data_clone_error<u8>(realm, decoder));
- if (!handle_tag_is_in_table(static_cast<HandleTag>(tag)))
- return HTML::data_clone_error_from_serialization_error(realm, Error::from_string_literal("Invalid CryptoKey handle tag"));
- return static_cast<HandleTag>(tag);
-}
-
struct CryptoKeyCacheEntry {
GC::Weak<CryptoKey> key;
Bindings::WrapperWorldWeakValueCache<JS::Object> usages_objects;
@@ -120,173 +113,6 @@ static JS::ThrowCompletionOr<GC::Ref<JS::Object>> create_algorithm_object(JS::Re
}));
}
-void serialize_handle(HTML::StructuredSerializeWriter& encoder, ByteBuffer const& buffer)
-{
- encoder.encode(to_underlying(HandleTag::ByteBuffer));
- encoder.encode(buffer);
-}
-
-void serialize_handle(HTML::StructuredSerializeWriter& encoder, ::Crypto::PK::RSAPublicKey const& key)
-{
- encoder.encode(to_underlying(HandleTag::RSAPublicKey));
- HTML::encode_unsigned_big_integer(encoder, key.modulus());
- HTML::encode_unsigned_big_integer(encoder, key.public_exponent());
-}
-
-WebIDL::ExceptionOr<::Crypto::PK::RSAPublicKey> deserialize_rsa_public_key(HTML::StructuredSerializeReader& decoder, JS::Realm& realm)
-{
- auto modulus = TRY(HTML::decode_unsigned_big_integer(decoder, realm));
- auto public_exponent = TRY(HTML::decode_unsigned_big_integer(decoder, realm));
- return ::Crypto::PK::RSAPublicKey { move(modulus), move(public_exponent) };
-}
-
-void serialize_handle(HTML::StructuredSerializeWriter& encoder, ::Crypto::PK::RSAPrivateKey const& key)
-{
- encoder.encode(to_underlying(HandleTag::RSAPrivateKey));
- HTML::encode_unsigned_big_integer(encoder, key.modulus());
- HTML::encode_unsigned_big_integer(encoder, key.private_exponent());
- HTML::encode_unsigned_big_integer(encoder, key.public_exponent());
- HTML::encode_unsigned_big_integer(encoder, key.prime1());
- HTML::encode_unsigned_big_integer(encoder, key.prime2());
- HTML::encode_unsigned_big_integer(encoder, key.exponent1());
- HTML::encode_unsigned_big_integer(encoder, key.exponent2());
- HTML::encode_unsigned_big_integer(encoder, key.coefficient());
-}
-
-WebIDL::ExceptionOr<::Crypto::PK::RSAPrivateKey> deserialize_rsa_private_key(HTML::StructuredSerializeReader& decoder, JS::Realm& realm)
-{
- auto modulus = TRY(HTML::decode_unsigned_big_integer(decoder, realm));
- auto private_exponent = TRY(HTML::decode_unsigned_big_integer(decoder, realm));
- auto public_exponent = TRY(HTML::decode_unsigned_big_integer(decoder, realm));
- auto prime1 = TRY(HTML::decode_unsigned_big_integer(decoder, realm));
- auto prime2 = TRY(HTML::decode_unsigned_big_integer(decoder, realm));
- auto exponent1 = TRY(HTML::decode_unsigned_big_integer(decoder, realm));
- auto exponent2 = TRY(HTML::decode_unsigned_big_integer(decoder, realm));
- auto coefficient = TRY(HTML::decode_unsigned_big_integer(decoder, realm));
- return ::Crypto::PK::RSAPrivateKey { move(modulus), move(private_exponent), move(public_exponent), move(prime1), move(prime2), move(exponent1), move(exponent2), move(coefficient) };
-}
-
-void serialize_ec_public_key(HTML::StructuredSerializeWriter& encoder, ::Crypto::PK::ECPublicKey const& key)
-{
- encoder.encode(MUST(key.x_bytes()));
- encoder.encode(MUST(key.y_bytes()));
-}
-
-void serialize_handle(HTML::StructuredSerializeWriter& encoder, ::Crypto::PK::ECPublicKey const& key)
-{
- encoder.encode(to_underlying(HandleTag::ECPublicKey));
- serialize_ec_public_key(encoder, key);
-}
-
-WebIDL::ExceptionOr<::Crypto::PK::ECPublicKey> deserialize_ec_public_key(HTML::StructuredSerializeReader& decoder, JS::Realm& realm)
-{
- auto x_bytes = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder));
- auto y_bytes = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder));
- auto scalar_size = x_bytes.size();
- return ::Crypto::PK::ECPublicKey { ::Crypto::UnsignedBigInteger::import_data(x_bytes), ::Crypto::UnsignedBigInteger::import_data(y_bytes), scalar_size };
-}
-
-void serialize_handle(HTML::StructuredSerializeWriter& encoder, ::Crypto::PK::ECPrivateKey const& key)
-{
- encoder.encode(to_underlying(HandleTag::ECPrivateKey));
- encoder.encode(MUST(key.d_bytes()));
- encoder.encode(key.parameters());
- encoder.encode(key.public_key().has_value());
- if (key.public_key().has_value())
- serialize_ec_public_key(encoder, *key.public_key());
-}
-
-WebIDL::ExceptionOr<::Crypto::PK::ECPrivateKey> deserialize_ec_private_key(HTML::StructuredSerializeReader& decoder, JS::Realm& realm)
-{
- auto d_bytes = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder));
- auto scalar_size = d_bytes.size();
- auto d = ::Crypto::UnsignedBigInteger::import_data(d_bytes);
-
- auto parameters = TRY(HTML::decode_or_throw_data_clone_error<Optional<::Crypto::ASN1::ObjectIdentifier>>(realm, decoder));
-
- Optional<::Crypto::PK::ECPublicKey> public_key;
- if (TRY(HTML::decode_or_throw_data_clone_error<bool>(realm, decoder)))
- public_key = TRY(deserialize_ec_public_key(decoder, realm));
-
- return ::Crypto::PK::ECPrivateKey { move(d), scalar_size, move(parameters), move(public_key) };
-}
-
-void serialize_handle(HTML::StructuredSerializeWriter& encoder, ::Crypto::PK::MLDSAPublicKey const& key)
-{
- encoder.encode(to_underlying(HandleTag::MLDSAPublicKey));
- encoder.encode(key.public_key());
-}
-
-WebIDL::ExceptionOr<::Crypto::PK::MLDSAPublicKey> deserialize_mldsa_public_key(HTML::StructuredSerializeReader& decoder, JS::Realm& realm)
-{
- return ::Crypto::PK::MLDSAPublicKey { TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder)) };
-}
-
-void serialize_handle(HTML::StructuredSerializeWriter& encoder, ::Crypto::PK::MLDSAPrivateKey const& key)
-{
- encoder.encode(to_underlying(HandleTag::MLDSAPrivateKey));
- encoder.encode(key.seed());
- encoder.encode(key.public_key());
- encoder.encode(key.private_key());
-}
-
-WebIDL::ExceptionOr<::Crypto::PK::MLDSAPrivateKey> deserialize_mldsa_private_key(HTML::StructuredSerializeReader& decoder, JS::Realm& realm)
-{
- auto seed = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder));
- auto public_key = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder));
- auto private_key = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder));
- return ::Crypto::PK::MLDSAPrivateKey { move(seed), move(public_key), move(private_key) };
-}
-
-void serialize_handle(HTML::StructuredSerializeWriter& encoder, ::Crypto::PK::MLKEMPublicKey const& key)
-{
- encoder.encode(to_underlying(HandleTag::MLKEMPublicKey));
- encoder.encode(key.public_key());
-}
-
-WebIDL::ExceptionOr<::Crypto::PK::MLKEMPublicKey> deserialize_mlkem_public_key(HTML::StructuredSerializeReader& decoder, JS::Realm& realm)
-{
- return ::Crypto::PK::MLKEMPublicKey { TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder)) };
-}
-
-void serialize_handle(HTML::StructuredSerializeWriter& encoder, ::Crypto::PK::MLKEMPrivateKey const& key)
-{
- encoder.encode(to_underlying(HandleTag::MLKEMPrivateKey));
- encoder.encode(key.seed());
- encoder.encode(key.public_key());
- encoder.encode(key.private_key());
-}
-
-WebIDL::ExceptionOr<::Crypto::PK::MLKEMPrivateKey> deserialize_mlkem_private_key(HTML::StructuredSerializeReader& decoder, JS::Realm& realm)
-{
- auto seed = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder));
- auto public_key = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder));
- auto private_key = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder));
- return ::Crypto::PK::MLKEMPrivateKey { move(seed), move(public_key), move(private_key) };
-}
-
-void serialize_handle(HTML::StructuredSerializeWriter& encoder, OKPPublicKey const& key)
-{
- encoder.encode(to_underlying(HandleTag::OKPPublicKey));
- encoder.encode(key.bytes);
-}
-
-WebIDL::ExceptionOr<OKPPublicKey> deserialize_okp_public_key(HTML::StructuredSerializeReader& decoder, JS::Realm& realm)
-{
- return OKPPublicKey { TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder)) };
-}
-
-void serialize_handle(HTML::StructuredSerializeWriter& encoder, OKPPrivateKey const& key)
-{
- encoder.encode(to_underlying(HandleTag::OKPPrivateKey));
- encoder.encode(key.bytes);
-}
-
-WebIDL::ExceptionOr<OKPPrivateKey> deserialize_okp_private_key(HTML::StructuredSerializeReader& decoder, JS::Realm& realm)
-{
- return OKPPrivateKey { TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder)) };
-}
-
}
GC_DEFINE_ALLOCATOR(CryptoKey);
@@ -300,93 +126,6 @@ enum class SerializedKeyAlgorithmType : u8 {
Kmac,
};
-static void serialize_algorithm(HTML::StructuredSerializeWriter& serialized, CryptoKey::InternalAlgorithmData const& algorithm)
-{
- algorithm.visit(
- [&](CryptoKey::KeyAlgorithmData const& algorithm) {
- serialized.encode(to_underlying(SerializedKeyAlgorithmType::Key));
- serialized.encode(algorithm.name());
- },
- [&](CryptoKey::RsaKeyAlgorithmData const& algorithm) {
- serialized.encode(to_underlying(SerializedKeyAlgorithmType::Rsa));
- serialized.encode(algorithm.name());
- serialized.encode(algorithm.modulus_length());
- serialized.encode(algorithm.public_exponent());
- },
- [&](CryptoKey::RsaHashedKeyAlgorithmData const& algorithm) {
- serialized.encode(to_underlying(SerializedKeyAlgorithmType::RsaHashed));
- serialized.encode(algorithm.name());
- serialized.encode(algorithm.modulus_length());
- serialized.encode(algorithm.public_exponent());
- serialized.encode(algorithm.hash());
- },
- [&](CryptoKey::EcKeyAlgorithmData const& algorithm) {
- serialized.encode(to_underlying(SerializedKeyAlgorithmType::Ec));
- serialized.encode(algorithm.name());
- serialized.encode(algorithm.named_curve());
- },
- [&](CryptoKey::AesKeyAlgorithmData const& algorithm) {
- serialized.encode(to_underlying(SerializedKeyAlgorithmType::Aes));
- serialized.encode(algorithm.name());
- serialized.encode(algorithm.length());
- },
- [&](CryptoKey::HmacKeyAlgorithmData const& algorithm) {
- serialized.encode(to_underlying(SerializedKeyAlgorithmType::Hmac));
- serialized.encode(algorithm.name());
- serialized.encode(algorithm.hash());
- serialized.encode(algorithm.length());
- },
- [&](CryptoKey::KmacKeyAlgorithmData const& algorithm) {
- serialized.encode(to_underlying(SerializedKeyAlgorithmType::Kmac));
- serialized.encode(algorithm.name());
- serialized.encode(algorithm.length());
- });
-}
-
-static WebIDL::ExceptionOr<CryptoKey::InternalAlgorithmData> deserialize_algorithm(HTML::StructuredSerializeReader& serialized, JS::Realm& realm)
-{
- auto type = static_cast<SerializedKeyAlgorithmType>(TRY(HTML::decode_or_throw_data_clone_error<u8>(realm, serialized)));
- switch (type) {
- case SerializedKeyAlgorithmType::Key:
- return CryptoKey::KeyAlgorithmData { TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized)) };
- case SerializedKeyAlgorithmType::Rsa:
- return CryptoKey::RsaKeyAlgorithmData {
- TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized)),
- TRY(HTML::decode_or_throw_data_clone_error<u32>(realm, serialized)),
- TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, serialized)),
- };
- case SerializedKeyAlgorithmType::RsaHashed:
- return CryptoKey::RsaHashedKeyAlgorithmData {
- TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized)),
- TRY(HTML::decode_or_throw_data_clone_error<u32>(realm, serialized)),
- TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, serialized)),
- TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized)),
- };
- case SerializedKeyAlgorithmType::Ec:
- return CryptoKey::EcKeyAlgorithmData {
- TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized)),
- TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized)),
- };
- case SerializedKeyAlgorithmType::Aes:
- return CryptoKey::AesKeyAlgorithmData {
- TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized)),
- TRY(HTML::decode_or_throw_data_clone_error<u16>(realm, serialized)),
- };
- case SerializedKeyAlgorithmType::Hmac:
- return CryptoKey::HmacKeyAlgorithmData {
- TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized)),
- TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized)),
- TRY(HTML::decode_or_throw_data_clone_error<WebIDL::UnsignedLong>(realm, serialized)),
- };
- case SerializedKeyAlgorithmType::Kmac:
- return CryptoKey::KmacKeyAlgorithmData {
- TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized)),
- TRY(HTML::decode_or_throw_data_clone_error<WebIDL::UnsignedLong>(realm, serialized)),
- };
- }
- VERIFY_NOT_REACHED();
-}
-
GC::Ref<CryptoKey> CryptoKey::create(InternalKeyData key_data)
{
return GC::Heap::the().allocate<CryptoKey>(move(key_data));
@@ -490,87 +229,284 @@ Utf16String const& CryptoKey::algorithm_name() const
return m_algorithm_name;
}
-WebIDL::ExceptionOr<void> CryptoKey::serialization_steps(HTML::StructuredSerializeWriter& serialized, bool, HTML::SerializationMemory&)
-{
- // 1. Set serialized.[[Type]] to the [[type]] internal slot of value.
- if (serialized.type() == HTML::SerializationType::Storage)
- serialized.encode(bindings_type());
- else
- serialized.encode(to_underlying(m_type));
-
- // 2. Set serialized.[[Extractable]] to the [[extractable]] internal slot of value.
- serialized.encode(m_extractable);
-
- // 3. Set serialized.[[Algorithm]] to the sub-serialization of the [[algorithm]] internal slot of value.
- serialize_algorithm(serialized, m_algorithm);
+// The fields of a CryptoKey, which its serialization steps in Rust (Libraries/LibWeb/Bindings/Rust/src/crypto) write and
+// its deserialization steps read. The strings of a key that C++ hands over are the receiver's, and its bytes borrow from
+// the key, or from what is exported of it, for the call. Rust lends what it creates a key from.
+struct CryptoKeyFields {
+ u8 type { 0 };
+ bool extractable { false };
+ u8 algorithm_type { 0 };
+ FlatPtr algorithm_name { 0 };
+ u32 modulus_length { 0 };
+ ReadonlyBytes public_exponent;
+ FlatPtr hash { 0 };
+ FlatPtr named_curve { 0 };
+ u32 length { 0 };
+ ReadonlySpan<u8> usages;
+ u8 handle_tag { 0 };
+ Array<ReadonlyBytes, 8> handle_buffers;
+ size_t handle_buffer_count { 0 };
+ bool has_ec_parameters { false };
+ ReadonlySpan<u32> ec_parameters;
+ bool has_ec_public_key { false };
+};
- // 4. Set serialized.[[Usages]] to the sub-serialization of the [[usages]] internal slot of value.
- serialized.encode(m_key_usages);
+extern "C" {
+
+void web_crypto_key_with_fields(JSObject*, void* state, void (*steps)(void* state, CryptoKeyFields const*));
+JSCompletion web_crypto_key_create(void* realm, CryptoKeyFields const*, JSObject** out_key);
+}
+
+// NB: The Rust side names these values by their underlying values.
+static_assert(to_underlying(KeyType::Public) == to_underlying(Bindings::KeyType::Public));
+static_assert(to_underlying(KeyType::Private) == to_underlying(Bindings::KeyType::Private));
+static_assert(to_underlying(KeyType::Secret) == to_underlying(Bindings::KeyType::Secret));
+static_assert(to_underlying(Bindings::KeyType::Secret) == 2);
+static_assert(sizeof(Bindings::KeyUsage) == 1);
+static_assert(to_underlying(Bindings::KeyUsage::Encrypt) == 0);
+static_assert(to_underlying(Bindings::KeyUsage::Decrypt) == 1);
+static_assert(to_underlying(Bindings::KeyUsage::Sign) == 2);
+static_assert(to_underlying(Bindings::KeyUsage::Verify) == 3);
+static_assert(to_underlying(Bindings::KeyUsage::DeriveKey) == 4);
+static_assert(to_underlying(Bindings::KeyUsage::DeriveBits) == 5);
+static_assert(to_underlying(Bindings::KeyUsage::WrapKey) == 6);
+static_assert(to_underlying(Bindings::KeyUsage::UnwrapKey) == 7);
+static_assert(to_underlying(Bindings::KeyUsage::EncapsulateKey) == 8);
+static_assert(to_underlying(Bindings::KeyUsage::EncapsulateBits) == 9);
+static_assert(to_underlying(Bindings::KeyUsage::DecapsulateKey) == 10);
+static_assert(to_underlying(Bindings::KeyUsage::DecapsulateBits) == 11);
+static_assert(to_underlying(SerializedKeyAlgorithmType::Key) == 0);
+static_assert(to_underlying(SerializedKeyAlgorithmType::Kmac) == 6);
+static_assert(to_underlying(HandleTag::ECPrivateKey) == 4);
+static_assert(to_underlying(HandleTag::OKPPrivateKey) == 10);
+
+static ByteBuffer export_big_integer(::Crypto::UnsignedBigInteger const& value)
+{
+ auto buffer = MUST(ByteBuffer::create_zeroed(value.byte_length()));
+ auto written = value.export_data(buffer.bytes());
+ VERIFY(written.size() == buffer.size());
+ return buffer;
+}
+
+void web_crypto_key_with_fields(JSObject* object, void* state, void (*steps)(void* state, CryptoKeyFields const*))
+{
+ auto const& key = Bindings::impl_from<CryptoKey>(*JS::HostABI::object_from_abi(object));
+ CryptoKeyFields fields;
+ fields.type = to_underlying(key.type());
+ fields.extractable = key.extractable();
+
+ Utf16String algorithm_name = key.algorithm_name();
+ Utf16String hash;
+ Utf16String named_curve;
+ key.internal_algorithm().visit(
+ [&](CryptoKey::KeyAlgorithmData const&) {
+ fields.algorithm_type = to_underlying(SerializedKeyAlgorithmType::Key);
+ },
+ [&](CryptoKey::RsaKeyAlgorithmData const& algorithm) {
+ fields.algorithm_type = to_underlying(SerializedKeyAlgorithmType::Rsa);
+ fields.modulus_length = algorithm.modulus_length();
+ fields.public_exponent = algorithm.public_exponent().bytes();
+ },
+ [&](CryptoKey::RsaHashedKeyAlgorithmData const& algorithm) {
+ fields.algorithm_type = to_underlying(SerializedKeyAlgorithmType::RsaHashed);
+ fields.modulus_length = algorithm.modulus_length();
+ fields.public_exponent = algorithm.public_exponent().bytes();
+ hash = algorithm.hash();
+ },
+ [&](CryptoKey::EcKeyAlgorithmData const& algorithm) {
+ fields.algorithm_type = to_underlying(SerializedKeyAlgorithmType::Ec);
+ named_curve = algorithm.named_curve();
+ },
+ [&](CryptoKey::AesKeyAlgorithmData const& algorithm) {
+ fields.algorithm_type = to_underlying(SerializedKeyAlgorithmType::Aes);
+ fields.length = algorithm.length();
+ },
+ [&](CryptoKey::HmacKeyAlgorithmData const& algorithm) {
+ fields.algorithm_type = to_underlying(SerializedKeyAlgorithmType::Hmac);
+ hash = algorithm.hash();
+ fields.length = algorithm.length();
+ },
+ [&](CryptoKey::KmacKeyAlgorithmData const& algorithm) {
+ fields.algorithm_type = to_underlying(SerializedKeyAlgorithmType::Kmac);
+ fields.length = algorithm.length();
+ });
+ fields.algorithm_name = move(algorithm_name).into_raw();
+ fields.hash = move(hash).into_raw();
+ fields.named_curve = move(named_curve).into_raw();
+
+ auto usages = key.internal_usages();
+ fields.usages = { reinterpret_cast<u8 const*>(usages.data()), usages.size() };
+
+ // NB: The inline capacity holds every buffer that a handle exports, so that none moves while the fields borrow it.
+ Vector<ByteBuffer, 8> exported;
+ auto add = [&](ReadonlyBytes bytes) { fields.handle_buffers[fields.handle_buffer_count++] = bytes; };
+ auto add_exported = [&](ByteBuffer buffer) {
+ exported.unchecked_append(move(buffer));
+ add(exported.last().bytes());
+ };
+ key.handle().visit(
+ [&](ByteBuffer const& buffer) {
+ fields.handle_tag = to_underlying(HandleTag::ByteBuffer);
+ add(buffer.bytes());
+ },
+ [&](::Crypto::PK::RSAPublicKey const& rsa_key) {
+ fields.handle_tag = to_underlying(HandleTag::RSAPublicKey);
+ add_exported(export_big_integer(rsa_key.modulus()));
+ add_exported(export_big_integer(rsa_key.public_exponent()));
+ },
+ [&](::Crypto::PK::RSAPrivateKey const& rsa_key) {
+ fields.handle_tag = to_underlying(HandleTag::RSAPrivateKey);
+ add_exported(export_big_integer(rsa_key.modulus()));
+ add_exported(export_big_integer(rsa_key.private_exponent()));
+ add_exported(export_big_integer(rsa_key.public_exponent()));
+ add_exported(export_big_integer(rsa_key.prime1()));
+ add_exported(export_big_integer(rsa_key.prime2()));
+ add_exported(export_big_integer(rsa_key.exponent1()));
+ add_exported(export_big_integer(rsa_key.exponent2()));
+ add_exported(export_big_integer(rsa_key.coefficient()));
+ },
+ [&](::Crypto::PK::ECPublicKey const& ec_key) {
+ fields.handle_tag = to_underlying(HandleTag::ECPublicKey);
+ add_exported(MUST(ec_key.x_bytes()));
+ add_exported(MUST(ec_key.y_bytes()));
+ },
+ [&](::Crypto::PK::ECPrivateKey const& ec_key) {
+ fields.handle_tag = to_underlying(HandleTag::ECPrivateKey);
+ add_exported(MUST(ec_key.d_bytes()));
+ fields.has_ec_parameters = ec_key.parameters().has_value();
+ if (fields.has_ec_parameters)
+ fields.ec_parameters = ec_key.parameters()->span();
+ fields.has_ec_public_key = ec_key.public_key().has_value();
+ if (fields.has_ec_public_key) {
+ add_exported(MUST(ec_key.public_key()->x_bytes()));
+ add_exported(MUST(ec_key.public_key()->y_bytes()));
+ }
+ },
+ [&](::Crypto::PK::MLDSAPublicKey const& mldsa_key) {
+ fields.handle_tag = to_underlying(HandleTag::MLDSAPublicKey);
+ add(mldsa_key.public_key().bytes());
+ },
+ [&](::Crypto::PK::MLDSAPrivateKey const& mldsa_key) {
+ fields.handle_tag = to_underlying(HandleTag::MLDSAPrivateKey);
+ add(mldsa_key.seed().bytes());
+ add(mldsa_key.public_key().bytes());
+ add(mldsa_key.private_key().bytes());
+ },
+ [&](::Crypto::PK::MLKEMPublicKey const& mlkem_key) {
+ fields.handle_tag = to_underlying(HandleTag::MLKEMPublicKey);
+ add_exported(mlkem_key.public_key());
+ },
+ [&](::Crypto::PK::MLKEMPrivateKey const& mlkem_key) {
+ fields.handle_tag = to_underlying(HandleTag::MLKEMPrivateKey);
+ add(mlkem_key.seed().bytes());
+ add(mlkem_key.public_key().bytes());
+ add(mlkem_key.private_key().bytes());
+ },
+ [&](OKPPublicKey const& okp_key) {
+ fields.handle_tag = to_underlying(HandleTag::OKPPublicKey);
+ add(okp_key.bytes.bytes());
+ },
+ [&](OKPPrivateKey const& okp_key) {
+ fields.handle_tag = to_underlying(HandleTag::OKPPrivateKey);
+ add(okp_key.bytes.bytes());
+ });
- // 5. Set serialized.[[Handle]] to the [[handle]] internal slot of value.
- m_key_data.visit([&](auto const& handle) { serialize_handle(serialized, handle); });
+ steps(state, &fields);
- return {};
+ for (auto& buffer : exported)
+ secure_zero(buffer.data(), buffer.size());
}
-WebIDL::ExceptionOr<void> CryptoKey::deserialization_steps(JS::Realm& realm, HTML::StructuredSerializeReader& serialized, HTML::DeserializationMemory&)
+static WebIDL::ExceptionOr<CryptoKey::InternalKeyData> handle_from_fields(JS::VM& vm, CryptoKeyFields const& fields)
{
- // 1. Initialize the [[type]] internal slot of value to serialized.[[Type]].
- if (serialized.type() == HTML::SerializationType::Storage) {
- auto type = TRY(HTML::decode_or_throw_data_clone_error<Bindings::KeyType>(realm, serialized));
- m_type = type == Bindings::KeyType::Public ? KeyType::Public : (type == Bindings::KeyType::Private ? KeyType::Private : KeyType::Secret);
- } else {
- m_type = static_cast<KeyType>(TRY(HTML::decode_or_throw_data_clone_error<int>(realm, serialized)));
- }
+ auto buffer = [&](size_t index) {
+ VERIFY(index < fields.handle_buffer_count);
+ return fields.handle_buffers[index];
+ };
+ auto copy = [&](size_t index) -> WebIDL::ExceptionOr<ByteBuffer> {
+ return TRY_OR_THROW_OOM(vm, ByteBuffer::copy(buffer(index)));
+ };
+ auto big_integer = [&](size_t index) { return ::Crypto::UnsignedBigInteger::import_data(buffer(index)); };
- // 2. Initialize the [[extractable]] internal slot of value to serialized.[[Extractable]].
- m_extractable = TRY(HTML::decode_or_throw_data_clone_error<bool>(realm, serialized));
-
- // 3. Initialize the [[algorithm]] internal slot of value to the sub-deserialization of serialized.[[Algorithm]].
- m_algorithm = TRY(deserialize_algorithm(serialized, realm));
-
- // 4. Initialize the [[usages]] internal slot of value to the sub-deserialization of serialized.[[Usages]].
- m_key_usages = TRY(HTML::decode_or_throw_data_clone_error<Vector<KeyUsage>>(realm, serialized));
-
- // 5. Initialize the [[handle]] internal slot of value to serialized.[[Handle]].
- auto tag = TRY(decode_handle_tag(serialized, realm));
- switch (tag) {
+ switch (static_cast<HandleTag>(fields.handle_tag)) {
case HandleTag::ByteBuffer:
- m_key_data = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, serialized));
- break;
+ return TRY(copy(0));
case HandleTag::RSAPublicKey:
- m_key_data = TRY(deserialize_rsa_public_key(serialized, realm));
- break;
+ return ::Crypto::PK::RSAPublicKey { big_integer(0), big_integer(1) };
case HandleTag::RSAPrivateKey:
- m_key_data = TRY(deserialize_rsa_private_key(serialized, realm));
- break;
+ return ::Crypto::PK::RSAPrivateKey { big_integer(0), big_integer(1), big_integer(2), big_integer(3), big_integer(4), big_integer(5), big_integer(6), big_integer(7) };
case HandleTag::ECPublicKey:
- m_key_data = TRY(deserialize_ec_public_key(serialized, realm));
- break;
- case HandleTag::ECPrivateKey:
- m_key_data = TRY(deserialize_ec_private_key(serialized, realm));
- break;
+ return ::Crypto::PK::ECPublicKey { big_integer(0), big_integer(1), buffer(0).size() };
+ case HandleTag::ECPrivateKey: {
+ Optional<::Crypto::ASN1::ObjectIdentifier> parameters;
+ if (fields.has_ec_parameters) {
+ ::Crypto::ASN1::ObjectIdentifier identifier;
+ TRY_OR_THROW_OOM(vm, identifier.try_append(fields.ec_parameters.data(), fields.ec_parameters.size()));
+ parameters = move(identifier);
+ }
+ Optional<::Crypto::PK::ECPublicKey> public_key;
+ if (fields.has_ec_public_key)
+ public_key = ::Crypto::PK::ECPublicKey { big_integer(1), big_integer(2), buffer(1).size() };
+ return ::Crypto::PK::ECPrivateKey { big_integer(0), buffer(0).size(), move(parameters), move(public_key) };
+ }
case HandleTag::MLDSAPublicKey:
- m_key_data = TRY(deserialize_mldsa_public_key(serialized, realm));
- break;
+ return ::Crypto::PK::MLDSAPublicKey { TRY(copy(0)) };
case HandleTag::MLDSAPrivateKey:
- m_key_data = TRY(deserialize_mldsa_private_key(serialized, realm));
- break;
+ return ::Crypto::PK::MLDSAPrivateKey { TRY(copy(0)), TRY(copy(1)), TRY(copy(2)) };
case HandleTag::MLKEMPublicKey:
- m_key_data = TRY(deserialize_mlkem_public_key(serialized, realm));
- break;
+ return ::Crypto::PK::MLKEMPublicKey { TRY(copy(0)) };
case HandleTag::MLKEMPrivateKey:
- m_key_data = TRY(deserialize_mlkem_private_key(serialized, realm));
- break;
+ return ::Crypto::PK::MLKEMPrivateKey { TRY(copy(0)), TRY(copy(1)), TRY(copy(2)) };
case HandleTag::OKPPublicKey:
- m_key_data = TRY(deserialize_okp_public_key(serialized, realm));
- break;
+ return OKPPublicKey { TRY(copy(0)) };
case HandleTag::OKPPrivateKey:
- m_key_data = TRY(deserialize_okp_private_key(serialized, realm));
- break;
+ return OKPPrivateKey { TRY(copy(0)) };
+ }
+ VERIFY_NOT_REACHED();
+}
+
+static WebIDL::ExceptionOr<CryptoKey::InternalAlgorithmData> algorithm_from_fields(JS::VM& vm, CryptoKeyFields const& fields)
+{
+ auto name = Utf16String::from_raw(fields.algorithm_name);
+ switch (static_cast<SerializedKeyAlgorithmType>(fields.algorithm_type)) {
+ case SerializedKeyAlgorithmType::Key:
+ return CryptoKey::KeyAlgorithmData { move(name) };
+ case SerializedKeyAlgorithmType::Rsa:
+ return CryptoKey::RsaKeyAlgorithmData { move(name), fields.modulus_length, TRY_OR_THROW_OOM(vm, ByteBuffer::copy(fields.public_exponent)) };
+ case SerializedKeyAlgorithmType::RsaHashed:
+ return CryptoKey::RsaHashedKeyAlgorithmData { move(name), fields.modulus_length, TRY_OR_THROW_OOM(vm, ByteBuffer::copy(fields.public_exponent)), Utf16String::from_raw(fields.hash) };
+ case SerializedKeyAlgorithmType::Ec:
+ return CryptoKey::EcKeyAlgorithmData { move(name), Utf16String::from_raw(fields.named_curve) };
+ case SerializedKeyAlgorithmType::Aes:
+ return CryptoKey::AesKeyAlgorithmData { move(name), static_cast<u16>(fields.length) };
+ case SerializedKeyAlgorithmType::Hmac:
+ return CryptoKey::HmacKeyAlgorithmData { move(name), Utf16String::from_raw(fields.hash), fields.length };
+ case SerializedKeyAlgorithmType::Kmac:
+ return CryptoKey::KmacKeyAlgorithmData { move(name), fields.length };
}
+ VERIFY_NOT_REACHED();
+}
- return {};
+JSCompletion web_crypto_key_create(void* realm, CryptoKeyFields const* fields, JSObject** out_key)
+{
+ auto& js_realm = *static_cast<JS::Realm*>(realm);
+ auto& vm = js_realm.vm();
+ auto key = [&]() -> WebIDL::ExceptionOr<GC::Ref<CryptoKey>> {
+ auto key = CryptoKey::create(TRY(handle_from_fields(vm, *fields)));
+ key->set_type(static_cast<KeyType>(fields->type));
+ key->set_extractable(fields->extractable);
+ key->set_algorithm(TRY(algorithm_from_fields(vm, *fields)));
+ Vector<KeyUsage> usages;
+ TRY_OR_THROW_OOM(vm, usages.try_ensure_capacity(fields->usages.size()));
+ for (auto usage : fields->usages)
+ usages.unchecked_append(static_cast<KeyUsage>(usage));
+ key->set_usages(move(usages));
+ return key;
+ }();
+ if (key.is_exception())
+ return Bindings::completion_to_abi(js_realm, key.release_error());
+ *out_key = JS::HostABI::object_to_abi(Bindings::wrap(Bindings::host_defined_wrapper_world(js_realm), js_realm, key.release_value()).ptr());
+ return Bindings::completion_to_abi(js_realm, JS::js_undefined());
}
}
diff --git a/Libraries/LibWeb/Crypto/CryptoKey.h b/Libraries/LibWeb/Crypto/CryptoKey.h
index b515eef3276..bda7a9a87f2 100644
--- a/Libraries/LibWeb/Crypto/CryptoKey.h
+++ b/Libraries/LibWeb/Crypto/CryptoKey.h
@@ -13,7 +13,6 @@
#include <LibGC/Ptr.h>
#include <LibJS/Forward.h>
#include <LibWeb/Bindings/CryptoKey.h>
-#include <LibWeb/Bindings/Serializable.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Crypto/CryptoBindings.h>
#include <LibWebCommon/WebIDL/Types.h>
@@ -43,9 +42,7 @@ enum class KeyType {
Secret,
};
-class WEB_API CryptoKey final
- : public Bindings::GCAllocatedWrappable
- , public Bindings::Serializable {
+class WEB_API CryptoKey final : public Bindings::GCAllocatedWrappable {
WEB_WRAPPABLE(CryptoKey, Bindings::GCAllocatedWrappable);
GC_DECLARE_ALLOCATOR(CryptoKey);
@@ -140,9 +137,6 @@ public:
InternalKeyData const& handle() const { return m_key_data; }
Utf16String const& algorithm_name() const;
- virtual WebIDL::ExceptionOr<void> serialization_steps(HTML::StructuredSerializeWriter&, bool for_storage, HTML::SerializationMemory&) override;
- virtual WebIDL::ExceptionOr<void> deserialization_steps(JS::Realm&, HTML::StructuredSerializeReader&, HTML::DeserializationMemory&) override;
-
private:
explicit CryptoKey(InternalKeyData);
CryptoKey();
diff --git a/Libraries/LibWeb/Crypto/CryptoKeySerializationTags.h b/Libraries/LibWeb/Crypto/CryptoKeySerializationTags.h
index 55e8d8336df..2b6badb9b89 100644
--- a/Libraries/LibWeb/Crypto/CryptoKeySerializationTags.h
+++ b/Libraries/LibWeb/Crypto/CryptoKeySerializationTags.h
@@ -74,22 +74,4 @@ static constexpr Array<KeyAlgorithmTagExpectation, 7> s_key_algorithm_tag_expect
{ KeyAlgorithmTag::KmacKeyAlgorithm, HTML::Expectation::PositiveGolden },
} };
-static constexpr bool handle_tag_is_in_table(HandleTag tag)
-{
- for (auto const& entry : s_handle_tag_expectations) {
- if (entry.tag == tag)
- return true;
- }
- return false;
-}
-
-static constexpr bool key_algorithm_tag_is_in_table(KeyAlgorithmTag tag)
-{
- for (auto const& entry : s_key_algorithm_tag_expectations) {
- if (entry.tag == tag)
- return true;
- }
- return false;
-}
-
}
diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.cpp b/Libraries/LibWeb/HTML/StructuredSerialize.cpp
index 2d0e1c590ad..c300b141693 100644
--- a/Libraries/LibWeb/HTML/StructuredSerialize.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerialize.cpp
@@ -1252,20 +1252,6 @@ WebIDL::ExceptionOr<ByteBuffer> TransferDataDecoder::decode_buffer()
return buffer.release_value();
}
-void encode_unsigned_big_integer(StructuredSerializeWriter& writer, ::Crypto::UnsignedBigInteger const& value)
-{
- auto buffer = MUST(ByteBuffer::create_zeroed(value.byte_length()));
- auto written = value.export_data(buffer.bytes());
- VERIFY(written.size() == buffer.size());
- writer.encode(buffer);
-}
-
-WebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> decode_unsigned_big_integer(StructuredSerializeReader& reader, JS::Realm& realm)
-{
- auto buffer = TRY(decode_or_throw_data_clone_error<ByteBuffer>(realm, reader));
- return ::Crypto::UnsignedBigInteger::import_data(buffer);
-}
-
WebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> TransferDataDecoder::decode_unsigned_big_integer()
{
auto buffer = TRY(decode_buffer());
diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.h b/Libraries/LibWeb/HTML/StructuredSerialize.h
index 8d2832f15e4..af55f253e38 100644
--- a/Libraries/LibWeb/HTML/StructuredSerialize.h
+++ b/Libraries/LibWeb/HTML/StructuredSerialize.h
@@ -168,9 +168,6 @@ WEB_API WebIDL::ExceptionOr<JS::Value> structured_deserialize_internal(JS::VM&,
WEB_API WebIDL::Exception data_clone_error_from_serialization_error(JS::Realm&, AK::Error const&);
-void encode_unsigned_big_integer(StructuredSerializeWriter&, ::Crypto::UnsignedBigInteger const&);
-WebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> decode_unsigned_big_integer(StructuredSerializeReader&, JS::Realm&);
-
void encode_signed_big_integer(StructuredSerializeWriter&, ::Crypto::SignedBigInteger const&);
WebIDL::ExceptionOr<::Crypto::SignedBigInteger> decode_signed_big_integer(StructuredSerializeReader&, JS::Realm&);
diff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
index bcdfaee126e..eab9d36dcb0 100644
--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
@@ -44,6 +44,7 @@ enum class SerializableSteps : u8 {
Rust,
DOMException,
QuotaExceededError,
+ CryptoKey,
Cpp,
};
@@ -55,6 +56,7 @@ u8 web_structured_serialize_writer_type(StructuredSerializeWriter*);
void web_structured_serialize_writer_encode_u8(StructuredSerializeWriter*, u8);
void web_structured_serialize_writer_encode_bool(StructuredSerializeWriter*, bool);
void web_structured_serialize_writer_encode_i32(StructuredSerializeWriter*, i32);
+void web_structured_serialize_writer_encode_u16(StructuredSerializeWriter*, u16);
void web_structured_serialize_writer_encode_u32(StructuredSerializeWriter*, u32);
void web_structured_serialize_writer_encode_u64(StructuredSerializeWriter*, u64);
void web_structured_serialize_writer_encode_f64(StructuredSerializeWriter*, double);
@@ -73,6 +75,7 @@ bool web_structured_serialize_reader_is_at_end(StructuredSerializeReader*);
JSCompletion web_structured_serialize_reader_decode_u8(StructuredSerializeReader*, void* realm, u8*);
JSCompletion web_structured_serialize_reader_decode_bool(StructuredSerializeReader*, void* realm, bool*);
JSCompletion web_structured_serialize_reader_decode_i32(StructuredSerializeReader*, void* realm, i32*);
+JSCompletion web_structured_serialize_reader_decode_u16(StructuredSerializeReader*, void* realm, u16*);
JSCompletion web_structured_serialize_reader_decode_u32(StructuredSerializeReader*, void* realm, u32*);
JSCompletion web_structured_serialize_reader_decode_u64(StructuredSerializeReader*, void* realm, u64*);
JSCompletion web_structured_serialize_reader_decode_size(StructuredSerializeReader*, void* realm, size_t*);
@@ -80,6 +83,7 @@ JSCompletion web_structured_serialize_reader_decode_f64(StructuredSerializeReade
JSCompletion web_structured_serialize_reader_decode_utf16_string(StructuredSerializeReader*, void* realm, FlatPtr*);
JSCompletion web_structured_serialize_reader_decode_optional_utf16_string(StructuredSerializeReader*, void* realm, bool* has_value, FlatPtr*);
JSCompletion web_structured_serialize_reader_decode_byte_buffer(StructuredSerializeReader*, void* realm, ByteBuffer** buffer);
+u8 const* web_structured_serialize_byte_buffer_data(ByteBuffer*);
size_t web_structured_serialize_byte_buffer_size(ByteBuffer*);
JSObject* web_structured_serialize_array_buffer_from_byte_buffer(void* realm, ByteBuffer*, bool shared);
void web_structured_serialize_byte_buffer_destroy(ByteBuffer*);
@@ -216,6 +220,11 @@ void web_structured_serialize_writer_encode_i32(StructuredSerializeWriter* write
writer->encode(static_cast<int>(value));
}
+void web_structured_serialize_writer_encode_u16(StructuredSerializeWriter* writer, u16 value)
+{
+ writer->encode(value);
+}
+
void web_structured_serialize_writer_encode_u32(StructuredSerializeWriter* writer, u32 value)
{
writer->encode(value);
@@ -304,6 +313,11 @@ JSCompletion web_structured_serialize_reader_decode_i32(StructuredSerializeReade
return completion;
}
+JSCompletion web_structured_serialize_reader_decode_u16(StructuredSerializeReader* reader, void* realm, u16* value)
+{
+ return decode_into(realm_from_abi(realm), *reader, *value);
+}
+
JSCompletion web_structured_serialize_reader_decode_u32(StructuredSerializeReader* reader, void* realm, u32* value)
{
return decode_into(realm_from_abi(realm), *reader, *value);
@@ -355,6 +369,11 @@ JSCompletion web_structured_serialize_reader_decode_byte_buffer(StructuredSerial
return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<JS::Value> { JS::js_undefined() });
}
+u8 const* web_structured_serialize_byte_buffer_data(ByteBuffer* buffer)
+{
+ return buffer->data();
+}
+
size_t web_structured_serialize_byte_buffer_size(ByteBuffer* buffer)
{
return buffer->size();
@@ -572,6 +591,8 @@ u8 web_structured_serialize_serializable_steps(u16 interface_name)
return to_underlying(SerializableSteps::DOMException);
case Bindings::InterfaceName::QuotaExceededError:
return to_underlying(SerializableSteps::QuotaExceededError);
+ case Bindings::InterfaceName::CryptoKey:
+ return to_underlying(SerializableSteps::CryptoKey);
default:
if (Bindings::serializable_interface_is_implemented_in_rust(static_cast<Bindings::InterfaceName>(interface_name)))
return to_underlying(SerializableSteps::Rust);
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index a73f1752913..ee1a0dabf66 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -40,7 +40,7 @@ ALLOWED_REALM_MENTIONS = {
"Clipboard": (4, 16, "clipboard item/data callbacks still materialize JS values in caller-selected realms"),
"ContentSecurityPolicy": (4, 10, "CSP violation/report objects and callbacks still materialize JS-facing values"),
"CookieStore": (2, 19, "cookie-store async callbacks and promise/value materialization still thread realms"),
- "Crypto": (8, 382, "WebCrypto algorithms still use realms for buffer/key/promise materialization"),
+ "Crypto": (8, 369, "WebCrypto algorithms still use realms for buffer/key/promise materialization"),
"DOM": (10, 33, "DOM abort plumbing and node helpers still have callback/materialization realm use"),
"Fetch": (
20,
@@ -52,7 +52,7 @@ ALLOWED_REALM_MENTIONS = {
"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),
"HTML": (
65,
- 197,
+ 195,
"HTML algorithms still contain structured serialization, including posted-message preparation, canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; RemoteWindow mirrors Window's postMessage; "
"the C++ glue of the Rust structured serialization reads records and creates platform objects in a given realm",
),