#!/usr/bin/env python3
"""
Detailed test to capture exact error messages
"""

import requests
import re
from urllib.parse import urljoin

BASE_URL = "http://localhost:8080"
PLUGIN_PAGE = "/wp-admin/admin.php?page=adstxt-guru-connect"

session = requests.Session()

# Login
print("Logging in...")
login_data = {
    'log': 'admin',
    'pwd': 'password123',
    'wp-submit': 'Log In',
    'redirect_to': urljoin(BASE_URL, '/wp-admin/'),
    'testcookie': '1'
}
session.get(urljoin(BASE_URL, "/wp-login.php"))
response = session.post(urljoin(BASE_URL, "/wp-login.php"), data=login_data)
print("Logged in\n")

# Get the plugin page to find nonces
print("Getting plugin page...")
response = session.get(urljoin(BASE_URL, PLUGIN_PAGE))

# Extract error divs function
def extract_messages(html):
    messages = []
    # Look for error/success divs
    patterns = [
        r'<div class="[^"]*error[^"]*"[^>]*>([^<]+)</div>',
        r'<div class="[^"]*success[^"]*"[^>]*>([^<]+)</div>',
        r'<b>Error</b><br />([^<]+)</div>'
    ]
    for pattern in patterns:
        matches = re.findall(pattern, html)
        messages.extend(matches)
    return messages

print("\n" + "="*60)
print("DETAILED ERROR MESSAGE TESTS")
print("="*60)

# Test 1: CSRF without nonce
print("\n1. CSRF Attack - No nonce:")
data = {'atg-connect-custom': 'ATTACK_CONTENT'}
response = session.post(urljoin(BASE_URL, PLUGIN_PAGE), data=data)
messages = extract_messages(response.text)
if messages:
    for msg in messages:
        print(f"   Error: {msg}")
else:
    if "Custom ads.txt records updated" not in response.text:
        print("   ✓ Update blocked (no success message)")
    else:
        print("   ✗ VULNERABLE: Update succeeded without nonce!")

# Test 2: Invalid nonce
print("\n2. CSRF Attack - Invalid nonce:")
data = {
    'atg-connect-custom': 'ATTACK_CONTENT',
    'atg_connect_custom_nonce': 'invalid123'
}
response = session.post(urljoin(BASE_URL, PLUGIN_PAGE), data=data)
messages = extract_messages(response.text)
if messages:
    for msg in messages:
        print(f"   Error: {msg}")
else:
    print("   No explicit error message shown")

# Test 3: Directory traversal with valid nonce
print("\n3. Directory Traversal - /etc/passwd with valid nonce:")
# Get fresh nonce
response = session.get(urljoin(BASE_URL, PLUGIN_PAGE))
match = re.search(r'name="atg_connect_nonce"\s+value="([^"]*)"', response.text)
if match:
    nonce = match.group(1)
    data = {
        'atg-connect-path': '/etc/passwd',
        'atg_connect_nonce': nonce
    }
    response = session.post(urljoin(BASE_URL, PLUGIN_PAGE), data=data)
    messages = extract_messages(response.text)
    if messages:
        for msg in messages:
            print(f"   Error: {msg}")
    # Check for specific security messages
    if "Security error: Path must be within the WordPress installation directory" in response.text:
        print("   ✓ Specific error: Path must be within WordPress directory")
    if "Security error: Only ads.txt files are allowed" in response.text:
        print("   ✓ Specific error: Only ads.txt files allowed")

# Test 4: .htaccess attempt
print("\n4. Arbitrary File - .htaccess with valid nonce:")
response = session.get(urljoin(BASE_URL, PLUGIN_PAGE))
match = re.search(r'name="atg_connect_nonce"\s+value="([^"]*)"', response.text)
if match:
    nonce = match.group(1)
    data = {
        'atg-connect-path': '/var/www/html/.htaccess',
        'atg_connect_nonce': nonce
    }
    response = session.post(urljoin(BASE_URL, PLUGIN_PAGE), data=data)
    messages = extract_messages(response.text)
    if messages:
        for msg in messages:
            print(f"   Error: {msg}")
    if "Only ads.txt files are allowed" in response.text:
        print("   ✓ Correct error: Only ads.txt files are allowed")

# Test 5: Valid ads.txt path 
print("\n5. Valid Path - ads.txt in WordPress directory:")
response = session.get(urljoin(BASE_URL, PLUGIN_PAGE))
match = re.search(r'name="atg_connect_nonce"\s+value="([^"]*)"', response.text)
if match:
    nonce = match.group(1)
    data = {
        'atg-connect-path': '/var/www/html/ads.txt',
        'atg_connect_nonce': nonce
    }
    response = session.post(urljoin(BASE_URL, PLUGIN_PAGE), data=data)
    messages = extract_messages(response.text)
    if "Path to ads.txt file updated successfully" in response.text:
        print("   ✓ Valid path accepted: Update successful")
    elif messages:
        for msg in messages:
            print(f"   Info: {msg}")
    else:
        print("   File may not exist or other validation failed")

print("\n" + "="*60)