Skip to content

Add initial Web Crypto support and QuotaExceededError - #45

Open
karthik2804 wants to merge 1 commit into
bytecodealliance:mainfrom
karthik2804:crypto
Open

karthik2804 wants to merge 1 commit into
bytecodealliance:mainfrom
karthik2804:crypto

Conversation

@karthik2804

Copy link
Copy Markdown
Contributor

This is a first step towards a fuller SubtleCrypto: it adds the crypto global with getRandomValues and randomUUID, and subtle.digest for SHA-1/256/384/512.

Also add QuotaExceededError, the DOMException subclass WebIDL now defines, which getRandomValues throws, and enable the matching WPT suites.

This is a first step towards a fuller `SubtleCrypto`: it adds the `crypto` global with
`getRandomValues` and `randomUUID`, and `subtle.digest` for SHA-1/256/384/512.

Also add `QuotaExceededError`, the `DOMException` subclass WebIDL now defines, which
`getRandomValues` throws, and enable the matching WPT suites.

Signed-off-by: Karthik Ganeshram <kganeshr@akamai.com>
@karthik2804
karthik2804 marked this pull request as ready for review November 17, 2026 13:21

@tschneidereit tschneidereit left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left a whole bunch of feedback, but nevertheless, this is in good shape for the most part. It currently has a major safety issue for no fault of its own though, which I'm fixing over in #46.

Comment on lines +17 to +21
#[webidl_union]
pub enum BufferSource<'a> {
View(ArrayBufferView<'a>),
Buffer(ArrayBuffer<'a>),
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also exists in the web-encoding crate, in decoder-common.rs (as ArrayBufferViewOrArrayBuffer). Please unify both by moving this new definition (because it has the right name) into a shared place. I think you can put it into the js crate's typedarray.rs.

Comment on lines +82 to +90
let value = object.get_property(scope, c"name")?;
if value.is_undefined() {
return Err(throw_type_error(
scope,
c"Algorithm: Missing required property 'name'",
));
}
// Step 2.4: Let _algName_ be the value of the `name` attribute of _initialAlg_.
String::from_jsval_throwing(scope, value, Default::default())?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be made a little bit nicer by introducing an Algorithm union like so:

/// <https://w3c.github.io/webcrypto/#dfn-Algorithm>
#[webidl_dictionary]
pub struct Algorithm {
    pub name: String,
}

With this code then just becoming

Suggested change
let value = object.get_property(scope, c"name")?;
if value.is_undefined() {
return Err(throw_type_error(
scope,
c"Algorithm: Missing required property 'name'",
));
}
// Step 2.4: Let _algName_ be the value of the `name` attribute of _initialAlg_.
String::from_jsval_throwing(scope, value, Default::default())?
Algorithm::from_jsval_throwing(scope, object.to_jsval(scope)?)?.name

Comment on lines +45 to +46
BufferSource::View(view) => view.copy_bytes(scope)?,
BufferSource::Buffer(buffer) => buffer.copy_bytes(scope)?,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These copies aren't needed: you can use {view,buffer}.with_bytes(|b| hash.digest(b)), or perhaps even add an impl to BufferSource that makes with_bytes available on the union itself.

Comment thread Cargo.toml
Comment on lines +48 to +49
sha1 = "0.10"
sha2 = "0.10"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please always make sure you're using the latest versions of dependencies. In this case, 0.11 is available for both of these.

Comment on lines +69 to +71
let mut result = Ok(());
array.with_bytes_mut(|bytes| result = getrandom::fill(bytes));
result.map_err(|e| DOMExceptionError::new("OperationError", e.to_string()))?;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, getrandom::fill is extremely inefficient on WASI :( Instead of using random.get-random-bytes, which is available on both p2 and p3, it calls random.get-random-u64 in a loop. For the max buffer size of 64KB, that means 8192 calls.

Ideally that'd be fixed in the getrandom crate; if you're up for it, opening a PR there and keeping things as-is here would be okay. Otherwise, we should introduce a random module in the platform crate, similar to the existing clock one, and use get-random-bytes directly on p2 and p3, and getrandom only on native.

Also, the three lines here can be merged into a single one (or two, with wrapping, probably):

array.with_bytes_mut(getrandom::fill).map_err(|e| DOMExceptionError::new("OperationError", e.to_string()))?;

// Step 11: Let _result_ be the result of `creating an ArrayBuffer` in _realm_,
// containing _digest_.
// Step 12: Resolve _promise_ with _result_.
// (SHA over an in-memory buffer is cheap next to scheduling it, so steps 7-10 run inline

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately this changes the order of operations. Consider this JS code:

crypto.subtle.digest(a, d).then(B);
Promise.resolve().then(A);

With this implementation, B runs before A, where the spec requires A to run before B. So unfortunately this isn't a shortcut we can really take :(

What you can do instead is return a pending promise and use EventLoop::queue_ready queue a task that resolves it.

let exception = match DOMException::new(scope, message.into(), name.into()) {
Ok(exc) => exc,
Err(_) => return ExnThrown,
let exc_val = if name == "QuotaExceededError" {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feels pretty icky to me. Let's remove it and instead have a ThrowException impl for QuotaExceededError itself (obviously over in `quota_exceeded_error.rs):

impl ThrowException for QuotaExceededError {
    fn throw(self, scope: &Scope<'_>) -> ExnThrown {
        let exc = self.to_jsval(scope).expect("Value conversion doesn't fail");
        js::exception::set_pending(scope, exc, ExceptionStackBehavior::Capture)
    }
}

(Bonus points if you change set_pending to accept an impl ToJSVal<'s>, as I've done lots of methods on e.g. js::Object, and remove the let exc line.)

See my comments on get_random_values on the implications of this change.


/// <https://w3c.github.io/webcrypto/#Crypto-method-getRandomValues>
#[method]
fn get_random_values<'r>(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you apply my suggestion in dom_exception.rs, this method needs to change a bit: the returned error becomes ExnThrown, and the various error return paths need to do the throwing themselves. A simplified version looks like this:

#[method]
fn get_random_values<'r>(
    &self,
    scope: &'r Scope<'_>,
    array: ArrayBufferView<'r>,
) -> Result<ArrayBufferView<'r>, ExnThrown> {
    if !matches!(array.view_kind(), /* integer kinds */) {
        return Err(DOMExceptionError::new("TypeMismatchError", "…").throw(scope));
    }
    if array.byte_length() > MAX_RANDOM_BYTES {
        return Err(QuotaExceededError::new(scope, Some("…".into()), Some(QuotaExceededErrorOptions {..}))?.throw(scope));
    }
    array
        .with_bytes_mut(getrandom::fill)
        .map_err(|e| DOMExceptionError::new("OperationError", e.to_string()).throw(scope))?;
    Ok(array)
}

/// Run the constructor steps: validate _quota_ and _requested_, then build the object's
/// state, whose `DOMException` name is "QuotaExceededError".
///
/// TODO: Rust code can't yet throw a `QuotaExceededError` with a quota or requested. The only

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With my suggested other changes, this entire TODO item goes away, and you can create this error just fine using QuotaExceededError::new. If that all works out, please inline this create function into new again.

///
/// `constructor(optional DOMString message = "", optional QuotaExceededErrorOptions options = {})`
#[constructor]
fn new(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to make the other suggested changes work:

Suggested change
fn new(
pub fn new(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants