Turnstile
Cloudflare Turnstile verification for the endpoints that have to be unauthenticated — sign-up, login, recovery, waitlists.
Some endpoints cannot require a token, because getting a token is what they are for: sign-up, login, password recovery, waitlists, a public chat that costs money per message. Cloudflare Turnstile puts a challenge in front of them. The browser or webview solves it, the client sends the resulting token with the request, and the server asks Cloudflare whether that token is good before the handler runs.
github.com/redelay/go-framework/server/turnstile verifies tokens and gates
routes. modules/turnstile wires it from the environment.
Wire it up
import _ "github.com/redelay/go-framework/modules/turnstile"
TURNSTILE_SECRET_FILE=/run/secrets/turnstile_secret
TURNSTILE_ROUTES=POST /api/v1/users/,POST /api/v1/login/recover/*
TURNSTILE_REPORT_ROUTES=POST /api/v1/waitlist # optional, go-framework ≥ v0.43.0
That is the whole integration. The routes worth protecting are registered by modules the app does not own, so they are named in configuration rather than declared at each handler.
With a secret but no routes — or routes but no secret — the app still serves, and
says so at WARN. A deployment that verifies nothing while reading as though it
does is the failure this is built to prevent, so it is never left to be inferred
from a missing log line.
Report mode
go-framework ≥ v0.43.0. TURNSTILE_REPORT_ROUTES takes the same patterns as TURNSTILE_ROUTES. A route
there is verified exactly as an enforced one would be, and the outcome is logged
and observed, but the request is always served. It is how a route gets real
numbers ("how many callers arrive without a token? from which clients?") before
anyone decides to enforce on it. Switching on enforcement is then moving the
pattern from one list to the other.
- A request matching both lists is enforced: report mode never weakens a gate. The module warns at boot, naming the overlapping patterns.
TURNSTILE_FAIL_OPENdoes not apply. A report route serves whatever the outcome.- Report routes alone are enough to install the guard;
TURNSTILE_ROUTESmay be empty. - The module logs each report decision as
turnstile: report: would allow(DEBUG),would refuse(INFO),siteverify unavailable(WARN) ormisconfigured(ERROR).
In code, turnstile.WithReportRoutes(patterns...) is the option behind it (it
panics on an unparseable pattern, like Guard), and turnstile.Overlapping(a, b)
returns the patterns two lists share.
Route patterns
METHOD /path, where * matches one segment and ** matches the rest. The
method may be *, or omitted entirely, to match any.
POST /api/v1/users/
POST /api/v1/login/recover/*
* /api/v1/waitlist
A trailing slash is insignificant on both sides. chi serves /users/ and
/users, so a gate catching only one spelling would read as protection without
being any. Dotted and doubled-slash paths are matched in resolved form too.
An unparseable pattern fails the boot. Skipping it would leave the route it names ungated while the configuration reads as though it were protected.
Choosing which routes to gate
Gate the endpoints that a stranger can reach and that do work on their behalf: create an account, send mail or SMS, spend money. Leave authenticated endpoints alone — a challenge there only inconveniences people who are already signed in, and abuse by a named account is a rate-limiting problem, not a bot problem.
Do not decide this from security in /openapi.json. In this framework
modules.Security("BearerAuth") is spec metadata; it documents a route, it
does not enforce anything. Enforcement comes from middleware, so a route can
declare no security and still answer 401 — and the spec will not tell you.
The only reliable test is to ask the running service. Probe each candidate with deliberately invalid input and read 401 against anything else:
# from inside the container, if the edge restricts who may call the API
cid=$(docker ps -q -f name=<stack>_api. | head -1)
pid=$(docker inspect -f '{{.State.Pid}}' "$cid")
nsenter -t "$pid" -n curl -s -o /dev/null -w '%{http_code}\n' \
-X POST -H 'Content-Type: application/json' -d '{}' \
http://localhost:8080/api/v1/<route>
401 means auth is enforced and Turnstile is the wrong tool. Anything else —
400, 403, 200 — means a stranger reaches it. Invalid input is refused
before any work happens, so the probe is safe to run against production.
One caveat: an enumeration-safe endpoint answers success for any input by
design. POST /login/recover/{email} returns 200 "password recovery email sent"
for a string that is not an address, which is correct behaviour and also exactly
why it needs gating.
A probe answers is it enforced. It does not answer does anyone call it, and that second question is where gates usually fail: when two routes do the same job, gating one and leaving its twin open protects nothing while reading as protection. Grep the client repos for call sites before fixing a list — a list built from what is registered, rather than from what clients use, invites exactly that mistake.
Some endpoints can never carry a token, whatever the client does, and must
never end up inside a wildcard: an RFC 8058 one-click unsubscribe is POSTed by
the recipient's mail client, with no browser and no JavaScript to render a
widget. Webhooks and callbacks from third parties are the same. Gating one does
not inconvenience a user — it silently breaks deliverability or an integration.
Prefer exact patterns over * wherever such a sibling exists, and say why in a
comment next to the configuration, because the wildcard is exactly the kind of
thing a later tidy-up introduces.
Wildcards also matter for metrics: label by the matched pattern, never the request path (see Observability).
Server-to-server paths are unaffected either way. The guard is HTTP middleware, so in-process service calls and event handlers never pass through it — a flow reacting to an event does not need a token.
Where the token comes from
The header CF-Turnstile-Response first, then a turnstile_token field in a
JSON or form-encoded body. Reading the body to find it leaves the body intact for
the handler.
The header is the only option for routes that carry no body — POST /login/recover/{email} takes the address in the path. Form-encoded support is
what lets the OAuth2 password flow be gated.
Set TURNSTILE_TOKEN_HEADER or TURNSTILE_TOKEN_FIELD to rename them; setting
one and leaving the other empty disables the other source.
What the caller gets back
| Situation | Status | code |
|---|---|---|
| No token on a gated route | 403 | turnstile_required |
| Cloudflare rejected the token | 403 | turnstile_invalid |
| Token already used, or expired | 403 | turnstile_expired |
| Our own secret is wrong | 500 | turnstile_misconfigured |
| siteverify unreachable | 503 | turnstile_unavailable |
Bodies keep the usual {"detail": "..."} shape and add code, so a client can
tell "solve it again" from "this is the server's fault" without parsing prose.
Tokens are single-use. A request that fails after verification needs a fresh
token, not a retry of the same one — on turnstile_expired the client should
reset the widget.
Telling the server why there is no token
A client that sends no token can say why in X-Turnstile-Client
(turnstile.ClientStateHeader):
| Value | Meaning |
|---|---|
unavailable | no widget could run on this client |
timeout | the challenge did not answer in time |
error | the widget reported an error |
superseded | a newer challenge replaced this one |
Anything else is recorded as other. The header is recorded, never trusted:
it changes no decision. It separates "this client could not have produced a
token" from "the challenge did not answer in time", which is the question report
mode is there to answer. Because the value set is closed, it is safe as a log
field or metric label whatever a client sends.
Deliberate choices
- CORS preflights are never gated. A browser sends
OPTIONSwithout a token and will not send the real request if it fails. - An unreachable siteverify fails closed (503).
TURNSTILE_FAIL_OPEN=truereverses that; it never admits a token Cloudflare actively rejected. - A bad secret is a 500, not a 403. It is not something the caller can fix by trying again, and it should page you, not them.
- A body too large to buffer is refused, not waved through. Truncated JSON cannot parse, but truncated form data parses fine, so without the cap the guard would decide on a partial read of a body the handler then sees in full.
Defence in depth
TURNSTILE_HOSTNAMES requires the hostname that solved the challenge to be one
of a list, behind the widget's own allowlist. Native webviews report the scheme's
host, so a Capacitor app needs localhost in both places. TURNSTILE_ACTION
does the same for the widget's action.
Testing
Cloudflare publishes test secrets. Use them so suites run the real verification path with a deterministic answer, rather than a flag that skips verification and leaves the gate untested:
| Constant | Secret | Answer |
|---|---|---|
TestSecretAlwaysPasses | 1x0000000000000000000000000000000AA | every token verifies |
TestSecretAlwaysFails | 2x0000000000000000000000000000000AA | every token fails |
TestSecretAlwaysSpent | 3x0000000000000000000000000000000AA | timeout-or-duplicate |
Where a suite has no egress, point TURNSTILE_VERIFY_URL at a stub instead.
Observability
turnstile.WithObserver (or modules/turnstile.AddObserver) is called for every
gated or reported request with a turnstile.Event:
| Field | |
|---|---|
Method, Path | the request as sent (Path is the raw r.URL.Path) |
Pattern | the path part of the configured pattern that matched, e.g. /api/v1/items/*/vote (go-framework ≥ v0.43.1) |
Outcome | allowed, missing_token, invalid, expired, misconfigured, unavailable, failed_open |
Report | true on a report-only route: the outcome is what enforcement would have decided |
ClientState | from X-Turnstile-Client, see above; "" when absent |
Result, Err, Duration | Cloudflare's verdict, any error, time spent |
Use Pattern, not Path, as a metric label. Under a * or ** pattern,
Path is whatever the caller sent, so a series per path hands them the
cardinality of your Prometheus. Pattern is a closed set fixed by
configuration; with a literal pattern it equals the path.
The module logs every event: DEBUG when verified, INFO on a rejection,
WARN when siteverify is unavailable, and ERROR when our own secret is wrong,
since that one means every gated request is failing. Report routes log as
described under Report mode.
Metrics
go-modules metrics.TurnstileDecision is a ready-made observer:
import (
"github.com/redelay/go-modules/metrics"
turnstilemod "github.com/redelay/go-framework/modules/turnstile"
)
turnstilemod.AddObserver(metrics.TurnstileDecision)
It counts turnstile_decisions_total{route, outcome}, every decision rather than
only refusals, so a non-zero outcome="allowed" proves the observer is wired.
route is Event.Pattern (go-modules ≥ v0.83.1; earlier versions used the raw
path). The counter is created lazily: no series exists until the first decision
after boot.
Alert on the outcome values, not the HTTP codes: the response code
turnstile_required is outcome="missing_token", turnstile_invalid is
invalid, turnstile_expired is expired.
A tokenless request that explains itself (go-modules ≥ v0.84.2)
A request with no token is not one thing. A client that cannot produce one
says why in X-Turnstile-Client (see Telling the server why there is no token), and
the counter records that reason as its own outcome instead of folding it into
missing_token:
| outcome | what it means |
|---|---|
missing_token | no token and no explanation — a client that predates the header, or the header dropped in transit by a proxy, a CORS preflight or a missing forward. This is the one to alert on. |
client_unavailable | no widget could run on that client |
client_timeout | the challenge did not answer in time |
client_error | the widget reported an error |
client_superseded | a newer challenge replaced this one |
client_other | the header carried something outside the set |
The set is closed, so the label cannot be grown by a caller: at most twelve
outcomes per route (seven gate outcomes plus five client_*).
Only a missing token is mapped. Event.ClientState is filled from the
header on every request, including ones that carried a good token, so a
request with both is decided by the token — allowed, invalid or expired —
and the header is ignored. A client cannot move its own requests out of
invalid by setting a header.
Reading a dashboard across the upgrade: missing_token drops as clients
that explain themselves move into their own buckets. That is the point, and it
looks exactly like a fix. An alert on missing_token becomes sharper — it now
means the header is genuinely not arriving, rather than that plus every
client-side failure.
To prove the wiring in production without writing anything, send one request
without a token to an enforced route. The guard refuses it with 403
before the handler runs, so no row, mail or event is created, and
missing_token goes to 1. Never probe a report route this way: it serves the
request.
Environment
| Variable | Default | |
|---|---|---|
TURNSTILE_SECRET | — | secret key; prefer the _FILE form |
TURNSTILE_SECRET_FILE | — | path to a file holding the secret |
TURNSTILE_ROUTES | — | comma-separated route patterns, enforced |
TURNSTILE_REPORT_ROUTES | — | comma-separated route patterns, verified and reported but never refused (≥ v0.43.0) |
TURNSTILE_HOSTNAMES | — | allowed challenge hostnames |
TURNSTILE_ACTION | — | required widget action |
TURNSTILE_FAIL_OPEN | false | serve when siteverify is unreachable |
TURNSTILE_VERIFY_URL | Cloudflare's | override, for stubs |
TURNSTILE_TIMEOUT | 5s | per-call timeout |
TURNSTILE_TOKEN_HEADER | CF-Turnstile-Response | |
TURNSTILE_TOKEN_FIELD | turnstile_token | |
TURNSTILE_MAX_BODY_BYTES | 1048576 | body buffer cap |
A note on Bot Fight Mode
Cloudflare's zone-wide Bot Fight Mode is a different tool, and on the free tier it
cannot be skipped by WAF rules. It challenges everything, including native
webviews whose origin is http://localhost and whose user agent is not a browser's.
Turnstile is the targeted alternative: it protects the handful of endpoints that
need it without putting a challenge in front of an app's ordinary traffic.