#!/bin/bash

# Container Image Scanner - Security Testing Script
# This script performs comprehensive security testing

set -euo pipefail

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Test results
PASSED=0
FAILED=0
WARNINGS=0

echo -e "${BLUE}🔒 Container Image Scanner - Security Testing${NC}"
echo "=================================================="

# Function to print test results
print_result() {
    local test_name="$1"
    local result="$2"
    local message="$3"
    
    if [ "$result" = "PASS" ]; then
        echo -e "✅ ${GREEN}PASS${NC}: $test_name - $message"
        ((PASSED++))
    elif [ "$result" = "FAIL" ]; then
        echo -e "❌ ${RED}FAIL${NC}: $test_name - $message"
        ((FAILED++))
    else
        echo -e "⚠️  ${YELLOW}WARN${NC}: $test_name - $message"
        ((WARNINGS++))
    fi
}

# Test 1: Check for hardcoded secrets
echo -e "\n${BLUE}1. Checking for hardcoded secrets...${NC}"
if grep -r -i "password\|secret\|key\|token" src/ --exclude-dir=node_modules --exclude="*.md" | grep -v "// " | grep -v "process.env" > /dev/null 2>&1; then
    print_result "Hardcoded Secrets" "FAIL" "Found potential hardcoded secrets in source code"
    grep -r -i "password\|secret\|key\|token" src/ --exclude-dir=node_modules --exclude="*.md" | grep -v "// " | grep -v "process.env" || true
else
    print_result "Hardcoded Secrets" "PASS" "No hardcoded secrets found"
fi

# Test 2: Check .gitignore for sensitive files
echo -e "\n${BLUE}2. Checking .gitignore configuration...${NC}"
if grep -q "\.env" .gitignore && grep -q "aws-credentials" .gitignore && grep -q "\.aws/" .gitignore; then
    print_result "Gitignore Configuration" "PASS" "Sensitive files properly excluded"
else
    print_result "Gitignore Configuration" "FAIL" "Missing sensitive file exclusions in .gitignore"
fi

# Test 3: Check npm audit
echo -e "\n${BLUE}3. Running npm security audit...${NC}"
if npm audit --audit-level moderate > /dev/null 2>&1; then
    print_result "NPM Security Audit" "PASS" "No moderate or high severity vulnerabilities found"
else
    print_result "NPM Security Audit" "FAIL" "Security vulnerabilities found in dependencies"
    npm audit --audit-level moderate || true
fi

# Test 4: Check for proper error handling
echo -e "\n${BLUE}4. Checking error handling...${NC}"
if grep -r "console.error" src/ | grep -v "error.message" | grep -v "error.stack" > /dev/null 2>&1; then
    print_result "Error Handling" "WARN" "Some error logs may expose sensitive information"
else
    print_result "Error Handling" "PASS" "Error handling appears secure"
fi

# Test 5: Check TypeScript configuration
echo -e "\n${BLUE}5. Checking TypeScript security settings...${NC}"
if [ -f "tsconfig.json" ]; then
    if grep -q '"strict": true' tsconfig.json; then
        print_result "TypeScript Configuration" "PASS" "Strict mode enabled"
    else
        print_result "TypeScript Configuration" "WARN" "TypeScript strict mode not enabled"
    fi
else
    print_result "TypeScript Configuration" "FAIL" "No TypeScript configuration found"
fi

# Test 6: Check for console.log in production code
echo -e "\n${BLUE}6. Checking for debug statements...${NC}"
if grep -r "console.log" src/ --exclude="*.test.ts" --exclude="*.spec.ts" > /dev/null 2>&1; then
    print_result "Debug Statements" "WARN" "Found console.log statements in production code"
    grep -r "console.log" src/ --exclude="*.test.ts" --exclude="*.spec.ts" || true
else
    print_result "Debug Statements" "PASS" "No debug statements found in production code"
fi

# Test 7: Check file permissions
echo -e "\n${BLUE}7. Checking file permissions...${NC}"
if find . -name "*.sh" -not -perm 755 | grep -q .; then
    print_result "File Permissions" "WARN" "Some shell scripts may have incorrect permissions"
    find . -name "*.sh" -not -perm 755 || true
else
    print_result "File Permissions" "PASS" "File permissions appear correct"
fi

# Test 8: Check for AWS credential usage
echo -e "\n${BLUE}8. Checking AWS credential handling...${NC}"
if grep -r "AWS_ACCESS_KEY\|AWS_SECRET" src/ > /dev/null 2>&1; then
    print_result "AWS Credentials" "FAIL" "Direct AWS credential usage found"
    grep -r "AWS_ACCESS_KEY\|AWS_SECRET" src/ || true
else
    print_result "AWS Credentials" "PASS" "No direct AWS credential usage found"
fi

# Test 9: Check for SQL injection vulnerabilities
echo -e "\n${BLUE}9. Checking for SQL injection vulnerabilities...${NC}"
if grep -r "SELECT\|INSERT\|UPDATE\|DELETE" src/ | grep -v "// " | grep -v "/\*" > /dev/null 2>&1; then
    print_result "SQL Injection" "WARN" "Found SQL statements - review for injection vulnerabilities"
else
    print_result "SQL Injection" "PASS" "No SQL statements found"
fi

# Test 10: Check for proper input validation
echo -e "\n${BLUE}10. Checking input validation...${NC}"
if grep -r "req.body\|req.params\|req.query" src/ | grep -v "validation\|validate\|sanitize" > /dev/null 2>&1; then
    print_result "Input Validation" "WARN" "Found request parameter usage - ensure proper validation"
else
    print_result "Input Validation" "PASS" "Input validation appears to be implemented"
fi

# Test 11: Check for HTTPS enforcement
echo -e "\n${BLUE}11. Checking HTTPS enforcement...${NC}"
if grep -r "https://" src/ > /dev/null 2>&1; then
    print_result "HTTPS Enforcement" "PASS" "HTTPS usage found in code"
else
    print_result "HTTPS Enforcement" "WARN" "No explicit HTTPS enforcement found"
fi

# Test 12: Check for rate limiting
echo -e "\n${BLUE}12. Checking rate limiting implementation...${NC}"
if grep -r "rate.*limit\|rateLimit" src/ > /dev/null 2>&1; then
    print_result "Rate Limiting" "PASS" "Rate limiting implementation found"
else
    print_result "Rate Limiting" "WARN" "No rate limiting implementation found"
fi

# Test 13: Check for security headers
echo -e "\n${BLUE}13. Checking security headers...${NC}"
if grep -r "helmet\|security.*header" src/ > /dev/null 2>&1; then
    print_result "Security Headers" "PASS" "Security headers implementation found"
else
    print_result "Security Headers" "WARN" "No security headers implementation found"
fi

# Test 14: Check for proper session management
echo -e "\n${BLUE}14. Checking session management...${NC}"
if grep -r "session\|cookie" src/ | grep -v "// " > /dev/null 2>&1; then
    if grep -r "secure.*cookie\|httpOnly" src/ > /dev/null 2>&1; then
        print_result "Session Management" "PASS" "Secure session management found"
    else
        print_result "Session Management" "WARN" "Session management found but may not be secure"
    fi
else
    print_result "Session Management" "PASS" "No session management (stateless application)"
fi

# Test 15: Check for proper CORS configuration
echo -e "\n${BLUE}15. Checking CORS configuration...${NC}"
if grep -r "cors" src/ > /dev/null 2>&1; then
    if grep -r "origin.*localhost\|origin.*127.0.0.1" src/ > /dev/null 2>&1; then
        print_result "CORS Configuration" "PASS" "Restrictive CORS configuration found"
    else
        print_result "CORS Configuration" "WARN" "CORS found but may be too permissive"
    fi
else
    print_result "CORS Configuration" "WARN" "No CORS configuration found"
fi

# Test 16: Check for environment-specific configurations
echo -e "\n${BLUE}16. Checking environment configurations...${NC}"
if grep -r "NODE_ENV" src/ > /dev/null 2>&1; then
    print_result "Environment Configuration" "PASS" "Environment-specific configuration found"
else
    print_result "Environment Configuration" "WARN" "No environment-specific configuration found"
fi

# Test 17: Check for proper logging configuration
echo -e "\n${BLUE}17. Checking logging configuration...${NC}"
if grep -r "winston\|bunyan\|pino" src/ > /dev/null 2>&1; then
    print_result "Logging Configuration" "PASS" "Structured logging library found"
else
    if grep -r "console.error\|console.warn" src/ > /dev/null 2>&1; then
        print_result "Logging Configuration" "WARN" "Basic logging found - consider structured logging"
    else
        print_result "Logging Configuration" "FAIL" "No logging configuration found"
    fi
fi

# Test 18: Check for dependency pinning
echo -e "\n${BLUE}18. Checking dependency pinning...${NC}"
if [ -f "package-lock.json" ]; then
    print_result "Dependency Pinning" "PASS" "package-lock.json found - dependencies are pinned"
else
    print_result "Dependency Pinning" "WARN" "No package-lock.json found - dependencies not pinned"
fi

# Test 19: Check for test coverage
echo -e "\n${BLUE}19. Checking test coverage...${NC}"
if [ -d "tests" ] || [ -d "test" ] || grep -q "jest\|mocha\|jasmine" package.json; then
    print_result "Test Coverage" "PASS" "Testing framework found"
else
    print_result "Test Coverage" "WARN" "No testing framework found"
fi

# Test 20: Check for security documentation
echo -e "\n${BLUE}20. Checking security documentation...${NC}"
if [ -f "SECURITY.md" ] || [ -f "SECURITY-REVIEW.md" ] || grep -i security README.md > /dev/null 2>&1; then
    print_result "Security Documentation" "PASS" "Security documentation found"
else
    print_result "Security Documentation" "WARN" "No security documentation found"
fi

# Summary
echo -e "\n${BLUE}Security Test Summary${NC}"
echo "===================="
echo -e "✅ ${GREEN}Passed: $PASSED${NC}"
echo -e "⚠️  ${YELLOW}Warnings: $WARNINGS${NC}"
echo -e "❌ ${RED}Failed: $FAILED${NC}"

# Overall result
if [ $FAILED -eq 0 ]; then
    if [ $WARNINGS -eq 0 ]; then
        echo -e "\n🎉 ${GREEN}All security tests passed!${NC}"
        exit 0
    else
        echo -e "\n⚠️  ${YELLOW}Security tests passed with warnings. Review warnings above.${NC}"
        exit 0
    fi
else
    echo -e "\n💥 ${RED}Security tests failed! Address the failures above before deployment.${NC}"
    exit 1
fi
