Schedule icon
Webhook icon
Get icon
Request icon
Script icon
Docker icon
Set icon
If icon
SlackIncomingWebhook icon
Log icon
Return icon

Cloudflare WAF Custom Rule Block Rate & Anomaly Sentinel

Detect Cloudflare WAF block rate spikes over 1-hour baselines via GraphQL Analytics, track telemetry in KV, and dispatch Slack incident alerts.

Categories
CloudInfrastructure

Continuously audits Cloudflare Web Application Firewall (WAF) mitigation trends across production zones using the Cloudflare GraphQL Analytics API. The workflow analyzes time-series buckets (firewallEventsAdaptiveByTimeGroups) and granular security events (firewallEventsAdaptive), tracking mitigated actions including block, challenge, managed_challenge, and js_challenge. By contrasting the immediate evaluation window against a rolling 1-hour historical baseline, the flow flags acute surges (> 500%), distinguishes potential custom rule false positives from active DDoS or credential stuffing attacks, persists operational telemetry in Kestra KV store, and routes diagnostic incident cards to Slack.

How it works

  1. Baseline Retrieval: Queries Kestra Key-Value store (cloudflare_waf_telemetry_{zone_id}) to inspect historical baseline metrics and previous telemetry states.
  2. GraphQL Analytics Query: Interrogates https://api.cloudflare.com/client/v4/graphql using io.kestra.plugin.core.http.Request to pull 5-minute event buckets alongside detailed mitigation records across the configured lookback window.
  3. Spike & Anomaly Evaluation: A sandboxed Python container aggregates 5-minute time buckets, calculates rolling 1-hour baseline averages, and computes the relative mitigation spike percentage.
  4. Forensic Root Cause Isolation: Extracts and ranks top offending custom rule IDs, client Autonomous System Numbers (ASNs), targeted URI endpoints, and source IP addresses. Differentiates single-rule false positive misconfigurations affecting legitimate traffic from distributed volumetric floods.
  5. Telemetry Persistence: Updates Kestra KV storage with structured telemetry (cloudflare_waf_telemetry_{zone_id}) for long-term trending.
  6. Incident Escalation: If the rate spike breaches configured thresholds, dispatches a rich Slack Block Kit notification detailing rule impact analysis, offending ASNs, and actionable triage recommendations.

Architecture diagram

flowchart TD
    A[periodic_waf_audit Schedule / Webhook Trigger] --> B[get_previous_waf_telemetry KV Get]
    B --> C[query_cloudflare_waf_analytics HTTP Request]
    C --> D[evaluate_waf_block_rate_and_anomalies Python Script]
    D --> E[record_waf_telemetry_in_kv KV Set]
    E --> F[check_waf_spike_anomaly Flowable If]
    F -- Spike Detected --> G[notify_slack_waf_spike Slack Webhook]
    F -- Normal Baseline --> H[log_nominal_waf_state Log]
    G --> I[export_waf_sentinel_manifest Return]
    H --> I

Architecture components

  • Schedule & Webhook Triggers (periodic_waf_audit, on_waf_security_webhook): Enables continuous 5-minute interval audits and event-driven SIEM webhook invocations.
  • KV Store Reader (get_previous_waf_telemetry): Fetches previous baseline averages to maintain rate consistency across workflow runs.
  • HTTP Client (query_cloudflare_waf_analytics): Communicates with Cloudflare GraphQL Analytics API using secure token authentication.
  • Forensic Engine (evaluate_waf_block_rate_and_anomalies): Computes rate variance and performs multi-dimensional security triage inside a Python container.
  • KV Store Writer (record_waf_telemetry_in_kv): Stores updated security metrics under cloudflare_waf_telemetry_{zone_id} for stateful surveillance.
  • Slack Alerting (notify_slack_waf_spike): Generates rich Block Kit messages for SecOps response teams.

Key capabilities

  • Adaptive Sampling Ingestion: Leverages Cloudflare adaptive firewall event datasets to audit high-volume traffic without truncating surge patterns.
  • Rolling Baseline Comparison: Calculates 1-hour moving averages across 5-minute intervals to prevent alert fatigue from steady-state background scanner noise.
  • Root Cause Disambiguation: Cross-references top rule hit concentration with ASN diversity to immediately identify whether a new WAF rule is inadvertently dropping legitimate customer traffic or mitigating an actual distributed attack.
  • Native KV State Tracking: Uses Kestra's built-in KV store to ensure persistent, stateless execution without external database infrastructure.

What you get

  • Real-time detection of WAF block surges exceeding 500% over standard operating baselines.
  • Automated classification separating custom rule misconfigurations from active credential stuffing and Layer 7 botnets.
  • Forensic breakdown of offending rule IDs, client ASNs, attacking IPs, and targeted paths.
  • State tracking in Kestra KV store under cloudflare_waf_telemetry_{zone_id}.
  • Rich Slack notifications with direct triage indicators.

Who it's for

  • Security Operations (SecOps) teams overseeing cloud perimeter defenses and edge firewall policies.
  • Site Reliability Engineers (SREs) managing web application uptime and customer journey availability.
  • DevSecOps engineers verifying newly deployed WAF custom rules and rate-limiting expressions in production.

Why orchestrate this with Kestra

  • Zero-Infrastructure Orchestration: Executes end-to-end WAF monitoring, metric parsing, state caching, and alerting without managing external time-series databases or serverless daemons.
  • Native KV Store Integration: Built-in Key-Value persistence enables seamless historical baseline tracking across periodic workflow executions.
  • Robust Error Handling: Encapsulates API rate limits, transient network partitions, and pipeline failures with native retry parameters and Slack fallback hooks.
  • Declarative Security Automation: Standardizes cloud perimeter audits in declarative GitOps-managed YAML workflows.

Use cases

  • Post-Deployment WAF Rule Validation: Audit newly published custom firewall expressions to catch over-blocking and false positives before customer checkout workflows fail.
  • DDoS & Credential Stuffing Early Warning: Detect volumetric attack floods on login, signup, and API endpoints the moment edge mitigation rates spike.
  • Edge Security Telemetry Ingestion: Export continuous WAF mitigation metrics into upstream SIEM and observability dashboards.

Inputs

Name Type Default Description
zone_id STRING 023e105f4ecef8ad9ca31a8372d0c353 Hexadecimal 32-character identifier of the Cloudflare zone.
spike_threshold_pct FLOAT 500.0 Percentage surge over 1-hour baseline required to flag an anomaly.
lookback_minutes INT 75 Minutes queried from GraphQL API for baseline and current metrics.
min_block_count_for_spike INT 50 Minimum mitigated requests needed before triggering an alert.
alert_on_spike BOOL True Dispatches Slack alerts when anomalies are confirmed.

Expected outputs

  • {{ outputs.evaluate_waf_block_rate_and_anomalies.vars.status }}: Operational classification (NOMINAL_HEALTHY, NOMINAL_WITH_MITIGATIONS, ANOMALOUS_BLOCK_RATE_SPIKE).
  • {{ outputs.evaluate_waf_block_rate_and_anomalies.vars.spike_detected }}: Boolean flag indicating confirmed block rate anomaly.
  • {{ outputs.evaluate_waf_block_rate_and_anomalies.vars.spike_percentage }}: Percentage surge relative to baseline average.
  • {{ outputs.evaluate_waf_block_rate_and_anomalies.vars.current_interval_blocks }}: Total mitigated requests in current 5-minute interval.
  • {{ outputs.evaluate_waf_block_rate_and_anomalies.vars.baseline_interval_avg }}: Rolling 1-hour average mitigated requests per interval.
  • {{ outputs.evaluate_waf_block_rate_and_anomalies.vars.root_cause_summary }}: Forensic assessment differentiating misconfigurations from volumetric attacks.

Prerequisites

  • Cloudflare account with active zone on Pro, Business, or Enterprise tier supporting GraphQL Firewall Events Analytics.
  • Cloudflare API Token with Zone.Analytics:Read and Zone.Zone:Read permissions.
  • Slack Incoming Webhook URL configured for incident escalation.

Secrets

  • CLOUDFLARE_API_TOKEN: Cloudflare API token used to query the GraphQL Analytics endpoint.
  • SLACK_WEBHOOK_URL: Slack Incoming Webhook URL for security incident notifications.
  • CLOUDFLARE_WAF_WEBHOOK_KEY: Authentication key for inbound webhook triggers.

Quick start

  1. Store your Cloudflare API token in Kestra secrets under CLOUDFLARE_API_TOKEN.
  2. Store your Slack Incoming Webhook URL under SLACK_WEBHOOK_URL.
  3. Import this blueprint into your Kestra instance in namespace company.security.
  4. Run a manual execution with your Cloudflare Zone ID to baseline current traffic and establish initial KV records.
  5. Enable the periodic_waf_audit schedule trigger to run automated surveillance every 5 minutes.

Common pitfalls and troubleshooting

  • Adaptive Sampling Estimates: High-volume DDoS floods utilize Cloudflare adaptive sampling; counts represent statistically accurate aggregations rather than raw request counts.
  • API Token Scope: Ensure the API token has Analytics:Read permissions at the zone level; account-scoped tokens without zone assignment will return HTTP 403 Forbidden.
  • Low Baseline False Positives: On newly created domains with near-zero traffic, a sudden jump from 0 to 10 blocks represents an infinite mathematical percentage spike. Use min_block_count_for_spike (default: 50) to prevent alerts on non-threatening bursts.

How to extend

  • Automated Rule Disabling: Integrate an io.kestra.plugin.cloudflare.waf or HTTP PUT task to automatically toggle a misconfigured custom rule to log mode if false positive criteria are met.
  • PagerDuty Escalation: Add io.kestra.plugin.pagerduty.IncidentCreate to page the on-call SecOps engineer for critical severity attacks.
  • IP Reputation Enrichment: Connect an AbuseIPDB or VirusTotal lookup task to enrich top attacking ASNs and client IPs before dispatching Slack notifications.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.