UNPKG

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