Lightpanda: the headless browser designed for AI and automation
webapi: deriveBits/deriveKey normalize their algorithm by name
orezraey64ef7ddfeb0f
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.htmlindex 1597ec8a0..79c14d373 100644--- a/src/browser/tests/crypto.html+++ b/src/browser/tests/crypto.html@@ -1763,6 +1763,94 @@});</script>+<script id=derive-algorithm-names type=module>+ const state = await testing.async();+ const subtle = crypto.subtle;+ const errorName = async (fn) => {+ try {+ await fn();+ return null;+ } catch (err) {+ return err.name;+ }+ };+ const hex = (buf) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join("");+ const raw = new Uint8Array(16);+ const hkdfKey = await subtle.importKey("raw", raw, "HKDF", false, ["deriveBits", "deriveKey"]);+ const pbkdf2Key = await subtle.importKey("raw", raw, "PBKDF2", false, ["deriveBits"]);+ const ecdh = await subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);+ const hkdf = { name: "HKDF", hash: "SHA-256", salt: raw, info: raw };+ const pbkdf2 = { name: "PBKDF2", hash: "SHA-256", salt: raw, iterations: 1 };+ const aes = { name: "AES-GCM", length: 128 };++ const results = {+ hkdf: hex(await subtle.deriveBits(hkdf, hkdfKey, 128)),+ pbkdf2: hex(await subtle.deriveBits(pbkdf2, pbkdf2Key, 128)),+ // The name picks the algorithm, case-insensitively for ASCII only+ // (U+212A KELVIN SIGN isn't "K").+ lower: hex(await subtle.deriveBits({ ...hkdf, name: "hkdf" }, hkdfKey, 128)),+ hkdfKelvin: await errorName(() => subtle.deriveBits({ ...hkdf, name: "H\u212ADF" }, hkdfKey, 128)),+ pbkdf2Kelvin: await errorName(() => subtle.deriveBits({ ...pbkdf2, name: "PB\u212ADF2" }, pbkdf2Key, 128)),+ unknownName: await errorName(() => subtle.deriveBits({ ...hkdf, name: "foo" }, hkdfKey, 128)),+ unknownString: await errorName(() => subtle.deriveBits("foo", pbkdf2Key, 128)),+ unknownNull: await errorName(() => subtle.deriveBits(null, pbkdf2Key, 128)),+ unknownDeriveKey: await errorName(() => subtle.deriveKey({ ...hkdf, name: "foo" }, hkdfKey, aes, true, ["encrypt"])),+ // Another algorithm's members are ignored, not taken as its params.+ hkdfIterations: hex(await subtle.deriveBits({ ...hkdf, iterations: 1 }, hkdfKey, 128)),+ pbkdf2Info: hex(await subtle.deriveBits({ ...pbkdf2, info: raw }, pbkdf2Key, 128)),+ // The params of the named algorithm are required: a TypeError without one+ // of its members, a bare string name, or an object without a name.+ hkdfMissingInfo: await errorName(() => subtle.deriveBits({ ...pbkdf2, name: "HKDF" }, hkdfKey, 128)),+ pbkdf2MissingIterations: await errorName(() => subtle.deriveBits({ ...hkdf, name: "PBKDF2" }, pbkdf2Key, 128)),+ ecdhMissingPublic: await errorName(() => subtle.deriveBits({ ...hkdf, name: "ECDH" }, ecdh.privateKey, 128)),+ bareName: await errorName(() => subtle.deriveBits("PBKDF2", pbkdf2Key, 128)),+ noName: await errorName(() => subtle.deriveBits({}, pbkdf2Key, 128)),+ badSalt: await errorName(() => subtle.deriveBits({ ...pbkdf2, salt: "x" }, pbkdf2Key, 128)),+ // iterations is an [EnforceRange] unsigned long: truncated, not wrapped.+ iterationsFraction: hex(await subtle.deriveBits({ ...pbkdf2, iterations: 1.9 }, pbkdf2Key, 128)),+ iterationsNegative: await errorName(() => subtle.deriveBits({ ...pbkdf2, iterations: -1 }, pbkdf2Key, 128)),+ iterationsTooLarge: await errorName(() => subtle.deriveBits({ ...pbkdf2, iterations: 2 ** 32 + 1 }, pbkdf2Key, 128)),+ iterationsNaN: await errorName(() => subtle.deriveBits({ ...pbkdf2, iterations: NaN }, pbkdf2Key, 128)),+ hashWithoutName: await errorName(() => subtle.deriveBits({ ...hkdf, hash: {} }, hkdfKey, 128)),+ unknownHash: await errorName(() => subtle.deriveBits({ ...hkdf, hash: "foo" }, hkdfKey, 128)),+ // deriveKey normalizes the algorithm before derivedKeyType.+ unknownBeforeDerived: await errorName(() => subtle.deriveKey({ ...hkdf, name: "foo" }, hkdfKey, "AES-FOO", true, ["encrypt"])),+ missingBeforeDerived: await errorName(() => subtle.deriveKey({ ...hkdf, info: undefined }, hkdfKey, "AES-FOO", true, ["encrypt"])),+ // The key checks come after.+ otherKey: await errorName(() => subtle.deriveBits(hkdf, pbkdf2Key, 128)),+ };++ state.resolve();+ await state.done(() => {+ testing.expectEqual(32, results.hkdf.length);+ testing.expectEqual(32, results.pbkdf2.length);+ testing.expectEqual(results.hkdf, results.lower);+ testing.expectEqual("NotSupportedError", results.hkdfKelvin);+ testing.expectEqual("NotSupportedError", results.pbkdf2Kelvin);+ testing.expectEqual("NotSupportedError", results.unknownName);+ testing.expectEqual("NotSupportedError", results.unknownString);+ testing.expectEqual("NotSupportedError", results.unknownNull);+ testing.expectEqual("NotSupportedError", results.unknownDeriveKey);+ testing.expectEqual(results.hkdf, results.hkdfIterations);+ testing.expectEqual(results.pbkdf2, results.pbkdf2Info);+ testing.expectEqual("TypeError", results.hkdfMissingInfo);+ testing.expectEqual("TypeError", results.pbkdf2MissingIterations);+ testing.expectEqual("TypeError", results.ecdhMissingPublic);+ testing.expectEqual("TypeError", results.bareName);+ testing.expectEqual("TypeError", results.noName);+ testing.expectEqual("TypeError", results.badSalt);+ testing.expectEqual(results.pbkdf2, results.iterationsFraction);+ testing.expectEqual("TypeError", results.iterationsNegative);+ testing.expectEqual("TypeError", results.iterationsTooLarge);+ testing.expectEqual("TypeError", results.iterationsNaN);+ testing.expectEqual("TypeError", results.hashWithoutName);+ testing.expectEqual("NotSupportedError", results.unknownHash);+ testing.expectEqual("NotSupportedError", results.unknownBeforeDerived);+ testing.expectEqual("TypeError", results.missingBeforeDerived);+ testing.expectEqual("InvalidAccessError", results.otherKey);+ });+</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.zigindex e082c53c8..6315858f9 100644--- a/src/browser/webapi/SubtleCrypto.zig+++ b/src/browser/webapi/SubtleCrypto.zig@@ -402,12 +402,13 @@ fn exportJwk(key: *CryptoKey, exec: *const Execution) !Jwk {/// (the WebIDL type is `[EnforceRange] unsigned long?`).pub fn deriveBits(_: *const SubtleCrypto,- algo: algorithm.Derive,+ algo_value: js.Value,base_key: *const CryptoKey,length: ?js.EnforceRange(u32),exec: *const Execution,) !js.Promise {const local = exec.js.local.?;+ const algo = try algorithm.Derive.fromJs(algo_value, local);const bits = try deriveRaw(algo, base_key, if (length) |l| l.value else null, base_key.canDeriveBits(), exec);return local.resolvePromise(js.ArrayBuffer{ .values = bits });}@@ -416,7 +417,7 @@ pub fn deriveBits(/// `derived`, then import them as that key type.pub fn deriveKey(_: *const SubtleCrypto,- algo: algorithm.Derive,+ algo_value: js.Value,base_key: *const CryptoKey,derived: algorithm.DerivedKey,extractable: bool,@@ -424,10 +425,8 @@ pub fn deriveKey(exec: *const Execution,) !js.Promise {const local = exec.js.local.?;- // The algorithm (its hash) is normalized before derivedKeyType.- if (algo.hash()) |hash| {- _ = try hash.name(local);- }+ // The algorithm is normalized before derivedKeyType.+ const algo = try algorithm.Derive.fromJs(algo_value, local);// The base key's deriveKey usage (not deriveBits) gates this operation.const usage_ok = base_key.canDeriveKey();diff --git a/src/browser/webapi/crypto/KDF.zig b/src/browser/webapi/crypto/KDF.zigindex 54275223b..7f1466b37 100644--- a/src/browser/webapi/crypto/KDF.zig+++ b/src/browser/webapi/crypto/KDF.zig@@ -79,8 +79,8 @@ pub fn pbkdf2(}const blocks = std.math.divCeil(usize, out_len, crypto.EVP_MD_size(digest)) catch unreachable;- if (@as(u64, blocks) * params.iterations > PBKDF2_MAX_WORK) {- log.warn(.js, "PBKDF2 work limit", .{ .length = out_len, .iterations = params.iterations });+ if (@as(u64, blocks) * params.iterations.value > PBKDF2_MAX_WORK) {+ log.warn(.js, "PBKDF2 work limit", .{ .length = out_len, .iterations = params.iterations.value });return error.OperationError;}@@ -92,7 +92,7 @@ pub fn pbkdf2(base_key._key.len,@ptrCast(salt.ptr),salt.len,- params.iterations,+ params.iterations.value,digest,out.len,out.ptr,diff --git a/src/browser/webapi/crypto/algorithm.zig b/src/browser/webapi/crypto/algorithm.zigindex 2f44def6c..e390673a8 100644--- a/src/browser/webapi/crypto/algorithm.zig+++ b/src/browser/webapi/crypto/algorithm.zig@@ -18,6 +18,8 @@//! This file provides various arguments needed for crypto APIs.+const std = @import("std");+const js = @import("../../js/js.zig");const CryptoKey = @import("../CryptoKey.zig");@@ -25,7 +27,9 @@ const CryptoKey = @import("../CryptoKey.zig");/// The TypeError of an algorithm identifier object without a `name`.pub const missing_name = "required member name is undefined";-/// A HashAlgorithmIdentifier: either `"SHA-256"` or `{name: "SHA-256"}`.+/// A HashAlgorithmIdentifier: either `"SHA-256"` or `{name: "SHA-256"}`. The+/// same conversion as any AlgorithmIdentifier's, which Derive reads its name+/// with.pub const Hash = union(enum) {string: []const u8,object: struct { name: []const u8 },@@ -102,32 +106,55 @@ pub const Init = union(enum) {name: []const u8,};const EcdhKeyDeriveParams = struct {- /// Can be Ed25519 or X25519.+ /// ECDH or X25519.name: []const u8,public: *const CryptoKey,};};-/// Algorithm for deriveBits() and deriveKey(). Variants are distinguished by-/// their required members (`iterations` for PBKDF2, `info` for HKDF, `public`-/// for ECDH/X25519), so probe order doesn't cause ambiguity.+/// Algorithm for deriveBits() and deriveKey(), an AlgorithmIdentifier+/// normalized as the spec does: its name picks the algorithm (an unknown one+/// is NotSupportedError), then the value is converted to that algorithm's+/// params dictionary (a TypeError without a required member). Taken as a+/// js.Value, not probed by shape, so the name decides, not the members.pub const Derive = union(enum) {pbkdf2: Pbkdf2Params,hkdf: HkdfParams,ecdh_or_x25519: Init.EcdhKeyDeriveParams,- /// The hash of PBKDF2's or HKDF's params; null for ECDH and X25519.- pub fn hash(self: Derive) ?Hash {- return switch (self) {- .pbkdf2 => |p| p.hash,- .hkdf => |p| p.hash,- .ecdh_or_x25519 => null,+ pub fn fromJs(value: js.Value, local: *const js.Local) !Derive {+ const identifier = try convert(Hash, value, local);+ const name = try identifier.name(local);+ if (std.ascii.eqlIgnoreCase(name, "PBKDF2")) {+ const params = try convert(Pbkdf2Params, value, local);+ _ = try params.hash.name(local);+ return .{ .pbkdf2 = params };+ }+ if (std.ascii.eqlIgnoreCase(name, "HKDF")) {+ const params = try convert(HkdfParams, value, local);+ _ = try params.hash.name(local);+ return .{ .hkdf = params };+ }+ if (std.ascii.eqlIgnoreCase(name, "ECDH") or std.ascii.eqlIgnoreCase(name, "X25519")) {+ return .{ .ecdh_or_x25519 = try convert(Init.EcdhKeyDeriveParams, value, local) };+ }+ return error.NotSupported;+ }++ /// `value` as `T`. A value that isn't one (a string for a dictionary, a+ /// missing member) is a TypeError; the page's own exception stays pending.+ fn convert(comptime T: type, value: js.Value, local: *const js.Local) !T {+ return local.jsValueToZig(T, value) catch |err| switch (err) {+ error.JsException, error.OutOfMemory => err,+ else => local.typeError("algorithm is missing a required member"),};}pub const Pbkdf2Params = struct {hash: Hash,- iterations: u32,+ /// An [EnforceRange] unsigned long: converted once the name is known+ /// to be PBKDF2's, so it's a TypeError out of range, not wrapped.+ iterations: js.EnforceRange(u32),name: []const u8,salt: js.TypedArray(u8),};