fix(db): row-out repository reads bypass the identity map — stale write-back over nativeUpdate at flush; insertUser via em.insert; settings round-trip pinned

This commit is contained in:
jubnl
2026-09-22 20:32:35 +02:00
parent e9d0cb60e0
commit 8d0dddf385
21 changed files with 442 additions and 172 deletions
+30
View File
@@ -72,6 +72,36 @@ describe('PROFILE-001 — Get current user profile', () => {
});
});
// PUT /api/auth/me/settings — F3 (task-1-review.md): the B1 regression's
// user-visible symptom was exactly this route answering 200 while silently
// discarding the write. Asserts the DB row directly, not only the response
// body, and the response body against a fresh GET /api/auth/me — either one
// alone would have missed B1 (the response body came from the pre-flush
// in-memory entity, which still looked right).
describe('PUT /api/auth/me/settings (F3)', () => {
it('PROFILE-016 — a username+email change persists: the response, a fresh GET, and the raw row all agree', async () => {
const { user } = createUser(testDb, { username: 'before-name', email: 'before@example.test' });
const put = await request(app)
.put('/api/auth/me/settings')
.set('Cookie', authCookie(user.id))
.send({ username: 'after-name', email: 'after@example.test' });
expect(put.status).toBe(200);
expect(put.body.success).toBe(true);
expect(put.body.user).toMatchObject({ username: 'after-name', email: 'after@example.test' });
const get = await request(app)
.get('/api/auth/me')
.set('Cookie', authCookie(user.id));
expect(get.status).toBe(200);
expect(get.body.user).toMatchObject({ username: 'after-name', email: 'after@example.test' });
const row = testDb.prepare('SELECT username, email FROM users WHERE id = ?').get(user.id) as { username: string; email: string };
expect(row.username).toBe('after-name');
expect(row.email).toBe('after@example.test');
});
});
describe('Avatar', () => {
it('PROFILE-002 — upload valid JPEG avatar updates avatar_url', async () => {
const { user } = createUser(testDb);
@@ -27,8 +27,9 @@ function insertRaw(key: string, value: string | null): void {
/**
* Runs `fn` while counting queries MikroORM actually issues over the shared
* connection, so a regression test can assert "one query, with this value"
* rather than only the value — the identity-map bug I1 fixed (Task 0 review)
* returned the *right* value from a stale cache with *zero* queries, which a
* rather than only the value — a regression in the `disableIdentityMap: true`
* ruling (Plan 3b Task 1 fix round, `task-1-review.md` B1) would return the
* *right* value from a stale identity-map hit with *zero* queries, which a
* value-only assertion would never catch.
*/
async function withQueryCount<T>(fn: () => Promise<T>): Promise<{ value: T; queries: number }> {
@@ -67,12 +68,12 @@ describe('AppSettingsRepository', () => {
expect(values.has('collab_links_enabled')).toBe(false);
});
// I1 (Task 0 review): getValue is a primary-key findOne, which MikroORM
// answers from the identity map on a repeat call unless `refresh: true` is
// set — invisible to a raw write or delete on the same key inside the same
// request. These reproduce the review's two failing probes and pin the
// Plan 3b Task 1 fix round (task-1-review.md B1): getValue is a
// primary-key findOne, which MikroORM would answer from the identity map
// on a repeat call absent `disableIdentityMap: true` — invisible to a raw
// write or delete on the same key inside the same request. These pin the
// fix at one query each.
describe('getValue sees a raw write/delete on the same key in the same request (I1, identity-map regression)', () => {
describe('getValue sees a raw write/delete on the same key in the same request (disableIdentityMap regression)', () => {
it('APPSETREPO-013: deleteValue then getValue reads null, not the deleted row, in one query', async () => {
insertRaw('bag_tracking_enabled', 'v');
expect(await appSettings.getValue('bag_tracking_enabled')).toBe('v'); // populate the identity map
@@ -88,10 +88,9 @@ describe('CategoriesRepository', () => {
expect(entity?.user?.isInitialized()).toBe(false);
});
// I1 (Task 0 review): findById carries `refresh: true`, the ruling every
// Plan 3 PK read follows — and it is load-bearing here (Task 3 review,
// Important 2's correction): `{ id }` is exactly the primary key, so
// without `refresh` this would be served from the identity map with
// Plan 3b Task 1 fix round (task-1-review.md B1): findById carries
// `disableIdentityMap: true` — `{ id }` is exactly the primary key, so
// without it this would risk being served from the identity map with
// zero queries and the stale pre-UPDATE color. `queries === 1` proves
// the real re-query happens.
it('CATREPO-008: a raw UPDATE on the same row then findById reads the new value, in one query', async () => {
@@ -92,14 +92,10 @@ describe('TagsRepository', () => {
expect(entity?.user.isInitialized()).toBe(false);
});
// I1 (Task 0 review): findByIdAndUser carries `{ refresh: true }` (via
// the shared findOwnedByUser helper), the ruling every Plan 3 PK read
// follows. This call's filter is `{ id, user }`, not PK-only, so it
// always re-queries and merges fresh data regardless of `refresh` (Task
// 3 review, Important 2's correction: the identity-map short-circuit
// fires only for an exactly-PK filter, not for a `fields` restriction)
// — this proves the (still correct) outcome in one query rather than a
// refresh-vs-no-refresh contrast.
// Plan 3b Task 1 fix round (task-1-review.md B1): findByIdAndUser
// carries `disableIdentityMap: true` (via the shared findOwnedByUser
// helper) — always re-queries and merges fresh data, in one query, and
// never lands in the request's identity map.
it('TAGREPO-009: a raw UPDATE on the same row then findByIdAndUser reads the new value, in one query', async () => {
const { user } = createUser(testDb);
const created = createTag(testDb, user.id, { name: 'Stale', color: '#111111' });
@@ -20,7 +20,8 @@ afterAll(async () => { await t.close(); testDb.close(); });
/**
* Runs `fn` while counting queries MikroORM actually issues over the shared
* connection — see `AppSettings.repository.test.ts` for why a value-only
* assertion can't catch the identity-map bug I1 fixed (Task 0 review).
* assertion can't catch a regression in the `disableIdentityMap: true`
* ruling (Plan 3b Task 1 fix round, `task-1-review.md` B1).
*/
async function withQueryCount<T>(fn: () => Promise<T>): Promise<{ value: T; queries: number }> {
const connection = t.orm.em.getConnection();
@@ -70,11 +71,13 @@ describe('UsersRepository', () => {
expect(await users.getApiKeyColumn(999999, 'maps_api_key')).toBeNull();
});
// I1 (Task 0 review): getEmail/getApiKeyColumn are primary-key findOne
// calls, which MikroORM answers from the identity map on a repeat call
// unless `refresh: true` is set — invisible to a raw UPDATE on the same
// user id inside the same request. Pins the fix at one query each.
describe('getEmail/getApiKeyColumn see a raw UPDATE on the same user in the same request (I1, identity-map regression)', () => {
// Plan 3b Task 1 fix round (task-1-review.md B1): getEmail/getApiKeyColumn
// are primary-key findOne calls, which MikroORM would answer from the
// identity map on a repeat call absent `disableIdentityMap: true` —
// invisible to a raw UPDATE on the same user id inside the same request.
// Pins the fix at one query each; the property is preserved (B1's fix
// dropped `refresh: true`, not this guarantee).
describe('getEmail/getApiKeyColumn see a raw UPDATE on the same user in the same request (disableIdentityMap regression)', () => {
it('USERSREPO-007: a raw UPDATE users SET email then getEmail reads the new email, in one query', async () => {
const { user } = createUser(testDb, { email: 'old@example.com' });
expect(await users.getEmail(user.id)).toBe('old@example.com'); // populate the identity map
@@ -200,6 +203,37 @@ describe('UsersRepository', () => {
expect(row.role).toBe('admin');
expect(row.login_count).toBe(0);
});
it('USERSREPO-057: insertUser (F2) never flushes an unrelated pending entity in the same EM', async () => {
// Simulate an unrelated pending change elsewhere in the request's EM —
// a managed entity persist()-ed but not yet flushed by its own code
// path. Before F2's fix, `insertUser`'s `persist().flush()` committed
// the WHOLE unit of work, so this row would land in the DB too.
const pending = t.em.create(Users, {
username: 'pending-unflushed',
email: 'pending@example.com',
password_hash: 'x',
role: 'user',
first_seen_version: '9.9.9',
login_count: 0,
});
t.em.persist(pending);
await users.insertUser({
username: 'freshuser',
email: 'fresh@example.com',
password_hash: 'hashed',
role: 'user',
first_seen_version: '1.2.3',
});
const pendingRow = testDb.prepare('SELECT * FROM users WHERE username = ?').get('pending-unflushed');
expect(pendingRow).toBeUndefined(); // insertUser must not have flushed it
const freshRow = testDb.prepare('SELECT * FROM users WHERE username = ?').get('freshuser');
expect(freshRow).toBeDefined(); // but the intended row is there
t.em.clear(); // discard the still-pending unflushed entity before the next test
});
});
describe('findByEmailCI (AU12/O4)', () => {
@@ -218,6 +252,26 @@ describe('UsersRepository', () => {
});
});
// Plan 3b Task 1 fix round item 7 — AuthService.demoLogin's exact statement
// (`SELECT * FROM users WHERE email = ?`), missing from the inventory,
// added now so Task 5 has it.
describe('findByEmailExact (AuthService.demoLogin, inventory correction)', () => {
it('USERSREPO-057B: matches only the exact case, unlike every other email lookup here', async () => {
const { user } = createUser(testDb, { email: 'Demo.User@Example.com' });
const row = await users.findByEmailExact('Demo.User@Example.com');
expect(row?.id).toBe(user.id);
expect(await users.findByEmailExact('demo.user@example.com')).toBeNull(); // different case — no match
expect(await users.findByEmailExact('nope@example.com')).toBeNull();
});
it('USERSREPO-057C: a guest row IS returned — no guest filter, unlike findByEmailCI/findForPasswordReset', async () => {
const { user } = createUser(testDb, { email: 'demoguest@example.com' });
testDb.prepare('UPDATE users SET is_guest = 1 WHERE id = ?').run(user.id);
const row = await users.findByEmailExact('demoguest@example.com');
expect(row?.id).toBe(user.id);
});
});
describe('touchLastLogin (AU13/AU34/AU35/PK12/O16)', () => {
it('USERSREPO-020: bumps login_count by exactly 1 and stamps last_login, in one statement', async () => {
const { user } = createUser(testDb);
@@ -315,7 +369,7 @@ describe('UsersRepository', () => {
expect(await users.findById(999999)).toBeNull();
});
it('USERSREPO-031: sees a raw UPDATE on the same id in the same request (I1, identity-map regression)', async () => {
it('USERSREPO-031: sees a raw UPDATE on the same id in the same request (disableIdentityMap regression)', async () => {
const { user } = createUser(testDb, { username: 'before' });
await users.findById(user.id); // populate the identity map
testDb.prepare('UPDATE users SET username = ? WHERE id = ?').run('after', user.id);
@@ -60,27 +60,19 @@ describe('findOwnedByUser', () => {
expect(await findOwnedByUser<Tags, 'user'>(tags, 999999, 'user', owner.id)).toBeNull();
});
// Task 0 review I1's PK-read ruling, extended to this helper (Task 3):
// `options.refresh` passes through to `findOne`. This helper's filter is
// `{ id, [ownerField]: ownerId }`, not PK-only, so it always re-queries
// and merges fresh data regardless of `refresh` (proven below: a raw
// write on the same row is visible either way) — the identity-map
// short-circuit (and the staleness it can cause without `refresh`) fires
// only when the filter is exactly the primary key, which is what
// AppSettingsRepository.getValue's PK-only `findOne` hit and this
// multi-condition filter never does (Task 3 review, Important 2's
// correction — `fields` has nothing to do with it). `refresh` stays on
// this helper regardless, matching the Task 0 review's blanket PK-read
// ruling and staying correct if a future caller narrows the filter to
// PK-only.
it('OWNEDLOOKUP-006: { refresh: true } sees a raw UPDATE on the same row in the same request, in one query', async () => {
// Plan 3b Task 1 fix round (task-1-review.md B1): `findOwnedByUser` always
// passes `disableIdentityMap: true` now (no longer an opt-in `options`
// parameter) — every call answers from a throwaway forked context, so a
// raw write on the same row earlier in the request is always visible, in
// one query, and the entity never lands in the request's identity map.
it('OWNEDLOOKUP-006: sees a raw UPDATE on the same row in the same request, in one query (disableIdentityMap)', async () => {
const { user: owner } = createUser(testDb);
const tag = createTag(testDb, owner.id, { name: 'Old' });
expect((await findOwnedByUser<Tags, 'user'>(tags, tag.id, 'user', owner.id))?.name).toBe('Old'); // populate the identity map
expect((await findOwnedByUser<Tags, 'user'>(tags, tag.id, 'user', owner.id))?.name).toBe('Old');
testDb.prepare('UPDATE tags SET name = ? WHERE id = ?').run('New', tag.id);
const connection = t.orm.em.getConnection();
const spy = vi.spyOn(connection, 'execute');
const found = await findOwnedByUser<Tags, 'user'>(tags, tag.id, 'user', owner.id, { refresh: true });
const found = await findOwnedByUser<Tags, 'user'>(tags, tag.id, 'user', owner.id);
expect(found?.name).toBe('New');
expect(spy.mock.calls.length).toBe(1);
spy.mockRestore();
@@ -0,0 +1,100 @@
/**
* Regression test for Plan 3b Task 1's B1 finding
* (`.superpowers/sdd/2026-09-22-orm-phase3b/task-1-review.md`): a `Users`
* row read with `fields` + `refresh: true` (no `disableIdentityMap`) left a
* *partially hydrated, managed* entity in the request `EntityManager`'s
* identity map. A second such read, with a *different* field set, on the
* *same* row re-snapshotted only its own fields — the first read's fields
* stayed on the entity object but fell out of the snapshot MikroORM's
* change-set computer diffs against, so they looked like a pending change.
* The next `flush()` (including the implicit one at `UnitOfWork.transactional`
* commit) then emitted an `UPDATE users SET <those columns> …` carrying the
* STALE pre-request values, landing *after* an intervening `nativeUpdate`
* inside the same transaction and silently reverting it.
*
* No single-method test can catch this by construction (`Users.repository.test.ts`
* exercises one method per case): this file drives the two-reads-then-a-write
* interaction that is the actual trigger, inside `withRequestContext` (every
* authenticated request's shape) and `uow.transactional` (every multi-write
* request's shape).
*
* The fix (this task): every row-out read passes `disableIdentityMap: true`.
* MikroORM forks the EM with `keepTransactionContext: true`, loads inside the
* fork, then clears it — nothing is added to the *request's* identity map, so
* there is nothing for a later `flush()` to find dirty.
* See https://mikro-orm.io/docs/entity-manager#disableidentitymap and
* `node_modules/@mikro-orm/core/EntityManager.js:807-824`.
*
* Mutation proof (recorded in `task-1-fix-report.md`, not re-run here): reverting
* ONE of the two reads below to the pre-fix shape (`fields` + `refresh: true`,
* no `disableIdentityMap`) makes IMWB-001 fail with the stale write-back this
* test is built to catch.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { createUser } from '../../../helpers/factories';
import { Users } from '../../../../src/db/entities/Users.entity';
import type { UsersRepository } from '../../../../src/db/repositories/Users.repository';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { withRequestContext } from '../../../../src/nest/database/request-context';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let users: UsersRepository;
let uow: UnitOfWork;
beforeAll(async () => {
t = await createTestOrm(testDb);
users = t.repo(Users);
uow = new UnitOfWork(t.em);
});
beforeEach(() => { resetTestDb(testDb); t.clear(); });
afterAll(async () => { await t.close(); testDb.close(); });
describe('identity-map write-back (task-1-review.md B1)', () => {
it('IMWB-001: findByIdWithPasswordVersion then getApiKeyColumns then patchProfile — the profile write survives the request', async () => {
const { user } = createUser(testDb, { username: 'before', email: 'before@example.test' });
const originalPasswordVersion = (testDb.prepare('SELECT password_version FROM users WHERE id = ?').get(user.id) as { password_version: number }).password_version;
await withRequestContext(t.orm, async () => {
// Projection A — the JwtAuthGuard/GlobalAuthGuard shape.
await users.findByIdWithPasswordVersion(user.id);
// Projection B — a second UsersRepository read with a different field set,
// the UserProfileService shape (e.g. the MfaPolicyGuard/getApiKeyColumns
// reads that run on the same request).
await users.getApiKeyColumns(user.id);
// The intended write, inside the request's own transaction.
await uow.transactional(async () => {
await users.patchProfile(user.id, { username: 'newname' });
});
});
const row = testDb
.prepare('SELECT username, email, password_version FROM users WHERE id = ?')
.get(user.id) as { username: string; email: string; password_version: number };
expect(row.username).toBe('newname'); // the nativeUpdate must stick
expect(row.email).toBe('before@example.test'); // untouched by either read
expect(row.password_version).toBe(originalPasswordVersion); // untouched by either read
});
it('IMWB-002: findByIdWithPasswordVersion then getApiKeyColumns then setPassword — password_version survives (Task 5 session-invalidation case)', async () => {
const { user } = createUser(testDb, { username: 'someone' });
await withRequestContext(t.orm, async () => {
await users.findByIdWithPasswordVersion(user.id);
await users.getApiKeyColumns(user.id);
await uow.transactional(async () => {
await users.setPassword(user.id, 'NEWHASH', 5);
});
});
const row = testDb
.prepare('SELECT password_hash, password_version, username FROM users WHERE id = ?')
.get(user.id) as { password_hash: string; password_version: number; username: string };
expect(row.password_hash).toBe('NEWHASH');
expect(row.password_version).toBe(5); // the session-invalidation gate — must NOT revert to the pre-change value
expect(row.username).toBe('someone'); // untouched by either read
});
});
+21 -4
View File
@@ -37,8 +37,21 @@ function makeReq(overrides: {
} as unknown as Request;
}
/** A fake `UsersRepository` whose `findByIdWithPasswordVersion` returns the given row. */
function usersRepo(row: UserWithPasswordVersion | null): UsersRepository {
/**
* A fake `UsersRepository` whose `findByIdWithPasswordVersion` returns the
* given row.
*
* `password_version` is widened to `number | null` here, unlike the real
* `UserWithPasswordVersion.password_version: number` — the column is
* `INTEGER NOT NULL DEFAULT 0`, so a real row can never carry `null`, but
* AUTH-JWT-009 (task-1-review.md F5) still needs to pin
* `verifyJwtAndLoadUser`'s `typeof row.password_version === 'number' ? … :
* 0` fallback branch, which is otherwise unreachable through the real type.
* Widening the fake, not `UserWithPasswordVersion` itself (which would
* loosen a production type for a test-only case), keeps that column's real
* NOT-NULL guarantee intact everywhere else.
*/
function usersRepo(row: (Omit<UserWithPasswordVersion, 'password_version'> & { password_version: number | null }) | null): UsersRepository {
return { findByIdWithPasswordVersion: vi.fn(async () => row) } as unknown as UsersRepository;
}
@@ -125,8 +138,12 @@ describe('verifyJwtAndLoadUser', () => {
expect(await verifyJwtAndLoadUser(current, users)).not.toBeNull();
});
it('AUTH-JWT-009: a pre-pv token still works against a never-reset user (both read as 0)', async () => {
const users = usersRepo({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 0 });
it('AUTH-JWT-009: a pre-pv token still works against a row whose password_version reads as unset (both fall back to 0)', async () => {
// password_version: null pins the `typeof row.password_version === 'number' ? … : 0`
// fallback branch directly (task-1-review.md F5) — unreachable through
// the real UsersRepository, whose column is NOT NULL DEFAULT 0, but
// worth keeping covered rather than deleting the branch it guards.
const users = usersRepo({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: null });
const legacy = jwt.sign({ id: 1 }, 'test-secret', { algorithm: 'HS256' });
expect(await verifyJwtAndLoadUser(legacy, users)).not.toBeNull();
+6 -2
View File
@@ -560,13 +560,17 @@ describe('authenticateDownload', () => {
verifyJwtAndLoadUser.mockReturnValue({ id: 42 });
const result = await svc.authenticateDownload(req({ cookie: 'cookie-jwt', bearer: 'bearer-jwt' }));
expect(result).toEqual({ userId: 42 });
expect(verifyJwtAndLoadUser).toHaveBeenCalledWith('cookie-jwt', expect.anything());
// The concrete expected argument, not expect.anything(): emStub.getRepository
// always returns a fresh `{}` (task-1-review.md F6) — deep-equal, not a
// reference match, so this pins WHICH repository (an empty object, this
// suite's stand-in for UsersRepository), not merely "a repository".
expect(verifyJwtAndLoadUser).toHaveBeenCalledWith('cookie-jwt', {});
});
it('FILE-SVC-033: a bearer token is used when no cookie is present; invalid JWTs 401', async () => {
verifyJwtAndLoadUser.mockReturnValue({ id: 7 });
expect(await svc.authenticateDownload(req({ bearer: 'bearer-jwt' }))).toEqual({ userId: 7 });
expect(verifyJwtAndLoadUser).toHaveBeenCalledWith('bearer-jwt', expect.anything());
expect(verifyJwtAndLoadUser).toHaveBeenCalledWith('bearer-jwt', {}); // see FILE-SVC-032's comment
verifyJwtAndLoadUser.mockReturnValue(null);
expect(await svc.authenticateDownload(req({ bearer: 'stale' }))).toEqual({ error: 'Invalid or expired token', status: 401 });
@@ -178,7 +178,7 @@ describe('applyPlatformUploads', () => {
res,
next,
);
expect(h.verifyJwtAndLoadUser).toHaveBeenCalledWith('jwt123', expect.anything());
expect(h.verifyJwtAndLoadUser).toHaveBeenCalledWith('jwt123', expect.objectContaining({ findByIdWithPasswordVersion: expect.any(Function) }));
expect(h.sendToResponse).toHaveBeenCalledWith('photos', 'a.jpg', res);
});
@@ -188,7 +188,7 @@ describe('applyPlatformUploads', () => {
h.verifyJwtAndLoadUser.mockReturnValue({ id: 1 });
const res = makeRes();
await photoHandler()({ params: { filename: 'a.jpg' }, headers: {}, query: { token: 'qtok' } }, res, next);
expect(h.verifyJwtAndLoadUser).toHaveBeenCalledWith('qtok', expect.anything());
expect(h.verifyJwtAndLoadUser).toHaveBeenCalledWith('qtok', expect.objectContaining({ findByIdWithPasswordVersion: expect.any(Function) }));
expect(h.sendToResponse).toHaveBeenCalledWith('photos', 'a.jpg', res);
});