Ga naar de inhoud
Korur

Cloudflare Tunnel and Access, end to end

How cloudflared reaches the edge, what Access evaluates, and how Cf-Access-Jwt-Assertion is validated at the origin, traced through source and a lab.

A Cloudflare Tunnel removes the inbound path to an origin, and Cloudflare Access puts an identity check in front of a hostname. Most deployments stop there, and that leaves a gap that is easy to miss: the origin still trusts whatever the connector hands it, and the connector, unless told otherwise, trusts whatever the edge sends down the tunnel. The access block of an ingress rule defaults to empty1, so out of the box nothing between the edge and the application checks that Access actually ran.

This article follows one HTTPS request from a browser to a workload: through Access policy evaluation at the edge, through the cloudflared connection that carries it, and through the JWT check that should happen before the origin sees a byte. Code paths are pinned to cloudflared 2026.10.7 and to go-oidc v3.17.0, the library that release builds its token verifier on. The lab at the end reproduces the token validation and ingress matching claims; steps that need a live Cloudflare account are marked as inspected.

Three enforcement points on one request

A tunnel hostname is a proxied DNS record whose target is <UUID>.cfargotunnel.com, and that target only proxies traffic for DNS records in the same Cloudflare account2. The browser's TLS session ends at the Cloudflare edge. If the hostname belongs to an Access application, the edge decides there whether the request may continue. A request that passes carries an application token in the Cf-Access-Jwt-Assertion request header3, and the edge forwards it into one of the tunnel's connections. On the far side, cloudflared picks an ingress rule, runs the rule's middleware, and only then dials the origin.

That gives three places where identity can be enforced, and they fail in different ways. I treat the first as the policy decision and the other two as proof that it was made.

Where identity is checked on a tunnelled request
PointWhat it checksHow it refusesConfigured in
Cloudflare edge (Access)Policies against the identity established at login; session tokens on the team and application domainsRedirect to login, or a block pageAccess application and its policies
cloudflared ingress ruleJWT signature, issuer, expiry and not-before, and an aud value from the rule's audTag list403 for a missing header or a foreign audience; a proxy error for an invalid tokenoriginRequest.access on the rule
Origin applicationThe same JWT, plus whatever authorization the application ownsWhatever the application returnsApplication code

How the connector reaches the edge

The tunnel token

A remotely managed tunnel starts from a single token. In cloudflared it is the TunnelToken struct in connection/connection.go: JSON with the keys a (account tag), s (tunnel secret, bytes), t (tunnel UUID) and an optional e (endpoint), base64-encoded with the standard alphabet and decoded by ParseToken in cmd/cloudflared/tunnel/subcommands.go45. The token is therefore the tunnel secret itself, not a reference to it, which is why Cloudflare states plainly that anyone with access to the token can run the tunnel6. Refreshing the token stops the old value from opening new connections, but connectors that are already running stay connected and the tunnel keeps serving traffic6. That includes a connector someone else started with the leaked token, and restarting your own replicas with the new token does nothing about it: the foreign connector keeps its edge connections and keeps receiving its share of requests. Cloudflare's procedure for a compromised token therefore has a step between the two: refresh the token, delete every connection of the tunnel with DELETE /client/v4/accounts/$ACCOUNT_ID/cfd_tunnel/$TUNNEL_ID/connections, which the page describes as cleaning up any unauthorized connections, and then restart each replica with the new token6. The leak is contained once the connections are deleted, not once your replicas have restarted. The call deletes all of the tunnel's connections, which is why the procedure ends with restarting every replica on the new token; plan for the hostname to be unavailable until the first restarted replica has reconnected.

Since release 2025.4.0 the token can be read from a file with --token-file7. I prefer it over both alternatives in Kubernetes, and the reasons differ per alternative. --token puts the secret itself into the container's args, so it is part of the pod spec, and into the process command line in /proc/<pid>/cmdline8. TUNNEL_TOKEN sourced through valueFrom.secretKeyRef keeps the pod spec clean, because the spec holds only the Secret's name and key9, but the value is still in the process environment: it can be read from /proc/<pid>/environ by anyone who passes the ptrace read check on the process10, it shows up in kubectl exec -- env, and every child process inherits a copy of it11. A Secret mounted as a file and passed with --token-file avoids both exposures: the spec names only the volume, and the value lives in a file that nothing inherits.

Edge discovery

The connector finds the edge through DNS. EdgeDiscovery in edgediscovery/allregions/discovery.go looks up the SRV record _v2-origintunneld._tcp.argotunnel.com, and if the system resolver fails it retries over DNS over TLS against 1.1.1.1:85312. ResolveEdge in regions.go then insists on at least two answers and keeps them as two regions; with fewer it returns an error instead of running degraded13. In the lab the SRV lookup returned region1.v2.argotunnel.com and region2.v2.argotunnel.com, both on port 7844, which matches the hostnames and port Cloudflare documents for firewall rules14.

The hidden --ha-connections flag defaults to 4 in cmd/cloudflared/tunnel/cmd.go15. Supervisor.initialize in supervisor/supervisor.go starts connection index 0 alone and waits until it registers or fails; only after the first success does it start indexes 1 to 3, one second apart (registrationInterval), each reusing the transport the first connection settled on16. Addresses come from Regions.GetUnusedAddr, which takes from whichever region has more unused addresses and picks at random when they are level, so the four connections spread across both regions. Cloudflare describes the result as four outbound connections to four different servers in at least two data centres17.

Transport selection: QUIC first, HTTP/2 as fallback

NewProtocolSelector in connection/protocol.go turns --protocol into a selector. quic and http2 are fixed choices with no fallback; auto, the default, starts with QUIC and permits a fallback to HTTP/218. The documentation describes the trigger as cloudflared being unable to establish UDP connections7. The two transports present different TLS identities to the edge, which matters for any firewall that filters on SNI.

Edge transports in cloudflared 2026.10.7
PropertyQUICHTTP/2
Layer 4UDP to port 7844TCP to port 7844
TLS server namequic.cftunnel.comh2.cftunnel.com
ALPNargotunnelnone set by TLSSettings
Unit of one requestA bidirectional QUIC stream opened by the edgeAn HTTP/2 request served by HTTP2Connection.ServeHTTP
Chosen when--protocol quic, or first under auto--protocol http2, or after fallback under auto
Post-quantum key agreement (client offer)X25519MLKEM768, then P256Kyber768Draft00, then P-256; --post-quantum drops P-256The same curve list and the same --post-quantum behaviour; whether the edge negotiates PQ on h2 is unverified

The post-quantum row needs a word, because the code and the documentation disagree. Cloudflare's run parameters page still says post-quantum key agreement is not supported on http27. In 2026.10.7, EdgeTunnelServer in supervisor/tunnel.go applies cfdcrypto.TLSConfigWithCurvePreferences to the HTTP/2 edge dial exactly as it does for QUIC, and serveHTTP2 carries the comment that HTTP/2 supports post-quantum key exchange the same way QUIC does19. crypto/curves.go defines one protocol-agnostic list per mode: in the default prefer mode the client offers X25519MLKEM768, P256Kyber768Draft00 and P-256, in that order, and in strict mode only the two post-quantum curves20. --post-quantum selects strict mode in features/selector.go21, so it restricts both transports. RELEASE_NOTES lists the change, TUN-10413, under release 2026.5.022. What the code fixes is the client's offer; I have not verified that the edge selects a post-quantum group on an HTTP/2 connection, and a strict-mode connector over HTTP/2 is the case I would test before relying on it.

The QUIC parameters are aggressive. quic/constants.go sets a 5 second handshake idle timeout, a 5 second maximum idle timeout and a 1 second keep-alive period23. Under RFC 9000 the effective idle timeout is the minimum of the values both endpoints advertise, and a connection idle for longer is closed silently with its state discarded24. A connector that stalls for a few seconds loses its connections, which matters for how it is scheduled. createUDPConnForConnIndex in connection/quic.go also remembers the local UDP port it used for each connection index and binds the same port when that index redials, falling back to a random port only if the bind fails25.

Registration and remote configuration

On a QUIC connection cloudflared opens the first stream itself, the control stream the edge expects, and acts as the RPC client on it: NewRegistrationClient in tunnelrpc/registration_client.go wraps the raw stream in a Cap'n Proto transport and calls registerConnection on the edge's RegistrationServer2627. The Cap'n Proto schema in tunnelrpc/proto/tunnelrpc.capnp defines the call: registerConnection(auth :TunnelAuth, tunnelId :Data, connIndex :UInt8, options :ConnectionOptions), where TunnelAuth carries accountTag and tunnelSecret, the two values from the token. The reply is a ConnectionResponse union of either a ConnectionError with cause, retryAfter and shouldRetry, or ConnectionDetails with the connection uuid, the edge locationName and a tunnelIsRemotelyManaged flag28.

For a remotely managed tunnel the ingress rules live at Cloudflare and arrive in the opposite direction, not on the registration stream. The edge opens an RPC stream and calls updateConfiguration(version :Int32, config :Data) on cloudflared, which serves the schema's CloudflaredServer interface, an extension of SessionManager and ConfigurationManager2829. Orchestrator.UpdateConfig in orchestration/orchestrator.go ignores any version equal to or older than the one it holds, and on a configuration it cannot parse it logs the error and keeps serving the previous rules30. A bad push leaves the connector on its last good configuration.

Readiness is equally simple. ReadyServer in metrics/readiness.go answers /ready on the metrics listener with 200 when the connection tracker counts at least one active connection and 503 otherwise, with a JSON body of status, readyConnections and connectorId31. One connection out of four is enough to report ready.

A request on the wire

On QUIC every proxied request is its own bidirectional stream. cloudflared dialled the connection, so it is the QUIC client, and it receives request streams through AcceptStream; they are server-initiated bidirectional streams, the type RFC 9000 marks with the low stream ID bits 0x0124. QUIC gives no ordering guarantee between streams, so a slow upload on one request does not hold back the bytes of another sharing the same connection.

The streams on a connection use three framings, defined in tunnelrpc/quic/protocol.go32. A data stream, opened by the edge for each request, starts with the six byte signature 0A 36 CD 12 A1 3E and the two byte ASCII version 01, written by writeDataStreamPreamble and read back by RequestServerStream.ReadConnectRequestData. An RPC stream starts with the signature 52 BB 82 5C DB 65 alone; Cap'n Proto RPC follows directly, and CloudflaredServer.handleRPC never reads a version29. The control stream that cloudflared opens first carries no preamble at all: Cap'n Proto RPC starts at byte 0. CloudflaredServer.Serve dispatches edge-opened streams on their first six bytes. After its version, a data stream continues with a Cap'n Proto ConnectRequest:

tunnelrpc/proto/quic_metadata_protocol.capnp, cloudflared 2026.10.7text
struct ConnectRequest @0xc47116a1045e4061 {
	dest @0 :Text;
	type @1 :ConnectionType;
	metadata @2 :List(Metadata);
}

enum ConnectionType @0xc52e1bac26d379c8 {
	http @0;
	websocket @1;
	tcp @2;
}

struct Metadata @0xe1446b97bfd1cd37 {
    key @0 :Text;
	val @1 :Text;
}

struct ConnectResponse @0xb1032ec91cef8727 {
	error @0 :Text;
	metadata @1 :List(Metadata);
}

HTTP semantics are carried in the metadata list. buildHTTPRequest in connection/quic_connection.go reads the method from HttpMethod, the host from HttpHost, and every header value from a key of the form HttpHeader:<Name>26. The Access token therefore travels to the connector as a metadata entry with the key HttpHeader:Cf-Access-Jwt-Assertion. The response goes back as a ConnectResponse with the status under HttpStatus and the headers under HttpHeader:<Name>, followed by the body on the same stream.

Errors take two shapes, and the difference becomes important in the section on validation. If ProxyHTTP returns an error before a response was sent, handleDataStream writes a ConnectResponse whose error field holds the error text, without an HTTP status; I have not verified what the edge renders to the browser for that case. On the HTTP/2 transport the same error reaches HTTP2Connection.ServeHTTP, which calls WriteErrorResponse; that writes a 502 and sets the cf-cloudflared-response-meta header to mark cloudflared, not the origin, as the source33.

Access policy evaluation at the edge

Access is deny by default: a user who matches no Allow policy is refused. Each policy has one action out of Allow, Block, Bypass and Service Auth, and its rules combine as Include (OR), Require (AND) and Exclude (NOT); every policy needs at least one Include rule, and the values inside a single Require rule are joined with AND. Evaluation runs Bypass and Service Auth policies first, top to bottom, and then Allow and Block policies in their order, stopping at the first Allow or Block match34. Two details deserve more attention than they get. Bypass enforces no Access control and the requests it lets through are not logged, so a Bypass on one path of an internal application is an unaudited hole. And the AND inside a Require rule means that adding a second group to it narrows the audience to members of both groups, which is rarely what the person adding it intended.

Machines authenticate with service tokens: the client sends CF-Access-Client-Id and CF-Access-Client-Secret on each request, and the matching policy must use the Service Auth action, otherwise Access sends the client to an identity provider login it cannot complete35.

Sessions and group membership

Logging in creates a global session token stored on the team domain, which spares the user a fresh login per application, and Access then issues an application token for each application the user reaches, stored on the protected domain. Both are delivered in a cookie named CF_Authorization, one per domain, alongside CF_Session (4 hours), CF_AppSession (24 hours) and CF_Device (30 days)36. Session lengths resolve from the most specific setting to the least: client session, then policy session, then application session, then global session. When an application token expires and the global session is still valid, Access issues a new application token, and when a session expires Access rechecks the stored identity against the application's policies37.

The consequence for group-based policies is easy to miss. With Entra ID, Access evaluates logins against the group membership in the token returned at authentication, not against groups synchronised by SCIM; nested groups apply at authentication, but SCIM provisions only direct members38. Access evaluates updated identity provider data only when the user authenticates again38, and the identity it rechecks when a policy or application session expires is the one stored with the global session37. Removing someone from the Entra group that a policy names therefore does not end their access, and a short application or policy session does not help: when it expires, Access re-evaluates the stored identity, which still lists the removed group, and issues a new application token as long as the global session is valid. What bounds the window is the global session duration, because only its expiry sends the user back to Entra ID for fresh group claims. The other ways to close it are an administrator revoking the user's session (after which the user cannot log in again for up to one minute37) and the SCIM option that revokes a user's active session when their group membership changes in Entra ID38. I keep the global session short for a team that reaches administrative applications and treat revocation as part of removing someone from a group, rather than relying on application session lengths.

The application token

The token in Cf-Access-Jwt-Assertion is a JWS in compact serialization: the base64url encoding of the protected header, a dot, the base64url payload, a dot, and the base64url signature, where the signature covers the first two parts joined by the dot39. The header carries alg and kid; Access signs with RS2563.

Claims of an Access application token for a user
ClaimContent
audThe Application Audience (AUD) tag of the Access application
issThe Cloudflare Access domain URL, https://<team>.cloudflareaccess.com
exp, iat, nbfExpiry, issuance and not-before times in Unix time
emailThe user's email address as verified by the identity provider
subThe user ID, unique per email per account; empty for a service token, which sets common_name to the Client ID
typeapp for an application token, org for a global session token
identity_nonceA cache key for fetching the full identity
countryThe country the user authenticated from
customCustom claims, best effort; trimmed when the serialized claim exceeds about 1 KB

The claim descriptions above are Cloudflare's40. The token holds only a subset of the identity; the rest, including identity provider data and device posture, comes from the team domain's /cdn-cgi/access/get-identity endpoint. Because custom can be trimmed, I never authorize on it.

The signing keys are published at https://<team>.cloudflareaccess.com/cdn-cgi/access/certs. The response holds keys, both current keys as JWKs; public_cert, the current key in PEM; and public_certs, both keys in PEM. Access rotates the signing key every six weeks by default and keeps the previous key valid for seven days after a rotation, and Cloudflare asks validators to fetch keys from the endpoint and match on kid rather than hard-code a key3. That is the rollover pattern the JWK specification describes, where kid selects among the keys in a set41, and OpenID Connect Core makes the verifier side explicit: on an unfamiliar kid, go back to the key set URL and fetch again42. A validator that pins public_cert breaks every six weeks.

What cloudflared checks, line by line

When an ingress rule has access.required set, validateIngress in ingress/ingress.go builds a JWTValidator with the rule's team name and AUD tags and attaches it to the rule's handlers43. The Terraform provider documents the same block as validating each request's Cf-Access-Jwt-Assertion header for all layer 7 requests to the hostname44. The whole validator is short enough to read in full:

ingress/middleware/jwtvalidator.go, cloudflared 2026.10.7, lines 28 to 86, verbatimtext
func NewJWTValidator(teamName string, environment string, audTags []string) *JWTValidator {
	var certsURL string
	if environment == credentials.FedEndpoint {
		certsURL = fmt.Sprintf(cloudflareAccessFedCertsURL, teamName)
	} else {
		certsURL = fmt.Sprintf(cloudflareAccessCertsURL, teamName)
	}

	certsEndpoint := fmt.Sprintf("%s/cdn-cgi/access/certs", certsURL)

	config := &oidc.Config{
		SkipClientIDCheck: true,
	}

	ctx := context.Background()
	keySet := oidc.NewRemoteKeySet(ctx, certsEndpoint)
	verifier := oidc.NewVerifier(certsURL, keySet, config)
	return &JWTValidator{
		IDTokenVerifier: verifier,
		audTags:         audTags,
	}
}

func (v *JWTValidator) Name() string {
	return "AccessJWTValidator"
}

func (v *JWTValidator) Handle(ctx context.Context, r *http.Request) (*HandleResult, error) {
	accessJWT := r.Header.Get(headerKeyAccessJWTAssertion)
	if accessJWT == "" {
		// log the exact error message here. the message is specific to the handler implementation logic, we don't gain anything
		// in passing it upstream. and each handler impl know what logging level to use for each.
		return &HandleResult{
			ShouldFilterRequest: true,
			StatusCode:          http.StatusForbidden,
			Reason:              "no access token in request",
		}, nil
	}

	token, err := v.IDTokenVerifier.Verify(ctx, accessJWT)
	if err != nil {
		return nil, err
	}

	// We want at least one audTag to match
	for _, jwtAudTag := range token.Audience {
		for _, acceptedAudTag := range v.audTags {
			if acceptedAudTag == jwtAudTag {
				return &HandleResult{ShouldFilterRequest: false}, nil
			}
		}
	}

	return &HandleResult{
		ShouldFilterRequest: true,
		StatusCode:          http.StatusForbidden,
		Reason:              fmt.Sprintf("Invalid token in jwt: %v", token.Audience),
	}, nil
}

The issuer the verifier expects is the bare team URL, https://<team>.cloudflareaccess.com, and the key set is its /cdn-cgi/access/certs path45. SkipClientIDCheck turns off go-oidc's own audience check, and the nested loop replaces it: the request passes if any aud value in the token equals any configured AUD tag. RFC 7519 requires a processor to reject a token whose aud does not name it46, and RFC 8725 repeats it as a best current practice47; the loop is how cloudflared satisfies that, and it is what stops a valid token for one Access application from opening another application served by the same tunnel.

Everything else happens in IDTokenVerifier.Verify in oidc/verify.go of go-oidc v3.17.0, in this order48. It parses the token, accepting only the configured algorithms and defaulting to RS256 alone when none are configured, so an alg of none or HS256 fails at parse time, which is the algorithm pinning RFC 8725 asks libraries to support. It requires exactly one signature, verifies it against the remote key set, compares iss for exact equality, skips the client ID check as configured, rejects a token whose exp lies before the current time with no leeway, and accepts an nbf up to five minutes in the future. The two time checks are deliberately asymmetric: the five minute allowance applies only to nbf, so a connector whose clock runs fast starts refusing tokens just before they expire, while one whose clock runs slow by up to five minutes still accepts brand new ones. RFC 7519 permits a small leeway on both claims46; go-oidc grants it on one.

A refusal is not the same as an error

Handle has two ways to stop a request, and Proxy.applyIngressMiddleware in proxy/proxy.go treats them differently49. A filtered result (missing header, or no matching audience) writes the result's status, 403, and the request ends there; ProxyHTTP logs it and returns nil. A verification error (bad signature, expired token, foreign issuer, wrong algorithm) is wrapped as error while processing middleware handler %s, filled with the handler's Name(), which for this validator is the AccessJWTValidator in the excerpt above, and returned as an error with applied false, so ProxyHTTP returns it to the transport. On HTTP/2 that becomes the 502 described earlier, and on QUIC an error ConnectResponse.

This matters for operations. A user whose application token expired between the edge check and the connector, or a connector with a skewed clock, produces proxy errors rather than 403 responses, so a dashboard that counts 403s at the connector to watch Access enforcement sees nothing. The log line to alert on is the wrapped middleware error.

Outcome per token at a cloudflared ingress rule with access.required (lab-verified rows marked)
Token presentedgo-oidc resultcloudflared outcome
No Cf-Access-Jwt-Assertion headernot called403, reason no access token in request
Valid, aud in the rule's list (lab)acceptedproxied to the origin
Valid, aud of another application (lab)accepted403, reason Invalid token in jwt
exp one second in the past (lab)oidc: token is expiredmiddleware error, not a 403
nbf four minutes in the future (lab)acceptedproxied
nbf six minutes in the future (lab)before the nbf (not before) timemiddleware error
Foreign iss (lab)id token issued by a different providermiddleware error
HS256 keyed with the RSA modulus (lab)unexpected signature algorithmmiddleware error
RS256 with an unpublished key and a known kid (lab)failed to verify id token signaturemiddleware error, after one key set fetch

Configuration errors fail closed. validateAccessConfiguration rejects AUD tags without a team name but deliberately accepts required: true with neither, to allow an initial setup43. With an empty AUD list the audience loop has nothing to match, so no request can pass: the hostname is down, not open.

Key set refresh on a failed signature

RemoteKeySet.verify in oidc/jwks.go first tries every cached key whose kid matches the token (or every key, if the token has none). If none verifies, it fetches the remote key set and tries again50. Its comment cites the OpenID Connect rule for an unfamiliar kid, but the code also refetches when the kid is familiar and the signature is simply wrong. Concurrent fetches are coalesced through an in-flight marker, and sequential ones mostly are not. The exception is a timing window in keysFromRemote: the fetching goroutine first calls r.inflight.done(keys, err), which releases every waiter, and only afterwards takes r.mu and sets r.inflight = nil. A failed verification that starts inside that window finds the finished marker, attaches to it and gets its result without a new request. So every failed verification triggers a refetch, apart from that opportunistic coalescing. In the lab, 100 forged tokens carrying the kid of a published key caused between 66 and 100 key set fetches over 20 runs, and exactly 100 in 12 of them.

In front of cloudflared this is mostly academic, because a request has to clear Access at the edge before it reaches the connector. It is not academic for the third enforcement point. An origin that validates the header with the same library and is reachable from inside its network, for example by other workloads in the same cluster, turns every forged token into an outbound request to the team domain. An application-side validator should put a floor on how often it refreshes the key set.

Path rules and the normalization gap

Ingress rules are evaluated first match wins. Ingress.FindMatchingRule strips a port from the host, walks the internal rules and then the user's rules, and falls back to the last rule; Rule.Matches compares the host exactly or as a *. suffix and tests the path against the rule's regular expression43. Since commit 059f86a of 2026-09-29, tagged VULN-141859, FindMatchingRule can first pass the path through canonicalPathForMatching, which converts backslashes to slashes and resolves dot segments with path.Clean, for rule selection only; the request sent to the origin is untouched. The commit message says the change shipped disabled by default because it can break existing routing51. In 2026.10.7 that is still the case: --disable-path-normalization (environment TUNNEL_DISABLE_PATH_NORMALIZATION) defaults to true, and its help text warns that an unnormalized path could bypass Access rules and reach a protected origin15. Orchestrator.updateIngress copies the flag into every configuration pushed from the edge30.

The edge normalizes too, but for itself. With the zone defaults, normalization type RFC 3986, normalize incoming URLs on and normalize URLs to origin off52: RFC 3986 normalization removes dot segments and percent-decodes unreserved characters53, and features such as Access see the normalized URL while the origin, which for a tunnel means cloudflared, receives the original. Consider a hostname with two tunnel rules, ^/public/ without Access and the rest of the host with Access required. A request for /public/../admin sent by a client that does not collapse dot segments, curl --path-as-is for example, is evaluated at the edge as /admin, but reaches cloudflared as /public/../admin, matches the first rule, skips the JWT check, and is resolved by the origin as /admin. Whether Access at the edge stopped it depends on how the application's paths were scoped.

The tool you would use to check this misleads. cloudflared tunnel ingress rule <URL> parses the rules with ParseIngress, which never sets DisablePathNormalization, so it always normalizes. In the lab it reported rule 1, the Access rule, for /public/../admin, with and without --disable-path-normalization=true on the command line, while a running connector on default flags compares the raw path. My rule is simple: never separate protected and unprotected content on one hostname with tunnel path rules. Give the public part its own hostname, and its own Access application or none.

How Korur wires it

Korur keeps its Cloudflare configuration in Terraform with the cloudflare/cloudflare provider at ~> 5.27.0, applied from a pipeline rather than a laptop, and runs the connector on Kubernetes, where Argo CD syncs it from Git with pruning and self-healing on. Identity comes from Entra ID. The design follows from the analysis above: the edge decides, the connector proves, and the configuration makes it impossible to publish a hostname without both.

Tunnel, ingress and DNS, reduced from Korur's Terraform modulehcl
resource "cloudflare_zero_trust_tunnel_cloudflared" "stormcloud" {
  account_id = var.account_id
  name       = var.tunnel_name
  config_src = "cloudflare"
  # no tunnel_secret: Cloudflare generates it, so it never enters state
  lifecycle {
    prevent_destroy = true
  }
}

resource "cloudflare_zero_trust_tunnel_cloudflared_config" "stormcloud" {
  account_id = var.account_id
  tunnel_id  = cloudflare_zero_trust_tunnel_cloudflared.stormcloud.id
  config = {
    ingress = concat(
      [for hostname, route in var.tunnel_routes : {
        hostname = hostname
        service  = route.service
        origin_request = {
          access = {
            required  = true
            team_name = var.access_team_name
            aud_tag   = [var.access_aud_tags[hostname]]
          }
          http_host_header   = startswith(route.service, "https://") ? hostname : null
          origin_server_name = startswith(route.service, "https://") ? hostname : null
        }
      }],
      [{ hostname = null, service = "http_status:404", origin_request = null }],
    )
  }
}

resource "cloudflare_dns_record" "tunnel" {
  for_each   = var.tunnel_routes
  zone_id    = var.zone_ids[each.value.zone]
  name       = each.key
  type       = "CNAME"
  content    = "${cloudflare_zero_trust_tunnel_cloudflared.stormcloud.id}.cfargotunnel.com"
  proxied    = true
  ttl        = 1
  depends_on = [cloudflare_zero_trust_tunnel_cloudflared_config.stormcloud]
}

Four choices in that module carry the security argument. The tunnel is remotely managed (config_src = "cloudflare") and declares no tunnel_secret; the provider marks that attribute sensitive and requires at least 32 bytes when set54, and leaving it out means neither the secret nor a token derived from it lands in Terraform state or in a saved plan. Every ingress rule sets access.required with exactly one AUD tag, the one of that hostname's own Access application, so a token minted for one internal application is refused by the connector on every other. The last rule is http_status:404, so a hostname without a rule never reaches the cluster. And the DNS record depends on the ingress configuration, so a hostname only resolves to the tunnel once its rule, and with it the JWT check, exists.

On the Access side there is one self-hosted application per hostname, restricted to a single identity provider with automatic redirect, and one reusable Allow policy whose only Include is a single Entra group, referenced by object ID. I would never use an email-domain rule for administrative interfaces: it admits every account in the tenant. For http_host_header and origin_server_name, the connector dials the in-cluster ingress controller by its Service name, while the controller routes on the Host header and presents the certificate for the public hostname; the two origin parameters set the Host header and the name cloudflared expects in the origin certificate1, so the controller sees the request as if it had come straight from the internet.

The Kubernetes side runs two fixed replicas, never autoscaled. Cloudflare sends each request to the geographically closest replica and does not steer traffic between replicas17, so adding replicas buys availability, not load spreading, and removing one drops whatever it is carrying. Rollouts surge first, so a new replica connects before an old one leaves. The pod runs as a non-root user with all capabilities dropped and a read-only root file system, mounts the token from a Secret through --token-file, and uses /ready for both readiness and liveness. The memory limit is set, the CPU limit deliberately is not: with a 5 second QUIC idle timeout and 1 second keep-alives, a connector throttled by its CFS quota for a few seconds loses its edge connections, and that is a failure I would rather not manufacture. An egress NetworkPolicy allows only DNS to the cluster resolver, TCP and UDP 7844 and TCP 443 to addresses outside the cluster ranges, and the one in-cluster entrypoint the tunnel is allowed to dial. Once a policy with Egress selects the pod, everything not listed is denied, provided the network plugin implements NetworkPolicy55.

None of that stops a workload inside the cluster from calling an origin Service directly, around the connector. That path is the reason the third enforcement point exists, and it is closed by the application validating Cf-Access-Jwt-Assertion itself or by ingress policy on the origin that admits only the controller.

Lab: discovery, rule matching and token validation

Environment, recorded on 2026-11-06: Fedora Linux 43 (Workstation Edition), kernel 7.2.13-100.fc43.x86_64, cloudflared 2026.10.7 (built 2026-10-30), Go 1.26.10, github.com/coreos/go-oidc/v3 v3.17.0, github.com/go-jose/go-jose/v4 v4.1.6, and dig from BIND 9.18.51-dev. No Cloudflare account is needed for steps 1 to 3. The cloudflared binary must be 2026.10.7 for the rule matching output to match.

Step 1: edge discovery records

Resolve what cloudflared resolves at start-upshell
$ dig +short SRV _v2-origintunneld._tcp.argotunnel.com
2 1 7844 region2.v2.argotunnel.com.
1 1 7844 region1.v2.argotunnel.com.
$ dig +short A region1.v2.argotunnel.com | head -3
198.41.192.107
198.41.192.57
198.41.192.67

The SRV answer gives the two regions on port 7844 that ResolveEdge requires, and the addresses fall inside the ranges Cloudflare publishes for region114.

Step 2: ingress rule matching

ingress.yml: a public path rule in front of an Access rule on the same hostyaml
ingress:
  - hostname: app.example.test
    path: ^/public/
    service: http://127.0.0.1:8080
  - hostname: app.example.test
    service: http://127.0.0.1:8080
    originRequest:
      access:
        required: true
        teamName: example
        audTag:
          - 0000000000000000000000000000000000000000000000000000000000000000
  - service: http_status:404
Validate the rules and ask which rule a URL selectsshell
$ cloudflared tunnel --config ingress.yml ingress validate
Validating rules from  ingress.yml
OK
$ cloudflared tunnel --config ingress.yml ingress rule https://app.example.test/public/x
Using rules from ingress.yml
Matched rule #0
	hostname: app.example.test
	path: ^/public/
	service: http://127.0.0.1:8080
$ cloudflared tunnel --config ingress.yml ingress rule 'https://app.example.test/public/../admin'
Using rules from ingress.yml
Matched rule #1
	hostname: app.example.test
	service: http://127.0.0.1:8080
$ cloudflared tunnel --config ingress.yml ingress rule 'https://app.example.test/public/%2e%2e/admin'
Using rules from ingress.yml
Matched rule #1
	hostname: app.example.test
	service: http://127.0.0.1:8080
$ cloudflared tunnel --disable-path-normalization=true --config ingress.yml \
    ingress rule 'https://app.example.test/public/../admin'
Using rules from ingress.yml
Matched rule #1
	hostname: app.example.test
	service: http://127.0.0.1:8080
$ cloudflared tunnel --config ingress.yml ingress rule https://other.example.test/
Using rules from ingress.yml
Matched rule #2
	service: http_status:404

The last dot-segment case is the point: the checker normalizes regardless of the flag, so it reports the Access rule, while a connector running with the 2026.10.7 default would match /public/../admin against rule 0. That half of the comparison comes from reading FindMatchingRule, the flag default in cmd.go and Orchestrator.updateIngress, not from a run, because exercising the running connector needs a live tunnel.

Step 3: the verifier cloudflared builds, exercised

The program builds its verifier exactly as NewJWTValidator does, serves a JWKS from a local test server standing in for the team domain, presents the tokens from the earlier table and counts key set fetches.

Set up the module (run `go mod tidy` only after main.go exists, or it removes both requirements)shell
$ mkdir verifier && cd verifier
$ go mod init lab/verifier
$ go get github.com/coreos/go-oidc/[email protected] github.com/go-jose/go-jose/[email protected]
main.gotext
package main

import (
	"context"
	"crypto/rand"
	"crypto/rsa"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync"
	"time"

	"github.com/coreos/go-oidc/v3/oidc"
	"github.com/go-jose/go-jose/v4"
	"github.com/go-jose/go-jose/v4/jwt"
)

const aud = "lab-aud-tag"

var (
	mu   sync.Mutex
	keys []jose.JSONWebKey // public keys served at /cdn-cgi/access/certs
)

func newKey(kid string) *rsa.PrivateKey {
	k, _ := rsa.GenerateKey(rand.Reader, 2048)
	mu.Lock()
	keys = append(keys, jose.JSONWebKey{Key: &k.PublicKey, KeyID: kid, Algorithm: "RS256", Use: "sig"})
	mu.Unlock()
	return k
}

func sign(k any, alg jose.SignatureAlgorithm, kid string, c jwt.Claims) string {
	opts := (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", kid)
	s, err := jose.NewSigner(jose.SigningKey{Algorithm: alg, Key: k}, opts)
	if err != nil {
		panic(err)
	}
	raw, err := jwt.Signed(s).Claims(c).Serialize()
	if err != nil {
		panic(err)
	}
	return raw
}

func main() {
	fetches := 0
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		mu.Lock()
		defer mu.Unlock()
		fetches++
		_ = json.NewEncoder(w).Encode(jose.JSONWebKeySet{Keys: keys})
	}))
	defer srv.Close()
	iss := srv.URL // stands in for https://<team>.cloudflareaccess.com

	k1 := newKey("k1")
	// Same construction as cloudflared's NewJWTValidator.
	v := oidc.NewVerifier(iss, oidc.NewRemoteKeySet(context.Background(), iss+"/cdn-cgi/access/certs"),
		&oidc.Config{SkipClientIDCheck: true})

	now := time.Now()
	base := func() jwt.Claims {
		return jwt.Claims{Issuer: iss, Audience: jwt.Audience{aud}, Subject: "u1",
			IssuedAt: jwt.NewNumericDate(now), NotBefore: jwt.NewNumericDate(now),
			Expiry: jwt.NewNumericDate(now.Add(time.Hour))}
	}
	check := func(name, tok string) {
		t, err := v.Verify(context.Background(), tok)
		switch {
		case err != nil:
			fmt.Printf("%-28s error  %v\n", name, err)
		case len(t.Audience) == 1 && t.Audience[0] == aud:
			fmt.Printf("%-28s allow\n", name)
		default:
			fmt.Printf("%-28s 403    aud=%v\n", name, t.Audience)
		}
	}

	check("valid", sign(k1, jose.RS256, "k1", base()))
	c := base()
	c.Audience = jwt.Audience{"other-app"}
	check("other application aud", sign(k1, jose.RS256, "k1", c))
	c = base()
	c.Expiry = jwt.NewNumericDate(now.Add(-time.Second))
	check("expired 1s ago", sign(k1, jose.RS256, "k1", c))
	c = base()
	c.NotBefore = jwt.NewNumericDate(now.Add(4 * time.Minute))
	check("nbf 4m in the future", sign(k1, jose.RS256, "k1", c))
	c = base()
	c.NotBefore = jwt.NewNumericDate(now.Add(6 * time.Minute))
	check("nbf 6m in the future", sign(k1, jose.RS256, "k1", c))
	c = base()
	c.Issuer = "https://evil.cloudflareaccess.com"
	check("foreign issuer", sign(k1, jose.RS256, "k1", c))
	check("HS256, key = n bytes", sign(k1.PublicKey.N.Bytes(), jose.HS256, "k1", base()))
	k2, _ := rsa.GenerateKey(rand.Reader, 2048)
	forged := sign(k2, jose.RS256, "k1", base())
	check("RS256, unpublished key", forged)
	before := fetches
	for i := 0; i < 100; i++ {
		_, _ = v.Verify(context.Background(), forged)
	}
	fmt.Printf("JWKS fetches caused by 100 forged tokens: %d\n", fetches-before)
	k3 := newKey("k3") // rotation: new key published after the verifier cached k1
	before = fetches
	check("RS256, rotated kid k3", sign(k3, jose.RS256, "k3", base()))
	fmt.Printf("JWKS fetches caused by kid k3: %d\n", fetches-before)
}
Output of go mod tidy && go vet . && go run . (timestamps, the test server port and the forged-token fetch count differ per run)shell
$ go mod tidy && go vet . && go run .
valid                        allow
other application aud        403    aud=[other-app]
expired 1s ago               error  oidc: token is expired (Token Expiry: 2026-11-06 00:31:32 +0300 +03)
nbf 4m in the future         allow
nbf 6m in the future         error  oidc: current time 2026-11-06 00:31:33.198749651 +0300 +03 m=+0.073242719 before the nbf (not before) time: 2026-11-06 00:37:33 +0300 +03
foreign issuer               error  oidc: id token issued by a different provider, expected "http://127.0.0.1:42587" got "https://evil.cloudflareaccess.com"
HS256, key = n bytes         error  oidc: malformed jwt: unexpected signature algorithm "HS256"; expected ["RS256"]
RS256, unpublished key       error  failed to verify signature: failed to verify id token signature
JWKS fetches caused by 100 forged tokens: 100
RS256, rotated kid k3        allow
JWKS fetches caused by kid k3: 1

The forged-token count is not stable from run to run. Over 20 runs of the same binary it ranged from 66 to 100 and was exactly 100 in 12 runs; the run above is one of those. The spread comes from the window described earlier: because inflight.done releases the waiters before r.inflight is set back to nil, the next sequential Verify sometimes attaches to the fetch that has just finished, and how often depends on goroutine scheduling. The rotation case returned one fetch in all 20 runs. Three results are worth keeping. The nbf window is five minutes and the exp window is zero, as Verify reads. Key rotation costs exactly one fetch, which is the behaviour the Access rotation schedule relies on. And a forged signature under a known kid costs up to one fetch per attempt, which is the reason for the refresh floor recommended earlier. The HS256 case is the classic algorithm-confusion attempt, using public key material as an HMAC secret; it never reaches signature verification because the algorithm list is pinned.

Step 4: a live connector (inspected, not run)

These commands need a Cloudflare account and a remotely managed tunnel, so I list them with the output their source code determines rather than a captured run. createUDPConnForConnIndex in connection/quic.go opens each QUIC socket with net.ListenUDP and never connects it25, so ss shows the sockets as UNCONN with a wildcard peer such as 0.0.0.0:*, and port 7844 never appears in its output; filter by process name instead, and use a capture to see the edge addresses. Replace token with a file holding the tunnel token.

Inspected: requires a tunnel tokenshell
$ cloudflared tunnel --no-autoupdate --metrics 127.0.0.1:2000 run --token-file ./token &
$ curl -s 127.0.0.1:2000/ready
# body fields per metrics/readiness.go: status, readyConnections, connectorId
$ curl -s 127.0.0.1:2000/metrics | grep -E '^cloudflared_tunnel_ha_connections'
$ ss -uanp | grep cloudflared   # under QUIC: one UNCONN socket per connection index, wildcard peer
$ sudo tcpdump -ni any udp port 7844   # root: shows the edge peers on port 7844
$ base64 -d ./token | jq 'keys'   # expect ["a","s","t"], plus "e" when an endpoint is set

The metric name comes from Cloudflare's metrics reference56. The last command prints only the field names, but the decoded token contains the tunnel secret, so do not drop the jq filter on a token that is still in use.

Failure modes and where they come from

Failures seen from the browser, mapped to the layer and mechanism
SymptomLayerMechanismWhat I do about it
Cloudflare error 1033 or 1016EdgeNo connector holds a connection. The troubleshooting page attributes 1033 to a tunnel not connected57; the DNS records page says visitors see 1016 when a tunnel stops2Check /ready on every replica and egress to port 7844
502 while the tunnel is healthycloudflared to originConnection refused, wrong port, protocol mismatch or a certificate that does not match the hostname57Set originServerName and httpHostHeader for HTTPS origins
Proxy error for a logged-in usercloudflared Access middlewareExpired, not-yet-valid or otherwise invalid token is returned as an error, not a 403Alert on error while processing middleware handler AccessJWTValidator; keep connector clocks synchronised
403 Invalid token in jwtcloudflared Access middlewareThe token's aud is not in the rule's audTag, typically after an Access application was recreated with a new AUDFeed aud_tag from the application resource, never a copied string
Removed user still has accessAccess sessionsGroup membership is read from the identity provider at authentication38; application and policy session expiry rechecks the stored identity37Short global session for the team; revoke on removal; SCIM group-change reauthentication
Protected path reachable through a public rulecloudflared ingressPath normalization is off by default in 2026.10.7 and the edge forwards the original pathOne hostname per protection level
Leaked tunnel tokenTunnel control planeThe token contains the tunnel secret; a refresh blocks new connections but leaves running connectors, an attacker's included, connected6Refresh, delete all tunnel connections through the API, then restart replicas with the new token
Connector quietly on HTTP/2TransportUnder auto, failed UDP makes cloudflared fall back7 to TCP with the h2.cftunnel.com server name18; the post-quantum curve offer stays the same in 2026.10.720Allow UDP 7844 egress, or pin the protocol knowing the trade

The tunnel's transport is robust; the weak points sit at the seams: between what the edge evaluates and what the connector matches, between when Access decided and when the token is checked, and between the connector and everything else that can reach the origin. Access at the edge is necessary, and on its own it is a single check that the rest of the path takes on trust. Setting access.required with the hostname's own AUD tag makes the connector a second, independent check at almost no cost. Validating the header in the application closes the last path, the one that never touches the tunnel at all.

Bronnen

  1. Origin configuration parameters Cloudflare
  2. Cloudflare Tunnel: DNS records Cloudflare
  3. Validate JWTs Cloudflare
  4. cloudflared 2026.10.7: connection/connection.go (TunnelToken) Cloudflare, GitHub
  5. cloudflared 2026.10.7: cmd/cloudflared/tunnel/subcommands.go (ParseToken) Cloudflare, GitHub
  6. Tunnel permissions Cloudflare
  7. Tunnel run parameters Cloudflare
  8. proc_pid_cmdline(5) Linux man-pages
  9. Distribute Credentials Securely Using Secrets Kubernetes
  10. proc_pid_environ(5) Linux man-pages
  11. environ(7) Linux man-pages
  12. cloudflared 2026.10.7: edgediscovery/allregions/discovery.go Cloudflare, GitHub
  13. cloudflared 2026.10.7: edgediscovery/allregions/regions.go Cloudflare, GitHub
  14. Tunnel with firewall Cloudflare
  15. cloudflared 2026.10.7: cmd/cloudflared/tunnel/cmd.go (flag defaults) Cloudflare, GitHub
  16. cloudflared 2026.10.7: supervisor/supervisor.go Cloudflare, GitHub
  17. Tunnel availability and failover Cloudflare
  18. cloudflared 2026.10.7: connection/protocol.go Cloudflare, GitHub
  19. cloudflared 2026.10.7: supervisor/tunnel.go (edge dial and serveHTTP2) Cloudflare, GitHub
  20. cloudflared 2026.10.7: crypto/curves.go Cloudflare, GitHub
  21. cloudflared 2026.10.7: features/selector.go Cloudflare, GitHub
  22. cloudflared 2026.10.7: RELEASE_NOTES Cloudflare, GitHub
  23. cloudflared 2026.10.7: quic/constants.go Cloudflare, GitHub
  24. RFC 9000: QUIC: A UDP-Based Multiplexed and Secure Transport IETF
  25. cloudflared 2026.10.7: connection/quic.go Cloudflare, GitHub
  26. cloudflared 2026.10.7: connection/quic_connection.go Cloudflare, GitHub
  27. cloudflared 2026.10.7: tunnelrpc/registration_client.go Cloudflare, GitHub
  28. cloudflared 2026.10.7: tunnelrpc/proto/tunnelrpc.capnp Cloudflare, GitHub
  29. cloudflared 2026.10.7: tunnelrpc/quic/cloudflared_server.go Cloudflare, GitHub
  30. cloudflared 2026.10.7: orchestration/orchestrator.go Cloudflare, GitHub
  31. cloudflared 2026.10.7: metrics/readiness.go Cloudflare, GitHub
  32. cloudflared 2026.10.7: tunnelrpc/quic/protocol.go Cloudflare, GitHub
  33. cloudflared 2026.10.7: connection/http2.go Cloudflare, GitHub
  34. Access policies Cloudflare
  35. Service tokens Cloudflare
  36. Session management Cloudflare
  37. Microsoft Entra ID as an identity provider Cloudflare
  38. RFC 7515: JSON Web Signature (JWS) IETF
  39. Application token Cloudflare
  40. RFC 7517: JSON Web Key (JWK) IETF
  41. OpenID Connect Core 1.0, section 10.1.1: Rotation of Asymmetric Signing Keys OpenID Foundation
  42. cloudflared 2026.10.7: ingress/ingress.go Cloudflare, GitHub
  43. cloudflare_zero_trust_tunnel_cloudflared_config, provider v5.27.0 Cloudflare, GitHub
  44. cloudflared 2026.10.7: ingress/middleware/jwtvalidator.go Cloudflare, GitHub
  45. RFC 7519: JSON Web Token (JWT) IETF
  46. RFC 8725: JSON Web Token Best Current Practices IETF
  47. go-oidc v3.17.0: oidc/verify.go CoreOS, GitHub
  48. cloudflared 2026.10.7: proxy/proxy.go Cloudflare, GitHub
  49. go-oidc v3.17.0: oidc/jwks.go CoreOS, GitHub
  50. cloudflared commit 059f86a: VULN-141859, normalize request path when using access rules Cloudflare, GitHub
  51. URL normalization settings Cloudflare
  52. How URL normalization works Cloudflare
  53. cloudflare_zero_trust_tunnel_cloudflared, provider v5.27.0 Cloudflare, GitHub
  54. Network Policies Kubernetes
  55. Tunnel metrics Cloudflare
  56. Cloudflare Tunnel: common errors Cloudflare

Mogen we meten hoe u hier kwam?

Wij gebruiken analytische cookies om te zien welke pagina's werken en welke advertentie u hier bracht. Weigert u, dan werkt de site precies hetzelfde en plaatsen wij geen analytische cookies. Cookiebeleid