Repository navigation
Add initial Web Crypto support and QuotaExceededError - #45
karthik2804 wants to merge 1 commit into
Conversation
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>
tschneidereit
left a comment
There was a problem hiding this comment.
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.
| #[webidl_union] | ||
| pub enum BufferSource<'a> { | ||
| View(ArrayBufferView<'a>), | ||
| Buffer(ArrayBuffer<'a>), | ||
| } |
There was a problem hiding this comment.
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.
| 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())? |
There was a problem hiding this comment.
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
| 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 |
| BufferSource::View(view) => view.copy_bytes(scope)?, | ||
| BufferSource::Buffer(buffer) => buffer.copy_bytes(scope)?, |
There was a problem hiding this comment.
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.
| sha1 = "0.10" | ||
| sha2 = "0.10" |
There was a problem hiding this comment.
Please always make sure you're using the latest versions of dependencies. In this case, 0.11 is available for both of these.
| let mut result = Ok(()); | ||
| array.with_bytes_mut(|bytes| result = getrandom::fill(bytes)); | ||
| result.map_err(|e| DOMExceptionError::new("OperationError", e.to_string()))?; |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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" { |
There was a problem hiding this comment.
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>( |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
to make the other suggested changes work:
| fn new( | |
| pub fn new( |
This is a first step towards a fuller
SubtleCrypto: it adds thecryptoglobal withgetRandomValuesandrandomUUID, andsubtle.digestfor SHA-1/256/384/512.Also add
QuotaExceededError, theDOMExceptionsubclass WebIDL now defines, whichgetRandomValuesthrows, and enable the matching WPT suites.