065e4ed215df673de9283e59fcedfcac5278fedd8c8145372cc2ac18f19cb534d7609241aec000d8d69922916a128cabc78e42c170fa88677a9d024bd68a19 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. aws4
  2. ----
  3. A small utility to sign [vanilla Node.js http(s)](https://nodejs.org/api/http.html) request options using Amazon's
  4. [AWS Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html).
  5. If you want to sign and send AWS requests using [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API), then check out [aws4fetch](https://github.com/mhart/aws4fetch) – otherwise you can also bundle this library for use [in older browsers](./browser).
  6. The only AWS service I know of that *doesn't* support v4 is
  7. [SimpleDB](https://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API.html)
  8. (it only supports [AWS Signature Version 2](https://github.com/mhart/aws2)).
  9. It also provides defaults for a number of core AWS headers and
  10. request parameters, making it very easy to query AWS services, or
  11. build out a fully-featured AWS library.
  12. Example
  13. -------
  14. ```javascript
  15. var https = require('https')
  16. var aws4 = require('aws4')
  17. // to illustrate usage, we'll create a utility function to request and pipe to stdout
  18. function request(opts) { https.request(opts, function(res) { res.pipe(process.stdout) }).end(opts.body || '') }
  19. // aws4 will sign an options object as you'd pass to http.request, with an AWS service and region
  20. var opts = { host: 'my-bucket.s3.us-west-1.amazonaws.com', path: '/my-object', service: 's3', region: 'us-west-1' }
  21. // aws4.sign() will sign and modify these options, ready to pass to http.request
  22. aws4.sign(opts, { accessKeyId: '', secretAccessKey: '' })
  23. // or it can get credentials from process.env.AWS_ACCESS_KEY_ID, etc
  24. aws4.sign(opts)
  25. // for most AWS services, aws4 can figure out the service and region if you pass a host
  26. opts = { host: 'my-bucket.s3.us-west-1.amazonaws.com', path: '/my-object' }
  27. // usually it will add/modify request headers, but you can also sign the query:
  28. opts = { host: 'my-bucket.s3.amazonaws.com', path: '/?X-Amz-Expires=12345', signQuery: true }
  29. // and for services with simple hosts, aws4 can infer the host from service and region:
  30. opts = { service: 'sqs', region: 'us-east-1', path: '/?Action=ListQueues' }
  31. // and if you're using us-east-1, it's the default:
  32. opts = { service: 'sqs', path: '/?Action=ListQueues' }
  33. aws4.sign(opts)
  34. console.log(opts)
  35. /*
  36. {
  37. host: 'sqs.us-east-1.amazonaws.com',
  38. path: '/?Action=ListQueues',
  39. headers: {
  40. Host: 'sqs.us-east-1.amazonaws.com',
  41. 'X-Amz-Date': '20121226T061030Z',
  42. Authorization: 'AWS4-HMAC-SHA256 Credential=ABCDEF/20121226/us-east-1/sqs/aws4_request, ...'
  43. }
  44. }
  45. */
  46. // we can now use this to query AWS
  47. request(opts)
  48. /*
  49. <?xml version="1.0"?>
  50. <ListQueuesResponse xmlns="https://queue.amazonaws.com/doc/2012-11-05/">
  51. ...
  52. */
  53. // aws4 can infer the HTTP method if a body is passed in
  54. // method will be POST and Content-Type: 'application/x-www-form-urlencoded; charset=utf-8'
  55. request(aws4.sign({ service: 'iam', body: 'Action=ListGroups&Version=2010-05-08' }))
  56. /*
  57. <ListGroupsResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/">
  58. ...
  59. */
  60. // you can specify any custom option or header as per usual
  61. request(aws4.sign({
  62. service: 'dynamodb',
  63. region: 'ap-southeast-2',
  64. method: 'POST',
  65. path: '/',
  66. headers: {
  67. 'Content-Type': 'application/x-amz-json-1.0',
  68. 'X-Amz-Target': 'DynamoDB_20120810.ListTables'
  69. },
  70. body: '{}'
  71. }))
  72. /*
  73. {"TableNames":[]}
  74. ...
  75. */
  76. // you can also specify extra headers to ignore during signing
  77. request(aws4.sign({
  78. host: '07tjusf2h91cunochc.us-east-1.aoss.amazonaws.com',
  79. method: 'PUT',
  80. path: '/my-index',
  81. body: '{"mappings":{}}',
  82. headers: {
  83. 'Content-Type': 'application/json',
  84. 'X-Amz-Content-Sha256': 'UNSIGNED-PAYLOAD'
  85. },
  86. extraHeadersToIgnore: {
  87. 'content-length': true
  88. }
  89. }))
  90. // and headers to include that would normally be ignored
  91. request(aws4.sign({
  92. service: 'mycustomservice',
  93. path: '/whatever',
  94. headers: {
  95. 'Range': 'bytes=200-1000, 2000-6576, 19000-'
  96. },
  97. extraHeadersToInclude: {
  98. 'range': true
  99. }
  100. }))
  101. // The raw RequestSigner can be used to generate CodeCommit Git passwords
  102. var signer = new aws4.RequestSigner({
  103. service: 'codecommit',
  104. host: 'git-codecommit.us-east-1.amazonaws.com',
  105. method: 'GIT',
  106. path: '/v1/repos/MyAwesomeRepo',
  107. })
  108. var password = signer.getDateTime() + 'Z' + signer.signature()
  109. // see example.js for examples with other services
  110. ```
  111. API
  112. ---
  113. ### aws4.sign(requestOptions, [credentials])
  114. Calculates and populates any necessary AWS headers and/or request
  115. options on `requestOptions`. Returns `requestOptions` as a convenience for chaining.
  116. `requestOptions` is an object holding the same options that the Node.js
  117. [http.request](https://nodejs.org/docs/latest/api/http.html#http_http_request_options_callback)
  118. function takes.
  119. The following properties of `requestOptions` are used in the signing or
  120. populated if they don't already exist:
  121. - `hostname` or `host` (will try to be determined from `service` and `region` if not given)
  122. - `method` (will use `'GET'` if not given or `'POST'` if there is a `body`)
  123. - `path` (will use `'/'` if not given)
  124. - `body` (will use `''` if not given)
  125. - `service` (will try to be calculated from `hostname` or `host` if not given)
  126. - `region` (will try to be calculated from `hostname` or `host` or use `'us-east-1'` if not given)
  127. - `signQuery` (to sign the query instead of adding an `Authorization` header, defaults to false)
  128. - `extraHeadersToIgnore` (an object with lowercase header keys to ignore when signing, eg `{ 'content-length': true }`)
  129. - `extraHeadersToInclude` (an object with lowercase header keys to include when signing, overriding any ignores)
  130. - `headers['Host']` (will use `hostname` or `host` or be calculated if not given)
  131. - `headers['Content-Type']` (will use `'application/x-www-form-urlencoded; charset=utf-8'`
  132. if not given and there is a `body`)
  133. - `headers['Date']` (used to calculate the signature date if given, otherwise `new Date` is used)
  134. Your AWS credentials (which can be found in your
  135. [AWS console](https://portal.aws.amazon.com/gp/aws/securityCredentials))
  136. can be specified in one of two ways:
  137. - As the second argument, like this:
  138. ```javascript
  139. aws4.sign(requestOptions, {
  140. secretAccessKey: "<your-secret-access-key>",
  141. accessKeyId: "<your-access-key-id>",
  142. sessionToken: "<your-session-token>"
  143. })
  144. ```
  145. - From `process.env`, such as this:
  146. ```
  147. export AWS_ACCESS_KEY_ID="<your-access-key-id>"
  148. export AWS_SECRET_ACCESS_KEY="<your-secret-access-key>"
  149. export AWS_SESSION_TOKEN="<your-session-token>"
  150. ```
  151. (will also use `AWS_ACCESS_KEY` and `AWS_SECRET_KEY` if available)
  152. The `sessionToken` property and `AWS_SESSION_TOKEN` environment variable are optional for signing
  153. with [IAM STS temporary credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html).
  154. Installation
  155. ------------
  156. With [npm](https://www.npmjs.com/) do:
  157. ```
  158. npm install aws4
  159. ```
  160. Can also be used [in the browser](./browser).
  161. Thanks
  162. ------
  163. Thanks to [@jed](https://github.com/jed) for his
  164. [dynamo-client](https://github.com/jed/dynamo-client) lib where I first
  165. committed and subsequently extracted this code.
  166. Also thanks to the
  167. [official Node.js AWS SDK](https://github.com/aws/aws-sdk-js) for giving
  168. me a start on implementing the v4 signature.