#!/usr/bin/env python3
"""
Test the ads.txt Guru API endpoint security
This is the endpoint that the ads.txt Guru service calls
"""

import requests
import json
import base64

BASE_URL = "http://localhost:8080"

print("Testing ads.txt Guru API Endpoint")
print("="*50)

# First, let's get the connection data from the plugin
session = requests.Session()

# Login as admin to get the connect data
login_data = {
    'log': 'admin',
    'pwd': 'password123', 
    'wp-submit': 'Log In',
}
session.post(f"{BASE_URL}/wp-login.php", data=login_data)

# Get plugin page to see the connection details
response = session.get(f"{BASE_URL}/wp-admin/admin.php?page=adstxt-guru-connect")

# Extract the connect data (if visible)
import re
match = re.search(r'<textarea[^>]*id="atg-connect-copy"[^>]*>([^<]+)</textarea>', response.text)
if match:
    connect_data = match.group(1).strip()
    print(f"Found Connect Data: {connect_data[:50]}...")
    
    # Decode it to see the credentials
    decoded = json.loads(base64.b64decode(connect_data))
    print(f"\nDecoded credentials:")
    print(f"  Key: {decoded['key']}")
    print(f"  Secret: {decoded['secret']}")
    print(f"  Token param: {decoded['param']}")
    print(f"  URL: {decoded['url']}")
    
    # Test 1: Try the API endpoint WITHOUT authentication
    print("\n1. Test API without authentication:")
    response = requests.post(BASE_URL, data={
        'atg-connect-key': 'wrong_key',
        'atg-connect-secret': 'wrong_secret'
    })
    if 'success' in response.text:
        print("   ✗ API responded to unauthenticated request!")
    else:
        print("   ✓ No response to unauthenticated request")
    
    # Test 2: Try with correct key/secret but no token
    print("\n2. Test API with key/secret but no token:")
    response = requests.post(BASE_URL, data={
        'atg-connect-key': decoded['key'],
        'atg-connect-secret': decoded['secret']
    })
    if 'success' in response.text:
        print("   ✗ API responded without token!")
    else:
        print("   ✓ Token required for API access")
    
    # Test 3: Check if this endpoint is vulnerable to path manipulation
    print("\n3. Test if API endpoint has path validation:")
    print("   Note: We can't fully test this without ads.txt Guru server")
    print("   The API expects to receive ads.txt content from their server")
    print("   The vulnerability was in the ADMIN PANEL, not the API endpoint")
    
    # Test 4: Test mode check
    print("\n4. Test the connection test mode:")
    token_param = decoded['param']
    response = requests.post(BASE_URL, data={
        'atg-connect-key': decoded['key'],
        'atg-connect-secret': decoded['secret'],
        f'atg-connect-token-{token_param}': 'test1234567890123456789012345678',  # 32 chars
        'atg-connect-test': '1'
    })
    if response.text:
        print(f"   Test mode response: {response.text}")
    
else:
    print("Could not find Connect Data in admin panel")

print("\n" + "="*50)
print("\nAPI Endpoint Security Notes:")
print("- The API requires key + secret + token (3-factor auth)")
print("- Token param name is randomized (atg-connect-token-XXXXXXXX)")
print("- Token must be exactly 32 alphanumeric characters")
print("- The API fetches content from ads.txt Guru servers, not from user input")
print("- The path manipulation vulnerability was in the ADMIN FORM, not here")