Skip to content

Commit c993eb5

Browse files
authored
Merge pull request #172 from node-oauth/release-4.3.0
merge release 4.3.0 into master
2 parents e01e841 + cf7b701 commit c993eb5

16 files changed

+748
-81
lines changed

.github/workflows/tests-release.yml

+17-32
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@ jobs:
2323
runs-on: ubuntu-latest
2424

2525
steps:
26-
- uses: actions/checkout@v2
27-
- uses: actions/setup-node@v2
26+
- uses: actions/checkout@v3
27+
- uses: actions/setup-node@v3
2828
with:
29-
node-version: '12'
29+
node-version: '14'
3030
# install to create local package-lock.json but don't cache the files
3131
# also: no audit for dev dependencies
3232
- run: npm i --package-lock-only && npm audit --production
@@ -40,24 +40,16 @@ jobs:
4040
needs: [audit]
4141
strategy:
4242
matrix:
43-
node: [12, 14, 16]
43+
node: [14, 16, 18]
4444
steps:
4545
- name: Checkout ${{ matrix.node }}
46-
uses: actions/checkout@v2
46+
uses: actions/checkout@v3
4747

4848
- name: Setup node ${{ matrix.node }}
49-
uses: actions/setup-node@v2
49+
uses: actions/setup-node@v3
5050
with:
5151
node-version: ${{ matrix.node }}
5252

53-
- name: Cache dependencies ${{ matrix.node }}
54-
uses: actions/cache@v1
55-
with:
56-
path: ~/.npm
57-
key: ${{ runner.os }}-node-${{ matrix.node }}-${{ hashFiles('**/package-lock.json') }}
58-
restore-keys: |
59-
${{ runner.os }}-node-${{ matrix.node }}
60-
6153
# for this workflow we also require npm audit to pass
6254
- run: npm i
6355
- run: npm run test:coverage
@@ -81,35 +73,28 @@ jobs:
8173
needs: [unittest]
8274
strategy:
8375
matrix:
84-
node: [12, 14] # TODO get running for node 16
76+
node: [14] # TODO get running for node 16 once we removed bluebird dependency
8577
steps:
8678
# checkout this repo
8779
- name: Checkout ${{ matrix.node }}
88-
uses: actions/checkout@v2
80+
uses: actions/checkout@v3
8981

9082
# checkout express-adapter repo
9183
- name: Checkout express-adapter ${{ matrix.node }}
92-
uses: actions/checkout@v2
84+
uses: actions/checkout@v3
9385
with:
9486
repository: node-oauth/express-oauth-server
9587
path: github/testing/express
9688

9789
- name: Setup node ${{ matrix.node }}
98-
uses: actions/setup-node@v2
90+
uses: actions/setup-node@v3
9991
with:
10092
node-version: ${{ matrix.node }}
10193

102-
- name: Cache dependencies ${{ matrix.node }}
103-
uses: actions/cache@v1
104-
with:
105-
path: ~/.npm
106-
key: ${{ runner.os }}-node-${{ matrix.node }}-node-oauth/express-oauth-server-${{ hashFiles('github/testing/express/**/package-lock.json') }}
107-
restore-keys: |
108-
${{ runner.os }}-node-${{ matrix.node }}-node-oauth/express-oauth-server
109-
11094
# in order to test the adapter we need to use the current checkout
11195
# and install it as local dependency
11296
# we just cloned and install it as local dependency
97+
# xxx: added bluebird as explicit dependency
11398
- run: |
11499
cd github/testing/express
115100
npm i
@@ -122,10 +107,10 @@ jobs:
122107
runs-on: ubuntu-latest
123108
needs: [integrationtests]
124109
steps:
125-
- uses: actions/checkout@v2
126-
- uses: actions/setup-node@v2
110+
- uses: actions/checkout@v3
111+
- uses: actions/setup-node@v3
127112
with:
128-
node-version: 12
113+
node-version: 14
129114
registry-url: https://registry.npmjs.org/
130115
- run: npm i
131116
- run: npm publish --dry-run
@@ -139,11 +124,11 @@ jobs:
139124
contents: read
140125
packages: write
141126
steps:
142-
- uses: actions/checkout@v2
143-
- uses: actions/setup-node@v2
127+
- uses: actions/checkout@v3
128+
- uses: actions/setup-node@v3
144129
with:
145130
# we always publish targeting the lowest supported node version
146-
node-version: 12
131+
node-version: 14
147132
registry-url: $registry-url(npm)
148133
- run: npm i
149134
- run: npm publish --dry-run

.github/workflows/tests.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ jobs:
1818
runs-on: ubuntu-latest
1919
strategy:
2020
matrix:
21-
node: [12, 14, 16]
21+
node: [14, 16, 18]
2222
steps:
2323
- name: Checkout ${{ matrix.node }}
2424
uses: actions/checkout@v2

index.d.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ declare namespace OAuth2Server {
306306
*
307307
*/
308308
saveAuthorizationCode(
309-
code: Pick<AuthorizationCode, 'authorizationCode' | 'expiresAt' | 'redirectUri' | 'scope'>,
309+
code: Pick<AuthorizationCode, 'authorizationCode' | 'expiresAt' | 'redirectUri' | 'scope' | 'codeChallenge' | 'codeChallengeMethod'>,
310310
client: Client,
311311
user: User,
312312
callback?: Callback<AuthorizationCode>): Promise<AuthorizationCode | Falsey>;
@@ -410,6 +410,8 @@ declare namespace OAuth2Server {
410410
scope?: string | string[] | undefined;
411411
client: Client;
412412
user: User;
413+
codeChallenge?: string;
414+
codeChallengeMethod?: string;
413415
[key: string]: any;
414416
}
415417

lib/grant-types/authorization-code-grant-type.js

+31
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const promisify = require('promisify-any').use(Promise);
1313
const ServerError = require('../errors/server-error');
1414
const isFormat = require('@node-oauth/formats');
1515
const util = require('util');
16+
const pkce = require('../pkce/pkce');
1617

1718
/**
1819
* Constructor.
@@ -118,6 +119,36 @@ AuthorizationCodeGrantType.prototype.getAuthorizationCode = function(request, cl
118119
throw new InvalidGrantError('Invalid grant: `redirect_uri` is not a valid URI');
119120
}
120121

122+
// optional: PKCE code challenge
123+
124+
if (code.codeChallenge) {
125+
if (!request.body.code_verifier) {
126+
throw new InvalidGrantError('Missing parameter: `code_verifier`');
127+
}
128+
129+
const hash = pkce.getHashForCodeChallenge({
130+
method: code.codeChallengeMethod,
131+
verifier: request.body.code_verifier
132+
});
133+
134+
if (!hash) {
135+
// notice that we assume that codeChallengeMethod is already
136+
// checked at an earlier stage when being read from
137+
// request.body.code_challenge_method
138+
throw new ServerError('Server error: `getAuthorizationCode()` did not return a valid `codeChallengeMethod` property');
139+
}
140+
141+
if (code.codeChallenge !== hash) {
142+
throw new InvalidGrantError('Invalid grant: code verifier is invalid');
143+
}
144+
}
145+
else {
146+
if (request.body.code_verifier) {
147+
// No code challenge but code_verifier was passed in.
148+
throw new InvalidGrantError('Invalid grant: code verifier is invalid');
149+
}
150+
}
151+
121152
return code;
122153
});
123154
};

lib/handlers/authorize-handler.js

+35-8
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ const UnauthorizedClientError = require('../errors/unauthorized-client-error');
2121
const isFormat = require('@node-oauth/formats');
2222
const tokenUtil = require('../utils/token-util');
2323
const url = require('url');
24+
const pkce = require('../pkce/pkce');
2425

2526
/**
2627
* Response types.
@@ -77,10 +78,6 @@ AuthorizeHandler.prototype.handle = function(request, response) {
7778
throw new InvalidArgumentError('Invalid argument: `response` must be an instance of Response');
7879
}
7980

80-
if (request.query.allowed === 'false' || request.body.allowed === 'false') {
81-
return Promise.reject(new AccessDeniedError('Access denied: user denied access to application'));
82-
}
83-
8481
const fns = [
8582
this.getAuthorizationCodeLifetime(),
8683
this.getClient(request),
@@ -98,7 +95,7 @@ AuthorizeHandler.prototype.handle = function(request, response) {
9895
return Promise.bind(this)
9996
.then(function() {
10097
state = this.getState(request);
101-
if(request.query.allowed === 'false') {
98+
if (request.query.allowed === 'false' || request.body.allowed === 'false') {
10299
throw new AccessDeniedError('Access denied: user denied access to application');
103100
}
104101
})
@@ -114,8 +111,10 @@ AuthorizeHandler.prototype.handle = function(request, response) {
114111
})
115112
.then(function(authorizationCode) {
116113
ResponseType = this.getResponseType(request);
114+
const codeChallenge = this.getCodeChallenge(request);
115+
const codeChallengeMethod = this.getCodeChallengeMethod(request);
117116

118-
return this.saveAuthorizationCode(authorizationCode, expiresAt, scope, client, uri, user);
117+
return this.saveAuthorizationCode(authorizationCode, expiresAt, scope, client, uri, user, codeChallenge, codeChallengeMethod);
119118
})
120119
.then(function(code) {
121120
const responseType = new ResponseType(code.authorizationCode);
@@ -293,13 +292,20 @@ AuthorizeHandler.prototype.getRedirectUri = function(request, client) {
293292
* Save authorization code.
294293
*/
295294

296-
AuthorizeHandler.prototype.saveAuthorizationCode = function(authorizationCode, expiresAt, scope, client, redirectUri, user) {
297-
const code = {
295+
AuthorizeHandler.prototype.saveAuthorizationCode = function(authorizationCode, expiresAt, scope, client, redirectUri, user, codeChallenge, codeChallengeMethod) {
296+
let code = {
298297
authorizationCode: authorizationCode,
299298
expiresAt: expiresAt,
300299
redirectUri: redirectUri,
301300
scope: scope
302301
};
302+
303+
if(codeChallenge && codeChallengeMethod){
304+
code = Object.assign({
305+
codeChallenge: codeChallenge,
306+
codeChallengeMethod: codeChallengeMethod
307+
}, code);
308+
}
303309
return promisify(this.model.saveAuthorizationCode, 3).call(this.model, code, client, user);
304310
};
305311

@@ -369,6 +375,27 @@ AuthorizeHandler.prototype.updateResponse = function(response, redirectUri, stat
369375
response.redirect(url.format(redirectUri));
370376
};
371377

378+
AuthorizeHandler.prototype.getCodeChallenge = function(request) {
379+
return request.body.code_challenge;
380+
};
381+
382+
/**
383+
* Get code challenge method from request or defaults to plain.
384+
* https://www.rfc-editor.org/rfc/rfc7636#section-4.3
385+
*
386+
* @throws {InvalidRequestError} if request contains unsupported code_challenge_method
387+
* (see https://www.rfc-editor.org/rfc/rfc7636#section-4.4)
388+
*/
389+
AuthorizeHandler.prototype.getCodeChallengeMethod = function(request) {
390+
const algorithm = request.body.code_challenge_method;
391+
392+
if (algorithm && !pkce.isValidMethod(algorithm)) {
393+
throw new InvalidRequestError(`Invalid request: transform algorithm '${algorithm}' not supported`);
394+
}
395+
396+
return algorithm || 'plain';
397+
};
398+
372399
/**
373400
* Export constructor.
374401
*/

lib/handlers/token-handler.js

+11-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ const TokenModel = require('../models/token-model');
1818
const UnauthorizedClientError = require('../errors/unauthorized-client-error');
1919
const UnsupportedGrantTypeError = require('../errors/unsupported-grant-type-error');
2020
const auth = require('basic-auth');
21+
const pkce = require('../pkce/pkce');
2122
const isFormat = require('@node-oauth/formats');
2223

2324
/**
@@ -114,12 +115,14 @@ TokenHandler.prototype.handle = function(request, response) {
114115
TokenHandler.prototype.getClient = function(request, response) {
115116
const credentials = this.getClientCredentials(request);
116117
const grantType = request.body.grant_type;
118+
const codeVerifier = request.body.code_verifier;
119+
const isPkce = pkce.isPKCERequest({ grantType, codeVerifier });
117120

118121
if (!credentials.clientId) {
119122
throw new InvalidRequestError('Missing parameter: `client_id`');
120123
}
121124

122-
if (this.isClientAuthenticationRequired(grantType) && !credentials.clientSecret) {
125+
if (this.isClientAuthenticationRequired(grantType) && !credentials.clientSecret && !isPkce) {
123126
throw new InvalidRequestError('Missing parameter: `client_secret`');
124127
}
125128

@@ -174,6 +177,7 @@ TokenHandler.prototype.getClient = function(request, response) {
174177
TokenHandler.prototype.getClientCredentials = function(request) {
175178
const credentials = auth(request);
176179
const grantType = request.body.grant_type;
180+
const codeVerifier = request.body.code_verifier;
177181

178182
if (credentials) {
179183
return { clientId: credentials.name, clientSecret: credentials.pass };
@@ -183,6 +187,12 @@ TokenHandler.prototype.getClientCredentials = function(request) {
183187
return { clientId: request.body.client_id, clientSecret: request.body.client_secret };
184188
}
185189

190+
if (pkce.isPKCERequest({ grantType, codeVerifier })) {
191+
if(request.body.client_id) {
192+
return { clientId: request.body.client_id };
193+
}
194+
}
195+
186196
if (!this.isClientAuthenticationRequired(grantType)) {
187197
if(request.body.client_id) {
188198
return { clientId: request.body.client_id };

lib/pkce/pkce.js

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
'use strict';
2+
3+
/**
4+
* Module dependencies.
5+
*/
6+
const { base64URLEncode } = require('../utils/string-util');
7+
const { createHash } = require('../utils/crypto-util');
8+
const codeChallengeRegexp = /^([a-zA-Z0-9.\-_~]){43,128}$/;
9+
/**
10+
* Export `TokenUtil`.
11+
*/
12+
13+
const pkce = {
14+
/**
15+
* Return hash for code-challenge method-type.
16+
*
17+
* @param method {String} the code challenge method
18+
* @param verifier {String} the code_verifier
19+
* @return {String|undefined}
20+
*/
21+
getHashForCodeChallenge: function({ method, verifier }) {
22+
// to prevent undesired side-effects when passing some wird values
23+
// to createHash or base64URLEncode we first check if the values are right
24+
if (pkce.isValidMethod(method) && typeof verifier === 'string' && verifier.length > 0) {
25+
if (method === 'plain') {
26+
return verifier;
27+
}
28+
29+
if (method === 'S256') {
30+
const hash = createHash({ data: verifier });
31+
return base64URLEncode(hash);
32+
}
33+
}
34+
},
35+
36+
/**
37+
* Check if the request is a PCKE request. We assume PKCE if grant type is
38+
* 'authorization_code' and code verifier is present.
39+
*
40+
* @param grantType {String}
41+
* @param codeVerifier {String}
42+
* @return {boolean}
43+
*/
44+
isPKCERequest: function ({ grantType, codeVerifier }) {
45+
return grantType === 'authorization_code' && !!codeVerifier;
46+
},
47+
48+
/**
49+
* Matches a code verifier (or code challenge) against the following criteria:
50+
*
51+
* code-verifier = 43*128unreserved
52+
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
53+
* ALPHA = %x41-5A / %x61-7A
54+
* DIGIT = %x30-39
55+
*
56+
* @see: https://datatracker.ietf.org/doc/html/rfc7636#section-4.1
57+
* @param codeChallenge {String}
58+
* @return {Boolean}
59+
*/
60+
codeChallengeMatchesABNF: function (codeChallenge) {
61+
return typeof codeChallenge === 'string' &&
62+
!!codeChallenge.match(codeChallengeRegexp);
63+
},
64+
65+
/**
66+
* Checks if the code challenge method is one of the supported methods
67+
* 'sha256' or 'plain'
68+
*
69+
* @param method {String}
70+
* @return {boolean}
71+
*/
72+
isValidMethod: function (method) {
73+
return method === 'S256' || method === 'plain';
74+
}
75+
};
76+
77+
module.exports = pkce;

0 commit comments

Comments
 (0)