// Preservation Tests — AES-GCM Credential Round-Trip // Task 2: 確認基線行為(修復前執行,預期通過) // // **Validates: Requirements 3.9** import { SELF } from 'cloudflare:test'; import { describe, it, expect } from 'vitest'; import * as fc from 'fast-check'; // ───────────────────────────────────────────────────────────────────────────── // Property: Credential round-trip // // For all non-zero credential name/secret pairs, // POST /credentials → GET /credentials/:name/secret returns the same secret. // This validates AES-GCM encrypt → decrypt round-trip correctness. // // **Validates: Requirements 3.9** // ───────────────────────────────────────────────────────────────────────────── describe('Preservation: AES-GCM credential round-trip', () => { it('property: POST /credentials then GET /credentials/:name/secret returns original secret', async () => { // Generate non-empty name and secret pairs const nameArb = fc.string({ minLength: 1, maxLength: 30 }).filter(s => s.trim().length > 0); const secretArb = fc.string({ minLength: 1, maxLength: 100 }).filter(s => s.length > 0); await fc.assert( fc.asyncProperty(nameArb, secretArb, async (name, secret) => { // Use a unique suffix to avoid collisions between runs const uniqueName = `${name}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`; // POST /credentials — store encrypted credential const createRes = await SELF.fetch('http://localhost/credentials', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: uniqueName, secret, type: 'api_key' }), }); expect(createRes.status).toBe(201); const created = await createRes.json() as Record; expect(created.success).toBe(true); const credId = (created.data as Record).id as string; // GET /credentials/:name/secret — retrieve and decrypt const getRes = await SELF.fetch(`http://localhost/credentials/${credId}/secret`); expect(getRes.status).toBe(200); const retrieved = await getRes.json() as Record; expect(retrieved.success).toBe(true); // The decrypted secret must equal the original const retrievedSecret = (retrieved.data as Record).secret as string; expect(retrievedSecret).toBe(secret); }), { numRuns: 5 } ); }); it('example: specific name/secret round-trip preserves secret', async () => { const name = 'preservation-test-key'; const secret = 'my-super-secret-api-key-12345'; const createRes = await SELF.fetch('http://localhost/credentials', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, secret, type: 'bearer_token' }), }); expect(createRes.status).toBe(201); const created = await createRes.json() as Record; const credId = (created.data as Record).id as string; const getRes = await SELF.fetch(`http://localhost/credentials/${credId}/secret`); expect(getRes.status).toBe(200); const retrieved = await getRes.json() as Record; expect((retrieved.data as Record).secret).toBe(secret); }); });