-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathauth.js
445 lines (419 loc) · 16.3 KB
/
auth.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
var Auth = (function() {
var isBrowser = (typeof(window) == 'object');
var crypto = isBrowser ? null : require('crypto');
var msgpack = isBrowser ? window.Ably.msgpack : require('msgpack-js');
function noop() {}
function random() { return ('000000' + Math.floor(Math.random() * 1E16)).slice(-16); }
var hmac, toBase64;
if(isBrowser) {
toBase64 = Base64.encode;
hmac = function(text, key) {
return CryptoJS.HmacSHA256(text, key).toString(CryptoJS.enc.Base64);
};
} else {
toBase64 = function(str) { return (new Buffer(str, 'ascii')).toString('base64'); };
hmac = function(text, key) {
var inst = crypto.createHmac('SHA256', key);
inst.update(text);
return inst.digest('base64');
};
}
function c14n(capability) {
if(!capability)
return '';
if(typeof(capability) == 'string')
capability = JSON.parse(capability);
var c14nCapability = {};
var keys = Utils.keysArray(capability, true);
if(!keys)
return '';
keys.sort();
for(var i = 0; i < keys.length; i++) {
c14nCapability[keys[i]] = capability[keys[i]].sort();
}
return JSON.stringify(c14nCapability);
}
function Auth(rest, options) {
this.rest = rest;
this.tokenParams = {};
/* decide default auth method */
var key = options.key;
if(key) {
if(!options.clientId) {
/* we have the key and do not need to authenticate the client,
* so default to using basic auth */
Logger.logAction(Logger.LOG_MINOR, 'Auth()', 'anonymous, using basic auth');
this.method = 'basic';
this.key = key;
this.basicKey = toBase64(key);
return;
}
/* token auth, but we have the key so we can authorise
* ourselves */
if(!hmac) {
var msg = 'client-side token request signing not supported';
Logger.logAction(Logger.LOG_ERROR, 'Auth()', msg);
throw new Error(msg);
}
}
/* using token auth, but decide the method */
this.method = 'token';
if(options.token) {
/* options.token may contain a token string or, for convenience, a TokenDetails */
options.tokenDetails = (typeof(options.token) === 'string') ? {token: options.token} : options.token;
}
this.tokenDetails = options.tokenDetails;
if(options.authCallback) {
Logger.logAction(Logger.LOG_MINOR, 'Auth()', 'using token auth with authCallback');
} else if(options.authUrl) {
Logger.logAction(Logger.LOG_MINOR, 'Auth()', 'using token auth with authUrl');
} else if(options.keySecret) {
Logger.logAction(Logger.LOG_MINOR, 'Auth()', 'using token auth with client-side signing');
} else if(options.tokenDetails) {
Logger.logAction(Logger.LOG_MINOR, 'Auth()', 'using token auth with supplied token only');
} else {
var msg = 'options must include valid authentication parameters';
Logger.logAction(Logger.LOG_ERROR, 'Auth()', msg);
throw new Error(msg);
}
}
/**
* Ensure valid auth credentials are present. This may rely in an already-known
* and valid token, and will obtain a new token if necessary or explicitly
* requested.
* Authorisation will use the parameters supplied on construction except
* where overridden with the options supplied in the call.
* @param authOptions
* an object containing the request params:
* - key: (optional) the key to use; if not specified, a key
* passed in constructing the Rest interface may be used
*
* - queryTime (optional) boolean indicating that the Ably system should be
* queried for the current time when none is specified explicitly.
*
* - force (optional) boolean indicating that a new token should be requested,
* even if a current token is still valid.
*
* @param tokenParams
* an object containing the parameters for the requested token:
*
* - ttl: (optional) the requested life of any new token in ms. If none
* is specified a default of 1 hour is provided. The maximum lifetime
* is 24hours; any request exceeeding that lifetime will be rejected
* with an error.
*
* - capability: (optional) the capability to associate with the access token.
* If none is specified, a token will be requested with all of the
* capabilities of the specified key.
*
* - clientId: (optional) a client Id to associate with the token
*
* - timestamp: (optional) the time in ms since the epoch. If none is specified,
* the system will be queried for a time value to use.
*
* @param callback (err, tokenDetails)
*/
Auth.prototype.authorise = function(authOptions, tokenParams, callback) {
var token = this.tokenDetails;
if(token) {
if(token.expires === undefined || (token.expires > this.getTimestamp())) {
if(!(authOptions && authOptions.force)) {
Logger.logAction(Logger.LOG_MINOR, 'Auth.getToken()', 'using cached token; expires = ' + token.expires);
callback(null, token);
return;
}
} else {
/* expired, so remove */
Logger.logAction(Logger.LOG_MINOR, 'Auth.getToken()', 'deleting expired token');
this.tokenDetails = null;
}
}
var self = this;
this.requestToken(authOptions, tokenParams, function(err, tokenResponse) {
if(err) {
callback(err);
return;
}
callback(null, (self.tokenDetails = tokenResponse));
});
};
/**
* Request an access token
* @param authOptions
* an object containing the request options:
* - key: the key to use.
*
* - authCallback: (optional) a javascript callback to be used, passing a set of token
* request params, to get a signed token request.
*
* - authUrl: (optional) a URL to be used to GET or POST a set of token request
* params, to obtain a signed token request.
*
* - authHeaders: (optional) a set of application-specific headers to be added to any request
* made to the authUrl.
*
* - authParams: (optional) a set of application-specific query params to be added to any
* request made to the authUrl.
*
* - queryTime (optional) boolean indicating that the ably system should be
* queried for the current time when none is specified explicitly
*
* - requestHeaders (optional, unsuported, for testing only) extra headers to add to the
* requestToken request
*
* @param tokenParams
* an object containing the parameters for the requested token:
* - ttl: (optional) the requested life of the token in milliseconds. If none is specified
* a default of 1 hour is provided. The maximum lifetime is 24hours; any request
* exceeeding that lifetime will be rejected with an error.
*
* - capability: (optional) the capability to associate with the access token.
* If none is specified, a token will be requested with all of the
* capabilities of the specified key.
*
* - clientId: (optional) a client Id to associate with the token; if not
* specified, a clientId passed in constructing the Rest interface will be used
*
* - timestamp: (optional) the time in ms since the epoch. If none is specified,
* the system will be queried for a time value to use.
*
* @param callback (err, tokenDetails)
*/
Auth.prototype.requestToken = function(authOptions, tokenParams, callback) {
/* shuffle and normalise arguments as necessary */
if(typeof(authOptions) == 'function' && !callback) {
callback = authOptions;
authOptions = tokenParams = null;
}
else if(typeof(tokenParams) == 'function' && !callback) {
callback = tokenParams;
tokenParams = authOptions;
authOptions = null;
}
/* merge supplied options with the already-known options */
authOptions = Utils.mixin(Utils.copy(this.rest.options), authOptions);
tokenParams = tokenParams || Utils.copy(this.tokenParams);
callback = callback || noop;
var format = authOptions.format || 'json';
/* first set up whatever callback will be used to get signed
* token requests */
var tokenRequestCallback, rest = this.rest;
if(authOptions.authCallback) {
Logger.logAction(Logger.LOG_MINOR, 'Auth.requestToken()', 'using token auth with auth_callback');
tokenRequestCallback = authOptions.authCallback;
} else if(authOptions.authUrl) {
Logger.logAction(Logger.LOG_MINOR, 'Auth.requestToken()', 'using token auth with auth_url');
/* if no authParams given, check if they were given in the URL */
if(!authOptions.authParams) {
var queryIdx = authOptions.authUrl.indexOf('?');
if(queryIdx > -1) {
authOptions.authParams = Utils.parseQueryString(authOptions.authUrl.slice(queryIdx));
authOptions.authUrl = authOptions.authUrl.slice(0, queryIdx);
}
}
tokenRequestCallback = function(params, cb) {
var authHeaders = Utils.mixin({accept: 'application/json'}, authOptions.authHeaders);
Http.getUri(rest, authOptions.authUrl, authHeaders || {}, Utils.mixin(params, authOptions.authParams), function(err, body, headers, unpacked) {
if(err || unpacked) return cb(err, body);
if(BufferUtils.isBuffer(body)) body = body.toString();
if(headers['content-type'] && headers['content-type'].indexOf('application/json') > -1) {
try {
body = JSON.parse(body);
} catch(e) {
cb(new ErrorInfo('Unexpected error processing authURL response; err = ' + e.message, 40000, 400));
return;
}
}
cb(null, body);
});
};
} else if(authOptions.key) {
var self = this;
Logger.logAction(Logger.LOG_MINOR, 'Auth.requestToken()', 'using token auth with client-side signing');
tokenRequestCallback = function(params, cb) { self.createTokenRequest(authOptions, params, cb); };
} else {
throw new Error('Auth.requestToken(): authOptions must include valid authentication parameters');
}
/* normalise token params */
if('capability' in tokenParams)
tokenParams.capability = c14n(tokenParams.capability);
var rest = this.rest;
var tokenRequest = function(signedTokenParams, tokenCb) {
var requestHeaders,
keyName = signedTokenParams.keyName,
tokenUri = function(host) { return rest.baseUri(host) + '/keys/' + keyName + '/requestToken';};
if(Http.post) {
requestHeaders = Utils.defaultPostHeaders(format);
if(authOptions.requestHeaders) Utils.mixin(requestHeaders, authOptions.requestHeaders);
signedTokenParams = (format == 'msgpack') ? msgpack.encode(signedTokenParams, true): JSON.stringify(signedTokenParams);
Http.post(rest, tokenUri, requestHeaders, signedTokenParams, null, tokenCb);
} else {
requestHeaders = Utils.defaultGetHeaders();
if(authOptions.requestHeaders) Utils.mixin(requestHeaders, authOptions.requestHeaders);
Http.get(rest, tokenUri, requestHeaders, signedTokenParams, tokenCb);
}
};
tokenRequestCallback(tokenParams, function(err, tokenRequestOrDetails) {
if(err) {
Logger.logAction(Logger.LOG_ERROR, 'Auth.requestToken()', 'token request signing call returned error; err = ' + Utils.inspectError(err));
if(!('code' in err))
err.code = 40170;
if(!('statusCode' in err))
err.statusCode = 401;
callback(err);
return;
}
/* the response from the callback might be a token string, a signed request or a token details */
if(typeof(tokenRequestOrDetails) === 'string') {
callback(null, {token: tokenRequestOrDetails});
return;
}
if('issued' in tokenRequestOrDetails) {
callback(null, tokenRequestOrDetails);
return;
}
/* it's a token request, so make the request */
tokenRequest(tokenRequestOrDetails, function(err, tokenResponse, headers, unpacked) {
if(err) {
Logger.logAction(Logger.LOG_ERROR, 'Auth.requestToken()', 'token request API call returned error; err = ' + Utils.inspectError(err));
callback(err);
return;
}
if(!unpacked) tokenResponse = (format == 'msgpack') ? msgpack.decode(tokenResponse) : JSON.parse(tokenResponse);
Logger.logAction(Logger.LOG_MINOR, 'Auth.getToken()', 'token received');
callback(null, tokenResponse);
});
});
};
/**
* Create and sign a token request based on the given options.
* NOTE this can only be used when the key value is available locally.
* Otherwise, signed token requests must be obtained from the key
* owner (either using the token request callback or url).
*
* @param authOptions
* an object containing the request options:
* - key: the key to use.
*
* - queryTime (optional) boolean indicating that the ably system should be
* queried for the current time when none is specified explicitly
*
* - requestHeaders (optional, unsuported, for testing only) extra headers to add to the
* requestToken request
*
* @param tokenParams
* an object containing the parameters for the requested token:
* - ttl: (optional) the requested life of the token in ms. If none is specified
* a default of 1 hour is provided. The maximum lifetime is 24hours; any request
* exceeeding that lifetime will be rejected with an error.
*
* - capability: (optional) the capability to associate with the access token.
* If none is specified, a token will be requested with all of the
* capabilities of the specified key.
*
* - clientId: (optional) a client Id to associate with the token; if not
* specified, a clientId passed in constructing the Rest interface will be used
*
* - timestamp: (optional) the time in ms since the epoch. If none is specified,
* the system will be queried for a time value to use.
*
*/
Auth.prototype.createTokenRequest = function(authOptions, tokenParams, callback) {
authOptions = authOptions || this.rest.options;
tokenParams = tokenParams || Utils.copy(this.tokenParams);
var key = authOptions.key;
if(!key) {
callback(new Error('No key specified'));
return;
}
var keyParts = key.split(':'),
keyName = keyParts[0],
keySecret = keyParts[1];
if(!keySecret) {
callback(new Error('Invalid key specified'));
return;
}
var request = Utils.mixin({ keyName: keyName }, tokenParams),
clientId = tokenParams.clientId || '',
ttl = tokenParams.ttl || '',
capability = tokenParams.capability || '',
rest = this.rest,
self = this;
(function(authoriseCb) {
if(request.timestamp) {
authoriseCb();
return;
}
if(authOptions.queryTime) {
rest.time(function(err, time) {
if(err) {callback(err); return;}
request.timestamp = time;
authoriseCb();
});
return;
}
request.timestamp = self.getTimestamp();
authoriseCb();
})(function() {
/* nonce */
/* NOTE: there is no expectation that the client
* specifies the nonce; this is done by the library
* However, this can be overridden by the client
* simply for testing purposes. */
var nonce = request.nonce || (request.nonce = random()),
timestamp = request.timestamp;
var signText
= request.keyName + '\n'
+ ttl + '\n'
+ capability + '\n'
+ clientId + '\n'
+ timestamp + '\n'
+ nonce + '\n';
/* mac */
/* NOTE: there is no expectation that the client
* specifies the mac; this is done by the library
* However, this can be overridden by the client
* simply for testing purposes. */
request.mac = request.mac || hmac(signText, keySecret);
Logger.logAction(Logger.LOG_MINOR, 'Auth.getTokenRequest()', 'generated signed request');
callback(null, request);
});
};
/**
* Get the auth query params to use for a websocket connection,
* based on the current auth parameters
*/
Auth.prototype.getAuthParams = function(callback) {
if(this.method == 'basic')
callback(null, {key: this.key});
else
this.authorise(null, null, function(err, tokenDetails) {
if(err) {
callback(err);
return;
}
callback(null, {access_token:tokenDetails.token});
});
};
/**
* Get the authorization header to use for a REST or comet request,
* based on the current auth parameters
*/
Auth.prototype.getAuthHeaders = function(callback) {
if(this.method == 'basic') {
callback(null, {authorization: 'Basic ' + this.basicKey});
} else {
this.authorise(null, null, function(err, tokenDetails) {
if(err) {
callback(err);
return;
}
callback(null, {authorization: 'Bearer ' + toBase64(tokenDetails.token)});
});
}
};
Auth.prototype.getTimestamp = function() {
return Date.now() + (this.rest.serverTimeOffset || 0);
};
return Auth;
})();