Skip to content
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

Cope with unhandled rejected promises in /token handler #142

Merged
merged 1 commit into from
Nov 17, 2021
Merged
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
182 changes: 93 additions & 89 deletions src/lib/oauth2-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,105 +172,109 @@ export class OAuth2Service extends EventEmitter {
res.json({ keys: this.issuer.keys.toJSON() });
};

private tokenHandler: RequestHandler = async (req, res) => {
const tokenTtl = defaultTokenTtl;

res.set({
'Cache-Control': 'no-store',
Pragma: 'no-cache',
});

let xfn: ScopesOrTransform | undefined;

assertIsValidTokenRequest(req.body);
const reqBody = req.body;
private tokenHandler: RequestHandler = async (req, res, next) => {
try {
const tokenTtl = defaultTokenTtl;

res.set({
'Cache-Control': 'no-store',
Pragma: 'no-cache',
});

let xfn: ScopesOrTransform | undefined;

assertIsValidTokenRequest(req.body);
const reqBody = req.body;

let { scope } = reqBody;

switch (req.body.grant_type) {
case 'client_credentials':
xfn = scope;
break;
case 'password':
xfn = (_header, payload) => {
Object.assign(payload, {
sub: reqBody.username,
amr: ['pwd'],
scope,
});
};
break;
case 'authorization_code':
scope = 'dummy';
xfn = (_header, payload) => {
Object.assign(payload, {
sub: 'johndoe',
amr: ['pwd'],
scope,
});
};
break;
case 'refresh_token':
scope = 'dummy';
xfn = (_header, payload) => {
Object.assign(payload, {
sub: 'johndoe',
amr: ['pwd'],
scope,
});
};
break;
default:
return res.status(400).json({
error: 'invalid_grant',
});
}

let { scope } = reqBody;
const token = await this.buildToken(req, tokenTtl, xfn);
const body: Record<string, unknown> = {
access_token: token,
token_type: 'Bearer',
expires_in: tokenTtl,
scope,
};
if (req.body.grant_type !== 'client_credentials') {
const credentials = basicAuth(req);
const clientId = credentials ? credentials.name : req.body.client_id;

switch (req.body.grant_type) {
case 'client_credentials':
xfn = scope;
break;
case 'password':
xfn = (_header, payload) => {
Object.assign(payload, {
sub: reqBody.username,
amr: ['pwd'],
scope,
});
};
break;
case 'authorization_code':
scope = 'dummy';
xfn = (_header, payload) => {
Object.assign(payload, {
sub: 'johndoe',
amr: ['pwd'],
scope,
});
};
break;
case 'refresh_token':
scope = 'dummy';
xfn = (_header, payload) => {
const xfn: JwtTransform = (_header, payload) => {
Object.assign(payload, {
sub: 'johndoe',
amr: ['pwd'],
scope,
aud: clientId,
});
if (reqBody.code !== undefined && this.#nonce[reqBody.code]) {
Object.assign(payload, {
nonce: this.#nonce[reqBody.code],
});
delete this.#nonce[reqBody.code];
}
};
break;
default:
return res.status(400).json({
error: 'invalid_grant',
});
}

const token = await this.buildToken(req, tokenTtl, xfn);
const body: Record<string, unknown> = {
access_token: token,
token_type: 'Bearer',
expires_in: tokenTtl,
scope,
};
if (req.body.grant_type !== 'client_credentials') {
const credentials = basicAuth(req);
const clientId = credentials ? credentials.name : req.body.client_id;

const xfn: JwtTransform = (_header, payload) => {
Object.assign(payload, {
sub: 'johndoe',
aud: clientId,
});
if (reqBody.code !== undefined && this.#nonce[reqBody.code]) {
Object.assign(payload, {
nonce: this.#nonce[reqBody.code],
});
delete this.#nonce[reqBody.code];
}
};

body.id_token = await this.buildToken(req, tokenTtl, xfn);
body.refresh_token = uuidv4();
}
body.id_token = await this.buildToken(req, tokenTtl, xfn);
body.refresh_token = uuidv4();
}

const tokenEndpointResponse: MutableResponse = {
body,
statusCode: 200,
};
const tokenEndpointResponse: MutableResponse = {
body,
statusCode: 200,
};

/**
* Before token response event.
*
* @event OAuth2Service#beforeResponse
* @param {MutableResponse} response The response body and status code.
* @param {IncomingMessage} req The incoming HTTP request.
*/
this.emit(Events.BeforeResponse, tokenEndpointResponse, req);
/**
* Before token response event.
*
* @event OAuth2Service#beforeResponse
* @param {MutableResponse} response The response body and status code.
* @param {IncomingMessage} req The incoming HTTP request.
*/
this.emit(Events.BeforeResponse, tokenEndpointResponse, req);

return res
.status(tokenEndpointResponse.statusCode)
.json(tokenEndpointResponse.body);
return res
.status(tokenEndpointResponse.statusCode)
.json(tokenEndpointResponse.body);
} catch (e) {
return next(e);
}
};

private authorizeHandler: RequestHandler = (req, res) => {
Expand Down
15 changes: 15 additions & 0 deletions test/oauth2-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,19 @@ describe('OAuth 2 Server', () => {
new OAuth2Server(undefined, "test/keys/localhost-cert.pem");
}).toThrow();
});

it('should not raise an UnhandledPromiseRejectionWarning when wrongly invoking the /token endpoint', async () => {
const server = new OAuth2Server();

await expect(server.start()).resolves.not.toThrow();

const host = `http://127.0.0.1:${server.address().port}`;
const res = await request(host)
.post('/token')
.set('Content-Type', 'multipart/form-data;');

expect(res.text).toContain("[ERR_ASSERTION]: Invalid &#39;grant_type&#39; type");

await expect(server.stop()).resolves.not.toThrow();
});
});