script/dom/
cryptokey.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::ptr::NonNull;
7
8use dom_struct::dom_struct;
9use js::jsapi::{Heap, JSObject, Value};
10use malloc_size_of::MallocSizeOf;
11use script_bindings::conversions::SafeToJSValConvertible;
12
13use crate::dom::bindings::cell::DomRefCell;
14use crate::dom::bindings::codegen::Bindings::CryptoKeyBinding::{
15    CryptoKeyMethods, CryptoKeyPair, KeyType, KeyUsage,
16};
17use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
18use crate::dom::bindings::root::DomRoot;
19use crate::dom::globalscope::GlobalScope;
20use crate::dom::subtlecrypto::KeyAlgorithmAndDerivatives;
21use crate::script_runtime::{CanGc, JSContext};
22
23pub(crate) enum CryptoKeyOrCryptoKeyPair {
24    CryptoKey(DomRoot<CryptoKey>),
25    CryptoKeyPair(CryptoKeyPair),
26}
27
28/// The underlying cryptographic data this key represents
29pub(crate) enum Handle {
30    RsaPrivateKey(rsa::RsaPrivateKey),
31    RsaPublicKey(rsa::RsaPublicKey),
32    P256PrivateKey(p256::SecretKey),
33    P384PrivateKey(p384::SecretKey),
34    P521PrivateKey(p521::SecretKey),
35    P256PublicKey(p256::PublicKey),
36    P384PublicKey(p384::PublicKey),
37    P521PublicKey(p521::PublicKey),
38    X25519PrivateKey(x25519_dalek::StaticSecret),
39    X25519PublicKey(x25519_dalek::PublicKey),
40    Aes128Key(aes::cipher::crypto_common::Key<aes::Aes128>),
41    Aes192Key(aes::cipher::crypto_common::Key<aes::Aes192>),
42    Aes256Key(aes::cipher::crypto_common::Key<aes::Aes256>),
43    HkdfSecret(Vec<u8>),
44    Pbkdf2(Vec<u8>),
45    Hmac(Vec<u8>),
46    Ed25519(Vec<u8>),
47    MlKem512PrivateKey((ml_kem::B32, ml_kem::B32)),
48    MlKem768PrivateKey((ml_kem::B32, ml_kem::B32)),
49    MlKem1024PrivateKey((ml_kem::B32, ml_kem::B32)),
50    MlKem512PublicKey(Box<ml_kem::Encoded<ml_kem::kem::EncapsulationKey<ml_kem::MlKem512Params>>>),
51    MlKem768PublicKey(Box<ml_kem::Encoded<ml_kem::kem::EncapsulationKey<ml_kem::MlKem768Params>>>),
52    MlKem1024PublicKey(
53        Box<ml_kem::Encoded<ml_kem::kem::EncapsulationKey<ml_kem::MlKem1024Params>>>,
54    ),
55    MlDsa44PrivateKey(ml_dsa::B32),
56    MlDsa65PrivateKey(ml_dsa::B32),
57    MlDsa87PrivateKey(ml_dsa::B32),
58    MlDsa44PublicKey(Box<ml_dsa::EncodedVerifyingKey<ml_dsa::MlDsa44>>),
59    MlDsa65PublicKey(Box<ml_dsa::EncodedVerifyingKey<ml_dsa::MlDsa65>>),
60    MlDsa87PublicKey(Box<ml_dsa::EncodedVerifyingKey<ml_dsa::MlDsa87>>),
61    ChaCha20Poly1305Key(chacha20poly1305::Key),
62    Argon2Password(Vec<u8>),
63}
64
65/// <https://w3c.github.io/webcrypto/#cryptokey-interface>
66#[dom_struct]
67pub(crate) struct CryptoKey {
68    reflector_: Reflector,
69
70    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-type>
71    key_type: KeyType,
72
73    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-extractable>
74    extractable: Cell<bool>,
75
76    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-algorithm>
77    ///
78    /// The contents of the [[algorithm]] internal slot shall be, or be derived from, a
79    /// KeyAlgorithm.
80    #[no_trace]
81    algorithm: KeyAlgorithmAndDerivatives,
82
83    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-algorithm_cached>
84    #[ignore_malloc_size_of = "Defined in mozjs"]
85    algorithm_cached: Heap<*mut JSObject>,
86
87    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-usages>
88    ///
89    /// The contents of the [[usages]] internal slot shall be of type Sequence<KeyUsage>.
90    usages: DomRefCell<Vec<KeyUsage>>,
91
92    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-usages_cached>
93    #[ignore_malloc_size_of = "Defined in mozjs"]
94    usages_cached: Heap<*mut JSObject>,
95
96    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-handle>
97    #[no_trace]
98    handle: Handle,
99}
100
101impl CryptoKey {
102    fn new_inherited(
103        key_type: KeyType,
104        extractable: bool,
105        algorithm: KeyAlgorithmAndDerivatives,
106        usages: Vec<KeyUsage>,
107        handle: Handle,
108    ) -> CryptoKey {
109        CryptoKey {
110            reflector_: Reflector::new(),
111            key_type,
112            extractable: Cell::new(extractable),
113            algorithm,
114            algorithm_cached: Heap::default(),
115            usages: DomRefCell::new(usages),
116            usages_cached: Heap::default(),
117            handle,
118        }
119    }
120
121    pub(crate) fn new(
122        global: &GlobalScope,
123        key_type: KeyType,
124        extractable: bool,
125        algorithm: KeyAlgorithmAndDerivatives,
126        usages: Vec<KeyUsage>,
127        handle: Handle,
128        can_gc: CanGc,
129    ) -> DomRoot<CryptoKey> {
130        let crypto_key = reflect_dom_object(
131            Box::new(CryptoKey::new_inherited(
132                key_type,
133                extractable,
134                algorithm.clone(),
135                usages.clone(),
136                handle,
137            )),
138            global,
139            can_gc,
140        );
141
142        let cx = GlobalScope::get_cx();
143
144        // Create and store a cached object of algorithm
145        rooted!(in(*cx) let mut algorithm_object_value: Value);
146        algorithm.safe_to_jsval(cx, algorithm_object_value.handle_mut(), can_gc);
147        crypto_key
148            .algorithm_cached
149            .set(algorithm_object_value.to_object());
150
151        // Create and store a cached object of usages
152        rooted!(in(*cx) let mut usages_object_value: Value);
153        usages.safe_to_jsval(cx, usages_object_value.handle_mut(), can_gc);
154        crypto_key
155            .usages_cached
156            .set(usages_object_value.to_object());
157
158        crypto_key
159    }
160
161    pub(crate) fn algorithm(&self) -> &KeyAlgorithmAndDerivatives {
162        &self.algorithm
163    }
164
165    pub(crate) fn usages(&self) -> Vec<KeyUsage> {
166        self.usages.borrow().clone()
167    }
168
169    pub(crate) fn handle(&self) -> &Handle {
170        &self.handle
171    }
172
173    pub(crate) fn set_extractable(&self, extractable: bool) {
174        self.extractable.set(extractable);
175    }
176
177    pub(crate) fn set_usages(&self, usages: &[KeyUsage]) {
178        *self.usages.borrow_mut() = usages.to_owned();
179
180        // Create and store a cached object of usages
181        let cx = GlobalScope::get_cx();
182        rooted!(in(*cx) let mut usages_object_value: Value);
183        usages.safe_to_jsval(cx, usages_object_value.handle_mut(), CanGc::note());
184        self.usages_cached.set(usages_object_value.to_object());
185    }
186}
187
188impl CryptoKeyMethods<crate::DomTypeHolder> for CryptoKey {
189    /// <https://w3c.github.io/webcrypto/#dom-cryptokey-type>
190    fn Type(&self) -> KeyType {
191        // Reflects the [[type]] internal slot, which contains the type of the underlying key.
192        self.key_type
193    }
194
195    /// <https://w3c.github.io/webcrypto/#dom-cryptokey-extractable>
196    fn Extractable(&self) -> bool {
197        // Reflects the [[extractable]] internal slot, which indicates whether or not the raw
198        // keying material may be exported by the application.
199        self.extractable.get()
200    }
201
202    /// <https://w3c.github.io/webcrypto/#dom-cryptokey-algorithm>
203    fn Algorithm(&self, _cx: JSContext) -> NonNull<JSObject> {
204        // Returns the cached ECMAScript object associated with the [[algorithm]] internal slot.
205        NonNull::new(self.algorithm_cached.get()).unwrap()
206    }
207
208    /// <https://w3c.github.io/webcrypto/#dom-cryptokey-usages>
209    fn Usages(&self, _cx: JSContext) -> NonNull<JSObject> {
210        // Returns the cached ECMAScript object associated with the [[usages]] internal slot, which
211        // indicates which cryptographic operations are permissible to be used with this key.
212        NonNull::new(self.usages_cached.get()).unwrap()
213    }
214}
215
216impl Handle {
217    pub(crate) fn as_bytes(&self) -> &[u8] {
218        match self {
219            Self::Pbkdf2(bytes) => bytes,
220            Self::Hmac(bytes) => bytes,
221            Self::Ed25519(bytes) => bytes,
222            _ => unreachable!(),
223        }
224    }
225}
226
227impl MallocSizeOf for Handle {
228    fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
229        match self {
230            Handle::RsaPrivateKey(private_key) => private_key.size_of(ops),
231            Handle::RsaPublicKey(public_key) => public_key.size_of(ops),
232            Handle::P256PrivateKey(private_key) => private_key.size_of(ops),
233            Handle::P384PrivateKey(private_key) => private_key.size_of(ops),
234            Handle::P521PrivateKey(private_key) => private_key.size_of(ops),
235            Handle::P256PublicKey(public_key) => public_key.size_of(ops),
236            Handle::P384PublicKey(public_key) => public_key.size_of(ops),
237            Handle::P521PublicKey(public_key) => public_key.size_of(ops),
238            Handle::X25519PrivateKey(private_key) => private_key.size_of(ops),
239            Handle::X25519PublicKey(public_key) => public_key.size_of(ops),
240            Handle::Aes128Key(key) => key.size_of(ops),
241            Handle::Aes192Key(key) => key.size_of(ops),
242            Handle::Aes256Key(key) => key.size_of(ops),
243            Handle::HkdfSecret(secret) => secret.size_of(ops),
244            Handle::Pbkdf2(bytes) => bytes.size_of(ops),
245            Handle::Hmac(bytes) => bytes.size_of(ops),
246            Handle::Ed25519(bytes) => bytes.size_of(ops),
247            Handle::MlKem512PrivateKey(seed) => seed.0.size_of(ops) + seed.1.size_of(ops),
248            Handle::MlKem768PrivateKey(seed) => seed.0.size_of(ops) + seed.1.size_of(ops),
249            Handle::MlKem1024PrivateKey(seed) => seed.0.size_of(ops) + seed.1.size_of(ops),
250            Handle::MlKem512PublicKey(public_key) => public_key.size_of(ops),
251            Handle::MlKem768PublicKey(public_key) => public_key.size_of(ops),
252            Handle::MlKem1024PublicKey(public_key) => public_key.size_of(ops),
253            Handle::MlDsa44PrivateKey(seed) => seed.size_of(ops),
254            Handle::MlDsa65PrivateKey(seed) => seed.size_of(ops),
255            Handle::MlDsa87PrivateKey(seed) => seed.size_of(ops),
256            Handle::MlDsa44PublicKey(public_key) => public_key.size_of(ops),
257            Handle::MlDsa65PublicKey(public_key) => public_key.size_of(ops),
258            Handle::MlDsa87PublicKey(public_key) => public_key.size_of(ops),
259            Handle::ChaCha20Poly1305Key(key) => key.size_of(ops),
260            Handle::Argon2Password(password) => password.size_of(ops),
261        }
262    }
263}