carlos / platform Public

Merge origin/main into sec-unit-app-demobuild

Census chain conflict: main's sec-edge-redirect-linklocal line kept, this
branch's overlay re-proposed after it (seal fea6bec1, overlay and card
unchanged).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 1b8b361b61e06f6494f62ed89047b52a1f8ec0af parent b34b66cparent 15b1ee6
65 files changed, +2,869 −163
  • .amadan/go-toolchain.sh +10 −2
  • docs/superpowers/notes/census-proposal-sec-edge-redirect-linklocal.md +19 −0
  • internal/activator/backend_unit.go +20 −1
  • internal/activator/healthaddr_guard_test.go +49 −0
  • internal/console/accountindex.go +1 −1
  • internal/console/accountlinks.go +2 −3
  • internal/console/analyticsview.go +2 −3
  • internal/console/apitemporary.go +1 −2
  • internal/console/appdomainbuy.go +1 −2
  • internal/console/appdomains.go +2 −3
  • internal/console/applist.go +2 −3
  • internal/console/appregionset.go +1 −2
  • internal/console/appsettings.go +8 −9
  • internal/console/appswap.go +1 −2
  • internal/console/archpage.go +1 −2
  • internal/console/authcli.go +5 −6
  • internal/console/billingcard.go +1 −2
  • internal/console/billingchange.go +3 −4
  • internal/console/billingcheckout.go +1 −2
  • internal/console/billingops.go +1 −2
  • internal/console/billingpage_test.go +2 −2
  • internal/console/billingportal.go +1 −2
  • internal/console/browserrestart.go +2 −3
  • internal/console/browserretry.go +2 −3
  • internal/console/browserupdates.go +1 −2
  • internal/console/confirm.go +4 −4
  • internal/console/confirm_test.go +1 −1
  • internal/console/controlplane.go +2 −3
  • internal/console/csrf.go +55 −0
  • internal/console/csrf_scan_test.go +398 −0
  • internal/console/csrf_test.go +207 −0
  • internal/console/demo_claim_kept.go +2 −2
  • internal/console/demo_claim_page.go +2 −2
  • internal/console/economicspass.go +3 −4
  • internal/console/envform.go +2 −3
  • internal/console/errorsview.go +2 −3
  • internal/console/fleets.go +5 −6
  • internal/console/gate_shadow_guard_test.go +1,390 −0
  • internal/console/gettingstarted_handlers.go +1 −2
  • internal/console/mobilenav_test.go +1 −1
  • internal/console/opshell.go +1 −1
  • internal/console/opshell_test.go +1 −1
  • internal/console/ownership.go +5 −6
  • internal/console/pendinghandlers.go +2 −3
  • internal/console/pipelinepage.go +5 −3
  • internal/console/planlapse_keep.go +1 −2
  • internal/console/protectionsetting.go +1 −2
  • internal/console/regionpicker.go +1 −2
  • internal/console/server.go +18 −18
  • internal/console/stepup.go +5 −4
  • internal/console/storepage.go +1 −2
  • internal/console/svcpage.go +1 −2
  • internal/edge/edge.go +16 −8
  • internal/edge/http_fallback_redirect_test.go +85 −0
  • internal/edge/prober.go +10 −4
  • internal/edge/upstreamdial.go +16 −0
  • internal/edge/upstreamdial_test.go +143 −0
  • internal/host/unitsettle.go +28 −11
  • internal/host/unitsettle_guard_test.go +62 −0
  • internal/provision/ffr_census_test.go +11 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-sec-edge-redirect-linklocal.tsv +7 −0
  • internal/upstreamguard/guardtest/resolver.go +69 −0
  • internal/upstreamguard/upstreamguard.go +76 −0
  • internal/upstreamguard/upstreamguard_test.go +89 −0

CI passed — run details

diff --git a/.amadan/go-toolchain.sh b/.amadan/go-toolchain.sh
index e2f45b1aa..549fe8de5 100644
--- a/.amadan/go-toolchain.sh
+++ b/.amadan/go-toolchain.sh
@@ -15,8 +15,16 @@
# only switches to a toolchain line NEWER than the local one. GOTOOLCHAIN
# does downgrade. "+auto" still lets a go.mod that needs a newer Go fetch it.
#
-# Re-check when Go ships a fix for the deadlock: move this to that version
-# (it also carries GO-2026-6859), with the early subtests as the witness.
+# Re-check when Go ships a fix for the deadlock: move this to that version,
+# with the early subtests as the witness.
+#
+# GO-2026-6859 is present in 1.26.10. Triggering it needs a request body
+# that exceeds its MaxBytesReader limit, read on another goroutine than the
+# handler's while the handler writes headers, with net/http's own response
+# writer passed to MaxBytesReader; #904 checked every production
+# MaxBytesReader site and found none. Go 1.26.11 contains both the
+# GO-2026-6859 fix and a separate change that deadlocks the edge proxy, and
+# no release yet has the fix without the deadlock.
GOTOOLCHAIN=go1.26.10+auto
export GOTOOLCHAIN
go version
diff --git a/docs/superpowers/notes/census-proposal-sec-edge-redirect-linklocal.md b/docs/superpowers/notes/census-proposal-sec-edge-redirect-linklocal.md
new file mode 100644
index 000000000..336857b17
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-sec-edge-redirect-linklocal.md
@@ -0,0 +1,19 @@
+# Census approval: sec-edge-redirect-linklocal
+
+Ruling `census-ruling-sec-edge-redirect-linklocal`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/unitsettle.go` `routeReady` | body | unchanged (5) | same reads (Socket, Addr, Health, Host); the connect and the HTTP probe move into readyConnect/readyProbe, which dial through upstreamguard and so refuse a link-local or IMDS upstream after resolution, before connect; unix sockets, timeout and probe unchanged; no read added |
+
+Envelopes re-pinned: `internal/activator`, `internal/edge`, `internal/host`, `internal/upstreamguard`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/host/unitsettle.go` `routeReady`: authority, task B3,J1,J4. Basis: root-route
+
+Seal: `4eda67fee53800e2cfa4177b954c7f0fce6bdfcfbfe1aa2547ddcec3027b668b` โ†’ `4eda67fee53800e2cfa4177b954c7f0fce6bdfcfbfe1aa2547ddcec3027b668b`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-sec-edge-redirect-linklocal.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go
index 7da200c49..5dff27268 100644
--- a/internal/activator/backend_unit.go
+++ b/internal/activator/backend_unit.go
@@ -51,6 +51,7 @@ import (
"errors"
"fmt"
"io"
+ "net"
"net/http"
"os/exec"
"strings"
@@ -64,6 +65,7 @@ import (
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/upstreamguard"
)
// UnitName is the systemd unit backing a unit-backed tenant's route โ€”
@@ -264,14 +266,31 @@ func (unitRep) Close(context.Context) error { return nil }
// that can't accept a unix listener yet; see the carlos-app@.socket unit's
// fallback note).
func waitHealthyAddr(addr string, timeout time.Duration) error {
+ return waitHealthyAddrVia(net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}, addr, timeout)
+}
+
+// waitHealthyAddrVia is waitHealthyAddr dialing with base (a test sets its
+// Resolver) behind upstreamguard: rt.Addr is route-supplied, so a link-local
+// or IMDS destination is refused after resolution and before connect, and
+// that refusal ends the wait at once. The transport is the default one's
+// settings without the environment proxy, so the guard judges the upstream
+// itself rather than a proxy.
+func waitHealthyAddrVia(base net.Dialer, addr string, timeout time.Duration) error {
+ tr := http.DefaultTransport.(*http.Transport).Clone()
+ tr.Proxy = nil
+ tr.DialContext = upstreamguard.Dialer(base).DialContext
+ defer tr.CloseIdleConnections()
deadline := time.Now().Add(timeout)
- client := healthClient(&http.Client{Timeout: 3 * time.Second})
+ client := healthClient(&http.Client{Timeout: 3 * time.Second, Transport: tr})
var last error
var poll time.Duration
for time.Now().Before(deadline) {
if last = probeHealth(client, "http://"+addr+"/"); last == nil {
return nil
}
+ if errors.Is(last, upstreamguard.ErrLinkLocal) {
+ return fmt.Errorf("instance health check: %w", last)
+ }
poll = nextHealthPoll(poll)
time.Sleep(poll)
}
diff --git a/internal/activator/healthaddr_guard_test.go b/internal/activator/healthaddr_guard_test.go
new file mode 100644
index 000000000..38b44aad1
--- /dev/null
+++ b/internal/activator/healthaddr_guard_test.go
@@ -0,0 +1,49 @@
+package activator
+
+import (
+ "errors"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/upstreamguard"
+ "github.com/carlosframework/platform/internal/upstreamguard/guardtest"
+)
+
+// TestWaitHealthyAddrRefusesLinkLocal: a unit route's TCP upstream is
+// health-checked on wake before the edge proxies to it, so the check dials
+// through upstreamguard too. A name resolving to 169.254.169.254 is refused
+// after resolution (nothing is connected), and the refusal ends the wait at
+// once instead of polling a destination that can never be allowed.
+func TestWaitHealthyAddrRefusesLinkLocal(t *testing.T) {
+ base := net.Dialer{Resolver: guardtest.Resolver(t, "imds.test", "169.254.169.254")}
+ for _, tc := range []struct {
+ name string
+ wait func() error
+ }{
+ {"name resolving to IMDS", func() error { return waitHealthyAddrVia(base, "imds.test:80", 5*time.Second) }},
+ {"IMDS literal, production dialer", func() error { return waitHealthyAddr("169.254.169.254:80", 5*time.Second) }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ start := time.Now()
+ err := tc.wait()
+ if !errors.Is(err, upstreamguard.ErrLinkLocal) {
+ t.Fatalf("wait = %v, want ErrLinkLocal", err)
+ }
+ if d := time.Since(start); d > 2*time.Second {
+ t.Fatalf("wait took %v; a refused destination must end the wait at once", d)
+ }
+ })
+ }
+}
+
+func TestWaitHealthyAddrLoopbackStillWorks(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
+ t.Cleanup(srv.Close)
+ if err := waitHealthyAddr(strings.TrimPrefix(srv.URL, "http://"), 2*time.Second); err != nil {
+ t.Fatalf("waitHealthyAddr on loopback: %v", err)
+ }
+}
diff --git a/internal/console/accountindex.go b/internal/console/accountindex.go
index 69e14d25c..3951e9f6b 100644
--- a/internal/console/accountindex.go
+++ b/internal/console/accountindex.go
@@ -19,7 +19,7 @@ func (s *Server) handleAccountsIndex(w http.ResponseWriter, r *http.Request) {
accounts[i].Seg = preferredSeg(accounts, &accounts[i])
}
p := page{
- Title: "Accounts", Address: addr, CSRF: raw,
+ Title: "Accounts", Address: addr, CSRF: csrfToken(raw),
Accounts: accounts, IndexOf: indexAccounts,
}
p.Flash, p.FlashErr = s.takeFlash(w, r)
diff --git a/internal/console/accountlinks.go b/internal/console/accountlinks.go
index 1ecf01c14..aa5051133 100644
--- a/internal/console/accountlinks.go
+++ b/internal/console/accountlinks.go
@@ -21,7 +21,6 @@ package console
import (
"context"
- "crypto/subtle"
"errors"
"log"
"net/http"
@@ -340,7 +339,7 @@ func (s *Server) handleLinkUnlinkPage(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -363,7 +362,7 @@ func (s *Server) handleLinkUnlinkPage(w http.ResponseWriter, r *http.Request) {
Title: linkCopy(copyLD28, "home", l.Name),
Lines: []string{linkCopy(copyLD27, "home", l.Name)},
Action: "/a/" + url.PathEscape(acct.Sqid) + "/links/" + l.ID + "/unlink",
- Fields: [][2]string{{"csrf", raw}},
+ Fields: [][2]string{{"csrf", csrfToken(raw)}},
Button: linkCopy(copyLD28, "home", l.Name),
Danger: true,
CancelURL: p.Nav + "/fleet",
diff --git a/internal/console/analyticsview.go b/internal/console/analyticsview.go
index 2b33ec349..d80a55928 100644
--- a/internal/console/analyticsview.go
+++ b/internal/console/analyticsview.go
@@ -9,7 +9,6 @@ package console
import (
"context"
- "crypto/subtle"
"errors"
"log"
"math"
@@ -106,7 +105,7 @@ func (s *Server) handleAppAnalyticsSetting(w http.ResponseWriter, r *http.Reques
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -166,7 +165,7 @@ func (s *Server) handleAccountAnalyticsSetting(w http.ResponseWriter, r *http.Re
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/apitemporary.go b/internal/console/apitemporary.go
index 8f137f9d6..c7b5ee775 100644
--- a/internal/console/apitemporary.go
+++ b/internal/console/apitemporary.go
@@ -2,7 +2,6 @@ package console
import (
"context"
- "crypto/subtle"
"errors"
"fmt"
"log"
@@ -437,7 +436,7 @@ func (s *Server) handleAppKeep(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/appdomainbuy.go b/internal/console/appdomainbuy.go
index 7490415e1..d400d525b 100644
--- a/internal/console/appdomainbuy.go
+++ b/internal/console/appdomainbuy.go
@@ -2,7 +2,6 @@ package console
import (
"context"
- "crypto/subtle"
"net/http"
"net/url"
"strconv"
@@ -89,7 +88,7 @@ func (s *Server) domainBuyBrowserGate(w http.ResponseWriter, r *http.Request) (s
if !ok {
return "", "", nil, "", false
}
- if r.Method == http.MethodPost && subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if r.Method == http.MethodPost && !csrfFormOK(r, raw) {
s.renderMessage(w, r, 403, domainBuyCopy["refused"], domainBuyCopy["csrf"])
return "", "", nil, "", false
}
diff --git a/internal/console/appdomains.go b/internal/console/appdomains.go
index 35460b721..440b79643 100644
--- a/internal/console/appdomains.go
+++ b/internal/console/appdomains.go
@@ -15,7 +15,6 @@ package console
import (
"context"
- "crypto/subtle"
"log"
"net/http"
"strings"
@@ -34,7 +33,7 @@ func (s *Server) handleAppDomainAttach(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -104,7 +103,7 @@ func (s *Server) handleAppDomainDetach(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/applist.go b/internal/console/applist.go
index b5e4c47b9..5a87df44b 100644
--- a/internal/console/applist.go
+++ b/internal/console/applist.go
@@ -2,7 +2,6 @@ package console
import (
"context"
- "crypto/subtle"
"errors"
"log"
"net/http"
@@ -181,7 +180,7 @@ func (s *Server) handleAppStar(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -257,7 +256,7 @@ func (s *Server) handleAppExtend(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/appregionset.go b/internal/console/appregionset.go
index 28682956d..829a8a52e 100644
--- a/internal/console/appregionset.go
+++ b/internal/console/appregionset.go
@@ -24,7 +24,6 @@ package console
import (
"context"
- "crypto/subtle"
"fmt"
"log"
"net/http"
@@ -437,7 +436,7 @@ func (s *Server) handleAppRegionSet(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go
index 54902ae62..5cce435fc 100644
--- a/internal/console/appsettings.go
+++ b/internal/console/appsettings.go
@@ -29,7 +29,6 @@ package console
import (
"context"
- "crypto/subtle"
"errors"
"fmt"
"html/template"
@@ -901,7 +900,7 @@ func (s *Server) handleAppRename(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -1009,7 +1008,7 @@ func (s *Server) handleAppRename(w http.ResponseWriter, r *http.Request) {
},
Action: "/a/" + url.PathEscape(acct.Sqid) + "/apps/" + url.PathEscape(app) + "/rename",
Fields: [][2]string{
- {"csrf", raw}, {"to", to},
+ {"csrf", csrfToken(raw)}, {"to", to},
},
Button: "Rename",
CancelTab: "settings",
@@ -1182,7 +1181,7 @@ func (s *Server) handleAppGate(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -1283,7 +1282,7 @@ func (s *Server) handleAppRateLimit(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -1390,7 +1389,7 @@ func (s *Server) handleAppDelete(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -1533,7 +1532,7 @@ func (s *Server) handleStoreDestroy(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -1691,7 +1690,7 @@ func (s *Server) handleAppMoveAccount(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -1790,7 +1789,7 @@ func (s *Server) handleAppMoveAccount(w http.ResponseWriter, r *http.Request) {
Note: "You'll confirm it's really you with your passkey.",
Action: "/a/" + url.PathEscape(acct.Sqid) + "/apps/" + url.PathEscape(app) + "/move",
Fields: [][2]string{
- {"csrf", raw}, {"to", dest.Sqid},
+ {"csrf", csrfToken(raw)}, {"to", dest.Sqid},
},
Button: "Move to " + dest.Name,
CancelTab: "settings",
diff --git a/internal/console/appswap.go b/internal/console/appswap.go
index 04e6f38c5..b9a240c99 100644
--- a/internal/console/appswap.go
+++ b/internal/console/appswap.go
@@ -2,7 +2,6 @@ package console
import (
"context"
- "crypto/subtle"
"errors"
"fmt"
"log"
@@ -22,7 +21,7 @@ func (s *Server) handleAppSwap(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/archpage.go b/internal/console/archpage.go
index 6701e2656..1388971c3 100644
--- a/internal/console/archpage.go
+++ b/internal/console/archpage.go
@@ -14,7 +14,6 @@
package console
import (
- "crypto/subtle"
"log"
"net/http"
"time"
@@ -123,7 +122,7 @@ func (s *Server) handleArchitectureRefresh(w http.ResponseWriter, r *http.Reques
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index 085bbc850..71c5fd752 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -23,7 +23,6 @@ package console
import (
"context"
- "crypto/subtle"
"encoding/json"
"errors"
"fmt"
@@ -1114,7 +1113,7 @@ func (s *Server) handleCLIApprovePage(w http.ResponseWriter, r *http.Request) {
s.renderHome(w, r, homeForm{Next: next, Banner: copyText("cli.signin_prompt")})
return
}
- p := cliPage{page: page{Title: copyText("cli.title"), Address: addr, CSRF: raw},
+ p := cliPage{page: page{Title: copyText("cli.title"), Address: addr, CSRF: csrfToken(raw)},
Days: int(CLITokenTTL / (24 * time.Hour))}
switch {
case code == "":
@@ -1224,14 +1223,14 @@ func (s *Server) handleCLIApprove(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
code := NormalizeUserCode(r.FormValue("code"))
action := r.FormValue("action")
now := time.Now()
- p := cliPage{page: page{Title: copyText("cli.title"), Address: addr, CSRF: raw},
+ p := cliPage{page: page{Title: copyText("cli.title"), Address: addr, CSRF: csrfToken(raw)},
Code: code, Days: int(CLITokenTTL / (24 * time.Hour))}
// Wrong codes are counted wherever a code is resolved, and against both
@@ -1376,7 +1375,7 @@ func (s *Server) handleCLITokens(w http.ResponseWriter, r *http.Request) {
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read your terminals. Please try again.")
return
}
- p := cliPage{page: page{Title: "Your settings", Address: addr, CSRF: raw, MobileParent: &navLink{Label: "Accounts", Href: "/accounts"}},
+ p := cliPage{page: page{Title: "Your settings", Address: addr, CSRF: csrfToken(raw), MobileParent: &navLink{Label: "Accounts", Href: "/accounts"}},
Tokens: toks, Console: s.cfg.Origin, Days: int(CLITokenTTL / (24 * time.Hour)),
ServiceAccounts: s.serviceAccountSqids(toks)}
methods, err := s.store.SignInMethodsFor(addr)
@@ -1432,7 +1431,7 @@ func (s *Server) handleCLITokenRevoke(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/billingcard.go b/internal/console/billingcard.go
index 7c8ea9bf7..1bb6b3081 100644
--- a/internal/console/billingcard.go
+++ b/internal/console/billingcard.go
@@ -2,7 +2,6 @@ package console
import (
"context"
- "crypto/subtle"
"log"
"net/http"
"time"
@@ -15,7 +14,7 @@ func (s *Server) handleBillingCard(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.billingCSRFRefused(w, r)
return
}
diff --git a/internal/console/billingchange.go b/internal/console/billingchange.go
index 980bc436a..f7f00be14 100644
--- a/internal/console/billingchange.go
+++ b/internal/console/billingchange.go
@@ -3,7 +3,6 @@ package console
import (
"context"
"crypto/rand"
- "crypto/subtle"
"encoding/hex"
"errors"
"fmt"
@@ -153,7 +152,7 @@ func (s *Server) handleBillingChange(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.billingCSRFRefused(w, r)
return
}
@@ -203,7 +202,7 @@ func (s *Server) renderChangeConfirm(w http.ResponseWriter, r *http.Request, add
if q.Known {
line = fmt.Sprintf(billingCopy["confirm.line"], plans.FormatMinor(q.Currency, q.Estimate))
}
- fields := [][2]string{{"csrf", raw}}
+ fields := [][2]string{{"csrf", csrfToken(raw)}}
if ask.Plan != "" {
fields = append(fields, [2]string{"plan", ask.Plan})
} else {
@@ -581,7 +580,7 @@ func (s *Server) handleBillingRenewal(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.billingCSRFRefused(w, r)
return
}
diff --git a/internal/console/billingcheckout.go b/internal/console/billingcheckout.go
index 42412fa0e..984cf0301 100644
--- a/internal/console/billingcheckout.go
+++ b/internal/console/billingcheckout.go
@@ -3,7 +3,6 @@ package console
import (
"context"
"crypto/rand"
- "crypto/subtle"
"encoding/hex"
"errors"
"fmt"
@@ -152,7 +151,7 @@ func (s *Server) handleBillingCheckout(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/billingops.go b/internal/console/billingops.go
index afeaadbfb..496289efa 100644
--- a/internal/console/billingops.go
+++ b/internal/console/billingops.go
@@ -2,7 +2,6 @@ package console
import (
"context"
- "crypto/subtle"
"database/sql"
"encoding/json"
"errors"
@@ -746,7 +745,7 @@ func (s *Server) handleBillingConfirm(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/billingpage_test.go b/internal/console/billingpage_test.go
index afbb097c8..e839c0aae 100644
--- a/internal/console/billingpage_test.go
+++ b/internal/console/billingpage_test.go
@@ -252,7 +252,7 @@ func TestBillingPageOffAndGate(t *testing.T) {
t.Errorf("the eyebrow %q is not the map's", want)
}
for _, want := range []string{
- `action="/a/` + pf.acct.Sqid + `/billing/checkout"`, `name="csrf" value="` + pf.csrf + `"`,
+ `action="/a/` + pf.acct.Sqid + `/billing/checkout"`, `name="csrf" value="` + csrfToken(pf.csrf) + `"`,
`name="plan" value="personal"`, `name="plan" value="community"`, `name="plan" value="business"`,
esc(billingCopy["buy.title"]), esc(billingCopy["buy.button"]),
`name="pack_apps"`, `max="20"`,
@@ -455,7 +455,7 @@ func TestBillingPagePaidFacts(t *testing.T) {
if strings.Contains(body, base+`checkout"`) {
t.Error("a paid account was offered checkout")
}
- if n, m := strings.Count(body, `method="post" action="/a/`+pf.acct.Sqid+`/billing/`), strings.Count(body, `name="csrf" value="`+pf.csrf+`"`); m < n || n == 0 {
+ if n, m := strings.Count(body, `method="post" action="/a/`+pf.acct.Sqid+`/billing/`), strings.Count(body, `name="csrf" value="`+csrfToken(pf.csrf)+`"`); m < n || n == 0 {
t.Errorf("%d billing forms, %d CSRF fields", n, m)
}
diff --git a/internal/console/billingportal.go b/internal/console/billingportal.go
index fb320b272..e3882a1f5 100644
--- a/internal/console/billingportal.go
+++ b/internal/console/billingportal.go
@@ -2,7 +2,6 @@ package console
import (
"crypto/rand"
- "crypto/subtle"
"encoding/hex"
"log"
"net/http"
@@ -35,7 +34,7 @@ func (s *Server) handleBillingPortal(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.billingCSRFRefused(w, r)
return
}
diff --git a/internal/console/browserrestart.go b/internal/console/browserrestart.go
index 8ad2a8f75..e5e4aedab 100644
--- a/internal/console/browserrestart.go
+++ b/internal/console/browserrestart.go
@@ -2,7 +2,6 @@ package console
import (
"context"
- "crypto/subtle"
"log"
"net/http"
"net/url"
@@ -48,7 +47,7 @@ func (s *Server) handleBrowserRestart(w http.ResponseWriter, r *http.Request, ho
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -102,7 +101,7 @@ func (s *Server) handleBrowserRestart(w http.ResponseWriter, r *http.Request, ho
}
words := approvedBrowserRestartCopy
if !confirmed(r) {
- cv := &ConfirmView{Action: r.URL.Path, Fields: [][2]string{{"csrf", raw}}, CancelTab: "instances"}
+ cv := &ConfirmView{Action: r.URL.Path, Fields: [][2]string{{"csrf", csrfToken(raw)}}, CancelTab: "instances"}
if host == "" {
cv.Title, cv.Lines, cv.Button = words.AppTitle, []string{words.AppLine}, words.Button
} else {
diff --git a/internal/console/browserretry.go b/internal/console/browserretry.go
index 46800330b..73718f7fc 100644
--- a/internal/console/browserretry.go
+++ b/internal/console/browserretry.go
@@ -2,7 +2,6 @@ package console
import (
"context"
- "crypto/subtle"
"errors"
"log"
"net/http"
@@ -34,7 +33,7 @@ func (s *Server) handleInstanceRetry(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -91,7 +90,7 @@ func (s *Server) handleInstanceRetry(w http.ResponseWriter, r *http.Request) {
}
if !confirmed(r) {
s.renderConfirm(w, r, addr, raw, acct, role, app, &ConfirmView{
- Action: r.URL.Path, Fields: [][2]string{{"csrf", raw}}, CancelURL: back,
+ Action: r.URL.Path, Fields: [][2]string{{"csrf", csrfToken(raw)}}, CancelURL: back,
Title: fill.Replace(swapCopy.RetryTitle), Lines: []string{fill.Replace(line)},
Button: swapCopy.RetryButton,
})
diff --git a/internal/console/browserupdates.go b/internal/console/browserupdates.go
index 3100074a6..662a3cd57 100644
--- a/internal/console/browserupdates.go
+++ b/internal/console/browserupdates.go
@@ -17,7 +17,6 @@ package console
import (
"context"
- "crypto/subtle"
"fmt"
"net/http"
"net/url"
@@ -224,7 +223,7 @@ func (s *Server) updatesFormGate(w http.ResponseWriter, r *http.Request, ctx con
if !ok {
return updatesFormTarget{}, false
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return updatesFormTarget{}, false
}
diff --git a/internal/console/confirm.go b/internal/console/confirm.go
index 1f5a936db..ffb0bbc65 100644
--- a/internal/console/confirm.go
+++ b/internal/console/confirm.go
@@ -115,7 +115,7 @@ func (s *Server) confirmPromote(w http.ResponseWriter, r *http.Request, addr, ra
Title: "Promote " + version + " to " + channel + "?",
Action: "/a/" + url.PathEscape(acct.Sqid) + "/apps/" + url.PathEscape(app) + "/promote",
Fields: [][2]string{
- {"csrf", raw}, {"channel", channel}, {"version", version}, {"back", r.FormValue("back")},
+ {"csrf", csrfToken(raw)}, {"channel", channel}, {"version", version}, {"back", r.FormValue("back")},
},
Button: "Promote " + version,
CancelTab: backTab(r),
@@ -177,7 +177,7 @@ func (s *Server) confirmRollback(w http.ResponseWriter, r *http.Request, addr, r
// target pins what the card promised: the confirmed POST refuses if
// the channel's history has moved on since this was rendered.
Fields: [][2]string{
- {"csrf", raw}, {"channel", channel}, {"target", target}, {"back", r.FormValue("back")},
+ {"csrf", csrfToken(raw)}, {"channel", channel}, {"target", target}, {"back", r.FormValue("back")},
},
Button: "Roll back to " + target,
Danger: true,
@@ -198,7 +198,7 @@ func (s *Server) confirmFastTrack(w http.ResponseWriter, r *http.Request, addr,
Note: "You'll confirm it's really you with your passkey. The version keeps a permanent 'delay skipped' badge.",
Action: "/a/" + url.PathEscape(acct.Sqid) + "/apps/" + url.PathEscape(app) + "/fasttrack",
Fields: [][2]string{
- {"csrf", raw}, {"channel", channel},
+ {"csrf", csrfToken(raw)}, {"channel", channel},
},
Button: "Skip the delay",
Danger: true,
@@ -229,7 +229,7 @@ func (s *Server) confirmRetireCanary(w http.ResponseWriter, r *http.Request, add
},
Action: "/a/" + url.PathEscape(acct.Sqid) + "/apps/" + url.PathEscape(app) + "/canary/retire",
Fields: [][2]string{
- {"csrf", raw}, {"name", name}, {"back", r.FormValue("back")},
+ {"csrf", csrfToken(raw)}, {"name", name}, {"back", r.FormValue("back")},
},
Button: "Retire " + name,
Danger: true,
diff --git a/internal/console/confirm_test.go b/internal/console/confirm_test.go
index 4d50bbe73..6af21f370 100644
--- a/internal/console/confirm_test.go
+++ b/internal/console/confirm_test.go
@@ -41,7 +41,7 @@ func confirmCard(t *testing.T, status int, body, title, csrf string) string {
if !strings.Contains(body, `<input type="hidden" name="confirmed" value="1">`) {
t.Fatalf("card carries no confirmed=1 marker, so its button cannot land the action:\n%s", body)
}
- if !strings.Contains(body, `<input type="hidden" name="csrf" value="`+csrf+`">`) {
+ if !strings.Contains(body, `<input type="hidden" name="csrf" value="`+csrfToken(csrf)+`">`) {
t.Fatalf("card carries no csrf field, so its resubmit would be refused:\n%s", body)
}
if !strings.Contains(body, `<button type="submit"`) {
diff --git a/internal/console/controlplane.go b/internal/console/controlplane.go
index f2fcb3f31..af5324915 100644
--- a/internal/console/controlplane.go
+++ b/internal/console/controlplane.go
@@ -29,7 +29,6 @@ package console
import (
"bytes"
"context"
- "crypto/subtle"
"debug/buildinfo"
"debug/elf"
"errors"
@@ -210,7 +209,7 @@ func (s *Server) handleAppControlPlaneClear(w http.ResponseWriter, r *http.Reque
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -267,7 +266,7 @@ func (s *Server) handleAppControlPlaneSet(w http.ResponseWriter, r *http.Request
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/csrf.go b/internal/console/csrf.go
new file mode 100644
index 000000000..46e382993
--- /dev/null
+++ b/internal/console/csrf.go
@@ -0,0 +1,55 @@
+package console
+
+// The console's CSRF token is double-submitted: every signed-in form carries
+// it as a hidden "csrf" field and every state-changing POST checks it against
+// the browser's own session. It is derived from the session one way, so the
+// token on a page is never the 30-day session itself: a page that leaks (a
+// saved copy, a screenshot, a proxy logging HTML) leaks a value that can only
+// be checked against the session, never used as one. It is also never the
+// sessions table's key, hashToken(raw), so a database read does not yield a
+// page's token either way round.
+//
+// csrfFormOK is the one door every handler checks through, and
+// TestNoRawSessionAsCSRF (csrf_scan_test.go) holds the package to that.
+
+import (
+ "crypto/subtle"
+ "net/http"
+)
+
+// csrfDomain separates the CSRF derivation from every other hash of the
+// session (hashToken(raw) is the sessions table key).
+const csrfDomain = "carlos-console-csrf-v1:"
+
+// csrfToken is the CSRF token for a session. No session, no token: a
+// signed-out page renders an empty field, as it always has.
+func csrfToken(rawSession string) string {
+ if rawSession == "" {
+ return ""
+ }
+ return hashToken(csrfDomain + rawSession)
+}
+
+// csrfOK reports whether got is the CSRF token for rawSession, in constant
+// time. An empty session or an empty token never matches.
+func csrfOK(got, rawSession string) bool {
+ if rawSession == "" || got == "" {
+ return false
+ }
+ ok := subtle.ConstantTimeCompare([]byte(got), []byte(csrfToken(rawSession)))
+ // TRANSITION(csrf-v1): remove one release after the release that ships
+ // the derived token. A form rendered before that deploy carries the raw
+ // session; it stays accepted for one release, then this branch goes.
+ ok |= subtle.ConstantTimeCompare([]byte(got), []byte(rawSession))
+ return ok == 1
+}
+
+// csrfFormOK reports whether the request body carries exactly one csrf value
+// and it is good for rawSession. The body is parsed the way the handlers'
+// own r.FormValue("csrf") checks always parsed it (a no-op when the handler
+// already parsed it); a token only in the query string does not count.
+func csrfFormOK(r *http.Request, rawSession string) bool {
+ _ = r.FormValue("csrf")
+ v := r.PostForm["csrf"]
+ return len(v) == 1 && csrfOK(v[0], rawSession)
+}
diff --git a/internal/console/csrf_scan_test.go b/internal/console/csrf_scan_test.go
new file mode 100644
index 000000000..33e4d68fd
--- /dev/null
+++ b/internal/console/csrf_scan_test.go
@@ -0,0 +1,398 @@
+package console
+
+// TestNoRawSessionAsCSRF is the completeness check for the derived CSRF token
+// (csrf.go): every value the console binds to the name csrf is csrfToken(...)
+// (or, for a copy map, a string literal), and every check of a posted token
+// goes through csrfFormOK, the only caller of csrfOK. A new handler that
+// echoes the session into a form or a JSON reply, or reads a posted csrf by
+// hand, fails here rather than in review. The field name is matched through
+// string constants too, so naming it does not blind the scan.
+
+import (
+ "bytes"
+ "go/ast"
+ "go/parser"
+ "go/printer"
+ "go/token"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// csrfReaderAllow names the functions that may read the posted csrf field by
+// hand: csrf.go itself, and the demo report door, whose csrf is its own signed
+// token (validDemoReportToken), not the session's.
+var csrfReaderAllow = map[string]bool{
+ "csrf.go:csrfFormOK": true,
+ "apidemoreports.go:handleDemoReport": true,
+}
+
+// csrfOKCallers names the only function that may call csrfOK.
+var csrfOKCallers = map[string]bool{"csrf.go:csrfFormOK": true}
+
+// Canary floors: how many csrfToken(...) emitters, and how many of them fill
+// a CSRF: field, the scan must see. Today: 22 and 10. A rename of page.CSRF,
+// or a refactor that moves emitters somewhere the scan cannot see, drops
+// these and fails loudly instead of passing an empty scan.
+const (
+ csrfMinEmitters = 19
+ csrfMinCSRFFields = 8
+)
+
+func TestNoRawSessionAsCSRF(t *testing.T) {
+ names, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ var files []*ast.File
+ var fileNames []string
+ for _, name := range names {
+ if strings.HasSuffix(name, "_test.go") {
+ continue
+ }
+ src, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, err := parser.ParseFile(fset, name, src, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ files = append(files, f)
+ fileNames = append(fileNames, name)
+ }
+ if len(files) < 100 {
+ t.Fatalf("scanned %d files; the glob is not seeing the package", len(files))
+ }
+ sc := newCSRFScan(fset, files)
+ for i, f := range files {
+ sc.file(f, fileNames[i])
+ }
+ sort.Strings(sc.out)
+ for _, b := range sc.out {
+ t.Error(b)
+ }
+ t.Logf("csrfToken emitters %d, CSRF: fields %d", sc.emitters, sc.csrfFields)
+ if sc.emitters < csrfMinEmitters {
+ t.Errorf("scan saw %d csrfToken(...) emitters, want at least %d: did emitters move or get renamed?", sc.emitters, csrfMinEmitters)
+ }
+ if sc.csrfFields < csrfMinCSRFFields {
+ t.Errorf("scan saw %d CSRF: csrfToken(...) fields, want at least %d: was page.CSRF renamed?", sc.csrfFields, csrfMinCSRFFields)
+ }
+}
+
+// TestNoRawSessionAsCSRFNegativeControl: each bad shape, in a small source
+// string, is flagged; the good shapes are not.
+func TestNoRawSessionAsCSRFNegativeControl(t *testing.T) {
+ const src = `package console
+
+const csrfField = "csrf"
+const csrfAlias = csrfField
+const csrfJoined = "cs" + "rf"
+
+func bad(r *http.Request, raw string) {
+ _ = subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) // A1
+ _ = subtle.ConstantTimeCompare([]byte(raw), []byte(r.PostForm.Get("csrf"))) // A2
+ _ = subtle.ConstantTimeCompare([]byte(r.PostFormValue("csrf")), []byte(raw)) // A3
+ if tok := r.PostForm["csrf"]; len(tok) != 1 { // A4
+ }
+ if r.FormValue(csrfField) != raw { // A5 (Astra)
+ }
+ _ = r.URL.Query().Get("csrf") // A6
+ _ = csrfOK(r.URL.Query().Get("csrf"), raw) // A7
+ _ = csrfOK(r.FormValue("token"), raw) // A8
+ _ = r.PostForm[csrfAlias] // A9
+ _ = r.URL.Query()[csrfJoined] // A10
+ _ = [][2]string{{"csrf", raw}} // B1
+ form.Set("csrf", raw) // B2
+ _ = url.Values{"csrf": {raw}} // B3
+ _ = [][2]string{{csrfField, raw}} // B4 (Astra)
+ _ = url.Values{csrfField: {raw}} // B5
+ form.Add(csrfJoined, raw) // B6
+ _ = map[string]any{"csrf": raw} // B7 (Fable)
+ _ = map[string]string{"csrf": raw} // B8
+ _ = map[string]any{csrfAlias: s.session(r)} // B9
+ _ = page{Address: addr, CSRF: raw} // C1
+ p.CSRF = raw // C2
+}
+
+func good(r *http.Request, raw string) {
+ _ = csrfFormOK(r, raw)
+ _ = [][2]string{{"csrf", csrfToken(raw)}, {"name", raw}}
+ form.Set("csrf", csrfToken(raw))
+ form.Set("name", raw)
+ _ = url.Values{csrfField: {csrfToken(raw)}}
+ _ = map[string]string{"csrf": "This request was blocked."}
+ _ = map[string]any{"csrf": csrfToken(raw)}
+ _ = page{Address: addr, CSRF: csrfToken(raw)}
+ p.CSRF = csrfToken(raw)
+ _ = subtle.ConstantTimeCompare([]byte(a), []byte(b))
+ _ = r.FormValue("name")
+ _ = r.URL.Query().Get("next")
+ _ = []string{"host", "category", "details", "csrf"}
+}
+`
+ fset := token.NewFileSet()
+ f, err := parser.ParseFile(fset, "neg.go", src, parser.ParseComments)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sc := newCSRFScan(fset, []*ast.File{f})
+ sc.file(f, "neg.go")
+ lines := strings.Split(src, "\n")
+ flagged := map[string]bool{}
+ for _, g := range sc.out {
+ // "neg.go:LINE: ..."
+ rest := strings.TrimPrefix(g, "neg.go:")
+ n, err := strconv.Atoi(rest[:strings.IndexByte(rest, ':')])
+ if err != nil {
+ t.Fatalf("finding %q has no line", g)
+ }
+ line := lines[n-1]
+ i := strings.LastIndex(line, "// ")
+ if i < 0 {
+ t.Errorf("flagged an unmarked (good) line %d: %s", n, g)
+ continue
+ }
+ flagged[strings.Fields(line[i+3:])[0]] = true
+ }
+ for _, want := range []string{"A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "A10",
+ "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "C1", "C2"} {
+ if !flagged[want] {
+ t.Errorf("bad shape %s was not flagged; findings: %q", want, sc.out)
+ }
+ }
+ // The good half's emitters count toward the canary.
+ if sc.emitters != 6 || sc.csrfFields != 2 {
+ t.Errorf("canary counts = %d emitters, %d CSRF fields; want 6 and 2", sc.emitters, sc.csrfFields)
+ }
+}
+
+// csrfScan walks parsed files for the shapes TestNoRawSessionAsCSRF forbids.
+type csrfScan struct {
+ fset *token.FileSet
+ consts map[string]string // every string constant declared in the scanned files
+ out []string // "file:line: why"
+
+ emitters, csrfFields int // canary counts (csrf.go excluded)
+}
+
+// newCSRFScan resolves the string constants the files declare (package level
+// or local; a const built from other consts or by + is followed), so the
+// field name matches however it is spelled.
+func newCSRFScan(fset *token.FileSet, files []*ast.File) *csrfScan {
+ sc := &csrfScan{fset: fset, consts: map[string]string{}}
+ var specs []*ast.ValueSpec
+ for _, f := range files {
+ ast.Inspect(f, func(n ast.Node) bool {
+ if gd, ok := n.(*ast.GenDecl); ok && gd.Tok == token.CONST {
+ for _, s := range gd.Specs {
+ specs = append(specs, s.(*ast.ValueSpec))
+ }
+ }
+ return true
+ })
+ }
+ for changed := true; changed; {
+ changed = false
+ for _, vs := range specs {
+ for i, id := range vs.Names {
+ if i >= len(vs.Values) {
+ break
+ }
+ if _, done := sc.consts[id.Name]; done {
+ continue
+ }
+ if v, ok := sc.str(vs.Values[i]); ok {
+ sc.consts[id.Name] = v
+ changed = true
+ }
+ }
+ }
+ }
+ return sc
+}
+
+// str evaluates a constant string expression: a literal, a known const, or
+// a + of those.
+func (sc *csrfScan) str(e ast.Expr) (string, bool) {
+ switch e := e.(type) {
+ case *ast.BasicLit:
+ if e.Kind != token.STRING {
+ return "", false
+ }
+ s, err := strconv.Unquote(e.Value)
+ return s, err == nil
+ case *ast.Ident:
+ s, ok := sc.consts[e.Name]
+ return s, ok
+ case *ast.ParenExpr:
+ return sc.str(e.X)
+ case *ast.BinaryExpr:
+ if e.Op != token.ADD {
+ return "", false
+ }
+ a, ok1 := sc.str(e.X)
+ b, ok2 := sc.str(e.Y)
+ return a + b, ok1 && ok2
+ }
+ return "", false
+}
+
+func (sc *csrfScan) isCSRF(e ast.Expr) bool {
+ s, ok := sc.str(e)
+ return ok && s == "csrf"
+}
+
+func (sc *csrfScan) file(f *ast.File, name string) {
+ flag := func(n ast.Node, why string) {
+ sc.out = append(sc.out, name+":"+strconv.Itoa(sc.fset.Position(n.Pos()).Line)+": "+why)
+ }
+ for _, decl := range f.Decls {
+ fn := ""
+ if fd, ok := decl.(*ast.FuncDecl); ok {
+ fn = fd.Name.Name
+ }
+ readerOK := csrfReaderAllow[name+":"+fn]
+ ast.Inspect(decl, func(n ast.Node) bool {
+ switch n := n.(type) {
+ case *ast.CallExpr:
+ if isCSRFTokenCall(n) && name != "csrf.go" {
+ sc.emitters++
+ }
+ if id, ok := n.Fun.(*ast.Ident); ok && id.Name == "csrfOK" && !csrfOKCallers[name+":"+fn] {
+ flag(n, "csrfOK called outside csrfFormOK; use csrfFormOK")
+ }
+ if isSel(n.Fun, "ConstantTimeCompare") && !readerOK {
+ for _, a := range n.Args {
+ if sc.readsCSRFField(a) {
+ flag(n, "hand-rolled CSRF compare; use csrfFormOK")
+ }
+ }
+ }
+ if (isSel(n.Fun, "Set") || isSel(n.Fun, "Add")) && len(n.Args) == 2 && sc.isCSRF(n.Args[0]) && !isCSRFTokenCall(n.Args[1]) {
+ flag(n, `csrf field set to something other than csrfToken(...)`)
+ }
+ if !readerOK && sc.isCSRFRead(n) {
+ flag(n, "posted csrf read by hand; use csrfFormOK")
+ }
+ case *ast.IndexExpr:
+ if !readerOK && sc.isCSRF(n.Index) && (isSel(n.X, "PostForm", "Form") || isQueryCall(n.X)) {
+ flag(n, "posted csrf read by hand; use csrfFormOK")
+ }
+ case *ast.CompositeLit:
+ // {"csrf", X}: a hidden-field pair.
+ if len(n.Elts) == 2 && sc.isCSRF(n.Elts[0]) && !isCSRFTokenCall(n.Elts[1]) {
+ flag(n, `{"csrf", X} with X not csrfToken(...)`)
+ }
+ case *ast.KeyValueExpr:
+ // "csrf": X in a map or url.Values. Legal values: a string
+ // literal (a copy map's entry), csrfToken(...), or
+ // {csrfToken(...)}.
+ if sc.isCSRF(n.Key) && !csrfValueOK(n.Value) {
+ flag(n, `"csrf": X with X not csrfToken(...)`)
+ }
+ if id, isID := n.Key.(*ast.Ident); isID && id.Name == "CSRF" {
+ if isCSRFTokenCall(n.Value) {
+ sc.csrfFields++
+ } else {
+ flag(n, "CSRF: X with X not csrfToken(...)")
+ }
+ }
+ case *ast.AssignStmt:
+ for i, l := range n.Lhs {
+ if !isSel(l, "CSRF") || i >= len(n.Rhs) {
+ continue
+ }
+ if isCSRFTokenCall(n.Rhs[i]) {
+ sc.csrfFields++
+ } else {
+ flag(n, ".CSRF = X with X not csrfToken(...)")
+ }
+ }
+ }
+ return true
+ })
+ }
+}
+
+func csrfValueOK(v ast.Expr) bool {
+ if bl, ok := v.(*ast.BasicLit); ok && bl.Kind == token.STRING {
+ return true
+ }
+ if cl, ok := v.(*ast.CompositeLit); ok {
+ return len(cl.Elts) == 1 && isCSRFTokenCall(cl.Elts[0])
+ }
+ return isCSRFTokenCall(v)
+}
+
+// readsCSRFField reports whether e contains a read of the csrf field.
+func (sc *csrfScan) readsCSRFField(e ast.Expr) bool {
+ var buf bytes.Buffer
+ _ = printer.Fprint(&buf, token.NewFileSet(), e)
+ s := buf.String()
+ for _, needle := range []string{`FormValue("csrf")`, `PostForm["csrf"]`, `PostForm.Get("csrf")`, `PostFormValue("csrf")`, `Form.Get("csrf")`, `Form["csrf"]`} {
+ if strings.Contains(s, needle) {
+ return true
+ }
+ }
+ found := false
+ ast.Inspect(e, func(n ast.Node) bool {
+ switch n := n.(type) {
+ case *ast.CallExpr:
+ found = found || sc.isCSRFRead(n)
+ case *ast.IndexExpr:
+ found = found || (sc.isCSRF(n.Index) && (isSel(n.X, "PostForm", "Form") || isQueryCall(n.X)))
+ }
+ return !found
+ })
+ return found
+}
+
+// isCSRFRead: r.FormValue(csrf), r.PostFormValue(csrf), r.PostForm.Get(csrf),
+// r.Form.Get(csrf), r.URL.Query().Get(csrf), with csrf any constant
+// expression equal to "csrf".
+func (sc *csrfScan) isCSRFRead(c *ast.CallExpr) bool {
+ if len(c.Args) != 1 || !sc.isCSRF(c.Args[0]) {
+ return false
+ }
+ if isSel(c.Fun, "FormValue", "PostFormValue") {
+ return true
+ }
+ if sel, ok := c.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "Get" && (isSel(sel.X, "PostForm", "Form") || isQueryCall(sel.X)) {
+ return true
+ }
+ return false
+}
+
+// isQueryCall: X.Query(), as in r.URL.Query().
+func isQueryCall(e ast.Expr) bool {
+ c, ok := e.(*ast.CallExpr)
+ return ok && len(c.Args) == 0 && isSel(c.Fun, "Query")
+}
+
+func isSel(e ast.Expr, names ...string) bool {
+ sel, ok := e.(*ast.SelectorExpr)
+ if !ok {
+ return false
+ }
+ for _, n := range names {
+ if sel.Sel.Name == n {
+ return true
+ }
+ }
+ return false
+}
+
+func isCSRFTokenCall(e ast.Expr) bool {
+ c, ok := e.(*ast.CallExpr)
+ if !ok {
+ return false
+ }
+ id, ok := c.Fun.(*ast.Ident)
+ return ok && id.Name == "csrfToken"
+}
diff --git a/internal/console/csrf_test.go b/internal/console/csrf_test.go
new file mode 100644
index 000000000..d0fe8bb3e
--- /dev/null
+++ b/internal/console/csrf_test.go
@@ -0,0 +1,207 @@
+package console
+
+// The CSRF token is a one-way derivation of the session (csrf.go), so a page
+// that leaks โ€” a screenshot, a saved copy, a proxy log of the HTML โ€” no longer
+// leaks a 30-day session. The raw session is still accepted for one release
+// so forms rendered before the deploy keep working.
+
+import (
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+)
+
+func TestCSRFTokenIsNotTheSession(t *testing.T) {
+ raw := "s3ss10n-t0ken-for-the-test"
+ tok := csrfToken(raw)
+ if tok == raw {
+ t.Fatal("csrfToken returned the raw session")
+ }
+ if tok == hashToken(raw) {
+ t.Fatal("csrfToken equals hashToken(raw), the sessions table's key")
+ }
+ if tok != csrfToken(raw) {
+ t.Fatal("csrfToken is not stable")
+ }
+ if !regexp.MustCompile(`^[0-9a-f]{64}$`).MatchString(tok) {
+ t.Fatalf("csrfToken = %q, want 64 lowercase hex", tok)
+ }
+ if csrfToken("other-session") == tok {
+ t.Fatal("two sessions share a CSRF token")
+ }
+ if csrfToken("") != "" {
+ t.Fatal("no session must mean no token, so signed-out pages render none")
+ }
+}
+
+func TestCSRFOKAcceptsDerivedAndTransitionRaw(t *testing.T) {
+ raw := "s3ss10n-t0ken-for-the-test"
+ if !csrfOK(csrfToken(raw), raw) {
+ t.Fatal("the derived token was refused")
+ }
+ // TRANSITION(csrf-v1): a form rendered before the deploy carries raw.
+ if !csrfOK(raw, raw) {
+ t.Fatal("the raw session was refused during the transition release")
+ }
+}
+
+func TestCSRFOKRefusesOther(t *testing.T) {
+ raw := "s3ss10n-t0ken-for-the-test"
+ tok := csrfToken(raw)
+ for name, got := range map[string]string{
+ "empty": "",
+ "other session's derived": csrfToken("other-session"),
+ "other session's raw": "other-session",
+ "truncated derived": tok[:len(tok)-1],
+ "truncated raw": raw[:len(raw)-1],
+ "session hash": hashToken(raw),
+ "derived plus a byte": tok + "0",
+ } {
+ if csrfOK(got, raw) {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+ // No session is never a match, not even for an empty token.
+ if csrfOK("", "") || csrfOK(csrfToken(""), "") {
+ t.Fatal("an empty session accepted a token")
+ }
+}
+
+func TestCSRFFormOKWantsExactlyOneBodyValue(t *testing.T) {
+ raw := "s3ss10n-t0ken-for-the-test"
+ tok := csrfToken(raw)
+ post := func(body, query string) *http.Request {
+ r, _ := http.NewRequest(http.MethodPost, "/x?"+query, strings.NewReader(body))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ return r
+ }
+ if !csrfFormOK(post(url.Values{"csrf": {tok}}.Encode(), ""), raw) {
+ t.Fatal("one derived body value was refused")
+ }
+ if !csrfFormOK(post(url.Values{"csrf": {raw}}.Encode(), ""), raw) {
+ t.Fatal("one raw body value was refused during the transition")
+ }
+ for name, r := range map[string]*http.Request{
+ "none": post("", ""),
+ "query only": post("", "csrf="+tok),
+ "two values": post(url.Values{"csrf": {tok, tok}}.Encode(), ""),
+ "raw + derived": post(url.Values{"csrf": {raw, tok}}.Encode(), ""),
+ "wrong": post(url.Values{"csrf": {"wrong"}}.Encode(), ""),
+ } {
+ if csrfFormOK(r, raw) {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+}
+
+// TestSignedInPageDoesNotContainSessionToken: no page a signed-in browser
+// fetches carries the session cookie's value; the forms carry the derived
+// token instead.
+func TestSignedInPageDoesNotContainSessionToken(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInPaul(t, fx)
+ raw := sessionToken(t, fx, c)
+ tok := csrfToken(raw)
+ if status, loc, _ := postForm(t, c, fx.u("/apps/new"), url.Values{"csrf": {tok}, "name": {"zephyr"}}); status != http.StatusSeeOther {
+ t.Fatalf("create app = %d -> %q", status, loc)
+ }
+ for _, u := range []string{
+ fx.ts.URL + "/accounts",
+ fx.ts.URL + "/accounts/new",
+ fx.ts.URL + "/settings",
+ fx.u("/"),
+ fx.u("/settings"),
+ fx.u("/apps/zephyr"),
+ fx.u("/apps/zephyr/settings"),
+ fx.u("/apps/zephyr/releases"),
+ } {
+ status, _, body := get(t, c, u)
+ if status != http.StatusOK {
+ t.Fatalf("GET %s = %d", u, status)
+ }
+ if strings.Contains(body, raw) {
+ t.Errorf("GET %s: the page carries the raw session token", u)
+ }
+ if !strings.Contains(body, `name="csrf" value="`+tok+`"`) {
+ t.Errorf("GET %s: no form carries the derived CSRF token", u)
+ }
+ }
+
+ // A confirm card: its hidden fields are built in Go, not by the layout.
+ freshApp(t, fx, "sprout")
+ status, _, body := postForm(t, c, fx.u("/apps/sprout/rename"), url.Values{"csrf": {tok}, "to": {"sapling"}})
+ card := confirmCard(t, status, body, "Rename sprout to sapling?", raw)
+ if strings.Contains(card, raw) {
+ t.Error("the confirm card carries the raw session token")
+ }
+
+ // The signed-in demo claim page, which fills its own CSRF field.
+ s, _, claim := claimTestServer(t)
+ b := newClaimBrowser(t, s, claim)
+ b.login("actual@example.com", MethodKeymail, true)
+ page := b.request("GET", "/demo/claim", nil).Body.String()
+ if b.session == "" || strings.Contains(page, b.session) {
+ t.Error("the signed-in demo claim page carries the raw session token")
+ }
+ if !strings.Contains(page, `name="csrf" value="`+csrfToken(b.session)+`"`) {
+ t.Error("the signed-in demo claim page carries no derived CSRF token")
+ }
+}
+
+// TestCSRFTransitionEndToEnd: a form rendered before the deploy (raw token)
+// and one rendered after (derived) both go through during the transition
+// release; anything else is the same 403 as ever.
+func TestCSRFTransitionEndToEnd(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInPaul(t, fx)
+ raw := sessionToken(t, fx, c)
+ for name, form := range map[string]url.Values{
+ "raw (pre-deploy page)": {"csrf": {raw}, "name": {"before"}},
+ "derived": {"csrf": {csrfToken(raw)}, "name": {"after"}},
+ } {
+ if status, loc, body := postForm(t, c, fx.u("/apps/new"), form); status != http.StatusSeeOther {
+ t.Fatalf("%s: create app = %d -> %q:\n%s", name, status, loc, body)
+ }
+ }
+ for name, form := range map[string]url.Values{
+ "none": {"name": {"none"}},
+ "wrong": {"csrf": {"wrong"}, "name": {"wrong"}},
+ "session hash": {"csrf": {hashToken(raw)}, "name": {"hash"}},
+ "other's derived": {"csrf": {csrfToken("someone-else")}, "name": {"other"}},
+ "two csrf values": {"csrf": {csrfToken(raw), "wrong"}, "name": {"two"}},
+ } {
+ status, _, body := postForm(t, c, fx.u("/apps/new"), form)
+ if status != http.StatusForbidden || !strings.Contains(body, "Cross-site request blocked.") {
+ t.Fatalf("%s: create app = %d, want 403 Cross-site request blocked.", name, status)
+ }
+ }
+}
+
+// TestStepUpReplayCarriesDerivedCSRF: a step-up-protected POST sent with the
+// derived token parks without any token, and the replay after the passkey
+// round trip satisfies the CSRF check and lands. That the replay injects the
+// derived token, not the raw session, is pinned by TestNoRawSessionAsCSRF
+// (the form.Set("csrf", ...) shape).
+func TestStepUpReplayCarriesDerivedCSRF(t *testing.T) {
+ fx, c, raw := memberFixture(t)
+ tok := csrfToken(raw)
+ status, loc, _ := postForm(t, c, fx.u("/members/remove"),
+ url.Values{"csrf": {tok}, "address": {"kim@keymail.dev"}})
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, fx.fk.srv.URL) {
+ t.Fatalf("removal = %d -> %q, want a redirect into Keymail", status, loc)
+ }
+ var leaked int
+ fx.st.db.QueryRow(`SELECT COUNT(*) FROM pending_actions WHERE form LIKE ? OR form LIKE ?`, "%"+raw+"%", "%"+tok+"%").Scan(&leaked)
+ if leaked != 0 {
+ t.Fatal("a pending action stored a CSRF token")
+ }
+ status, loc, body := completeStepUp(t, fx, c, loc)
+ if status != http.StatusSeeOther {
+ t.Fatalf("resumed removal = %d -> %q:\n%s", status, loc, body)
+ }
+ if role, _ := fx.st.Role(OpsAccountID, "kim@keymail.dev"); role != "" {
+ t.Fatalf("kim is still a %q after the replayed removal", role)
+ }
+}
diff --git a/internal/console/demo_claim_kept.go b/internal/console/demo_claim_kept.go
index e5fb4400f..107dd08fb 100644
--- a/internal/console/demo_claim_kept.go
+++ b/internal/console/demo_claim_kept.go
@@ -32,7 +32,7 @@ func (s *Server) handleDemoClaimKeptPage(w http.ResponseWriter, r *http.Request)
}
_, session, _ := s.session(r)
s.demoClaimPageHeaders(w, s.km.Origin())
- _ = s.renderDemoClaimPage(w, demoClaimPageData{Chrome: page{Brand: s.brandName()}, Copy: demoClaimBrowserCopy(), State: "missing", Nonce: demoClaimNonce(raw, session), CSRF: session})
+ _ = s.renderDemoClaimPage(w, demoClaimPageData{Chrome: page{Brand: s.brandName()}, Copy: demoClaimBrowserCopy(), State: "missing", Nonce: demoClaimNonce(raw, session), CSRF: csrfToken(session)})
}
func (s *Server) handleDemoClaimKept(w http.ResponseWriter, r *http.Request) {
@@ -47,7 +47,7 @@ func (s *Server) handleDemoClaimKept(w http.ResponseWriter, r *http.Request) {
cookie := demoClaimCookie(r)
_, session, _ := s.session(r)
nonce := r.PostForm.Get("nonce")
- if cookie == "" || nonce == "" || subtle.ConstantTimeCompare([]byte(nonce), []byte(demoClaimNonce(cookie, session))) != 1 || (session != "" && subtle.ConstantTimeCompare([]byte(r.PostForm.Get("csrf")), []byte(session)) != 1) {
+ if cookie == "" || nonce == "" || subtle.ConstantTimeCompare([]byte(nonce), []byte(demoClaimNonce(cookie, session))) != 1 || (session != "" && !csrfFormOK(r, session)) {
s.demoClaimBrowserError(w, 403, demoClaimWrongSite)
return
}
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index 2c9e8f925..6db225e31 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -163,7 +163,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
setDemoClaimCookie(w, cookie, time.Now().Add(15*time.Minute))
}
address, session, _ := s.session(r)
- p := demoClaimPageData{Chrome: s.basePage(r), Copy: demoClaimBrowserCopy(), Nonce: demoClaimNonce(cookie, session), CSRF: session, Address: address, State: "missing"}
+ p := demoClaimPageData{Chrome: s.basePage(r), Copy: demoClaimBrowserCopy(), Nonce: demoClaimNonce(cookie, session), CSRF: csrfToken(session), Address: address, State: "missing"}
selection, resume := s.takeDemoClaimSelection(w, r, session, p.Nonce)
s.chrome(&p.Chrome)
p.Copy["next"] = fmt.Sprintf(demoClaimCLINext, s.cfg.Origin)
@@ -330,7 +330,7 @@ func (s *Server) demoClaimBrowserGate(w http.ResponseWriter, r *http.Request) bo
cookie := demoClaimCookie(r)
_, session, _ := s.session(r)
nonce := r.PostForm.Get("nonce")
- if cookie == "" || nonce == "" || subtle.ConstantTimeCompare([]byte(nonce), []byte(demoClaimNonce(cookie, session))) != 1 || (session != "" && subtle.ConstantTimeCompare([]byte(r.PostForm.Get("csrf")), []byte(session)) != 1) {
+ if cookie == "" || nonce == "" || subtle.ConstantTimeCompare([]byte(nonce), []byte(demoClaimNonce(cookie, session))) != 1 || (session != "" && !csrfFormOK(r, session)) {
s.demoClaimBrowserError(w, 403, demoClaimWrongSite)
return false
}
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go
index ad0aa06b2..8afa5f78f 100644
--- a/internal/console/economicspass.go
+++ b/internal/console/economicspass.go
@@ -2,7 +2,6 @@ package console
import (
"context"
- "crypto/subtle"
"encoding/json"
"errors"
"fmt"
@@ -1342,7 +1341,7 @@ func (s *Server) handleEconomicsScenarioSave(w http.ResponseWriter, r *http.Requ
http.NotFound(w, r)
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -1470,7 +1469,7 @@ func (s *Server) handleEconomicsBillSave(w http.ResponseWriter, r *http.Request)
http.NotFound(w, r)
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -1555,7 +1554,7 @@ func (s *Server) handleEconomicsTierSave(w http.ResponseWriter, r *http.Request)
http.NotFound(w, r)
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/envform.go b/internal/console/envform.go
index 64a1307f9..57bf5a4eb 100644
--- a/internal/console/envform.go
+++ b/internal/console/envform.go
@@ -6,7 +6,7 @@
// Form protocol, POST /a/{sqid}/apps/{app}/settings/environments, sent
// application/x-www-form-urlencoded only:
//
-// csrf the session token
+// csrf csrfToken(session), csrf.go
// bundle the bundle with staged changes, "" when none
// ver.<b> every card's version as the page showed it
// sealed_to the fingerprint of the key the page seals to:
@@ -48,7 +48,6 @@ package console
import (
"context"
- "crypto/subtle"
"errors"
"log"
"mime"
@@ -715,7 +714,7 @@ func (s *Server) handleEnvForm(w http.ResponseWriter, r *http.Request) {
s.renderMessage(w, r, http.StatusRequestEntityTooLarge, "Refused", "This form is too large.")
return
}
- if tok := r.PostForm["csrf"]; len(tok) != 1 || subtle.ConstantTimeCompare([]byte(tok[0]), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/errorsview.go b/internal/console/errorsview.go
index 3eaa3b791..665986684 100644
--- a/internal/console/errorsview.go
+++ b/internal/console/errorsview.go
@@ -7,7 +7,6 @@ package console
import (
"context"
- "crypto/subtle"
"log"
"net/http"
"net/url"
@@ -298,7 +297,7 @@ func (s *Server) handleAppErrorLevel(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -341,7 +340,7 @@ func (s *Server) handleAccountErrorLevel(w http.ResponseWriter, r *http.Request)
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index bad2b9c16..d2ecb3b58 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -24,7 +24,6 @@ package console
import (
"context"
"crypto/rand"
- "crypto/subtle"
"encoding/hex"
"errors"
"fmt"
@@ -1208,7 +1207,7 @@ func (s *Server) handleAppPlace(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -1250,7 +1249,7 @@ func (s *Server) handleFleetPlacePage(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -1613,7 +1612,7 @@ func (s *Server) handleFleetRotateBoxPage(w http.ResponseWriter, r *http.Request
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -1678,7 +1677,7 @@ func (s *Server) handleFleetDetachBoxPage(w http.ResponseWriter, r *http.Request
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -1745,7 +1744,7 @@ func (s *Server) handleFleetTagBoxPage(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/gate_shadow_guard_test.go b/internal/console/gate_shadow_guard_test.go
new file mode 100644
index 000000000..a8229571b
--- /dev/null
+++ b/internal/console/gate_shadow_guard_test.go
@@ -0,0 +1,1390 @@
+package console
+
+// TestConsoleJSONNeverCarriesGateHash guards the password gate's one secret:
+// provision.Record.Gate (and registry.Route.Gate, the converged copy) is an
+// app's bcrypt hash and never leaves the console. Every view that carries a
+// record today shadows it with a shallower `json:"gate,omitempty"` field that
+// is always "" (apiRecordView, instanceGetRecord, apiinstances.go). This test
+// makes that a rule for every future view rather than a habit.
+//
+// It type-checks the package once and finds every JSON sink in it, by the
+// callee's types.Func.FullName: writeJSON (its body), json.Marshal,
+// json.MarshalIndent and (*json.Encoder).Encode, plus every function of the
+// package whose sink body can carry one of its own interface-holding
+// parameters (demoClaimReply, relayConn.send, or one that wraps the parameter
+// in a map: a wrapper), found to a fixed point.
+//
+// For each call it takes the static type of the body argument. Where a value
+// can hide another type (an interface, or a map, slice, array, pointer or
+// struct holding one) it follows the value back: a composite literal's
+// values in such slots, any(x), append, a type assertion, a local variable or
+// one of its fields or elements to everything the function assigns there
+// (multi-result and range assignments included), and a call to a function of
+// the package into its return expressions, binding its parameters to the
+// call's arguments. What it cannot follow (a function value, a callee given a
+// map or pointer to fill, a package variable, a struct field read off a
+// parameter, a call outside the package) is an unresolved site, and
+// gsUnresolved pins that inventory: a site appearing or disappearing fails,
+// so a new blind spot is always seen and checked by hand.
+//
+// Each type is then walked as encoding/json walks it (exported fields;
+// embedded structs promoted, the shallowest field of a JSON name winning, a
+// tagged one breaking a tie and an untied pair dropping both; invalid tag
+// names ignored; pointers, slices, arrays and map values), failing where a
+// Gate field wins under its own JSON name ("gate" for Record, "Gate" for
+// Route, which has no tag). A type whose method set, promoted methods
+// included, has MarshalJSON or MarshalText is not encoded field by field, so
+// no shadow protects it: every field it holds, exported or not, is walked,
+// and any Gate reached fails (registry.ColdRows writes its whole Route).
+//
+// json.Marshal also builds what the console stores, and a stored record must
+// keep its hash. Those few calls are named in gsNotResponses, by enclosing
+// function and body type; an entry that no longer matches fails.
+//
+// A negative control type-checks a small in-memory package against the same
+// provision and registry types: exactly its leak* functions must be flagged
+// and exactly its unresolved* functions reported as unresolved.
+
+import (
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "go/types"
+ "path/filepath"
+ "reflect"
+ "slices"
+ "sort"
+ "strings"
+ "testing"
+ "unicode"
+
+ "golang.org/x/tools/go/packages"
+ "golang.org/x/tools/go/types/typeutil"
+)
+
+const (
+ gsProvision = "github.com/carlosframework/platform/internal/provision"
+ gsRegistry = "github.com/carlosframework/platform/internal/registry"
+)
+
+// gsNotResponses are the json.Marshal calls that must carry the hash because
+// they are not answers: an enclosing function (FullName) and the body types it
+// may marshal whole. Adding one is a ruling; the reason goes beside it.
+var gsNotResponses = map[string][]string{
+ // The record a new lifetime writes to the bucket (Allocation.Body ->
+ // provision.WriteRecord): the bucket is where the hash lives.
+ "(*" + sgConsole + ".Server).createRecordWithLifetimeLocked": {gsProvision + ".Record"},
+ // An in-memory change stamp for the replica placement cache, compared
+ // and never sent.
+ sgConsole + ".replicaStamp": {gsProvision + ".Record"},
+}
+
+// gsUnresolved is every place a JSON body's value comes from that the guard
+// cannot follow, as "function: kind expression". Each was read by hand and
+// carries no record or route. A new one fails until it is made traceable or
+// read and added; one that disappears fails until removed.
+var gsUnresolved = []string{
+ // stamp is a local func value: nil, or a time formatted RFC 3339.
+ "(*Server).handleAPIAppList: call stamp",
+ // region is filled by echoCreatedRegion inside a closure: region codes,
+ // names, a label, a source and the available list, no record.
+ "(*Server).handleAPICreateApp: handed to maps.Copy",
+ // The job comes from s.systemJobs; its Result is set only by
+ // setResult, whose one caller (apisystemgeoip.go) stores a
+ // geoip.Pointer.
+ "(*Server).handleAPISystemJob: receiver s",
+}
+
+func TestConsoleJSONNeverCarriesGateHash(t *testing.T) {
+ root, err := filepath.Abs(filepath.Join("..", ".."))
+ if err != nil {
+ t.Fatal(err)
+ }
+ cfg := &packages.Config{Dir: root, Env: sgEnv(),
+ Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax |
+ packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports,
+ }
+ pkgs, err := packages.Load(cfg, "./internal/console")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if packages.PrintErrors(pkgs) > 0 || len(pkgs) != 1 {
+ t.Fatal("loading internal/console failed")
+ }
+ pkg := pkgs[0]
+ deps := gsDeps(pkg.Types)
+ gates := gsGateFields(t, deps)
+
+ res := gsScan(pkg.Fset, pkg.TypesInfo, pkg.Syntax, pkg.Types, gates)
+ t.Logf("%d JSON sink calls checked; %d shadowed Gate fields seen; %d unresolved sites; wrappers: %s",
+ res.calls, res.shadowed, len(res.open), strings.Join(res.wrappers, ", "))
+ used := map[string]bool{}
+ for _, f := range res.findings {
+ if slices.Contains(gsNotResponses[f.fn], f.root) {
+ used[f.fn] = true
+ continue
+ }
+ t.Errorf("%s: JSON body reaches the gate hash as %s; shadow it with a shallower HiddenGate string `json:\"gate,omitempty\"` (apiRecordView)", f.pos, f.path)
+ }
+ for fn := range gsNotResponses {
+ if !used[fn] {
+ t.Errorf("gsNotResponses names %s, which no longer marshals a gate hash; remove the entry", fn)
+ }
+ }
+ for _, k := range gsSortedKeys(res.open) {
+ if !slices.Contains(gsUnresolved, k) {
+ t.Errorf("%s: the guard cannot follow %q into a JSON body; make it traceable, or read it by hand and add it to gsUnresolved", res.open[k].pos, k)
+ }
+ }
+ for _, k := range gsUnresolved {
+ if _, ok := res.open[k]; !ok {
+ t.Errorf("gsUnresolved lists %q, which the guard no longer finds; remove it", k)
+ }
+ }
+ // The guard must have seen what it guards: the record views' shadows,
+ // and the sinks it is named for. Zero means it went blind (a field or
+ // sink renamed), not that the package is clean.
+ if res.calls < 100 || res.shadowed == 0 || len(res.wrappers) == 0 {
+ t.Errorf("guard saw %d sink calls, %d shadowed Gate fields, %d wrappers; it no longer finds what it checks", res.calls, res.shadowed, len(res.wrappers))
+ }
+
+ t.Run("negative control", func(t *testing.T) {
+ fset := token.NewFileSet()
+ file, err := parser.ParseFile(fset, "gate_shadow_fixture.go", gsFixtureSrc, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ info := &types.Info{Types: map[ast.Expr]types.TypeAndValue{}, Defs: map[*ast.Ident]types.Object{},
+ Uses: map[*ast.Ident]types.Object{}, Selections: map[*ast.SelectorExpr]*types.Selection{},
+ Instances: map[*ast.Ident]types.Instance{}, Implicits: map[ast.Node]types.Object{}}
+ conf := types.Config{Importer: gsImporter(deps)}
+ fix, err := conf.Check("example.com/gateshadowfixture", fset, []*ast.File{file}, info)
+ if err != nil {
+ t.Fatalf("type-check the fixture: %v", err)
+ }
+ res := gsScan(fset, info, []*ast.File{file}, fix, gates)
+ flagged, open := map[string]bool{}, map[string]bool{}
+ for _, f := range res.findings {
+ flagged[f.in] = true
+ }
+ for _, o := range res.open {
+ open[o.in] = true
+ }
+ for _, d := range file.Decls {
+ fd, ok := d.(*ast.FuncDecl)
+ if !ok {
+ continue
+ }
+ name := fd.Name.Name
+ switch leak := strings.HasPrefix(name, "leak"); {
+ case leak && !flagged[name]:
+ t.Errorf("fixture %s leaks the gate hash but was not flagged", name)
+ case !leak && flagged[name]:
+ t.Errorf("fixture %s shadows the gate hash but was flagged", name)
+ }
+ switch unres := strings.HasPrefix(name, "unresolved"); {
+ case unres && !open[name]:
+ t.Errorf("fixture %s cannot be followed but was not reported unresolved", name)
+ case !unres && open[name]:
+ t.Errorf("fixture %s was reported unresolved", name)
+ }
+ }
+ if t.Failed() {
+ for _, k := range gsSortedKeys(res.open) {
+ t.Logf("unresolved: %s", k)
+ }
+ }
+ })
+}
+
+// gsFixtureSrc is the negative control. Each leak* function must be flagged,
+// each unresolved* one reported unresolved, and nothing else either.
+const gsFixtureSrc = `package gateshadowfixture
+
+import (
+ "encoding/json"
+ "io"
+ "maps"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+type v struct{ provision.Record }
+
+type w struct {
+ provision.Record
+ HiddenGate string ` + "`json:\"gate,omitempty\"`" + `
+}
+
+func leakEmbedded() { _, _ = json.Marshal(v{}) }
+
+func safeShadowed() { _, _ = json.Marshal(w{}) }
+
+// A shadow two levels up still wins.
+func safeShadowedDeeper() { _, _ = json.Marshal(struct{ w }{}) }
+
+// A shadow beside a named field does not reach into it.
+func leakNestedNotShadowed() {
+ _, _ = json.Marshal(struct {
+ Rec provision.Record ` + "`json:\"rec\"`" + `
+ HiddenGate string ` + "`json:\"gate,omitempty\"`" + `
+ }{})
+}
+
+// Route's Gate has no tag: it is emitted as "Gate", and a "gate" shadow
+// does not hide it.
+func leakRoute() {
+ _, _ = json.Marshal(struct {
+ registry.Route
+ HiddenGate string ` + "`json:\"gate,omitempty\"`" + `
+ }{})
+}
+
+func leakPointerSlice() { _, _ = json.MarshalIndent([]*provision.Record{}, "", " ") }
+
+func leakMapValue() { _, _ = json.Marshal(map[string]any{"ok": 1, "rec": map[string]any{"r": v{}}}) }
+
+func safeMapValue() { _, _ = json.Marshal(map[string]any{"rec": []w{}}) }
+
+func leakLocalMap() {
+ var rec provision.Record
+ out := map[string]any{"ok": true}
+ out["rec"] = &rec
+ _ = json.NewEncoder(io.Discard).Encode(out)
+}
+
+func leakConversion() { _, _ = json.Marshal(any(registry.Route{})) }
+
+// A struct literal's field values are its type's fields, already walked;
+// an interface field hides what it holds.
+func safeStructField() { _, _ = json.Marshal(w{Record: provision.Record{}}) }
+
+func leakInterfaceField() { _, _ = json.Marshal(struct{ X any }{X: v{}}) }
+
+func reply(dst io.Writer, body any) { _ = json.NewEncoder(dst).Encode(body) }
+
+func leakWrapper() { reply(io.Discard, map[string]v{}) }
+
+func safeWrapper() { reply(io.Discard, w{}) }
+
+func leakEncoderMethod() {
+ enc := json.NewEncoder(io.Discard)
+ _ = enc.Encode(struct{ R *registry.Route }{})
+}
+
+// Returns of the package's own functions, with their parameters bound.
+func answer() map[string]any { return map[string]any{"rec": provision.Record{}} }
+
+func leakHelperReturn() { _, _ = json.Marshal(answer()) }
+
+func wrapIt(x any) map[string]any {
+ out := map[string]any{}
+ out["x"] = x
+ return out
+}
+
+func leakHelperParam() { _, _ = json.Marshal(wrapIt(v{})) }
+
+func safeHelperParam() { _, _ = json.Marshal(wrapIt(w{})) }
+
+func scanReply() (any, error) { return v{}, nil }
+
+func leakMultiResult() {
+ reply, err := scanReply()
+ if err != nil {
+ return
+ }
+ _, _ = json.Marshal(reply)
+}
+
+func named() (out any) {
+ out = &v{}
+ return
+}
+
+func leakNamedResult() { _, _ = json.Marshal(named()) }
+
+// Structs held in locals.
+func leakStructLocal() {
+ resp := struct{ X any }{X: v{}}
+ _, _ = json.Marshal(resp)
+}
+
+func leakStructFieldAssign() {
+ var resp struct{ X any }
+ resp.X = []v{}
+ _, _ = json.Marshal(&resp)
+}
+
+func leakRange() {
+ items := []any{v{}}
+ for _, it := range items {
+ _, _ = json.Marshal(it)
+ }
+}
+
+// A wrapper that wraps its parameter before encoding it.
+func replyData(dst io.Writer, body any) {
+ _ = json.NewEncoder(dst).Encode(map[string]any{"data": body})
+}
+
+func leakWrapperWrapsParam() { replyData(io.Discard, v{}) }
+
+func safeWrapperWrapsParam() { replyData(io.Discard, w{}) }
+
+// A promoted MarshalJSON makes the shadow useless: ColdRows writes its
+// whole Route.
+type coldView struct {
+ registry.ColdRows
+ Route struct{}
+}
+
+func leakPromotedMarshaler() { _, _ = json.Marshal(coldView{}) }
+
+func safeMarshaler() { _, _ = json.Marshal(struct{ At time.Time }{}) }
+
+// Two local types of one name are two types.
+func safeLocalType() {
+ type response struct{ OK bool }
+ _, _ = json.Marshal(response{})
+}
+
+func leakLocalType() {
+ type response struct{ provision.Record }
+ _, _ = json.Marshal(response{})
+}
+
+// An invalid tag name is ignored: A and B keep their Go names, both emitted.
+func leakInvalidTags() {
+ _, _ = json.Marshal(struct {
+ A provision.Record ` + "`json:\"\\t\"`" + `
+ B provision.Record ` + "`json:\"\\t\"`" + `
+ }{})
+}
+
+// A map or receiver a function of the package fills.
+func fill(m map[string]any) { m["rec"] = v{} }
+
+func leakFilledByCallee() {
+ out := make(map[string]any)
+ fill(out)
+ _, _ = json.Marshal(out)
+}
+
+type bag struct{ M map[string]any }
+
+func (b *bag) put(x any) { b.M["x"] = x }
+
+func leakFilledByMethod() {
+ b := bag{M: map[string]any{}}
+ b.put(v{})
+ _, _ = json.Marshal(b)
+}
+
+// What the guard cannot follow.
+func unresolvedCallee() {
+ out := map[string]any{}
+ maps.Copy(out, map[string]any{})
+ _, _ = json.Marshal(out)
+}
+
+func unresolvedFuncValue() {
+ f := func() any { return v{} }
+ _, _ = json.Marshal(f())
+}
+
+var held any
+
+func unresolvedPackageVar() { _, _ = json.Marshal(held) }
+`
+
+// gsGate is a guarded field and the JSON name it is emitted under.
+type gsGate struct {
+ owner string
+ name string
+}
+
+// gsGateFields finds Record.Gate and Route.Gate in the loaded types, so a
+// rename fails here rather than letting the guard go blind.
+func gsGateFields(t *testing.T, deps map[string]*types.Package) map[*types.Var]gsGate {
+ t.Helper()
+ out := map[*types.Var]gsGate{}
+ for _, want := range []struct{ pkg, typ string }{{gsProvision, "Record"}, {gsRegistry, "Route"}} {
+ p := deps[want.pkg]
+ if p == nil {
+ t.Fatalf("%s is not among internal/console's imports", want.pkg)
+ }
+ obj := p.Scope().Lookup(want.typ)
+ if obj == nil {
+ t.Fatalf("%s.%s not found; update the guard", want.pkg, want.typ)
+ }
+ st, ok := obj.Type().Underlying().(*types.Struct)
+ if !ok {
+ t.Fatalf("%s.%s is not a struct", want.pkg, want.typ)
+ }
+ found := false
+ for i := 0; i < st.NumFields(); i++ {
+ if f := st.Field(i); f.Name() == "Gate" {
+ name, _ := gsJSONName(st.Tag(i))
+ if name == "" {
+ name = "Gate"
+ }
+ out[f] = gsGate{owner: want.typ, name: name}
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("%s.%s has no Gate field; update the guard", want.pkg, want.typ)
+ }
+ }
+ return out
+}
+
+// gsDeps is every package internal/console reaches, by path.
+func gsDeps(p *types.Package) map[string]*types.Package {
+ out := map[string]*types.Package{}
+ var walk func(*types.Package)
+ walk = func(p *types.Package) {
+ if out[p.Path()] != nil {
+ return
+ }
+ out[p.Path()] = p
+ for _, q := range p.Imports() {
+ walk(q)
+ }
+ }
+ walk(p)
+ return out
+}
+
+type gsImporter map[string]*types.Package
+
+func (m gsImporter) Import(path string) (*types.Package, error) {
+ if p := m[path]; p != nil {
+ return p, nil
+ }
+ return nil, fmt.Errorf("import %q not loaded", path)
+}
+
+func gsSortedKeys[V any](m map[string]V) []string {
+ keys := make([]string, 0, len(m))
+ for k := range m {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ return keys
+}
+
+type gsFinding struct {
+ pos token.Position
+ in string // enclosing function's name, "" at package level
+ fn string // its types.Func.FullName
+ root string // the walked type, types.TypeString
+ path string // e.g. apiThing.Record.gate
+}
+
+// gsOpen is one place a body's value comes from that the trace cannot follow.
+type gsOpen struct {
+ pos token.Position
+ in string // the function it is in, by name
+}
+
+type gsResult struct {
+ findings []gsFinding
+ open map[string]gsOpen // by "function: kind expression"
+ calls int
+ shadowed int
+ wrappers []string
+}
+
+// gsScanner holds what one package's scan shares.
+type gsScanner struct {
+ fset *token.FileSet
+ info *types.Info
+ pkg *types.Package
+ decls map[*types.Func]*ast.FuncDecl
+ sinks map[string]map[int]bool // callee FullName -> body parameter indexes
+ hidem typeutil.Map // types.Type -> bool
+}
+
+func (sc *gsScanner) sinkParams(call *ast.CallExpr) map[int]bool {
+ if fn, ok := typeutil.Callee(sc.info, call).(*types.Func); ok {
+ return sc.sinks[fn.Origin().FullName()]
+ }
+ return nil
+}
+
+func (sc *gsScanner) short(fn *types.Func) string {
+ return strings.ReplaceAll(fn.FullName(), sc.pkg.Path()+".", "")
+}
+
+// hides reports whether a value of t can carry a type its static type does
+// not show: an interface, or a pointer, map, slice, array or struct holding
+// one.
+func (sc *gsScanner) hides(t types.Type) bool {
+ if t == nil {
+ return false
+ }
+ if r := sc.hidem.At(t); r != nil {
+ return r.(bool)
+ }
+ sc.hidem.Set(t, false) // a cycle adds nothing
+ h := false
+ switch u := t.Underlying().(type) {
+ case *types.Interface:
+ h = true
+ case *types.Pointer:
+ h = sc.hides(u.Elem())
+ case *types.Slice:
+ h = sc.hides(u.Elem())
+ case *types.Array:
+ h = sc.hides(u.Elem())
+ case *types.Map:
+ h = sc.hides(u.Elem())
+ case *types.Struct:
+ for i := 0; i < u.NumFields() && !h; i++ {
+ f := u.Field(i)
+ h = (f.Exported() || f.Embedded()) && sc.hides(f.Type())
+ }
+ }
+ sc.hidem.Set(t, h)
+ return h
+}
+
+// gsScan finds every JSON sink call in files and walks its body's types.
+func gsScan(fset *token.FileSet, info *types.Info, files []*ast.File, pkg *types.Package, gates map[*types.Var]gsGate) gsResult {
+ sc := &gsScanner{fset: fset, info: info, pkg: pkg, decls: map[*types.Func]*ast.FuncDecl{},
+ sinks: map[string]map[int]bool{
+ "encoding/json.Marshal": {0: true},
+ "encoding/json.MarshalIndent": {0: true},
+ "(*encoding/json.Encoder).Encode": {0: true},
+ }}
+ for _, file := range files {
+ for _, d := range file.Decls {
+ if fd, ok := d.(*ast.FuncDecl); ok {
+ if fn, ok := info.Defs[fd.Name].(*types.Func); ok {
+ sc.decls[fn] = fd
+ }
+ }
+ }
+ }
+ if fn, ok := pkg.Scope().Lookup("writeJSON").(*types.Func); ok {
+ sig := fn.Type().(*types.Signature)
+ for i := 0; i < sig.Params().Len(); i++ {
+ if sig.Params().At(i).Name() == "body" {
+ sc.sinks[fn.FullName()] = map[int]bool{i: true}
+ }
+ }
+ }
+ // eachSink calls visit for every sink body argument in n.
+ eachSink := func(n ast.Node, visit func(arg ast.Expr, call *ast.CallExpr)) {
+ ast.Inspect(n, func(n ast.Node) bool {
+ if call, ok := n.(*ast.CallExpr); ok {
+ for i := range sc.sinkParams(call) {
+ if i < len(call.Args) {
+ visit(call.Args[i], call)
+ }
+ }
+ }
+ return true
+ })
+ }
+
+ // Wrappers, to a fixed point: a function whose sink body can carry its
+ // own parameter is a sink for that parameter.
+ var wrappers []string
+ for changed := true; changed; {
+ changed = false
+ for fn, fd := range sc.decls {
+ if fd.Body == nil {
+ continue
+ }
+ eachSink(fd.Body, func(arg ast.Expr, _ *ast.CallExpr) {
+ tr := sc.trace()
+ tr.types(&gsFrame{decl: fd, fn: fn}, arg)
+ for j := range tr.hits {
+ name := fn.FullName()
+ if sc.sinks[name] == nil {
+ sc.sinks[name] = map[int]bool{}
+ wrappers = append(wrappers, sc.short(fn))
+ }
+ if !sc.sinks[name][j] {
+ sc.sinks[name][j] = true
+ changed = true
+ }
+ }
+ })
+ }
+ }
+ sort.Strings(wrappers)
+
+ res := gsResult{wrappers: wrappers, open: map[string]gsOpen{}}
+ w := &gsWalker{gates: gates}
+ for _, file := range files {
+ for _, d := range file.Decls {
+ frame := &gsFrame{}
+ var n ast.Node = d
+ if fd, ok := d.(*ast.FuncDecl); ok {
+ if fd.Body == nil {
+ continue
+ }
+ fn, _ := info.Defs[fd.Name].(*types.Func)
+ frame, n = &gsFrame{decl: fd, fn: fn}, fd.Body
+ }
+ eachSink(n, func(arg ast.Expr, call *ast.CallExpr) {
+ res.calls++
+ tr := sc.trace()
+ for _, typ := range tr.types(frame, arg) {
+ leaks, shadowed := w.walk(typ)
+ res.shadowed += shadowed
+ for _, l := range leaks {
+ f := gsFinding{pos: fset.Position(call.Pos()), root: types.TypeString(typ, nil), path: l}
+ if frame.fn != nil {
+ f.in, f.fn = frame.fn.Name(), frame.fn.FullName()
+ }
+ res.findings = append(res.findings, f)
+ }
+ }
+ for k, o := range tr.open {
+ if _, ok := res.open[k]; !ok {
+ res.open[k] = o
+ }
+ }
+ })
+ }
+ }
+ return res
+}
+
+// gsFrame is one function the trace is in. A frame entered through a call
+// binds the callee's parameters (and receiver) to the call's arguments,
+// read in the caller's frame.
+type gsFrame struct {
+ decl *ast.FuncDecl // nil at package level
+ fn *types.Func
+ caller *gsFrame
+ args map[*types.Var]ast.Expr
+}
+
+// gsTrace follows one sink body argument back to the types it can carry.
+type gsTrace struct {
+ sc *gsScanner
+ followed map[*ast.CallExpr]bool
+ hand map[gsHand]bool
+ seen map[gsSeen]bool
+ hits map[int]bool // the outermost function's parameters reached
+ open map[string]gsOpen
+}
+
+type gsSeen struct {
+ f *gsFrame
+ v *types.Var
+}
+
+func (sc *gsScanner) trace() *gsTrace {
+ return &gsTrace{sc: sc, followed: map[*ast.CallExpr]bool{}, hand: map[gsHand]bool{}, seen: map[gsSeen]bool{},
+ hits: map[int]bool{}, open: map[string]gsOpen{}}
+}
+
+func (tr *gsTrace) unresolved(f *gsFrame, kind string, e ast.Expr) {
+ in, name := "package level", ""
+ if f.fn != nil {
+ in, name = tr.sc.short(f.fn), f.fn.Name()
+ }
+ k := in + ": " + kind + " " + types.ExprString(e)
+ if _, ok := tr.open[k]; !ok {
+ tr.open[k] = gsOpen{pos: tr.sc.fset.Position(e.Pos()), in: name}
+ }
+}
+
+// types is e's static type and, where e can hide others, every type it can
+// carry.
+func (tr *gsTrace) types(f *gsFrame, e ast.Expr) []types.Type {
+ info := tr.sc.info
+ e = ast.Unparen(e)
+ t := info.TypeOf(e)
+ out := []types.Type{t}
+ hides := tr.sc.hides(t)
+ switch x := e.(type) {
+ case *ast.CompositeLit:
+ // Values only matter in slots that hide them.
+ if t == nil {
+ break
+ }
+ for i, el := range x.Elts {
+ var key ast.Expr
+ if kv, ok := el.(*ast.KeyValueExpr); ok {
+ key, el = kv.Key, kv.Value
+ }
+ if tr.sc.hides(tr.slot(t, key, i)) {
+ out = append(out, tr.types(f, el)...)
+ }
+ }
+ case *ast.UnaryExpr:
+ if x.Op == token.AND {
+ out = append(out, tr.types(f, x.X)...)
+ } else if hides {
+ tr.unresolved(f, "expression", x)
+ }
+ case *ast.CallExpr:
+ if !hides {
+ break
+ }
+ if tv, ok := info.Types[x.Fun]; ok && tv.IsType() {
+ if len(x.Args) == 1 {
+ out = append(out, tr.types(f, x.Args[0])...) // any(x)
+ }
+ break
+ }
+ if b, ok := tr.builtin(x); ok {
+ if b == "make" || b == "new" {
+ break // an empty value: it carries what is assigned to it later
+ }
+ if b != "append" {
+ tr.unresolved(f, "builtin", x)
+ break
+ }
+ for _, a := range x.Args {
+ out = append(out, tr.types(f, a)...)
+ }
+ break
+ }
+ out = append(out, tr.results(f, x, 0)...)
+ case *ast.Ident:
+ if hides {
+ out = append(out, tr.ident(f, x)...)
+ }
+ case *ast.SelectorExpr, *ast.IndexExpr, *ast.StarExpr:
+ if hides {
+ out = append(out, tr.rooted(f, e)...)
+ }
+ case *ast.TypeAssertExpr:
+ if hides {
+ out = append(out, tr.types(f, x.X)...)
+ }
+ case *ast.BasicLit, *ast.FuncLit:
+ default:
+ if hides {
+ tr.unresolved(f, "expression", e)
+ }
+ }
+ return out
+}
+
+// slot is the type the i'th element of a composite literal of type lit
+// fills: a map's or a list's element type, or a struct's field.
+func (tr *gsTrace) slot(lit types.Type, key ast.Expr, i int) types.Type {
+ switch u := lit.Underlying().(type) {
+ case *types.Map:
+ return u.Elem()
+ case *types.Slice:
+ return u.Elem()
+ case *types.Array:
+ return u.Elem()
+ case *types.Struct:
+ if id, ok := key.(*ast.Ident); ok {
+ if f, ok := tr.sc.info.Uses[id].(*types.Var); ok {
+ return f.Type()
+ }
+ } else if key == nil && i < u.NumFields() {
+ return u.Field(i).Type()
+ }
+ }
+ return types.Typ[types.Invalid]
+}
+
+func (tr *gsTrace) builtin(call *ast.CallExpr) (string, bool) {
+ id, ok := ast.Unparen(call.Fun).(*ast.Ident)
+ if !ok {
+ return "", false
+ }
+ b, ok := tr.sc.info.Uses[id].(*types.Builtin)
+ if !ok {
+ return "", false
+ }
+ return b.Name(), true
+}
+
+// rooted follows a field, element or dereference back to the value it is
+// read from; everything that value can carry covers the part.
+func (tr *gsTrace) rooted(f *gsFrame, e ast.Expr) []types.Type {
+ x := e
+ for {
+ switch y := ast.Unparen(x).(type) {
+ case *ast.SelectorExpr:
+ sel := tr.sc.info.Selections[y]
+ if sel == nil { // a qualified identifier: another package's variable
+ return tr.ident(f, y.Sel)
+ }
+ if sel.Kind() != types.FieldVal {
+ tr.unresolved(f, "method value", e)
+ return nil
+ }
+ x = y.X
+ case *ast.IndexExpr:
+ x = y.X
+ case *ast.StarExpr:
+ x = y.X
+ case *ast.Ident:
+ return tr.ident(f, y)
+ default:
+ return tr.types(f, y)
+ }
+ }
+}
+
+// ident follows a variable: a bound parameter to its argument, the
+// outermost function's parameter to a wrapper hit, and a local to
+// everything assigned to it.
+func (tr *gsTrace) ident(f *gsFrame, id *ast.Ident) []types.Type {
+ v, ok := tr.sc.info.Uses[id].(*types.Var)
+ if !ok {
+ return nil // a constant, function or nil
+ }
+ return tr.variable(f, v, id)
+}
+
+func (tr *gsTrace) variable(f *gsFrame, v *types.Var, id ast.Expr) []types.Type {
+ if v.Pkg() != tr.sc.pkg || v.Parent() == tr.sc.pkg.Scope() {
+ tr.unresolved(f, "package variable", id)
+ return nil
+ }
+ if f.decl == nil {
+ tr.unresolved(f, "variable", id)
+ return nil
+ }
+ k := gsSeen{f, v}
+ if tr.seen[k] {
+ return nil
+ }
+ tr.seen[k] = true
+ var out []types.Type
+ sig := f.fn.Type().(*types.Signature)
+ isParam := false
+ if arg, ok := f.args[v]; ok {
+ isParam = true
+ out = append(out, tr.types(f.caller, arg)...)
+ } else if v == sig.Recv() {
+ tr.unresolved(f, "receiver", id)
+ return nil
+ } else {
+ for j := 0; j < sig.Params().Len(); j++ {
+ if sig.Params().At(j) != v {
+ continue
+ }
+ isParam = true
+ if f.caller == nil {
+ tr.hits[j] = true
+ } else {
+ tr.unresolved(f, "parameter", id)
+ }
+ }
+ for j := 0; j < sig.Results().Len(); j++ {
+ if sig.Results().At(j) == v {
+ isParam = true // a named result, assigned in the body
+ }
+ }
+ }
+ got, defined := tr.assigned(f, v)
+ out = append(out, got...)
+ if !defined && !isParam {
+ tr.unresolved(f, "variable", id)
+ }
+ return out
+}
+
+// gsRootIs reports whether e is v or a field, element or dereference of it.
+func gsRootIs(info *types.Info, e ast.Expr, v *types.Var) bool {
+ for {
+ switch y := ast.Unparen(e).(type) {
+ case *ast.SelectorExpr:
+ if sel := info.Selections[y]; sel == nil || sel.Kind() != types.FieldVal {
+ return false
+ }
+ e = y.X
+ case *ast.IndexExpr:
+ e = y.X
+ case *ast.StarExpr:
+ e = y.X
+ case *ast.Ident:
+ return info.Uses[y] == v || info.Defs[y] == v
+ default:
+ return false
+ }
+ }
+}
+
+// assigned is every type the frame's function stores in v or in a part of
+// it, and whether it defines v. A map or pointer handed to a callee, or a
+// method called on v, may be filled where the trace cannot see: unresolved.
+func (tr *gsTrace) assigned(f *gsFrame, v *types.Var) (out []types.Type, defined bool) {
+ info := tr.sc.info
+ isV := func(e ast.Expr) bool {
+ id, ok := ast.Unparen(e).(*ast.Ident)
+ return ok && (info.Uses[id] == v || info.Defs[id] == v)
+ }
+ ast.Inspect(f.decl, func(n ast.Node) bool {
+ switch s := n.(type) {
+ case *ast.AssignStmt:
+ for i, l := range s.Lhs {
+ if !gsRootIs(info, l, v) {
+ continue
+ }
+ if isV(l) {
+ defined = true
+ }
+ switch {
+ case len(s.Lhs) == len(s.Rhs):
+ out = append(out, tr.types(f, s.Rhs[i])...)
+ case len(s.Rhs) == 1:
+ out = append(out, tr.multi(f, s.Rhs[0], i)...)
+ }
+ }
+ case *ast.ValueSpec:
+ for i, name := range s.Names {
+ if info.Defs[name] != v {
+ continue
+ }
+ defined = true
+ switch {
+ case len(s.Values) == len(s.Names):
+ out = append(out, tr.types(f, s.Values[i])...)
+ case len(s.Values) == 1:
+ out = append(out, tr.multi(f, s.Values[0], i)...)
+ }
+ }
+ case *ast.RangeStmt:
+ if (s.Key != nil && isV(s.Key)) || (s.Value != nil && isV(s.Value)) {
+ defined = true
+ out = append(out, tr.types(f, s.X)...)
+ }
+ case *ast.CallExpr:
+ if tr.sc.sinkParams(s) != nil {
+ break
+ }
+ if _, ok := tr.builtin(s); ok {
+ break
+ }
+ fn, _ := typeutil.Callee(info, s).(*types.Func)
+ var sig *types.Signature
+ if fn != nil {
+ fn = fn.Origin()
+ sig = fn.Type().(*types.Signature)
+ }
+ if sel, ok := ast.Unparen(s.Fun).(*ast.SelectorExpr); ok && isV(sel.X) && !types.IsInterface(v.Type()) {
+ if m := info.Selections[sel]; m != nil && m.Kind() == types.MethodVal {
+ var recv *types.Var
+ if sig != nil {
+ recv = sig.Recv()
+ }
+ out = append(out, tr.handed(f, s, fn, recv, "method call")...)
+ }
+ }
+ for j, a := range s.Args {
+ a = ast.Unparen(a)
+ u, ok := a.(*ast.UnaryExpr)
+ if ok && u.Op == token.AND && gsRootIs(info, u.X, v) || isV(a) && gsMutable(v.Type()) {
+ var param *types.Var
+ if sig != nil && j < sig.Params().Len() && !(sig.Variadic() && j == sig.Params().Len()-1) {
+ param = sig.Params().At(j)
+ }
+ out = append(out, tr.handed(f, s, fn, param, "handed to")...)
+ }
+ }
+ }
+ return true
+ })
+ return out, defined
+}
+
+// gsMutable reports whether a callee given a value of t can change what
+// the caller's value holds.
+func gsMutable(t types.Type) bool {
+ switch t.Underlying().(type) {
+ case *types.Map, *types.Pointer:
+ return true
+ }
+ return false
+}
+
+// multi is the i'th value of a multi-value right-hand side.
+func (tr *gsTrace) multi(f *gsFrame, rhs ast.Expr, i int) []types.Type {
+ switch r := ast.Unparen(rhs).(type) {
+ case *ast.CallExpr:
+ return tr.results(f, r, i)
+ case *ast.IndexExpr: // v, ok := m[k]
+ if i == 0 {
+ return tr.rooted(f, r)
+ }
+ case *ast.TypeAssertExpr: // v, ok := x.(T)
+ if i == 0 {
+ return tr.types(f, r.X)
+ }
+ default:
+ if i == 0 && tr.sc.hides(tr.sc.info.TypeOf(r)) {
+ tr.unresolved(f, "expression", r)
+ }
+ }
+ return nil
+}
+
+// results is what the i'th result of a call can carry: for a function of
+// the package, its return expressions read in a frame that binds its
+// parameters to the call's arguments.
+func (tr *gsTrace) results(f *gsFrame, call *ast.CallExpr, i int) []types.Type {
+ info := tr.sc.info
+ rt := info.TypeOf(call)
+ var out []types.Type
+ if tup, ok := rt.(*types.Tuple); ok {
+ if i >= tup.Len() {
+ return nil
+ }
+ rt = tup.At(i).Type()
+ out = append(out, rt)
+ }
+ if !tr.sc.hides(rt) || tr.followed[call] {
+ return out
+ }
+ tr.followed[call] = true
+ fn, _ := typeutil.Callee(info, call).(*types.Func)
+ if fn != nil {
+ fn = fn.Origin()
+ }
+ g := tr.enter(f, call, fn)
+ if g == nil {
+ tr.unresolved(f, "call", call.Fun)
+ return out
+ }
+ decl := g.decl
+ res := fn.Type().(*types.Signature).Results()
+ ast.Inspect(decl.Body, func(n ast.Node) bool {
+ switch r := n.(type) {
+ case *ast.FuncLit:
+ return false
+ case *ast.ReturnStmt:
+ switch {
+ case len(r.Results) == res.Len():
+ out = append(out, tr.types(g, r.Results[i])...)
+ case len(r.Results) == 1:
+ out = append(out, tr.multi(g, r.Results[0], i)...)
+ case len(r.Results) == 0 && res.At(i).Name() != "":
+ // A bare return: the named result, as assigned.
+ out = append(out, tr.variable(g, res.At(i), decl.Name)...)
+ }
+ }
+ return true
+ })
+ return out
+}
+
+// enter is the frame of a call to fn, a function of the package, with its
+// parameters and receiver bound to the call's arguments; nil when fn has no
+// body here.
+func (tr *gsTrace) enter(f *gsFrame, call *ast.CallExpr, fn *types.Func) *gsFrame {
+ if fn == nil {
+ return nil
+ }
+ decl := tr.sc.decls[fn]
+ if decl == nil || decl.Body == nil {
+ return nil
+ }
+ sig := fn.Type().(*types.Signature)
+ g := &gsFrame{decl: decl, fn: fn, caller: f, args: map[*types.Var]ast.Expr{}}
+ params := sig.Params()
+ if len(call.Args) == params.Len() || sig.Variadic() && len(call.Args) >= params.Len()-1 {
+ for j := 0; j < params.Len() && j < len(call.Args); j++ {
+ if sig.Variadic() && j == params.Len()-1 {
+ break
+ }
+ g.args[params.At(j)] = call.Args[j]
+ }
+ }
+ if recv := sig.Recv(); recv != nil {
+ if sel, ok := ast.Unparen(call.Fun).(*ast.SelectorExpr); ok {
+ g.args[recv] = sel.X
+ }
+ }
+ return g
+}
+
+// handed follows a value the caller handed to fn (as param, or as the
+// receiver) into what fn stores in it. A callee outside the package, a
+// function value or a variadic slot cannot be followed: unresolved.
+func (tr *gsTrace) handed(f *gsFrame, call *ast.CallExpr, fn *types.Func, param *types.Var, kind string) []types.Type {
+ g := tr.enter(f, call, fn)
+ if g == nil || param == nil {
+ tr.unresolved(f, kind, call.Fun)
+ return nil
+ }
+ k := gsHand{call, param}
+ if tr.hand[k] {
+ return nil
+ }
+ tr.hand[k] = true
+ got, _ := tr.assigned(g, param)
+ return got
+}
+
+type gsHand struct {
+ call *ast.CallExpr
+ param *types.Var
+}
+
+// gsWalker walks a type as encoding/json encodes it.
+type gsWalker struct {
+ gates map[*types.Var]gsGate
+ memo typeutil.Map // types.Type -> []string, leak paths; nil while in progress
+ opaque typeutil.Map // the same, for types under a custom marshaller
+ shad int
+}
+
+// walk returns the paths by which t emits a gate field, and how many gate
+// fields a shallower field shadowed on the way.
+func (w *gsWalker) walk(t types.Type) ([]string, int) {
+ w.shad = 0
+ leaks := w.value(t)
+ return leaks, w.shad
+}
+
+func gsDeref(t types.Type) types.Type {
+ for {
+ p, ok := t.Underlying().(*types.Pointer)
+ if !ok {
+ return t
+ }
+ t = p.Elem()
+ }
+}
+
+func gsLabel(t types.Type) string {
+ return types.TypeString(t, func(p *types.Package) string { return p.Name() })
+}
+
+// gsMarshaler reports whether encoding/json hands t, or *t, to its own
+// MarshalJSON or MarshalText, promoted methods included.
+func gsMarshaler(t types.Type) bool {
+ if types.IsInterface(t) {
+ return false
+ }
+ for _, m := range []types.Type{t, types.NewPointer(t)} {
+ ms := types.NewMethodSet(m)
+ if ms.Lookup(nil, "MarshalJSON") != nil || ms.Lookup(nil, "MarshalText") != nil {
+ return true
+ }
+ }
+ return false
+}
+
+func (w *gsWalker) value(t types.Type) []string {
+ if t == nil {
+ return nil
+ }
+ t = gsDeref(t)
+ if r := w.memo.At(t); r != nil {
+ return r.([]string)
+ }
+ w.memo.Set(t, []string(nil)) // a cycle adds nothing new
+ var leaks []string
+ if gsMarshaler(t) {
+ leaks = w.held(t)
+ } else {
+ switch u := t.Underlying().(type) {
+ case *types.Struct:
+ label := gsLabel(t)
+ for _, f := range w.fields(t) {
+ if g, ok := w.gates[f.v]; ok {
+ if f.name == g.name {
+ leaks = append(leaks, label+"."+g.owner+"."+f.name)
+ }
+ continue
+ }
+ for _, l := range w.value(f.v.Type()) {
+ leaks = append(leaks, label+"."+f.name+" -> "+l)
+ }
+ }
+ case *types.Slice:
+ leaks = w.value(u.Elem())
+ case *types.Array:
+ leaks = w.value(u.Elem())
+ case *types.Map:
+ leaks = w.value(u.Elem())
+ }
+ }
+ w.memo.Set(t, leaks)
+ return leaks
+}
+
+// held is every gate field t holds anywhere, exported or not, under any
+// name: what a custom marshaller could write.
+func (w *gsWalker) held(t types.Type) []string {
+ t = gsDeref(t)
+ if r := w.opaque.At(t); r != nil {
+ return r.([]string)
+ }
+ w.opaque.Set(t, []string(nil))
+ var leaks []string
+ switch u := t.Underlying().(type) {
+ case *types.Struct:
+ label := gsLabel(t)
+ for i := 0; i < u.NumFields(); i++ {
+ f := u.Field(i)
+ if g, ok := w.gates[f]; ok {
+ leaks = append(leaks, label+"."+g.owner+".Gate (custom marshaller)")
+ continue
+ }
+ for _, l := range w.held(f.Type()) {
+ leaks = append(leaks, label+"."+f.Name()+" -> "+l)
+ }
+ }
+ case *types.Slice:
+ leaks = w.held(u.Elem())
+ case *types.Array:
+ leaks = w.held(u.Elem())
+ case *types.Map:
+ leaks = append(w.held(u.Key()), w.held(u.Elem())...)
+ }
+ w.opaque.Set(t, leaks)
+ return leaks
+}
+
+type gsField struct {
+ name string
+ tagged bool
+ depth int
+ v *types.Var
+}
+
+func gsCount(m *typeutil.Map, t types.Type) int {
+ if m == nil {
+ return 0
+ }
+ if n := m.At(t); n != nil {
+ return n.(int)
+ }
+ return 0
+}
+
+// fields is encoding/json's typeFields over go/types: the fields a struct
+// type emits, after promotion and dominance, keyed by type identity. A gate
+// field that loses to a shallower or tagged one of its name counts as
+// shadowed.
+func (w *gsWalker) fields(t types.Type) []gsField {
+ type scan struct {
+ typ types.Type
+ depth int
+ }
+ var all []gsField
+ next := []scan{{typ: t}}
+ var count, nextCount *typeutil.Map
+ var visited typeutil.Map
+ for len(next) > 0 {
+ current := next
+ next = nil
+ count, nextCount = nextCount, new(typeutil.Map)
+ for _, s := range current {
+ if visited.At(s.typ) != nil {
+ continue
+ }
+ visited.Set(s.typ, true)
+ st := s.typ.Underlying().(*types.Struct)
+ for i := 0; i < st.NumFields(); i++ {
+ sf := st.Field(i)
+ ft := sf.Type()
+ if p, ok := ft.(*types.Pointer); ok {
+ ft = p.Elem()
+ }
+ _, isStruct := ft.Underlying().(*types.Struct)
+ if sf.Embedded() {
+ if !sf.Exported() && !isStruct {
+ continue
+ }
+ } else if !sf.Exported() {
+ continue
+ }
+ name, skip := gsJSONName(st.Tag(i))
+ if skip {
+ continue
+ }
+ if name != "" || !sf.Embedded() || !isStruct {
+ f := gsField{name: name, tagged: name != "", depth: s.depth, v: sf}
+ if f.name == "" {
+ f.name = sf.Name()
+ }
+ all = append(all, f)
+ if gsCount(count, s.typ) > 1 {
+ all = append(all, f) // embedded twice at this depth: annihilates
+ }
+ continue
+ }
+ n := gsCount(nextCount, ft) + 1
+ nextCount.Set(ft, n)
+ if n == 1 {
+ next = append(next, scan{typ: ft, depth: s.depth + 1})
+ }
+ }
+ }
+ }
+ sort.SliceStable(all, func(i, j int) bool {
+ if all[i].name != all[j].name {
+ return all[i].name < all[j].name
+ }
+ if all[i].depth != all[j].depth {
+ return all[i].depth < all[j].depth
+ }
+ return all[i].tagged && !all[j].tagged
+ })
+ var out []gsField
+ for i := 0; i < len(all); {
+ j := i + 1
+ for j < len(all) && all[j].name == all[i].name {
+ j++
+ }
+ group := all[i:j]
+ win := -1
+ if len(group) == 1 || group[0].depth != group[1].depth || group[0].tagged != group[1].tagged {
+ win = 0
+ out = append(out, group[0])
+ }
+ for k, f := range group {
+ if _, ok := w.gates[f.v]; ok && k != win {
+ w.shad++
+ }
+ }
+ i = j
+ }
+ return out
+}
+
+// gsJSONName is a field's json tag name ("" for none or an invalid one, as
+// encoding/json's isValidTag rules) and whether the tag drops the field.
+func gsJSONName(tag string) (string, bool) {
+ v := reflect.StructTag(tag).Get("json")
+ if v == "-" {
+ return "", true
+ }
+ name, _, _ := strings.Cut(v, ",")
+ if !gsValidTag(name) {
+ name = ""
+ }
+ return name, false
+}
+
+// gsValidTag is encoding/json's isValidTag.
+func gsValidTag(s string) bool {
+ if s == "" {
+ return false
+ }
+ for _, c := range s {
+ switch {
+ case strings.ContainsRune("!#$%&()*+-./:;<=>?@[]^_{|}~ ", c):
+ // Backslash and quote chars are reserved, but otherwise any
+ // punctuation chars are allowed in a tag name.
+ case !unicode.IsLetter(c) && !unicode.IsDigit(c):
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/console/gettingstarted_handlers.go b/internal/console/gettingstarted_handlers.go
index 5932cc4ed..579b4c27f 100644
--- a/internal/console/gettingstarted_handlers.go
+++ b/internal/console/gettingstarted_handlers.go
@@ -1,7 +1,6 @@
package console
import (
- "crypto/subtle"
"log"
"net/http"
"time"
@@ -27,7 +26,7 @@ func (s *Server) gettingStartedRequest(w http.ResponseWriter, r *http.Request) (
if !ok {
return "", nil, false
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return "", nil, false
}
diff --git a/internal/console/mobilenav_test.go b/internal/console/mobilenav_test.go
index fa066772a..cbf4f8bff 100644
--- a/internal/console/mobilenav_test.go
+++ b/internal/console/mobilenav_test.go
@@ -336,7 +336,7 @@ func TestHeaderHoldsBackAndProfile(t *testing.T) {
`<details class="profile" id="profile">`,
`<summary aria-label="`,
`<a class="addr" href="/settings">`,
- `name="csrf" value="` + csrf + `"`,
+ `name="csrf" value="` + csrfToken(csrf) + `"`,
`<script data-profile-menu>`,
} {
if !strings.Contains(head+rest, need) {
diff --git a/internal/console/opshell.go b/internal/console/opshell.go
index 7c10adf0d..12d5d454c 100644
--- a/internal/console/opshell.go
+++ b/internal/console/opshell.go
@@ -83,7 +83,7 @@ func (s *Server) opPage(addr, raw, rail string) page {
return page{
Title: opRailLabel(rail),
Address: addr,
- CSRF: raw,
+ CSRF: csrfToken(raw),
Op: &opShell{
Rail: rail,
View: "page",
diff --git a/internal/console/opshell_test.go b/internal/console/opshell_test.go
index 18a40bd38..67a97da0f 100644
--- a/internal/console/opshell_test.go
+++ b/internal/console/opshell_test.go
@@ -319,7 +319,7 @@ func TestOperatorShellAccountMenu(t *testing.T) {
fx := newConsoleFixture(t)
c := signInOperator(t, fx)
_, _, body := get(t, c, fx.ts.URL+"/fleet/index")
- csrf := sessionToken(t, fx, c)
+ csrf := csrfToken(sessionToken(t, fx, c))
for _, want := range []string{
`<a href="/">Customer console</a>`,
`<form method="post" action="/auth/signout">`,
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index 92a866402..6157b416d 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -12,7 +12,6 @@ package console
import (
"context"
- "crypto/subtle"
"database/sql"
"errors"
"fmt"
@@ -39,7 +38,7 @@ func (s *Server) handleRemoveMember(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -71,7 +70,7 @@ func (s *Server) handleTransferOwnership(w http.ResponseWriter, r *http.Request)
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -104,7 +103,7 @@ func (s *Server) handleDeleteAccount(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -279,7 +278,7 @@ func (s *Server) handleRestoreApp(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -389,7 +388,7 @@ func (s *Server) handlePurgeApp(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/pendinghandlers.go b/internal/console/pendinghandlers.go
index da3dae398..012518167 100644
--- a/internal/console/pendinghandlers.go
+++ b/internal/console/pendinghandlers.go
@@ -25,7 +25,6 @@ package console
import (
"context"
- "crypto/subtle"
"encoding/json"
"errors"
"fmt"
@@ -736,7 +735,7 @@ func (s *Server) handlePendingConfirm(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -825,7 +824,7 @@ func (s *Server) handlePendingReject(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/pipelinepage.go b/internal/console/pipelinepage.go
index 22de0c73d..f9f913bf2 100644
--- a/internal/console/pipelinepage.go
+++ b/internal/console/pipelinepage.go
@@ -18,7 +18,6 @@ package console
import (
"context"
- "crypto/subtle"
"fmt"
"log"
"net/http"
@@ -270,14 +269,17 @@ func (s *Server) handlePipelineSettingsSave(w http.ResponseWriter, r *http.Reque
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(p.CSRF)) != 1 {
+ // p.CSRF is the derived token; the step-up gate below wants the session
+ // itself, which appPage has already validated.
+ _, raw, _ := s.session(r)
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
if s.refuseAppNoBucket(w, r) {
return
}
- addr, raw, app := p.Address, p.CSRF, p.AppName
+ addr, app := p.Address, p.AppName
rows := parsePipelineRows(r)
switch action := r.FormValue("action"); {
diff --git a/internal/console/planlapse_keep.go b/internal/console/planlapse_keep.go
index c1fb4c873..64e280f70 100644
--- a/internal/console/planlapse_keep.go
+++ b/internal/console/planlapse_keep.go
@@ -1,7 +1,6 @@
package console
import (
- "crypto/subtle"
"fmt"
"log"
"net/http"
@@ -174,7 +173,7 @@ func (s *Server) handlePlanKeepSave(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/protectionsetting.go b/internal/console/protectionsetting.go
index 983ce319e..ee35d9927 100644
--- a/internal/console/protectionsetting.go
+++ b/internal/console/protectionsetting.go
@@ -9,7 +9,6 @@ package console
import (
"context"
- "crypto/subtle"
"errors"
"log"
"net/http"
@@ -56,7 +55,7 @@ func (s *Server) handleAppProtectionSetting(w http.ResponseWriter, r *http.Reque
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/regionpicker.go b/internal/console/regionpicker.go
index 71c51b8fb..363fd6245 100644
--- a/internal/console/regionpicker.go
+++ b/internal/console/regionpicker.go
@@ -2,7 +2,6 @@ package console
import (
"context"
- "crypto/subtle"
"fmt"
"github.com/carlosframework/platform/internal/geo"
"github.com/carlosframework/platform/internal/geoip"
@@ -106,7 +105,7 @@ func (s *Server) handleNewAppRegion(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
jsonError(w, http.StatusForbidden, "Cross-site request blocked.")
return
}
diff --git a/internal/console/server.go b/internal/console/server.go
index cb60800dd..48624b1e1 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -2379,7 +2379,7 @@ type page struct {
Title string
Address string // signed-in address, "" when signed out
- CSRF string // the session token, double-submitted on the signout POST
+ CSRF string // csrfToken(session) (csrf.go), double-submitted on every form POST
Error string
Welcome bool // one-shot "account created" banner
BrowserRestartCopy BrowserRestartCopy
@@ -2963,7 +2963,7 @@ func (s *Server) basePage(r *http.Request) page {
if !ok {
return page{}
}
- return page{Address: addr, CSRF: raw}
+ return page{Address: addr, CSRF: csrfToken(raw)}
}
// ---- session plumbing -------------------------------------------------------
@@ -3292,7 +3292,7 @@ func (s *Server) handleNewAccountForm(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
- p := page{Title: "New account", Address: addr, CSRF: raw, MobileParent: &navLink{Label: "Accounts", Href: "/accounts#nav-new"}}
+ p := page{Title: "New account", Address: addr, CSRF: csrfToken(raw), MobileParent: &navLink{Label: "Accounts", Href: "/accounts#nav-new"}}
p.Flash, p.FlashErr = s.takeFlash(w, r)
if accts, err := s.store.AccountsFor(addr); err != nil {
log.Printf("console: switcher: %v", err)
@@ -3327,7 +3327,7 @@ func (s *Server) handleNewAccount(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -3373,7 +3373,7 @@ func (s *Server) handleInvite(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -3546,7 +3546,7 @@ func (s *Server) handleRevokeInvite(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -3627,7 +3627,7 @@ func (s *Server) handleInvitePage(w http.ResponseWriter, r *http.Request) {
Title: "Join " + a.Name + "?",
Lines: []string{inv.InvitedBy + " invited you to join " + a.Name + " as a member."},
Action: "/invite/" + url.PathEscape(token),
- Fields: [][2]string{{"csrf", raw}},
+ Fields: [][2]string{{"csrf", csrfToken(raw)}},
Button: "Join " + a.Name,
CancelURL: "/",
}
@@ -3645,7 +3645,7 @@ func (s *Server) handleAcceptInvite(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -3937,8 +3937,8 @@ func (s *Server) handleSignout(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
- // CSRF: the session token double-submitted as a hidden form field.
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ // CSRF: csrfToken(session) double-submitted as a hidden form field.
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -4236,7 +4236,7 @@ func (s *Server) accountPage(w http.ResponseWriter, r *http.Request, addr, raw s
}
end()
p := page{
- Address: addr, CSRF: raw,
+ Address: addr, CSRF: csrfToken(raw),
Account: acct, Role: role, Base: "/a/" + url.PathEscape(acct.Sqid),
CanPromote: s.cfg.Key != nil,
BillingNav: s.billing != nil,
@@ -5701,7 +5701,7 @@ func (s *Server) handleNewApp(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -5853,7 +5853,7 @@ func (s *Server) handlePromote(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -6130,7 +6130,7 @@ func (s *Server) handleRollback(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -6313,7 +6313,7 @@ func (s *Server) handleProduction(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -6385,7 +6385,7 @@ func (s *Server) handleFastTrack(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -6630,7 +6630,7 @@ func (s *Server) handleNewCanary(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
@@ -6808,7 +6808,7 @@ func (s *Server) handleRetireCanary(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
diff --git a/internal/console/stepup.go b/internal/console/stepup.go
index 9f589326f..a80f1b016 100644
--- a/internal/console/stepup.go
+++ b/internal/console/stepup.go
@@ -332,9 +332,10 @@ func (s *Server) stashRequest(w http.ResponseWriter, r *http.Request, addr, raw
s.renderMessage(w, r, http.StatusBadRequest, "Refused", "That request could not be read.")
return "", false
}
- // The csrf field is deliberately NOT stored. It is the raw session token,
- // and sessions are kept hashed here precisely so a database read is not a
- // session; parking a live one in a form blob would quietly undo that. The
+ // The csrf field is deliberately NOT stored. It is derived from the session
+ // (csrf.go) and, from a page rendered before csrf-v1, may be the raw session
+ // token itself; sessions are kept hashed here precisely so a database read
+ // is not a session, and parking one in a form blob would undo that. The
// resume re-injects it from the cookie the resuming request carries โ€” which
// costs nothing in safety, because the cross-site question was already
// answered before this stash was ever created.
@@ -481,7 +482,7 @@ func (s *Server) resume(w http.ResponseWriter, r *http.Request, p *pendingAction
// the resumed request must satisfy the same CSRF check as any other, and
// the token it satisfies it with is this browser's own, read from its
// cookie, not something recovered from storage.
- form.Set("csrf", raw)
+ form.Set("csrf", csrfToken(raw))
req, err := http.NewRequestWithContext(context.WithValue(r.Context(), stepUpReplayKey{}, true), p.Method, p.Path, strings.NewReader(form.Encode()))
if err != nil {
log.Printf("console: resume %s %s: %v", p.Method, p.Path, err)
diff --git a/internal/console/storepage.go b/internal/console/storepage.go
index 83f453646..8c903ebe7 100644
--- a/internal/console/storepage.go
+++ b/internal/console/storepage.go
@@ -2,7 +2,6 @@ package console
import (
"context"
- "crypto/subtle"
"encoding/json"
"fmt"
"log"
@@ -89,7 +88,7 @@ func (s *Server) storeFormCSRF(w http.ResponseWriter, r *http.Request, raw strin
s.renderMessage(w, r, http.StatusBadRequest, "Refused", "Could not read the form. Please try again.")
return false
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return false
}
diff --git a/internal/console/svcpage.go b/internal/console/svcpage.go
index 8d09a7ca1..cd8e8ebf7 100644
--- a/internal/console/svcpage.go
+++ b/internal/console/svcpage.go
@@ -78,7 +78,6 @@
package console
import (
- "crypto/subtle"
"errors"
"fmt"
"log"
@@ -249,7 +248,7 @@ func (s *Server) serviceOwner(w http.ResponseWriter, r *http.Request) (addr, raw
if !ok {
return "", "", nil, false
}
- if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ if !csrfFormOK(r, raw) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return "", "", nil, false
}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 8169239ed..6eeba4de1 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -3864,7 +3864,14 @@ func (e *Edge) httpFallbackHandler() http.Handler {
http.Error(w, "Use HTTPS", http.StatusBadRequest)
return
}
- http.Redirect(w, r, "https://"+host+r.URL.RequestURI(), http.StatusFound)
+ // Only a rooted path may follow the host: a rootless target
+ // ("x:@evil.example/p", "*") would otherwise splice itself onto the
+ // authority. Twin of console.redirectTarget (console imports edge).
+ uri := r.URL.RequestURI()
+ if !strings.HasPrefix(uri, "/") {
+ uri = "/"
+ }
+ http.Redirect(w, r, "https://"+host+uri, http.StatusFound)
})
}
@@ -4002,18 +4009,19 @@ func unixProxy(socketPath string) *httputil.ReverseProxy {
// A loopback upstream is this box's own process, so a refused dial there is
// a restart in progress: the dial is retried for hold.dial (one deadline
// fixed per dial) instead of 502ing at once. hold.dial <= 0, or a remote
-// addr, keeps the stock dialer (hold.dialer is nil in production).
+// addr, dials once. Either way the dial is upstreamDialer's (hold.dialer is
+// nil in production), which refuses link-local and IMDS addresses.
func tcpProxy(addr string, hold localHold) *httputil.ReverseProxy {
+ dial := hold.dialer
+ if dial == nil {
+ dial = upstreamDialer().DialContext
+ }
tr := &http.Transport{
MaxIdleConns: 32,
IdleConnTimeout: 90 * time.Second,
- DialContext: hold.dialer,
+ DialContext: dial,
}
if hold.dial > 0 && isLocalUpstream(addr) {
- dial := hold.dialer
- if dial == nil {
- dial = (&net.Dialer{}).DialContext
- }
tr.DialContext = func(ctx context.Context, network, a string) (net.Conn, error) {
return retryLocalDial(ctx, time.Now().Add(hold.dial), func(actx context.Context) (net.Conn, error) {
return dial(actx, network, a)
@@ -4108,7 +4116,7 @@ func multiProxy(host string, p *proberSet, hold localHold) *httputil.ReverseProx
var cursor atomic.Uint64
dial := hold.dialer
if dial == nil {
- dial = (&net.Dialer{}).DialContext
+ dial = upstreamDialer().DialContext // refuses link-local and IMDS
}
return &httputil.ReverseProxy{
Rewrite: func(pr *httputil.ProxyRequest) {
diff --git a/internal/edge/http_fallback_redirect_test.go b/internal/edge/http_fallback_redirect_test.go
new file mode 100644
index 000000000..bce6fcf27
--- /dev/null
+++ b/internal/edge/http_fallback_redirect_test.go
@@ -0,0 +1,85 @@
+package edge
+
+import (
+ "bufio"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// TestHTTPFallbackRedirectRootlessTarget pins the :80 redirect to its own
+// authority. The redirect is "https://" + host + the request-target, and a
+// request-target that does not start with "/" (a rootless "x:@evil.example/p"
+// keeps "@evil.example/p" as its opaque part; "*" stays "*") would splice
+// itself onto the host and turn the Location into userinfo@another-host. The
+// rule is console.redirectTarget's: anything not rooted becomes "/".
+//
+// The requests are parsed off the wire with http.ReadRequest, as the :80
+// server parses them, because httptest.NewRequest cannot express a rootless
+// target.
+func TestHTTPFallbackRedirectRootlessTarget(t *testing.T) {
+ const host = "shop.example.com"
+ backend, _ := hostEchoBackend(t, "primary")
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{
+ Host: host, Kind: "service",
+ Addr: backend.Listener.Addr().String(), Status: "ready",
+ }); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ h := e.httpFallbackHandler()
+
+ serve := func(t *testing.T, requestLine string) *httptest.ResponseRecorder {
+ t.Helper()
+ req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(
+ requestLine + "\r\nHost: " + host + "\r\n\r\n")))
+ if err != nil {
+ t.Fatalf("ReadRequest(%q): %v", requestLine, err)
+ }
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ return rec
+ }
+
+ for _, tc := range []struct {
+ name, requestLine, want string
+ }{
+ {"rootless", "GET x:@evil.example/p HTTP/1.1", "https://" + host + "/"},
+ {"asterisk", "GET * HTTP/1.1", "https://" + host + "/"},
+ // The absolute form's authority replaces the Host header (RFC 9112
+ // ยง3.2.2, and net/http does the same), so naming this box's own host
+ // there is an ordinary redirect.
+ {"absolute form, own host", "GET http://" + host + "/p?q=1 HTTP/1.1", "https://" + host + "/p?q=1"},
+ {"origin form", "GET /a/b?c=1 HTTP/1.1", "https://" + host + "/a/b?c=1"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ rec := serve(t, tc.requestLine)
+ if rec.Code != http.StatusFound {
+ t.Fatalf("status = %d, want 302", rec.Code)
+ }
+ if loc := rec.Header().Get("Location"); loc != tc.want {
+ t.Fatalf("Location = %q, want %q", loc, tc.want)
+ }
+ })
+ }
+
+ // An absolute-form target naming a host this box does not serve is that
+ // host's request, not shop's: it gets unknownHost (404, no fallback URL
+ // configured), never a Location pointing at the foreign authority.
+ t.Run("absolute form, foreign host", func(t *testing.T) {
+ rec := serve(t, "GET http://evil.example/p HTTP/1.1")
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404 (unknownHost)", rec.Code)
+ }
+ if loc := rec.Header().Get("Location"); loc != "" {
+ t.Fatalf("Location = %q, want none", loc)
+ }
+ })
+}
diff --git a/internal/edge/prober.go b/internal/edge/prober.go
index 3463a34fa..4dc10dd7e 100644
--- a/internal/edge/prober.go
+++ b/internal/edge/prober.go
@@ -128,13 +128,19 @@ type proberSet struct {
// newProberSet builds the set with hold.probe as the probe timeout (T in
// the readmission formula, spec ยง3), and hold.dialer, when set, as the
-// probes' dialer, so a test's instrumented dialer sees the probes too. A
-// non-positive probe falls back to probeTimeout: an unbounded probe would
-// stall every tick behind one black-holed upstream.
+// probes' dialer, so a test's instrumented dialer sees the probes too;
+// unset (production), the probes dial with upstreamDialer, which refuses
+// link-local and IMDS addresses. A non-positive probe falls back to
+// probeTimeout: an unbounded probe would stall every tick behind one
+// black-holed upstream.
func newProberSet(hold localHold) *proberSet {
if hold.probe <= 0 {
hold.probe = probeTimeout
}
+ dial := hold.dialer
+ if dial == nil {
+ dial = upstreamDialer().DialContext
+ }
return &proberSet{
hosts: make(map[string]*hostProber),
hold: hold,
@@ -153,7 +159,7 @@ func newProberSet(hold localHold) *proberSet {
MaxIdleConnsPerHost: 1,
IdleConnTimeout: 90 * time.Second,
ResponseHeaderTimeout: hold.probe,
- DialContext: hold.dialer, // nil: the default dialer
+ DialContext: dial,
},
},
}
diff --git a/internal/edge/upstreamdial.go b/internal/edge/upstreamdial.go
new file mode 100644
index 000000000..28857146e
--- /dev/null
+++ b/internal/edge/upstreamdial.go
@@ -0,0 +1,16 @@
+package edge
+
+import (
+ "net"
+
+ "github.com/carlosframework/platform/internal/upstreamguard"
+)
+
+// upstreamDialer is the dialer for a TCP upstream when no test dialer is set
+// (hold.dialer nil, as in production): the plain net.Dialer the transports
+// used before, behind upstreamguard, which refuses link-local and IMDS
+// addresses after resolution and before connect. tcpProxy, multiProxy and
+// the prober use it; unix sockets, backhaul hops and tunnels do not.
+func upstreamDialer() *net.Dialer {
+ return upstreamguard.Dialer(net.Dialer{})
+}
diff --git a/internal/edge/upstreamdial_test.go b/internal/edge/upstreamdial_test.go
new file mode 100644
index 000000000..4c2d367b2
--- /dev/null
+++ b/internal/edge/upstreamdial_test.go
@@ -0,0 +1,143 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/upstreamguard"
+ "github.com/carlosframework/platform/internal/upstreamguard/guardtest"
+)
+
+// proxyErr serves one request through p and returns the status and the
+// error p's ErrorHandler was handed (nil if it was not called), keeping the
+// production ErrorHandler's answer.
+func proxyErr(t *testing.T, p *httputil.ReverseProxy) (int, error) {
+ t.Helper()
+ var got error
+ orig := p.ErrorHandler
+ p.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
+ got = err
+ orig(w, r, err)
+ }
+ rec := httptest.NewRecorder()
+ p.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://shop.example.com/", nil))
+ return rec.Code, got
+}
+
+// TestTCPProxyRefusesNameResolvingToIMDS: an upstream NAME is checked after
+// resolution, at the address the dialer is about to connect to. imds.test
+// resolves (through a fake DNS zone, guardtest.Resolver) to 169.254.169.254; the
+// Control hook runs before connect, so nothing is connected and the request
+// answers 502 with the refusal as its cause.
+func TestTCPProxyRefusesNameResolvingToIMDS(t *testing.T) {
+ d := upstreamDialer()
+ d.Resolver = guardtest.Resolver(t, "imds.test", "169.254.169.254")
+ p := tcpProxy("imds.test:80", localHold{dialer: d.DialContext})
+ code, err := proxyErr(t, p)
+ if code != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502", code)
+ }
+ if !errors.Is(err, upstreamguard.ErrLinkLocal) {
+ t.Fatalf("proxy error = %v, want one wrapping upstreamguard.ErrLinkLocal", err)
+ }
+}
+
+// TestUpstreamDialSitesRefuseLinkLocal checks the production wiring: with
+// hold.dialer nil, as New leaves it, each of the three upstream dial sites
+// (tcpProxy, multiProxy, the prober's transport) dials through the guarded
+// dialer rather than the stdlib's default. Each nil check comes before any
+// dial, so a missing guard fails the test without connecting anywhere.
+func TestUpstreamDialSitesRefuseLinkLocal(t *testing.T) {
+ hold := defaultLocalHold()
+ if hold.dialer != nil {
+ t.Fatal("defaultLocalHold has a dialer; this test is about the nil (production) path")
+ }
+
+ t.Run("tcpProxy", func(t *testing.T) {
+ p := tcpProxy("169.254.169.254:80", hold)
+ tr, ok := p.Transport.(*http.Transport)
+ if !ok || tr.DialContext == nil {
+ t.Fatal("tcpProxy transport has no DialContext: it would dial with the stdlib's unguarded default")
+ }
+ code, err := proxyErr(t, p)
+ if code != http.StatusBadGateway || !errors.Is(err, upstreamguard.ErrLinkLocal) {
+ t.Fatalf("status = %d, err = %v; want 502 wrapping upstreamguard.ErrLinkLocal", code, err)
+ }
+ })
+
+ t.Run("prober", func(t *testing.T) {
+ ps := newProberSet(hold)
+ tr, ok := ps.client.Transport.(*http.Transport)
+ if !ok || tr.DialContext == nil {
+ t.Fatal("prober transport has no DialContext: it would dial with the stdlib's unguarded default")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ conn, err := tr.DialContext(ctx, "tcp", "169.254.169.254:80")
+ if conn != nil {
+ conn.Close()
+ }
+ if !errors.Is(err, upstreamguard.ErrLinkLocal) {
+ t.Fatalf("probe dial err = %v, want upstreamguard.ErrLinkLocal", err)
+ }
+ })
+
+ // multiProxy's fallback dialer is a closure variable the test cannot
+ // inspect, so its upstream is fe80::1 with no zone: unguarded, the kernel
+ // refuses that connect locally (no interface to send on); guarded, the
+ // Control hook refuses it first. Either way nothing leaves the box.
+ t.Run("multiProxy", func(t *testing.T) {
+ const host = "ha.example.com"
+ ps := newProberSet(hold)
+ defer ps.Stop()
+ ps.Sync(map[string]probeSpec{host: {Host: host, Addrs: []string{"[fe80::1]:80"}, Health: frozenHealth()}})
+ tr, ok := multiProxy(host, ps, hold).Transport.(*http.Transport)
+ if !ok {
+ t.Fatal("multiProxy transport is not an *http.Transport")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ conn, err := tr.DialContext(ctx, "tcp", multiDialHost)
+ if conn != nil {
+ conn.Close()
+ }
+ if !errors.Is(err, errNoLiveUpstream) || !strings.Contains(err.Error(), upstreamguard.ErrLinkLocal.Error()) {
+ t.Fatalf("multi dial err = %v, want errNoLiveUpstream naming upstreamguard.ErrLinkLocal", err)
+ }
+ })
+
+ // The guard must not cost a real upstream anything: loopback, through
+ // tcpProxy's local-hold path and through the prober.
+ t.Run("loopback allowed", func(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer backend.Close()
+ addr := backend.Listener.Addr().String()
+
+ p := tcpProxy(addr, hold)
+ code, err := proxyErr(t, p)
+ if code != http.StatusOK || err != nil {
+ t.Fatalf("tcpProxy to %s: status = %d, err = %v; want 200", addr, code, err)
+ }
+
+ ps := newProberSet(hold)
+ tr := ps.client.Transport.(*http.Transport)
+ if tr.DialContext == nil {
+ t.Fatal("prober transport has no DialContext")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ conn, err := tr.DialContext(ctx, "tcp", addr)
+ if err != nil {
+ t.Fatalf("probe dial %s: %v", addr, err)
+ }
+ conn.Close()
+ })
+}
diff --git a/internal/host/unitsettle.go b/internal/host/unitsettle.go
index 54767a4b1..6dfe95d79 100644
--- a/internal/host/unitsettle.go
+++ b/internal/host/unitsettle.go
@@ -29,6 +29,7 @@ import (
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/upstreamguard"
)
type unitProps struct {
@@ -294,7 +295,8 @@ func unitSettleTimeout(getenv func(string) string) time.Duration {
// routeReady is the readiness check for rt's effective upstream (spec ยง2.4):
// Socket wins over Addr. With a configured probe it is an HTTP GET; without
// one, a connect. nil when the route has no upstream: settle then requires
-// the unit to stay active for its Hold.
+// the unit to stay active for its Hold. Both dial through upstreamguard
+// (readyConnect, readyProbe).
func routeReady(rt registry.Route, timeout time.Duration) func() error {
network, address := "unix", rt.Socket
if address == "" {
@@ -304,13 +306,7 @@ func routeReady(rt registry.Route, timeout time.Duration) func() error {
return nil
}
if rt.Health == "" {
- return func() error {
- c, err := net.DialTimeout(network, address, timeout)
- if err != nil {
- return fmt.Errorf("connect %s: %w", address, err)
- }
- return c.Close()
- }
+ return readyConnect(net.Dialer{}, network, address, timeout)
}
var h provision.Health
if err := json.Unmarshal([]byte(rt.Health), &h); err != nil {
@@ -321,10 +317,31 @@ func routeReady(rt registry.Route, timeout time.Duration) func() error {
if hostHdr == "" {
hostHdr = rt.Host
}
+ return readyProbe(net.Dialer{}, network, address, h, hostHdr, timeout)
+}
+
+// readyConnect is routeReady's connect check, dialing with base (a test sets
+// its Resolver) behind upstreamguard: a TCP upstream is route-supplied, so a
+// link-local or IMDS destination is refused after resolution and before
+// connect. A unix socket path passes the guard.
+func readyConnect(base net.Dialer, network, address string, timeout time.Duration) func() error {
+ base.Timeout = timeout
+ dialer := upstreamguard.Dialer(base)
+ return func() error {
+ c, err := dialer.Dial(network, address)
+ if err != nil {
+ return fmt.Errorf("connect %s: %w", address, err)
+ }
+ return c.Close()
+ }
+}
+
+// readyProbe is routeReady's HTTP probe, dialing as readyConnect does.
+func readyProbe(base net.Dialer, network, address string, h provision.Health, hostHdr string, timeout time.Duration) func() error {
+ dialer := upstreamguard.Dialer(base)
client := &http.Client{Timeout: timeout, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, Transport: &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
- var d net.Dialer
- return d.DialContext(ctx, network, address)
+ return dialer.DialContext(ctx, network, address)
},
}}
return func() error {
@@ -335,7 +352,7 @@ func routeReady(rt registry.Route, timeout time.Duration) func() error {
req.Host = hostHdr
resp, err := client.Do(req)
if err != nil {
- return fmt.Errorf("dial: %v", err)
+ return fmt.Errorf("dial: %w", err)
}
io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10))
resp.Body.Close()
diff --git a/internal/host/unitsettle_guard_test.go b/internal/host/unitsettle_guard_test.go
new file mode 100644
index 000000000..dcce93f51
--- /dev/null
+++ b/internal/host/unitsettle_guard_test.go
@@ -0,0 +1,62 @@
+package host
+
+import (
+ "errors"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/upstreamguard"
+ "github.com/carlosframework/platform/internal/upstreamguard/guardtest"
+)
+
+// TestRouteReadyRefusesLinkLocal: the host's readiness checks dial a
+// route's TCP upstream (a bare connect without a health probe, an HTTP GET
+// with one), so both go through upstreamguard. A name resolving to
+// 169.254.169.254 is refused after resolution, and proofRouteReady, which
+// checks each of a route's Addrs, refuses an IMDS literal among them.
+func TestRouteReadyRefusesLinkLocal(t *testing.T) {
+ base := net.Dialer{Resolver: guardtest.Resolver(t, "imds.test", "169.254.169.254")}
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { ln.Close() })
+ probe := `{"path":"/healthz","status":200}`
+ for _, tc := range []struct {
+ name string
+ ready func() error
+ }{
+ {"connect, name resolving to IMDS", readyConnect(base, "tcp", "imds.test:80", time.Second)},
+ {"probe, name resolving to IMDS", readyProbe(base, "tcp", "imds.test:80", provision.Health{Path: "/healthz", Status: 200}, "x", time.Second)},
+ {"connect, IMDS literal, production dialer", routeReady(registry.Route{Host: "x", Addr: "169.254.169.254:80"}, time.Second)},
+ {"probe, IMDS literal, production dialer", routeReady(registry.Route{Host: "x", Addr: "169.254.169.254:80", Health: probe}, time.Second)},
+ {"proof, IMDS among Addrs", proofRouteReady(registry.Route{Host: "x", Addrs: ln.Addr().String() + ",169.254.169.254:80"}, time.Second)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if err := tc.ready(); !errors.Is(err, upstreamguard.ErrLinkLocal) {
+ t.Fatalf("ready = %v, want ErrLinkLocal", err)
+ }
+ })
+ }
+}
+
+func TestRouteReadyLoopbackStillWorks(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }))
+ t.Cleanup(srv.Close)
+ addr := strings.TrimPrefix(srv.URL, "http://")
+ for _, rt := range []registry.Route{
+ {Host: "x", Addr: addr},
+ {Host: "x", Addr: addr, Health: `{"path":"/healthz","status":200}`},
+ {Host: "x", Addrs: addr + "," + addr},
+ } {
+ if err := proofRouteReady(rt, time.Second)(); err != nil {
+ t.Fatalf("ready(%+v) = %v, want nil", rt, err)
+ }
+ }
+}
diff --git a/internal/provision/ffr_census_test.go b/internal/provision/ffr_census_test.go
index 3fed324f2..b133f42a1 100644
--- a/internal/provision/ffr_census_test.go
+++ b/internal/provision/ffr_census_test.go
@@ -14,11 +14,22 @@ package provision
// condition, unchanged. They write exactly what their caller writes and
// nothing else, so they are record-transport, like prefixStore.Put and
// snapStore.PutFrom.
+//
+// sec-console-csrf-derive re-pins five existing console units whose only
+// change is the CSRF check (subtle.ConstantTimeCompare on r.FormValue("csrf")
+// becomes csrfFormOK) and, in handleBrowserRestart and handleInstanceRetry,
+// the confirm card's csrf field (raw becomes csrfToken(raw)). Which records
+// they write, and how, is unchanged; class and kinds are as before.
func ffrWriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), omrRunWriteCensusInventory()...)
for _, r := range []censusEntry{
{"internal/host/startuptiming.go", "opCountingStore.Put", "record-transport", "def:Put,sel:Put", "3c40a2e5877b6d0bc189d8d5bf1229d7eafd08dd70655773f1ea9ff75c62ebc5"},
{"internal/host/startuptiming.go", "dirCountingStore.PutFrom", "record-transport", "def:PutFrom,sel:PutFrom", "90b82a86936f37c9dd53d3afd6c5d9ebbaab9df6e8d2b883a69dcf52a125b2fc"},
+ {"internal/console/appsettings.go", "Server.handleAppGate", "record-writer", "key:UpdateRecord", "1e53ebef92fd70db108d2714e09e9e9f9742fc96c63aa86c663bf41684f7cb69"},
+ {"internal/console/appsettings.go", "Server.handleAppRateLimit", "record-writer", "key:UpdateRecord", "9e34ff9f2347c591ce0b4668b385b2edd4c2d8dd2a3a535a870becdc33842516"},
+ {"internal/console/browserrestart.go", "Server.handleBrowserRestart", "key-site", "lit:instances", "d1f4000a3212a5124bafb0c1275228b1648bf6cf4cefe8ba27fcace6ad03534e"},
+ {"internal/console/browserretry.go", "Server.handleInstanceRetry", "key-site", "lit:instances", "871e5a4672eedc5bd8b80b42ed34e424b3031adde25f1b779125e8b5eca28658"},
+ {"internal/console/browserupdates.go", "Server.updatesFormGate", "key-site", "lit:instances", "6d15e442848429a6fb8ab398673af68b9fb67b8a9e6edd6765562c62e57154d6"},
} {
replaced := false
for i, e := range entries {
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 39b7059ca..c6b70708e 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -232,4 +232,5 @@ plan14-root-reads-omr-run.tsv f82b5e513d7434e1440c13aa4aa8bc06348745749a21593cf4
plan14-root-reads-fleet-first-reconcile-speed.tsv 9206205b2a3bf27b8b85310f4a44f94ef0c5886d85d6e55dbf2f22e073a8af11
plan14-root-reads-free-storage-250.tsv 9206205b2a3bf27b8b85310f4a44f94ef0c5886d85d6e55dbf2f22e073a8af11
plan14-root-reads-fleet-first-reconcile-speed-4.tsv 4eda67fee53800e2cfa4177b954c7f0fce6bdfcfbfe1aa2547ddcec3027b668b
+plan14-root-reads-sec-edge-redirect-linklocal.tsv 4eda67fee53800e2cfa4177b954c7f0fce6bdfcfbfe1aa2547ddcec3027b668b
plan14-root-reads-sec-unit-app-demobuild.tsv fea6bec1f00dace47aa6006bf8606602efda4cecfa4fe3c3890136c0fb27720c
diff --git a/internal/provision/testdata/plan14-root-reads-sec-edge-redirect-linklocal.tsv b/internal/provision/testdata/plan14-root-reads-sec-edge-redirect-linklocal.tsv
new file mode 100644
index 000000000..b45c288e4
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-sec-edge-redirect-linklocal.tsv
@@ -0,0 +1,7 @@
+# Census overlay sec-edge-redirect-linklocal, written by census-propose (#369). census-ruling-sec-edge-redirect-linklocal, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-sec-edge-redirect-linklocal.md.
+# 1 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+internal/host/unitsettle.go routeReady authority B3,J1,J4 root-route;rev3=census-ruling-sec-edge-redirect-linklocal;basis=same reads (Socket, Addr, Health, Host); the connect and the HTTP probe move into readyConnect/readyProbe, which dial through upstreamguard and so refuse a link-local or IMDS upstream after resolution, before connect; unix sockets, timeout and probe unchanged; no read added registry:Addr@160,registry:Health@211,registry:Health@352,registry:Host@554,registry:Socket@102 28727e6d1982928fec940b8b4be5ff0f70a88cd74818f027b7f0510d9209ddf8
+@coverage internal/activator b638116af5b710dd44ac56956f6cf627d881f87f22ed48de22c057d4efc94ada
+@coverage internal/edge 489fb5122e86036adb06ffb77fb8aaa79767d3dbb64458dd718fa5b667945edf
+@coverage internal/host 80e3a350373509c6d7d074c2b06512206200a3369a86298d4cdae3ca42eafa1c
+@coverage internal/upstreamguard 2da6f647eb21296c5af4af7496adf65340a6cc9f82ab4501ff8f4e92063fc6b9
diff --git a/internal/upstreamguard/guardtest/resolver.go b/internal/upstreamguard/guardtest/resolver.go
new file mode 100644
index 000000000..81a24d2fc
--- /dev/null
+++ b/internal/upstreamguard/guardtest/resolver.go
@@ -0,0 +1,69 @@
+// Package guardtest is a test helper for upstreamguard's callers: a
+// net.Resolver backed by a one-name fake DNS server on loopback, so a test
+// can make a hostname resolve to 169.254.169.254 without touching real DNS
+// or connecting there. Only tests import it.
+package guardtest
+
+import (
+ "context"
+ "net"
+ "net/netip"
+ "strings"
+ "testing"
+
+ "golang.org/x/net/dns/dnsmessage"
+)
+
+// Resolver answers A queries for name with ip (an IPv4 literal), AAAA
+// queries for name with nothing, and anything else with NXDOMAIN. Pass it
+// as a net.Dialer's Resolver.
+func Resolver(t testing.TB, name, ip string) *net.Resolver {
+ t.Helper()
+ addr := netip.MustParseAddr(ip).As4()
+ fq := strings.ToLower(strings.TrimSuffix(name, ".")) + "."
+ pc, err := net.ListenPacket("udp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { pc.Close() })
+ go func() {
+ buf := make([]byte, 1500)
+ for {
+ n, from, err := pc.ReadFrom(buf)
+ if err != nil {
+ return
+ }
+ var p dnsmessage.Parser
+ h, err := p.Start(buf[:n])
+ if err != nil {
+ continue
+ }
+ q, err := p.Question()
+ if err != nil {
+ continue
+ }
+ hdr := dnsmessage.Header{ID: h.ID, Response: true, Authoritative: true}
+ known := strings.ToLower(q.Name.String()) == fq
+ if !known {
+ hdr.RCode = dnsmessage.RCodeNameError
+ }
+ b := dnsmessage.NewBuilder(nil, hdr)
+ _ = b.StartQuestions()
+ _ = b.Question(q)
+ if known && q.Type == dnsmessage.TypeA {
+ _ = b.StartAnswers()
+ _ = b.AResource(dnsmessage.ResourceHeader{Name: q.Name, Class: dnsmessage.ClassINET, TTL: 60},
+ dnsmessage.AResource{A: addr})
+ }
+ msg, err := b.Finish()
+ if err != nil {
+ continue
+ }
+ _, _ = pc.WriteTo(msg, from)
+ }
+ }()
+ return &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ var d net.Dialer
+ return d.DialContext(ctx, "udp", pc.LocalAddr().String())
+ }}
+}
diff --git a/internal/upstreamguard/upstreamguard.go b/internal/upstreamguard/upstreamguard.go
new file mode 100644
index 000000000..4b5eb932d
--- /dev/null
+++ b/internal/upstreamguard/upstreamguard.go
@@ -0,0 +1,76 @@
+// Package upstreamguard refuses connections to link-local addresses and the
+// AWS instance metadata service. Every dial to a route's TCP upstream (the
+// edge's proxies and prober, the activator's wake health check, the host's
+// readiness checks) goes through Dialer, so an upstream of 169.254.169.254,
+// or a name resolving to it, is never connected. It imports only the
+// standard library.
+package upstreamguard
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "net/netip"
+ "syscall"
+)
+
+// ErrLinkLocal is the dial error for a refused destination.
+var ErrLinkLocal = errors.New("upstreamguard: refusing a link-local upstream address")
+
+// refused are the destinations no upstream may have: 169.254.0.0/16 and
+// fe80::/10 (link-local, IMDS's IPv4 address among them) and fd00:ec2::254,
+// IMDS's IPv6 address, which is not link-local.
+var refused = []netip.Prefix{
+ netip.MustParsePrefix("169.254.0.0/16"),
+ netip.MustParsePrefix("fe80::/10"),
+ netip.MustParsePrefix("fd00:ec2::254/128"),
+}
+
+// Control is a net.Dialer Control hook. The dialer calls it with the
+// address it has already resolved, after creating the socket and before
+// connecting it, so a refusal means nothing was connected, and a name is
+// judged by what it resolved to rather than how it is spelled. IPv4-mapped
+// IPv6 is unmapped first. An address that is not ip:port (a unix socket
+// path) is let through.
+func Control(network, address string, _ syscall.RawConn) error {
+ ap, err := netip.ParseAddrPort(address)
+ if err != nil {
+ return nil
+ }
+ ip := ap.Addr().WithZone("").Unmap()
+ for _, p := range refused {
+ if p.Contains(ip) {
+ return fmt.Errorf("%w: %s %s", ErrLinkLocal, network, address)
+ }
+ }
+ return nil
+}
+
+// Dialer returns a copy of base with Control in front of base's own hook:
+// Timeout, KeepAlive, Resolver and the rest are kept. A base ControlContext
+// (which net.Dialer prefers over Control) is chained the same way.
+func Dialer(base net.Dialer) *net.Dialer {
+ d := base
+ switch {
+ case base.ControlContext != nil:
+ next := base.ControlContext
+ d.ControlContext = func(ctx context.Context, network, address string, c syscall.RawConn) error {
+ if err := Control(network, address, c); err != nil {
+ return err
+ }
+ return next(ctx, network, address, c)
+ }
+ case base.Control != nil:
+ next := base.Control
+ d.Control = func(network, address string, c syscall.RawConn) error {
+ if err := Control(network, address, c); err != nil {
+ return err
+ }
+ return next(network, address, c)
+ }
+ default:
+ d.Control = Control
+ }
+ return &d
+}
diff --git a/internal/upstreamguard/upstreamguard_test.go b/internal/upstreamguard/upstreamguard_test.go
new file mode 100644
index 000000000..d2d8f76e0
--- /dev/null
+++ b/internal/upstreamguard/upstreamguard_test.go
@@ -0,0 +1,89 @@
+package upstreamguard_test
+
+import (
+ "context"
+ "errors"
+ "net"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/upstreamguard"
+ "github.com/carlosframework/platform/internal/upstreamguard/guardtest"
+)
+
+// TestControl is the hook's table: link-local (IPv4 and IPv6, mapped or
+// zoned) and the AWS IMDS IPv6 address are refused; loopback and private
+// addresses, which real upstreams use, and unix paths are not.
+func TestControl(t *testing.T) {
+ for _, tc := range []struct {
+ network, address string
+ refused bool
+ }{
+ {"tcp4", "169.254.169.254:80", true},
+ {"tcp6", "[::ffff:169.254.169.254]:80", true},
+ {"tcp4", "169.254.0.1:8080", true},
+ {"tcp6", "[fe80::1]:80", true},
+ {"tcp6", "[fe80::1%eth0]:80", true},
+ {"tcp6", "[fd00:ec2::254]:80", true},
+ {"tcp4", "127.0.0.1:80", false},
+ {"tcp4", "10.0.0.5:80", false},
+ {"tcp6", "[::1]:80", false},
+ {"tcp6", "[fd00:ec2::253]:80", false},
+ {"unix", "/run/carlos/app.sock", false},
+ } {
+ err := upstreamguard.Control(tc.network, tc.address, nil)
+ if got := errors.Is(err, upstreamguard.ErrLinkLocal); got != tc.refused {
+ t.Errorf("Control(%q, %q) = %v, want refused=%v", tc.network, tc.address, err, tc.refused)
+ }
+ }
+}
+
+// TestDialerKeepsBaseAndChainsControl: Dialer keeps the caller's settings
+// and runs the caller's own Control (and ControlContext) after the guard.
+func TestDialerKeepsBaseAndChainsControl(t *testing.T) {
+ r := guardtest.Resolver(t, "imds.test", "169.254.169.254")
+ var ran int
+ base := net.Dialer{Timeout: 7 * time.Second, KeepAlive: 11 * time.Second, Resolver: r,
+ Control: func(string, string, syscall.RawConn) error { ran++; return nil }}
+ d := upstreamguard.Dialer(base)
+ if d.Timeout != base.Timeout || d.KeepAlive != base.KeepAlive || d.Resolver != r {
+ t.Fatalf("Dialer lost the base settings: %+v", d)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ if _, err := d.DialContext(ctx, "tcp", "imds.test:80"); !errors.Is(err, upstreamguard.ErrLinkLocal) {
+ t.Fatalf("dial imds.test = %v, want ErrLinkLocal after resolution", err)
+ }
+ if ran != 0 {
+ t.Fatalf("base Control ran %d times on a refused address, want 0", ran)
+ }
+
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+ c, err := d.DialContext(ctx, "tcp", ln.Addr().String())
+ if err != nil {
+ t.Fatalf("dial loopback: %v", err)
+ }
+ c.Close()
+ if ran != 1 {
+ t.Fatalf("base Control ran %d times on loopback, want 1", ran)
+ }
+
+ var ranCtx int
+ dc := upstreamguard.Dialer(net.Dialer{ControlContext: func(context.Context, string, string, syscall.RawConn) error { ranCtx++; return nil }})
+ if _, err := dc.DialContext(ctx, "tcp", "169.254.169.254:80"); !errors.Is(err, upstreamguard.ErrLinkLocal) {
+ t.Fatalf("dial with a base ControlContext = %v, want ErrLinkLocal", err)
+ }
+ if c, err := dc.DialContext(ctx, "tcp", ln.Addr().String()); err != nil {
+ t.Fatalf("dial loopback with a base ControlContext: %v", err)
+ } else {
+ c.Close()
+ }
+ if ranCtx != 1 {
+ t.Fatalf("base ControlContext ran %d times, want 1", ranCtx)
+ }
+}