summaryrefslogtreecommitdiffstats
path: root/remoting/webapp/oauth2.js
blob: b8268bf24ccaef3b5f755c2800dddad6f21a68f5 (plain)
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview
 * OAuth2 class that handles retrieval/storage of an OAuth2 token.
 *
 * Uses a content script to trampoline the OAuth redirect page back into the
 * extension context.  This works around the lack of native support for
 * chrome-extensions in OAuth2.
 */

// TODO(jamiewalch): Delete this code once Chromoting is a v2 app and uses the
// identity API (http://crbug.com/ 134213).

'use strict';

/** @suppress {duplicate} */
var remoting = remoting || {};

/** @type {remoting.OAuth2} */
remoting.oauth2 = null;


/** @constructor */
remoting.OAuth2 = function() {
};

// Constants representing keys used for storing persistent state.
/** @private */
remoting.OAuth2.prototype.KEY_REFRESH_TOKEN_ = 'oauth2-refresh-token';
/** @private */
remoting.OAuth2.prototype.KEY_REFRESH_TOKEN_REVOKABLE_ =
    'oauth2-refresh-token-revokable';
/** @private */
remoting.OAuth2.prototype.KEY_ACCESS_TOKEN_ = 'oauth2-access-token';
/** @private */
remoting.OAuth2.prototype.KEY_XSRF_TOKEN_ = 'oauth2-xsrf-token';
/** @private */
remoting.OAuth2.prototype.KEY_EMAIL_ = 'remoting-email';

// Constants for parameters used in retrieving the OAuth2 credentials.
/** @private */
remoting.OAuth2.prototype.SCOPE_ =
      'https://www.googleapis.com/auth/chromoting ' +
      'https://www.googleapis.com/auth/googletalk ' +
      'https://www.googleapis.com/auth/userinfo#email';

// Configurable URLs/strings.
/** @private
 *  @return {string} OAuth2 redirect URI.
 */
remoting.OAuth2.prototype.getRedirectUri_ = function() {
  return remoting.settings.OAUTH2_REDIRECT_URL;
};

/** @private
 *  @return {string} API client ID.
 */
remoting.OAuth2.prototype.getClientId_ = function() {
  return remoting.settings.OAUTH2_CLIENT_ID;
};

/** @private
 *  @return {string} API client secret.
 */
remoting.OAuth2.prototype.getClientSecret_ = function() {
  return remoting.settings.OAUTH2_CLIENT_SECRET;
};

/** @private
 *  @return {string} OAuth2 authentication URL.
 */
remoting.OAuth2.prototype.getOAuth2AuthEndpoint_ = function() {
  return remoting.settings.OAUTH2_BASE_URL + '/auth';
};

/** @private
 *  @return {string} OAuth2 token URL.
 */
remoting.OAuth2.prototype.getOAuth2TokenEndpoint_ = function() {
  return remoting.settings.OAUTH2_BASE_URL + '/token';
};

/** @private
 *  @return {string} OAuth token revocation URL.
 */
remoting.OAuth2.prototype.getOAuth2RevokeTokenEndpoint_ = function() {
  return remoting.settings.OAUTH2_BASE_URL + '/revoke';
};

/** @private
 *  @return {string} OAuth2 userinfo API URL.
 */
remoting.OAuth2.prototype.getOAuth2ApiUserInfoEndpoint_ = function() {
  return remoting.settings.OAUTH2_API_BASE_URL + '/v1/userinfo';
};

/** @return {boolean} True if the app is already authenticated. */
remoting.OAuth2.prototype.isAuthenticated = function() {
  if (this.getRefreshToken_()) {
    return true;
  }
  return false;
};

/**
 * Removes all storage, and effectively unauthenticates the user.
 *
 * @return {void} Nothing.
 */
remoting.OAuth2.prototype.clear = function() {
  window.localStorage.removeItem(this.KEY_EMAIL_);
  this.clearAccessToken_();
  this.clearRefreshToken_();
};

/**
 * Sets the refresh token.
 *
 * This method also marks the token as revokable, so that this object will
 * revoke the token when it no longer needs it.
 *
 * @param {string} token The new refresh token.
 * @return {void} Nothing.
 */
remoting.OAuth2.prototype.setRefreshToken = function(token) {
  window.localStorage.setItem(this.KEY_REFRESH_TOKEN_, escape(token));
  window.localStorage.setItem(this.KEY_REFRESH_TOKEN_REVOKABLE_, true);
  window.localStorage.removeItem(this.KEY_EMAIL_);
  this.clearAccessToken_();
};

/**
 * Gets the refresh token.
 *
 * This method also marks the refresh token as not revokable, so that this
 * object will not revoke the token when it no longer needs it. After this
 * object has exported the token, it cannot know whether it is still in use
 * when this object no longer needs it.
 *
 * @return {?string} The refresh token, if authenticated, or NULL.
 */
remoting.OAuth2.prototype.exportRefreshToken = function() {
  window.localStorage.removeItem(this.KEY_REFRESH_TOKEN_REVOKABLE_);
  return this.getRefreshToken_();
};

/**
 * @return {?string} The refresh token, if authenticated, or NULL.
 * @private
 */
remoting.OAuth2.prototype.getRefreshToken_ = function() {
  var value = window.localStorage.getItem(this.KEY_REFRESH_TOKEN_);
  if (typeof value == 'string') {
    return unescape(value);
  }
  return null;
};

/**
 * Clears the refresh token.
 *
 * @return {void} Nothing.
 * @private
 */
remoting.OAuth2.prototype.clearRefreshToken_ = function() {
  if (window.localStorage.getItem(this.KEY_REFRESH_TOKEN_REVOKABLE_)) {
    this.revokeToken_(this.getRefreshToken_());
  }
  window.localStorage.removeItem(this.KEY_REFRESH_TOKEN_);
  window.localStorage.removeItem(this.KEY_REFRESH_TOKEN_REVOKABLE_);
};

/**
 * @param {string} token The new access token.
 * @param {number} expiration Expiration time in milliseconds since epoch.
 * @return {void} Nothing.
 */
remoting.OAuth2.prototype.setAccessToken = function(token, expiration) {
  var access_token = {'token': token, 'expiration': expiration};
  window.localStorage.setItem(this.KEY_ACCESS_TOKEN_,
                              JSON.stringify(access_token));
};

/**
 * Returns the current access token, setting it to a invalid value if none
 * existed before.
 *
 * @private
 * @return {{token: string, expiration: number}} The current access token, or
 * an invalid token if not authenticated.
 */
remoting.OAuth2.prototype.getAccessTokenInternal_ = function() {
  if (!window.localStorage.getItem(this.KEY_ACCESS_TOKEN_)) {
    // Always be able to return structured data.
    this.setAccessToken('', 0);
  }
  var accessToken = window.localStorage.getItem(this.KEY_ACCESS_TOKEN_);
  if (typeof accessToken == 'string') {
    var result = jsonParseSafe(accessToken);
    if (result && 'token' in result && 'expiration' in result) {
      return /** @type {{token: string, expiration: number}} */ result;
    }
  }
  console.log('Invalid access token stored.');
  return {'token': '', 'expiration': 0};
};

/**
 * Returns true if the access token is expired, or otherwise invalid.
 *
 * Will throw if !isAuthenticated().
 *
 * @return {boolean} True if a new access token is needed.
 * @private
 */
remoting.OAuth2.prototype.needsNewAccessToken_ = function() {
  if (!this.isAuthenticated()) {
    throw 'Not Authenticated.';
  }
  var access_token = this.getAccessTokenInternal_();
  if (!access_token['token']) {
    return true;
  }
  if (Date.now() > access_token['expiration']) {
    return true;
  }
  return false;
};

/**
 * @return {void} Nothing.
 * @private
 */
remoting.OAuth2.prototype.clearAccessToken_ = function() {
  window.localStorage.removeItem(this.KEY_ACCESS_TOKEN_);
};

/**
 * Update state based on token response from the OAuth2 /token endpoint.
 *
 * @private
 * @param {function(XMLHttpRequest, string): void} onDone Callback to invoke on
 *     completion.
 * @param {XMLHttpRequest} xhr The XHR object for this request.
 * @return {void} Nothing.
 */
remoting.OAuth2.prototype.processTokenResponse_ = function(onDone, xhr) {
  /** @type {string} */
  var accessToken = '';
  if (xhr.status == 200) {
    try {
      // Don't use jsonParseSafe here unless you move the definition out of
      // remoting.js, otherwise this won't work from the OAuth trampoline.
      // TODO(jamiewalch): Fix this once we're no longer using the trampoline.
      var tokens = JSON.parse(xhr.responseText);
      if ('refresh_token' in tokens) {
        this.setRefreshToken(tokens['refresh_token']);
      }

      // Offset by 120 seconds so that we can guarantee that the token
      // we return will be valid for at least 2 minutes.
      // If the access token is to be useful, this object must make some
      // guarantee as to how long the token will be valid for.
      // The choice of 2 minutes is arbitrary, but that length of time
      // is part of the contract satisfied by callWithToken().
      // Offset by a further 30 seconds to account for RTT issues.
      accessToken = /** @type {string} */ (tokens['access_token']);
      this.setAccessToken(accessToken,
          (tokens['expires_in'] - (120 + 30)) * 1000 + Date.now());
    } catch (err) {
      console.error('Invalid "token" response from server:',
                    /** @type {*} */ (err));
    }
  } else {
    console.error('Failed to get tokens. Status: ' + xhr.status +
                  ' response: ' + xhr.responseText);
  }
  onDone(xhr, accessToken);
};

/**
 * Asynchronously retrieves a new access token from the server.
 *
 * Will throw if !isAuthenticated().
 *
 * @param {function(XMLHttpRequest): void} onDone Callback to invoke on
 *     completion.
 * @return {void} Nothing.
 * @private
 */
remoting.OAuth2.prototype.refreshAccessToken_ = function(onDone) {
  if (!this.isAuthenticated()) {
    throw 'Not Authenticated.';
  }

  var parameters = {
    'client_id': this.getClientId_(),
    'client_secret': this.getClientSecret_(),
    'refresh_token': this.getRefreshToken_(),
    'grant_type': 'refresh_token'
  };

  remoting.xhr.post(this.getOAuth2TokenEndpoint_(),
                    this.processTokenResponse_.bind(this, onDone),
                    parameters);
};

/**
 * Redirect page to get a new OAuth2 Refresh Token.
 *
 * @return {void} Nothing.
 */
remoting.OAuth2.prototype.doAuthRedirect = function() {
  var xsrf_token = remoting.generateXsrfToken();
  window.localStorage.setItem(this.KEY_XSRF_TOKEN_, xsrf_token);
  var GET_CODE_URL = this.getOAuth2AuthEndpoint_() + '?' +
    remoting.xhr.urlencodeParamHash({
          'client_id': this.getClientId_(),
          'redirect_uri': this.getRedirectUri_(),
          'scope': this.SCOPE_,
          'state': xsrf_token,
          'response_type': 'code',
          'access_type': 'offline',
          'approval_prompt': 'force'
        });
  window.location.replace(GET_CODE_URL);
};

/**
 * Asynchronously exchanges an authorization code for a refresh token.
 *
 * @param {string} code The new refresh token.
 * @param {string} state The state parameter received from the OAuth redirect.
 * @param {function(XMLHttpRequest):void} onDone Callback to invoke on
 *     completion.
 * @return {void} Nothing.
 */
remoting.OAuth2.prototype.exchangeCodeForToken = function(code, state, onDone) {
  var xsrf_token = window.localStorage.getItem(this.KEY_XSRF_TOKEN_);
  window.localStorage.removeItem(this.KEY_XSRF_TOKEN_);
  if (xsrf_token == undefined || state != xsrf_token) {
    // Invalid XSRF token, or unexpected OAuth2 redirect. Abort.
    onDone(null);
  }
  var parameters = {
    'client_id': this.getClientId_(),
    'client_secret': this.getClientSecret_(),
    'redirect_uri': this.getRedirectUri_(),
    'code': code,
    'grant_type': 'authorization_code'
  };
  remoting.xhr.post(this.getOAuth2TokenEndpoint_(),
                    this.processTokenResponse_.bind(this, onDone),
                    parameters);
};

/**
 * Interprets unexpected HTTP response codes to authentication XMLHttpRequests.
 * The caller should handle the usual expected responses (200, 400) separately.
 *
 * @private
 * @param {number} xhrStatus Status (HTTP response code) of the XMLHttpRequest.
 * @return {remoting.Error} An error code to be raised.
 */
remoting.OAuth2.prototype.interpretUnexpectedXhrStatus_ = function(xhrStatus) {
  // Return AUTHENTICATION_FAILED by default, so that the user can try to
  // recover from an unexpected failure by signing in again.
  /** @type {remoting.Error} */
  var error = remoting.Error.AUTHENTICATION_FAILED;
  if (xhrStatus == 502 || xhrStatus == 503) {
    error = remoting.Error.SERVICE_UNAVAILABLE;
  } else if (xhrStatus == 0) {
    error = remoting.Error.NETWORK_FAILURE;
  } else {
    console.warn('Unexpected authentication response code: ' + xhrStatus);
  }
  return error;
};

/**
 * Revokes a refresh or an access token.
 *
 * @param {string?} token An access or refresh token.
 * @return {void} Nothing.
 * @private
 */
remoting.OAuth2.prototype.revokeToken_ = function(token) {
  if (!token || (token.length == 0)) {
    return;
  }
  var parameters = { 'token': token };

  /** @param {XMLHttpRequest} xhr The XHR reply. */
  var processResponse = function(xhr) {
    if (xhr.status != 200) {
      console.log('Failed to revoke token. Status: ' + xhr.status +
                  ' ; response: ' + xhr.responseText + ' ; xhr: ', xhr);
    }
  };
  remoting.xhr.post(this.getOAuth2RevokeTokenEndpoint_(),
                    processResponse,
                    parameters);
};

/**
 * Call a function with an access token, refreshing it first if necessary.
 * The access token will remain valid for at least 2 minutes.
 *
 * @param {function(string):void} onOk Function to invoke with access token if
 *     an access token was successfully retrieved.
 * @param {function(remoting.Error):void} onError Function to invoke with an
 *     error code on failure.
 * @return {void} Nothing.
 */
remoting.OAuth2.prototype.callWithToken = function(onOk, onError) {
  if (this.isAuthenticated()) {
    if (this.needsNewAccessToken_()) {
      this.refreshAccessToken_(this.onRefreshToken_.bind(this, onOk, onError));
    } else {
      onOk(this.getAccessTokenInternal_()['token']);
    }
  } else {
    onError(remoting.Error.NOT_AUTHENTICATED);
  }
};

/**
 * Process token refresh results and notify caller.
 *
 * @param {function(string):void} onOk Function to invoke with access token if
 *     an access token was successfully retrieved.
 * @param {function(remoting.Error):void} onError Function to invoke with an
 *     error code on failure.
 * @param {XMLHttpRequest} xhr The result of the refresh operation.
 * @param {string} accessToken The fresh access token.
 * @private
 */
remoting.OAuth2.prototype.onRefreshToken_ = function(onOk, onError, xhr,
                                                     accessToken) {
  /** @type {remoting.Error} */
  var error = remoting.Error.UNEXPECTED;
  if (xhr.status == 200) {
    onOk(accessToken);
    return;
  } else if (xhr.status == 400) {
    var result =
        /** @type {{error: string}} */ (jsonParseSafe(xhr.responseText));
    if (result && result.error == 'invalid_grant') {
      error = remoting.Error.AUTHENTICATION_FAILED;
    }
  } else {
    error = this.interpretUnexpectedXhrStatus_(xhr.status);
  }
  onError(error);
};

/**
 * Get the user's email address.
 *
 * @param {function(string):void} onOk Callback invoked when the email
 *     address is available.
 * @param {function(remoting.Error):void} onError Callback invoked if an
 *     error occurs.
 * @return {void} Nothing.
 */
remoting.OAuth2.prototype.getEmail = function(onOk, onError) {
  var cached = window.localStorage.getItem(this.KEY_EMAIL_);
  if (typeof cached == 'string') {
    onOk(cached);
    return;
  }
  /** @type {remoting.OAuth2} */
  var that = this;
  /** @param {XMLHttpRequest} xhr The XHR response. */
  var onResponse = function(xhr) {
    var email = null;
    if (xhr.status == 200) {
      var result = jsonParseSafe(xhr.responseText);
      if (result && 'email' in result) {
        window.localStorage.setItem(that.KEY_EMAIL_, result['email']);
        onOk(result['email']);
        return;
      } else {
        console.error(
            'Cannot parse userinfo response: ', xhr.responseText, xhr);
        onError(remoting.Error.UNEXPECTED);
        return;
      }
    }
    console.error('Unable to get email address:', xhr.status, xhr);
    if (xhr.status == 401) {
      onError(remoting.Error.AUTHENTICATION_FAILED);
    } else {
      onError(that.interpretUnexpectedXhrStatus_(xhr.status));
    }
  };

  /** @param {string} token The access token. */
  var getEmailFromToken = function(token) {
    var headers = { 'Authorization': 'OAuth ' + token };
    remoting.xhr.get(that.getOAuth2ApiUserInfoEndpoint_(),
                     onResponse, '', headers);
  };

  this.callWithToken(getEmailFromToken, onError);
};

/**
 * If the user's email address is cached, return it, otherwise return null.
 *
 * @return {?string} The email address, if it has been cached by a previous call
 *     to getEmail, otherwise null.
 */
remoting.OAuth2.prototype.getCachedEmail = function() {
  var value = window.localStorage.getItem(this.KEY_EMAIL_);
  if (typeof value == 'string') {
    return value;
  }
  return null;
};