Skip to content

πŸ”’ Autonomous Zero Trust Security Agent for Cloudflare Workers - AI-powered API protection with Shadow AI detection, deception honeypots, and real-time threat analysis.

Notifications You must be signed in to change notification settings

aqilc/cf-ai-malicious-req-security

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Zero Trust Security Agent πŸ”’

Cloudflare Workers application implementing an autonomous security agent for API protection with Shadow AI detection and honeypot deception capabilities.

Tests TypeScript Cloudflare Workers

🎯 Overview

This project demonstrates a sophisticated Zero Trust Security Agent that autonomously protects APIs from threats including:

  • πŸ€– Shadow AI Detection - Identifies LLM-driven automated attacks
  • πŸ›‘οΈ Real-time Threat Analysis - Uses Cloudflare's AI models for intelligent decisions
  • 🍯 Deception Honeypots - Wastes attacker time with convincing fake responses
  • πŸ“Š Dynamic Trust Scoring - Maintains IP reputation using Durable Objects
  • ⚑ High Performance - Optimized for speed with parallel processing

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Client        │────│  Security Agent  │────│  Origin API     β”‚
β”‚   Request       β”‚    β”‚  (Worker)        β”‚    β”‚  (Protected)    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
                              β”œβ”€β”€ Durable Objects (Trust Tracking)
                              β”œβ”€β”€ Workers AI (Threat Analysis)
                              β”œβ”€β”€ AI Gateway (Enterprise Controls)
                              β”œβ”€β”€ KV Storage (Security Logs)
                              └── Honeypot Service (Deception)

Core Components

  • src/index.ts - Main entry point with optimized request routing
  • src/securityAgent.ts - Autonomous security analysis and decision engine
  • src/durableObjects.ts - Trust tracking and persistent state management
  • src/aiGateway.ts - Enterprise AI integration with observability
  • src/honeypot.ts - Deceptive response generation system
  • src/types.ts - TypeScript definitions and interfaces

πŸš€ Quick Start

Prerequisites

  • Bun installed (https://bun.sh)
  • Cloudflare account with Workers and AI enabled
  • Wrangler CLI configured (npx wrangler login)

Installation

# Clone or download the project
cd cf_ai_job_appl

# Install dependencies (minimal - Bun has most built-in)
bun install

# Verify setup
bun run test-all

Local Development

# Run all tests (unit + integration)
bun run test-all

# Build the project
bun run build

# Type checking
bun run type-check

# Test standalone logic (no deployment needed)
bun run test-standalone

# Start local development server
bun run dev

πŸ§ͺ Testing

The project includes comprehensive testing without requiring your Cloudflare credentials:

Unit Tests

bun test

Tests the core security agent logic with mocked services.

Standalone Integration Tests

bun run test-standalone

Tests the complete security flow including:

  • βœ… Legitimate request processing
  • βœ… Suspicious bot detection
  • βœ… Malicious path blocking
  • βœ… XSS attempt prevention

All Tests

bun run test-all

Runs both unit and integration tests.

πŸ“¦ Deployment

1. Configure Cloudflare Resources

Update wrangler.toml with your actual resource IDs:

# Replace these mock values with your actual IDs
[[ai.bindings]]
type = "ai_gateway"
name = "AI_GATEWAY"
gateway_id = "your-actual-gateway-id"        # ← Replace this
gateway_token = "your-actual-gateway-token"  # ← Replace this

[[kv_namespaces]]
binding = "SECURITY_LOGS"
id = "your-actual-kv-namespace-id"           # ← Replace this
preview_id = "your-preview-kv-namespace-id"  # ← Replace this

2. Create Required Resources

# Create KV namespace for security logs
npx wrangler kv:namespace create "SECURITY_LOGS"
npx wrangler kv:namespace create "SECURITY_LOGS" --preview

# Create AI Gateway (via Cloudflare dashboard)
# Go to AI > AI Gateway > Create Gateway

3. Deploy

# Deploy to Cloudflare Workers
bun run deploy

# Or with Wrangler directly
npx wrangler deploy

πŸ›‘οΈ Security Features

Autonomous Decision Making

The agent makes intelligent, autonomous decisions based on real-time analysis:

Decision Trigger Response
Allow Low risk (0-35) Process normally
Monitor Low-moderate risk (35-60) Enhanced logging
Honeypot Moderate risk (60-80) Deploy deception
Block High risk (80+) Deny access

Risk Factors Analyzed

  • User Agent Patterns - Detects automated tools, bots, scripts
  • Path Analysis - Identifies suspicious endpoints (/admin, /wp-admin, etc.)
  • Payload Inspection - Scans for XSS, SQL injection, command injection
  • Request Patterns - Analyzes frequency, headers, behavior
  • Trust History - Maintains per-IP reputation scores

Honeypot Strategies

When deploying deception, the agent can:

  1. Fake Data Response - Convincing but fabricated API data
  2. Fake Errors - Realistic error messages with delays
  3. Slow Response - Artificial processing delays
  4. Redirect Loops - Waste computational resources
  5. AI-Generated - Custom deceptive responses via LLM

πŸ”§ Configuration

Environment Variables

Set these in your wrangler.toml:

[vars]
HONEYPOT_MODE = "true"        # Enable/disable honeypot responses
LOG_LEVEL = "debug"           # Logging: debug, info, warn, error
THREAT_THRESHOLD = "5"        # Score threshold for auto-blocking (0-100)

Development vs Production

# Development
[env.development]
vars = { HONEYPOT_MODE = "true", LOG_LEVEL = "debug" }

# Production  
[env.production]
vars = { HONEYPOT_MODE = "true", LOG_LEVEL = "info" }

πŸ“Š Monitoring & Observability

Security Event Logging

All security events are logged to multiple destinations:

  • KV Namespace - Long-term storage (30 days retention)
  • AI Gateway - AI call observability and usage tracking
  • Durable Objects - Real-time state and trust scores

Log Types

  • monitor:ip:timestamp - Enhanced monitoring events
  • honeypot:ip:timestamp - Deception activations
  • ai_request:request_id - AI analysis calls
  • ai_error:request_id - AI service failures

Metrics Dashboard

Access through Cloudflare dashboard:

  • Request volume and patterns
  • Security decision distribution
  • AI Gateway usage and costs
  • Durable Object performance

πŸ§ͺ Testing Your Deployment

Once deployed, test the security agent:

Legitimate Request

curl -H "User-Agent: Mozilla/5.0" https://your-worker.your-subdomain.workers.dev/api/users
# Expected: 200 OK with normal response

Suspicious Bot

curl -H "User-Agent: python-requests/2.28.0" https://your-worker.your-subdomain.workers.dev/admin
# Expected: 403 Blocked or honeypot response

Malicious Path

curl https://your-worker.your-subdomain.workers.dev/wp-admin
# Expected: 403 Blocked immediately

XSS Attempt

curl -X POST -H "Content-Type: application/json" \
  -d '{"query":"<script>alert(\"xss\")</script>"}' \
  https://your-worker.your-subdomain.workers.dev/search
# Expected: 403 Blocked or honeypot

⚑ Performance Optimizations

The application is optimized for production use:

Speed Optimizations

  • Quick Pre-checks - Obviously malicious requests blocked in <1ms
  • Smart AI Usage - AI only called for moderate+ risk requests
  • Parallel Processing - Multiple operations run concurrently
  • Efficient Risk Scoring - Fast pattern matching algorithms

Cost Optimizations

  • Minimal Dependencies - Uses Bun's built-in tools
  • Selective AI Calls - Reduces AI Gateway costs
  • Optimized Durable Objects - Efficient state management
  • Smart Caching - Reduces redundant calculations

Resource Usage

  • Memory - ~10MB typical usage
  • CPU - ~5ms average processing time
  • AI Calls - Only for requests scoring >30 risk points
  • Storage - Automatic cleanup with TTL

πŸ” Troubleshooting

Common Issues

Tests Failing

# Verify TypeScript compilation
bun run type-check

# Run standalone tests
bun run test-standalone

Deployment Issues

# Check Wrangler authentication
npx wrangler whoami

# Verify resource IDs in wrangler.toml
npx wrangler kv:namespace list

Performance Issues

# Monitor via Cloudflare dashboard
# Adjust THREAT_THRESHOLD in wrangler.toml
# Review AI Gateway usage patterns

Debug Mode

Enable debug logging:

[vars]
LOG_LEVEL = "debug"

View logs:

npx wrangler tail

πŸ›£οΈ Development Roadmap

Immediate Enhancements

  • Custom risk scoring rules
  • Geographic threat analysis
  • Rate limiting integration
  • Custom honeypot templates

Advanced Features

  • Machine learning model training
  • Threat intelligence feeds
  • Multi-tenant support
  • Advanced analytics dashboard

🀝 Contributing

Development Setup

git clone <repository>
cd cf_ai_job_appl
bun install
bun run test-all

Code Style

  • Use TypeScript for all new code
  • Follow the existing patterns
  • Add tests for new features
  • Update documentation

Testing Requirements

All changes must pass:

bun run test-all      # Unit + integration tests
bun run type-check    # TypeScript validation
bun run build         # Compilation check

πŸ“„ License

MIT License - See LICENSE file for details.

πŸ”— Resources


Built with ❀️ for Cloudflare's Zero Trust Security platform

About

πŸ”’ Autonomous Zero Trust Security Agent for Cloudflare Workers - AI-powered API protection with Shadow AI detection, deception honeypots, and real-time threat analysis.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published