From 5eff7b302d6c765328b477757084335fc661fcf7 Mon Sep 17 00:00:00 2001 From: Patrick Schiller Date: Sat, 5 Dec 2026 11:39:16 +0100 Subject: [PATCH 1/2] fix(security): enforce direct-report access boundaries Signed-off-by: Patrick Schiller --- .../src/api/project-booking-range.e2e.spec.ts | 43 +++++++-- apps/api-e2e/src/api/projects.e2e.spec.ts | 95 +++++++++++++++++-- .../api/solo-customers-reports.e2e.spec.ts | 24 ++++- .../src/api/time-entry-projects.e2e.spec.ts | 75 +++++++++++++-- .../src/api/work-schedules.e2e.spec.ts | 78 +++++++++++++-- apps/api/openapi.json | 25 +++++ .../src/app/projects/projects.controller.ts | 39 ++++---- apps/api/src/app/projects/projects.service.ts | 27 +++++- .../app/projects/solo-project-access.guard.ts | 4 +- .../app/time-entries/time-entries.service.ts | 45 +++++---- .../work-schedules.controller.ts | 18 +--- 11 files changed, 383 insertions(+), 90 deletions(-) diff --git a/apps/api-e2e/src/api/project-booking-range.e2e.spec.ts b/apps/api-e2e/src/api/project-booking-range.e2e.spec.ts index e5d8a03..dad09d7 100644 --- a/apps/api-e2e/src/api/project-booking-range.e2e.spec.ts +++ b/apps/api-e2e/src/api/project-booking-range.e2e.spec.ts @@ -22,11 +22,19 @@ describe('POST /timeentries/book-project — retroactive range booking', () => { }); async function fixture() { + const manager = await seedEmployee(ctx.prisma, { + personalNo: '0010', + firstName: 'Mara', + lastName: 'Manager', + email: 'manager@test.local', + role: 'Manager', + }); const worker = await seedEmployee(ctx.prisma, { personalNo: '1001', firstName: 'Willi', lastName: 'Worker', email: 'worker@test.local', + managerId: manager.id, }); const other = await seedEmployee(ctx.prisma, { personalNo: '1002', @@ -34,13 +42,6 @@ describe('POST /timeentries/book-project — retroactive range booking', () => { lastName: 'Other', email: 'other@test.local', }); - const manager = await seedEmployee(ctx.prisma, { - personalNo: '0010', - firstName: 'Mara', - lastName: 'Manager', - email: 'manager@test.local', - role: 'Manager', - }); const project = await seedProject(ctx.prisma, { code: 'P-RANGE', assigneeIds: [worker.id], @@ -51,7 +52,24 @@ describe('POST /timeentries/book-project — retroactive range booking', () => { serviceOrders: [{ orderNo: 'SA-1', title: 'Design' }], }); const foreign = await seedProject(ctx.prisma, { code: 'P-FOREIGN' }); - return { worker, other, manager, project, ordered, foreign }; + return { + worker, + other, + manager, + project, + ordered, + foreign, + }; + } + + function seedUnrelatedManager() { + return seedEmployee(ctx.prisma, { + personalNo: '0011', + firstName: 'Uma', + lastName: 'Unrelated', + email: 'unrelated-manager@test.local', + role: 'Manager', + }); } /** Today at the given UTC hour (fractions allowed, e.g. 12.5 = 12:30Z). */ @@ -294,10 +312,12 @@ describe('POST /timeentries/book-project — retroactive range booking', () => { ).toBe(true); }); - it('foreign ranges need Manager/HRAdmin', async () => { + it('foreign ranges need the direct Manager/HRAdmin', async () => { const { worker, other, manager, project } = await fixture(); + const unrelatedManager = await seedUnrelatedManager(); const otherToken = await login(ctx.http, other.email); const managerToken = await login(ctx.http, manager.email); + const unrelatedManagerToken = await login(ctx.http, unrelatedManager.email); await seedEntry(worker.id, 9, 15); const payload = { @@ -315,6 +335,11 @@ describe('POST /timeentries/book-project — retroactive range booking', () => { .set('Authorization', `Bearer ${otherToken}`) .send(payload) .expect(403); + await ctx.http + .post('/api/timeentries/book-project') + .set('Authorization', `Bearer ${unrelatedManagerToken}`) + .send(payload) + .expect(403); await ctx.http .post('/api/timeentries/book-project') .set('Authorization', `Bearer ${managerToken}`) diff --git a/apps/api-e2e/src/api/projects.e2e.spec.ts b/apps/api-e2e/src/api/projects.e2e.spec.ts index 64fbdf9..ff8f39a 100644 --- a/apps/api-e2e/src/api/projects.e2e.spec.ts +++ b/apps/api-e2e/src/api/projects.e2e.spec.ts @@ -39,20 +39,31 @@ describe('Projects — CRUD, service orders, assignment matrix', () => { firstName: 'Willi', lastName: 'Worker', email: 'worker@test.local', + managerId: manager.id, }); return { hr, manager, worker }; } - it('GET /projects is readable without a token; mutations are role-guarded', async () => { - const { manager, worker } = await fixture(); + it('project reads and mutations require authentication and the Manager/HRAdmin role', async () => { + const { hr, manager, worker } = await fixture(); + const existing = await seedProject(ctx.prisma, { code: 'P-EXISTING' }); - await ctx.http.get('/api/projects').expect(200); + await ctx.http.get('/api/projects').expect(401); + await ctx.http.get(`/api/projects/${existing.id}`).expect(401); await ctx.http .post('/api/projects') .send({ code: 'P-1', name: 'One' }) .expect(401); const workerToken = await login(ctx.http, worker.email); + await ctx.http + .get('/api/projects') + .set('Authorization', `Bearer ${workerToken}`) + .expect(403); + await ctx.http + .get(`/api/projects/${existing.id}`) + .set('Authorization', `Bearer ${workerToken}`) + .expect(403); await ctx.http .post('/api/projects') .set('Authorization', `Bearer ${workerToken}`) @@ -60,6 +71,14 @@ describe('Projects — CRUD, service orders, assignment matrix', () => { .expect(403); const managerToken = await login(ctx.http, manager.email); + await ctx.http + .get('/api/projects') + .set('Authorization', `Bearer ${managerToken}`) + .expect(200); + await ctx.http + .get(`/api/projects/${existing.id}`) + .set('Authorization', `Bearer ${managerToken}`) + .expect(200); const created = await ctx.http .post('/api/projects') .set('Authorization', `Bearer ${managerToken}`) @@ -69,6 +88,16 @@ describe('Projects — CRUD, service orders, assignment matrix', () => { expect(created.body.isActive).toBe(true); expect(created.body.assignedEmployeeCount).toBe(0); expect(created.body.activityCount).toBe(0); + + const hrToken = await login(ctx.http, hr.email); + await ctx.http + .get('/api/projects') + .set('Authorization', `Bearer ${hrToken}`) + .expect(200); + await ctx.http + .get(`/api/projects/${existing.id}`) + .set('Authorization', `Bearer ${hrToken}`) + .expect(200); }); it('HRAdmin may create; duplicate codes are rejected with 409', async () => { @@ -98,10 +127,14 @@ describe('Projects — CRUD, service orders, assignment matrix', () => { .expect(200); expect(updated.body.isActive).toBe(false); - const activeOnly = await ctx.http.get('/api/projects').expect(200); + const activeOnly = await ctx.http + .get('/api/projects') + .set('Authorization', `Bearer ${token}`) + .expect(200); expect(activeOnly.body.length).toBe(0); const all = await ctx.http .get('/api/projects?includeInactive=true') + .set('Authorization', `Bearer ${token}`) .expect(200); expect(all.body.length).toBe(1); }); @@ -168,7 +201,10 @@ describe('Projects — CRUD, service orders, assignment matrix', () => { .delete(`/api/projects/${p1.id}/service-orders/${created.body.id}`) .set('Authorization', `Bearer ${token}`) .expect(204); - const after = await ctx.http.get(`/api/projects/${p1.id}`).expect(200); + const after = await ctx.http + .get(`/api/projects/${p1.id}`) + .set('Authorization', `Bearer ${token}`) + .expect(200); expect(after.body.serviceOrders.length).toBe(0); }); @@ -223,6 +259,7 @@ describe('Projects — CRUD, service orders, assignment matrix', () => { it('bookable returns only active, assigned projects with their active orders', async () => { const { worker } = await fixture(); + const token = await login(ctx.http, worker.email); const active = await seedProject(ctx.prisma, { code: 'P-ACTIVE', assigneeIds: [worker.id], @@ -240,6 +277,7 @@ describe('Projects — CRUD, service orders, assignment matrix', () => { const res = await ctx.http .get(`/api/projects/bookable?employeeId=${worker.id}`) + .set('Authorization', `Bearer ${token}`) .expect(200); expect(res.body).toEqual([ { @@ -261,6 +299,45 @@ describe('Projects — CRUD, service orders, assignment matrix', () => { ]); }); + it('scopes bookable projects to self, direct reports, or HRAdmin', async () => { + const { hr, manager, worker } = await fixture(); + const unrelatedManager = await seedEmployee(ctx.prisma, { + personalNo: '0011', + firstName: 'Una', + lastName: 'Related', + email: 'unrelated-manager@test.local', + role: 'Manager', + }); + const otherEmployee = await seedEmployee(ctx.prisma, { + personalNo: '1002', + firstName: 'Other', + lastName: 'Employee', + email: 'other@test.local', + }); + await seedProject(ctx.prisma, { + code: 'P-SCOPED', + assigneeIds: [worker.id], + }); + + await ctx.http + .get(`/api/projects/bookable?employeeId=${worker.id}`) + .expect(401); + for (const actor of [worker, manager, hr]) { + const token = await login(ctx.http, actor.email); + await ctx.http + .get(`/api/projects/bookable?employeeId=${worker.id}`) + .set('Authorization', `Bearer ${token}`) + .expect(200); + } + for (const actor of [unrelatedManager, otherEmployee]) { + const token = await login(ctx.http, actor.email); + await ctx.http + .get(`/api/projects/bookable?employeeId=${worker.id}`) + .set('Authorization', `Bearer ${token}`) + .expect(403); + } + }); + it('service orders with booked time cannot be deleted (409), only deactivated', async () => { const { hr, worker } = await fixture(); const token = await login(ctx.http, hr.email); @@ -341,7 +418,8 @@ describe('Projects — CRUD, service orders, assignment matrix', () => { }); it('reports gross booked minutes per project and order (closed, non-rejected)', async () => { - const { worker } = await fixture(); + const { manager, worker } = await fixture(); + const token = await login(ctx.http, manager.email); const project = await seedProject(ctx.prisma, { code: 'P-IST', assigneeIds: [worker.id], @@ -378,7 +456,10 @@ describe('Projects — CRUD, service orders, assignment matrix', () => { }, }); // open → ignored - const res = await ctx.http.get(`/api/projects/${project.id}`).expect(200); + const res = await ctx.http + .get(`/api/projects/${project.id}`) + .set('Authorization', `Bearer ${token}`) + .expect(200); expect(res.body.bookedMinutes).toBe(240); expect(res.body.serviceOrders[0].bookedMinutes).toBe(120); }); diff --git a/apps/api-e2e/src/api/solo-customers-reports.e2e.spec.ts b/apps/api-e2e/src/api/solo-customers-reports.e2e.spec.ts index 4a2ffb3..ce463bc 100644 --- a/apps/api-e2e/src/api/solo-customers-reports.e2e.spec.ts +++ b/apps/api-e2e/src/api/solo-customers-reports.e2e.spec.ts @@ -46,7 +46,7 @@ describe('Solo customers, project ownership and customer statements', () => { ).body as { id: string; name: string }; } - it('requires Solo ownership and keeps legacy Team project reads public', async () => { + it('requires authentication in Team mode and preserves Solo owner isolation', async () => { const owner = await seedEmployee(ctx.prisma, { personalNo: 'TEAM', firstName: 'Team', @@ -54,8 +54,24 @@ describe('Solo customers, project ownership and customer statements', () => { email: 'team-admin@test.local', role: 'HRAdmin', }); + const outsider = await seedEmployee(ctx.prisma, { + personalNo: 'OUTSIDE', + firstName: 'Other', + lastName: 'Employee', + email: 'other@test.local', + role: 'HRAdmin', + }); const token = await login(ctx.http, owner.email); - await ctx.http.get('/api/projects').expect(200); + const outsiderToken = await login(ctx.http, outsider.email); + await ctx.http.get('/api/projects').expect(401); + await ctx.http + .get('/api/projects') + .set('Authorization', `Bearer ${token}`) + .expect(200); + await ctx.http + .get('/api/projects') + .set('Authorization', `Bearer ${outsiderToken}`) + .expect(200); await ctx.http .get('/api/customers') .set('Authorization', `Bearer ${token}`) @@ -75,6 +91,10 @@ describe('Solo customers, project ownership and customer statements', () => { .get('/api/projects') .set('Authorization', `Bearer ${token}`) .expect(200); + await ctx.http + .get('/api/projects') + .set('Authorization', `Bearer ${outsiderToken}`) + .expect(403); }); it('creates minimal customers and assigns new projects to the owner atomically', async () => { diff --git a/apps/api-e2e/src/api/time-entry-projects.e2e.spec.ts b/apps/api-e2e/src/api/time-entry-projects.e2e.spec.ts index 665cdcc..1cf3c09 100644 --- a/apps/api-e2e/src/api/time-entry-projects.e2e.spec.ts +++ b/apps/api-e2e/src/api/time-entry-projects.e2e.spec.ts @@ -24,11 +24,19 @@ describe('TimeEntries × Projects — clock-in, retroactive assignment, split', }); async function fixture() { + const manager = await seedEmployee(ctx.prisma, { + personalNo: '0010', + firstName: 'Mara', + lastName: 'Manager', + email: 'manager@test.local', + role: 'Manager', + }); const worker = await seedEmployee(ctx.prisma, { personalNo: '1001', firstName: 'Willi', lastName: 'Worker', email: 'worker@test.local', + managerId: manager.id, }); const other = await seedEmployee(ctx.prisma, { personalNo: '1002', @@ -36,13 +44,6 @@ describe('TimeEntries × Projects — clock-in, retroactive assignment, split', lastName: 'Other', email: 'other@test.local', }); - const manager = await seedEmployee(ctx.prisma, { - personalNo: '0010', - firstName: 'Mara', - lastName: 'Manager', - email: 'manager@test.local', - role: 'Manager', - }); const assigned = await seedProject(ctx.prisma, { code: 'P-ASSIGNED', assigneeIds: [worker.id], @@ -79,6 +80,16 @@ describe('TimeEntries × Projects — clock-in, retroactive assignment, split', }; } + function seedUnrelatedManager() { + return seedEmployee(ctx.prisma, { + personalNo: '0011', + firstName: 'Uma', + lastName: 'Unrelated', + email: 'unrelated-manager@test.local', + role: 'Manager', + }); + } + /** Closed mid-day entry (always inside the 07:00–23:00 frame). */ async function seedClosedEntry( employeeId: string, @@ -124,6 +135,32 @@ describe('TimeEntries × Projects — clock-in, retroactive assignment, split', }); } + describe('Manager time-entry scope', () => { + it('allows a direct Manager to list report entries and rejects an unrelated Manager', async () => { + const { worker, manager } = await fixture(); + const unrelatedManager = await seedUnrelatedManager(); + const entry = await seedClosedEntry(worker.id); + const managerToken = await login(ctx.http, manager.email); + const unrelatedManagerToken = await login( + ctx.http, + unrelatedManager.email, + ); + + const visible = await ctx.http + .get(`/api/timeentries?employeeId=${worker.id}`) + .set('Authorization', `Bearer ${managerToken}`) + .expect(200); + expect( + visible.body.some((row: { id: string }) => row.id === entry.id), + ).toBe(true); + + await ctx.http + .get(`/api/timeentries?employeeId=${worker.id}`) + .set('Authorization', `Bearer ${unrelatedManagerToken}`) + .expect(403); + }); + }); + describe('clock-in with project', () => { it('books the entry onto an assigned active project', async () => { const { worker, assigned } = await fixture(); @@ -234,11 +271,16 @@ describe('TimeEntries × Projects — clock-in, retroactive assignment, split', .expect(403); }); - it('approved entries are editable (lock removed); foreign entries need Manager/HRAdmin', async () => { + it('approved entries are editable; only the direct Manager/HRAdmin may edit foreign entries', async () => { const { worker, other, manager, assigned } = await fixture(); + const unrelatedManager = await seedUnrelatedManager(); const workerToken = await login(ctx.http, worker.email); const otherToken = await login(ctx.http, other.email); const managerToken = await login(ctx.http, manager.email); + const unrelatedManagerToken = await login( + ctx.http, + unrelatedManager.email, + ); // Closed entries auto-approve, so retroactive booking must work on them. const approved = await seedClosedEntry(worker.id, { status: 'Approved' }); @@ -255,6 +297,11 @@ describe('TimeEntries × Projects — clock-in, retroactive assignment, split', .set('Authorization', `Bearer ${otherToken}`) .send({ projectId: null }) .expect(403); + await ctx.http + .patch(`/api/timeentries/${entry.id}`) + .set('Authorization', `Bearer ${unrelatedManagerToken}`) + .send({ projectId: assigned.id }) + .expect(403); await ctx.http .patch(`/api/timeentries/${entry.id}`) .set('Authorization', `Bearer ${managerToken}`) @@ -497,10 +544,15 @@ describe('TimeEntries × Projects — clock-in, retroactive assignment, split', expect(res.body.second.status).toBe('Rejected'); }); - it('foreign entries can only be split by Manager/HRAdmin', async () => { + it('foreign entries can only be split by the direct Manager/HRAdmin', async () => { const { worker, other, manager } = await fixture(); + const unrelatedManager = await seedUnrelatedManager(); const otherToken = await login(ctx.http, other.email); const managerToken = await login(ctx.http, manager.email); + const unrelatedManagerToken = await login( + ctx.http, + unrelatedManager.email, + ); const entry = await seedClosedEntry(worker.id); const at = new Date( entry.clockIn.getTime() + 60 * 60 * 1000, @@ -511,6 +563,11 @@ describe('TimeEntries × Projects — clock-in, retroactive assignment, split', .set('Authorization', `Bearer ${otherToken}`) .send({ at }) .expect(403); + await ctx.http + .post(`/api/timeentries/${entry.id}/split`) + .set('Authorization', `Bearer ${unrelatedManagerToken}`) + .send({ at }) + .expect(403); await ctx.http .post(`/api/timeentries/${entry.id}/split`) .set('Authorization', `Bearer ${managerToken}`) diff --git a/apps/api-e2e/src/api/work-schedules.e2e.spec.ts b/apps/api-e2e/src/api/work-schedules.e2e.spec.ts index 0245fab..271a489 100644 --- a/apps/api-e2e/src/api/work-schedules.e2e.spec.ts +++ b/apps/api-e2e/src/api/work-schedules.e2e.spec.ts @@ -56,20 +56,73 @@ describe('WorkSchedules — CRUD + assignment', () => { shortBreakMinutes: 0, }; - it('non-HR cannot create a schedule (401 without token, 403 as employee)', async () => { + it('non-HR cannot create a schedule', async () => { await ctx.http.post('/api/work-schedules').send(samplePayload).expect(401); - await seedEmployee(ctx.prisma, { + const employee = await seedEmployee(ctx.prisma, { personalNo: '1001', firstName: 'Reg', lastName: 'Ular', email: 'reg@test.local', }); - const empToken = await login(ctx.http, 'reg@test.local'); - await ctx.http + const manager = await seedEmployee(ctx.prisma, { + personalNo: '0010', + firstName: 'Mara', + lastName: 'Manager', + email: 'manager@test.local', + role: 'Manager', + }); + for (const actor of [employee, manager]) { + const token = await login(ctx.http, actor.email); + await ctx.http + .post('/api/work-schedules') + .set('Authorization', `Bearer ${token}`) + .send(samplePayload) + .expect(403); + } + }); + + it('schedule reads require an HRAdmin', async () => { + const hrToken = await setupHR(); + const created = await ctx.http .post('/api/work-schedules') - .set('Authorization', `Bearer ${empToken}`) + .set('Authorization', `Bearer ${hrToken}`) .send(samplePayload) - .expect(403); + .expect(201); + const employee = await seedEmployee(ctx.prisma, { + personalNo: '1001', + firstName: 'Reg', + lastName: 'Ular', + email: 'reg@test.local', + }); + const manager = await seedEmployee(ctx.prisma, { + personalNo: '0010', + firstName: 'Mara', + lastName: 'Manager', + email: 'manager@test.local', + role: 'Manager', + }); + + await ctx.http.get('/api/work-schedules').expect(401); + await ctx.http.get(`/api/work-schedules/${created.body.id}`).expect(401); + for (const actor of [employee, manager]) { + const token = await login(ctx.http, actor.email); + await ctx.http + .get('/api/work-schedules') + .set('Authorization', `Bearer ${token}`) + .expect(403); + await ctx.http + .get(`/api/work-schedules/${created.body.id}`) + .set('Authorization', `Bearer ${token}`) + .expect(403); + } + await ctx.http + .get('/api/work-schedules') + .set('Authorization', `Bearer ${hrToken}`) + .expect(200); + await ctx.http + .get(`/api/work-schedules/${created.body.id}`) + .set('Authorization', `Bearer ${hrToken}`) + .expect(200); }); it('HR can create + read + update + delete a schedule', async () => { @@ -83,13 +136,17 @@ describe('WorkSchedules — CRUD + assignment', () => { expect(created.body.coreTimes.length).toBe(2); expect(created.body.workingDays).toBe(31); - const list = await ctx.http.get('/api/work-schedules').expect(200); + const list = await ctx.http + .get('/api/work-schedules') + .set('Authorization', `Bearer ${token}`) + .expect(200); expect( list.body.some((s: { id: string }) => s.id === created.body.id), ).toBe(true); const got = await ctx.http .get(`/api/work-schedules/${created.body.id}`) + .set('Authorization', `Bearer ${token}`) .expect(200); expect(got.body.id).toBe(created.body.id); @@ -104,7 +161,10 @@ describe('WorkSchedules — CRUD + assignment', () => { .delete(`/api/work-schedules/${created.body.id}`) .set('Authorization', `Bearer ${token}`) .expect(204); - await ctx.http.get(`/api/work-schedules/${created.body.id}`).expect(404); + await ctx.http + .get(`/api/work-schedules/${created.body.id}`) + .set('Authorization', `Bearer ${token}`) + .expect(404); }); it('rejects schedules whose frame or core windows do not increase', async () => { @@ -147,6 +207,7 @@ describe('WorkSchedules — CRUD + assignment', () => { .expect(201); const reread = await ctx.http .get(`/api/work-schedules/${first.body.id}`) + .set('Authorization', `Bearer ${token}`) .expect(200); expect(reread.body.isDefault).toBe(false); expect(second.body.isDefault).toBe(true); @@ -228,6 +289,7 @@ describe('WorkSchedules — CRUD + assignment', () => { await update({ ...samplePayload, scheduledWorkday }).expect(400); const reread = await ctx.http .get(`/api/work-schedules/${created.body.id}`) + .set('Authorization', authorization) .expect(200); expect(reread.body.terminalRules).toEqual(terminalRules); expect(reread.body.scheduledWorkday).toBeNull(); diff --git a/apps/api/openapi.json b/apps/api/openapi.json index 0feecdb..e001bac 100644 --- a/apps/api/openapi.json +++ b/apps/api/openapi.json @@ -1129,6 +1129,11 @@ } } }, + "security": [ + { + "bearer": [] + } + ], "tags": ["work-schedules"] }, "post": { @@ -1189,6 +1194,11 @@ } } }, + "security": [ + { + "bearer": [] + } + ], "tags": ["work-schedules"] }, "put": { @@ -1357,6 +1367,11 @@ } } }, + "security": [ + { + "bearer": [] + } + ], "tags": ["projects"] }, "post": { @@ -1437,6 +1452,11 @@ } } }, + "security": [ + { + "bearer": [] + } + ], "tags": ["projects"] } }, @@ -1465,6 +1485,11 @@ } } }, + "security": [ + { + "bearer": [] + } + ], "tags": ["projects"] }, "put": { diff --git a/apps/api/src/app/projects/projects.controller.ts b/apps/api/src/app/projects/projects.controller.ts index 6da54bc..dffc397 100644 --- a/apps/api/src/app/projects/projects.controller.ts +++ b/apps/api/src/app/projects/projects.controller.ts @@ -21,7 +21,6 @@ import { ApiOkResponse, ApiTags, } from '@nestjs/swagger'; -import { JwtAuthGuard } from '../auth/jwt-auth.guard'; import { Roles } from '../auth/roles.decorator'; import { RolesGuard } from '../auth/roles.guard'; import { ProjectsService } from './projects.service'; @@ -47,7 +46,10 @@ export class ProjectsController { constructor(private readonly projects: ProjectsService) {} @Get() + @ApiBearerAuth() @ApiOkResponse({ type: [ProjectDto] }) + @UseGuards(RolesGuard) + @Roles('Manager', 'HRAdmin') list( @Query('includeInactive') includeInactive?: string, ): Promise { @@ -58,29 +60,34 @@ export class ProjectsController { // declaration order and ParseUUIDPipe would reject them with a 400. @Get('assignments') @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') listAssignments(): Promise { return this.projects.listAssignments(); } @Get('bookable') + @ApiBearerAuth() @ApiOkResponse({ type: [BookableProjectDto] }) listBookable( @Query('employeeId', new ParseUUIDPipe()) employeeId: string, + @CurrentUser() user: JwtUser, ): Promise { - return this.projects.listBookable(employeeId); + return this.projects.listBookable(employeeId, user); } @Get(':id') + @ApiBearerAuth() @ApiOkResponse({ type: ProjectDto }) + @UseGuards(RolesGuard) + @Roles('Manager', 'HRAdmin') get(@Param('id', new ParseUUIDPipe()) id: string): Promise { return this.projects.getById(id); } @Get(':id/report') @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') report( @Param('id', new ParseUUIDPipe()) id: string, @@ -97,7 +104,7 @@ export class ProjectsController { @Post() @ApiCreatedResponse({ type: ProjectDto }) @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') create( @Body() dto: UpsertProjectDto, @@ -109,7 +116,7 @@ export class ProjectsController { @Put(':id') @ApiOkResponse({ type: ProjectDto }) @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') update( @Param('id', new ParseUUIDPipe()) id: string, @@ -121,7 +128,7 @@ export class ProjectsController { @Delete(':id') @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') @HttpCode(HttpStatus.NO_CONTENT) remove( @@ -138,7 +145,7 @@ export class ProjectsController { 'Project contains activities (PROJECT_HAS_ACTIVITIES), the order number already exists, or the order exceeds the project plan.', }) @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') createServiceOrder( @Param('id', new ParseUUIDPipe()) id: string, @@ -151,7 +158,7 @@ export class ProjectsController { @Put(':id/service-orders/:orderId') @ApiOkResponse({ type: ServiceOrderDto }) @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') updateServiceOrder( @Param('id', new ParseUUIDPipe()) id: string, @@ -164,7 +171,7 @@ export class ProjectsController { @Delete(':id/service-orders/:orderId') @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') @HttpCode(HttpStatus.NO_CONTENT) removeServiceOrder( @@ -182,7 +189,7 @@ export class ProjectsController { }) @ApiNotFoundResponse({ description: 'Project not found.' }) @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') listActivities( @Param('id', new ParseUUIDPipe()) id: string, @@ -198,7 +205,7 @@ export class ProjectsController { 'Project contains service orders (PROJECT_HAS_SERVICE_ORDERS) or the activity name already exists.', }) @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') createActivity( @Param('id', new ParseUUIDPipe()) id: string, @@ -215,7 +222,7 @@ export class ProjectsController { description: 'Activity name already exists in this project.', }) @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') updateActivity( @Param('id', new ParseUUIDPipe()) id: string, @@ -233,7 +240,7 @@ export class ProjectsController { description: 'Activity is referenced by a time entry.', }) @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') @HttpCode(HttpStatus.NO_CONTENT) removeActivity( @@ -246,7 +253,7 @@ export class ProjectsController { @Put(':id/assignments/:employeeId') @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') @HttpCode(HttpStatus.NO_CONTENT) assign( @@ -259,7 +266,7 @@ export class ProjectsController { @Delete(':id/assignments/:employeeId') @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) + @UseGuards(RolesGuard) @Roles('Manager', 'HRAdmin') @HttpCode(HttpStatus.NO_CONTENT) unassign( diff --git a/apps/api/src/app/projects/projects.service.ts b/apps/api/src/app/projects/projects.service.ts index 25940a1..c775923 100644 --- a/apps/api/src/app/projects/projects.service.ts +++ b/apps/api/src/app/projects/projects.service.ts @@ -71,9 +71,7 @@ export class ProjectsService { }), this.loadIstStats(), ]); - return rows.map((r) => - toProjectDto(r, stats.get(r.id) ?? EMPTY_IST_STATS), - ); + return rows.map((r) => toProjectDto(r, stats.get(r.id) ?? EMPTY_IST_STATS)); } async getById(id: string): Promise { @@ -498,7 +496,11 @@ export class ProjectsService { } /** Active projects the employee is assigned to — the booking selector source. */ - async listBookable(employeeId: string): Promise { + async listBookable( + employeeId: string, + actor: JwtUser, + ): Promise { + await this.assertBookableReadAccess(employeeId, actor); const rows = await this.prisma.project.findMany({ where: { isActive: true, @@ -531,6 +533,23 @@ export class ProjectsService { })); } + private async assertBookableReadAccess( + employeeId: string, + actor: JwtUser, + ): Promise { + if (employeeId === actor.id || actor.role === 'HRAdmin') return; + const isDirectReport = + actor.role === 'Manager' && + (await this.prisma.employee.count({ + where: { id: employeeId, managerId: actor.id }, + })) > 0; + if (!isDirectReport) { + throw new ForbiddenException( + "Employees may only access their own or their team's bookable projects", + ); + } + } + /** * Booking authorization used by clock-in, retroactive assignment, and split: * the project must exist (404), be active (400), and the employee must be diff --git a/apps/api/src/app/projects/solo-project-access.guard.ts b/apps/api/src/app/projects/solo-project-access.guard.ts index 40895b1..a08b7ca 100644 --- a/apps/api/src/app/projects/solo-project-access.guard.ts +++ b/apps/api/src/app/projects/solo-project-access.guard.ts @@ -7,7 +7,7 @@ import { JwtAuthGuard } from '../auth/jwt-auth.guard'; import type { JwtUser } from '../auth/jwt.strategy'; import { InstallationService } from '../installation/installation.service'; -/** Preserve legacy Team reads while enforcing authenticated Solo ownership. */ +/** Authenticate every project request and enforce Solo ownership boundaries. */ @Injectable() export class SoloProjectAccessGuard extends JwtAuthGuard { constructor(private readonly installation: InstallationService) { @@ -15,8 +15,8 @@ export class SoloProjectAccessGuard extends JwtAuthGuard { } override async canActivate(context: ExecutionContext): Promise { - if (!(await this.installation.isSolo())) return true; await super.canActivate(context); + if (!(await this.installation.isSolo())) return true; const request = context.switchToHttp().getRequest<{ user: JwtUser; query: { employeeId?: string }; diff --git a/apps/api/src/app/time-entries/time-entries.service.ts b/apps/api/src/app/time-entries/time-entries.service.ts index 634af37..ff80b8c 100644 --- a/apps/api/src/app/time-entries/time-entries.service.ts +++ b/apps/api/src/app/time-entries/time-entries.service.ts @@ -938,7 +938,7 @@ export class TimeEntriesService { select: { employeeId: true, projectId: true, voidedAt: true }, }); if (!entry) throw new NotFoundException(`Time entry ${id} not found`); - this.assertSelfOrAdmin(entry.employeeId, user); + await this.assertSelfOrManagerOrAdmin(entry.employeeId, user); await this.assertTransactionAccess( tx, entry.employeeId, @@ -2035,7 +2035,7 @@ export class TimeEntriesService { 'Solo access is limited to your own time entries', ); } - this.assertSelfOrAdmin(employeeId, user); + await this.assertSelfOrManagerOrAdmin(employeeId, user); } private assertMutable( @@ -2094,25 +2094,27 @@ export class TimeEntriesService { throw new ForbiddenException( 'Solo writes are limited to your own entries', ); - } else if (actorId !== employeeId) { + } + const employee = await tx.employee.findUnique({ + where: { id: employeeId }, + select: { isActive: true, managerId: true }, + }); + if (!employee?.isActive) + throw new ForbiddenException('Employee account is not active'); + if (!isSolo && actorId !== employeeId) { const actor = await tx.employee.findUnique({ where: { id: actorId }, select: { isActive: true, role: true }, }); if ( !actor?.isActive || - (actor.role !== 'Manager' && actor.role !== 'HRAdmin') + (actor.role !== 'HRAdmin' && + (actor.role !== 'Manager' || employee.managerId !== actorId)) ) throw new ForbiddenException( - 'Current manager or administrator access is required', + 'Current direct manager or administrator access is required', ); } - const employee = await tx.employee.findUnique({ - where: { id: employeeId }, - select: { isActive: true }, - }); - if (!employee?.isActive) - throw new ForbiddenException('Employee account is not active'); return isSolo; } @@ -2384,13 +2386,20 @@ export class TimeEntriesService { }); } - private assertSelfOrAdmin(employeeId: string, user: JwtUser): void { - const isAdmin = user.role === 'Manager' || user.role === 'HRAdmin'; - if (employeeId !== user.id && !isAdmin) { - throw new ForbiddenException( - 'Only the owner or a Manager/HRAdmin may modify this entry', - ); - } + private async assertSelfOrManagerOrAdmin( + employeeId: string, + user: JwtUser, + ): Promise { + if (employeeId === user.id || user.role === 'HRAdmin') return; + const isDirectManager = + user.role === 'Manager' && + (await this.prisma.employee.count({ + where: { id: employeeId, managerId: user.id }, + })) > 0; + if (isDirectManager) return; + throw new ForbiddenException( + 'Only the owner, their direct Manager, or an HRAdmin may access this entry', + ); } private clearClockOutAudit() { diff --git a/apps/api/src/app/work-schedules/work-schedules.controller.ts b/apps/api/src/app/work-schedules/work-schedules.controller.ts index ba33d3c..9f36876 100644 --- a/apps/api/src/app/work-schedules/work-schedules.controller.ts +++ b/apps/api/src/app/work-schedules/work-schedules.controller.ts @@ -30,7 +30,10 @@ import { } from './work-schedules.dto'; @ApiTags('work-schedules') +@ApiBearerAuth() @Controller('work-schedules') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('HRAdmin') export class WorkSchedulesController { constructor(private readonly schedules: WorkSchedulesService) {} @@ -50,18 +53,12 @@ export class WorkSchedulesController { @Post() @ApiCreatedResponse({ type: WorkScheduleResponse }) - @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) - @Roles('HRAdmin') create(@Body() dto: UpsertWorkScheduleDto): Promise { return this.schedules.create(dto); } @Put(':id') @ApiOkResponse({ type: WorkScheduleResponse }) - @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) - @Roles('HRAdmin') update( @Param('id', new ParseUUIDPipe()) id: string, @Body() dto: UpsertWorkScheduleDto, @@ -70,18 +67,12 @@ export class WorkSchedulesController { } @Delete(':id') - @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) - @Roles('HRAdmin') @HttpCode(HttpStatus.NO_CONTENT) remove(@Param('id', new ParseUUIDPipe()) id: string): Promise { return this.schedules.remove(id); } @Post(':id/assign') - @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) - @Roles('HRAdmin') assign( @Param('id', new ParseUUIDPipe()) id: string, @Body() dto: AssignToEmployeeDto, @@ -90,9 +81,6 @@ export class WorkSchedulesController { } @Post(':id/bulk-assign') - @ApiBearerAuth() - @UseGuards(JwtAuthGuard, RolesGuard) - @Roles('HRAdmin') bulkAssign( @Param('id', new ParseUUIDPipe()) id: string, @Body() dto: BulkAssignDto, From 1ac8d17812483dce5b5a9637fc021fca0298713e Mon Sep 17 00:00:00 2001 From: Patrick Schiller Date: Sat, 5 Dec 2026 11:49:15 +0100 Subject: [PATCH 2/2] test(security): align activity suites with access boundaries Signed-off-by: Patrick Schiller --- .../src/api/project-activities.e2e.spec.ts | 35 +++++++++++++++---- .../src/api/time-entry-activities.e2e.spec.ts | 13 ++++--- 2 files changed, 36 insertions(+), 12 deletions(-) diff --git a/apps/api-e2e/src/api/project-activities.e2e.spec.ts b/apps/api-e2e/src/api/project-activities.e2e.spec.ts index f5d2061..0e351b0 100644 --- a/apps/api-e2e/src/api/project-activities.e2e.spec.ts +++ b/apps/api-e2e/src/api/project-activities.e2e.spec.ts @@ -318,9 +318,15 @@ describe('Project activity catalog', () => { const inactiveConflict = await addOrder().expect(409); expect(inactiveConflict.body.code).toBe('PROJECT_HAS_ACTIVITIES'); - const item = await ctx.http.get(projectPath).expect(200); + const item = await ctx.http + .get(projectPath) + .auth(token, { type: 'bearer' }) + .expect(200); expect(item.body.activityCount).toBe(1); - const listed = await ctx.http.get('/api/projects').expect(200); + const listed = await ctx.http + .get('/api/projects') + .auth(token, { type: 'bearer' }) + .expect(200); expect(listed.body).toContainEqual( expect.objectContaining({ id: project.id, activityCount: 1 }), ); @@ -331,8 +337,14 @@ describe('Project activity catalog', () => { .expect(200); expect(edited.body.activityCount).toBe(1); - await ctx.http.delete(activityPath).auth(token, { type: 'bearer' }).expect(204); - const empty = await ctx.http.get(projectPath).expect(200); + await ctx.http + .delete(activityPath) + .auth(token, { type: 'bearer' }) + .expect(204); + const empty = await ctx.http + .get(projectPath) + .auth(token, { type: 'bearer' }) + .expect(200); expect(empty.body.activityCount).toBe(0); await addOrder().expect(201); }); @@ -357,7 +369,10 @@ describe('Project activity catalog', () => { } else { expect(activity.body.code).toBe('PROJECT_HAS_SERVICE_ORDERS'); } - const saved = await ctx.http.get(`/api/projects/${project.id}`).expect(200); + const saved = await ctx.http + .get(`/api/projects/${project.id}`) + .auth(token, { type: 'bearer' }) + .expect(200); expect(saved.body.activityCount).toBe(activity.status === 201 ? 1 : 0); expect(saved.body.serviceOrders).toHaveLength(order.status === 201 ? 1 : 0); }); @@ -382,7 +397,10 @@ describe('Project activity catalog', () => { }, }); - const mixed = await ctx.http.get(projectPath).expect(200); + const mixed = await ctx.http + .get(projectPath) + .auth(token, { type: 'bearer' }) + .expect(200); expect(mixed.body).toMatchObject({ activityCount: 1, serviceOrders: [expect.objectContaining({ id: legacyOrder.id })], @@ -423,7 +441,10 @@ describe('Project activity catalog', () => { .delete(`${path}/${activity.id}`) .auth(token, { type: 'bearer' }) .expect(409); - await ctx.http.delete(orderPath).auth(token, { type: 'bearer' }).expect(204); + await ctx.http + .delete(orderPath) + .auth(token, { type: 'bearer' }) + .expect(204); expect( await ctx.prisma.timeEntry.findUnique({ where: { id: entry.id } }), ).toEqual(entry); diff --git a/apps/api-e2e/src/api/time-entry-activities.e2e.spec.ts b/apps/api-e2e/src/api/time-entry-activities.e2e.spec.ts index 5ed3dd0..454b056 100644 --- a/apps/api-e2e/src/api/time-entry-activities.e2e.spec.ts +++ b/apps/api-e2e/src/api/time-entry-activities.e2e.spec.ts @@ -24,13 +24,18 @@ describe('Time entry activity corrections', () => { await ctx.reset(); }); - async function employee(label: string, role?: 'Manager' | 'HRAdmin') { + async function employee( + label: string, + role?: 'Manager' | 'HRAdmin', + managerId?: string, + ) { return seedEmployee(ctx.prisma, { personalNo: label, firstName: 'Synthetic', lastName: label, email: `${label}@editor.test`, role, + managerId, }); } @@ -39,11 +44,9 @@ describe('Time entry activity corrections', () => { } async function fixture() { - const worker = await employee('worker'); - const other = await employee('other'); - // Manager is intentionally not the entry owner's supervisor or assigned to - // the entry's project; the existing editor permits privileged corrections. const manager = await employee('manager', 'Manager'); + const worker = await employee('worker', undefined, manager.id); + const other = await employee('other'); const hr = await employee('hr', 'HRAdmin'); const assigned = await seedProject(ctx.prisma, { code: 'EDITOR',