UNPKG

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