From 14f8ae4dd8bede83f4e4fc9f7fd532ab5e2c05b8 Mon Sep 17 00:00:00 2001 From: Dmitry Volyntsev Date: Thu, 12 Nov 2026 18:26:58 -0800 Subject: [PATCH] WebCrypto: reject empty HMAC keys in importKey() Previously, importKey() accepted an empty raw or JWK HMAC key. The HMAC import key operation requires a DataError when the key data length is zero. It is reported as TypeError, as other invalid key data in njs. The issue was introduced in 7b2b7612 (0.7.0) and the QuickJS counterpart in 75ca26f8 (0.8.10). --- external/njs_webcrypto_module.c | 5 +++++ external/qjs_webcrypto_module.c | 5 +++++ test/webcrypto/import.t.mjs | 12 ++++++++++++ 3 files changed, 22 insertions(+) diff --git a/external/njs_webcrypto_module.c b/external/njs_webcrypto_module.c index 61b3e6c9..f12244ea 100644 --- a/external/njs_webcrypto_module.c +++ b/external/njs_webcrypto_module.c @@ -4298,6 +4298,11 @@ njs_webcrypto_import_key_internal(njs_vm_t *vm, njs_webcrypto_key_format_t fmt, } } + if (key->u.s.raw.length == 0) { + njs_vm_type_error(vm, "HMAC key cannot be empty"); + goto fail; + } + break; case NJS_ALGORITHM_AES_GCM: diff --git a/external/qjs_webcrypto_module.c b/external/qjs_webcrypto_module.c index 5defe8c9..f4b22b69 100644 --- a/external/qjs_webcrypto_module.c +++ b/external/qjs_webcrypto_module.c @@ -4294,6 +4294,11 @@ qjs_webcrypto_import_key_internal(JSContext *cx, qjs_webcrypto_key_format_t fmt, } } + if (wkey->u.s.raw.length == 0) { + JS_ThrowTypeError(cx, "HMAC key cannot be empty"); + goto fail; + } + break; case QJS_ALGORITHM_AES_GCM: diff --git a/test/webcrypto/import.t.mjs b/test/webcrypto/import.t.mjs index 9972d68d..0160d7c4 100644 --- a/test/webcrypto/import.t.mjs +++ b/test/webcrypto/import.t.mjs @@ -424,6 +424,12 @@ let hmac_tsuite = { extractable: true, usage: [ "sign", "verify" ] }, exception: "TypeError: unknown hash name: \"SHA-385\"" }, + { key: { fmt: "raw", + key: "", + alg: { name: "HMAC", hash: "SHA-256" }, + extractable: true, + usage: [ "sign", "verify" ] }, + exception: "TypeError: HMAC key cannot be empty" }, { key: { fmt: "spki", key: "ec.spki", alg: { name: "HMAC" }, @@ -489,6 +495,12 @@ let hmac_tsuite = { extractable: true, usage: [ "sign" ]}, exception: "TypeError: Invalid JWK oct key" }, + { key: { fmt: "jwk", + key: { alg: 'HS256', ext: true, k: '', kty: 'oct' }, + alg: { name: "HMAC", hash: "SHA-256" }, + extractable: true, + usage: [ "sign" ]}, + exception: "TypeError: HMAC key cannot be empty" }, { key: { fmt: "jwk", key: { alg: 'HS256', k: 'AA', key_ops: [ 'sign' ], kty: 'oct' }, alg: { name: "HMAC", hash: "SHA-256" }, -- 2.47.3