Skip to main content

bitwarden_crypto/
slow_crypto_span.rs

1//! Marks slow cryptographic operations (KDFs, RSA, ML-DSA) on the browser performance timeline.
2//!
3//! On WASM, each operation becomes a `performance.measure` entry carrying Chrome DevTools
4//! extensibility metadata, so the DevTools Performance panel shows it in its own track:
5//!
6//! ```text
7//!   ▾ Crypto
8//!     Slow Crypto   [ Argon2id ]          [ RSA decrypt ]   [ ML-DSA sign ]
9//! ```
10//!
11//! Outside of WASM the span compiles to a no-op.
12
13/// A slow cryptographic operation shown on the performance timeline.
14#[derive(Clone, Copy)]
15pub(crate) enum SlowCryptoOp {
16    Pbkdf2,
17    Argon2id,
18    RsaKeyGeneration,
19    RsaEncrypt,
20    RsaDecrypt,
21    MlDsaKeyGeneration,
22    MlDsaExpandSeed,
23    MlDsaSign,
24    MlDsaVerify,
25}
26
27/// Measures a [`SlowCryptoOp`] from creation until drop.
28pub(crate) struct SlowCryptoSpan {
29    /// The operation and its `performance.now()` start time, if the timeline is available.
30    #[cfg(all(feature = "wasm", target_arch = "wasm32"))]
31    entry: Option<(SlowCryptoOp, f64)>,
32}
33
34impl SlowCryptoSpan {
35    /// Starts measuring `op`. Keep the returned guard alive for the duration of the operation.
36    #[must_use]
37    pub(crate) fn start(op: SlowCryptoOp) -> Self {
38        #[cfg(all(feature = "wasm", target_arch = "wasm32"))]
39        {
40            Self {
41                entry: timeline::now().map(|start| (op, start)),
42            }
43        }
44
45        #[cfg(not(all(feature = "wasm", target_arch = "wasm32")))]
46        {
47            let _ = op;
48            Self {}
49        }
50    }
51}
52
53/// Measures `op` for exactly as long as `f` runs.
54pub(crate) fn measure<T>(op: SlowCryptoOp, f: impl FnOnce() -> T) -> T {
55    let _span = SlowCryptoSpan::start(op);
56    f()
57}
58
59impl Drop for SlowCryptoSpan {
60    fn drop(&mut self) {
61        #[cfg(all(feature = "wasm", target_arch = "wasm32"))]
62        {
63            let Some((op, start)) = self.entry else {
64                return;
65            };
66            timeline::measure(op, start);
67        }
68    }
69}
70
71/// Bindings to the `performance` API
72#[cfg(all(feature = "wasm", target_arch = "wasm32"))]
73mod timeline {
74    use wasm_bindgen::prelude::*;
75
76    use super::SlowCryptoOp;
77
78    // Chrome DevTools extensibility API: entries with this metadata get a custom track.
79    const DATA_TYPE: &str = "track-entry";
80    const TRACK_GROUP: &str = "Crypto";
81    const TRACK: &str = "Slow Crypto";
82
83    /// Recorded duration of every RSA decrypt, in milliseconds.
84    ///
85    /// The `rsa` crate's decryption is not constant time (RUSTSEC-2023-0071), so recording the
86    /// measured duration would publish a timing side channel on the private key. The timeline only
87    /// needs to show that a decrypt happened. Roughly one RSA-2048 OAEP decrypt in WASM (V8, Apple
88    /// M-series, `opt-level = "z"`: ~2.7 ms).
89    const RSA_DECRYPT_DURATION_MS: f64 = 3.0;
90
91    #[wasm_bindgen]
92    extern "C" {
93        #[wasm_bindgen(catch, js_namespace = performance, js_name = now)]
94        fn performance_now() -> Result<f64, JsValue>;
95
96        #[wasm_bindgen(catch, js_namespace = performance, js_name = measure)]
97        fn performance_measure(name: &str, options: &JsValue) -> Result<JsValue, JsValue>;
98    }
99
100    pub(super) fn now() -> Option<f64> {
101        performance_now().ok()
102    }
103
104    /// Records `op` from `start` until now (or for a fixed duration, see [`end`]), e.g.
105    /// `performance.measure("Argon2id", { start, end, detail: { devtools: { dataType:
106    /// "track-entry", trackGroup: "Crypto", track: "Slow Crypto" } } })`.
107    pub(super) fn measure(op: SlowCryptoOp, start: f64) {
108        let Some(end) = end(op, start) else {
109            return;
110        };
111
112        let devtools = object(&[
113            ("dataType", DATA_TYPE.into()),
114            ("trackGroup", TRACK_GROUP.into()),
115            ("track", TRACK.into()),
116        ]);
117        let detail = object(&[("devtools", devtools)]);
118        let options = object(&[
119            ("start", start.into()),
120            ("end", end.into()),
121            ("detail", detail),
122        ]);
123
124        // Best effort: a rejected measure must not fail the cryptographic operation.
125        let _ = performance_measure(name(op), &options);
126    }
127
128    /// End of the recorded entry. Fixed for operations whose real duration leaks secrets.
129    fn end(op: SlowCryptoOp, start: f64) -> Option<f64> {
130        match op {
131            SlowCryptoOp::RsaDecrypt => Some(start + RSA_DECRYPT_DURATION_MS),
132            _ => now(),
133        }
134    }
135
136    fn name(op: SlowCryptoOp) -> &'static str {
137        match op {
138            SlowCryptoOp::Pbkdf2 => "PBKDF2",
139            SlowCryptoOp::Argon2id => "Argon2id",
140            SlowCryptoOp::RsaKeyGeneration => "RSA key generation",
141            SlowCryptoOp::RsaEncrypt => "RSA encrypt",
142            SlowCryptoOp::RsaDecrypt => "RSA decrypt",
143            SlowCryptoOp::MlDsaKeyGeneration => "ML-DSA key generation",
144            SlowCryptoOp::MlDsaExpandSeed => "ML-DSA expand seed",
145            SlowCryptoOp::MlDsaSign => "ML-DSA sign",
146            SlowCryptoOp::MlDsaVerify => "ML-DSA verify",
147        }
148    }
149
150    fn object(fields: &[(&str, JsValue)]) -> JsValue {
151        let object = js_sys::Object::new();
152        for (key, value) in fields {
153            let _ = js_sys::Reflect::set(&object, &JsValue::from_str(key), value);
154        }
155        object.into()
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn span_outside_wasm_is_a_no_op() {
165        let span = SlowCryptoSpan::start(SlowCryptoOp::Argon2id);
166        drop(span);
167    }
168
169    #[test]
170    fn measure_returns_closure_result() {
171        assert_eq!(measure(SlowCryptoOp::Pbkdf2, || 42), 42);
172    }
173}