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 fromcloudflaredto nginx stays on the host.Access is checked twice.
cloudflaredvalidates 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-Authheader, 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 fromcloudflared'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
| Piece | Where | What it does |
|---|---|---|
edge-network | same file | Internal network with a pinned subnet. Only cloudflared and nginx join it. |
tunnel-egress-network | same file | cloudflared's own way out (7844 TCP/UDP, 443). Nothing connects in. |
| Client address | modules/nginx/nginx.conf | real_ip_header CF-Connecting-IP, trusted only from edge-network's subnet |
| Token | SSM /chainr/dev/tunnel/TUNNEL_TOKEN | Declared in app-secrets.tf, hydrated into dotenv/prod/tunnel.env, which only cloudflared reads |
| Deploy guard | infra/aws/cicd/deploy-on-host.sh | Refuses to deploy without the token, rather than start a stack nothing can reach |
| Security group | infra/terraform/envs/dev/network.tf | ingress = []. It must be explicitly empty: omitting inline rules leaves existing ones on AWS. |
| Instance metadata | infra/terraform/envs/dev/ec2.tf | http_put_response_hop_limit = 1, so a metadata token can't cross a docker bridge |
| Metrics | modules/monitoring/prometheus/prometheus.yml | Job cloudflared, discovered through the Docker socket proxy |
| Guard rails | tools/security/test_edge_config.py | Pins 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.devand the like). Universal SSL covers one level only.You need your Access team name (the
<team>in the<team>.cloudflareaccess.comaddress Access redirects to) and the application's AUD tag.nginx routes by hostname (
server_nameinmodules/nginx/conf.d/), so the new hostnames must appear there.
Steps:
Create the tunnel: Zero Trust → Networks → Tunnels → Create a tunnel → Cloudflared. Copy only the token from the install command. Compose runs the connector.
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>' ```
Deploy and check the connector: the tunnel shows Healthy, Loki's
{service="cloudflared"}showsRegistered tunnel connectionfour times, andcloudflared_tunnel_ha_connectionsis 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.
Check each hostname: the page loads after the Access login, and nginx's log shows visitors' own IPs, not
10.250.0.xor Cloudflare addresses.
Troubleshooting
| You see | Cause | Fix |
|---|---|---|
| 1033 | The connector isn't connected, or the CNAME points at a different tunnel | Check the tunnel's health and {service="cloudflared"}. Compare the CNAME's tunnel ID with the tunnel's. |
| Bare 404 Not Found | No route for this hostname on the tunnel | Add the route |
| 403 straight after the Access login | Wrong team name or AUD tag in Protect with Access | Copy both from the Access application |
| Cloudflare-branded 502 | The route's service URL is wrong, or nginx is down | It must be HTTP nginx:80. Check docker compose … ps nginx. |
| nginx 502 | The container behind that vhost is down | docker compose … ps and its logs |
| 521 | A proxied A record still points at the Elastic IP, which accepts nothing now | Replace it with the tunnel CNAME |
| "Site can't be reached" just after DNS changes | Your resolver cached "doesn't exist": the zone's negative-cache TTL is 30 minutes | Flush local DNS, or wait it out |
Operating it
Logs: Grafana → Explore → Loki
{service="cloudflared"}. On the host, asec2-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_connectionsis normally 4. At 0, the hostnames are down: the tunnel is the only way in.cloudflared_tunnel_total_requestsandcloudflared_tunnel_request_errorsshow 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.ymland deploy. Compose recreates the container, which reconnects in a few seconds. Cloudflare supportscloudflaredreleases 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 sizeat startup is a host tuning note, not an error. To clear it, setnet.core.rmem_maxandnet.core.wmem_maxto7500000in/etc/sysctl.d/on the host.Headers nginx receives:
CF-Connecting-IP(the client, which nginx trusts fromedge-networkonly),X-Forwarded-Proto: https,Cf-Access-Jwt-AssertionandCf-Ray.X-Forwarded-Foralso 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: 168hinmodules/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.