Skip to content

Commit f921a05

Browse files
mcollinaUzlopak
andauthored
Merge pull request from GHSA-376v-xgjx-7mfr
* Correctly use crypto.timingSafeEqual Signed-off-by: Matteo Collina <hello@matteocollina.com> Co-Authored-By: Uzlopak <aras.abbasi@googlemail.com> * apply requested change Co-authored-by: Uzlopak <aras.abbasi@googlemail.com>
1 parent c435e93 commit f921a05

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

Diff for: plugin.js

+14-5
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,13 @@ function verifyBearerAuthFactory (options) {
1818
if (_options.keys instanceof Set) _options.keys = Array.from(_options.keys)
1919
const { keys, errorResponse, contentType, bearerType, auth, addHook = true, verifyErrorLogLevel = 'error' } = _options
2020

21+
for (let i = 0, il = keys.length; i < il; ++i) {
22+
if (typeof keys[i] !== 'string') {
23+
throw new Error('options.keys has to contain only string entries')
24+
}
25+
keys[i] = Buffer.from(keys[i])
26+
}
27+
2128
return function verifyBearerAuth (request, reply, done) {
2229
const header = request.raw.headers.authorization
2330
if (!header) {
@@ -89,17 +96,19 @@ function verifyBearerAuthFactory (options) {
8996
}
9097

9198
function authenticate (keys, key) {
92-
return keys.findIndex((a) => compare(a, key)) !== -1
99+
const b = Buffer.from(key)
100+
return keys.findIndex((a) => compare(a, b)) !== -1
93101
}
94102

95103
// perform constant-time comparison to prevent timing attacks
96104
function compare (a, b) {
97-
try {
98-
// may throw if they have different length, can't convert to Buffer, etc...
99-
return crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b))
100-
} catch {
105+
if (a.length !== b.length) {
106+
// Delay return with cryptographically secure timing check.
107+
crypto.timingSafeEqual(a, a)
101108
return false
102109
}
110+
111+
return crypto.timingSafeEqual(a, b)
103112
}
104113

105114
function plugin (fastify, options, done) {

Diff for: test/decorate.test.js

+8
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,11 @@ test('verifyBearerAuthFactory', (t) => {
2020
t.ok(fastify.verifyBearerAuthFactory)
2121
})
2222
})
23+
24+
test('verifyBearerAuthFactory', (t) => {
25+
t.plan(1)
26+
fastify.ready(() => {
27+
const keys = { keys: new Set([123456]) }
28+
t.throws(() => fastify.verifyBearerAuthFactory(keys), /keys has to contain only string entries/)
29+
})
30+
})

0 commit comments

Comments
 (0)