Assign identifiers on the server for pricing_page on Production
pending
PRODUCTION
What changes
Draft a pull request to assign Flagsmith identifiers on the server (review and open it yourself; Gatecrasher never pushes code). pr.draft Guidance only, never executed
PR draft
Assign visitor identifier on the server so users can't pick their experiment group
## Problem
The `pricing_page` price test buckets visitors by identifier. The identifier was generated in the browser (`crypto.randomUUID()`) and stored in a cookie that JavaScript could write. Anyone could change `acme_visitor` or re-roll it until they landed in `price_low`. The scan reproduced this: about half of arbitrary identifiers get `price_low`.
## Fix
- `main.go`: new `GET /api/session` endpoint. It reads the `acme_visitor` cookie and accepts it only if it matches the format the server issues (`visitor-` followed by 32 hex characters). Otherwise it generates a new identifier with `crypto/rand` and sets it as an `HttpOnly`, `SameSite=Lax` cookie, with `Secure` when served over TLS. It returns `{"identifier": ...}`.
- `app.js`: `visitorId()` now fetches the identifier from `/api/session` instead of generating it and writing the cookie. The browser can no longer create or overwrite the identifier through `document.cookie`.
Cookies set earlier by the browser don't match the new format, so those visitors get a new server-assigned identifier once and then keep it.
## Limits (please read)
- The identifier is still passed to the Flagsmith client SDK, and the client-side environment key is public by design. A determined user can still call the Flagsmith API directly with any identifier. This change stops casual tampering through the app's cookie but does not fully prevent it.
- To close it completely, evaluate `pricing_page` on the server for the server-assigned identifier (using the server-side key) and send only the resulting price to the page. That is a larger change, so it is not part of this PR.
- The `plan` trait is still set from the browser. That is a separate finding and is untouched here.
## Testing
- Load `/` with no cookies and confirm an `acme_visitor` cookie is set with the `HttpOnly` flag.
- Confirm `document.cookie` does not show `acme_visitor`.
- Reload and confirm the same identifier and variant are kept.
- Send a request with a forged `acme_visitor` value and confirm `/api/session` replaces it.Proposed change (a suggestion to review; Gatecrasher never applies it):
--- a/app.js+++ b/app.js@@ -10,15 +10,11 @@ return hit ? decodeURIComponent(hit.split("=")[1]) : null; } -// Each visitor gets a random browser-generated ID kept in a cookie.-function visitorId() {- let id = cookie("acme_visitor");- if (!id) {- id = "visitor-" + crypto.randomUUID();- document.cookie = "acme_visitor=" + id + "; path=/; max-age=31536000; SameSite=Lax";- }- return id;-}+// The server assigns the visitor ID (HttpOnly cookie); the browser only reads it back.+async function visitorId() {+ const res = await fetch("/api/session", { credentials: "same-origin" });+ return (await res.json()).identifier;+} function show(id, visible) { document.getElementById(id).hidden = !visible;@@ -45,7 +41,7 @@ } async function main() {- const id = visitorId();+ const id = await visitorId(); document.getElementById("visitor").textContent = id; const plan = cookie("acme_plan") || "free"; document.getElementById("plan").value = plan;--- a/main.go+++ b/main.go@@ -8,6 +8,8 @@ import ( "bufio" "context"+ "crypto/rand" "embed"+ "encoding/hex" "encoding/json" "errors"@@ -60,9 +62,49 @@ mux.HandleFunc("GET /{$}", s.serveAsset("index.html", "text/html; charset=utf-8", false)) mux.HandleFunc("GET /app.js", s.serveAsset("app.js", "text/javascript; charset=utf-8", true)) mux.HandleFunc("GET /api/checkout-config", s.checkoutConfig)+ mux.HandleFunc("GET /api/session", s.session) return mux } +// session returns the visitor identifier, assigning one server-side on the+// first visit. The identifier lives in an HttpOnly cookie, so the browser+// cannot choose or re-roll it by writing document.cookie.+func (s *shop) session(w http.ResponseWriter, r *http.Request) {+ id := ""+ if c, err := r.Cookie("acme_visitor"); err == nil && validVisitorID(c.Value) {+ id = c.Value+ }+ if id == "" {+ buf := make([]byte, 16)+ if _, err := rand.Read(buf); err != nil {+ http.Error(w, "cannot assign visitor id", http.StatusInternalServerError)+ return+ }+ id = "visitor-" + hex.EncodeToString(buf)+ http.SetCookie(w, &http.Cookie{+ Name: "acme_visitor",+ Value: id,+ Path: "/",+ MaxAge: 31536000,+ HttpOnly: true,+ Secure: r.TLS != nil,+ SameSite: http.SameSiteLaxMode,+ })+ }+ w.Header().Set("Cache-Control", "no-store")+ writeJSON(w, http.StatusOK, map[string]string{"identifier": id})+}++// validVisitorID accepts only identifiers this server issued.+func validVisitorID(id string) bool {+ rest, ok := strings.CutPrefix(id, "visitor-")+ if !ok || len(rest) != 32 {+ return false+ }+ _, err := hex.DecodeString(rest)+ return err == nil+}+ // serveAsset serves an embedded file, optionally substituting the lab keys // in place (one token per line, so line numbers never shift). func (s *shop) serveAsset(name, contentType string, template bool) http.HandlerFunc {Re-rolling pricing_page closes only when identifiers are assigned on the server, or when the percentage rollout or variant split is removed. Marking the flag Server-side only hides it from client SDKs but does not stop re-rolling: a server that evaluates it for a browser-chosen identifier is still steered. manual Guidance only, never executed
After the fix is live, restart the experiment so its results are not biased by forged or re-rolled assignments. Gatecrasher never stops or restarts experiments itself. manual Guidance only, never executed
Why
What could break
No code that reads this setting was found in the scanned repository.
Guidance only. This plan changes nothing in Flagsmith: review the drafts above and make the change in your code.