3 querystring = require('querystring'),
4 crypto = require('crypto'),
5 lru = require('./lru'),
6 credentialsCache = lru(1000)
8 // http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
10 function hmac(key, string, encoding) {
11 return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
14 function hash(string, encoding) {
15 return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
18 // This function assumes the string has already been percent encoded
19 function encodeRfc3986(urlEncodedString) {
20 return urlEncodedString.replace(/[!'()*]/g, function(c) {
21 return '%' + c.charCodeAt(0).toString(16).toUpperCase()
25 // request: { path | body, [host], [method], [headers], [service], [region] }
26 // credentials: { accessKeyId, secretAccessKey, [sessionToken] }
27 function RequestSigner(request, credentials) {
29 if (typeof request === 'string') request = url.parse(request)
31 var headers = request.headers = (request.headers || {}),
32 hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)
34 this.request = request
35 this.credentials = credentials || this.defaultCredentials()
37 this.service = request.service || hostParts[0] || ''
38 this.region = request.region || hostParts[1] || 'us-east-1'
40 // SES uses a different domain from the service name
41 if (this.service === 'email') this.service = 'ses'
43 if (!request.method && request.body)
44 request.method = 'POST'
46 if (!headers.Host && !headers.host) {
47 headers.Host = request.hostname || request.host || this.createHost()
49 // If a port is specified explicitly, use it as is
51 headers.Host += ':' + request.port
53 if (!request.hostname && !request.host)
54 request.hostname = headers.Host || headers.host
57 RequestSigner.prototype.matchHost = function(host) {
58 var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/)
59 var hostParts = (match || []).slice(1, 3)
61 // ES's hostParts are sometimes the other way round, if the value that is expected
62 // to be region equals ‘es’ switch them back
63 // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
64 if (hostParts[1] === 'es')
65 hostParts = hostParts.reverse()
70 // http://docs.aws.amazon.com/general/latest/gr/rande.html
71 RequestSigner.prototype.isSingleRegion = function() {
72 // Special case for S3 and SimpleDB in us-east-1
73 if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
75 return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
76 .indexOf(this.service) >= 0
79 RequestSigner.prototype.createHost = function() {
80 var region = this.isSingleRegion() ? '' :
81 (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
82 service = this.service === 'ses' ? 'email' : this.service
83 return service + region + '.amazonaws.com'
86 RequestSigner.prototype.prepareRequest = function() {
89 var request = this.request, headers = request.headers, query
91 if (request.signQuery) {
93 this.parsedPath.query = query = this.parsedPath.query || {}
95 if (this.credentials.sessionToken)
96 query['X-Amz-Security-Token'] = this.credentials.sessionToken
98 if (this.service === 's3' && !query['X-Amz-Expires'])
99 query['X-Amz-Expires'] = 86400
101 if (query['X-Amz-Date'])
102 this.datetime = query['X-Amz-Date']
104 query['X-Amz-Date'] = this.getDateTime()
106 query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
107 query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
108 query['X-Amz-SignedHeaders'] = this.signedHeaders()
112 if (!request.doNotModifyHeaders) {
113 if (request.body && !headers['Content-Type'] && !headers['content-type'])
114 headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
116 if (request.body && !headers['Content-Length'] && !headers['content-length'])
117 headers['Content-Length'] = Buffer.byteLength(request.body)
119 if (this.credentials.sessionToken)
120 headers['X-Amz-Security-Token'] = this.credentials.sessionToken
122 if (this.service === 's3')
123 headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
125 if (headers['X-Amz-Date'])
126 this.datetime = headers['X-Amz-Date']
128 headers['X-Amz-Date'] = this.getDateTime()
131 delete headers.Authorization
132 delete headers.authorization
136 RequestSigner.prototype.sign = function() {
137 if (!this.parsedPath) this.prepareRequest()
139 if (this.request.signQuery) {
140 this.parsedPath.query['X-Amz-Signature'] = this.signature()
142 this.request.headers.Authorization = this.authHeader()
145 this.request.path = this.formatPath()
150 RequestSigner.prototype.getDateTime = function() {
151 if (!this.datetime) {
152 var headers = this.request.headers,
153 date = new Date(headers.Date || headers.date || new Date)
155 this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
160 RequestSigner.prototype.getDate = function() {
161 return this.getDateTime().substr(0, 8)
164 RequestSigner.prototype.authHeader = function() {
166 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
167 'SignedHeaders=' + this.signedHeaders(),
168 'Signature=' + this.signature(),
172 RequestSigner.prototype.signature = function() {
173 var date = this.getDate(),
174 cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
175 kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
177 kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
178 kRegion = hmac(kDate, this.region)
179 kService = hmac(kRegion, this.service)
180 kCredentials = hmac(kService, 'aws4_request')
181 credentialsCache.set(cacheKey, kCredentials)
183 return hmac(kCredentials, this.stringToSign(), 'hex')
186 RequestSigner.prototype.stringToSign = function() {
190 this.credentialString(),
191 hash(this.canonicalString(), 'hex'),
195 RequestSigner.prototype.canonicalString = function() {
196 if (!this.parsedPath) this.prepareRequest()
198 var pathStr = this.parsedPath.path,
199 query = this.parsedPath.query,
201 normalizePath = this.service !== 's3',
202 decodePath = this.service === 's3' || this.request.doNotEncodePath,
203 decodeSlashesInPath = this.service === 's3',
204 firstValOnly = this.service === 's3',
205 bodyHash = this.service === 's3' && this.request.signQuery ?
206 'UNSIGNED-PAYLOAD' : hash(this.request.body || '', 'hex')
209 queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
211 obj[key] = !Array.isArray(query[key]) ? query[key] :
212 (firstValOnly ? query[key][0] : query[key].slice().sort())
216 if (pathStr !== '/') {
217 if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
218 pathStr = pathStr.split('/').reduce(function(path, piece) {
219 if (normalizePath && piece === '..') {
221 } else if (!normalizePath || piece !== '.') {
222 if (decodePath) piece = querystring.unescape(piece)
223 path.push(encodeRfc3986(querystring.escape(piece)))
227 if (pathStr[0] !== '/') pathStr = '/' + pathStr
228 if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
232 this.request.method || 'GET',
235 this.canonicalHeaders() + '\n',
236 this.signedHeaders(),
241 RequestSigner.prototype.canonicalHeaders = function() {
242 var headers = this.request.headers
243 function trimAll(header) {
244 return header.toString().trim().replace(/\s+/g, ' ')
246 return Object.keys(headers)
247 .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
248 .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
252 RequestSigner.prototype.signedHeaders = function() {
253 return Object.keys(this.request.headers)
254 .map(function(key) { return key.toLowerCase() })
259 RequestSigner.prototype.credentialString = function() {
268 RequestSigner.prototype.defaultCredentials = function() {
269 var env = process.env
271 accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
272 secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
273 sessionToken: env.AWS_SESSION_TOKEN,
277 RequestSigner.prototype.parsePath = function() {
278 var path = this.request.path || '/',
279 queryIx = path.indexOf('?'),
283 query = querystring.parse(path.slice(queryIx + 1))
284 path = path.slice(0, queryIx)
287 // S3 doesn't always encode characters > 127 correctly and
288 // all services don't encode characters > 255 correctly
289 // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
290 if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
291 path = path.split('/').map(function(piece) {
292 return querystring.escape(querystring.unescape(piece))
302 RequestSigner.prototype.formatPath = function() {
303 var path = this.parsedPath.path,
304 query = this.parsedPath.query
306 if (!query) return path
308 // Services don't support empty query string keys
309 if (query[''] != null) delete query['']
311 return path + '?' + encodeRfc3986(querystring.stringify(query))
314 aws4.RequestSigner = RequestSigner
316 aws4.sign = function(request, credentials) {
317 return new RequestSigner(request, credentials).sign()