/**
 * Data Exposure Test Fixtures
 * Tests for detecting sensitive data exposure in logs, responses, and error handling
 */

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

export const dataExposureTests: TestGroup = {
  name: 'Data Exposure',
  tier: 'B',
  layer: 2,
  description: 'Detection of sensitive data exposure in logs, responses, and error handling',
  
  truePositives: [
    {
      name: 'Data Exposure - True Positives',
      expectFindings: true,
      expectedCategories: ['data_exposure'],
      description: 'Data exposure patterns that MUST be detected',
      file: {
        path: 'src/api/users/route.ts',
        content: `
import { NextResponse } from 'next/server'

// Full error stack in response - HIGH
export async function GET() {
  try {
    const users = await db.user.findMany()
    return NextResponse.json(users)
  } catch (error) {
    return NextResponse.json({
      error: error.stack,  // Stack trace exposed!
      details: error
    }, { status: 500 })
  }
}

// Logging passwords - CRITICAL
export async function POST(request: Request) {
  const { email, password } = await request.json()
  console.log('Login attempt:', email, password)  // Password logged!

  return authenticate(email, password)
}

// Logging API keys - HIGH
export async function useKey(apiKey: string) {
  console.log('Using API key:', apiKey)  // Secret logged!
  return callAPI(apiKey)
}

// Returning full user object with sensitive fields - MEDIUM
export async function getUser(userId: string) {
  const user = await db.user.findUnique({
    where: { id: userId },
    include: {
      apiKeys: true,    // API keys exposed!
      sessions: true,   // Sessions exposed!
    }
  })
  return NextResponse.json(user)  // No field filtering!
}

// Debug endpoint in production - HIGH
export async function DEBUG() {
  return NextResponse.json({
    env: process.env,  // All env vars exposed!
    config: serverConfig,
  })
}

// Verbose internal error details - MEDIUM
export async function handleError(error: any) {
  return NextResponse.json({
    error: error.message,
    internalCode: error.code,
    query: error.query,  // SQL query exposed!
    trace: error.trace,
  })
}
`,
        language: 'typescript',
        size: 1400,
      },
    },
    {
      name: 'Data Exposure - More Response Patterns',
      expectFindings: true,
      expectedCategories: ['data_exposure'],
      description: 'Additional data exposure patterns in responses that MUST be detected',
      file: {
        path: 'src/api/admin/route.ts',
        content: `
import { NextResponse } from 'next/server'

// Full error object in response - HIGH
export async function fetchResource() {
  try {
    const data = await db.resource.findMany()
    return NextResponse.json(data)
  } catch (error) {
    return NextResponse.json(error)  // Full error object exposed!
  }
}

// Error spread in response - HIGH
export async function updateResource() {
  try {
    await db.resource.update({ where: { id: 1 }, data: {} })
  } catch (err) {
    return NextResponse.json({ ...err, timestamp: Date.now() })  // Error spread!
  }
}

// Stack trace in API response - HIGH
export async function processRequest() {
  try {
    await doSomething()
  } catch (error) {
    return NextResponse.json({
      error: error.stack,  // Stack trace exposed!
      details: 'Internal error'
    })
  }
}

// Detailed error info in response - MEDIUM
export async function handleWebhook() {
  try {
    await processWebhook()
  } catch (err) {
    return res.status(500).json({
      details: err.details,  // Internal details exposed
      internal: err.message
    })
  }
}

// User object in response (may contain sensitive fields) - LOW
export async function getProfile(userId: string) {
  const user = await db.user.findUnique({ where: { id: userId } })
  return NextResponse.json({ user })  // May expose sensitive fields
}
`,
        language: 'typescript',
        size: 1100,
      },
    },
  ],
  
  falseNegatives: [
    {
      name: 'Data Exposure - False Negatives',
      expectFindings: false,
      description: 'Safe error handling patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'ai_pattern',
          maxCount: 2,
          reason: 'AI boilerplate error messages are info-level findings',
        },
        {
          category: 'data_exposure',
          maxCount: 2,
          reason: 'Exposing filtered user object is low/info-level, not a security issue',
        },
      ],
      file: {
        path: 'src/api/safe-handlers.ts',
        content: `
import { NextResponse } from 'next/server'

// error.message only - SAFE (recommended pattern)
export async function GET() {
  try {
    const data = await fetchData()
    return NextResponse.json(data)
  } catch (error) {
    console.error('Error:', error)  // Logged for debugging - SAFE
    return NextResponse.json({
      error: error.message  // Only message, not stack - SAFE
    }, { status: 500 })
  }
}

// Static error message - SAFE
export async function POST() {
  try {
    await doSomething()
  } catch {
    return NextResponse.json({
      error: 'An error occurred'  // Generic message - SAFE
    }, { status: 500 })
  }
}

// Logging non-sensitive data - SAFE
export async function logRequest(request: Request) {
  const { method, url } = request
  console.log(\`\${method} \${url}\`)  // No secrets - SAFE
}

// Filtered user response - SAFE
export async function getUser(userId: string) {
  const user = await db.user.findUnique({
    where: { id: userId },
    select: {
      id: true,
      name: true,
      email: true,
      // No sensitive fields selected
    }
  })
  return NextResponse.json(user)
}

// Config check message - SAFE
export async function checkConfig() {
  if (!process.env.OPENAI_API_KEY) {
    return NextResponse.json({
      error: 'OpenAI API key not configured'  // Operational info - SAFE
    }, { status: 500 })
  }
}
`,
        language: 'typescript',
        size: 1200,
      },
    },
  ],
}
