Testing CORS Implementation

Testing CORS Implementation

Browser-Based Testing

// Test CORS from browser console
async function testCORS(url, options = {}) {
    try {
        const response = await fetch(url, {
            method: options.method || 'GET',
            credentials: options.credentials || 'omit',
            headers: options.headers || {}
        });
        
        console.log('CORS Test Success:', {
            status: response.status,
            headers: Object.fromEntries(response.headers.entries()),
            corsAllowed: true
        });
        
        return await response.json();
    } catch (error) {
        console.error('CORS Test Failed:', error);
        return { corsAllowed: false, error: error.message };
    }
}

// Test different scenarios
testCORS('https://api.example.com/data', { credentials: 'include' });
testCORS('https://api.example.com/data', { 
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    credentials: 'include'
});

Automated CORS Testing

const axios = require('axios');

async function auditCORSPolicy(apiUrl, testOrigins) {
    const results = [];
    
    for (const origin of testOrigins) {
        // Test simple request
        try {
            const response = await axios.get(apiUrl, {
                headers: { 'Origin': origin }
            });
            
            results.push({
                origin,
                method: 'GET',
                allowed: !!response.headers['access-control-allow-origin'],
                allowedOrigin: response.headers['access-control-allow-origin'],
                credentials: response.headers['access-control-allow-credentials']
            });
        } catch (error) {
            results.push({
                origin,
                method: 'GET',
                allowed: false,
                error: error.message
            });
        }
        
        // Test preflight request
        try {
            const preflightResponse = await axios.options(apiUrl, {
                headers: {
                    'Origin': origin,
                    'Access-Control-Request-Method': 'POST',
                    'Access-Control-Request-Headers': 'Content-Type, Authorization'
                }
            });
            
            results.push({
                origin,
                method: 'OPTIONS',
                allowed: !!preflightResponse.headers['access-control-allow-origin'],
                allowedMethods: preflightResponse.headers['access-control-allow-methods'],
                allowedHeaders: preflightResponse.headers['access-control-allow-headers'],
                maxAge: preflightResponse.headers['access-control-max-age']
            });
        } catch (error) {
            results.push({
                origin,
                method: 'OPTIONS',
                allowed: false,
                error: error.message
            });
        }
    }
    
    return results;
}

// Test various origins
const testOrigins = [
    'https://legitimate-app.com',
    'https://evil-site.com',
    'null',
    'file://',
    'http://localhost:3000'
];

auditCORSPolicy('https://api.example.com/endpoint', testOrigins)
    .then(results => {
        console.log('CORS Audit Results:');
        results.forEach(result => {
            console.log(`Origin: ${result.origin}, Method: ${result.method}, Allowed: ${result.allowed}`);
        });
    });