Skip to content

Commit

Permalink
Merge pull request #331 from stephenplusplus/spp--better-error-message
Browse files Browse the repository at this point in the history
common: throw error when missing credentials in non g[ac]e env
  • Loading branch information
silvolu committed Dec 15, 2014
2 parents af986b7 + 39fe978 commit 81d1c76
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
19 changes: 19 additions & 0 deletions lib/common/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,19 @@ function makeWritableStream(dup, options, onComplete) {
module.exports.makeWritableStream = makeWritableStream;

function makeAuthorizedRequest(config) {
var GAE_OR_GCE = !config || (!config.credentials && !config.keyFile);

var missingCredentialsError = new Error();
missingCredentialsError.message = [
'A connection to gcloud must be established via either a `keyFilename` ',
'property or a `credentials` object.',
'\n\n',
'See the "Getting Started with gcloud" section for more information:',
'\n\n',
'\thttps://googlecloudplatform.github.io/gcloud-node/#/docs/',
'\n'
].join('');

var authorize = gsa(config);

function makeRequest(reqOpts, callback) {
Expand All @@ -358,6 +371,12 @@ function makeAuthorizedRequest(config) {

function onAuthorizedRequest(err, authorizedReqOpts) {
if (err) {
if (GAE_OR_GCE && err.code === 'ENOTFOUND') {
// The metadata server wasn't found. The user must not actually be in
// a GAE or GCE environment.
throw missingCredentialsError;
}

if (err.code === 401 &&
++tokenRefreshAttempts <= MAX_TOKEN_REFRESH_ATTEMPTS) {
authorize(reqOpts, onAuthorizedRequest);
Expand Down
22 changes: 21 additions & 1 deletion test/common/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

/*global describe, it */
/*global describe, it, beforeEach */

'use strict';

Expand Down Expand Up @@ -48,6 +48,10 @@ function fakeRequest() {
}

describe('common/util', function() {
beforeEach(function() {
gsa_Override = null;
});

describe('arrayize', function() {
it('should arrayize if the input is not an array', function(done) {
var o = util.arrayize('text');
Expand Down Expand Up @@ -320,6 +324,22 @@ describe('common/util', function() {
});
});

it('should throw if not GCE/GAE & missing credentials', function() {
gsa_Override = function() {
return function authorize(reqOpts, callback) {
// Simulate the metadata server not existing.
callback({ code: 'ENOTFOUND' });
};
};

assert.throws(function() {
// Don't provide a keyFile or credentials object.
var connectionConfig = {};
var makeRequest = util.makeAuthorizedRequest(connectionConfig);
makeRequest({}, util.noop);
}, /A connection to gcloud must be established/);
});

it('should handle malformed key response', function(done) {
var makeRequest = util.makeAuthorizedRequest({
credentials: {
Expand Down

0 comments on commit 81d1c76

Please sign in to comment.