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
56 this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'
59 RequestSigner.prototype.matchHost = function(host) {
60 var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/)
61 var hostParts = (match || []).slice(1, 3)
63 // ES's hostParts are sometimes the other way round, if the value that is expected
64 // to be region equals ‘es’ switch them back
65 // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
66 if (hostParts[1] === 'es')
67 hostParts = hostParts.reverse()
72 // http://docs.aws.amazon.com/general/latest/gr/rande.html
73 RequestSigner.prototype.isSingleRegion = function() {
74 // Special case for S3 and SimpleDB in us-east-1
75 if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
77 return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
78 .indexOf(this.service) >= 0
81 RequestSigner.prototype.createHost = function() {
82 var region = this.isSingleRegion() ? '' :
83 (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
84 service = this.service === 'ses' ? 'email' : this.service
85 return service + region + '.amazonaws.com'
88 RequestSigner.prototype.prepareRequest = function() {
91 var request = this.request, headers = request.headers, query
93 if (request.signQuery) {
95 this.parsedPath.query = query = this.parsedPath.query || {}
97 if (this.credentials.sessionToken)
98 query['X-Amz-Security-Token'] = this.credentials.sessionToken
100 if (this.service === 's3' && !query['X-Amz-Expires'])
101 query['X-Amz-Expires'] = 86400
103 if (query['X-Amz-Date'])
104 this.datetime = query['X-Amz-Date']
106 query['X-Amz-Date'] = this.getDateTime()
108 query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
109 query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
110 query['X-Amz-SignedHeaders'] = this.signedHeaders()
114 if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {
115 if (request.body && !headers['Content-Type'] && !headers['content-type'])
116 headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
118 if (request.body && !headers['Content-Length'] && !headers['content-length'])
119 headers['Content-Length'] = Buffer.byteLength(request.body)
121 if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])
122 headers['X-Amz-Security-Token'] = this.credentials.sessionToken
124 if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])
125 headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
127 if (headers['X-Amz-Date'] || headers['x-amz-date'])
128 this.datetime = headers['X-Amz-Date'] || headers['x-amz-date']
130 headers['X-Amz-Date'] = this.getDateTime()
133 delete headers.Authorization
134 delete headers.authorization
138 RequestSigner.prototype.sign = function() {
139 if (!this.parsedPath) this.prepareRequest()
141 if (this.request.signQuery) {
142 this.parsedPath.query['X-Amz-Signature'] = this.signature()
144 this.request.headers.Authorization = this.authHeader()
147 this.request.path = this.formatPath()
152 RequestSigner.prototype.getDateTime = function() {
153 if (!this.datetime) {
154 var headers = this.request.headers,
155 date = new Date(headers.Date || headers.date || new Date)
157 this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
159 // Remove the trailing 'Z' on the timestamp string for CodeCommit git access
160 if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1)
165 RequestSigner.prototype.getDate = function() {
166 return this.getDateTime().substr(0, 8)
169 RequestSigner.prototype.authHeader = function() {
171 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
172 'SignedHeaders=' + this.signedHeaders(),
173 'Signature=' + this.signature(),
177 RequestSigner.prototype.signature = function() {
178 var date = this.getDate(),
179 cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
180 kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
182 kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
183 kRegion = hmac(kDate, this.region)
184 kService = hmac(kRegion, this.service)
185 kCredentials = hmac(kService, 'aws4_request')
186 credentialsCache.set(cacheKey, kCredentials)
188 return hmac(kCredentials, this.stringToSign(), 'hex')
191 RequestSigner.prototype.stringToSign = function() {
195 this.credentialString(),
196 hash(this.canonicalString(), 'hex'),
200 RequestSigner.prototype.canonicalString = function() {
201 if (!this.parsedPath) this.prepareRequest()
203 var pathStr = this.parsedPath.path,
204 query = this.parsedPath.query,
205 headers = this.request.headers,
207 normalizePath = this.service !== 's3',
208 decodePath = this.service === 's3' || this.request.doNotEncodePath,
209 decodeSlashesInPath = this.service === 's3',
210 firstValOnly = this.service === 's3',
213 if (this.service === 's3' && this.request.signQuery) {
214 bodyHash = 'UNSIGNED-PAYLOAD'
215 } else if (this.isCodeCommitGit) {
218 bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||
219 hash(this.request.body || '', 'hex')
223 queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
225 obj[key] = !Array.isArray(query[key]) ? query[key] :
226 (firstValOnly ? query[key][0] : query[key].slice().sort())
230 if (pathStr !== '/') {
231 if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
232 pathStr = pathStr.split('/').reduce(function(path, piece) {
233 if (normalizePath && piece === '..') {
235 } else if (!normalizePath || piece !== '.') {
236 if (decodePath) piece = querystring.unescape(piece)
237 path.push(encodeRfc3986(querystring.escape(piece)))
241 if (pathStr[0] !== '/') pathStr = '/' + pathStr
242 if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
246 this.request.method || 'GET',
249 this.canonicalHeaders() + '\n',
250 this.signedHeaders(),
255 RequestSigner.prototype.canonicalHeaders = function() {
256 var headers = this.request.headers
257 function trimAll(header) {
258 return header.toString().trim().replace(/\s+/g, ' ')
260 return Object.keys(headers)
261 .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
262 .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
266 RequestSigner.prototype.signedHeaders = function() {
267 return Object.keys(this.request.headers)
268 .map(function(key) { return key.toLowerCase() })
273 RequestSigner.prototype.credentialString = function() {
282 RequestSigner.prototype.defaultCredentials = function() {
283 var env = process.env
285 accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
286 secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
287 sessionToken: env.AWS_SESSION_TOKEN,
291 RequestSigner.prototype.parsePath = function() {
292 var path = this.request.path || '/',
293 queryIx = path.indexOf('?'),
297 query = querystring.parse(path.slice(queryIx + 1))
298 path = path.slice(0, queryIx)
301 // S3 doesn't always encode characters > 127 correctly and
302 // all services don't encode characters > 255 correctly
303 // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
304 if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
305 path = path.split('/').map(function(piece) {
306 return querystring.escape(querystring.unescape(piece))
316 RequestSigner.prototype.formatPath = function() {
317 var path = this.parsedPath.path,
318 query = this.parsedPath.query
320 if (!query) return path
322 // Services don't support empty query string keys
323 if (query[''] != null) delete query['']
325 return path + '?' + encodeRfc3986(querystring.stringify(query))
328 aws4.RequestSigner = RequestSigner
330 aws4.sign = function(request, credentials) {
331 return new RequestSigner(request, credentials).sign()