feat: RBAC Phase 3 - LegacyRole-Enum, RolesGuard und @Roles vollstaendig entfernt

Letzte Phase des RBAC-Umbaus: die transitionale Rollen-Infrastruktur,
die seit Phase 1 parallel zum neuen Role/Permission-System mitlief,
ist jetzt komplett weg.

- Prisma-Migration: User.legacyRole-Spalte und LegacyRole-Enum
  gedroppt (nichts liest die Spalte mehr, seit Phase 2 jeder Controller
  auf @RequirePermission laeuft).
- roles.guard.ts, roles.guard.spec.ts, roles.decorator.ts geloescht;
  RolesGuard aus den APP_GUARD-Providern entfernt.
- AuthenticatedUser/JWT-Payload verlieren das role-Feld (permissions
  werden ohnehin frisch pro Request aus der DB aufgeloest, nicht aus
  dem Claim).
- Users-API: CreateUserDto/UpdateUserDto akzeptieren jetzt roleId
  (eine echte Role.id) statt der alten role-Enum-Werte; UsersService
  validiert, dass die Rolle existiert und aktiv ist, bevor sie
  zugewiesen wird.
- Alle 34 e2e-Fixtures und der Seed-Script folgen dem neuen Schema.

Verifiziert: tsc, lint, build, unit (220/220), volle e2e-Suite
159/159 gruen - keine uebersprungenen Tests.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
This commit is contained in:
Nick SzaunigandClaude Sonnet 5 committed 2026-08-26 09:01:13 +02:00
1 parent 0284077d3b
commit ae53f7889e
51 files changed
+125 -224

No files matched your search

@@ -0,0 +1,10 @@
-- RBAC Phase 3: drops the transitional LegacyRole enum + User.legacyRole
-- column now that every controller runs on @RequirePermission and no code
-- reads the legacy field anymore (see permission-catalog.ts / roles module).
BEGIN;
ALTER TABLE "User" DROP COLUMN "legacyRole";
DROP TYPE "LegacyRole";
COMMIT;
-12
View File
@@ -16,17 +16,6 @@ datasource db {
// Benutzer / Auth / Audit (Abschnitt 3, 14, 15, 16) // Benutzer / Auth / Audit (Abschnitt 3, 14, 15, 16)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Superseded by the Role/Permission/RolePermission models below. Kept only
// as a transitional column (User.legacyRole) until the RBAC rollout's
// Phase 3 drops it — see docs/lastenheft.md RBAC migration notes.
enum LegacyRole {
ADMIN
BEEKEEPER
STAFF
READONLY
API_CLIENT
}
enum RoleStatus { enum RoleStatus {
ACTIVE ACTIVE
INACTIVE INACTIVE
@@ -80,7 +69,6 @@ model User {
email String @unique email String @unique
passwordHash String passwordHash String
name String name String
legacyRole LegacyRole @default(STAFF)
roleId String roleId String
role Role @relation(fields: [roleId], references: [id]) role Role @relation(fields: [roleId], references: [id])
isActive Boolean @default(true) isActive Boolean @default(true)
-1
View File
@@ -30,7 +30,6 @@ async function main(): Promise<void> {
email, email,
passwordHash, passwordHash,
name: 'Administrator', name: 'Administrator',
legacyRole: 'ADMIN',
roleId: adminRole.id, roleId: adminRole.id,
}, },
}); });
-2
View File
@@ -38,7 +38,6 @@ import { PublicModule } from './public/public.module';
import { TaskTemplatesModule } from './task-templates/task-templates.module'; import { TaskTemplatesModule } from './task-templates/task-templates.module';
import { SwarmControlModule } from './swarm-control/swarm-control.module'; import { SwarmControlModule } from './swarm-control/swarm-control.module';
import { JwtAuthGuard } from './auth/guards/jwt-auth.guard'; import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
import { RolesGuard } from './auth/guards/roles.guard';
import { PermissionsGuard } from './auth/guards/permissions.guard'; import { PermissionsGuard } from './auth/guards/permissions.guard';
import { PermissionsModule } from './auth/permissions/permissions.module'; import { PermissionsModule } from './auth/permissions/permissions.module';
@@ -86,7 +85,6 @@ import { PermissionsModule } from './auth/permissions/permissions.module';
controllers: [], controllers: [],
providers: [ providers: [
{ provide: APP_GUARD, useClass: JwtAuthGuard }, { provide: APP_GUARD, useClass: JwtAuthGuard },
{ provide: APP_GUARD, useClass: RolesGuard },
{ provide: APP_GUARD, useClass: PermissionsGuard }, { provide: APP_GUARD, useClass: PermissionsGuard },
{ provide: APP_GUARD, useClass: ThrottlerGuard }, { provide: APP_GUARD, useClass: ThrottlerGuard },
], ],
@@ -23,7 +23,6 @@ describe('AuthService', () => {
const activeUser = { const activeUser = {
id: 'user-1', id: 'user-1',
email: '[email protected]', email: '[email protected]',
legacyRole: 'STAFF',
isActive: true, isActive: true,
passwordHash: '', passwordHash: '',
}; };
+1 -5
View File
@@ -18,7 +18,6 @@ export interface CurrentUserProfile {
id: string; id: string;
email: string; email: string;
name: string; name: string;
role: string;
roleKey: string; roleKey: string;
roleName: string; roleName: string;
permissions: string[]; permissions: string[];
@@ -46,7 +45,6 @@ export class AuthService {
id: user.id, id: user.id,
email: user.email, email: user.email,
name: user.name, name: user.name,
role: user.legacyRole,
roleKey: user.role.key, roleKey: user.role.key,
roleName: user.role.name, roleName: user.role.name,
permissions: Array.from(permissions), permissions: Array.from(permissions),
@@ -62,7 +60,7 @@ export class AuthService {
parseDurationToMs(process.env.JWT_ACCESS_EXPIRES_IN ?? '15m') / 1000, parseDurationToMs(process.env.JWT_ACCESS_EXPIRES_IN ?? '15m') / 1000,
); );
return this.jwtService.sign( return this.jwtService.sign(
{ sub: user.id, email: user.email, role: user.role }, { sub: user.id, email: user.email },
{ {
secret: process.env.JWT_ACCESS_SECRET, secret: process.env.JWT_ACCESS_SECRET,
expiresIn: expiresInSeconds, expiresIn: expiresInSeconds,
@@ -106,7 +104,6 @@ export class AuthService {
const authenticatedUser: AuthenticatedUser = { const authenticatedUser: AuthenticatedUser = {
id: user.id, id: user.id,
email: user.email, email: user.email,
role: user.legacyRole,
}; };
const accessToken = this.signAccessToken(authenticatedUser); const accessToken = this.signAccessToken(authenticatedUser);
const refreshToken = await this.issueRefreshToken(user.id); const refreshToken = await this.issueRefreshToken(user.id);
@@ -138,7 +135,6 @@ export class AuthService {
const authenticatedUser: AuthenticatedUser = { const authenticatedUser: AuthenticatedUser = {
id: user.id, id: user.id,
email: user.email, email: user.email,
role: user.legacyRole,
}; };
const accessToken = this.signAccessToken(authenticatedUser); const accessToken = this.signAccessToken(authenticatedUser);
const newRefreshToken = await this.issueRefreshToken(user.id); const newRefreshToken = await this.issueRefreshToken(user.id);
@@ -1,5 +0,0 @@
import { SetMetadata } from '@nestjs/common';
import { LegacyRole as Role } from '../../../generated/prisma';
export const ROLES_KEY = 'roles';
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);
@@ -1,48 +0,0 @@
import { ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { RolesGuard } from './roles.guard';
import { LegacyRole as Role } from '../../../generated/prisma';
function createContext(user: { role: Role } | undefined): ExecutionContext {
return {
getHandler: () => ({}),
getClass: () => ({}),
switchToHttp: () => ({
getRequest: () => ({ user }),
}),
} as unknown as ExecutionContext;
}
describe('RolesGuard', () => {
it('allows access when no roles are required', () => {
const reflector = {
getAllAndOverride: () => undefined,
} as unknown as Reflector;
const guard = new RolesGuard(reflector);
expect(guard.canActivate(createContext(undefined))).toBe(true);
});
it('denies access when the user role does not match', () => {
const reflector = {
getAllAndOverride: () => [Role.ADMIN],
} as unknown as Reflector;
const guard = new RolesGuard(reflector);
expect(guard.canActivate(createContext({ role: Role.STAFF }))).toBe(false);
});
it('allows access when the user role matches', () => {
const reflector = {
getAllAndOverride: () => [Role.ADMIN],
} as unknown as Reflector;
const guard = new RolesGuard(reflector);
expect(guard.canActivate(createContext({ role: Role.ADMIN }))).toBe(true);
});
it('denies access when no user is attached to the request', () => {
const reflector = {
getAllAndOverride: () => [Role.ADMIN],
} as unknown as Reflector;
const guard = new RolesGuard(reflector);
expect(guard.canActivate(createContext(undefined))).toBe(false);
});
});
@@ -1,27 +0,0 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { LegacyRole as Role } from '../../../generated/prisma';
import { ROLES_KEY } from '../decorators/roles.decorator';
import { AuthenticatedUser } from '../types/authenticated-user';
interface RequestWithUser {
user?: AuthenticatedUser;
}
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles || requiredRoles.length === 0) {
return true;
}
const request = context.switchToHttp().getRequest<RequestWithUser>();
const user = request.user;
return !!user && requiredRoles.includes(user.role);
}
}
@@ -6,7 +6,6 @@ import { AuthenticatedUser } from '../types/authenticated-user';
interface AccessTokenPayload { interface AccessTokenPayload {
sub: string; sub: string;
email: string; email: string;
role: AuthenticatedUser['role'];
} }
@Injectable() @Injectable()
@@ -20,6 +19,6 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
} }
validate(payload: AccessTokenPayload): AuthenticatedUser { validate(payload: AccessTokenPayload): AuthenticatedUser {
return { id: payload.sub, email: payload.email, role: payload.role }; return { id: payload.sub, email: payload.email };
} }
} }
@@ -1,7 +1,4 @@
import { LegacyRole as Role } from '../../../generated/prisma';
export interface AuthenticatedUser { export interface AuthenticatedUser {
id: string; id: string;
email: string; email: string;
role: Role;
} }
@@ -1,6 +1,5 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from '@nestjs/swagger';
import { IsEmail, IsEnum, IsString, MinLength } from 'class-validator'; import { IsEmail, IsString, MinLength } from 'class-validator';
import { LegacyRole as Role } from '../../../generated/prisma';
export class CreateUserDto { export class CreateUserDto {
@ApiProperty() @ApiProperty()
@@ -16,7 +15,8 @@ export class CreateUserDto {
@IsString() @IsString()
name!: string; name!: string;
@ApiProperty({ enum: Role }) @ApiProperty({ description: 'Id of an active Role' })
@IsEnum(Role) @IsString()
role!: Role; @MinLength(1)
roleId!: string;
} }
@@ -1,6 +1,5 @@
import { ApiPropertyOptional } from '@nestjs/swagger'; import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsOptional, IsString } from 'class-validator'; import { IsOptional, IsString, MinLength } from 'class-validator';
import { LegacyRole as Role } from '../../../generated/prisma';
export class UpdateUserDto { export class UpdateUserDto {
@ApiPropertyOptional() @ApiPropertyOptional()
@@ -8,8 +7,9 @@ export class UpdateUserDto {
@IsString() @IsString()
name?: string; name?: string;
@ApiPropertyOptional({ enum: Role }) @ApiPropertyOptional({ description: 'Id of an active Role' })
@IsOptional() @IsOptional()
@IsEnum(Role) @IsString()
role?: Role; @MinLength(1)
roleId?: string;
} }
@@ -13,18 +13,25 @@ describe('UsersService', () => {
update: jest.Mock; update: jest.Mock;
}; };
role: { role: {
findUniqueOrThrow: jest.Mock; findUnique: jest.Mock;
}; };
}; };
let auditLog: { record: jest.Mock }; let auditLog: { record: jest.Mock };
const staffRole = {
id: 'role-staff',
key: 'STAFF',
name: 'Mitarbeiter',
status: 'ACTIVE',
};
const existingUser = { const existingUser = {
id: 'user-1', id: 'user-1',
email: '[email protected]', email: '[email protected]',
passwordHash: 'hashed', passwordHash: 'hashed',
name: 'Existing User', name: 'Existing User',
legacyRole: 'STAFF', roleId: staffRole.id,
roleId: 'role-staff', role: staffRole,
isActive: true, isActive: true,
createdAt: new Date(), createdAt: new Date(),
deactivatedAt: null, deactivatedAt: null,
@@ -39,9 +46,7 @@ describe('UsersService', () => {
update: jest.fn(), update: jest.fn(),
}, },
role: { role: {
findUniqueOrThrow: jest findUnique: jest.fn().mockResolvedValue(staffRole),
.fn()
.mockResolvedValue({ id: 'role-staff', key: 'STAFF' }),
}, },
}; };
auditLog = { record: jest.fn().mockResolvedValue(undefined) }; auditLog = { record: jest.fn().mockResolvedValue(undefined) };
@@ -61,7 +66,9 @@ describe('UsersService', () => {
id: existingUser.id, id: existingUser.id,
email: existingUser.email, email: existingUser.email,
name: existingUser.name, name: existingUser.name,
role: existingUser.legacyRole, roleId: staffRole.id,
roleKey: staffRole.key,
roleName: staffRole.name,
isActive: existingUser.isActive, isActive: existingUser.isActive,
createdAt: existingUser.createdAt, createdAt: existingUser.createdAt,
deactivatedAt: existingUser.deactivatedAt, deactivatedAt: existingUser.deactivatedAt,
@@ -84,7 +91,36 @@ describe('UsersService', () => {
email: existingUser.email, email: existingUser.email,
password: 'password123', password: 'password123',
name: 'New', name: 'New',
role: 'STAFF', roleId: staffRole.id,
}),
).rejects.toBeInstanceOf(ConflictException);
});
it('create throws NotFoundException when the role does not exist', async () => {
prisma.user.findUnique.mockResolvedValue(null);
prisma.role.findUnique.mockResolvedValue(null);
await expect(
usersService.create({
email: '[email protected]',
password: 'password123',
name: 'New User',
roleId: 'missing-role',
}),
).rejects.toBeInstanceOf(NotFoundException);
});
it('create throws ConflictException when the role is not active', async () => {
prisma.user.findUnique.mockResolvedValue(null);
prisma.role.findUnique.mockResolvedValue({
...staffRole,
status: 'INACTIVE',
});
await expect(
usersService.create({
email: '[email protected]',
password: 'password123',
name: 'New User',
roleId: staffRole.id,
}), }),
).rejects.toBeInstanceOf(ConflictException); ).rejects.toBeInstanceOf(ConflictException);
}); });
@@ -101,7 +137,7 @@ describe('UsersService', () => {
email: '[email protected]', email: '[email protected]',
password: 'password123', password: 'password123',
name: 'New User', name: 'New User',
role: 'STAFF', roleId: staffRole.id,
}); });
expect(result.id).toBe('user-2'); expect(result.id).toBe('user-2');
+46 -32
View File
@@ -6,17 +6,25 @@ import {
import * as bcrypt from 'bcryptjs'; import * as bcrypt from 'bcryptjs';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service'; import { AuditLogService } from '../audit/audit-log.service';
import { User } from '../../generated/prisma'; import { Prisma } from '../../generated/prisma';
import { CreateUserDto } from './dto/create-user.dto'; import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto'; import { UpdateUserDto } from './dto/update-user.dto';
const BCRYPT_SALT_ROUNDS = 12; const BCRYPT_SALT_ROUNDS = 12;
const USER_WITH_ROLE = {
include: { role: true },
} satisfies { include: Prisma.UserInclude };
type UserWithRole = Prisma.UserGetPayload<typeof USER_WITH_ROLE>;
export interface UserSummary { export interface UserSummary {
id: string; id: string;
email: string; email: string;
name: string; name: string;
role: string; roleId: string;
roleKey: string;
roleName: string;
isActive: boolean; isActive: boolean;
createdAt: Date; createdAt: Date;
deactivatedAt: Date | null; deactivatedAt: Date | null;
@@ -29,41 +37,43 @@ export class UsersService {
private readonly auditLog: AuditLogService, private readonly auditLog: AuditLogService,
) {} ) {}
private toSummary(user: User): UserSummary { private toSummary(user: UserWithRole): UserSummary {
const { id, email, name, legacyRole, isActive, createdAt, deactivatedAt } =
user;
return { return {
id, id: user.id,
email, email: user.email,
name, name: user.name,
role: legacyRole, roleId: user.roleId,
isActive, roleKey: user.role.key,
createdAt, roleName: user.role.name,
deactivatedAt, isActive: user.isActive,
createdAt: user.createdAt,
deactivatedAt: user.deactivatedAt,
}; };
} }
/** private async assertActiveRole(roleId: string): Promise<void> {
* Resolves the RBAC roleId that corresponds to a legacy role key, so const role = await this.prisma.role.findUnique({ where: { id: roleId } });
* User.roleId stays in sync while callers still speak in terms of the if (!role) {
* legacy enum (Phase 1 of the RBAC rollout; see Role/Permission models). throw new NotFoundException('Role not found');
*/ }
private async resolveRoleId(legacyRole: string): Promise<string> { if (role.status !== 'ACTIVE') {
const role = await this.prisma.role.findUniqueOrThrow({ throw new ConflictException('Role is not active');
where: { key: legacyRole }, }
});
return role.id;
} }
async findAll(): Promise<UserSummary[]> { async findAll(): Promise<UserSummary[]> {
const users = await this.prisma.user.findMany({ const users = await this.prisma.user.findMany({
...USER_WITH_ROLE,
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
}); });
return users.map((user) => this.toSummary(user)); return users.map((user) => this.toSummary(user));
} }
async findById(id: string): Promise<User> { async findById(id: string): Promise<UserWithRole> {
const user = await this.prisma.user.findUnique({ where: { id } }); const user = await this.prisma.user.findUnique({
where: { id },
...USER_WITH_ROLE,
});
if (!user) { if (!user) {
throw new NotFoundException('User not found'); throw new NotFoundException('User not found');
} }
@@ -74,8 +84,8 @@ export class UsersService {
return this.toSummary(await this.findById(id)); return this.toSummary(await this.findById(id));
} }
async findByEmail(email: string): Promise<User | null> { async findByEmail(email: string): Promise<UserWithRole | null> {
return this.prisma.user.findUnique({ where: { email } }); return this.prisma.user.findUnique({ where: { email }, ...USER_WITH_ROLE });
} }
async create( async create(
@@ -86,16 +96,16 @@ export class UsersService {
if (existing) { if (existing) {
throw new ConflictException('Email already in use'); throw new ConflictException('Email already in use');
} }
await this.assertActiveRole(dto.roleId);
const passwordHash = await bcrypt.hash(dto.password, BCRYPT_SALT_ROUNDS); const passwordHash = await bcrypt.hash(dto.password, BCRYPT_SALT_ROUNDS);
const roleId = await this.resolveRoleId(dto.role);
const user = await this.prisma.user.create({ const user = await this.prisma.user.create({
data: { data: {
email: dto.email, email: dto.email,
passwordHash, passwordHash,
name: dto.name, name: dto.name,
legacyRole: dto.role, roleId: dto.roleId,
roleId,
}, },
...USER_WITH_ROLE,
}); });
await this.auditLog.record({ await this.auditLog.record({
entityType: 'User', entityType: 'User',
@@ -113,14 +123,16 @@ export class UsersService {
actingUserId?: string, actingUserId?: string,
): Promise<UserSummary> { ): Promise<UserSummary> {
const before = await this.findById(id); const before = await this.findById(id);
const roleId = dto.role ? await this.resolveRoleId(dto.role) : undefined; if (dto.roleId) {
await this.assertActiveRole(dto.roleId);
}
const user = await this.prisma.user.update({ const user = await this.prisma.user.update({
where: { id }, where: { id },
data: { data: {
name: dto.name, name: dto.name,
legacyRole: dto.role, roleId: dto.roleId,
roleId,
}, },
...USER_WITH_ROLE,
}); });
await this.auditLog.record({ await this.auditLog.record({
entityType: 'User', entityType: 'User',
@@ -138,6 +150,7 @@ export class UsersService {
const user = await this.prisma.user.update({ const user = await this.prisma.user.update({
where: { id }, where: { id },
data: { isActive: false, deactivatedAt: new Date() }, data: { isActive: false, deactivatedAt: new Date() },
...USER_WITH_ROLE,
}); });
await this.auditLog.record({ await this.auditLog.record({
entityType: 'User', entityType: 'User',
@@ -158,6 +171,7 @@ export class UsersService {
const user = await this.prisma.user.update({ const user = await this.prisma.user.update({
where: { id }, where: { id },
data: { isActive: true, deactivatedAt: null }, data: { isActive: true, deactivatedAt: null },
...USER_WITH_ROLE,
}); });
await this.auditLog.record({ await this.auditLog.record({
entityType: 'User', entityType: 'User',
@@ -34,7 +34,6 @@ describe('Apiaries (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -44,7 +43,6 @@ describe('Apiaries (e2e)', () => {
email: readonlyEmail, email: readonlyEmail,
passwordHash, passwordHash,
name: 'Readonly', name: 'Readonly',
legacyRole: 'READONLY',
role: { connect: { key: 'READONLY' } }, role: { connect: { key: 'READONLY' } },
}, },
}); });
@@ -34,7 +34,6 @@ describe('Audit log (e2e)', () => {
email: adminEmail, email: adminEmail,
passwordHash, passwordHash,
name: 'Admin', name: 'Admin',
legacyRole: 'ADMIN',
role: { connect: { key: 'ADMIN' } }, role: { connect: { key: 'ADMIN' } },
}, },
}); });
@@ -44,7 +43,6 @@ describe('Audit log (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -24,7 +24,6 @@ describe('Auth login throttling (e2e)', () => {
email, email,
passwordHash, passwordHash,
name: 'Throttle E2E User', name: 'Throttle E2E User',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
-1
View File
@@ -23,7 +23,6 @@ describe('Auth (e2e)', () => {
email, email,
passwordHash, passwordHash,
name: 'Auth E2E User', name: 'Auth E2E User',
legacyRole: 'ADMIN',
role: { connect: { key: 'ADMIN' } }, role: { connect: { key: 'ADMIN' } },
}, },
}); });
@@ -8,7 +8,6 @@ import {
import { PATH_METADATA } from '@nestjs/common/constants'; import { PATH_METADATA } from '@nestjs/common/constants';
import { AppModule } from '../src/app.module'; import { AppModule } from '../src/app.module';
import { IS_PUBLIC_KEY } from '../src/auth/decorators/public.decorator'; import { IS_PUBLIC_KEY } from '../src/auth/decorators/public.decorator';
import { ROLES_KEY } from '../src/auth/decorators/roles.decorator';
import { REQUIRE_PERMISSION_KEY } from '../src/auth/decorators/require-permission.decorator'; import { REQUIRE_PERMISSION_KEY } from '../src/auth/decorators/require-permission.decorator';
import { PERMISSION_CATALOG } from '../src/auth/permissions/permission-catalog'; import { PERMISSION_CATALOG } from '../src/auth/permissions/permission-catalog';
@@ -22,7 +21,7 @@ const ALLOWLIST = new Set([
]); ]);
describe('Authorization coverage (e2e)', () => { describe('Authorization coverage (e2e)', () => {
it('every non-public route requires a role or a catalog-valid permission', async () => { it('every non-public route requires a catalog-valid permission', async () => {
const moduleRef = await Test.createTestingModule({ const moduleRef = await Test.createTestingModule({
imports: [AppModule, DiscoveryModule], imports: [AppModule, DiscoveryModule],
}).compile(); }).compile();
@@ -64,19 +63,14 @@ describe('Authorization coverage (e2e)', () => {
continue; continue;
} }
const roles = reflector.getAllAndOverride<unknown[]>(ROLES_KEY, [
handler,
constructor,
]);
const permissions = reflector.getAllAndOverride<string[]>( const permissions = reflector.getAllAndOverride<string[]>(
REQUIRE_PERMISSION_KEY, REQUIRE_PERMISSION_KEY,
[handler, constructor], [handler, constructor],
); );
const hasRoles = Array.isArray(roles) && roles.length > 0;
const hasPermissions = const hasPermissions =
Array.isArray(permissions) && permissions.length > 0; Array.isArray(permissions) && permissions.length > 0;
if (!hasRoles && !hasPermissions) { if (!hasPermissions) {
uncoveredRoutes.push(routeKey); uncoveredRoutes.push(routeKey);
} }
if (hasPermissions) { if (hasPermissions) {
@@ -38,7 +38,6 @@ describe('Automation rules (e2e)', () => {
email: adminEmail, email: adminEmail,
passwordHash, passwordHash,
name: 'Automation E2E Admin', name: 'Automation E2E Admin',
legacyRole: 'ADMIN',
role: { connect: { key: 'ADMIN' } }, role: { connect: { key: 'ADMIN' } },
}, },
}); });
@@ -48,7 +47,6 @@ describe('Automation rules (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Automation E2E Staff', name: 'Automation E2E Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -41,7 +41,6 @@ describe('Bottling (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -32,7 +32,6 @@ describe('Calendar (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -46,7 +46,6 @@ describe('Colonies (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -56,7 +55,6 @@ describe('Colonies (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -37,7 +37,6 @@ describe('Dashboard (e2e)', () => {
email: readonlyEmail, email: readonlyEmail,
passwordHash, passwordHash,
name: 'Readonly', name: 'Readonly',
legacyRole: 'READONLY',
role: { connect: { key: 'READONLY' } }, role: { connect: { key: 'READONLY' } },
}, },
}); });
@@ -41,7 +41,6 @@ describe('Documents (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Documents E2E Beekeeper', name: 'Documents E2E Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -51,7 +50,6 @@ describe('Documents (e2e)', () => {
email: readonlyEmail, email: readonlyEmail,
passwordHash, passwordHash,
name: 'Documents E2E Readonly', name: 'Documents E2E Readonly',
legacyRole: 'READONLY',
role: { connect: { key: 'READONLY' } }, role: { connect: { key: 'READONLY' } },
}, },
}); });
@@ -34,7 +34,6 @@ describe('Equipment (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -44,7 +43,6 @@ describe('Equipment (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
-1
View File
@@ -29,7 +29,6 @@ describe('Export (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -36,7 +36,6 @@ describe('Extractions (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -46,7 +45,6 @@ describe('Extractions (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -40,7 +40,6 @@ describe('Feedings (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -50,7 +49,6 @@ describe('Feedings (e2e)', () => {
email: readonlyEmail, email: readonlyEmail,
passwordHash, passwordHash,
name: 'Readonly', name: 'Readonly',
legacyRole: 'READONLY',
role: { connect: { key: 'READONLY' } }, role: { connect: { key: 'READONLY' } },
}, },
}); });
@@ -37,7 +37,6 @@ describe('Harvests (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -47,7 +46,6 @@ describe('Harvests (e2e)', () => {
email: readonlyEmail, email: readonlyEmail,
passwordHash, passwordHash,
name: 'Readonly', name: 'Readonly',
legacyRole: 'READONLY',
role: { connect: { key: 'READONLY' } }, role: { connect: { key: 'READONLY' } },
}, },
}); });
@@ -53,7 +53,6 @@ describe('Honey batches (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -63,7 +62,6 @@ describe('Honey batches (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
-2
View File
@@ -49,7 +49,6 @@ describe('Import (e2e)', () => {
email: adminEmail, email: adminEmail,
passwordHash, passwordHash,
name: 'Import E2E Admin', name: 'Import E2E Admin',
legacyRole: 'ADMIN',
role: { connect: { key: 'ADMIN' } }, role: { connect: { key: 'ADMIN' } },
}, },
}); });
@@ -59,7 +58,6 @@ describe('Import (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Import E2E Staff', name: 'Import E2E Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -41,7 +41,6 @@ describe('Inspections (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -51,7 +50,6 @@ describe('Inspections (e2e)', () => {
email: readonlyEmail, email: readonlyEmail,
passwordHash, passwordHash,
name: 'Readonly', name: 'Readonly',
legacyRole: 'READONLY',
role: { connect: { key: 'READONLY' } }, role: { connect: { key: 'READONLY' } },
}, },
}); });
@@ -34,7 +34,6 @@ describe('Notifications (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -44,7 +43,6 @@ describe('Notifications (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -34,7 +34,6 @@ describe('Products (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -44,7 +43,6 @@ describe('Products (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
-1
View File
@@ -42,7 +42,6 @@ describe('Public batch origin page (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
-1
View File
@@ -26,7 +26,6 @@ describe('QR codes (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
-1
View File
@@ -33,7 +33,6 @@ describe('Queens (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
-3
View File
@@ -19,7 +19,6 @@ interface RoleBody {
interface MeBody { interface MeBody {
id: string; id: string;
email: string; email: string;
role: string;
roleKey: string; roleKey: string;
permissions: string[]; permissions: string[];
} }
@@ -57,7 +56,6 @@ describe('Roles (e2e)', () => {
email: adminEmail, email: adminEmail,
passwordHash, passwordHash,
name: 'Roles E2E Admin', name: 'Roles E2E Admin',
legacyRole: 'ADMIN',
role: { connect: { key: 'ADMIN' } }, role: { connect: { key: 'ADMIN' } },
}, },
}); });
@@ -67,7 +65,6 @@ describe('Roles (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Roles E2E Staff', name: 'Roles E2E Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
-1
View File
@@ -39,7 +39,6 @@ describe('Search and filters (e2e)', () => {
email: readonlyEmail, email: readonlyEmail,
passwordHash, passwordHash,
name: 'Readonly', name: 'Readonly',
legacyRole: 'READONLY',
role: { connect: { key: 'READONLY' } }, role: { connect: { key: 'READONLY' } },
}, },
}); });
@@ -60,7 +60,6 @@ describe('Statistics (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
-2
View File
@@ -33,7 +33,6 @@ describe('Storage (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -43,7 +42,6 @@ describe('Storage (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -36,7 +36,6 @@ describe('Swarm control checks (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -46,7 +45,6 @@ describe('Swarm control checks (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -31,7 +31,6 @@ describe('TaskTemplates (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
-2
View File
@@ -34,7 +34,6 @@ describe('Tasks (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -44,7 +43,6 @@ describe('Tasks (e2e)', () => {
email: readonlyEmail, email: readonlyEmail,
passwordHash, passwordHash,
name: 'Readonly', name: 'Readonly',
legacyRole: 'READONLY',
role: { connect: { key: 'READONLY' } }, role: { connect: { key: 'READONLY' } },
}, },
}); });
@@ -35,7 +35,6 @@ describe('Treatments (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -45,7 +44,6 @@ describe('Treatments (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
+7 -3
View File
@@ -17,18 +17,23 @@ describe('Users (e2e)', () => {
let adminAccessToken: string; let adminAccessToken: string;
let staffAccessToken: string; let staffAccessToken: string;
let createdUserId: string; let createdUserId: string;
let beekeeperRoleId: string;
beforeAll(async () => { beforeAll(async () => {
app = await createTestApp(); app = await createTestApp();
prisma = app.get(PrismaService); prisma = app.get(PrismaService);
const beekeeperRole = await prisma.role.findUniqueOrThrow({
where: { key: 'BEEKEEPER' },
});
beekeeperRoleId = beekeeperRole.id;
const passwordHash = await bcrypt.hash(password, 12); const passwordHash = await bcrypt.hash(password, 12);
const admin = await prisma.user.create({ const admin = await prisma.user.create({
data: { data: {
email: adminEmail, email: adminEmail,
passwordHash, passwordHash,
name: 'Users E2E Admin', name: 'Users E2E Admin',
legacyRole: 'ADMIN',
role: { connect: { key: 'ADMIN' } }, role: { connect: { key: 'ADMIN' } },
}, },
}); });
@@ -38,7 +43,6 @@ describe('Users (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Users E2E Staff', name: 'Users E2E Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -76,7 +80,7 @@ describe('Users (e2e)', () => {
email: `users-e2e-created-${Date.now()}@example.com`, email: `users-e2e-created-${Date.now()}@example.com`,
password: 'AnotherSecret123!', password: 'AnotherSecret123!',
name: 'Created via e2e', name: 'Created via e2e',
role: 'BEEKEEPER', roleId: beekeeperRoleId,
}) })
.expect(201); .expect(201);
const created = response.body as UserBody & { passwordHash?: string }; const created = response.body as UserBody & { passwordHash?: string };
+3 -1
View File
@@ -11,7 +11,9 @@ export interface UserBody {
id: string; id: string;
email: string; email: string;
name: string; name: string;
role: string; roleId: string;
roleKey: string;
roleName: string;
isActive: boolean; isActive: boolean;
createdAt: string; createdAt: string;
deactivatedAt: string | null; deactivatedAt: string | null;
-2
View File
@@ -35,7 +35,6 @@ describe('Varroa measurements (e2e)', () => {
email: beekeeperEmail, email: beekeeperEmail,
passwordHash, passwordHash,
name: 'Beekeeper', name: 'Beekeeper',
legacyRole: 'BEEKEEPER',
role: { connect: { key: 'BEEKEEPER' } }, role: { connect: { key: 'BEEKEEPER' } },
}, },
}); });
@@ -45,7 +44,6 @@ describe('Varroa measurements (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Staff', name: 'Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });
@@ -48,7 +48,6 @@ describe('Webhooks (e2e)', () => {
email: adminEmail, email: adminEmail,
passwordHash, passwordHash,
name: 'Webhooks E2E Admin', name: 'Webhooks E2E Admin',
legacyRole: 'ADMIN',
role: { connect: { key: 'ADMIN' } }, role: { connect: { key: 'ADMIN' } },
}, },
}); });
@@ -58,7 +57,6 @@ describe('Webhooks (e2e)', () => {
email: staffEmail, email: staffEmail,
passwordHash, passwordHash,
name: 'Webhooks E2E Staff', name: 'Webhooks E2E Staff',
legacyRole: 'STAFF',
role: { connect: { key: 'STAFF' } }, role: { connect: { key: 'STAFF' } },
}, },
}); });