Files
TREK/server/tests/unit/db/repositories/OauthConsents.repository.test.ts
T
Isaias Tavares 98533f3dbe refactor(db): type the database settings and inject one engine
The settings for the database were one flat record whose url and pool size
were meaningful only for Postgres, so every reader had to re-check the URL.
They are now a discriminated union per engine (DbEngineSettings): the
Postgres arm carries its URL and a pool size already capped at the ceiling,
and the SQLite arm carries nothing else. The env schema uses the same ceiling
constant, so the boot check and the derivation cannot drift apart.

The engine was resolved from the environment by every caller that needed it
(the lifecycle, the unit of work, the backup adapters), each building its own
instance. The engine is now provided once per container by
DatabaseEngineModule and injected everywhere, so the state an engine keeps
(Postgres's reopen hook) is the same wherever it is used. resolveEngine stays
for the MikroORM CLI config and the DI factory, and nothing else calls it.

The engine's reopen no longer carries a `reopenSwapsConnection` flag. The
engine itself decides what a reopen needs: SQLite closes and reconnects the
ORM's connection before the schema bootstrap (its handle is swapped under
Kysely's cache), and Postgres only migrates, because a restore replaces the
contents of the database the pool already reaches. The Postgres pool is never
closed on a reopen, since ending it waits for connections lent out during the
restore.

The backup ports answer every method the same way. verify() now throws a
DomainError for a refused archive on both engines, and the restore path maps
it back to the same { success: false, error, status } result, so the HTTP
response of a refused restore (status and body) is unchanged. The restore
step that swaps the database and then always reopens it is shared in
nest/backup/database-swap.ts, with the error-description helper in
nest/common, instead of two copies that could drift.
2026-11-05 01:04:21 -03:00

154 lines
7.1 KiB
TypeScript

import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
import { OauthClients } from '../../../../src/db/entities/OauthClients.entity';
import { OauthConsents } from '../../../../src/db/entities/OauthConsents.entity';
import type { OauthConsentsRepository } from '../../../../src/db/repositories/OauthConsents.repository';
import { withRequestContext } from '../../../../src/nest/database/request-context';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser } from '../../../helpers/factories';
import { findRow, findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let consents: OauthConsentsRepository;
let uow: UnitOfWork;
beforeAll(async () => {
t = await createTestOrm(testDb);
consents = t.repo(OauthConsents);
uow = new UnitOfWork(t.em, new SqliteEngine());
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
testDb.exec('DELETE FROM oauth_consents');
testDb.exec('DELETE FROM oauth_clients');
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function seedClient(userId: number, clientId: string): Promise<void> {
await insertRow(t, OauthClients, {
id: `row-${clientId}`,
user: userId,
name: 'C',
client_id: clientId,
client_secret_hash: 'hash',
redirect_uris: '[]',
allowed_scopes: '[]',
});
}
/** The stored consent of `userId` for `clientId`, or null. */
function storedConsent(clientId: string, userId: number) {
return findRow(t, OauthConsents, { client: clientId, user: userId });
}
describe('OauthConsentsRepository', () => {
describe('findScopes (OA11)', () => {
it('OAUTHCONSENTREPO-001: null when no consent has been granted', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-1');
expect(await consents.findScopes('proto-1', user.id)).toBeNull();
});
it('OAUTHCONSENTREPO-002: returns the stored scopes JSON text', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-2');
await insertRow(t, OauthConsents, { client: 'proto-2', user: user.id, scopes: '["trips:read"]' });
expect(await consents.findScopes('proto-2', user.id)).toEqual({ scopes: '["trips:read"]' });
});
});
describe('upsertGrant (OA12)', () => {
it('OAUTHCONSENTREPO-003: inserts a new row exactly as the legacy INSERT would', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-3');
await consents.upsertGrant('proto-3', user.id, '["a"]');
const row = await storedConsent('proto-3', user.id);
expect({ client_id: row?.client_id, user_id: row?.user_id, scopes: row?.scopes }).toEqual({
client_id: 'proto-3',
user_id: user.id,
scopes: '["a"]',
});
});
it('OAUTHCONSENTREPO-004: on an existing (client, user) it replaces the row in place — no duplicate, matching ON CONFLICT(client_id, user_id) DO UPDATE', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-4');
await consents.upsertGrant('proto-4', user.id, '["a"]');
await consents.upsertGrant('proto-4', user.id, '["a","b"]');
const rows = await findRows(t, OauthConsents, { client: 'proto-4', user: user.id });
expect(rows).toHaveLength(1);
expect(rows[0].scopes).toBe('["a","b"]');
});
it('OAUTHCONSENTREPO-005: updated_at is bumped on every call, insert or merge alike (unconditional, matching INSERT OR REPLACE)', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-5');
await consents.upsertGrant('proto-5', user.id, '["a"]');
const first = await storedConsent('proto-5', user.id);
await updateRows(t, OauthConsents, { client: 'proto-5' }, { updated_at: '2000-01-01 00:00:00' });
await consents.upsertGrant('proto-5', user.id, '["a","b"]');
const second = await storedConsent('proto-5', user.id);
expect(second?.updated_at).not.toBe('2000-01-01 00:00:00');
expect(first?.updated_at).toBeTruthy();
});
it('OAUTHCONSENTREPO-006: the same client scoped by different users stores two separate rows, not a collision', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await seedClient(a.id, 'proto-6');
await consents.upsertGrant('proto-6', a.id, '["a"]');
await consents.upsertGrant('proto-6', b.id, '["b"]');
expect(await consents.findScopes('proto-6', a.id)).toEqual({ scopes: '["a"]' });
expect(await consents.findScopes('proto-6', b.id)).toEqual({ scopes: '["b"]' });
});
});
// task-4-review.md F2: this is NOT a B1/D-shape regression test — that
// shape needs TWO managed reads with different field sets on the same
// row (task-1-rereview.md M-A/M-B), and `OauthConsentsRepository` has
// exactly one read method, so the D-shape is not constructible here at
// all. Mutating `findScopes`'s `disableIdentityMap: true` to `refresh:
// true` leaves this case green either way — it was never testing the
// mechanism its old name/comment claimed. What it DOES pin, genuinely:
// a single `findScopes` read leaves nothing dirty (the entity's snapshot
// and current data are identical, so the change-set computer finds no
// diff), and a raw write to the same row on the transaction's own
// connection, made afterward, is never fought by the closing flush.
describe('findScopes does not dirty the entity it reads', () => {
it("OAUTHCONSENTREPO-007: findScopes then a raw write on the same transaction connection — the raw write survives the transaction's closing flush", async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-7');
await insertRow(t, OauthConsents, { client: 'proto-7', user: user.id, scopes: '["a"]' });
await withRequestContext(t.orm, async () => {
await uow.transactional(async () => {
// The only read shape this repository has — a single projection,
// so no second, differently-projected read of the same row can
// ever be lingering in the identity map for this one to collide
// with.
await consents.findScopes('proto-7', user.id);
// A write bypassing the ORM entirely, on the SAME single SQLite
// connection the open transaction holds (D3/D6) — the shape any
// nativeUpdate write from elsewhere in the same request takes.
// test-sql-allow: the write has to run on the connection the open transaction holds, past the ORM.
testDb
.prepare('UPDATE oauth_consents SET scopes = ? WHERE client_id = ? AND user_id = ?')
.run('["a","b"]', 'proto-7', user.id);
});
});
const row = await storedConsent('proto-7', user.id);
expect(row?.scopes).toBe('["a","b"]');
});
});
});