chain-rdeveloper portal
build

Cloudflare Tunnel

The dev host is reached only through an outbound-only Cloudflare Tunnel: a cloudflared container on the host dials Cloudflare and carries each request back to nginx. Nothing on the host accepts a connection from the internet. This closed Known gap 15 in .claude/CLAUDE.md (October 2026):

  • No inbound port. The security group has no inbound rules, and the host publishes no port.

  • Encrypted end to end. Browsers reach Cloudflare over TLS, and Cloudflare reaches the host through the tunnel, which is encrypted between Cloudflare and cloudflared. The hop from cloudflared to nginx stays on the host.

  • Access is checked twice. cloudflared validates the Cloudflare Access token on every request before passing it on, so a hostname that loses its Access application still can't reach the stack.

  • No edge secret to rotate. The X-Origin-Auth header, its Transform Rule, its 90-day rotation and the zone-editing Cloudflare API token are gone.

  • Rate limits count per client. nginx takes the client address from CF-Connecting-IP, trusted only from cloudflared's network.

  • Containers can't reach the instance role. The metadata hop limit is 1, so no container can fetch the credentials that decrypt the app's secrets.

How it fits

browser ─TLS─▶ Cloudflare edge (Access) ◀═══ tunnel (QUIC/TLS) ═══ cloudflared ─▶ nginx ─▶ stack
                                            dialled OUT from the host       edge-network
                                                                            10.250.0.0/28

host: security group with no inbound rules · no published ports · metadata hop limit 1
PieceWhereWhat it does
edge-networksame fileInternal network with a pinned subnet. Only cloudflared and nginx join it.
tunnel-egress-networksame filecloudflared's own way out (7844 TCP/UDP, 443). Nothing connects in.
Client addressmodules/nginx/nginx.confreal_ip_header CF-Connecting-IP, trusted only from edge-network's subnet
TokenSSM /chainr/dev/tunnel/TUNNEL_TOKENDeclared in app-secrets.tf, hydrated into dotenv/prod/tunnel.env, which only cloudflared reads
Deploy guardinfra/aws/cicd/deploy-on-host.shRefuses to deploy without the token, rather than start a stack nothing can reach
Security groupinfra/terraform/envs/dev/network.tfingress = []. It must be explicitly empty: omitting inline rules leaves existing ones on AWS.
Instance metadatainfra/terraform/envs/dev/ec2.tfhttp_put_response_hop_limit = 1, so a metadata token can't cross a docker bridge
Metricsmodules/monitoring/prometheus/prometheus.ymlJob cloudflared, discovered through the Docker socket proxy
Guard railstools/security/test_edge_config.pyPins every row above

The tunnel is remotely managed: its routes, which Cloudflare calls published application routes, and the Access check are set on the tunnel in the Zero Trust dashboard. Only the token lives in this repo's world. Route changes apply without restarting cloudflared, and cloudflared logs every configuration it receives, so a change made in the dashboard shows up in Loki.

Setting up a tunnel for a new environment

This is what a new environment needs, such as a dedicated instance for a design partner.

Before you start:

  • The tunnel and the Access application must be in the Cloudflare account that holds the zone. A route can only publish a hostname from a zone in its tunnel's own account.

  • The edge certificate must cover second-level names (app.dev and the like). Universal SSL covers one level only.

  • You need your Access team name (the <team> in the <team>.cloudflareaccess.com address Access redirects to) and the application's AUD tag.

  • nginx routes by hostname (server_name in modules/nginx/conf.d/), so the new hostnames must appear there.

Steps:

  1. Create the tunnel: Zero Trust → Networks → Tunnels → Create a tunnel → Cloudflared. Copy only the token from the install command. Compose runs the connector.

  2. Store the token before the first deploy. The deploy refuses to run without it, and refuses CHANGE_ME:

    ```bash cd infra/terraform/envs/dev terraform apply # creates /chainr/dev/tunnel/TUNNELTOKEN = CHANGEME

    aws ssm put-parameter --profile chainr-dev --overwrite --type SecureString \ --name /chainr/dev/tunnel/TUNNEL_TOKEN --value '<token>' ```

  3. Deploy and check the connector: the tunnel shows Healthy, Loki's {service="cloudflared"} shows Registered tunnel connection four times, and cloudflared_tunnel_ha_connections is 4.

  4. For each hostname:

    • Make sure the live zone has a proxied CNAME from the hostname to <tunnel-id>.cfargotunnel.com. Adding a route normally creates it, but not if another record held the name at the time. Adding it by hand always works.

    • Add the route on the tunnel: service HTTP nginx:80, no Host header override, Protect with Access on, with the team name and AUD tag.

  5. Check each hostname: the page loads after the Access login, and nginx's log shows visitors' own IPs, not 10.250.0.x or Cloudflare addresses.

Troubleshooting

You seeCauseFix
1033The connector isn't connected, or the CNAME points at a different tunnelCheck the tunnel's health and {service="cloudflared"}. Compare the CNAME's tunnel ID with the tunnel's.
Bare 404 Not FoundNo route for this hostname on the tunnelAdd the route
403 straight after the Access loginWrong team name or AUD tag in Protect with AccessCopy both from the Access application
Cloudflare-branded 502The route's service URL is wrong, or nginx is downIt must be HTTP nginx:80. Check docker compose … ps nginx.
nginx 502The container behind that vhost is downdocker compose … ps and its logs
521A proxied A record still points at the Elastic IP, which accepts nothing nowReplace it with the tunnel CNAME
"Site can't be reached" just after DNS changesYour resolver cached "doesn't exist": the zone's negative-cache TTL is 30 minutesFlush local DNS, or wait it out

Operating it

  • Logs: Grafana → Explore → Loki {service="cloudflared"}. On the host, as ec2-user (sudo su - ec2-user) in ~/chainr/modules: docker compose -f docker-compose.yml -f docker-compose.prod.yml -f docker-compose.ecr.yml logs -f cloudflared.

  • Health: cloudflared_tunnel_ha_connections is normally 4. At 0, the hostnames are down: the tunnel is the only way in. cloudflared_tunnel_total_requests and cloudflared_tunnel_request_errors show traffic and failures. Nothing alerts on these yet, because the stack has no notification channel (Phase 3, Alerting).

  • Shell access: SSM Session Manager only (terraform output ssm_session_command). It is outbound too, so it needs no inbound rule.

  • Upgrading: bump the pinned tag in docker-compose.prod.yml and deploy. Compose recreates the container, which reconnects in a few seconds. Cloudflare supports cloudflared releases for about a year, so bump at least every few months.

  • If the token leaks: rotate it from the tunnel's page in the dashboard, or through the API. If in doubt, create a new tunnel, move the routes to it, then delete the old one. Either way, put the new token in SSM and redeploy.

  • QUIC buffer warning: failed to sufficiently increase receive buffer size at startup is a host tuning note, not an error. To clear it, set net.core.rmem_max and net.core.wmem_max to 7500000 in /etc/sysctl.d/ on the host.

  • Headers nginx receives: CF-Connecting-IP (the client, which nginx trusts from edge-network only), X-Forwarded-Proto: https, Cf-Access-Jwt-Assertion and Cf-Ray. X-Forwarded-For also arrives, but it can carry values the client supplied, so never use it as the client address.

  • Privacy: nginx's access log records each visitor's IP address. IP addresses are personal data. Loki keeps logs for 7 days (retention_period: 168h in modules/monitoring/loki/loki-config.yml).

Checking the lockdown

Run this after any change to the network, the security group or the compose files, and from time to time anyway. From infra/terraform/envs/dev:

# Nothing answers on the host's address (expect a timeout):
curl -m 5 "http://$(terraform output -raw public_ip)/"

# No inbound rules (expect []):
aws ec2 describe-security-groups --profile chainr-dev \
  --filters Name=group-name,Values=chainr-dev-compose-host \
  --query 'SecurityGroups[0].IpPermissions'

# Containers cut off from the instance role (expect 1):
aws ec2 describe-instances --profile chainr-dev \
  --instance-ids "$(terraform output -raw instance_id)" \
  --query 'Reservations[0].Instances[0].MetadataOptions.HttpPutResponseHopLimit'

On the host (terraform output ssm_session_command). A session starts as ssm-user, who isn't in the docker group and whose ~ isn't the repo's, so switch to ec2-user first. The deploy runs as that user, in ~/chainr:

sudo su - ec2-user

# A container gets no metadata token: expect "000" and "curl exit 28" (timed out)
docker run --rm curlimages/curl:8.10.1 -s -m 3 -o /dev/null -w '%{http_code}\n' -X PUT \
  http://169.254.169.254/latest/api/token -H 'X-aws-ec2-metadata-token-ttl-seconds: 60'
echo "curl exit $?"

# The host itself still gets one, for the SSM agent and ECR pulls: expect "200"
curl -s -m 3 -o /dev/null -w '%{http_code}\n' -X PUT \
  http://169.254.169.254/latest/api/token -H 'X-aws-ec2-metadata-token-ttl-seconds: 60'

The checks print status codes rather than pass/fail messages, so a docker or permissions error can't pass for a blocked request.

tools/security/test_edge_config.py holds the same facts in the code, so these checks catch drift made outside it (in the console, say).

History

Until October 2026, Cloudflare's edge reached nginx on the Elastic IP's port 80 in plain HTTP. The security group admitted only Cloudflare's published IP ranges, and nginx refused requests without an X-Origin-Auth header that a Cloudflare Transform Rule added. The migration ran in four stages: the connector, a test hostname, the cutover, and the removal of the direct path. That last stage emptied the security group's ingress, unpublished nginx's port, set the metadata hop limit to 1, and retired origin auth with its rotation, its SSM parameters, the Transform Rule and the Cloudflare API tokens. The datachainr.com zone also moved to a new Cloudflare account during it. That move is where the 1016 and negative-cache rows in Troubleshooting come from.