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