Skip to main content

rong_crypto/
lib.rs

1//! # Web Cryptography module
2//!
3//! Installs `globalThis.crypto` ([`Crypto`]) together with the
4//! [`SubtleCrypto`] and [`CryptoKey`] interfaces, following the
5//! [Web Cryptography API](https://w3c.github.io/webcrypto/) and the
6//! `globalThis.crypto` semantics shared by browsers, Deno and workerd.
7//!
8//! ## Implemented
9//!
10//! - `crypto.getRandomValues(typedArray)` and `crypto.randomUUID()`
11//! - `crypto.subtle.digest` - SHA-1, SHA-256, SHA-384, SHA-512
12//! - `crypto.subtle.importKey` / `exportKey` - `raw` and `jwk` (`kty: "oct"`)
13//! - `crypto.subtle.generateKey` - HMAC, AES-GCM, AES-CBC
14//! - `crypto.subtle.sign` / `verify` - HMAC with any of the four hashes
15//! - `crypto.subtle.encrypt` / `decrypt` - AES-GCM (96-bit IV, 128-bit tag)
16//!   and AES-CBC (PKCS#7)
17//! - `crypto.subtle.deriveBits` / `deriveKey` - PBKDF2 and HKDF
18//!
19//! ## Not implemented
20//!
21//! Asymmetric algorithms (RSASSA-PKCS1-v1_5, RSA-PSS, RSA-OAEP, ECDSA, ECDH,
22//! Ed25519, X25519) and AES-CTR/AES-KW are recognized by name and rejected
23//! with a `NotSupportedError` that names the algorithm. Key wrapping
24//! (`wrapKey`/`unwrapKey`) is likewise absent.
25
26mod algorithm;
27mod buffer;
28mod crypto;
29mod error;
30mod hash;
31mod jwk;
32mod key;
33mod ops;
34mod subtle;
35
36use rong::{JSResult, PropertyDescriptor};
37
38pub use crypto::Crypto;
39pub use key::CryptoKey;
40pub use subtle::SubtleCrypto;
41
42/// Register `Crypto`, `SubtleCrypto` and `CryptoKey`, then install the
43/// `globalThis.crypto` instance with its `subtle` member.
44pub fn init(ctx: &rong::JSContext) -> JSResult<()> {
45    buffer::init(ctx)?;
46    ctx.register_class::<CryptoKey>()?;
47    ctx.register_class::<SubtleCrypto>()?;
48    ctx.register_class::<Crypto>()?;
49
50    let crypto = Crypto::instance(ctx)?;
51    // A single `SubtleCrypto` object per `Crypto`, so `crypto.subtle` keeps
52    // its identity across accesses the way the platform does.
53    crypto.define_property(
54        "subtle",
55        PropertyDescriptor::from_rust(ctx, subtle::SubtleCrypto::instance(ctx)?)
56            .enumerable()
57            .readonly(),
58    )?;
59    ctx.global().set("crypto", crypto)?;
60
61    Ok(())
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67    use rong_test::*;
68
69    /// The JavaScript-level conformance suite. It lives next to the crate
70    /// rather than in `tests/unit`, so it is loaded as an inline source.
71    const CRYPTO_SUITE: &str = include_str!("../tests/crypto.js");
72
73    #[test]
74    fn crypto_conformance_suite() {
75        async_run!(|ctx: JSContext| async move {
76            rong_console::init(&ctx)?;
77            rong_encoding::init(&ctx)?;
78            init(&ctx)?;
79
80            let passed = UnitJSRunner::load_source(&ctx, CRYPTO_SUITE)
81                .await?
82                .run()
83                .await?;
84            assert!(passed);
85
86            Ok(())
87        });
88    }
89
90    #[test]
91    fn init_installs_the_crypto_global_once() {
92        run(|ctx| {
93            init(ctx)?;
94            // A second init must be a no-op rather than a duplicate-class error.
95            init(ctx)?;
96
97            let shape: Vec<String> = ctx.eval(Source::from_bytes(
98                r#"[
99                    String(crypto instanceof Crypto),
100                    String(crypto.subtle instanceof SubtleCrypto),
101                    String(crypto.subtle === crypto.subtle),
102                    typeof crypto.getRandomValues,
103                    typeof crypto.randomUUID,
104                    typeof crypto.subtle.digest,
105                    typeof Crypto,
106                    typeof SubtleCrypto,
107                    typeof CryptoKey,
108                ]"#,
109            ))?;
110            assert_eq!(
111                shape,
112                vec![
113                    "true", "true", "true", "function", "function", "function", "function",
114                    "function", "function",
115                ]
116            );
117            Ok(())
118        });
119    }
120
121    #[test]
122    fn get_random_values_fills_only_the_view() {
123        run(|ctx| {
124            init(ctx)?;
125            let result: Vec<i32> = ctx.eval(Source::from_bytes(
126                r#"
127                const backing = new Uint8Array(6);
128                const view = new Uint8Array(backing.buffer, 2, 2);
129                const returned = crypto.getRandomValues(view);
130                [
131                  returned === view ? 1 : 0,
132                  backing[0], backing[1], backing[4], backing[5],
133                ]
134                "#,
135            ))?;
136            assert_eq!(result, vec![1, 0, 0, 0, 0]);
137            Ok(())
138        });
139    }
140
141    #[test]
142    fn get_random_values_reports_spec_error_names() {
143        run(|ctx| {
144            init(ctx)?;
145            let names: Vec<String> = ctx.eval(Source::from_bytes(
146                r#"
147                function nameOf(fn) {
148                  try { fn(); return "no error"; } catch (error) { return error.name; }
149                }
150                [
151                  nameOf(() => crypto.getRandomValues(new Uint8Array(65537))),
152                  nameOf(() => crypto.getRandomValues(new Float32Array(4))),
153                  nameOf(() => crypto.getRandomValues(new Float64Array(4))),
154                  nameOf(() => crypto.getRandomValues({})),
155                  nameOf(() => crypto.getRandomValues(new Uint8Array(65536))),
156                ]
157                "#,
158            ))?;
159            assert_eq!(
160                names,
161                vec![
162                    "QuotaExceededError",
163                    "TypeMismatchError",
164                    "TypeMismatchError",
165                    "TypeMismatchError",
166                    "no error",
167                ]
168            );
169            Ok(())
170        });
171    }
172}