import { Test, TestingModule } from "@nestjs/testing"; import { ApiKeysService } from "./api-keys.service"; import { PrismaService } from "../prisma/prisma.service"; import { NotFoundException, UnauthorizedException } from "@nestjs/common"; import * as crypto from "crypto"; describe("ApiKeysService", () => { let service: ApiKeysService; const mockPrisma = { apiKey: { findMany: jest.fn(), findUnique: jest.fn(), create: jest.fn(), update: jest.fn(), delete: jest.fn(), }, }; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ ApiKeysService, { provide: PrismaService, useValue: mockPrisma }, ], }).compile(); service = module.get(ApiKeysService); jest.clearAllMocks(); }); it("should be defined", () => { expect(service).toBeDefined(); }); describe("create", () => { it("should generate a cn_live_ key, hash it with sha256, and return raw secret once", async () => { mockPrisma.apiKey.create.mockImplementation(({ data }) => ({ id: "key-1", name: data.name, keyPrefix: data.keyPrefix, scopes: data.scopes, status: "ACTIVE", description: data.description, expiresAt: data.expiresAt, createdAt: new Date(), })); const res = await service.create({ name: "Torob Sync", scopes: ["read", "write"], }); expect(res.rawKey).toMatch(/^cn_live_[0-9a-f]{48}$/); expect(res.apiKey.keyPrefix).toBe(res.rawKey.substring(0, 12)); expect(res.apiKey.scopes).toEqual(["read", "write"]); expect(mockPrisma.apiKey.create).toHaveBeenCalled(); }); }); describe("validateKey", () => { it("should throw UnauthorizedException if key format is invalid", async () => { await expect(service.validateKey("invalid-prefix-123")).rejects.toThrow( UnauthorizedException, ); await expect(service.validateKey("")).rejects.toThrow( UnauthorizedException, ); }); it("should throw UnauthorizedException if key not found", async () => { mockPrisma.apiKey.findUnique.mockResolvedValue(null); await expect( service.validateKey("cn_live_0123456789abcdef0123456789abcdef"), ).rejects.toThrow(UnauthorizedException); }); it("should throw UnauthorizedException if key is REVOKED", async () => { mockPrisma.apiKey.findUnique.mockResolvedValue({ id: "key-1", status: "REVOKED", scopes: "read", }); await expect( service.validateKey("cn_live_0123456789abcdef0123456789abcdef"), ).rejects.toThrow("این API Key باطل یا غیرفعال شده است"); }); it("should throw UnauthorizedException if key is expired", async () => { mockPrisma.apiKey.findUnique.mockResolvedValue({ id: "key-1", status: "ACTIVE", scopes: "read", expiresAt: new Date(Date.now() - 10000), // past }); await expect( service.validateKey("cn_live_0123456789abcdef0123456789abcdef"), ).rejects.toThrow("این API Key منقضی شده است"); }); it("should grant Admin role only if explicit admin scope is present", async () => { const rawKey = "cn_live_11112222333344445555666677778888"; mockPrisma.apiKey.findUnique.mockResolvedValue({ id: "key-admin", name: "Admin Key", status: "ACTIVE", scopes: "read,admin,write", expiresAt: null, }); mockPrisma.apiKey.update.mockResolvedValue({}); const user = await service.validateKey(rawKey); expect(user.role).toBe("Admin"); expect(user.isApiKey).toBe(true); expect(user.scopes).toContain("admin"); }); it("should grant USER role if scope is wildcard or regular scope without admin", async () => { const rawKey = "cn_live_11112222333344445555666677778888"; mockPrisma.apiKey.findUnique.mockResolvedValue({ id: "key-user", name: "Torob Bot", status: "ACTIVE", scopes: "*", expiresAt: null, }); mockPrisma.apiKey.update.mockResolvedValue({}); const user = await service.validateKey(rawKey); expect(user.role).toBe("USER"); }); }); describe("toggleStatus & delete", () => { it("should toggle status from ACTIVE to REVOKED", async () => { mockPrisma.apiKey.findUnique.mockResolvedValue({ id: "key-1", status: "ACTIVE", }); mockPrisma.apiKey.update.mockResolvedValue({ id: "key-1", status: "REVOKED", scopes: "read", }); const res = await service.toggleStatus("key-1"); expect(res.status).toBe("REVOKED"); expect(mockPrisma.apiKey.update).toHaveBeenCalledWith({ where: { id: "key-1" }, data: { status: "REVOKED" }, select: expect.any(Object), }); }); it("should throw NotFoundException on non-existent key in delete", async () => { mockPrisma.apiKey.findUnique.mockResolvedValue(null); await expect(service.delete("non-existent")).rejects.toThrow( NotFoundException, ); }); }); });