Skip to main content

API Endpoints & Testing Interface

This section implements a comprehensive set of HTTP endpoints that provide visibility, control, and testing capabilities for the Enforcement Engine. These endpoints enable security operators to monitor system health, verify enforcement effectiveness, and troubleshoot issues in production environments.

Endpoint Architecture Overview

The API provides three categories of functionality:

1. Operational Monitoring

  • Status Dashboard: Visual interface showing system health and current enforcement statistics
  • Service Information: Machine-readable service status for automated monitoring
  • Real-time Metrics: Current threat counts, enforcement distribution, and system performance

2. Testing & Validation

  • Response Logic Testing: Automated tests to verify graduated response decisions
  • Connection Testing: Service binding validation between Intelligence Collector and Enforcement Engine
  • Effectiveness Measurement: Comprehensive analysis of enforcement coverage and performance
  • Individual IP Checking: Query specific IP addresses to see their current enforcement status

3. Manual Control

  • Manual Enforcement: On-demand trigger for immediate threat processing
  • System Administration: Direct access to force enforcement cycles outside the scheduled runs

Status Dashboard & Service Information

Purpose: Provides both human-readable and machine-readable interfaces for monitoring the Enforcement Engine's operational status and current enforcement configuration.

Key capabilities:

  • Visual Dashboard: Interactive HTML interface with real-time statistics and testing tools
  • Response Level Visualization: Clear table showing the graduated response matrix (Block/Challenge/Rate Limit/Allow)
  • Current Enforcement Status: Live counts of IPs in each enforcement category
  • Automated Testing Integration: Built-in response logic validation with pass/fail indicators
  • Interactive Testing: Web-based tools for checking individual IPs and triggering tests

Why this approach: The dual interface (HTML + JSON) serves both human operators who need visual feedback and automated monitoring systems that require structured data. The embedded JavaScript enables real-time testing without external tools.

src/controllers/status.ts
import { Env } from '../types';
import { getEnforcementStats } from '../lib/stats';
import { testResponseLogic } from '../lib/testing';

// Enhanced status page with response level breakdown
export async function handleStatusPage(env: Env): Promise<Response> {
try {
// Get current enforcement stats
const stats = await getEnforcementStats(env);

// Test response logic
const testResults = await testResponseLogic(env);

const html = `
<!DOCTYPE html>
<html>
<head>
<title>Enforcement Engine Status</title>
<meta charset="UTF-8">
<style>
body { font-family: monospace; max-width: 900px; margin: 50px auto; }
.status-box { border: 1px solid #ccc; padding: 20px; margin: 20px 0; }
.green { color: green; } .red { color: red; } .orange { color: orange; }
.metric { margin: 10px 0; }
pre { background: #f4f4f4; padding: 10px; overflow-x: auto; }
table { width: 100%; border-collapse: collapse; margin: 10px 0; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
button { margin: 5px; padding: 10px; cursor: pointer; }
input { margin: 5px; padding: 8px; width: 200px; }
#testResults { background: #f8f8f8; padding: 10px; margin: 10px 0; display: none; }
</style>
</head>
<body>
<h1>⚖️ Enforcement Engine Status</h1>

<div class="status-box">
<h2>System Status</h2>
<div class="metric">Service: <span class="green">● RUNNING</span></div>
<div class="metric">Last Enforcement: ${stats.last_update || 'Never'}</div>
<div class="metric">Next Run: in ${Math.ceil((30 - new Date().getMinutes() % 30))} minutes</div>
</div>

<div class="status-box">
<h2>Response Level Configuration</h2>
<table>
<tr>
<th>Score Range</th>
<th>Response Level</th>
<th>Action</th>
<th>Description</th>
</tr>
<tr>
<td>4+</td>
<td><span style="color: red;">BLOCK</span></td>
<td>deny</td>
<td>High confidence threat - immediate block</td>
</tr>
<tr>
<td>2-3</td>
<td><span style="color: orange;">CHALLENGE</span></td>
<td>challenge</td>
<td>Medium confidence - require CAPTCHA</td>
</tr>
<tr>
<td>1</td>
<td><span style="color: blue;">RATE_LIMIT</span></td>
<td>rate_limit</td>
<td>Low confidence - throttle requests</td>
</tr>
<tr>
<td>0 or Whitelisted</td>
<td><span style="color: green;">LOG_ONLY</span></td>
<td>allow</td>
<td>Clean or protected IP - monitor only</td>
</tr>
</table>
</div>

<div class="status-box">
<h2>Current Enforcement Rules</h2>
<div class="metric">🚫 Blocked IPs: <strong>${stats.blocked_ips || 0}</strong></div>
<div class="metric">🔒 Challenged IPs: <strong>${stats.challenged_ips || 0}</strong></div>
<div class="metric">⏳ Rate Limited IPs: <strong>${stats.rate_limited_ips || 0}</strong></div>
<div class="metric">📝 Total Threats Processed: <strong>${stats.total_threats || 0}</strong></div>
</div>

<div class="status-box">
<h2>Response Logic Testing</h2>
<div class="metric">Tests Passed: <span class="green">${testResults.passed}/${testResults.total_tests}</span></div>
<details>
<summary>View Test Details</summary>
<pre>${testResults.results.map(r =>
`${r.ip.padEnd(15)} | Score: ${r.score} | Expected: ${r.expected.padEnd(10)} | Actual: ${r.actual.padEnd(10)} | ${r.passed ? '✓' : '✗'}`
).join('\\n')}</pre>
</details>
</div>

<div class="status-box">
<h2>Testing & Verification</h2>
<div class="metric">
<button onclick="runTest('/test/effectiveness')">📊 Measure Effectiveness</button>
<button onclick="runTest('/test/connection')">🔗 Test Connection</button>
</div>

<h3>Quick IP Checks:</h3>
<div style="margin: 10px 0;">
<input type="text" id="ipInput" placeholder="Enter IP address" value="192.0.2.100">
<button onclick="checkIP()">Check IP Status</button>
</div>

<div id="testResults">
<pre id="testOutput"></pre>
</div>
</div>

<div class="status-box">
<h2>API Endpoints</h2>
<pre>
GET /status - This status page
GET /info - Service information (JSON)
GET /test/response-logic - Test response level logic
GET /test/effectiveness - Measure enforcement effectiveness
GET /test/connection - Test Intelligence Collector connection
POST /enforce - Manual enforcement trigger
</pre>
</div>

<div class="status-box">
<h2>Quick Test Commands</h2>
<pre>
# Test response logic
curl "https://[worker-url]/test/response-logic"

# Manually trigger enforcement
curl -X POST "https://[worker-url]/enforce"

# Check service info
curl "https://[worker-url]/info"

# Initialize IP lists
curl -X POST "https://[worker-url]/lists/init"
</pre>
</div>

<script>
async function runTest(endpoint) {
const results = document.getElementById('testResults');
const output = document.getElementById('testOutput');

results.style.display = 'block';
output.textContent = 'Running test...';

try {
const response = await fetch(endpoint);
const data = await response.json();
output.textContent = JSON.stringify(data, null, 2);
} catch (error) {
output.textContent = 'Error: ' + error.message;
}
}

async function checkIP() {
const ip = document.getElementById('ipInput').value;
if (!ip) return;

await runTest('/check?ip=' + encodeURIComponent(ip));
}
</script>
</body>
</html>`;

return new Response(html, {
headers: { 'Content-Type': 'text/html' }
});

} catch (err) {
const error = err as Error;
return new Response(`Error generating status page: ${error.message}`, {
status: 500,
headers: { 'Content-Type': 'text/plain' }
});
}
}

export async function handleServiceInfo(env: Env): Promise<Response> {
return new Response(JSON.stringify({
service: 'enforcement-engine',
status: 'operational',
timestamp: new Date().toISOString()
}), {
headers: { 'Content-Type': 'application/json' }
});
}
Update Required: Add Status Routes to index.ts

After implementing the status controllers, update your main router to handle these endpoints:

src/index.ts
import { handleStatusPage, handleServiceInfo } from './controllers/status';

// Add these routes to your switch statement:
case '/status':
return handleStatusPage(env);

case '/info':
return handleServiceInfo(env);

Test your implementation: Visit https://your-worker.subdomain.workers.dev/status to see the interactive dashboard!

Response Logic Testing & IP Status Validation

Purpose: Implements comprehensive testing capabilities to validate the enforcement system's decision-making logic and provide detailed status information for individual IP addresses.

Core testing functions:

1. Automated Response Logic Testing

Tests the graduated response system with predefined test cases to ensure correct threat categorization:

  • Score 0: Should result in LOG_ONLY (clean IP, monitoring only)
  • Score 1: Should result in RATE_LIMIT (low confidence threat, throttling)
  • Score 2-3: Should result in CHALLENGE (medium confidence, CAPTCHA required)
  • Score 4+: Should result in BLOCK (high confidence, immediate denial)
  • Whitelisted Override: Any whitelisted IP should result in LOG_ONLY regardless of score

2. Individual IP Status Checking

Provides detailed forensic information about any IP address:

  • Threat Database Lookup: Searches current threat intelligence for the IP
  • Enforcement List Verification: Checks which Cloudflare IP List (if any) contains the IP
  • Score Analysis: Shows threat confidence score and contributing threat intelligence sources
  • Response Reasoning: Explains why the system chose a specific enforcement level
  • Fallback Handling: Uses cached data when live Intelligence Collector is unavailable

3. Enforcement List Cross-Reference

Validates that IPs are correctly placed in their corresponding Cloudflare IP Lists:

  • List Enumeration: Checks all active enforcement lists (Block, Challenge, Rate Limit)
  • Consistency Verification: Ensures IP placement matches threat score-based decisions
  • Health Monitoring: Identifies discrepancies between expected and actual enforcement

Operational value: These testing capabilities enable security operators to verify system correctness, troubleshoot enforcement issues, and audit specific IP decisions for compliance or investigation purposes.

src/lib/testing.ts
import { EnforcementEffectiveness, Env, ThreatIP } from '../types';
import { determineResponse } from './response-logic';
import { getThreatsFromCollector } from './intelligence-collector';
import { getIPListIds } from './ip-list-management';
import { CloudflareIPLists } from './cloudflare-ip-lists';
import { getEnforcementStats } from './stats';

// Test response determination with sample data
export async function testResponseLogic(env: Env): Promise<any> {
const testCases = [
{ ip: '192.0.2.1', score: 0, whitelisted: false, expected: 'log_only' },
{ ip: '192.0.2.2', score: 1, whitelisted: false, expected: 'rate_limit' },
{ ip: '192.0.2.3', score: 2, whitelisted: false, expected: 'challenge' },
{ ip: '192.0.2.4', score: 3, whitelisted: false, expected: 'challenge' },
{ ip: '192.0.2.5', score: 4, whitelisted: false, expected: 'block' },
{ ip: '192.0.2.6', score: 5, whitelisted: false, expected: 'block' },
{ ip: '173.245.48.1', score: 5, whitelisted: true, expected: 'log_only' }
];

const results = [];

for (const testCase of testCases) {
const response = determineResponse(testCase.score, testCase.whitelisted);
const passed = response.level === testCase.expected;

results.push({
ip: testCase.ip,
score: testCase.score,
whitelisted: testCase.whitelisted,
expected: testCase.expected,
actual: response.level,
passed: passed,
description: response.description
});
}

return {
total_tests: results.length,
passed: results.filter(r => r.passed).length,
failed: results.filter(r => !r.passed).length,
results: results
};
}

// Check the current enforcement status of a specific IP
export async function checkIPStatus(ip: string, env: Env): Promise<any> {
console.log(`Checking enforcement status for IP: ${ip}`);

try {
// Get current threat data (from cache or live fetch)
let threats: ThreatIP[] = [];

try {
// Try to get fresh data from Intelligence Collector
threats = await getThreatsFromCollector(env);
} catch (error) {
console.warn('Could not fetch fresh data, using cache');
const cachedThreats = await env.ENFORCEMENT_DATA.get('cached_threats');
if (cachedThreats) {
threats = JSON.parse(cachedThreats);
}
}

// Find this specific IP in the threat data
const threatInfo = threats.find(t => t.ip === ip);

if (!threatInfo) {
// IP not in threat database - check if it's in any current enforcement lists
const enforcement = await checkIPInEnforcementLists(ip, env);

return {
ip: ip,
found_in_threats: false,
enforcement_level: enforcement ? enforcement.level : 'allow',
enforcement_list: enforcement ? enforcement.list_name : null,
score: 0,
sources: [],
is_whitelisted: false,
status: 'clean'
};
}

// Determine response level for this threat
const response = determineResponse(threatInfo.score, threatInfo.is_whitelisted);

// Check if IP is actually in the corresponding enforcement list
const inEnforcement = await checkIPInEnforcementLists(ip, env);

return {
ip: ip,
found_in_threats: true,
enforcement_level: response.action === 'allow' ? 'allow' :
response.action === 'deny' ? 'block' :
response.action === 'challenge' ? 'challenge' :
response.action === 'rate_limit' ? 'rate_limit' : 'unknown',
enforcement_list: inEnforcement ? inEnforcement.list_name : null,
score: threatInfo.score,
sources: threatInfo.sources,
is_whitelisted: threatInfo.is_whitelisted,
status: threatInfo.is_whitelisted ? 'whitelisted' :
threatInfo.score >= 4 ? 'high_threat' :
threatInfo.score >= 2 ? 'medium_threat' :
threatInfo.score >= 1 ? 'low_threat' : 'clean',
response_reason: response.description
};

} catch (error) {
console.error(`Error checking IP status for ${ip}:`, error);
throw error;
}
}

// Check if an IP is in any of the current enforcement lists
export async function checkIPInEnforcementLists(ip: string, env: Env): Promise<any> {
try {
const listIds = await getIPListIds(env);
const ipLists = new CloudflareIPLists(env.CF_API_TOKEN, env.CF_ACCOUNT_ID);

for (const [level, listId] of Object.entries(listIds)) {
const items = await ipLists.getListItems(listId);
const found = items.some(item => item.ip === ip);

if (found) {
return {
level: level,
list_id: listId,
list_name: `threat_${level}`
};
}
}

return null;
} catch (error) {
console.warn('Error checking enforcement lists:', error);
return null;
}
}

// Measure enforcement effectiveness and generate metrics
export async function measureEnforcementEffectiveness(env: Env): Promise<EnforcementEffectiveness> {
console.log('Measuring enforcement effectiveness...');

try {
// Get current enforcement statistics
const stats = await getEnforcementStats(env);

// Get list details from Cloudflare
const listIds = await getIPListIds(env);
const ipLists = new CloudflareIPLists(env.CF_API_TOKEN, env.CF_ACCOUNT_ID);

const effectiveness: EnforcementEffectiveness = {
timestamp: new Date().toISOString(),
enforcement_coverage: {},
list_health: {},
threat_distribution: {
total_threats: stats.total_threats,
blocked: stats.blocked_ips,
challenged: stats.challenged_ips,
rate_limited: stats.rate_limited_ips,
allowed: stats.total_threats - (stats.blocked_ips + stats.challenged_ips + stats.rate_limited_ips)
},
performance_score: 0
};

// Check each enforcement list
for (const [level, listId] of Object.entries(listIds)) {
const listInfo = await ipLists.getListInfo(listId);
const items = await ipLists.getListItems(listId);

effectiveness.list_health[level] = {
list_id: listId,
name: listInfo?.name || 'Unknown',
item_count: items.length,
last_modified: listInfo?.modified_on || 'Unknown',
status: items.length > 0 ? 'active' : 'empty',
sample_ips: items.slice(0, 3).map(item => item.ip)
};
}

// Calculate coverage percentages
const total = effectiveness.threat_distribution.total_threats;
if (total > 0) {
effectiveness.enforcement_coverage = {
blocked_percentage: Math.round((effectiveness.threat_distribution.blocked / total) * 100),
challenged_percentage: Math.round((effectiveness.threat_distribution.challenged / total) * 100),
rate_limited_percentage: Math.round((effectiveness.threat_distribution.rate_limited / total) * 100),
allowed_percentage: Math.round((effectiveness.threat_distribution.allowed / total) * 100)
};

// Simple performance score (higher percentage of high-confidence blocks is better)
effectiveness.performance_score = Math.round(
(effectiveness.threat_distribution.blocked / total) * 100
);
}

return effectiveness;

} catch (error) {
console.error('Error measuring enforcement effectiveness:', error);
throw error;
}
}
src/controllers/api.ts
import { Env } from '../types';
import { testResponseLogic, measureEnforcementEffectiveness, checkIPStatus } from '../lib/testing';
import { enforceThreats } from '../lib/enforcement';
import { getThreatsFromCollector } from '../lib/intelligence-collector';

export async function handleTestResponseLogic(env: Env): Promise<Response> {
const testResults = await testResponseLogic(env);
return new Response(JSON.stringify(testResults, null, 2), {
headers: { 'Content-Type': 'application/json' }
});
}
Update Required: Add Response Logic Testing Route to index.ts

After implementing the testing library, add the response logic endpoint to your router:

src/index.ts
import { handleTestResponseLogic } from './controllers/api';

// Add this route to your switch statement:
case '/test/response-logic':
return handleTestResponseLogic(env);

Test your implementation: Try curl "https://your-worker.subdomain.workers.dev/test/response-logic" to verify your graduated response logic is working correctly!

Enforcement Effectiveness Measurement

Purpose: Provides comprehensive analytics and metrics about the enforcement system's performance, coverage, and operational health. This endpoint generates business intelligence for security teams to measure and optimize their threat response strategy.

Key measurement categories:

1. Threat Distribution Analysis

Analyzes how threats are categorized and distributed across enforcement levels:

  • Total Processing Volume: Number of threats processed in the current cycle
  • Enforcement Breakdown: Count of IPs in each category (Block/Challenge/Rate Limit/Allow)
  • Coverage Percentages: Proportional distribution showing enforcement balance
  • Trend Identification: Patterns in threat severity and response allocation

2. Cloudflare IP List Health Assessment

Monitors the operational status of enforcement infrastructure:

  • List Inventory: Status of each IP List (Block, Challenge, Rate Limit)
  • Population Metrics: Current item counts and last modification times
  • Sample Data: Representative IPs from each list for verification
  • Infrastructure Health: Identifies empty lists or potential synchronization issues

3. Performance Scoring

Calculates effectiveness metrics for operational assessment:

  • High-Confidence Blocking Rate: Percentage of high-score threats successfully blocked
  • Response Proportionality: How well enforcement levels match threat confidence scores
  • System Efficiency: Overall performance score based on threat categorization accuracy

Strategic value: These metrics enable security teams to validate their threat intelligence quality, optimize response thresholds, and demonstrate enforcement effectiveness to stakeholders. The data supports data-driven decision making for security policy adjustments.

src/controllers/api.ts
// Handle effectiveness measurement requests
export async function handleEffectivenessTest(env: Env): Promise<Response> {
try {
const effectiveness = await measureEnforcementEffectiveness(env);

return new Response(JSON.stringify(effectiveness, null, 2), {
headers: { 'Content-Type': 'application/json' }
});

} catch (err) {
const error = err as Error;
return new Response(JSON.stringify({
error: 'Effectiveness measurement failed',
message: error.message
}), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
Update Required: Add Effectiveness Measurement Route to index.ts

After implementing the effectiveness measurement function, add this endpoint to your router:

src/index.ts
import { handleEffectivenessTest } from './controllers/api';

// Add this route to your switch statement:
case '/test/effectiveness':
return handleEffectivenessTest(env);

Test your implementation: Use curl "https://your-worker.subdomain.workers.dev/test/effectiveness" to get detailed metrics about your enforcement performance and Cloudflare IP List health!

Service Binding Connection Testing

Purpose: Validates the critical Service Binding connection between the Enforcement Engine and Intelligence Collector. This endpoint ensures that the microservices communication is functioning correctly and threat data is flowing properly.

Connection validation process:

1. Service Binding Health Check

Tests the Cloudflare Workers Service Binding that enables direct communication between services:

  • Binding Availability: Verifies the INTELLIGENCE_COLLECTOR service binding is properly configured
  • Authentication: Confirms that Service Bindings provide automatic authentication between Workers
  • Network Connectivity: Validates that requests can reach the Intelligence Collector service
  • Response Format: Ensures the Intelligence Collector returns properly formatted threat data

2. Data Flow Verification

Validates that threat intelligence data is flowing correctly:

  • Data Retrieval: Attempts to fetch actual threat data from the Intelligence Collector
  • Format Validation: Confirms the response structure matches expected API contracts
  • Sample Data: Returns representative threat records for manual verification
  • Volume Metrics: Reports the number of threats received to indicate system health

3. Error Diagnosis

Provides detailed error information when connectivity issues occur:

  • Specific Error Messages: Clear descriptions of connection failures for troubleshooting
  • Service Status: Information about which component is causing the failure
  • Timestamp Tracking: When the connection test was performed for correlation with other logs

Operational importance: Service Bindings are critical infrastructure for microservices communication in Cloudflare Workers. This endpoint enables quick diagnosis of inter-service connectivity issues, which are essential for proper threat intelligence flow and enforcement effectiveness.

src/controllers/api.ts
// other codes
// Test connection to Intelligence Collector
export async function handleTestConnection(env: Env): Promise<Response> {
try {
console.log('Testing connection to Intelligence Collector...');

const threats = await getThreatsFromCollector(env);

return new Response(JSON.stringify({
success: true,
message: 'Service Binding to Intelligence Collector successful',
binding_type: 'Workers Service Binding',
threats_received: threats.length,
sample_threats: threats.slice(0, 3),
timestamp: new Date().toISOString()
}, null, 2), {
headers: { 'Content-Type': 'application/json' }
});

} catch (err) {
const error = err as Error;
return new Response(JSON.stringify({
success: false,
error: 'Failed to connect to Intelligence Collector via Service Binding',
binding_status: 'Service Binding failed',
message: error.message,
timestamp: new Date().toISOString()
}), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
Update Required: Add Connection Testing Route to index.ts

After implementing the connection testing function, add this endpoint to your router:

src/index.ts
import { handleTestConnection } from './controllers/api';

// Add this route to your switch statement:
case '/test/connection':
return handleTestConnection(env);

Test your implementation: Run curl "https://your-worker.subdomain.workers.dev/test/connection" to verify your Service Binding to the Intelligence Collector is working properly!

Manual Enforcement Trigger

Purpose: Provides on-demand enforcement capability that allows security operators to immediately trigger threat processing and rule updates outside of the scheduled 30-minute cycles.

Manual enforcement scenarios:

1. Emergency Response

Immediate threat processing when urgent security situations arise:

  • Critical Threat Discovery: When new high-priority threats are identified that require immediate blocking
  • Incident Response: During active security incidents requiring rapid enforcement updates
  • Threat Intelligence Updates: When fresh intelligence becomes available that needs immediate application

2. Testing & Validation

Controlled testing of enforcement workflows:

  • Deployment Verification: After configuration changes or system updates
  • Integration Testing: Validating end-to-end enforcement pipeline functionality
  • Performance Testing: Measuring enforcement processing time and effectiveness

3. Administrative Operations

Operational control for system maintenance:

  • Schedule Override: Forcing enforcement when scheduled triggers are temporarily disabled
  • Consistency Restoration: Re-synchronizing enforcement state after system maintenance
  • Manual Synchronization: Ensuring Cloudflare IP Lists match current threat intelligence

Implementation details:

  • Asynchronous Processing: Uses ctx.waitUntil() to process enforcement in the background without blocking the HTTP response
  • Immediate Response: Returns success confirmation immediately while enforcement continues asynchronously
  • Error Handling: Captures and reports enforcement failures for troubleshooting
  • POST Method: Requires explicit POST request to prevent accidental triggers from web crawlers or caching systems

Operational safety: Manual enforcement provides critical operational flexibility while maintaining the same safety controls and validation logic as scheduled enforcement cycles.

src/controllers/api.ts
// other codes

// Manual enforcement trigger
export async function handleManualEnforcement(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
if (request.method === 'POST') {
try {
ctx.waitUntil(enforceThreats(env));
return new Response(JSON.stringify({
success: true,
message: 'Manual enforcement completed',
timestamp: new Date().toISOString()
}), {
headers: { 'Content-Type': 'application/json' }
});
} catch (err) {
const error = err as Error;
return new Response(JSON.stringify({
success: false,
error: error.message
}), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}

return new Response('Method not allowed', { status: 405 });
}
Update Required: Add Manual Enforcement Route to index.ts

After implementing the manual enforcement handler, add this endpoint to your router:

src/index.ts
import { handleManualEnforcement } from './controllers/api';

// Add this route to your switch statement:
case '/enforce':
return handleManualEnforcement(request, env, ctx);

Test your implementation: Use curl -X POST "https://your-worker.subdomain.workers.dev/enforce" to manually trigger an immediate enforcement cycle!

Individual IP Status Checking

Purpose: Provides detailed forensic analysis of individual IP addresses, enabling security analysts to investigate specific IPs and understand their current enforcement status within the system.

IP analysis capabilities:

1. Threat Intelligence Lookup

Comprehensive search through current threat data:

  • Database Search: Queries active threat intelligence data for the specified IP address
  • Threat Score Analysis: Shows confidence score and contributing intelligence sources
  • Whitelist Status: Indicates whether the IP has been whitelisted for protection
  • Source Attribution: Lists which threat intelligence feeds flagged this IP

2. Enforcement Status Verification

Cross-references the IP's theoretical and actual enforcement status:

  • Expected Response Level: What enforcement level the IP should have based on its threat score
  • Actual Enforcement: Which Cloudflare IP List (if any) currently contains this IP
  • Consistency Check: Validates that expected and actual enforcement levels match
  • Status Explanation: Provides reasoning for the enforcement decision

3. Operational Intelligence

Provides context for security operations and incident response:

  • First/Last Seen: When the IP was first and most recently observed in threat intelligence
  • Threat Classification: Human-readable status (Clean, Low Threat, Medium Threat, High Threat, Whitelisted)
  • Response Reasoning: Detailed explanation of why the system chose the specific enforcement level
  • Fallback Handling: Uses cached threat data when live Intelligence Collector is unavailable

Investigation workflows: This endpoint enables security analysts to quickly investigate suspicious IPs during incident response, verify enforcement decisions for compliance audits, and troubleshoot user-reported access issues by checking if legitimate IPs are incorrectly blocked.

src/controllers/api.ts
// other codes

// Handle individual IP status checks
export async function handleCheckIP(ip: string, env: Env): Promise<Response> {
try {
const status = await checkIPStatus(ip, env);

return new Response(JSON.stringify(status, null, 2), {
headers: { 'Content-Type': 'application/json' }
});

} catch (err) {
const error = err as Error;
return new Response(JSON.stringify({
error: `Failed to check IP ${ip}`,
message: error.message
}), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
Update Required: Add IP Status Checking Route to index.ts

After implementing the IP status checking handler, add this endpoint to your router:

src/index.ts
import { handleCheckIP } from './controllers/api';

// Add this route to your switch statement:
case '/check':
const checkIp = url.searchParams.get('ip');
if (!checkIp) {
return new Response('{"error": "ip parameter required"}', {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
return handleCheckIP(checkIp, env);

Test your implementation: Try curl "https://your-worker.subdomain.workers.dev/check?ip=192.0.2.1" to analyze the enforcement status of any IP address!

HTTP Request Router & API Orchestration

Purpose: Implements the main HTTP request routing system that coordinates all API endpoints and provides a unified interface for the Enforcement Engine's capabilities.

Routing architecture:

1. Request Processing Pipeline

Systematic handling of all incoming HTTP requests:

  • URL Parsing: Extracts path and query parameters from incoming requests
  • CORS Handling: Manages cross-origin requests for web-based testing interfaces
  • Method Validation: Ensures appropriate HTTP methods are used for each endpoint
  • Parameter Extraction: Safely extracts and validates query parameters and request bodies

2. Endpoint Orchestration

Central coordination of all API functionality:

  • Route Mapping: Maps URL paths to appropriate handler functions
  • Controller Integration: Connects routing to specialized controller modules
  • Error Handling: Provides consistent error responses across all endpoints
  • Response Formatting: Ensures uniform JSON response structure

3. Service Integration Points

Connects HTTP endpoints to core enforcement functionality:

  • Status Monitoring: Routes status requests to dashboard and service info handlers
  • Testing Interfaces: Connects testing endpoints to validation and measurement functions
  • Manual Controls: Integrates manual enforcement triggers with core processing logic
  • Query Capabilities: Links IP checking functionality to threat analysis systems

4. Operational Features

Production-ready capabilities for system administration:

  • Comprehensive Endpoint Discovery: Default route returns complete API documentation
  • Version Information: Provides API version and service identification
  • Error Diagnostics: Detailed error reporting for troubleshooting
  • Method Enforcement: Proper HTTP method validation and 405 responses

API design principles: The routing system follows REST conventions, provides self-documenting endpoints, and maintains consistent error handling. The centralized approach enables easy addition of new endpoints while maintaining system coherence.

src/index.ts
import { Env } from './types';
import { handleStatusPage, handleServiceInfo } from './controllers/status';
import {
handleTestResponseLogic,
handleManualEnforcement,
handleEffectivenessTest,
handleCheckIP,
handleTestConnection,
} from './controllers/api';
import { enforceThreats } from './lib/enforcement';

export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
const url = new URL(request.url);
const path = url.pathname;

// Handle CORS preflight requests
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
}
});
}

try {
// Route handling
switch (path) {
case '/status':
return handleStatusPage(env);

case '/info':
return handleServiceInfo(env);

case '/test/response-logic':
return handleTestResponseLogic(env);

case '/enforce':
return handleManualEnforcement(request, env, ctx);

case '/test/effectiveness':
return handleEffectivenessTest(env);

case '/test/connection':
return handleTestConnection(env);

case '/check':
const checkIp = url.searchParams.get('ip');
if (!checkIp) {
return new Response('{"error": "ip parameter required"}', {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
return handleCheckIP(checkIp, env);

default:
return new Response(JSON.stringify({
message: 'Enforcement Engine API',
version: '1.0.0',
endpoints: [
'/status - Status page',
'/info - Service information',
'/test/response-logic - Test response logic',
'/test/effectiveness - Measure enforcement effectiveness',
'/test/connection - Test Intelligence Collector connection',
'/check?ip=1.2.3.4 - Check specific IP status',
'POST /enforce - Manual enforcement trigger',
'/cache/status - Cache status'
]
}), {
headers: { 'Content-Type': 'application/json' }
});
}
} catch (err) {
const error = err as Error;
return new Response(JSON.stringify({
error: 'Internal server error',
message: error.message
}), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
},

// other codes
};
Final Step: Complete Your Router Implementation

Your final index.ts should now include all endpoints and imports:

src/index.ts
import { Env } from './types';
import { handleStatusPage, handleServiceInfo } from './controllers/status';
import {
handleTestResponseLogic,
handleManualEnforcement,
handleEffectivenessTest,
handleCheckIP,
handleTestConnection
} from './controllers/api';
import { enforceThreats } from './lib/enforcement';

export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
const url = new URL(request.url);
const path = url.pathname;

// Add all your case statements here as shown in the previous tips

// Don't forget your default route with endpoint documentation!
},

async scheduled(event: ScheduledEvent, env: Env): Promise<void> {
await enforceThreats(env);
}
};

Final test: Visit https://your-worker.subdomain.workers.dev/ to see your complete API documentation with all available endpoints!

API Implementation Summary

This endpoint implementation demonstrates several key patterns for production API design in serverless security systems:

Comprehensive Observability

  • Multi-format Interfaces: Both human-readable dashboards and machine-readable JSON endpoints
  • Real-time Testing: Embedded testing capabilities that don't require external tools
  • Detailed Diagnostics: Comprehensive error reporting and system health monitoring
  • Performance Metrics: Quantitative measurement of enforcement effectiveness

Operational Excellence

  • Manual Override Capabilities: Emergency controls for immediate threat response
  • Service Health Monitoring: Connection testing and dependency validation
  • Forensic Analysis: Individual IP investigation capabilities for incident response
  • Automated Validation: Built-in testing that verifies system correctness

Production-Ready Design

  • Consistent Error Handling: Uniform error response structure across all endpoints
  • CORS Support: Web-based testing interfaces that work across origins
  • Self-Documenting: API discovery endpoints that list all available functionality
  • Method Enforcement: Proper HTTP semantics and method validation

Security-First Approach

  • Input Validation: All parameters are validated before processing
  • Audit Trails: All administrative actions generate proper audit logs
  • Safe Defaults: Error conditions fail safely without exposing sensitive information
  • Access Controls: POST-only methods for operations that modify system state

This API design enables security teams to operate the enforcement system confidently in production environments while providing the visibility and control needed for effective threat response operations.