Files
ApiCore/ApiCore-Backend/test/authorization-coverage.e2e-spec.ts
T
Nick Szaunig 62004483cf
Backend Image / build-and-push (push) Successful in 2m57s
Frontend Image / build-and-push (push) Successful in 2m30s
feat: MFA (TOTP) und Self-Service-Profilseite
Benutzer koennen jetzt selbst Zwei-Faktor-Authentifizierung einrichten
und ihr Profil verwalten (Name, E-Mail, Passwort, Profilbild).

Backend:
- Neues MfaModule (src/auth/mfa/): AES-256-GCM-verschluesselte
  TOTP-Secrets (otplib), QR-Code-Erzeugung, kurzlebige Setup-/
  Challenge-JWTs fuer den 2-Schritt-Login-Flow
- Neues ProfileModule (src/profile/): PATCH /profile,
  POST /profile/password, POST/DELETE/GET /profile/avatar,
  POST /profile/mfa/enroll(/confirm), POST /profile/mfa/disable -
  alle self-scoped ueber actor.id, ohne @RequirePermission (siehe
  ALLOWLIST in authorization-coverage.e2e-spec.ts)
- AuthService.login() zweistufig: bei aktivem MFA erst
  { mfaRequired, mfaToken } statt Tokens, neuer Endpunkt
  POST /auth/mfa/verify schliesst den Flow ab
- Admin-Recovery: POST /users/:id/mfa/reset (users:update) fuer
  verlorene MFA-Geraete, da es keinen E-Mail-Reset-Flow gibt

Frontend:
- Login-Seite mit zweitem Schritt fuer den TOTP-Code
- Neue Profilseite (/profile, ausserhalb des admin-only
  Settings-Bereichs): Profilbild, Name/E-Mail, Passwort, MFA-Ein-/
  Ausrichtung mit QR-Code-Dialog
- Header zeigt jetzt Avatar mit Dropdown (Profil/Abmelden) statt
  nur E-Mail-Text
- Admin-Users-Tabelle zeigt MFA-Status + Reset-Button

Haertung nach Security-Review (Backend/Frontend-Diff, kein CRITICAL,
mehrere MEDIUM behoben):
- Access-Token wird bei Passwortwechsel sofort ungueltig
  (User.passwordChangedAt + JWT-iat-Vergleich in
  PermissionResolverService.isTokenValid, vorher isUserActive) statt
  erst nach bis zu 15 Minuten
- E-Mail-Aenderung verlangt jetzt aktuelles Passwort
- POST /profile/password und /profile/mfa/disable haben jetzt das
  gleiche strikte Throttling wie Login (SENSITIVE_ACTION_THROTTLE)
- Kein stiller leerer Verschluesselungs-Key-Fallback mehr (wirft
  jetzt explizit)

Bewusst zurueckgestellt (dokumentiert, kein aktiver Exploit-Pfad):
dedizierter Verschluesselungs-Key fuer MFA-Secrets statt
JWT_ACCESS_SECRET-Ableitung, dedizierte users:mfa-reset-Permission
statt users:update, separate JWT-Secrets pro Token-Zweck.

Verifiziert: tsc/eslint clean, 297/297 Backend- + 31/31
Frontend-Unit-Tests, Build clean auf beiden Projekten. e2e weiterhin
durch bekanntes WSL2/Postgres-Problem blockiert. Unabhaengiges
Security- und Code-Quality-Review durchgefuehrt (0 CRITICAL, 0 HIGH).
2026-08-27 00:25:34 +02:00

100 lines
3.4 KiB
TypeScript

import { Test } from '@nestjs/testing';
import {
DiscoveryModule,
DiscoveryService,
MetadataScanner,
Reflector,
} from '@nestjs/core';
import { PATH_METADATA } from '@nestjs/common/constants';
import { AppModule } from '../src/app.module';
import { IS_PUBLIC_KEY } from '../src/auth/decorators/public.decorator';
import { REQUIRE_PERMISSION_KEY } from '../src/auth/decorators/require-permission.decorator';
import { PERMISSION_CATALOG } from '../src/auth/permissions/permission-catalog';
// Routes intentionally left without a role/permission check: they act on the
// caller's own data (notifications) or are the auth bootstrap endpoint that
// every authenticated user must be able to reach regardless of permissions.
const ALLOWLIST = new Set([
'NotificationsController.findAll',
'NotificationsController.markRead',
'AuthController.me',
'ProfileController.updateProfile',
'ProfileController.changePassword',
'ProfileController.uploadAvatar',
'ProfileController.deleteAvatar',
'ProfileController.getAvatar',
'ProfileController.enrollMfa',
'ProfileController.confirmMfaEnrollment',
'ProfileController.disableMfa',
]);
describe('Authorization coverage (e2e)', () => {
it('every non-public route requires a catalog-valid permission', async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule, DiscoveryModule],
}).compile();
const discovery = moduleRef.get(DiscoveryService);
const reflector = moduleRef.get(Reflector);
const scanner = moduleRef.get(MetadataScanner);
const catalogKeys = new Set<string>(
PERMISSION_CATALOG.map((entry) => entry.key),
);
const uncoveredRoutes: string[] = [];
const invalidPermissionKeys: string[] = [];
for (const wrapper of discovery.getControllers()) {
const instance = wrapper.instance as object | undefined;
if (!instance) {
continue;
}
const constructor = instance.constructor;
const controllerName = constructor.name;
const prototype = Object.getPrototypeOf(instance) as object;
const isPublicClass =
reflector.get<boolean>(IS_PUBLIC_KEY, constructor) === true;
for (const methodName of scanner.getAllMethodNames(prototype)) {
const handler = (prototype as Record<string, () => unknown>)[
methodName
];
const isRouteHandler =
Reflect.getMetadata(PATH_METADATA, handler) !== undefined;
if (!isRouteHandler) {
continue;
}
const routeKey = `${controllerName}.${methodName}`;
const isPublicMethod =
reflector.get<boolean>(IS_PUBLIC_KEY, handler) === true;
if (isPublicClass || isPublicMethod || ALLOWLIST.has(routeKey)) {
continue;
}
const permissions = reflector.getAllAndOverride<string[]>(
REQUIRE_PERMISSION_KEY,
[handler, constructor],
);
const hasPermissions =
Array.isArray(permissions) && permissions.length > 0;
if (!hasPermissions) {
uncoveredRoutes.push(routeKey);
}
if (hasPermissions) {
for (const key of permissions) {
if (!catalogKeys.has(key)) {
invalidPermissionKeys.push(`${routeKey} -> ${key}`);
}
}
}
}
}
expect(uncoveredRoutes).toEqual([]);
expect(invalidPermissionKeys).toEqual([]);
await moduleRef.close();
});
});