Skip to content

[v20.x backport] various WebCryptoAPI and WPT updates #58589

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions lib/internal/crypto/cfrg.js
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,14 @@ async function cfrgImportKey(
'DataError');
}

if (keyData.alg !== undefined && (name === 'Ed25519' || name === 'Ed448')) {
if (keyData.alg !== name && keyData.alg !== 'EdDSA') {
throw lazyDOMException(
'JWK "alg" does not match the requested algorithm',
'DataError');
}
}

if (!isPublic && typeof keyData.x !== 'string') {
throw lazyDOMException('Invalid JWK', 'DataError');
}
Expand Down
3 changes: 2 additions & 1 deletion lib/internal/crypto/hkdf.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const {
ArrayBuffer,
FunctionPrototypeCall,
} = primordials;

Expand Down Expand Up @@ -141,7 +142,7 @@ async function hkdfDeriveBits(algorithm, baseKey, length) {
const { hash, salt, info } = algorithm;

if (length === 0)
throw lazyDOMException('length cannot be zero', 'OperationError');
return new ArrayBuffer(0);
if (length === null)
throw lazyDOMException('length cannot be null', 'OperationError');
if (length % 8) {
Expand Down
7 changes: 3 additions & 4 deletions lib/internal/crypto/pbkdf2.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const {
ArrayBuffer,
FunctionPrototypeCall,
} = primordials;

Expand Down Expand Up @@ -98,10 +99,8 @@ async function pbkdf2DeriveBits(algorithm, baseKey, length) {
'iterations cannot be zero',
'OperationError');

const raw = baseKey[kKeyObject].export();

if (length === 0)
throw lazyDOMException('length cannot be zero', 'OperationError');
return new ArrayBuffer(0);
if (length === null)
throw lazyDOMException('length cannot be null', 'OperationError');
if (length % 8) {
Expand All @@ -113,7 +112,7 @@ async function pbkdf2DeriveBits(algorithm, baseKey, length) {
let result;
try {
result = await pbkdf2Promise(
raw, salt, iterations, length / 8, normalizeHashName(hash.name),
baseKey[kKeyObject].export(), salt, iterations, length / 8, normalizeHashName(hash.name),
);
} catch (err) {
throw lazyDOMException(
Expand Down
1 change: 1 addition & 0 deletions lib/internal/crypto/webcrypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,7 @@ async function exportKeyJWK(key) {
// Fall through
case 'Ed448':
jwk.crv ||= key.algorithm.name;
jwk.alg = key.algorithm.name;
return jwk;
case 'AES-CTR':
// Fall through
Expand Down
12 changes: 10 additions & 2 deletions test/common/wpt.js
Original file line number Diff line number Diff line change
Expand Up @@ -451,8 +451,16 @@ class StatusLoader {

load() {
const dir = path.join(__dirname, '..', 'wpt');
const statusFile = path.join(dir, 'status', `${this.path}.json`);
const result = JSON.parse(fs.readFileSync(statusFile, 'utf8'));
let statusFile = path.join(dir, 'status', `${this.path}.json`);
let result;

if (fs.existsSync(statusFile)) {
result = JSON.parse(fs.readFileSync(statusFile, 'utf8'));
} else {
statusFile = path.join(dir, 'status', `${this.path}.cjs`);
result = require(statusFile);
}

this.rules.addRules(result);

const subDir = fixtures.path('wpt', this.path);
Expand Down
6 changes: 3 additions & 3 deletions test/fixtures/wpt/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ Last update:
- interfaces: https://github.com/web-platform-tests/wpt/tree/df731dab88/interfaces
- performance-timeline: https://github.com/web-platform-tests/wpt/tree/17ebc3aea0/performance-timeline
- resource-timing: https://github.com/web-platform-tests/wpt/tree/22d38586d0/resource-timing
- resources: https://github.com/web-platform-tests/wpt/tree/1e140d63ec/resources
- resources: https://github.com/web-platform-tests/wpt/tree/919874f84f/resources
- streams: https://github.com/web-platform-tests/wpt/tree/2bd26e124c/streams
- url: https://github.com/web-platform-tests/wpt/tree/67880a4eb8/url
- user-timing: https://github.com/web-platform-tests/wpt/tree/5ae85bf826/user-timing
- wasm/jsapi: https://github.com/web-platform-tests/wpt/tree/cde25e7e3c/wasm/jsapi
- wasm/webapi: https://github.com/web-platform-tests/wpt/tree/fd1b23eeaa/wasm/webapi
- WebCryptoAPI: https://github.com/web-platform-tests/wpt/tree/5e042cbc4e/WebCryptoAPI
- WebCryptoAPI: https://github.com/web-platform-tests/wpt/tree/edd42c005c/WebCryptoAPI
- webidl/ecmascript-binding/es-exceptions: https://github.com/web-platform-tests/wpt/tree/a370aad338/webidl/ecmascript-binding/es-exceptions
- webmessaging/broadcastchannel: https://github.com/web-platform-tests/wpt/tree/e97fac4791/webmessaging/broadcastchannel

[Web Platform Tests]: https://github.com/web-platform-tests/wpt
[`git node wpt`]: https://github.com/nodejs/node-core-utils/blob/main/docs/git-node.md#git-node-wpt
[`git node wpt`]: https://github.com/nodejs/node-core-utils/blob/main/docs/git-node.md#git-node-wpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// META: title=WebCryptoAPI: CryptoKey cached ECMAScript objects

// https://w3c.github.io/webcrypto/#dom-cryptokey-algorithm
// https://github.com/servo/servo/issues/33908

promise_test(function() {
return self.crypto.subtle.generateKey(
{
name: "AES-CTR",
length: 256,
},
true,
["encrypt"],
).then(
function(key) {
let a = key.algorithm;
let b = key.algorithm;
assert_true(a === b);
},
function(err) {
assert_unreached("generateKey threw an unexpected error: " + err.toString());
}
);
}, "CryptoKey.algorithm getter returns cached object");

promise_test(function() {
return self.crypto.subtle.generateKey(
{
name: "AES-CTR",
length: 256,
},
true,
["encrypt"],
).then(
function(key) {
let a = key.usages;
let b = key.usages;
assert_true(a === b);
},
function(err) {
assert_unreached("generateKey threw an unexpected error: " + err.toString());
}
);
}, "CryptoKey.usages getter returns cached object");
73 changes: 32 additions & 41 deletions test/fixtures/wpt/WebCryptoAPI/derive_bits_keys/cfrg_curves_bits.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
function define_tests_25519() {
return define_tests("X25519");
}

function define_tests_448() {
return define_tests("X448");
}

function define_tests() {
function define_tests(algorithmName) {
// May want to test prefixed implementations.
var subtle = self.crypto.subtle;

// Verify the derive functions perform checks against the all-zero value results,
// ensuring small-order points are rejected.
// https://www.rfc-editor.org/rfc/rfc7748#section-6.1
// TODO: The spec states that the check must be done on use, but there is discussion about doing it on import.
// https://github.com/WICG/webcrypto-secure-curves/pull/13
Object.keys(kSmallOrderPoint).forEach(function(algorithmName) {
{
kSmallOrderPoint[algorithmName].forEach(function(test) {
promise_test(async() => {
let derived;
Expand All @@ -23,22 +28,23 @@ function define_tests() {
false, [])
derived = await subtle.deriveBits({name: algorithmName, public: publicKey}, privateKey, 8 * sizes[algorithmName]);
} catch (err) {
assert_false(privateKey === undefined, "Private key should be valid.");
assert_false(publicKey === undefined, "Public key should be valid.");
assert_true(privateKey !== undefined, "Private key should be valid.");
assert_true(publicKey !== undefined, "Public key should be valid.");
assert_equals(err.name, "OperationError", "Should throw correct error, not " + err.name + ": " + err.message + ".");
}
assert_equals(derived, undefined, "Operation succeeded, but should not have.");
}, algorithmName + " key derivation checks for all-zero value result with a key of order " + test.order);
});
});
}

return importKeys(pkcs8, spki, sizes)
.then(function(results) {
publicKeys = results.publicKeys;
privateKeys = results.privateKeys;
noDeriveBitsKeys = results.noDeriveBitsKeys;
ecdhKeys = results.ecdhKeys;

Object.keys(sizes).forEach(function(algorithmName) {
{
// Basic success case
promise_test(function(test) {
return subtle.deriveBits({name: algorithmName, public: publicKeys[algorithmName]}, privateKeys[algorithmName], 8 * sizes[algorithmName])
Expand All @@ -59,25 +65,6 @@ function define_tests() {
});
}, algorithmName + " mixed case parameters");

// Null length
// "Null" is not valid per the current spec
// - https://github.com/w3c/webcrypto/issues/322
// - https://github.com/w3c/webcrypto/issues/329
//
// Proposal for a spec change:
// - https://github.com/w3c/webcrypto/pull/345
//
// This test case may be replaced by these new tests:
// - https://github.com/web-platform-tests/wpt/pull/43400
promise_test(function(test) {
return subtle.deriveBits({name: algorithmName, public: publicKeys[algorithmName]}, privateKeys[algorithmName], null)
.then(function(derivation) {
assert_true(equalBuffers(derivation, derivations[algorithmName]), "Derived correct bits");
}, function(err) {
assert_unreached("deriveBits failed with error " + err.name + ": " + err.message);
});
}, algorithmName + " with null length");

// Shorter than entire derivation per algorithm
promise_test(function(test) {
return subtle.deriveBits({name: algorithmName, public: publicKeys[algorithmName]}, privateKeys[algorithmName], 8 * sizes[algorithmName] - 32)
Expand Down Expand Up @@ -122,11 +109,7 @@ function define_tests() {

// - wrong algorithm
promise_test(function(test) {
publicKey = publicKeys["X25519"];
if (algorithmName === "X25519") {
publicKey = publicKeys["X448"];
}
return subtle.deriveBits({name: algorithmName, public: publicKey}, privateKeys[algorithmName], 8 * sizes[algorithmName])
return subtle.deriveBits({name: algorithmName, public: ecdhKeys[algorithmName]}, privateKeys[algorithmName], 8 * sizes[algorithmName])
.then(function(derivation) {
assert_unreached("deriveBits succeeded but should have failed with InvalidAccessError");
}, function(err) {
Expand Down Expand Up @@ -186,16 +169,17 @@ function define_tests() {
assert_equals(err.name, "OperationError", "Should throw correct error, not " + err.name + ": " + err.message);
});
}, algorithmName + " asking for too many bits");
});
}
});

function importKeys(pkcs8, spki, sizes) {
var privateKeys = {};
var publicKeys = {};
var noDeriveBitsKeys = {};
var ecdhPublicKeys = {};

var promises = [];
Object.keys(pkcs8).forEach(function(algorithmName) {
{
var operation = subtle.importKey("pkcs8", pkcs8[algorithmName],
{name: algorithmName},
false, ["deriveBits", "deriveKey"])
Expand All @@ -205,8 +189,8 @@ function define_tests() {
privateKeys[algorithmName] = null;
});
promises.push(operation);
});
Object.keys(pkcs8).forEach(function(algorithmName) {
}
{
var operation = subtle.importKey("pkcs8", pkcs8[algorithmName],
{name: algorithmName},
false, ["deriveKey"])
Expand All @@ -216,8 +200,8 @@ function define_tests() {
noDeriveBitsKeys[algorithmName] = null;
});
promises.push(operation);
});
Object.keys(spki).forEach(function(algorithmName) {
}
{
var operation = subtle.importKey("spki", spki[algorithmName],
{name: algorithmName},
false, [])
Expand All @@ -227,10 +211,17 @@ function define_tests() {
publicKeys[algorithmName] = null;
});
promises.push(operation);
});

}
{
var operation = subtle.importKey("spki", ecSPKI,
{name: "ECDH", namedCurve: "P-256"},
false, [])
.then(function(key) {
ecdhPublicKeys[algorithmName] = key;
});
}
return Promise.all(promises)
.then(function(results) {return {privateKeys: privateKeys, publicKeys: publicKeys, noDeriveBitsKeys: noDeriveBitsKeys}});
.then(function(results) {return {privateKeys: privateKeys, publicKeys: publicKeys, noDeriveBitsKeys: noDeriveBitsKeys, ecdhKeys: ecdhPublicKeys}});
}

// Compares two ArrayBuffer or ArrayBufferView objects. If bitCount is
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// META: title=WebCryptoAPI: deriveKey() Using ECDH with CFRG Elliptic Curves
// META: script=cfrg_curves_bits_fixtures.js
// META: script=cfrg_curves_bits.js

// Define subtests from a `promise_test` to ensure the harness does not
// complete before the subtests are available. `explicit_done` cannot be used
// for this purpose because the global `done` function is automatically invoked
// by the WPT infrastructure in dedicated worker tests defined using the
// "multi-global" pattern.
promise_test(define_tests_25519, 'setup - define tests');
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// META: title=WebCryptoAPI: deriveBits() Using ECDH with CFRG Elliptic Curves
// META: title=WebCryptoAPI: deriveKey() Using ECDH with CFRG Elliptic Curves
// META: script=cfrg_curves_bits_fixtures.js
// META: script=cfrg_curves_bits.js

Expand All @@ -7,4 +7,4 @@
// for this purpose because the global `done` function is automatically invoked
// by the WPT infrastructure in dedicated worker tests defined using the
// "multi-global" pattern.
promise_test(define_tests, 'setup - define tests');
promise_test(define_tests_448, 'setup - define tests');

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading