crypto: fix argument validation in crypto.timingSafeEqual fast path · nodejs/node@ad376c3

1+

// Test v8 fast path for crypto.timingSafeEqual works correctly.

2+

// Flags: --expose-internals --allow-natives-syntax

3+

'use strict';

4+5+

const common = require('../common');

6+7+

if (!common.hasCrypto)

8+

common.skip('missing crypto');

9+10+

const assert = require('assert');

11+

const crypto = require('crypto');

12+13+

// V8 Fast API

14+

const foo = Buffer.from('foo');

15+

const bar = Buffer.from('bar');

16+

const longer = Buffer.from('longer');

17+

function testFastPath(buf1, buf2) {

18+

return crypto.timingSafeEqual(buf1, buf2);

19+

}

20+

eval('%PrepareFunctionForOptimization(testFastPath)');

21+

assert.strictEqual(testFastPath(foo, bar), false);

22+

eval('%OptimizeFunctionOnNextCall(testFastPath)');

23+

assert.strictEqual(testFastPath(foo, bar), false);

24+

assert.strictEqual(testFastPath(foo, foo), true);

25+

assert.throws(() => testFastPath(foo, longer), {

26+

code: 'ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH',

27+

});

28+

assert.throws(() => testFastPath(foo, ''), {

29+

code: 'ERR_INVALID_ARG_TYPE',

30+

});

31+

assert.throws(() => testFastPath('', ''), {

32+

code: 'ERR_INVALID_ARG_TYPE',

33+

});

34+35+

if (common.isDebug) {

36+

const { internalBinding } = require('internal/test/binding');

37+

const { getV8FastApiCallCount } = internalBinding('debug');

38+

assert.strictEqual(getV8FastApiCallCount('crypto.timingSafeEqual.ok'), 2);

39+

assert.strictEqual(getV8FastApiCallCount('crypto.timingSafeEqual.error'), 3);

40+

}