feat(19.3-02): Cloudflare Turnstile verification as turnstile:open|closed middleware

- bouncer: Turnstile.Verify posts secret/response/remoteip to siteverify with
  a 5 s bound and PHP's open and closed modes (503 unconfigured in production,
  422 on a missing, rejected or overlong token, an error or a timeout); errors
  never carry the secret or the token
- bouncer: Turnstile.Middleware reads the token from the query, a JSON body or
  a form body, restores the body and writes refusals through a published
  TurnstileWriter or neutral JSON
- surf: factory turnstile:open|closed from turnstile.secret/turnstile.field
  (a published *bouncer.Turnstile wins), client IP with trusted proxies; any
  other param fails boot
- docs: Turnstile section, middleware table, README rows
This commit is contained in:
Jakub Zych
2026-10-15 17:54:58 +02:00
parent 5055e8bb61
commit 597c79bae7
7 changed files with 469 additions and 5 deletions

View File

@@ -27,7 +27,7 @@ Use cases:
- Overlapping constrained routes: two routes that ServeMux would refuse side by side, such as `/shelves/items/{id}` and `/shelves/{shelfId}/follow`, boot as one overlap family when their constraints keep them apart. Requests are tried against the family's routes in registration order, as Laravel does, and each route keeps its own path values and middleware.
- Named middleware from plugins (`pact.HasMiddleware`), parameterized middleware used as `name:param` (`pact.HasMiddlewareFactories`) and house middleware for the JSON envelope and error handling (`pact.HasHouseMiddleware`). Duplicate or unknown names fail boot.
- Raw groups (`surf.Router.GroupRaw`) for routes that must not be wrapped in house middleware, such as webhooks or file streams: house middleware is refused there, the default body limit is skipped and a panic returns a bare 500.
- Built-in middleware names: `throttle:<bucket>` or `throttle:<max>,<minutes>`, `body.limit:<bytes>`, `cors:<profile>`, `locale.from-principal`, plus `backend` (the admin guard) when the admin is enabled.
- Built-in middleware names: `throttle:<bucket>` or `throttle:<max>,<minutes>`, `body.limit:<bytes>`, `cors:<profile>`, `turnstile:open` and `turnstile:closed` (Cloudflare Turnstile through `bouncer.Turnstile`, built from `turnstile.secret`, with the client IP from `surf.ClientIP` and refusals written by a published `bouncer.TurnstileWriter` when there is one), `locale.from-principal`, plus `backend` (the admin guard) when the admin is enabled.
- Named CORS profiles: `cors:<profile>` applies `http.cors_profiles.<profile>` (read by `surf.LoadCORSProfiles`, validated like `http.cors`) to a route group, and surf registers an `OPTIONS` route for each such path that answers the preflight from the profile, since ServeMux would answer it with 405 before the middleware runs. An unknown profile, two profiles on one path and a profiled path that `http.cors.paths` also matches fail boot.
- Fixed-window rate limiting (`surf.FixedWindowLimiter`): named buckets from plugins that implement `surf.BucketProvider`, or inline limits keyed by the signed-in user, or by client IP for guests. Rejected requests get a 429 with `Retry-After` and `X-RateLimit-*` headers. The in-process `surf.MemoryStore` sits behind the `surf.Store` interface; `surf.BuildRouter` uses a `surf.Store` published on the app instead when there is one, which is how `serve` shares counters across instances through [cooler](../cooler/README.md)'s Redis store (`http.rate_limit.store: redis`).
- Client IP resolution for limiter keys (`surf.ClientIP`) that only trusts `X-Forwarded-For` hops when the direct peer is inside a configured trusted proxy range (`surf.TrustedProxies`).
@@ -159,6 +159,8 @@ The generated application `main` wires surf in with `surf.ServeCommand` and `sur
| `http.cors.max_age` | `0` | Preflight cache time in seconds. |
| `http.cors.supports_credentials` | `false` | Sends `Access-Control-Allow-Credentials: true`. Combined with `*` in `allowed_origins` it fails boot. With credentials, a pattern or several origins, every response on a CORS path carries `Vary: Origin`, preflights and disallowed origins included. |
| `http.cors_profiles.<name>.*` | none | A CORS profile for `cors:<name>`: the `http.cors` keys except `paths` (`allowed_origins`, `allowed_origins_patterns`, `allowed_methods`, `allowed_headers`, `exposed_headers`, `max_age`, `supports_credentials`), validated the same way. Names use lower-case letters, digits, underscore and dash. |
| `turnstile.secret` | empty | Cloudflare Turnstile secret for `turnstile:open` and `turnstile:closed`. Without it `turnstile:open` passes and `turnstile:closed` answers 503 in the production environment (passes elsewhere). A `*bouncer.Turnstile` published on the app replaces the verifier built from this key. Environment: `SUMMER_TURNSTILE__SECRET`. |
| `turnstile.field` | `turnstile_token` | Request field (query, JSON body or form body) carrying the Turnstile token. |
| `http.rate_limit.store` | `memory` | Where `throttle` counters live: `memory` (per instance) or `redis` (shared by every instance through [cooler](../cooler/README.md), which then needs `redis.url`). Only `serve` installs the Redis store; `route:list` keeps the memory store and never dials Redis. Any other value fails at boot. Environment: `SUMMER_HTTP__RATE_LIMIT__STORE`. |
| `http.access_log` | `false` | Logs one `http request` record per request (method, matched pattern, status, duration in milliseconds; never the path or query). Environment: `SUMMER_HTTP__ACCESS_LOG`. |
| `storage.uploads.serve` | `false` | Mounts the uploads route `GET <storage.uploads.public_path_prefix>/{path...}` (prefix default `/storage/uploads`; it must then be an absolute URL path, or start-up fails) on `attach.StaticHandlerPublic` with `X-Content-Type-Options: nosniff`, a sandboxing CSP and `Content-Disposition: attachment` for anything but a raster image. Prefer a separate origin for uploads in production. Environment: `SUMMER_STORAGE__UPLOADS__SERVE`. |

View File

@@ -9,6 +9,7 @@ import (
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/party"
@@ -437,6 +438,9 @@ func (r *Router) wrap(rt route) (http.Handler, error) {
return nil, fmt.Errorf("surf: plugin %q route %s %s references unknown CORS profile %q (define http.cors_profiles.%s)", rt.pluginID, rt.method, rt.path, param, param)
}
}
if base == "turnstile" && param != "open" && param != "closed" {
return nil, fmt.Errorf("surf: plugin %q route %s %s: turnstile:%s must be turnstile:open or turnstile:closed", rt.pluginID, rt.method, rt.path, param)
}
if base == "body.limit" {
if _, err := parseBodyLimit(param); err != nil {
return nil, fmt.Errorf("surf: plugin %q: %w", rt.pluginID, err)
@@ -521,6 +525,20 @@ func BuildRouter(app *backpack.App, plugins []party.Plugin) (*Router, error) {
}); err != nil {
return nil, err
}
turnstile, turnstileField := buildTurnstile(app)
if err := r.RegisterMiddlewareFactory("surf", "turnstile", func(param string) pact.Middleware {
// wrap refuses a param other than open or closed before this runs.
var write bouncer.TurnstileWriter
if app != nil {
if pub, ok := app.Lookup[bouncer.TurnstileWriter](); ok && pub != nil {
write = pub
}
}
clientIP := func(req *http.Request) string { return ClientIP(req, trusted) }
return turnstile.Middleware(param == "closed", turnstileField, clientIP, write)
}); err != nil {
return nil, err
}
if app != nil {
corsCfg, err := LoadCORSConfig(app.Config)
if err != nil {
@@ -620,6 +638,25 @@ func BuildRouter(app *backpack.App, plugins []party.Plugin) (*Router, error) {
return r, nil
}
// buildTurnstile returns the verifier behind turnstile:open|closed and the
// token field: a *bouncer.Turnstile published on the app wins, else one built
// from turnstile.secret, with Production set in the production environment.
// turnstile.field defaults to bouncer.DefaultTurnstileField.
func buildTurnstile(app *backpack.App) (*bouncer.Turnstile, string) {
field := bouncer.DefaultTurnstileField
if app == nil || app.Config == nil {
return bouncer.NewTurnstile("", false), field
}
if f := strings.TrimSpace(app.Config.String("turnstile.field")); f != "" {
field = f
}
if pub, ok := app.Lookup[*bouncer.Turnstile](); ok && pub != nil {
return pub, field
}
production := strings.EqualFold(strings.TrimSpace(app.Config.Environment()), "production")
return bouncer.NewTurnstile(strings.TrimSpace(app.Config.String("turnstile.secret")), production), field
}
// checkAdminPrefix fails boot when a plugin other than cabana owns a route at
// or under the admin prefix: the admin SPA and API own that whole subtree.
func (r *Router) checkAdminPrefix(prefix string) error {

View File

@@ -3,11 +3,13 @@ package surf
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
@@ -262,3 +264,86 @@ func TestCORSProfileSmoke(t *testing.T) {
t.Fatalf("BuildRouter with cors:missing error = %v", err)
}
}
// turnstileRoutes declares POST /guest (turnstile:closed) and POST /register
// (turnstile:open); both echo the body they received.
func turnstileRoutes(closedMW, openMW string) routesPluginFunc {
echo := func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(b)
}
return routesPluginFunc{id: "acme.guest", routes: func(r pact.Router) {
r.Post("/guest", echo, closedMW)
r.Post("/register", echo, openMW)
}}
}
func TestTurnstileMiddlewareSmoke(t *testing.T) {
var calls atomic.Int64
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
_ = r.ParseForm()
ok := r.PostForm.Get("response") == "ok" && r.PostForm.Get("secret") == "test-secret"
w.Header().Set("Content-Type", "application/json")
if ok {
_, _ = io.WriteString(w, `{"success":true}`)
return
}
_, _ = io.WriteString(w, `{"success":false,"error-codes":["invalid-input-response"]}`)
}))
defer fake.Close()
files := func() map[string]string { return map[string]string{"http.yaml": transportBodyLimits} }
post := func(h http.Handler, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
// A configured verifier (published, pointed at the fake).
app := transportApp(t, "development", files())
verifier := bouncer.NewTurnstile("test-secret", false)
verifier.Endpoint = fake.URL
if err := app.Publish[*bouncer.Turnstile](verifier); err != nil {
t.Fatal(err)
}
h, err := Assemble(app, []party.Plugin{turnstileRoutes("turnstile:closed", "turnstile:open")})
if err != nil {
t.Fatal(err)
}
body := `{"turnstile_token":"ok","name":"x"}`
if rec := post(h, "/guest", body); rec.Code != http.StatusOK || rec.Body.String() != body {
t.Fatalf("guest with a good token = %d %q, want 200 and the full body", rec.Code, rec.Body.String())
}
if rec := post(h, "/guest", `{"turnstile_token":"bad","name":"x"}`); rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("guest with a bad token = %d, want 422", rec.Code)
}
// Open mode with no secret passes without a siteverify call.
before := calls.Load()
h, err = Assemble(transportApp(t, "development", files()), []party.Plugin{turnstileRoutes("turnstile:closed", "turnstile:open")})
if err != nil {
t.Fatal(err)
}
if rec := post(h, "/register", `{"name":"x"}`); rec.Code != http.StatusOK {
t.Fatalf("open mode without a secret = %d, want 200", rec.Code)
}
if calls.Load() != before {
t.Fatal("open mode without a secret called siteverify")
}
// Closed mode with no secret in production is unavailable.
h, err = Assemble(transportApp(t, "production", files()), []party.Plugin{turnstileRoutes("turnstile:closed", "turnstile:open")})
if err != nil {
t.Fatal(err)
}
if rec := post(h, "/guest", body); rec.Code != http.StatusServiceUnavailable {
t.Fatalf("closed mode unconfigured in production = %d, want 503", rec.Code)
}
if _, err := BuildRouter(transportApp(t, "development", files()), []party.Plugin{turnstileRoutes("turnstile:maybe", "turnstile:open")}); err == nil || !strings.Contains(err.Error(), "turnstile:maybe") {
t.Fatalf("turnstile:maybe error = %v", err)
}
}