Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: an algorithm or hash without a name is a TypeError

orezraey61fc63b5bc1f
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.html
index 408eb21f2..ad75dac42 100644
--- a/src/browser/tests/crypto.html
+++ b/src/browser/tests/crypto.html
@@ -1639,6 +1639,118 @@
});
</script>
+<script id=algorithm-without-name 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 raw = new Uint8Array(16);
+ const data = new Uint8Array(8);
+ const e = new Uint8Array([1, 0, 1]);
+ const aes = await subtle.generateKey({ name: "AES-GCM", length: 128 }, true, ["encrypt", "decrypt"]);
+ const kw = await subtle.generateKey({ name: "AES-KW", length: 128 }, true, ["wrapKey", "unwrapKey"]);
+ const hmac = await subtle.generateKey({ name: "HMAC", hash: "SHA-256" }, true, ["sign", "verify"]);
+ const ecdsa = await subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]);
+ const rsa = await subtle.generateKey({ name: "RSA-OAEP", modulusLength: 1024, publicExponent: e, hash: "SHA-256" }, true, ["encrypt", "decrypt"]);
+ const spki = await subtle.exportKey("spki", rsa.publicKey);
+ const pbkdf2 = await subtle.importKey("raw", raw, "PBKDF2", false, ["deriveBits", "deriveKey"]);
+ const deriveKeyOnly = await subtle.importKey("raw", raw, "PBKDF2", false, ["deriveKey"]);
+ const hkdf = await subtle.importKey("raw", raw, "HKDF", false, ["deriveBits"]);
+ const pbkdf2Params = (hash) => ({ name: "PBKDF2", hash, salt: raw, iterations: 1 });
+ const wrapped = await subtle.wrapKey("raw", aes, kw, "AES-KW");
+
+ const results = {
+ // An algorithm object without a name is a TypeError, whatever its other
+ // members, instead of the name "[object Object]".
+ importEmpty: await errorName(() => subtle.importKey("raw", raw, {}, true, ["encrypt"])),
+ importHashOnly: await errorName(() => subtle.importKey("raw", raw, { hash: "SHA-256" }, true, ["sign"])),
+ importCurveOnly: await errorName(() => subtle.importKey("raw", raw, { namedCurve: "P-256" }, true, [])),
+ importArray: await errorName(() => subtle.importKey("raw", raw, [], true, ["encrypt"])),
+ importJwk: await errorName(() => subtle.importKey("jwk", { kty: "oct", k: "AAAAAAAAAAAAAAAAAAAAAA" }, {}, true, ["encrypt"])),
+ encrypt: await errorName(() => subtle.encrypt({ iv: new Uint8Array(12) }, aes, data)),
+ decrypt: await errorName(() => subtle.decrypt({}, aes, data)),
+ sign: await errorName(() => subtle.sign({ hash: "SHA-256" }, hmac, data)),
+ verify: await errorName(() => subtle.verify({}, hmac, data, data)),
+ deriveKeyType: await errorName(() => subtle.deriveKey(pbkdf2Params("SHA-256"), pbkdf2, { length: 128 }, true, ["encrypt"])),
+ wrapKey: await errorName(() => subtle.wrapKey("raw", aes, kw, {})),
+ unwrapKey: await errorName(() => subtle.unwrapKey("raw", wrapped, kw, {}, "AES-GCM", true, ["encrypt"])),
+ unwrappedKey: await errorName(() => subtle.unwrapKey("raw", wrapped, kw, "AES-KW", {}, true, ["encrypt"])),
+ // The unwrapping algorithm is normalized first, the unwrapped key's next,
+ // and the key checks come after both.
+ unwrapUnknownFirst: await errorName(() => subtle.unwrapKey("raw", wrapped, kw, "foo", {}, true, ["encrypt"])),
+ unwrapBeforeKey: await errorName(() => subtle.unwrapKey("raw", wrapped, aes, "AES-KW", {}, true, ["encrypt"])),
+ unwrapHashBeforeKey: await errorName(() => subtle.unwrapKey("raw", wrapped, aes, "AES-KW", { name: "HMAC", hash: {} }, true, ["sign"])),
+ // deriveKey normalizes the algorithm before derivedKeyType.
+ deriveHashFirst: await errorName(() => subtle.deriveKey(pbkdf2Params({}), pbkdf2, "AES-FOO", true, ["encrypt"])),
+ // A name that isn't a known algorithm stays NotSupportedError: a
+ // function's own name (""), null as a string, a number.
+ importFunction: await errorName(() => subtle.importKey("raw", raw, function () {}, true, ["encrypt"])),
+ importNull: await errorName(() => subtle.importKey("raw", raw, null, true, ["encrypt"])),
+ importNumberName: await errorName(() => subtle.importKey("raw", raw, { name: 1 }, true, ["encrypt"])),
+ // So is a hash without a name, for every algorithm that takes one.
+ generateHmacHash: await errorName(() => subtle.generateKey({ name: "HMAC", hash: {} }, true, ["sign"])),
+ generateRsaHash: await errorName(() => subtle.generateKey({ name: "RSA-OAEP", modulusLength: 1024, publicExponent: e, hash: {} }, true, ["sign"])),
+ importHmacHash: await errorName(() => subtle.importKey("raw", raw, { name: "HMAC", hash: {} }, true, ["sign"])),
+ importRsaHash: await errorName(() => subtle.importKey("spki", spki, { name: "RSA-OAEP", hash: {} }, true, ["encrypt"])),
+ pbkdf2Hash: await errorName(() => subtle.deriveBits(pbkdf2Params({}), pbkdf2, 128)),
+ hkdfHash: await errorName(() => subtle.deriveBits({ name: "HKDF", hash: {}, salt: raw, info: raw }, hkdf, 128)),
+ deriveHmacHash: await errorName(() => subtle.deriveKey(pbkdf2Params("SHA-256"), pbkdf2, { name: "HMAC", hash: {} }, true, ["sign"])),
+ ecdsaHashArray: await errorName(() => subtle.sign({ name: "ECDSA", hash: [] }, ecdsa.privateKey, data)),
+ ecdsaHashFunction: await errorName(() => subtle.sign({ name: "ECDSA", hash: function () {} }, ecdsa.privateKey, data)),
+ // The hash is normalized before the base key's checks.
+ pbkdf2HashBeforeUsage: await errorName(() => subtle.deriveBits(pbkdf2Params({}), deriveKeyOnly, 128)),
+ pbkdf2UnknownBeforeUsage: await errorName(() => subtle.deriveBits(pbkdf2Params("foo"), deriveKeyOnly, 128)),
+ pbkdf2UnknownBeforeKey: await errorName(() => subtle.deriveBits(pbkdf2Params("foo"), hkdf, 128)),
+ // A stray hash without a name on an algorithm that takes none is ignored.
+ aesStrayHash: await errorName(() => subtle.importKey("raw", raw, { name: "AES-GCM", hash: {} }, true, ["encrypt"])),
+ deriveAesStrayHash: await errorName(() => subtle.deriveKey(pbkdf2Params("SHA-256"), pbkdf2, { name: "AES-GCM", length: 128, hash: {} }, true, ["encrypt"])),
+ };
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual("TypeError", results.importEmpty);
+ testing.expectEqual("TypeError", results.importHashOnly);
+ testing.expectEqual("TypeError", results.importCurveOnly);
+ testing.expectEqual("TypeError", results.importArray);
+ testing.expectEqual("TypeError", results.importJwk);
+ testing.expectEqual("TypeError", results.encrypt);
+ testing.expectEqual("TypeError", results.decrypt);
+ testing.expectEqual("TypeError", results.sign);
+ testing.expectEqual("TypeError", results.verify);
+ testing.expectEqual("TypeError", results.deriveKeyType);
+ testing.expectEqual("TypeError", results.wrapKey);
+ testing.expectEqual("TypeError", results.unwrapKey);
+ testing.expectEqual("TypeError", results.unwrappedKey);
+ testing.expectEqual("NotSupportedError", results.unwrapUnknownFirst);
+ testing.expectEqual("TypeError", results.unwrapBeforeKey);
+ testing.expectEqual("TypeError", results.unwrapHashBeforeKey);
+ testing.expectEqual("TypeError", results.deriveHashFirst);
+ testing.expectEqual("NotSupportedError", results.importFunction);
+ testing.expectEqual("NotSupportedError", results.importNull);
+ testing.expectEqual("NotSupportedError", results.importNumberName);
+ testing.expectEqual("TypeError", results.generateHmacHash);
+ testing.expectEqual("TypeError", results.generateRsaHash);
+ testing.expectEqual("TypeError", results.importHmacHash);
+ testing.expectEqual("TypeError", results.importRsaHash);
+ testing.expectEqual("TypeError", results.pbkdf2Hash);
+ testing.expectEqual("TypeError", results.hkdfHash);
+ testing.expectEqual("TypeError", results.deriveHmacHash);
+ testing.expectEqual("TypeError", results.ecdsaHashArray);
+ testing.expectEqual("NotSupportedError", results.ecdsaHashFunction);
+ testing.expectEqual("TypeError", results.pbkdf2HashBeforeUsage);
+ testing.expectEqual("NotSupportedError", results.pbkdf2UnknownBeforeUsage);
+ testing.expectEqual("NotSupportedError", results.pbkdf2UnknownBeforeKey);
+ testing.expectEqual(null, results.aesStrayHash);
+ testing.expectEqual(null, results.deriveAesStrayHash);
+ });
+</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 b8624e42a..245718fa3 100644
--- a/src/browser/webapi/SubtleCrypto.zig
+++ b/src/browser/webapi/SubtleCrypto.zig
@@ -36,6 +36,7 @@ const common = @import("crypto/common.zig");
const log = lp.log;
const String = lp.String;
const Execution = js.Execution;
+const missing_name = algorithm.missing_name;
/// The SubtleCrypto interface of the Web Crypto API provides a number of low-level
/// cryptographic functions.
@@ -124,7 +125,7 @@ pub fn importKey(
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const name = algo.algoName();
+ const name = algo.algoName() orelse return local.typeError(missing_name);
// Asymmetric algorithms (EC, OKP). Usage validation runs first (bad/empty
// usages → SyntaxError) so the failure-path tests pass regardless of whether
@@ -141,7 +142,7 @@ pub fn importKey(
return EC.import(name, algo.namedCurve(), format, der, is_private, extractable, mask, exec);
}
if (RSA.scheme(name)) |scheme| {
- const hash_name = importHash(algo) orelse return local.typeError("RSA import requires a hash");
+ const hash_name = try importHash(algo, local) orelse return local.typeError("RSA import requires a hash");
const is_jwk = std.mem.eql(u8, format, "jwk");
switch (key_data) {
.bytes => |b| {
@@ -170,7 +171,7 @@ pub fn importKey(
}
if (eqlIgnoreCase(name, "HMAC")) {
const length = try HMAC.lengthParam(importLength(algo), local);
- const hash_name = importHash(algo) orelse return local.typeError("HMAC import requires a hash");
+ const hash_name = try importHash(algo, local) orelse return local.typeError("HMAC import requires a hash");
return HMAC.importJwk(hash_name, jwk, length, extractable, key_usages, exec);
}
// HKDF and PBKDF2 keys only come in "raw".
@@ -212,7 +213,7 @@ pub fn importKey(
}
if (eqlIgnoreCase(name, "HMAC")) {
const length = try HMAC.lengthParam(importLength(algo), local);
- const hash_name = importHash(algo) orelse return local.typeError("HMAC import requires a hash");
+ const hash_name = try importHash(algo, local) orelse return local.typeError("HMAC import requires a hash");
return HMAC.import(hash_name, raw, length, extractable, key_usages, exec);
}
@@ -223,12 +224,9 @@ pub fn importKey(
/// The hash of an importKey algorithm that carries one (HMAC, RSA): those
/// params {name, hash} match the `.hmac` variant of the Import union (same
/// shape), so the hash is read there. Null for the other variants.
-fn importHash(algo: algorithm.Import) ?[]const u8 {
+fn importHash(algo: algorithm.Import, local: *const js.Local) !?[]const u8 {
return switch (algo) {
- .hmac => |h| switch (h.hash) {
- .string => |s| s,
- .object => |o| o.name,
- },
+ .hmac => |h| try h.hash.name(local),
else => null,
};
}
@@ -425,6 +423,11 @@ pub fn deriveKey(
key_usages: []const []const u8,
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 base key's deriveKey usage (not deriveBits) gates this operation.
const usage_ok = base_key.canDeriveKey();
@@ -437,7 +440,6 @@ pub fn deriveKey(
return AES.import(k.name, bits, extractable, key_usages, exec);
},
.hmac => |h| {
- const local = exec.js.local.?;
// 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) {
@@ -449,13 +451,14 @@ pub fn deriveKey(
return error.NotSupported;
}
const requested = try HMAC.lengthParam(h.length, local);
- const hash_name = common.canonicalHash(h.hash.name()) orelse return error.NotSupported;
+ const hash_name = common.canonicalHash(try h.hash.name(local)) orelse return error.NotSupported;
const hash_md = crypto.findDigest(hash_name) catch return error.NotSupported;
// Default length, per spec, is the hash's block size (in bits).
const length: u32 = requested orelse @intCast(crypto.EVP_MD_block_size(hash_md) * 8);
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;
@@ -536,7 +539,8 @@ pub fn wrapKey(
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- try checkWrappingKey(algo, wrapping_key, .wrap);
+ const name = try wrapAlgorithmName(algo, local);
+ try checkWrappingKey(name, wrapping_key, .wrap);
const bytes = switch (try exportAs(format, key, exec)) {
.bytes => |bytes| bytes,
@@ -559,7 +563,15 @@ pub fn unwrapKey(
key_usages: []const []const u8,
exec: *const Execution,
) !js.Promise {
- try checkWrappingKey(algo, unwrapping_key, .unwrap);
+ const local = exec.js.local.?;
+ const name = try wrapAlgorithmName(algo, local);
+ // The unwrapped key's algorithm (its name and hash) is normalized next,
+ // before the key checks.
+ if (unwrapped_key_algo.algoName() == null) {
+ return local.typeError(missing_name);
+ }
+ _ = try importHash(unwrapped_key_algo, local);
+ try checkWrappingKey(name, unwrapping_key, .unwrap);
const bytes = try cryptBytes(algo, unwrapping_key, wrapped_key.values, .unwrap, exec);
const key_data: algorithm.KeyData = if (std.mem.eql(u8, format, "jwk"))
@@ -593,15 +605,21 @@ const CryptUse = enum {
}
};
-/// The checks wrapKey/unwrapKey make on the wrapping key before touching the
-/// other key, in the spec's order: an algorithm that can wrap (AES-KW) or
-/// encrypt (RSA-OAEP, AES-CBC/CTR/GCM), the same algorithm as the wrapping key,
-/// and the wrapKey/unwrapKey usage.
-fn checkWrappingKey(algo: algorithm.Encrypt, wrapping_key: *const CryptoKey, use: CryptUse) !void {
- const name = algo.algoName();
+/// 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.
+fn checkWrappingKey(name: []const u8, wrapping_key: *const CryptoKey, use: CryptUse) !void {
if (!eqlIgnoreCase(name, wrapping_key._algorithm.name)) {
return error.InvalidAccessError;
}
@@ -634,7 +652,7 @@ fn cryptBytes(
use: CryptUse,
exec: *const Execution,
) ![]const u8 {
- const name = algo.algoName();
+ 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
@@ -643,7 +661,7 @@ fn cryptBytes(
if (eqlIgnoreCase(name, "RSA-OAEP")) {
const label: []const u8 = switch (algo) {
.params => |p| if (p.label) |l| l.values else "",
- .name => "",
+ .name, .nameless => "",
};
return RSA.crypt(key, data, label, use.encrypting(), use.usage(), exec);
}
@@ -660,7 +678,7 @@ fn cryptBytes(
const params = switch (algo) {
.params => |p| p,
// A bare string identifier carries no iv/counter, so it can't drive AES.
- .name => return error.NotSupported,
+ .name, .nameless => return error.NotSupported,
};
return AES.crypt(params, key, data, use.encrypting(), use.usage(), exec);
}
@@ -675,8 +693,9 @@ pub fn sign(
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const params = try signParams(algo, local);
- try checkSigningKey(algo, key, CryptoKey.Usages.sign);
+ const name = algo.algoName() orelse return local.typeError(missing_name);
+ const params = try signParams(name, algo, local);
+ try checkSigningKey(name, 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),
@@ -700,8 +719,9 @@ pub fn verify(
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const params = try signParams(algo, local);
- try checkSigningKey(algo, key, CryptoKey.Usages.verify);
+ const name = algo.algoName() orelse return local.typeError(missing_name);
+ const params = try signParams(name, algo, local);
+ try checkSigningKey(name, 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),
@@ -727,8 +747,7 @@ const SignParams = struct {
/// 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(algo: algorithm.Sign, local: *const js.Local) !SignParams {
- const name = algo.algoName();
+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");
@@ -741,30 +760,23 @@ fn signParams(algo: algorithm.Sign, local: *const js.Local) !SignParams {
return .{};
}
-/// The name of a HashAlgorithmIdentifier, `(object or DOMString)`: an object's
-/// `name`, required (a TypeError without one), or the value as a string.
+/// 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 Algorithm = struct { name: []const u8 };
- const name = blk: {
- if (value.isObject()) {
- const object = local.jsValueToZig(Algorithm, value) catch |err| break :blk err;
- break :blk object.name;
- }
- break :blk local.jsValueToZig([]const u8, value);
- } catch |err| switch (err) {
+ 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 name;
+ 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.
-fn checkSigningKey(algo: algorithm.Sign, key: *const CryptoKey, usage: u8) !void {
- const name = algo.algoName();
+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;
@@ -798,7 +810,7 @@ pub fn digest(_: *const SubtleCrypto, algo: DigestInput, data: js.TypedArray(u8)
const local = exec.js.local.?;
const algo_name = algo.name() orelse {
- return local.typeError("required member name is undefined");
+ return local.typeError(missing_name);
};
if (algo_name.len > 10) {
return error.NotSupported;
diff --git a/src/browser/webapi/crypto/HMAC.zig b/src/browser/webapi/crypto/HMAC.zig
index 551bb1522..885f9ac9e 100644
--- a/src/browser/webapi/crypto/HMAC.zig
+++ b/src/browser/webapi/crypto/HMAC.zig
@@ -45,10 +45,7 @@ pub fn init(
// Normalization converts the dictionary's members, then the hash: an
// unrecognized one surfaces as NotSupportedError, before the usages.
const length = try lengthParam(params.length, local);
- const hash_name = common.canonicalHash(switch (params.hash) {
- .string => |str| str,
- .object => |obj| obj.name,
- }) orelse return error.NotSupported;
+ const hash_name = common.canonicalHash(try params.hash.name(local)) orelse return error.NotSupported;
const digest = crypto.findDigest(hash_name) catch return error.NotSupported;
// HMAC only accepts sign / verify; any other usage is a SyntaxError per
diff --git a/src/browser/webapi/crypto/KDF.zig b/src/browser/webapi/crypto/KDF.zig
index 2343253ff..54275223b 100644
--- a/src/browser/webapi/crypto/KDF.zig
+++ b/src/browser/webapi/crypto/KDF.zig
@@ -35,8 +35,8 @@ const log = lp.log;
/// its cost.
const PBKDF2_MAX_WORK: u64 = 1 << 24;
-/// Errors a derivation can raise, each mapping to a specific DOMException name.
-pub const Error = error{ InvalidAccessError, NotSupported, OperationError, OutOfMemory };
+/// Errors a derivation can raise: a TypeError, or one mapping to a DOMException.
+pub const Error = error{ InvalidAccessError, NotSupported, OperationError, OutOfMemory, TypeError };
/// Validates the base key against the requested algorithm (shared by PBKDF2 and
/// HKDF). `usage_ok` is the caller-checked usage gate (deriveBits for
@@ -68,8 +68,9 @@ pub fn pbkdf2(
usage_ok: bool,
exec: *const Execution,
) Error![]const u8 {
+ // Normalizing the params (the hash) comes before the key checks.
+ const digest = crypto.findDigest(try params.hash.name(exec.js.local.?)) catch return error.NotSupported;
try checkBaseKey(base_key, "PBKDF2", usage_ok);
- const digest = crypto.findDigest(params.hash.name()) catch return error.NotSupported;
const out_len = try outputLen(length);
// A zero-length derivation is valid and yields an empty buffer; the C
// routines reject a zero output length, so short-circuit here.
@@ -109,8 +110,9 @@ pub fn hkdf(
usage_ok: bool,
exec: *const Execution,
) Error![]const u8 {
+ // Normalizing the params (the hash) comes before the key checks.
+ const digest = crypto.findDigest(try params.hash.name(exec.js.local.?)) catch return error.NotSupported;
try checkBaseKey(base_key, "HKDF", usage_ok);
- const digest = crypto.findDigest(params.hash.name()) catch return error.NotSupported;
const out = try exec.local_arena.alloc(u8, try outputLen(length));
// A zero-length derivation is valid and yields an empty buffer; the C
// routines reject a zero output length, so short-circuit here.
diff --git a/src/browser/webapi/crypto/RSA.zig b/src/browser/webapi/crypto/RSA.zig
index 915cc62ca..7e14ba295 100644
--- a/src/browser/webapi/crypto/RSA.zig
+++ b/src/browser/webapi/crypto/RSA.zig
@@ -31,7 +31,7 @@ const js = @import("../../js/js.zig");
const CryptoKey = @import("../CryptoKey.zig");
const Execution = js.Execution;
-pub fn validate(params: algorithm.Init.RsaHashedKeyGen, key_usages: []const []const u8) !void {
+pub fn validate(params: algorithm.Init.RsaHashedKeyGen, hash_name: []const u8, key_usages: []const []const u8) !void {
const allowed: []const []const u8 = blk: {
if (eql(params.name, "RSASSA-PKCS1-v1_5") or eql(params.name, "RSA-PSS")) {
break :blk &.{ "sign", "verify" };
@@ -42,10 +42,6 @@ pub fn validate(params: algorithm.Init.RsaHashedKeyGen, key_usages: []const []co
return error.NotSupported;
};
- const hash_name = switch (params.hash) {
- .string => |s| s,
- .object => |o| o.name,
- };
if (canonicalHash(hash_name) == null) {
return error.NotSupported;
}
@@ -174,7 +170,8 @@ pub fn generate(
// the hash (validate). The usages come after.
const s = scheme(params.name) orelse return error.NotSupported;
const requested_bits = try modulusLength(params, local);
- try validate(params, key_usages);
+ const requested_hash = try params.hash.name(local);
+ try validate(params, requested_hash, key_usages);
// Generation runs on the main thread and can't be interrupted, and its cost
// grows steeply with the size: 8192 bits takes seconds, 16384 (BoringSSL's
@@ -182,10 +179,7 @@ pub fn generate(
// 2048 or 4096 in practice. Chrome allows 16384 but generates off-thread.
if (requested_bits > max_modulus_length) return error.OperationError;
- const hash_name = canonicalHash(switch (params.hash) {
- .string => |str| str,
- .object => |o| o.name,
- }).?;
+ const hash_name = canonicalHash(requested_hash).?;
const private_mask = maskOf(s.private_usages, key_usages);
const public_mask = maskOf(s.public_usages, key_usages);
// The private key must end up with at least one usage.
diff --git a/src/browser/webapi/crypto/algorithm.zig b/src/browser/webapi/crypto/algorithm.zig
index a2534d5e2..2f44def6c 100644
--- a/src/browser/webapi/crypto/algorithm.zig
+++ b/src/browser/webapi/crypto/algorithm.zig
@@ -22,6 +22,25 @@ const js = @import("../../js/js.zig");
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"}`.
+pub const Hash = union(enum) {
+ string: []const u8,
+ object: struct { name: []const u8 },
+ /// An object without a `name`: a TypeError, as for the algorithm itself.
+ nameless: js.Object,
+
+ pub fn name(self: Hash, local: *const js.Local) error{TypeError}![]const u8 {
+ return switch (self) {
+ .string => |s| s,
+ .object => |o| o.name,
+ .nameless => local.typeError(missing_name),
+ };
+ }
+};
+
/// Passed for `generateKey()`.
pub const Init = union(enum) {
/// For RSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP: pass an RsaHashedKeyGenParams object.
@@ -45,10 +64,7 @@ pub const Init = union(enum) {
/// https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedKeyGenParams
pub const RsaHashedKeyGen = struct {
- hash: union(enum) {
- string: []const u8,
- object: struct { name: []const u8 },
- },
+ hash: Hash,
/// This should be at least 2048.
/// Some organizations are now recommending that it should be 4096.
/// An [EnforceRange] unsigned long, kept as a value: this dictionary
@@ -76,10 +92,7 @@ pub const Init = union(enum) {
/// https://developer.mozilla.org/en-US/docs/Web/API/HmacKeyGenParams
pub const HmacKeyGen = struct {
/// Its also possible to pass this in an object.
- hash: union(enum) {
- string: []const u8,
- object: struct { name: []const u8 },
- },
+ hash: Hash,
/// If omitted, default is the block size of the chosen hash function.
/// An [EnforceRange] unsigned long, kept as a value: HMAC.init converts
/// it (HMAC.lengthParam) once the name is known to be HMAC's, since
@@ -103,18 +116,14 @@ pub const Derive = union(enum) {
hkdf: HkdfParams,
ecdh_or_x25519: Init.EcdhKeyDeriveParams,
- /// A hash AlgorithmIdentifier — either `"SHA-256"` or `{name: "SHA-256"}`.
- pub const Hash = union(enum) {
- string: []const u8,
- object: struct { name: []const u8 },
-
- pub fn name(self: Hash) []const u8 {
- return switch (self) {
- .string => |s| s,
- .object => |o| o.name,
- };
- }
- };
+ /// 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 const Pbkdf2Params = struct {
hash: Hash,
@@ -136,9 +145,12 @@ pub const Derive = union(enum) {
/// the more specific shapes win.
pub const DerivedKey = union(enum) {
/// `length` as in Import.hmac.
- hmac: struct { hash: Derive.Hash, length: ?js.Value = null, name: []const u8 },
+ 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,
};
@@ -147,10 +159,7 @@ pub const DerivedKey = union(enum) {
/// JS value coerces to a string).
pub const Import = union(enum) {
hmac: struct {
- hash: union(enum) {
- string: []const u8,
- object: struct { name: []const u8 },
- },
+ hash: Hash,
/// HMAC's [EnforceRange] unsigned long, kept as a value: RSA imports
/// share this variant and ignore it. HMAC.lengthParam converts it.
length: ?js.Value = null,
@@ -158,13 +167,18 @@ pub const Import = union(enum) {
},
ec: struct { name: []const u8, namedCurve: []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,
- pub fn algoName(self: Import) []const u8 {
+ /// Null for an object without a name.
+ pub fn algoName(self: Import) ?[]const u8 {
return switch (self) {
.hmac => |h| h.name,
.ec => |e| e.name,
.object => |o| o.name,
+ .nameless => null,
.name => |n| n,
};
}
@@ -222,11 +236,16 @@ pub const Encrypt = union(enum) {
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,
- pub fn algoName(self: Encrypt) []const u8 {
+ /// Null for an object without a name.
+ pub fn algoName(self: Encrypt) ?[]const u8 {
return switch (self) {
.params => |p| p.name,
+ .nameless => null,
.name => |n| n,
};
}
@@ -245,18 +264,23 @@ pub const Sign = union(enum) {
/// 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,
- pub fn algoName(self: Sign) []const u8 {
+ /// Null for an object without a name.
+ pub fn algoName(self: Sign) ?[]const u8 {
return switch (self) {
.string => |string| string,
.object => |object| object.name,
+ .nameless => null,
};
}
/// The `hash` member, if present.
pub fn hash(self: Sign) ?js.Value {
return switch (self) {
- .string => null,
+ .string, .nameless => null,
.object => |object| object.hash,
};
}
@@ -264,7 +288,7 @@ pub const Sign = union(enum) {
/// The `saltLength` member, if present.
pub fn saltLength(self: Sign) ?js.Value {
return switch (self) {
- .string => null,
+ .string, .nameless => null,
.object => |object| object.saltLength,
};
}