dbgate-api-premium 7.0.4 → 7.1.0

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.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dbgate-api-premium",
3
3
  "main": "src/index.js",
4
- "version": "7.0.4",
5
- "homepage": "https://dbgate.org/",
4
+ "version": "7.1.0",
5
+ "homepage": "https://www.dbgate.io/",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "https://github.com/dbgate/dbgate.git"
@@ -30,10 +30,11 @@
30
30
  "compare-versions": "^3.6.0",
31
31
  "cors": "^2.8.5",
32
32
  "cross-env": "^6.0.3",
33
- "dbgate-datalib": "^7.0.4",
33
+ "dbgate-datalib": "^7.1.0",
34
34
  "dbgate-query-splitter": "^4.11.9",
35
- "dbgate-sqltree": "^7.0.4",
36
- "dbgate-tools": "^7.0.4",
35
+ "dbgate-rest": "^7.1.0",
36
+ "dbgate-sqltree": "^7.1.0",
37
+ "dbgate-tools": "^7.1.0",
37
38
  "debug": "^4.3.4",
38
39
  "diff": "^5.0.0",
39
40
  "diff2html": "^3.4.13",
@@ -87,7 +88,7 @@
87
88
  "devDependencies": {
88
89
  "@types/fs-extra": "^9.0.11",
89
90
  "@types/lodash": "^4.14.149",
90
- "dbgate-types": "^7.0.4",
91
+ "dbgate-types": "^7.1.0",
91
92
  "env-cmd": "^10.1.0",
92
93
  "jsdoc-to-markdown": "^9.0.5",
93
94
  "node-loader": "^1.0.2",
@@ -55,6 +55,8 @@ function authMiddleware(req, res, next) {
55
55
  '/stream',
56
56
  '/storage/get-connections-for-login-page',
57
57
  '/storage/set-admin-password',
58
+ '/storage/request-password-reset',
59
+ '/storage/reset-password',
58
60
  '/auth/get-providers',
59
61
  '/connections/dblogin-web',
60
62
  '/connections/dblogin-app',
@@ -202,10 +202,10 @@ module.exports = {
202
202
 
203
203
  const storageConnections = await storage.connections(req);
204
204
  if (storageConnections) {
205
- return storageConnections;
205
+ return storageConnections.map(maskConnection);
206
206
  }
207
207
  if (portalConnections) {
208
- if (platformInfo.allowShellConnection) return portalConnections;
208
+ if (platformInfo.allowShellConnection) return portalConnections.map(x => encryptConnection(x));
209
209
  return portalConnections.map(maskConnection).filter(x => connectionHasPermission(x, loadedPermissions));
210
210
  }
211
211
  return (await this.datastore.find()).filter(x => connectionHasPermission(x, loadedPermissions));
@@ -243,13 +243,13 @@ module.exports = {
243
243
  subprocess.send({ ...connection, requestDbList });
244
244
  return new Promise((resolve, reject) => {
245
245
  let isWaitingForVolatile = false;
246
-
246
+
247
247
  const cleanup = () => {
248
248
  if (connection._id && pendingTestSubprocesses[connection._id]) {
249
249
  delete pendingTestSubprocesses[connection._id];
250
250
  }
251
251
  };
252
-
252
+
253
253
  subprocess.on('message', resp => {
254
254
  if (handleProcessCommunication(resp, subprocess)) return;
255
255
  // @ts-ignore
@@ -279,8 +279,8 @@ module.exports = {
279
279
  reject(new MissingCredentialsError(missingCredentialsDetail));
280
280
  }
281
281
  });
282
-
283
- subprocess.on('exit', (code) => {
282
+
283
+ subprocess.on('exit', code => {
284
284
  // If exit happens while waiting for volatile, that's expected
285
285
  if (isWaitingForVolatile && code === 0) {
286
286
  cleanup();
@@ -291,8 +291,8 @@ module.exports = {
291
291
  reject(new Error(`Test subprocess exited with code ${code}`));
292
292
  }
293
293
  });
294
-
295
- subprocess.on('error', (err) => {
294
+
295
+ subprocess.on('error', err => {
296
296
  cleanup();
297
297
  reject(err);
298
298
  });
@@ -327,7 +327,7 @@ module.exports = {
327
327
  return testRes;
328
328
  } else {
329
329
  volatileConnections[res._id] = res;
330
-
330
+
331
331
  // Check if there's a pending test subprocess waiting for this volatile connection
332
332
  const pendingTest = pendingTestSubprocesses[conid];
333
333
  if (pendingTest) {
@@ -335,7 +335,7 @@ module.exports = {
335
335
  try {
336
336
  // Send the volatile connection to the waiting subprocess
337
337
  subprocess.send({ ...res, requestDbList, isVolatileResolved: true });
338
-
338
+
339
339
  // Wait for the test result and emit it as an event
340
340
  subprocess.once('message', resp => {
341
341
  if (handleProcessCommunication(resp, subprocess)) return;
@@ -358,7 +358,7 @@ module.exports = {
358
358
  delete pendingTestSubprocesses[conid];
359
359
  }
360
360
  }
361
-
361
+
362
362
  return res;
363
363
  }
364
364
  },
@@ -484,12 +484,12 @@ module.exports = {
484
484
 
485
485
  const storageConnection = await storage.getConnection({ conid });
486
486
  if (storageConnection) {
487
- return storageConnection;
487
+ return mask ? maskConnection(storageConnection) : storageConnection;
488
488
  }
489
489
 
490
490
  if (portalConnections) {
491
491
  const res = portalConnections.find(x => x._id == conid) || null;
492
- return mask && !platformInfo.allowShellConnection ? maskConnection(res) : res;
492
+ return mask && !platformInfo.allowShellConnection ? maskConnection(res) : encryptConnection(res);
493
493
  }
494
494
  const res = await this.datastore.get(conid);
495
495
  return res || null;
@@ -165,6 +165,11 @@ module.exports = {
165
165
  if (!connection) {
166
166
  throw new Error(`databaseConnections: Connection with conid="${conid}" not found`);
167
167
  }
168
+
169
+ if (connection.engine?.endsWith('@rest')) {
170
+ return { isApiConnection: true };
171
+ }
172
+
168
173
  if (connection.passwordMode == 'askPassword' || connection.passwordMode == 'askUser') {
169
174
  throw new MissingCredentialsError({ conid, passwordMode: connection.passwordMode });
170
175
  }
@@ -0,0 +1,316 @@
1
+ // *** This file is part of DbGate Premium ***
2
+
3
+ const crypto = require('crypto');
4
+ const connections = require('./connections');
5
+ const socket = require('../utility/socket');
6
+ const { fork } = require('child_process');
7
+ const _ = require('lodash');
8
+ const AsyncLock = require('async-lock');
9
+ const { handleProcessCommunication } = require('../utility/processComm');
10
+ const lock = new AsyncLock();
11
+ const config = require('./config');
12
+ const processArgs = require('../utility/processArgs');
13
+ const { testConnectionPermission, loadPermissionsFromRequest, hasPermission } = require('../utility/hasPermission');
14
+ const { MissingCredentialsError } = require('../utility/exceptions');
15
+ const pipeForkLogs = require('../utility/pipeForkLogs');
16
+ const { getLogger, extractErrorLogData } = require('dbgate-tools');
17
+ const { sendToAuditLog } = require('../utility/auditlog');
18
+ const { decryptPasswordString } = require('../utility/crypting');
19
+ const { getRestAuthFromConnection } = require('../utility/connectUtility');
20
+
21
+ const logger = getLogger('restConnection');
22
+
23
+ module.exports = {
24
+ opened: [],
25
+ closed: {},
26
+ requests: {},
27
+
28
+ handle_apiInfo(conid, { apiInfo }) {
29
+ const existing = this.opened.find(x => x.conid == conid);
30
+ if (!existing) return;
31
+ existing.apiInfo = apiInfo;
32
+ socket.emitChanged(`rest-api-info-changed`, { conid });
33
+ },
34
+
35
+ handle_status(conid, { status }) {
36
+ const existing = this.opened.find(x => x.conid == conid);
37
+ if (!existing) return;
38
+ if (existing.status && status && existing.status.counter > status.counter) return;
39
+ existing.status = status;
40
+ socket.emitChanged(`rest-status-changed`, { conid });
41
+ },
42
+
43
+ handle_ping() {},
44
+
45
+ handle_response(conid, { msgid, ...response }) {
46
+ const pending = this.requests[msgid];
47
+ if (!pending) {
48
+ logger.warn(
49
+ `DBGM-00275 restConnections: Received response for unknown or already handled msgid="${msgid}" (conid="${conid}")`
50
+ );
51
+ return;
52
+ }
53
+ const [resolve, reject] = pending;
54
+ resolve(response);
55
+ delete this.requests[msgid];
56
+ },
57
+
58
+ async ensureOpened(conid) {
59
+ const res = await lock.acquire(conid, async () => {
60
+ const existing = this.opened.find(x => x.conid == conid);
61
+ if (existing) return existing;
62
+
63
+ const connection = await connections.getCore({ conid });
64
+ if (!connection) {
65
+ throw new Error(`restConnections: Connection with conid="${conid}" not found`);
66
+ }
67
+
68
+ if (connection.passwordMode == 'askPassword' || connection.passwordMode == 'askUser') {
69
+ throw new MissingCredentialsError({ conid, passwordMode: connection.passwordMode });
70
+ }
71
+
72
+ const subprocess = fork(
73
+ global['API_PACKAGE'] || process.argv[1],
74
+ ['--is-forked-api', '--start-process', 'restConnectionProcess', ...processArgs.getPassArgs()],
75
+ {
76
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
77
+ }
78
+ );
79
+
80
+ pipeForkLogs(subprocess);
81
+
82
+ const newOpened = {
83
+ conid,
84
+ subprocess,
85
+ apiInfo: null,
86
+ connection,
87
+ status: {
88
+ name: 'pending',
89
+ },
90
+ disconnected: false,
91
+ };
92
+
93
+ this.opened.push(newOpened);
94
+ delete this.closed[conid];
95
+ socket.emitChanged(`rest-status-changed`, { conid });
96
+
97
+ subprocess.on('message', message => {
98
+ // @ts-ignore
99
+ const { msgtype } = message;
100
+ if (handleProcessCommunication(message, subprocess)) return;
101
+ if (newOpened.disconnected) return;
102
+ const funcName = `handle_${msgtype}`;
103
+ if (!this[funcName]) {
104
+ logger.error({ msgtype, conid }, 'DBGM-00276 Unknown message type from subprocess restConnectionProcess');
105
+ return;
106
+ }
107
+ this[funcName](conid, message);
108
+ });
109
+
110
+ subprocess.on('exit', () => {
111
+ if (newOpened.disconnected) return;
112
+ this.close(conid, false);
113
+ });
114
+
115
+ subprocess.on('error', err => {
116
+ logger.error(extractErrorLogData(err), 'DBGM-00277 Error in REST connection subprocess');
117
+ if (newOpened.disconnected) return;
118
+ this.close(conid, false);
119
+ });
120
+
121
+ subprocess.send({
122
+ msgtype: 'connect',
123
+ connection: { ...connection, restAuth: getRestAuthFromConnection(connection) },
124
+ globalSettings: await config.getSettings(),
125
+ });
126
+ return newOpened;
127
+ });
128
+ return res;
129
+ },
130
+
131
+ close(conid, kill = true) {
132
+ const existing = this.opened.find(x => x.conid == conid);
133
+ if (existing) {
134
+ existing.disconnected = true;
135
+ if (kill) {
136
+ try {
137
+ existing.subprocess.kill();
138
+ } catch (err) {
139
+ logger.error(extractErrorLogData(err), 'DBGM-00278 Error killing REST subprocess');
140
+ }
141
+ }
142
+ this.opened = this.opened.filter(x => x.conid != conid);
143
+ this.closed[conid] = {
144
+ ...existing.status,
145
+ name: 'error',
146
+ };
147
+ socket.emitChanged(`rest-status-changed`, { conid });
148
+ }
149
+ },
150
+
151
+ disconnect_meta: true,
152
+ async disconnect({ conid }, req) {
153
+ await testConnectionPermission(conid, req);
154
+ await this.close(conid, true);
155
+ return { status: 'ok' };
156
+ },
157
+
158
+ getApiInfo_meta: true,
159
+ async getApiInfo({ conid }, req) {
160
+ if (!conid) return null;
161
+
162
+ await testConnectionPermission(conid, req);
163
+
164
+ const opened = await this.ensureOpened(conid);
165
+ sendToAuditLog(req, {
166
+ category: 'restop',
167
+ component: 'RestConnectionsController',
168
+ action: 'getApiInfo',
169
+ event: 'rest.getApiInfo',
170
+ severity: 'info',
171
+ conid,
172
+ sessionParam: `${conid}`,
173
+ sessionGroup: 'getApiInfo',
174
+ message: `Loaded API info for REST connection`,
175
+ });
176
+
177
+ return opened?.apiInfo ?? null;
178
+ },
179
+
180
+ restStatus_meta: true,
181
+ async restStatus() {
182
+ return {
183
+ ...this.closed,
184
+ ..._.mapValues(_.keyBy(this.opened, 'conid'), 'status'),
185
+ };
186
+ },
187
+
188
+ ping_meta: true,
189
+ async ping({ conidArray, strmid }) {
190
+ await Promise.all(
191
+ _.uniq(conidArray).map(async conid => {
192
+ try {
193
+ const opened = await this.ensureOpened(conid);
194
+ if (!opened) {
195
+ return Promise.resolve();
196
+ }
197
+ opened.subprocess.send({ msgtype: 'ping' });
198
+ } catch (err) {
199
+ logger.error(extractErrorLogData(err), 'DBGM-00279 Error pinging REST connection');
200
+ this.close(conid);
201
+ }
202
+ })
203
+ );
204
+ socket.setStreamIdFilter(strmid, { conid: conidArray ?? [] });
205
+ return { status: 'ok' };
206
+ },
207
+
208
+ refresh_meta: true,
209
+ async refresh({ conid, keepOpen }, req) {
210
+ await testConnectionPermission(conid, req);
211
+ if (!keepOpen) this.close(conid);
212
+
213
+ const opened = await this.ensureOpened(conid);
214
+ return this.sendRequest(opened, { msgtype: 'refresh' });
215
+ },
216
+
217
+ testConnection_meta: true,
218
+ async testConnection({ conid }, req) {
219
+ await testConnectionPermission(conid, req);
220
+ const opened = await this.ensureOpened(conid);
221
+ if (!opened) {
222
+ return { errorMessage: 'Could not open REST connection' };
223
+ }
224
+ const res = await this.sendRequest(opened, { msgtype: 'testConnection' });
225
+ if (res.errorMessage) {
226
+ return {
227
+ errorMessage: res.errorMessage,
228
+ };
229
+ }
230
+ return { status: 'ok' };
231
+ },
232
+
233
+ async executeCore(msgtype, { conid, method, endpoint, parameters, server }, req) {
234
+ await testConnectionPermission(conid, req);
235
+ const opened = await this.ensureOpened(conid);
236
+ if (!opened) {
237
+ return { errorMessage: 'Could not open REST connection' };
238
+ }
239
+ const auth = getRestAuthFromConnection(opened.connection);
240
+ return this.sendRequest(opened, {
241
+ msgtype,
242
+ method,
243
+ endpoint,
244
+ parameters,
245
+ server,
246
+ auth,
247
+ });
248
+ },
249
+
250
+ executeOpenapi_meta: true,
251
+ async executeOpenapi({ conid, method, endpoint, parameters, server }, req) {
252
+ return this.executeCore('executeOpenapi', { conid, method, endpoint, parameters, server }, req);
253
+ },
254
+
255
+ executeOdata_meta: true,
256
+ async executeOdata({ conid, method, endpoint, parameters, server }, req) {
257
+ return this.executeCore('executeOdata', { conid, method, endpoint, parameters, server }, req);
258
+ },
259
+
260
+ apiQuery_meta: true,
261
+ async apiQuery({ conid, server, query, variables }, req) {
262
+ await testConnectionPermission(conid, req);
263
+ const opened = await this.ensureOpened(conid);
264
+ if (!opened) {
265
+ return { errorMessage: 'Could not open REST connection' };
266
+ }
267
+ const auth = getRestAuthFromConnection(opened.connection);
268
+ const res = await this.sendRequest(opened, {
269
+ msgtype: 'apiQuery',
270
+ server,
271
+ query,
272
+ variables,
273
+ auth,
274
+ });
275
+ return res;
276
+ },
277
+
278
+ loadGraphqlConnectionData_meta: true,
279
+ async loadGraphqlConnectionData(
280
+ { conid, server, operationName, projection, queryField, selectedFieldSelection, pageSize, filterParameterName, filterValue },
281
+ req
282
+ ) {
283
+ await testConnectionPermission(conid, req);
284
+ const opened = await this.ensureOpened(conid);
285
+ if (!opened) {
286
+ return { errorMessage: 'Could not open REST connection' };
287
+ }
288
+ const auth = getRestAuthFromConnection(opened.connection);
289
+ return this.sendRequest(opened, {
290
+ msgtype: 'loadGraphqlConnectionData',
291
+ server,
292
+ operationName,
293
+ projection,
294
+ queryField,
295
+ selectedFieldSelection,
296
+ pageSize,
297
+ filterParameterName,
298
+ filterValue,
299
+ auth,
300
+ });
301
+ },
302
+
303
+ sendRequest(conn, message) {
304
+ const msgid = crypto.randomUUID();
305
+ const promise = new Promise((resolve, reject) => {
306
+ this.requests[msgid] = [resolve, reject];
307
+ try {
308
+ conn.subprocess.send({ msgid, ...message });
309
+ } catch (err) {
310
+ logger.error(extractErrorLogData(err), 'DBGM-00280 Error sending request to REST connection');
311
+ this.close(conn.conid);
312
+ }
313
+ });
314
+ return promise;
315
+ },
316
+ };
@@ -172,7 +172,7 @@ module.exports = {
172
172
  byline(subprocess.stderr).on('data', pipeDispatcher('error'));
173
173
  subprocess.on('exit', code => {
174
174
  // console.log('... EXITED', code);
175
- this.rejectRequest(runid, { message: 'No data returned, maybe input data source is too big' });
175
+ this.rejectRequest(runid, { message: 'DBGM-00281 No data returned, maybe input data source is too big' });
176
176
  logger.info({ code, pid: subprocess.pid }, 'DBGM-00016 Exited process');
177
177
  socket.emit(`runner-done-${runid}`, code);
178
178
  this.opened = this.opened.filter(x => x.runid != runid);
@@ -225,7 +225,7 @@ module.exports = {
225
225
  subprocess.on('exit', code => {
226
226
  console.log('... EXITED', code);
227
227
  logger.info({ code, pid: subprocess.pid }, 'DBGM-00017 Exited process');
228
- this.dispatchMessage(runid, `Finished external process with code ${code}`);
228
+ this.dispatchMessage(runid, `DBGM-00282 Finished external process with code ${code}`);
229
229
  socket.emit(`runner-done-${runid}`, code);
230
230
  if (onFinished) {
231
231
  onFinished();
@@ -233,7 +233,7 @@ module.exports = {
233
233
  this.opened = this.opened.filter(x => x.runid != runid);
234
234
  });
235
235
  subprocess.on('spawn', () => {
236
- this.dispatchMessage(runid, `Started external process ${command}`);
236
+ this.dispatchMessage(runid, `DBGM-00283 Started external process ${command}`);
237
237
  });
238
238
  subprocess.on('error', error => {
239
239
  console.log('... ERROR subprocess', error);
@@ -279,7 +279,7 @@ module.exports = {
279
279
  if (script.type == 'json') {
280
280
  if (!platformInfo.isElectron) {
281
281
  if (!checkSecureDirectoriesInScript(script)) {
282
- return { errorMessage: 'Unallowed directories in script' };
282
+ return { errorMessage: 'DBGM-00284 Unallowed directories in script' };
283
283
  }
284
284
  }
285
285
 
@@ -299,10 +299,10 @@ module.exports = {
299
299
  action: 'script',
300
300
  severity: 'warn',
301
301
  detail: script,
302
- message: 'Scripts are not allowed',
302
+ message: 'DBGM-00285 Scripts are not allowed',
303
303
  });
304
304
 
305
- return { errorMessage: 'Shell scripting is not allowed' };
305
+ return { errorMessage: 'DBGM-00286 Shell scripting is not allowed' };
306
306
  }
307
307
 
308
308
  sendToAuditLog(req, {
@@ -312,7 +312,7 @@ module.exports = {
312
312
  action: 'script',
313
313
  severity: 'info',
314
314
  detail: script,
315
- message: 'Running JS script',
315
+ message: 'DBGM-00287 Running JS script',
316
316
  });
317
317
 
318
318
  return this.startCore(runid, scriptTemplate(script, false));
@@ -327,7 +327,7 @@ module.exports = {
327
327
  async cancel({ runid }) {
328
328
  const runner = this.opened.find(x => x.runid == runid);
329
329
  if (!runner) {
330
- throw new Error('Invalid runner');
330
+ throw new Error('DBGM-00288 Invalid runner');
331
331
  }
332
332
  runner.subprocess.kill();
333
333
  return { state: 'ok' };
@@ -353,7 +353,7 @@ module.exports = {
353
353
  async loadReader({ functionName, props }) {
354
354
  if (!platformInfo.isElectron) {
355
355
  if (props?.fileName && !checkSecureDirectories(props.fileName)) {
356
- return { errorMessage: 'Unallowed file' };
356
+ return { errorMessage: 'DBGM-00289 Unallowed file' };
357
357
  }
358
358
  }
359
359
  const prefix = extractShellApiPlugins(functionName)
@@ -371,7 +371,7 @@ module.exports = {
371
371
  scriptResult_meta: true,
372
372
  async scriptResult({ script }) {
373
373
  if (script.type != 'json') {
374
- return { errorMessage: 'Only JSON scripts are allowed' };
374
+ return { errorMessage: 'DBGM-00290 Only JSON scripts are allowed' };
375
375
  }
376
376
 
377
377
  const promise = new Promise(async (resolve, reject) => {