fetchlet_web/limits.rs
1use crate::{Error, Result};
2
3/// Caller budgets for Web API operations. Each is unlimited when `None`;
4/// the embedder owns the values and documents them with its other limits.
5#[derive(Clone, Debug, Default, PartialEq, Eq)]
6pub struct WebLimits {
7 /// Bytes one `crypto.subtle.digest` call, or one `node:crypto` hash or
8 /// HMAC, hashes.
9 pub digest_bytes: Option<usize>,
10 /// `CompressionStream` and `DecompressionStream` instances open at once
11 /// in an invocation.
12 pub compression_streams: Option<usize>,
13 /// Bytes one `DecompressionStream` produces.
14 pub decompressed_bytes: Option<usize>,
15 /// Modulus length of a generated RSA key, in bits, which bounds the
16 /// time key generation takes.
17 pub rsa_modulus_bits: Option<usize>,
18 /// Iterations of one PBKDF2 derivation.
19 pub pbkdf2_iterations: Option<usize>,
20 /// Working memory of one `node:crypto` scrypt derivation, 128 * r *
21 /// (N + p + 2) bytes as OpenSSL counts it for `maxmem`, which the host
22 /// allocates.
23 pub scrypt_memory_bytes: Option<usize>,
24}
25
26#[cfg_attr(
27 not(any(feature = "compression", feature = "web-crypto")),
28 allow(dead_code)
29)]
30pub(crate) fn check_limit(
31 limit: Option<usize>,
32 observed: usize,
33 resource: &'static str,
34) -> Result<()> {
35 if limit.is_some_and(|limit| observed > limit) {
36 return Err(Error::LimitExceeded(resource));
37 }
38 Ok(())
39}
40
41/// A zeroed output buffer whose length a guest chose. A failed allocation
42/// becomes an error instead of aborting the host process.
43#[cfg_attr(not(feature = "web-crypto"), allow(dead_code))]
44pub(crate) fn zeroed(length: usize) -> Result<Vec<u8>> {
45 let mut bytes = Vec::new();
46 bytes
47 .try_reserve_exact(length)
48 .map_err(|_| Error::Unavailable("memory for the output"))?;
49 bytes.resize(length, 0);
50 Ok(bytes)
51}