carlos / platform Public

console: derive the CSRF token instead of echoing the session token

Every signed-in page embedded the raw 30-day session token as its CSRF
field. The token is now csrfToken(raw) = hashToken("carlos-console-csrf-v1:"
+ raw), never the session nor its table key. Every emitter (page.CSRF,
confirm fields, the step-up replay) emits it and every checker goes
through csrfFormOK: exactly one csrf body value, constant-time against
the derived token. The raw session is still accepted for one transition
release (grep TRANSITION(csrf-v1)). TestNoRawSessionAsCSRF holds the
package to this shape.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c1436a36028b70bd6d3bf4ebd47ae0ff102ee1e2 parent 3793aa4
47 files changed, +588 −137
  • 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 +238 −0
  • internal/console/csrf_test.go +187 −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/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

CI failed — run details

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..ccabe4f4c
--- /dev/null
+++ b/internal/console/csrf_scan_test.go
@@ -0,0 +1,238 @@
+package console
+
+// TestNoRawSessionAsCSRF is the completeness check for the derived CSRF token
+// (csrf.go): every form token the console emits is csrfToken(...), and every
+// check of a posted token goes through csrfFormOK/csrfOK. A new handler that
+// echoes the session into a form, or compares a posted csrf by hand, fails
+// here rather than in review.
+
+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,
+}
+
+func TestNoRawSessionAsCSRF(t *testing.T) {
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ var bad []string
+ scanned := 0
+ for _, name := range files {
+ 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)
+ }
+ scanned++
+ bad = append(bad, csrfScanFile(fset, f, name)...)
+ }
+ if scanned < 100 {
+ t.Fatalf("scanned %d files; the glob is not seeing the package", scanned)
+ }
+ sort.Strings(bad)
+ for _, b := range bad {
+ t.Error(b)
+ }
+}
+
+// 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
+
+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
+ }
+ _ = [][2]string{{"csrf", raw}} // B1
+ form.Set("csrf", raw) // B2
+ _ = url.Values{"csrf": {raw}} // B3
+ _ = 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))
+ _ = page{Address: addr, CSRF: csrfToken(raw)}
+ p.CSRF = csrfToken(raw)
+ _ = subtle.ConstantTimeCompare([]byte(a), []byte(b))
+}
+`
+ fset := token.NewFileSet()
+ f, err := parser.ParseFile(fset, "neg.go", src, parser.ParseComments)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := csrfScanFile(fset, f, "neg.go")
+ // Which marked lines were flagged.
+ lines := strings.Split(src, "\n")
+ flagged := map[string]bool{}
+ for _, g := range got {
+ // "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.TrimSpace(line[i+3:])] = true
+ }
+ for _, want := range []string{"A1", "A2", "A3", "A4", "B1", "B2", "B3", "C1", "C2"} {
+ if !flagged[want] {
+ t.Errorf("bad shape %s was not flagged; findings: %q", want, got)
+ }
+ }
+}
+
+// csrfScanFile returns one "file:line: why" per offending site in f.
+func csrfScanFile(fset *token.FileSet, f *ast.File, name string) []string {
+ var out []string
+ flag := func(n ast.Node, why string) {
+ out = append(out, name+":"+strconv.Itoa(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:
+ switch {
+ case isSel(n.Fun, "ConstantTimeCompare") && !readerOK:
+ for _, a := range n.Args {
+ if readsCSRFField(a) {
+ flag(n, "hand-rolled CSRF compare; use csrfFormOK")
+ }
+ }
+ case (isSel(n.Fun, "Set") || isSel(n.Fun, "Add")) && len(n.Args) == 2 && isStr(n.Args[0], "csrf") && !isCSRFTokenCall(n.Args[1]):
+ flag(n, `csrf form field set to something other than csrfToken(...)`)
+ }
+ if !readerOK && isCSRFRead(n) {
+ flag(n, "posted csrf read by hand; use csrfFormOK")
+ }
+ case *ast.IndexExpr:
+ if !readerOK && isSel(n.X, "PostForm", "Form") && isStr(n.Index, "csrf") {
+ flag(n, "posted csrf read by hand; use csrfFormOK")
+ }
+ case *ast.CompositeLit:
+ // {"csrf", X}: a hidden-field pair.
+ if len(n.Elts) == 2 && isStr(n.Elts[0], "csrf") && !isCSRFTokenCall(n.Elts[1]) {
+ flag(n, `{"csrf", X} with X not csrfToken(...)`)
+ }
+ case *ast.KeyValueExpr:
+ // url.Values{"csrf": {X}}. A "csrf" key with a plain string
+ // value is a copy map's entry, not a form.
+ if cl, isCL := n.Value.(*ast.CompositeLit); isCL && isStr(n.Key, "csrf") &&
+ (len(cl.Elts) != 1 || !isCSRFTokenCall(cl.Elts[0])) {
+ flag(n, `"csrf": {X} with X not csrfToken(...)`)
+ }
+ if id, isID := n.Key.(*ast.Ident); isID && id.Name == "CSRF" && !isCSRFTokenCall(n.Value) {
+ 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) && !isCSRFTokenCall(n.Rhs[i]) {
+ flag(n, ".CSRF = X with X not csrfToken(...)")
+ }
+ }
+ }
+ return true
+ })
+ }
+ return out
+}
+
+// readsCSRFField reports whether the expression's source mentions a read of
+// the posted csrf field.
+func 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
+ }
+ }
+ return false
+}
+
+// isCSRFRead: r.FormValue("csrf"), r.PostFormValue("csrf"), r.PostForm.Get("csrf"), r.Form.Get("csrf").
+func isCSRFRead(c *ast.CallExpr) bool {
+ if len(c.Args) != 1 || !isStr(c.Args[0], "csrf") {
+ 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") {
+ return true
+ }
+ return false
+}
+
+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 isStr(e ast.Expr, want string) bool {
+ bl, ok := e.(*ast.BasicLit)
+ if !ok || bl.Kind != token.STRING {
+ return false
+ }
+ s, err := strconv.Unquote(bl.Value)
+ return err == nil && s == want
+}
+
+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..653885ae1
--- /dev/null
+++ b/internal/console/csrf_test.go
@@ -0,0 +1,187 @@
+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)
+ }
+ }
+}
+
+// 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/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
}