Truly independent web browser
LibWeb: Port CryptoKey to Rust
Shannon Booth922cce322548
diff --git a/Libraries/LibWeb/Bindings/MainThreadVM.cpp b/Libraries/LibWeb/Bindings/MainThreadVM.cppindex f0a65da94f8..fa706d8579e 100644--- a/Libraries/LibWeb/Bindings/MainThreadVM.cpp+++ b/Libraries/LibWeb/Bindings/MainThreadVM.cpp@@ -45,7 +45,6 @@#include <LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h>#include <LibWeb/ContentSecurityPolicy/Directives/KeywordSources.h>#include <LibWeb/ContentSecurityPolicy/Directives/Names.h>-#include <LibWeb/Crypto/CryptoKey.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Element.h>#include <LibWeb/Fetch/Fetching/BodyStreamPullSource.h>@@ -797,7 +796,6 @@ void shut_down_agent()Fetch::Fetching::disarm_all_body_stream_wakes();HTML::clear_message_event_ports_caches();PerformanceTimeline::clear_supported_entry_types_caches();- Crypto::clear_crypto_key_caches();ServiceWorker::clear_service_worker_container_ready_promise_caches();PermissionsAPI::PermissionStore::forget_statuses_of_this_agent();FileAPI::forget_blob_url_store_of_this_agent();diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rsindex e2cd68222e9..7b904ccb9b9 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs@@ -69,6 +69,10 @@ impl<'a, 'memory> SerializationWriter<'a, 'memory> {self.serialized().encode_i32(value);}+ pub(crate) fn write_u16(&mut self, value: u16) {+ self.serialized().encode_u16(value);+ }+pub(crate) fn write_u32(&mut self, value: u32) {self.serialized().encode_u32(value);}@@ -150,6 +154,10 @@ impl<'a, 'memory> SerializationReader<'a, 'memory> {self.serialized().decode_i32()}+ pub(crate) fn read_u16(&mut self) -> WebIdlResult<u16> {+ self.serialized().decode_u16()+ }+pub(crate) fn read_u32(&mut self) -> WebIdlResult<u32> {self.serialized().decode_u32()}diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rsindex 1bacf7d1b40..314b45fb565 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs@@ -6,63 +6,396 @@* 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::cell::{Cell, RefCell};use core::ffi::c_void;use core::ptr::NonNull;-use ak::Utf16String;-use libjs_rust::api::{Gc, Object, RawNativeFunctionResult, Realm};-use libwebcommon_rust::html::serialization_records::SerializationType;+use ak::{Span, Utf16String};+use libjs_rust::api::{+ Array, CellRoot, ErrorKind, ErrorType, Gc, GcRefCell, GcWeak, IntegrityLevel, MarkedVec, Must, Object,+ PrimitiveString, PropertyKey, RawNativeFunctionResult, Trace, Value, Vm,+};++use crate::bindings::conversions::create_uint8_array;+use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, create_dictionary_object};+use crate::bindings::setlike::WorldEntries;+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};+use crate::bindings::{CallContext, Exception, WebIdlResult};++#[derive(Clone, Copy)]+#[repr(u8)]+pub(crate) enum KeyType {+ Public,+ Private,+ Secret,+}++const KEY_TYPE_VALUES: [KeyType; 3] = [KeyType::Public, KeyType::Private, KeyType::Secret];++#[derive(Clone, Copy)]+#[repr(u8)]+pub(crate) enum KeyUsage {+ Encrypt,+ Decrypt,+ Sign,+ Verify,+ DeriveKey,+ DeriveBits,+ WrapKey,+ UnwrapKey,+ EncapsulateKey,+ EncapsulateBits,+ DecapsulateKey,+ DecapsulateBits,+}++const KEY_USAGE_VALUES: [KeyUsage; 12] = [+ KeyUsage::Encrypt,+ KeyUsage::Decrypt,+ KeyUsage::Sign,+ KeyUsage::Verify,+ KeyUsage::DeriveKey,+ KeyUsage::DeriveBits,+ KeyUsage::WrapKey,+ KeyUsage::UnwrapKey,+ KeyUsage::EncapsulateKey,+ KeyUsage::EncapsulateBits,+ KeyUsage::DecapsulateKey,+ KeyUsage::DecapsulateBits,+];++enum InternalAlgorithmData {+ Key {+ name: Utf16String,+ },+ Rsa {+ name: Utf16String,+ modulus_length: u32,+ public_exponent: Vec<u8>,+ },+ RsaHashed {+ name: Utf16String,+ modulus_length: u32,+ public_exponent: Vec<u8>,+ hash: Utf16String,+ },+ Ec {+ name: Utf16String,+ named_curve: Utf16String,+ },+ Aes {+ name: Utf16String,+ length: u16,+ },+ Hmac {+ name: Utf16String,+ hash: Utf16String,+ length: u32,+ },+ Kmac {+ name: Utf16String,+ length: u32,+ },+}++impl InternalAlgorithmData {+ fn name(&self) -> &Utf16String {+ match self {+ Self::Key { name }+ | Self::Rsa { name, .. }+ | Self::RsaHashed { name, .. }+ | Self::Ec { name, .. }+ | Self::Aes { name, .. }+ | Self::Hmac { name, .. }+ | Self::Kmac { name, .. } => name,+ }+ }+}++struct CryptoKeyHandle(NonNull<c_void>);++impl Drop for CryptoKeyHandle {+ fn drop(&mut self) {+ // SAFETY: The key handle is owned by this object.+ unsafe { web_crypto_key_destroy_handle(self.0.as_ptr()) };+ }+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct CachedAlgorithmObject {+ wrapper: GcWeak<Object>,+ object: Gc<Object>,+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CryptoKey {+ #[gc(untraced)]+ r#type: Cell<Option<KeyType>>,+ #[gc(untraced)]+ extractable: Cell<bool>,+ #[gc(untraced)]+ algorithm: RefCell<InternalAlgorithmData>,+ #[gc(untraced)]+ key_usages: RefCell<Vec<KeyUsage>>,+ #[gc(untraced)]+ handle: RefCell<Option<CryptoKeyHandle>>,+ #[gc(untraced)]+ algorithm_name: RefCell<Utf16String>,+ cached_algorithm_objects: GcRefCell<Vec<CachedAlgorithmObject>>,+ cached_usages_objects: WorldEntries<Object>,+}++impl Wrappable for CryptoKey {+ const FINALIZES: bool = true;-use crate::bindings::{Exception, WebIdlResult};-use crate::html::structured_serialize::reader::StructuredSerializeReader;-use crate::html::structured_serialize::writer::StructuredSerializeWriter;+ fn finalize(object: Ref<Self>) {+ object.handle.borrow_mut().take();+ }+}-/// 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.+fn create_key_algorithm_object(cx: &CallContext, name: &Utf16String) -> WebIdlResult<Gc<Object>> {+ let object = create_dictionary_object(cx);+ object.create_data_property_or_throw(+ cx.vm(),+ &PropertyKey::from_utf8("name"),+ Value::from_string(PrimitiveString::create(cx.vm(), name.clone())),+ )?;+ Ok(object)+}++fn create_algorithm_object(cx: &CallContext, algorithm: &InternalAlgorithmData) -> WebIdlResult<Gc<Object>> {+ let vm = cx.vm();+ match algorithm {+ InternalAlgorithmData::Key { name } => create_key_algorithm_object(cx, name),+ InternalAlgorithmData::Rsa {+ name,+ modulus_length,+ public_exponent,+ } => {+ let object = create_key_algorithm_object(cx, name)?;+ object.create_data_property_or_throw(+ vm,+ &PropertyKey::from_utf8("modulusLength"),+ Value::from_f64(f64::from(*modulus_length)),+ )?;+ object.create_data_property_or_throw(+ vm,+ &PropertyKey::from_utf8("publicExponent"),+ Value::from_object(create_uint8_array(cx, public_exponent)?),+ )?;+ Ok(object)+ }+ InternalAlgorithmData::RsaHashed {+ name,+ modulus_length,+ public_exponent,+ hash,+ } => {+ let object = create_key_algorithm_object(cx, name)?;+ object.create_data_property_or_throw(+ vm,+ &PropertyKey::from_utf8("modulusLength"),+ Value::from_f64(f64::from(*modulus_length)),+ )?;+ object.create_data_property_or_throw(+ vm,+ &PropertyKey::from_utf8("publicExponent"),+ Value::from_object(create_uint8_array(cx, public_exponent)?),+ )?;+ object.create_data_property_or_throw(+ vm,+ &PropertyKey::from_utf8("hash"),+ Value::from_object(create_key_algorithm_object(cx, hash)?),+ )?;+ Ok(object)+ }+ InternalAlgorithmData::Ec { name, named_curve } => {+ let object = create_key_algorithm_object(cx, name)?;+ object.create_data_property_or_throw(+ vm,+ &PropertyKey::from_utf8("namedCurve"),+ Value::from_string(PrimitiveString::create(vm, named_curve.clone())),+ )?;+ Ok(object)+ }+ InternalAlgorithmData::Aes { name, length } => {+ let object = create_key_algorithm_object(cx, name)?;+ object.create_data_property_or_throw(+ vm,+ &PropertyKey::from_utf8("length"),+ Value::from_i32(i32::from(*length)),+ )?;+ Ok(object)+ }+ InternalAlgorithmData::Hmac { name, hash, length } => {+ let object = create_key_algorithm_object(cx, name)?;+ object.create_data_property_or_throw(+ vm,+ &PropertyKey::from_utf8("hash"),+ Value::from_object(create_key_algorithm_object(cx, hash)?),+ )?;+ object.create_data_property_or_throw(+ vm,+ &PropertyKey::from_utf8("length"),+ Value::from_f64(f64::from(*length)),+ )?;+ Ok(object)+ }+ InternalAlgorithmData::Kmac { name, length } => {+ let object = create_key_algorithm_object(cx, name)?;+ object.create_data_property_or_throw(+ vm,+ &PropertyKey::from_utf8("length"),+ Value::from_f64(f64::from(*length)),+ )?;+ Ok(object)+ }+ }+}++#[allow(+ clippy::unnecessary_wraps,+ reason = "the generated bindings can propagate exceptions from every getter"+)]+impl CryptoKey {+ fn create(vm: &Vm, handle: CryptoKeyHandle) -> Ref<Self> {+ allocate(vm, |_| Self {+ r#type: Cell::new(None),+ extractable: Cell::new(false),+ algorithm: RefCell::new(InternalAlgorithmData::Key {+ name: Utf16String::default(),+ }),+ key_usages: RefCell::default(),+ handle: RefCell::new(Some(handle)),+ algorithm_name: RefCell::default(),+ cached_algorithm_objects: GcRefCell::default(),+ cached_usages_objects: WorldEntries::default(),+ })+ }++ fn handle(&self) -> NonNull<c_void> {+ self.handle.borrow().as_ref().expect("a live key has its handle").0+ }++ fn set_algorithm(&self, algorithm: InternalAlgorithmData) {+ self.algorithm.replace(algorithm);+ self.algorithm_name.replace(Utf16String::default());+ self.cached_algorithm_objects.replace(Vec::new());+ }++ fn set_usages(&self, usages: Vec<KeyUsage>) {+ self.key_usages.replace(usages);+ }++ fn key_type(&self) -> KeyType {+ self.r#type+ .get()+ .expect("the key type is initialized before it is read")+ }++ pub(crate) fn extractable(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ Ok(self.extractable.get())+ }++ pub(crate) fn bindings_type(&self, _: &mut CallContext) -> WebIdlResult<KeyType> {+ Ok(self.key_type())+ }++ pub(crate) fn algorithm(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ let wrapper = cx.vm().this_value().as_object();+ self.cached_algorithm_objects+ .borrow_mut(cx.vm())+ .retain(|entry| entry.wrapper.get().is_some());++ let cached_object = self+ .cached_algorithm_objects+ .borrow()+ .iter()+ .find_map(|entry| (entry.wrapper.get() == Some(wrapper)).then_some(entry.object));+ if let Some(object) = cached_object {+ return Ok(Value::from_object(object));+ }++ let object = create_algorithm_object(cx, &self.algorithm.borrow())?;+ self.cached_algorithm_objects+ .borrow_mut(cx.vm())+ .push(CachedAlgorithmObject {+ wrapper: GcWeak::new(cx.vm().heap(), wrapper),+ object,+ });+ Ok(Value::from_object(object))+ }++ pub(crate) fn usages(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ let usages = self.cached_usages_objects.get_or_create(cx, || {+ let vm = cx.vm();+ let values = MarkedVec::new(vm);+ for usage in self.key_usages.borrow().iter() {+ values.push(Value::from_string(PrimitiveString::create_from_ascii(+ vm,+ KEY_USAGES[*usage as usize],+ )));+ }+ let usages = CellRoot::new(Array::create_from_list(vm, cx.realm(), &values));+ usages.cell().set_integrity_level(vm, IntegrityLevel::Frozen).must();+ usages.cell().upcast()+ });+ Ok(Value::from_object(usages))+ }++ fn algorithm_name(&self) -> Utf16String {+ let mut algorithm_name = self.algorithm_name.borrow_mut();+ if algorithm_name.is_empty() {+ *algorithm_name = self.algorithm.borrow().name().clone();+ }+ algorithm_name.clone()+ }+}++#[derive(Default)]#[repr(C)]-struct RawFields<'a> {- /// Crypto::KeyType, in the order of Bindings::KeyType.+struct RawAlgorithm<'a> {r#type: u8,- extractable: bool,- algorithm_type: u8,- algorithm_name: usize,+ name: usize,modulus_length: u32,- public_exponent: ak::Span<'a, u8>,+ public_exponent: Span<'a, u8>,hash: usize,named_curve: usize,length: u32,- /// Bindings::KeyUsage.- usages: ak::Span<'a, u8>,+}++#[repr(C)]+struct RawHandle<'a> {handle_tag: u8,- handle_buffers: [ak::Span<'a, u8>; MAX_HANDLE_BUFFERS],+ handle_buffers: [Span<'a, u8>; MAX_HANDLE_BUFFERS],handle_buffer_count: usize,has_ec_parameters: bool,- ec_parameters: ak::Span<'a, u32>,+ ec_parameters: Span<'a, u32>,has_ec_public_key: bool,}unsafe extern "C" {- fn web_crypto_key_with_fields(- key: *mut c_void,+ fn web_crypto_key_destroy_handle(handle: *mut c_void);+ fn web_crypto_key_encode_handle(+ handle: *mut c_void,state: *mut c_void,- steps: unsafe extern "C" fn(state: *mut c_void, fields: *const RawFields<'_>),+ steps: unsafe extern "C" fn(state: *mut c_void, handle: *const RawHandle<'_>),);- fn web_crypto_key_create(+ fn web_crypto_key_decode_handle(realm: *mut c_void,- fields: &RawFields<'_>,- out_key: &mut *mut c_void,+ fields: &RawHandle<'_>,+ out_handle: &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.+/// The identifiers by which a storage record holds a key type.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.+/// The identifiers by which a storage record holds a key usage.const KEY_USAGES: [&[u8]; 12] = [b"encrypt",b"decrypt",@@ -98,17 +431,17 @@ 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));+fn encode_identifier(serialized: &mut SerializationWriter, identifier: &[u8]) {+ serialized.write_utf16_string(&Utf16String::from_ascii(identifier));}/// The index of the identifier that a storage record holds.fn decode_identifier(- serialized: &StructuredSerializeReader,+ serialized: &mut SerializationReader,identifiers: &[&[u8]],unknown_message: &[u8],) -> WebIdlResult<u8> {- let identifier = serialized.decode_utf16_string()?;+ let identifier = serialized.read_utf16_string()?;identifiers.iter().position(|candidate| identifier == Utf16String::from_ascii(candidate))@@ -116,217 +449,442 @@ fn decode_identifier(.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);- }- // SAFETY: The object is a live CryptoKey, and the writer lives for the call.- unsafe {- web_crypto_key_with_fields(- key.as_ptr().cast(),- core::ptr::from_ref(serialized).cast_mut().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),- )- };+impl Serializable for CryptoKey {+ fn serialization_steps(+ &self,+ _: &mut CallContext,+ serialized: &mut SerializationWriter,+ for_storage: bool,+ ) -> WebIdlResult<()> {+ // 1. Set serialized.[[Type]] to the [[type]] internal slot of value.+ let key_type = self.key_type() as u8;+ if for_storage {+ encode_identifier(serialized, KEY_TYPES[usize::from(key_type)]);+ } else {+ serialized.write_i32(i32::from(key_type));+ }- // 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.write_bool(self.extractable.get());- // 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);+ // 3. Set serialized.[[Algorithm]] to the sub-serialization of the [[algorithm]] internal slot of value.+ let algorithm = self.algorithm.borrow();+ let fields = algorithm.fields();+ serialized.write_u8(fields.r#type);+ serialized.write_utf16_string(algorithm.name());+ match &*algorithm {+ InternalAlgorithmData::Key { .. } => {}+ InternalAlgorithmData::Rsa {+ modulus_length,+ public_exponent,+ ..+ } => {+ serialized.write_u32(*modulus_length);+ serialized.write_bytes(public_exponent);}+ InternalAlgorithmData::RsaHashed {+ modulus_length,+ public_exponent,+ hash,+ ..+ } => {+ serialized.write_u32(*modulus_length);+ serialized.write_bytes(public_exponent);+ serialized.write_utf16_string(hash);+ }+ InternalAlgorithmData::Ec { named_curve, .. } => serialized.write_utf16_string(named_curve),+ InternalAlgorithmData::Aes { length, .. } => serialized.write_u16(*length),+ InternalAlgorithmData::Hmac { hash, length, .. } => {+ serialized.write_utf16_string(hash);+ serialized.write_u32(*length);+ }+ InternalAlgorithmData::Kmac { length, .. } => serialized.write_u32(*length),}- 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);+ // 4. Set serialized.[[Usages]] to the sub-serialization of the [[usages]] internal slot of value.+ let usages = self.key_usages.borrow();+ serialized.write_u64(usages.len() as u64);+ for &usage in usages.iter() {+ if for_storage {+ encode_identifier(serialized, KEY_USAGES[usage as usize]);+ } else {+ serialized.write_u8(usage as u8);+ }}- }- // 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());+ // 5. Set serialized.[[Handle]] to the [[handle]] internal slot of value.+ unsafe extern "C" fn steps(state: *mut c_void, fields: *const RawHandle<'_>) {+ // SAFETY: The writer and the fields are lent for this call.+ let (serialized, fields) = unsafe { (&mut *state.cast::<SerializationWriter<'_, '_>>(), &*fields) };+ serialized.write_u8(fields.handle_tag);+ let buffers = &fields.handle_buffers[..fields.handle_buffer_count];+ if fields.handle_tag != HANDLE_EC_PRIVATE_KEY {+ for buffer in buffers {+ serialized.write_bytes(buffer.as_slice());+ }+ return;+ }+ serialized.write_bytes(buffers[0].as_slice());+ serialized.write_bool(fields.has_ec_parameters);+ if fields.has_ec_parameters {+ let parameters = fields.ec_parameters.as_slice();+ serialized.write_u64(parameters.len() as u64);+ for ¶meter in parameters {+ serialized.write_u32(parameter);+ }+ }+ serialized.write_bool(fields.has_ec_public_key);+ if fields.has_ec_public_key {+ serialized.write_bytes(buffers[1].as_slice());+ serialized.write_bytes(buffers[2].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 ¶meter in parameters {- serialized.encode_u32(parameter);++ // SAFETY: The handle is live and the writer is lent until the service returns.+ unsafe {+ web_crypto_key_encode_handle(self.handle().as_ptr(), core::ptr::from_mut(serialized).cast(), steps);}+ Ok(())}- 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"))?- };+ fn deserialization_steps(cx: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Ref<Self>> {+ let for_storage = serialized.is_for_storage();- // 2. Initialize the [[extractable]] internal slot of value to serialized.[[Extractable]].- let extractable = serialized.decode_bool()?;+ // 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.read_i32()?)+ .ok()+ .filter(|&r#type| usize::from(r#type) < KEY_TYPES.len())+ .ok_or_else(|| data_clone_error(b"Invalid structured serialize key type"))?+ };- // 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_bytes()?);- if algorithm_type == ALGORITHM_RSA_HASHED {- hash = serialized.decode_utf16_string()?;+ // 2. Initialize the [[extractable]] internal slot of value to serialized.[[Extractable]].+ let extractable = serialized.read_bool()?;++ // 3. Initialize the [[algorithm]] internal slot of value to the sub-deserialization of serialized.[[Algorithm]].+ let algorithm_type = serialized.read_u8()?;+ if algorithm_type > ALGORITHM_KMAC {+ return Err(data_clone_error(b"Invalid CryptoKey algorithm"));+ }+ let name = serialized.read_utf16_string()?;+ let (mut modulus_length, mut public_exponent, mut hash, mut named_curve, mut length) =+ (0, &[][..], Utf16String::default(), Utf16String::default(), 0);+ match algorithm_type {+ ALGORITHM_RSA | ALGORITHM_RSA_HASHED => {+ modulus_length = serialized.read_u32()?;+ public_exponent = serialized.read_borrowed_bytes()?;+ if algorithm_type == ALGORITHM_RSA_HASHED {+ hash = serialized.read_utf16_string()?;+ }}+ ALGORITHM_EC => named_curve = serialized.read_utf16_string()?,+ ALGORITHM_AES => length = u32::from(serialized.read_u16()?),+ ALGORITHM_HMAC => {+ hash = serialized.read_utf16_string()?;+ length = serialized.read_u32()?;+ }+ ALGORITHM_KMAC => length = serialized.read_u32()?,+ ALGORITHM_KEY => {}+ _ => unreachable!("the type is that of an algorithm, as checked above"),}- 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()?;++ // 4. Initialize the [[usages]] internal slot of value to the sub-deserialization of serialized.[[Usages]].+ let usage_count = serialized.read_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.read_u8()?)+ .filter(|&usage| usize::from(usage) < KEY_USAGES.len())+ .ok_or_else(|| data_clone_error(b"Invalid structured serialize key usage"))?+ };+ usages.push(KEY_USAGE_VALUES[usize::from(usage)]);}- 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"))?+ // 5. Initialize the [[handle]] internal slot of value to serialized.[[Handle]].+ let handle_tag = serialized.read_u8()?;+ let Some(&buffer_count) = HANDLE_BUFFER_COUNTS.get(usize::from(handle_tag)) else {+ return Err(data_clone_error(b"Invalid CryptoKey handle tag"));};- 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<&[u8]> = 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_bytes()?);- 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()?);+ let mut buffers: Vec<&[u8]> = 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.read_borrowed_bytes()?);+ has_ec_parameters = serialized.read_bool()?;+ if has_ec_parameters {+ let parameter_count = serialized.read_u64()?;+ for _ in 0..parameter_count {+ ec_parameters.push(serialized.read_u32()?);+ }+ }+ has_ec_public_key = serialized.read_bool()?;+ if has_ec_public_key {+ buffers.push(serialized.read_borrowed_bytes()?);+ buffers.push(serialized.read_borrowed_bytes()?);+ }+ } else {+ for _ in 0..buffer_count {+ buffers.push(serialized.read_borrowed_bytes()?);}}- has_ec_public_key = serialized.decode_bool()?;- if has_ec_public_key {- buffers.push(serialized.decode_bytes()?);- buffers.push(serialized.decode_bytes()?);++ let mut handle_buffers = [Span::default(); MAX_HANDLE_BUFFERS];+ for (span, buffer) in handle_buffers.iter_mut().zip(&buffers) {+ *span = Span::new(buffer);}- } else {- for _ in 0..buffer_count {- buffers.push(serialized.decode_bytes()?);+ let fields = RawHandle {+ handle_tag,+ handle_buffers,+ handle_buffer_count: buffers.len(),+ has_ec_parameters,+ ec_parameters: Span::new(&ec_parameters),+ has_ec_public_key,+ };+ let mut handle = core::ptr::null_mut();+ // SAFETY: The realm is live, and the fields are lent for the call.+ unsafe { web_crypto_key_decode_handle(cx.realm().as_ptr().cast(), &fields, &mut handle) }.into_completion()?;+ let key = Self::create(+ cx.vm(),+ CryptoKeyHandle(NonNull::new(handle).expect("LibWeb creates the key handle")),+ );++ let mut public_exponent_bytes = Vec::new();+ if public_exponent_bytes.try_reserve_exact(public_exponent.len()).is_err() {+ return cx+ .vm()+ .throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])+ .map_err(Into::into);}+ public_exponent_bytes.extend_from_slice(public_exponent);+ key.r#type.set(Some(KEY_TYPE_VALUES[usize::from(r#type)]));+ key.extractable.set(extractable);+ key.set_algorithm(InternalAlgorithmData::from_fields(+ &RawAlgorithm {+ r#type: algorithm_type,+ modulus_length,+ length,+ ..RawAlgorithm::default()+ },+ name,+ hash,+ named_curve,+ public_exponent_bytes,+ ));+ key.set_usages(usages);+ Ok(key)}+}- 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);+impl InternalAlgorithmData {+ fn fields(&self) -> RawAlgorithm<'_> {+ let mut fields = RawAlgorithm {+ name: self.name().raw_identity(),+ ..RawAlgorithm::default()+ };+ fields.r#type = match self {+ Self::Key { .. } => ALGORITHM_KEY,+ Self::Rsa {+ modulus_length,+ public_exponent,+ ..+ } => {+ fields.modulus_length = *modulus_length;+ fields.public_exponent = Span::new(public_exponent);+ ALGORITHM_RSA+ }+ Self::RsaHashed {+ modulus_length,+ public_exponent,+ hash,+ ..+ } => {+ fields.modulus_length = *modulus_length;+ fields.public_exponent = Span::new(public_exponent);+ fields.hash = hash.raw_identity();+ ALGORITHM_RSA_HASHED+ }+ Self::Ec { named_curve, .. } => {+ fields.named_curve = named_curve.raw_identity();+ ALGORITHM_EC+ }+ Self::Aes { length, .. } => {+ fields.length = u32::from(*length);+ ALGORITHM_AES+ }+ Self::Hmac { hash, length, .. } => {+ fields.hash = hash.raw_identity();+ fields.length = *length;+ ALGORITHM_HMAC+ }+ Self::Kmac { length, .. } => {+ fields.length = *length;+ ALGORITHM_KMAC+ }+ };+ fields}- 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)),- 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,++ fn from_fields(+ fields: &RawAlgorithm<'_>,+ name: Utf16String,+ hash: Utf16String,+ named_curve: Utf16String,+ public_exponent: Vec<u8>,+ ) -> Self {+ let RawAlgorithm {+ r#type,+ modulus_length,+ length,+ ..+ } = *fields;+ match r#type {+ ALGORITHM_KEY => Self::Key { name },+ ALGORITHM_RSA => Self::Rsa {+ name,+ modulus_length,+ public_exponent,+ },+ ALGORITHM_RSA_HASHED => Self::RsaHashed {+ name,+ modulus_length,+ public_exponent,+ hash,+ },+ ALGORITHM_EC => Self::Ec { name, named_curve },+ ALGORITHM_AES => Self::Aes {+ name,+ length: u16::try_from(length).expect("an AES key has a 16-bit length"),+ },+ ALGORITHM_HMAC => Self::Hmac { name, hash, length },+ ALGORITHM_KMAC => Self::Kmac { name, length },+ _ => unreachable!("the type is that of a key algorithm"),+ }+ }+}++/// # Safety+///+/// The VM is live and the caller transfers ownership of the handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_crypto_key_create(vm: *const c_void, handle: *mut c_void) -> *mut c_void {+ // SAFETY: The VM is live and the handle is owned.+ let vm = unsafe { &*vm.cast::<Vm>() };+ let handle = CryptoKeyHandle(NonNull::new(handle).expect("LibWeb supplies the handle"));+ cell_into_abi(CryptoKey::create(vm, handle))+}++/// # Safety+///+/// The key must be a live CryptoKey cell.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_crypto_key_handle(key: *mut c_void) -> *mut c_void {+ // SAFETY: LibWeb supplies a live CryptoKey cell.+ unsafe { cell_from_abi::<CryptoKey>(key) }.handle().as_ptr()+}++/// # Safety+///+/// The key must be a live CryptoKey cell.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_crypto_key_extractable(key: *mut c_void) -> bool {+ // SAFETY: LibWeb supplies a live CryptoKey cell.+ unsafe { cell_from_abi::<CryptoKey>(key) }.extractable.get()+}++/// # Safety+///+/// The key must be a live CryptoKey cell.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_crypto_key_set_extractable(key: *mut c_void, extractable: bool) {+ // SAFETY: LibWeb supplies a live CryptoKey cell.+ unsafe { cell_from_abi::<CryptoKey>(key) }.extractable.set(extractable);+}++/// # Safety+///+/// The key must be a live CryptoKey cell.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_crypto_key_type(key: *mut c_void) -> u8 {+ // SAFETY: LibWeb supplies a live CryptoKey cell.+ unsafe { cell_from_abi::<CryptoKey>(key) }.key_type() as u8+}++/// # Safety+///+/// The key must be a live CryptoKey cell and the type must be a valid KeyType.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_crypto_key_set_type(key: *mut c_void, r#type: u8) {+ // SAFETY: LibWeb supplies a live CryptoKey cell.+ let key = unsafe { cell_from_abi::<CryptoKey>(key) };+ key.r#type.set(Some(KEY_TYPE_VALUES[usize::from(r#type)]));+}++/// # Safety+///+/// The key must be a live CryptoKey cell and fields must point to writable storage.+#[unsafe(no_mangle)]+unsafe extern "C" fn web_rust_crypto_key_get_algorithm(key: *mut c_void, fields: *mut c_void) {+ // SAFETY: LibWeb supplies a live CryptoKey cell.+ let key = unsafe { cell_from_abi::<CryptoKey>(key) };+ let algorithm = key.algorithm.borrow();+ // SAFETY: LibWeb reads the fields before mutating the key or letting it die.+ unsafe { fields.cast::<RawAlgorithm<'_>>().write(algorithm.fields()) };+}++/// # Safety+///+/// The key must be a live CryptoKey cell and fields must own their strings.+#[unsafe(no_mangle)]+unsafe extern "C" fn web_rust_crypto_key_set_algorithm(key: *mut c_void, fields: &RawAlgorithm<'_>) {+ // SAFETY: LibWeb supplies a live CryptoKey cell and transfers the strings.+ let (key, name, hash, named_curve) = unsafe {+ (+ cell_from_abi::<CryptoKey>(key),+ Utf16String::from_raw_owned(fields.name),+ Utf16String::from_raw_owned(fields.hash),+ Utf16String::from_raw_owned(fields.named_curve),+ )};- 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")) })+ key.set_algorithm(InternalAlgorithmData::from_fields(+ fields,+ name,+ hash,+ named_curve,+ fields.public_exponent.as_slice().to_vec(),+ ));+}++/// # Safety+///+/// The key must be a live CryptoKey cell. The caller takes ownership of the returned string.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_crypto_key_algorithm_name(key: *mut c_void) -> usize {+ // SAFETY: LibWeb supplies a live CryptoKey cell.+ unsafe { cell_from_abi::<CryptoKey>(key) }.algorithm_name().into_raw()+}++/// # Safety+///+/// The key must be a live CryptoKey cell and steps must not mutate it.+#[unsafe(no_mangle)]+unsafe extern "C" fn web_rust_crypto_key_with_usages(+ key: *mut c_void,+ state: *mut c_void,+ steps: unsafe extern "C" fn(*mut c_void, Span<'_, KeyUsage>),+) {+ // SAFETY: LibWeb supplies a live CryptoKey cell and the usages are lent for the callback.+ let key = unsafe { cell_from_abi::<CryptoKey>(key) };+ unsafe { steps(state, Span::new(&key.key_usages.borrow())) };+}++/// # Safety+///+/// The key must be a live CryptoKey cell and usages must contain valid KeyUsage values.+#[unsafe(no_mangle)]+unsafe extern "C" fn web_rust_crypto_key_set_usages(key: *mut c_void, usages: Span<'_, KeyUsage>) {+ // SAFETY: LibWeb supplies a live CryptoKey cell and lends the usages for the call.+ unsafe { cell_from_abi::<CryptoKey>(key) }.set_usages(usages.as_slice().to_vec());}diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/mod.rsindex c0cb8026a83..3237617c898 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/mod.rs@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The serialization steps of the serializable interfaces of the Web Cryptography API, which LibWeb implements in C++.+//! The Web Cryptography API.+#[cfg_attr(not(web_idl_bindings), allow(dead_code))]pub(crate) mod crypto_key;diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rsindex 2526f8cb7f0..92a6a3e7fa4 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs@@ -38,7 +38,6 @@ use crate::bindings::structured_data::{SerializationReader, SerializationWriter, TransferDataReader, TransferDataWriter, Transferable,};use crate::bindings::{CallContext, Exception, WebIdlResult};-use crate::crypto::crypto_key;use crate::html::image_bitmap::ImageBitmap;use crate::html::message_port::MessagePort;use crate::html::offscreen_canvas;@@ -994,7 +993,6 @@ impl<'memory> Serializer<'_, '_, 'memory> {SerializableSteps::QuotaExceededError => {quota_exceeded_error::serialization_steps(&QuotaExceededErrorFields::of(object), serialized);}- SerializableSteps::CryptoKey => crypto_key::serialization_steps(object, serialized),SerializableSteps::RTCEncodedAudioFrame => {crate::webrtc::rtc_encoded_audio_frame::serialization_steps(object,@@ -1584,9 +1582,6 @@ 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)?)- }SerializableSteps::RTCEncodedAudioFrame => {Value::from_object(crate::webrtc::rtc_encoded_audio_frame::deserialization_steps(realm,diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/serializable.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/serializable.rsindex d84820a6afb..8e7fb81267e 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/serializable.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/serializable.rs@@ -22,7 +22,6 @@ pub(crate) enum SerializableSteps {Rust,DOMException,QuotaExceededError,- CryptoKey,RTCEncodedAudioFrame,}diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cppindex 337ff67f907..f804cb88497 100644--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp@@ -4860,7 +4860,7 @@ WebIDL::ExceptionOr<ExportKeyResult> ECDSA::export_key(JS::Realm&, KeyFormat for// Set the parameters field to an instance of the ECParameters ASN.1 type defined in [RFC5480] as follows:// Set the subjectPublicKey field to keyData// If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":- auto& algorithm = key->ec_algorithm();+ auto algorithm = key->ec_algorithm();if (algorithm.named_curve().is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {// Let keyData be the octet string that represents the Elliptic Curve public key represented by the [[handle]] internal slot// of key according to the encoding rules specified in Section 2.3.3 of [SEC1] and using the uncompressed form.@@ -4923,7 +4923,7 @@ WebIDL::ExceptionOr<ExportKeyResult> ECDSA::export_key(JS::Realm&, KeyFormat for// Set the privateKey field to keyData.// Set the parameters field to an instance of the ECParameters ASN.1 type defined in [RFC5480] as follows:// If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":- auto& algorithm = key->ec_algorithm();+ auto algorithm = key->ec_algorithm();if (algorithm.named_curve().is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {// Let keyData be the result of DER-encoding an instance of the ECPrivateKey structure defined// in Section 3 of [RFC5915] for the Elliptic Curve private key represented by the [[handle]] internal slot@@ -4982,7 +4982,7 @@ WebIDL::ExceptionOr<ExportKeyResult> ECDSA::export_key(JS::Realm&, KeyFormat forjwk.kty = "EC"_utf16;// 3. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":- auto& algorithm = key->ec_algorithm();+ auto algorithm = key->ec_algorithm();if (algorithm.named_curve().is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {// 1. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256":if (algorithm.named_curve() == "P-256"_utf16) {@@ -5095,7 +5095,7 @@ WebIDL::ExceptionOr<ExportKeyResult> ECDSA::export_key(JS::Realm&, KeyFormat forByteBuffer data;// 2. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":- auto& algorithm = key->ec_algorithm();+ auto algorithm = key->ec_algorithm();if (algorithm.named_curve().is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {// Let data be an octet string representing the Elliptic Curve point Q represented by [[handle]] internal slot// of key according to [SEC1] 2.3.3 using the uncompressed format.@@ -5288,8 +5288,8 @@ WebIDL::ExceptionOr<ByteBuffer> ECDH::derive_bits(JS::Realm& realm, AlgorithmPar// 7. If the name attribute of the [[algorithm]] internal slot of publicKey is not equal to// the name property of the [[algorithm]] internal slot of key, then throw an InvalidAccessError.- auto& internal_algorithm = key->ec_algorithm();- auto& public_internal_algorithm = public_key->ec_algorithm();+ auto internal_algorithm = key->ec_algorithm();+ auto public_internal_algorithm = public_key->ec_algorithm();if (internal_algorithm.name() != public_internal_algorithm.name()) {return WebIDL::InvalidAccessError::create("Algorithm mismatch"_utf16);}@@ -5839,7 +5839,7 @@ WebIDL::ExceptionOr<ExportKeyResult> ECDH::export_key(JS::Realm&, KeyFormat form// Set the parameters field to an instance of the ECParameters ASN.1 type defined in [RFC5480] as follows:// Set the subjectPublicKey field to keyData// If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":- auto& algorithm = key->ec_algorithm();+ auto algorithm = key->ec_algorithm();if (algorithm.named_curve().is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {// Let keyData be the octet string that represents the Elliptic Curve public key represented by the [[handle]] internal slot// of key according to the encoding rules specified in Section 2.3.3 of [SEC1] and using the uncompressed form.@@ -5902,7 +5902,7 @@ WebIDL::ExceptionOr<ExportKeyResult> ECDH::export_key(JS::Realm&, KeyFormat form// Set the privateKey field to keyData.// Set the parameters field to an instance of the ECParameters ASN.1 type defined in [RFC5480] as follows:// If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":- auto& algorithm = key->ec_algorithm();+ auto algorithm = key->ec_algorithm();if (algorithm.named_curve().is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {// Let keyData be the result of DER-encoding an instance of the ECPrivateKey structure defined// in Section 3 of [RFC5915] for the Elliptic Curve private key represented by the [[handle]] internal slot@@ -5961,7 +5961,7 @@ WebIDL::ExceptionOr<ExportKeyResult> ECDH::export_key(JS::Realm&, KeyFormat formjwk.kty = "EC"_utf16;// 3. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":- auto& algorithm = key->ec_algorithm();+ auto algorithm = key->ec_algorithm();if (algorithm.named_curve().is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {// 1. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256":if (algorithm.named_curve() == "P-256"_utf16) {@@ -6074,7 +6074,7 @@ WebIDL::ExceptionOr<ExportKeyResult> ECDH::export_key(JS::Realm&, KeyFormat formByteBuffer data;// 2. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":- auto& algorithm = key->ec_algorithm();+ auto algorithm = key->ec_algorithm();if (algorithm.named_curve().is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {// Let data be the octet string that represents the Elliptic Curve public key represented by the [[handle]] internal slot// of key according to the encoding rules specified in Section 2.3.3 of [SEC1] and using the uncompressed form.diff --git a/Libraries/LibWeb/Crypto/CryptoKey.cpp b/Libraries/LibWeb/Crypto/CryptoKey.cppindex bca606496bc..dbcf2abc750 100644--- a/Libraries/LibWeb/Crypto/CryptoKey.cpp+++ b/Libraries/LibWeb/Crypto/CryptoKey.cpp@@ -6,261 +6,195 @@*/#include <AK/Memory.h>-#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 <LibJS/Runtime/Realm.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Bindings/RustSerialization.h>-#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/Crypto/CryptoKey.h>#include <LibWeb/Crypto/CryptoKeySerializationTags.h>#include <LibWeb/WebIDL/AbstractOperations.h>namespace Web::Crypto {-namespace {--struct CryptoKeyCacheEntry {- GC::Weak<CryptoKey> key;- Bindings::WrapperWorldWeakValueCache<JS::Object> usages_objects;+enum class SerializedKeyAlgorithmType : u8 {+ Key,+ Rsa,+ RsaHashed,+ Ec,+ Aes,+ Hmac,+ Kmac,};-static Vector<CryptoKeyCacheEntry>& crypto_key_caches()-{- static thread_local NeverDestroyed<Vector<CryptoKeyCacheEntry>> caches;- return *caches;-}--static void prune_crypto_key_caches()-{- crypto_key_caches().remove_all_matching([](auto const& entry) {- return !entry.key;- });-}--static CryptoKeyCacheEntry& cache_for(CryptoKey& key)-{- auto& caches = crypto_key_caches();- prune_crypto_key_caches();+struct CryptoKeyAlgorithmFields {+ u8 type { 0 };+ FlatPtr name { 0 };+ u32 modulus_length { 0 };+ ReadonlyBytes public_exponent;+ FlatPtr hash { 0 };+ FlatPtr named_curve { 0 };+ u32 length { 0 };+};- for (auto& entry : caches) {- if (entry.key.ptr().ptr() == &key)- return entry;- }+struct CryptoKeyHandleFields {+ 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 };+};- caches.append(CryptoKeyCacheEntry { key, {} });- return caches.last();-}+extern "C" {+CryptoKey* web_rust_crypto_key_create(JSVM*, CryptoKey::InternalKeyData*);+CryptoKey::InternalKeyData const* web_rust_crypto_key_handle(CryptoKey const*);+bool web_rust_crypto_key_extractable(CryptoKey const*);+u8 web_rust_crypto_key_type(CryptoKey const*);+void web_rust_crypto_key_set_extractable(CryptoKey*, bool);+void web_rust_crypto_key_set_type(CryptoKey*, u8);+void web_rust_crypto_key_get_algorithm(CryptoKey const*, CryptoKeyAlgorithmFields*);+void web_rust_crypto_key_set_algorithm(CryptoKey*, CryptoKeyAlgorithmFields const*);+FlatPtr web_rust_crypto_key_algorithm_name(CryptoKey const*);+void web_rust_crypto_key_with_usages(CryptoKey const*, void*, void (*)(void*, ReadonlySpan<KeyUsage>));+void web_rust_crypto_key_set_usages(CryptoKey*, ReadonlySpan<KeyUsage>);++void web_crypto_key_destroy_handle(CryptoKey::InternalKeyData*);+void web_crypto_key_encode_handle(CryptoKey::InternalKeyData const*, void*, void (*)(void*, CryptoKeyHandleFields const*));+JSCompletion web_crypto_key_decode_handle(void* realm, CryptoKeyHandleFields const*, CryptoKey::InternalKeyData** out_handle);}-void clear_crypto_key_caches()+GC::Ref<CryptoKey> CryptoKey::create(InternalKeyData key_data){- crypto_key_caches().clear();+ return *web_rust_crypto_key_create(JS::HostABI::vm_to_abi(JS::VM::the()), new InternalKeyData(move(key_data)));}-namespace {--static JS::ThrowCompletionOr<GC::Ref<JS::Uint8Array>> create_uint8_array_from_bytes(JS::Realm& realm, ReadonlyBytes bytes)+void web_crypto_key_destroy_handle(CryptoKey::InternalKeyData* handle){- auto array = TRY(JS::Uint8Array::create(realm, bytes.size()));- array->viewed_array_buffer()->overwrite(0, bytes.data(), bytes.size());- return array;+ handle->visit(+ [](ByteBuffer& data) { secure_zero(data.data(), data.size()); },+ [](OKPPublicKey& data) { secure_zero(data.bytes.data(), data.bytes.size()); },+ [](OKPPrivateKey& data) { secure_zero(data.bytes.data(), data.bytes.size()); },+ [](auto& data) { secure_zero(reinterpret_cast<u8*>(&data), sizeof(data)); });+ delete handle;}-static JS::ThrowCompletionOr<GC::Ref<JS::Object>> create_key_algorithm_object(JS::Realm& realm, Utf16String const& name)+CryptoKey::InternalKeyData const& CryptoKey::handle() const{- auto object = JS::Object::create(realm, realm.intrinsics().object_prototype());- TRY(object->create_data_property_or_throw("name"_utf16_fly_string, JS::PrimitiveString::create(realm.vm(), name)));- return object;+ return *web_rust_crypto_key_handle(this);}-static JS::ThrowCompletionOr<GC::Ref<JS::Object>> create_algorithm_object(JS::Realm& realm, CryptoKey::InternalAlgorithmData const& algorithm)+void CryptoKey::set_algorithm(InternalAlgorithmData algorithm){- return TRY(algorithm.visit(- [&](CryptoKey::KeyAlgorithmData const& algorithm) -> JS::ThrowCompletionOr<GC::Ref<JS::Object>> {- return create_key_algorithm_object(realm, algorithm.name());+ CryptoKeyAlgorithmFields fields;+ Utf16String hash;+ Utf16String named_curve;+ auto name = algorithm.visit([](auto const& data) { return data.name(); });+ algorithm.visit(+ [&](KeyAlgorithmData const&) {+ fields.type = to_underlying(SerializedKeyAlgorithmType::Key);},- [&](CryptoKey::RsaKeyAlgorithmData const& algorithm) -> JS::ThrowCompletionOr<GC::Ref<JS::Object>> {- auto object = TRY(create_key_algorithm_object(realm, algorithm.name()));- TRY(object->create_data_property_or_throw("modulusLength"_utf16_fly_string, JS::Value(algorithm.modulus_length())));- TRY(object->create_data_property_or_throw("publicExponent"_utf16_fly_string, TRY(create_uint8_array_from_bytes(realm, algorithm.public_exponent().bytes()))));- return object;+ [&](RsaKeyAlgorithmData const& data) {+ fields.type = to_underlying(SerializedKeyAlgorithmType::Rsa);+ fields.modulus_length = data.modulus_length();+ fields.public_exponent = data.public_exponent().bytes();},- [&](CryptoKey::RsaHashedKeyAlgorithmData const& algorithm) -> JS::ThrowCompletionOr<GC::Ref<JS::Object>> {- auto object = TRY(create_key_algorithm_object(realm, algorithm.name()));- TRY(object->create_data_property_or_throw("modulusLength"_utf16_fly_string, JS::Value(algorithm.modulus_length())));- TRY(object->create_data_property_or_throw("publicExponent"_utf16_fly_string, TRY(create_uint8_array_from_bytes(realm, algorithm.public_exponent().bytes()))));- TRY(object->create_data_property_or_throw("hash"_utf16_fly_string, TRY(create_key_algorithm_object(realm, algorithm.hash()))));- return object;+ [&](RsaHashedKeyAlgorithmData const& data) {+ fields.type = to_underlying(SerializedKeyAlgorithmType::RsaHashed);+ fields.modulus_length = data.modulus_length();+ fields.public_exponent = data.public_exponent().bytes();+ hash = data.hash();},- [&](CryptoKey::EcKeyAlgorithmData const& algorithm) -> JS::ThrowCompletionOr<GC::Ref<JS::Object>> {- auto object = TRY(create_key_algorithm_object(realm, algorithm.name()));- TRY(object->create_data_property_or_throw("namedCurve"_utf16_fly_string, JS::PrimitiveString::create(realm.vm(), algorithm.named_curve())));- return object;+ [&](EcKeyAlgorithmData const& data) {+ fields.type = to_underlying(SerializedKeyAlgorithmType::Ec);+ named_curve = data.named_curve();},- [&](CryptoKey::AesKeyAlgorithmData const& algorithm) -> JS::ThrowCompletionOr<GC::Ref<JS::Object>> {- auto object = TRY(create_key_algorithm_object(realm, algorithm.name()));- TRY(object->create_data_property_or_throw("length"_utf16_fly_string, JS::Value(algorithm.length())));- return object;+ [&](AesKeyAlgorithmData const& data) {+ fields.type = to_underlying(SerializedKeyAlgorithmType::Aes);+ fields.length = data.length();},- [&](CryptoKey::HmacKeyAlgorithmData const& algorithm) -> JS::ThrowCompletionOr<GC::Ref<JS::Object>> {- auto object = TRY(create_key_algorithm_object(realm, algorithm.name()));- TRY(object->create_data_property_or_throw("hash"_utf16_fly_string, TRY(create_key_algorithm_object(realm, algorithm.hash()))));- TRY(object->create_data_property_or_throw("length"_utf16_fly_string, JS::Value(algorithm.length())));- return object;+ [&](HmacKeyAlgorithmData const& data) {+ fields.type = to_underlying(SerializedKeyAlgorithmType::Hmac);+ hash = data.hash();+ fields.length = data.length();},- [&](CryptoKey::KmacKeyAlgorithmData const& algorithm) -> JS::ThrowCompletionOr<GC::Ref<JS::Object>> {- auto object = TRY(create_key_algorithm_object(realm, algorithm.name()));- TRY(object->create_data_property_or_throw("length"_utf16_fly_string, JS::Value(algorithm.length())));- return object;- }));-}-+ [&](KmacKeyAlgorithmData const& data) {+ fields.type = to_underlying(SerializedKeyAlgorithmType::Kmac);+ fields.length = data.length();+ });+ fields.name = move(name).into_raw();+ fields.hash = move(hash).into_raw();+ fields.named_curve = move(named_curve).into_raw();+ web_rust_crypto_key_set_algorithm(this, &fields);}-GC_DEFINE_ALLOCATOR(CryptoKey);-enum class SerializedKeyAlgorithmType : u8 {- Key,- Rsa,- RsaHashed,- Ec,- Aes,- Hmac,- Kmac,-};--GC::Ref<CryptoKey> CryptoKey::create(InternalKeyData key_data)+void CryptoKey::set_usages(Vector<KeyUsage> usages){- return GC::Heap::the().allocate<CryptoKey>(move(key_data));+ web_rust_crypto_key_set_usages(this, usages.span());}-CryptoKey::CryptoKey(InternalKeyData key_data)- : m_algorithm(KeyAlgorithmData {})- , m_key_data(move(key_data))+bool CryptoKey::extractable() const{+ return web_rust_crypto_key_extractable(this);}-void CryptoKey::finalize()+KeyType CryptoKey::type() const{- Base::finalize();- m_key_data.visit(- [](ByteBuffer& data) { secure_zero(data.data(), data.size()); },- [](OKPPublicKey& data) { secure_zero(data.bytes.data(), data.bytes.size()); },- [](OKPPrivateKey& data) { secure_zero(data.bytes.data(), data.bytes.size()); },- [](auto& data) { secure_zero(reinterpret_cast<u8*>(&data), sizeof(data)); });+ return static_cast<KeyType>(web_rust_crypto_key_type(this));}-void CryptoKey::visit_edges(Cell::Visitor& visitor)+void CryptoKey::set_extractable(bool extractable){- Base::visit_edges(visitor);- for (auto const& cached_algorithm_object : m_cached_algorithm_objects)- visitor.visit(cached_algorithm_object.object);+ web_rust_crypto_key_set_extractable(this, extractable);}-void CryptoKey::set_algorithm(InternalAlgorithmData algorithm)+void CryptoKey::set_type(KeyType type){- m_algorithm = move(algorithm);- m_algorithm_name = {};- m_cached_algorithm_objects.clear();+ web_rust_crypto_key_set_type(this, to_underlying(type));}-void CryptoKey::set_usages(Vector<KeyUsage> usages)-{- m_key_usages = move(usages);-}--Bindings::KeyType CryptoKey::bindings_type() const+CryptoKey::InternalAlgorithmData CryptoKey::internal_algorithm() const{- switch (m_type) {- case KeyType::Public:- return Bindings::KeyType::Public;- case KeyType::Private:- return Bindings::KeyType::Private;- case KeyType::Secret:- return Bindings::KeyType::Secret;+ CryptoKeyAlgorithmFields fields;+ web_rust_crypto_key_get_algorithm(this, &fields);+ auto name = Utf16String::from_raw(fields.name);+ switch (static_cast<SerializedKeyAlgorithmType>(fields.type)) {+ case SerializedKeyAlgorithmType::Key:+ return KeyAlgorithmData { move(name) };+ case SerializedKeyAlgorithmType::Rsa:+ return RsaKeyAlgorithmData { move(name), fields.modulus_length, MUST(ByteBuffer::copy(fields.public_exponent)) };+ case SerializedKeyAlgorithmType::RsaHashed:+ return RsaHashedKeyAlgorithmData { move(name), fields.modulus_length, MUST(ByteBuffer::copy(fields.public_exponent)), Utf16String::from_raw(fields.hash) };+ case SerializedKeyAlgorithmType::Ec:+ return EcKeyAlgorithmData { move(name), Utf16String::from_raw(fields.named_curve) };+ case SerializedKeyAlgorithmType::Aes:+ return AesKeyAlgorithmData { move(name), static_cast<u16>(fields.length) };+ case SerializedKeyAlgorithmType::Hmac:+ return HmacKeyAlgorithmData { move(name), Utf16String::from_raw(fields.hash), fields.length };+ case SerializedKeyAlgorithmType::Kmac:+ return KmacKeyAlgorithmData { move(name), fields.length };}VERIFY_NOT_REACHED();}-JS::ThrowCompletionOr<JS::Value> CryptoKey::algorithm(JS::Realm& realm)-{- auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);- auto wrapper = Bindings::wrap(wrapper_world, realm, GC::Ref { *this });- m_cached_algorithm_objects.remove_all_matching([](auto const& entry) { return !entry.wrapper; });-- auto cached_object = m_cached_algorithm_objects.find_if([&](auto const& entry) { return entry.wrapper.ptr() == wrapper; });- if (!cached_object.is_end())- return cached_object->object;-- auto object = TRY(create_algorithm_object(realm, m_algorithm));- m_cached_algorithm_objects.append({ wrapper, object });- return object;-}--JS::ThrowCompletionOr<JS::Value> CryptoKey::usages(JS::Realm& realm)+Vector<KeyUsage> CryptoKey::internal_usages() const{- auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);- auto& cache = cache_for(*this);-- if (auto object = cache.usages_objects.get(wrapper_world))- return object;-- auto usages = GC::make_root(JS::Array::create_from<KeyUsage>(realm, m_key_usages.span(), [&](auto& key_usage) -> JS::Value {- return JS::PrimitiveString::create(realm.vm(), Bindings::idl_enum_to_string(key_usage));- }));- MUST(usages->set_integrity_level(JS::Object::IntegrityLevel::Frozen));-- cache.usages_objects.set(wrapper_world, *usages);- return GC::Ref<JS::Object> { *usages };+ Vector<KeyUsage> usages;+ web_rust_crypto_key_with_usages(this, &usages, [](void* state, ReadonlySpan<KeyUsage> values) {+ static_cast<Vector<KeyUsage>*>(state)->append(values.data(), values.size());+ });+ return usages;}-Utf16String const& CryptoKey::algorithm_name() const+Utf16String CryptoKey::algorithm_name() const{- if (m_algorithm_name.is_empty())- m_algorithm_name = m_algorithm.visit([](auto const& algorithm) { return algorithm.name(); });- return m_algorithm_name;-}--// 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 };-};--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);+ return Utf16String::adopt_raw(web_rust_crypto_key_algorithm_name(this));}-// 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(KeyType::Public) == 0);+static_assert(to_underlying(KeyType::Private) == 1);+static_assert(to_underlying(KeyType::Secret) == 2);+static_assert(sizeof(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);@@ -286,55 +220,9 @@ static ByteBuffer export_big_integer(::Crypto::UnsignedBigInteger const& value)return buffer;}-void web_crypto_key_with_fields(JSObject* object, void* state, void (*steps)(void* state, CryptoKeyFields const*))+void web_crypto_key_encode_handle(CryptoKey::InternalKeyData const* handle, void* state, void (*steps)(void*, CryptoKeyHandleFields 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() };-+ CryptoKeyHandleFields fields;// 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; };@@ -342,7 +230,7 @@ void web_crypto_key_with_fields(JSObject* object, void* state, void (*steps)(voiexported.unchecked_append(move(buffer));add(exported.last().bytes());};- key.handle().visit(+ handle->visit([&](ByteBuffer const& buffer) {fields.handle_tag = to_underlying(HandleTag::ByteBuffer);add(buffer.bytes());@@ -415,7 +303,7 @@ void web_crypto_key_with_fields(JSObject* object, void* state, void (*steps)(voisecure_zero(buffer.data(), buffer.size());}-static WebIDL::ExceptionOr<CryptoKey::InternalKeyData> handle_from_fields(JS::VM& vm, CryptoKeyFields const& fields)+static WebIDL::ExceptionOr<CryptoKey::InternalKeyData> handle_from_fields(JS::VM& vm, CryptoKeyHandleFields const& fields){auto buffer = [&](size_t index) {VERIFY(index < fields.handle_buffer_count);@@ -463,47 +351,13 @@ static WebIDL::ExceptionOr<CryptoKey::InternalKeyData> handle_from_fields(JS::VMVERIFY_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();-}--JSCompletion web_crypto_key_create(void* realm, CryptoKeyFields const* fields, JSObject** out_key)+JSCompletion web_crypto_key_decode_handle(void* realm, CryptoKeyHandleFields const* fields, CryptoKey::InternalKeyData** out_handle){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());+ auto handle = handle_from_fields(js_realm.vm(), *fields);+ if (handle.is_exception())+ return Bindings::completion_to_abi(js_realm, handle.release_error());+ *out_handle = new CryptoKey::InternalKeyData(handle.release_value());return Bindings::completion_to_abi(js_realm, JS::js_undefined());}diff --git a/Libraries/LibWeb/Crypto/CryptoKey.h b/Libraries/LibWeb/Crypto/CryptoKey.hindex b07ca17db97..b29edc22fe0 100644--- a/Libraries/LibWeb/Crypto/CryptoKey.h+++ b/Libraries/LibWeb/Crypto/CryptoKey.h@@ -13,7 +13,7 @@#include <LibGC/Ptr.h>#include <LibJS/Forward.h>#include <LibWeb/Bindings/CryptoKey.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Crypto/CryptoBindings.h>#include <LibWebCommon/WebIDL/Types.h>@@ -42,9 +42,8 @@ enum class KeyType {Secret,};-class WEB_API CryptoKey final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(CryptoKey, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(CryptoKey);+class WEB_API CryptoKey final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(CryptoKey, crypto_key)public:using ImportKeyData = Variant<ByteBuffer, JsonWebKey>;@@ -116,44 +115,22 @@ public:[[nodiscard]] static GC::Ref<CryptoKey> create(InternalKeyData);- bool extractable() const { return m_extractable; }- KeyType type() const { return m_type; }- Bindings::KeyType bindings_type() const;- JS::ThrowCompletionOr<JS::Value> algorithm(JS::Realm&);- JS::ThrowCompletionOr<JS::Value> usages(JS::Realm&);+ bool extractable() const;+ KeyType type() const;- InternalAlgorithmData const& internal_algorithm() const { return m_algorithm; }- Vector<KeyUsage> internal_usages() const { return m_key_usages; }- RsaHashedKeyAlgorithmData const& rsa_hashed_algorithm() const { return m_algorithm.get<RsaHashedKeyAlgorithmData>(); }- EcKeyAlgorithmData const& ec_algorithm() const { return m_algorithm.get<EcKeyAlgorithmData>(); }- HmacKeyAlgorithmData const& hmac_algorithm() const { return m_algorithm.get<HmacKeyAlgorithmData>(); }+ InternalAlgorithmData internal_algorithm() const;+ Vector<KeyUsage> internal_usages() const;+ RsaHashedKeyAlgorithmData rsa_hashed_algorithm() const { return internal_algorithm().get<RsaHashedKeyAlgorithmData>(); }+ EcKeyAlgorithmData ec_algorithm() const { return internal_algorithm().get<EcKeyAlgorithmData>(); }+ HmacKeyAlgorithmData hmac_algorithm() const { return internal_algorithm().get<HmacKeyAlgorithmData>(); }- void set_extractable(bool extractable) { m_extractable = extractable; }- void set_type(KeyType type) { m_type = type; }+ void set_extractable(bool);+ void set_type(KeyType);void set_algorithm(InternalAlgorithmData);void set_usages(Vector<KeyUsage>);- InternalKeyData const& handle() const { return m_key_data; }- Utf16String const& algorithm_name() const;--private:- explicit CryptoKey(InternalKeyData);-- virtual void finalize() override;- virtual void visit_edges(Cell::Visitor&) override;-- KeyType m_type;- bool m_extractable { false };- InternalAlgorithmData m_algorithm;-- Vector<KeyUsage> m_key_usages;- InternalKeyData m_key_data; // [[handle]]- mutable Utf16String m_algorithm_name;- struct CachedAlgorithmObject {- GC::Weak<JS::HostObject> wrapper;- GC::Ptr<JS::Object> object;- };- Vector<CachedAlgorithmObject> m_cached_algorithm_objects;+ InternalKeyData const& handle() const;+ Utf16String algorithm_name() const;};struct CryptoKeyPair {@@ -161,7 +138,4 @@ struct CryptoKeyPair {GC::Ref<CryptoKey> private_key;};-// For an agent that goes away, whose weak references the cache would keep beyond the end of its heap.-void clear_crypto_key_caches();-}diff --git a/Libraries/LibWeb/Crypto/CryptoKey.idl b/Libraries/LibWeb/Crypto/CryptoKey.idlindex 3360a0250c4..f423fdd766d 100644--- a/Libraries/LibWeb/Crypto/CryptoKey.idl+++ b/Libraries/LibWeb/Crypto/CryptoKey.idl@@ -4,7 +4,7 @@ enum KeyType { "public", "private", "secret" };enum KeyUsage { "encrypt", "decrypt", "sign", "verify", "deriveKey", "deriveBits", "wrapKey", "unwrapKey", "encapsulateKey", "encapsulateBits", "decapsulateKey", "decapsulateBits" };// https://w3c.github.io/webcrypto/#cryptokey-interface-[SecureContext,Exposed=(Window,Worker),Serializable]+[SecureContext,Exposed=(Window,Worker),Serializable,ImplementedIn=Rust]interface CryptoKey {[ImplementedAs=bindings_type] readonly attribute KeyType type;readonly attribute boolean extractable;diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Libraries/LibWeb/Crypto/SubtleCrypto.cppindex 245e8c0eb3f..def4033d70f 100644--- a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp@@ -1522,7 +1522,8 @@ static ErrorOr<CryptoKey::InternalKeyData> public_key_for_private_key(CryptoKeyif (private_key.public_key().has_value())return *private_key.public_key();- auto const& named_curve = key.ec_algorithm().named_curve();+ auto algorithm = key.ec_algorithm();+ auto const& named_curve = algorithm.named_curve();auto point = TRY([&] -> ErrorOr<::Crypto::Curves::SECPxxxr1Point> {if (named_curve == "P-256"_utf16)return ::Crypto::Curves::SECP256r1 {}.generate_public_key(private_key.d());diff --git a/Meta/Generators/libweb_bindings/rust_structured_serialize.py b/Meta/Generators/libweb_bindings/rust_structured_serialize.pyindex 9e1f4934c49..4485afc62f5 100644--- a/Meta/Generators/libweb_bindings/rust_structured_serialize.py+++ b/Meta/Generators/libweb_bindings/rust_structured_serialize.py@@ -31,7 +31,7 @@ STORAGE_IDENTIFIERS = ()# The serializable interfaces implemented in C++ whose steps run in Rust.-CPP_INTERFACES_WITH_RUST_STEPS = ("CryptoKey", "DOMException", "QuotaExceededError", "RTCEncodedAudioFrame")+CPP_INTERFACES_WITH_RUST_STEPS = ("DOMException", "QuotaExceededError", "RTCEncodedAudioFrame")def write_rust_serializable_dispatch(out: TextIO, interfaces: List[Interface], values: Dict[str, int]) -> None:diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex a69de404302..1b6c45619a9 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -45,8 +45,8 @@ ALLOWED_REALM_MENTIONS = {"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,- 377,+ 7,+ 371,"WebCrypto algorithms still use realms for buffer/key/promise materialization and for normalizing algorithm ""dictionaries, which SubtleCrypto.supports() does in the caller realm",),