soul-cli 0.8.2 → 0.9.3

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 (57) hide show
  1. package/.env.sample +11 -2
  2. package/.github/dependabot.yml +9 -0
  3. package/.github/workflows/ci.yml +33 -0
  4. package/.github/workflows/npm-publish.yml +19 -6
  5. package/.husky/pre-commit +0 -3
  6. package/README.md +14 -7
  7. package/ROADMAP.md +154 -0
  8. package/docs/extensions-examples.md +96 -16
  9. package/docs/ws-examples.md +4 -0
  10. package/eslint.config.js +29 -0
  11. package/package.json +40 -20
  12. package/scripts/dev.sh +64 -0
  13. package/src/cli.test.js +128 -0
  14. package/src/config/index.js +10 -2
  15. package/src/config/index.test.js +120 -0
  16. package/src/controllers/auth/common.js +1 -16
  17. package/src/controllers/auth/common.test.js +23 -0
  18. package/src/controllers/auth/tables.js +1 -1
  19. package/src/controllers/auth/token.js +30 -7
  20. package/src/controllers/auth/user.js +20 -20
  21. package/src/controllers/auth/user.test.js +232 -0
  22. package/src/controllers/auth.test.js +445 -0
  23. package/src/controllers/rows.js +159 -112
  24. package/src/controllers/rows.test.js +88 -1
  25. package/src/controllers/tables.js +63 -17
  26. package/src/controllers/tables.test.js +185 -0
  27. package/src/db/index.test.js +21 -0
  28. package/src/extensions.js +105 -36
  29. package/src/extensions.test.js +340 -0
  30. package/src/index.js +29 -20
  31. package/src/index.test.js +118 -0
  32. package/src/middlewares/api.js +1 -1
  33. package/src/middlewares/api.test.js +29 -0
  34. package/src/middlewares/auth.js +11 -48
  35. package/src/middlewares/auth.test.js +105 -0
  36. package/src/middlewares/validation.test.js +60 -0
  37. package/src/schemas/index.js +3 -1
  38. package/src/schemas/rows.js +15 -5
  39. package/src/schemas/tables.js +28 -4
  40. package/src/server.js +83 -1
  41. package/src/services/authService.js +33 -3
  42. package/src/services/authService.test.js +115 -0
  43. package/src/services/rowService.js +25 -18
  44. package/src/services/rowService.test.js +153 -0
  45. package/src/services/tableService.js +15 -17
  46. package/src/services/tableService.test.js +190 -0
  47. package/src/swagger/swagger.json +4 -7
  48. package/src/utils/index.js +25 -2
  49. package/src/utils/index.test.js +135 -0
  50. package/src/utils/logger.js +15 -0
  51. package/src/utils/sql.js +112 -0
  52. package/src/utils/sql.test.js +115 -0
  53. package/src/websocket.js +46 -8
  54. package/src/websocket.test.js +121 -0
  55. package/.eslintignore +0 -2
  56. package/.eslintrc.js +0 -24
  57. package/src/middlewares/logger.js +0 -13
@@ -0,0 +1,340 @@
1
+ const fs = require('fs');
2
+ const os = require('os');
3
+ const path = require('path');
4
+ const express = require('express');
5
+ const cookieParser = require('cookie-parser');
6
+ const supertest = require('supertest');
7
+
8
+ // mirrors the real app's middleware setup closely enough for these tests
9
+ // -- auth-wrapped extension routes read req.cookies, which only exists
10
+ // with cookie-parser applied.
11
+ const createApp = () => express().use(cookieParser());
12
+
13
+ describe('setupExtensions', () => {
14
+ let extensionsDir;
15
+
16
+ afterEach(() => {
17
+ if (extensionsDir) {
18
+ fs.rmSync(extensionsDir, { recursive: true, force: true });
19
+ extensionsDir = undefined;
20
+ }
21
+ jest.dontMock('./config');
22
+ jest.resetModules();
23
+ });
24
+
25
+ const loadWithExtensionsDir = (files) => {
26
+ extensionsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'soul-ext-'));
27
+ Object.entries(files).forEach(([filename, content]) => {
28
+ fs.writeFileSync(path.join(extensionsDir, filename), content);
29
+ });
30
+
31
+ jest.resetModules();
32
+ jest.doMock('./config', () => ({
33
+ ...jest.requireActual('./config'),
34
+ extensions: { path: extensionsDir },
35
+ }));
36
+
37
+ return require('./extensions').setupExtensions;
38
+ };
39
+
40
+ it('does nothing (just logs) when no extensions path is configured', async () => {
41
+ jest.resetModules();
42
+ jest.doMock('./config', () => ({
43
+ ...jest.requireActual('./config'),
44
+ extensions: { path: null },
45
+ }));
46
+ const { setupExtensions } = require('./extensions');
47
+ const logger = require('./utils/logger');
48
+ const infoSpy = jest.spyOn(logger, 'info').mockImplementation(() => {});
49
+
50
+ const app = createApp();
51
+ await setupExtensions(app, {});
52
+
53
+ expect(infoSpy).toHaveBeenCalledWith(
54
+ expect.stringContaining('No extensions directory'),
55
+ );
56
+ infoSpy.mockRestore();
57
+ });
58
+
59
+ it('registers GET/POST/PUT/DELETE/PATCH routes, each with db access', async () => {
60
+ const setupExtensions = loadWithExtensionsDir({
61
+ 'api.js': `
62
+ module.exports = {
63
+ getRoute: {
64
+ method: 'GET',
65
+ path: '/ext/get',
66
+ handler: (req, res, db) => res.json({ method: 'GET', hasDb: !!db }),
67
+ },
68
+ postRoute: {
69
+ method: 'POST',
70
+ path: '/ext/post',
71
+ handler: (req, res, db) => res.json({ method: 'POST', hasDb: !!db }),
72
+ },
73
+ putRoute: {
74
+ method: 'PUT',
75
+ path: '/ext/put',
76
+ handler: (req, res, db) => res.json({ method: 'PUT', hasDb: !!db }),
77
+ },
78
+ deleteRoute: {
79
+ method: 'DELETE',
80
+ path: '/ext/delete',
81
+ handler: (req, res, db) => res.json({ method: 'DELETE', hasDb: !!db }),
82
+ },
83
+ patchRoute: {
84
+ method: 'PATCH',
85
+ path: '/ext/patch',
86
+ handler: (req, res, db) => res.json({ method: 'PATCH', hasDb: !!db }),
87
+ },
88
+ };
89
+ `,
90
+ });
91
+
92
+ const app = createApp();
93
+ const fakeDb = { marker: 'the-real-db' };
94
+ await setupExtensions(app, fakeDb);
95
+
96
+ const agent = supertest(app);
97
+
98
+ expect((await agent.get('/ext/get')).body).toEqual({
99
+ method: 'GET',
100
+ hasDb: true,
101
+ });
102
+ expect((await agent.post('/ext/post')).body).toEqual({
103
+ method: 'POST',
104
+ hasDb: true,
105
+ });
106
+ expect((await agent.put('/ext/put')).body).toEqual({
107
+ method: 'PUT',
108
+ hasDb: true,
109
+ });
110
+ expect((await agent.delete('/ext/delete')).body).toEqual({
111
+ method: 'DELETE',
112
+ hasDb: true,
113
+ });
114
+ // PATCH used to be silently unsupported -- it's now handled generically
115
+ // like any other method Express itself supports.
116
+ expect((await agent.patch('/ext/patch')).body).toEqual({
117
+ method: 'PATCH',
118
+ hasDb: true,
119
+ });
120
+ });
121
+
122
+ it('logs a warning and skips a route with a genuinely unsupported method', async () => {
123
+ const setupExtensions = loadWithExtensionsDir({
124
+ 'api.js': `
125
+ module.exports = {
126
+ bogus: {
127
+ method: 'FOOBAR',
128
+ path: '/ext/bogus',
129
+ handler: (req, res) => res.json({ ok: true }),
130
+ },
131
+ };
132
+ `,
133
+ });
134
+ const logger = require('./utils/logger');
135
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => {});
136
+
137
+ const app = createApp();
138
+ await setupExtensions(app, {});
139
+
140
+ expect(warnSpy).toHaveBeenCalledWith(
141
+ expect.stringContaining("unsupported method 'FOOBAR'"),
142
+ );
143
+ warnSpy.mockRestore();
144
+ });
145
+
146
+ it('merges routes from every .js file in the extensions directory, ignoring non-.js files', async () => {
147
+ const setupExtensions = loadWithExtensionsDir({
148
+ 'users.js': `
149
+ module.exports = {
150
+ fromUsers: {
151
+ method: 'GET',
152
+ path: '/ext/from-users-file',
153
+ handler: (req, res) => res.json({ file: 'users.js' }),
154
+ },
155
+ };
156
+ `,
157
+ 'reports.js': `
158
+ module.exports = {
159
+ fromReports: {
160
+ method: 'GET',
161
+ path: '/ext/from-reports-file',
162
+ handler: (req, res) => res.json({ file: 'reports.js' }),
163
+ },
164
+ };
165
+ `,
166
+ 'readme.md': '# not an extension, should be ignored',
167
+ });
168
+
169
+ const app = createApp();
170
+ await setupExtensions(app, {});
171
+ const agent = supertest(app);
172
+
173
+ expect((await agent.get('/ext/from-users-file')).body).toEqual({
174
+ file: 'users.js',
175
+ });
176
+ expect((await agent.get('/ext/from-reports-file')).body).toEqual({
177
+ file: 'reports.js',
178
+ });
179
+ });
180
+
181
+ describe('auth-wrapped extension routes', () => {
182
+ let generateToken;
183
+ let realConfig;
184
+
185
+ beforeAll(() => {
186
+ // ensure the default tables/role exist for the table-scoped
187
+ // permission test below, idempotently safe to call regardless of
188
+ // what other test files have already done against the shared db.
189
+ require('./index');
190
+ generateToken = require('./utils').generateToken;
191
+ realConfig = require('./config');
192
+ });
193
+
194
+ it('auth: true rejects a request with no access token', async () => {
195
+ const setupExtensions = loadWithExtensionsDir({
196
+ 'api.js': `
197
+ module.exports = {
198
+ protectedRoute: {
199
+ method: 'GET',
200
+ path: '/ext/protected',
201
+ auth: true,
202
+ handler: (req, res) => res.json({ ok: true }),
203
+ },
204
+ };
205
+ `,
206
+ });
207
+ const app = createApp();
208
+ await setupExtensions(app, {});
209
+
210
+ const res = await supertest(app).get('/ext/protected');
211
+ expect(res.status).toBe(401);
212
+ });
213
+
214
+ it('auth: true allows any authenticated request', async () => {
215
+ const setupExtensions = loadWithExtensionsDir({
216
+ 'api.js': `
217
+ module.exports = {
218
+ protectedRoute: {
219
+ method: 'GET',
220
+ path: '/ext/protected',
221
+ auth: true,
222
+ handler: (req, res) => res.json({ ok: true }),
223
+ },
224
+ };
225
+ `,
226
+ });
227
+ const app = createApp();
228
+ await setupExtensions(app, {});
229
+
230
+ const token = await generateToken(
231
+ { username: 'ext-user', isSuperuser: false, roleIds: [1] },
232
+ realConfig.tokenSecret,
233
+ '1H',
234
+ );
235
+
236
+ const res = await supertest(app)
237
+ .get('/ext/protected')
238
+ .set('Cookie', [`accessToken=${token}`]);
239
+ expect(res.status).toBe(200);
240
+ });
241
+
242
+ it('auth: { superuserOnly: true } rejects a non-superuser', async () => {
243
+ const setupExtensions = loadWithExtensionsDir({
244
+ 'api.js': `
245
+ module.exports = {
246
+ adminRoute: {
247
+ method: 'GET',
248
+ path: '/ext/admin',
249
+ auth: { superuserOnly: true },
250
+ handler: (req, res) => res.json({ ok: true }),
251
+ },
252
+ };
253
+ `,
254
+ });
255
+ const app = createApp();
256
+ await setupExtensions(app, {});
257
+
258
+ const token = await generateToken(
259
+ { username: 'ext-user', isSuperuser: false, roleIds: [1] },
260
+ realConfig.tokenSecret,
261
+ '1H',
262
+ );
263
+
264
+ const res = await supertest(app)
265
+ .get('/ext/admin')
266
+ .set('Cookie', [`accessToken=${token}`]);
267
+ expect(res.status).toBe(403);
268
+ });
269
+
270
+ it('auth: { superuserOnly: true } allows a superuser', async () => {
271
+ const setupExtensions = loadWithExtensionsDir({
272
+ 'api.js': `
273
+ module.exports = {
274
+ adminRoute: {
275
+ method: 'GET',
276
+ path: '/ext/admin',
277
+ auth: { superuserOnly: true },
278
+ handler: (req, res) => res.json({ ok: true }),
279
+ },
280
+ };
281
+ `,
282
+ });
283
+ const app = createApp();
284
+ await setupExtensions(app, {});
285
+
286
+ const token = await generateToken(
287
+ { username: 'ext-admin', isSuperuser: true },
288
+ realConfig.tokenSecret,
289
+ '1H',
290
+ );
291
+
292
+ const res = await supertest(app)
293
+ .get('/ext/admin')
294
+ .set('Cookie', [`accessToken=${token}`]);
295
+ expect(res.status).toBe(200);
296
+ });
297
+
298
+ it('auth: { table } checks table permission for the request method', async () => {
299
+ const setupExtensions = loadWithExtensionsDir({
300
+ 'api.js': `
301
+ module.exports = {
302
+ readUsers: {
303
+ method: 'GET',
304
+ path: '/ext/users-search',
305
+ auth: { table: 'users' },
306
+ handler: (req, res) => res.json({ ok: true }),
307
+ },
308
+ deleteUsers: {
309
+ method: 'DELETE',
310
+ path: '/ext/users-purge',
311
+ auth: { table: 'users' },
312
+ handler: (req, res) => res.json({ ok: true }),
313
+ },
314
+ };
315
+ `,
316
+ });
317
+ const app = createApp();
318
+ await setupExtensions(app, {});
319
+
320
+ // the default role (role id 1) has read-only access to tables that
321
+ // existed when it was created -- see createDefaultTables().
322
+ const token = await generateToken(
323
+ { username: 'ext-reader', isSuperuser: false, roleIds: [1] },
324
+ realConfig.tokenSecret,
325
+ '1H',
326
+ );
327
+ const cookie = [`accessToken=${token}`];
328
+
329
+ const readRes = await supertest(app)
330
+ .get('/ext/users-search')
331
+ .set('Cookie', cookie);
332
+ expect(readRes.status).toBe(200);
333
+
334
+ const deleteRes = await supertest(app)
335
+ .delete('/ext/users-purge')
336
+ .set('Cookie', cookie);
337
+ expect(deleteRes.status).toBe(403);
338
+ });
339
+ });
340
+ });
package/src/index.js CHANGED
@@ -2,15 +2,16 @@
2
2
 
3
3
  const express = require('express');
4
4
  const bodyParser = require('body-parser');
5
- const winston = require('winston');
6
5
  const expressWinston = require('express-winston');
7
6
  const cors = require('cors');
7
+ const helmet = require('helmet');
8
8
  const rateLimit = require('express-rate-limit');
9
9
  const swaggerUi = require('swagger-ui-express');
10
10
  const cookieParser = require('cookie-parser');
11
11
 
12
12
  const config = require('./config/index');
13
13
  const db = require('./db/index');
14
+ const logger = require('./utils/logger');
14
15
 
15
16
  const rootRoutes = require('./routes/index');
16
17
  const tablesRoutes = require('./routes/tables');
@@ -22,31 +23,34 @@ const { setupExtensions } = require('./extensions');
22
23
  const {
23
24
  createDefaultTables,
24
25
  createInitialUser,
25
- removeRevokedRefreshTokens,
26
26
  checkAuthConfigs,
27
27
  } = require('./controllers/auth');
28
28
 
29
29
  const { runCLICommands } = require('./commands');
30
- const { authConstants } = require('./constants');
31
30
 
32
31
  const app = express();
33
32
 
34
33
  app.use(bodyParser.json());
35
34
  app.use(cookieParser());
35
+ app.use(helmet());
36
36
 
37
37
  // Activate wal mode
38
38
  db.exec('PRAGMA journal_mode = WAL');
39
39
 
40
40
  // Enable CORS
41
41
  let corsOrigin = config.cors.origin;
42
+ const isWildcardOrigin = corsOrigin.includes('*');
42
43
 
43
- if (corsOrigin.includes('*')) {
44
+ if (isWildcardOrigin) {
44
45
  corsOrigin = '*';
46
+ logger.warn(
47
+ "CORS_ORIGIN_WHITELIST includes '*' -- credentialed requests (cookies) will be rejected by browsers for a wildcard origin, so credentials are disabled. Set an explicit origin list to allow cookie-based auth cross-origin.",
48
+ );
45
49
  }
46
50
 
47
51
  const corsOptions = {
48
52
  origin: corsOrigin,
49
- credentials: true,
53
+ credentials: !isWildcardOrigin,
50
54
  allowedHeaders: ['Content-Type', 'Authorization'],
51
55
  };
52
56
 
@@ -56,16 +60,10 @@ app.use(cors(corsOptions));
56
60
  if (config.verbose !== null) {
57
61
  app.use(
58
62
  expressWinston.logger({
59
- transports: [new winston.transports.Console()],
60
- format: winston.format.combine(
61
- winston.format.colorize(),
62
-
63
- winston.format.json(),
64
- ),
63
+ winstonInstance: logger,
65
64
  meta: false,
66
65
  msg: 'HTTP {{req.method}} {{req.url}}',
67
66
  expressFormat: true,
68
-
69
67
  colorize: false,
70
68
  }),
71
69
  );
@@ -91,17 +89,11 @@ if (config.auth) {
91
89
  createDefaultTables();
92
90
  createInitialUser();
93
91
  } else {
94
- console.warn(
95
- 'Warning: Soul is running in open mode without authentication or authorization for API endpoints. Please be aware that your API endpoints will not be secure.',
92
+ logger.warn(
93
+ 'Soul is running in open mode without authentication or authorization for API endpoints. Please be aware that your API endpoints will not be secure.',
96
94
  );
97
95
  }
98
96
 
99
- // remove revoked refresh tokens every X days
100
- setInterval(
101
- removeRevokedRefreshTokens,
102
- authConstants.REVOKED_REFRESH_TOKENS_REMOVAL_TIME_RANGE,
103
- );
104
-
105
97
  // If the user has passed custom CLI commands run the command and exit to avoid running the server
106
98
  runCLICommands();
107
99
 
@@ -114,4 +106,21 @@ app.use('/api/auth', authRoutes);
114
106
 
115
107
  setupExtensions(app, db);
116
108
 
109
+ // Final error-handling middleware: catches errors passed via next(err) or
110
+ // thrown/rejected in async route handlers (Express 5 forwards these
111
+ // automatically). Logs full detail server-side and returns a sanitized
112
+ // message -- never the raw error/stack -- to the client.
113
+ // eslint-disable-next-line no-unused-vars
114
+ app.use((err, req, res, next) => {
115
+ logger.error(err.message, { stack: err.stack });
116
+
117
+ if (res.headersSent) {
118
+ return;
119
+ }
120
+
121
+ res.status(err.status || 500).json({
122
+ message: err.status ? err.message : 'Internal server error',
123
+ });
124
+ });
125
+
117
126
  module.exports = app;
@@ -0,0 +1,118 @@
1
+ const supertest = require('supertest');
2
+
3
+ describe('app bootstrap (src/index.js)', () => {
4
+ // config is a singleton fixed for the whole test run (AUTH=true, no rate
5
+ // limiting, non-wildcard CORS from .env or CI defaults) -- these branches
6
+ // depend on config values that differ per-scenario, so build a fresh app
7
+ // per test with a mocked config instead of relying on ambient env state
8
+ // (which would also make wildcard-CORS coverage depend on whether a local
9
+ // .env happens to be present).
10
+ const freshAppWith = (configOverrides) => {
11
+ jest.resetModules();
12
+ jest.doMock('./config/index', () => ({
13
+ ...jest.requireActual('./config/index'),
14
+ ...configOverrides,
15
+ }));
16
+ return require('./index');
17
+ };
18
+
19
+ afterEach(() => {
20
+ jest.dontMock('./config/index');
21
+ jest.resetModules();
22
+ });
23
+
24
+ it('returns a sanitized 500 (no stack trace) for an unexpected error, via the global error handler', async () => {
25
+ const app = require('./index');
26
+
27
+ // malformed JSON is rejected by body-parser before any route handler
28
+ // runs, so this exercises the global error middleware, not a
29
+ // controller's own try/catch.
30
+ const res = await supertest(app)
31
+ .post('/api/tables')
32
+ .set('Content-Type', 'application/json')
33
+ .send('{ not valid json');
34
+
35
+ expect(res.status).toBe(400);
36
+ // a real stack trace is multi-line, with frames like
37
+ // "at functionName (/path/to/file.js:12:34)" -- the parser's own
38
+ // one-line message (safe to show for a 4xx) shouldn't be confused
39
+ // with that.
40
+ expect(res.body.message).not.toMatch(/\n\s*at .+:\d+:\d+/);
41
+ expect(res.body).not.toHaveProperty('stack');
42
+ });
43
+
44
+ it('disables CORS credentials for a wildcard origin', async () => {
45
+ const app = freshAppWith({ cors: { origin: ['*'] } });
46
+
47
+ const res = await supertest(app)
48
+ .get('/api/health')
49
+ .set('Origin', 'http://example.com');
50
+
51
+ expect(res.headers['access-control-allow-origin']).toBe('*');
52
+ expect(res.headers['access-control-allow-credentials']).toBeUndefined();
53
+ });
54
+
55
+ it('enables CORS credentials for an explicit origin list', async () => {
56
+ const app = freshAppWith({
57
+ cors: { origin: ['http://trusted.example.com'] },
58
+ });
59
+
60
+ const res = await supertest(app)
61
+ .get('/api/health')
62
+ .set('Origin', 'http://trusted.example.com');
63
+
64
+ expect(res.headers['access-control-allow-origin']).toBe(
65
+ 'http://trusted.example.com',
66
+ );
67
+ expect(res.headers['access-control-allow-credentials']).toBe('true');
68
+ });
69
+
70
+ it('applies rate limiting when enabled', async () => {
71
+ const app = freshAppWith({
72
+ rateLimit: { enabled: true, windowMs: 60000, max: 2 },
73
+ });
74
+ const agent = supertest(app);
75
+
76
+ await agent.get('/api/health');
77
+ await agent.get('/api/health');
78
+ const limited = await agent.get('/api/health');
79
+
80
+ expect(limited.status).toBe(429);
81
+ });
82
+
83
+ it('warns and skips default-table/initial-user setup when auth is disabled', async () => {
84
+ jest.resetModules();
85
+ jest.doMock('./config/index', () => ({
86
+ ...jest.requireActual('./config/index'),
87
+ auth: false,
88
+ }));
89
+
90
+ // the warning fires synchronously while ./index loads, so the spy has
91
+ // to be attached (against this same fresh module registry) beforehand.
92
+ const logger = require('./utils/logger');
93
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => {});
94
+
95
+ require('./index');
96
+
97
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('open mode'));
98
+ warnSpy.mockRestore();
99
+ });
100
+
101
+ it('logs HTTP requests when verbose logging is enabled', async () => {
102
+ const app = freshAppWith({ verbose: 'console' });
103
+
104
+ const res = await supertest(app).get('/api/health');
105
+
106
+ expect(res.status).toBe(200);
107
+ });
108
+
109
+ it('does not rate limit when disabled', async () => {
110
+ const app = freshAppWith({ rateLimit: { enabled: false } });
111
+ const agent = supertest(app);
112
+
113
+ for (let i = 0; i < 5; i++) {
114
+ const res = await agent.get('/api/health');
115
+ expect(res.status).not.toBe(429);
116
+ }
117
+ });
118
+ });
@@ -56,7 +56,7 @@ const processRowRequest = async (req, res, next) => {
56
56
  if (validation.errorStatus) {
57
57
  return res.status(400).json({
58
58
  message: validation.message,
59
- error: validation.details,
59
+ error: validation.error,
60
60
  });
61
61
  }
62
62
  }
@@ -0,0 +1,29 @@
1
+ // config.auth is fixed to true for the whole test run (set via the npm test
2
+ // script), so the "AUTH is disabled but an auth-only table was requested"
3
+ // branch can only be exercised by mocking config directly. Other modules
4
+ // required transitively (e.g. src/db/index.js) still need a real-shaped
5
+ // config, so start from the actual module and only override `auth`.
6
+ jest.mock('../config', () => ({
7
+ ...jest.requireActual('../config'),
8
+ auth: false,
9
+ }));
10
+
11
+ const { processRowRequest } = require('./api');
12
+
13
+ describe('processRowRequest', () => {
14
+ it('returns 403 when an auth-endpoint table is requested with AUTH disabled', async () => {
15
+ const req = { params: { name: '_users' }, method: 'GET' };
16
+ const res = { status: jest.fn().mockReturnThis(), send: jest.fn() };
17
+ const next = jest.fn();
18
+
19
+ await processRowRequest(req, res, next);
20
+
21
+ expect(res.status).toHaveBeenCalledWith(403);
22
+ expect(res.send).toHaveBeenCalledWith(
23
+ expect.objectContaining({
24
+ message: expect.stringContaining('AUTH'),
25
+ }),
26
+ );
27
+ expect(next).not.toHaveBeenCalled();
28
+ });
29
+ });
@@ -1,5 +1,6 @@
1
1
  const config = require('../config');
2
- const { decodeToken, toBoolean } = require('../utils/index');
2
+ const { decodeToken } = require('../utils/index');
3
+ const logger = require('../utils/logger');
3
4
  const { apiConstants, responseMessages } = require('../constants');
4
5
  const { authService } = require('../services');
5
6
 
@@ -20,69 +21,31 @@ const hasAccess = async (req, res, next) => {
20
21
  config.tokenSecret,
21
22
  );
22
23
  req.user = payload;
23
- } catch (error) {
24
+ } catch {
25
+ // an invalid/expired access token is a routine client-side
26
+ // condition, not an unexpected server error -- not logged as one.
24
27
  return res
25
28
  .status(401)
26
29
  .send({ message: errorMessage.INVALID_ACCESS_TOKEN_ERROR });
27
30
  }
28
31
 
29
- // if the user is a super_user, allow access on the resource
30
- if (toBoolean(payload.isSuperuser)) {
31
- return next();
32
- }
33
-
34
32
  // if the endpoint is set to be accessed by any user regardless of there roles, then allow access
35
33
  if (apiConstants.universalAccessEndpoints.includes(originalURL)) {
36
34
  return next();
37
35
  }
38
36
 
39
- // if table_name is not passed from the router throw unauthorized error
40
- if (!tableName) {
41
- return res
42
- .status(403)
43
- .send({ message: errorMessage.NOT_AUTHORIZED_ERROR });
44
- }
45
-
46
- // if the user is not a super user, fetch the permission of the user from the DB
47
- const rolePermissions = authService.getPermissionByRoleIds({
48
- roleIds: payload.roleIds,
49
- });
50
-
51
- const resourcePermission = rolePermissions.filter(
52
- (row) => row.table_name === tableName,
53
- );
54
-
55
- if (resourcePermission.length <= 0) {
56
- return res
57
- .status(403)
58
- .send({ message: errorMessage.PERMISSION_NOT_DEFINED_ERROR });
37
+ if (authService.hasTablePermission({ payload, tableName, verb })) {
38
+ return next();
59
39
  }
60
40
 
61
- // If the user has permission on the table in at least in one of the roles then allow access on the table
62
- let hasPermission = false;
63
-
64
- resourcePermission.some((resource) => {
65
- const httpMethod =
66
- apiConstants.httpMethodDefinitions[verb].toLowerCase();
67
-
68
- if (toBoolean(resource[httpMethod])) {
69
- hasPermission = true;
70
- return true;
71
- }
72
- });
73
-
74
- if (hasPermission) {
75
- next();
76
- } else {
77
- return res
78
- .status(403)
79
- .send({ message: errorMessage.NOT_AUTHORIZED_ERROR });
80
- }
41
+ return res
42
+ .status(403)
43
+ .send({ message: errorMessage.NOT_AUTHORIZED_ERROR });
81
44
  } else {
82
45
  next();
83
46
  }
84
47
  } catch (error) {
85
- console.log(error);
48
+ logger.error(error.message, { stack: error.stack });
86
49
  res.status(401).send({ message: error.message });
87
50
  }
88
51
  };