aws4.js 11 KB

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