Files
ApiCore/ApiCore-Backend/test/import.e2e-spec.ts
T
Nick SzaunigandClaude Sonnet 5 139ea6fdd7 feat: RBAC Rollen & Rechte (Phase 1 - Datenmodell, Roles-Verwaltung, Guard-Infrastruktur)
Replaces the fixed 5-value Role enum with a database-driven Role/Permission
model: admins can create custom roles with a precise per-resource/action
permission set (83-key code-owned catalog), instead of being locked to
ADMIN/BEEKEEPER/STAFF/READONLY/API_CLIENT.

- New Role/Permission/RolePermission tables; legacy Role enum renamed to
  LegacyRole and kept as User.legacyRole so all existing @Roles() call
  sites keep working unchanged during the migration.
- New RolesController/RolesService (CRUD, permission-set editing,
  deactivate/reactivate) with lockout-prevention invariants: system roles
  (ADMIN) can't be edited or deactivated, and a role still assigned to
  users can't be deactivated.
- New PermissionResolverService (30s-cached, DB-fresh per user) and
  PermissionsGuard + @RequirePermission(), registered as an additional
  APP_GUARD alongside the legacy RolesGuard so both systems run
  side-by-side until controllers are migrated in Phase 2.
- PermissionCatalogSyncService seeds any new catalog entries into the DB
  on boot, so future features only touch the TS catalog.
- New GET /auth/me returns the caller's role and effective permissions.
- Migration hand-written (destructive column rename) with grants derived
  from a fresh grep of every existing @Roles() call site, verified
  against 5 controllers read in full for STAFF's exact write boundary.
- test/roles.e2e-spec.ts covers the new endpoints and invariants end to
  end; test/authorization-coverage.e2e-spec.ts added but skipped until
  Phase 2 gives every controller a @RequirePermission.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-08-26 06:52:24 +02:00

191 lines
6.1 KiB
TypeScript

import { INestApplication } from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import request from 'supertest';
import { App } from 'supertest/types';
import { PrismaService } from '../src/prisma/prisma.service';
import { createTestApp } from './utils/create-test-app';
import { login } from './utils/api';
interface ImportRowBody {
row: number;
status: 'created' | 'skipped' | 'error';
message?: string;
id?: string;
}
interface ImportReportBody {
entity: string;
totalRows: number;
created: number;
skipped: number;
errors: number;
rows: ImportRowBody[];
}
function csvFile(content: string) {
return Buffer.from(content, 'utf-8');
}
describe('Import (e2e)', () => {
let app: INestApplication<App>;
let prisma: PrismaService;
const adminEmail = `import-e2e-admin-${Date.now()}@example.com`;
const staffEmail = `import-e2e-staff-${Date.now()}@example.com`;
const password = 'SuperSecret123!';
let adminId: string;
let staffId: string;
let adminToken: string;
let staffToken: string;
let apiaryId: string;
const apiaryName = `Import-Stand-${Date.now()}`;
beforeAll(async () => {
app = await createTestApp();
prisma = app.get(PrismaService);
const passwordHash = await bcrypt.hash(password, 12);
const admin = await prisma.user.create({
data: {
email: adminEmail,
passwordHash,
name: 'Import E2E Admin',
legacyRole: 'ADMIN',
role: { connect: { key: 'ADMIN' } },
},
});
adminId = admin.id;
const staff = await prisma.user.create({
data: {
email: staffEmail,
passwordHash,
name: 'Import E2E Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } },
},
});
staffId = staff.id;
adminToken = (await login(app, adminEmail, password)).accessToken;
staffToken = (await login(app, staffEmail, password)).accessToken;
const apiary = await prisma.apiary.create({ data: { name: apiaryName } });
apiaryId = apiary.id;
});
afterAll(async () => {
await prisma.colony.deleteMany({ where: { apiaryId } });
await prisma.apiary.deleteMany({ where: { id: apiaryId } });
await prisma.apiary.deleteMany({
where: { name: { startsWith: 'CSV-Bienenstand-' } },
});
await prisma.queen.deleteMany({
where: { code: { startsWith: 'CSV-Q-' } },
});
await prisma.refreshToken.deleteMany({
where: { userId: { in: [adminId, staffId] } },
});
await prisma.auditLog.deleteMany({
where: { userId: { in: [adminId, staffId] } },
});
await prisma.user.deleteMany({ where: { id: { in: [adminId, staffId] } } });
await app.close();
});
it('rejects a non-admin', () => {
return request(app.getHttpServer())
.post('/api/v1/import/apiaries')
.set('Authorization', `Bearer ${staffToken}`)
.attach('file', csvFile('name\nTest'), {
filename: 'apiaries.csv',
contentType: 'text/csv',
})
.expect(403);
});
it('rejects a file without a .csv extension', () => {
return request(app.getHttpServer())
.post('/api/v1/import/apiaries')
.set('Authorization', `Bearer ${adminToken}`)
.attach('file', csvFile('name\nTest'), {
filename: 'apiaries.txt',
contentType: 'text/plain',
})
.expect(400);
});
it('imports apiaries, reporting one created and one validation error', async () => {
const csv = `name,location\nCSV-Bienenstand-${Date.now()},Garten\n,Ohne Namen`;
const response = await request(app.getHttpServer())
.post('/api/v1/import/apiaries')
.set('Authorization', `Bearer ${adminToken}`)
.attach('file', csvFile(csv), {
filename: 'apiaries.csv',
contentType: 'text/csv',
})
.expect(201);
const report = response.body as ImportReportBody;
expect(report.entity).toBe('apiaries');
expect(report.totalRows).toBe(2);
expect(report.created).toBe(1);
expect(report.errors).toBe(1);
expect(report.rows[1].status).toBe('error');
});
it('imports colonies, resolving the apiary by name and skipping duplicate codes on re-import', async () => {
const code = `CSV-V-${Date.now()}`;
const csv = `code,apiaryName,colonyType\n${code},${apiaryName},PRODUCTION_COLONY`;
const firstResponse = await request(app.getHttpServer())
.post('/api/v1/import/colonies')
.set('Authorization', `Bearer ${adminToken}`)
.attach('file', csvFile(csv), {
filename: 'colonies.csv',
contentType: 'text/csv',
})
.expect(201);
const firstReport = firstResponse.body as ImportReportBody;
expect(firstReport.created).toBe(1);
const secondResponse = await request(app.getHttpServer())
.post('/api/v1/import/colonies')
.set('Authorization', `Bearer ${adminToken}`)
.attach('file', csvFile(csv), {
filename: 'colonies.csv',
contentType: 'text/csv',
})
.expect(201);
const secondReport = secondResponse.body as ImportReportBody;
expect(secondReport.created).toBe(0);
expect(secondReport.skipped).toBe(1);
});
it('reports an error when the referenced apiary is unknown', async () => {
const csv = `code,apiaryName,colonyType\nCSV-V-Unknown,Nicht Vorhanden,PRODUCTION_COLONY`;
const response = await request(app.getHttpServer())
.post('/api/v1/import/colonies')
.set('Authorization', `Bearer ${adminToken}`)
.attach('file', csvFile(csv), {
filename: 'colonies.csv',
contentType: 'text/csv',
})
.expect(201);
const report = response.body as ImportReportBody;
expect(report.errors).toBe(1);
expect(report.rows[0].message).toContain('nicht gefunden');
});
it('imports queens', async () => {
const code = `CSV-Q-${Date.now()}`;
const csv = `code,breed\n${code},Carnica`;
const response = await request(app.getHttpServer())
.post('/api/v1/import/queens')
.set('Authorization', `Bearer ${adminToken}`)
.attach('file', csvFile(csv), {
filename: 'queens.csv',
contentType: 'text/csv',
})
.expect(201);
const report = response.body as ImportReportBody;
expect(report.created).toBe(1);
});
});