Back to Terraform

Rulesets and WAF: Phases, Expressions and Security Policy Ownership

November 6, 2026 Wasil Zafar 32 min read

Configure ordered security behavior while keeping one authoritative owner for each shared ruleset

Table of Contents

  1. Follow a Request Through Ruleset Phases
  2. Give Each Ruleset Collection One Terraform Owner
  3. Compose Custom Rules, Managed Rules and Overrides
  4. Treat Rate Limiting, DDoS and Bot Settings as Distinct Controls
  5. Test the Allow Path as Carefully as the Block Path

Follow a Request Through Ruleset Phases

The custom ruleset was correct, reviewed, and completely inert.

It had the right expression, the right action and a test that passed against the API. It also had no effect on a single request, because nothing executed it. The rules existed in a container that no phase entry point called. That is the first distinction worth holding onto: a ruleset is an object, and a phase is a schedule. Creating the object does not put it on the schedule.

A phase is a stage in the request's life, not a product. Cloudflare fixes the phase names and their order; you cannot add a phase or move one. You can only write rules into a phase's entry point. Phases exist at two scopes, account and zone, and for the same phase the account rules run first. Account-level phases are currently an Enterprise capability, which is why an account rule can look deployed and still cover nothing on a lower plan.

Each phase has at most one entry point per scope. That entry point is an ordered list. Its rules can act directly, or they can execute another ruleset that belongs to the same phase. The entry point is the only write surface for the phase; a custom ruleset without an execute rule is storage, not policy. This single sentence explains most "the rule is there but it never fires" tickets.

The security sequence is shorter than the full phase list. The request passes through redirect, sanitize, transform, configuration and origin phases before the WAF work begins. The controls this article owns then run in a fixed order:

  1. HTTP DDoS mitigation, which is always on and configured separately.
  2. Custom rules in http_request_firewall_custom.
  3. Rate limiting rules in http_ratelimit, which must sit at the end of that phase's list.
  4. Managed rules in http_request_firewall_managed.
  5. Bot fight mode evaluation in http_request_sbfm, driven by settings rather than a ruleset you own.
  6. Cache settings, then the origin.

Terminating actions end the journey. Block, redirect and the challenge actions stop evaluation, so later rules and later phases never see the request. Non-terminating actions such as log can be overwritten by later rules in the same phase, and the last change wins. This is why "allow" is a dangerous word in a review: a skip rule removes selected products from evaluation, but it is not a blanket permission for the request.

Field values freeze inside a phase. A URL rewrite changes what later phases see, but two rules in the same phase observe the same values. If a later rule needs the original URI, it has to read a raw field. The distinction matters when a redirect rule and a WAF rule appear to disagree about the path; neither is wrong, they are looking at different snapshots.

Cloudflare security evaluation
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    REQ["Client request
reaches the edge"] --> P1["Redirect, sanitize
and transform phases"] P1 --> P2["Configuration and
origin phases"] P2 --> C["http_request_firewall_custom
ordered custom rules"] C -->|"no terminating match"| R["http_ratelimit
rate rules at the end"] R -->|"within limit"| M["http_request_firewall_managed
execute managed rulesets"] M -->|"no managed action"| S["http_request_sbfm
evaluated from settings"] S --> CA["http_request_cache_settings"] CA --> O["Origin"] C -->|"block, challenge or redirect"| X["Response returned
later phases skipped"] R -->|"over limit"| X M -->|"managed block"| X DD["ddos_l7 entry point
configuration only"] -.->|"tunes"| DP["DDoS mitigation
always on"] DP -.->|"attack traffic removed
before WAF rules"| C BM["Bot Management settings
score and detections"] -.->|"inputs for custom rules"| C classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class REQ,P1,P2 primary; class C,R,M secondary; class CA,O ok; class X danger; class DD,DP,BM,S warn;

Scope is part of the address. A rule that blocks a path in one zone does not exist at the account, and an account rule that omits the Enterprise plan guard can match nothing at all. Account-level WAF also needs its own add-on. A clean apply proves the API accepted the document, not that the edge will evaluate it for the zone in front of you.

An account rule can shadow a zone rule. Because account rules run first, an account block never reaches the zone's exception. If the zone owner cannot see the account collection, a change that looks safe in the zone has an invisible upstream dependency. Ownership has to cross the scope boundary, not stop at it.

Account and zone entry points in the Cloudflare ruleset pipeline The account scope holds an Enterprise-only entry point evaluated before the zone for the same phase. The zone scope holds one entry point for each phase. A custom ruleset only runs when an execute rule in the matching phase calls it, while a managed ruleset is Cloudflare-owned and versioned. A terminating action returns a response before later phases run. The ddos_l7 entry point configures the always-on DDoS system rather than adding a request step. One entry point per phase, one owner per collection The account scope is evaluated first. The zone scope is where most teams actually write policy. Account scope Enterprise phases only account entry point kind = root Runs before the zone entry point for the same phase. Account WAF needs its add-on and a plan guard in the execute expression, or it covers nothing. One entry point per phase. There is no second write surface. Zone scope One entry point for each phase custom rules http_request_firewall_custom rate limiting http_ratelimit managed rules http_request_firewall_managed bot fight mode http_request_sbfm cache http_request_cache_settings custom ruleset: kind = custom Runs only when an execute rule calls it. managed ruleset Cloudflare-owned and versioned. one ordered rules list A ref per rule keeps identity stable. Order is part of the policy. terminating action Returns now. Later phases do not run. ddos_l7 is a configuration surface, not a request step. It tunes the always-on DDoS system.

The response path has its own phases. Sensitive data detection runs in a response firewall phase, and rate limiting can use response fields in a later pass. A control that must inspect what the origin returned cannot be tested by looking only at the request pipeline. Read the phase list as two timelines, request and response, joined at the origin.

ddos_l7 is a configuration desk, not a checkpoint. The phase name appears in the list, but its rules do not execute as a request step; they tune the always-on DDoS system. Super Bot Fight Mode has a similar boundary: its rules are no longer supported through the Rulesets API. Managing either one as if it were an ordinary WAF phase produces a document that looks deployed and behaves differently.

Versioning is part of the audit trail. Every ruleset modification creates a new version, and more than one version can be in use at the same time. When a deployment selects a ruleset by ID, it normally selects the latest version. That is convenient, and it is also why a managed override can change behavior without a Terraform diff: Cloudflare published a new version underneath your execute rule.

The phase map is stable; the ownership map is not. A request follows the same order in every zone. What changes between teams is who writes each entry point, and that is where the next section begins. Most WAF incidents are ownership incidents wearing an expression costume.

Last apply wins is not a merge

Two roots writing one phase collection both produce valid plans and neither sees the other. The API replaces the whole ordered list, so the later apply silently deletes the earlier policy. Assign one Terraform address per scope and phase before writing any rules.

Give Each Ruleset Collection One Terraform Owner

Two pull requests added two rules to the same phase. Each lived in its own root, each plan was green, and each author had a screenshot proving the rule existed. They applied eleven minutes apart. The second apply removed the first rule, because both roots were writing the same collection and neither knew the other existed.

The Terraform resource is the collection. A cloudflare_ruleset maps to one ruleset, and its rules are a complete ordered list. The provider sends that list as the new definition; the API does not merge it with rules someone added in the dashboard. A resource that owns a phase entry point owns every rule in that entry point, including the rules it has never seen.

In provider 5.28.1 the list is an attribute. With Terraform 1.17.1 and that provider release, the current schema takes a list of objects. Older examples still show repeated rule blocks, which was the v4 shape. Mixing the two shapes fails at plan time. That failure is the good outcome. The bad outcome is a half-migrated root where one stale resource and one new resource both claim the same phase.

One collection, one address. Write the ownership map as scope plus phase, then map the entry point for each pair to exactly one Terraform address. If two addresses claim the same pair, both plans remain valid and the last apply wins. Terraform cannot detect the conflict, because each root has its own state and neither state records the other's rules.

A custom ruleset is a second collection in the same phase. Its address is separate from the entry point's address, and the execute rule is the only link between them. Both need owners: the entry point owner decides whether the custom ruleset runs, and the custom ruleset owner decides what it contains.

Split by phase and scope, not by team. A platform team and an application team can both contribute security intent without both owning one collection: the application team supplies expressions, the platform team owns the ordered list. Different phases are a legitimate split, because custom rules, rate limiting and managed rules are separate collections. Two team roots writing the same entry point are not a split; they are a race.

Refs make rule identity stable. Every rule should carry a unique ref. The provider matches rules by that value; without it, an edit can delete a rule and create a new one with a new ID. Rule IDs are what log fields, dashboards, exception rules and incident notes point at, so churn is not cosmetic. Changing the ref is also a create, so choose refs as names: once, deliberately, and then leave them alone.

The default ref is the rule ID. Imported configuration often arrives that way. It preserves the current identity, but it makes the ref unreadable and easy to regenerate by accident. cf-terraforming emits refs equal to rule IDs; renaming one later creates a new rule. If a rename is worth doing, do it as a reviewed change and update the override and log references in the same window.

Import the whole collection. Import targets the ruleset, not a rule inside it. If two resources already exist for one phase, importing does not resolve the conflict: one resource must leave state and configuration before the survivor can own the list. Import the entire collection first, then reconcile its rules in one plan. A partial import is how teams end up with two owners and a state file that looks innocent.

Deleting the resource deletes the policy. Removing a phase entry point can remove every rule in that entry point, including rules nobody intended to touch. prevent_destroy is a useful brake for production collections, but it only stops Terraform from deleting the resource it knows about. It does not stop a second owner from overwriting the rules. Ownership is the control; the lifecycle setting is the seatbelt.

Read the plan as a policy diff. Look for the collection address, the rule count, the order, every ref and every enabled flag. A plan that proposes to replace the ruleset is a change of identity, not an edit. A plan that shows rules disappearing is an ownership collision until proven otherwise. The reviewer should be able to say which rule moved, which rule changed action, and which rule is new.

Collisions announce themselves indirectly. A ruleset version can increment without a Terraform apply, a plan can propose adding rules that already exist, and Security Events can name a rule ID that no current configuration declares. Any one of those is evidence of a second writer, even when no plan failed.

Give Each Ruleset Collection One Terraform Owner
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Inventory: scope + phase
account or zone"] --> B{"How many Terraform
addresses own it?"} B -->|"exactly one"| C["cloudflare_ruleset
full ordered rules list"] B -->|"two or more"| D["Each address writes
the full list"] C --> E["terraform plan
diff by rule ref"] D --> F["Apply order decides
which rules survive"] F --> G["Missing controls
and dead rule IDs"] E --> H{"Every rule has
a unique ref?"} H -->|"yes"| I["Apply preserves
rule IDs"] H -->|"no"| J["Provider may delete
and recreate rules"] J --> K["Overrides and alerts
reference old IDs"] I --> L["One state address
one audit trail"] G --> M["Rollback is a new
reviewed change"] K --> M classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,B primary; class C,E secondary; class D,F danger; class G,J,K,M warn; class H,I,L ok;

Name and kind are identity, not settings. The API treats the ruleset name and kind as immutable, and a different phase means a different collection even if the rules are copied across. That is a safe operation only when the old collection is deliberately retired; otherwise the plan is proposing to leave one policy and create another under the same review comment.

A module is a contract, not a second owner. A thin module that accepts the full ordered list can centralize validation, naming and ref conventions. It cannot make two instantiations safe for one phase. If the module is called twice with the same scope and phase, the second call is the second owner. Enforce the pair as an input constraint, or let the module own the list and accept rule objects as values.

Compose Custom Rules, Managed Rules and Overrides

Custom rules express intent you own. They run in the custom phase, in order, and stop at the first terminating match. Their budget is plan-dependent, from a handful of rules on the free tier to four figures on Enterprise, so a phase inventory is also a capacity plan. Log actions and regex support are plan-gated as well; an expression that works in staging can be rejected in production for reasons that have nothing to do with its logic.

Write expressions as tests, then read them aloud. A few shapes cover most production rules:

  • http.request.uri.path eq "/login" and http.request.method eq "POST" scopes a credential-stuffing rule to one endpoint and one method.
  • ip.src in $office_ips references a named list instead of a pasted range that will drift.
  • not cf.bot_management.verified_bot and cf.bot_management.score lt 30 targets likely automation while sparing verified crawlers.

Check the operators rather than guessing: equality is exact, containment is a substring test, and pattern matching needs regex support. Membership uses in, with sets or named lists. Parenthesize mixed boolean expressions; the language has a precedence order, but a reviewer should not need to reconstruct it from memory.

Path, query and host are different fields. The path field excludes the query string, the query field is separate, and the host field is the authority. A rule that means "the login page with a redirect parameter" needs more than path equality. Missing headers and empty headers also land in different rate-limit counters, so a presence check belongs in the expression rather than in a comment.

Actions are not interchangeable. Block returns a response and stops evaluation; a custom block response must use a 4xx status. Challenge actions present an interstitial and are usually the safer first enforcement for traffic you do not yet trust. Log records a match without stopping it and is not available on every plan. Skip removes selected products or rules from evaluation, and it is not an allow rule for the whole request.

Lists are shared references, not policy. A list holds items of one kind, and rules reference it by name with the in operator. That indirection is useful: an address can be added once for several rules. It is also a blast radius. Editing the list changes every rule that uses it, and deleting it breaks the expressions that reference it. Give lists their own owner, and review a list change as a policy change rather than a data refresh.

Managed rules are coverage you rent. An execute rule in the managed phase points at a Cloudflare-owned ruleset by ID. The Cloudflare Managed Ruleset and the OWASP Core Ruleset are the two usual targets. Their IDs are documented and discoverable, but they should come from the API or a data source, not from a tutorial that was accurate two years ago. Scope the execute rule deliberately: true means every request at that scope.

Overrides are where rented policy becomes yours. Precedence runs from specific to general: rule overrides beat category or tag overrides, which beat ruleset-wide overrides. An override can change the action or the enabled state, and some products allow a score threshold or a sensitivity level. The trap is durability: ruleset and category overrides apply to future rules in the managed ruleset too. If a decision must not drift when Cloudflare ships new signatures, pin it with a rule override.

Composition is not inheritance. A custom ruleset does not inherit the expression of the execute rule that calls it. The execute rule decides whether the whole ruleset runs; each rule inside still evaluates its own expression. Review both layers, or a broad execute expression will quietly widen a rule that looked narrow in isolation.

Overrides outlive the signature

A ruleset-wide or category override keeps applying to rules Cloudflare adds later, so protected behavior can change without a Terraform diff. Pin decisions that must not drift to a specific rule override, and review the execute scope and the inner expressions together.

Custom rulesets consume the same budget. A zone can hold only a small number of custom rulesets, and their rules count against the phase maximum. Creating one for every team looks tidy and runs out of room. Prefer one readable custom ruleset with clear refs over several that each hold a single expression.

Exceptions are rules, and order is their whole point. A skip rule must appear before the execute rule it is meant to pre-empt. Skip the whole managed ruleset by ID, or skip individual rules with the map keyed by ruleset ID. The narrower form is usually the right one: a path that breaks on one signature should not lose the entire managed ruleset. A skip rule with a clear ref is also easier to find in Security Events during an incident.

Payload logging is a data decision. Matched-data logging encrypts request payloads with a public key you supply. The private key does not belong in Terraform, and the payload does not belong in state or in a broad log sink. If the team cannot name the retention period and the readers, the feature is not ready, regardless of how useful the detection would be.

Account scope raises the stakes. Account-level managed rules apply across zones and require the Enterprise add-on plus a plan guard in the expression. Enabling every managed rule at account scope is specifically discouraged: rules disabled by default are disabled for false-positive reasons, and one override can change every Enterprise zone at once. A zone-level deployment with a narrow expression is usually the better first move.

Treat Rate Limiting, DDoS and Bot Settings as Distinct Controls

Three products answer three different questions. Rate limiting asks how often one client repeats an action. DDoS protection asks whether aggregate traffic looks like an attack. Bot management asks whether a request looks automated. None of them answers another's question, and a plan that funds only one leaves the other two gaps open.

Three questions, three controls

Rate limiting counts repetition, DDoS reads aggregate volume, and bot management scores automation. Each one is blind to the other two questions, so map every exposed path to the control that actually answers its threat before tuning thresholds.

ControlTerraform surfacePhase and scopeEntitlement to checkHarmless test
Custom rulescloudflare_ruleset, entry point or custom rulesethttp_request_firewall_custom; zone, or account rulesets on EnterpriseRule count (5 / 20 / 100 / 1,000), log action and regex by planProbe path returns the configured 4xx; a normal page still returns 2xx
Managed rulescloudflare_ruleset with an execute rulehttp_request_firewall_managed; zone or accountManaged ruleset availability; account WAF needs the Enterprise add-on and a plan guardOverride to log, request the probe, confirm the managed rule ref in events
Rate limitingcloudflare_ruleset plus the ratelimit blockhttp_ratelimit; zone, account ruleset on EnterprisePeriod, characteristics and mitigation options; challenge duration rulesLow threshold on a probe path, a handful of requests, record the 429 or challenge
HTTP DDoScloudflare_ruleset plus overridesddos_l7; zone, with ddos_l4 at account scopeAlways-on ruleset; override ability and sensitivity options by planStage a log override, read Security Events, then restore the action
Bot Managementcloudflare_bot_management plus a custom ruleZone settings; the score is read in the custom phaseEnterprise add-on; Super Bot Fight Mode is not managed through the Rulesets APILog-only rule on the score; a confirmed verified bot is still allowed

Rate limiting counts; it does not absorb. A rate rule increments a counter for a set of characteristics and acts when the threshold is crossed. The data-center characteristic is mandatory, so counters are per location; a threshold is not a global quota, and a distributed client can stay under it in every location. Rules must sit at the end of the rate-limit list, and the action can block, challenge or log.

The rate-limit parameters have plan-shaped edges. Period, characteristics and mitigation duration vary by plan. Below Enterprise, challenge actions use request throttling, which means the duration must be zero; block throttling is an Enterprise capability. The legacy rate-limit resource is deprecated, so a new rule belongs in the rate-limit phase, not in the old resource.

Read the cached-asset switch backwards. The API field means "count only requests that reach the origin", which is the opposite of the dashboard label. If the rule expression uses a custom list, cached assets must be included, so the field has to be false. Getting this wrong makes a rule look quieter than it is, especially on a site with a high cache hit ratio.

Order changes what gets counted. Custom rules run before rate limiting, so a custom block prevents the rate-limit counter from incrementing. If the goal is to measure a pattern before enforcing it, log in the custom phase and let rate limiting do the counting. Two controls observing the same request can disagree about whether it ever arrived.

DDoS protection is always on; the phase only tunes it. The HTTP DDoS managed ruleset is enabled whether or not a Terraform resource exists. A ddos_l7 entry point writes overrides: an action, a sensitivity level, or rule-specific changes. The managed ruleset keeps working without you; the resource changes how aggressively it works, and that difference is the whole safety story.

Order is part of a DDoS override. During an attack, Cloudflare evaluates the override rules and applies the first one whose expression and sensitivity both match. A lower-sensitivity block rule placed after a higher-sensitivity log rule never runs. Changing an action from block to log is therefore a policy change that can open a path, not a cosmetic edit, and reordering such rules deserves the same review as changing an expression.

Read-only rules ignore overrides. Some managed rules cannot be tuned, and an override aimed at one has no effect. That is not a failed apply; it is the product boundary. Check the read-back rather than assuming every ID in the ruleset is adjustable, and do not treat a successful apply as evidence that the sensitivity changed.

A managed ruleset update is an upstream change. Cloudflare can publish a new version with new signatures between two Terraform runs. The execute rule still points at the same ID, so the diff is empty while behavior moves. Watch the ruleset version in read-back and treat a version jump as a policy event.

Bot Management produces a signal, not a decision. It scores requests and exposes detections, but it does not block on its own. The decision belongs in a custom rule that reads the score, usually with verified-bot and static-resource exceptions. The add-on is Enterprise, so a rule that references the score is meaningless without the entitlement, even if the expression validates.

Super Bot Fight Mode is settings-owned. Its phase still appears in the request path, but Cloudflare no longer supports changing its rules through the Rulesets API. Use the bot management settings resource, and expect dashboard changes to show up as drift. Do not model it as a normal ruleset collection; the collection is not the control surface.

Entitlements deserve a read-back test. A plan can be structurally valid while the account lacks the product, the phase or the rule budget. After apply, read the object back and send one harmless request through the intended path. A successful apply proves the API accepted a document; it does not prove the edge enforces it.

Rate limiting, DDoS protection and bot management cover different failure modes Rate limiting counts repeats per client and per data center and acts only after a threshold, so it cannot absorb a volumetric flood. DDoS protection is always on and tuned through the ddos_l7 entry point, but it does not encode application intent and cannot identify a slow credential-stuffing attempt. Bot Management produces a score and blocks nothing by itself, so scrapers pass unless a custom rule acts on the score. A single funded control leaves the other two gaps open. Three controls, three failure modes Each column answers a different question. Funding one does not cover the other two. Rate limiting counts repeats per client and per data center acts only after a threshold cannot absorb a flood test: low threshold, few requests on a path you control DDoS protection always on, tuned by overrides acts on attack patterns does not encode app intent ddos_l7 is configuration only test: log override, read events then restore the action Bot Management scores each request 1-99 blocks nothing by itself needs a custom rule to act Enterprise add-on test: log the score, allow a verified bot Failure path: one control funded, the other two assumed A per-client limit cannot absorb a volumetric flood. DDoS mitigation does not know which login attempt is legitimate. Neither stops scrapers without a bot-score rule, and a bot score cannot authorize a user.

Test the Allow Path as Carefully as the Block Path

Every security rule has two outcomes. One is the request it stops; the other is the request it should not have stopped. The block path is easy to demonstrate and easy to over-test. The allow path is where revenue, support tickets and trust live, and it needs the same evidence.

A block is half the evidence

A 403 proves something stopped the request, not that the intended rule did it or that legitimate clients still pass. Pair every block probe with a browser, an API client, a webhook and a verified crawler, then name the rule ID and ray ID in the record.

Use a probe you control. A dedicated path or header that only your test sends is enough to prove a block. It is harmless, repeatable and does not resemble an attack. For the allow path, replay the real client shapes: a browser navigation, an API call with its key, a webhook delivery, and a verified crawler if the site depends on one. A control that blocks all four is not strict; it is broken.

Stage in log mode where the product allows it. Managed rules and DDoS overrides can run with a log action, which records what would have been blocked without blocking it. Rate limiting can start with a generous threshold or a challenge instead of a block. The first deployment is a measurement, not an enforcement ceremony, and a measurement that produces no false positives is a result worth recording.

Ordering needs its own test. Put a skip or exception above a block rule, send the probe, and confirm the request passes. Move the exception below the block and confirm it no longer does. That pair of requests proves the order, which is the part reviewers cannot see from a single expression. It also catches the common mistake of adding an exception after the rule it was meant to pre-empt.

Evidence must name the rule. A 403 proves something blocked the request; it does not prove which control did it. Record the ray ID, the timestamp, the phase, the rule ID and description from Security Events, and the ruleset version from the API read-back. If the event names a different rule than the one under review, the test failed even if the status code matched.

False positives need an owner and a switch. Decide in advance who can disable a rule, which ref they disable, and what "disable" means. Setting enabled to false is reversible and keeps the expression; deleting the rule is a policy change with its own review. The incident record should say which one happened, who approved it, and when the rule will be re-tested.

API clients need their own allow path. A managed challenge that a browser solves is a hard failure for a payment webhook or a mobile client that cannot render a page. Test the machine clients separately, and consider a narrow skip for a verified key rather than a blanket challenge on the path. The allow path is not one request; it is one request per client contract.

Re-test after every collection change. A ref rename, a reorder, a new override or a managed ruleset update can change behavior without changing the expression under review. The regression suite is small: one intended block, one intended allow, one exception path and one rate-limit threshold. Run it against the phase collection that changed, not the whole edge.

Do not test on traffic you do not own. A sandbox zone or a probe path you control is the default. Testing against production needs explicit authorization, a rollback that someone else can execute, and a window that is short enough to watch.

The exit criterion is boring. The intended block returns the intended status, the legitimate clients still succeed, the exception still passes, and the plan after cleanup is empty. Anything more elaborate is a penetration test, which is a different exercise with different authorization and a different scope.

Lab

Review an ordered WAF policy

Execution status: design-only. The steps are written for a disposable zone you own; no API token, zone or request was used to produce this article. Every identifier below is illustrative.

Prerequisites. Terraform CLI 1.17.1, Cloudflare provider 5.28.1, a disposable zone or an isolated path, read access to Security Events, and a terminal with curl.

Minimal setup. Create labs/cf04/ with three records: a phase inventory, an ordered rule table, and an evidence log. The inventory is the artifact that prevents the ownership failure.

RecordWhat it holds
phases.mdOne row per scope and phase: zone, phase, Terraform address, owner, rule count
order.mdPosition, ref, expression, action, and the neighbor each rule must precede
evidence.mdRequest, expected decision, observed status, ray ID, rule ref, timestamp
  1. Inventory every scope and phase you can see. Mark any pair with two Terraform addresses as a finding, not a detail. Include phases that have no resource yet, because an empty phase is still a collection someone will claim later.
  2. Pick one collection. Import it whole or create it in the sandbox, then record the ruleset ID and every rule ref before editing. If a rule has no ref, add one in a separate reviewed change first.
  3. Freeze the intended order in order.md: position, ref, expression, action, and the neighbor it must precede. An order with no stated reason is not reviewable.
  4. Add one probe rule to the custom phase. Use the expression http.request.uri.path eq "/__waf_probe", a block action with a 403 response, and the ref lab_probe_block. Place it after any exception that must win.
  5. Plan and apply to the disposable zone. Read the plan for rule count, order and refs. A replacement of the collection is a stop sign; an update that preserves every ref is the expected shape.
  6. Request the probe path and a normal page from the same client. Record the status, the ray ID, and the rule ID and description shown in Security Events. The status alone is not evidence.
  7. Repeat the allow path with the real client shapes: browser, API key, webhook. A challenge on an API client is a false positive even if a browser would pass, and it belongs in the decision record.
  8. Remove the probe rule and re-plan. The collection should return to its pre-test state with the same refs. If a ref changed, the test changed the policy rather than measuring it.
  9. Write the false-positive card: the ref, the symptom, who may disable it, whether disable or delete is allowed, and the request that proves the re-enable worked.

Expected observation. The probe returns 403 from the named rule, the normal page and each legitimate client keep their previous status, and the cleanup plan is empty. Security Events names the same rule and phase that the order table predicted.

Failure checks. The lab fails if the probe rule fires before an exception, if an edit changes a rule ID, if Security Events names a different rule, or if the allow path was never requested. It also fails if the only evidence is a screenshot of a plan.

Cost dimensions. Zero with plan-only work. A disposable zone adds the domain and any plan the feature requires; no traffic generation is needed.

Cleanup. Remove the probe rule, destroy the lab collection if the exercise created it, and delete the sandbox zone only after its DNS and certificate records are no longer needed.

Evidence to keep. The phase inventory, the ordered rule table, the plan output, the request log with ray IDs, the Security Events export and the false-positive decision record.

The policy is not the configuration file. It is the ordered decisions, the owner who can change them, and the evidence that both outcomes were observed.

Next in the Series

In Cache, Redirect, Transform and Origin Rules as Code, we'll explore Compose traffic rules by phase and prove that caching or rewriting does not expose the wrong response.