carlos / platform Public

console: close the CSRF scan's blind spots (review round 1)

TestNoRawSessionAsCSRF now resolves string constants (and + of them)
wherever it matches the field name, flags any "csrf": key whose value is
neither a string literal nor csrfToken(...), any csrfOK call outside
csrfFormOK and any query-string read of csrf, and keeps a canary floor of
csrfToken emitters and CSRF: fields so a rename fails loudly. New negative
controls cover each shape. The signed-in page test also checks a confirm
card and the signed-in demo claim page.

Behaviour note for this branch: csrf must now come from the POST body,
exactly once; a csrf only in the query string, or sent twice, is refused
with the existing 403.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev fd963c44eea4eb3a7f9ae0aaf1cb0998b5097447 parent c1436a3
2 files changed, +243 −63
  • internal/console/csrf_scan_test.go +223 −63
  • internal/console/csrf_test.go +20 −0

CI failed — run details

diff --git a/internal/console/csrf_scan_test.go b/internal/console/csrf_scan_test.go
index ccabe4f4c..33e4d68fd 100644
--- a/internal/console/csrf_scan_test.go
+++ b/internal/console/csrf_scan_test.go
@@ -1,10 +1,12 @@
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.
+// (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"
@@ -28,15 +30,27 @@ var csrfReaderAllow = map[string]bool{
"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) {
- files, err := filepath.Glob("*.go")
+ names, err := filepath.Glob("*.go")
if err != nil {
t.Fatal(err)
}
fset := token.NewFileSet()
- var bad []string
- scanned := 0
- for _, name := range files {
+ var files []*ast.File
+ var fileNames []string
+ for _, name := range names {
if strings.HasSuffix(name, "_test.go") {
continue
}
@@ -48,16 +62,27 @@ func TestNoRawSessionAsCSRF(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- scanned++
- bad = append(bad, csrfScanFile(fset, f, name)...)
+ 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))
}
- if scanned < 100 {
- t.Fatalf("scanned %d files; the glob is not seeing the package", scanned)
+ sc := newCSRFScan(fset, files)
+ for i, f := range files {
+ sc.file(f, fileNames[i])
}
- sort.Strings(bad)
- for _, b := range bad {
+ 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
@@ -65,26 +90,50 @@ func TestNoRawSessionAsCSRF(t *testing.T) {
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
}
- _ = [][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
+ 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()
@@ -92,11 +141,11 @@ func good(r *http.Request, raw string) {
if err != nil {
t.Fatal(err)
}
- got := csrfScanFile(fset, f, "neg.go")
- // Which marked lines were flagged.
+ sc := newCSRFScan(fset, []*ast.File{f})
+ sc.file(f, "neg.go")
lines := strings.Split(src, "\n")
flagged := map[string]bool{}
- for _, g := range got {
+ for _, g := range sc.out {
// "neg.go:LINE: ..."
rest := strings.TrimPrefix(g, "neg.go:")
n, err := strconv.Atoi(rest[:strings.IndexByte(rest, ':')])
@@ -109,20 +158,99 @@ func good(r *http.Request, raw string) {
t.Errorf("flagged an unmarked (good) line %d: %s", n, g)
continue
}
- flagged[strings.TrimSpace(line[i+3:])] = true
+ flagged[strings.Fields(line[i+3:])[0]] = true
}
- for _, want := range []string{"A1", "A2", "A3", "A4", "B1", "B2", "B3", "C1", "C2"} {
+ 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, got)
+ 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
}
-// 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
+// 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) {
- out = append(out, name+":"+strconv.Itoa(fset.Position(n.Pos()).Line)+": "+why)
+ sc.out = append(sc.out, name+":"+strconv.Itoa(sc.fset.Position(n.Pos()).Line)+": "+why)
}
for _, decl := range f.Decls {
fn := ""
@@ -133,41 +261,56 @@ func csrfScanFile(fset *token.FileSet, f *ast.File, name string) []string {
ast.Inspect(decl, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.CallExpr:
- switch {
- case isSel(n.Fun, "ConstantTimeCompare") && !readerOK:
+ 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 readsCSRFField(a) {
+ if sc.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) {
+ 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 && isSel(n.X, "PostForm", "Form") && isStr(n.Index, "csrf") {
+ 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 && isStr(n.Elts[0], "csrf") && !isCSRFTokenCall(n.Elts[1]) {
+ 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:
- // 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(...)`)
+ // "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" && !isCSRFTokenCall(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) && !isCSRFTokenCall(n.Rhs[i]) {
+ 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(...)")
}
}
@@ -175,12 +318,20 @@ func csrfScanFile(fset *token.FileSet, f *ast.File, name string) []string {
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 {
+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()
@@ -189,23 +340,41 @@ func readsCSRFField(e ast.Expr) bool {
return true
}
}
- return false
+ 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").
-func isCSRFRead(c *ast.CallExpr) bool {
- if len(c.Args) != 1 || !isStr(c.Args[0], "csrf") {
+// 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") {
+ 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 {
@@ -219,15 +388,6 @@ func isSel(e ast.Expr, names ...string) bool {
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 {
diff --git a/internal/console/csrf_test.go b/internal/console/csrf_test.go
index 653885ae1..d0fe8bb3e 100644
--- a/internal/console/csrf_test.go
+++ b/internal/console/csrf_test.go
@@ -128,6 +128,26 @@ func TestSignedInPageDoesNotContainSessionToken(t *testing.T) {
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)