Skip to content

Commit d9115ec

Browse files
connection: refetch token if invalid.
1 parent 4e6f384 commit d9115ec

File tree

2 files changed

+75
-16
lines changed

2 files changed

+75
-16
lines changed

lib/common/connection.js

+28-10
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
'use strict';
2323

2424
var events = require('events');
25+
var extend = require('extend');
2526
var fs = require('fs');
2627
var GAPIToken = require('gapitoken');
2728
var nodeutil = require('util');
@@ -35,6 +36,9 @@ var METADATA_TOKEN_URL =
3536
'http://metadata/computeMetadata/v1/instance/service-accounts/default/' +
3637
'token';
3738

39+
/** @const {number} Maximum amount of times to attempt refreshing a token. */
40+
var MAX_TOKEN_REFRESH_ATTEMPTS = 1;
41+
3842
/** @const {object} gcloud-node's package.json file. */
3943
var PKG = require('../../package.json');
4044

@@ -217,7 +221,8 @@ Connection.prototype.fetchServiceAccountToken_ = function(callback) {
217221

218222
/**
219223
* Make an authorized request if the current connection token is still valid. If
220-
* it's not, try to reconnect.
224+
* it's not, try to reconnect to the limit specified by MAX_ATTEMPTS. If a valid
225+
* connection still cannot be made, execute the callback with the API error.
221226
*
222227
* @param {object} requestOptions - Request options.
223228
* @param {function=} callback - The callback function.
@@ -227,14 +232,25 @@ Connection.prototype.fetchServiceAccountToken_ = function(callback) {
227232
*/
228233
Connection.prototype.req = function(requestOptions, callback) {
229234
var that = this;
235+
var tokenRefreshAttempts = 0;
230236
callback = callback || util.noop;
231-
this.createAuthorizedReq(requestOptions, function(err, authorizedReq) {
237+
function onAuthorized(err, authorizedReq) {
232238
if (err) {
233239
callback(err);
234240
return;
235241
}
236-
that.requester(authorizedReq, callback);
237-
});
242+
that.requester(authorizedReq, function(err) {
243+
if (err && err.code === 401 &&
244+
++tokenRefreshAttempts <= MAX_TOKEN_REFRESH_ATTEMPTS) {
245+
// Invalid token. Try to fetch a new one.
246+
that.token = null;
247+
that.createAuthorizedReq(requestOptions, onAuthorized);
248+
return;
249+
}
250+
callback.apply(null, util.toArray(arguments));
251+
});
252+
}
253+
this.createAuthorizedReq(requestOptions, onAuthorized);
238254
};
239255

240256
/**
@@ -246,10 +262,10 @@ Connection.prototype.req = function(requestOptions, callback) {
246262
* @example
247263
* conn.createAuthorizedReq({}, function(err) {});
248264
*/
249-
Connection.prototype.createAuthorizedReq = function(reqOpts, callback) {
265+
Connection.prototype.createAuthorizedReq = function(requestOptions, callback) {
250266
var that = this;
251-
// Add user agent.
252-
reqOpts.headers = reqOpts.headers || {};
267+
268+
var reqOpts = extend(true, {}, requestOptions, { headers: {} });
253269

254270
if (reqOpts.headers['User-Agent']) {
255271
reqOpts.headers['User-Agent'] += '; ' + USER_AGENT;
@@ -305,9 +321,11 @@ Connection.prototype.isConnected = function() {
305321
* @return {object} Authorized request options.
306322
*/
307323
Connection.prototype.authorizeReq = function(requestOptions) {
308-
requestOptions.headers = requestOptions.headers || {};
309-
requestOptions.headers.Authorization = 'Bearer ' + this.token.accessToken;
310-
return requestOptions;
324+
return extend(true, {}, requestOptions, {
325+
headers: {
326+
Authorization: 'Bearer ' + this.token.accessToken
327+
}
328+
});
311329
};
312330

313331
/**

test/common/connection.js

+47-6
Original file line numberDiff line numberDiff line change
@@ -141,13 +141,54 @@ describe('Connection', function() {
141141
conn.req({ uri: 'https://someuri' }, function() {});
142142
});
143143

144-
it('should pass error to callback', function(done) {
145-
var error = new Error('Something terrible happened.');
146-
conn.fetchToken = function(cb) {
147-
cb(error);
144+
it('should fetch a new token if API returns a 401', function() {
145+
var fetchTokenCount = 0;
146+
conn.fetchToken = function(callback) {
147+
fetchTokenCount++;
148+
callback(null, tokenNeverExpires);
149+
};
150+
conn.requester = function(req, callback) {
151+
if (fetchTokenCount === 1) {
152+
callback({ code: 401 });
153+
} else {
154+
callback(null);
155+
}
156+
};
157+
conn.req({ uri: 'https://someuri' }, function() {});
158+
assert.equal(fetchTokenCount, 2);
159+
});
160+
161+
it('should try API request 2 times', function(done) {
162+
// Fail 1: invalid token.
163+
// -- try to get token --
164+
// Fail 2: invalid token.
165+
// -- execute callback with error.
166+
var error = { code: 401 };
167+
var requesterCount = 0;
168+
conn.fetchToken = function(callback) {
169+
callback(null, tokenNeverExpires);
170+
};
171+
conn.requester = function(req, callback) {
172+
requesterCount++;
173+
callback(error);
174+
};
175+
conn.req({ uri: 'https://someuri' }, function(err) {
176+
assert.equal(requesterCount, 2);
177+
assert.deepEqual(err, error);
178+
done();
179+
});
180+
});
181+
182+
it('should pass all arguments from requester to callback', function(done) {
183+
var args = [null, 1, 2, 3];
184+
conn.fetchToken = function(callback) {
185+
callback(null, tokenNeverExpires);
186+
};
187+
conn.requester = function(req, callback) {
188+
callback.apply(null, args);
148189
};
149-
conn.req({}, function(err) {
150-
assert.equal(error, err);
190+
conn.req({ uri: 'https://someuri' }, function() {
191+
assert.deepEqual([].slice.call(arguments), args);
151192
done();
152193
});
153194
});

0 commit comments

Comments
 (0)