test(server): seed the service, MCP and route specs through the ORM factories

Service, MCP, integration and e2e suites with up to a dozen raw
statements now seed and read through the factories. A buildApp() suite
uses the app's own ORM, a partial-module e2e or a unit suite a
createTestOrm() or sharedTestOrm() handle on its database. Reads that
used to come back undefined now come back null, and the assertions say
so; where a projected SELECT was compared whole, the same columns are
picked off the row.

Two reads inside the scheduler's delivery callback stay synchronous raw
statements, marked, so they keep seeing the row at the moment of
delivery. Two more database mocks lose a canAccessTrip/isOwner stand-in
the module no longer exports.
This commit is contained in:
Maurice
2026-10-08 15:49:34 +02:00
parent d28e91d056
commit e2ce2ad05c
25 changed files with 727 additions and 555 deletions
+35 -33
View File
@@ -50,7 +50,12 @@ import { SessionRenewalInterceptor } from '../../src/nest/auth/session-renewal.i
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { countRows, deleteRows, findRow, findRows, updateRows } from '../helpers/factories/rows';
import { readAppSetting, setAppSetting } from '../helpers/factories/settings';
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { Users } from '../../src/db/entities/Users.entity';
describe('Auth e2e (real auth guard + real service + real cookie service + temp SQLite)', () => {
let server: Server;
@@ -79,10 +84,11 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
return nest;
}
const auditRows = (action: string) =>
(db.prepare('SELECT COUNT(*) AS n FROM audit_log WHERE action = ?').get(action) as { n: number }).n;
let orm: TestOrm;
const auditRows = (action: string) => countRows(orm, AuditLog, { action });
beforeAll(async () => {
orm = await createTestOrm(db);
const seeded = createUser(db as never, { username: 'auth-e2e', email: 'u@example.test' });
userId = seeded.user.id;
userEmail = seeded.user.email;
@@ -93,6 +99,7 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
afterAll(async () => {
await app.close();
await orm.close();
});
it('GET /app-config is optional-auth (200 without a cookie, real toggles)', async () => {
@@ -119,22 +126,22 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
});
it('POST /login sets the httpOnly trek_session cookie and audits user.login', async () => {
const before = auditRows('user.login');
const before = await auditRows('user.login');
const res = await request(server).post('/api/auth/login').send({ email: userEmail, password: userPassword });
expect(res.status).toBe(200);
expect(typeof res.body.token).toBe('string');
expect(res.body.user.id).toBe(userId);
const setCookie = res.headers['set-cookie'] as unknown as string[];
expect(setCookie.some((c) => c.startsWith('trek_session=') && /HttpOnly/i.test(c))).toBe(true);
expect(auditRows('user.login')).toBe(before + 1);
expect(await auditRows('user.login')).toBe(before + 1);
}, 10000);
it('POST /login with a wrong password answers the generic 401 and audits user.login_failed', async () => {
const before = auditRows('user.login_failed');
const before = await auditRows('user.login_failed');
const res = await request(server).post('/api/auth/login').send({ email: userEmail, password: 'wrong-password' });
expect(res.status).toBe(401);
expect(res.body).toEqual({ error: 'Invalid email or password' });
expect(auditRows('user.login_failed')).toBe(before + 1);
expect(await auditRows('user.login_failed')).toBe(before + 1);
}, 10000);
it('POST /login with remember_me sets a persistent cookie (Max-Age present)', async () => {
@@ -227,7 +234,7 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
}, 10000);
it('POST /register creates the user, sets the cookie and audits user.register', async () => {
const before = auditRows('user.register');
const before = await auditRows('user.register');
const res = await request(server)
.post('/api/auth/register')
.send({ username: 'fresh-e2e', email: 'fresh-e2e@example.test', password: 'Str0ng!Pass1' });
@@ -236,9 +243,9 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
expect(res.body.user.username).toBe('fresh-e2e');
const setCookie = res.headers['set-cookie'] as unknown as string[];
expect(setCookie.some((c) => c.startsWith('trek_session=') && /HttpOnly/i.test(c))).toBe(true);
expect(auditRows('user.register')).toBe(before + 1);
const row = db.prepare('SELECT id FROM users WHERE email = ?').get('fresh-e2e@example.test');
expect(row).toBeDefined();
expect(await auditRows('user.register')).toBe(before + 1);
const row = await findRow(orm, Users, { email: 'fresh-e2e@example.test' });
expect(row).not.toBeNull();
});
it('POST /login with a shapeless body answers the pipe 400 envelope', async () => {
@@ -250,7 +257,7 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
it('PUT /me/api-keys stores the key instance-wide and audits it once (#1939)', async () => {
const admin = createUser(db as never, { username: 'keys-admin', email: 'keys-admin@example.test', role: 'admin' });
const before = auditRows('settings.api_keys_update');
const before = await auditRows('settings.api_keys_update');
const res = await request(server)
.put('/api/auth/me/api-keys')
@@ -263,16 +270,14 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
expect(res.body).not.toHaveProperty('changedKeys');
// What every member's search will now resolve to, encrypted at rest.
const stored = db.prepare("SELECT value FROM app_settings WHERE key = 'maps_api_key'").get() as { value: string };
expect(stored.value).toMatch(/^enc:v1:/);
const stored = await readAppSetting(orm, 'maps_api_key');
expect(stored).toMatch(/^enc:v1:/);
// And the admin panel reads back what the search uses.
const settings = await request(server).get('/api/auth/me/settings').set('Cookie', sessionCookie(admin.user.id));
expect(settings.body.settings.maps_api_key).toBe('e2e-google-key');
expect(auditRows('settings.api_keys_update')).toBe(before + 1);
const row = db
.prepare("SELECT resource, details FROM audit_log WHERE action = 'settings.api_keys_update' ORDER BY id DESC LIMIT 1")
.get() as { resource: string; details: string };
expect(await auditRows('settings.api_keys_update')).toBe(before + 1);
const [row] = await findRows(orm, AuditLog, { action: 'settings.api_keys_update' }, { id: 'desc' });
expect(row.resource).toBe('api_keys');
expect(row.details).toContain('maps_api_key');
expect(row.details).not.toContain('e2e-google-key');
@@ -282,7 +287,7 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
.put('/api/auth/me/api-keys')
.set('Cookie', sessionCookie(admin.user.id))
.send({ maps_api_key: 'e2e-google-key' });
expect(auditRows('settings.api_keys_update')).toBe(before + 1);
expect(await auditRows('settings.api_keys_update')).toBe(before + 1);
}, 10000);
it('GET /me/settings names the variable behind a key set in the environment, never its value (#1881)', async () => {
@@ -306,15 +311,12 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
const admin = createUser(db as never, { username: 'keys-cfg-admin', email: 'keys-cfg-admin@example.test', role: 'admin' });
// Seeded here instead of riding on the save above, so running this case on
// its own asserts the same thing.
const setInstanceKey = (value: string | null) => {
const setInstanceKey = async (value: string | null) => {
if (value === null) {
db.prepare("DELETE FROM app_settings WHERE key = 'maps_api_key'").run();
await deleteRows(orm, AppSettings, { key: 'maps_api_key' });
return;
}
db.prepare(
`INSERT INTO app_settings (key, value) VALUES ('maps_api_key', ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value`
).run(encrypt_api_key(value));
await setAppSetting(orm, 'maps_api_key', encrypt_api_key(value));
};
const hasMapsKey = async (userId: number) => {
const res = await request(server).get('/api/auth/app-config').set('Cookie', sessionCookie(userId));
@@ -322,8 +324,8 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
return res.body.has_maps_key;
};
setInstanceKey('instance-configured-key');
db.prepare('UPDATE users SET maps_api_key = NULL WHERE id = ?').run(admin.user.id);
await setInstanceKey('instance-configured-key');
await updateRows(orm, Users, { id: admin.user.id }, { maps_api_key: null });
// Instance key, no column anywhere: the member searches with it, so the
// client is told the feature is there.
expect(await hasMapsKey(member.user.id)).toBe(true);
@@ -331,22 +333,22 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
// The reported half of #1939: the key exists only in one admin's column.
// It is not the member's to spend, so they are told there is none instead
// of being offered a Google search that answers 403.
setInstanceKey(null);
db.prepare('UPDATE users SET maps_api_key = ? WHERE id = ?').run(encrypt_api_key('admins-own-key'), admin.user.id);
await setInstanceKey(null);
await updateRows(orm, Users, { id: admin.user.id }, { maps_api_key: encrypt_api_key('admins-own-key') });
expect(await hasMapsKey(member.user.id)).toBe(false);
// That same column still counts for the admin themselves.
expect(await hasMapsKey(admin.user.id)).toBe(true);
});
describe('passkey origin gate (#2147)', () => {
beforeAll(() => {
db.prepare("INSERT INTO app_settings (key, value) VALUES ('passkey_login', 'true') ON CONFLICT(key) DO UPDATE SET value = 'true'").run();
beforeAll(async () => {
await setAppSetting(orm, 'passkey_login', 'true');
// What getAppUrl() really yields with APP_URL unset — the phantom config.
appUrlRef.value = 'http://localhost:3001';
});
afterAll(() => {
db.prepare("DELETE FROM app_settings WHERE key = 'passkey_login'").run();
afterAll(async () => {
await deleteRows(orm, AppSettings, { key: 'passkey_login' });
appUrlRef.value = 'https://x';
});
+13 -7
View File
@@ -84,11 +84,15 @@ import { FilesModule } from '../../src/nest/files/files.module';
import { PhotosModule } from '../../src/nest/photos/photos.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { deleteRows, insertRow, updateRows } from '../helpers/factories/rows';
import { Trips } from '../../src/db/entities/Trips.entity';
import { TripFiles } from '../../src/db/entities/TripFiles.entity';
describe('Files + photos e2e (real auth guard + temp SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
let orm: TestOrm;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), RealtimeModule, FilesModule, PhotosModule] }).compile();
@@ -101,9 +105,10 @@ describe('Files + photos e2e (real auth guard + temp SQLite)', () => {
beforeAll(async () => {
seedUser(db as never, { id: 1 });
db.prepare('INSERT INTO trips (id, user_id, title) VALUES (5, 1, ?)').run('Trip');
db.prepare("INSERT INTO trip_files (id, trip_id, filename, original_name, uploaded_by) VALUES (1, 5, 'stored-a.pdf', 'a.pdf', 1)").run();
db.prepare("INSERT INTO trip_files (id, trip_id, filename, original_name, uploaded_by, starred) VALUES (9, 5, 'stored-b.pdf', 'b.pdf', 1, 0)").run();
orm = await createTestOrm(db);
await insertRow(orm, Trips, { id: 5, user: 1, title: 'Trip' });
await insertRow(orm, TripFiles, { id: 1, trip: 5, filename: 'stored-a.pdf', original_name: 'a.pdf', uploadedByRef: 1 });
await insertRow(orm, TripFiles, { id: 9, trip: 5, filename: 'stored-b.pdf', original_name: 'b.pdf', uploadedByRef: 1, starred: 0 });
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
server = app.getHttpServer();
@@ -118,6 +123,7 @@ describe('Files + photos e2e (real auth guard + temp SQLite)', () => {
afterAll(async () => {
await app.close();
await orm.close();
});
it('401 listing files without a session cookie', async () => {
@@ -140,13 +146,13 @@ describe('Files + photos e2e (real auth guard + temp SQLite)', () => {
// longer intercepts it. Trip 5 is a persistent row seeded once in
// `beforeAll` (not re-seeded per test), so it is removed and restored
// around this one assertion instead.
db.prepare('DELETE FROM trips WHERE id = 5').run();
await deleteRows(orm, Trips, { id: 5 });
try {
const res = await request(server).get('/api/trips/5/files').set('Cookie', sessionCookie(1));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
} finally {
db.prepare("INSERT INTO trips (id, user_id, title) VALUES (5, 1, 'Trip')").run();
await insertRow(orm, Trips, { id: 5, user: 1, title: 'Trip' });
}
});
@@ -156,7 +162,7 @@ describe('Files + photos e2e (real auth guard + temp SQLite)', () => {
expect(res.body.file.id).toBe(9);
expect(res.body.file.starred).toBe(1);
// put it back so the case is order-independent
db.prepare('UPDATE trip_files SET starred = 0 WHERE id = 9').run();
await updateRows(orm, TripFiles, { id: 9 }, { starred: 0 });
});
it('403 deleting without file_delete permission', async () => {
+43 -37
View File
@@ -32,7 +32,11 @@ import { NotificationsModule } from '../../src/nest/notifications/notifications.
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { deleteRows, findRows } from '../helpers/factories/rows';
import { readAppSetting, setAppSetting } from '../helpers/factories/settings';
import { makeUser } from '../helpers/factories/users';
import { PushSubscriptions } from '../../src/db/entities/PushSubscriptions.entity';
const ENDPOINT = 'https://fcm.googleapis.com/fcm/send/e2e-device';
@@ -46,15 +50,22 @@ function subscription(endpoint = ENDPOINT) {
};
}
function rows() {
return db
.prepare('SELECT user_id, endpoint, vapid_public_key, user_agent FROM push_subscriptions ORDER BY id')
.all() as {
user_id: number;
endpoint: string;
vapid_public_key: string;
user_agent: string | null;
}[];
let orm: TestOrm;
async function rows() {
return (await findRows(orm, PushSubscriptions, {}, { id: 'asc' })).map((r) => ({
user_id: r.user_id,
endpoint: r.endpoint,
vapid_public_key: r.vapid_public_key,
user_agent: r.user_agent,
}));
}
/** An app setting the push service keeps; fails the case when it is not there. */
async function storedSetting(key: string): Promise<string> {
const value = await readAppSetting(orm, key);
if (value === null) throw new Error(`no app setting ${key}`);
return value;
}
describe('Web Push e2e (real auth guard + temp SQLite)', () => {
@@ -74,24 +85,22 @@ describe('Web Push e2e (real auth guard + temp SQLite)', () => {
}
beforeAll(async () => {
// harness.ts's seedUser() omits password_hash, which the migrated schema
// requires NOT NULL: a raw insert of the same SeededUser shape instead.
const seed = db.prepare(
"INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES (?, ?, ?, 'x', 'user', 0)",
);
seed.run(1, 'e2e-user-1', 'one@example.test');
seed.run(2, 'e2e-user-2', 'two@example.test');
// The two users the session cookies are signed for, pinned to ids 1 and 2.
orm = await createTestOrm(db);
await makeUser(orm, { id: 1, username: 'e2e-user-1', email: 'one@example.test', role: 'user', password_version: 0 });
await makeUser(orm, { id: 2, username: 'e2e-user-2', email: 'two@example.test', role: 'user', password_version: 0 });
app = await build();
server = app.getHttpServer();
});
beforeEach(() => {
db.prepare('DELETE FROM push_subscriptions').run();
beforeEach(async () => {
await deleteRows(orm, PushSubscriptions);
safeFetchFollow.mockReset();
});
afterAll(async () => {
await app.close();
await orm.close();
});
it('401 on every push route without a session cookie', async () => {
@@ -106,12 +115,10 @@ describe('Web Push e2e (real auth guard + temp SQLite)', () => {
});
it('GET public-key: the pair exists from bootstrap on, so the route only reads it', async () => {
const stored = db.prepare("SELECT value FROM app_settings WHERE key = 'web_push_vapid_public_key'").get() as {
value: string;
};
const stored = await storedSetting('web_push_vapid_public_key');
const res = await request(server).get('/api/notifications/push/public-key').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ publicKey: stored.value });
expect(res.body).toEqual({ publicKey: stored });
const raw = Buffer.from(res.body.publicKey, 'base64url');
expect(raw.length).toBe(65);
expect(raw[0]).toBe(0x04);
@@ -128,7 +135,7 @@ describe('Web Push e2e (real auth guard + temp SQLite)', () => {
.send({ subscription: subscription() });
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true, devices: 1 });
expect(rows()).toEqual([
expect(await rows()).toEqual([
{ user_id: 1, endpoint: ENDPOINT, vapid_public_key: key.publicKey, user_agent: 'e2e-browser/1.0' },
]);
});
@@ -143,7 +150,7 @@ describe('Web Push e2e (real auth guard + temp SQLite)', () => {
.set('Cookie', sessionCookie(2))
.send({ subscription: subscription() });
expect(res.body).toEqual({ success: true, devices: 1 });
expect(rows().map((r) => r.user_id)).toEqual([2]);
expect((await rows()).map((r) => r.user_id)).toEqual([2]);
});
it('POST subscriptions: 400 with the bespoke message for a host that is not a push service', async () => {
@@ -153,7 +160,7 @@ describe('Web Push e2e (real auth guard + temp SQLite)', () => {
.send({ subscription: subscription('https://example.com/collect') });
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Push endpoint is not a known push service' });
expect(rows()).toEqual([]);
expect(await rows()).toEqual([]);
});
it('POST subscriptions: 400 from the contract when the keys are missing', async () => {
@@ -176,7 +183,7 @@ describe('Web Push e2e (real auth guard + temp SQLite)', () => {
.set('Cookie', sessionCookie(2))
.send({ endpoint: ENDPOINT });
expect(stranger.status).toBe(200);
expect(rows()).toHaveLength(1);
expect(await rows()).toHaveLength(1);
const owner = await request(server)
.delete('/api/notifications/push/subscriptions')
@@ -184,7 +191,7 @@ describe('Web Push e2e (real auth guard + temp SQLite)', () => {
.send({ endpoint: ENDPOINT });
expect(owner.status).toBe(200);
expect(owner.body).toEqual({ success: true });
expect(rows()).toEqual([]);
expect(await rows()).toEqual([]);
const again = await request(server)
.delete('/api/notifications/push/subscriptions')
@@ -225,16 +232,15 @@ describe('Web Push e2e (real auth guard + temp SQLite)', () => {
});
it('a stored private key that no longer decrypts turns push off with a 503 and is never replaced', async () => {
const readKey = (key: string) =>
(db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string }).value;
const readKey = storedSetting;
const unreadable = 'enc:v1:bm90IGEgY2lwaGVydGV4dA';
const publicKey = readKey('web_push_vapid_public_key');
const ciphertext = readKey('web_push_vapid_private_key');
const publicKey = await readKey('web_push_vapid_public_key');
const ciphertext = await readKey('web_push_vapid_private_key');
await request(server)
.post('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(1))
.send({ subscription: subscription() });
db.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(unreadable, 'web_push_vapid_private_key');
await setAppSetting(orm, 'web_push_vapid_private_key', unreadable);
try {
const key = await request(server).get('/api/notifications/push/public-key').set('Cookie', sessionCookie(1));
expect(key.status).toBe(503);
@@ -249,11 +255,11 @@ describe('Web Push e2e (real auth guard + temp SQLite)', () => {
expect(test.body).toEqual({ success: false, error: 'Web Push is currently unavailable on this server' });
expect(safeFetchFollow).not.toHaveBeenCalled();
// The device registered before stays, and neither stored row was touched.
expect(rows().map((r) => r.endpoint)).toEqual([ENDPOINT]);
expect(readKey('web_push_vapid_public_key')).toBe(publicKey);
expect(readKey('web_push_vapid_private_key')).toBe(unreadable);
expect((await rows()).map((r) => r.endpoint)).toEqual([ENDPOINT]);
expect(await readKey('web_push_vapid_public_key')).toBe(publicKey);
expect(await readKey('web_push_vapid_private_key')).toBe(unreadable);
} finally {
db.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(ciphertext, 'web_push_vapid_private_key');
await setAppSetting(orm, 'web_push_vapid_private_key', ciphertext);
}
const back = await request(server).get('/api/notifications/push/public-key').set('Cookie', sessionCookie(1));
expect(back.body).toEqual({ publicKey });