|
1 | 1 | // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
2 | 2 |
|
| 3 | +// Pays the first load of the egress module at collection, not inside a clocked test. |
| 4 | +import '@objectstack/core/egress'; |
3 | 5 | import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; |
4 | 6 | import { mkdtempSync, rmSync } from 'node:fs'; |
5 | 7 | import { tmpdir } from 'node:os'; |
@@ -34,6 +36,8 @@ import { |
34 | 36 | import { SystemObjectName } from '@objectstack/spec/system'; |
35 | 37 | import type { IDataEngine } from '@objectstack/core'; |
36 | 38 | import { sso } from '@better-auth/sso'; |
| 39 | +import { twoFactor } from 'better-auth/plugins/two-factor'; |
| 40 | +import { organization } from 'better-auth/plugins/organization'; |
37 | 41 | import { AuthManager } from './auth-manager'; |
38 | 42 | import { createMemoryEngine } from './impersonation-bearer-rotation.test'; |
39 | 43 |
|
@@ -899,3 +903,199 @@ describe('a single-use auth value is redeemed at most once, even across processe |
899 | 903 | expect(await stored(driver, 'bystander')).toHaveLength(1); |
900 | 904 | }); |
901 | 905 | }); |
| 906 | + |
| 907 | +describe('a guarded increment is one atomic conditional write, even across processes sharing a database', () => { |
| 908 | + // The same two-replica shape as the single-use suite above: two ObjectQL |
| 909 | + // engines, each with its own SQL driver connection to ONE SQLite file and |
| 910 | + // its own factory-wrapped adapter. Each replica pauses once, right after its |
| 911 | + // first read of a guarded row, until both replicas have read — so both |
| 912 | + // calls see the guard pass before either one writes. The three call shapes |
| 913 | + // are ones better-auth 1.7.12 itself issues against `incrementOne`. |
| 914 | + const GUARDED = new Set(['sys_two_factor', 'sys_team']); |
| 915 | + type Where = { field: string; value: unknown; operator?: string; connector?: string }; |
| 916 | + type Adapter = { |
| 917 | + create(a: { model: string; data: Record<string, unknown> }): Promise<Record<string, unknown>>; |
| 918 | + findOne(a: { model: string; where: Where[] }): Promise<Record<string, unknown> | null>; |
| 919 | + incrementOne(a: { |
| 920 | + model: string; where: Where[]; increment: Record<string, number>; set?: Record<string, unknown>; |
| 921 | + }): Promise<Record<string, unknown> | null>; |
| 922 | + }; |
| 923 | + const gate = (parties: number) => { |
| 924 | + let arrived = 0; |
| 925 | + let open!: () => void; |
| 926 | + const opened = new Promise<void>((resolve) => { open = resolve; }); |
| 927 | + return async () => { |
| 928 | + if (++arrived === parties) open(); |
| 929 | + await opened; |
| 930 | + }; |
| 931 | + }; |
| 932 | + |
| 933 | + const dirs: string[] = []; |
| 934 | + const engines: ObjectQL[] = []; |
| 935 | + afterEach(async () => { |
| 936 | + while (engines.length) { |
| 937 | + try { await engines.pop()!.destroy(); } catch { /* noop */ } |
| 938 | + } |
| 939 | + while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true }); |
| 940 | + }); |
| 941 | + |
| 942 | + const replica = async (file: string, atRead?: () => Promise<void>): Promise<{ adapter: Adapter; driver: SqlDriver }> => { |
| 943 | + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true }); |
| 944 | + const engine = new ObjectQL(); |
| 945 | + engines.push(engine); |
| 946 | + engine.registerDriver(driver, true); |
| 947 | + await engine.init(); |
| 948 | + for (const object of authIdentityObjects) engine.registry.registerObject(object as never, '@objectstack/plugin-auth'); |
| 949 | + await engine.syncSchemas(); |
| 950 | + |
| 951 | + let read = false; |
| 952 | + const seen = new Proxy(engine, { |
| 953 | + get(target, prop) { |
| 954 | + const member = Reflect.get(target, prop, target); |
| 955 | + if (prop !== 'findOne') return typeof member === 'function' ? member.bind(target) : member; |
| 956 | + return async (object: string, ...rest: unknown[]) => { |
| 957 | + const row = await (member as (...a: unknown[]) => Promise<unknown>).call(target, object, ...rest); |
| 958 | + if (GUARDED.has(object) && !read) { |
| 959 | + read = true; |
| 960 | + await atRead?.(); |
| 961 | + } |
| 962 | + return row; |
| 963 | + }; |
| 964 | + }, |
| 965 | + }); |
| 966 | + const options = { |
| 967 | + plugins: [ |
| 968 | + twoFactor({ schema: buildTwoFactorPluginSchema() }), |
| 969 | + organization({ schema: buildOrganizationPluginSchema(), teams: { enabled: true } }), |
| 970 | + ], |
| 971 | + }; |
| 972 | + const adapter = (createObjectQLAdapterFactory(seen as unknown as IDataEngine) as unknown as (o: unknown) => Adapter)(options); |
| 973 | + return { adapter, driver }; |
| 974 | + }; |
| 975 | + |
| 976 | + /** Two replicas over one fresh file, both paused at their first guarded read. */ |
| 977 | + const twoReplicas = async () => { |
| 978 | + const dir = mkdtempSync(join(tmpdir(), 'os-auth-guarded-increment-')); |
| 979 | + dirs.push(dir); |
| 980 | + const file = join(dir, 'auth.db'); |
| 981 | + const bothRead = gate(2); |
| 982 | + return [await replica(file, bothRead), await replica(file, bothRead)] as const; |
| 983 | + }; |
| 984 | + /** One replica, no pause: the sequential control. */ |
| 985 | + const oneReplica = async () => { |
| 986 | + const dir = mkdtempSync(join(tmpdir(), 'os-auth-guarded-increment-')); |
| 987 | + dirs.push(dir); |
| 988 | + return replica(join(dir, 'auth.db')); |
| 989 | + }; |
| 990 | + |
| 991 | + const eq = (field: string, value: unknown): Where => ({ field, value, operator: 'eq', connector: 'AND' }); |
| 992 | + const stored = async (driver: SqlDriver, object: string, id: unknown) => |
| 993 | + ((await driver.find(object, { object, where: { id } } as never)) as Array<Record<string, unknown>>)[0]; |
| 994 | + |
| 995 | + const twoFactorRow = async (adapter: Adapter, backupCodes = 'codes-v1') => { |
| 996 | + const user = await adapter.create({ model: 'user', data: { email: `u${Math.random()}@example.com`, name: 'U', emailVerified: false } }); |
| 997 | + return adapter.create({ model: 'twoFactor', data: { userId: user.id, secret: 'totp-secret', backupCodes } }); |
| 998 | + }; |
| 999 | + const teamRow = async (adapter: Adapter) => { |
| 1000 | + const org = await adapter.create({ model: 'organization', data: { name: 'Org', slug: `org-${Math.random()}`.replace('.', '') } }); |
| 1001 | + return adapter.create({ model: 'team', data: { name: 'Team', organizationId: org.id, memberCount: 0 } }); |
| 1002 | + }; |
| 1003 | + |
| 1004 | + // A guard on a stored value, and an absolute `set` that moves it. |
| 1005 | + const swapGuardedValue = (adapter: Adapter, id: unknown, from: string, to: string) => |
| 1006 | + adapter.incrementOne({ model: 'twoFactor', where: [eq('id', id), eq('backupCodes', from)], increment: {}, set: { backupCodes: to } }); |
| 1007 | + // No guard beyond the row: +1. |
| 1008 | + const incrementUnguarded = (adapter: Adapter, id: unknown) => |
| 1009 | + adapter.incrementOne({ model: 'twoFactor', where: [eq('id', id)], increment: { failedVerificationCount: 1 } }); |
| 1010 | + // A guard on the counter itself (below a bound), +1. |
| 1011 | + const incrementBelowBound = (adapter: Adapter, id: unknown, maximum: number) => |
| 1012 | + adapter.incrementOne({ |
| 1013 | + model: 'team', |
| 1014 | + where: [eq('id', id), { field: 'memberCount', value: maximum, operator: 'lt', connector: 'AND' }], |
| 1015 | + increment: { memberCount: 1 }, |
| 1016 | + }); |
| 1017 | + |
| 1018 | + it('a guard on a stored value admits exactly one of two concurrent conditional writes on two engines over one database', async () => { |
| 1019 | + const [a, b] = await twoReplicas(); |
| 1020 | + const row = await twoFactorRow(a.adapter); |
| 1021 | + |
| 1022 | + const answers = await Promise.all([ |
| 1023 | + swapGuardedValue(a.adapter, row.id, 'codes-v1', 'codes-v2-by-a'), |
| 1024 | + swapGuardedValue(b.adapter, row.id, 'codes-v1', 'codes-v2-by-b'), |
| 1025 | + ]); |
| 1026 | + |
| 1027 | + expect(answers.filter((r) => r !== null), 'conditional writes applied').toHaveLength(1); |
| 1028 | + const accepted = answers.find((r) => r !== null)!; |
| 1029 | + expect((await stored(a.driver, 'sys_two_factor', row.id)).backup_codes).toBe(accepted.backupCodes); |
| 1030 | + }); |
| 1031 | + |
| 1032 | + it('two concurrent unguarded increments on two engines over one database are both applied', async () => { |
| 1033 | + const [a, b] = await twoReplicas(); |
| 1034 | + const row = await twoFactorRow(a.adapter); |
| 1035 | + |
| 1036 | + const answers = await Promise.all([incrementUnguarded(a.adapter, row.id), incrementUnguarded(b.adapter, row.id)]); |
| 1037 | + |
| 1038 | + expect(answers.map((r) => r?.failedVerificationCount).sort()).toEqual([1, 2]); |
| 1039 | + expect((await stored(a.driver, 'sys_two_factor', row.id)).failed_verification_count).toBe(2); |
| 1040 | + }); |
| 1041 | + |
| 1042 | + it('a guard on the counter admits exactly one of two concurrent increments up to its bound on two engines over one database', async () => { |
| 1043 | + const [a, b] = await twoReplicas(); |
| 1044 | + const team = await teamRow(a.adapter); |
| 1045 | + |
| 1046 | + const answers = await Promise.all([incrementBelowBound(a.adapter, team.id, 1), incrementBelowBound(b.adapter, team.id, 1)]); |
| 1047 | + |
| 1048 | + expect(answers.filter((r) => r !== null), 'increments applied').toHaveLength(1); |
| 1049 | + expect(answers.find((r) => r !== null)).toMatchObject({ id: team.id, memberCount: 1 }); |
| 1050 | + expect((await stored(a.driver, 'sys_team', team.id)).member_count).toBe(1); |
| 1051 | + }); |
| 1052 | + |
| 1053 | + it('one caller at a time: each guarded increment applies, and a guard that no longer holds changes nothing', async () => { |
| 1054 | + const { adapter, driver } = await oneReplica(); |
| 1055 | + const row = await twoFactorRow(adapter); |
| 1056 | + const team = await teamRow(adapter); |
| 1057 | + |
| 1058 | + expect(await swapGuardedValue(adapter, row.id, 'codes-v1', 'codes-v2')).toMatchObject({ id: row.id, backupCodes: 'codes-v2' }); |
| 1059 | + expect(await swapGuardedValue(adapter, row.id, 'codes-v1', 'codes-v3'), 'the same guard a second time').toBeNull(); |
| 1060 | + expect((await stored(driver, 'sys_two_factor', row.id)).backup_codes).toBe('codes-v2'); |
| 1061 | + |
| 1062 | + expect((await incrementUnguarded(adapter, row.id))?.failedVerificationCount).toBe(1); |
| 1063 | + expect((await incrementUnguarded(adapter, row.id))?.failedVerificationCount).toBe(2); |
| 1064 | + |
| 1065 | + expect(await incrementBelowBound(adapter, team.id, 2)).toMatchObject({ memberCount: 1 }); |
| 1066 | + expect(await incrementBelowBound(adapter, team.id, 2)).toMatchObject({ memberCount: 2 }); |
| 1067 | + expect(await incrementBelowBound(adapter, team.id, 2), 'the bound is reached').toBeNull(); |
| 1068 | + expect((await stored(driver, 'sys_team', team.id)).member_count).toBe(2); |
| 1069 | + |
| 1070 | + expect(await incrementUnguarded(adapter, 'no-such-row'), 'a row that does not exist').toBeNull(); |
| 1071 | + }); |
| 1072 | + |
| 1073 | + it('the row a guarded increment answers carries the fields a read of that row carries, internal columns included', async () => { |
| 1074 | + const { adapter } = await oneReplica(); |
| 1075 | + const row = await twoFactorRow(adapter); |
| 1076 | + const team = await teamRow(adapter); |
| 1077 | + const fieldsOf = (r: Record<string, unknown> | null) => Object.keys(r ?? {}).sort(); |
| 1078 | + const read = (model: string, id: unknown) => adapter.findOne({ model, where: [eq('id', id)] }); |
| 1079 | + |
| 1080 | + const counted = await incrementUnguarded(adapter, row.id); |
| 1081 | + expect(counted).toMatchObject({ id: row.id, secret: 'totp-secret', backupCodes: 'codes-v1', failedVerificationCount: 1 }); |
| 1082 | + expect(fieldsOf(counted)).toEqual(fieldsOf(await read('twoFactor', row.id))); |
| 1083 | + |
| 1084 | + const swapped = await swapGuardedValue(adapter, row.id, 'codes-v1', 'codes-v2'); |
| 1085 | + expect(swapped).toMatchObject({ id: row.id, secret: 'totp-secret', backupCodes: 'codes-v2' }); |
| 1086 | + expect(fieldsOf(swapped)).toEqual(fieldsOf(await read('twoFactor', row.id))); |
| 1087 | + |
| 1088 | + const reserved = await incrementBelowBound(adapter, team.id, 5); |
| 1089 | + expect(reserved).toMatchObject({ id: team.id, memberCount: 1 }); |
| 1090 | + expect(fieldsOf(reserved)).toEqual(fieldsOf(await read('team', team.id))); |
| 1091 | + }); |
| 1092 | + |
| 1093 | + it('a counter stored as null counts from zero', async () => { |
| 1094 | + const { adapter, driver } = await oneReplica(); |
| 1095 | + const row = await twoFactorRow(adapter); |
| 1096 | + await driver.update('sys_two_factor', row.id as string, { failed_verification_count: null }); |
| 1097 | + |
| 1098 | + expect((await incrementUnguarded(adapter, row.id))?.failedVerificationCount).toBe(1); |
| 1099 | + expect((await stored(driver, 'sys_two_factor', row.id)).failed_verification_count).toBe(1); |
| 1100 | + }); |
| 1101 | +}); |
0 commit comments