Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

3 lat temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. aws4
  2. ----
  3. [![Build Status](https://secure.travis-ci.org/mhart/aws4.png?branch=master)](http://travis-ci.org/mhart/aws4)
  4. A small utility to sign vanilla Node.js http(s) request options using Amazon's
  5. [AWS Signature Version 4](http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html).
  6. If you want to sign and send AWS requests in a modern browser, or an environment like [Cloudflare Workers](https://developers.cloudflare.com/workers/), then check out [aws4fetch](https://github.com/mhart/aws4fetch) – otherwise you can also bundle this library for use [in the browser](./browser).
  7. This signature is supported by nearly all Amazon services, including
  8. [S3](http://docs.aws.amazon.com/AmazonS3/latest/API/),
  9. [EC2](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/),
  10. [DynamoDB](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API.html),
  11. [Kinesis](http://docs.aws.amazon.com/kinesis/latest/APIReference/),
  12. [Lambda](http://docs.aws.amazon.com/lambda/latest/dg/API_Reference.html),
  13. [SQS](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/),
  14. [SNS](http://docs.aws.amazon.com/sns/latest/api/),
  15. [IAM](http://docs.aws.amazon.com/IAM/latest/APIReference/),
  16. [STS](http://docs.aws.amazon.com/STS/latest/APIReference/),
  17. [RDS](http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/),
  18. [CloudWatch](http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/),
  19. [CloudWatch Logs](http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/),
  20. [CodeDeploy](http://docs.aws.amazon.com/codedeploy/latest/APIReference/),
  21. [CloudFront](http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/),
  22. [CloudTrail](http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/),
  23. [ElastiCache](http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/),
  24. [EMR](http://docs.aws.amazon.com/ElasticMapReduce/latest/API/),
  25. [Glacier](http://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-api.html),
  26. [CloudSearch](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/APIReq.html),
  27. [Elastic Load Balancing](http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/),
  28. [Elastic Transcoder](http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/api-reference.html),
  29. [CloudFormation](http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/),
  30. [Elastic Beanstalk](http://docs.aws.amazon.com/elasticbeanstalk/latest/api/),
  31. [Storage Gateway](http://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html),
  32. [Data Pipeline](http://docs.aws.amazon.com/datapipeline/latest/APIReference/),
  33. [Direct Connect](http://docs.aws.amazon.com/directconnect/latest/APIReference/),
  34. [Redshift](http://docs.aws.amazon.com/redshift/latest/APIReference/),
  35. [OpsWorks](http://docs.aws.amazon.com/opsworks/latest/APIReference/),
  36. [SES](http://docs.aws.amazon.com/ses/latest/APIReference/),
  37. [SWF](http://docs.aws.amazon.com/amazonswf/latest/apireference/),
  38. [AutoScaling](http://docs.aws.amazon.com/AutoScaling/latest/APIReference/),
  39. [Mobile Analytics](http://docs.aws.amazon.com/mobileanalytics/latest/ug/server-reference.html),
  40. [Cognito Identity](http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/),
  41. [Cognito Sync](http://docs.aws.amazon.com/cognitosync/latest/APIReference/),
  42. [Container Service](http://docs.aws.amazon.com/AmazonECS/latest/APIReference/),
  43. [AppStream](http://docs.aws.amazon.com/appstream/latest/developerguide/appstream-api-rest.html),
  44. [Key Management Service](http://docs.aws.amazon.com/kms/latest/APIReference/),
  45. [Config](http://docs.aws.amazon.com/config/latest/APIReference/),
  46. [CloudHSM](http://docs.aws.amazon.com/cloudhsm/latest/dg/api-ref.html),
  47. [Route53](http://docs.aws.amazon.com/Route53/latest/APIReference/requests-rest.html) and
  48. [Route53 Domains](http://docs.aws.amazon.com/Route53/latest/APIReference/requests-rpc.html).
  49. Indeed, the only AWS services that *don't* support v4 as of 2014-12-30 are
  50. [Import/Export](http://docs.aws.amazon.com/AWSImportExport/latest/DG/api-reference.html) and
  51. [SimpleDB](http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API.html)
  52. (they only support [AWS Signature Version 2](https://github.com/mhart/aws2)).
  53. It also provides defaults for a number of core AWS headers and
  54. request parameters, making it very easy to query AWS services, or
  55. build out a fully-featured AWS library.
  56. Example
  57. -------
  58. ```javascript
  59. var http = require('http'),
  60. https = require('https'),
  61. aws4 = require('aws4')
  62. // given an options object you could pass to http.request
  63. var opts = {host: 'sqs.us-east-1.amazonaws.com', path: '/?Action=ListQueues'}
  64. // alternatively (as aws4 can infer the host):
  65. opts = {service: 'sqs', region: 'us-east-1', path: '/?Action=ListQueues'}
  66. // alternatively (as us-east-1 is default):
  67. opts = {service: 'sqs', path: '/?Action=ListQueues'}
  68. aws4.sign(opts) // assumes AWS credentials are available in process.env
  69. console.log(opts)
  70. /*
  71. {
  72. host: 'sqs.us-east-1.amazonaws.com',
  73. path: '/?Action=ListQueues',
  74. headers: {
  75. Host: 'sqs.us-east-1.amazonaws.com',
  76. 'X-Amz-Date': '20121226T061030Z',
  77. Authorization: 'AWS4-HMAC-SHA256 Credential=ABCDEF/20121226/us-east-1/sqs/aws4_request, ...'
  78. }
  79. }
  80. */
  81. // we can now use this to query AWS using the standard node.js http API
  82. http.request(opts, function(res) { res.pipe(process.stdout) }).end()
  83. /*
  84. <?xml version="1.0"?>
  85. <ListQueuesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">
  86. ...
  87. */
  88. ```
  89. More options
  90. ------------
  91. ```javascript
  92. // you can also pass AWS credentials in explicitly (otherwise taken from process.env)
  93. aws4.sign(opts, {accessKeyId: '', secretAccessKey: ''})
  94. // can also add the signature to query strings
  95. aws4.sign({service: 's3', path: '/my-bucket?X-Amz-Expires=12345', signQuery: true})
  96. // create a utility function to pipe to stdout (with https this time)
  97. function request(o) { https.request(o, function(res) { res.pipe(process.stdout) }).end(o.body || '') }
  98. // aws4 can infer the HTTP method if a body is passed in
  99. // method will be POST and Content-Type: 'application/x-www-form-urlencoded; charset=utf-8'
  100. request(aws4.sign({service: 'iam', body: 'Action=ListGroups&Version=2010-05-08'}))
  101. /*
  102. <ListGroupsResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/">
  103. ...
  104. */
  105. // can specify any custom option or header as per usual
  106. request(aws4.sign({
  107. service: 'dynamodb',
  108. region: 'ap-southeast-2',
  109. method: 'POST',
  110. path: '/',
  111. headers: {
  112. 'Content-Type': 'application/x-amz-json-1.0',
  113. 'X-Amz-Target': 'DynamoDB_20120810.ListTables'
  114. },
  115. body: '{}'
  116. }))
  117. /*
  118. {"TableNames":[]}
  119. ...
  120. */
  121. // works with all other services that support Signature Version 4
  122. request(aws4.sign({service: 's3', path: '/', signQuery: true}))
  123. /*
  124. <ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  125. ...
  126. */
  127. request(aws4.sign({service: 'ec2', path: '/?Action=DescribeRegions&Version=2014-06-15'}))
  128. /*
  129. <DescribeRegionsResponse xmlns="http://ec2.amazonaws.com/doc/2014-06-15/">
  130. ...
  131. */
  132. request(aws4.sign({service: 'sns', path: '/?Action=ListTopics&Version=2010-03-31'}))
  133. /*
  134. <ListTopicsResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
  135. ...
  136. */
  137. request(aws4.sign({service: 'sts', path: '/?Action=GetSessionToken&Version=2011-06-15'}))
  138. /*
  139. <GetSessionTokenResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
  140. ...
  141. */
  142. request(aws4.sign({service: 'cloudsearch', path: '/?Action=ListDomainNames&Version=2013-01-01'}))
  143. /*
  144. <ListDomainNamesResponse xmlns="http://cloudsearch.amazonaws.com/doc/2013-01-01/">
  145. ...
  146. */
  147. request(aws4.sign({service: 'ses', path: '/?Action=ListIdentities&Version=2010-12-01'}))
  148. /*
  149. <ListIdentitiesResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">
  150. ...
  151. */
  152. request(aws4.sign({service: 'autoscaling', path: '/?Action=DescribeAutoScalingInstances&Version=2011-01-01'}))
  153. /*
  154. <DescribeAutoScalingInstancesResponse xmlns="http://autoscaling.amazonaws.com/doc/2011-01-01/">
  155. ...
  156. */
  157. request(aws4.sign({service: 'elasticloadbalancing', path: '/?Action=DescribeLoadBalancers&Version=2012-06-01'}))
  158. /*
  159. <DescribeLoadBalancersResponse xmlns="http://elasticloadbalancing.amazonaws.com/doc/2012-06-01/">
  160. ...
  161. */
  162. request(aws4.sign({service: 'cloudformation', path: '/?Action=ListStacks&Version=2010-05-15'}))
  163. /*
  164. <ListStacksResponse xmlns="http://cloudformation.amazonaws.com/doc/2010-05-15/">
  165. ...
  166. */
  167. request(aws4.sign({service: 'elasticbeanstalk', path: '/?Action=ListAvailableSolutionStacks&Version=2010-12-01'}))
  168. /*
  169. <ListAvailableSolutionStacksResponse xmlns="http://elasticbeanstalk.amazonaws.com/docs/2010-12-01/">
  170. ...
  171. */
  172. request(aws4.sign({service: 'rds', path: '/?Action=DescribeDBInstances&Version=2012-09-17'}))
  173. /*
  174. <DescribeDBInstancesResponse xmlns="http://rds.amazonaws.com/doc/2012-09-17/">
  175. ...
  176. */
  177. request(aws4.sign({service: 'monitoring', path: '/?Action=ListMetrics&Version=2010-08-01'}))
  178. /*
  179. <ListMetricsResponse xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">
  180. ...
  181. */
  182. request(aws4.sign({service: 'redshift', path: '/?Action=DescribeClusters&Version=2012-12-01'}))
  183. /*
  184. <DescribeClustersResponse xmlns="http://redshift.amazonaws.com/doc/2012-12-01/">
  185. ...
  186. */
  187. request(aws4.sign({service: 'cloudfront', path: '/2014-05-31/distribution'}))
  188. /*
  189. <DistributionList xmlns="http://cloudfront.amazonaws.com/doc/2014-05-31/">
  190. ...
  191. */
  192. request(aws4.sign({service: 'elasticache', path: '/?Action=DescribeCacheClusters&Version=2014-07-15'}))
  193. /*
  194. <DescribeCacheClustersResponse xmlns="http://elasticache.amazonaws.com/doc/2014-07-15/">
  195. ...
  196. */
  197. request(aws4.sign({service: 'elasticmapreduce', path: '/?Action=DescribeJobFlows&Version=2009-03-31'}))
  198. /*
  199. <DescribeJobFlowsResponse xmlns="http://elasticmapreduce.amazonaws.com/doc/2009-03-31">
  200. ...
  201. */
  202. request(aws4.sign({service: 'route53', path: '/2013-04-01/hostedzone'}))
  203. /*
  204. <ListHostedZonesResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
  205. ...
  206. */
  207. request(aws4.sign({service: 'appstream', path: '/applications'}))
  208. /*
  209. {"_links":{"curie":[{"href":"http://docs.aws.amazon.com/appstream/latest/...
  210. ...
  211. */
  212. request(aws4.sign({service: 'cognito-sync', path: '/identitypools'}))
  213. /*
  214. {"Count":0,"IdentityPoolUsages":[],"MaxResults":16,"NextToken":null}
  215. ...
  216. */
  217. request(aws4.sign({service: 'elastictranscoder', path: '/2012-09-25/pipelines'}))
  218. /*
  219. {"NextPageToken":null,"Pipelines":[]}
  220. ...
  221. */
  222. request(aws4.sign({service: 'lambda', path: '/2014-11-13/functions/'}))
  223. /*
  224. {"Functions":[],"NextMarker":null}
  225. ...
  226. */
  227. request(aws4.sign({service: 'ecs', path: '/?Action=ListClusters&Version=2014-11-13'}))
  228. /*
  229. <ListClustersResponse xmlns="http://ecs.amazonaws.com/doc/2014-11-13/">
  230. ...
  231. */
  232. request(aws4.sign({service: 'glacier', path: '/-/vaults', headers: {'X-Amz-Glacier-Version': '2012-06-01'}}))
  233. /*
  234. {"Marker":null,"VaultList":[]}
  235. ...
  236. */
  237. request(aws4.sign({service: 'storagegateway', body: '{}', headers: {
  238. 'Content-Type': 'application/x-amz-json-1.1',
  239. 'X-Amz-Target': 'StorageGateway_20120630.ListGateways'
  240. }}))
  241. /*
  242. {"Gateways":[]}
  243. ...
  244. */
  245. request(aws4.sign({service: 'datapipeline', body: '{}', headers: {
  246. 'Content-Type': 'application/x-amz-json-1.1',
  247. 'X-Amz-Target': 'DataPipeline.ListPipelines'
  248. }}))
  249. /*
  250. {"hasMoreResults":false,"pipelineIdList":[]}
  251. ...
  252. */
  253. request(aws4.sign({service: 'opsworks', body: '{}', headers: {
  254. 'Content-Type': 'application/x-amz-json-1.1',
  255. 'X-Amz-Target': 'OpsWorks_20130218.DescribeStacks'
  256. }}))
  257. /*
  258. {"Stacks":[]}
  259. ...
  260. */
  261. request(aws4.sign({service: 'route53domains', body: '{}', headers: {
  262. 'Content-Type': 'application/x-amz-json-1.1',
  263. 'X-Amz-Target': 'Route53Domains_v20140515.ListDomains'
  264. }}))
  265. /*
  266. {"Domains":[]}
  267. ...
  268. */
  269. request(aws4.sign({service: 'kinesis', body: '{}', headers: {
  270. 'Content-Type': 'application/x-amz-json-1.1',
  271. 'X-Amz-Target': 'Kinesis_20131202.ListStreams'
  272. }}))
  273. /*
  274. {"HasMoreStreams":false,"StreamNames":[]}
  275. ...
  276. */
  277. request(aws4.sign({service: 'cloudtrail', body: '{}', headers: {
  278. 'Content-Type': 'application/x-amz-json-1.1',
  279. 'X-Amz-Target': 'CloudTrail_20131101.DescribeTrails'
  280. }}))
  281. /*
  282. {"trailList":[]}
  283. ...
  284. */
  285. request(aws4.sign({service: 'logs', body: '{}', headers: {
  286. 'Content-Type': 'application/x-amz-json-1.1',
  287. 'X-Amz-Target': 'Logs_20140328.DescribeLogGroups'
  288. }}))
  289. /*
  290. {"logGroups":[]}
  291. ...
  292. */
  293. request(aws4.sign({service: 'codedeploy', body: '{}', headers: {
  294. 'Content-Type': 'application/x-amz-json-1.1',
  295. 'X-Amz-Target': 'CodeDeploy_20141006.ListApplications'
  296. }}))
  297. /*
  298. {"applications":[]}
  299. ...
  300. */
  301. request(aws4.sign({service: 'directconnect', body: '{}', headers: {
  302. 'Content-Type': 'application/x-amz-json-1.1',
  303. 'X-Amz-Target': 'OvertureService.DescribeConnections'
  304. }}))
  305. /*
  306. {"connections":[]}
  307. ...
  308. */
  309. request(aws4.sign({service: 'kms', body: '{}', headers: {
  310. 'Content-Type': 'application/x-amz-json-1.1',
  311. 'X-Amz-Target': 'TrentService.ListKeys'
  312. }}))
  313. /*
  314. {"Keys":[],"Truncated":false}
  315. ...
  316. */
  317. request(aws4.sign({service: 'config', body: '{}', headers: {
  318. 'Content-Type': 'application/x-amz-json-1.1',
  319. 'X-Amz-Target': 'StarlingDoveService.DescribeDeliveryChannels'
  320. }}))
  321. /*
  322. {"DeliveryChannels":[]}
  323. ...
  324. */
  325. request(aws4.sign({service: 'cloudhsm', body: '{}', headers: {
  326. 'Content-Type': 'application/x-amz-json-1.1',
  327. 'X-Amz-Target': 'CloudHsmFrontendService.ListAvailableZones'
  328. }}))
  329. /*
  330. {"AZList":["us-east-1a","us-east-1b","us-east-1c"]}
  331. ...
  332. */
  333. request(aws4.sign({
  334. service: 'swf',
  335. body: '{"registrationStatus":"REGISTERED"}',
  336. headers: {
  337. 'Content-Type': 'application/x-amz-json-1.0',
  338. 'X-Amz-Target': 'SimpleWorkflowService.ListDomains'
  339. }
  340. }))
  341. /*
  342. {"domainInfos":[]}
  343. ...
  344. */
  345. request(aws4.sign({
  346. service: 'cognito-identity',
  347. body: '{"MaxResults": 1}',
  348. headers: {
  349. 'Content-Type': 'application/x-amz-json-1.1',
  350. 'X-Amz-Target': 'AWSCognitoIdentityService.ListIdentityPools'
  351. }
  352. }))
  353. /*
  354. {"IdentityPools":[]}
  355. ...
  356. */
  357. request(aws4.sign({
  358. service: 'mobileanalytics',
  359. path: '/2014-06-05/events',
  360. body: JSON.stringify({events:[{
  361. eventType: 'a',
  362. timestamp: new Date().toISOString(),
  363. session: {},
  364. }]}),
  365. headers: {
  366. 'Content-Type': 'application/json',
  367. 'X-Amz-Client-Context': JSON.stringify({
  368. client: {client_id: 'a', app_title: 'a'},
  369. custom: {},
  370. env: {platform: 'a'},
  371. services: {},
  372. }),
  373. }
  374. }))
  375. /*
  376. (HTTP 202, empty response)
  377. */
  378. // Generate CodeCommit Git access password
  379. var signer = new aws4.RequestSigner({
  380. service: 'codecommit',
  381. host: 'git-codecommit.us-east-1.amazonaws.com',
  382. method: 'GIT',
  383. path: '/v1/repos/MyAwesomeRepo',
  384. })
  385. var password = signer.getDateTime() + 'Z' + signer.signature()
  386. ```
  387. API
  388. ---
  389. ### aws4.sign(requestOptions, [credentials])
  390. This calculates and populates the `Authorization` header of
  391. `requestOptions`, and any other necessary AWS headers and/or request
  392. options. Returns `requestOptions` as a convenience for chaining.
  393. `requestOptions` is an object holding the same options that the node.js
  394. [http.request](http://nodejs.org/docs/latest/api/http.html#http_http_request_options_callback)
  395. function takes.
  396. The following properties of `requestOptions` are used in the signing or
  397. populated if they don't already exist:
  398. - `hostname` or `host` (will be determined from `service` and `region` if not given)
  399. - `method` (will use `'GET'` if not given or `'POST'` if there is a `body`)
  400. - `path` (will use `'/'` if not given)
  401. - `body` (will use `''` if not given)
  402. - `service` (will be calculated from `hostname` or `host` if not given)
  403. - `region` (will be calculated from `hostname` or `host` or use `'us-east-1'` if not given)
  404. - `headers['Host']` (will use `hostname` or `host` or be calculated if not given)
  405. - `headers['Content-Type']` (will use `'application/x-www-form-urlencoded; charset=utf-8'`
  406. if not given and there is a `body`)
  407. - `headers['Date']` (used to calculate the signature date if given, otherwise `new Date` is used)
  408. Your AWS credentials (which can be found in your
  409. [AWS console](https://portal.aws.amazon.com/gp/aws/securityCredentials))
  410. can be specified in one of two ways:
  411. - As the second argument, like this:
  412. ```javascript
  413. aws4.sign(requestOptions, {
  414. secretAccessKey: "<your-secret-access-key>",
  415. accessKeyId: "<your-access-key-id>",
  416. sessionToken: "<your-session-token>"
  417. })
  418. ```
  419. - From `process.env`, such as this:
  420. ```
  421. export AWS_SECRET_ACCESS_KEY="<your-secret-access-key>"
  422. export AWS_ACCESS_KEY_ID="<your-access-key-id>"
  423. export AWS_SESSION_TOKEN="<your-session-token>"
  424. ```
  425. (will also use `AWS_ACCESS_KEY` and `AWS_SECRET_KEY` if available)
  426. The `sessionToken` property and `AWS_SESSION_TOKEN` environment variable are optional for signing
  427. with [IAM STS temporary credentials](http://docs.aws.amazon.com/STS/latest/UsingSTS/using-temp-creds.html).
  428. Installation
  429. ------------
  430. With [npm](http://npmjs.org/) do:
  431. ```
  432. npm install aws4
  433. ```
  434. Can also be used [in the browser](./browser).
  435. Thanks
  436. ------
  437. Thanks to [@jed](https://github.com/jed) for his
  438. [dynamo-client](https://github.com/jed/dynamo-client) lib where I first
  439. committed and subsequently extracted this code.
  440. Also thanks to the
  441. [official node.js AWS SDK](https://github.com/aws/aws-sdk-js) for giving
  442. me a start on implementing the v4 signature.