Exercise 3: Audit Log Alerter
Objective
Scan Cloudflare Account Audit Logs for specific security events (such as logins from new IP addresses) and send real-time notifications to Discord.
This exercise teaches you how to build security monitoring automation that detects suspicious activities and provides immediate alerts to security teams.
What You'll Learn
- Security Monitoring: Detect anomalous account activities
- Audit Log Analysis: Parse and filter Cloudflare audit events
- Real-time Alerting: Send immediate notifications to security teams
- State Management: Track processed events to avoid duplicates
Architecture Overview
Cloudflare Audit Logs → Worker (Cron) → Event Analysis → Discord Webhook
↓
KV State Store
↓
Last Check Tracking
- Trigger: Cron-based polling every minute for real-time detection
- Analysis: Smart filtering for security-relevant events
- Alerting: Rich Discord notifications with context
- State: KV storage to track processing timestamps
Prerequisites
Before starting this exercise, ensure you have:
- Cloudflare account with audit log access
- Discord server with webhook permissions
- Understanding of security event patterns
- Basic knowledge of audit log analysis
Instructions
1. Project Setup
Create a new Worker project for security monitoring:
npm create cloudflare@latest audit-alerter
# Select "Hello World" Worker
# Choose TypeScript
# Select "Yes" to deploy
cd audit-alerter
2. Configure Secrets
Add the required API credentials:
npx wrangler secret put DISCORD_WEBHOOK_URL
npx wrangler secret put CLOUDFLARE_API_TOKEN
npx wrangler secret put CLOUDFLARE_ACCOUNT_ID
3. Setup KV Storage
Create a KV namespace for state management:
npx wrangler kv namespace create STATE_STORE
4. Configure Cron Trigger
Update your wrangler.jsonc for frequent monitoring:
{
"name": "audit-alerter",
"main": "src/index.ts",
"compatibility_date": "2024-12-02",
"triggers": {
"crons": ["*/1 * * * *"]
},
"kv_namespaces": [
{
"binding": "STATE_STORE",
"id": "your_kv_namespace_id"
}
],
"observability": {
"traces": true,
"metrics": true
}
}
5. Implementation Challenge
Your task is to implement a Worker that:
- Polls Cloudflare audit logs every minute for new events
- Analyzes events for security-relevant activities
- Detects suspicious patterns like new IP logins, permission changes
- Sends rich Discord alerts with event context and risk assessment
- Maintains processing state to avoid duplicate alerts
- Implements intelligent filtering to reduce noise
Key Security Events to Monitor:
- Login attempts from new IP addresses
- Permission elevation or role changes
- API token creation or modification
- Critical configuration changes
- Failed authentication attempts
🔍 Hint: Audit Log Event Types
Focus on these critical action types:
const criticalEvents = [
'login', // User login events
'add', // User/permission additions
'change', // Configuration changes
'delete', // Deletions
'create', // Resource creation
'revoke' // Token/access revocation
];
🎯 Hint: Risk Assessment Logic
Implement risk scoring based on:
- New IP Address: High risk if first time seeing this IP
- Off-hours Activity: Medium risk for actions outside business hours
- Privileged Operations: High risk for admin-level changes
- Geographic Anomalies: High risk for unusual locations
- Multiple Failures: High risk for repeated failed attempts
📱 Hint: Discord Message Format
Use Discord's rich embed format:
{
embeds: [{
title: "🚨 Security Alert",
color: 0xff0000, // Red for high risk
fields: [
{ name: "Event", value: "Login from new IP", inline: true },
{ name: "User", value: "user@company.com", inline: true },
{ name: "Risk Level", value: "HIGH", inline: true }
],
timestamp: new Date().toISOString()
}]
}
Testing Your Solution
- Controlled Testing: Generate test events in your Cloudflare account
- IP Detection: Login from a different network to trigger new IP alerts
- Permission Changes: Modify user roles to test privilege escalation detection
- Discord Integration: Verify message formatting and channel delivery
- State Validation: Confirm duplicate events are properly filtered
Success Criteria
Your implementation should:
- ✅ Successfully monitor audit logs in real-time (every minute)
- ✅ Detect new IP address logins accurately
- ✅ Identify privilege escalation events
- ✅ Send well-formatted Discord alerts with context
- ✅ Maintain state to prevent duplicate notifications
- ✅ Implement risk-based alerting with severity levels
- ✅ Handle API failures gracefully without losing events
Solution
🔒 Complete Security Monitoring Solution
This content is password-protected. Enter the password to view the content.
Next Steps
After completing this exercise, you've built a comprehensive security monitoring system that:
- Provides real-time threat detection across your Cloudflare infrastructure
- Delivers actionable security alerts with rich context
- Maintains intelligent state to reduce alert fatigue
- Scales automatically to handle high audit log volumes
This monitoring foundation can be extended to integrate with SIEM systems, trigger automated responses, or feed machine learning models for advanced threat detection!