UNPKG

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