heimdall-api-platform 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -0
  3. package/lib/clients/http-client.js +296 -0
  4. package/lib/commons-cache.js +185 -0
  5. package/lib/commons-const.js +203 -0
  6. package/lib/commons-elasticsearch.js +49 -0
  7. package/lib/commons-errors.js +278 -0
  8. package/lib/commons-opensearch.js +37 -0
  9. package/lib/commons-splunk.js +105 -0
  10. package/lib/commons-util.js +669 -0
  11. package/lib/default-routes-docs.js +141 -0
  12. package/lib/default-routes-pos.js +111 -0
  13. package/lib/default-routes-pre.js +151 -0
  14. package/lib/environment.js +81 -0
  15. package/lib/factory/api-gateway.js +12 -0
  16. package/lib/factory/client-factory.js +41 -0
  17. package/lib/factory/function-factory.js +40 -0
  18. package/lib/factory/operation-flow-factory.js +64 -0
  19. package/lib/factory/server-factory.js +15 -0
  20. package/lib/factory/transformation-function-factory.js +47 -0
  21. package/lib/handle-route.js +472 -0
  22. package/lib/index.js +50 -0
  23. package/lib/jwt-util.js +38 -0
  24. package/lib/license/license-service.js +27 -0
  25. package/lib/models/base-context.js +77 -0
  26. package/lib/models/elastic-index-data.js +76 -0
  27. package/lib/models/flow-context.js +58 -0
  28. package/lib/models/flow-indexed.js +62 -0
  29. package/lib/models/operation-function-indexed.js +22 -0
  30. package/lib/models/operation-function-transformation-indexed.js +23 -0
  31. package/lib/models/operation-http-indexed.js +38 -0
  32. package/lib/models/operation-mock-indexed.js +22 -0
  33. package/lib/models/route-context.js +69 -0
  34. package/lib/models/security-route.js +41 -0
  35. package/lib/models/service-context.js +65 -0
  36. package/lib/models/service-group.js +15 -0
  37. package/lib/models/service-route.js +23 -0
  38. package/lib/models/splunk-data.js +70 -0
  39. package/lib/operations/abstract-operation.js +73 -0
  40. package/lib/operations/function.js +143 -0
  41. package/lib/operations/http.js +286 -0
  42. package/lib/operations/mock.js +34 -0
  43. package/lib/operations/monitor-check.js +151 -0
  44. package/lib/orchestration-flow.js +323 -0
  45. package/lib/public/redoc.html +152 -0
  46. package/lib/public/swagger.html +143 -0
  47. package/lib/router.js +29 -0
  48. package/lib/security-validation.js +46 -0
  49. package/lib/services/server.js +211 -0
  50. package/lib/services/template-monitorcheck-route.js +61 -0
  51. package/package.json +90 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Márcio Rosa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # heimdall-api-platform
2
+ This application is an gateway api platform
@@ -0,0 +1,296 @@
1
+ "use strict";
2
+
3
+ const Util = require("../commons-util");
4
+ const Const = require("../commons-const");
5
+ const { CreateHttpError } = require("../commons-errors");
6
+ const http = require("http");
7
+ const https = require("https");
8
+ const doRequest = require("axios");
9
+ const path = require("path");
10
+ const _ = require("underscore");
11
+ const { promisify } = require("util");
12
+ const FormData = require('form-data');
13
+
14
+
15
+ // require("axios-debug-log")({
16
+ // request: function (debug, config) {
17
+ // Util.info(
18
+ // `stage=request method=interceptors.request url=${config.baseURL}${config.url} request=${config.data}`
19
+ // );
20
+ // },
21
+ // response: function (debug, response) {
22
+ // Util.info(
23
+ // `stage=request method=interceptors.response url=${response.config.baseURL}${response.config.url} request=${
24
+ // response.config.data
25
+ // } response=${JSON.stringify(response.data, null, 2)}`
26
+ // );
27
+ // },
28
+ // error: function (debug, error) {
29
+ // Util.error(
30
+ // `stage=request method=interceptors.error url=${error.config.baseURL}${error.config.url} request=${
31
+ // error.config.data
32
+ // } error=${JSON.stringify(new CreateHttpError(error), null, 2)}`
33
+ // );
34
+ // },
35
+ // });
36
+
37
+ class HttpClient {
38
+ constructor(options) {
39
+ if (!options.host) {
40
+ Util.throwErrorIfItExists(new Error("The url can not be empty."));
41
+ }
42
+
43
+ this.host = options.host || "";
44
+ this.basePath = options.basePath || "";
45
+ this.user = options.user;
46
+ this.password = options.password || "";
47
+ this.token = options.token || "";
48
+ this.poolSize = options.poolSize || Const.DEFAULT_POOLSIZE;
49
+ this.authentication = options.authentication || "";
50
+ this.timeout = options.timeout || Const.DEFAULT_TIMEOUT_MS;
51
+ this.mtls = options.mtls || {};
52
+ this.enableMtls = this.mtls.hasOwnProperty("cert") && this.mtls.hasOwnProperty("key") ? true : false;
53
+ this.enableMtlsPfx = this.mtls.hasOwnProperty("pfx") && this.mtls.hasOwnProperty("passphrase") ? true : false;
54
+ this.protocol = this.host.substr(0, this.host.indexOf(":"));
55
+ }
56
+
57
+ generateRequestOptions(options) {
58
+
59
+ let requestOptions = {
60
+ method: (options.method || Const.HTTP_METHOD.GET).toLocaleLowerCase(),
61
+ baseURL: this.host,
62
+ url: path.join("/", this.basePath),
63
+ params: options.query || {},
64
+ timeout: this.timeout,
65
+ gzip: true,
66
+ responseType: "json",
67
+ headers: this.generateRequestHeaders(options),
68
+ };
69
+
70
+ // Adicionar options.path à URL se existir
71
+ if (options.path) {
72
+ requestOptions.url = path.join(requestOptions.url, "/", options.path);
73
+ }
74
+
75
+ // Construir a URL completa
76
+ requestOptions.urlFull = requestOptions.baseURL + requestOptions.url;
77
+
78
+ // Ajustar a URL para rotas de monitoramento
79
+ if (options.monitor) {
80
+ requestOptions.url = this.host + path.join("/", options.path || "").replace(/\\/g, "/");
81
+ }
82
+
83
+ //Validate path windows
84
+ if (process.platform == 'win32') {
85
+ requestOptions.url = requestOptions.url.replace(/\\/g, "/");
86
+ }
87
+
88
+ // Configurar agentes HTTP/HTTPS com mTLS se necessário
89
+ if (this.protocol === "https") {
90
+ if (this.enableMtls) {
91
+ requestOptions.httpsAgent = new https.Agent({
92
+ cert: Buffer.from(this.mtls.cert, "base64").toString("utf8"),
93
+ key: Buffer.from(this.mtls.key, "base64").toString("utf8"),
94
+ keepAlive: true,
95
+ });
96
+ } else if (this.enableMtlsPfx) {
97
+ requestOptions.httpsAgent = new https.Agent({
98
+ pfx: Buffer.from(this.mtls.pfx, "base64"),
99
+ passphrase: Buffer.from(this.mtls.passphrase, "base64").toString("utf8"),
100
+ minVersion: 'TLSv1.2',
101
+ keepAlive: true,
102
+ });
103
+ } else {
104
+ requestOptions.httpsAgent = this.getAgent();
105
+ }
106
+ } else {
107
+ requestOptions.httpAgent = this.getAgent();
108
+ }
109
+
110
+ // Configurar dados da requisição para métodos POST
111
+ if (
112
+ requestOptions.method === Const.HTTP_METHOD.POST.toLocaleLowerCase() &&
113
+ requestOptions.headers[Const.HEADERS.CONTENT_TYPE].indexOf(Const.FORM_CONTENT_TYPE_VALUE) > -1
114
+ ) {
115
+ requestOptions.data = !_.isEmpty(options.params) ? options.params : options.body;
116
+ requestOptions.dataType = "form";
117
+ } else if (
118
+ requestOptions.method === Const.HTTP_METHOD.POST.toLowerCase() &&
119
+ requestOptions.headers[Const.HEADERS.CONTENT_TYPE].indexOf(Const.FORM_MULTIPART_CONTENT_TYPE_VALUE) > -1
120
+ ) {
121
+ requestOptions.dataType = "multipart";
122
+
123
+ const form = new FormData();
124
+
125
+ if (options.request?.file) {
126
+ const request = options.request;
127
+ const file = request.file;
128
+ form.append(options.service.rawOptions.uploadFieldName || 'file', file.buffer, {
129
+ filename: file.originalname,
130
+ contentType: file.mimetype,
131
+ });
132
+ }
133
+
134
+ // Adiciona outros campos do params/body
135
+ const fields = !_.isEmpty(options.params) ? options.params : options.body;
136
+ if (fields && typeof fields === 'object') {
137
+ for (const [key, value] of Object.entries(fields)) {
138
+ form.append(key, value);
139
+ }
140
+ }
141
+
142
+ // Sobrescreve os headers para incluir os do FormData
143
+ requestOptions.headers = {
144
+ ...requestOptions.headers,
145
+ ...form.getHeaders(),
146
+ };
147
+
148
+ requestOptions.data = form;
149
+
150
+ } else if (!_.isEmpty(options.body)) {
151
+ requestOptions.dataType = "json";
152
+ requestOptions.data = JSON.stringify(options.body);
153
+ }
154
+
155
+ return requestOptions;
156
+ }
157
+
158
+
159
+ getAgent() {
160
+ let agent = null;
161
+
162
+ switch (this.protocol) {
163
+ case "https":
164
+ agent = new https.Agent({ keepAlive: true });
165
+ break;
166
+ default:
167
+ agent = new http.Agent({ keepAlive: true });
168
+ break;
169
+ }
170
+
171
+ agent.maxSockets = this.poolSize || Const.DEFAULT_POOLSIZE;
172
+
173
+ return agent;
174
+ }
175
+
176
+ generateRequestHeaders(options) {
177
+ let headers = {};
178
+
179
+ if (options.headers) {
180
+ headers = _.extend(headers, options.headers);
181
+ }
182
+
183
+ if (this.authentication && this.authentication.toLowerCase() === "basic" && this.user && this.password) {
184
+ headers.Authorization = "Basic " + new Buffer(this.user + ":" + this.password).toString("base64");
185
+ }
186
+
187
+ if (this.authentication && this.authentication.toLowerCase() === "bearer" && this.token) {
188
+ headers.Authorization = "Bearer " + this.token;
189
+ }
190
+
191
+ /*if (options.method == Const.HTTP_METHOD.POST &&
192
+ options.headers[Const.HEADERS.CONTENT_TYPE] == 'application/x-www-form-urlencoded;charset=UTF-8') {
193
+ headers[Const.HEADERS.CONTENT_LENGTH] = querystring.stringify(options.params).length;
194
+ } else {
195
+ headers[Const.HEADERS.CONTENT_LENGTH] = querystring.stringify(options.body).length;
196
+ }*/
197
+
198
+ //headers.Connection = 'keep-alive';
199
+
200
+ headers.Connection = "close";
201
+
202
+ return headers;
203
+ }
204
+
205
+ //TODO ADICIONAR O STEPFLOW PORQUE ELE TEM O CONTEXT
206
+ async execute(options, callbackStep) {
207
+
208
+ let requestOptions = this.generateRequestOptions(options);
209
+
210
+ Util.info(
211
+ `stage=init method=HttpClient.execute (${this.protocol.toUpperCase()}) for Client Name=${options.name || ""
212
+ } config`,
213
+ {
214
+ uuid: options.uuid || "",
215
+ flowStepUuid: options.flowStepUuid || "",
216
+ contextUuid: options.contextUuid || "",
217
+ timeout: requestOptions.timeout,
218
+ method: requestOptions.method,
219
+ url: requestOptions.urlFull,
220
+ body: Util.isJSONValid(requestOptions.data) ? Util.obfuscationJSON(requestOptions.data) : {},
221
+ query: requestOptions.params || {},
222
+ headers: Util.obfuscationJSON(requestOptions.headers || {}),
223
+ }
224
+ );
225
+
226
+ doRequest(requestOptions)
227
+ .then((response) => {
228
+ Util.info(
229
+ `stage=end method=HttpClient.execute (${this.protocol.toUpperCase()}) for Client Name=${options.name || ""
230
+ } response`,
231
+ {
232
+ uuid: options.uuid || "",
233
+ flowStepUuid: options.flowStepUuid || "",
234
+ contextUuid: options.contextUuid || "",
235
+ timeout: requestOptions.timeout,
236
+ method: requestOptions.method,
237
+ url: requestOptions.urlFull,
238
+ body: Util.isJSONValid(requestOptions.data) ? Util.obfuscationJSON(requestOptions.data) : {},
239
+ query: requestOptions.params || {},
240
+ headers: Util.obfuscationJSON(requestOptions.headers || {}),
241
+ result: Util.obfuscationJSON(response.data || {}),
242
+ }
243
+ );
244
+
245
+ callbackStep(null, response);
246
+ })
247
+ .catch((error) => {
248
+ //TODO: TRATAR ESSES ERROS
249
+ //error.code[EHOSTUNREACH,ECONNREFUSED,ECONNRESET,ESOCKETTIMEDOUT]
250
+
251
+ Util.error(
252
+ `stage=error method=HttpClient.execute (${this.protocol.toUpperCase()}) for Client Name=${options.name || ""
253
+ } response`,
254
+ {
255
+ uuid: options.uuid || "",
256
+ flowStepUuid: options.flowStepUuid || "",
257
+ contextUuid: options.contextUuid || "",
258
+ timeout: requestOptions.timeout,
259
+ method: requestOptions.method,
260
+ url: requestOptions.urlFull,
261
+ body: Util.isJSONValid(requestOptions.data) ? Util.obfuscationJSON(requestOptions.data) : {},
262
+ query: requestOptions.params || {},
263
+ headers: Util.obfuscationJSON(requestOptions.headers || {}),
264
+ error: Util.obfuscationJSON(new CreateHttpError(error) || {}),
265
+ }
266
+ );
267
+
268
+ if (error || error.response.status >= Const.HTTP_STATUS.ERROR_CLIENT_RANGE_START) {
269
+ callbackStep(new CreateHttpError(error), null);
270
+ } else {
271
+ Util.info(
272
+ `stage=error method=HttpClient.execute (${this.protocol.toUpperCase()}) for Client Name=${options.name || ""
273
+ } response`,
274
+ {
275
+ uuid: options.uuid || "",
276
+ flowStepUuid: options.flowStepUuid || "",
277
+ contextUuid: options.contextUuid || "",
278
+ timeout: requestOptions.timeout,
279
+ method: requestOptions.method,
280
+ url: requestOptions.urlFull,
281
+ body: Util.isJSONValid(requestOptions.data) ? Util.obfuscationJSON(requestOptions.data) : {},
282
+ query: requestOptions.params || {},
283
+ headers: Util.obfuscationJSON(requestOptions.headers || {}),
284
+ result: Util.obfuscationJSON(error.response.data || {}),
285
+ }
286
+ );
287
+
288
+ callbackStep(null, error.response || {});
289
+ }
290
+ });
291
+ }
292
+ }
293
+
294
+ HttpClient.prototype.executePromise = promisify(HttpClient.prototype.execute);
295
+
296
+ module.exports = HttpClient;
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+
3
+ const redis = require("redis");
4
+ const { promisify } = require("util");
5
+ const NodeCache = require("node-cache");
6
+ const Util = require("./commons-util.js");
7
+
8
+ const DEFAULT_REDIS_CONNECT_TIMEOUT = 30000;
9
+ const DEFAULT_REDIS_RECONNECT_TIMEOUT = 30000;
10
+
11
+ class RedisClient {
12
+ constructor(options = {}) {
13
+ this.enableRedis = options.enableRedis || false;
14
+ this.readClient = null;
15
+ this.writerClient = null;
16
+
17
+ this.localCache = new NodeCache({
18
+ stdTTL: 120, // Default TTL of 120 seconds
19
+ checkperiod: 1, // Check expired keys every 1 second
20
+ });
21
+
22
+ if (this.enableRedis && options.redisCache) {
23
+ const { reader, writer } = options.redisCache;
24
+ this.readClient = this.createRedisClient(reader, "read");
25
+ this.writerClient = this.createRedisClient(writer, "writer");
26
+ }
27
+ }
28
+
29
+ createRedisClient(config, type) {
30
+ if (!config) {
31
+ Util.warning(`stage=warn method=createRedisClient message=No Redis configuration provided for type=${type}`);
32
+ return null;
33
+ }
34
+
35
+ const client = redis.createClient(config.port, config.host, {
36
+ enable_offline_queue: false,
37
+ no_ready_check: true,
38
+ connect_timeout: config.connectTimeout || DEFAULT_REDIS_CONNECT_TIMEOUT,
39
+ retry_strategy: RedisClient.retryStrategy,
40
+ });
41
+
42
+ client.on("error", (err) => {
43
+ Util.error(`stage=error method=createRedisClient message=Redis[${type}] error`, err);
44
+ });
45
+
46
+ client.on("connect", () => {
47
+ Util.info(`stage=info method=createRedisClient message=Redis[${type}] connected`, {
48
+ host: config.host,
49
+ port: config.port,
50
+ });
51
+ });
52
+
53
+ return client;
54
+ }
55
+
56
+ async put(cacheName, key, value, ttl) {
57
+ const composedKey = this.composeKey(cacheName, key);
58
+
59
+ if (this.writerClient && this.writerClient.connected) {
60
+ const setexAsync = promisify(this.writerClient.setex).bind(this.writerClient);
61
+ try {
62
+ await setexAsync(composedKey, ttl, JSON.stringify(value));
63
+ Util.info(`stage=info method=put message=Cache set successfully`, { cacheName, key, ttl });
64
+ return;
65
+ } catch (err) {
66
+ Util.error(`stage=error method=put message=Error setting cache in Redis`, err);
67
+ }
68
+ }
69
+
70
+ // Fallback to local cache
71
+ this.localCache.set(composedKey, value, ttl);
72
+ Util.warning(`stage=warn method=put message=Using local cache as fallback`, { cacheName, key });
73
+ }
74
+
75
+ async get(cacheName, key) {
76
+ const composedKey = this.composeKey(cacheName, key);
77
+
78
+ if (this.readClient && this.readClient.connected) {
79
+ const getAsync = promisify(this.readClient.get).bind(this.readClient);
80
+ try {
81
+ const entry = await getAsync(composedKey);
82
+ if (entry) {
83
+ Util.info(`stage=info method=get message=Cache hit in Redis`, { cacheName, key });
84
+ return JSON.parse(entry);
85
+ } else {
86
+ Util.warning(`stage=warn method=get message=Cache miss in Redis`, { cacheName, key });
87
+ }
88
+ } catch (err) {
89
+ Util.error(`stage=error method=get message=Error retrieving cache from Redis`, err);
90
+ }
91
+ }
92
+
93
+ // Fallback to local cache
94
+ const localValue = this.localCache.get(composedKey);
95
+ if (localValue) {
96
+ Util.info(`stage=info method=get message=Cache hit in local cache`, { cacheName, key });
97
+ } else {
98
+ Util.warning(`stage=warn method=get message=Cache miss in local cache`, { cacheName, key });
99
+ }
100
+ return localValue || null;
101
+ }
102
+
103
+ async delete(cacheName, key) {
104
+ const composedKey = this.composeKey(cacheName, key);
105
+
106
+ if (this.writerClient && this.writerClient.connected) {
107
+ const delAsync = promisify(this.writerClient.del).bind(this.writerClient);
108
+ try {
109
+ const result = await delAsync(composedKey);
110
+ if (result) {
111
+ Util.info(`stage=info method=delete message=Key deleted successfully in Redis`, { cacheName, key });
112
+ return;
113
+ }
114
+ Util.warning(`stage=warn method=delete message=Key not found in Redis`, { cacheName, key });
115
+ } catch (err) {
116
+ Util.error(`stage=error method=delete message=Error deleting key in Redis`, err);
117
+ }
118
+ }
119
+
120
+ // Fallback to local cache
121
+ const localDeleted = this.localCache.del(composedKey);
122
+ if (localDeleted) {
123
+ Util.info(`stage=info method=delete message=Key deleted successfully in local cache`, { cacheName, key });
124
+ } else {
125
+ Util.warning(`stage=warn method=delete message=Key not found in local cache`, { cacheName, key });
126
+ }
127
+ }
128
+
129
+ async getKeys(cacheName) {
130
+ if (this.readClient && this.readClient.connected) {
131
+ const keysAsync = promisify(this.readClient.keys).bind(this.readClient);
132
+ try {
133
+ const keys = await keysAsync(`${cacheName}:*`);
134
+ if (keys.length) {
135
+ Util.info(`stage=info method=getKeys message=Keys found in Redis`, { cacheName, keys });
136
+ return keys;
137
+ }
138
+ Util.warning(`stage=warn method=getKeys message=No keys found in Redis`, { cacheName });
139
+ } catch (err) {
140
+ Util.error(`stage=error method=getKeys message=Error retrieving keys from Redis`, err);
141
+ }
142
+ }
143
+
144
+ // Fallback to local cache
145
+ const keys = this.localCache.keys().filter((key) => key.startsWith(`${cacheName}:`));
146
+ if (keys.length) {
147
+ Util.info(`stage=info method=getKeys message=Keys found in local cache`, { cacheName, keys });
148
+ } else {
149
+ Util.warning(`stage=warn method=getKeys message=No keys found in local cache`, { cacheName });
150
+ }
151
+ return keys;
152
+ }
153
+
154
+ composeKey(cacheName, key) {
155
+ return `${cacheName}:${key}`;
156
+ }
157
+
158
+ static retryStrategy(options) {
159
+ const MAX_RETRY_TIME = 1000 * 60 * 60;
160
+ const MAX_ATTEMPTS = 10;
161
+
162
+ if (options.error && options.error.code === "ECONNREFUSED") {
163
+ Util.error(`stage=error method=retryStrategy message=Connection refused`, options.error);
164
+ return DEFAULT_REDIS_RECONNECT_TIMEOUT;
165
+ }
166
+
167
+ if (options.total_retry_time > MAX_RETRY_TIME) {
168
+ Util.error(`stage=error method=retryStrategy message=Retry time exhausted`);
169
+ return new Error("Retry time exhausted");
170
+ }
171
+
172
+ if (options.attempt > MAX_ATTEMPTS) {
173
+ Util.warning(`stage=warn method=retryStrategy message=Max attempts reached`, { attempts: options.attempt });
174
+ return undefined;
175
+ }
176
+
177
+ Util.info(`stage=info method=retryStrategy message=Retrying connection`, { attempts: options.attempt });
178
+ return Math.min(options.attempt * 100, DEFAULT_REDIS_RECONNECT_TIMEOUT);
179
+ }
180
+ }
181
+
182
+ module.exports = {
183
+ createClient: (options) => new RedisClient(options),
184
+ RedisClient,
185
+ };