@galadrim/galadmin 0.2.6 → 0.2.8

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.
@@ -359,12 +359,17 @@ export type AuthRole = {
359
359
  filters?: string;
360
360
  useArgon2?: boolean;
361
361
  };
362
+ export type TrustedUser = {
363
+ role: string;
364
+ userId?: string | number;
365
+ };
362
366
  export type Config = {
363
367
  enriched?: boolean;
364
368
  name: string;
365
369
  sessionSecret: string;
366
370
  useMysql2?: boolean;
367
- auth: {
371
+ trustedAuth?: (req: any) => TrustedUser | null | Promise<TrustedUser | null>;
372
+ auth?: {
368
373
  username: string;
369
374
  password: string;
370
375
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galadrim/galadmin",
3
- "version": "0.2.6",
3
+ "version": "0.2.8",
4
4
  "main": "dist/index.js",
5
5
  "scripts": {
6
6
  "test": "jest",
package/src/api.ts CHANGED
@@ -209,6 +209,21 @@ declare global {
209
209
  }
210
210
  }
211
211
 
212
+ // Columns of `view` the current role may not see (cf. the config middleware below).
213
+ export const hiddenColumnsOf = (view) => (view && view.__hiddenColumns) || [];
214
+
215
+ // Removes the hidden columns from a record before it is sent.
216
+ export const stripHiddenColumns = (view, record) => {
217
+ for (const name of hiddenColumnsOf(view)) delete record[name];
218
+ return record;
219
+ };
220
+
221
+ // Whether a write payload touches a hidden column.
222
+ export const touchesHiddenColumn = (view, data) =>
223
+ hiddenColumnsOf(view).some(
224
+ (name) => data && Object.prototype.hasOwnProperty.call(data, name),
225
+ );
226
+
212
227
  export default (db, config) => {
213
228
  const app = express();
214
229
 
@@ -243,14 +258,19 @@ export default (db, config) => {
243
258
  })
244
259
  .map((view) => {
245
260
  if (view.type === "table") {
261
+ const allowed = (column) =>
262
+ !column.roles ||
263
+ (req.session.user &&
264
+ column.roles.includes(req.session.user.role));
246
265
  return {
247
266
  ...view,
248
- columns: view.columns.filter(
249
- (column) =>
250
- !column.roles ||
251
- (req.session.user &&
252
- column.roles.includes(req.session.user.role)),
253
- ),
267
+ columns: view.columns.filter(allowed),
268
+ // SECURITY: a column's `roles` must hold server-side too. Rows are read with SELECT *, and
269
+ // writes take any column sent: the names of the columns this role may not see are kept
270
+ // here, stripped from every record sent back and refused in every write.
271
+ __hiddenColumns: view.columns
272
+ .filter((column) => !allowed(column))
273
+ .map((column) => column.name),
254
274
  };
255
275
  } else {
256
276
  return view;
@@ -564,6 +584,7 @@ export default (db, config) => {
564
584
  }
565
585
  }
566
586
  }
587
+ for (const record of records) stripHiddenColumns(view, record);
567
588
  res.send({
568
589
  records,
569
590
  input,
@@ -678,6 +699,9 @@ export default (db, config) => {
678
699
  }
679
700
  }
680
701
  }
702
+ if (columns.some((name) => hiddenColumnsOf(view).includes(name))) {
703
+ return res.sendStatus(403);
704
+ }
681
705
 
682
706
  let queryString;
683
707
  if (db.dbType === "POSTGRESQL") {
@@ -861,7 +885,7 @@ export default (db, config) => {
861
885
  await column.formatValue(record);
862
886
  }
863
887
  }
864
- res.send(record);
888
+ res.send(stripHiddenColumns(view, record));
865
889
  } else {
866
890
  res.sendStatus(404);
867
891
  }
@@ -872,6 +896,9 @@ export default (db, config) => {
872
896
  if (!areSafeColumnNames(req.body.data)) {
873
897
  return res.status(400).send({ error: "Invalid column name" });
874
898
  }
899
+ if (touchesHiddenColumn(view, req.body.data)) {
900
+ return res.sendStatus(403);
901
+ }
875
902
  for (let key in req.body.data) {
876
903
  if (
877
904
  req.body.data[key] == "NULL" ||
@@ -1150,6 +1177,9 @@ export default (db, config) => {
1150
1177
  const hasPanel =
1151
1178
  req.body.panelIndex !== undefined && req.body.panelIndex !== null;
1152
1179
  const panel = hasPanel ? view.recordViewPanels[req.body.panelIndex] : null;
1180
+ if (!hasPanel && touchesHiddenColumn(view, req.body.data)) {
1181
+ return res.sendStatus(403);
1182
+ }
1153
1183
  try {
1154
1184
  for (let key in req.body.data) {
1155
1185
  if (
package/src/index.ts CHANGED
@@ -65,6 +65,26 @@ export default (config: Config): any => {
65
65
  name: 'galadmin.sid'
66
66
  }));
67
67
 
68
+ // trustedAuth: the host app (e.g. behind its own SSO) says who the user is, on every request.
69
+ // galadmin then has no login of its own: /api/login is refused, config.auth and authRoles are unused.
70
+ if (config.trustedAuth) {
71
+ app.use(async (req, res, next) => {
72
+ try {
73
+ const user = await config.trustedAuth(req);
74
+ if (user) {
75
+ if (JSON.stringify(req.session.user) !== JSON.stringify(user)) {
76
+ req.session.user = user;
77
+ }
78
+ } else if (req.session.user) {
79
+ delete req.session.user;
80
+ }
81
+ next();
82
+ } catch (err) {
83
+ next(err);
84
+ }
85
+ });
86
+ }
87
+
68
88
  const passwordMatch = async (password: string, hash: string, useArgon2: boolean) => {
69
89
  if (password === hash || bcrypt.compareSync(password, hash)) {
70
90
  return true;
@@ -81,7 +101,10 @@ export default (config: Config): any => {
81
101
  }
82
102
 
83
103
  app.post('/api/login', async (req, res) => {
84
- if (req.body.username === config.auth.username && req.body.password === config.auth.password) {
104
+ if (config.trustedAuth) {
105
+ return res.send({ success: false })
106
+ }
107
+ if (config.auth && req.body.username === config.auth.username && req.body.password === config.auth.password) {
85
108
  req.session.user = { role: "root" }
86
109
  res.send({ success: true })
87
110
  } else if (config.authRoles) {
@@ -126,7 +149,7 @@ export default (config: Config): any => {
126
149
 
127
150
  app.use("/api", async (req, res, next) => {
128
151
  if (req.method === "OPTIONS" || req.session.user) {
129
- if (req.session?.user?.userId) {
152
+ if (req.session?.user?.userId && !config.trustedAuth) {
130
153
  // we check that the user still exists
131
154
  let stillExists = false;
132
155
  for (const authRole of config.authRoles) {
@@ -428,6 +428,11 @@ export type AuthRole = {
428
428
  useArgon2?: boolean;
429
429
  };
430
430
 
431
+ export type TrustedUser = {
432
+ role: string;
433
+ userId?: string | number;
434
+ };
435
+
431
436
  export type Config = {
432
437
  /** Ne pas renseigner !!! */
433
438
  enriched?: boolean;
@@ -440,8 +445,15 @@ export type Config = {
440
445
 
441
446
  useMysql2?: boolean;
442
447
 
448
+ /**
449
+ * Authentification déléguée à l'application hôte (par exemple derrière son SSO) : appelée à chaque
450
+ * requête, renvoie l'utilisateur (`role`, et `userId` pour la traçabilité) ou null. Quand elle est
451
+ * définie, galadmin n'a plus de login propre : `auth` et `authRoles` ne servent plus.
452
+ */
453
+ trustedAuth?: (req: any) => TrustedUser | null | Promise<TrustedUser | null>;
454
+
443
455
  /** Identifiants permettant d'accéder au back-office */
444
- auth: {
456
+ auth?: {
445
457
  /** Nom d'utilisateur */
446
458
  username: string;
447
459
 
@@ -0,0 +1,86 @@
1
+ import * as request from "supertest";
2
+ import { buildApiApp } from "./helpers/app";
3
+ import { FakeDb } from "./helpers/fakeDb";
4
+ import { baseConfig, fruitSchema, fruitView, schemaRow } from "./helpers/fixtures";
5
+
6
+ jest.mock("axios");
7
+
8
+ /**
9
+ * A column's `roles` must hold on the server, not only in the interface: rows are read with SELECT *, so a
10
+ * column hidden from a role must be stripped from what is sent back, and refused in writes.
11
+ */
12
+ describe("column roles enforced server-side", () => {
13
+ let db: FakeDb;
14
+ const row = { id: 1, fruitName: "Pomme", acidity: 3, secret: "s3cr3t" };
15
+ const config = () =>
16
+ baseConfig({
17
+ views: [
18
+ fruitView({
19
+ roles: ["root", "user"],
20
+ columns: [
21
+ { label: "Nom", name: "fruitName" },
22
+ { label: "Acidité", name: "acidity" },
23
+ { label: "Secret", name: "secret", roles: ["root"] },
24
+ ],
25
+ }),
26
+ ],
27
+ });
28
+
29
+ beforeEach(() => {
30
+ db = new FakeDb();
31
+ db.schemaRows = fruitSchema([schemaRow("fruits", "secret")]);
32
+ });
33
+
34
+ it("GET /api/record leaves the hidden column out for a role that may not see it", async () => {
35
+ db.queueRows([{ ...row }]);
36
+ const res = await request(buildApiApp(db, config(), { role: "user", userId: 7 }))
37
+ .get("/api/record")
38
+ .query({ viewIndex: 0, recordId: 1 })
39
+ .expect(200);
40
+ expect(res.body.fruitName).toBe("Pomme");
41
+ expect(res.body).not.toHaveProperty("secret");
42
+ });
43
+
44
+ it("GET /api/record keeps it for a role that may see it", async () => {
45
+ db.queueRows([{ ...row }]);
46
+ const res = await request(buildApiApp(db, config(), { role: "root", userId: 1 }))
47
+ .get("/api/record")
48
+ .query({ viewIndex: 0, recordId: 1 })
49
+ .expect(200);
50
+ expect(res.body.secret).toBe("s3cr3t");
51
+ });
52
+
53
+ it("POST /api/records leaves the hidden column out of every record", async () => {
54
+ db.defaultResult = { err: null, rows: [{ ...row, total: 1, count: 1 }] };
55
+ const res = await request(buildApiApp(db, config(), { role: "user", userId: 7 }))
56
+ .post("/api/records")
57
+ .send({ viewIndex: 0, page: 1, filters: [] })
58
+ .expect(200);
59
+ expect(res.body.records.length).toBeGreaterThan(0);
60
+ for (const record of res.body.records) expect(record).not.toHaveProperty("secret");
61
+ });
62
+
63
+ it("POST /api/updateRecord refuses to write the hidden column", async () => {
64
+ await request(buildApiApp(db, config(), { role: "user", userId: 7 }))
65
+ .post("/api/updateRecord")
66
+ .send({ viewIndex: 0, primaryValue: 1, data: { secret: "x" } })
67
+ .expect(403);
68
+ expect(db.dataQueries().length).toBe(0);
69
+ });
70
+
71
+ it("POST /api/updateRecord still writes the visible columns", async () => {
72
+ db.queueRows({ affectedRows: 1 });
73
+ await request(buildApiApp(db, config(), { role: "user", userId: 7 }))
74
+ .post("/api/updateRecord")
75
+ .send({ viewIndex: 0, primaryValue: 1, data: { fruitName: "Poire" } })
76
+ .expect((res) => expect(res.status).not.toBe(403));
77
+ });
78
+
79
+ it("POST /api/createRecord refuses to set the hidden column", async () => {
80
+ await request(buildApiApp(db, config(), { role: "user", userId: 7 }))
81
+ .post("/api/createRecord")
82
+ .send({ viewIndex: 0, data: { fruitName: "Kiwi", secret: "x" } })
83
+ .expect(403);
84
+ expect(db.dataQueries().length).toBe(0);
85
+ });
86
+ });
@@ -258,6 +258,55 @@ describe("index middleware (src/index.ts)", () => {
258
258
  });
259
259
  });
260
260
 
261
+ describe("trustedAuth", () => {
262
+ const trusted = (user: any) =>
263
+ mysqlConfig({ trustedAuth: jest.fn(async () => user) });
264
+
265
+ it("authenticates from the host app, without a galadmin login", async () => {
266
+ const { app } = buildAppWithDb(trusted({ role: "root", userId: 7 }), withSchema());
267
+ const auth = await request(app).get("/api/isAuthenticated").expect(200);
268
+ expect(auth.body).toEqual({ isAuthenticated: true });
269
+ });
270
+
271
+ it("refuses the api when the host app returns no user", async () => {
272
+ const { app } = buildAppWithDb(trusted(null), withSchema());
273
+ await request(app).get("/api/config").expect(401);
274
+ const auth = await request(app).get("/api/isAuthenticated").expect(200);
275
+ expect(auth.body).toEqual({ isAuthenticated: false });
276
+ });
277
+
278
+ it("refuses the password login, shared account included", async () => {
279
+ const { app } = buildAppWithDb(trusted(null), withSchema());
280
+ const res = await request(app)
281
+ .post("/api/login")
282
+ .send({ username: "admin", password: "admin-pass" })
283
+ .expect(200);
284
+ expect(res.body).toEqual({ success: false });
285
+ });
286
+
287
+ it("drops the access as soon as the host app stops vouching for the user", async () => {
288
+ let user: any = { role: "user", userId: 3 };
289
+ const config = mysqlConfig({ trustedAuth: jest.fn(async () => user) });
290
+ const { app } = buildAppWithDb(config, withSchema());
291
+ const agent = request.agent(app);
292
+ expect((await agent.get("/api/isAuthenticated")).body).toEqual({ isAuthenticated: true });
293
+ user = null;
294
+ expect((await agent.get("/api/isAuthenticated")).body).toEqual({ isAuthenticated: false });
295
+ });
296
+
297
+ it("never runs the authRoles re-check against the database", async () => {
298
+ const config = mysqlConfig({
299
+ trustedAuth: jest.fn(async () => ({ role: "editor", userId: 3 })),
300
+ authRoles: [
301
+ { role: "editor", table: "users", usernameField: "u", passwordField: "p", idField: "id" },
302
+ ],
303
+ });
304
+ const { app, instance } = buildAppWithDb(config, withSchema());
305
+ await request(app).get("/api/isAuthenticated").expect(200);
306
+ expect(instance.query.mock.calls.some(([sql]: any[]) => /FROM \?\? WHERE \?\? = \?/.test(sql))).toBe(false);
307
+ });
308
+ });
309
+
261
310
  describe("GET /api/isAuthenticated and /api/logout", () => {
262
311
  it("reports unauthenticated state before login", async () => {
263
312
  const { app } = buildAppWithDb(mysqlConfig(), withSchema(fruitSchema()));