|
| 1 | +import { mkdtempSync, rmSync } from 'node:fs'; |
| 2 | +import { createRequire } from 'node:module'; |
| 3 | +import os from 'node:os'; |
| 4 | +import path from 'node:path'; |
| 5 | +import { fileURLToPath, pathToFileURL } from 'node:url'; |
| 6 | + |
| 7 | +const currentDir = path.dirname(fileURLToPath(import.meta.url)); |
| 8 | +const applicationDir = path.resolve(currentDir, '../application'); |
| 9 | + |
| 10 | +// resolves to the BUILT package (adminforth/dist) the test application runs on; |
| 11 | +// rebuild it (`npx tsc` in adminforth/) after editing adminforth sources or the assertions below test stale code |
| 12 | +const require = createRequire(import.meta.url); |
| 13 | +// jest's resolver does not know the `node:sqlite` builtin, so it is required directly |
| 14 | +const { DatabaseSync } = require('node:sqlite'); |
| 15 | +const adminforthEntry = require.resolve('adminforth', { paths: [applicationDir] }); |
| 16 | +const { default: AdminForth } = await import(pathToFileURL(adminforthEntry).href); |
| 17 | + |
| 18 | +const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'af-backend-only-filters-')); |
| 19 | +const dbPath = path.join(fixtureDir, 'db.sqlite'); |
| 20 | +const db = new DatabaseSync(dbPath); |
| 21 | +db.exec(` |
| 22 | + CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL, password_hash TEXT NOT NULL, last_ip TEXT NOT NULL); |
| 23 | + INSERT INTO users VALUES (1, 'a@example.test', 'hash-a', '10.0.0.1'); |
| 24 | + INSERT INTO users VALUES (2, 'b@example.test', 'hash-b', '10.0.0.2'); |
| 25 | + CREATE TABLE posts (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL); |
| 26 | + INSERT INTO posts VALUES (1, 1); |
| 27 | +`); |
| 28 | +db.close(); |
| 29 | + |
| 30 | +process.env.ADMINFORTH_SECRET ??= 'x'.repeat(64); |
| 31 | + |
| 32 | +delete (globalThis as any).adminforth; |
| 33 | +const app = new AdminForth({ |
| 34 | + baseUrl: '', |
| 35 | + auth: { |
| 36 | + usersResourceId: 'users', |
| 37 | + usernameField: 'email', |
| 38 | + passwordHashField: 'password_hash', |
| 39 | + }, |
| 40 | + dataSources: [{ id: 'sqlite', url: `sqlite://${dbPath}` }], |
| 41 | + resources: [ |
| 42 | + { |
| 43 | + resourceId: 'users', |
| 44 | + table: 'users', |
| 45 | + dataSource: 'sqlite', |
| 46 | + columns: [ |
| 47 | + { name: 'id', primaryKey: true }, |
| 48 | + { name: 'email' }, |
| 49 | + { name: 'password_hash', backendOnly: true }, |
| 50 | + // hidden by role, like PII which only some admins may read |
| 51 | + { name: 'last_ip', backendOnly: ({ adminUser }) => adminUser.dbUser.role !== 'superadmin' }, |
| 52 | + ], |
| 53 | + hooks: { |
| 54 | + list: { |
| 55 | + // server code may still filter by hidden columns |
| 56 | + beforeDatasourceRequest: async ({ query }) => { |
| 57 | + if (query.hookFilter) { |
| 58 | + query.filters.push({ field: 'password_hash', operator: 'eq', value: 'hash-b' }); |
| 59 | + } |
| 60 | + return { ok: true }; |
| 61 | + }, |
| 62 | + }, |
| 63 | + }, |
| 64 | + }, |
| 65 | + { |
| 66 | + resourceId: 'posts', |
| 67 | + table: 'posts', |
| 68 | + dataSource: 'sqlite', |
| 69 | + columns: [ |
| 70 | + { name: 'id', primaryKey: true }, |
| 71 | + { name: 'user_id', foreignResource: { resourceId: 'users' } }, |
| 72 | + ], |
| 73 | + }, |
| 74 | + ], |
| 75 | + menu: [{ label: 'Users', resourceId: 'users' }], |
| 76 | +}); |
| 77 | +await app.discoverDatabases(); |
| 78 | + |
| 79 | +const endpoints: any[] = []; |
| 80 | +app.restApi.registerEndpoints({ endpoint: (config: any) => endpoints.push(config) }); |
| 81 | + |
| 82 | +afterAll(() => { |
| 83 | + rmSync(fixtureDir, { recursive: true, force: true }); |
| 84 | +}); |
| 85 | + |
| 86 | +function call(endpointPath: string, body: Record<string, unknown>, role = 'admin') { |
| 87 | + const { handler } = endpoints.find((endpoint) => endpoint.path === endpointPath); |
| 88 | + return handler({ |
| 89 | + body, |
| 90 | + adminUser: { pk: '1', username: 'a@example.test', dbUser: { role } }, |
| 91 | + headers: {}, |
| 92 | + query: {}, |
| 93 | + cookies: {}, |
| 94 | + requestUrl: endpointPath, |
| 95 | + abortSignal: new AbortController().signal, |
| 96 | + }); |
| 97 | +} |
| 98 | + |
| 99 | +const listUsers = (filters: unknown, extra: Record<string, unknown> = {}, role?: string) => |
| 100 | + call('/get_resource_data', { resourceId: 'users', source: 'list', limit: 10, offset: 0, sort: [], filters, ...extra }, role); |
| 101 | + |
| 102 | +const passwordHashFilter = { field: 'password_hash', operator: 'ilike', value: 'hash-a%' }; |
| 103 | +const passwordHashError = { error: 'Filter: column "password_hash" cannot be used (backendOnly is true).' }; |
| 104 | + |
| 105 | +describe('filters on backendOnly columns', () => { |
| 106 | + it.each([ |
| 107 | + ['top level', [passwordHashFilter]], |
| 108 | + ['single filter object', passwordHashFilter], |
| 109 | + ['nested in or', { operator: 'and', subFilters: [{ operator: 'or', subFilters: [{ field: 'email', operator: 'eq', value: 'x' }, passwordHashFilter] }] }], |
| 110 | + ['compared as rightField', [{ field: 'email', operator: 'eq', rightField: 'password_hash' }]], |
| 111 | + ])('get_resource_data rejects them %s', async (_, filters) => { |
| 112 | + expect(await listUsers(filters)).toEqual(passwordHashError); |
| 113 | + }); |
| 114 | + |
| 115 | + it('get_resource_data rejects them for show source', async () => { |
| 116 | + const result = await call('/get_resource_data', { |
| 117 | + resourceId: 'users', source: 'show', limit: 1, offset: 0, filters: [{ field: 'id', operator: 'eq', value: 1 }, passwordHashFilter], |
| 118 | + }); |
| 119 | + expect(result).toEqual(passwordHashError); |
| 120 | + }); |
| 121 | + |
| 122 | + it('get_resource_data keeps filters on readable columns', async () => { |
| 123 | + const result = await listUsers([{ field: 'email', operator: 'eq', value: 'b@example.test' }]); |
| 124 | + expect(result.data).toEqual([expect.objectContaining({ id: 2, email: 'b@example.test' })]); |
| 125 | + }); |
| 126 | + |
| 127 | + it('get_resource_data resolves role based backendOnly per user', async () => { |
| 128 | + const lastIpFilter = [{ field: 'last_ip', operator: 'eq', value: '10.0.0.2' }]; |
| 129 | + expect(await listUsers(lastIpFilter)).toEqual({ error: 'Filter: column "last_ip" cannot be used (backendOnly is true).' }); |
| 130 | + |
| 131 | + const result = await listUsers(lastIpFilter, {}, 'superadmin'); |
| 132 | + expect(result.data).toEqual([expect.objectContaining({ id: 2, last_ip: '10.0.0.2' })]); |
| 133 | + }); |
| 134 | + |
| 135 | + it('get_resource_data applies backendOnly filters added by hooks', async () => { |
| 136 | + const result = await listUsers([], { hookFilter: true }); |
| 137 | + expect(result.data).toEqual([expect.objectContaining({ id: 2 })]); |
| 138 | + expect(result.data[0]).not.toHaveProperty('password_hash'); |
| 139 | + }); |
| 140 | + |
| 141 | + it('get_resource_foreign_data rejects them on the target resource', async () => { |
| 142 | + const result = await call('/get_resource_foreign_data', { |
| 143 | + resourceId: 'posts', column: 'user_id', limit: 10, offset: 0, filters: [passwordHashFilter], |
| 144 | + }); |
| 145 | + expect(result).toEqual(passwordHashError); |
| 146 | + }); |
| 147 | + |
| 148 | + it('aggregate rejects them', async () => { |
| 149 | + const result = await call('/aggregate', { |
| 150 | + resourceId: 'users', aggregations: { total: { operation: 'count' } }, filters: [passwordHashFilter], |
| 151 | + }); |
| 152 | + expect(result).toEqual(passwordHashError); |
| 153 | + }); |
| 154 | +}); |
0 commit comments