/
config.js
673 lines (623 loc) · 21.7 KB
/
config.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
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
/**
* Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You
* may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
var AWS = require('./core');
require('./event_listeners');
require('./event_emitter');
require('./metadata_service');
var inherit = AWS.util.inherit;
/**
* The main configuration class used by all service objects to set
* the region, credentials, and other options for requests.
*
* By default, credentials and region settings are left unconfigured.
* This should be configured by the application before using any
* AWS service APIs.
*
* In order to set global configuration options, properties should
* be assigned to the global {AWS.config} object.
*
* @see AWS.config
*
* @!attribute credentials
* @return [AWS.Credentials] the AWS credentials to sign requests with.
*
* @!attribute region
* @example Set the global region setting to us-west-2
* AWS.config.update({region: 'us-west-2'});
* @return [AWS.Credentials] The region to send service requests to.
* @see http://docs.amazonwebservices.com/general/latest/gr/rande.html
* A list of available endpoints for each AWS service
*
* @!attribute maxRetries
* @return [Integer] the maximum amount of retries to perform for a
* service request. By default this value is calculated by the specific
* service object that the request is being made to.
*
* @!attribute paramValidation
* @return [Boolean] whether input parameters should be validated against
* the operation description before sending the request. Defaults to true.
*
* @!attribute computeChecksums
* @return [Boolean] whether to compute checksums for payload bodies when
* the service accepts it (currently supported in S3 only).
*
* @!attribute sslEnabled
* @return [Boolean] whether SSL is enabled for requests
*
* @!attribute s3ForcePathStyle
* @return [Boolean] whether to force path style URLs for S3 objects
*/
AWS.Config = inherit({
/**
* Creates a new configuration object. This is the object that passes
* option data along to service requests, including credentials, security,
* region information, and some service specific settings.
*
* @example Creating a new configuration object with credentials and region
* var config = new AWS.Config({
* accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2'
* });
* @option options accessKeyId [String] your AWS access key ID.
* @option options secretAccessKey [String] your AWS secret access key.
* @option options sessionToken [AWS.Credentials] the optional AWS
* session token to sign requests with.
* @option options credentials [AWS.Credentials] the AWS credentials
* to sign requests with. You can either specify this object, or
* specify the accessKeyId and secretAccessKey options directly.
* @option options region [String] the region to send service requests to.
* See {region} for more information.
* @option options maxRetries [Integer] the maximum amount of retries to
* attempt with a request. See {maxRetries} for more information.
* @option options sslEnabled [Boolean] whether to enable SSL for
* requests.
* @option options paramValidation [Boolean] whether parameter validation
* is on.
* @option options computeChecksums [Boolean] whether to compute checksums
* for payload bodies when the service accepts it (currently supported
* in S3 only)
* @option options s3ForcePathStyle [Boolean] whether to force path
* style URLs for S3 objects.
* @option options httpOptions [map] A set of options to pass to the low-level
* HTTP request. Currently supported options are:
*
* * **agent** [http.Agent, https.Agent] — the Agent object to perform
* HTTP requests with. Used for connection pooling. Defaults to the global
* agent (`http.globalAgent`) for non-SSL connections. Note that for
* SSL connections, a special Agent object is used in order to enable
* peer certificate verification.
* * **timeout** [Integer] — The number of milliseconds to wait before
* giving up on a connection attempt. Defaults to no timeout.
*/
constructor: function Config(options) {
if (options === undefined) options = {};
options = this.extractCredentials(options);
AWS.util.each.call(this, this.keys, function (key, value) {
this.set(key, options[key], value);
});
},
/**
* Updates the current configuration object with new options.
*
* @example Update maxRetries property of a configuration object
* config.update({maxRetries: 10});
* @param [Object] options a map of option keys and values.
* @see constructor
*/
update: function update(options) {
options = this.extractCredentials(options);
AWS.util.each.call(this, options, function (key, value) {
if (this.keys.hasOwnProperty(key)) this[key] = value;
});
},
/**
* @api private
*/
getCredentials: function getCredentials(callback) {
var self = this;
function finish(err) {
callback(err, err ? null : self.credentials);
}
function credError(msg, err) {
return new AWS.util.error(err || new Error(), {
code: 'CredentialsError', message: msg
});
}
function getAsyncCredentials() {
self.credentials.get(function(err) {
if (err) {
var msg = 'Could not load credentials from ' +
self.credentials.constructor.name;
err = credError(msg, err);
}
finish(err);
});
}
function getStaticCredentials() {
var err = null;
if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) {
err = credError('Missing credentials');
}
finish(err);
}
if (self.credentials) {
if (typeof self.credentials.get === 'function') {
getAsyncCredentials();
} else { // static credentials
getStaticCredentials();
}
} else if (self.credentialProvider) {
self.credentialProvider.resolve(function(err, creds) {
if (err) {
err = credError('Could not load credentials from any providers', err);
}
self.credentials = creds;
finish(err);
});
} else {
finish(credError('No credentials to load'));
}
},
/**
* Loads configuration data from a JSON file into this config object.
* @note Loading configuration will reset all existing configuration
* on the object.
* @param path [String] the path to load configuration from
* @return [AWS.Config] the same configuration object
*/
loadFromPath: function loadFromPath(path) {
this.clear();
var options = JSON.parse(AWS.util.readFileSync(path));
var fileSystemCreds = new AWS.FileSystemCredentials(path, this);
var chain = new AWS.CredentialProviderChain();
chain.providers.unshift(fileSystemCreds);
chain.resolve(function (err, creds) {
if (err) throw err;
else options.credentials = creds;
});
this.constructor(options);
return this;
},
/**
* Clears configuration data on this object
*
* @api private
*/
clear: function clear() {
/*jshint forin:false */
AWS.util.each.call(this, this.keys, function (key) {
delete this[key];
});
// reset credential provider
this.set('credentials', undefined);
this.set('credentialProvider', undefined);
},
/**
* Sets a property on the configuration object, allowing for a
* default value
* @api private
*/
set: function set(property, value, defaultValue) {
if (value === undefined) {
if (defaultValue === undefined) {
defaultValue = this.keys[property];
}
if (typeof defaultValue === 'function') {
this[property] = defaultValue.call(this);
} else {
this[property] = defaultValue;
}
} else {
this[property] = value;
}
},
/**
* All of the keys with their default values.
*
* @constant
* @api private
*/
keys: {
credentials: function () {
var credentials = null;
new AWS.CredentialProviderChain([
function () { return new AWS.EnvironmentCredentials('AWS'); },
function () { return new AWS.EnvironmentCredentials('AMAZON'); }
]).resolve(function(err, creds) {
if (!err) credentials = creds;
});
return credentials;
},
credentialProvider: function() {
return new AWS.CredentialProviderChain([
function() { return new AWS.EC2MetadataCredentials(); }
]);
},
region: function() {
return process.env.AWS_REGION || process.env.AMAZON_REGION;
},
httpOptions: {},
maxRetries: undefined,
paramValidation: true,
sslEnabled: true,
s3ForcePathStyle: false,
computeChecksums: true,
dynamoDbCrc32: true
},
/**
* Extracts accessKeyId, secretAccessKey and sessionToken
* from a configuration hash.
*
* @api private
*/
extractCredentials: function extractCredentials(options) {
if (options.accessKeyId && options.secretAccessKey) {
options = AWS.util.copy(options);
options.credentials = new AWS.Credentials(options);
}
return options;
}
});
/**
* Represents your AWS security credentials, specifically the
* {accessKeyId}, {secretAccessKey}, and optional {sessionToken}.
* Creating a `Credentials` object allows you to pass around your
* security information to configuration and service objects.
*
* Note that this class typically does not need to be constructed manually,
* as the {AWS.Config} and {AWS.Client} classes both accept simple
* options hashes with the three keys. These structures will be converted
* into Credentials objects automatically.
*
* ## Expiring and Refreshing Credentials
*
* Occasionally credentials can expire in the middle of a long-running
* application. In this case, the SDK will automatically attempt to
* refresh the credentials from the storage location if the Credentials
* class implements the {refresh} method.
*
* If you are implementing a credential storage location, you
* will want to create a subclass of the `Credentials` class and
* override the {refresh} method. This method allows credentials to be
* retrieved from the backing store, be it a file system, database, or
* some network storage. The method should reset the credential attributes
* on the object.
*
* @!attribute expired
* @return [Boolean] whether the credentials have been expired and
* require a refresh
* @!attribute accessKeyId
* @return [String] the AWS access key ID
* @!attribute secretAccessKey
* @return [String] the AWS secret access key
* @!attribute sessionToken
* @return [String] an optional AWS session token
*/
AWS.Credentials = inherit({
/**
* A credentials object can be created using positional arguments or an options
* hash.
*
* @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null)
* Creates a Credentials object with a given set of credential information
* as positional arguments.
* @param accessKeyId [String] the AWS access key ID
* @param secretAccessKey [String] the AWS secret access key
* @param sessionToken [String] the optional AWS session token
* @example Create a credentials object with AWS credentials
* var creds = new AWS.Credentials('akid', 'secret', 'session');
* @overload AWS.Credentials(options)
* Creates a Credentials object with a given set of credential information
* as an options hash.
* @option options accessKeyId [String] the AWS access key ID
* @option options secretAccessKey [String] the AWS secret access key
* @option options sessionToken [String] the optional AWS session token
* @example Create a credentials object with AWS credentials
* var creds = new AWS.Credentials({
* accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session'
* });
*/
constructor: function Credentials() {
this.expired = false;
if (arguments.length == 1 && typeof arguments[0] === 'object') {
var creds = arguments[0].credentials || arguments[0];
this.accessKeyId = creds.accessKeyId;
this.secretAccessKey = creds.secretAccessKey;
this.sessionToken = creds.sessionToken;
} else {
this.accessKeyId = arguments[0];
this.secretAccessKey = arguments[1];
this.sessionToken = arguments[2];
}
},
needsRefresh: function needsRefresh() {
return this.expired || !this.accessKeyId || !this.secretAccessKey;
},
get: function get(callback) {
var self = this;
if (this.needsRefresh()) {
this.refresh(function(err) {
if (!err) self.expired = false; // reset expired flag
callback(err);
});
} else {
callback();
}
},
/**
* Refreshes the credentials.
*
* @note Subclasses should override this class to reset the
* {accessKeyId}, {secretAccessKey} and optional {sessionToken}
* on the credentials object.
*/
refresh: function refresh(callback) {
callback();
}
});
/**
* Represents credentials from a JSON file on disk.
* If the credentials expire, the SDK can {refresh} the credentials
* from the file.
*
* The format of the file should be similar to the options passed to
* {AWS.Config}:
*
* ```js
* {accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'optional'}
* ```
*
* @example Loading credentials from disk
* var creds = new AWS.FileSystemCredentials('./configuration.json');
* creds.accessKeyId == 'AKID'
*
* @!attribute filename
* @readonly
* @return [String] the path to the JSON file on disk containing the
* credentials.
*/
AWS.FileSystemCredentials = inherit(AWS.Credentials, {
/**
* @overload AWS.FileSystemCredentials(filename, initialCredentials=null)
* Creates a new FileSystemCredentials object from a filename
*
* @param filename [String] the path on disk to the JSON file to load.
* @param initialCredentials [String] default credentials to load
* if not specified in the file.
*/
constructor: function FileSystemCredentials(filename, initialCredentials) {
this.filename = filename;
AWS.Credentials.call(this, initialCredentials);
this.get(function() {});
},
/**
* Loads the credentials from the {filename} on disk.
*/
refresh: function refresh(callback) {
if (!callback) callback = function(err) { if (err) throw err; };
try {
AWS.Credentials.call(this, JSON.parse(AWS.util.readFileSync(this.filename)));
if (!this.accessKeyId || !this.secretAccessKey) {
throw new Error('Credentials not set in ' + this.filename);
}
callback();
} catch (err) {
callback(err);
}
}
});
/**
* Represents credentials from the environment.
*
* By default, this class will look for the matching environment variables
* prefixed by a given {envPrefix}. The un-prefixed environment variable names
* for each credential value is listed below:
*
* ```js
* accessKeyId: ACCESS_KEY_ID
* secretAccessKey: SECRET_ACCESS_KEY
* sessionToken: SESSION_TOKEN
* ```
*
* With the default prefix of 'AWS', the environment variables would be:
*
* AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN
*
* @!attribute envPrefix
* @readonly
* @return [String] the prefix for the environment variable names excluding
* the separating underscore ('_').
*/
AWS.EnvironmentCredentials = inherit(AWS.Credentials, {
/**
* Creates a new EnvironmentCredentials class with a given variable
* prefix {envPrefix}. For example, to load credentials using the 'AWS'
* prefix:
*
* ```js
* var creds = new AWS.EnvironmentCredentials('AWS');
* creds.accessKeyId == 'AKID' // from AWS_ACCESS_KEY_ID env var
* ```
*
* @param envPrefix [String] the prefix to use (e.g., 'AWS') for environment
* variables. Do not include the separating underscore.
*/
constructor: function EnvironmentCredentials(envPrefix) {
this.envPrefix = envPrefix;
this.get(function() {});
},
/**
* Loads credentials from the environment using the prefixed
* environment variables.
*/
refresh: function refresh(callback) {
/*jshint maxcomplexity:10*/
if (!callback) callback = function(err) { if (err) throw err; };
if (process === undefined) {
callback(new Error('No process info available'));
return;
}
var keys = ['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY', 'SESSION_TOKEN'];
var values = [];
for (var i = 0; i < keys.length; i++) {
var prefix = '';
if (this.envPrefix) prefix = this.envPrefix + '_';
values[i] = process.env[prefix + keys[i]];
if (!values[i] && keys[i] !== 'SESSION_TOKEN') {
callback(new Error('Variable ' + prefix + keys[i] + ' not set.'));
return;
}
}
AWS.Credentials.apply(this, values);
callback();
}
});
AWS.EC2MetadataCredentials = inherit(AWS.Credentials, {
constructor: function EC2MetadataCredentials(options) {
this.serviceError = null;
this.metadataService = new AWS.MetadataService(options);
this.metadata = {};
},
refresh: function refresh(callback) {
var self = this;
if (!callback) callback = function(err) { if (err) throw err; };
if (self.serviceError) {
callback(self.serviceError);
return;
}
self.metadataService.loadCredentials(function (err, creds) {
if (err) {
self.serviceError = err;
} else {
self.metadata = creds;
self.accessKeyId = creds.AccessKeyId;
self.secretAccessKey = creds.SecretAccessKey;
self.sessionToken = creds.Token;
}
callback(err, creds);
});
}
});
/**
* Creates a credential provider chain that searches for AWS credentials
* in a list of credential providers specified by the {providers} property.
*
* By default, the chain will use the {defaultProviders} to resolve credentials.
* These providers will look in the environment using the
* {AWS.EnvironmentCredentials} class with the 'AWS' and 'AMAZON' prefixes.
*
* ## Setting Providers
*
* Each provider in the {providers} list should be a function that returns
* a {AWS.Credentials} object, or a hardcoded credentials object. The function
* form allows for delayed execution of the credential construction.
*
* ## Resolving Credentials from a Chain
*
* Call {resolve} to return the first valid credential object that can be
* loaded by the provider chain.
*
* For example, to resolve a chain with a custom provider that checks a file
* on disk after the set of {defaultProviders}:
*
* ```js
* var diskProvider = new AWS.FileSystemCredentials('./creds.json');
* var chain = new AWS.CredentialProviderChain();
* chain.providers.push(diskProvider);
* chain.resolve();
* ```
*
* The above code will return the `diskProvider` object if the
* file contains credentials and the `defaultProviders` do not contain
* any credential settings.
*
* @!attribute providers
* @return [Array<AWS.Credentials, Function>]
* a list of credentials objects or functions that return credentials
* objects. If the provider is a function, the function will be
* executed lazily when the provider needs to be checked for valid
* credentials. By default, this object will be set to the
* {defaultProviders}.
* @see defaultProviders
*/
AWS.CredentialProviderChain = inherit(AWS.Credentials, {
/**
* Creates a new CredentialProviderChain with a default set of providers
* specified by {defaultProviders}.
*/
constructor: function CredentialProviderChain(providers) {
if (providers) {
this.providers = providers;
} else {
this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0);
}
},
/**
* Resolves the provider chain by searching for the first set of
* credentials in {providers}.
*
* @callback callback function(err, credentials)
* Called when the provider resolves the chain to a credentials object
* or null if no credentials can be found.
*
* @param err [Error] the error object returned if no credentials are
* found.
* @param credentials [AWS.Credentials] the credentials object resolved
* by the provider chain.
* @return [AWS.CredentialProviderChain] the provider, for chaining.
*/
resolve: function resolve(callback) {
if (this.providers.length === 0) {
callback(new Error('No providers'));
return;
}
var index = 0;
var providers = this.providers.slice(0);
function resolveNext(err, creds) {
if ((!err && creds) || index === providers.length) {
callback(err, creds);
return;
}
var provider = providers[index++];
if (typeof provider === 'function') {
creds = provider.call();
} else {
creds = provider;
}
if (creds.get) {
creds.get(function(err) {
resolveNext(err, err ? null : creds);
});
} else {
resolveNext(null, creds);
}
}
resolveNext();
return this;
}
});
/**
* The default set of providers used by a vanilla CredentialProviderChain.
*/
AWS.CredentialProviderChain.defaultProviders = [
function () { return new AWS.EnvironmentCredentials('AWS'); },
function () { return new AWS.EnvironmentCredentials('AMAZON'); },
function () { return new AWS.EC2MetadataCredentials(); }
];
/**
* @return [AWS.Config] The global configuration object singleton instance
* @readonly
* @see AWS.Config
*/
AWS.config = new AWS.Config();