aws4.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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(\.cn)?$/)
  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 && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])
  90. headers['X-Amz-Security-Token'] = this.credentials.sessionToken
  91. if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])
  92. headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
  93. if (headers['X-Amz-Date'] || headers['x-amz-date'])
  94. this.datetime = headers['X-Amz-Date'] || 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. headers = this.request.headers,
  158. queryStr = '',
  159. normalizePath = this.service !== 's3',
  160. decodePath = this.service === 's3' || this.request.doNotEncodePath,
  161. decodeSlashesInPath = this.service === 's3',
  162. firstValOnly = this.service === 's3',
  163. bodyHash
  164. if (this.service === 's3' && this.request.signQuery) {
  165. bodyHash = 'UNSIGNED-PAYLOAD'
  166. } else if (this.isCodeCommitGit) {
  167. bodyHash = ''
  168. } else {
  169. bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||
  170. hash(this.request.body || '', 'hex')
  171. }
  172. if (query) {
  173. queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
  174. if (!key) return obj
  175. obj[key] = !Array.isArray(query[key]) ? query[key] :
  176. (firstValOnly ? query[key][0] : query[key].slice().sort())
  177. return obj
  178. }, {})))
  179. }
  180. if (pathStr !== '/') {
  181. if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
  182. pathStr = pathStr.split('/').reduce(function(path, piece) {
  183. if (normalizePath && piece === '..') {
  184. path.pop()
  185. } else if (!normalizePath || piece !== '.') {
  186. if (decodePath) piece = decodeURIComponent(piece)
  187. path.push(encodeRfc3986(encodeURIComponent(piece)))
  188. }
  189. return path
  190. }, []).join('/')
  191. if (pathStr[0] !== '/') pathStr = '/' + pathStr
  192. if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
  193. }
  194. return [
  195. this.request.method || 'GET',
  196. pathStr,
  197. queryStr,
  198. this.canonicalHeaders() + '\n',
  199. this.signedHeaders(),
  200. bodyHash,
  201. ].join('\n')
  202. }
  203. RequestSigner.prototype.canonicalHeaders = function() {
  204. var headers = this.request.headers
  205. function trimAll(header) {
  206. return header.toString().trim().replace(/\s+/g, ' ')
  207. }
  208. return Object.keys(headers)
  209. .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
  210. .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
  211. .join('\n')
  212. }
  213. RequestSigner.prototype.signedHeaders = function() {
  214. return Object.keys(this.request.headers)
  215. .map(function(key) { return key.toLowerCase() })
  216. .sort()
  217. .join(';')
  218. }
  219. RequestSigner.prototype.credentialString = function() {
  220. return [
  221. this.getDate(),
  222. this.region,
  223. this.service,
  224. 'aws4_request',
  225. ].join('/')
  226. }
  227. RequestSigner.prototype.defaultCredentials = function() {
  228. var env = process.env
  229. return {
  230. accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
  231. secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
  232. sessionToken: env.AWS_SESSION_TOKEN,
  233. }
  234. }
  235. RequestSigner.prototype.parsePath = function() {
  236. var path = this.request.path || '/',
  237. queryIx = path.indexOf('?'),
  238. query = null
  239. if (queryIx >= 0) {
  240. query = querystring.parse(path.slice(queryIx + 1))
  241. path = path.slice(0, queryIx)
  242. }
  243. // S3 doesn't always encode characters > 127 correctly and
  244. // all services don't encode characters > 255 correctly
  245. // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
  246. if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
  247. path = path.split('/').map(function(piece) {
  248. return encodeURIComponent(decodeURIComponent(piece))
  249. }).join('/')
  250. }
  251. this.parsedPath = {
  252. path: path,
  253. query: query,
  254. }
  255. }
  256. RequestSigner.prototype.formatPath = function() {
  257. var path = this.parsedPath.path,
  258. query = this.parsedPath.query
  259. if (!query) return path
  260. // Services don't support empty query string keys
  261. if (query[''] != null) delete query['']
  262. return path + '?' + encodeRfc3986(querystring.stringify(query))
  263. }
  264. aws4.RequestSigner = RequestSigner
  265. aws4.sign = function(request, credentials) {
  266. return new RequestSigner(request, credentials).sign()
  267. }