Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: encrypt, sign and deriveKey normalize their algorithm by name

orezraey2b9700b0b030
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.html
index a33197fab..e3814d30b 100644
--- a/src/browser/tests/crypto.html
+++ b/src/browser/tests/crypto.html
@@ -2530,6 +2530,203 @@
});
</script>
+<script id=operations-by-name type=module>
+ const state = await testing.async();
+ // encrypt/decrypt/wrapKey, sign/verify and deriveKey's derivedKeyType are
+ // normalized by name: another algorithm's member is ignored, a missing one
+ // of its own is a TypeError, [EnforceRange] members don't wrap, and the
+ // key checks come after. Each line is "case=outcome", as Chrome gives it.
+ const s = crypto.subtle;
+ const out = [];
+ const show = (r) => r instanceof CryptoKey ? `key:${r.type}:${r.algorithm.name}:${r.algorithm.length ?? ""}` : r instanceof ArrayBuffer ? `buf:${r.byteLength}` : String(r);
+ const run = async (label, f) => { try { out.push(label + "=" + show(await f())); } catch (e) { out.push(label + "=" + e.name); } };
+ const data = new Uint8Array(16);
+ const gcmKey = await s.generateKey({ name: "AES-GCM", length: 128 }, false, ["encrypt", "decrypt", "wrapKey"]);
+ const cbcKey = await s.generateKey({ name: "AES-CBC", length: 128 }, false, ["encrypt"]);
+ const ctrKey = await s.generateKey({ name: "AES-CTR", length: 128 }, false, ["encrypt"]);
+ const kw = await s.generateKey({ name: "AES-KW", length: 128 }, false, ["wrapKey"]);
+ const target = await s.generateKey({ name: "AES-GCM", length: 128 }, true, ["encrypt"]);
+ const iv12 = new Uint8Array(12), iv16 = new Uint8Array(16);
+
+ await run("enc GCM ok", () => s.encrypt({ name: "AES-GCM", iv: iv12 }, gcmKey, data));
+ await run("enc GCM string", () => s.encrypt("AES-GCM", gcmKey, data));
+ await run("enc GCM no iv", () => s.encrypt({ name: "AES-GCM" }, gcmKey, data));
+ await run("enc GCM tag 2^32+128", () => s.encrypt({ name: "AES-GCM", iv: iv12, tagLength: 2 ** 32 + 128 }, gcmKey, data));
+ await run("enc GCM tag 256", () => s.encrypt({ name: "AES-GCM", iv: iv12, tagLength: 256 }, gcmKey, data));
+ await run("enc GCM tag 96", () => s.encrypt({ name: "AES-GCM", iv: iv12, tagLength: 96 }, gcmKey, data));
+ await run("enc GCM tag null", () => s.encrypt({ name: "AES-GCM", iv: iv12, tagLength: null }, gcmKey, data));
+ await run("enc GCM stray counter", () => s.encrypt({ name: "AES-GCM", iv: iv12, counter: 5, length: 999 }, gcmKey, data));
+ await run("enc CTR ok", () => s.encrypt({ name: "AES-CTR", counter: iv16, length: 64 }, ctrKey, data));
+ await run("enc CTR len 2^32+64", () => s.encrypt({ name: "AES-CTR", counter: iv16, length: 2 ** 32 + 64 }, ctrKey, data));
+ await run("enc CTR len 256", () => s.encrypt({ name: "AES-CTR", counter: iv16, length: 256 }, ctrKey, data));
+ await run("enc CTR len 129", () => s.encrypt({ name: "AES-CTR", counter: iv16, length: 129 }, ctrKey, data));
+ await run("enc CTR len 0", () => s.encrypt({ name: "AES-CTR", counter: iv16, length: 0 }, ctrKey, data));
+ await run("enc CTR no length", () => s.encrypt({ name: "AES-CTR", counter: iv16 }, ctrKey, data));
+ await run("enc CBC no iv", () => s.encrypt({ name: "AES-CBC" }, cbcKey, data));
+ await run("enc CBC stray tag", () => s.encrypt({ name: "AES-CBC", iv: iv16, tagLength: 2 ** 40 }, cbcKey, data));
+ await run("enc GCM on CBC key", () => s.encrypt({ name: "AES-GCM", iv: iv12 }, cbcKey, data));
+ await run("enc AES-KW", () => s.encrypt("AES-KW", kw, data));
+ await run("enc unknown", () => s.encrypt("foo", gcmKey, data));
+ await run("enc nameless", () => s.encrypt({ iv: iv12 }, gcmKey, data));
+ await run("wrap KW stray iv", () => s.wrapKey("raw", target, kw, { name: "AES-KW", iv: 5 }));
+ await run("wrap GCM string", () => s.wrapKey("raw", target, gcmKey, "AES-GCM"));
+ await run("wrap unknown", () => s.wrapKey("raw", target, gcmKey, "foo"));
+
+ const hmac = await s.generateKey({ name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
+ const ecdsa = await s.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
+ const ed = await s.generateKey("Ed25519", false, ["sign"]);
+ await run("sign HMAC stray hash", () => s.sign({ name: "HMAC", hash: "SHA-999" }, hmac, data));
+ await run("sign HMAC stray saltLength", () => s.sign({ name: "HMAC", saltLength: -5 }, hmac, data));
+ await run("sign ECDSA no hash", () => s.sign({ name: "ECDSA" }, ecdsa.privateKey, data));
+ await run("sign ECDSA string", () => s.sign("ECDSA", ecdsa.privateKey, data));
+ await run("sign ECDSA bad hash", () => s.sign({ name: "ECDSA", hash: "SHA-999" }, ecdsa.privateKey, data));
+ await run("sign PSS no salt", () => s.sign({ name: "RSA-PSS" }, hmac, data));
+ await run("sign PSS salt 2^32", () => s.sign({ name: "RSA-PSS", saltLength: 2 ** 32 }, hmac, data));
+ await run("sign PSS on HMAC key", () => s.sign({ name: "RSA-PSS", saltLength: 32 }, hmac, data));
+ await run("sign Ed448", () => s.sign("Ed448", ed.privateKey, data));
+ await run("sign Ed25519 stray hash", () => s.sign({ name: "Ed25519", hash: "SHA-999" }, ed.privateKey, data));
+ await run("sign unknown", () => s.sign("foo", hmac, data));
+
+ const pb = await s.importKey("raw", data, "PBKDF2", false, ["deriveKey"]);
+ const pbp = { name: "PBKDF2", hash: "SHA-256", salt: data, iterations: 1 };
+ const ecdh = await s.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveKey"]);
+ const x = await s.generateKey("X25519", false, ["deriveKey"]);
+ const dk = (type, ext, usages, algo = pbp, key = pb) => s.deriveKey(algo, key, type, ext, usages);
+ await run("dk AES len 2^32+128", () => dk({ name: "AES-GCM", length: 2 ** 32 + 128 }, true, ["encrypt"]));
+ await run("dk AES len 100", () => dk({ name: "AES-GCM", length: 100 }, true, ["encrypt"]));
+ await run("dk AES no length", () => dk({ name: "AES-GCM" }, true, ["encrypt"]));
+ await run("dk AES string", () => dk("AES-GCM", true, ["encrypt"]));
+ await run("dk AES stray hash", () => dk({ name: "AES-GCM", length: 128, hash: "SHA-999" }, true, ["encrypt"]));
+ await run("dk HMAC length 0", () => dk({ name: "HMAC", hash: "SHA-256", length: 0 }, true, ["sign"]));
+ await run("dk HMAC ok", () => dk({ name: "HMAC", hash: "SHA-256" }, true, ["sign"]));
+ await run("dk HKDF from PBKDF2", () => dk("HKDF", false, ["deriveBits"]));
+ await run("dk HKDF from ECDH", () => dk("HKDF", false, ["deriveBits"], { name: "ECDH", public: ecdh.publicKey }, ecdh.privateKey));
+ await run("dk HKDF from X25519", () => dk({ name: "HKDF" }, false, ["deriveKey"], { name: "X25519", public: x.publicKey }, x.privateKey));
+ await run("dk HKDF extractable", () => dk("HKDF", true, ["deriveBits"], { name: "ECDH", public: ecdh.publicKey }, ecdh.privateKey));
+ await run("dk PBKDF2 from ECDH", () => dk("PBKDF2", false, ["deriveBits"], { name: "ECDH", public: ecdh.publicKey }, ecdh.privateKey));
+ await run("dk ECDSA", () => dk({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]));
+ await run("dk unknown", () => dk("foo", true, ["sign"]));
+ const expected = [
+ "enc GCM ok=buf:32",
+ "enc GCM string=TypeError",
+ "enc GCM no iv=TypeError",
+ "enc GCM tag 2^32+128=TypeError",
+ "enc GCM tag 256=TypeError",
+ "enc GCM tag 96=buf:28",
+ "enc GCM tag null=OperationError",
+ "enc GCM stray counter=buf:32",
+ "enc CTR ok=buf:16",
+ "enc CTR len 2^32+64=TypeError",
+ "enc CTR len 256=TypeError",
+ "enc CTR len 129=OperationError",
+ "enc CTR len 0=OperationError",
+ "enc CTR no length=TypeError",
+ "enc CBC no iv=TypeError",
+ "enc CBC stray tag=buf:32",
+ "enc GCM on CBC key=InvalidAccessError",
+ "enc AES-KW=NotSupportedError",
+ "enc unknown=NotSupportedError",
+ "enc nameless=TypeError",
+ "wrap KW stray iv=buf:24",
+ "wrap GCM string=TypeError",
+ "wrap unknown=NotSupportedError",
+ "sign HMAC stray hash=buf:32",
+ "sign HMAC stray saltLength=buf:32",
+ "sign ECDSA no hash=TypeError",
+ "sign ECDSA string=TypeError",
+ "sign ECDSA bad hash=NotSupportedError",
+ "sign PSS no salt=TypeError",
+ "sign PSS salt 2^32=TypeError",
+ "sign PSS on HMAC key=InvalidAccessError",
+ "sign Ed448=NotSupportedError",
+ "sign Ed25519 stray hash=buf:64",
+ "sign unknown=NotSupportedError",
+ "dk AES len 2^32+128=TypeError",
+ "dk AES len 100=OperationError",
+ "dk AES no length=TypeError",
+ "dk AES string=TypeError",
+ "dk AES stray hash=key:secret:AES-GCM:128",
+ "dk HMAC length 0=TypeError",
+ "dk HMAC ok=key:secret:HMAC:512",
+ "dk HKDF from PBKDF2=OperationError",
+ "dk HKDF from ECDH=key:secret:HKDF:",
+ "dk HKDF from X25519=key:secret:HKDF:",
+ "dk HKDF extractable=SyntaxError",
+ "dk PBKDF2 from ECDH=key:secret:PBKDF2:",
+ "dk ECDSA=NotSupportedError",
+ "dk unknown=NotSupportedError"
+ ];
+
+ state.resolve();
+ await state.done(() => {
+ for (let i = 0; i < expected.length; i++) {
+ testing.expectEqual(expected[i], out[i]);
+ }
+ });
+</script>
+
+<script id=buffers-after-normalization type=module>
+ const state = await testing.async();
+ // An algorithm is normalized before the operation reads its buffers, and
+ // its name is read once: a getter on it that transfers the data, keyData or
+ // wrapped key leaves the operation with an empty buffer, not the old bytes.
+ // The buffers' types are still checked first. As Chrome gives each case.
+ const s = crypto.subtle; const out = [];
+ const show = (r) => r instanceof CryptoKey ? `key:${r.algorithm.name}` : r instanceof ArrayBuffer ? `buf:${r.byteLength}` : String(r);
+ const run = async (label, f) => { try { out.push(label + "=" + show(await f())); } catch (e) { out.push(label + "=" + e.name); } };
+ const gcm = await s.generateKey({ name: "AES-GCM", length: 128 }, false, ["encrypt"]);
+ const hmac = await s.generateKey({ name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
+ const kw = await s.generateKey({ name: "AES-KW", length: 128 }, true, ["wrapKey", "unwrapKey"]);
+ const target = await s.generateKey({ name: "AES-GCM", length: 128 }, true, ["encrypt"]);
+ const getterAlgo = (base, buf) => ({ ...base, get name() { buf.buffer.transfer(); return base.name; } });
+ let data = new Uint8Array(16);
+ await run("encrypt transferred", () => s.encrypt(getterAlgo({ name: "AES-GCM", iv: new Uint8Array(12) }, data), gcm, data));
+ data = new Uint8Array(16);
+ await run("sign transferred", () => s.sign(getterAlgo({ name: "HMAC" }, data), hmac, data));
+ let keyData = new Uint8Array(16);
+ await run("importKey transferred", () => s.importKey("raw", keyData, getterAlgo({ name: "AES-GCM" }, keyData), true, ["encrypt"]));
+ const wrapped = new Uint8Array(await s.wrapKey("raw", target, kw, "AES-KW"));
+ await run("unwrapKey transferred", () => s.unwrapKey("raw", wrapped, kw, getterAlgo({ name: "AES-KW" }, wrapped), "AES-GCM", true, ["encrypt"]));
+ let getterCalls = 0;
+ await run("name read once", async () => { await s.encrypt({ iv: new Uint8Array(12), get name() { getterCalls++; return "AES-GCM"; } }, gcm, new Uint8Array(4)); return getterCalls; });
+ await run("sign string data", () => s.sign("HMAC", hmac, "abc"));
+ await run("encrypt bad data bad algo", () => s.encrypt("foo", gcm, 5));
+ // A BufferSource member is copied once the whole dictionary is read, so a
+ // later member's getter that transfers it leaves it empty (the spec's
+ // order; Chrome reads AES-GCM's tagLength before its iv, and keeps the iv).
+ const hk = await s.importKey("raw", new Uint8Array(16).fill(3), "HKDF", false, ["deriveBits"]);
+ const salt = new Uint8Array(8).fill(4);
+ const fullInfo = await s.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: new Uint8Array(5).fill(5) }, hk, 128);
+ await run("hkdf info transferred by salt", async () => {
+ const info = new Uint8Array(5).fill(5);
+ const bits = await s.deriveBits({ name: "HKDF", hash: "SHA-256", info, get salt() { info.buffer.transfer(); return salt; } }, hk, 128);
+ const empty = await s.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: new Uint8Array(0) }, hk, 128);
+ return new Uint8Array(bits).join() === new Uint8Array(empty).join() && new Uint8Array(bits).join() !== new Uint8Array(fullInfo).join();
+ });
+ await run("gcm iv transferred by tagLength", () => {
+ const iv = new Uint8Array(12);
+ return s.encrypt({ name: "AES-GCM", iv, get tagLength() { iv.buffer.transfer(); return 128; } }, gcm, new Uint8Array(4));
+ });
+ const expected = [
+ "encrypt transferred=buf:16",
+ "sign transferred=buf:32",
+ "importKey transferred=DataError",
+ "unwrapKey transferred=OperationError",
+ "name read once=1",
+ "sign string data=TypeError",
+ "encrypt bad data bad algo=TypeError",
+ "hkdf info transferred by salt=true",
+ "gcm iv transferred by tagLength=OperationError"
+ ];
+
+ state.resolve();
+ await state.done(() => {
+ for (let i = 0; i < expected.length; i++) {
+ testing.expectEqual(expected[i], out[i]);
+ }
+ });
+</script>
+
<script id="digest" type=module>
const state = await testing.async();
async function hash(algo, data) {
diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zig
index 5de7a20b5..3570a3906 100644
--- a/src/browser/webapi/SubtleCrypto.zig
+++ b/src/browser/webapi/SubtleCrypto.zig
@@ -114,13 +114,22 @@ fn generateKeyFromName(
pub fn importKey(
_: *const SubtleCrypto,
format: []const u8,
- key_data: algorithm.KeyData,
+ key_data_value: js.Value,
algo_value: js.Value,
extractable: bool,
key_usages: []const []const u8,
exec: *const Execution,
) !js.Promise {
- const algo = try algorithm.Import.fromJs(algo_value, exec.js.local.?);
+ const local = exec.js.local.?;
+ // keyData converts first (a JWK's members are read then), but a buffer's
+ // bytes are only read after the algorithm is normalized (bufferBytes).
+ var key_data = local.jsValueToZig(algorithm.KeyData, key_data_value) catch |err| {
+ return algorithm.conversionError(err, local, "keyData is neither a BufferSource nor a JsonWebKey");
+ };
+ const algo = try algorithm.Import.fromJs(algo_value, local);
+ if (key_data == .bytes) {
+ key_data = .{ .bytes = .{ .values = try bufferBytes(key_data_value, local) } };
+ }
return importNormalized(format, key_data, algo, extractable, key_usages, exec);
}
@@ -438,7 +447,7 @@ pub fn deriveKey(
_: *const SubtleCrypto,
algo_value: js.Value,
base_key: *const CryptoKey,
- derived: algorithm.DerivedKey,
+ derived_value: js.Value,
extractable: bool,
key_usages: []const []const u8,
exec: *const Execution,
@@ -446,29 +455,26 @@ pub fn deriveKey(
const local = exec.js.local.?;
// The algorithm is normalized before derivedKeyType.
const algo = try algorithm.Derive.fromJs(algo_value, local);
+ const derived = try algorithm.DerivedKey.fromJs(derived_value, local);
// The base key's deriveKey usage (not deriveBits) gates this operation.
const usage_ok = base_key.canDeriveKey();
switch (derived) {
- .keyed => |k| {
- if (AES.canonicalName(k.name) == null) {
- return error.NotSupported;
+ .aes => |a| {
+ // "Get key length": an AES key is 128, 192 or 256 bits.
+ const length = a.length.value;
+ if (length != 128 and length != 192 and length != 256) {
+ return error.OperationError;
}
- const bits = try deriveRaw(algo, base_key, k.length, usage_ok, exec);
- return AES.import(k.name, bits, extractable, key_usages, exec);
+ const bits = try deriveRaw(algo, base_key, length, usage_ok, exec);
+ return AES.import(a.name, bits, extractable, key_usages, exec);
},
.hmac => |h| {
- // This shape ({name, hash, length?}) also matches an AES algorithm
- // carrying a stray `hash`, or another algorithm's: go by the name.
- if (AES.canonicalName(h.name) != null) {
- const length = try HMAC.lengthParam(h.length, local) orelse return local.typeError("AES requires a length");
- const bits = try deriveRaw(algo, base_key, length, usage_ok, exec);
- return AES.import(h.name, bits, extractable, key_usages, exec);
- }
- if (!eqlIgnoreCase(h.name, "HMAC")) {
- return error.NotSupported;
- }
const requested = try HMAC.lengthParam(h.length, local);
+ // "Get key length": a present length must be non-zero.
+ if (requested == 0) {
+ return local.typeError("HMAC length must not be zero");
+ }
const hash_name = try h.hash.canonical(local);
const hash_md = crypto.findDigest(hash_name) catch return error.NotSupported;
// Default length, per spec, is the hash's block size (in bits).
@@ -476,10 +482,11 @@ pub fn deriveKey(
const bits = try deriveRaw(algo, base_key, length, usage_ok, exec);
return HMAC.import(hash_name, bits, length, extractable, key_usages, exec);
},
- .nameless => return local.typeError(missing_name),
- .object, .name => {
- log.debug(.not_implemented, "SubtleCrypto.deriveKey", .{});
- return error.NotSupported;
+ // HKDF and PBKDF2 have no key length: the whole derivation, which only
+ // ECDH and X25519 can give (PBKDF2 and HKDF need a length).
+ .named => {
+ const bits = try deriveRaw(algo, base_key, null, usage_ok, exec);
+ return importNormalized("raw", .{ .bytes = .{ .values = bits } }, .{ .named = derived.named }, extractable, key_usages, exec);
},
}
}
@@ -518,26 +525,32 @@ fn deriveRaw(
/// Encrypts data with the given key and algorithm.
pub fn encrypt(
_: *const SubtleCrypto,
- algo: algorithm.Encrypt,
+ algo_value: js.Value,
key: *CryptoKey,
- data: js.TypedArray(u8),
+ data_value: js.Value,
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const out = try cryptBytes(algo, key, data.values, .encrypt, exec);
+ try checkBufferSource(data_value, local);
+ const algo = try algorithm.Encrypt.fromJs(algo_value, local, false);
+ const data = try bufferBytes(data_value, local);
+ const out = try cryptBytes(algo, key, data, .encrypt, exec);
return local.resolvePromise(js.ArrayBuffer{ .values = out });
}
/// Decrypts data with the given key and algorithm.
pub fn decrypt(
_: *const SubtleCrypto,
- algo: algorithm.Encrypt,
+ algo_value: js.Value,
key: *CryptoKey,
- data: js.TypedArray(u8),
+ data_value: js.Value,
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const out = try cryptBytes(algo, key, data.values, .decrypt, exec);
+ try checkBufferSource(data_value, local);
+ const algo = try algorithm.Encrypt.fromJs(algo_value, local, false);
+ const data = try bufferBytes(data_value, local);
+ const out = try cryptBytes(algo, key, data, .decrypt, exec);
return local.resolvePromise(js.ArrayBuffer{ .values = out });
}
@@ -548,12 +561,12 @@ pub fn wrapKey(
format: []const u8,
key: *CryptoKey,
wrapping_key: *CryptoKey,
- algo: algorithm.Encrypt,
+ algo_value: js.Value,
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const name = try wrapAlgorithmName(algo, local);
- try checkWrappingKey(name, wrapping_key, .wrap);
+ const algo = try algorithm.Encrypt.fromJs(algo_value, local, true);
+ try checkWrappingKey(algo.algoName(), wrapping_key, .wrap);
const bytes = switch (try exportAs(format, key, exec)) {
.bytes => |bytes| bytes,
@@ -568,21 +581,23 @@ pub fn wrapKey(
pub fn unwrapKey(
_: *const SubtleCrypto,
format: []const u8,
- wrapped_key: js.TypedArray(u8),
+ wrapped_key_value: js.Value,
unwrapping_key: *CryptoKey,
- algo: algorithm.Encrypt,
+ algo_value: js.Value,
unwrapped_key_value: js.Value,
extractable: bool,
key_usages: []const []const u8,
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const name = try wrapAlgorithmName(algo, local);
+ try checkBufferSource(wrapped_key_value, local);
+ const algo = try algorithm.Encrypt.fromJs(algo_value, local, true);
// The unwrapped key's algorithm is normalized next, before the key checks.
const unwrapped_key_algo = try algorithm.Import.fromJs(unwrapped_key_value, local);
- try checkWrappingKey(name, unwrapping_key, .unwrap);
+ const wrapped_key = try bufferBytes(wrapped_key_value, local);
+ try checkWrappingKey(algo.algoName(), unwrapping_key, .unwrap);
- const bytes = try cryptBytes(algo, unwrapping_key, wrapped_key.values, .unwrap, exec);
+ const bytes = try cryptBytes(algo, unwrapping_key, wrapped_key, .unwrap, exec);
const key_data: algorithm.KeyData = if (std.mem.eql(u8, format, "jwk"))
.{ .jwk = try parseJwk(bytes, exec) }
else
@@ -592,6 +607,25 @@ pub fn unwrapKey(
return importNormalized(format, key_data, unwrapped_key_algo, extractable, key_usages, exec);
}
+/// A BufferSource argument taken as a value. Its type is checked when the
+/// operation is called (a TypeError, as WebIDL's conversion gives), but its
+/// bytes are read with `bufferBytes` only once the algorithm is normalized:
+/// normalizing runs the page's getters, which can transfer the buffer, and
+/// its bytes must then read as the now-empty buffer rather than through a
+/// pointer into a moved backing store.
+fn checkBufferSource(value: js.Value, local: *const js.Local) !void {
+ if (!value.isArrayBuffer() and !value.isArrayBufferView()) {
+ return local.typeError("expected an ArrayBuffer or ArrayBufferView");
+ }
+}
+
+fn bufferBytes(value: js.Value, local: *const js.Local) ![]const u8 {
+ const buffer = local.jsValueToZig(js.TypedArray(u8), value) catch |err| {
+ return algorithm.conversionError(err, local, "expected an ArrayBuffer or ArrayBufferView");
+ };
+ return buffer.values;
+}
+
/// What `cryptBytes` is for, which decides the direction and the usage the key
/// needs.
const CryptUse = enum {
@@ -614,17 +648,6 @@ const CryptUse = enum {
}
};
-/// The name of a wrapKey/unwrapKey algorithm, normalized first: one without a
-/// name is a TypeError, one that can't wrap (AES-KW) or encrypt (RSA-OAEP,
-/// AES-CBC/CTR/GCM) NotSupportedError.
-fn wrapAlgorithmName(algo: algorithm.Encrypt, local: *const js.Local) ![]const u8 {
- const name = algo.algoName() orelse return local.typeError(missing_name);
- if (!eqlIgnoreCase(name, "RSA-OAEP") and AES.canonicalName(name) == null) {
- return error.NotSupported;
- }
- return name;
-}
-
/// The checks wrapKey/unwrapKey make on the wrapping key before touching the
/// other key, in the spec's order: the same algorithm as the wrapping key, and
/// the wrapKey/unwrapKey usage.
@@ -661,54 +684,36 @@ fn cryptBytes(
use: CryptUse,
exec: *const Execution,
) ![]const u8 {
- const name = algo.algoName() orelse return exec.js.local.?.typeError(missing_name);
- // RSA-OAEP is handled before the switch: it may arrive as a bare string
- // ("RSA-OAEP"), which would hit `.name => NotSupported` below. An RSA key
- // used with another algorithm's name falls through to AES.crypt, which
- // rejects the key type. The other RSA algorithms don't encrypt, and end
- // up NotSupported below.
- if (eqlIgnoreCase(name, "RSA-OAEP")) {
- const label: []const u8 = switch (algo) {
- .params => |p| if (p.label) |l| l.values else "",
- .name, .nameless => "",
- };
- return RSA.crypt(key, data, label, use.encrypting(), use.usage(), exec);
- }
-
- // AES-KW has no encrypt/decrypt, only its key wrap; its params are just
- // the name, so a bare string is fine.
- if (eqlIgnoreCase(name, "AES-KW")) {
- if (use == .encrypt or use == .decrypt) {
- return error.NotSupported;
- }
- return AES.keyWrap(key, data, use.encrypting(), use.usage(), exec);
+ switch (algo) {
+ .rsa_oaep => |p| {
+ const label: []const u8 = if (p.label) |l| l.values else "";
+ return RSA.crypt(key, data, label, use.encrypting(), use.usage(), exec);
+ },
+ // AES-KW has no encrypt/decrypt (fromJs only allows it for wrapping).
+ .aes_kw => return AES.keyWrap(key, data, use.encrypting(), use.usage(), exec),
+ .aes => |params| return AES.crypt(params, key, data, use.encrypting(), use.usage(), exec),
}
-
- const params = switch (algo) {
- .params => |p| p,
- // A bare string identifier carries no iv/counter, so it can't drive AES.
- .name, .nameless => return error.NotSupported,
- };
- return AES.crypt(params, key, data, use.encrypting(), use.usage(), exec);
}
/// Generate a digital signature.
pub fn sign(
_: *const SubtleCrypto,
/// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/sign#algorithm
- algo: algorithm.Sign,
+ algo_value: js.Value,
key: *CryptoKey,
- data: []const u8, // ArrayBuffer.
+ data_value: js.Value,
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const name = algo.algoName() orelse return local.typeError(missing_name);
- const params = try signParams(name, algo, local);
- try checkSigningKey(name, key, CryptoKey.Usages.sign);
+ try checkBufferSource(data_value, local);
+ const algo = try algorithm.Sign.fromJs(algo_value, local);
+ const data = try bufferBytes(data_value, local);
+ const hash_name = try algo.hashName(local);
+ try checkSigningKey(algo.algoName(), key, CryptoKey.Usages.sign);
const signature = switch (key._type) {
.hmac => try HMAC.sign(key, data, exec),
- .rsa => try RSA.sign(key, data, params.salt_length, exec),
- .ec => try EC.sign(key, data, params.hash orelse return error.OperationError, exec),
+ .rsa => try RSA.sign(key, data, algo.saltLength(), exec),
+ .ec => try EC.sign(key, data, hash_name orelse return error.OperationError, exec),
.ed25519 => try OKP.sign(key, data, exec),
// A signing algorithm with no sign here yet (Ed448).
else => {
@@ -722,20 +727,24 @@ pub fn sign(
/// Verify a digital signature.
pub fn verify(
_: *const SubtleCrypto,
- algo: algorithm.Sign,
+ algo_value: js.Value,
key: *const CryptoKey,
- signature: []const u8, // ArrayBuffer.
- data: []const u8, // ArrayBuffer.
+ signature_value: js.Value,
+ data_value: js.Value,
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const name = algo.algoName() orelse return local.typeError(missing_name);
- const params = try signParams(name, algo, local);
- try checkSigningKey(name, key, CryptoKey.Usages.verify);
+ try checkBufferSource(signature_value, local);
+ try checkBufferSource(data_value, local);
+ const algo = try algorithm.Sign.fromJs(algo_value, local);
+ const signature = try bufferBytes(signature_value, local);
+ const data = try bufferBytes(data_value, local);
+ const hash_name = try algo.hashName(local);
+ try checkSigningKey(algo.algoName(), key, CryptoKey.Usages.verify);
const valid = switch (key._type) {
.hmac => try HMAC.verify(key, signature, data),
- .rsa => try RSA.verify(key, signature, data, params.salt_length),
- .ec => try EC.verify(key, signature, data, params.hash orelse return error.OperationError),
+ .rsa => try RSA.verify(key, signature, data, algo.saltLength()),
+ .ec => try EC.verify(key, signature, data, hash_name orelse return error.OperationError),
.ed25519 => try OKP.verify(key, signature, data),
// A signing algorithm with no verify here yet (Ed448).
else => {
@@ -746,53 +755,11 @@ pub fn verify(
return local.resolvePromise(valid);
}
-/// The members of a sign/verify algorithm that normalization converts:
-/// RSA-PSS's `saltLength` (RsaPssParams) and ECDSA's `hash` (EcdsaParams).
-/// The other algorithms ignore them.
-const SignParams = struct {
- salt_length: ?u32 = null,
- /// A canonical hash name.
- hash: ?[]const u8 = null,
-};
-
-/// Normalizes `algo`'s params, before the key checks: a missing member, a
-/// saltLength outside [EnforceRange] unsigned long or a hash that isn't an
-/// algorithm identifier is a TypeError, an unknown hash NotSupportedError.
-fn signParams(name: []const u8, algo: algorithm.Sign, local: *const js.Local) !SignParams {
- if (eqlIgnoreCase(name, "RSA-PSS")) {
- const value = algo.saltLength() orelse return local.typeError("RSA-PSS requires a saltLength");
- const salt_length = js.enforceRange(u32, try value.toF64()) catch return local.typeError("saltLength is out of range");
- return .{ .salt_length = salt_length };
- }
- if (eqlIgnoreCase(name, "ECDSA")) {
- const value = algo.hash() orelse return local.typeError("ECDSA requires a hash");
- return .{ .hash = common.canonicalHash(try hashName(value, local)) orelse return error.NotSupported };
- }
- return .{};
-}
-
-/// The name of a HashAlgorithmIdentifier, `(object or DOMString)`, converted
-/// as algorithm.Hash: an object's `name`, required (a TypeError without one),
-/// or the value as a string.
-fn hashName(value: js.Value, local: *const js.Local) ![]const u8 {
- const hash = local.jsValueToZig(algorithm.Hash, value) catch |err| switch (err) {
- // The page's own exception (a throwing getter or toString), pending.
- error.JsException => return err,
- else => return local.typeError("hash is not an algorithm identifier"),
- };
- return hash.name(local);
-}
-
-/// The checks sign/verify make before the algorithm's own, in the spec's
-/// order: an algorithm that signs (else NotSupported), the key's own algorithm,
-/// and the sign or verify usage (else InvalidAccessError). The names match
-/// case-insensitively, as algorithm normalization does.
+/// The checks sign/verify make after normalizing their algorithm, in the
+/// spec's order: the key's own algorithm, and the sign or verify usage (else
+/// InvalidAccessError). The names match case-insensitively, as normalization
+/// does.
fn checkSigningKey(name: []const u8, key: *const CryptoKey, usage: u8) !void {
- const signing = [_][]const u8{ "HMAC", "RSASSA-PKCS1-v1_5", "RSA-PSS", "ECDSA", "Ed25519", "Ed448" };
- for (signing) |s| {
- if (eqlIgnoreCase(name, s)) break;
- } else return error.NotSupported;
-
if (!eqlIgnoreCase(name, key._algorithm.name)) {
return error.InvalidAccessError;
}
diff --git a/src/browser/webapi/crypto/algorithm.zig b/src/browser/webapi/crypto/algorithm.zig
index be2ab8cb6..36ca0add7 100644
--- a/src/browser/webapi/crypto/algorithm.zig
+++ b/src/browser/webapi/crypto/algorithm.zig
@@ -180,18 +180,33 @@ pub const Derive = union(enum) {
};
};
-/// The `derivedKeyType` argument to `deriveKey()` — the algorithm of the key to
-/// produce. HMAC carries a hash; AES carries a length. Probed in that order so
-/// the more specific shapes win.
+/// The `derivedKeyType` argument to `deriveKey()`, normalized by name as Init
+/// is, for both "importKey" and "get key length": AES with its required
+/// `length` (an [EnforceRange] unsigned short), HMAC with its hash and
+/// optional `length`, HKDF and PBKDF2 with just their name. Another algorithm
+/// has no key length, so it's NotSupportedError.
pub const DerivedKey = union(enum) {
+ aes: struct { length: js.EnforceRange(u16), name: []const u8 },
/// `length` as in Import.hmac.
hmac: struct { hash: Hash, length: ?js.Value = null, name: []const u8 },
- keyed: struct { length: u32, name: []const u8 },
- object: struct { name: []const u8 },
- /// An object without a `name`: a TypeError, as for every algorithm
- /// identifier. Probed before the string, which would coerce it.
- nameless: js.Object,
- name: []const u8,
+ /// HKDF or PBKDF2, whose key length is null: the whole derivation.
+ named: []const u8,
+
+ pub fn fromJs(value: js.Value, local: *const js.Local) !DerivedKey {
+ const name = try identifierName(value, local);
+ if (isOneOf(name, &.{ "AES-CTR", "AES-CBC", "AES-GCM", "AES-KW" })) {
+ return .{ .aes = try convert(@FieldType(DerivedKey, "aes"), value, name, local) };
+ }
+ if (isOneOf(name, &.{"HMAC"})) {
+ const params = try convert(@FieldType(DerivedKey, "hmac"), value, name, local);
+ _ = try params.hash.canonical(local);
+ return .{ .hmac = params };
+ }
+ if (isOneOf(name, &.{ "HKDF", "PBKDF2" })) {
+ return .{ .named = name };
+ }
+ return error.NotSupported;
+ }
};
/// Algorithm for `importKey()` and unwrapKey's unwrapped key, normalized as
@@ -286,6 +301,14 @@ fn isOneOf(name: []const u8, comptime names: []const []const u8) bool {
return false;
}
+/// An optional [EnforceRange] member kept as a value (absent or undefined is
+/// null), converted to `T`: out of range is a TypeError. null converts to 0,
+/// as WebIDL does, where an optional `?T` member would read it as absent.
+fn rangeMember(comptime T: type, value: ?js.Value, local: *const js.Local) !?T {
+ const v = value orelse return null;
+ return js.enforceRange(T, try v.toF64()) catch local.typeError("algorithm member is out of range");
+}
+
/// The error of a failed conversion of a page value: the page's own pending
/// exception, or running out of memory, stays as is; anything else is a
/// TypeError with `message`.
@@ -298,18 +321,23 @@ pub fn conversionError(err: anyerror, local: *const js.Local, message: []const u
/// `value` as the params dictionary `T` of the algorithm called `name`. The
/// name was read once already, to pick `T`, and isn't read again: a getter on
-/// it runs once, as in browsers, so it can't answer another algorithm's name
-/// for the params than the one that picked them. Each other member is read in
-/// order: absent or undefined takes its default, or null if optional, and is
-/// otherwise a TypeError, as is a value that doesn't convert (out of an
-/// [EnforceRange] range, say). A string identifier has no members, so it only
-/// converts to a dictionary with no required one (as `{name: value}` would).
-/// The page's own exception stays pending.
+/// it runs once, as in browsers (WPT's "transferred ... during call" tests
+/// transfer a buffer from it). Each other member is read in order: absent or
+/// undefined takes its default, or null if optional, and is otherwise a
+/// TypeError, as is a value that doesn't convert. A string identifier has no
+/// members, so it only converts to a dictionary with no required one (as
+/// `{name: value}` would). The page's own exception stays pending.
+///
+/// A BufferSource member (an iv, a salt, ...) is checked when it's read, but,
+/// as normalization asks, its bytes are copied once every member is read: a
+/// later member's getter can transfer it, and it then copies as empty rather
+/// than leaving a pointer into a moved backing store.
fn convert(comptime T: type, value: js.Value, name: []const u8, local: *const js.Local) !T {
const object: ?js.Object = if (value.isObject()) value.toObject() else null;
var out: T = undefined;
const info = @typeInfo(T).@"struct";
- inline for (info.field_names, info.field_types, info.field_attrs) |field_name, FieldType, attrs| {
+ var buffers: [info.field_names.len]?js.Value = @splat(null);
+ inline for (info.field_names, info.field_types, info.field_attrs, 0..) |field_name, FieldType, attrs, i| {
if (comptime std.mem.eql(u8, field_name, "name")) {
out.name = name;
} else {
@@ -320,9 +348,16 @@ fn convert(comptime T: type, value: js.Value, name: []const u8, local: *const js
break :blk if (m.isUndefined()) null else m;
};
if (member) |m| {
- @field(out, field_name) = local.jsValueToZig(FieldType, m) catch |err| {
- return conversionError(err, local, "algorithm has a missing or invalid member");
- };
+ if (comptime isBufferSource(FieldType)) {
+ if (!m.isArrayBuffer() and !m.isArrayBufferView()) {
+ return local.typeError("algorithm has a missing or invalid member");
+ }
+ buffers[i] = m;
+ } else {
+ @field(out, field_name) = local.jsValueToZig(FieldType, m) catch |err| {
+ return conversionError(err, local, "algorithm has a missing or invalid member");
+ };
+ }
} else if (comptime attrs.defaultValue(FieldType)) |default| {
@field(out, field_name) = default;
} else if (comptime @typeInfo(FieldType) == .optional) {
@@ -332,9 +367,24 @@ fn convert(comptime T: type, value: js.Value, name: []const u8, local: *const js
}
}
}
+ inline for (info.field_names, info.field_types, 0..) |field_name, FieldType, i| {
+ if (comptime isBufferSource(FieldType)) {
+ if (buffers[i]) |m| {
+ const view = local.jsValueToZig(js.TypedArray(u8), m) catch |err| {
+ return conversionError(err, local, "algorithm has a missing or invalid member");
+ };
+ @field(out, field_name) = .{ .values = try local.call_arena.dupe(u8, view.values) };
+ }
+ }
+ }
return out;
}
+/// Whether a params member is a BufferSource, copied by `convert`.
+fn isBufferSource(comptime FieldType: type) bool {
+ return FieldType == js.TypedArray(u8) or FieldType == ?js.TypedArray(u8);
+}
+
/// Key material handed to `importKey()`: either a BufferSource (raw/spki/pkcs8)
/// or a JSON Web Key object (jwk). `bytes` is probed first — a JWK is a plain
/// object and won't coerce to a TypedArray.
@@ -369,74 +419,115 @@ pub const KeyData = union(enum) {
};
};
-/// Algorithm for `encrypt()` / `decrypt()`. AES-CBC/CTR/GCM and RSA-OAEP share one struct
-/// (fields are mode-specific and optional) and dispatch on `name`; a bare string
-/// is the fallback form.
+/// Algorithm for `encrypt()` / `decrypt()` and wrapKey/unwrapKey, normalized
+/// by name as Init is: RSA-OAEP's optional label; AES-CBC's and AES-GCM's `iv`
+/// and AES-CTR's `counter` and `length` (an [EnforceRange] octet), required;
+/// AES-GCM's optional `additionalData` and `tagLength` (an [EnforceRange]
+/// octet). AES-KW only wraps, so it's NotSupportedError for encrypt/decrypt.
pub const Encrypt = union(enum) {
- params: struct {
+ rsa_oaep: struct { label: ?js.TypedArray(u8) = null, name: []const u8 },
+ /// AES-CBC, AES-CTR or AES-GCM, in the one shape AES.crypt reads.
+ aes: AesParams,
+ /// AES-KW, which takes no params.
+ aes_kw: []const u8,
+
+ pub const AesParams = struct {
additionalData: ?js.TypedArray(u8) = null,
counter: ?js.TypedArray(u8) = null,
iv: ?js.TypedArray(u8) = null,
- /// RSA-OAEP.
- label: ?js.TypedArray(u8) = null,
length: ?u32 = null,
name: []const u8,
tagLength: ?u32 = null,
- },
- /// An object without a `name`: a TypeError, as for every algorithm
- /// identifier. Probed before the string, which would coerce it.
- nameless: js.Object,
- name: []const u8,
+ };
+
+ /// `wrapping` is for wrapKey/unwrapKey, whose algorithm can also be AES-KW.
+ pub fn fromJs(value: js.Value, local: *const js.Local, wrapping: bool) !Encrypt {
+ const name = try identifierName(value, local);
+ if (wrapping and isOneOf(name, &.{"AES-KW"})) {
+ return .{ .aes_kw = name };
+ }
+ if (isOneOf(name, &.{"RSA-OAEP"})) {
+ return .{ .rsa_oaep = try convert(@FieldType(Encrypt, "rsa_oaep"), value, name, local) };
+ }
+ if (isOneOf(name, &.{"AES-CBC"})) {
+ const params = try convert(struct { iv: js.TypedArray(u8), name: []const u8 }, value, name, local);
+ return .{ .aes = .{ .iv = params.iv, .name = params.name } };
+ }
+ if (isOneOf(name, &.{"AES-CTR"})) {
+ const params = try convert(struct { counter: js.TypedArray(u8), length: js.EnforceRange(u8), name: []const u8 }, value, name, local);
+ return .{ .aes = .{ .counter = params.counter, .length = params.length.value, .name = params.name } };
+ }
+ if (isOneOf(name, &.{"AES-GCM"})) {
+ const params = try convert(struct {
+ additionalData: ?js.TypedArray(u8) = null,
+ iv: js.TypedArray(u8),
+ name: []const u8,
+ tagLength: ?js.Value = null,
+ }, value, name, local);
+ return .{ .aes = .{
+ .additionalData = params.additionalData,
+ .iv = params.iv,
+ .name = params.name,
+ .tagLength = if (try rangeMember(u8, params.tagLength, local)) |t| t else null,
+ } };
+ }
+ return error.NotSupported;
+ }
- /// Null for an object without a name.
- pub fn algoName(self: Encrypt) ?[]const u8 {
+ pub fn algoName(self: Encrypt) []const u8 {
return switch (self) {
- .params => |p| p.name,
- .nameless => null,
- .name => |n| n,
+ .rsa_oaep => |p| p.name,
+ .aes => |p| p.name,
+ .aes_kw => |n| n,
};
}
};
-/// For `sign()` functionality.
+/// Algorithm for `sign()` / `verify()`, normalized by name as Init is:
+/// RSA-PSS's `saltLength` (an [EnforceRange] unsigned long) and ECDSA's hash,
+/// required; HMAC, RSASSA-PKCS1-v1_5 and Ed25519 take just their name.
pub const Sign = union(enum) {
- string: []const u8,
- object: struct {
- /// ECDSA. Kept as a value, like `saltLength`: it's only converted
- /// (a HashAlgorithmIdentifier) when the algorithm is ECDSA.
- hash: ?js.Value = null,
- name: []const u8,
- /// RSA-PSS. Kept as a value: it's only converted (an [EnforceRange]
- /// unsigned long) when the algorithm is RSA-PSS, so another algorithm
- /// ignores the member, as normalization does.
- saltLength: ?js.Value = null,
- },
- /// An object without a `name`: a TypeError, as for every algorithm
- /// identifier. Probed after the object, which needs the name.
- nameless: js.Object,
+ named: []const u8,
+ rsa_pss: struct { name: []const u8, saltLength: js.EnforceRange(u32) },
+ ecdsa: struct { hash: Hash, name: []const u8 },
+
+ pub fn fromJs(value: js.Value, local: *const js.Local) !Sign {
+ const name = try identifierName(value, local);
+ if (isOneOf(name, &.{"RSA-PSS"})) {
+ return .{ .rsa_pss = try convert(@FieldType(Sign, "rsa_pss"), value, name, local) };
+ }
+ if (isOneOf(name, &.{"ECDSA"})) {
+ const params = try convert(@FieldType(Sign, "ecdsa"), value, name, local);
+ _ = try params.hash.canonical(local);
+ return .{ .ecdsa = params };
+ }
+ if (isOneOf(name, &.{ "HMAC", "RSASSA-PKCS1-v1_5", "Ed25519" })) {
+ return .{ .named = name };
+ }
+ return error.NotSupported;
+ }
- /// Null for an object without a name.
- pub fn algoName(self: Sign) ?[]const u8 {
+ pub fn algoName(self: Sign) []const u8 {
return switch (self) {
- .string => |string| string,
- .object => |object| object.name,
- .nameless => null,
+ .named => |n| n,
+ .rsa_pss => |p| p.name,
+ .ecdsa => |p| p.name,
};
}
- /// The `hash` member, if present.
- pub fn hash(self: Sign) ?js.Value {
+ /// RSA-PSS's salt length.
+ pub fn saltLength(self: Sign) ?u32 {
return switch (self) {
- .string, .nameless => null,
- .object => |object| object.hash,
+ .rsa_pss => |p| p.saltLength.value,
+ else => null,
};
}
- /// The `saltLength` member, if present.
- pub fn saltLength(self: Sign) ?js.Value {
+ /// ECDSA's hash, by its registered name (fromJs checked it).
+ pub fn hashName(self: Sign, local: *const js.Local) !?[]const u8 {
return switch (self) {
- .string, .nameless => null,
- .object => |object| object.saltLength,
+ .ecdsa => |p| try p.hash.canonical(local),
+ else => null,
};
}
};