-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.js
187 lines (159 loc) · 5.13 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
const AWS = require('aws-sdk');
const co = require('co');
const url = require('url');
const http = require('http');
const options = require('optimist')
.argv;
const context = {};
const profile = process.env.AWS_PROFILE || options.profile || 'default';
var creds = {};
AWS.CredentialProviderChain.defaultProviders = [
() => { return new AWS.EnvironmentCredentials('AWS'); },
() => { return new AWS.EnvironmentCredentials('AMAZON'); },
() => { return new AWS.SharedIniFileCredentials({ profile: profile }); },
() => { return new AWS.EC2MetadataCredentials(); }
];
var execute = function(endpoint, region, path, headers, method, body) {
return new Promise((resolve, reject) => {
var req = new AWS.HttpRequest(endpoint);
if(options.quiet !== true) {
console.log('>>>', method, path);
}
req.method = method || 'GET';
req.path = path;
req.region = region;
req.body = body;
req.headers['presigned-expires'] = false;
req.headers.Host = endpoint.host;
var signer = new AWS.Signers.V4(req, 'es');
signer.addAuthorization(creds, new Date());
// Now we have signed the "headers", we add extra headers passing
// from the browser. We must strip any connection control, transport encoding
// incorrect Origin headers, and make sure we don't change the Host header from
// the one used for signing
var keys = Object.keys(headers)
for (var i = 0, len = keys.length; i < len; i++) {
if (keys[i] != "host" &&
keys[i] != "accept-encoding" &&
keys[i] != "connection" &&
keys[i] != "origin") {
req.headers[keys[i]] = headers[keys[i]];
}
}
var client = new AWS.NodeHttpClient();
client.handleRequest(req, null, (httpResp) => {
var body = '';
httpResp.on('data', (chunk) => {
body += chunk;
});
httpResp.on('end', (chunk) => {
resolve({
statusCode: httpResp.statusCode,
headers: httpResp.headers,
body: body
});
});
}, (err) => {
console.log('Error: ' + err);
reject(err);
});
});
};
var readBody = function(request) {
return new Promise(resolve => {
var body = [];
request.on('data', chunk => {
body.push(chunk);
});
request.on('end', _ => {
resolve(Buffer.concat(body).toString());
});
});
};
var requestHandler = function(request, response) {
var body = [];
request.on('data', chunk => {
body.push(chunk);
});
request.on('end', _ => {
var buf = Buffer.concat(body).toString();
co(function*(){
return yield execute(context.endpoint, context.region, request.url, request.headers, request.method, buf);
})
.then(resp => {
// We need to pass through the response headers from the origin
// back to the UA, but strip any connection control and content encoding
// headers
var headers = {}
var keys = Object.keys(resp.headers);
for (var i = 0, klen = keys.length; i < klen; i++) {
var k = keys[i];
if (k != undefined && k != "connection" && k != "content-encoding") {
headers[k] = resp.headers[keys[i]];
}
}
response.writeHead(resp.statusCode, headers);
response.end(resp.body);
})
.catch(err => {
console.log('Unexpected error:', err.message);
console.log(err.stack);
response.writeHead(500, { 'Content-Type': 'application/json' });
response.end(err);
});
});
};
var server = http.createServer(requestHandler);
var startServer = function() {
return new Promise((resolve) => {
server.listen(context.port, function(){
console.log('Listening on', context.port);
resolve();
});
});
};
var main = function() {
co(function*(){
var maybeUrl = options._[0];
context.region = options.region || 'eu-west-1';
context.port = options.port || 9200;
if(!maybeUrl || (maybeUrl && maybeUrl == 'help') || options.help || options.h) {
console.log('Usage: aws-es-proxy [options] <url>');
console.log();
console.log('Options:');
console.log("\t--profile \tAWS profile \t(Default: default)");
console.log("\t--region \tAWS region \t(Default: eu-west-1)");
console.log("\t--port \tLocal port \t(Default: 9200)");
console.log("\t--quiet \tLog less");
process.exit(1);
}
if(maybeUrl && maybeUrl.indexOf('http') === 0) {
var uri = url.parse(maybeUrl);
context.endpoint = new AWS.Endpoint(uri.host);
}
var chain = new AWS.CredentialProviderChain();
yield chain.resolvePromise()
.then(function (credentials) {
creds = credentials;
})
.catch(function (err) {
console.log('Error while getting AWS Credentials.')
console.log(err);
process.exit(1);
});
yield startServer();
})
.then(res => {
// start service
console.log('Service started!');
})
.catch(err => {
console.error('Error:', err.message);
console.log(err.stack);
process.exit(1);
});
};
if(!module.parent) {
main();
}
module.exports = main;