/** * crypto.ts — AES-256-GCM 加解密工具单元测试 * * 测试策略: * - Web Crypto API (crypto.subtle) 在 jsdom 中不可用,完整 mock global.crypto * - 使用 jest.resetModules() + 动态 import 确保每个测试用例获得干净的模块实例 * (cachedKey 是模块级变量,测试间需要隔离) * - 通过 mock 的 crypto.subtle 方法验证参数传递是否正确 * - 覆盖正常路径、密钥缺失、加解密异常、key 缓存等场景 */ // @ts-nocheck import { describe, it, expect, beforeEach, afterEach, jest } from '@jest/globals'; // ─── Mock 定义 ─────────────────────────────────────────────────────────────── const mockImportKey = jest.fn<(...args: unknown[]) => Promise>(); const mockDeriveKey = jest.fn<(...args: unknown[]) => Promise>(); const mockEncrypt = jest.fn<(...args: unknown[]) => Promise>(); const mockDecrypt = jest.fn<(...args: unknown[]) => Promise>(); const mockGetRandomValues = jest.fn<(...args: unknown[]) => Uint8Array>(); const mockKeyMaterial = { type: 'secret' } as unknown as CryptoKey; const mockAesKey = { type: 'secret' } as unknown as CryptoKey; const TEST_SECRET = 'test-secret-key-12345'; const TEST_PLAINTEXT = 'Hello, Novalon!'; const TEST_CIPHERTEXT = new Uint8Array([0x41, 0x42, 0x43, 0x44]); // 'ABCD' const TEST_PLAINTEXT_BYTES = new TextEncoder().encode(TEST_PLAINTEXT); // 原始 crypto 引用,用于 afterEach 恢复 const originalCrypto = global.crypto; // ─── 测试变量 ──────────────────────────────────────────────────────────────── let encrypt: (plaintext: string) => Promise; let decrypt: (encryptedBase64: string) => Promise; beforeEach(async () => { jest.clearAllMocks(); // 设置 global.crypto mock Object.defineProperty(global, 'crypto', { value: { subtle: { importKey: mockImportKey, deriveKey: mockDeriveKey, encrypt: mockEncrypt, decrypt: mockDecrypt, }, getRandomValues: mockGetRandomValues, }, writable: true, configurable: true, }); // 默认 mock 实现 mockImportKey.mockResolvedValue(mockKeyMaterial); mockDeriveKey.mockResolvedValue(mockAesKey); mockGetRandomValues.mockImplementation((arr: unknown) => { const u8arr = arr as Uint8Array; // 固定填充 0xAB,保证输出可预测 for (let i = 0; i < u8arr.length; i++) { u8arr[i] = 0xAB; } return u8arr; }); mockEncrypt.mockResolvedValue(TEST_CIPHERTEXT.buffer as ArrayBuffer); mockDecrypt.mockResolvedValue(TEST_PLAINTEXT_BYTES.buffer as ArrayBuffer); process.env.NEXT_PUBLIC_ENCRYPTION_SECRET = TEST_SECRET; // 重置模块注册表 + 重新导入,确保 cachedKey 为 null jest.resetModules(); const mod = await import('./crypto'); encrypt = mod.encrypt; decrypt = mod.decrypt; }); afterEach(() => { delete process.env.NEXT_PUBLIC_ENCRYPTION_SECRET; global.crypto = originalCrypto; }); // ─── 辅助函数 ──────────────────────────────────────────────────────────────── /** 构造一个可以被 decrypt 正确解码的 base64 输入 */ function buildEncryptedBase64(iv: Uint8Array, ciphertext: Uint8Array): string { const combined = new Uint8Array(iv.length + ciphertext.length); combined.set(iv, 0); combined.set(ciphertext, iv.length); return btoa(String.fromCodePoint(...combined)); } // ─── 测试套件 ──────────────────────────────────────────────────────────────── describe('crypto', () => { describe('encrypt', () => { it('should encrypt plaintext and return base64-encoded string', async () => { const result = await encrypt(TEST_PLAINTEXT); // 输出是 base64 字符串 expect(typeof result).toBe('string'); expect(result.length).toBeGreaterThan(0); // 解码后验证结构:12 字节 IV + 4 字节密文 const decoded = Uint8Array.from(atob(result), (c) => c.codePointAt(0)!); expect(decoded.length).toBe(12 + TEST_CIPHERTEXT.length); expect(decoded.slice(0, 12)).toEqual(new Uint8Array(12).fill(0xAB)); expect(decoded.slice(12)).toEqual(TEST_CIPHERTEXT); // crypto.subtle.importKey 被正确调用 expect(mockImportKey).toHaveBeenCalledWith( 'raw', expect.any(Object), 'PBKDF2', false, ['deriveBits', 'deriveKey'], ); // crypto.subtle.deriveKey 被正确调用 expect(mockDeriveKey).toHaveBeenCalledWith( { name: 'PBKDF2', salt: expect.any(Object), iterations: 100_000, hash: 'SHA-256' }, mockKeyMaterial, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'], ); // crypto.subtle.encrypt 被正确调用 expect(mockEncrypt).toHaveBeenCalledWith( { name: 'AES-GCM', iv: new Uint8Array(12).fill(0xAB), tagLength: 128 }, mockAesKey, expect.any(Object), ); // crypto.getRandomValues 被调用 expect(mockGetRandomValues).toHaveBeenCalledTimes(1); }); it('should encrypt empty string', async () => { const result = await encrypt(''); expect(typeof result).toBe('string'); expect(result.length).toBeGreaterThan(0); // 即使明文为空,加密仍被调用 expect(mockEncrypt).toHaveBeenCalledTimes(1); }); it('should propagate crypto.subtle.encrypt errors', async () => { mockEncrypt.mockRejectedValue(new Error('Encryption failed')); await expect(encrypt(TEST_PLAINTEXT)).rejects.toThrow('Encryption failed'); }); it('should propagate crypto.subtle.importKey errors', async () => { mockImportKey.mockRejectedValue(new Error('Import key failed')); await expect(encrypt(TEST_PLAINTEXT)).rejects.toThrow('Import key failed'); }); it('should propagate crypto.subtle.deriveKey errors', async () => { mockDeriveKey.mockRejectedValue(new Error('Derive key failed')); await expect(encrypt(TEST_PLAINTEXT)).rejects.toThrow('Derive key failed'); }); }); describe('decrypt', () => { const validBase64Input = buildEncryptedBase64( new Uint8Array(12).fill(0xAB), TEST_CIPHERTEXT, ); it('should decrypt base64-encoded data and return plaintext', async () => { const result = await decrypt(validBase64Input); expect(result).toBe(TEST_PLAINTEXT); // crypto.subtle.decrypt 被正确调用 expect(mockDecrypt).toHaveBeenCalledWith( { name: 'AES-GCM', iv: new Uint8Array(12).fill(0xAB), tagLength: 128 }, mockAesKey, TEST_CIPHERTEXT, ); }); it('should propagate crypto.subtle.decrypt errors', async () => { mockDecrypt.mockRejectedValue(new Error('Decryption failed')); await expect(decrypt(validBase64Input)).rejects.toThrow('Decryption failed'); }); it('should throw on invalid base64 input', async () => { await expect(decrypt('not-valid-base64!!!')).rejects.toThrow(); }); }); describe('error handling', () => { it('should throw when NEXT_PUBLIC_ENCRYPTION_SECRET is missing', async () => { // 清除密钥 → getKey() 内部 getSecret() 将抛出异常 delete process.env.NEXT_PUBLIC_ENCRYPTION_SECRET; // 需要重置模块以清除 cachedKey 缓存 jest.resetModules(); const mod = await import('./crypto'); await expect(mod.encrypt(TEST_PLAINTEXT)).rejects.toThrow( 'NEXT_PUBLIC_ENCRYPTION_SECRET 未配置', ); }); }); describe('key caching', () => { it('should cache derived key across multiple calls', async () => { await encrypt('first call'); await encrypt('second call'); // importKey 和 deriveKey 应只被调用一次 expect(mockImportKey).toHaveBeenCalledTimes(1); expect(mockDeriveKey).toHaveBeenCalledTimes(1); }); }); });