-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
366 lines (294 loc) · 10.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
var fs = require('fs')
var path = require('path')
var http = require('http')
var env = process.env
var TIMEOUT_CODES = ['ECONNRESET', 'ETIMEDOUT', 'EHOSTUNREACH', 'Unknown system errno 64']
var httpCallbacks = []
exports.credentialsCallChain = [
loadCredentialsFromEnv,
loadCredentialsFromIniFile,
loadCredentialsFromHttp,
]
exports.regionCallChain = [
loadRegionFromEnv,
loadRegionFromIniFile,
]
exports.load = exports.loadCredentialsAndRegion = loadCredentialsAndRegion
exports.loadCredentials = loadCredentials
exports.loadRegion = loadRegion
exports.loadRegionSync = loadRegionSync
exports.loadCredentialsFromEnv = loadCredentialsFromEnv
exports.loadRegionFromEnv = loadRegionFromEnv
exports.loadRegionFromEnvSync = loadRegionFromEnvSync
exports.loadCredentialsFromIniFile = loadCredentialsFromIniFile
exports.loadRegionFromIniFile = loadRegionFromIniFile
exports.loadRegionFromIniFileSync = loadRegionFromIniFileSync
exports.loadCredentialsFromHttp = loadCredentialsFromHttp
exports.loadCredentialsFromEc2Metadata = loadCredentialsFromEc2Metadata
exports.loadCredentialsFromEcs = loadCredentialsFromEcs
exports.loadProfileFromIniFile = loadProfileFromIniFile
exports.loadProfileFromIniFileSync = loadProfileFromIniFileSync
exports.merge = merge
function loadCredentialsAndRegion(options, cb) {
if (!cb) { cb = options; options = {} }
cb = once(cb)
var out = {}
var callsRemaining = 2
function checkDone(propName) {
return function(err, data) {
if (err) return cb(err)
out[propName] = data
if (!--callsRemaining) return cb(null, out)
}
}
loadCredentials(options, checkDone('credentials'))
loadRegion(options, checkDone('region'))
}
function loadCredentials(options, cb) {
if (!cb) { cb = options; options = {} }
var credentialsCallChain = options.credentialsCallChain || exports.credentialsCallChain
function nextCall(i) {
credentialsCallChain[i](options, function(err, credentials) {
if (err) return cb(err)
if (credentials.accessKeyId && credentials.secretAccessKey) {
return cb(null, credentials)
}
if (i >= credentialsCallChain.length - 1) {
return cb(null, {})
}
nextCall(i + 1)
})
}
nextCall(0)
}
function loadRegion(options, cb) {
if (!cb) { cb = options; options = {} }
var regionCallChain = options.regionCallChain || exports.regionCallChain
function nextCall(i) {
regionCallChain[i](options, function(err, region) {
if (err) return cb(err)
if (region) {
return cb(null, region)
}
if (i >= regionCallChain.length - 1) {
return cb(null, 'us-east-1')
}
nextCall(i + 1)
})
}
nextCall(0)
}
function loadRegionSync(options) {
return loadRegionFromEnvSync(options) || loadRegionFromIniFileSync(options)
}
function loadCredentialsFromEnv(options, cb) {
if (!cb) { cb = options; options = {} }
cb(null, {
accessKeyId: env.AWS_ACCESS_KEY_ID || env.AMAZON_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AMAZON_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
sessionToken: env.AWS_SESSION_TOKEN || env.AMAZON_SESSION_TOKEN,
})
}
function loadRegionFromEnv(options, cb) {
if (!cb) { cb = options; options = {} }
cb(null, loadRegionFromEnvSync())
}
function loadRegionFromEnvSync() {
return env.AWS_REGION || env.AMAZON_REGION || env.AWS_DEFAULT_REGION
}
function loadCredentialsFromIniFile(options, cb) {
if (!cb) { cb = options; options = {} }
loadProfileFromIniFile(options, 'credentials', function(err, profile) {
if (err) return cb(err)
if (profile.aws_access_key_id) {
return cb(null, {
accessKeyId: profile.aws_access_key_id,
secretAccessKey: profile.aws_secret_access_key,
sessionToken: profile.aws_session_token,
})
}
loadProfileFromIniFile(options, 'config', function(err, profile) {
if (err) return cb(err)
cb(null, {
accessKeyId: profile.aws_access_key_id,
secretAccessKey: profile.aws_secret_access_key,
sessionToken: profile.aws_session_token,
})
})
})
}
function loadRegionFromIniFile(options, cb) {
if (!cb) { cb = options; options = {} }
loadProfileFromIniFile(options, 'credentials', function(err, profile) {
if (err) return cb(err)
if (profile.region) return cb(null, profile.region)
loadProfileFromIniFile(options, 'config', function(err, profile) {
if (err) return cb(err)
cb(null, profile.region)
})
})
}
function loadRegionFromIniFileSync(options) {
return loadProfileFromIniFileSync(options || {}, 'credentials').region ||
loadProfileFromIniFileSync(options || {}, 'config').region
}
function loadCredentialsFromHttp(options, cb) {
return process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI ?
loadCredentialsFromEcs(options, cb) : loadCredentialsFromEc2Metadata(options, cb)
}
function loadCredentialsFromEc2Metadata(options, cb) {
if (!cb) { cb = options; options = {} }
options.host = '169.254.169.254'
options.resolvePath = function(options, cb) {
options.path = '/latest/meta-data/iam/security-credentials/'
request(options, function(err, res, data) {
if (err) return cb(err)
if (res.statusCode === 404) {
return cb(new Error('Could not find IAM role. Check that you assigned an IAM role to your EC2 instance'))
}
if (res.statusCode !== 200) {
return cb(new Error('Failed to fetch IAM role: ' + res.statusCode + ' ' + data))
}
cb(null, options.path + data.split('\n')[0])
})
}
requestCredentials(options, cb)
}
function loadCredentialsFromEcs(options, cb) {
if (!cb) { cb = options; options = {} }
options.host = '169.254.170.2'
options.resolvePath = function(options, cb) {
cb(null, process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI)
}
requestCredentials(options, cb)
}
function requestCredentials(options, cb) {
httpCallbacks.push(cb)
if (httpCallbacks.length > 1) return // only want one caller at a time
cb = function(err, credentials) {
httpCallbacks.forEach(function(cb) { cb(err, credentials) })
httpCallbacks = []
}
if (options.timeout == null) options.timeout = 5000
options.resolvePath(options, function(err, path) {
if (err && ~TIMEOUT_CODES.indexOf(err.code)) return cb(null, {})
if (err) return cb(err)
options.path = path
request(options, function(err, res, data) {
if (err && ~TIMEOUT_CODES.indexOf(err.code)) return cb(null, {})
if (err) return cb(err)
if (res.statusCode !== 200) {
return cb(new Error('Failed to fetch IAM credentials: ' + res.statusCode + ' ' + data))
}
try { data = JSON.parse(data) } catch (e) { }
if (!data.AccessKeyId) {
return cb(new Error('Failed to fetch IAM credentials: ' + JSON.stringify(data)))
}
cb(null, {
accessKeyId: data.AccessKeyId,
secretAccessKey: data.SecretAccessKey,
sessionToken: data.Token,
expiration: new Date(data.Expiration),
})
})
})
}
function loadProfileFromIniFile(options, defaultFilename, cb) {
var filename = options.filename || path.join(resolveHome(), '.aws', defaultFilename)
var profile = options.profile || resolveProfile()
fs.readFile(filename, 'utf8', function(err, data) {
if (err && err.code === 'ENOENT') return cb(null, {})
if (err) return cb(err)
var parsedIni = parseAwsIni(data)
cb(null, parsedIni['profile ' + profile] || parsedIni[profile] || {})
})
}
function loadProfileFromIniFileSync(options, defaultFilename) {
var filename = options.filename || path.join(resolveHome(), '.aws', defaultFilename)
var profile = options.profile || resolveProfile()
var data
try {
data = fs.readFileSync(filename, 'utf8')
} catch (err) {
if (err.code === 'ENOENT') return {}
throw err
}
var parsedIni = parseAwsIni(data)
return parsedIni['profile ' + profile] || parsedIni[profile] || {}
}
function merge(obj, options, cb) {
if (!cb) { cb = options; options = {} }
var needRegion = !obj.region
var needCreds = !obj.credentials || !obj.credentials.accessKeyId || !obj.credentials.secretAccessKey
function loadCreds(cb) {
if (needRegion && needCreds) {
return loadCredentialsAndRegion(options, cb)
} else if (needRegion) {
return loadRegion(options, function(err, region) { cb(err, { region: region }) })
} else if (needCreds) {
return loadCredentials(options, function(err, credentials) { cb(err, { credentials: credentials }) })
}
cb(null, {})
}
loadCreds(function(err, creds) {
if (err) return cb(err)
if (creds.region) obj.region = creds.region
if (creds.credentials) {
if (!obj.credentials) {
obj.credentials = creds.credentials
} else {
Object.keys(creds.credentials).forEach(function(key) {
if (!obj.credentials[key]) obj.credentials[key] = creds.credentials[key]
})
}
}
cb()
})
}
function resolveProfile() {
return env.AWS_PROFILE || env.AMAZON_PROFILE || 'default'
}
function resolveHome() {
return env.HOME || env.USERPROFILE || ((env.HOMEDRIVE || 'C:') + env.HOMEPATH)
}
// Fairly strict INI parser – will only deal with alpha keys, must be within sections
function parseAwsIni(ini) {
var section
var out = Object.create(null)
var re = /^\[([^\]]+)\]\s*$|^([a-z_]+)\s*=\s*(.+?)\s*$/
var lines = ini.split(/\r?\n/)
lines.forEach(function(line) {
var match = line.match(re)
if (!match) return
if (match[1]) {
section = match[1]
if (out[section] == null) out[section] = Object.create(null)
} else if (section) {
out[section][match[2]] = match[3]
}
})
return out
}
function request(options, cb) {
cb = once(cb)
var req = http.request(options, function(res) {
var data = ''
res.setEncoding('utf8')
res.on('error', cb)
res.on('data', function(chunk) { data += chunk })
res.on('end', function() { cb(null, res, data) })
}).on('error', cb)
if (options.timeout != null) {
req.setTimeout(options.timeout)
req.on('timeout', function() { req.abort() })
}
req.end()
}
function once(cb) {
var called = false
return function() {
if (called) return
called = true
cb.apply(this, arguments)
}
}