This repository was archived by the owner on Apr 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathauthorization.js
More file actions
230 lines (208 loc) · 7.29 KB
/
authorization.js
File metadata and controls
230 lines (208 loc) · 7.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const hex = require('buf').to.hex;
const Joi = require('joi');
const URI = require('urijs');
const AppError = require('../error');
const config = require('../config');
const db = require('../db');
const logger = require('../logging')('routes.authorization');
const validators = require('../validators');
const { validateRequestedGrant, generateTokens } = require('../grant');
const verifyAssertion = require('../assertion');
const RESPONSE_TYPE_CODE = 'code';
const RESPONSE_TYPE_TOKEN = 'token';
const ACCESS_TYPE_ONLINE = 'online';
const ACCESS_TYPE_OFFLINE = 'offline';
const PKCE_SHA256_CHALLENGE_METHOD = 'S256'; // This server only supports S256 PKCE, no 'plain'
const PKCE_CODE_CHALLENGE_LENGTH = 43;
const MAX_TTL_S = config.get('expiration.accessToken') / 1000;
const allowHttpRedirects = config.get('allowHttpRedirects');
var ALLOWED_SCHEMES = [
'https'
];
if (allowHttpRedirects === true) {
// http scheme used when developing OAuth clients
ALLOWED_SCHEMES.push('http');
}
function isLocalHost(url) {
var host = new URI(url).hostname();
return host === 'localhost' || host === '127.0.0.1';
}
module.exports = {
validate: {
payload: {
client_id: validators.clientId,
assertion: validators.assertion
.required(),
redirect_uri: Joi.string()
.max(256)
// uri validation ref: https://github.com/hapijs/joi/blob/master/API.md#stringurioptions
.uri({
scheme: ALLOWED_SCHEMES
}),
scope: validators.scope,
response_type: Joi.string()
.valid(RESPONSE_TYPE_CODE, RESPONSE_TYPE_TOKEN)
.default(RESPONSE_TYPE_CODE),
state: Joi.string()
.max(256)
.when('response_type', {
is: RESPONSE_TYPE_TOKEN,
then: Joi.optional(),
otherwise: Joi.required()
}),
ttl: Joi.number()
.positive()
.max(MAX_TTL_S)
.default(MAX_TTL_S)
.when('response_type', {
is: RESPONSE_TYPE_TOKEN,
then: Joi.optional(),
otherwise: Joi.forbidden()
}),
access_type: Joi.string()
.valid(ACCESS_TYPE_OFFLINE, ACCESS_TYPE_ONLINE)
.default(ACCESS_TYPE_ONLINE)
.optional(),
code_challenge_method: Joi.string()
.valid(PKCE_SHA256_CHALLENGE_METHOD)
.when('response_type', {
is: RESPONSE_TYPE_CODE,
then: Joi.optional(),
otherwise: Joi.forbidden()
})
.when('code_challenge', {
is: Joi.string().required(),
then: Joi.required()
}),
code_challenge: Joi.string()
.length(PKCE_CODE_CHALLENGE_LENGTH)
.when('response_type', {
is: RESPONSE_TYPE_CODE,
then: Joi.optional(),
otherwise: Joi.forbidden()
}),
keys_jwe: validators.jwe
.when('response_type', {
is: RESPONSE_TYPE_CODE,
then: Joi.optional(),
otherwise: Joi.forbidden()
}),
acr_values: Joi.string().max(256).optional().allow(null)
}
},
response: {
schema: Joi.object().keys({
redirect: Joi.string(),
code: Joi.string(),
state: Joi.string(),
access_token: validators.token,
user: validators.uid,
token_type: Joi.string().valid('bearer'),
scope: Joi.string().allow(''),
auth_at: Joi.number(),
expires_in: Joi.number()
}).with('access_token', [
'token_type',
'scope',
'auth_at',
'expires_in'
]).with('code', [
'state',
'redirect',
]).without('code', [
'access_token'
])
},
handler: async function authorizationEndpoint(req) {
const claims = await verifyAssertion(req.payload.assertion);
const client = await db.getClient(Buffer.from(req.payload.client_id, 'hex'));
if (! client) {
logger.debug('notFound', { id: req.payload.client_id });
throw AppError.unknownClient(req.payload.client_id);
}
validateClientDetails(client, req.payload);
const grant = await validateRequestedGrant(claims, client, req.payload);
switch (req.payload.response_type) {
case RESPONSE_TYPE_CODE:
return await generateAuthorizationCode(client, req.payload, grant);
case RESPONSE_TYPE_TOKEN:
return await generateImplicitGrant(client, req.payload, grant);
default:
// Joi validation means this should never happen.
logger.critical('joi.response_type', { response_type: req.payload.response_type });
throw AppError.invalidResponseType();
}
}
};
async function generateAuthorizationCode(client, payload, grant) {
// Clients must use PKCE if and only if they are a pubic client.
if (client.publicClient) {
if (! payload.code_challenge_method || ! payload.code_challenge) {
logger.info('client.missingPkceParameters');
throw AppError.missingPkceParameters();
}
} else {
if (payload.code_challenge_method || payload.code_challenge) {
logger.info('client.notPublicClient');
throw AppError.notPublicClient({ id: payload.client_id });
}
}
const state = payload.state;
let code = await db.generateCode(Object.assign(grant, {
codeChallengeMethod: payload.code_challenge_method,
codeChallenge: payload.code_challenge,
}));
code = hex(code);
const redirect = URI(payload.redirect_uri).addQuery({ code, state });
return {
code,
state,
redirect: String(redirect)
};
}
// N.B. We do not correctly implement the "implicit grant" flow from
// RFC6749 which defines `response_type=token`. Instead we have a
// privileged set of clients that use `response_type=token` for something
// approximating the "resource owner password grant" flow, using an identity
// assertion to just directly grant tokens for their own use. Known current
// users of this functinality include:
//
// * Firefox Desktop, for getting "profile"-scoped tokens to access profile data
// * Firefox for Android, for getting "profile"-scoped tokens to access profile data
// * Firefox for iOS, for getting "profile"-scoped tokens to access profile data
//
// New clients should not do this, and should instead of `grant_type=fxa-credentials`
// on the /token endpoint.
//
// This route is kept for backwards-compatibility only.
async function generateImplicitGrant(client, payload, grant) {
if (! client.canGrant) {
logger.warn('grantType.notAllowed', {
id: hex(client.id),
grant_type: 'fxa-credentials'
});
throw AppError.invalidResponseType();
}
return generateTokens(Object.assign(grant, {
ttl: payload.ttl,
}));
}
function validateClientDetails(client, payload) {
// Clients must use a single specific redirect_uri,
// but they're allowed to not provide one and have us fill it in automatically.
payload.redirect_uri = payload.redirect_uri || client.redirectUri;
if (payload.redirect_uri !== client.redirectUri) {
logger.debug('redirect.mismatch', {
param: payload.redirect_uri,
registered: client.redirectUri
});
if (config.get('localRedirects') && isLocalHost(payload.redirect_uri)) {
logger.debug('redirect.local', { uri: payload.redirect_uri });
} else {
throw AppError.incorrectRedirect(payload.redirect_uri);
}
}
}