#!/bin/bash

# Advanced Security Audit - Deep Dive
# Tests advanced authentication, business logic, and data security

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

echo "======================================"
echo "Advanced Security Audit - Deep Dive"
echo "======================================"

PASS=0
FAIL=0
WARN=0

pass() { echo -e "${GREEN}✓ PASS${NC} - $1"; ((PASS++)); }
fail() { echo -e "${RED}✗ FAIL${NC} - $1"; ((FAIL++)); }
warn() { echo -e "${YELLOW}⚠ WARN${NC} - $1"; ((WARN++)); }
info() { echo -e "${BLUE}ℹ INFO${NC} - $1"; }

# ============================================================================
# AUTHENTICATION & SESSION SECURITY
# ============================================================================
echo -e "\n[SECTION 1] Advanced Authentication & Session Security"
echo "=========================================="

# Test: JWT token expiration handling
info "Testing JWT token expiration..."
EXPIRED_TOKEN="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwiaWF0IjoxNjE2MjM5MDIyLCJleHAiOjE2MTYyMzkwMjN9.invalid"
RESPONSE=$(curl -s -H "Host: $HOST" -H "Authorization: Bearer $EXPIRED_TOKEN" "$API/api/admin/me")
if echo "$RESPONSE" | grep -qiE "401|expired|unauthorized|invalid"; then
    pass "Expired JWT tokens are rejected"
else
    fail "System may accept expired JWT tokens"
fi

# Test: Token tampering detection
info "Testing JWT signature validation..."
TAMPERED="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI5OTkiLCJyb2xlIjoic3VwZXJfYWRtaW4ifQ.tampered"
RESPONSE=$(curl -s -H "Host: $HOST" -H "Authorization: Bearer $TAMPERED" "$API/api/admin/me")
if echo "$RESPONSE" | grep -qiE "401|invalid|unauthorized"; then
    pass "Tampered JWT signatures are detected"
else
    fail "JWT signature validation may be weak"
fi

# Test: Role escalation via JWT manipulation
info "Testing role escalation prevention..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":"test@test.com","password":"test","role":"super_admin"}' \
    "$API/api/admin/login")
if echo "$RESPONSE" | grep -qE "role.*super_admin"; then
    fail "Role injection possible in login"
else
    pass "Role injection blocked in authentication"
fi

# Test: Password reset token validation
info "Testing password reset security..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":"admin@test.com","token":"fake-token","password":"hacked123"}' \
    "$API/api/admin/reset-password")
if echo "$RESPONSE" | grep -qiE "200|success|password.*changed"; then
    fail "Password reset accepts invalid tokens!"
else
    pass "Password reset token validation working"
fi

# Test: Concurrent session handling
info "Testing concurrent session security..."
# Check if logout invalidates token
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":"test@test.com","password":"wrong"}' "$API/api/admin/login")
if echo "$RESPONSE" | grep -q "token"; then
    warn "Multiple login sessions may be allowed (check if desired)"
else
    pass "Login security checks in place"
fi

# ============================================================================
# BUSINESS LOGIC VULNERABILITIES
# ============================================================================
echo -e "\n[SECTION 2] Business Logic & Race Conditions"
echo "=========================================="

# Test: Negative price manipulation
info "Testing price manipulation..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"event_id":1,"seat_ids":[1],"seat_pricing":{"1":-100}}' \
    "$API/api/seats/hold")
if echo "$RESPONSE" | grep -qiE "error|invalid|must be positive"; then
    pass "Negative pricing rejected"
else
    warn "Check if negative pricing is validated server-side"
fi

# Test: Race condition in seat booking
info "Testing race condition protection..."
# Attempt simultaneous bookings
for i in {1..3}; do
    curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
        -d '{"event_id":1,"seat_ids":[999],"session_id":"race-test-'$i'"}' \
        "$API/api/seats/hold" &
done
wait
pass "Race condition test completed (manual review recommended)"

# Test: Order quantity manipulation
info "Testing order limits..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"event_id":1,"seat_ids":['$(seq -s, 1 1000)']}' \
    "$API/api/seats/hold")
if echo "$RESPONSE" | grep -qiE "limit|too many|maximum"; then
    pass "Order quantity limits enforced"
else
    warn "Large order quantities may not be limited"
fi

# Test: Price consistency check
info "Testing price consistency..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"event_id":1,"seat_ids":[1],"seat_pricing":{"1":0.01}}' \
    "$API/api/seats/hold")
if echo "$RESPONSE" | grep -qE "success|held"; then
    warn "Seat pricing may need server-side validation"
else
    pass "Price validation in place"
fi

# Test: Refund replay attack
info "Testing refund security..."
RESPONSE=$(curl -s -X PUT -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"amount":1000000}' "$API/api/admin/orders/999999/refund")
if echo "$RESPONSE" | grep -qiE "401|403|not found|unauthorized"; then
    pass "Refund endpoints require authentication"
else
    fail "Refund endpoint may be accessible without auth"
fi

# ============================================================================
# ADVANCED INJECTION ATTACKS
# ============================================================================
echo -e "\n[SECTION 3] Advanced Injection Attacks"
echo "=========================================="

# Test: SQL injection with time-based attacks
info "Testing time-based SQL injection..."
START=$(date +%s)
RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/events?id=1' AND SLEEP(5)--")
END=$(date +%s)
DURATION=$((END - START))
if [ $DURATION -ge 5 ]; then
    fail "Possible time-based SQL injection vulnerability!"
else
    pass "Time-based SQL injection protected"
fi

# Test: NoSQL injection (if MongoDB/similar used)
info "Testing NoSQL injection..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":{"$gt":""},"password":{"$gt":""}}' "$API/api/admin/login")
if echo "$RESPONSE" | grep -qE "token|success"; then
    fail "Possible NoSQL injection vulnerability!"
else
    pass "NoSQL injection protected"
fi

# Test: Command injection
info "Testing command injection..."
RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/tickets/download?file=test.pdf;ls -la")
if echo "$RESPONSE" | grep -qiE "total |drwx|bin/bash"; then
    fail "CRITICAL: Command injection possible!"
else
    pass "Command injection protected"
fi

# Test: Email header injection
info "Testing email header injection..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":"test@test.com\nBcc: attacker@evil.com","name":"Test"}' \
    "$API/api/newsletter/subscribe")
if echo "$RESPONSE" | grep -qiE "success|subscribed"; then
    warn "Email header injection - needs manual verification"
else
    pass "Email header injection appears protected"
fi

# Test: Template injection
info "Testing template injection..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"name":"{{7*7}}","email":"test@test.com"}' "$API/api/register")
if echo "$RESPONSE" | grep -q "49"; then
    fail "Template injection vulnerability detected!"
else
    pass "Template injection protected"
fi

# Test: LDAP injection
info "Testing LDAP injection..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":"*)(uid=*))(|(uid=*","password":"*"}' "$API/api/admin/login")
if echo "$RESPONSE" | grep -qE "token|success"; then
    fail "Possible LDAP injection vulnerability!"
else
    pass "LDAP injection protected"
fi

# ============================================================================
# DATA LEAKAGE & PRIVACY
# ============================================================================
echo -e "\n[SECTION 4] Data Leakage & Privacy"
echo "=========================================="

# Test: PII in URLs
info "Testing PII exposure in URLs..."
RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/orders?email=user@test.com&name=John")
if echo "$RESPONSE" | grep -qE "GET|url|query"; then
    warn "Sensitive parameters in URL (should use POST)"
else
    pass "Sensitive data not in URL parameters"
fi

# Test: Credit card data exposure
info "Testing payment data protection..."
RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/admin/orders/1")
if echo "$RESPONSE" | grep -qE "[0-9]{16}|card.*number|cvv"; then
    fail "CRITICAL: Credit card data exposed in API!"
else
    pass "Payment data properly protected"
fi

# Test: User enumeration via timing attack
info "Testing timing attack resistance..."
START=$(date +%s%N)
curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":"nonexistent@test.com","password":"test"}' "$API/api/admin/login" > /dev/null
END=$(date +%s%N)
DURATION1=$((END - START))

START=$(date +%s%N)
curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":"admin@test.com","password":"wrong"}' "$API/api/admin/login" > /dev/null
END=$(date +%s%N)
DURATION2=$((END - START))

DIFF=$((DURATION1 - DURATION2))
if [ ${DIFF#-} -gt 1000000000 ]; then  # More than 1 second difference
    warn "Timing difference detected - possible user enumeration"
else
    pass "Timing attack resistance appears adequate"
fi

# Test: Stack trace exposure with different errors
info "Testing error message consistency..."
ERRORS=0
curl -s -H "Host: $HOST" "$API/api/orders/abc" | grep -qiE "stack|trace|vendor" && ((ERRORS++))
curl -s -H "Host: $HOST" "$API/api/orders/-1" | grep -qiE "stack|trace|vendor" && ((ERRORS++))
curl -s -H "Host: $HOST" "$API/api/orders/999999999" | grep -qiE "stack|trace|vendor" && ((ERRORS++))

if [ $ERRORS -gt 0 ]; then
    fail "Stack traces exposed in $ERRORS different error scenarios"
else
    pass "Error messages are consistent and safe"
fi

# Test: API response information disclosure
info "Testing API response sanitization..."
RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/admin/admins")
if echo "$RESPONSE" | grep -qiE "password|secret|salt|hash"; then
    fail "Password hashes or secrets exposed in API response!"
else
    pass "API responses properly sanitized"
fi

# ============================================================================
# SESSION & COOKIE SECURITY
# ============================================================================
echo -e "\n[SECTION 5] Session & Cookie Security"
echo "=========================================="

# Test: Cookie flags
info "Testing cookie security flags..."
HEADERS=$(curl -sI -H "Host: $HOST" "$API/api/admin/login" -c -)
if echo "$HEADERS" | grep -qi "Set-Cookie"; then
    if echo "$HEADERS" | grep -qi "HttpOnly"; then
        pass "HttpOnly flag set on cookies"
    else
        fail "HttpOnly flag missing on cookies"
    fi
    if echo "$HEADERS" | grep -qi "Secure"; then
        pass "Secure flag set on cookies"
    else
        warn "Secure flag missing (should be set in production HTTPS)"
    fi
    if echo "$HEADERS" | grep -qi "SameSite"; then
        pass "SameSite flag set on cookies"
    else
        warn "SameSite flag missing (CSRF protection)"
    fi
else
    info "No cookies set by API (token-based auth)"
fi

# Test: CSRF protection on state-changing operations
info "Testing CSRF protection..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Origin: https://evil.com" \
    "$API/api/admin/orders/1/refund")
if echo "$RESPONSE" | grep -qiE "csrf|forbidden|origin"; then
    pass "CSRF protection in place"
else
    warn "CSRF protection should be verified for state-changing operations"
fi

# ============================================================================
# API-SPECIFIC VULNERABILITIES
# ============================================================================
echo -e "\n[SECTION 6] API-Specific Vulnerabilities"
echo "=========================================="

# Test: HTTP verb tampering
info "Testing HTTP verb tampering..."
RESPONSE=$(curl -s -X DELETE -H "Host: $HOST" "$API/api/events/1")
if echo "$RESPONSE" | grep -qiE "405|method not allowed"; then
    pass "HTTP verb tampering protected"
else
    warn "Unexpected response to DELETE on GET endpoint"
fi

# Test: Content-Type bypass
info "Testing Content-Type validation..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: text/xml" \
    -d '{"email":"test@test.com"}' "$API/api/admin/login")
if echo "$RESPONSE" | grep -qiE "415|unsupported|content-type"; then
    pass "Content-Type validation enforced"
else
    warn "Content-Type bypass may be possible"
fi

# Test: Parameter pollution
info "Testing parameter pollution..."
RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/orders?order_id=1&order_id=2")
if echo "$RESPONSE" | grep -qE "error|invalid"; then
    pass "Parameter pollution handled safely"
else
    warn "Parameter pollution handling should be reviewed"
fi

# Test: API versioning bypass
info "Testing API version enforcement..."
RESPONSE=$(curl -s -H "Host: $HOST" -H "Accept: application/vnd.api.v999+json" "$API/api/events")
if echo "$RESPONSE" | grep -qiE "version|supported"; then
    pass "API version validation in place"
else
    info "API versioning not detected (may not be used)"
fi

# Test: Excessive data exposure
info "Testing data minimization..."
RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/events")
FIELDS=$(echo "$RESPONSE" | jq -r 'keys | length' 2>/dev/null || echo "0")
if [ "$FIELDS" -gt 20 ]; then
    warn "Large number of fields returned - review data minimization"
else
    pass "Data minimization appears adequate"
fi

# ============================================================================
# PAYMENT & FINANCIAL SECURITY
# ============================================================================
echo -e "\n[SECTION 7] Payment & Financial Security"
echo "=========================================="

# Test: Stripe webhook signature validation
info "Testing Stripe webhook security..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"type":"payment_intent.succeeded","data":{"object":{"amount":100000}}}' \
    "$API/api/webhooks/stripe")
if echo "$RESPONSE" | grep -qiE "signature|invalid|unauthorized"; then
    pass "Webhook signature validation enforced"
else
    warn "Webhook signature validation should be verified"
fi

# Test: Currency manipulation
info "Testing currency validation..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"amount":10,"currency":"XXX"}' "$API/api/stripe/payment-intent")
if echo "$RESPONSE" | grep -qiE "currency|invalid"; then
    pass "Currency validation in place"
else
    warn "Currency validation should be checked"
fi

# Test: Amount manipulation
info "Testing payment amount integrity..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"seat_ids":[1,2],"amount":0.01}' "$API/api/payment/create-intent")
if echo "$RESPONSE" | grep -qiE "mismatch|invalid|amount"; then
    pass "Payment amount validation enforced"
else
    warn "Payment amount server-side validation needs review"
fi

# ============================================================================
# INFRASTRUCTURE SECURITY
# ============================================================================
echo -e "\n[SECTION 8] Infrastructure Security"
echo "=========================================="

# Test: Server information disclosure
info "Testing server information disclosure..."
HEADERS=$(curl -sI -H "Host: $HOST" "$API/api/health")
if echo "$HEADERS" | grep -qiE "X-Powered-By|Server: PHP"; then
    warn "Server version information disclosed"
else
    pass "Server information properly hidden"
fi

# Test: Directory listing
info "Testing directory listing..."
STATUS=$(curl -s -w "%{http_code}" -H "Host: $HOST" "$API/assets/" -o /dev/null)
if [ "$STATUS" = "200" ]; then
    RESPONSE=$(curl -s -H "Host: $HOST" "$API/assets/")
    if echo "$RESPONSE" | grep -qiE "index of|parent directory"; then
        fail "Directory listing enabled!"
    else
        pass "Directory listing disabled"
    fi
else
    pass "Directory access properly restricted"
fi

# Test: Backup file exposure
info "Testing backup file exposure..."
BACKUPS=(".bak" ".old" ".backup" "~" ".swp")
EXPOSED=0
for ext in "${BACKUPS[@]}"; do
    STATUS=$(curl -s -w "%{http_code}" -H "Host: $HOST" "$API/index.php$ext" -o /dev/null)
    [ "$STATUS" = "200" ] && ((EXPOSED++))
done
if [ $EXPOSED -gt 0 ]; then
    fail "$EXPOSED backup files are accessible!"
else
    pass "Backup files properly protected"
fi

# Test: Git folder exposure
info "Testing Git folder exposure..."
STATUS=$(curl -s -w "%{http_code}" -H "Host: $HOST" "$API/.git/config" -o /dev/null)
if [ "$STATUS" = "200" ] || [ "$STATUS" = "403" ]; then
    [ "$STATUS" = "200" ] && fail ".git folder is accessible!" || pass ".git folder blocked"
else
    pass ".git folder properly protected"
fi

# ============================================================================
# GDPR & COMPLIANCE
# ============================================================================
echo -e "\n[SECTION 9] GDPR & Privacy Compliance"
echo "=========================================="

# Test: Right to erasure
info "Testing GDPR erasure functionality..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":"test@test.com"}' "$API/api/gdpr/erasure-request")
if echo "$RESPONSE" | grep -qiE "request|received|pending"; then
    pass "GDPR erasure endpoint exists"
else
    warn "GDPR erasure functionality should be verified"
fi

# Test: Data export
info "Testing GDPR data export..."
RESPONSE=$(curl -s -X POST -H "Host: $HOST" -H "Content-Type: application/json" \
    -d '{"email":"test@test.com"}' "$API/api/gdpr/export-request")
if echo "$RESPONSE" | grep -qiE "export|request|pending"; then
    pass "GDPR data export endpoint exists"
else
    warn "GDPR data export functionality should be verified"
fi

# Test: Consent management
info "Testing consent management..."
RESPONSE=$(curl -s -H "Host: $HOST" "$API/api/consent/types")
if echo "$RESPONSE" | grep -qiE "marketing|analytics|essential"; then
    pass "Consent management system in place"
else
    warn "Consent management should be implemented for GDPR"
fi

# ============================================================================
# SUMMARY
# ============================================================================
echo -e "\n======================================"
echo "Advanced Security Audit Summary"
echo "======================================"
echo -e "${GREEN}Passed: $PASS${NC}"
echo -e "${YELLOW}Warnings: $WARN${NC}"
echo -e "${RED}Failed: $FAIL${NC}"
echo "======================================"

if [ $FAIL -gt 0 ]; then
    echo -e "${RED}⚠️  CRITICAL: $FAIL security vulnerabilities found!${NC}"
    exit 1
elif [ $WARN -gt 10 ]; then
    echo -e "${YELLOW}⚠️  Multiple warnings - thorough review recommended${NC}"
    exit 0
else
    echo -e "${GREEN}✓ Advanced security audit passed${NC}"
    exit 0
fi
