From: Dmitry Volyntsev Date: Fri, 13 Nov 2026 02:26:58 +0000 (-0800) Subject: WebCrypto: reject empty HMAC keys in importKey() X-Git-Url: https://git.kaiwu.me/http/$%7BGITURL%7D$%7Bcid%7D?a=commitdiff_plain;h=HEAD;p=njs.git 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). --- 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" },