/**
 * AI Agent Tools Test Fixtures
 * Tests for detecting overly permissive AI agent tool definitions
 */

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

export const aiAgentToolsTests: TestGroup = {
  name: 'AI Agent Tools',
  tier: 'A',
  layer: 2,
  description: 'Detection of overly permissive AI agent tool definitions that could be abused',
  
  truePositives: [
    {
      name: 'AI Agent Tools - True Positives',
      expectFindings: true,
      expectedCategories: ['ai_overpermissive_tool'],
      description: 'Overly permissive agent tool patterns that MUST be detected',
      file: {
        path: 'src/agents/overpermissive-tools.ts',
        content: `
import { z } from 'zod'
import { exec } from 'child_process'
import fs from 'fs'

// Over-permissive file system tool - HIGH
const fileSystemTool = {
  name: 'file_system',
  description: 'Read, write, or delete any file on the system',
  schema: z.object({
    operation: z.enum(['read', 'write', 'delete']),
    path: z.string(),  // No path restrictions!
    content: z.string().optional(),
  }),
  execute: async ({ operation, path, content }) => {
    switch (operation) {
      case 'read': return fs.readFileSync(path, 'utf-8')
      case 'write': return fs.writeFileSync(path, content!)
      case 'delete': return fs.unlinkSync(path)
    }
  }
}

// Unrestricted shell execution tool - CRITICAL
const shellTool = {
  name: 'shell',
  description: 'Execute any shell command',
  schema: z.object({
    command: z.string(),  // No command restrictions!
  }),
  execute: async ({ command }) => {
    return new Promise((resolve) => {
      exec(command, (err, stdout, stderr) => {
        resolve({ stdout, stderr })
      })
    })
  }
}

// Network access without restrictions - HIGH
const networkTool = {
  name: 'http_request',
  description: 'Make HTTP requests to any URL',
  schema: z.object({
    url: z.string(),  // No URL restrictions - SSRF risk!
    method: z.string(),
    body: z.any().optional(),
  }),
  execute: async ({ url, method, body }) => {
    return fetch(url, { method, body: JSON.stringify(body) })
  }
}

// Database access without user context - HIGH
const databaseTool = {
  name: 'database',
  description: 'Execute SQL queries',
  schema: z.object({
    query: z.string(),  // Raw SQL - injection risk!
  }),
  execute: async ({ query }) => {
    return db.query(query)  // No user_id scoping!
  }
}

// Tool without proper authorization - MEDIUM
const userDataTool = {
  name: 'get_user_data',
  description: 'Get any user data',
  schema: z.object({
    userId: z.string(),  // Can access ANY user!
  }),
  execute: async ({ userId }) => {
    // No check that agent's user can access this userId
    return db.user.findUnique({ where: { id: userId } })
  }
}
`,
        language: 'typescript',
        size: 1800,
      },
    },
  ],
  
  falseNegatives: [
    {
      name: 'AI Agent Tools - False Negatives',
      expectFindings: false,
      description: 'Properly scoped agent tool patterns that should NOT be flagged',
      file: {
        path: 'src/agents/safe-tools.ts',
        content: `
import { z } from 'zod'
import fs from 'fs'

// File system with path restrictions - SAFE
const safeFileSystemTool = {
  name: 'file_system',
  description: 'Read files from the allowed directory',
  schema: z.object({
    filename: z.string().regex(/^[a-zA-Z0-9_-]+\\.(txt|json|md)$/),
  }),
  execute: async ({ filename }, { userId }) => {
    // Scoped to user's directory
    const safePath = \`/data/users/\${userId}/\${filename}\`
    // No path traversal possible due to regex
    return fs.readFileSync(safePath, 'utf-8')
  }
}

// HTTP with URL allowlist - SAFE
const safeNetworkTool = {
  name: 'http_request',
  description: 'Make HTTP requests to allowed APIs',
  schema: z.object({
    api: z.enum(['weather', 'news', 'stocks']),
    params: z.record(z.string()),
  }),
  execute: async ({ api, params }) => {
    const allowedUrls = {
      weather: 'https://api.weather.gov',
      news: 'https://newsapi.org',
      stocks: 'https://api.stocks.com',
    }
    const url = new URL(allowedUrls[api])
    Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v))
    return fetch(url.toString())
  }
}

// Database with user scoping - SAFE
const safeDatabaseTool = {
  name: 'get_my_data',
  description: 'Get data belonging to the current user',
  schema: z.object({
    dataType: z.enum(['orders', 'settings', 'preferences']),
  }),
  execute: async ({ dataType }, { userId }) => {
    // Always scoped to current user
    return db[dataType].findMany({ where: { userId } })
  }
}
`,
        language: 'typescript',
        size: 1400,
      },
    },
  ],
}
