/**
 * BYOK (Bring Your Own Key) Test Fixtures
 * Tests for detecting insecure handling of user-provided API keys
 */

import type { TestGroup } from '../../types'

export const byokTests: TestGroup = {
  name: 'BYOK Patterns',
  tier: 'A',
  layer: 2,
  description: 'Detection of insecure BYOK (Bring Your Own Key) patterns',
  
  truePositives: [
    {
      name: 'BYOK - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_pattern'],
      description: 'Insecure BYOK patterns that MUST be detected',
      file: {
        path: 'src/api/ai/byok-storage.ts',
        content: `
import { db } from '@/lib/db'

// BYOK key stored in database (Medium - should encrypt)
export async function saveUserApiKey(userId: string, apiKey: string) {
  await db.user.update({
    where: { id: userId },
    data: { openaiApiKey: apiKey }  // Stored without encryption!
  })
}

// BYOK key logged (Medium - never log secrets)
export async function useUserKey(userId: string) {
  const user = await db.user.findUnique({ where: { id: userId } })
  console.log('Using API key:', user.openaiApiKey)  // Logged!
  return callOpenAI(user.openaiApiKey)
}

// BYOK key stored in plain text file
export function saveKeyToFile(apiKey: string) {
  fs.writeFileSync('/data/api-keys.txt', apiKey)
}

// Cross-tenant key access (High - data isolation risk)
export async function getAnyUserKey(targetUserId: string) {
  // No check that current user owns this key!
  const user = await db.user.findUnique({ where: { id: targetUserId } })
  return user.apiKey
}

// BYOK on unauthenticated endpoint (Medium - abuse risk)
export async function POST(request: Request) {
  // No auth check!
  const { apiKey, prompt } = await request.json()
  return callOpenAI(apiKey, prompt)
}
`,
        language: 'typescript',
        size: 1200,
      },
    },
  ],
  
  falseNegatives: [
    {
      name: 'BYOK - False Negatives',
      expectFindings: false,
      description: 'Secure BYOK patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'ai_endpoint_unprotected',
          maxCount: 1,
          reason: 'BYOK with auth but missing rate limiting is info-level (user pays for own usage)',
        },
      ],
      file: {
        path: 'src/api/ai/byok-transient.ts',
        content: `
import { auth } from '@/lib/auth'
import OpenAI from 'openai'

// Transient BYOK usage (authenticated) - SAFE (info at most)
export async function POST(request: Request) {
  // Auth check
  const session = await auth()
  if (!session?.user) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  // Key from request body, used transiently
  const { apiKey, prompt } = await request.json()

  // Key only exists in memory for this request
  const openai = new OpenAI({ apiKey })
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }]
  })

  // Key is NOT stored or logged - this is the IDEAL BYOK pattern
  return Response.json({ result: response.choices[0].message.content })
}

// User-scoped encrypted key storage - SAFE
export async function saveEncryptedKey(userId: string, apiKey: string) {
  const encryptedKey = await encrypt(apiKey, process.env.ENCRYPTION_KEY!)
  await db.user.update({
    where: { id: userId },
    data: { encryptedApiKey: encryptedKey }
  })
}
`,
        language: 'typescript',
        size: 1100,
      },
    },
  ],
}
