aws4.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. var aws4 = exports,
  2. url = require('url'),
  3. querystring = require('querystring'),
  4. crypto = require('crypto'),
  5. lru = require('./lru'),
  6. credentialsCache = lru(1000)
  7. // http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
  8. function hmac(key, string, encoding) {
  9. return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
  10. }
  11. function hash(string, encoding) {
  12. return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
  13. }
  14. // This function assumes the string has already been percent encoded
  15. function encodeRfc3986(urlEncodedString) {
  16. return urlEncodedString.replace(/[!'()*]/g, function(c) {
  17. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  18. })
  19. }
  20. // request: { path | body, [host], [method], [headers], [service], [region] }
  21. // credentials: { accessKeyId, secretAccessKey, [sessionToken] }
  22. function RequestSigner(request, credentials) {
  23. if (typeof request === 'string') request = url.parse(request)
  24. var headers = request.headers = (request.headers || {}),
  25. hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)
  26. this.request = request
  27. this.credentials = credentials || this.defaultCredentials()
  28. this.service = request.service || hostParts[0] || ''
  29. this.region = request.region || hostParts[1] || 'us-east-1'
  30. // SES uses a different domain from the service name
  31. if (this.service === 'email') this.service = 'ses'
  32. if (!request.method && request.body)
  33. request.method = 'POST'
  34. if (!headers.Host && !headers.host) {
  35. headers.Host = request.hostname || request.host || this.createHost()
  36. // If a port is specified explicitly, use it as is
  37. if (request.port)
  38. headers.Host += ':' + request.port
  39. }
  40. if (!request.hostname && !request.host)
  41. request.hostname = headers.Host || headers.host
  42. this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'
  43. }
  44. RequestSigner.prototype.matchHost = function(host) {
  45. var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/)
  46. var hostParts = (match || []).slice(1, 3)
  47. // ES's hostParts are sometimes the other way round, if the value that is expected
  48. // to be region equals ‘es’ switch them back
  49. // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
  50. if (hostParts[1] === 'es')
  51. hostParts = hostParts.reverse()
  52. return hostParts
  53. }
  54. // http://docs.aws.amazon.com/general/latest/gr/rande.html
  55. RequestSigner.prototype.isSingleRegion = function() {
  56. // Special case for S3 and SimpleDB in us-east-1
  57. if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
  58. return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
  59. .indexOf(this.service) >= 0
  60. }
  61. RequestSigner.prototype.createHost = function() {
  62. var region = this.isSingleRegion() ? '' :
  63. (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
  64. service = this.service === 'ses' ? 'email' : this.service
  65. return service + region + '.amazonaws.com'
  66. }
  67. RequestSigner.prototype.prepareRequest = function() {
  68. this.parsePath()
  69. var request = this.request, headers = request.headers, query
  70. if (request.signQuery) {
  71. this.parsedPath.query = query = this.parsedPath.query || {}
  72. if (this.credentials.sessionToken)
  73. query['X-Amz-Security-Token'] = this.credentials.sessionToken
  74. if (this.service === 's3' && !query['X-Amz-Expires'])
  75. query['X-Amz-Expires'] = 86400
  76. if (query['X-Amz-Date'])
  77. this.datetime = query['X-Amz-Date']
  78. else
  79. query['X-Amz-Date'] = this.getDateTime()
  80. query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
  81. query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
  82. query['X-Amz-SignedHeaders'] = this.signedHeaders()
  83. } else {
  84. if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {
  85. if (request.body && !headers['Content-Type'] && !headers['content-type'])
  86. headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
  87. if (request.body && !headers['Content-Length'] && !headers['content-length'])
  88. headers['Content-Length'] = Buffer.byteLength(request.body)
  89. if (this.credentials.sessionToken)
  90. headers['X-Amz-Security-Token'] = this.credentials.sessionToken
  91. if (this.service === 's3')
  92. headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
  93. if (headers['X-Amz-Date'])
  94. this.datetime = headers['X-Amz-Date']
  95. else
  96. headers['X-Amz-Date'] = this.getDateTime()
  97. }
  98. delete headers.Authorization
  99. delete headers.authorization
  100. }
  101. }
  102. RequestSigner.prototype.sign = function() {
  103. if (!this.parsedPath) this.prepareRequest()
  104. if (this.request.signQuery) {
  105. this.parsedPath.query['X-Amz-Signature'] = this.signature()
  106. } else {
  107. this.request.headers.Authorization = this.authHeader()
  108. }
  109. this.request.path = this.formatPath()
  110. return this.request
  111. }
  112. RequestSigner.prototype.getDateTime = function() {
  113. if (!this.datetime) {
  114. var headers = this.request.headers,
  115. date = new Date(headers.Date || headers.date || new Date)
  116. this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
  117. // Remove the trailing 'Z' on the timestamp string for CodeCommit git access
  118. if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1)
  119. }
  120. return this.datetime
  121. }
  122. RequestSigner.prototype.getDate = function() {
  123. return this.getDateTime().substr(0, 8)
  124. }
  125. RequestSigner.prototype.authHeader = function() {
  126. return [
  127. 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
  128. 'SignedHeaders=' + this.signedHeaders(),
  129. 'Signature=' + this.signature(),
  130. ].join(', ')
  131. }
  132. RequestSigner.prototype.signature = function() {
  133. var date = this.getDate(),
  134. cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
  135. kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
  136. if (!kCredentials) {
  137. kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
  138. kRegion = hmac(kDate, this.region)
  139. kService = hmac(kRegion, this.service)
  140. kCredentials = hmac(kService, 'aws4_request')
  141. credentialsCache.set(cacheKey, kCredentials)
  142. }
  143. return hmac(kCredentials, this.stringToSign(), 'hex')
  144. }
  145. RequestSigner.prototype.stringToSign = function() {
  146. return [
  147. 'AWS4-HMAC-SHA256',
  148. this.getDateTime(),
  149. this.credentialString(),
  150. hash(this.canonicalString(), 'hex'),
  151. ].join('\n')
  152. }
  153. RequestSigner.prototype.canonicalString = function() {
  154. if (!this.parsedPath) this.prepareRequest()
  155. var pathStr = this.parsedPath.path,
  156. query = this.parsedPath.query,
  157. queryStr = '',
  158. normalizePath = this.service !== 's3',
  159. decodePath = this.service === 's3' || this.request.doNotEncodePath,
  160. decodeSlashesInPath = this.service === 's3',
  161. firstValOnly = this.service === 's3',
  162. bodyHash = this.service === 's3' && this.request.signQuery ? 'UNSIGNED-PAYLOAD' :
  163. (this.isCodeCommitGit ? '' : hash(this.request.body || '', 'hex'))
  164. if (query) {
  165. queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
  166. if (!key) return obj
  167. obj[key] = !Array.isArray(query[key]) ? query[key] :
  168. (firstValOnly ? query[key][0] : query[key].slice().sort())
  169. return obj
  170. }, {})))
  171. }
  172. if (pathStr !== '/') {
  173. if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
  174. pathStr = pathStr.split('/').reduce(function(path, piece) {
  175. if (normalizePath && piece === '..') {
  176. path.pop()
  177. } else if (!normalizePath || piece !== '.') {
  178. if (decodePath) piece = querystring.unescape(piece)
  179. path.push(encodeRfc3986(querystring.escape(piece)))
  180. }
  181. return path
  182. }, []).join('/')
  183. if (pathStr[0] !== '/') pathStr = '/' + pathStr
  184. if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
  185. }
  186. return [
  187. this.request.method || 'GET',
  188. pathStr,
  189. queryStr,
  190. this.canonicalHeaders() + '\n',
  191. this.signedHeaders(),
  192. bodyHash,
  193. ].join('\n')
  194. }
  195. RequestSigner.prototype.canonicalHeaders = function() {
  196. var headers = this.request.headers
  197. function trimAll(header) {
  198. return header.toString().trim().replace(/\s+/g, ' ')
  199. }
  200. return Object.keys(headers)
  201. .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
  202. .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
  203. .join('\n')
  204. }
  205. RequestSigner.prototype.signedHeaders = function() {
  206. return Object.keys(this.request.headers)
  207. .map(function(key) { return key.toLowerCase() })
  208. .sort()
  209. .join(';')
  210. }
  211. RequestSigner.prototype.credentialString = function() {
  212. return [
  213. this.getDate(),
  214. this.region,
  215. this.service,
  216. 'aws4_request',
  217. ].join('/')
  218. }
  219. RequestSigner.prototype.defaultCredentials = function() {
  220. var env = process.env
  221. return {
  222. accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
  223. secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
  224. sessionToken: env.AWS_SESSION_TOKEN,
  225. }
  226. }
  227. RequestSigner.prototype.parsePath = function() {
  228. var path = this.request.path || '/',
  229. queryIx = path.indexOf('?'),
  230. query = null
  231. if (queryIx >= 0) {
  232. query = querystring.parse(path.slice(queryIx + 1))
  233. path = path.slice(0, queryIx)
  234. }
  235. // S3 doesn't always encode characters > 127 correctly and
  236. // all services don't encode characters > 255 correctly
  237. // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
  238. if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
  239. path = path.split('/').map(function(piece) {
  240. return querystring.escape(querystring.unescape(piece))
  241. }).join('/')
  242. }
  243. this.parsedPath = {
  244. path: path,
  245. query: query,
  246. }
  247. }
  248. RequestSigner.prototype.formatPath = function() {
  249. var path = this.parsedPath.path,
  250. query = this.parsedPath.query
  251. if (!query) return path
  252. // Services don't support empty query string keys
  253. if (query[''] != null) delete query['']
  254. return path + '?' + encodeRfc3986(querystring.stringify(query))
  255. }
  256. aws4.RequestSigner = RequestSigner
  257. aws4.sign = function(request, credentials) {
  258. return new RequestSigner(request, credentials).sign()
  259. }