UNPKG

24.9 kBJavaScriptView Raw
1var AWS = require('./core');
2require('./credentials');
3require('./credentials/credential_provider_chain');
4var PromisesDependency;
5
6/**
7 * The main configuration class used by all service objects to set
8 * the region, credentials, and other options for requests.
9 *
10 * By default, credentials and region settings are left unconfigured.
11 * This should be configured by the application before using any
12 * AWS service APIs.
13 *
14 * In order to set global configuration options, properties should
15 * be assigned to the global {AWS.config} object.
16 *
17 * @see AWS.config
18 *
19 * @!group General Configuration Options
20 *
21 * @!attribute credentials
22 * @return [AWS.Credentials] the AWS credentials to sign requests with.
23 *
24 * @!attribute region
25 * @example Set the global region setting to us-west-2
26 * AWS.config.update({region: 'us-west-2'});
27 * @return [AWS.Credentials] The region to send service requests to.
28 * @see http://docs.amazonwebservices.com/general/latest/gr/rande.html
29 * A list of available endpoints for each AWS service
30 *
31 * @!attribute maxRetries
32 * @return [Integer] the maximum amount of retries to perform for a
33 * service request. By default this value is calculated by the specific
34 * service object that the request is being made to.
35 *
36 * @!attribute maxRedirects
37 * @return [Integer] the maximum amount of redirects to follow for a
38 * service request. Defaults to 10.
39 *
40 * @!attribute paramValidation
41 * @return [Boolean|map] whether input parameters should be validated against
42 * the operation description before sending the request. Defaults to true.
43 * Pass a map to enable any of the following specific validation features:
44 *
45 * * **min** [Boolean] — Validates that a value meets the min
46 * constraint. This is enabled by default when paramValidation is set
47 * to `true`.
48 * * **max** [Boolean] — Validates that a value meets the max
49 * constraint.
50 * * **pattern** [Boolean] — Validates that a string value matches a
51 * regular expression.
52 * * **enum** [Boolean] — Validates that a string value matches one
53 * of the allowable enum values.
54 *
55 * @!attribute computeChecksums
56 * @return [Boolean] whether to compute checksums for payload bodies when
57 * the service accepts it (currently supported in S3 only).
58 *
59 * @!attribute convertResponseTypes
60 * @return [Boolean] whether types are converted when parsing response data.
61 * Currently only supported for JSON based services. Turning this off may
62 * improve performance on large response payloads. Defaults to `true`.
63 *
64 * @!attribute correctClockSkew
65 * @return [Boolean] whether to apply a clock skew correction and retry
66 * requests that fail because of an skewed client clock. Defaults to
67 * `false`.
68 *
69 * @!attribute sslEnabled
70 * @return [Boolean] whether SSL is enabled for requests
71 *
72 * @!attribute s3ForcePathStyle
73 * @return [Boolean] whether to force path style URLs for S3 objects
74 *
75 * @!attribute s3BucketEndpoint
76 * @note Setting this configuration option requires an `endpoint` to be
77 * provided explicitly to the service constructor.
78 * @return [Boolean] whether the provided endpoint addresses an individual
79 * bucket (false if it addresses the root API endpoint).
80 *
81 * @!attribute s3DisableBodySigning
82 * @return [Boolean] whether to disable S3 body signing when using signature version `v4`.
83 * Body signing can only be disabled when using https. Defaults to `true`.
84 *
85 * @!attribute useAccelerateEndpoint
86 * @note This configuration option is only compatible with S3 while accessing
87 * dns-compatible buckets.
88 * @return [Boolean] Whether to use the Accelerate endpoint with the S3 service.
89 * Defaults to `false`.
90 *
91 * @!attribute retryDelayOptions
92 * @example Set the base retry delay for all services to 300 ms
93 * AWS.config.update({retryDelayOptions: {base: 300}});
94 * // Delays with maxRetries = 3: 300, 600, 1200
95 * @example Set a custom backoff function to provide delay values on retries
96 * AWS.config.update({retryDelayOptions: {customBackoff: function(retryCount) {
97 * // returns delay in ms
98 * }}});
99 * @return [map] A set of options to configure the retry delay on retryable errors.
100 * Currently supported options are:
101 *
102 * * **base** [Integer] — The base number of milliseconds to use in the
103 * exponential backoff for operation retries. Defaults to 100 ms for all services except
104 * DynamoDB, where it defaults to 50ms.
105 * * **customBackoff ** [function] — A custom function that accepts a retry count
106 * and returns the amount of time to delay in milliseconds. The `base` option will be
107 * ignored if this option is supplied.
108 *
109 * @!attribute httpOptions
110 * @return [map] A set of options to pass to the low-level HTTP request.
111 * Currently supported options are:
112 *
113 * * **proxy** [String] — the URL to proxy requests through
114 * * **agent** [http.Agent, https.Agent] — the Agent object to perform
115 * HTTP requests with. Used for connection pooling. Note that for
116 * SSL connections, a special Agent object is used in order to enable
117 * peer certificate verification. This feature is only supported in the
118 * Node.js environment.
119 * * **connectTimeout** [Integer] — Sets the socket to timeout after
120 * failing to establish a connection with the server after
121 * `connectTimeout` milliseconds. This timeout has no effect once a socket
122 * connection has been established.
123 * * **timeout** [Integer] — Sets the socket to timeout after timeout
124 * milliseconds of inactivity on the socket. Defaults to two minutes
125 * (120000)
126 * * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous
127 * HTTP requests. Used in the browser environment only. Set to false to
128 * send requests synchronously. Defaults to true (async on).
129 * * **xhrWithCredentials** [Boolean] — Sets the "withCredentials"
130 * property of an XMLHttpRequest object. Used in the browser environment
131 * only. Defaults to false.
132 * @!attribute logger
133 * @return [#write,#log] an object that responds to .write() (like a stream)
134 * or .log() (like the console object) in order to log information about
135 * requests
136 *
137 * @!attribute systemClockOffset
138 * @return [Number] an offset value in milliseconds to apply to all signing
139 * times. Use this to compensate for clock skew when your system may be
140 * out of sync with the service time. Note that this configuration option
141 * can only be applied to the global `AWS.config` object and cannot be
142 * overridden in service-specific configuration. Defaults to 0 milliseconds.
143 *
144 * @!attribute signatureVersion
145 * @return [String] the signature version to sign requests with (overriding
146 * the API configuration). Possible values are: 'v2', 'v3', 'v4'.
147 *
148 * @!attribute signatureCache
149 * @return [Boolean] whether the signature to sign requests with (overriding
150 * the API configuration) is cached. Only applies to the signature version 'v4'.
151 * Defaults to `true`.
152 *
153 * @!attribute endpointDiscoveryEnabled
154 * @return [Boolean] whether to enable endpoint discovery for operations that
155 * allow optionally using an endpoint returned by the service.
156 * Defaults to 'false'
157 *
158 * @!attribute endpointCacheSize
159 * @return [Number] the size of the global cache storing endpoints from endpoint
160 * discovery operations. Once endpoint cache is created, updating this setting
161 * cannot change existing cache size.
162 * Defaults to 1000
163 *
164 * @!attribute hostPrefixEnabled
165 * @return [Boolean] whether to marshal request parameters to the prefix of
166 * hostname. Defaults to `true`.
167 *
168 * @!attribute stsRegionalEndpoints
169 * @return ['legacy'|'regional'] whether to send sts request to global endpoints or
170 * regional endpoints.
171 * Defaults to 'legacy'
172 */
173AWS.Config = AWS.util.inherit({
174 /**
175 * @!endgroup
176 */
177
178 /**
179 * Creates a new configuration object. This is the object that passes
180 * option data along to service requests, including credentials, security,
181 * region information, and some service specific settings.
182 *
183 * @example Creating a new configuration object with credentials and region
184 * var config = new AWS.Config({
185 * accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2'
186 * });
187 * @option options accessKeyId [String] your AWS access key ID.
188 * @option options secretAccessKey [String] your AWS secret access key.
189 * @option options sessionToken [AWS.Credentials] the optional AWS
190 * session token to sign requests with.
191 * @option options credentials [AWS.Credentials] the AWS credentials
192 * to sign requests with. You can either specify this object, or
193 * specify the accessKeyId and secretAccessKey options directly.
194 * @option options credentialProvider [AWS.CredentialProviderChain] the
195 * provider chain used to resolve credentials if no static `credentials`
196 * property is set.
197 * @option options region [String] the region to send service requests to.
198 * See {region} for more information.
199 * @option options maxRetries [Integer] the maximum amount of retries to
200 * attempt with a request. See {maxRetries} for more information.
201 * @option options maxRedirects [Integer] the maximum amount of redirects to
202 * follow with a request. See {maxRedirects} for more information.
203 * @option options sslEnabled [Boolean] whether to enable SSL for
204 * requests.
205 * @option options paramValidation [Boolean|map] whether input parameters
206 * should be validated against the operation description before sending
207 * the request. Defaults to true. Pass a map to enable any of the
208 * following specific validation features:
209 *
210 * * **min** [Boolean] — Validates that a value meets the min
211 * constraint. This is enabled by default when paramValidation is set
212 * to `true`.
213 * * **max** [Boolean] — Validates that a value meets the max
214 * constraint.
215 * * **pattern** [Boolean] — Validates that a string value matches a
216 * regular expression.
217 * * **enum** [Boolean] — Validates that a string value matches one
218 * of the allowable enum values.
219 * @option options computeChecksums [Boolean] whether to compute checksums
220 * for payload bodies when the service accepts it (currently supported
221 * in S3 only)
222 * @option options convertResponseTypes [Boolean] whether types are converted
223 * when parsing response data. Currently only supported for JSON based
224 * services. Turning this off may improve performance on large response
225 * payloads. Defaults to `true`.
226 * @option options correctClockSkew [Boolean] whether to apply a clock skew
227 * correction and retry requests that fail because of an skewed client
228 * clock. Defaults to `false`.
229 * @option options s3ForcePathStyle [Boolean] whether to force path
230 * style URLs for S3 objects.
231 * @option options s3BucketEndpoint [Boolean] whether the provided endpoint
232 * addresses an individual bucket (false if it addresses the root API
233 * endpoint). Note that setting this configuration option requires an
234 * `endpoint` to be provided explicitly to the service constructor.
235 * @option options s3DisableBodySigning [Boolean] whether S3 body signing
236 * should be disabled when using signature version `v4`. Body signing
237 * can only be disabled when using https. Defaults to `true`.
238 *
239 * @option options retryDelayOptions [map] A set of options to configure
240 * the retry delay on retryable errors. Currently supported options are:
241 *
242 * * **base** [Integer] — The base number of milliseconds to use in the
243 * exponential backoff for operation retries. Defaults to 100 ms for all
244 * services except DynamoDB, where it defaults to 50ms.
245 * * **customBackoff ** [function] — A custom function that accepts a retry count
246 * and returns the amount of time to delay in milliseconds. The `base` option will be
247 * ignored if this option is supplied.
248 * @option options httpOptions [map] A set of options to pass to the low-level
249 * HTTP request. Currently supported options are:
250 *
251 * * **proxy** [String] — the URL to proxy requests through
252 * * **agent** [http.Agent, https.Agent] — the Agent object to perform
253 * HTTP requests with. Used for connection pooling. Defaults to the global
254 * agent (`http.globalAgent`) for non-SSL connections. Note that for
255 * SSL connections, a special Agent object is used in order to enable
256 * peer certificate verification. This feature is only available in the
257 * Node.js environment.
258 * * **connectTimeout** [Integer] — Sets the socket to timeout after
259 * failing to establish a connection with the server after
260 * `connectTimeout` milliseconds. This timeout has no effect once a socket
261 * connection has been established.
262 * * **timeout** [Integer] — Sets the socket to timeout after timeout
263 * milliseconds of inactivity on the socket. Defaults to two minutes
264 * (120000).
265 * * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous
266 * HTTP requests. Used in the browser environment only. Set to false to
267 * send requests synchronously. Defaults to true (async on).
268 * * **xhrWithCredentials** [Boolean] — Sets the "withCredentials"
269 * property of an XMLHttpRequest object. Used in the browser environment
270 * only. Defaults to false.
271 * @option options apiVersion [String, Date] a String in YYYY-MM-DD format
272 * (or a date) that represents the latest possible API version that can be
273 * used in all services (unless overridden by `apiVersions`). Specify
274 * 'latest' to use the latest possible version.
275 * @option options apiVersions [map<String, String|Date>] a map of service
276 * identifiers (the lowercase service class name) with the API version to
277 * use when instantiating a service. Specify 'latest' for each individual
278 * that can use the latest available version.
279 * @option options logger [#write,#log] an object that responds to .write()
280 * (like a stream) or .log() (like the console object) in order to log
281 * information about requests
282 * @option options systemClockOffset [Number] an offset value in milliseconds
283 * to apply to all signing times. Use this to compensate for clock skew
284 * when your system may be out of sync with the service time. Note that
285 * this configuration option can only be applied to the global `AWS.config`
286 * object and cannot be overridden in service-specific configuration.
287 * Defaults to 0 milliseconds.
288 * @option options signatureVersion [String] the signature version to sign
289 * requests with (overriding the API configuration). Possible values are:
290 * 'v2', 'v3', 'v4'.
291 * @option options signatureCache [Boolean] whether the signature to sign
292 * requests with (overriding the API configuration) is cached. Only applies
293 * to the signature version 'v4'. Defaults to `true`.
294 * @option options dynamoDbCrc32 [Boolean] whether to validate the CRC32
295 * checksum of HTTP response bodies returned by DynamoDB. Default: `true`.
296 * @option options useAccelerateEndpoint [Boolean] Whether to use the
297 * S3 Transfer Acceleration endpoint with the S3 service. Default: `false`.
298 * @option options clientSideMonitoring [Boolean] whether to collect and
299 * publish this client's performance metrics of all its API requests.
300 * @option options endpointDiscoveryEnabled [Boolean] whether to enable endpoint
301 * discovery for operations that allow optionally using an endpoint returned by
302 * the service.
303 * Defaults to 'false'
304 * @option options endpointCacheSize [Number] the size of the global cache storing
305 * endpoints from endpoint discovery operations. Once endpoint cache is created,
306 * updating this setting cannot change existing cache size.
307 * Defaults to 1000
308 * @option options hostPrefixEnabled [Boolean] whether to marshal request
309 * parameters to the prefix of hostname.
310 * Defaults to `true`.
311 * @option options stsRegionalEndpoints ['legacy'|'regional'] whether to send sts request
312 * to global endpoints or regional endpoints.
313 * Defaults to 'legacy'.
314 */
315 constructor: function Config(options) {
316 if (options === undefined) options = {};
317 options = this.extractCredentials(options);
318
319 AWS.util.each.call(this, this.keys, function (key, value) {
320 this.set(key, options[key], value);
321 });
322 },
323
324 /**
325 * @!group Managing Credentials
326 */
327
328 /**
329 * Loads credentials from the configuration object. This is used internally
330 * by the SDK to ensure that refreshable {Credentials} objects are properly
331 * refreshed and loaded when sending a request. If you want to ensure that
332 * your credentials are loaded prior to a request, you can use this method
333 * directly to provide accurate credential data stored in the object.
334 *
335 * @note If you configure the SDK with static or environment credentials,
336 * the credential data should already be present in {credentials} attribute.
337 * This method is primarily necessary to load credentials from asynchronous
338 * sources, or sources that can refresh credentials periodically.
339 * @example Getting your access key
340 * AWS.config.getCredentials(function(err) {
341 * if (err) console.log(err.stack); // credentials not loaded
342 * else console.log("Access Key:", AWS.config.credentials.accessKeyId);
343 * })
344 * @callback callback function(err)
345 * Called when the {credentials} have been properly set on the configuration
346 * object.
347 *
348 * @param err [Error] if this is set, credentials were not successfully
349 * loaded and this error provides information why.
350 * @see credentials
351 * @see Credentials
352 */
353 getCredentials: function getCredentials(callback) {
354 var self = this;
355
356 function finish(err) {
357 callback(err, err ? null : self.credentials);
358 }
359
360 function credError(msg, err) {
361 return new AWS.util.error(err || new Error(), {
362 code: 'CredentialsError',
363 message: msg,
364 name: 'CredentialsError'
365 });
366 }
367
368 function getAsyncCredentials() {
369 self.credentials.get(function(err) {
370 if (err) {
371 var msg = 'Could not load credentials from ' +
372 self.credentials.constructor.name;
373 err = credError(msg, err);
374 }
375 finish(err);
376 });
377 }
378
379 function getStaticCredentials() {
380 var err = null;
381 if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) {
382 err = credError('Missing credentials');
383 }
384 finish(err);
385 }
386
387 if (self.credentials) {
388 if (typeof self.credentials.get === 'function') {
389 getAsyncCredentials();
390 } else { // static credentials
391 getStaticCredentials();
392 }
393 } else if (self.credentialProvider) {
394 self.credentialProvider.resolve(function(err, creds) {
395 if (err) {
396 err = credError('Could not load credentials from any providers', err);
397 }
398 self.credentials = creds;
399 finish(err);
400 });
401 } else {
402 finish(credError('No credentials to load'));
403 }
404 },
405
406 /**
407 * @!group Loading and Setting Configuration Options
408 */
409
410 /**
411 * @overload update(options, allowUnknownKeys = false)
412 * Updates the current configuration object with new options.
413 *
414 * @example Update maxRetries property of a configuration object
415 * config.update({maxRetries: 10});
416 * @param [Object] options a map of option keys and values.
417 * @param [Boolean] allowUnknownKeys whether unknown keys can be set on
418 * the configuration object. Defaults to `false`.
419 * @see constructor
420 */
421 update: function update(options, allowUnknownKeys) {
422 allowUnknownKeys = allowUnknownKeys || false;
423 options = this.extractCredentials(options);
424 AWS.util.each.call(this, options, function (key, value) {
425 if (allowUnknownKeys || Object.prototype.hasOwnProperty.call(this.keys, key) ||
426 AWS.Service.hasService(key)) {
427 this.set(key, value);
428 }
429 });
430 },
431
432 /**
433 * Loads configuration data from a JSON file into this config object.
434 * @note Loading configuration will reset all existing configuration
435 * on the object.
436 * @!macro nobrowser
437 * @param path [String] the path relative to your process's current
438 * working directory to load configuration from.
439 * @return [AWS.Config] the same configuration object
440 */
441 loadFromPath: function loadFromPath(path) {
442 this.clear();
443
444 var options = JSON.parse(AWS.util.readFileSync(path));
445 var fileSystemCreds = new AWS.FileSystemCredentials(path);
446 var chain = new AWS.CredentialProviderChain();
447 chain.providers.unshift(fileSystemCreds);
448 chain.resolve(function (err, creds) {
449 if (err) throw err;
450 else options.credentials = creds;
451 });
452
453 this.constructor(options);
454
455 return this;
456 },
457
458 /**
459 * Clears configuration data on this object
460 *
461 * @api private
462 */
463 clear: function clear() {
464 /*jshint forin:false */
465 AWS.util.each.call(this, this.keys, function (key) {
466 delete this[key];
467 });
468
469 // reset credential provider
470 this.set('credentials', undefined);
471 this.set('credentialProvider', undefined);
472 },
473
474 /**
475 * Sets a property on the configuration object, allowing for a
476 * default value
477 * @api private
478 */
479 set: function set(property, value, defaultValue) {
480 if (value === undefined) {
481 if (defaultValue === undefined) {
482 defaultValue = this.keys[property];
483 }
484 if (typeof defaultValue === 'function') {
485 this[property] = defaultValue.call(this);
486 } else {
487 this[property] = defaultValue;
488 }
489 } else if (property === 'httpOptions' && this[property]) {
490 // deep merge httpOptions
491 this[property] = AWS.util.merge(this[property], value);
492 } else {
493 this[property] = value;
494 }
495 },
496
497 /**
498 * All of the keys with their default values.
499 *
500 * @constant
501 * @api private
502 */
503 keys: {
504 credentials: null,
505 credentialProvider: null,
506 region: null,
507 logger: null,
508 apiVersions: {},
509 apiVersion: null,
510 endpoint: undefined,
511 httpOptions: {
512 timeout: 120000
513 },
514 maxRetries: undefined,
515 maxRedirects: 10,
516 paramValidation: true,
517 sslEnabled: true,
518 s3ForcePathStyle: false,
519 s3BucketEndpoint: false,
520 s3DisableBodySigning: true,
521 computeChecksums: true,
522 convertResponseTypes: true,
523 correctClockSkew: false,
524 customUserAgent: null,
525 dynamoDbCrc32: true,
526 systemClockOffset: 0,
527 signatureVersion: null,
528 signatureCache: true,
529 retryDelayOptions: {},
530 useAccelerateEndpoint: false,
531 clientSideMonitoring: false,
532 endpointDiscoveryEnabled: false,
533 endpointCacheSize: 1000,
534 hostPrefixEnabled: true,
535 stsRegionalEndpoints: null
536 },
537
538 /**
539 * Extracts accessKeyId, secretAccessKey and sessionToken
540 * from a configuration hash.
541 *
542 * @api private
543 */
544 extractCredentials: function extractCredentials(options) {
545 if (options.accessKeyId && options.secretAccessKey) {
546 options = AWS.util.copy(options);
547 options.credentials = new AWS.Credentials(options);
548 }
549 return options;
550 },
551
552 /**
553 * Sets the promise dependency the SDK will use wherever Promises are returned.
554 * Passing `null` will force the SDK to use native Promises if they are available.
555 * If native Promises are not available, passing `null` will have no effect.
556 * @param [Constructor] dep A reference to a Promise constructor
557 */
558 setPromisesDependency: function setPromisesDependency(dep) {
559 PromisesDependency = dep;
560 // if null was passed in, we should try to use native promises
561 if (dep === null && typeof Promise === 'function') {
562 PromisesDependency = Promise;
563 }
564 var constructors = [AWS.Request, AWS.Credentials, AWS.CredentialProviderChain];
565 if (AWS.S3) {
566 constructors.push(AWS.S3);
567 if (AWS.S3.ManagedUpload) {
568 constructors.push(AWS.S3.ManagedUpload);
569 }
570 }
571 AWS.util.addPromises(constructors, PromisesDependency);
572 },
573
574 /**
575 * Gets the promise dependency set by `AWS.config.setPromisesDependency`.
576 */
577 getPromisesDependency: function getPromisesDependency() {
578 return PromisesDependency;
579 }
580});
581
582/**
583 * @return [AWS.Config] The global configuration object singleton instance
584 * @readonly
585 * @see AWS.Config
586 */
587AWS.config = new AWS.Config();