Skip to content

Truly independent web browser

LibWeb: Port shared WebCrypto algorithm helpers to Rust

Shannon Boothcedb50ef2f7d
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
index 867a60a7e11..33314779c2c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
@@ -13,14 +13,323 @@ use core::ffi::c_void;
use core::ptr::{NonNull, null, null_mut};
use std::rc::Rc;
-use ak::{Span, Utf16String};
-use libjs_rust::api::{Gc, RawNativeFunctionResult, Realm, Trace, Value};
+use ak::{Span, Utf16String, Utf16StringUnits};
+use libjs_rust::api::{Gc, RawNativeFunctionResult, Realm, Trace, Value, Vm};
-use crate::bindings::WebIdlResult;
-use crate::bindings::interface::{Ref, cell_from_abi, cell_into_abi};
+use crate::bindings::interface::{Ref, cell_from_abi, cell_into_abi, realm_arguments};
+use crate::bindings::{CallContext, WebIdlResult};
use crate::crypto::crypto_bindings::{CryptoKeyPair, JsonWebKey, RawJsonWebKey};
use crate::crypto::crypto_key::{CryptoKey, KeyUsage};
-use crate::crypto::subtle_crypto::{CryptoKeyOrCryptoKeyPair, KeyFormat};
+use crate::crypto::subtle_crypto::{AlgorithmIdentifier, CryptoKeyOrCryptoKeyPair, KeyFormat, normalize_an_algorithm};
+
+// https://w3c.github.io/webcrypto/#algorithm-overview
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct AlgorithmParams {
+ pub(crate) name: Utf16String,
+}
+
+struct HashAlgorithmIdentifier {
+ name: Utf16String,
+}
+
+fn hash_algorithm_identifier_from_value(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ hash_value: Value,
+ hash_string: Option<Utf16String>,
+) -> WebIdlResult<HashAlgorithmIdentifier> {
+ let algorithm = if let Some(hash_string) = hash_string {
+ AlgorithmIdentifier::DOMString(hash_string)
+ } else if hash_value.is_string() {
+ AlgorithmIdentifier::DOMString(hash_value.to_utf16_string(vm)?)
+ } else if hash_value.is_object() {
+ AlgorithmIdentifier::Object(hash_value.to_object(vm)?)
+ } else {
+ unreachable!("the hash is a string or an object")
+ };
+
+ let normalized_algorithm = normalize_an_algorithm(vm, realm, &algorithm, "digest")?;
+ Ok(HashAlgorithmIdentifier {
+ name: normalized_algorithm.parameter.name,
+ })
+}
+
+/// # Safety
+///
+/// The VM and realm are live, the value or string is live, and the output is writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_crypto_hash_algorithm_identifier_from_value(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ value: u64,
+ raw_string: usize,
+ out_name: &mut usize,
+) -> RawNativeFunctionResult {
+ // SAFETY: The caller supplies the live VM, realm and value.
+ let ((vm, realm), value) = unsafe { (realm_arguments(vm, realm), Value::from_raw(value)) };
+ let hash_string = (raw_string != 0).then(|| {
+ // SAFETY: The caller lends a live string and we take our own reference.
+ unsafe {
+ ak::reference_utf16_string(raw_string);
+ Utf16String::from_raw_owned(raw_string)
+ }
+ });
+ let result = hash_algorithm_identifier_from_value(vm, realm, value, hash_string)
+ .map(|identifier| {
+ *out_name = identifier.name.into_raw();
+ Value::UNDEFINED
+ })
+ .map_err(|error| error.throw(&CallContext::new(vm, realm)));
+ RawNativeFunctionResult::from_completion(result)
+}
+
+// https://w3c.github.io/webcrypto/#concept-usage-intersection
+fn usage_intersection(a: &[KeyUsage], b: &[KeyUsage]) -> Vec<KeyUsage> {
+ let mut result = Vec::new();
+ for &usage in a {
+ if b.contains(&usage) && !result.contains(&usage) {
+ result.push(usage);
+ }
+ }
+ result.sort_unstable_by_key(|usage| *usage as u8);
+ result
+}
+
+// https://w3c.github.io/webcrypto/#concept-normalized-usages
+pub(crate) fn normalized_key_usages(usages: &[KeyUsage]) -> Vec<KeyUsage> {
+ usage_intersection(
+ usages,
+ &[
+ KeyUsage::Encrypt,
+ KeyUsage::Decrypt,
+ KeyUsage::Sign,
+ KeyUsage::Verify,
+ KeyUsage::DeriveKey,
+ KeyUsage::DeriveBits,
+ KeyUsage::WrapKey,
+ KeyUsage::UnwrapKey,
+ KeyUsage::EncapsulateKey,
+ KeyUsage::EncapsulateBits,
+ KeyUsage::DecapsulateKey,
+ KeyUsage::DecapsulateBits,
+ ],
+ )
+}
+
+/// # Safety
+///
+/// The spans and the receiver are valid for this call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_crypto_usage_intersection(
+ a: Span<'_, KeyUsage>,
+ b: Span<'_, KeyUsage>,
+ state: *mut c_void,
+ receive: ReceiveUsages,
+) {
+ let result = usage_intersection(a.as_slice(), b.as_slice());
+ // SAFETY: The caller supplies a receiver that takes the span only for the call.
+ unsafe { receive(state, Span::new(&result)) };
+}
+
+/// # Safety
+///
+/// The span and the receiver are valid for this call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_crypto_normalized_key_usages(
+ usages: Span<'_, KeyUsage>,
+ state: *mut c_void,
+ receive: ReceiveUsages,
+) {
+ let result = normalized_key_usages(usages.as_slice());
+ // SAFETY: The caller supplies a receiver that takes the span only for the call.
+ unsafe { receive(state, Span::new(&result)) };
+}
+
+#[derive(PartialEq, Eq)]
+#[repr(u8)]
+pub enum Base64DecodeResult {
+ #[allow(dead_code, reason = "the native base64 decoder constructs this result")]
+ Success,
+ #[allow(dead_code, reason = "the native base64 decoder constructs this result")]
+ OutOfMemory,
+ InvalidBase64,
+ NonAscii,
+}
+
+#[derive(Clone, Copy)]
+#[repr(u8)]
+pub enum Asn1Structure {
+ SubjectPublicKeyInfo,
+ PrivateKeyInfo,
+ #[allow(dead_code, reason = "the native ASN.1 callers supply this structure")]
+ OctetString,
+}
+
+unsafe extern "C" {
+ fn web_crypto_encode_base64url(bytes: Span<'_, u8>, receive: ReceiveBytes, state: *mut c_void) -> i32;
+ fn web_crypto_decode_base64url(raw: usize, out: *mut c_void, error_message: &mut usize) -> Base64DecodeResult;
+ fn web_crypto_decode_asn1_structure(
+ data: Span<'_, u8>,
+ structure: Asn1Structure,
+ out: *mut c_void,
+ all_consumed: &mut bool,
+ ) -> usize;
+}
+
+unsafe extern "C" fn receive_base64url_string(state: *mut c_void, bytes: Span<'_, u8>) {
+ // SAFETY: The state is the caller's slot, and the service lends the bytes.
+ unsafe { *state.cast::<Option<Utf16String>>() = Some(Utf16String::from_ascii(bytes.as_slice())) };
+}
+
+// https://www.rfc-editor.org/rfc/rfc7518#section-2
+fn base64_url_bytes_encode(bytes: &[u8]) -> Result<Utf16String, i32> {
+ let mut encoded = None;
+ // SAFETY: The input and the output slot live for the call.
+ let error = unsafe {
+ web_crypto_encode_base64url(
+ Span::new(bytes),
+ receive_base64url_string,
+ core::ptr::from_mut(&mut encoded).cast(),
+ )
+ };
+ if error != 0 {
+ return Err(error);
+ }
+ Ok(encoded.expect("LibWeb returns the base64url string"))
+}
+
+/// # Safety
+///
+/// The span is live and the output is writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_crypto_base64_url_bytes_encode(bytes: Span<'_, u8>, out: &mut usize) -> i32 {
+ match base64_url_bytes_encode(bytes.as_slice()) {
+ Ok(encoded) => {
+ *out = encoded.into_raw();
+ 0
+ }
+ Err(error) => error,
+ }
+}
+
+unsafe fn base64_url_bytes_decode(
+ base64_url_string: &Utf16String,
+ out: *mut c_void,
+ error_message: &mut usize,
+) -> Base64DecodeResult {
+ let is_ascii = match base64_url_string.as_units() {
+ Utf16StringUnits::Ascii(_) => true,
+ Utf16StringUnits::Latin1(units) => units.is_ascii(),
+ Utf16StringUnits::Utf16(units) => units.iter().all(|&unit| unit <= 0x7f),
+ };
+ if !is_ascii {
+ return Base64DecodeResult::NonAscii;
+ }
+
+ // SAFETY: The caller passes a live native ByteBuffer as the output.
+ let result = unsafe { web_crypto_decode_base64url(base64_url_string.raw_identity(), out, error_message) };
+ if result == Base64DecodeResult::InvalidBase64 {
+ // SAFETY: The decoder hands over an owned diagnostic string.
+ let detail = unsafe { Utf16String::from_raw_owned(*error_message) };
+ *error_message = libjs_rust::api::utf16_formatted("base64 decode: {}", &[&detail]).into_raw();
+ }
+ result
+}
+
+/// # Safety
+///
+/// The string is live and the output points to a live ByteBuffer.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_crypto_base64_url_bytes_decode(
+ raw: usize,
+ out: *mut c_void,
+ error_message: &mut usize,
+) -> Base64DecodeResult {
+ // SAFETY: The caller lends a live string and we take our own reference.
+ let base64_url_string = unsafe {
+ ak::reference_utf16_string(raw);
+ Utf16String::from_raw_owned(raw)
+ };
+ // SAFETY: The caller supplies a live ByteBuffer.
+ unsafe { base64_url_bytes_decode(&base64_url_string, out, error_message) }
+}
+
+// https://w3c.github.io/webcrypto/#concept-parse-an-asn1-structure
+unsafe fn parse_an_asn1_structure(
+ data: Span<'_, u8>,
+ structure: Asn1Structure,
+ exact_data: bool,
+ out: *mut c_void,
+) -> Result<(), Utf16String> {
+ // 1. Let data be a sequence of bytes to be parsed.
+ // 2. Let structure be the ASN.1 structure to be parsed.
+ // 3. Let exactData be an optional boolean value. If it is not supplied, let it be initialized to true.
+
+ // 4. Parse data according to the Distinguished Encoding Rules of [X690], using structure as the ASN.1 structure to be decoded.
+ let mut all_consumed = false;
+ // SAFETY: The caller passes a live native value of the specified structure.
+ let error = unsafe { web_crypto_decode_asn1_structure(data, structure, out, &mut all_consumed) };
+ if error != 0 {
+ // SAFETY: The decoder hands over an owned diagnostic string.
+ let detail = unsafe { Utf16String::from_raw_owned(error) };
+ let message = match structure {
+ Asn1Structure::SubjectPublicKeyInfo => "Error parsing subjectPublicKeyInfo: {}",
+ Asn1Structure::PrivateKeyInfo => "Error parsing privateKeyInfo: {}",
+ Asn1Structure::OctetString => "Read of kind OctetString failed: {}",
+ };
+ return Err(libjs_rust::api::utf16_formatted(message, &[&detail]));
+ }
+
+ // 5. If exactData was specified, and all of the bytes of data were not consumed during the parsing phase, then throw a DataError.
+ if exact_data && !all_consumed {
+ return Err(Utf16String::from_utf8(
+ "Not all bytes were consumed during the parsing phase",
+ ));
+ }
+
+ // 6. Return the parsed ASN.1 structure.
+ Ok(())
+}
+
+// https://w3c.github.io/webcrypto/#concept-parse-a-spki
+unsafe fn parse_a_subject_public_key_info(data: Span<'_, u8>, out: *mut c_void) -> Result<(), Utf16String> {
+ // When this specification says to parse a subjectPublicKeyInfo, the user agent must parse an ASN.1 structure,
+ // with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of subjectPublicKeyInfo,
+ // as specified in [RFC5280], and exactData set to true.
+ // SAFETY: The caller passes a live native SubjectPublicKey.
+ unsafe { parse_an_asn1_structure(data, Asn1Structure::SubjectPublicKeyInfo, true, out) }
+}
+
+// https://w3c.github.io/webcrypto/#concept-parse-a-privateKeyInfo
+unsafe fn parse_a_private_key_info(data: Span<'_, u8>, out: *mut c_void) -> Result<(), Utf16String> {
+ // When this specification says to parse a PrivateKeyInfo, the user agent must parse an ASN.1 structure
+ // with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of PrivateKeyInfo,
+ // as specified in [RFC5208], and exactData set to true.
+ // SAFETY: The caller passes a live native PrivateKey.
+ unsafe { parse_an_asn1_structure(data, Asn1Structure::PrivateKeyInfo, true, out) }
+}
+
+/// # Safety
+///
+/// The span is live and the output points to a live native value of the specified structure.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_crypto_parse_an_asn1_structure(
+ data: Span<'_, u8>,
+ structure: Asn1Structure,
+ exact_data: bool,
+ out: *mut c_void,
+) -> usize {
+ // SAFETY: The caller supplies a live value of the specified structure.
+ let result = unsafe {
+ match structure {
+ Asn1Structure::SubjectPublicKeyInfo => parse_a_subject_public_key_info(data, out),
+ Asn1Structure::PrivateKeyInfo => parse_a_private_key_info(data, out),
+ Asn1Structure::OctetString => parse_an_asn1_structure(data, structure, exact_data, out),
+ }
+ };
+ result.err().map_or(0, Utf16String::into_raw)
+}
#[derive(Clone, Copy)]
#[repr(u8)]
@@ -157,7 +466,6 @@ unsafe extern "C" {
) -> RawNativeFunctionResult;
fn web_crypto_algorithm_destroy(algorithm: *mut c_void);
fn web_crypto_algorithm_public_key_usages(algorithm: *mut c_void, state: *mut c_void, receive: ReceiveUsages);
- fn web_crypto_normalized_key_usages(usages: Span<'_, KeyUsage>, state: *mut c_void, receive: ReceiveUsages);
fn web_crypto_public_key_for_private_key(key: *mut c_void) -> *mut c_void;
fn web_crypto_algorithm_encrypt(
realm: *mut c_void,
@@ -344,10 +652,6 @@ impl CppAlgorithm {
Ok(Self(NonNull::new(out).expect("LibWeb returns an algorithm")))
}
- pub(crate) fn into_raw(self) -> *mut c_void {
- core::mem::ManuallyDrop::new(self).0.as_ptr()
- }
-
pub(crate) fn public_key_usages(&self) -> Option<Vec<KeyUsage>> {
let mut usages = None;
// SAFETY: This object owns the algorithm and the state is writable for the call.
@@ -731,19 +1035,6 @@ unsafe extern "C" fn receive_export_jwk(state: *mut c_void, key: &RawJsonWebKey<
};
}
-pub(crate) fn normalized_key_usages(usages: &[KeyUsage]) -> Vec<KeyUsage> {
- let mut normalized: Option<Vec<KeyUsage>> = None;
- // SAFETY: The usages and the output slot are lent for the call.
- unsafe {
- web_crypto_normalized_key_usages(
- Span::new(usages),
- core::ptr::from_mut(&mut normalized).cast(),
- receive_usages,
- );
- };
- normalized.expect("LibWeb returns the normalized usages")
-}
-
pub(crate) fn public_key_for_private_key(key: Ref<CryptoKey>) -> Option<Ref<CryptoKey>> {
// SAFETY: The key is live.
let public_key = unsafe { web_crypto_public_key_for_private_key(cell_into_abi(key)) };
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs
index 763c86db7c7..361592aa980 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs
@@ -7,16 +7,14 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use core::ffi::c_void;
-use core::ptr::NonNull;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::LazyLock;
-use ak::{Span, Utf16String};
+use ak::Utf16String;
use libjs_rust::api::{
- ArrayBuffer, ArrayBufferShared, ErrorKind, ErrorType, Gc, Must, Object, PrimitiveString, PropertyKey,
- RawNativeFunctionResult, Realm, Trace, Value, Vm,
+ ArrayBuffer, ArrayBufferShared, ErrorKind, ErrorType, Gc, Must, Object, PrimitiveString, PropertyKey, Realm, Trace,
+ Value, Vm,
};
use crate::bindings::conversions::BufferSource;
@@ -32,8 +30,8 @@ use crate::bindings::promise::{
};
use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};
use crate::crypto::crypto_algorithms::{
- AlgorithmId, Bytes, CppAlgorithm, EncapsulatedKeyData, ExportKeyResult, ImportKeyData, ParameterId,
- normalized_key_usages, public_key_for_private_key,
+ AlgorithmId, AlgorithmParams, Bytes, CppAlgorithm, EncapsulatedKeyData, ExportKeyResult, ImportKeyData,
+ ParameterId, normalized_key_usages, public_key_for_private_key,
};
#[allow(
unused_imports,
@@ -96,7 +94,7 @@ type SupportedAlgorithmsMap = HashMap<&'static str, RegisteredAlgorithms>;
#[derive(Clone, Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct NormalizedAlgorithmAndParameter {
- pub(crate) name: Utf16String,
+ pub(crate) parameter: AlgorithmParams,
#[gc(untraced)]
pub(crate) methods: Rc<CppAlgorithm>,
}
@@ -271,7 +269,7 @@ pub(crate) fn normalize_an_algorithm(
// 9. Set the name attribute of normalizedAlgorithm to algName.
let normalized_algorithm = NormalizedAlgorithmAndParameter {
methods,
- name: algorithm_name,
+ parameter: AlgorithmParams { name: algorithm_name },
};
// 13. Return normalizedAlgorithm.
@@ -340,7 +338,7 @@ impl SubtleCrypto {
};
// 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError.
- if normalized_algorithm.name != key.algorithm_name() {
+ if normalized_algorithm.parameter.name != key.algorithm_name() {
throw_in_this_context(dom_error("InvalidAccessError", b"Algorithm mismatch"));
return;
}
@@ -435,7 +433,7 @@ impl SubtleCrypto {
};
// 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError.
- if normalized_algorithm.name != key.algorithm_name() {
+ if normalized_algorithm.parameter.name != key.algorithm_name() {
throw_in_this_context(dom_error("InvalidAccessError", b"Algorithm mismatch"));
return;
}
@@ -923,7 +921,7 @@ impl SubtleCrypto {
// 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]]
// internal slot of key then throw an InvalidAccessError.
- if normalized_algorithm.name != key.algorithm_name() {
+ if normalized_algorithm.parameter.name != key.algorithm_name() {
throw_in_this_context(dom_error("InvalidAccessError", b"Algorithm mismatch"));
return;
}
@@ -1029,7 +1027,7 @@ impl SubtleCrypto {
// 10. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]]
// internal slot of key then throw an InvalidAccessError.
- if normalized_algorithm.name != key.algorithm_name() {
+ if normalized_algorithm.parameter.name != key.algorithm_name() {
throw_in_this_context(dom_error("InvalidAccessError", b"Algorithm mismatch"));
return;
}
@@ -1099,7 +1097,7 @@ impl SubtleCrypto {
// 6. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
// 7. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of baseKey then throw an InvalidAccessError.
- if normalized_algorithm.name != base_key.algorithm_name() {
+ if normalized_algorithm.parameter.name != base_key.algorithm_name() {
reject_promise(
vm,
promise,
@@ -1209,7 +1207,7 @@ impl SubtleCrypto {
// 10. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
// 11. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of baseKey then throw an InvalidAccessError.
- if normalized_algorithm.name != base_key.algorithm_name() {
+ if normalized_algorithm.parameter.name != base_key.algorithm_name() {
reject_promise(
vm,
promise,
@@ -1352,7 +1350,7 @@ impl SubtleCrypto {
// 9. If the name member of normalizedAlgorithm is not equal to the name attribute
// of the [[algorithm]] internal slot of wrappingKey then throw an InvalidAccessError.
- if normalized_algorithm.name != wrapping_key.algorithm_name() {
+ if normalized_algorithm.parameter.name != wrapping_key.algorithm_name() {
reject_promise(
vm,
promise,
@@ -1563,7 +1561,7 @@ impl SubtleCrypto {
// 12. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot
// of unwrappingKey then throw an InvalidAccessError.
- if normalized_algorithm.name != unwrapping_key.algorithm_name() {
+ if normalized_algorithm.parameter.name != unwrapping_key.algorithm_name() {
reject_promise(
vm,
promise,
@@ -1760,7 +1758,7 @@ impl SubtleCrypto {
// 10. If the name member of normalizedEncapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]
// internal slot of encapsulationKey then throw an InvalidAccessError.
- if normalized_encapsulation_algorithm.name != encapsulation_key.algorithm_name() {
+ if normalized_encapsulation_algorithm.parameter.name != encapsulation_key.algorithm_name() {
throw_in_this_context(dom_error("InvalidAccessError", b"Invalid encapsulation key algorithm"));
return;
}
@@ -1897,7 +1895,7 @@ impl SubtleCrypto {
// 8. If the name member of normalizedEncapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]
// internal slot of encapsulationKey then throw an InvalidAccessError.
- if normalized_encapsulation_algorithm.name != encapsulation_key.algorithm_name() {
+ if normalized_encapsulation_algorithm.parameter.name != encapsulation_key.algorithm_name() {
throw_in_this_context(dom_error("InvalidAccessError", b"Invalid encapsulation key algorithm"));
return;
}
@@ -2041,7 +2039,7 @@ impl SubtleCrypto {
// 11. If the name member of normalizedDecapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]
// internal slot of decapsulationKey then throw an InvalidAccessError.
- if normalized_decapsulation_algorithm.name != decapsulation_key.algorithm_name() {
+ if normalized_decapsulation_algorithm.parameter.name != decapsulation_key.algorithm_name() {
throw_in_this_context(dom_error("InvalidAccessError", b"Invalid algorithm name"));
return;
}
@@ -2174,7 +2172,7 @@ impl SubtleCrypto {
// 9. If the name member of normalizedDecapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]
// internal slot of decapsulationKey then throw an InvalidAccessError.
- if normalized_decapsulation_algorithm.name != decapsulation_key.algorithm_name() {
+ if normalized_decapsulation_algorithm.parameter.name != decapsulation_key.algorithm_name() {
throw_in_this_context(dom_error("InvalidAccessError", b"Invalid algorithm name"));
return;
}
@@ -3605,39 +3603,3 @@ fn create_algorithm_dictionary(vm: &Vm, realm: Gc<Realm>, name: &Utf16String) ->
)?;
Ok(dictionary)
}
-
-/// # Safety
-///
-/// The caller supplies a live VM and realm, a live object or string, and writable output storage.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_crypto_normalize_an_algorithm(
- vm: *const c_void,
- realm: *mut c_void,
- object: *mut c_void,
- name: usize,
- operation: Span<'_, u8>,
- out: &mut *mut c_void,
-) -> RawNativeFunctionResult {
- // SAFETY: The VM, realm, and algorithm value are live.
- let (vm, realm, algorithm) = unsafe {
- let vm = &*vm.cast::<Vm>();
- let realm = Gc::from_non_null(NonNull::new(realm.cast()).expect("the caller passes the realm"));
- let algorithm = if let Some(object) = NonNull::new(object.cast::<Object>()) {
- AlgorithmIdentifier::Object(Gc::from_non_null(object))
- } else {
- ak::reference_utf16_string(name);
- AlgorithmIdentifier::DOMString(Utf16String::from_raw_owned(name))
- };
- (vm, realm, algorithm)
- };
- let operation = std::str::from_utf8(operation.as_slice()).expect("an operation name is UTF-8");
- let result = normalize_an_algorithm(vm, realm, &algorithm, operation)
- .map(|normalized_algorithm| {
- *out = Rc::into_inner(normalized_algorithm.methods)
- .expect("a new algorithm has one owner")
- .into_raw();
- Value::UNDEFINED
- })
- .map_err(|exception| exception.throw(&CallContext::new(vm, realm)));
- RawNativeFunctionResult::from_completion(result)
-}
diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
index f804cb88497..d384ad5df35 100644
--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
@@ -11,7 +11,6 @@
#include <AK/Base64.h>
#include <AK/HashTable.h>
#include <AK/Memory.h>
-#include <AK/QuickSort.h>
#include <AK/Random.h>
#include <LibCrypto/ASN1/ASN1.h>
#include <LibCrypto/ASN1/Constants.h>
@@ -33,6 +32,7 @@
#include <LibCrypto/PK/MLDSA.h>
#include <LibCrypto/PK/MLKEM.h>
#include <LibCrypto/PK/RSA.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/ArrayBuffer.h>
#include <LibJS/Runtime/DataView.h>
@@ -40,33 +40,45 @@
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Crypto/CryptoAlgorithms.h>
-#include <LibWeb/Crypto/SubtleCrypto.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/ExceptionOrUtils.h>
namespace Web::Crypto {
-static JS::ThrowCompletionOr<HashAlgorithmIdentifier> hash_algorithm_identifier_from_value(JS::Realm& realm, JS::Value const hash_value)
-{
- auto& vm = realm.vm();
+extern "C" {
+JSCompletion web_rust_crypto_hash_algorithm_identifier_from_value(JSVM*, JS::Realm*, JSValue, FlatPtr, FlatPtr*);
+using ReceiveKeyUsages = void (*)(void*, ReadonlySpan<KeyUsage>);
+void web_rust_crypto_usage_intersection(ReadonlySpan<KeyUsage>, ReadonlySpan<KeyUsage>, void*, ReceiveKeyUsages);
+void web_rust_crypto_normalized_key_usages(ReadonlySpan<KeyUsage>, void*, ReceiveKeyUsages);
- auto maybe_normalized_algorithm = [&]() -> WebIDL::ExceptionOr<NormalizedAlgorithmAndParameter> {
- if (hash_value.is_string()) {
- auto const hash_string = TRY(hash_value.to_utf16_string(vm));
- return normalize_an_algorithm(realm, hash_string, "digest"_string);
- }
- if (hash_value.is_object()) {
- auto const hash_object = TRY(hash_value.to_object(vm));
- return normalize_an_algorithm(realm, hash_object, "digest"_string);
- }
- VERIFY_NOT_REACHED();
- }();
+using ReceiveEncodedBytes = void (*)(void*, ReadonlyBytes);
+int web_crypto_encode_base64url(ReadonlyBytes, ReceiveEncodedBytes, void*);
+int web_rust_crypto_base64_url_bytes_encode(ReadonlyBytes, FlatPtr*);
- if (maybe_normalized_algorithm.is_error()) {
- return WebIDL::exception_to_throw_completion(vm, realm, maybe_normalized_algorithm.exception());
- }
+enum class Base64DecodeResult : u8 {
+ Success,
+ OutOfMemory,
+ InvalidBase64,
+ NonAscii,
+};
+Base64DecodeResult web_crypto_decode_base64url(FlatPtr, ByteBuffer*, FlatPtr*);
+Base64DecodeResult web_rust_crypto_base64_url_bytes_decode(FlatPtr, ByteBuffer*, FlatPtr*);
- return HashAlgorithmIdentifier { maybe_normalized_algorithm.value().parameter->name };
+enum class Asn1Structure : u8 {
+ SubjectPublicKeyInfo,
+ PrivateKeyInfo,
+ OctetString,
+};
+FlatPtr web_crypto_decode_asn1_structure(ReadonlyBytes, Asn1Structure, void*, bool*);
+FlatPtr web_rust_crypto_parse_an_asn1_structure(ReadonlyBytes, Asn1Structure, bool, void*);
+}
+
+static JS::ThrowCompletionOr<HashAlgorithmIdentifier> hash_algorithm_identifier_from_value(JS::Realm& realm, JS::Value hash_value, FlatPtr hash_string = 0)
+{
+ FlatPtr name = 0;
+ TRY(JS::HostABI::completion_from_abi<void>(web_rust_crypto_hash_algorithm_identifier_from_value(
+ JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::value_to_abi(hash_value), hash_string, &name)));
+ return HashAlgorithmIdentifier { Utf16String::adopt_raw(name) };
}
static WebIDL::ExceptionOr<::Crypto::Hash::HashKind> sha_hash_kind(Utf16String const& hash_algorithm)
@@ -89,22 +101,23 @@ static WebIDL::ExceptionOr<ByteBuffer> export_public_exponent(JS::VM& vm, ::Cryp
return TRY_OR_THROW_OOM(vm, ByteBuffer::copy(exported_data));
}
-// https://w3c.github.io/webcrypto/#concept-usage-intersection
+static void receive_key_usages(void* state, ReadonlySpan<KeyUsage> usages)
+{
+ *static_cast<Vector<KeyUsage>*>(state) = Vector<KeyUsage>(usages);
+}
+
static Vector<KeyUsage> usage_intersection(ReadonlySpan<KeyUsage> a, ReadonlySpan<KeyUsage> b)
{
Vector<KeyUsage> result;
- for (auto const& usage : a) {
- if (b.contains_slow(usage) && !result.contains_slow(usage))
- result.append(usage);
- }
- quick_sort(result);
+ web_rust_crypto_usage_intersection(a, b, &result, receive_key_usages);
return result;
}
-// https://w3c.github.io/webcrypto/#concept-normalized-usages
Vector<KeyUsage> normalized_key_usages(ReadonlySpan<KeyUsage> usages)
{
- return usage_intersection(usages, { { KeyUsage::Encrypt, KeyUsage::Decrypt, KeyUsage::Sign, KeyUsage::Verify, KeyUsage::DeriveKey, KeyUsage::DeriveBits, KeyUsage::WrapKey, KeyUsage::UnwrapKey, KeyUsage::EncapsulateKey, KeyUsage::EncapsulateBits, KeyUsage::DecapsulateKey, KeyUsage::DecapsulateBits } });
+ Vector<KeyUsage> result;
+ web_rust_crypto_normalized_key_usages(usages, &result, receive_key_usages);
+ return result;
}
// https://w3c.github.io/webcrypto/#dfn-validate-rsa-key-generation-parameters
@@ -204,11 +217,21 @@ static JS::ThrowCompletionOr<::Crypto::UnsignedBigInteger> big_integer_from_api_
return ::Crypto::UnsignedBigInteger(0);
}
-// https://www.rfc-editor.org/rfc/rfc7518#section-2
+int web_crypto_encode_base64url(ReadonlyBytes bytes, ReceiveEncodedBytes receive, void* state)
+{
+ auto encoded = encode_base64url(bytes, AK::OmitPadding::Yes);
+ if (encoded.is_error())
+ return encoded.error().code();
+ receive(state, encoded.value().bytes_as_string_view().bytes());
+ return 0;
+}
+
static ErrorOr<Utf16String> base64_url_bytes_encode(ReadonlyBytes bytes)
{
- auto encoded = TRY(encode_base64url(bytes, AK::OmitPadding::Yes));
- return Utf16String::from_ascii_without_validation(encoded.bytes_as_string_view().bytes());
+ FlatPtr encoded = 0;
+ if (auto error = web_rust_crypto_base64_url_bytes_encode(bytes, &encoded); error != 0)
+ return Error::from_errno(error);
+ return Utf16String::adopt_raw(encoded);
}
ErrorOr<Utf16String> base64_url_uint_encode(::Crypto::UnsignedBigInteger integer)
@@ -225,20 +248,36 @@ ErrorOr<Utf16String> base64_url_uint_encode(::Crypto::UnsignedBigInteger integer
return TRY(base64_url_bytes_encode(result));
}
-WebIDL::ExceptionOr<ByteBuffer> base64_url_bytes_decode(JS::Realm& realm, Utf16String const& base64_url_string)
+Base64DecodeResult web_crypto_decode_base64url(FlatPtr raw, ByteBuffer* bytes, FlatPtr* error_message)
{
- auto& vm = realm.vm();
-
- if (!base64_url_string.is_ascii())
- return WebIDL::DataError::create(realm, "base64 decode: invalid base64url"_utf16);
-
+ auto base64_url_string = Utf16String::from_raw(raw);
auto base64_bytes_or_error = decode_base64url(base64_url_string.to_byte_string(), AK::LastChunkHandling::Loose);
if (base64_bytes_or_error.is_error()) {
if (base64_bytes_or_error.error().code() == ENOMEM)
- return vm.throw_completion<JS::InternalError>(vm.error_message(::JS::VM::ErrorMessage::OutOfMemory));
- return WebIDL::DataError::create(Utf16String::formatted("base64 decode: {}", base64_bytes_or_error.release_error()));
+ return Base64DecodeResult::OutOfMemory;
+ *error_message = Utf16String::formatted("{}", base64_bytes_or_error.release_error()).into_raw();
+ return Base64DecodeResult::InvalidBase64;
}
- return base64_bytes_or_error.release_value();
+ *bytes = base64_bytes_or_error.release_value();
+ return Base64DecodeResult::Success;
+}
+
+WebIDL::ExceptionOr<ByteBuffer> base64_url_bytes_decode(JS::Realm& realm, Utf16String const& base64_url_string)
+{
+ auto& vm = realm.vm();
+ ByteBuffer bytes;
+ FlatPtr error_message = 0;
+ switch (web_rust_crypto_base64_url_bytes_decode(base64_url_string.raw_identity(), &bytes, &error_message)) {
+ case Base64DecodeResult::Success:
+ return bytes;
+ case Base64DecodeResult::NonAscii:
+ return WebIDL::DataError::create(realm, "base64 decode: invalid base64url"_utf16);
+ case Base64DecodeResult::OutOfMemory:
+ return vm.throw_completion<JS::InternalError>(vm.error_message(::JS::VM::ErrorMessage::OutOfMemory));
+ case Base64DecodeResult::InvalidBase64:
+ return WebIDL::DataError::create(Utf16String::adopt_raw(error_message));
+ }
+ VERIFY_NOT_REACHED();
}
WebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> base64_url_uint_decode(JS::Realm& realm, Utf16String const& base64_url_string)
@@ -247,60 +286,64 @@ WebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> base64_url_uint_decode(JS::Rea
return ::Crypto::UnsignedBigInteger::import_data(base64_bytes_be);
}
-// https://w3c.github.io/webcrypto/#concept-parse-an-asn1-structure
-template<typename Structure>
-static WebIDL::ExceptionOr<Structure> parse_an_ASN1_structure(JS::Realm&, ReadonlyBytes data, bool exact_data = true)
+FlatPtr web_crypto_decode_asn1_structure(ReadonlyBytes data, Asn1Structure structure, void* out, bool* all_consumed)
{
- // 1. Let data be a sequence of bytes to be parsed.
- // 2. Let structure be the ASN.1 structure to be parsed.
- // 3. Let exactData be an optional boolean value. If it is not supplied, let it be initialized to true.
-
- // 4. Parse data according to the Distinguished Encoding Rules of [X690], using structure as the ASN.1 structure to be decoded.
::Crypto::ASN1::Decoder decoder(data);
- Structure structure;
- if constexpr (IsSame<Structure, ::Crypto::Certificate::SubjectPublicKey>) {
- auto maybe_subject_public_key = ::Crypto::Certificate::parse_subject_public_key_info(decoder);
- if (maybe_subject_public_key.is_error())
- return WebIDL::DataError::create(Utf16String::formatted("Error parsing subjectPublicKeyInfo: {}", maybe_subject_public_key.release_error()));
- structure = maybe_subject_public_key.release_value();
- } else if constexpr (IsSame<Structure, ::Crypto::Certificate::PrivateKey>) {
- auto maybe_private_key = ::Crypto::Certificate::parse_private_key_info(decoder);
- if (maybe_private_key.is_error())
- return WebIDL::DataError::create(Utf16String::formatted("Error parsing privateKeyInfo: {}", maybe_private_key.release_error()));
- structure = maybe_private_key.release_value();
- } else if constexpr (IsSame<Structure, StringView>) {
- auto read_result = decoder.read<StringView>(::Crypto::ASN1::Class::Universal, ::Crypto::ASN1::Kind::OctetString);
- if (read_result.is_error())
- return WebIDL::DataError::create(Utf16String::formatted("Read of kind OctetString failed: {}", read_result.error()));
- structure = read_result.release_value();
- } else {
- static_assert(DependentFalse<Structure>, "Don't know how to parse ASN.1 structure type");
+ switch (structure) {
+ case Asn1Structure::SubjectPublicKeyInfo: {
+ auto subject_public_key = ::Crypto::Certificate::parse_subject_public_key_info(decoder);
+ if (subject_public_key.is_error())
+ return Utf16String::formatted("{}", subject_public_key.release_error()).into_raw();
+ *static_cast<::Crypto::Certificate::SubjectPublicKey*>(out) = subject_public_key.release_value();
+ break;
}
+ case Asn1Structure::PrivateKeyInfo: {
+ auto private_key = ::Crypto::Certificate::parse_private_key_info(decoder);
+ if (private_key.is_error())
+ return Utf16String::formatted("{}", private_key.release_error()).into_raw();
+ *static_cast<::Crypto::Certificate::PrivateKey*>(out) = private_key.release_value();
+ break;
+ }
+ case Asn1Structure::OctetString: {
+ auto octet_string = decoder.read<StringView>(::Crypto::ASN1::Class::Universal, ::Crypto::ASN1::Kind::OctetString);
+ if (octet_string.is_error())
+ return Utf16String::formatted("{}", octet_string.error()).into_raw();
+ *static_cast<StringView*>(out) = octet_string.release_value();
+ break;
+ }
+ }
+ *all_consumed = decoder.eof();
+ return 0;
+}
- // 5. If exactData was specified, and all of the bytes of data were not consumed during the parsing phase, then throw a DataError.
- if (exact_data && !decoder.eof())
- return WebIDL::DataError::create("Not all bytes were consumed during the parsing phase"_utf16);
-
- // 6. Return the parsed ASN.1 structure.
+template<typename Structure>
+static WebIDL::ExceptionOr<Structure> parse_an_ASN1_structure(JS::Realm&, ReadonlyBytes data, bool exact_data = true)
+{
+ constexpr auto structure_kind = [] {
+ if constexpr (IsSame<Structure, ::Crypto::Certificate::SubjectPublicKey>)
+ return Asn1Structure::SubjectPublicKeyInfo;
+ else if constexpr (IsSame<Structure, ::Crypto::Certificate::PrivateKey>)
+ return Asn1Structure::PrivateKeyInfo;
+ else if constexpr (IsSame<Structure, StringView>)
+ return Asn1Structure::OctetString;
+ else
+ static_assert(DependentFalse<Structure>, "Don't know how to parse ASN.1 structure type");
+ }();
+ Structure structure;
+ auto error = web_rust_crypto_parse_an_asn1_structure(data, structure_kind, exact_data, &structure);
+ if (error != 0)
+ return WebIDL::DataError::create(Utf16String::adopt_raw(error));
return structure;
}
-// https://w3c.github.io/webcrypto/#concept-parse-a-spki
static WebIDL::ExceptionOr<::Crypto::Certificate::SubjectPublicKey> parse_a_subject_public_key_info(JS::Realm& realm, ReadonlyBytes bytes)
{
- // When this specification says to parse a subjectPublicKeyInfo, the user agent must parse an ASN.1 structure,
- // with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of subjectPublicKeyInfo,
- // as specified in [RFC5280], and exactData set to true.
- return parse_an_ASN1_structure<::Crypto::Certificate::SubjectPublicKey>(realm, bytes, true);
+ return parse_an_ASN1_structure<::Crypto::Certificate::SubjectPublicKey>(realm, bytes);
}
-// https://w3c.github.io/webcrypto/#concept-parse-a-privateKeyInfo
static WebIDL::ExceptionOr<::Crypto::Certificate::PrivateKey> parse_a_private_key_info(JS::Realm& realm, ReadonlyBytes bytes)
{
- // When this specification says to parse a PrivateKeyInfo, the user agent must parse an ASN.1 structure
- // with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of PrivateKeyInfo,
- // as specified in [RFC5208], and exactData set to true.
- return parse_an_ASN1_structure<::Crypto::Certificate::PrivateKey>(realm, bytes, true);
+ return parse_an_ASN1_structure<::Crypto::Certificate::PrivateKey>(realm, bytes);
}
static WebIDL::ExceptionOr<::Crypto::PK::RSAPrivateKey> parse_jwk_rsa_private_key(JS::Realm& realm, JsonWebKey const& jwk)
@@ -420,11 +463,6 @@ static WebIDL::ExceptionOr<void> validate_kmac_key_length(WebIDL::UnsignedLong l
AlgorithmParams::~AlgorithmParams() = default;
-JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> AlgorithmParams::from_value(JS::Realm&, JS::Value)
-{
- return adopt_own(*new AlgorithmParams {});
-}
-
AesCbcParams::~AesCbcParams() = default;
JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> AesCbcParams::from_value(JS::Realm& realm, JS::Value value)
@@ -1236,10 +1274,10 @@ WebIDL::ExceptionOr<GC::Ref<CryptoKey>> RSAOAEP::import_key(JS::Realm& realm, We
// 9. If hash is not undefined:
if (hash.has_value()) {
// 1. Let normalizedHash be the result of normalize an algorithm with alg set to hash and op set to digest.
- auto normalized_hash = TRY(normalize_an_algorithm(realm, AlgorithmIdentifier { *hash }, "digest"_string));
+ auto normalized_hash = TRY(hash_algorithm_identifier_from_value(realm, JS::js_undefined(), hash->raw_identity()));
// 2. If normalizedHash is not equal to the hash member of normalizedAlgorithm, throw a DataError.
- if (normalized_hash.parameter->name != normalized_algorithm.hash.name)
+ if (normalized_hash.name != normalized_algorithm.hash.name)
return WebIDL::DataError::create("Invalid hash"_utf16);
}
@@ -1829,10 +1867,10 @@ WebIDL::ExceptionOr<GC::Ref<CryptoKey>> RSAPSS::import_key(JS::Realm& realm, Alg
// 8. If hash is not undefined:
if (hash.has_value()) {
// 1. Let normalizedHash be the result of normalize an algorithm with alg set to hash and op set to digest.
- auto normalized_hash = TRY(normalize_an_algorithm(realm, AlgorithmIdentifier { *hash }, "digest"_string));
+ auto normalized_hash = TRY(hash_algorithm_identifier_from_value(realm, JS::js_undefined(), hash->raw_identity()));
// 2. If normalizedHash is not equal to the hash member of normalizedAlgorithm, throw a DataError.
- if (normalized_hash.parameter->name != normalized_algorithm.hash.name)
+ if (normalized_hash.name != normalized_algorithm.hash.name)
return WebIDL::DataError::create("Invalid hash"_utf16);
}
@@ -2417,10 +2455,10 @@ WebIDL::ExceptionOr<GC::Ref<CryptoKey>> RSASSAPKCS1::import_key(JS::Realm& realm
// 8. If hash is not undefined:
if (hash.has_value()) {
// 1. Let normalizedHash be the result of normalize an algorithm with alg set to hash and op set to digest.
- auto normalized_hash = TRY(normalize_an_algorithm(realm, AlgorithmIdentifier { *hash }, "digest"_string));
+ auto normalized_hash = TRY(hash_algorithm_identifier_from_value(realm, JS::js_undefined(), hash->raw_identity()));
// 2. If normalizedHash is not equal to the hash member of normalizedAlgorithm, throw a DataError.
- if (normalized_hash.parameter->name != normalized_algorithm.hash.name)
+ if (normalized_hash.name != normalized_algorithm.hash.name)
return WebIDL::DataError::create("Invalid hash"_utf16);
}
diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h
index 9cd9e37a354..fc3aa51ff6e 100644
--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h
+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h
@@ -23,7 +23,6 @@
namespace Web::Crypto {
-using AlgorithmIdentifier = Variant<GC::Ref<JS::Object>, Utf16String>;
using NamedCurve = Utf16String;
using ExportKeyResult = Variant<ByteBuffer, JsonWebKey>;
@@ -49,8 +48,6 @@ struct AlgorithmParams {
// NOTE: this is initialized when normalizing the algorithm name as the spec requests.
// It must not be set in `from_value`.
Utf16String name;
-
- static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::Realm&, JS::Value);
};
// https://w3c.github.io/webcrypto/#aes-cbc
diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp
index 92b07b5e598..d9b219cfd87 100644
--- a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp
+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp
@@ -119,11 +119,9 @@ using ReceiveJsonWebKey = void (*)(void*, RawJsonWebKey const&);
using ReceiveUsages = void (*)(void*, ReadonlySpan<KeyUsage>);
extern "C" {
-JSCompletion web_rust_crypto_normalize_an_algorithm(JSVM*, JS::Realm*, JSObject*, FlatPtr, ReadonlyBytes, NormalizedAlgorithmAndParameter**);
JSCompletion web_crypto_algorithm_from_value(JS::Realm*, AlgorithmId, ParameterId, JSValue, FlatPtr, NormalizedAlgorithmAndParameter**);
void web_crypto_algorithm_destroy(NormalizedAlgorithmAndParameter*);
void web_crypto_algorithm_public_key_usages(NormalizedAlgorithmAndParameter const*, void*, ReceiveUsages);
-void web_crypto_normalized_key_usages(ReadonlySpan<KeyUsage>, void*, ReceiveUsages);
CryptoKey* web_crypto_public_key_for_private_key(CryptoKey const*);
JSCompletion web_crypto_algorithm_encrypt(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);
JSCompletion web_crypto_algorithm_decrypt(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);
@@ -236,21 +234,6 @@ static void with_raw_json_web_key(JsonWebKey const& key, void* state, ReceiveJso
receive(state, raw);
}
-WebIDL::ExceptionOr<NormalizedAlgorithmAndParameter> normalize_an_algorithm(JS::Realm& realm, AlgorithmIdentifier const& algorithm, String operation)
-{
- JSObject* object = nullptr;
- FlatPtr name = 0;
- if (algorithm.has<Utf16String>())
- name = algorithm.get<Utf16String>().raw_identity();
- else
- object = JS::HostABI::object_to_abi(algorithm.get<GC::Ref<JS::Object>>().ptr());
-
- NormalizedAlgorithmAndParameter* normalized_algorithm = nullptr;
- TRY(JS::HostABI::completion_from_abi<void>(web_rust_crypto_normalize_an_algorithm(
- JS::HostABI::vm_to_abi(realm.vm()), &realm, object, name, operation.bytes(), &normalized_algorithm)));
- return move(*adopt_own(*normalized_algorithm));
-}
-
JSCompletion web_crypto_algorithm_from_value(JS::Realm* realm_pointer, AlgorithmId method_id, ParameterId parameter_id, JSValue value, FlatPtr name, NormalizedAlgorithmAndParameter** out)
{
auto& realm = *realm_pointer;
@@ -311,7 +294,7 @@ JSCompletion web_crypto_algorithm_from_value(JS::Realm* realm_pointer, Algorithm
auto object = JS::HostABI::value_from_abi(value);
switch (parameter_id) {
case ParameterId::AlgorithmParams:
- return AlgorithmParams::from_value(realm, object);
+ return adopt_own(*new AlgorithmParams {});
case ParameterId::RsaHashedKeyGenParams:
return RsaHashedKeyGenParams::from_value(realm, object);
case ParameterId::RsaHashedImportParams:
@@ -385,12 +368,6 @@ void web_crypto_algorithm_public_key_usages(NormalizedAlgorithmAndParameter cons
receive(state, *usages);
}
-void web_crypto_normalized_key_usages(ReadonlySpan<KeyUsage> usages, void* state, ReceiveUsages receive)
-{
- auto normalized = normalized_key_usages(usages);
- receive(state, normalized.span());
-}
-
static ErrorOr<CryptoKey::InternalKeyData> public_key_for_private_key(CryptoKey const& key)
{
return key.handle().visit(
diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.h b/Libraries/LibWeb/Crypto/SubtleCrypto.h
index bc226b77be4..fabbc35ee78 100644
--- a/Libraries/LibWeb/Crypto/SubtleCrypto.h
+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.h
@@ -17,6 +17,5 @@ struct NormalizedAlgorithmAndParameter {
NonnullOwnPtr<AlgorithmMethods> methods;
NonnullOwnPtr<AlgorithmParams> parameter;
};
-WebIDL::ExceptionOr<NormalizedAlgorithmAndParameter> normalize_an_algorithm(JS::Realm&, AlgorithmIdentifier const& algorithm, String operation);
}
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 882182313e2..f5e642b2707 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -45,10 +45,10 @@ 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": (
- 6,
- 358,
+ 5,
+ 354,
"WebCrypto algorithms still use realms for buffer/key/promise materialization and for normalizing algorithm "
- "dictionaries, which SubtleCrypto.supports() does in the caller realm. The native CryptoKey wrapper "
+ "dictionaries. The native CryptoKey wrapper "
"uses the caller's realm and wrapper world",
),
"DOM": (