import { ConflictException, NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Prisma } from '@prisma/client'; import { EncryptionService } from '../common/crypto/encryption.service'; import { PrismaService } from '../prisma/prisma.service'; import { ApiKeysService } from './api-keys.service'; function prismaKnownError(code: string): Prisma.PrismaClientKnownRequestError { return new Prisma.PrismaClientKnownRequestError('mock', { code, clientVersion: 'test', }); } describe('ApiKeysService', () => { let service: ApiKeysService; let prisma: { apiKey: { create: jest.Mock; findMany: jest.Mock; findUnique: jest.Mock; update: jest.Mock; delete: jest.Mock; }; }; let encryption: { encrypt: jest.Mock; decrypt: jest.Mock }; const dbApiKey = { id: 1, userId: 1, serviceName: 'openrouter_api_key', key: 'encrypted-payload', createdAt: new Date('2026-01-01'), updatedAt: new Date('2026-01-01'), }; beforeEach(async () => { prisma = { apiKey: { create: jest.fn(), findMany: jest.fn(), findUnique: jest.fn(), update: jest.fn(), delete: jest.fn(), }, }; encryption = { encrypt: jest.fn().mockReturnValue('encrypted-payload'), decrypt: jest.fn().mockReturnValue('sk-or-v1-plaintext'), }; const module: TestingModule = await Test.createTestingModule({ providers: [ ApiKeysService, { provide: PrismaService, useValue: prisma }, { provide: EncryptionService, useValue: encryption }, ], }).compile(); service = module.get(ApiKeysService); }); describe('create()', () => { it('should encrypt the key before storing it and never return it', async () => { prisma.apiKey.create.mockResolvedValue(dbApiKey); const result = await service.create({ userId: 1, serviceName: 'openrouter_api_key', key: 'sk-or-v1-plaintext', }); expect(encryption.encrypt).toHaveBeenCalledWith('sk-or-v1-plaintext'); expect(result).not.toHaveProperty('key'); expect(result.serviceName).toBe('openrouter_api_key'); }); it('should throw ConflictException when the service already has a key for this user', async () => { prisma.apiKey.create.mockRejectedValue(prismaKnownError('P2002')); await expect( service.create({ userId: 1, serviceName: 'openrouter_api_key', key: 'x', }), ).rejects.toThrow(ConflictException); }); it('should rethrow unexpected errors', async () => { prisma.apiKey.create.mockRejectedValue(new Error('boom')); await expect( service.create({ userId: 1, serviceName: 'openrouter_api_key', key: 'x', }), ).rejects.toThrow('boom'); }); }); describe('findAll()', () => { it('should list all keys without filtering when no userId is given', async () => { prisma.apiKey.findMany.mockResolvedValue([dbApiKey]); const result = await service.findAll(); expect(prisma.apiKey.findMany).toHaveBeenCalledWith( expect.objectContaining({ where: undefined }), ); expect(result).toHaveLength(1); expect(result[0]).not.toHaveProperty('key'); }); it('should filter by userId when given', async () => { prisma.apiKey.findMany.mockResolvedValue([dbApiKey]); await service.findAll(1); expect(prisma.apiKey.findMany).toHaveBeenCalledWith( expect.objectContaining({ where: { userId: 1 } }), ); }); }); describe('findOne()', () => { it('should return the key metadata when found', async () => { prisma.apiKey.findUnique.mockResolvedValue(dbApiKey); const result = await service.findOne(1); expect(result.id).toBe(1); expect(result).not.toHaveProperty('key'); }); it('should throw NotFoundException when missing', async () => { prisma.apiKey.findUnique.mockResolvedValue(null); await expect(service.findOne(999)).rejects.toThrow(NotFoundException); }); }); describe('update()', () => { it('should re-encrypt the key when a new value is provided', async () => { prisma.apiKey.update.mockResolvedValue(dbApiKey); await service.update(1, { key: 'nouvelle-valeur' }); expect(encryption.encrypt).toHaveBeenCalledWith('nouvelle-valeur'); }); it('should not touch the key field when no new value is provided', async () => { prisma.apiKey.update.mockResolvedValue(dbApiKey); await service.update(1, { serviceName: 'nouveau_nom' }); const updateArgs = ( prisma.apiKey.update.mock.calls[0] as [Prisma.ApiKeyUpdateArgs] )[0]; expect(updateArgs.data.key).toBeUndefined(); expect(encryption.encrypt).not.toHaveBeenCalled(); }); it('should throw NotFoundException when the key does not exist', async () => { prisma.apiKey.update.mockRejectedValue(prismaKnownError('P2025')); await expect(service.update(999, { serviceName: 'x' })).rejects.toThrow( NotFoundException, ); }); it('should throw ConflictException on duplicate (userId, serviceName)', async () => { prisma.apiKey.update.mockRejectedValue(prismaKnownError('P2002')); await expect(service.update(1, { serviceName: 'dup' })).rejects.toThrow( ConflictException, ); }); it('should rethrow unexpected errors', async () => { prisma.apiKey.update.mockRejectedValue(new Error('boom')); await expect(service.update(1, { serviceName: 'x' })).rejects.toThrow( 'boom', ); }); }); describe('remove()', () => { it('should delete the key', async () => { prisma.apiKey.delete.mockResolvedValue(dbApiKey); await expect(service.remove(1)).resolves.toBeUndefined(); }); it('should throw NotFoundException when the key does not exist', async () => { prisma.apiKey.delete.mockRejectedValue(prismaKnownError('P2025')); await expect(service.remove(999)).rejects.toThrow(NotFoundException); }); it('should rethrow unexpected errors', async () => { prisma.apiKey.delete.mockRejectedValue(new Error('boom')); await expect(service.remove(1)).rejects.toThrow('boom'); }); }); describe('getDecryptedValue()', () => { it('should return the decrypted plaintext value for internal use', async () => { prisma.apiKey.findUnique.mockResolvedValue(dbApiKey); const value = await service.getDecryptedValue(1, 'openrouter_api_key'); expect(prisma.apiKey.findUnique).toHaveBeenCalledWith({ where: { userId_serviceName: { userId: 1, serviceName: 'openrouter_api_key' }, }, }); expect(encryption.decrypt).toHaveBeenCalledWith('encrypted-payload'); expect(value).toBe('sk-or-v1-plaintext'); }); it('should throw NotFoundException when no key exists for this service', async () => { prisma.apiKey.findUnique.mockResolvedValue(null); await expect( service.getDecryptedValue(1, 'unknown_service'), ).rejects.toThrow(NotFoundException); }); }); describe('getAllDecrypted()', () => { it('should return a map of serviceName to decrypted value for every key of the user', async () => { prisma.apiKey.findMany.mockResolvedValue([ dbApiKey, { ...dbApiKey, id: 2, serviceName: 'elevenlabs_api_key', key: 'other-encrypted', }, ]); encryption.decrypt.mockImplementation((payload: string) => payload === 'other-encrypted' ? 'sk-el-plaintext' : 'sk-or-v1-plaintext', ); const result = await service.getAllDecrypted(1); expect(prisma.apiKey.findMany).toHaveBeenCalledWith({ where: { userId: 1 }, }); expect(result).toEqual({ openrouter_api_key: 'sk-or-v1-plaintext', elevenlabs_api_key: 'sk-el-plaintext', }); }); it('should return an empty object when the user has no keys', async () => { prisma.apiKey.findMany.mockResolvedValue([]); await expect(service.getAllDecrypted(1)).resolves.toEqual({}); }); }); });