config.js 29 KB

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