|
| 1 | +import { ExecutionContext, ForbiddenException, HttpException, UnauthorizedException } from '@nestjs/common'; |
| 2 | +import { PrismaService } from '../common/prisma.service'; |
| 3 | +import { JwtOrManagementKeyGuard } from './jwt-or-management-key.guard'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Integration test for the management-key path of the guard, against a real |
| 7 | + * database. The JWT fallback (no key presented) is Passport's unchanged |
| 8 | + * behaviour and is not exercised here. |
| 9 | + */ |
| 10 | +const prisma = new PrismaService(); |
| 11 | +// Redis not connected → the per-key rate limit falls open (not under test here). |
| 12 | +const noRedis = { isConnected: false } as never; |
| 13 | +const guard = new JwtOrManagementKeyGuard(prisma as never, noRedis); |
| 14 | + |
| 15 | +const TAG = `mgmtcli-test-${Date.now()}`; |
| 16 | +const orgId = `${TAG}-org`; |
| 17 | +const adminId = `${TAG}-admin`; |
| 18 | +const memberId = `${TAG}-member`; |
| 19 | + |
| 20 | +const keys = { |
| 21 | + mcp: `mcp_${'a'.repeat(40)}${Date.now()}`, |
| 22 | + read: `mcp_${'b'.repeat(40)}${Date.now()}`, |
| 23 | + admin: `mcp_${'c'.repeat(40)}${Date.now()}`, |
| 24 | + memberAdminScope: `mcp_${'d'.repeat(40)}${Date.now()}`, |
| 25 | + inactive: `mcp_${'e'.repeat(40)}${Date.now()}`, |
| 26 | +}; |
| 27 | + |
| 28 | +function contextFor(key: string | undefined, method: string): { ctx: ExecutionContext; req: Record<string, unknown> } { |
| 29 | + const req: Record<string, unknown> = { |
| 30 | + method, |
| 31 | + headers: key ? { authorization: `Bearer ${key}` } : {}, |
| 32 | + }; |
| 33 | + const ctx = { |
| 34 | + switchToHttp: () => ({ getRequest: () => req }), |
| 35 | + } as unknown as ExecutionContext; |
| 36 | + return { ctx, req }; |
| 37 | +} |
| 38 | + |
| 39 | +beforeAll(async () => { |
| 40 | + await prisma.$connect(); |
| 41 | + await prisma.organization.create({ data: { id: orgId, name: TAG } }); |
| 42 | + await prisma.user.create({ |
| 43 | + data: { id: adminId, email: `${TAG}[email protected]`, role: 'ADMIN', organizationId: orgId }, |
| 44 | + }); |
| 45 | + await prisma.user.create({ |
| 46 | + data: { id: memberId, email: `${TAG}[email protected]`, role: 'VIEWER', organizationId: orgId }, |
| 47 | + }); |
| 48 | + await prisma.organizationMember.create({ data: { userId: adminId, organizationId: orgId, role: 'ADMIN' } }); |
| 49 | + await prisma.organizationMember.create({ data: { userId: memberId, organizationId: orgId, role: 'VIEWER' } }); |
| 50 | + |
| 51 | + const mk = (key: string, userId: string, scope: 'MCP' | 'MANAGEMENT_READ' | 'MANAGEMENT_ADMIN', isActive = true) => |
| 52 | + prisma.mcpApiKey.create({ data: { key, name: key.slice(0, 12), userId, organizationId: orgId, scope, isActive } }); |
| 53 | + await mk(keys.mcp, adminId, 'MCP'); |
| 54 | + await mk(keys.read, adminId, 'MANAGEMENT_READ'); |
| 55 | + await mk(keys.admin, adminId, 'MANAGEMENT_ADMIN'); |
| 56 | + await mk(keys.memberAdminScope, memberId, 'MANAGEMENT_ADMIN'); |
| 57 | + await mk(keys.inactive, adminId, 'MANAGEMENT_ADMIN', false); |
| 58 | +}); |
| 59 | + |
| 60 | +afterAll(async () => { |
| 61 | + await prisma.mcpApiKey.deleteMany({ where: { organizationId: orgId } }); |
| 62 | + await prisma.organizationMember.deleteMany({ where: { organizationId: orgId } }); |
| 63 | + await prisma.user.deleteMany({ where: { organizationId: orgId } }); |
| 64 | + await prisma.organization.deleteMany({ where: { id: orgId } }); |
| 65 | + await prisma.$disconnect(); |
| 66 | +}); |
| 67 | + |
| 68 | +describe('JwtOrManagementKeyGuard (management-key path)', () => { |
| 69 | + it('rejects an MCP-scoped key on the management API', async () => { |
| 70 | + const { ctx } = contextFor(keys.mcp, 'GET'); |
| 71 | + await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(UnauthorizedException); |
| 72 | + }); |
| 73 | + |
| 74 | + it('rejects an inactive key', async () => { |
| 75 | + const { ctx } = contextFor(keys.inactive, 'GET'); |
| 76 | + await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(UnauthorizedException); |
| 77 | + }); |
| 78 | + |
| 79 | + it('allows a MANAGEMENT_READ key on a GET and sets the user+role', async () => { |
| 80 | + const { ctx, req } = contextFor(keys.read, 'GET'); |
| 81 | + await expect(guard.canActivate(ctx)).resolves.toBe(true); |
| 82 | + expect(req.user).toMatchObject({ sub: adminId, role: 'ADMIN', organizationId: orgId }); |
| 83 | + expect(req.mcpKeyScope).toBe('MANAGEMENT_READ'); |
| 84 | + }); |
| 85 | + |
| 86 | + it('forbids a MANAGEMENT_READ key on a non-safe method', async () => { |
| 87 | + const { ctx } = contextFor(keys.read, 'POST'); |
| 88 | + await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(ForbiddenException); |
| 89 | + }); |
| 90 | + |
| 91 | + it('allows a MANAGEMENT_ADMIN key on a POST', async () => { |
| 92 | + const { ctx, req } = contextFor(keys.admin, 'POST'); |
| 93 | + await expect(guard.canActivate(ctx)).resolves.toBe(true); |
| 94 | + expect(req.user).toMatchObject({ sub: adminId, role: 'ADMIN' }); |
| 95 | + }); |
| 96 | + |
| 97 | + it('carries a non-admin owner role even with an admin-scope key (RolesGuard will cap it)', async () => { |
| 98 | + const { ctx, req } = contextFor(keys.memberAdminScope, 'POST'); |
| 99 | + await expect(guard.canActivate(ctx)).resolves.toBe(true); |
| 100 | + expect((req.user as { role: string }).role).toBe('VIEWER'); |
| 101 | + }); |
| 102 | + |
| 103 | + it('accepts the key via the X-API-Key header too', async () => { |
| 104 | + const req: Record<string, unknown> = { method: 'GET', headers: { 'x-api-key': keys.read } }; |
| 105 | + const ctx = { switchToHttp: () => ({ getRequest: () => req }) } as unknown as ExecutionContext; |
| 106 | + await expect(guard.canActivate(ctx)).resolves.toBe(true); |
| 107 | + }); |
| 108 | + |
| 109 | + it('rate-limits a key once Redis is connected and the per-minute ceiling is exceeded', async () => { |
| 110 | + const counts = new Map<string, number>(); |
| 111 | + const fakeRedis = { |
| 112 | + isConnected: true, |
| 113 | + incr: async (k: string) => { const n = (counts.get(k) ?? 0) + 1; counts.set(k, n); return n; }, |
| 114 | + expire: async () => undefined, |
| 115 | + ttl: async () => 60, |
| 116 | + } as never; |
| 117 | + const previous = process.env.MANAGEMENT_RATE_LIMIT_PER_MINUTE; |
| 118 | + process.env.MANAGEMENT_RATE_LIMIT_PER_MINUTE = '2'; |
| 119 | + try { |
| 120 | + const limited = new JwtOrManagementKeyGuard(prisma as never, fakeRedis); |
| 121 | + const call = () => limited.canActivate(contextFor(keys.admin, 'GET').ctx); |
| 122 | + await expect(call()).resolves.toBe(true); |
| 123 | + await expect(call()).resolves.toBe(true); |
| 124 | + let thrown: unknown; |
| 125 | + try { await call(); } catch (error) { thrown = error; } |
| 126 | + expect(thrown).toBeInstanceOf(HttpException); |
| 127 | + expect((thrown as HttpException).getStatus()).toBe(429); |
| 128 | + } finally { |
| 129 | + if (previous === undefined) delete process.env.MANAGEMENT_RATE_LIMIT_PER_MINUTE; |
| 130 | + else process.env.MANAGEMENT_RATE_LIMIT_PER_MINUTE = previous; |
| 131 | + } |
| 132 | + }); |
| 133 | +}); |
0 commit comments