Most Cloudflare deployments are configured for browsers. A SaaS app’s most important traffic comes from code. The first five changes close the gaps that hurt API-driven apps most. The next five are the baseline every zone should have. The last section covers geo controls, which are a business decision as much as a security one.
Almost everything here is done in the Cloudflare dashboard. No Cloudflare CLI is needed. The commands are for verification, plus two optional origin tasks. The one real prerequisite: the zone is active on Cloudflare’s nameservers and the app records are proxied. If traffic doesn’t pass through Cloudflare, nothing below applies.
# macOS brew install jq # Ubuntu / WSL sudo apt install -y curl jq dnsutils openssl
Replace the highlighted values with ours.
export CF_API_TOKEN="your-scoped-api-token" export ZONE_ID="your-zone-id" export APP_HOST="app.example.com" export API_HOST="api.example.com"
This is the one that turns a performance setting into a data exposure. If a “Cache Everything” rule touches the app, an authenticated JSON response can be cached at the edge and served to a different customer. The fix is an explicit bypass rule, placed last so nothing overrides it.
(http.host eq "api.example.com") or starts_with(http.request.uri.path, "/api/") or any(lower(http.request.headers.names[*])[*] == "authorization") or http.cookie contains "session="
curl -s -o /dev/null -D - -H "Authorization: Bearer $TEST_TOKEN" \ "https://$API_HOST/v1/me" | grep -i cf-cache-status
If the origin answers anyone who knows its IP, every rule on this page is optional for an adversary. SaaS teams often point the API hostname straight at a load balancer “for performance”. Route everything through Cloudflare, then make the origin refuse anything that didn’t come from it. If the origin IP was public before Cloudflare, assume it’s known.
sudo cloudflared service install TUNNEL_TOKEN_FROM_DASHBOARDSG=sg-0123456789abcdef0 for cidr in $(curl -s https://www.cloudflare.com/ips-v4); do aws ec2 authorize-security-group-ingress --group-id "$SG" \ --ip-permissions "IpProtocol=tcp,FromPort=443,ToPort=443,IpRanges=[{CidrIp=$cidr,Description=cloudflare}]" done for cidr in $(curl -s https://www.cloudflare.com/ips-v6); do aws ec2 authorize-security-group-ingress --group-id "$SG" \ --ip-permissions "IpProtocol=tcp,FromPort=443,ToPort=443,Ipv6Ranges=[{CidrIpv6=$cidr,Description=cloudflare}]" done # then close the open door aws ec2 revoke-security-group-ingress --group-id "$SG" --protocol tcp --port 443 --cidr 0.0.0.0/0
# CA file: download from Cloudflare's Authenticated Origin Pulls docs ssl_client_certificate /etc/nginx/certs/authenticated_origin_pull_ca.pem; ssl_verify_client on;
curl -sk -m 10 -o /dev/null -w "%{http_code}\n" \
--resolve "$APP_HOST:443:ORIGIN_IP" "https://$APP_HOST/"
# expect: 000 (blocked) or a TLS error. A 200 means the origin is still open.A customer’s integration script can’t solve a challenge. Bot Fight Mode applied to API paths breaks integrations and webhooks, and the support tickets arrive before anyone connects the cause. Skip bot checks for authenticated API calls and known webhook paths. Keep them on login, signup and password reset, where credential stuffing happens. The skip only removes bot checks. The app still rejects invalid tokens, and rate limiting in change 4 still applies.
(starts_with(http.request.uri.path, "/api/")
and any(lower(http.request.headers.names[*])[*] == "authorization"))
or http.request.uri.path in {"/webhooks/stripe" "/webhooks/github"}http.request.uri.path in {"/login" "/api/auth/login" "/signup"}
and cf.bot_management.score lt 30
and not cf.bot_management.verified_botIP-based limits fail in both directions. One enterprise customer behind a corporate NAT looks like an attack, and an adversary rotating residential proxies looks like many polite users. Pro and Business count by IP, which is still worth having on auth endpoints. Enterprise Advanced Rate Limiting can count by API key or header, which is what a SaaS API needs. On Pro, the app should enforce its own per-key limits.
authorization (or x-api-key). Set the threshold from real traffic, not a guess. Pull the busiest key’s peak from analytics and add headroom.http.request.method eq "POST"
and http.request.uri.path in {"/login" "/api/auth/login" "/api/auth/password-reset"}http.response.code in {401 403}for i in $(seq 1 15); do
curl -s -o /dev/null -w "%{http_code} " -X POST \
-H "Content-Type: application/json" -d '{}' "https://$APP_HOST/api/auth/login"
done; echo
# expect: the early requests return 4xx from the app, then 429 from CloudflareSchema validation drops any request that doesn’t match our OpenAPI spec before it reaches the app. That stops a whole class of injection and mass-assignment attempts without writing WAF rules by hand. For partner or machine-to-machine integrations, mTLS means a stolen API key alone isn’t enough. The caller also needs the client certificate.
http.host eq "partners-api.example.com"
and not cf.tls_client_auth.cert_verifiedcurl -s -o /dev/null -w "%{http_code}\n" https://partners-api.example.com/v1/health
curl -s -o /dev/null -w "%{http_code}\n" --cert client.pem --key client.key \
https://partners-api.example.com/v1/health“Flexible” mode encrypts traffic to Cloudflare and sends it to the origin in plaintext. The padlock still shows. Full (strict) encrypts both legs and validates the origin certificate. HSTS is worth having, but a mistake persists in browsers for the full max-age, so start short.
openssl s_client -connect "$APP_HOST:443" -tls1_1 </dev/null 2>&1 | grep -iE "alert|no protocols" curl -sI "https://$APP_HOST" | grep -i strict-transport-security
The Cloudflare Managed Ruleset is low-noise and safe to turn on. The OWASP Core Ruleset is noisier, especially against JSON request bodies, so it needs a tuning period. Enterprise can deploy it in Log mode. On Pro and Business, start at the least sensitive settings and tighten from there.
Whoever controls the Cloudflare account controls DNS, certificates and every rule on this page. It deserves the same protection as the AWS root account. The Global API Key grants full access to everything and should not exist in any script.
curl -s https://api.cloudflare.com/client/v4/user/tokens/verify \ -H "Authorization: Bearer $CF_API_TOKEN" | jq '.result.status'
Unproxied records leak origin IPs. Stale CNAMEs pointing at deleted cloud resources invite subdomain takeover. DNSSEC stops spoofed answers, and CAA records limit which certificate authorities can issue for our domain.
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?per_page=500" \ -H "Authorization: Bearer $CF_API_TOKEN" \ | jq -r '.result[] | select(.proxied==false) | "\(.type)\t\(.name)\t\(.content)"'
dig +short DS example.com dig +short CAA example.com
The dashboard keeps security events for a short window. Incident questions tend to arrive weeks later. Logpush sends HTTP and firewall events to our SIEM or S3, which also becomes SOC 2 evidence instead of screenshots. Without Enterprise, alerts are the minimum.
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/logpush/jobs" \
-H "Authorization: Bearer $CF_API_TOKEN" | jq '.result[] | {name, dataset, enabled}'Geo rules cut background noise from opportunistic scanning and credential stuffing. They are not a strong control on their own, because any VPN or residential proxy gets around them. They do have a real business cost: a block list can quietly lock out a customer, a contractor or our own support vendor. So we check traffic before we block. The challenge rule must exclude API and webhook paths, for the same reason as change 3: code can’t solve a challenge.
T1 is Cloudflare’s code for Tor exit nodes.and not ip.src in $partner_ips to both rules.ip.src.country in {"RU" "BR" "CN" "KP" "IR" "NG" "RO" "SY" "SD" "UA" "IN" "T1"}ip.src.continent ne "NA" and http.host ne "api.example.com" and not starts_with(http.request.uri.path, "/api/") and not http.request.uri.path in {"/webhooks/stripe" "/webhooks/github"} and not cf.client.bot
The block expression is the same list written as one set. It’s easier to maintain, and ip.src.country replaces the older ip.geoip.country field. The original form still works if pasted as written.
curl -sI "https://$APP_HOST/" | grep -i cf-mitigated # expect: cf-mitigated: challenge curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $TEST_TOKEN" "https://$API_HOST/v1/me" # expect: 200. A 403 means the API exclusion is missing.