-
Notifications
You must be signed in to change notification settings - Fork 253
/
oauth2.js
370 lines (317 loc) · 12.6 KB
/
oauth2.js
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
const taskcluster = require('taskcluster-client');
const { scopeIntersection } = require('taskcluster-lib-scopes');
const oauth2orize = require('oauth2orize');
const _ = require('lodash');
const WebServerError = require('../utils/WebServerError');
const tryCatch = require('../utils/tryCatch');
const ensureLoggedIn = require('../utils/ensureLoggedIn');
const expressWrapAsync = require('../utils/expressWrapAsync');
const unpromisify = require('../utils/unpromisify');
module.exports = (cfg, AuthorizationCode, AccessToken, strategies, auth, monitor) => {
// Create OAuth 2.0 server
const server = oauth2orize.createServer();
server.serializeClient((client, done) => done(null, {
// Only serialize clientId and use findRegisteredClient afterward
clientId: client.clientId,
}));
server.deserializeClient((client, done) => done(null, client));
function findRegisteredClient(clientId) {
return cfg.login.registeredClients.find(client => client.clientId === clientId);
}
/**
* Grant implicit authorization.
*
* The callback takes the `client` requesting authorization, the authenticated
* `user` granting access, and their response, which contains approved scope,
* duration, etc. as parsed by the application. The application issues a token,
* which is bound to these values.
*/
server.grant(oauth2orize.grant.token(unpromisify(async (client, user, ares, areq) => {
const registeredClient = findRegisteredClient(client.clientId);
if (!registeredClient) {
throw new oauth2orize.AuthorizationError(null, 'unauthorized_client');
}
if (!_.isEqual(registeredClient.scope.sort(), areq.scope.sort())) {
throw new oauth2orize.AuthorizationError(null, 'invalid_scope');
}
if (!registeredClient.redirectUri.some(uri => uri === areq.redirectURI)) {
throw new oauth2orize.AuthorizationError(null, 'access_denied');
}
if (registeredClient.responseType !== 'token') {
throw new oauth2orize.AuthorizationError(null, 'unsupported_response_type');
}
// The access token we give to third parties
const accessToken = new Buffer.from(taskcluster.slugid()).toString('base64');
const currentUser = await strategies[user.identityProviderId].userFromIdentity(user.identity);
const userScopes = (await auth.expandScopes({scopes: currentUser.scopes()})).scopes;
await AccessToken.create({
// OAuth2 client
clientId: registeredClient.clientId,
redirectUri: areq.redirectURI,
identity: user.identity,
identityProviderId: user.identityProviderId,
accessToken: accessToken,
expires: taskcluster.fromNow('10 minutes'),
clientDetails: {
clientId: ares.clientId,
description: ares.description || `Client generated by ${user.identity} for OAuth2 Client ${registeredClient.clientId}`,
scopes: scopeIntersection(ares.scope, userScopes),
expires: ares.expires ?
ares.expires > taskcluster.fromNow(registeredClient.maxExpires) ?
taskcluster.fromNow(registeredClient.maxExpires).toISOString() :
ares.expires.toISOString()
: taskcluster.fromNow(registeredClient.maxExpires).toISOString(),
deleteOnExpiration: true,
},
}, true);
return accessToken;
})));
/**
* Grant authorization codes
*
* The callback takes the `client` requesting authorization, the `redirectURI`
* (which is used as a verifier in the subsequent exchange), the authenticated
* `user` granting access, and their response, which contains approved scope,
* duration, etc. as parsed by the application. The application issues a code,
* which is bound to these values, and will be exchanged for an access token.
*/
server.grant(oauth2orize.grant.code(unpromisify(async (client, redirectURI, user, ares, areq) => {
const code = taskcluster.slugid();
const registeredClient = findRegisteredClient(client.clientId);
if (!registeredClient) {
throw new oauth2orize.AuthorizationError(null, 'unauthorized_client');
}
if (!_.isEqual(registeredClient.scope.sort(), areq.scope.sort())) {
throw new oauth2orize.AuthorizationError(null, 'invalid_scope');
}
if (!registeredClient.redirectUri.some(uri => uri === redirectURI)) {
throw new oauth2orize.AuthorizationError(null, 'access_denied');
}
if (registeredClient.responseType !== 'code') {
throw new oauth2orize.AuthorizationError(null, 'unsupported_response_type');
}
const currentUser = await strategies[user.identityProviderId].userFromIdentity(user.identity);
if (!currentUser) {
throw new oauth2orize.AuthorizationError(null, 'server_error');
}
const userScopes = (await auth.expandScopes({scopes: currentUser.scopes()})).scopes;
await AuthorizationCode.create({
code,
// OAuth2 client
clientId: registeredClient.clientId,
redirectUri: redirectURI,
identity: user.identity,
identityProviderId: user.identityProviderId,
// A maximum of 10 minutes is recommended in https://tools.ietf.org/html/rfc6749#section-4.1.2
expires: taskcluster.fromNow('10 minutes'),
clientDetails: {
clientId: ares.clientId,
description: `Client generated by ${user.identity} for OAuth2 Client ${registeredClient.clientId}`,
scopes: scopeIntersection(ares.scope, userScopes),
expires: ares.expires ?
ares.expires > taskcluster.fromNow(registeredClient.maxExpires) ?
taskcluster.fromNow(registeredClient.maxExpires).toISOString() :
ares.expires.toISOString()
: taskcluster.fromNow(registeredClient.maxExpires).toISOString(),
deleteOnExpiration: true,
},
}, true);
return code;
})));
/**
* After a client has obtained an authorization grant from the user,
* we exchange the authorization code for an access token.
*
* The callback accepts the `client`, which is exchanging `code` and any
* `redirectURI` from the authorization request for verification. If these values
* are validated, the application issues a Taskcluster token on behalf of the user who
* authorized the code.
*/
server.exchange(oauth2orize.exchange.code(unpromisify(async (client, code, redirectURI) => {
const entry = await AuthorizationCode.load({ code }, true);
if (!entry) {
return false;
}
if (redirectURI !== entry.redirectUri) {
return false;
}
// Although we eventually delete expired rows, that only happens once per day
// so we need to check that the accessToken is not expired.
if (new Date(entry.clientDetails.expires) < new Date()) {
return false;
}
const accessToken = new Buffer.from(taskcluster.slugid()).toString('base64');
await AccessToken.create({
// OAuth2 client
clientId: entry.clientId,
redirectUri: redirectURI,
identity: entry.identity,
identityProviderId: entry.identityProviderId,
// The access token we give to third parties
accessToken,
// This table is used alongside the AuthorizationCode table which has a 10 minute recommended expiration
expires: taskcluster.fromNow('10 minutes'),
clientDetails: entry.clientDetails,
}, true);
return accessToken;
})));
const authorization = [
ensureLoggedIn(),
(req, res, done) => {
server.authorization(unpromisify(async (clientID, redirectURI, scope) => {
const client = findRegisteredClient(clientID);
if (!client) {
return [false];
}
if (!client.redirectUri.some(uri => uri === redirectURI)) {
return [false];
}
return [client, redirectURI];
}, {returnsArray: true}),
unpromisify(async (client, user, scope) => {
// Skip consent form if the client is whitelisted
if (client.whitelisted && user && _.isEqual(client.scope.sort(), scope.sort())) {
const opts = {};
if (req.query.expires) {
opts.expires = taskcluster.fromNow(req.query.expires);
}
// If you return `true` in the second argument (the `immediate` argument) it will skip the dialog,
// automatically authorizing the decision.
// It's called to decide whether to immediately approve the request and return a redirect
// to the `redirect_uri`.
return [true, {
scope,
clientId: `${user.identity}/${client.clientId}-${taskcluster.slugid().slice(0, 6)}`,
...opts,
}];
}
return [false];
}, {returnsArray: true}),
)(req, res, done);
},
(req, res) => {
const client = findRegisteredClient(req.query.client_id);
let expires = client.maxExpires;
if (req.query.expires) {
try {
if (new Date(taskcluster.fromNow(req.query.expires)) > new Date(taskcluster.fromNow(client.maxExpires))) {
expires = client.maxExpires;
} else {
expires = req.query.expires;
}
} catch (e) {
// req.query.expires was probably an invalid date.
// We default to the max expiration time defined by the client.
}
}
const query = new URLSearchParams({
transactionID: req.oauth2.transactionID,
client_id: req.query.client_id,
expires,
scope: req.query.scope,
clientId: `${req.user.identity}/${client.clientId}-${taskcluster.slugid().slice(0, 6)}`,
});
res.redirect(`${cfg.app.publicUrl}/third-party?${query}`);
},
server.errorHandler({ mode: 'indirect' }),
];
const decision = [
ensureLoggedIn(),
server.decision((req, done) => {
const { scope, description, expires, clientId } = req.body;
return done(null, {
scope: scope ? scope.split(' ') : [],
description,
expires: new Date(expires),
clientId,
});
}),
server.errorHandler({ mode: 'indirect' }),
];
/**
* Token endpoint
*
* `token` middleware handles client requests to exchange
* an authorization code for a Taskcluster token.
*/
const token = [
server.token(),
server.errorHandler(),
];
/**
* Credential endpoint - Resource server
*
* The Taskcluster deployment acts as a "resource server" by serving Taskcluster
* credentials given a valid OAuth2 access token.
*
* This is accomplished by calling the endpoint <root-url>/login/oauth/credentials with the header
* Authorization: Bearer <access-token>
*
* The response is a JSON body of the form:
*
* {
* "credentials": {
* "clientId": "...",
* "accessToken": "...",
* },
* "expires": "..."
* }
*
*
*/
const getCredentials = expressWrapAsync(async (req, res) => {
// Don't report much to the user, to avoid revealing sensitive information, although
// it is likely in the service logs.
const inputError = new WebServerError('InputError', 'Could not generate credentials for this access token');
const entry = await AccessToken.load({ accessToken: req.accessToken }, true);
if (!entry) {
throw inputError;
}
// Although we eventually delete expired rows, that only happens once per day
// so we need to check that the accessToken is not expired.
if (new Date(entry.clientDetails.expires) < new Date()) {
throw inputError;
}
const { clientId, ...data } = entry.clientDetails;
const currentUser = await strategies[entry.identityProviderId].userFromIdentity(entry.identity);
if (!currentUser) {
throw inputError;
}
// Create permacreds to give admins the ability to audit and revoke
// the access at any time and that the client scanner process will
// automatically disable any clients that have too many scopes
const [clientError, client] = await tryCatch(
auth
.use({ authorizedScopes: currentUser.scopes() })
.createClient(clientId, {
...data,
expires: new Date(data.expires),
}),
);
if (clientError) {
throw inputError;
}
// Move expires back by 30 seconds to ensure the user refreshes well in advance of the
// actual credential expiration time
const exp = new Date(client.expires);
client.expires = new Date(exp.setSeconds(exp.getSeconds() - 30)).toISOString();
monitor.log.createCredentials({
clientId: client.clientId,
expires: client.expires,
userIdentity: entry.identity,
});
res.send({
expires: client.expires,
credentials: {
clientId: client.clientId,
accessToken: client.accessToken,
},
});
});
return {
authorization,
decision,
token,
getCredentials,
};
};