@proteinjs/user 1.20.2 → 1.22.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.
Files changed (39) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/generated/index.js +1 -1
  3. package/dist/generated/index.js.map +1 -1
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +1 -0
  7. package/dist/index.js.map +1 -1
  8. package/dist/src/NoPrincipalError.d.ts +27 -0
  9. package/dist/src/NoPrincipalError.d.ts.map +1 -0
  10. package/dist/src/NoPrincipalError.js +67 -0
  11. package/dist/src/NoPrincipalError.js.map +1 -0
  12. package/dist/src/SharedRecord.d.ts.map +1 -1
  13. package/dist/src/SharedRecord.js +25 -6
  14. package/dist/src/SharedRecord.js.map +1 -1
  15. package/dist/src/tables/RoleGrantEventTable.d.ts +2 -0
  16. package/dist/src/tables/RoleGrantEventTable.d.ts.map +1 -1
  17. package/dist/src/tables/RoleGrantEventTable.js +2 -0
  18. package/dist/src/tables/RoleGrantEventTable.js.map +1 -1
  19. package/dist/src/tables/UserStatusEventTable.d.ts +2 -0
  20. package/dist/src/tables/UserStatusEventTable.d.ts.map +1 -1
  21. package/dist/src/tables/UserStatusEventTable.js +2 -0
  22. package/dist/src/tables/UserStatusEventTable.js.map +1 -1
  23. package/dist/test/SharedRecordNoPrincipal.test.d.ts +28 -0
  24. package/dist/test/SharedRecordNoPrincipal.test.d.ts.map +1 -0
  25. package/dist/test/SharedRecordNoPrincipal.test.js +332 -0
  26. package/dist/test/SharedRecordNoPrincipal.test.js.map +1 -0
  27. package/dist/test/auditTrailsDurable.test.d.ts +2 -0
  28. package/dist/test/auditTrailsDurable.test.d.ts.map +1 -0
  29. package/dist/test/auditTrailsDurable.test.js +47 -0
  30. package/dist/test/auditTrailsDurable.test.js.map +1 -0
  31. package/generated/index.ts +1 -1
  32. package/index.ts +1 -0
  33. package/package.json +4 -4
  34. package/src/NoPrincipalError.ts +52 -0
  35. package/src/SharedRecord.ts +30 -6
  36. package/src/tables/RoleGrantEventTable.ts +2 -0
  37. package/src/tables/UserStatusEventTable.ts +2 -0
  38. package/test/SharedRecordNoPrincipal.test.ts +206 -0
  39. package/test/auditTrailsDurable.test.ts +46 -0
@@ -0,0 +1,206 @@
1
+ import moment from 'moment';
2
+ import { Db, DbDriver, Reference, StringColumn, Table } from '@proteinjs/db';
3
+ import { KnexDriver } from '@proteinjs/db-driver-knex';
4
+ import { Session, SessionData, SessionDataStorage } from '@proteinjs/server-api';
5
+ import { SourceRepository } from '@proteinjs/reflection';
6
+ import { NoPrincipalError } from '../src/NoPrincipalError';
7
+ import {
8
+ getSharedDb,
9
+ getSharedDbAsSystem,
10
+ setSkipAccessGrants,
11
+ SharedRecord,
12
+ withSharedRecordColumns,
13
+ } from '../src/SharedRecord';
14
+ import { AccessGrantTable } from '../src/tables/AccessGrantTable';
15
+ import { tables } from '../src/tables/tables';
16
+ import { User } from '../src/tables/UserTable';
17
+ import { UserRepo } from '../src/UserRepo';
18
+
19
+ /**
20
+ * A grant-scoped operation on a shared table with NO principal — access grants enforced, no session
21
+ * user in the context (a background executor, a boot- or deploy-time migration, a socket event
22
+ * callback) — refuses AT THE SOURCE with `NoPrincipalError`: the table, the operation and the first
23
+ * stack frame outside the libraries on one line, instead of the query builder's opaque `Must not pass
24
+ * in undefined for value in condition … principal`. With a session user, or with grants skipped, the
25
+ * operation is unchanged: the rows come back.
26
+ */
27
+ export interface NoPrincipalItem extends SharedRecord {
28
+ name: string;
29
+ }
30
+
31
+ export class NoPrincipalItemTable extends Table<NoPrincipalItem> {
32
+ name = 'user_test_no_principal_item';
33
+ // Public doors: the subject under test is the shared-record principal requirement, not the door.
34
+ auth: Table<NoPrincipalItem>['auth'] = {
35
+ db: { all: 'public' },
36
+ service: { all: 'public' },
37
+ };
38
+ columns = withSharedRecordColumns<NoPrincipalItem>({
39
+ name: new StringColumn('name'),
40
+ });
41
+ }
42
+
43
+ class DbDriverFactory {
44
+ constructor(private dbDriver: DbDriver) {}
45
+
46
+ getDbDriver() {
47
+ return this.dbDriver;
48
+ }
49
+ }
50
+
51
+ class TestSessionDataStorage implements SessionDataStorage {
52
+ environment = 'node' as 'node';
53
+ static SESSION_DATA: { [id: string]: SessionData } = {};
54
+
55
+ setData(data: SessionData) {
56
+ TestSessionDataStorage.SESSION_DATA['sessionData'] = data;
57
+ }
58
+
59
+ getData(): SessionData {
60
+ return TestSessionDataStorage.SESSION_DATA['sessionData'];
61
+ }
62
+ }
63
+
64
+ const owner: User = {
65
+ name: 'Owner',
66
+ email: 'owner',
67
+ password: 'test',
68
+ emailVerified: false,
69
+ roles: [],
70
+ created: moment(),
71
+ updated: moment(),
72
+ id: 'owner',
73
+ };
74
+
75
+ const dbDriver = new KnexDriver({
76
+ host: 'localhost',
77
+ user: 'root',
78
+ password: '',
79
+ dbName: 'test',
80
+ });
81
+ const userRepo = new UserRepo();
82
+ const itemTable = new NoPrincipalItemTable();
83
+
84
+ const dropTable = async (table: Table<any>) => {
85
+ if (await dbDriver.getKnex().schema.withSchema(dbDriver.getDbName()).hasTable(table.name)) {
86
+ await dbDriver.getKnex().schema.withSchema(dbDriver.getDbName()).dropTable(table.name);
87
+ }
88
+ };
89
+
90
+ const noSessionUser = () => userRepo.setUser(undefined as unknown as User);
91
+
92
+ /** The NoPrincipalError `operation` rejects with — the rows, if it resolved, are the failure. */
93
+ async function thrownBy(operation: Promise<unknown>): Promise<NoPrincipalError> {
94
+ let result: unknown;
95
+ try {
96
+ result = await operation;
97
+ } catch (error) {
98
+ if (error instanceof NoPrincipalError) {
99
+ return error;
100
+ }
101
+ throw new Error(`expected NoPrincipalError, got ${(error as Error).constructor.name}: ${(error as Error).message}`);
102
+ }
103
+ throw new Error(`expected NoPrincipalError, the operation resolved with ${JSON.stringify(result)}`);
104
+ }
105
+
106
+ describe('SharedRecord — a grant-scoped operation with no principal refuses by name', () => {
107
+ let getDefaultDbDriver: jest.SpyInstance;
108
+
109
+ beforeAll(async () => {
110
+ (SourceRepository.get() as any).objectCache['@proteinjs/db/DefaultDbDriverFactory'] = [
111
+ new DbDriverFactory(dbDriver),
112
+ ];
113
+ (SourceRepository.get() as any).objectCache['@proteinjs/server-api/SessionDataStorage'] = [
114
+ new TestSessionDataStorage(),
115
+ ];
116
+ (SourceRepository.get() as any).objectCache['@proteinjs/db/Table'] = [
117
+ tables.AccessGrant,
118
+ itemTable as Table<NoPrincipalItem>,
119
+ ];
120
+ (SourceRepository.get() as any).objectCache['@proteinjs/user-auth/AuthenticatedUserRepo'] = [userRepo];
121
+ Session.setData({ sessionId: 'test-session', user: 'guest', data: {} });
122
+ if (dbDriver.start) {
123
+ await dbDriver.start();
124
+ }
125
+ getDefaultDbDriver = jest.spyOn(Db, 'getDefaultDbDriver').mockImplementation(() => dbDriver);
126
+ });
127
+
128
+ beforeEach(async () => {
129
+ setSkipAccessGrants(false);
130
+ await dbDriver.getTableManager().loadTable(itemTable);
131
+ await dbDriver.getTableManager().loadTable(tables.AccessGrant);
132
+ });
133
+
134
+ afterEach(async () => {
135
+ await dropTable(itemTable);
136
+ await dropTable(new AccessGrantTable());
137
+ });
138
+
139
+ afterAll(async () => {
140
+ setSkipAccessGrants(false);
141
+ getDefaultDbDriver.mockRestore();
142
+ if (dbDriver.stop) {
143
+ await dbDriver.stop();
144
+ }
145
+ });
146
+
147
+ /** A scope root the owner created with grants enforced — its owner grant conferred by the insert. */
148
+ async function ownersItem(): Promise<NoPrincipalItem> {
149
+ userRepo.setUser(owner);
150
+ return await getSharedDb().insert(itemTable, { name: 'the owner’s item' });
151
+ }
152
+
153
+ it('with grants enforced and no session user, a read throws NoPrincipalError naming the table, the operation and this file', async () => {
154
+ await ownersItem();
155
+ noSessionUser();
156
+
157
+ const error = await thrownBy(getSharedDb().query(itemTable, {}));
158
+
159
+ expect({ table: error.table, operation: error.operation }).toEqual({ table: itemTable.name, operation: 'read' });
160
+ expect(error.frame).toContain('SharedRecordNoPrincipal.test.ts');
161
+ expect(error.message.split('\n')).toHaveLength(1);
162
+ expect(error.message).toBe(
163
+ `${itemTable.name}: a read that needs a principal ran with none ` +
164
+ `(no session user in this async context, access grants enforced) — at ${error.frame}`
165
+ );
166
+ });
167
+
168
+ it('with grants enforced and no session user, a write and an attaching insert refuse the same way, naming their operations', async () => {
169
+ const item = await ownersItem();
170
+ noSessionUser();
171
+
172
+ const write = await thrownBy(getSharedDb().update(itemTable, { id: item.id, name: 'renamed with no principal' }));
173
+ expect({ table: write.table, operation: write.operation }).toEqual({ table: itemTable.name, operation: 'write' });
174
+
175
+ const attach = await thrownBy(
176
+ getSharedDb().insert(itemTable, {
177
+ name: 'attached with no principal',
178
+ permissionSource: new Reference(itemTable.name, item.id),
179
+ } as Omit<NoPrincipalItem, keyof SharedRecord>)
180
+ );
181
+ expect({ table: attach.table, operation: attach.operation }).toEqual({
182
+ table: itemTable.name,
183
+ operation: 'insert',
184
+ });
185
+
186
+ expect((await getSharedDbAsSystem().query(itemTable, {})).map((row) => row.name)).toEqual(['the owner’s item']);
187
+ });
188
+
189
+ it('with a session user the rows come back — unchanged', async () => {
190
+ const item = await ownersItem();
191
+
192
+ const rows = await getSharedDb().query(itemTable, {});
193
+
194
+ expect(rows.map((row) => row.id)).toEqual([item.id]);
195
+ });
196
+
197
+ it('with grants skipped and no session user the rows come back — unchanged', async () => {
198
+ const item = await ownersItem();
199
+ noSessionUser();
200
+ setSkipAccessGrants(true);
201
+
202
+ const rows = await getSharedDb().query(itemTable, {});
203
+
204
+ expect(rows.map((row) => row.id)).toEqual([item.id]);
205
+ });
206
+ });
@@ -0,0 +1,46 @@
1
+ import { UserAuth } from '@proteinjs/user-auth';
2
+ import { TableAuth, TableServiceAuth } from '@proteinjs/db';
3
+ import { tables } from '../src/tables/tables';
4
+
5
+ /**
6
+ * The audit trails keep their rows (`Table.durable`): no caller deletes a role grant or a status
7
+ * change — break-glass admin included — and the refusal is the 403 that names the table. The
8
+ * record surfaces read the same verdict (no delete act, no Delete on the form).
9
+ */
10
+
11
+ type UserAuthInternals = { userRepo?: { getUser: () => { email: string; roles: string[] } } };
12
+
13
+ const refusalOf = (act: () => unknown) => {
14
+ try {
15
+ act();
16
+ } catch (error: any) {
17
+ return { name: error?.name, status: error?.status, message: error?.message };
18
+ }
19
+ return undefined;
20
+ };
21
+
22
+ describe('the audit trails are durable', () => {
23
+ beforeEach(() => {
24
+ (UserAuth as unknown as UserAuthInternals).userRepo = {
25
+ getUser: () => ({ email: 'admin@test.local', roles: ['admin'] }),
26
+ };
27
+ });
28
+
29
+ afterEach(() => {
30
+ (UserAuth as unknown as UserAuthInternals).userRepo = undefined;
31
+ });
32
+
33
+ for (const table of [tables.RoleGrantEvent, tables.UserStatusEvent]) {
34
+ it(`${table.name}: every caller's delete is refused on both doors, admin included`, () => {
35
+ for (const api of ['db', 'service'] as const) {
36
+ expect(refusalOf(() => new TableAuth().canDelete(table, api))).toEqual({
37
+ name: 'ServiceRefusal',
38
+ status: 403,
39
+ message: `Table ${table.name} is durable: its rows are never deleted`,
40
+ });
41
+ expect(new TableAuth().canPerform(table, 'delete', api)).toBe(false);
42
+ }
43
+ expect(refusalOf(() => new TableServiceAuth().canAccess('delete', [table, { id: 'event-1' }]))?.status).toBe(403);
44
+ });
45
+ }
46
+ });