-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
361 lines (321 loc) · 9.03 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
const express = require("express");
const bodyParser = require("body-parser");
const { createProxyMiddleware } = require("http-proxy-middleware");
const mysql = require("mysql");
const Pool = require("pg-pool");
const fs = require("fs");
// Create Express Server
const app = express();
const NodeCache = require("node-cache");
const { init } = require("express/lib/application");
// #region Initialization
const tokenCache = new NodeCache({
stdTTL: 1800, // 30 minutes
checkperiod: 300, // 5 minutes
maxKeys: 100,
deleteOnExpire: true,
});
const config = {
ALLOW_PUBLIC_ACCESS: process.env.ALLOW_PUBLIC_ACCESS || false,
TENANT_ID: process.env.TENANT_ID || "Default",
TENANT_NAME: process.env.TENANT_NAME || "Default",
TENANT_SLUG: process.env.TENANT_SLUG || "default",
LOG_LEVEL: process.env.LOG_LEVEL || "warn",
API_SERVICE_URL:
process.env.API_SERVICE_URL || "http://localhost:8080/graphql",
HOST: process.env.HOST || "0.0.0.0",
PORT: process.env.PORT || 3000,
LOG_LEVEL_OVERRIDE_DURATION: process.env.LOG_LEVEL_OVERRIDE_DURATION || 300,
ENV: process.env.ENV || "NA",
PERMITTED_ROUTES_FILE: process.env.PERMITTED_ROUTES_FILE || "./config/permitted-routes.json",
PERMITTED_ROUTES_JSON: process.env.PERMITTED_ROUTES_JSON || ""
};
if (fs.existsSync(config.PERMITTED_ROUTES_FILE)) {
if (config.PERMITTED_ROUTES_JSON) {
config.PERMITTED_ROUTES = JSON.parse(config.PERMITTED_ROUTES_JSON)
}
else {
config.PERMITTED_ROUTES = JSON.parse(fs.readFileSync(config.PERMITTED_ROUTES_FILE));
}
}
// #endregion
// #region LOGGING
// Setup Log Levels
const gLogFunc = console.log;
const gWarnFunc = console.warn;
function initLogLevels(level) {
console.debug = () => { };
console.trace = () => { };
console.info = () => { };
console.warn = () => { };
console.log = () => { };
if (level === "warn") {
console.log = () => { };
console.warn = gWarnFunc;
}
if (level === "error") {
console.log = () => { };
console.warn = () => { };
}
if (level === "info") {
console.log = gLogFunc;
console.warn = gWarnFunc;
}
gLogFunc("Log Level set to ", level);
}
initLogLevels(config.LOG_LEVEL);
gLogFunc("Service running with configuration:", config);
// #endregion
// #region Public Endpoints
// Public Endpoints
app.get("/healthcheck", (req, res, next) => {
res.send("All OK");
});
// Allow enabling verbose logging for debugging
app.post("/logs/:level", (req, res, next) => {
initLogLevels(req.params.level);
setTimeout(() => {
initLogLevels(config.LOG_LEVEL);
}, config.LOG_LEVEL_OVERRIDE_DURATION * 1000);
res.send(`Log Level Changed to ${req.params.level}`);
});
// Allow cache reset for testing
app.post("/cache/reset", (req, res, next) => {
tokenCache.flushAll();
res.send(`Cache Reset`);
});
app.delete("/cache/:key", (req, res, next) => {
tokenCache.del(req.params.key);
res.send(`Cache has been deleted for key: ${req.params.key}`);
});
// #endregion
// #region Utilities
let dbConn;
async function initDBConnection() {
return new Promise(async (resolve, reject) => {
try {
if (process.env.DB_TYPE === "mysql") {
dbConn = mysql.createPool({
connectionLimit: 5,
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
});
} else {
dbConn = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_DATABASE,
password: process.env.DB_PASSWORD,
port: 5432,
});
}
resolve(true);
} catch (err) {
console.log("Failure in creating DB connection pool:", err);
reject(err);
}
});
}
async function dbQuery(query, params) {
return new Promise(async (resolve, reject) => {
try {
dbConn.query(query, params, (error, results) => {
if (error) {
reject(error);
} else {
// console.log('dbQuery Results:', results);
resolve(results.rows ? results.rows : results);
}
});
} catch (err) {
console.log("Failure in query: ", err);
reject(err);
}
});
}
async function fetchAPIKeysInfo(key) {
return new Promise(async (resolve, reject) => {
try {
let query = "";
let params;
if (process.env.DB_TYPE === "mysql") {
params = [key];
query =
"SELECT * FROM prefect_api_keys WHERE api_key=? AND CURDATE() < key_expr_dt";
} else {
params = [key];
query =
"SELECT * FROM prefect_api_keys WHERE api_key=$1 AND CURRENT_TIMESTAMP < key_expr_dt";
}
dbConn.query(query, params, (error, results) => {
if (error) {
reject(error);
} else {
// console.log('dbQuery Results:', results);
resolve(results.rows ? results.rows : results);
}
});
} catch (err) {
console.log("Failure in query: ", err);
reject(err);
}
});
}
/**
*
* @param {String} url "Url to validate against route rules"
* @param {Array} routes "Allowed or Permitted routes to match against"
* @returns
*/
const checkRoutes = (url, routes) => {
if (!routes || !routes.length) {
return false;
}
regexRoutes = routes.map(route => route.replace(/\*/g, "[^ ]*"));
for (let i = 0; i < regexRoutes.length; i++) {
const match = url.match(regexRoutes[i]);
if (match) {
return true;
}
}
return false;
};
const allowPassthrough = (url, method, acl) => {
// check config for public access
if (config.ALLOW_PUBLIC_ACCESS) {
return true;
}
// check permitted routes
if (config.PERMITTED_ROUTES && config.PERMITTED_ROUTES[method]?.length && checkRoutes(url, config.PERMITTED_ROUTES[method])) {
return true;
}
// check acl
if (checkRoutes(url, acl?.ops)) {
return true;
}
return false;
};
// #endregion
// #region Middleware
// Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Auth Middleware
app.use(async (req, res, next) => {
let apiKey = null;
const authHeader = req.headers.authorization;
if (authHeader) {
apiKey = authHeader.split(" ")[1];
} else {
apiKey = req.get("x-prefect-user-id");
}
if (apiKey) {
req.apikey = apiKey;
let acl = tokenCache.get(apiKey);
if (!acl) {
// Fetch ACL from database and store in cache
const aclDB = await fetchAPIKeysInfo(apiKey);
if (aclDB && aclDB.length > 0) {
acl = aclDB[0];
acl.ops = acl.scopes.split(",").map((el) => el.trim());
console.log("ACL: ", acl);
tokenCache.set(apiKey, acl);
} else {
acl = {
user_id: "Anonymous",
ops: [],
};
}
}
console.log("ACL: ", acl);
req.acl = acl;
}
if (!allowPassthrough(req.url, req.method, req.acl)) {
console.warn(`AUTH-PROXY-AUDIT: ${req.url}`)
return res.status(401).send("Unauthorized");
} else {
next();
}
});
// #endregion
// #region Proxy Setup
app.use(
"/",
createProxyMiddleware({
target: config.API_SERVICE_URL,
changeOrigin: true,
logLevel: "error",
// pathRewrite: {
// [`^/graphql`]: "/graphql",
// },
onProxyRes: (proxyRes, req, res) => {
console.log("Response from API: ", proxyRes.statusCode);
console.log("Response Headers", proxyRes.headers);
var body = [];
proxyRes.on("data", function (chunk) {
body.push(chunk);
});
proxyRes.on("end", function () {
body = Buffer.concat(body).toString();
console.log("res from proxied server:", body);
// res.end("my response to cli");
});
},
onProxyReq: (proxyReq, req, res) => {
console.log("URL", req.url);
console.log("Headers:", req.headers);
console.log("Body:", req.body);
if (
req.url === "/" &&
req.body &&
req.body.query &&
req.body.query.includes("auth_info")
) {
res.json({
data: {
auth_info: { tenant_id: config.TENANT_ID },
},
});
} else if (
req.url === "/" &&
req.body &&
req.body.query &&
req.body.query.includes("tenant(where")
) {
res.json({
data: {
tenant: [
{
name: config.TENANT_NAME,
slug: config.TENANT_SLUG,
id: config.TENANT_ID,
},
],
},
});
} else {
// Proxy request to end point
const writeBody = (bodyData) => {
proxyReq.setHeader("Content-Length", Buffer.byteLength(bodyData));
if (config.LOG_LEVEL === "debug") {
proxyReq.removeHeader('Accept-Encoding')
}
proxyReq.write(bodyData);
};
if (req.body) {
writeBody(JSON.stringify(req.body));
}
}
},
})
);
// #endregion
// Start the Proxy
app.listen(config.PORT, config.HOST, async () => {
gLogFunc(`Starting Proxy at ${config.HOST}:${config.PORT}`);
if (!dbConn) {
await initDBConnection();
}
});