source: trip-planner-front/node_modules/aws4/aws4.js@ eed0bf8

Last change on this file since eed0bf8 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 11.9 KB
Line 
1var aws4 = exports,
2 url = require('url'),
3 querystring = require('querystring'),
4 crypto = require('crypto'),
5 lru = require('./lru'),
6 credentialsCache = lru(1000)
7
8// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
9
10function hmac(key, string, encoding) {
11 return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
12}
13
14function hash(string, encoding) {
15 return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
16}
17
18// This function assumes the string has already been percent encoded
19function encodeRfc3986(urlEncodedString) {
20 return urlEncodedString.replace(/[!'()*]/g, function(c) {
21 return '%' + c.charCodeAt(0).toString(16).toUpperCase()
22 })
23}
24
25function encodeRfc3986Full(str) {
26 return encodeRfc3986(encodeURIComponent(str))
27}
28
29// A bit of a combination of:
30// https://github.com/aws/aws-sdk-java-v2/blob/dc695de6ab49ad03934e1b02e7263abbd2354be0/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java#L59
31// https://github.com/aws/aws-sdk-js/blob/18cb7e5b463b46239f9fdd4a65e2ff8c81831e8f/lib/signers/v4.js#L191-L199
32// https://github.com/mhart/aws4fetch/blob/b3aed16b6f17384cf36ea33bcba3c1e9f3bdfefd/src/main.js#L25-L34
33var HEADERS_TO_IGNORE = {
34 'authorization': true,
35 'connection': true,
36 'x-amzn-trace-id': true,
37 'user-agent': true,
38 'expect': true,
39 'presigned-expires': true,
40 'range': true,
41}
42
43// request: { path | body, [host], [method], [headers], [service], [region] }
44// credentials: { accessKeyId, secretAccessKey, [sessionToken] }
45function RequestSigner(request, credentials) {
46
47 if (typeof request === 'string') request = url.parse(request)
48
49 var headers = request.headers = (request.headers || {}),
50 hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host)
51
52 this.request = request
53 this.credentials = credentials || this.defaultCredentials()
54
55 this.service = request.service || hostParts[0] || ''
56 this.region = request.region || hostParts[1] || 'us-east-1'
57
58 // SES uses a different domain from the service name
59 if (this.service === 'email') this.service = 'ses'
60
61 if (!request.method && request.body)
62 request.method = 'POST'
63
64 if (!headers.Host && !headers.host) {
65 headers.Host = request.hostname || request.host || this.createHost()
66
67 // If a port is specified explicitly, use it as is
68 if (request.port)
69 headers.Host += ':' + request.port
70 }
71 if (!request.hostname && !request.host)
72 request.hostname = headers.Host || headers.host
73
74 this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'
75}
76
77RequestSigner.prototype.matchHost = function(host) {
78 var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)
79 var hostParts = (match || []).slice(1, 3)
80
81 // ES's hostParts are sometimes the other way round, if the value that is expected
82 // to be region equals ‘es’ switch them back
83 // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
84 if (hostParts[1] === 'es')
85 hostParts = hostParts.reverse()
86
87 if (hostParts[1] == 's3') {
88 hostParts[0] = 's3'
89 hostParts[1] = 'us-east-1'
90 } else {
91 for (var i = 0; i < 2; i++) {
92 if (/^s3-/.test(hostParts[i])) {
93 hostParts[1] = hostParts[i].slice(3)
94 hostParts[0] = 's3'
95 break
96 }
97 }
98 }
99
100 return hostParts
101}
102
103// http://docs.aws.amazon.com/general/latest/gr/rande.html
104RequestSigner.prototype.isSingleRegion = function() {
105 // Special case for S3 and SimpleDB in us-east-1
106 if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
107
108 return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
109 .indexOf(this.service) >= 0
110}
111
112RequestSigner.prototype.createHost = function() {
113 var region = this.isSingleRegion() ? '' : '.' + this.region,
114 subdomain = this.service === 'ses' ? 'email' : this.service
115 return subdomain + region + '.amazonaws.com'
116}
117
118RequestSigner.prototype.prepareRequest = function() {
119 this.parsePath()
120
121 var request = this.request, headers = request.headers, query
122
123 if (request.signQuery) {
124
125 this.parsedPath.query = query = this.parsedPath.query || {}
126
127 if (this.credentials.sessionToken)
128 query['X-Amz-Security-Token'] = this.credentials.sessionToken
129
130 if (this.service === 's3' && !query['X-Amz-Expires'])
131 query['X-Amz-Expires'] = 86400
132
133 if (query['X-Amz-Date'])
134 this.datetime = query['X-Amz-Date']
135 else
136 query['X-Amz-Date'] = this.getDateTime()
137
138 query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
139 query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
140 query['X-Amz-SignedHeaders'] = this.signedHeaders()
141
142 } else {
143
144 if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {
145 if (request.body && !headers['Content-Type'] && !headers['content-type'])
146 headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
147
148 if (request.body && !headers['Content-Length'] && !headers['content-length'])
149 headers['Content-Length'] = Buffer.byteLength(request.body)
150
151 if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])
152 headers['X-Amz-Security-Token'] = this.credentials.sessionToken
153
154 if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])
155 headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
156
157 if (headers['X-Amz-Date'] || headers['x-amz-date'])
158 this.datetime = headers['X-Amz-Date'] || headers['x-amz-date']
159 else
160 headers['X-Amz-Date'] = this.getDateTime()
161 }
162
163 delete headers.Authorization
164 delete headers.authorization
165 }
166}
167
168RequestSigner.prototype.sign = function() {
169 if (!this.parsedPath) this.prepareRequest()
170
171 if (this.request.signQuery) {
172 this.parsedPath.query['X-Amz-Signature'] = this.signature()
173 } else {
174 this.request.headers.Authorization = this.authHeader()
175 }
176
177 this.request.path = this.formatPath()
178
179 return this.request
180}
181
182RequestSigner.prototype.getDateTime = function() {
183 if (!this.datetime) {
184 var headers = this.request.headers,
185 date = new Date(headers.Date || headers.date || new Date)
186
187 this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
188
189 // Remove the trailing 'Z' on the timestamp string for CodeCommit git access
190 if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1)
191 }
192 return this.datetime
193}
194
195RequestSigner.prototype.getDate = function() {
196 return this.getDateTime().substr(0, 8)
197}
198
199RequestSigner.prototype.authHeader = function() {
200 return [
201 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
202 'SignedHeaders=' + this.signedHeaders(),
203 'Signature=' + this.signature(),
204 ].join(', ')
205}
206
207RequestSigner.prototype.signature = function() {
208 var date = this.getDate(),
209 cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
210 kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
211 if (!kCredentials) {
212 kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
213 kRegion = hmac(kDate, this.region)
214 kService = hmac(kRegion, this.service)
215 kCredentials = hmac(kService, 'aws4_request')
216 credentialsCache.set(cacheKey, kCredentials)
217 }
218 return hmac(kCredentials, this.stringToSign(), 'hex')
219}
220
221RequestSigner.prototype.stringToSign = function() {
222 return [
223 'AWS4-HMAC-SHA256',
224 this.getDateTime(),
225 this.credentialString(),
226 hash(this.canonicalString(), 'hex'),
227 ].join('\n')
228}
229
230RequestSigner.prototype.canonicalString = function() {
231 if (!this.parsedPath) this.prepareRequest()
232
233 var pathStr = this.parsedPath.path,
234 query = this.parsedPath.query,
235 headers = this.request.headers,
236 queryStr = '',
237 normalizePath = this.service !== 's3',
238 decodePath = this.service === 's3' || this.request.doNotEncodePath,
239 decodeSlashesInPath = this.service === 's3',
240 firstValOnly = this.service === 's3',
241 bodyHash
242
243 if (this.service === 's3' && this.request.signQuery) {
244 bodyHash = 'UNSIGNED-PAYLOAD'
245 } else if (this.isCodeCommitGit) {
246 bodyHash = ''
247 } else {
248 bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||
249 hash(this.request.body || '', 'hex')
250 }
251
252 if (query) {
253 var reducedQuery = Object.keys(query).reduce(function(obj, key) {
254 if (!key) return obj
255 obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] :
256 (firstValOnly ? query[key][0] : query[key])
257 return obj
258 }, {})
259 var encodedQueryPieces = []
260 Object.keys(reducedQuery).sort().forEach(function(key) {
261 if (!Array.isArray(reducedQuery[key])) {
262 encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key]))
263 } else {
264 reducedQuery[key].map(encodeRfc3986Full).sort()
265 .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) })
266 }
267 })
268 queryStr = encodedQueryPieces.join('&')
269 }
270 if (pathStr !== '/') {
271 if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
272 pathStr = pathStr.split('/').reduce(function(path, piece) {
273 if (normalizePath && piece === '..') {
274 path.pop()
275 } else if (!normalizePath || piece !== '.') {
276 if (decodePath) piece = decodeURIComponent(piece.replace(/\+/g, ' '))
277 path.push(encodeRfc3986Full(piece))
278 }
279 return path
280 }, []).join('/')
281 if (pathStr[0] !== '/') pathStr = '/' + pathStr
282 if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
283 }
284
285 return [
286 this.request.method || 'GET',
287 pathStr,
288 queryStr,
289 this.canonicalHeaders() + '\n',
290 this.signedHeaders(),
291 bodyHash,
292 ].join('\n')
293}
294
295RequestSigner.prototype.canonicalHeaders = function() {
296 var headers = this.request.headers
297 function trimAll(header) {
298 return header.toString().trim().replace(/\s+/g, ' ')
299 }
300 return Object.keys(headers)
301 .filter(function(key) { return HEADERS_TO_IGNORE[key.toLowerCase()] == null })
302 .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
303 .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
304 .join('\n')
305}
306
307RequestSigner.prototype.signedHeaders = function() {
308 return Object.keys(this.request.headers)
309 .map(function(key) { return key.toLowerCase() })
310 .filter(function(key) { return HEADERS_TO_IGNORE[key] == null })
311 .sort()
312 .join(';')
313}
314
315RequestSigner.prototype.credentialString = function() {
316 return [
317 this.getDate(),
318 this.region,
319 this.service,
320 'aws4_request',
321 ].join('/')
322}
323
324RequestSigner.prototype.defaultCredentials = function() {
325 var env = process.env
326 return {
327 accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
328 secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
329 sessionToken: env.AWS_SESSION_TOKEN,
330 }
331}
332
333RequestSigner.prototype.parsePath = function() {
334 var path = this.request.path || '/'
335
336 // S3 doesn't always encode characters > 127 correctly and
337 // all services don't encode characters > 255 correctly
338 // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
339 if (/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(path)) {
340 path = encodeURI(decodeURI(path))
341 }
342
343 var queryIx = path.indexOf('?'),
344 query = null
345
346 if (queryIx >= 0) {
347 query = querystring.parse(path.slice(queryIx + 1))
348 path = path.slice(0, queryIx)
349 }
350
351 this.parsedPath = {
352 path: path,
353 query: query,
354 }
355}
356
357RequestSigner.prototype.formatPath = function() {
358 var path = this.parsedPath.path,
359 query = this.parsedPath.query
360
361 if (!query) return path
362
363 // Services don't support empty query string keys
364 if (query[''] != null) delete query['']
365
366 return path + '?' + encodeRfc3986(querystring.stringify(query))
367}
368
369aws4.RequestSigner = RequestSigner
370
371aws4.sign = function(request, credentials) {
372 return new RequestSigner(request, credentials).sign()
373}
Note: See TracBrowser for help on using the repository browser.