#!/bin/bash

# Security Audit Script for Global Gala API
# Tests common security vulnerabilities

API="http://162.214.79.3"
HOST="dev.globalgalashow.com"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo "======================================"
echo "Global Gala API Security Audit"
echo "Testing: $HOST"
echo "======================================"

PASS_COUNT=0
FAIL_COUNT=0
WARN_COUNT=0

# Helper functions
pass() {
    echo -e "${GREEN}✓ PASS${NC} - $1"
    ((PASS_COUNT++))
}

fail() {
    echo -e "${RED}✗ FAIL${NC} - $1"
    ((FAIL_COUNT++))
}

warn() {
    echo -e "${YELLOW}⚠ WARN${NC} - $1"
    ((WARN_COUNT++))
}

# Test 1: Unauthenticated access to protected endpoints
echo -e "\n[TEST 1] Authentication & Authorization"
echo "----------------------------------------"

RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/admin/orders" -w "%{http_code}")
if echo "$RESPONSE" | grep -qE "401|Unauthenticated"; then
    pass "Admin orders endpoint requires authentication"
else
    fail "Admin orders endpoint accessible without auth!"
fi

RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/admin/me" -w "%{http_code}")
if echo "$RESPONSE" | grep -qE "401|Unauthenticated"; then
    pass "Admin 'me' endpoint requires authentication"
else
    fail "Admin 'me' endpoint accessible without auth!"
fi

RESPONSE=$(curl -s -H "Host: $HOST" -H "Authorization: Bearer fake-token-123" "$API/api/admin/me")
if echo "$RESPONSE" | grep -qE "401|Unauthorized|invalid|token"; then
    pass "Invalid JWT tokens are rejected"
else
    fail "System accepts invalid JWT tokens!"
fi

# Test 2: Rate Limiting
echo -e "\n[TEST 2] Rate Limiting"
echo "----------------------------------------"

RATE_LIMITED=false
for i in {1..8}; do
    RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
        -d '{"email":"test@test.com","password":"wrong"}' \
        "$API/api/admin/login" -w "\n%{http_code}")

    if echo "$RESPONSE" | grep -q "429"; then
        pass "Rate limiting triggered after $i attempts"
        RATE_LIMITED=true
        break
    fi
    sleep 0.3
done

if [ "$RATE_LIMITED" = false ]; then
    warn "Rate limiting not triggered after 8 login attempts (may be whitelisted IP)"
fi

# Test 3: Security Headers
echo -e "\n[TEST 3] Security Headers"
echo "----------------------------------------"

HEADERS=$(curl -sI -H "Host: $HOST" "$API/api/health")

if echo "$HEADERS" | grep -qi "X-Frame-Options"; then
    pass "X-Frame-Options header present"
else
    fail "X-Frame-Options header missing (clickjacking risk)"
fi

if echo "$HEADERS" | grep -qi "X-Content-Type-Options"; then
    pass "X-Content-Type-Options header present"
else
    fail "X-Content-Type-Options header missing (MIME sniffing risk)"
fi

if echo "$HEADERS" | grep -qi "X-XSS-Protection"; then
    pass "X-XSS-Protection header present"
else
    warn "X-XSS-Protection header missing"
fi

if echo "$HEADERS" | grep -qi "Strict-Transport-Security"; then
    pass "Strict-Transport-Security header present"
else
    warn "HSTS header missing (should be added in production)"
fi

# Test 4: Sensitive File Exposure
echo -e "\n[TEST 4] Sensitive File Protection"
echo "----------------------------------------"

STATUS=$(curl -s -w "%{http_code}" -H "Host: $HOST" "$API/.env" -o /dev/null)
if [ "$STATUS" = "404" ] || [ "$STATUS" = "403" ]; then
    pass ".env file is not accessible"
else
    fail ".env file is accessible! Status: $STATUS"
fi

STATUS=$(curl -s -w "%{http_code}" -H "Host: $HOST" "$API/../.env" -o /dev/null)
if [ "$STATUS" = "404" ] || [ "$STATUS" = "403" ]; then
    pass "Path traversal to .env blocked"
else
    fail "Path traversal possible! Status: $STATUS"
fi

STATUS=$(curl -s -w "%{http_code}" -H "Host: $HOST" "$API/composer.json" -o /dev/null)
if [ "$STATUS" = "404" ] || [ "$STATUS" = "403" ]; then
    pass "composer.json not accessible"
else
    warn "composer.json is accessible (exposes dependencies)"
fi

# Test 5: Debug Mode & Error Disclosure
echo -e "\n[TEST 5] Debug Mode & Information Disclosure"
echo "----------------------------------------"

RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/nonexistent-endpoint-12345")
if echo "$RESPONSE" | grep -qiE "whoops|laravel|debug|stack trace|vendor/laravel"; then
    fail "Debug mode appears to be enabled! Stack traces visible"
else
    pass "Debug mode disabled - no stack traces exposed"
fi

RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/admin/orders/99999999")
if echo "$RESPONSE" | grep -qiE "sql|mysql|select \*|from |database"; then
    fail "SQL queries exposed in error messages"
else
    pass "SQL queries not exposed in error messages"
fi

# Test 6: SQL Injection Tests
echo -e "\n[TEST 6] SQL Injection Protection"
echo "----------------------------------------"

RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/events?id=1' OR '1'='1")
if echo "$RESPONSE" | grep -qiE "sql|mysql|syntax error|database"; then
    fail "Possible SQL injection vulnerability detected"
else
    pass "SQL injection attempt handled safely"
fi

RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/seats/search?query='; DROP TABLE users;--")
if echo "$RESPONSE" | grep -qiE "sql|mysql|drop table|database"; then
    fail "SQL injection in search parameter possible"
else
    pass "SQL injection in search blocked"
fi

# Test 7: CORS Configuration
echo -e "\n[TEST 7] CORS Configuration"
echo "----------------------------------------"

RESPONSE=$(curl -sI -H "Host: $HOST" -H "Origin: https://malicious-site.com" \
    -H "Access-Control-Request-Method: POST" \
    -X OPTIONS "$API/api/admin/login")

if echo "$RESPONSE" | grep -qi "Access-Control-Allow-Origin: \*"; then
    fail "CORS allows all origins (*) - security risk!"
elif echo "$RESPONSE" | grep -qi "Access-Control-Allow-Origin"; then
    ORIGIN=$(echo "$RESPONSE" | grep -i "Access-Control-Allow-Origin" | head -1)
    pass "CORS configured with specific origin: $ORIGIN"
else
    pass "CORS not allowing malicious origins"
fi

# Test 8: User Enumeration
echo -e "\n[TEST 8] User Enumeration"
echo "----------------------------------------"

RESPONSE1=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":"nonexistent99999@test.com","password":"test"}' \
    "$API/api/admin/login")

RESPONSE2=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":"admin@test.com","password":"wrongpassword"}' \
    "$API/api/admin/login")

# Check if responses are significantly different
if [ "$RESPONSE1" != "$RESPONSE2" ]; then
    if echo "$RESPONSE1" | grep -qi "user not found" || echo "$RESPONSE2" | grep -qi "invalid password"; then
        warn "Login errors may allow user enumeration (different messages)"
    else
        pass "Login errors use generic messages"
    fi
else
    pass "Consistent error messages prevent user enumeration"
fi

# Test 9: Mass Assignment Protection
echo -e "\n[TEST 9] Mass Assignment Protection"
echo "----------------------------------------"

RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":"test999@test.com","password":"test123","is_admin":true,"role":"super_admin"}' \
    "$API/api/register")

if echo "$RESPONSE" | grep -qE "is_admin.*true|role.*admin"; then
    fail "Mass assignment vulnerability - admin fields accepted!"
else
    pass "Mass assignment protection working (admin fields ignored)"
fi

# Test 10: Public Endpoint Access
echo -e "\n[TEST 10] Public Endpoints"
echo "----------------------------------------"

STATUS=$(curl -s -w "%{http_code}" -H "Host: $HOST" "$API/api/health" -o /dev/null)
if [ "$STATUS" = "200" ]; then
    pass "Health endpoint is public and accessible"
else
    warn "Health endpoint returned status: $STATUS"
fi

STATUS=$(curl -s -w "%{http_code}" -H "Host: $HOST" "$API/api/events" -o /dev/null)
if [ "$STATUS" = "200" ]; then
    pass "Events endpoint is public and accessible"
else
    warn "Events endpoint returned status: $STATUS (may require auth)"
fi

# Test 11: JWT Token Security
echo -e "\n[TEST 11] JWT Token Security"
echo "----------------------------------------"

# Test with "alg: none" attack
RESPONSE=$(curl -s -H "Host: $HOST" \
    -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJzdWIiOiIxIiwiaWF0IjoxNjE2MjM5MDIyfQ." \
    "$API/api/admin/me")

if echo "$RESPONSE" | grep -qE "401|Unauthorized|invalid|token"; then
    pass "JWT 'alg: none' attack prevented"
else
    fail "System may accept JWT tokens with 'alg: none'!"
fi

# Summary
echo -e "\n======================================"
echo "Security Audit Summary"
echo "======================================"
echo -e "${GREEN}Passed: $PASS_COUNT${NC}"
echo -e "${YELLOW}Warnings: $WARN_COUNT${NC}"
echo -e "${RED}Failed: $FAIL_COUNT${NC}"
echo "======================================"

if [ $FAIL_COUNT -gt 0 ]; then
    echo -e "${RED}⚠️  CRITICAL: $FAIL_COUNT security issues found!${NC}"
    exit 1
elif [ $WARN_COUNT -gt 5 ]; then
    echo -e "${YELLOW}⚠️  Multiple warnings - review recommended${NC}"
    exit 0
else
    echo -e "${GREEN}✓ Security audit passed${NC}"
    exit 0
fi
