git-off

Log

Files

Refs

README

config.js (21710B)

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