@proteinjs/user-server 1.25.0 → 1.26.1

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.
@@ -0,0 +1,66 @@
1
+ import { Db, Migration, SourceRecordLoader, tables as dbTables } from '@proteinjs/db';
2
+ import { tables } from '@proteinjs/user';
3
+ import { Logger } from '@proteinjs/logger';
4
+
5
+ /**
6
+ * Retires the legacy `user.roles` text column's data. The cutover to the typed `role_list` array
7
+ * (BackfillUserRolesArray) left the old comma-text column physically present and undeclared, its
8
+ * cells intact on every pre-cutover row: a stored key that is also the property's name (`roles`),
9
+ * riding every read of the table. The row reader seats a cell by its declared column name alone
10
+ * (@proteinjs/db ≥ 1.55.0), so the cell is inert — but data no declared column owns has no
11
+ * business on the row. This NULLs it wherever the typed column already carries the roles, or the
12
+ * legacy cell holds nothing to carry (the empty string a pre-cutover signup wrote).
13
+ *
14
+ * Never a legacy value the backfill has not consumed: a row with legacy text and no `role_list`
15
+ * is left for BackfillUserRolesArray — this migration cannot run ahead of it by construction.
16
+ *
17
+ * Idempotent by shape: a NULLed cell no longer matches. Automated (the deploy-gated series); the
18
+ * column itself goes in a later `manual` migration (a destructive contraction), once every
19
+ * environment reads zero legacy cells. Raw SQL through the driver on both sides, as the backfill
20
+ * reads it: the column is undeclared, so the ORM neither reads nor writes it. A database whose
21
+ * user table never had the column (a fresh install) is a clean no-op.
22
+ */
23
+ export class RetireLegacyUserRolesColumn implements SourceRecordLoader<Migration> {
24
+ table = dbTables.Migration;
25
+ record = {
26
+ id: '2f6c0b9e-9c7a-4e0d-8f1b-5a3d7c2e9b41',
27
+ description: `Retire the legacy comma-text user.roles column's cells once role_list carries the roles`,
28
+ estimate: async () => {
29
+ if (!(await this.legacyColumnExists())) {
30
+ return { units: 0, unit: 'rows', note: 'no legacy roles column on the user table' };
31
+ }
32
+
33
+ const counted = (await Db.getDefaultDbDriver().runQuery(() => ({
34
+ sql: `SELECT COUNT(*) AS pending FROM ${tables.User.name} WHERE ${this.retirableCells()}`,
35
+ }))) as unknown as Array<{ pending: number | string }>;
36
+ return { units: Number(counted[0]?.pending ?? 0), unit: 'rows' };
37
+ },
38
+ run: async () => {
39
+ const logger = new Logger({ name: this.constructor.name });
40
+ if (!(await this.legacyColumnExists())) {
41
+ logger.info({ message: `No legacy roles column on ${tables.User.name}; nothing to retire` });
42
+ return { retired: 0 };
43
+ }
44
+
45
+ const retired = await Db.getDefaultDbDriver().runDml(() => ({
46
+ sql: `UPDATE ${tables.User.name} SET roles = NULL WHERE ${this.retirableCells()}`,
47
+ }));
48
+ logger.info({ message: `Retired legacy user roles cells`, obj: { retired } });
49
+ return { retired };
50
+ },
51
+ };
52
+
53
+ /** The cells this migration may NULL: a legacy value the typed column already carries, or nothing at all. */
54
+ private retirableCells(): string {
55
+ return `roles IS NOT NULL AND (role_list IS NOT NULL OR roles = '')`;
56
+ }
57
+
58
+ private async legacyColumnExists(): Promise<boolean> {
59
+ const legacyColumn = await Db.getDefaultDbDriver().runQuery(() => ({
60
+ sql:
61
+ `SELECT column_name FROM information_schema.columns ` +
62
+ `WHERE table_name = '${tables.User.name}' AND column_name = 'roles'`,
63
+ }));
64
+ return legacyColumn.length > 0;
65
+ }
66
+ }
@@ -6,9 +6,10 @@ import { Service } from '@proteinjs/service';
6
6
 
7
7
  /**
8
8
  * The ONE write path for user roles (the `user.roles` column is service-protected — generic
9
- * record writes cannot touch it). Grants and revokes are validated against the roles catalog and
10
- * audited: the role update and its `role_grant_event` row (actor, target, role, action; `created`
11
- * is the timestamp) commit in one transaction, so the trail cannot diverge from the grants.
9
+ * record writes cannot touch it). A grant is validated against the roles catalog; a revoke takes any
10
+ * string the record holds (a retired role stays removable here, see `changeRole`). Both are audited:
11
+ * the role update and its `role_grant_event` row (actor, target, role, action; `created` is the
12
+ * timestamp) commit in one transaction, so the trail cannot diverge from the grants.
12
13
  *
13
14
  * Break-glass roles are never granted through the service door — see `changeRole`; revoking one
14
15
  * stays allowed. The ONE break-glass grant in code is `bootstrapAdmin`, the dev first-admin door
@@ -133,8 +134,13 @@ export class Roles implements RolesService {
133
134
 
134
135
  private async changeRole(userId: string, role: string, action: 'grant' | 'revoke'): Promise<void> {
135
136
  const logger = new Logger({ name: `Roles.${action}Role` });
137
+ // The catalog gates what may be GRANTED. A revoke takes any string the record holds: a role a
138
+ // consumer retired (its catalog entry gone, its holders' rows untouched) must stay removable
139
+ // through this audited path, never only by a raw UPDATE — so the catalog is not consulted for
140
+ // a revoke, and a revoke of a string the record does not hold is the no-change early return
141
+ // below, as for any role.
136
142
  const entry = RolesCatalog.getEntry(role);
137
- if (!entry) {
143
+ if (!entry && action === 'grant') {
138
144
  throw new Error(`'${role}' is not a known role. Pick one from the roles catalog.`);
139
145
  }
140
146
 
@@ -143,7 +149,7 @@ export class Roles implements RolesService {
143
149
  // in Spanner Studio, by a human, on purpose (and, on a DEV server only, the first-admin door
144
150
  // `bootstrapAdmin`). Revoke stays open: de-escalation toward "held by nobody day-to-day"
145
151
  // should ride the audited path, not require database access.
146
- if (entry.breakGlass && action === 'grant') {
152
+ if (entry?.breakGlass && action === 'grant') {
147
153
  throw new Error(
148
154
  `'${role}' is a break-glass role — this service refuses to grant it. The only path to ` +
149
155
  `break-glass is a manual UPDATE on the user row in Spanner Studio. (Revoking it here ` +
@@ -155,7 +161,7 @@ export class Roles implements RolesService {
155
161
  // 'roles' permission carries — only an admin may hand them out. Server-side and fail-closed:
156
162
  // the service door admits 'roles' holders, so this check is what keeps a user-admin from
157
163
  // granting such a role. Revoke stays open — the break-glass de-escalation precedent above.
158
- if (entry.adminGrantOnly && action === 'grant' && !UserAuth.hasRole('admin')) {
164
+ if (entry?.adminGrantOnly && action === 'grant' && !UserAuth.hasRole('admin')) {
159
165
  throw new Error(
160
166
  `'${role}' can only be granted by an admin — the 'roles' grant does not cover it. ` +
161
167
  `(Revoking it here stays allowed.)`
@@ -4,18 +4,26 @@ import { SpannerEmulatorProvisioner, getDropTestTable } from '@proteinjs/db-driv
4
4
  import { SourceRepository } from '@proteinjs/reflection';
5
5
  import { tables } from '@proteinjs/user';
6
6
  import { BackfillUserRolesArray } from '../src/migrations/BackfillUserRolesArray';
7
+ import { RetireLegacyUserRolesColumn } from '../src/migrations/RetireLegacyUserRolesColumn';
7
8
 
8
9
  /**
9
- * The user.roles cutover migration against a real Spanner emulator, simulating a deployed
10
+ * The user.roles cutover migrations against a real Spanner emulator, simulating a deployed
10
11
  * database: the user table carries the NEW schema (role_list, added by schema sync) PLUS the
11
12
  * legacy comma-string `roles` column with pre-cutover data — exactly the state a deployment is
12
- * in when the migration runs.
13
+ * in when the migrations run. Every read below goes through the ORM: what the row reader makes
14
+ * of a row holding BOTH cells — the legacy `roles` (a word, an empty string, NULL) and the typed
15
+ * `role_list` — is the law this suite proves, not a comment's claim.
13
16
  *
14
17
  * Pinned outcomes:
15
18
  * - legacy comma strings land in role_list as normalized arrays (trim, drop empties, dedupe)
16
- * - empty/NULL legacy values stay untouched (no roles then, no roles now)
17
- * - rows already carrying role_list are never clobbered (idempotence / post-cutover grants win)
18
- * - a database that never had the legacy column (fresh install) is a clean no-op
19
+ * - empty/NULL legacy values stay untouched by the backfill (no roles then, no roles now)
20
+ * - rows already carrying role_list are never clobbered (idempotence / post-cutover grants win),
21
+ * and the ORM reads the array beside the stale legacy word
22
+ * - the retirement NULLs every legacy cell the typed column has absorbed — or that held nothing —
23
+ * and never one the backfill has not consumed; the ORM reads the same arrays before and after
24
+ * (a NULL legacy cell beside the array is the shape a row reader seating by property name
25
+ * would blank)
26
+ * - a database that never had the legacy column (fresh install) is a clean no-op for both
19
27
  */
20
28
 
21
29
  const spannerDriver = new SpannerDriver({
@@ -33,6 +41,8 @@ class DbDriverFactory {
33
41
  const dropTable = getDropTestTable(spannerDriver);
34
42
 
35
43
  const runMigration = async () => await new BackfillUserRolesArray().record.run();
44
+ const runRetirement = async () => await new RetireLegacyUserRolesColumn().record.run();
45
+ const estimateRetirement = async () => await new RetireLegacyUserRolesColumn().record.estimate();
36
46
 
37
47
  const rawUserInsert = async (id: string, legacyRoles: string | null) => {
38
48
  const rolesValue = legacyRoles === null ? 'NULL' : `'${legacyRoles}'`;
@@ -51,6 +61,14 @@ const rawRoleList = async (id: string) =>
51
61
  }))) as unknown as Array<{ role_list: string | null }>
52
62
  )[0].role_list;
53
63
 
64
+ /** The legacy cell as the database holds it. */
65
+ const rawRoles = async (id: string) =>
66
+ (
67
+ (await spannerDriver.runQuery(() => ({
68
+ sql: `SELECT roles FROM ${tables.User.name} WHERE id = '${id}'`,
69
+ }))) as unknown as Array<{ roles: string | null }>
70
+ )[0].roles;
71
+
54
72
  describe('BackfillUserRolesArray — legacy comma-string roles → typed role_list', () => {
55
73
  beforeAll(async () => {
56
74
  (SourceRepository.get() as any).objectCache['@proteinjs/db/DefaultDbDriverFactory'] = [new DbDriverFactory()];
@@ -72,8 +90,64 @@ describe('BackfillUserRolesArray — legacy comma-string roles → typed role_li
72
90
 
73
91
  it('is a clean no-op on a database that never had the legacy roles column', async () => {
74
92
  expect(await runMigration()).toEqual({ backfilled: 0 });
93
+ expect(await runRetirement()).toEqual({ retired: 0 });
94
+ expect(await estimateRetirement()).toMatchObject({ units: 0, unit: 'rows' });
75
95
  }, 60000);
76
96
 
97
+ it('retires every legacy cell the typed column has absorbed, never one the backfill has not consumed; the ORM reads the same arrays before and after', async () => {
98
+ await spannerDriver.runUpdateSchema(`ALTER TABLE ${tables.User.name} ADD COLUMN roles STRING(255)`);
99
+ const db = getDbAsSystem();
100
+ try {
101
+ await rawUserInsert('retire-carried', 'admin');
102
+ await rawUserInsert('retire-empty', '');
103
+ await rawUserInsert('retire-null', null);
104
+ // A legacy value the backfill has not consumed yet: role_list NULL, legacy text present.
105
+ await rawUserInsert('retire-unconsumed', 'ops');
106
+ // A post-cutover grant beside a stale legacy word (the collision shape).
107
+ const granted = await db.insert(tables.User, {
108
+ name: 'Granted',
109
+ email: 'granted@test.local',
110
+ password: 'test',
111
+ emailVerified: false,
112
+ roles: ['ops', 'dev'],
113
+ });
114
+ await spannerDriver.runDml(() => ({
115
+ sql: `UPDATE ${tables.User.name} SET roles = 'admin' WHERE id = '${granted.id}'`,
116
+ }));
117
+ // Carry the one consumable legacy value over (as the backfill would); leave 'retire-unconsumed' as a later backfill's.
118
+ await db.update(tables.User, { id: 'retire-carried', roles: ['admin'] });
119
+
120
+ // Before: the ORM reads the arrays beside the legacy cells, whatever they hold.
121
+ expect((await db.get(tables.User, { id: 'retire-carried' })).roles).toEqual(['admin']);
122
+ expect((await db.get(tables.User, { id: granted.id })).roles).toEqual(['ops', 'dev']);
123
+
124
+ expect(await estimateRetirement()).toMatchObject({ units: 3, unit: 'rows' });
125
+ expect(await runRetirement()).toEqual({ retired: 3 });
126
+
127
+ // The retired cells are NULL; the unconsumed legacy value is untouched.
128
+ expect(await rawRoles('retire-carried')).toBeNull();
129
+ expect(await rawRoles('retire-empty')).toBeNull();
130
+ expect(await rawRoles('retire-null')).toBeNull();
131
+ expect(await rawRoles(granted.id)).toBeNull();
132
+ expect(await rawRoles('retire-unconsumed')).toBe('ops');
133
+ expect(await rawRoleList('retire-unconsumed')).toBeNull();
134
+
135
+ // After: a NULL legacy cell beside the array — the ORM still reads the array.
136
+ expect((await db.get(tables.User, { id: 'retire-carried' })).roles).toEqual(['admin']);
137
+ expect((await db.get(tables.User, { id: granted.id })).roles).toEqual(['ops', 'dev']);
138
+ const everyone = await db.query(tables.User, {});
139
+ expect(everyone.find((user) => user.id === granted.id)?.roles).toEqual(['ops', 'dev']);
140
+ expect(everyone.find((user) => user.id === 'retire-carried')?.roles).toEqual(['admin']);
141
+
142
+ // Re-run: nothing left to retire.
143
+ expect(await runRetirement()).toEqual({ retired: 0 });
144
+ expect(await estimateRetirement()).toMatchObject({ units: 0, unit: 'rows' });
145
+ } finally {
146
+ await dropTable(tables.User as Table<any>);
147
+ await spannerDriver.getTableManager().loadTable(tables.User);
148
+ }
149
+ }, 120000);
150
+
77
151
  it('backfills, normalizes, preserves, and re-runs clean on a deployed-shape database', async () => {
78
152
  // Simulate the deployed state: the legacy column exists beside the new schema.
79
153
  await spannerDriver.runUpdateSchema(`ALTER TABLE ${tables.User.name} ADD COLUMN roles STRING(255)`);
@@ -4,7 +4,7 @@ import { SpannerDriver } from '@proteinjs/db-driver-spanner';
4
4
  import { SpannerEmulatorProvisioner, getDropTestTable } from '@proteinjs/db-driver-spanner/test';
5
5
  import { SourceRepository } from '@proteinjs/reflection';
6
6
  import { Session, SessionData, SessionDataStorage } from '@proteinjs/server-api';
7
- import { RoleCatalogEntry, USER_PERMISSIONS, UserRepo, tables } from '@proteinjs/user';
7
+ import { RoleCatalogEntry, RolesCatalog, USER_PERMISSIONS, UserRepo, tables } from '@proteinjs/user';
8
8
  import { Roles } from '../src/services/Roles';
9
9
 
10
10
  /**
@@ -192,6 +192,47 @@ describe('Roles service — grant/revoke outcomes and audit trail', () => {
192
192
  expect(await auditRows()).toHaveLength(0);
193
193
  }, 60000);
194
194
 
195
+ /**
196
+ * A held role string is always revocable. The catalog gates what may be GRANTED; a record's roles
197
+ * column holds whatever was granted while the catalog knew the role — and a consumer retires roles
198
+ * (the app's skill-outings row left its mapping and catalog, fold 48). If revoke were catalog-checked
199
+ * too, every holder of a retired role would keep it forever, removable only by a raw UPDATE outside
200
+ * the audited path. So revoke accepts any string the record holds, audited like any revoke; the
201
+ * grant side stays catalog-checked (the test above).
202
+ */
203
+ it('revokes a held role the catalog no longer knows — the audited path stays open after a role retires', async () => {
204
+ const catalog = (SourceRepository.get() as any).objectCache[
205
+ '@proteinjs/user/RoleCatalogEntry'
206
+ ] as RoleCatalogEntry[];
207
+ const retired = { role: 'skill-outings', description: 'A role a consumer later retired' } as RoleCatalogEntry;
208
+ catalog.push(retired);
209
+ try {
210
+ await new Roles().grantRole(targetId, 'skill-outings');
211
+ expect(await targetRoles()).toEqual(['skill-outings']);
212
+ } finally {
213
+ catalog.splice(catalog.indexOf(retired), 1); // the role leaves the catalog; the record still holds it
214
+ }
215
+ expect(RolesCatalog.isKnownRole('skill-outings')).toBe(false);
216
+
217
+ await new Roles().revokeRole(targetId, 'skill-outings');
218
+
219
+ expect(await targetRoles()).toEqual([]);
220
+ const events = await auditRows();
221
+ expect(events.map((event) => event.action).sort()).toEqual(['grant', 'revoke']);
222
+ expect(events.find((event) => event.action === 'revoke')).toMatchObject({
223
+ actor: 'actor-1',
224
+ target: targetId,
225
+ role: 'skill-outings',
226
+ });
227
+ }, 60000);
228
+
229
+ it('revoking an unknown role the user does not hold stays a no-op — nothing written, nothing audited', async () => {
230
+ await new Roles().revokeRole(targetId, 'made-up');
231
+
232
+ expect(await targetRoles()).toEqual([]);
233
+ expect(await auditRows()).toHaveLength(0);
234
+ }, 60000);
235
+
195
236
  it('refuses to grant an admin-grant-only role when the caller is not an admin — and writes nothing', async () => {
196
237
  // A user-admin's full day-to-day grant set — pointedly including 'roles' (the door this
197
238
  // service sits behind) — must NOT be able to hand out an admin-grant-only role.