-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathindex.js
381 lines (334 loc) · 14 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
"use strict";
var debug = require("debug")("plugin:apikeys");
var url = require("url");
var rs = require("jsrsasign");
var fs = require("fs");
var path = require("path");
<<<<<<< HEAD
const memoredpath = path.resolve(__dirname,'../../..')+'/third_party/memored/memored';
=======
const memoredpath = '../third_party/memored/index';
>>>>>>> 7d0c3c0
var cache = require(memoredpath);
var JWS = rs.jws.JWS;
var requestLib = require("request");
var _ = require("lodash");
const PRIVATE_JWT_VALUES = ["application_name", "client_id", "api_product_list", "iat", "exp"];
const SUPPORTED_DOUBLE_ASTERIK_PATTERN = "**";
const SUPPORTED_SINGLE_ASTERIK_PATTERN = "*";
// const SUPPORTED_SINGLE_FORWARD_SLASH_PATTERN = "/"; // ?? this has yet to be used in any module.
const acceptAlg = ["RS256"];
var acceptField = {};
acceptField.alg = acceptAlg;
var productOnly;
var cacheKey = false;
var cacheKeyTTL = 60000; //set default cache TTL to 1 minute
var cacheSize = 100; //default cache size
module.exports.init = function(config, logger, stats) {
var request = config.request ? requestLib.defaults(config.request) : requestLib;
var keys = config.jwk_keys ? JSON.parse(config.jwk_keys) : null;
var middleware = function(req, res, next) {
var apiKeyHeaderName = config.hasOwnProperty("api-key-header") ? config["api-key-header"] : "x-api-key";
//set to true retain the api key
var keepApiKey = config.hasOwnProperty('keep-api-key') ? config['keep-api-key'] : false;
//cache api keys
cacheKey = config.hasOwnProperty("cacheKey") ? config.cacheKey : false;
//cache ttl
<<<<<<< HEAD
cacheKeyTTL = config.hasOwnProperty("cacheKeyTTL") ? config.cacheKeyTTL : cacheKeyTTL;
//cache size
cacheSize = config.hasOwnProperty("cacheSize") ? config.cacheSize : cacheSize;
=======
cacheKeyTTL = config.hasOwnProperty("cacheKeyTTL") ? config.cacheKeyTTL : 60000;
//cache size
cacheSize = config.hasOwnProperty("cacheSize") ? config.cacheSize : 100;
>>>>>>> 7d0c3c0
//set grace period
var gracePeriod = config.hasOwnProperty("gracePeriod") ? config.gracePeriod : 0;
acceptField.gracePeriod = gracePeriod;
//store api keys here
var apiKey;
//this flag will enable check against resource paths only
productOnly = config.hasOwnProperty("productOnly") ? config.productOnly : false;
//if local proxy is set, ignore proxies
if (process.env.EDGEMICRO_LOCAL_PROXY === "1") {
productOnly = true;
}
//leaving rest of the code same to ensure backward compatibility
apiKey = req.headers[apiKeyHeaderName]
if ( apiKey ) {
if (!keepApiKey) {
delete(req.headers[apiKeyHeaderName]); // don't pass this header to target
}
exchangeApiKeyForToken(req, res, next, config, logger, stats, middleware, apiKey);
} else if (req.reqUrl && req.reqUrl.query && (apiKey = req.reqUrl.query[apiKeyHeaderName])) {
exchangeApiKeyForToken(req, res, next, config, logger, stats, middleware, apiKey);
} else {
if (config.allowNoAuthorization) {
return next();
} else {
debug('missing_authorization');
return sendError(req, res, next, logger, stats, 'missing_authorization', 'Missing API Key header');
}
}
}
var exchangeApiKeyForToken = function(req, res, next, config, logger, stats, middleware, apiKey) {
var cacheControl = req.headers["cache-control"] || 'no-cache';
if (cacheKey || (cacheControl && cacheControl.indexOf("no-cache") < 0)) { // caching is allowed
cache.read(apiKey, function(err, value) {
if (value) {
if (Date.now() / 1000 < value.exp) { // not expired yet (token expiration is in seconds)
debug("api key cache hit", apiKey);
return authorize(req, res, next, logger, stats, value);
} else {
cache.remove(apiKey);
debug("api key cache expired", apiKey);
requestApiKeyJWT(req, res, next, config, logger, stats, middleware, apiKey);
}
} else {
debug("api key cache miss", apiKey);
requestApiKeyJWT(req, res, next, config, logger, stats, middleware, apiKey);
}
});
} else {
requestApiKeyJWT(req, res, next, config, logger, stats, middleware, apiKey);
}
}
function requestApiKeyJWT(req, res, next, config, logger, stats, middleware, apiKey) {
if (!config.verify_api_key_url) return sendError(req, res, next, logger, stats, "invalid_request", "API Key Verification URL not configured");
var api_key_options = {
url: config.verify_api_key_url,
method: "POST",
json: {
"apiKey": apiKey
},
headers: {
"x-dna-api-key": apiKey
}
};
if (config.agentOptions) {
if (config.agentOptions.requestCert) {
api_key_options.requestCert = true;
if (config.agentOptions.cert && config.agentOptions.key) {
api_key_options.key = fs.readFileSync(path.resolve(config.agentOptions.key), "utf8");
api_key_options.cert = fs.readFileSync(path.resolve(config.agentOptions.cert), "utf8");
if (config.agentOptions.ca) api_key_options.ca = fs.readFileSync(path.resolve(config.agentOptions.ca), "utf8");
} else if (config.agentOptions.pfx) {
api_key_options.pfx = fs.readFileSync(path.resolve(config.agentOptions.pfx));
}
if (config.agentOptions.rejectUnauthorized) {
api_key_options.rejectUnauthorized = true;
}
if (config.agentOptions.secureProtocol) {
api_key_options.secureProtocol = true;
}
if (config.agentOptions.ciphers) {
api_key_options.ciphers = config.agentOptions.ciphers;
}
if (config.agentOptions.passphrase) api_key_options.passphrase = config.agentOptions.passphrase;
}
}
debug(api_key_options);
request(api_key_options, function(err, response, body) {
if (err) {
debug("verify apikey gateway timeout");
return sendError(req, res, next, logger, stats, "gateway_timeout", err.message);
}
if (response.statusCode !== 200) {
if (config.allowInvalidAuthorization) {
console.warn("ignoring err");
return next();
} else {
debug("verify apikey access_denied");
return sendError(req, res, next, logger, stats, "access_denied", response.statusMessage);
}
}
verify(body, config, logger, stats, middleware, req, res, next, apiKey);
});
}
var verify = function(token, config, logger, stats, middleware, req, res, next, apiKey) {
var isValid = false;
var oauthtoken = token && token.token ? token.token : token;
var decodedToken = JWS.parse(oauthtoken);
debug(decodedToken)
if (keys) {
debug("using jwk");
var pem = getPEM(decodedToken, keys);
isValid = JWS.verifyJWT(oauthtoken, pem, acceptField);
} else {
debug("validating jwt");
debug(config.public_key)
isValid = JWS.verifyJWT(oauthtoken, config.public_key, acceptField);
}
if (!isValid) {
if (config.allowInvalidAuthorization) {
console.warn("ignoring err");
return next();
} else {
debug("invalid token");
return sendError(req, res, next, logger, stats, "invalid_token");
}
} else {
authorize(req, res, next, logger, stats, decodedToken.payloadObj, apiKey);
}
};
return {
onrequest: function(req, res, next) {
if (process.env.EDGEMICRO_LOCAL === "1") {
debug ("MG running in local mode. Skipping OAuth");
next();
} else {
middleware(req, res, next);
}
}
};
function authorize(req, res, next, logger, stats, decodedToken, apiKey) {
if (checkIfAuthorized(config, req.reqUrl.path, res.proxy, decodedToken)) {
req.token = decodedToken;
var authClaims = _.omit(decodedToken, PRIVATE_JWT_VALUES);
req.headers["x-authorization-claims"] = Buffer.from(JSON.stringify(authClaims)).toString("base64");
if (apiKey) {
var cacheControl = req.headers["cache-control"] || "no-cache";
if (cacheKey || (cacheControl && cacheControl.indexOf("no-cache") < 0)) { // caching is toFixed
// default to now (in seconds) + 30m if not set
decodedToken.exp = decodedToken.exp || +(((Date.now() / 1000) + 1800).toFixed(0));
//apiKeyCache[apiKey] = decodedToken;
cache.size(function(err, sizevalue) {
if (!err && sizevalue != null && sizevalue < cacheSize) {
cache.store(apiKey, decodedToken, cacheKeyTTL);
} else {
debug('too many keys in cache; ignore storing token');
}
});
} else {
debug("api key cache skip", apiKey);
}
}
next();
} else {
return sendError(req, res, next, logger, stats, "access_denied");
}
}
}
// from the product name(s) on the token, find the corresponding proxy
// then check if that proxy is one of the authorized proxies in bootstrap
const checkIfAuthorized = module.exports.checkIfAuthorized = function checkIfAuthorized(config, urlPath, proxy, decodedToken) {
var parsedUrl = url.parse(urlPath);
//
debug("product only: " + productOnly);
//
if (!decodedToken.api_product_list) {
debug("no api product list");
return false;
}
return decodedToken.api_product_list.some(function(product) {
const validProxyNames = config.product_to_proxy[product];
if (!productOnly) {
if (!validProxyNames) {
debug("no proxies found for product");
return false;
}
}
const apiproxies = config.product_to_api_resource[product];
var matchesProxyRules = false;
if (apiproxies && apiproxies.length) {
apiproxies.forEach(function(tempApiProxy) {
if (matchesProxyRules) {
//found one
debug("found matching proxy rule");
return;
}
urlPath = parsedUrl.pathname;
const apiproxy = tempApiProxy.includes(proxy.base_path) ?
tempApiProxy :
proxy.base_path + (tempApiProxy.startsWith("/") ? "" : "/") + tempApiProxy
if (apiproxy.endsWith("/") && !urlPath.endsWith("/")) {
urlPath = urlPath + "/";
}
if (apiproxy.includes(SUPPORTED_DOUBLE_ASTERIK_PATTERN)) {
const regex = apiproxy.replace(/\*\*/gi, ".*")
matchesProxyRules = urlPath.match(regex)
} else {
if (apiproxy.includes(SUPPORTED_SINGLE_ASTERIK_PATTERN)) {
const regex = apiproxy.replace(/\*/gi, "[^/]+");
matchesProxyRules = urlPath.match(regex)
} else {
// if(apiproxy.includes(SUPPORTED_SINGLE_FORWARD_SLASH_PATTERN)){
// }
matchesProxyRules = urlPath === apiproxy;
}
}
})
} else {
matchesProxyRules = true
}
debug("matches proxy rules: " + matchesProxyRules);
//add pattern matching here
if (!productOnly)
return matchesProxyRules && validProxyNames.indexOf(proxy.name) >= 0;
else
return matchesProxyRules;
});
}
function getPEM(decodedToken, keys) {
var i = 0;
debug("jwk kid " + decodedToken.headerObj.kid);
for (; i < keys.length; i++) {
if (keys.kid === decodedToken.headerObj.kid) {
break;
}
}
var publickey = rs.KEYUTIL.getKey(keys.keys[i]);
return rs.KEYUTIL.getPEM(publickey);
}
function setResponseCode(res,code) {
switch ( code ) {
case 'invalid_request': {
res.statusCode = 400;
break;
}
case 'access_denied':{
res.statusCode = 403;
break;
}
case 'invalid_token':
case 'missing_authorization':
case 'invalid_authorization': {
res.statusCode = 401;
break;
}
case 'gateway_timeout': {
res.statusCode = 504;
break;
}
default: {
res.statusCode = 500;
break;
}
}
}
function sendError(req, res, next, logger, stats, code, message) {
setResponseCode(res,code)
var response = {
error: code,
error_description: message
};
debug("auth failure", res.statusCode, code, message ? message : "", req.headers, req.method, req.url);
logger.error({
req: req,
res: res
}, "apikeys");
//opentracing
if (process.env.EDGEMICRO_OPENTRACE) {
try {
const traceHelper = require('../microgateway-core/lib/trace-helper');
traceHelper.setChildErrorSpan('apikeys', req.headers);
} catch (err) {}
}
//
if (!res.finished) res.setHeader("content-type", "application/json");
res.end(JSON.stringify(response));
stats.incrementStatusCount(res.statusCode);
next(code, message);
return code;
}