Truly independent web browser
LibWeb: Handle Web Crypto's backend results without unwrapping them
Shannon Boothd96b91bc5279
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rsindex 016f277231d..05dbafbbaaf 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs@@ -501,17 +501,17 @@ impl AlgorithmMethods for Sha {let result_buffer = libcrypto_rust::sha_digest(hash_kind, data.as_slice()).map(Bytes::new);// 2. If performing the operation results in an error, then throw an OperationError.- if result_buffer.is_err() {+ let Ok(result_buffer) = result_buffer else {return Err(Exception::Dom("OperationError",Utf16String::from_utf8("Failed to create result buffer"),));- }+ };// 3. Return result.// https://wicg.github.io/webcrypto-modern-algos/#sha3-operations-digest// 3. Return the Keccak encoding of result.- Ok(result_buffer.expect("LibCrypto returns the digest"))+ Ok(result_buffer)}}@@ -573,15 +573,15 @@ impl AlgorithmMethods for CShakeParams {.map(Bytes::new);// 5. If performing the operation results in an error, then throw an OperationError.- if let Err(detail) = result {- return Err(Exception::Dom(+ let result = result.map_err(|detail| {+ Exception::Dom("OperationError",libjs_rust::api::utf16_formatted("Hash function failed: {}", &[&detail.message()]),- ));- }+ )+ })?;// 6. Return the Keccak encoding of result.- Ok(result.expect("LibCrypto returns the digest"))+ Ok(result)}}@@ -810,10 +810,10 @@ fn kmac_calculate_mac(customization.map(Bytes::as_slice),).map(Bytes::new);- if mac.is_err() {+ let Ok(mac) = mac else {return Err(dom_error("OperationError", b"KMAC operation failed"));- }- Ok(mac.expect("LibCrypto returns a MAC"))+ };+ Ok(mac)}#[derive(Clone, Trace)]@@ -2185,12 +2185,12 @@ impl AlgorithmMethods for HkdfParams {.map(Bytes::new);// 6. If the key derivation operation fails, then throw an OperationError.- if result.is_err() {+ let Ok(result) = result else {return Err(dom_error("OperationError", b"Failed to derive key"));- }+ };// 7. Return result.- Ok(result.expect("LibCrypto returns the derived bytes"))+ Ok(result)}}@@ -2269,12 +2269,12 @@ impl AlgorithmMethods for Pbkdf2Params {.map(Bytes::new);// 6. If the key derivation operation fails, then throw an OperationError.- if result.is_err() {+ let Ok(result) = result else {return Err(dom_error("OperationError", b"Failed to derive key"));- }+ };// 7. Return result.- Ok(result.expect("LibCrypto returns the derived bytes"))+ Ok(result)}}@@ -2503,15 +2503,15 @@ impl AlgorithmMethods for Argon2Params {let result = libcrypto_rust::argon2_derive_key(kind, &inputs).map(Bytes::new);// 10. If the key derivation operation fails, then throw an OperationError.- if let Err(detail) = result {- return Err(Exception::Dom(+ let result = result.map_err(|detail| {+ Exception::Dom("OperationError",libjs_rust::api::utf16_formatted("Hashing function failed: {}", &[&detail.message()]),- ));- }+ )+ })?;// 11. Return result.- Ok(result.expect("LibCrypto returns the derived bytes"))+ Ok(result)}}@@ -2721,12 +2721,12 @@ impl AlgorithmMethods for AesCbc {normalized_algorithm.iv.as_slice(),).map(Bytes::new);- if ciphertext.is_err() {+ let Ok(ciphertext) = ciphertext else {return Err(dom_error("OperationError", b"Failed to encrypt"));- }+ };// 4. Return ciphertext.- Ok(ciphertext.expect("LibCrypto returns the result"))+ Ok(ciphertext)}// https://w3c.github.io/webcrypto/#aes-cbc-operations-decrypt@@ -2771,12 +2771,12 @@ impl AlgorithmMethods for AesCbc {normalized_algorithm.iv.as_slice(),).map(Bytes::new);- if plaintext.is_err() {+ let Ok(plaintext) = plaintext else {return Err(dom_error("OperationError", b"Failed to decrypt"));- }+ };// 7. Return plaintext.- Ok(plaintext.expect("LibCrypto returns the result"))+ Ok(plaintext)}// https://w3c.github.io/webcrypto/#aes-cbc-operations-import-key@@ -3505,12 +3505,12 @@ impl AlgorithmMethods for AesCtr {normalized_algorithm.length,).map(Bytes::new);- if ciphertext.is_err() {+ let Ok(ciphertext) = ciphertext else {return Err(dom_error("OperationError", b"Encryption failed"));- }+ };// 4. Return ciphertext.- Ok(ciphertext.expect("LibCrypto returns the result"))+ Ok(ciphertext)}// https://w3c.github.io/webcrypto/#aes-ctr-operations-decrypt@@ -3555,12 +3555,12 @@ impl AlgorithmMethods for AesCtr {normalized_algorithm.length,).map(Bytes::new);- if plaintext.is_err() {+ let Ok(plaintext) = plaintext else {return Err(dom_error("OperationError", b"Decryption failed"));- }+ };// 4. Return plaintext.- Ok(plaintext.expect("LibCrypto returns the result"))+ Ok(plaintext)}}@@ -3988,13 +3988,13 @@ impl AlgorithmMethods for AesGcm {).map(Bytes::new);- if plaintext.is_err() {+ let Ok(plaintext) = plaintext else {return Err(dom_error("OperationError", b"Decryption failed"));- }+ };// Otherwise: Let plaintext be the output P of the Authenticated Decryption Function.// 9. Return plaintext.- Ok(plaintext.expect("LibCrypto returns plaintext"))+ Ok(plaintext)}// https://w3c.github.io/webcrypto/#aes-gcm-operations-generate-key@@ -4423,12 +4423,12 @@ impl AlgorithmMethods for AesKw {// with plaintext as the plaintext to be wrapped and using the default Initial Value defined in Section 2.2.3.1 of the same document.let ciphertext =libcrypto_rust::aes_kw_cipher(true, key.byte_handle_bytes(), plaintext.as_slice()).map(Bytes::new);- if ciphertext.is_err() {+ let Ok(ciphertext) = ciphertext else {return Err(dom_error("OperationError", b"Key wrap failed"));- }+ };// 3. Return ciphertext.- Ok(ciphertext.expect("LibCrypto returns the result"))+ Ok(ciphertext)}// https://w3c.github.io/webcrypto/#aes-kw-operations-unwrap-key@@ -4444,12 +4444,12 @@ impl AlgorithmMethods for AesKw {// 2. If the Key Unwrap operation returns an error, then throw an OperationError.let plaintext =libcrypto_rust::aes_kw_cipher(false, key.byte_handle_bytes(), ciphertext.as_slice()).map(Bytes::new);- if plaintext.is_err() {+ let Ok(plaintext) = plaintext else {return Err(dom_error("OperationError", b"Key unwrap failed"));- }+ };// 3. Return plaintext.- Ok(plaintext.expect("LibCrypto returns the result"))+ Ok(plaintext)}}@@ -4532,15 +4532,15 @@ impl AlgorithmMethods for AesOcb {).map(Bytes::new);- if let Err(detail) = ciphertext {- return Err(Exception::Dom(+ let ciphertext = ciphertext.map_err(|detail| {+ Exception::Dom("OperationError",libjs_rust::api::utf16_formatted("Encryption failed: {}", &[&detail.message()]),- ));- }+ )+ })?;// 5. Return C.- Ok(ciphertext.expect("LibCrypto returns the result"))+ Ok(ciphertext)}// https://wicg.github.io/webcrypto-modern-algos/#aes-ocb-operations-decrypt@@ -4620,15 +4620,15 @@ impl AlgorithmMethods for AesOcb {// throw an OperationError// Otherwise:// Let plaintext be the output P of OCB-DECRYPT.- if let Err(detail) = plaintext {- return Err(Exception::Dom(+ let plaintext = plaintext.map_err(|detail| {+ Exception::Dom("OperationError",libjs_rust::api::utf16_formatted("Decryption failed: {}", &[&detail.message()]),- ));- }+ )+ })?;// 6. Return plaintext.- Ok(plaintext.expect("LibCrypto returns the result"))+ Ok(plaintext)}// https://wicg.github.io/webcrypto-modern-algos/#aes-ocb-operations-generate-key@@ -5026,15 +5026,15 @@ impl AlgorithmMethods for ChaCha20Poly1305 {).map(Bytes::new);- if let Err(detail) = ciphertext {- return Err(Exception::Dom(+ let ciphertext = ciphertext.map_err(|detail| {+ Exception::Dom("OperationError",libjs_rust::api::utf16_formatted("Encryption failed: {}", &[&detail.message()]),- ));- }+ )+ })?;// 5. Return ciphertext.- Ok(ciphertext.expect("LibCrypto returns the result"))+ Ok(ciphertext)}// https://wicg.github.io/webcrypto-modern-algos/#chacha20-poly1305-operations-decrypt@@ -5089,15 +5089,15 @@ impl AlgorithmMethods for ChaCha20Poly1305 {// throw an OperationError// Otherwise:// Let plaintext be the resulting plaintext.- if let Err(detail) = plaintext {- return Err(Exception::Dom(+ let plaintext = plaintext.map_err(|detail| {+ Exception::Dom("OperationError",libjs_rust::api::utf16_formatted("Decryption failed: {}", &[&detail.message()]),- ));- }+ )+ })?;// 6. Return plaintext.- Ok(plaintext.expect("LibCrypto returns the result"))+ Ok(plaintext)}// https://wicg.github.io/webcrypto-modern-algos/#chacha20-poly1305-operations-generate-key@@ -5517,10 +5517,6 @@ fn validate_rsa_key_generation_parameters(normalized_algorithm: &RsaKeyGenParamsOk(())}-fn rsa_key_metadata(vm: &Vm, key: Ref<CryptoKey>) -> WebIdlResult<(u32, Vec<u8>)> {- libcrypto_rust::rsa_read_key_metadata(key.handle()).map_err(|_| out_of_memory(vm))-}-fn parse_jwk_rsa_key(jwk: &JsonWebKey, is_private: bool) -> WebIdlResult<KeyHandle> {let decode = |component: &Option<Utf16String>| {base64_url_bytes_decode(component.as_ref().expect("the RSA JWK contains the component"))@@ -5549,21 +5545,17 @@ fn parse_jwk_rsa_key(jwk: &JsonWebKey, is_private: bool) -> WebIdlResult<KeyHandfn rsa_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool) -> WebIdlResult<Bytes> {let result = libcrypto_rust::rsa_export_der(key.handle(), is_public).map(Bytes::new);- if result.is_err() {+ let Ok(result) = result else {return vm.throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[]).map_err(Into::into);- }- Ok(result.expect("LibCrypto returns the DER bytes"))+ };+ Ok(result)}fn rsa_export_jwk_integer(vm: &Vm, key: Ref<CryptoKey>, component: RsaJwkInteger) -> WebIdlResult<Utf16String> {- let bytes = libcrypto_rust::rsa_export_jwk_integer(key.handle(), component).map(Bytes::new);- if bytes.is_err() {- return Err(out_of_memory(vm));- }- let bytes = bytes.expect("LibCrypto returns the exported integer");- Ok(base64_url_bytes_encode(bytes.as_slice()))+ let bytes = libcrypto_rust::rsa_export_jwk_integer(key.handle(), component).map_err(|_| out_of_memory(vm))?;+ Ok(base64_url_bytes_encode(&bytes))}fn key_format_to_string(format: KeyFormat) -> &'static str {@@ -5645,12 +5637,12 @@ impl AlgorithmMethods for RsaOaep {let ciphertext =libcrypto_rust::rsa_oaep_cipher(true, hash_kind, key.handle(), label.as_slice(), plaintext.as_slice()).map(Bytes::new);- if ciphertext.is_err() {+ let Ok(ciphertext) = ciphertext else {return Err(dom_error("OperationError", b"Failed to encrypt"));- }+ };// 6. Return ciphertext.- Ok(ciphertext.expect("LibCrypto returns the result"))+ Ok(ciphertext)}// https://w3c.github.io/webcrypto/#rsa-oaep-operations-decrypt@@ -5700,12 +5692,12 @@ impl AlgorithmMethods for RsaOaep {let plaintext =libcrypto_rust::rsa_oaep_cipher(false, hash_kind, key.handle(), label.as_slice(), ciphertext.as_slice()).map(Bytes::new);- if plaintext.is_err() {+ let Ok(plaintext) = plaintext else {return Err(dom_error("OperationError", b"Failed to encrypt"));- }+ };// 6. Return plaintext.- Ok(plaintext.expect("LibCrypto returns the result"))+ Ok(plaintext)}// https://w3c.github.io/webcrypto/#rsa-oaep-operations-generate-key@@ -6119,7 +6111,8 @@ impl AlgorithmMethods for RsaOaep {// 5. Set the modulusLength attribute of algorithm to the length, in bits, of the RSA public modulus.// 6. Set the publicExponent attribute of algorithm to the BigInteger representation of the RSA public exponent.- let (modulus_length, public_exponent) = rsa_key_metadata(cx.vm(), key)?;+ let (modulus_length, public_exponent) =+ libcrypto_rust::rsa_read_key_metadata(key.handle()).map_err(|_| out_of_memory(cx.vm()))?;// 7. Set the hash attribute of algorithm to the hash member of normalizedAlgorithm.let hash_name = normalized_algorithm.hash.name.clone();@@ -6475,12 +6468,12 @@ impl AlgorithmMethods for RsaPss {message.as_slice(),).map(Bytes::new);- if signature.is_err() {+ let Ok(signature) = signature else {return Err(dom_error("OperationError", b"Failed to sign message"));- }+ };// 5. Return signature.- Ok(signature.expect("LibCrypto returns the result"))+ Ok(signature)}// https://w3c.github.io/webcrypto/#rsa-pss-operations-verify@@ -6538,11 +6531,11 @@ impl AlgorithmMethods for RsaPss {message.as_slice(),signature.as_slice(),);- if verified.is_err() {+ let Ok(verified) = verified else {return Err(dom_error("OperationError", b"Failed to verify message"));- }+ };- Ok(verified.expect("LibCrypto returns the verification result"))+ Ok(verified)}// https://w3c.github.io/webcrypto/#rsa-pss-operations-import-key@@ -6834,7 +6827,8 @@ impl AlgorithmMethods for RsaPss {// 5. Set the modulusLength attribute of algorithm to the length, in bits, of the RSA public modulus.// 6. Set the publicExponent attribute of algorithm to the BigInteger representation of the RSA public exponent.- let (modulus_length, public_exponent) = rsa_key_metadata(cx.vm(), key)?;+ let (modulus_length, public_exponent) =+ libcrypto_rust::rsa_read_key_metadata(key.handle()).map_err(|_| out_of_memory(cx.vm()))?;// 7. Set the hash attribute of algorithm to the hash member of normalizedAlgorithm.let hash_name = normalized_algorithm.hash.name.clone();@@ -7181,12 +7175,12 @@ impl AlgorithmMethods for RsassaPkcs1 {let signature =libcrypto_rust::rsa_sign(hash_kind, key.handle(), RsaSignaturePadding::Pkcs1, message.as_slice()).map(Bytes::new);- if signature.is_err() {+ let Ok(signature) = signature else {return Err(dom_error("OperationError", b"Failed to sign message"));- }+ };// 5. Return signature.- Ok(signature.expect("LibCrypto returns the result"))+ Ok(signature)}// https://w3c.github.io/webcrypto/#rsassa-pkcs1-operations-verify@@ -7239,12 +7233,12 @@ impl AlgorithmMethods for RsassaPkcs1 {message.as_slice(),signature.as_slice(),);- if verified.is_err() {+ let Ok(verified) = verified else {return Err(dom_error("OperationError", b"Failed to verify message"));- }+ };// 4. Return result.- Ok(verified.expect("LibCrypto returns the verification result"))+ Ok(verified)}// https://w3c.github.io/webcrypto/#rsassa-pkcs1-operations-import-key@@ -7538,7 +7532,8 @@ impl AlgorithmMethods for RsassaPkcs1 {// 5. Set the modulusLength attribute of algorithm to the length, in bits, of the RSA public modulus.// 6. Set the publicExponent attribute of algorithm to the BigInteger representation of the RSA public exponent.- let (modulus_length, public_exponent) = rsa_key_metadata(cx.vm(), key)?;+ let (modulus_length, public_exponent) =+ libcrypto_rust::rsa_read_key_metadata(key.handle()).map_err(|_| out_of_memory(cx.vm()))?;// 7. Set the hash attribute of algorithm to the hash member of normalizedAlgorithm.let hash_name = normalized_algorithm.hash.name.clone();@@ -7827,33 +7822,17 @@ fn ec_parse_raw_public_key(vm: &Vm, curve: EcCurve, key_bytes: &Bytes) -> WebIdlreturn Err(dom_error("DataError", b"Failed to parse key"));};let key = CryptoKey::create(vm, key);- if !ec_key_is_valid(curve, key) {+ if !libcrypto_rust::ec_key_is_valid(curve, key.handle()) {return Err(dom_error("DataError", b"Invalid key"));}Ok(key)}-fn ec_key_is_valid(curve: EcCurve, key: Ref<CryptoKey>) -> bool {- libcrypto_rust::ec_key_is_valid(curve, key.handle())-}--fn ec_export_der(curve: EcCurve, key: Ref<CryptoKey>, is_public: bool) -> Result<Bytes, CryptoError> {- libcrypto_rust::ec_export_der(curve, key.handle(), is_public).map(Bytes::new)-}--fn ec_export_uncompressed(key: Ref<CryptoKey>) -> Result<Bytes, CryptoError> {- libcrypto_rust::ec_export_uncompressed(key.handle()).map(Bytes::new)-}-fn ec_export_public_coordinates(key: Ref<CryptoKey>) -> Result<(Bytes, Bytes), CryptoError> {let (x, y) = libcrypto_rust::ec_export_public_coordinates(key.handle())?;Ok((Bytes::new(x), Bytes::new(y)))}-fn ec_export_private_scalar(key: Ref<CryptoKey>) -> Result<Bytes, CryptoError> {- libcrypto_rust::ec_export_private_scalar(key.handle()).map(Bytes::new)-}-fn copy_bytes(vm: &Vm, bytes: &[u8]) -> WebIdlResult<Vec<u8>> {let mut copy = Vec::new();if copy.try_reserve_exact(bytes.len()).is_err() {@@ -8021,13 +8000,13 @@ impl AlgorithmMethods for Ecdsa {sha_hash_kind(hash_algorithm).map_err(|message| Exception::Dom("NotSupportedError", message))?;let digest = libcrypto_rust::sha_digest(hash_kind, message.as_slice()).map(Bytes::new);- if digest.is_err() {+ let Ok(digest) = digest else {return cx.vm().throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[]).map_err(Into::into);- }- let m = digest.expect("LibCrypto returns the digest");+ };+ let m = digest;// 4. Let d be the ECDSA private key associated with key.let d = key.handle();@@ -8130,13 +8109,13 @@ impl AlgorithmMethods for Ecdsa {sha_hash_kind(hash_algorithm).map_err(|message| Exception::Dom("NotSupportedError", message))?;let digest = libcrypto_rust::sha_digest(hash_kind, message.as_slice()).map(Bytes::new);- if digest.is_err() {+ let Ok(digest) = digest else {return cx.vm().throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[]).map_err(Into::into);- }- let m = digest.expect("LibCrypto returns the digest");+ };+ let m = digest;// 4. Let Q be the ECDSA public key associated with key.let q = key.handle();@@ -8170,13 +8149,9 @@ impl AlgorithmMethods for Ecdsa {// 5. Perform the ECDSA verifying process, as specified in [RFC6090], Section 5.4.3, with M as the received// message, (r, s) as the signature and using params as the EC domain parameters, and Q as the public key.let verification = libcrypto_rust::ec_verify(curve, q, m.as_slice(), r, s);- if let Err(message) = verification {- return Err(Exception::Dom(- "OperationError",- Utf16String::from_utf8(message.message()),- ));- }- result = verification.expect("LibCrypto returns the verification result");+ let verification = verification+ .map_err(|message| Exception::Dom("OperationError", Utf16String::from_utf8(message.message())))?;+ result = verification;} else {// Otherwise, the namedCurve attribute of the [[algorithm]] internal slot of key is a value specified in an applicable specification:// Perform the ECDSA verification steps specified in that specification passing in M, signature, params and Q and resulting in an indication of whether or not the purported signature is valid.@@ -8314,7 +8289,7 @@ impl AlgorithmMethods for Ecdsa {// 12. If the public key value is not a valid point on the Elliptic Curve identified// by the namedCurve member of normalizedAlgorithm throw a DataError.let curve = ec_curve_from_name(&named_curve).expect("the named curve is supported");- if !ec_key_is_valid(curve, key) {+ if !libcrypto_rust::ec_key_is_valid(curve, key.handle()) {return Err(dom_error("DataError", b"Invalid key"));}@@ -8417,7 +8392,7 @@ impl AlgorithmMethods for Ecdsa {// 12. If the private key value is not a valid point on the Elliptic Curve identified by the namedCurve// member of normalizedAlgorithm throw a DataError.let curve = ec_curve_from_name(&named_curve).expect("the named curve is supported");- if !ec_key_is_valid(curve, key) {+ if !libcrypto_rust::ec_key_is_valid(curve, key.handle()) {return Err(dom_error("DataError", b"Invalid key"));}@@ -8597,7 +8572,7 @@ impl AlgorithmMethods for Ecdsa {// 10. If the key value is not a valid point on the Elliptic Curve identified// by the namedCurve member of normalizedAlgorithm throw a DataError.let curve = ec_curve_from_name(&named_curve).expect("the named curve is supported");- if !ec_key_is_valid(curve, key) {+ if !libcrypto_rust::ec_key_is_valid(curve, key.handle()) {return Err(dom_error("DataError", b"Invalid key"));}@@ -8716,13 +8691,13 @@ impl AlgorithmMethods for Ecdsa {// If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-521":// Set parameters to the namedCurve choice with value equal to the object identifier secp521r1// defined in [RFC5480]- let maybe_data = ec_export_der(curve, key, true);+ let maybe_data = libcrypto_rust::ec_export_der(curve, key.handle(), true).map(Bytes::new);- if maybe_data.is_err() {+ let Ok(maybe_data) = maybe_data else {return Err(dom_error("DataError", b"Failed to encode public key"));- }+ };- data = maybe_data.expect("encoding succeeded");+ data = maybe_data;} else {// Otherwise:// FIXME: 1. Perform any key export steps defined by other applicable specifications, passing format and@@ -8777,13 +8752,13 @@ impl AlgorithmMethods for Ecdsa {// If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-521":// Set parameters to the namedCurve choice with value equal to the object identifier secp521r1// defined in [RFC5480]- let maybe_data = ec_export_der(curve, key, false);+ let maybe_data = libcrypto_rust::ec_export_der(curve, key.handle(), false).map(Bytes::new);- if maybe_data.is_err() {+ let Ok(maybe_data) = maybe_data else {return Err(dom_error("DataError", b"Failed to encode private key"));- }+ };- data = maybe_data.expect("encoding succeeded");+ data = maybe_data;} else {// Otherwise:// FIXME: 1. Perform any key export steps defined by other applicable specifications, passing format and@@ -8840,7 +8815,8 @@ impl AlgorithmMethods for Ecdsa {// 4. If the [[type]] internal slot of key is "private"if key.key_type() == KeyType::Private {// Set the d attribute of jwk according to the definition in Section 6.2.2.1 of JSON Web Algorithms [JWA].- let d_bytes = ec_export_private_scalar(key)+ let d_bytes = libcrypto_rust::ec_export_private_scalar(key.handle())+ .map(Bytes::new).map_err(|_| dom_error("DataError", b"Failed to encode private key"))?;jwk.d = Some(base64_url_bytes_encode(d_bytes.as_slice()));}@@ -8885,13 +8861,13 @@ impl AlgorithmMethods for Ecdsa {// "P-521":// Let data be a byte sequence representing the Elliptic Curve point Q represented by the [[handle]]// internal slot of key according to [SEC1] 2.3.3 using the uncompressed format.- let maybe_data = ec_export_uncompressed(key);+ let maybe_data = libcrypto_rust::ec_export_uncompressed(key.handle()).map(Bytes::new);- if maybe_data.is_err() {+ let Ok(maybe_data) = maybe_data else {return Err(dom_error("DataError", b"Failed to encode public key"));- }+ };- maybe_data.expect("encoding succeeded")+ maybe_data} else {// Perform any key export steps defined by other applicable specifications, passing format and// the namedCurve attribute of the [[algorithm]] internal slot of key and obtaining namedCurve and data.@@ -9305,7 +9281,7 @@ impl AlgorithmMethods for Ecdh {// 12. If the key value is not a valid point on the Elliptic Curve identified// by the namedCurve member of normalizedAlgorithm throw a DataError.let curve = ec_curve_from_name(&named_curve).expect("the named curve is supported");- if !ec_key_is_valid(curve, key) {+ if !libcrypto_rust::ec_key_is_valid(curve, key.handle()) {return Err(dom_error("DataError", b"Invalid key"));}@@ -9409,7 +9385,7 @@ impl AlgorithmMethods for Ecdh {// 12. If the key value is not a valid point on the Elliptic Curve identified// by the namedCurve member of normalizedAlgorithm throw a DataError.let curve = ec_curve_from_name(&named_curve).expect("the named curve is supported");- if !ec_key_is_valid(curve, key) {+ if !libcrypto_rust::ec_key_is_valid(curve, key.handle()) {return Err(dom_error("DataError", b"Invalid key"));}@@ -9551,7 +9527,7 @@ impl AlgorithmMethods for Ecdh {// 11. If the key value is not a valid point on the Elliptic Curve identified// by the namedCurve member of normalizedAlgorithm throw a DataError.let curve = ec_curve_from_name(&named_curve).expect("the named curve is supported");- if !ec_key_is_valid(curve, key) {+ if !libcrypto_rust::ec_key_is_valid(curve, key.handle()) {return Err(dom_error("DataError", b"Invalid key"));}@@ -9664,13 +9640,13 @@ impl AlgorithmMethods for Ecdh {// If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-521":// Set parameters to the namedCurve choice with value equal to the object identifier secp521r1// defined in [RFC5480]- let maybe_data = ec_export_der(curve, key, true);+ let maybe_data = libcrypto_rust::ec_export_der(curve, key.handle(), true).map(Bytes::new);- if maybe_data.is_err() {+ let Ok(maybe_data) = maybe_data else {return Err(dom_error("DataError", b"Failed to encode public key"));- }+ };- data = maybe_data.expect("encoding succeeded");+ data = maybe_data;} else {// Otherwise:// FIXME: 1. Perform any key export steps defined by other applicable specifications, passing format and@@ -9725,13 +9701,13 @@ impl AlgorithmMethods for Ecdh {// If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-521":// Set parameters to the namedCurve choice with value equal to the object identifier secp521r1// defined in [RFC5480]- let maybe_data = ec_export_der(curve, key, false);+ let maybe_data = libcrypto_rust::ec_export_der(curve, key.handle(), false).map(Bytes::new);- if maybe_data.is_err() {+ let Ok(maybe_data) = maybe_data else {return Err(dom_error("DataError", b"Failed to encode private key"));- }+ };- data = maybe_data.expect("encoding succeeded");+ data = maybe_data;} else {// Otherwise:// FIXME: 1. Perform any key export steps defined by other applicable specifications, passing format and@@ -9788,7 +9764,8 @@ impl AlgorithmMethods for Ecdh {// 4. If the [[type]] internal slot of key is "private"if key.key_type() == KeyType::Private {// Set the d attribute of jwk according to the definition in Section 6.2.2.1 of JSON Web Algorithms [JWA].- let d_bytes = ec_export_private_scalar(key)+ let d_bytes = libcrypto_rust::ec_export_private_scalar(key.handle())+ .map(Bytes::new).map_err(|_| dom_error("DataError", b"Failed to encode private key"))?;jwk.d = Some(base64_url_bytes_encode(d_bytes.as_slice()));}@@ -9834,13 +9811,13 @@ impl AlgorithmMethods for Ecdh {// Let data be the byte sequence 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.- let maybe_data = ec_export_uncompressed(key);+ let maybe_data = libcrypto_rust::ec_export_uncompressed(key.handle()).map(Bytes::new);- if maybe_data.is_err() {+ let Ok(maybe_data) = maybe_data else {return Err(dom_error("DataError", b"Failed to encode public key"));- }+ };- maybe_data.expect("encoding succeeded")+ maybe_data} else {// Perform any key export steps defined by other applicable specifications, passing format and// the namedCurve attribute of the [[algorithm]] internal slot of key and obtaining namedCurve and data.@@ -9899,29 +9876,25 @@ fn parse_octet_string(vm: &Vm, bytes: &[u8]) -> WebIdlResult<Vec<u8>> {}fn okp_generate_private_key(curve: OkpCurve) -> Result<Bytes, ()> {- let key = libcrypto_rust::okp_generate_private_key(curve).map(Bytes::new);- if key.is_err() {- return Err(());- }- Ok(key.expect("LibCrypto returns the private key"))+ libcrypto_rust::okp_generate_private_key(curve)+ .map(Bytes::new)+ .map_err(|_| ())}fn okp_generate_public_key(curve: OkpCurve, private_key: &[u8]) -> Result<Bytes, ()> {- let key = libcrypto_rust::okp_generate_public_key(curve, private_key).map(Bytes::new);- if key.is_err() {- return Err(());- }- Ok(key.expect("LibCrypto returns the public key"))+ libcrypto_rust::okp_generate_public_key(curve, private_key)+ .map(Bytes::new)+ .map_err(|_| ())}fn okp_export_der(vm: &Vm, curve: OkpCurve, is_public: bool, key: &[u8]) -> WebIdlResult<Bytes> {let result = libcrypto_rust::okp_export_der(curve, is_public, key).map(Bytes::new);- if result.is_err() {+ let Ok(result) = result else {return vm.throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[]).map_err(Into::into);- }- Ok(result.expect("LibCrypto returns the DER bytes"))+ };+ Ok(result)}fn out_of_memory(vm: &Vm) -> Exception {@@ -10467,12 +10440,11 @@ impl AlgorithmMethods for Ed25519 {let signature = libcrypto_rust::okp_sign(OkpCurve::Ed25519, key.okp_handle_bytes(), message.as_slice(), &[]).map(Bytes::new);- if signature.is_err() {+ let Ok(signature) = signature else {return Err(dom_error("OperationError", b"Failed to sign message"));- }+ };// 3. Return result.- let signature = signature.expect("LibCrypto returns the signature");let result = Bytes::new(copy_bytes(cx.vm(), signature.as_slice())?);Ok(result)}@@ -10507,15 +10479,11 @@ impl AlgorithmMethods for Ed25519 {message.as_slice(),&[],);- if let Err(error) = verified {- return Err(Exception::Dom(- "OperationError",- Utf16String::from_utf8(error.message()),- ));- }+ let verified =+ verified.map_err(|error| Exception::Dom("OperationError", Utf16String::from_utf8(error.message())))?;// 6. Return result.- Ok(verified.expect("LibCrypto returns the verification result"))+ Ok(verified)}}@@ -11075,13 +11043,13 @@ impl AlgorithmMethods for Ed448 {// with message as M and context as C, using the Ed448 private key associated with key.let signature = libcrypto_rust::okp_sign(OkpCurve::Ed448, key.okp_handle_bytes(), message.as_slice(), context).map(Bytes::new);- if signature.is_err() {+ let Ok(signature) = signature else {return Err(dom_error("OperationError", b"Failed to sign message"));- }+ };// 5. Return a new ArrayBuffer associated with the relevant global object of this [HTML],// and containing the bytes of the signature resulting from performing the Ed448 signing process.- Ok(signature.expect("LibCrypto returns the signature"))+ Ok(signature)}// https://wicg.github.io/webcrypto-secure-curves/#ed448-operations@@ -11126,17 +11094,13 @@ impl AlgorithmMethods for Ed448 {message.as_slice(),context,);- if let Err(error) = verified {- return Err(Exception::Dom(- "OperationError",- Utf16String::from_utf8(error.message()),- ));- }+ let verified =+ verified.map_err(|error| Exception::Dom("OperationError", Utf16String::from_utf8(error.message())))?;// 7. Let result be a boolean with the value true if the signature is valid// and the value false otherwise.// 8. Return result.- Ok(verified.expect("LibCrypto returns the verification result"))+ Ok(verified)}}@@ -11228,11 +11192,9 @@ impl AlgorithmMethods for X25519 {let secret =libcrypto_rust::okp_compute_coordinate(OkpCurve::X25519, private_key, public_key_data).map(Bytes::new);- if secret.is_err() {+ let Ok(secret) = secret else {return Err(dom_error("OperationError", b"Failed to compute secret"));- }-- let secret = secret.expect("LibCrypto returns the shared secret");+ };// 8. If secret is the all-zero value, then throw a OperationError.// This check must be performed in constant-time, as per [RFC7748] Section 6.1.@@ -11828,11 +11790,9 @@ impl AlgorithmMethods for X448 {let secret =libcrypto_rust::okp_compute_coordinate(OkpCurve::X448, private_key, public_key_data).map(Bytes::new);- if secret.is_err() {+ let Ok(secret) = secret else {return Err(dom_error("OperationError", b"Failed to compute secret"));- }-- let secret = secret.expect("LibCrypto returns the shared secret");+ };// 6. If secret is the all-zero value, then throw a OperationError. This check must be performed in constant-time, as per [RFC7748] Section 6.2.// NB: ORing all the bytes avoids an early exit on a nonzero byte.@@ -12399,12 +12359,10 @@ fn generate_mldsa_key_pair_from_seed(name: &Utf16String, seed: &Bytes) -> Resultunreachable!("the name identifies an ML-DSA parameter set")}-fn mldsa_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool, algorithm: KeyAlgorithm) -> WebIdlResult<Bytes> {- let result = libcrypto_rust::ml_export_der(key.handle(), is_public, algorithm).map(Bytes::new);- if result.is_err() {- return Err(out_of_memory(vm));- }- Ok(result.expect("LibCrypto returns the DER bytes"))+fn ml_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool, algorithm: KeyAlgorithm) -> WebIdlResult<Bytes> {+ libcrypto_rust::ml_export_der(key.handle(), is_public, algorithm)+ .map(Bytes::new)+ .map_err(|_| out_of_memory(vm))}#[derive(Clone, Trace)]@@ -12480,12 +12438,12 @@ impl AlgorithmMethods for MlDsa {let signature = libcrypto_rust::mldsa_sign(size, key.handle(), message.as_slice(), context).map(Bytes::new);// 5. If the ML-DSA.Sign algorithm returned an error, throw an OperationError.- if signature.is_err() {+ let Ok(signature) = signature else {return Err(dom_error("OperationError", b"Failed to sign message"));- }+ };// 6. Return result.- Ok(signature.expect("LibCrypto returns a signature"))+ Ok(signature)}// https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-operations-verify@@ -12544,12 +12502,12 @@ impl AlgorithmMethods for MlDsa {libcrypto_rust::mldsa_verify(size, key.handle(), message.as_slice(), signature.as_slice(), context);// 5. If the ML-DSA.Verify algorithm returned an error, throw an OperationError.- if verified.is_err() {+ let Ok(verified) = verified else {return Err(dom_error("OperationError", b"Failed to verify message"));- }+ };// 6. Return result.- Ok(verified.expect("LibCrypto returns the verification result"))+ Ok(verified)}// https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-operations-generate-key@@ -13039,7 +12997,7 @@ impl AlgorithmMethods for MlDsa {return Err(dom_error("NotSupportedError", b"Invalid algorithm"));};- let data = mldsa_export_der(vm, key, true, algorithm_oid)?;+ let data = ml_export_der(vm, key, true, algorithm_oid)?;// 4. Let result be the result of DER-encoding data.ExportKeyResult::Bytes(data)@@ -13094,7 +13052,7 @@ impl AlgorithmMethods for MlDsa {return Err(dom_error("NotSupportedError", b"Invalid algorithm"));};- let data = mldsa_export_der(vm, key, false, algorithm_oid)?;+ let data = ml_export_der(vm, key, false, algorithm_oid)?;// 4. Let result be the result of DER-encoding data.ExportKeyResult::Bytes(data)@@ -13189,14 +13147,6 @@ fn mlkem_read_public_key(vm: &Vm, bytes: &[u8]) -> WebIdlResult<Ref<CryptoKey>>Ok(CryptoKey::create(vm, key))}-fn mlkem_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool, algorithm: KeyAlgorithm) -> WebIdlResult<Bytes> {- let result = libcrypto_rust::ml_export_der(key.handle(), is_public, algorithm).map(Bytes::new);- if result.is_err() {- return Err(out_of_memory(vm));- }- Ok(result.expect("LibCrypto returns the DER bytes"))-}-#[derive(Clone, Trace)]#[gc(crate = libjs_rust)]pub(crate) struct MlKem;@@ -13645,7 +13595,7 @@ impl AlgorithmMethods for MlKem {return Err(dom_error("NotSupportedError", b"Invalid algorithm"));};- let data = mlkem_export_der(vm, key, true, algorithm_oid)?;+ let data = ml_export_der(vm, key, true, algorithm_oid)?;// 4. Let result be the result of DER-encoding data.ExportKeyResult::Bytes(data)@@ -13700,7 +13650,7 @@ impl AlgorithmMethods for MlKem {return Err(dom_error("NotSupportedError", b"Invalid algorithm"));};- let data = mlkem_export_der(vm, key, false, algorithm_oid)?;+ let data = ml_export_der(vm, key, false, algorithm_oid)?;// 4. Let result be the result of DER-encoding data.ExportKeyResult::Bytes(data)@@ -13798,17 +13748,17 @@ impl AlgorithmMethods for MlKem {let encapsulation = libcrypto_rust::mlkem_encapsulate(size, key.handle());// 5. If the ML-KEM.Encaps function returned an error, throw an OperationError.- if let Err(error) = encapsulation {- return Err(Exception::Dom(+ let encapsulation = encapsulation.map_err(|error| {+ Exception::Dom("OperationError",libjs_rust::api::utf16_formatted("Key encapsulation failed: {}", &[&error.message()]),- ));- }+ )+ })?;// 6. Let result be a new EncapsulatedBits dictionary.// 7. Set the sharedKey attribute of result to the result of creating an ArrayBuffer containing sharedKey.// 8. Set the ciphertext attribute of result to the result of creating an ArrayBuffer containing ciphertext.- let (shared_key, ciphertext) = encapsulation.expect("LibCrypto returns the encapsulation");+ let (shared_key, ciphertext) = encapsulation;let result = EncapsulatedBitsData {shared_key: Some(Bytes::new(shared_key)),ciphertext: Some(Bytes::new(ciphertext)),@@ -13855,14 +13805,12 @@ impl AlgorithmMethods for MlKem {let shared_key = libcrypto_rust::mlkem_decapsulate(size, key.handle(), ciphertext.as_slice()).map(Bytes::new);- if let Err(error) = shared_key {- return Err(Exception::Dom(+ let shared_key = shared_key.map_err(|error| {+ Exception::Dom("OperationError",libjs_rust::api::utf16_formatted("Key decapsulation failed: {}", &[&error.message()]),- ));- }-- let shared_key = shared_key.expect("LibCrypto returns the shared key");+ )+ })?;// 5. Return sharedKey.Ok(shared_key)