/**
 * Injection Vulnerabilities Test Fixtures
 * Comprehensive tests for SQL injection, XSS, command injection, and template injection
 */

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

export const injectionTests: TestGroup = {
  name: 'Injection Vulnerabilities',
  tier: 'A',
  layer: 2,
  description: 'Comprehensive detection of SQL injection, XSS, command injection, and template injection',
  
  truePositives: [
    {
      name: 'SQL Injection - Various Patterns',
      expectFindings: true,
      expectedCategories: ['dangerous_function'],
      description: 'Various SQL injection patterns across different frameworks',
      file: {
        path: 'src/api/sql-injection.ts',
        content: `
// Basic string concatenation
export async function getUserByName(name: string) {
  return db.query("SELECT * FROM users WHERE name = '" + name + "'")
}

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

// ORDER BY injection (often overlooked)
export async function getSortedUsers(sortColumn: string) {
  return db.query(\`SELECT * FROM users ORDER BY \${sortColumn}\`)
}

// LIMIT/OFFSET injection
export async function getPaginatedData(limit: string, offset: string) {
  return db.query(\`SELECT * FROM items LIMIT \${limit} OFFSET \${offset}\`)
}

// IN clause injection
export async function getUsersByIds(ids: string) {
  return db.query(\`SELECT * FROM users WHERE id IN (\${ids})\`)
}

// Table name injection
export async function getFromTable(tableName: string, id: string) {
  return db.query(\`SELECT * FROM \${tableName} WHERE id = '\${id}'\`)
}

// Multi-statement injection
export async function updateAndSelect(userId: string, newName: string) {
  const query = \`UPDATE users SET name = '\${newName}' WHERE id = '\${userId}'; SELECT * FROM users\`
  return db.query(query)
}

// Stored procedure injection
export async function callProcedure(procName: string, param: string) {
  return db.query(\`CALL \${procName}('\${param}')\`)
}
`,
        language: 'typescript',
        size: 1200,
      },
    },
    {
      name: 'XSS - Various Patterns',
      expectFindings: true,
      expectedCategories: ['dangerous_function'],
      description: 'Various XSS patterns in different contexts',
      file: {
        path: 'src/components/xss-vulnerable.tsx',
        content: `
import React from 'react'

// Direct innerHTML assignment
export function RenderUserHTML({ html }: { html: string }) {
  const divRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    if (divRef.current) {
      divRef.current.innerHTML = html // XSS!
    }
  }, [html])
  return <div ref={divRef} />
}

// dangerouslySetInnerHTML without sanitization
export function UserBio({ bioHtml }: { bioHtml: string }) {
  return <div dangerouslySetInnerHTML={{ __html: bioHtml }} />
}

// document.write
export function InjectScript(content: string) {
  document.write(content) // XSS!
}

// createElement with user content
export function CreateElement(tagName: string, content: string) {
  const el = document.createElement(tagName)
  el.innerHTML = content // XSS!
  document.body.appendChild(el)
}

// URL-based XSS
export function RedirectWithMessage(url: string) {
  window.location.href = \`javascript:alert('\${url}')\` // XSS via javascript: URL
}

// Event handler injection
export function AddHandler(element: HTMLElement, handler: string) {
  element.setAttribute('onclick', handler) // XSS!
}

// SVG injection
export function RenderSVG({ svgContent }: { svgContent: string }) {
  return <div dangerouslySetInnerHTML={{ __html: svgContent }} />
}
`,
        language: 'typescript',
        size: 1100,
      },
    },
    {
      name: 'Command Injection - Various Patterns',
      expectFindings: true,
      expectedCategories: ['dangerous_function'],
      description: 'Command injection patterns in Node.js and shell contexts',
      file: {
        path: 'src/utils/command-injection.ts',
        content: `
import { exec, execSync, spawn } from 'child_process'

// Basic exec with user input
export function runUserCommand(cmd: string) {
  exec(cmd, (err, stdout) => console.log(stdout))
}

// exec with template literal
export function processFile(filename: string) {
  exec(\`cat \${filename}\`)
}

// execSync with concatenation
export function getFileInfo(path: string) {
  return execSync('ls -la ' + path)
}

// Shell option enabled
export function runWithShell(command: string) {
  spawn(command, { shell: true })
}

// Backtick command substitution vulnerability
export function generateReport(date: string) {
  exec(\`echo "Report for \${date}" > /tmp/report.txt\`)
}

// Chained commands
export function chainedCommands(input: string) {
  exec(\`echo \${input} && whoami\`) // User can inject "; rm -rf /"
}

// Environment variable injection
export function setEnvAndRun(value: string) {
  exec(\`export VAR="\${value}" && ./script.sh\`)
}
`,
        language: 'typescript',
        size: 900,
      },
    },
  ],
  
  falseNegatives: [
    {
      name: 'Injection - Safe Patterns',
      expectFindings: false,
      description: 'Safe patterns that prevent injection attacks',
      allowedInfoFindings: [
        {
          category: 'dangerous_function',
          maxCount: 5,
          reason: 'SQL with allowlist validation and static commands generate info-level findings',
        },
      ],
      file: {
        path: 'src/api/safe-injection.ts',
        content: `
import { execFile } from 'child_process'
import DOMPurify from 'dompurify'

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

// Query builder with escaping - SAFE
export async function searchProducts(term: string) {
  return knex('products').where('name', 'ilike', \`%\${term}%\`)
}

// ORM - SAFE
export async function findUser(email: string) {
  return prisma.user.findUnique({ where: { email } })
}

// DOMPurify sanitized HTML - SAFE
export function SafeHTML({ html }: { html: string }) {
  const clean = DOMPurify.sanitize(html)
  return <div dangerouslySetInnerHTML={{ __html: clean }} />
}

// execFile with array args - SAFE
export function safeExec(filename: string) {
  execFile('ls', ['-la', filename])
}

// Allowlist validation - SAFE
export async function getSortedUsers(column: string) {
  const allowed = ['name', 'email', 'created_at']
  if (!allowed.includes(column)) {
    column = 'created_at'
  }
  return db.query(\`SELECT * FROM users ORDER BY \${column}\`)
}

// Static command - SAFE
export function getVersion() {
  return execSync('node --version')
}
`,
        language: 'typescript',
        size: 1000,
      },
    },
  ],
}
