script/dom/
crypto.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 dom_struct::dom_struct;
6use js::jsapi::{JSObject, Type};
7use js::rust::CustomAutoRooterGuard;
8use js::typedarray::{ArrayBufferView, ArrayBufferViewU8, TypedArray};
9use servo_rand::{RngCore, ServoRng};
10use uuid::Uuid;
11
12use crate::dom::bindings::cell::DomRefCell;
13use crate::dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods;
14use crate::dom::bindings::error::{Error, Fallible};
15use crate::dom::bindings::reflector::{DomGlobal, Reflector, reflect_dom_object};
16use crate::dom::bindings::root::{DomRoot, MutNullableDom};
17use crate::dom::bindings::str::DOMString;
18use crate::dom::globalscope::GlobalScope;
19use crate::dom::subtlecrypto::SubtleCrypto;
20use crate::script_runtime::{CanGc, JSContext};
21
22// https://developer.mozilla.org/en-US/docs/Web/API/Crypto
23#[dom_struct]
24pub(crate) struct Crypto {
25    reflector_: Reflector,
26    #[no_trace]
27    rng: DomRefCell<ServoRng>,
28    subtle: MutNullableDom<SubtleCrypto>,
29}
30
31impl Crypto {
32    fn new_inherited() -> Crypto {
33        Crypto {
34            reflector_: Reflector::new(),
35            rng: DomRefCell::new(ServoRng::default()),
36            subtle: MutNullableDom::default(),
37        }
38    }
39
40    pub(crate) fn new(global: &GlobalScope, can_gc: CanGc) -> DomRoot<Crypto> {
41        reflect_dom_object(Box::new(Crypto::new_inherited()), global, can_gc)
42    }
43}
44
45impl CryptoMethods<crate::DomTypeHolder> for Crypto {
46    /// <https://w3c.github.io/webcrypto/#dfn-Crypto-attribute-subtle>
47    fn Subtle(&self, can_gc: CanGc) -> DomRoot<SubtleCrypto> {
48        self.subtle
49            .or_init(|| SubtleCrypto::new(&self.global(), can_gc))
50    }
51
52    #[allow(unsafe_code)]
53    // https://w3c.github.io/webcrypto/#Crypto-method-getRandomValues
54    fn GetRandomValues(
55        &self,
56        _cx: JSContext,
57        mut input: CustomAutoRooterGuard<ArrayBufferView>,
58    ) -> Fallible<ArrayBufferView> {
59        let array_type = input.get_array_type();
60
61        if !is_integer_buffer(array_type) {
62            Err(Error::TypeMismatch)
63        } else {
64            let data = unsafe { input.as_mut_slice() };
65            if data.len() > 65536 {
66                return Err(Error::QuotaExceeded {
67                    quota: None,
68                    requested: None,
69                });
70            }
71            self.rng.borrow_mut().fill_bytes(data);
72            let underlying_object = unsafe { input.underlying_object() };
73            TypedArray::<ArrayBufferViewU8, *mut JSObject>::from(*underlying_object)
74                .map_err(|_| Error::JSFailed)
75        }
76    }
77
78    // https://w3c.github.io/webcrypto/#Crypto-method-randomUUID
79    fn RandomUUID(&self) -> DOMString {
80        let uuid = Uuid::new_v4();
81        uuid.hyphenated()
82            .encode_lower(&mut Uuid::encode_buffer())
83            .to_owned()
84            .into()
85    }
86}
87
88fn is_integer_buffer(array_type: Type) -> bool {
89    matches!(
90        array_type,
91        Type::Uint8 |
92            Type::Uint8Clamped |
93            Type::Int8 |
94            Type::Uint16 |
95            Type::Int16 |
96            Type::Uint32 |
97            Type::Int32 |
98            Type::BigInt64 |
99            Type::BigUint64
100    )
101}