Skip to main content

quickjs_jit_stdlib/llrt/llrt_crypto/subtle/
crypto_key.rs

1// Vendored from LLRT d9fd873e793c (modules/llrt_crypto/src/subtle/crypto_key.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5use std::rc::Rc;
6
7use crate::utils::{clone::StructuredClone, str_enum};
8use rquickjs::{
9    atom::PredefinedAtom,
10    class::{Trace, Tracer},
11    Class, Ctx, Exception, IntoJs, Object, Result, Value,
12};
13
14use crate::crypto::provider::CryptoError;
15
16use super::key_algorithm::KeyAlgorithm;
17
18#[derive(PartialEq, Clone, Copy)]
19pub enum KeyKind {
20    Secret,
21    Private,
22    Public,
23}
24
25str_enum!(KeyKind,Secret => "secret", Private => "private", Public => "public");
26
27#[rquickjs::class]
28#[derive(rquickjs::JsLifetime)]
29pub struct CryptoKey<'js> {
30    pub kind: KeyKind,
31    pub extractable: bool,
32    pub algorithm: KeyAlgorithm,
33    pub name: Box<str>,
34    pub usages: Vec<String>,
35    pub handle: Rc<[u8]>,
36    algorithm_cache: Option<Object<'js>>,
37    usages_cache: Option<Value<'js>>,
38}
39
40impl<'js> CryptoKey<'js> {
41    pub fn new<N, H>(
42        kind: KeyKind,
43        name: N,
44        extractable: bool,
45        algorithm: KeyAlgorithm,
46        usages: Vec<String>,
47        handle: H,
48    ) -> Self
49    where
50        N: Into<Box<str>>,
51        H: Into<Rc<[u8]>>,
52    {
53        Self {
54            kind,
55            extractable,
56            algorithm,
57            name: name.into(),
58            usages,
59            handle: handle.into(),
60            algorithm_cache: None,
61            usages_cache: None,
62        }
63    }
64}
65
66impl<'js> Trace<'js> for CryptoKey<'js> {
67    fn trace<'a>(&self, tracer: Tracer<'a, 'js>) {
68        if let Some(cached) = &self.algorithm_cache {
69            cached.trace(tracer);
70        }
71        if let Some(cached) = &self.usages_cache {
72            cached.trace(tracer);
73        }
74    }
75}
76
77impl<'js> StructuredClone<'js> for CryptoKey<'js> {
78    fn structured_clone(&self, ctx: &Ctx<'js>) -> Result<Value<'js>> {
79        Ok(Class::instance(
80            ctx.clone(),
81            CryptoKey {
82                kind: self.kind,
83                extractable: self.extractable,
84                algorithm: self.algorithm.clone(),
85                name: self.name.clone(),
86                usages: self.usages.clone(),
87                handle: self.handle.clone(),
88                algorithm_cache: None,
89                usages_cache: None,
90            },
91        )?
92        .into_value())
93    }
94}
95
96#[rquickjs::methods]
97impl<'js> CryptoKey<'js> {
98    #[qjs(constructor)]
99    fn constructor(ctx: Ctx<'_>) -> Result<Self> {
100        Err(Exception::throw_type(&ctx, "Illegal constructor"))
101    }
102
103    #[qjs(get, rename = "type")]
104    pub fn get_type(&self) -> &str {
105        self.kind.as_str()
106    }
107
108    #[qjs(get)]
109    pub fn extractable(&self) -> bool {
110        self.extractable
111    }
112
113    #[qjs(prop, rename = PredefinedAtom::SymbolToStringTag, configurable)]
114    pub fn to_string_tag() -> &'static str {
115        stringify!(CryptoKey)
116    }
117
118    #[qjs(get)]
119    pub fn algorithm(&mut self, ctx: Ctx<'js>) -> Result<Value<'js>> {
120        if let Some(cached) = &self.algorithm_cache {
121            return Ok(cached.clone().into_value());
122        }
123        let obj = self.algorithm.as_object(&ctx, self.name.as_ref())?;
124        self.algorithm_cache = Some(obj.clone());
125        Ok(obj.into_value())
126    }
127
128    #[qjs(get)]
129    pub fn usages(&mut self, ctx: Ctx<'js>) -> Result<Value<'js>> {
130        if let Some(cached) = &self.usages_cache {
131            return Ok(cached.clone());
132        }
133        let arr = self.usages.clone().into_js(&ctx)?;
134        self.usages_cache = Some(arr.clone());
135        Ok(arr)
136    }
137}
138
139impl<'js> CryptoKey<'js> {
140    pub fn check_validity(&self, usage: &str) -> std::result::Result<(), CryptoError> {
141        for key in self.usages.iter() {
142            if key == usage {
143                return Ok(());
144            }
145        }
146        Err(CryptoError::InvalidAccess(Some(
147            [
148                "CryptoKey with '",
149                self.name.as_ref(),
150                "', doesn't support '",
151                usage,
152                "'",
153            ]
154            .concat()
155            .into(),
156        )))
157    }
158
159    pub fn check_kind(&self, expected: KeyKind) -> std::result::Result<(), CryptoError> {
160        if self.kind != expected {
161            return Err(CryptoError::InvalidAccess(Some("Invalid key type".into())));
162        }
163
164        Ok(())
165    }
166}