Skip to content

Commit

Permalink
fix(connection): set token expiration date for GCE
Browse files Browse the repository at this point in the history
A response from the GCE metadata server responds with data in a
different format from that of the GAPIToken() request. Instead of
looking for a property that doesn't exist `token_expires`, we now
calculate the expiration timestamp from `expires_in`.

For more, see [Authenticating from Google Compute Engine][auth].

[auth]:https://developers.google.com/compute/docs/authentication#applications

Fixes #212
  • Loading branch information
stephenplusplus committed Sep 17, 2014
1 parent 91c7036 commit 2eb9903
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/common/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ Connection.prototype.fetchToken = function(callback) {
callback(err);
return;
}
var exp = new Date(body.token_expires * 1000);
var exp = new Date(Date.now() + body.expires_in * 1000);
callback(null, new Token(body.access_token, exp));
});
return;
Expand Down
35 changes: 35 additions & 0 deletions test/common/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,41 @@ describe('Connection', function() {
var tokenNeverExpires = new connection.Token('token', new Date(3000, 0, 0));
var tokenExpired = new connection.Token('token', new Date(2011, 0, 0));

describe('GCE', function() {
var gceConn;
var metadataResponse = {
body: {
access_token: 'y.8',
expires_in: 60
}
};

beforeEach(function() {
gceConn = new connection.Connection();
});

it('should fetch a token from the metadata server', function() {
gceConn.requester = function(opts) {
assert.equal(opts.uri.indexOf('http://metadata/'), 0);
};
gceConn.fetchToken();
});

it('should build token from the metadata server response', function() {
gceConn.requester = function(opts, callback) {
callback(null, metadataResponse, metadataResponse.body);
};
gceConn.fetchToken(function(err, token) {
assert.ifError(err);
assert(token instanceof connection.Token);
assert.equal(token.accessToken, metadataResponse.body.access_token);
var addedMs = metadataResponse.body.expires_in * 1000;
var tokenDate = new Date(Date.now() + addedMs);
assert.equal(token.expiry.getTime(), tokenDate.getTime());
});
});
});

it('should fetch a new token if token expires', function(done) {
conn.token = tokenExpired;
conn.fetchToken = function() {
Expand Down

0 comments on commit 2eb9903

Please sign in to comment.