/**
 * Dangerous Functions Test Fixtures
 * Tests for detecting eval, exec, SQL injection, XSS, and other dangerous function usage
 */

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

export const dangerousFunctionsTests: TestGroup = {
  name: 'Dangerous Functions',
  tier: 'A',
  layer: 2,
  description: 'Detection of dangerous function calls that can lead to code injection, SQL injection, and XSS',
  
  truePositives: [
    {
      name: 'Dangerous Functions - True Positives',
      expectFindings: true,
      expectedCategories: ['dangerous_function'],
      description: 'Dangerous function patterns that MUST be detected',
      file: {
        path: 'src/api/execute.ts',
        content: `
import { exec, execSync, spawn } from 'child_process'

// eval() with user input (Critical)
export function executeUserCode(userCode: string) {
  return eval(userCode)
}

// Function constructor (Critical)
export function createDynamicFunction(code: string) {
  return new Function('input', code)
}

// exec() with user input (Critical - Command Injection)
export function runCommand(userCommand: string) {
  exec(userCommand, (error, stdout) => {
    console.log(stdout)
  })
}

// execSync with template literal (Critical)
export function runUserScript(filename: string) {
  return execSync(\`node \${filename}\`)
}

// spawn with user-controlled args (High)
export function spawnProcess(program: string, args: string[]) {
  return spawn(program, args)
}

// SQL injection via string concatenation (Critical)
export async function getUser(userId: string) {
  const query = "SELECT * FROM users WHERE id = '" + userId + "'"
  return db.query(query)
}

// SQL injection via template literal (Critical)
export async function searchUsers(searchTerm: string) {
  return db.query(\`SELECT * FROM users WHERE name LIKE '%\${searchTerm}%'\`)
}

// innerHTML with user data (High - XSS)
export function renderUserContent(userHtml: string) {
  document.getElementById('content').innerHTML = userHtml
}

// dangerouslySetInnerHTML with user data (High - XSS in React)
export function UserContent({ html }: { html: string }) {
  return <div dangerouslySetInnerHTML={{ __html: html }} />
}

// Unvalidated redirect (Medium - Open Redirect)
export function redirect(url: string) {
  window.location.href = url
}

// setTimeout with string (Medium)
export function delayedExec(code: string) {
  setTimeout(code, 1000)
}

// setInterval with string (Medium)
export function repeatedExec(code: string) {
  setInterval(code, 1000)
}
`,
        language: 'typescript',
        size: 1800,
      },
    },
    {
      name: 'Dangerous Functions - SQL Injection Variants',
      expectFindings: true,
      expectedCategories: ['dangerous_function'],
      description: 'Various SQL injection patterns',
      file: {
        path: 'src/api/queries.ts',
        content: `
// String concatenation SQL injection
export async function getUserByEmail(email: string) {
  return db.query("SELECT * FROM users WHERE email = '" + email + "'")
}

// Template literal SQL injection
export async function searchProducts(term: string) {
  return db.query(\`SELECT * FROM products WHERE name LIKE '%\${term}%'\`)
}

// Multi-line SQL with injection
export async function getOrders(userId: string, status: string) {
  const query = \`
    SELECT * FROM orders 
    WHERE user_id = '\${userId}'
    AND status = '\${status}'
  \`
  return db.query(query)
}

// UPDATE statement injection
export async function updateUser(userId: string, name: string) {
  return db.query(\`UPDATE users SET name = '\${name}' WHERE id = '\${userId}'\`)
}

// DELETE statement injection
export async function deleteUser(userId: string) {
  return db.query("DELETE FROM users WHERE id = '" + userId + "'")
}
`,
        language: 'typescript',
        size: 900,
      },
    },
  ],
  
  falseNegatives: [
    {
      name: 'Dangerous Functions - False Negatives',
      expectFindings: false,
      description: 'Safe function patterns that should NOT be flagged',
      allowedInfoFindings: [
        {
          category: 'dangerous_function',
          maxCount: 6,
          reason: 'Static eval, hardcoded exec, and JSON.parse with safe sources generate info-level findings',
        },
      ],
      file: {
        path: 'src/api/safe-execute.ts',
        content: `
import { execSync } from 'child_process'

// Static eval (no user input) - SAFE
const config = eval('({ mode: "production" })')

// exec with hardcoded command - SAFE
function checkVersion() {
  return execSync('node --version').toString()
}

// Parameterized SQL queries - SAFE
async function getUser(userId: string) {
  return db.query('SELECT * FROM users WHERE id = $1', [userId])
}

// ORM queries - SAFE
async function findUser(userId: string) {
  return prisma.user.findUnique({ where: { id: userId } })
}

// innerHTML with static content - SAFE
function setStaticContent() {
  document.getElementById('footer').innerHTML = '<p>Copyright 2024</p>'
}

// React JSX (auto-escaped) - SAFE
function UserName({ name }: { name: string }) {
  return <div>{name}</div>
}

// dangerouslySetInnerHTML with sanitized content - SAFE
import DOMPurify from 'dompurify'
function SafeUserContent({ html }: { html: string }) {
  const clean = DOMPurify.sanitize(html)
  return <div dangerouslySetInnerHTML={{ __html: clean }} />
}

// JSON.parse from own database - SAFE
async function getConfig() {
  const row = await db.query('SELECT config FROM settings WHERE id = 1')
  return JSON.parse(row.config)
}

// JSON.parse with try-catch - SAFE
function parseConfig(data: string) {
  try {
    return JSON.parse(data)
  } catch {
    return {}
  }
}
`,
        language: 'typescript',
        size: 1400,
      },
    },
    {
      name: 'Dangerous Functions - Parameterized Queries',
      expectFindings: false,
      description: 'Properly parameterized SQL that should not be flagged',
      file: {
        path: 'src/api/safe-queries.ts',
        content: `
// Parameterized queries - SAFE
async function getUserById(id: string) {
  return db.query('SELECT * FROM users WHERE id = $1', [id])
}

// Named parameters - SAFE
async function findByEmail(email: string) {
  return db.query('SELECT * FROM users WHERE email = :email', { email })
}

// Prisma ORM - SAFE
async function getOrders(userId: string) {
  return prisma.order.findMany({
    where: { userId }
  })
}

// Drizzle ORM - SAFE
async function getProducts(category: string) {
  return db.select().from(products).where(eq(products.category, category))
}

// Knex query builder - SAFE
async function searchUsers(name: string) {
  return knex('users').where('name', 'like', \`%\${name}%\`)
}
`,
        language: 'typescript',
        size: 700,
      },
    },
  ],
}
