| | |

Cloudflare 18 ☁️ Edge Security, WAF & Zero Trust — Configuring WAF rules, DDoS protection, Rate Limiting, and Cloudflare Access for preview protection

⏱️ Estimated read: 30 min | |

The edge is the only place in your architecture that sees every request before your code does. That position is what makes it useful and what makes it dangerous to misconfigure: a rule that is twenty characters too broad blocks real customers, and a rule that is one field too narrow lets an attacker walk past while the dashboard shows green. Cloudflare exposes that position through four distinct mechanisms with four distinct failure modes, and the confusion between them is where most incident postmortems land.

WAF custom rules evaluate an expression you write against the request, in a fixed phase, in order, first terminating match wins. Managed rulesets are the same mechanism with someone else’s expressions, maintained by Cloudflare and by OWASP, that you deploy and tune rather than author. Rate limiting rules count requests matching a characteristic over a window and act when the count crosses a threshold — a different data model from the WAF because the decision depends on history, not on the current request. Cloudflare Access is not a filter at all; it is an authentication gate that terminates the request at the edge and only then proxies it, which is what makes it the correct tool for a preview deployment that must not be public.

The distinction matters because teams reach for the wrong one constantly. A credential-stuffing run against /login is rate limiting, not a WAF rule, because every individual request is well-formed. A path traversal attempt is a WAF rule, not rate limiting, because it happens once. An unprotected staging site holding production data is neither — it is an Access application that nobody created, and no amount of WAF tuning fixes it. And a volumetric flood is none of the above, because it is handled before any of these phases run.

This chapter works through them in the order a request encounters them: the L3/L4 and L7 DDoS layers that run before your rules exist, then the custom and managed WAF rules, then rate limiting with its counting characteristics and its bypass problem, then Access with its policies, service tokens, and JWT verification. The last section ties them together around the case they are most often used for badly: a preview deployment that is one DNS record away from being the breach.

Key point: These are four different tools because they answer four different questions — is this packet flood legitimate, is this request malicious, is this client asking too often, and is this person allowed in at all — and the most common production failure is answering the fourth question with the second tool.


Why it exists

The origin-exposure problem. An origin server with a public IP is reachable by anyone who learns the address, which happens through certificate transparency logs, through a DNS history service, or through an SSRF that returns the response body. The edge is only a defence if the origin is unreachable except through it — a Tunnel, an IP allowlist, or mTLS with an authenticated origin pull certificate. A perfectly tuned WAF in front of an origin that answers on its own IP is a WAF that an attacker routes around in one request.

The pattern-versus-behaviour problem. A WAF rule describes what a request looks like: this path, this header, this country, this user agent. That is the right model for a request that is intrinsically malformed — a ../ in a path segment, a UNION SELECT in a query value, a body that fails a schema. It is the wrong model for a request that is perfectly valid in isolation and hostile in aggregate, which is every credential-stuffing run, every scraping loop, and every enumeration sweep. Those need a counter, and a counter needs a window and a key.

The volumetric problem. A flood of 400 Gbps does not reach the WAF phase. It is dropped upstream by the L3/L4 mitigation, which is always on and unmetered on every plan including Free, and by the L7 HTTP DDoS ruleset, which is a managed ruleset with a sensitivity dial rather than a rule you write. The operational point is that you do not configure DDoS protection so much as you override its defaults when they misfire — and the misfire is usually a legitimate traffic spike being challenged, not an attack being missed.

The staging-data problem. The most common serious finding in a web application assessment is not a clever injection. It is an unauthenticated staging environment containing a production database copy, on a hostname that was never linked from anywhere and was therefore never considered part of the attack surface. Preview deployments make this worse by multiplying the environments: every branch gets a URL, every URL has the same environment variables, and the URL pattern is guessable. Access exists because a hostname that nobody knows about is not a security control.

The authentication-at-the-edge problem. Requiring a login before the origin sees the request means the origin’s own authentication bugs cannot be exploited by an unauthenticated visitor, because the visitor never becomes one. That is a categorically different guarantee from a WAF rule, which is a filter that can be wrong. Access is enforced by the same process that terminates TLS, and the request that does not carry a valid signed assertion is dropped before it is proxied.

The audit problem. When the question is “who accessed the staging site last Tuesday”, the answer needs to come from somewhere that logged the request before it reached the application. Access logs every authentication decision with the identity, the application, the timestamp, and the device posture, which is a compliance answer rather than a debugging one — and it is the reason Access is used on internal tools that have no login of their own.

The trade-off. Every control here narrows something legitimate. A block rule on a path pattern blocks the crawler that indexed you last week. A rate limit keyed on IP punishes a corporate NAT with two thousand users behind one address. A DDoS sensitivity of High challenges the marketing campaign that launched this morning. Access means an identity provider outage is a login outage, and a Service Token is a credential that must be rotated. The design discipline is the same throughout: start in log or challenge mode, measure what it would have done, then tighten — and write down the override that you will need to reverse at 2 a.m.


a. Custom rules, managed rulesets, and the phase order

A custom rule is an expression plus an action, deployed into a phase. The phase determines when it runs, and the order determines what has already happened when it does. Getting this wrong is the difference between a rule that fires and a rule that is never reached.

PHASE ORDER (simplified)

  L3/L4 DDoS mitigation           network layer, before TLS
       │
  L7 HTTP DDoS ruleset            ddos_l7, sensitivity-based
       │
  Custom rules                    http_request_firewall_custom
       │
  Managed rulesets                http_request_firewall_managed
       │
  Rate limiting rules             http_ratelimit
       │
  Origin / Access

The custom ruleset is where your expressions live, and the expression language is a filter over request fields with and, or, not, parentheses, and a set of operators that includes eq, ne, contains, matches, in, and starts_with. An unknown field fails at save time, which is the one kindness the interface offers.

# Block a path traversal attempt before it reaches the origin
(http.request.uri.path contains "../") or (http.request.uri.path contains "%2e%2e")

# Challenge requests carrying a known scanner user agent
(http.user_agent contains "sqlmap") or (http.user_agent contains "nikto")

# Block a country on an admin path, but only outside business hours UTC
(http.request.uri.path matches "^/admin" and ip.geoip.country in {"CN" "RU" "KP"})

# Challenge a high threat score on anything that is not a static asset
(cf.threat_score gt 20 and not http.request.uri.path matches "\\.(css|js|png|woff2)$")

The action set is small and the ordering of preference matters more than the list. Block returns a 403 and ends the request. Managed Challenge runs Cloudflare’s non-interactive challenge first and only falls back to a checkbox if it cannot reach a verdict — it is the correct default because it filters automation without filtering people. JS Challenge and Interactive Challenge are the older, more disruptive forms and are worth reserving for a genuine attack mode. Log records the match and continues, which is what every rule should do for its first week. Skip terminates the current phase and, optionally, skips subsequent components entirely, which is the action that lets a trusted integration through the rules below it.

# The skip that keeps a partner webhook alive
(http.request.uri.path eq "/webhooks/partner"
 and http.request.headers["x-partner-key"] eq "…")

Action: Skip
  Skip: all remaining custom rules
  Also skip: Managed ruleset, Rate limiting rules

That skip is a hole, and it should be treated as one: the header value is a secret, the path is fixed, and the rule is narrow enough that Log mode on it produces a countable number of lines per day. A skip that matches a path alone, without the secret, is a permanent bypass for anyone who reads the source.

Managed rulesets are deployed by attaching them in the http_request_firewall_managed phase, and there are two that matter. The Cloudflare Managed Ruleset covers known CVEs and high-confidence attack signatures and is updated continuously. The OWASP Core Ruleset is the ModSecurity-compatible rule family with a paranoia level that trades false positives for coverage, and its anomaly score threshold is the dial you actually tune. Both support per-rule overrides — disable one rule, change one rule’s action to Log — and the practice that keeps them usable is to deploy at Log first, review the matches against real traffic for a week, then enable with targeted exceptions rather than disabling the whole ruleset.

# The exception that keeps a form working under OWASP
Managed ruleset: OWASP Core Ruleset
  Rule 942100 (SQL injection) → Log for /api/search only
  Everything else → Block, anomaly threshold 40

# The reason: /api/search accepts a query DSL that looks like SQL

Two settings outside the rulesets are worth knowing because they behave differently from rules. The Security Level setting applies a blanket challenge posture and Under Attack Mode challenges every visitor for five seconds — a blunt instrument for the first ten minutes of an attack and a disaster if left on. Bot Fight Mode on the Free plan challenges detected automation, and its defining limitation is that it runs in a phase custom rules cannot skip, so an API client that is legitimately automated will be challenged with no clean bypass. On paid plans, Super Bot Fight Mode can be skipped by a custom rule, which is the reason the two behave nothing alike despite the similar name.


b. Rate limiting — characteristics, counting expressions, and where ip.src fails

A rate limiting rule has four parts: the characteristics that identify a client, the counting expression that decides which requests increment the counter, the threshold and period, and the mitigation that applies when the threshold is crossed.

The characteristics field is the one that decides whether the rule works. ip.src is the obvious choice and it fails in three specific ways: a corporate NAT puts thousands of users behind one address, a mobile carrier rotates addresses mid-session so a single attacker looks like twenty clients, and a distributed run uses a different address per attempt so no single key ever crosses the threshold. The characteristic set is what lets the rule key on something the attacker cannot cheaply rotate.

COMMON CHARACTERISTIC COMBINATIONS

  Public site, login POST    ip.src  +  http.request.uri.path
  API with keys              http.request.headers["x-api-key"]
  Per-account login          http.request.body.raw? no — use path + ip.src,
                             then count per-account in the application
  Scraping on content        ip.src  +  http.host
  Multi-tenant abuse         http.request.headers["x-tenant-id"]

There is a hard limitation worth stating plainly: the rate limiter cannot parse a JSON body, so a login form’s email field is not available as a characteristic. That means the per-account counter — the one that stops credential stuffing against a single user — has to live in the application or in a Worker that reads the body, and the edge rule is the coarse per-IP layer in front of it. Teams that expect the edge to do per-account limiting spend a long time looking for a field that does not exist.

# Coarse per-IP limit on login attempts
Characteristics:  ip.src, http.request.uri.path
Counting:         http.request.method eq "POST"
                  and http.request.uri.path eq "/login"
Period:           1 minute
Threshold:        10 requests
Mitigation:       Block for 10 minutes
Response:         429, JSON body, Retry-After header

The period options are fixed — ten seconds, one minute, two minutes, five minutes, ten minutes, and one hour — and the threshold is a count within that window. The choice is a trade between detection speed and false positives: a one-minute window at ten requests catches a script immediately and also catches a shared office on the morning someone rolls out a password manager. The mitigation timeout should be shorter than the period for anything user-facing, because a ten-minute block on a legitimate user is a support ticket and a one-minute block is an annoyance.

# API limit per key, generous window, no interaction
Characteristics:  http.request.headers["x-api-key"]
Counting:         http.request.method in {"POST" "PUT" "DELETE"}
Period:           1 minute
Threshold:        300
Mitigation:       Managed Challenge for 1 minute

Managed Challenge as the mitigation rather than Block is the right default for anything a browser reaches, because it lets a legitimate user through after a silent check and forces a script to solve something. Block belongs on pure API paths where the client is a program and a 429 with Retry-After is a response it can honour.

The counting expression is evaluated after the custom and managed rules, which has a consequence worth being explicit about: a request blocked by a WAF rule never increments a rate limit counter. That is usually correct — blocked traffic is not load — but it means a rate limit rule cannot be used to measure how much an attacker is sending, because the WAF is dropping it upstream. Watch Log mode on the WAF if you want the volume.

Wrapping this in a Worker is the pattern when the edge characteristics are insufficient, because the Worker sees the body and can key on the account.

// The per-account layer the edge cannot express
export default {
  async fetch(req: Request, env: Env) {
    const { email } = await req.json<{ email: string }>();
    // Hash the account so the limiter key is not a PII value in a log
    const key = `login:${await sha256(email)}`;
    const { success } = await env.LOGIN_LIMITER.limit({ key });
    if (!success) {
      return Response.json({ error: "too_many_attempts" }, { status: 429 });
    }
    return verifyCredentials(email, req, env);
  },
};

The two layers compose: the edge drops the volumetric per-IP run cheaply, and the Worker’s binding counts per account so the attacker cannot rotate addresses to avoid it. Neither alone stops credential stuffing, which is why the pattern is standard.


c. DDoS protection — the always-on layers and the sensitivity override

DDoS mitigation on Cloudflare is not something you enable. The network-layer mitigation is always on, unmetered on every plan including Free, and runs before the request becomes an HTTP transaction. The application-layer mitigation is a managed ruleset — HTTP DDoS attack protection — that is also on by default and that adapts to traffic patterns rather than matching fixed signatures.

HTTP DDoS RULESET: THE ONE DIAL

  Sensitivity          Behavior
  ─────────────────────────────────────────────────────
  High                 challenges early, most false positives
  Medium               the default
  Low                  challenges only on clear signals
  Essentially Off      logs only, useful during a migration

  Action on expression match:  Block / Managed Challenge
                               JS Challenge / Log

The override interface is per-ruleset and per-rule: you can raise or lower the sensitivity for the whole ruleset, change the action, or disable an individual rule. The realistic operational use is narrow. During a migration or a load test, lower the sensitivity or set it to Log so the expected spike does not trigger a challenge. During an active attack, raising it to High is a legitimate response for ten minutes. Leaving it at High permanently means every traffic spike is challenged, and the challenge is served to real users.

The blunt instruments belong here rather than in the WAF section because they are what teams reach for during an attack. Security Level applies a blanket posture to all traffic and Under Attack Mode issues a five-second JS challenge to every visitor. Under Attack Mode works, and it is a terrible user experience that breaks API clients, breaks monitoring, and breaks any integration that does not execute JavaScript. The correct sequence is: raise the DDoS sensitivity, deploy a targeted custom rule in challenge mode, and use Under Attack Mode for the ten minutes when the site is down anyway.

# The targeted rule during an attack, narrow enough to leave alone
(http.request.uri.path eq "/api/search"
 and cf.bot_management.score lt 30
 and http.request.headers["accept"] contains "text/html")

Action: Managed Challenge for 30 minutes

Note the cf.bot_management.score field — it requires Bot Management, which is an Enterprise feature, so the rule above is available only on that plan. On lower plans the equivalent expression uses cf.threat_score or falls back to an IP-based rate limit. Writing a rule against a field the plan does not have is a save-time error, which is at least a fast failure.

The one thing to remember about DDoS is that the control is not where the incidents are. A volumetric flood is visible, mitigated automatically, and resolves in minutes. The attacks that cost money are the ones that look like user traffic: an enumerator walking a sequential id space, a scraper pulling the catalogue, a stuffing run with a thousand addresses. Those pass every DDoS rule and are the reason the next two sections exist.


d. Cloudflare Access — policies, tokens, JWT verification, and preview protection

Access is an identity-aware proxy. The request hits Cloudflare, Cloudflare checks for a signed assertion, and only a request that carries one is proxied to the origin. The origin adds no code for this, which is what makes it usable on a staging site, an admin tool, a Grafana instance, or a preview deployment built by a framework that knows nothing about authentication.

An application is a hostname and optional path pattern plus an audience tag. A policy is a decision — Allow, Block, Bypass, or Service Auth — with a rule that identifies who. The rule selectors that cover most cases are email, email domain, identity provider group, IP range, country, device posture, and service token.

# The typical preview application
Application:  *.preview.example.com
              (wildcard covers every branch alias)
Session:      8 hours
Identity:     GitHub OAuth, restricted to the org

Policy 1 — Allow
  Include:  GitHub org == "acme"  AND  group == "engineering"
Policy 2 — Service Auth
  Include:  Service Token == "ci-smoke-tests"
Policy 3 — Bypass
  Include:  Everyone
  Path:     /health

The Bypass policy on /health is not optional. Access sits in front of the origin for everything else, so a health check that cannot authenticate sees a redirect to a login page and reports the service down. The same reasoning applies to static assets that a login page itself needs — the Access login page is served by Cloudflare, so this is rarely an issue, but an application that loads fonts from its own origin before authentication will need the path excepted.

Service tokens are the machine equivalent of a user, and they are how CI reaches a protected environment. The token is a client id and a client secret, sent as CF-Access-Client-Id and CF-Access-Client-Secret, and the secret is shown once at creation.

# A CI job reaching a preview behind Access
curl -sS "https://pr-142.preview.example.com/health" \
  -H "CF-Access-Client-Id: 6a1f…access" \
  -H "CF-Access-Client-Secret: 8c2e…"

The JWT assertion is the part that matters when the origin needs to know who the user is. Access sets Cf-Access-Jwt-Assertion on the proxied request (and a CF_Authorization cookie in the browser), signed with RS256 against the team’s keys, and the origin verifies it rather than trusting a header name.

import { jwtVerify, createRemoteJWKSet } from "jose";

// The keys rotate; the remote set caches and refetches on an unknown kid
const JWKS = (team: string) =>
  createRemoteJWKSet(new URL(`https://${team}.cloudflareaccess.com/cdn-cgi/access/certs`));

export async function verifyAccess(req: Request, env: Env) {
  const token =
    req.headers.get("Cf-Access-Jwt-Assertion") ??
    req.headers.get("cookie")?.match(/CF_Authorization=([^;]+)/)?.[1];

  // No assertion means the request did not come through Access at all
  if (!token) return null;

  const { payload } = await jwtVerify(token, JWKS(env.TEAM), {
    // Both must be checked; the audience tag is per-application
    issuer: `https://${env.TEAM}.cloudflareaccess.com`,
    audience: env.ACCESS_AUD,
  });

  // payload.email identifies the user; payload.sub is the stable id
  return { email: payload.email as string, sub: payload.sub as string };
}

Verifying the JWT in the origin is what makes Access defence in depth rather than a single gate. A request that reaches the origin some other way — through a leaked internal address, through a misconfigured tunnel route — carries no assertion, and an origin that checks for one rejects it. An origin that only checks whether the request arrived at all does not.

The Tunnel is the other half of the same guarantee. The origin must not have a public address, or Access is advisory. cloudflared opens an outbound connection from the origin to Cloudflare and proxies inbound traffic down it, so there is nothing to scan and nothing to hit directly.

# ~/.cloudflared/config.yml — one hostname, one origin, explicit 404 fallback
tunnel: 6ff42ae2-765d-4adf-8112-31c55c1551ef
credentials-file: /etc/cloudflared/6ff42ae2-765d-4adf-8112-31c55c1551ef.json
ingress:
  - hostname: preview.example.com
    service: http://localhost:3000
  # The catch-all is required; without it the tunnel refuses to start
  - service: http_status:404

Preview deployments are the case worth spelling out because the default is unsafe. A Pages project publishes every branch to <hash>.<project>.pages.dev, and a Workers preview publishes to <version>.<worker>.<subdomain>.workers.dev. Neither hostname is in your zone, so Access cannot be attached to it — a wildcard application requires the hostname to be proxied through Cloudflare on your account. The fix is a custom domain pattern: a wildcard DNS record *.preview.example.com proxied through Cloudflare, a Pages custom domain bound to that pattern, and a wildcard Access application in front. Then a preview is protected by one rule rather than by obscurity.

# The DNS and Access pairing that makes the wildcard work
DNS:      *.preview.example.com   AAAA  100::  (proxied, dummy origin)
Access:   *.preview.example.com
Tunnel:   preview.example.com → localhost:3000

# The 100:: placeholder is the documented discard prefix; with a Tunnel
# the DNS record exists only to make the hostname proxy through the edge.

Two configuration details prevent the common failures. The session duration is per-application and defaults high; an internal admin tool should be hours, and a preview should be short because the environment changes under the user. The identity provider restriction is the one that stops an application being open to anyone with a Google account — an Allow policy with only Emails ending in @example.com and a default One-time PIN login method lets anyone with a matching address request a code, which is a real misconfiguration that has been found in the wild.


Complete Example Session

# ============================================
# PART 1: THE CUSTOM RULESET
# ============================================
# Deploy a custom rule in log mode first; every rule earns its block
curl -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE/rulesets/$CUSTOM_ID" \
  -H "Authorization: Bearer $CF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "rules": [{
      "action": "log",
      "description": "traversal probe",
      "expression": "(http.request.uri.path contains \"../\" or http.request.uri.path contains \"%2e%2e\")",
      "enabled": true
    }]
  }'
# ============================================
# PART 2: THE MANAGED RULESET WITH AN EXCEPTION
# ============================================
# OWASP at paranoia 2, anomaly threshold 40, one path logged not blocked
curl -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE/rulesets/phases/http_request_firewall_managed/entrypoint" \
  -H "Authorization: Bearer $CF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "rules": [{
      "action": "execute",
      "expression": "true",
      "action_parameters": {
        "id": "'"$OWASP_ID"'",
        "overrides": {
          "rules": [{ "id": "942100", "action": "log", "enabled": true }]
        }
      }
    }]
  }'
# ============================================
# PART 3: THE RATE LIMIT RULE
# ============================================
# Per-IP on the login POST; managed challenge so a human can pass
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE/rulesets/$RATELIMIT_ID/rules" \
  -H "Authorization: Bearer $CF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "action": "managed_challenge",
    "description": "login brute force",
    "expression": "(http.request.method eq \"POST\" and http.request.uri.path eq \"/login\")",
    "action_parameters": {
      "characteristics": ["ip.src", "http.request.uri.path"],
      "period": 60,
      "requests_per_period": 10,
      "mitigation_timeout": 60
    }
  }'
# ============================================
# PART 4: THE WORKER LAYER FOR PER-ACCOUNT
# ============================================
// The edge cannot read the body; the Worker can, so it counts per account
const key = `login:${await sha256(email)}`;
const { success } = await env.LOGIN_LIMITER.limit({ key });
if (!success) return Response.json({ error: "too_many_attempts" }, { status: 429 });
# ============================================
# PART 5: THE DDoS OVERRIDE
# ============================================
# Raise sensitivity to High during an attack; revert it after
curl -X PATCH "https://api.cloudflare.com/client/v4/accounts/$ACCT/rulesets/$DDOS_ID" \
  -H "Authorization: Bearer $CF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "rules": [{ "id": "$RULE_ID", "action_parameters": { "sensitivity_level": "high" } }] }'
# ============================================
# PART 6: THE ACCESS APPLICATION
# ============================================
# A wildcard application in front of every preview branch
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$ACCT/access/apps" \
  -H "Authorization: Bearer $CF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Preview deployments",
    "domain": "*.preview.example.com",
    "type": "self_hosted",
    "session_duration": "8h",
    "auto_redirect_to_identity": true,
    "allowed_idps": ["'"$GITHUB_IDP_ID"'"]
  }'
# ============================================
# PART 7: THE POLICIES
# ============================================
# Allow the engineering group, bypass only the health path
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$ACCT/access/apps/$APP_ID/policies" \
  -H "Authorization: Bearer $CF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Engineers",
    "decision": "allow",
    "include": [{ "github": { "identity_provider_id": "'"$GITHUB_IDP_ID"'",
                              "name": "acme/engineering" } }]
  }'

curl -X POST "https://api.cloudflare.com/client/v4/accounts/$ACCT/access/apps/$APP_ID/policies" \
  -H "Authorization: Bearer $CF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Health check",
    "decision": "bypass",
    "include": [{ "everyone": {} }],
    "purpose_justification_required": false,
    "isolation_required": false,
    "path": "/health"
  }'
# ============================================
# PART 8: THE SERVICE TOKEN FOR CI
# ============================================
# The secret is returned once; store it in CI secrets immediately
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$ACCT/access/service_tokens" \
  -H "Authorization: Bearer $CF_TOKEN" \
  -d '{"name":"ci-smoke-tests","duration":"8760h"}'
# ============================================
# PART 9: THE ORIGIN JWT CHECK
# ============================================
const { payload } = await jwtVerify(token, JWKS(env.TEAM), {
  issuer: `https://${env.TEAM}.cloudflareaccess.com`,
  audience: env.ACCESS_AUD,
});
// A request without a valid assertion did not come through Access
# ============================================
# PART 10: THE TUNNEL
# ============================================
ingress:
  - hostname: preview.example.com
    service: http://localhost:3000
  - service: http_status:404

The ten parts covered a custom rule deployed in log mode, a managed ruleset with a path-scoped exception, a per-IP rate limit with a challenge mitigation, the Worker layer that counts per account, a DDoS sensitivity override for the duration of an attack, a wildcard Access application in front of every preview, the two policies that allow engineers and bypass the health check, a CI service token, the origin-side JWT verification that makes Access defence in depth, and the tunnel that removes the origin’s public address.


Quick Reference

The Four Mechanisms

MechanismPhaseDecides OnUnit
DDoS protectionddos_l7, L3/L4Volume and patternSensitivity level
Custom ruleshttp_request_firewall_customThe current requestExpression
Managed rulesetshttp_request_firewall_managedThe current requestRule id + override
Rate limitinghttp_ratelimitHistory of requestsCount per window
AccessBefore the originIdentitySigned assertion

Custom Rule Actions

ActionEffectUse When
block403, terminatesConfirmed malicious pattern
managed_challengeSilent check, fallback to checkboxDefault for browsers
js_challengeExecutes JS, 5 s delayLegacy, heavy attack
interactive_challengePuzzleLegacy, avoid
logRecords, continuesFirst week of any rule
skipEnds phase, optional component skipNarrow, secret-gated

Rate Limiting Characteristics

CharacteristicSurvives Proxy RotationSurvives NAT
ip.srcNoNo
http.request.headers["x-api-key"]YesYes
http.request.headers["x-tenant-id"]YesYes
http.hostYesYes
JSON body fieldNot available—

Access Rule Selectors

SelectorIdentifiesTypical Use
Email / domainUserInternal tools
IdP groupUser, managed centrallyEngineering access
IP rangeNetworkOffice, VPN
Service TokenMachineCI, monitoring
CountryGeographySanctions, travel
Device postureEndpoint healthAdmin consoles
EveryoneAnyBypass on /health

Access Headers and Claims

ItemValue
Cf-Access-Jwt-AssertionRS256 JWT on the proxied request
CF_AuthorizationBrowser cookie with the same JWT
Cf-Access-Client-Id / -SecretService token credentials
isshttps://<team>.cloudflareaccess.com
audPer-application audience tag
JWKShttps://<team>.cloudflareaccess.com/cdn-cgi/access/certs

Best Practices

✅ Do This:

# Deploy every new rule in log mode first
action: log    → review for a week → action: block             # ✅

# Challenge browsers, block programs
action: managed_challenge   on /login                          # ✅

# Key the limiter on something rotation-proof
characteristics: ["http.request.headers[\"x-api-key\"]"]       # ✅

# Count per account where the edge cannot
const key = `login:${await sha256(email)}`;                    # ✅
# Scope a managed-ruleset exception to one path
Rule 942100 → log, for /api/search only                        # ✅

# Bypass only the health path, not a prefix
path: /health                                                  # ✅

# Verify the assertion in the origin
issuer + audience, both checked                                # ✅

# Remove the origin's public address
cloudflared tunnel + proxied DNS only                          # ✅

❌ Don’t Do This:

# A skip that matches a path without a secret
expression: (http.request.uri.path eq "/webhooks")             # ❌

# Under Attack Mode left on overnight
security_level: under_attack                                   # ❌

# DDoS sensitivity pinned to High permanently
sensitivity_level: high                                        # ❌

# A rate limit that only keys on IP
characteristics: ["ip.src"]   on a shared NAT                  # ❌
# Access on a hostname that also answers directly
origin reachable on its own IP                                 # ❌

# Trusting a header name instead of the signed JWT
if (req.headers.get("Cf-Access-Authenticated-User-Email"))    # ❌

# A preview deployment protected by a guessable hostname
<random>.pages.dev, no Access                                  # ❌

# An Allow policy with no IdP restriction
include: everyone + one-time PIN allowed                       # ❌

Common Pitfalls

PitfallWhy It HappensFix
WAF rule never firesRequest blocked by a phase aboveCheck DDoS and custom order
Partner webhook 403sSkip matches path only, no secretAdd the secret header match
Office IP blockedRate limit keyed on ip.srcKey on a header or session
Attacker rotates past the limitSingle IP characteristicAdd account-level layer
Managed ruleset breaks a formOWASP anomaly scorePer-rule exception, scoped path
Health check reports downAccess intercepts /healthBypass policy on that path
Staging site found by a scannerNo Access, guessable hostnameWildcard app + proxied DNS
Origin reachable anywayPublic IP or DNS recordTunnel, or IP allowlist
Access login open to anyoneOne-time PIN allowedRestrict allowed_idps

Real-World Examples

1. Traversal probe

http.request.uri.path contains "../"

2. Scanner user agent

http.user_agent contains "sqlmap"

3. High threat score

cf.threat_score gt 20 and not http.request.uri.path matches "\\.(css|js)$"

4. Narrow skip

path eq "/webhooks/partner" and headers["x-partner-key"] eq "…"

5. Per-key API limit

characteristics: ["http.request.headers[\"x-api-key\"]"]

6. Challenge mitigation

action: managed_challenge, period 60, threshold 10

7. DDoS override

sensitivity_level: high, reverted after the attack

8. Wildcard application

domain: *.preview.example.com, session_duration: 8h

9. Service token in CI

curl -H "CF-Access-Client-Id: …" -H "CF-Access-Client-Secret: …"

10. JWT verification

jwtVerify(token, JWKS, { issuer, audience });

Visual

The Phase Order

┌──────────────────────────────────────────────────────────┐
│  THE PHASES A REQUEST PASSES THROUGH                     │
│                                                          │
│  L3/L4 DDoS      always on, unmetered, before TLS        │
│      │                                                   │
│      ▼                                                   │
│  L7 DDoS         HTTP managed ruleset, sensitivity       │
│      │                                                   │
│      ▼                                                   │
│  Custom rules    your expressions, first match wins      │
│      │                                                   │
│      ▼                                                   │
│  Managed rules   Cloudflare + OWASP rulesets             │
│      │                                                   │
│      ▼                                                   │
│  Rate limiting   counted after the above                 │
│      │                                                   │
│      ▼                                                   │
│  Origin          or Access, if the hostname is protected │
└──────────────────────────────────────────────────────────┘

Which Tool Answers Which Question

┌──────────────────────────────────────────────────────────┐
│  WHICH TOOL ANSWERS WHICH QUESTION                       │
│                                                          │
│  is this flood legitimate?     DDoS sensitivity          │
│  is this request malicious?    custom / managed rule     │
│  is this client too frequent?  rate limiting             │
│  is this person allowed in?    Access                    │
│                                                          │
│  A well-formed request can be                            │
│    - one of ten thousand (rate limit)                    │
│    - from the wrong person (Access)                      │
│    - and completely valid in isolation (neither WAF)     │
└──────────────────────────────────────────────────────────┘

The Rate Limit Key Problem

┌──────────────────────────────────────────────────────────┐
│  THE RATE LIMIT KEY PROBLEM                              │
│                                                          │
│  key = ip.src                                            │
│    10.0.0.1 ──► 2000 office users ──► false positives    │
│    attacker rotates 20 IPs ─────────► never crosses      │
│                                                          │
│  key = header["x-api-key"]                               │
│    per client — survives both                            │
│                                                          │
│  key = hash(email) in a Worker                           │
│    per account — the layer the edge cannot express       │
└──────────────────────────────────────────────────────────┘

Preview Protection

┌──────────────────────────────────────────────────────────┐
│  PREVIEW PROTECTION                                      │
│                                                          │
│  pr-142.pages.dev          no Access — not your zone     │
│        │                                                 │
│        ▼                                                 │
│  *.preview.example.com     proxied DNS + wildcard app    │
│        │                                                 │
│        ▼                                                 │
│  Access check ──► no assertion ──► redirect to IdP       │
│        │                                                 │
│        │ valid assertion                                 │
│        ▼                                                 │
│  Tunnel ──► localhost:3000   origin has no public IP     │
│                                                          │
│  Three things: wildcard app, proxied DNS, no public IP.  │
└──────────────────────────────────────────────────────────┘

Summary

ItemValue
Network DDoSAlways on, unmetered, all plans
HTTP DDoS rulesetddos_l7, sensitivity High/Medium/Low/Off
Custom rules phasehttp_request_firewall_custom
Managed rules phasehttp_request_firewall_managed
Rate limit phasehttp_ratelimit
Default safe actionmanaged_challenge
Rate limit periods10 s, 1 m, 2 m, 5 m, 10 m, 1 h
Counting limitationNo JSON body fields
Access assertion headerCf-Access-Jwt-Assertion
Access JWKShttps://<team>.cloudflareaccess.com/cdn-cgi/access/certs
Origin exposure fixcloudflared tunnel, proxied DNS only

Key takeaways:

  • The four mechanisms answer four different questions and are not interchangeable. A credential-stuffing run is well-formed in every individual request, so no WAF expression catches it and only a counter does. A path traversal happens once, so a counter never fires and only an expression catches it. Choosing the wrong tool is the most common misconfiguration in this chapter.
  • A WAF rule in log mode is not a wasted week. It is the only way to learn what the rule would have blocked before it blocks the wrong thing. Every rule that has ever caused an outage was deployed straight to block.
  • The rate limit key decides whether the rule works. ip.src collides on NAT and rotates under a distributed run. Key on a header the client must hold, and accept that per-account limiting needs the application or a Worker because the edge cannot read a JSON body.
  • DDoS protection is a sensitivity dial, not a ruleset you author. The realistic operations are lowering it for a planned spike and raising it for ten minutes of a real attack. Pinning it to High makes every traffic spike a challenge served to real users.
  • Access is a gate, not a filter. It terminates the request at the edge and only proxies one that carries a valid signed assertion — which means the origin must verify Cf-Access-Jwt-Assertion rather than trust a header name, or Access is a door with no wall behind it.
  • The origin must not have a public address. A tunnel makes Access the only path in; a public IP makes Access a suggestion that an attacker routes around with one DNS lookup. This is the detail that separates a protected staging site from one that appears protected.
  • Wildcard DNS plus a wildcard application is the preview pattern. A *.pages.dev hostname is outside your zone and cannot carry Access at all. A proxied *.preview.example.com can, and one application then covers every branch that will ever be deployed.

Remember: The edge is a sequence of decisions rather than a single firewall, and each decision has a different input. Volume arrives before your rules exist and is handled by sensitivity. Malformed requests are handled by expressions. Repeated legitimate-looking requests are handled by counters. Identity is handled by a signed assertion that the origin must verify. A request can be innocent on all four axes and still be an attack in aggregate, which is why the layers stack rather than replace each other — and the environment that most often skips all four is the preview deployment nobody remembered to protect, holding a copy of the production database behind a hostname that was never linked from anywhere.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!