test(storage): run the reclaim e2e and source check on the whole app

The reclaim e2e and the source-registration check mocked src/db/database,
which lint:test-mocks holds at zero for new files; both now boot buildApp
against the worker's snapshot db. The key parser drops its non-null
assertions (the indexed reads are typed string already), and the e2e sends
its refused bodies at once instead of awaiting inside a loop, so the eslint
ratchet stays where it was.
This commit is contained in:
Maurice
2026-11-01 14:20:00 +01:00
parent db0fbc1ccd
commit f44dd92ee0
3 changed files with 31 additions and 58 deletions
@@ -95,7 +95,7 @@ export function uploadKeysIn(value: string | null | undefined): StorageKeyRef[]
const next = matches[i + 1];
const tail = value.slice(start, next ? next.index : value.length);
const end = tail.search(KEY_END);
const category = match[1]!.toLowerCase();
const category = match[1].toLowerCase();
return keyVariants(end === -1 ? tail : tail.slice(0, end)).map((key) => ({ category, key }));
});
}
@@ -113,9 +113,9 @@ export function storageKeysIn(value: string | null | undefined, options: Storage
if (trimmed === '') return [];
const refs = uploadKeysIn(value);
const relative = /^\.?\/?([a-z0-9][a-z0-9-]*)\/(.+)$/i.exec(trimmed);
if (relative && SERVED.has(relative[1]!.toLowerCase())) {
const category = relative[1]!.toLowerCase();
for (const key of keyVariants(relative[2]!)) refs.push({ category, key });
if (relative && SERVED.has(relative[1].toLowerCase())) {
const category = relative[1].toLowerCase();
for (const key of keyVariants(relative[2])) refs.push({ category, key });
}
if (options.bare) {
const bare = options.bare;
@@ -166,7 +166,7 @@ function keyVariants(raw: string): string[] {
const whole = stripSuffix(raw);
for (const form of [whole, decoded(whole)]) {
add(form);
add(form.trim().split(/\s/)[0]!);
add(form.trim().split(/\s/)[0] ?? '');
}
return [...forms];
}
+24 -44
View File
@@ -1,38 +1,26 @@
/**
* Storage reclaim e2e: /api/admin/storage/reclaim through the real
* JwtAuthGuard + AdminGuard + ManagedGuard against a migrated temp SQLite, the
* Zod pipe on both bodies and the response contracts the handlers declare.
* This graph holds StorageModule alone, so no domain registers a reference
* source: every reclaimable category reports `sources_missing` and a pass
* cannot delete anything, which is the point of the ledger. RCLE-001 to RCLE-007.
* Storage reclaim e2e: /api/admin/storage/reclaim on the whole app (buildApp
* against the worker's snapshot test db), so the real JwtAuthGuard,
* AdminGuard and ManagedGuard, the Zod pipe on both bodies and the response
* contracts the handlers declare all stand in front of it. Every owner
* domain registers its reference source here, so a pass looks at every
* reclaimable category; the passes below only report. RCLE-001 to RCLE-007.
*/
import { db } from '../../src/db/database';
import { buildApp } from '../../src/bootstrap';
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { ManagedGuard } from '../../src/nest/common/managed.guard';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { StorageJobsService } from '../../src/nest/storage/storage-jobs.service';
import { STORAGE_RECLAIMABLE_CATEGORIES } from '../../src/nest/storage/storage-reclaim.types';
import { StorageModule } from '../../src/nest/storage/storage.module';
import { countRows, deleteRows, findRow } from '../helpers/factories/rows';
import { makeAdmin, makeUser } from '../helpers/factories/users';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { Test } from '@nestjs/testing';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
@@ -41,29 +29,19 @@ vi.mock('../../src/nest/audit/audit-log.logger', () => ({
logWarn: vi.fn(),
}));
describe('Storage reclaim e2e (real auth + admin guard + managed guard + migrated temp SQLite)', () => {
let orm: TestOrm;
describe('Storage reclaim e2e (whole app: real auth + admin guard + managed guard)', () => {
let orm: MikroORM;
let app: INestApplication;
let server: Server;
let adminCookie: string;
let userCookie: string;
beforeAll(async () => {
orm = await createTestOrm(db);
await makeUser(orm, { id: 1, email: 'e2e-reclaim@example.test' });
await makeAdmin(orm, { id: 2, email: 'e2e-reclaim-admin@example.test' });
userCookie = sessionCookie(1);
adminCookie = sessionCookie(2);
const moduleRef = await Test.createTestingModule({
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), StorageModule],
providers: [{ provide: APP_GUARD, useClass: ManagedGuard }],
}).compile();
app = moduleRef.createNestApplication();
app.use(cookieParser());
app.useGlobalPipes(new ZodValidationPipe());
app.useGlobalFilters(new TrekExceptionFilter());
await app.init();
app = await buildApp();
orm = app.get(MikroORM);
server = app.getHttpServer();
userCookie = sessionCookie((await makeUser(orm, { email: 'e2e-reclaim@example.test' })).user.id);
adminCookie = sessionCookie((await makeAdmin(orm, { email: 'e2e-reclaim-admin@example.test' })).user.id);
});
beforeEach(async () => {
@@ -72,8 +50,7 @@ describe('Storage reclaim e2e (real auth + admin guard + managed guard + migrate
});
afterAll(async () => {
await app.close();
await orm.close();
await app?.close();
});
it('RCLE-001: 401 without a session on both routes', async () => {
@@ -105,10 +82,12 @@ describe('Storage reclaim e2e (real auth + admin guard + managed guard + migrate
});
it('RCLE-004: PUT refuses a body outside the contract', async () => {
for (const body of [{}, { deleteEnabled: 'yes' }, { deleteEnabled: true, extra: 1 }]) {
const res = await request(server).put('/api/admin/storage/reclaim').set('Cookie', adminCookie).send(body);
expect(res.status).toBe(400);
}
const refused = await Promise.all(
[{}, { deleteEnabled: 'yes' }, { deleteEnabled: true, extra: 1 }].map((body) =>
request(server).put('/api/admin/storage/reclaim').set('Cookie', adminCookie).send(body),
),
);
expect(refused.map((res) => res.status)).toEqual([400, 400, 400]);
const run = await request(server)
.post('/api/admin/storage/reclaim/run')
.set('Cookie', adminCookie)
@@ -117,7 +96,7 @@ describe('Storage reclaim e2e (real auth + admin guard + managed guard + migrate
expect(await countRows(orm, AuditLog)).toBe(0);
});
it('RCLE-005: a pass without registered sources skips every reclaimable category, persists and audits', async () => {
it('RCLE-005: a report-only pass asks every registered source, deletes nothing, persists and audits', async () => {
const res = await request(server)
.post('/api/admin/storage/reclaim/run')
.set('Cookie', adminCookie)
@@ -125,7 +104,8 @@ describe('Storage reclaim e2e (real auth + admin guard + managed guard + migrate
expect(res.status).toBe(200);
expect(res.body.mode).toBe('report');
for (const category of STORAGE_RECLAIMABLE_CATEGORIES) {
expect(res.body.categories[category].skipped).toBe('sources_missing');
expect(res.body.categories[category].skipped).not.toBe('sources_missing');
expect(res.body.categories[category].deleted).toEqual({ objects: 0, bytes: 0 });
}
expect(res.body.categories.backups.skipped).toBe('not_reclaimed');
const audit = await findRow(orm, AuditLog, { action: 'admin.storage_reclaim_run' });
@@ -8,7 +8,6 @@
* forever, or swept while a domain's rows were never asked.
*/
import { buildApp } from '../../src/bootstrap';
import { db as testDb } from '../../src/db/database';
import { StorageReclaimRegistryService } from '../../src/nest/storage/storage-reclaim-registry.service';
import {
RECLAIM_LEDGER,
@@ -17,12 +16,7 @@ import {
} from '../../src/nest/storage/storage-reclaim.ledger';
import type { INestApplication } from '@nestjs/common';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
describe('RECLAIM-SRC: the app registers what the reclaim ledger waits for', () => {
let app: INestApplication;
@@ -32,8 +26,7 @@ describe('RECLAIM-SRC: the app registers what the reclaim ledger waits for', ()
});
afterAll(async () => {
await app.close();
testDb.close();
await app?.close();
});
it('RECLAIM-SRC-001: the registered source ids are exactly the ones the ledger requires', () => {