mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 07:07:31 +00:00
d28e91d056
The repository suites now write their fixtures and read back what a call left behind through the factories and readers, not hand-written SQLite on the better-sqlite3 handle. What stays raw is marked with test-sql-allow: the legacy statements the parity cases hold a repository read to, rows read as the table stores them (a BLOB, an integer the entity maps to a boolean), and a write that has to land on the connection an open transaction holds. Cases that pinned a "raw UPDATE" between two repository reads now make that write through a context of their own, which the repository's identity map knows as little about, so they still prove the same thing.
288 lines
12 KiB
TypeScript
288 lines
12 KiB
TypeScript
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } 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 { OauthClients } from '../../../../src/db/entities/OauthClients.entity';
|
|
import { deleteRows, findRow, insertRow, updateRows } from '../../../helpers/factories/rows';
|
|
import type { OauthClientsRepository } from '../../../../src/db/repositories/OauthClients.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 clients: OauthClientsRepository;
|
|
let uow: UnitOfWork;
|
|
|
|
beforeAll(async () => {
|
|
t = await createTestOrm(testDb);
|
|
clients = t.repo(OauthClients);
|
|
uow = new UnitOfWork(t.em);
|
|
});
|
|
beforeEach(async () => { resetTestDb(testDb); t.clear(); await deleteRows(t, OauthClients); });
|
|
afterAll(async () => { await t.close(); testDb.close(); });
|
|
|
|
async function seedClient(
|
|
overrides: Partial<{ id: string; userId: number | null; name: string; clientId: string; secretHash: string; redirectUris: string; allowedScopes: string; isPublic: number; createdVia: string; allowsClientCredentials: number }> = {},
|
|
): Promise<{ id: string; userId: number | null; clientId: string }> {
|
|
const id = overrides.id ?? `row-${Math.random().toString(36).slice(2)}`;
|
|
const clientId = overrides.clientId ?? `proto-${Math.random().toString(36).slice(2)}`;
|
|
await insertRow(t, OauthClients, {
|
|
id,
|
|
user: overrides.userId ?? null,
|
|
name: overrides.name ?? 'Test Client',
|
|
client_id: clientId,
|
|
client_secret_hash: overrides.secretHash ?? 'hash-value',
|
|
redirect_uris: overrides.redirectUris ?? '["https://example.com/cb"]',
|
|
allowed_scopes: overrides.allowedScopes ?? '["trips:read"]',
|
|
is_public: overrides.isPublic ?? 0,
|
|
created_via: overrides.createdVia ?? 'settings_ui',
|
|
allows_client_credentials: overrides.allowsClientCredentials ?? 0,
|
|
});
|
|
return { id, userId: overrides.userId ?? null, clientId };
|
|
}
|
|
|
|
/** The stored row, client_secret_hash included, which no repository read returns. */
|
|
function storedClient(id: string) {
|
|
return findRow(t, OauthClients, { id });
|
|
}
|
|
|
|
describe('OauthClientsRepository', () => {
|
|
describe('listByUser (OA1)', () => {
|
|
it('OAUTHCLIENTREPO-001: returns the caller\'s clients only, newest first, without the secret hash', async () => {
|
|
const { user } = createUser(testDb);
|
|
const { user: other } = createUser(testDb);
|
|
await seedClient({ userId: user.id, name: 'first', createdVia: 'settings_ui' });
|
|
testDb.exec("UPDATE oauth_clients SET created_at = '2020-01-01 00:00:00' WHERE name = 'first'");
|
|
await seedClient({ userId: user.id, name: 'second' });
|
|
testDb.exec("UPDATE oauth_clients SET created_at = '2021-01-01 00:00:00' WHERE name = 'second'");
|
|
await seedClient({ userId: other.id, name: 'not-mine' });
|
|
|
|
const rows = await clients.listByUser(user.id);
|
|
expect(rows.map((r) => r.name)).toEqual(['second', 'first']);
|
|
expect(rows[0]).not.toHaveProperty('client_secret_hash');
|
|
expect(rows[0].user_id).toBe(user.id);
|
|
});
|
|
|
|
it('OAUTHCLIENTREPO-002: empty for a user with no clients', async () => {
|
|
const { user } = createUser(testDb);
|
|
expect(await clients.listByUser(user.id)).toEqual([]);
|
|
});
|
|
|
|
it('OAUTHCLIENTREPO-002b: created_at NULL comes back null, not undefined (coverage: rule 16)', async () => {
|
|
const { user } = createUser(testDb);
|
|
const { id } = await seedClient({ userId: user.id, name: 'null-created' });
|
|
await updateRows(t, OauthClients, { id }, { created_at: null });
|
|
const rows = await clients.listByUser(user.id);
|
|
expect(rows[0].created_at).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe('countByUser / countAnonymous (OA2/OA3)', () => {
|
|
it('OAUTHCLIENTREPO-003: countByUser only counts the given user\'s rows', async () => {
|
|
const { user } = createUser(testDb);
|
|
const { user: other } = createUser(testDb);
|
|
await seedClient({ userId: user.id });
|
|
await seedClient({ userId: user.id });
|
|
await seedClient({ userId: other.id });
|
|
expect(await clients.countByUser(user.id)).toBe(2);
|
|
expect(await clients.countByUser(other.id)).toBe(1);
|
|
});
|
|
|
|
it('OAUTHCLIENTREPO-004: countAnonymous counts only NULL-user rows', async () => {
|
|
const { user } = createUser(testDb);
|
|
await seedClient({ userId: user.id });
|
|
await seedClient({ userId: null });
|
|
await seedClient({ userId: null });
|
|
expect(await clients.countAnonymous()).toBe(2);
|
|
});
|
|
});
|
|
|
|
describe('insertClient / findPublicById (OA4/OA5)', () => {
|
|
it('OAUTHCLIENTREPO-005: writes exactly the given columns and the re-select matches', async () => {
|
|
const { user } = createUser(testDb);
|
|
const row = await clients.insertClient({
|
|
id: 'client-row-1',
|
|
user_id: user.id,
|
|
name: 'My Client',
|
|
client_id: 'proto-abc',
|
|
client_secret_hash: 'secrethash',
|
|
redirect_uris: '["https://a.example.com/cb"]',
|
|
allowed_scopes: '["trips:read","trips:write"]',
|
|
is_public: 0,
|
|
created_via: 'settings_ui',
|
|
allows_client_credentials: 0,
|
|
});
|
|
expect(row).toMatchObject({
|
|
id: 'client-row-1',
|
|
user_id: user.id,
|
|
name: 'My Client',
|
|
client_id: 'proto-abc',
|
|
redirect_uris: '["https://a.example.com/cb"]',
|
|
allowed_scopes: '["trips:read","trips:write"]',
|
|
is_public: 0,
|
|
created_via: 'settings_ui',
|
|
allows_client_credentials: 0,
|
|
});
|
|
const raw = await storedClient('client-row-1');
|
|
expect(raw?.client_secret_hash).toBe('secrethash');
|
|
});
|
|
|
|
it('OAUTHCLIENTREPO-005b: findPublicById is null for an unknown id', async () => {
|
|
expect(await clients.findPublicById('nope')).toBeNull();
|
|
});
|
|
|
|
it('OAUTHCLIENTREPO-005c: findPublicById — created_at NULL comes back null, not undefined (coverage: rule 16)', async () => {
|
|
const { id } = await seedClient({ name: 'null-created-public' });
|
|
await updateRows(t, OauthClients, { id }, { created_at: null });
|
|
const row = await clients.findPublicById(id);
|
|
expect(row?.created_at).toBeNull();
|
|
});
|
|
|
|
it('OAUTHCLIENTREPO-006: insertClient writes a NULL user_id for anonymous DCR clients', async () => {
|
|
const row = await clients.insertClient({
|
|
id: 'client-row-2',
|
|
user_id: null,
|
|
name: 'DCR Client',
|
|
client_id: 'proto-dcr',
|
|
client_secret_hash: 'x',
|
|
redirect_uris: '[]',
|
|
allowed_scopes: '[]',
|
|
is_public: 1,
|
|
created_via: 'dcr',
|
|
allows_client_credentials: 0,
|
|
});
|
|
expect(row.user_id).toBeNull();
|
|
});
|
|
|
|
it('OAUTHCLIENTREPO-006b: throws when the read-back after insert finds no row (coverage: the guard branch)', async () => {
|
|
const spy = vi.spyOn(clients, 'findPublicById').mockResolvedValueOnce(null);
|
|
await expect(clients.insertClient({
|
|
id: 'client-row-ghost',
|
|
user_id: null,
|
|
name: 'Ghost Client',
|
|
client_id: 'proto-ghost',
|
|
client_secret_hash: 'x',
|
|
redirect_uris: '[]',
|
|
allowed_scopes: '[]',
|
|
is_public: 1,
|
|
created_via: 'dcr',
|
|
allows_client_credentials: 0,
|
|
})).rejects.toThrow('OauthClientsRepository.insertClient: row client-row-ghost not found immediately after insert');
|
|
spy.mockRestore();
|
|
});
|
|
});
|
|
|
|
describe('findOwned (OA6/OA9)', () => {
|
|
it('OAUTHCLIENTREPO-007: matches id+user, returns the superset projection', async () => {
|
|
const { user } = createUser(testDb);
|
|
const { id, clientId } = await seedClient({ userId: user.id, isPublic: 1 });
|
|
const row = await clients.findOwned(id, user.id);
|
|
expect(row).toEqual({ id, client_id: clientId, is_public: 1 });
|
|
});
|
|
|
|
it('OAUTHCLIENTREPO-008: 404-shape null for another user\'s client (never 403)', async () => {
|
|
const { user } = createUser(testDb);
|
|
const { user: other } = createUser(testDb);
|
|
const { id } = await seedClient({ userId: other.id });
|
|
expect(await clients.findOwned(id, user.id)).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe('updateSecretHash (OA7)', () => {
|
|
it('OAUTHCLIENTREPO-009: writes the new hash, nothing else', async () => {
|
|
const { id } = await seedClient({ secretHash: 'old' });
|
|
await clients.updateSecretHash(id, 'new-hash');
|
|
const row = await storedClient(id);
|
|
expect(row?.client_secret_hash).toBe('new-hash');
|
|
});
|
|
});
|
|
|
|
describe('remove (OA10)', () => {
|
|
it('OAUTHCLIENTREPO-010: deletes the row', async () => {
|
|
const { id } = await seedClient();
|
|
await clients.remove(id);
|
|
expect(await storedClient(id)).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe('findSdkProjection (OA15)', () => {
|
|
it('OAUTHCLIENTREPO-011: never carries client_secret_hash', async () => {
|
|
const { clientId } = await seedClient({ secretHash: 'super-secret', name: 'SDK Client' });
|
|
const row = await clients.findSdkProjection(clientId);
|
|
expect(row).toEqual({
|
|
client_id: clientId,
|
|
name: 'SDK Client',
|
|
redirect_uris: '["https://example.com/cb"]',
|
|
allowed_scopes: '["trips:read"]',
|
|
is_public: 0,
|
|
created_via: 'settings_ui',
|
|
});
|
|
expect(row).not.toHaveProperty('client_secret_hash');
|
|
});
|
|
|
|
it('OAUTHCLIENTREPO-012: null for unknown client_id', async () => {
|
|
expect(await clients.findSdkProjection('nonexistent')).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe('findAuthRow (OA21)', () => {
|
|
it('OAUTHCLIENTREPO-013: exactly the three auth columns, a distinct projection from OA15', async () => {
|
|
const { clientId } = await seedClient({ secretHash: 'auth-secret', isPublic: 0 });
|
|
const row = await clients.findAuthRow(clientId);
|
|
expect(row).toEqual({ client_id: clientId, client_secret_hash: 'auth-secret', is_public: 0 });
|
|
});
|
|
|
|
it('OAUTHCLIENTREPO-013b: null for unknown client_id', async () => {
|
|
expect(await clients.findAuthRow('nope')).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe('findByClientIdFull (OA29/OA30)', () => {
|
|
it('OAUTHCLIENTREPO-014: the full row, including the secret hash', async () => {
|
|
const { user } = createUser(testDb);
|
|
const { clientId } = await seedClient({ userId: user.id, secretHash: 'full-row-secret' });
|
|
const row = await clients.findByClientIdFull(clientId);
|
|
expect(row?.client_secret_hash).toBe('full-row-secret');
|
|
expect(row?.user_id).toBe(user.id);
|
|
});
|
|
|
|
it('OAUTHCLIENTREPO-015: null for unknown client_id', async () => {
|
|
expect(await clients.findByClientIdFull('nope')).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe('identity-map write-back regression (program RULING, D-shape)', () => {
|
|
// task-4-review.md F1: the D-shape needs the `nativeUpdate`'s target
|
|
// column in the FIRST, WIDER projection and absent from the SECOND,
|
|
// narrower one — a stale write-back only reverts a column the second
|
|
// read's snapshot doesn't already carry fresh. The original ordering
|
|
// here (`listByUser`, narrow, then `findAuthRow`, wide) had it backwards:
|
|
// `findAuthRow`'s own re-snapshot of `client_secret_hash` left that
|
|
// column clean, so the mutation this test exists to catch (reverting
|
|
// `disableIdentityMap: true` back to `refresh: true`) passed anyway.
|
|
// `findAuthRow` (wide, carries `client_secret_hash`) now goes FIRST and
|
|
// `findOwned` (narrow, no `client_secret_hash`) second — mutation-proven
|
|
// load-bearing in the task report.
|
|
it('OAUTHCLIENTREPO-016: findAuthRow then findOwned then updateSecretHash inside uow.transactional — the write survives', async () => {
|
|
const { user } = createUser(testDb);
|
|
const { id, clientId } = await seedClient({ userId: user.id, secretHash: 'original', name: 'kept-name' });
|
|
|
|
await withRequestContext(t.orm, async () => {
|
|
// Projection A — wide, carries client_secret_hash.
|
|
await clients.findAuthRow(clientId);
|
|
// Projection B — narrow, a different (smaller) field set on the same row.
|
|
await clients.findOwned(id, user.id);
|
|
// The intended write, inside the request's own transaction.
|
|
await uow.transactional(async () => {
|
|
await clients.updateSecretHash(id, 'rotated');
|
|
});
|
|
});
|
|
|
|
const row = await storedClient(id);
|
|
expect(row?.client_secret_hash).toBe('rotated'); // the nativeUpdate must stick
|
|
expect(row?.name).toBe('kept-name'); // untouched by either read
|
|
});
|
|
});
|
|
});
|