Chapters

Cloudflare and GCP

Kadé puts Cloudflare in front of its Google Cloud load balancer, for DDoS protection, a web application firewall at the edge, and caching close to shoppers. That adds a second proxy, a second TLS connection, and a second DNS provider. This chapter covers each of those joins, how to make sure Cloudflare is the only way in, and how to read the errors when something between the two breaks.

The front door · chapter 19 of 26 · 12 min read

Two jobs: DNS and proxy

Builds on22. DNS33. Reverse proxies and CDNs

Cloudflare does two separate jobs for Kadé, and most confusion comes from mixing them up:

#JobWhat it meansChapter link
1Authoritative DNS for kade.lkCloudflare answers "what is the IP of api.kade.lk?". This replaces Cloud DNS's public zone8
2Reverse proxy for chosen hostnamesFor "proxied" records, Cloudflare answers with its own IPs, so shoppers connect to Cloudflare, which then connects to the GCP load balancer11, 12
DNS: WHERE IS api.kade.lk?ShopperColombo · 203.0.113.99Cloudflare DNS (authoritative)api.kade.lk → 104.21.48.12 (Cloudflare)For an orange record, the answer is aCloudflare address. The real origin IP34.120.88.10 is never published.TRAFFIC: TWO CONNECTIONS, TWO TLS LEGSShopperbrowser or appCloudflare edgenearest city, e.g. ColomboWAF · DDoS · cacheGCP load balancer34.120.88.10Cloud Armor: origin lockCloud Runkade-apiedge legTLS 1origin legTLS 2Cloudflare ends the shopper's connection and opens its own to GCP: a proxy, as in chapter 11.

Cloudflare is a proxy in exactly the chapter 11 sense: it ends the shopper's connection at its nearest edge location and opens a new one to Kadé's load balancer. Everything else in this chapter follows from that: two TLS connections, a second set of forwarding headers, and the need to stop people going around it.

Moving kade.lk's DNS to Cloudflare

Making Cloudflare authoritative means changing the domain's name servers at the registrar. The order matters, mainly because of DNSSEC (chapter 8 section 09): if the registrar still holds a DS record for Cloud DNS's signing keys when the name servers change, resolvers that check DNSSEC will reject every answer, and the whole domain stops resolving.

Before the switch

  1. 1.Add kade.lk to CloudflareCloudflare scans existing records; compare every record with Cloud DNScheck before moving onrecord lists match
  2. 2.Set records to grey firstEverything DNS only, so the switch changes nobody's path yetcheck before moving onall records grey
  3. 3.Turn off DNSSEC at the old sideRemove the DS record at the .lk registrar; wait for its TTL (often 1-2 days)check before moving onno DS at the registrar

The switch

  1. 4.Change name servers at the registrarPoint kade.lk at the two Cloudflare name serverscheck before moving ondig NS kade.lk shows Cloudflare
  2. 5.Turn on DNSSEC in CloudflareAdd Cloudflare's new DS record at the registrarcheck before moving ondig +dnssec shows the ad flag

After

  1. 6.Set the mode, then go orangeFull (strict) first, then switch kade.lk, www, api to orange one at a timecheck before moving onsite works through Cloudflare
  2. 7.Lock the originCloud Armor allows only Cloudflare + secret header (section 06)check before moving ondirect IP returns 403
  3. 8.Delete the Cloud DNS public zoneOnly after the old name servers have aged out of caches (a few days)check before moving onkade-lk gone; kade-internal kept

Going grey first separates the two risky changes: a DNS provider change (steps 3 to 5) and a traffic path change (step 6). If the site breaks after step 4, it is DNS; after step 6, it is the proxy or TLS mode.

Orange or grey: a choice per record

Every DNS record in Cloudflare has a proxy setting, shown as a cloud icon:

Orange: proxied

Cloudflare answers DNS questions with its own addresses. Visitors connect to Cloudflare, which applies its WAF, DDoS protection and cache, then connects to your origin. The origin's real IP is never published.

Grey: DNS only

Cloudflare is just the DNS server. It answers with the real address in the record, and visitors connect straight to it. No WAF, no cache, no hiding the origin.

Each tab is one of Kadé's records. The "what if" flips api.kade.lk between orange and grey.

What if
THE RECORD IN CLOUDFLAREapi.kade.lkA34.120.88.10proxied (orange)WHAT A VISITOR GETS, AND WHERE THEY CONNECTVisitordig api.kade.lkDNS answer104.21.48.12 (Cloudflare)Cloudflare edgeWAF · DDoS · cacheGCP load balancer34.120.88.10

Protected: every visitor passes Cloudflare; the origin IP stays out of DNS

Cloudflare answers with its own address. The shopper connects to Cloudflare's edge, which applies the WAF and cache, then connects to 34.120.88.10 itself. The origin IP never appears in DNS.

Show as config
api.kade.lk  A  34.120.88.10  proxied (orange)

dig +short api.kade.lk  →  104.21.48.12, 172.67.140.9   (Cloudflare)
grey:                     →  34.120.88.10                 (origin)
#RecordType and valueProxyWhy
1kade.lkA → 34.120.88.10orangeShoppers type the bare domain too. If it were grey, those visits would skip Cloudflare, and the origin lock (section 06) would block them
2www.kade.lkA → 34.120.88.10orangeThe website
3api.kade.lkA → 34.120.88.10orangeThe app and website call it
4status.kade.lkCNAME → a status page providergreyNot Kadé's server; the provider handles its own TLS
5kade.lk MX→ the mail providerDNS onlyMail is not HTTP. MX and TXT records cannot be proxied
6_acme-challenge.kade.lkCNAME → Certificate Manager's DNS authorizationgreyLets Google issue and renew the origin certificate (section 05). A proxied answer would break the check
Cloudflare only proxies HTTP and HTTPS, on ports 80 and 443 and a short list of others (such as 8080 and 8443). Anything else, like SSH or a database, must be grey, which is another reason to keep those off the internet altogether (chapter 6).

Two connections, two TLS legs: the SSL/TLS mode

Builds on25. TLS and certificates

With an orange record there are two separate connections, each with its own TLS: the edge leg (shopper to Cloudflare) and the origin leg (Cloudflare to Kadé's load balancer). Cloudflare's SSL/TLS encryption mode controls only the origin leg. It is the most important single Cloudflare setting, and the names are easy to misread.

VisitorbrowserCloudflare edgeUniversal SSL certGCP load balancerGoogle-managed certHTTPedge legreadable on the wayHTTPorigin legreadable on the way

The SSL/TLS mode only changes the origin leg

Nothing is encrypted anywhere

No TLS on either leg. Only for sites that should not exist.

Show as config
Cloudflare → SSL/TLS → Overview → Encryption mode: Off
Edge leg:   HTTP
Origin leg: HTTP
#ModeOrigin legChecks the origin's certificate?Use
1OffHTTP, and the edge leg is HTTP too-Never
2FlexibleHTTP (unencrypted)-Never for anything real: the padlock is a lie for the second half of the trip
3FullHTTPSno any certificate, even self-signed or expiredA stepping stone only
4Full (strict)HTTPSyes valid, unexpired, matching the hostname, from a trusted CA or Cloudflare's Origin CAKadé's choice
5Strict (SSL-only origin pull)Always HTTPS, as Full (strict), even for visitors who used HTTPyesWhen the origin should never receive plain HTTP

Settings for the edge leg live elsewhere in Cloudflare and are worth turning on together:

#Edge settingWhat it doesKadé's value
1Always Use HTTPSCloudflare itself redirects http:// to https://on
2Minimum TLS versionRefuses older TLS from visitorsTLS 1.2, matching kade-tls on the origin (chapter 12)
3TLS 1.3Allows the newest, fastest handshakeon
4HSTSTells browsers to use HTTPS only, for a set timeon, after HTTPS has worked for a few weeks. Hard to undo: browsers remember it

Certificates on each leg

Each leg needs its own certificate, issued for the same hostnames but by different parties:

#LegCertificateIssued and renewed byCovers
1EdgeUniversal SSLCloudflare, automatically, freekade.lk and one level of subdomains (*.kade.lk). Deeper names like a.b.kade.lk need an Advanced certificate (paid)
2Origin, option AGoogle-managed, DNS authorization (chapter 12)Google, automaticallyTrusted by every browser, so it still works if a record is ever switched to grey
3Origin, option BCloudflare Origin CA certificateCloudflare, free, valid up to 15 years; uploaded to GCP as a self-managed certificateTrusted only by Cloudflare. Fine with Full (strict), but a grey record would show browsers an untrusted certificate
Kadé uses option A: it renews itself, needs only the grey _acme-challenge CNAME, and never breaks if a record changes. The load balancer authorization flavour of Google-managed certificates is the one that fails behind orange records, because the domain no longer points at the load balancer.

Origin lock: making Cloudflare the only way in

Cloudflare protects only traffic that goes through Cloudflare. The load balancer's IP 34.120.88.10 is not secret: it is in old DNS records, in scanners' databases, and anyone can find it. So the origin must refuse anything that did not come through Kadé's own Cloudflare zone. That takes three layers, one for each way around:

#Way aroundLayer that closes itWhere
1Straight to kade-api-xxxx.run.appCloud Run ingress internal-and-cloud-load-balancingChapter 10
2Straight to 34.120.88.10Cloud Armor allows only Cloudflare's IP ranges; default rule denieskade-edge-policy
3Through another Cloudflare account, pointed at Kadé's IPCloud Armor also requires a secret header that only Kadé's zone adds (a Cloudflare Transform Rule)kade-edge-policy

Try each way in, and switch layers off to see which one stops it:

What if
Shoppervia Kadé's Cloudflare zoneGCP load balancerCloud Armor kade-edge-policy2 · source is a Cloudflare IP?allow-list on3 · header x-kade-edge correct?check onCloud Run kade-api1 · ingress: LB onlyonCloudflare edgeadds x-kade-edge

Allowed: the shopper reaches kade-api

The normal path. Kadé's Cloudflare zone adds the secret header, the request comes from a Cloudflare address, so Cloud Armor allows it, and Cloud Run accepts it from the load balancer.

The real client IP, behind two proxies

Builds on33. X-Forwarded-For

Google's front end now sees a Cloudflare edge address as "the client" (chapter 12 section 06, Cloudflare preview). Cloudflare passes the shopper's address in its own headers:

#HeaderContainsKadé's use
1CF-Connecting-IPThe visitor's IP, one value, set by CloudflareThe app's client IP, and Cloud Armor's rate-limit key
2X-Forwarded-ForVisitor, then Cloudflare edge, then load balancer (GCP appends two)Logs only
3CF-IPCountryVisitor's country codeCountry rules in Cloud Armor, instead of origin.region_code, which now sees Cloudflare's location
4CF-RayCloudflare's ID for the requestMatch a request across Cloudflare's and GCP's logs

Who blocks what: Cloudflare or Cloud Armor

Both are web application firewalls. Running both is normal, but each rule should live in one place, decided by what that place can see:

#JobCloudflare (edge)Cloud Armor (origin)
1Large DDoS attacksyes absorbed before reaching GCPBackstop
2Bots, managed WAF rules, country rulesyes sees the real visitorOnly through Cloudflare's headers
3Rate limiting by visitoryes nativeBy CF-Connecting-IP header
4"Only Cloudflare may reach the origin"Cannot: it is the thing being checkedyes origin lock
5Last line if Cloudflare is misconfigured or bypassed-yes preconfigured WAF rules stay on
Some Cloudflare features (the full managed rule sets, advanced rate limiting) need a paid plan. Check the plan before relying on them.

Caching: one cache or two

Kadé now has two CDNs in a row. Each request for a product image can be answered by Cloudflare's cache, by Cloud CDN's cache, or by the Cloud Storage bucket:

ShopperGET /images/rice.jpgCloudflare cacheat the edge, near the shopperCloud CDN cacheat Google's edgekade-static bucketCloud StorageHIT: answered heremost requestsHIT on a Cloudflare missshields the bucketonly when both miss

On a release: purge Cloud CDN first, then Cloudflare. The other way, Cloudflare refills from Cloud CDN's old copy.

The API (api.kade.lk) skips both: a Cloudflare Cache Rule bypasses cache, and the API sends Cache-Control: no-store.

#RuleWhy
1Cloudflare is the cache shoppers hit; Cloud CDN stays on kade-static onlyCloudflare is closer to shoppers. Cloud CDN then shields the bucket from Cloudflare's own cache misses across many edge locations
2Never cache the APIA Cloudflare Cache Rule bypasses cache for api.kade.lk, and the API sends Cache-Control: no-store. Cloudflare does not cache JSON by default, but saying it explicitly avoids surprises
3Let the origin's Cache-Control decide lifetimesOne source of truth for both caches
4On release, purge both, inner firstPurge Cloud CDN, then Cloudflare. In the other order, Cloudflare can refill from Cloud CDN's old copy
5Use versioned file names (app.3f9c.js)New names never need purging at all
Data GCP sends to Cloudflare counts as internet egress from the load balancer. Every Cloudflare cache hit is data GCP does not send.

Other Cloudflare features worth knowing

#FeatureWhat it isGCP equivalent or link
1Transform RulesAdd, change or remove request and response headers at the edgeUsed for the secret origin header (section 06)
2Cache Rules, Configuration Rules, Redirect RulesPer-path control of caching, security level and redirectsURL map redirects and Cloud CDN settings (chapter 12)
3Cloudflare TunnelA small agent (cloudflared) on a VM opens an outgoing connection to Cloudflare, so the origin needs no public IP or load balancer at allA different design: suits a VM-hosted app; it uses Cloud NAT for its outgoing connection (chapter 7)
4Cloudflare Access (Zero Trust)Sign-in in front of an internal web appIAP for HTTPS (chapter 6.1)
5Cloudflare Load BalancingHealth-checked failover between origins at the DNS or proxy levelUsually unnecessary with a global GCP load balancer
6WorkersCode running at Cloudflare's edgeOut of scope here
7Logs (Logpush)Cloudflare's request logs sent to storage or a SIEMJoin with GCP logs by CF-Ray (chapter 16)
8Development ModeBypasses Cloudflare's cache for three hoursHandy while testing; remember it turns itself off

When it breaks: reading Cloudflare errors

When the origin leg fails, Cloudflare shows its own error page with a 52x code. Each code points at a specific link, so it tells you where to look before you open any log. Pick one:

526 · Invalid SSL certificate. Full (strict) mode found a certificate that is expired, self-signed, or for the wrong hostname.

Where to look
Certificate Manager: is the certificate ACTIVE, and does it cover this hostname (chapter 12, command 6)? Is _acme-challenge still DNS only?

Back to Kadé

Commands in this chapter

Commands 1 to 4 are read-only. Commands 5 to 7 change the project.

Is a name proxied? Look at the DNS answer

  • What it shows: The addresses visitors get for each name.
  • What to look for: Cloudflare addresses (for example in 104.16.0.0/13 or 172.64.0.0/13) mean orange. 34.120.88.10 means grey, and that name skips Cloudflare.
dig +short kade.lkdig +short www.kade.lkdig +short api.kade.lk

Did a response come through Cloudflare?

  • What it shows: The response headers.
  • What to look for: server: cloudflare and a cf-ray header. cf-cache-status: HIT on images means Cloudflare's cache answered.
curl -sI https://www.kade.lk/images/rice.jpg | grep -iE "server|cf-ray|cf-cache-status|via"

Test the origin lock from outside Cloudflare

  • What it shows: What happens when you skip Cloudflare and call the load balancer IP directly, with the right hostname.
  • What to look for: 403 from Cloud Armor. A 200 means the lock is open.
curl -s -o /dev/null -w "%{http_code}\n" \  --resolve api.kade.lk:443:34.120.88.10 https://api.kade.lk/v1/health

Check the DNSSEC chain after the move

  • What it shows: Whether a validating resolver accepts the answer.
  • What to look for: The ad flag in the header line means validated. SERVFAIL from a validating resolver points at a stale DS record.
dig +dnssec kade.lk @1.1.1.1 | grep -E "flags|status"

Allow only Cloudflare and Kadé's secret header (changes the project)

  • What it shows: The origin lock in kade-edge-policy: two allow rules (Cloudflare's 15 ranges split across them), each also requiring the header, and a default deny.
  • What to look for: Command 3 returns 403, while the site still works through Cloudflare. Use your own long random header value, and add the same value in a Cloudflare Transform Rule first.
gcloud compute security-policies rules create 500 --security-policy=kade-edge-policy \  --expression="(inIpRange(origin.ip,'173.245.48.0/20') || inIpRange(origin.ip,'103.21.244.0/22') || ...) \    && request.headers['x-kade-edge'] == 'REPLACE-WITH-LONG-RANDOM-VALUE'" \  --action=allowgcloud compute security-policies rules update 2147483647 \  --security-policy=kade-edge-policy --action=deny-403

Key the login rate limit on the real visitor (changes the project)

  • What it shows: The chapter 12 rate limit, now counted per CF-Connecting-IP instead of per source IP.
  • What to look for: In the logs, blocked requests carry different visitor IPs instead of a few Cloudflare addresses.
gcloud compute security-policies rules update 100 --security-policy=kade-edge-policy \  --enforce-on-key=HTTP-HEADER --enforce-on-key-name=CF-Connecting-IP

Purge Cloud CDN before Cloudflare (changes the project)

  • What it shows: Clears Cloud CDN's copy of changed files. Then purge the same paths in Cloudflare.
  • What to look for: The command waits until the purge is done. Only then purge Cloudflare.
gcloud compute url-maps invalidate-cdn-cache kade-url-map --path="/assets/*"

Spotted a mistake, or something unclear? Suggest an edit on GitHub

See it broken

Harbour is a platform built wrong on purpose. This defect is this chapter's idea, left undone: what it breaks, how you would find it, and the change that closes it.

  1. D8