From d33dac0f769b35817dabe25c855e69962fc4d515 Mon Sep 17 00:00:00 2001 From: Remi Antczak <140408771+remigiusz-antczak@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:11:53 +0100 Subject: [PATCH] G6: CSRF and cookie-flag leads (csrf_cookie_map.py) New report-only tool csrf_cookie_map.py, wired into review_checks.sh --full as tool csrf-cookie, with two rules: - missing-csrf-protection: a state-changing handler in a cookie-session file or path realm whose own text shows no anti-forgery defence (csrf or xsrf, or an Origin/Referer/Sec-Fetch-Site header compared against a literal or an allow-list), and no repo-wide CSRF layer that the repo does not disable. Django @csrf_exempt removes the layer cover. Reported at the line that commits the change. - missing-cookie-flags: a session-like cookie set without Secure, HttpOnly or SameSite (Go, Express, Flask/Django, Java Cookie and ResponseCookie, raw Set-Cookie strings). Expiry, csrf-named and variable-options cookies are skipped. attempt_limit_map.units gains innermost=False (Go wrapper registrations resolve to the inner handler only when asked), resolves mid-line Django path() calls, keeps sibling one-line Spring handlers apart and keeps a multi-line annotation that opens with `({` in its handler's unit. Output of cost_limit_map, attempt_limit_map and route_auth_map on the six dev fixtures is byte-identical to main. whole-project-report.md asks for one finding per vulnerable site. Dev set only (the tool was built against these fixtures, so this is an upper bound): csrf 12/12 positives, 0/8 decoys; cookie_flags 12/12, 0/8. Three independent review rounds folded. run-ci-tests.sh --affected: 56/56 suites pass. Tests: 71/71 Co-Authored-By: Claude Opus 5.5 --- .claude/skills/INDEX.md | 1 + .../skills/deep-code-review/INDEX-scripts.md | 1 + .claude/skills/deep-code-review/INDEX.md | 4 +- .../references/whole-project-report.md | 2 + .../scripts/attempt_limit_map.py | 15 +- .../scripts/csrf_cookie_map.py | 208 ++++++++++++++++++ .../deep-code-review/scripts/review_checks.sh | 10 +- SHA256SUMS | 11 +- changelog.d/g6-csrf-cookie-routes.md | 13 ++ scripts/ci-tests.d/csrf-cookie.sh | 4 + scripts/size-budgets.tsv | 8 +- scripts/test_csrf_cookie_map.py | 124 +++++++++++ scripts/test_csrf_cookie_review.py | 76 +++++++ scripts/test_csrf_cookie_round2.py | 63 ++++++ 14 files changed, 522 insertions(+), 18 deletions(-) create mode 100644 .claude/skills/deep-code-review/scripts/csrf_cookie_map.py create mode 100644 changelog.d/g6-csrf-cookie-routes.md create mode 100644 scripts/ci-tests.d/csrf-cookie.sh create mode 100644 scripts/test_csrf_cookie_map.py create mode 100644 scripts/test_csrf_cookie_review.py create mode 100644 scripts/test_csrf_cookie_round2.py diff --git a/.claude/skills/INDEX.md b/.claude/skills/INDEX.md index c05d6050a..18221bcd0 100644 --- a/.claude/skills/INDEX.md +++ b/.claude/skills/INDEX.md @@ -132,6 +132,7 @@ Run `python3 /scripts/` (`bash` for `.sh`). `name: purpose — argu - context_pack.py: bounded context pack for a DIFF review. — [--base REF] [--repo DIR] [--intent… - cost_limit_map.py: heuristic lead-finder for costly or unbounded HTTP endpoints… — DIR - coverage_ledger.py: completeness check for a machine-report coverage map. — [--domains SPEC] +- csrf_cookie_map.py: heuristic lead-finder for cookie-session handlers with no CSRF… — DIR - dependency_currency.py: how far behind is every dependency, and is it vulnerable. — [--root DIR] [--stdin] [--json]… - derived_numbers.py: bind a doc number to the counter that derives it. — [--fix] [--selftest] [ROOT] - design_drift.py: zero-token check that UI code still uses the project's design… — [--strict] [--json] [--tokens FILE]… diff --git a/.claude/skills/deep-code-review/INDEX-scripts.md b/.claude/skills/deep-code-review/INDEX-scripts.md index bb30113f0..cfcd4ea85 100644 --- a/.claude/skills/deep-code-review/INDEX-scripts.md +++ b/.claude/skills/deep-code-review/INDEX-scripts.md @@ -14,6 +14,7 @@ Generated by `scripts/skill_index.py` (do not hand-edit). The script half of `IN | `scripts/context_pack.py` | bounded context pack for a DIFF review. | context_pack.py [--base REF] [--repo DIR] [--intent FILE\|-] [--cap N] [--max-bytes N] | | `scripts/cost_limit_map.py` | heuristic lead-finder for costly or unbounded HTTP endpoints with no rate or quota limit evidence (… | python3 -I cost_limit_map.py DIR | | `scripts/coverage_ledger.py` | completeness check for a machine-report coverage map. | coverage_ledger.py [--domains SPEC] | +| `scripts/csrf_cookie_map.py` | heuristic lead-finder for cookie-session handlers with no CSRF defence and session cookies set with… | python3 -I csrf_cookie_map.py DIR | | `scripts/dependency_currency.py` | how far behind is every dependency, and is it vulnerable. | dependency_currency.py [--root DIR] [--stdin] [--json] [--budget SECS] [--today YYYY-MM-DD] | | `scripts/derived_numbers.py` | bind a doc number to the counter that derives it. | python3 derived_numbers.py [--fix] [--selftest] [ROOT] Exit codes: 0 ok (or fixed); 1 drift or bad marker; 2 usage or s… | | `scripts/design_drift.py` | zero-token check that UI code still uses the project's design tokens. | design_drift.py [--strict] [--json] [--tokens FILE] [--base REF] [PATH...] | diff --git a/.claude/skills/deep-code-review/INDEX.md b/.claude/skills/deep-code-review/INDEX.md index c00195e4c..3655f4668 100644 --- a/.claude/skills/deep-code-review/INDEX.md +++ b/.claude/skills/deep-code-review/INDEX.md @@ -149,8 +149,8 @@ Generated by `scripts/skill_index.py` (do not hand-edit; rerun it after changing | `references/ux-writes.md` | the target or diff writes from the UI: an optimistic mutation whose failure path rolls back, a load… | 2949 | | `references/web-fetch.md` | the target or diff fetches data for a view: dependent requests on the render-critical path, a share… | 5710 | | `references/web-render.md` | the target or diff renders a list or grid of rows / tiles, adds or removes React.memo / useMemo / u… | 4731 | -| `references/whole-project-report.md` | writing a whole-project security audit report, or when scripts/report_contract_lint.py rejects one. | 846 | +| `references/whole-project-report.md` | writing a whole-project security audit report, or when scripts/report_contract_lint.py rejects one. | 1041 | ## Scripts -44 scripts. Read `INDEX-scripts.md` when you need a script (a trigger and CLI per script). `../INDEX.md`, `### deep-code-review`, has only each one-line purpose and arguments. +45 scripts. Read `INDEX-scripts.md` when you need a script (a trigger and CLI per script). `../INDEX.md`, `### deep-code-review`, has only each one-line purpose and arguments. diff --git a/.claude/skills/deep-code-review/references/whole-project-report.md b/.claude/skills/deep-code-review/references/whole-project-report.md index 80f91caa3..3f821683e 100644 --- a/.claude/skills/deep-code-review/references/whole-project-report.md +++ b/.claude/skills/deep-code-review/references/whole-project-report.md @@ -31,6 +31,8 @@ Needs a running system: deployed config, WAF, runtime authz, vault, infra outsid A security audit (`security-review-mode.md`) has a `## Findings` section with one finding per top-level list item: `[] : : `. The path is the vulnerable handler or line, never a gate, helper or config used as evidence; give exactly one `path:line`, and put evidence cites after `evidence:` in the text or in other sections. Never cite a bare file name. A chain finding cites its end-state line as the primary and the other links after `evidence:`. Indented continuation lines, prose, and subsections whose heading names an attack path or chain are not linted. +One finding per vulnerable site, never a group or a range: each state-changing cookie-session handler without a CSRF defence (`csrf`, anchored on the line that commits the change, not the signature), each session-cookie set call missing a flag (`cookie-flags`, including a cookie that sets HttpOnly but not Secure or SameSite), each unauthenticated handler (`missing-authn`). A GET that sets a cookie is not `csrf`. The per-standard Files cell and the primary `path:line` list vulnerable sites only: a gate, middleware, interceptor, filter, helper or token table you read as evidence goes after `evidence:`, and a route a verified global gate covers is not `missing-authn`. Each `csrf-cookie` row from `review_checks.sh --full` is a lead: verify it, then file it at its own line. + Fixed class vocabulary: `missing-authn`, `missing-authz`, `object-access`, `ssrf`, `tls-off`, `outbound-timeout`, `secret-in-url`, `secret-in-log`, `hardcoded-secret` (credentials or tokens in source), `csrf`, `cookie-flags`, `rate-limit`, `pii-in-log`, `pii-data` (personal data committed, stored in plaintext or sent to a third party), `prompt-injection` (including tool-call JSON built from input), `injection`, `xss`, `other`. Pick the closest class; use `other` only when none fits. Example: `- [pii-data] src/api/users.py:42 high: serves SSNs and dates of birth unmasked. evidence: src/models.py:10` diff --git a/.claude/skills/deep-code-review/scripts/attempt_limit_map.py b/.claude/skills/deep-code-review/scripts/attempt_limit_map.py index fb535a6dc..3fac82e6f 100644 --- a/.claude/skills/deep-code-review/scripts/attempt_limit_map.py +++ b/.claude/skills/deep-code-review/scripts/attempt_limit_map.py @@ -193,10 +193,10 @@ def declend(lines, ln, py): return len(lines) -def units(root, texts): +def units(root, texts, innermost=False): """{file: [(line, end, methods, route)]} of every handler under root, sorted by line: the route_auth_map inventory (JS/TS, Python, Go, Spring, Django), where a Go registration, a Django `path(route, view)` and a Next `export const GET = handler` re-export are followed to the function they name (the unit is that function's first line), and `end` is the last line of - the handler. texts is filled with the masked text of every file read (comments blanked, strings kept).""" + the handler. texts is filled with the masked text of every file read (comments blanked, strings kept). A Go registration `HandleFunc(p, wrap(h))` follows `wrap`'s definition unless innermost is set, which follows `h`.""" def T(rel): if rel not in texts: raw = read(root, rel) @@ -225,11 +225,12 @@ def find(rx, near): tail = re.search(r"""["']\s*,\s*(.*)""", line) d = None if rel.endswith(".go") and tail: - for n in re.findall(r"[\w.]+", tail[1]): + for n in (lambda ns: ns[::-1] if innermost else ns)(re.findall(r"[\w.]+", tail[1])): d = find(r"^func\s+(?:\([^)]*\)\s*)?%s\s*\(" % re.escape(n.rpartition(".")[2]), rel) if d: break - elif rel.endswith(".py") and re.match(r"\s*(?:re_)?path\(|\s*url\(", line) and tail: - v = re.match(r"[\w.]+", tail[1]) + elif rel.endswith(".py") and re.search(r"(?:^|[\s\[,(])(?:re_)?path\(|(?:^|[\s\[,(])url\(", line) and tail: + lit = [x for x in re.finditer(r"""["']([^"']*)["']\s*,\s*""", line) if x[1].strip("/") == (route or "").strip("/")] # the tail after THIS route's string, not the line's first + v = re.match(r"[\w.]+", line[lit[0].end():] if lit else tail[1]) d = v and find(r"^[ \t]*(?:async\s+)?(?:def|class)\s+%s\b" % re.escape(v[0].replace(".as_view", "").rpartition(".")[2]), rel) else: im = re.match(r"\s*export\s+const\s+\w+\s*=\s*(\w+)\s*;?\s*$", line) # `export const POST = handler;`, handler imported by name @@ -241,7 +242,9 @@ def find(rx, near): j = l - 2 # the decorators and annotations above a handler (blank, comment and multi-line argument lines between them too) belong to it, not to the handler before while j >= 0: s = above[j].strip() - if s.startswith("@"): l = j + 1 + if s.startswith("@"): + if s.count("(") == s.count(")") and "{" in re.sub(r"\([^()]*\)", "", re.sub(r"\([^()]*\)", "", s)): break # a one-line declaration (class, or handler with its body) is not a decorator of the next handler; an unclosed `({` opens a multi-line annotation argument + l = j + 1 elif s and not s.startswith(("#", "//")): k = next((k for k in range(j - 1, max(j - 16, -1), -1) if above[k].lstrip().startswith("@") and "\n".join(above[k:j]).count("(") > "\n".join(above[k:j]).count(")")), None) if k is None: break diff --git a/.claude/skills/deep-code-review/scripts/csrf_cookie_map.py b/.claude/skills/deep-code-review/scripts/csrf_cookie_map.py new file mode 100644 index 000000000..c82271c24 --- /dev/null +++ b/.claude/skills/deep-code-review/scripts/csrf_cookie_map.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""csrf_cookie_map.py DIR -- heuristic lead-finder for cookie-session handlers with no CSRF defence and session cookies set without Secure, HttpOnly or SameSite (CWE-352/614/1004/1275). Report-only, stdlib only. + +Usage: python3 -I csrf_cookie_map.py DIR + +Read this when you review a cookie-session web app: a browser sends the session cookie on a cross-site form post, so a state-changing handler with no anti-forgery token, Origin check or +SameSite protection acts for whoever the victim is logged in as, and a session cookie without Secure/HttpOnly/SameSite leaks to plain HTTP, to script, or to cross-site requests. +A row is a lead, never a finding, and SILENCE IS NOT PROOF: a gateway, a framework default or a flag set in app config may cover what this scan cannot see. + +Rows are `filelinerulemessage`; stderr gets one summary line. +- `missing-csrf-protection`: a POST/PUT/PATCH/DELETE handler (route_auth_map.py inventory via attempt_limit_map.units: Express/Next/Flask/FastAPI, Go, Spring, Django) in a file that reads or sets a session + cookie (or uses a login/session decorator) whose own text shows no CSRF defence. Reported at the handler's last statement, where the change is committed. Defence = `csrf`/`xsrf` or a + `Sec-Fetch-Site`/`Origin`/`Referer` header COMPARED in the handler (a bare read is not a defence), a repo-wide CSRF layer named anywhere under DIR (Django `CsrfViewMiddleware`, csurf, + csrf-csrf, lusca, `CSRFProtect`, nosurf, gorilla/csrf, a Spring `SecurityFilterChain`) unless the repo disables it (`csrf().disable()`, `csrf(c -> c.disable())`, + `csrf(AbstractHttpConfigurer::disable)`; the disable wins whatever the file order), or any SameSite=Strict/Lax cookie in the repo. Django `@csrf_exempt` removes the layer cover from the handler + and, on a view with no method check, makes it a POST. Only a session-named cookie (or a session read) makes a handler or its path realm cookie-session; a `theme` cookie does not. Login, signup, register, webhook, callback and oauth routes are skipped. +- `missing-cookie-flags`: a cookie that looks like a session/auth cookie (name has sess, sid, auth, token, jwt, login, admin, remember or user, or is not a literal) set by Go `http.Cookie{...}`, + Express `res.cookie(...)`, Flask/Django `set_cookie(...)`, Java `new Cookie(...)` + `addCookie` or `ResponseCookie`, or a `Set-Cookie` header string, that lacks one of Secure, HttpOnly, SameSite. + Reported at the call (Java: the `addCookie` line). Expiry cookies (max-age 0, empty value), csrf/xsrf-named cookies, and cookies whose options argument is a bare identifier or a spread are skipped. + +ponytail: file-level cookie evidence and repo-wide CSRF evidence (one csurf line anywhere clears every handler); flags are read from the call's own text, so a flag set by app config +(`SESSION_COOKIE_SECURE`, `server.servlet.session.cookie.*`) reads as missing. Upgrade to per-framework parsing if precision matters more. +""" +import os, re, sys + +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from attempt_limit_map import PRUNE, shown, units, walk # noqa: E402 +from route_auth_map import pymask, read # noqa: E402 +from tenant_scope_check import mask # noqa: E402 + +STATE = {"POST", "PUT", "PATCH", "DELETE"} +SESSION = re.compile(r"\b(?:r|req|request)\.Cookie\(|\bcookies\(\)|\b(?:req|request)\.cookies\b|@CookieValue" + r"|\bsession\[|\bsession\.get\(|\brequest\.session\b|\breq\.session\b|\bgetSession\(|\bHttpSession\b") +DEFENCE = re.compile(r"csrf|xsrf", re.I) +HDR = re.compile(r"sec-fetch-site|\borigin\b|\breferer\b", re.I) +CMP = re.compile(r"===?|!==?|\bin\b|startswith|endswith|\.includes\(|\.has\(|\.equals\(|\.indexOf\(|\.test\(|\.match\(|compare", re.I) +SAMESITE = re.compile(r"same_?site[\"'`\s:=(.]{0,6}(?:strict|lax)\b", re.I) +NOVALUE = re.compile(r"(?:[!=]=+|\bis(?:\s+not)?)\s*(?:undefined|null|None|nil)\b|\b(?:undefined|null|None|nil)\s*[!=]=+") +DISABLE = re.compile(r"csrf\s*\(\s*\)\s*\.\s*disable|csrf\.disable|csrf\s*\(\s*\w+\s*->\s*\w+\s*\.\s*disable\s*\(|csrf\s*\(\s*AbstractHttpConfigurer::disable") +NAME = re.compile(r"""(?:Name\s*:|\(\s*|Set-Cookie["'`]?\s*[:,]\s*)["'`]([^"'`=;$]*)""") +GLOBAL = re.compile(r"CsrfViewMiddleware|\bcsurf\b|csrf-csrf|\blusca\b|CSRFProtect|\bnosurf\b|gorilla/csrf|SecurityFilterChain|\bcsrf_protect\b") +EXEMPT = re.compile(r"@csrf_exempt\b|@csrf\.exempt\b|\bcsrf\s*\(\s*\)\s*\.\s*disable\b|\bcsrf\.disable\b") +PUBLIC = re.compile(r"login|signin|sign-in|signup|sign-up|register|webhook|callback|oauth|logout", re.I) +SESSNAME = re.compile(r"sess|sid|auth|token|jwt|login|admin|remember|user", re.I) +EXPIRY = re.compile(r"""max_?age\s*[:=]\s*-?0\b|MaxAge\s*[:=]\s*-\d|expires\s*[:=]\s*(?:0\b|new Date\(0\))|Max-Age=0|\bsetMaxAge\(\s*(?:0|-\d+)\s*\)""", re.I) +FLAGS = (("Secure", r"secure"), ("HttpOnly", r"http_?only"), ("SameSite", r"same_?site")) +GOCOOKIE = re.compile(r"http\.Cookie\s*\{") +EXPRESS = re.compile(r"\bres\.cookie\(") +PYSET = re.compile(r"\bset_cookie\(") +HEADER = re.compile(r"""["'`]Set-Cookie["'`]|\bSet-Cookie\s*:""", re.I) +JNEW = re.compile(r"\b(\w+)\s*=\s*new\s+Cookie\(") +JADD = re.compile(r"\baddCookie\(\s*(\w+)\s*\)") +RESP = re.compile(r"ResponseCookie\s*\.\s*from\(") + + +def call_text(t, i): + """Text of the call or literal opened by the first ( or { at or after offset i of t, brackets balanced (strings are kept in the masked text).""" + n = len(t) + while i < n and t[i] not in "({": i += 1 + d, j = 0, i + while j < n: + d += t[j] in "({"; d -= t[j] in ")}" + j += 1 + if d == 0: break + return t[i:j] + + +def line_of(t, off): + """1-based line of offset off in t.""" + return t.count("\n", 0, off) + 1 + + +def args(call): + """Top-level comma-separated arguments of the bracketed call text.""" + out, d, cur = [], 0, "" + for c in call[1:-1] if call[-1:] in ")}" else call[1:]: + d += c in "({["; d -= c in ")}]" + if c == "," and d == 0: out.append(cur); cur = "" + else: cur += c + return out + [cur] + + +def sessionish(body): + """True if body reads session state or sets a cookie that is not named csrf/xsrf and is session-named or dynamically named.""" + if SESSION.search(body): return True + for m in re.finditer(r"\b(?:res\.cookie|set_cookie|SetCookie)\(|\baddCookie\(|new Cookie\(|Set-Cookie", body): + n = NAME.search(body[m.start():m.start() + 200]) + name = n[1] if n else "" + if not re.search(r"csrf|xsrf", name, re.I) and (not name or SESSNAME.search(name)): return True + return False + + +def missing(text): + """Names of the flags Secure/HttpOnly/SameSite that the cookie text does not set (a flag set false/False/off counts as missing).""" + out = [] + for name, rx in FLAGS: + m = re.search(r"(?:\b|[;\s\"'`])%s\b\s*(?:[:=(]\s*(\w+))?" % rx, text, re.I) + if not m or (m[1] or "").lower() in ("false", "none", "off", "0"): out.append(name) + return out + + +def cookie_rows(rel, t, cover=None): + """[(line, message)] for the session-looking cookies set in masked text t that lack a flag; cover (a list) gets one item per session-named or dynamic cookie with SameSite Strict/Lax.""" + sites = [] # (offset, text, name-or-None) + for rx in (GOCOOKIE, EXPRESS, PYSET): + for m in rx.finditer(t): sites.append((m.start(), call_text(t, m.end() - 1 if rx is GOCOOKIE else m.start()))) + for m in HEADER.finditer(t): # the rest of the line: a header value like `sid=..; Path=/`, not a read like `getHeader("Set-Cookie")` with no `=` + e = t.find("\n", m.end()) + sites.append((m.start(), t[m.start():e if e > 0 else len(t)])) + for m in RESP.finditer(t): sites.append((m.start(), t[m.start():t.find(";", m.end())])) + out = [] + for off, s in sites: + n = NAME.search(s) + name = n[1] if n else "" + if (name and not SESSNAME.search(name)) or re.search(r"csrf|xsrf", name, re.I) or EXPIRY.search(s): continue + if re.match(r"res\.cookie|set_cookie", t[off:off + 12]): # options passed as a variable or spread: flags unknown + a = args(s) + if re.search(r"\.\.\.|\*\*", s) or (len(a) > 2 and re.fullmatch(r"\s*[A-Za-z_$][\w$.]*\s*", a[2])): continue + if re.search(r"""Value\s*:\s*["']{2}|,\s*["']{2}\s*[,)]""", s): continue + if HEADER.search(s) and not re.search(r"=", s.split("Set-Cookie", 1)[-1]): continue + miss = missing(s) + if cover is not None and SAMESITE.search(s): cover.append(off) + if miss: out.append((line_of(t, off), "session cookie %s sets no %s" % (repr(name) if name else "(dynamic)", ", ".join(miss)))) + # Java: `Cookie c = new Cookie(..)` + c.setSecure/setHttpOnly + addCookie(c); reported at addCookie. Flags set on the variable or a Set-Cookie header string below it count. + for m in JNEW.finditer(t): + v = m[1] + nm = re.match(r"""\s*\(\s*["']([^"']*)""", t[m.end() - 1:]) + add = re.compile(r"\baddCookie\(\s*%s\s*\)" % re.escape(v)).search(t, m.end()) + if not add or (nm and not SESSNAME.search(nm[1])): continue + win = re.split(r"\n[ \t]*\}[ \t]*(?:\n|$)", t[m.end():add.end() + 400])[0] # to the end of the method + blk = "\n".join(l for l in win.split("\n") if re.search(r"\b%s\.set\w+\(|Set-Cookie" % re.escape(v), l) or "Set-Cookie" in l) + got = {"Secure": bool(re.search(r"\b%s\.setSecure\(\s*true" % v, blk)), "HttpOnly": bool(re.search(r"\b%s\.setHttpOnly\(\s*true" % v, blk)), + "SameSite": bool(re.search(r"%s\.setAttribute\(\s*[\"']SameSite|SameSite\s*=" % v, blk))} + if re.search(r"Set-Cookie", blk): # a hand-built Set-Cookie header carries its own flags + h = blk[blk.find("Set-Cookie"):] + got.update({k: got[k] or bool(re.search(k, h, re.I)) for k in got}) + gone = [k for k, ok in got.items() if not ok] + if cover is not None and got["SameSite"]: cover.append(m.start()) + if gone and not EXPIRY.search(win): out.append((line_of(t, add.start()), "session cookie %s sets no %s" % (repr(nm[1]) if nm else "(dynamic)", ", ".join(gone)))) + return sorted(set(out)) + + +def last_stmt(lines, a, b): + """1-based line of the last statement of the handler on lines a..b: the last line that is not blank or only closing brackets.""" + for i in range(min(b, len(lines)), a - 1, -1): + if re.sub(r"[\s)}\];,]", "", lines[i - 1]): return i + return a + + +def analyze(root): + """(rows, handlers): sorted (file, line, rule, message) rows for DIR root and the handler count.""" + texts = {} + us = units(root, texts, True) + layer = kill = False + for dp, dn, fn in os.walk(root): + dn[:] = [d for d in dn if d not in PRUNE] + for f in fn: + if f.endswith((".py", ".js", ".ts", ".mjs", ".java", ".kt", ".go", ".xml", ".gradle", ".kts", ".json", ".cfg", ".toml", ".txt")): + p = os.path.join(dp, f) + if os.path.getsize(p) <= 1 << 20 and "node_modules" not in p: + raw = read(root, os.path.relpath(p, root).replace(os.sep, "/")) or "" + layer, kill = layer or bool(GLOBAL.search(raw)), kill or bool(DISABLE.search((pymask if f.endswith(".py") else mask)(raw))) + for rel in walk(root)[0]: + if rel not in texts: + raw = read(root, rel) + if raw is not None: texts[rel] = (pymask if rel.endswith(".py") else mask)(raw, True) + cov = [] + crows = {rel: cookie_rows(rel, t, cov) for rel, t in texts.items() if t is not None} + # a SameSite=Strict/Lax cookie covers the repo only when no session cookie lacks SameSite; ponytail: repo-wide, not per route + glob = (layer and not kill) or (cov and not any("SameSite" in m for r in crows.values() for _, m in r)) + rows, n = [], sum(map(len, us.values())) + seg = lambda r: (r or "").strip("/").split("/")[0] + # a cookie realm is the first path segment of a route whose handler sets a session cookie: its other state-changing handlers are cookie-session too + realms = {seg(u[3]) for rel, rs in us.items() if texts.get(rel) for u in rs if sessionish("\n".join(texts[rel].split("\n")[u[0] - 1:max(u[1], u[0])])) and not PUBLIC.search(u[3] or "")} - {""} + for rel, t in sorted(texts.items()): + if t is None: continue + rows += [(shown(root, rel), ln, "missing-cookie-flags", m) for ln, m in crows[rel]] + lines = t.split("\n") + for u in us.get(rel, []): + a, b, ms, route = u[0], u[1], u[2].split("|"), u[3] + ln = min((r[1] for r in u[4] if r[0] == rel), default=a) + if b < ln and rel.endswith((".java", ".kt")): a = b = ln # dense one-line Java: the inventory span ends before its own mapping line + body = "\n".join(lines[a - 1:max(b, a)]) + if rel.endswith(".py") and "ANY" in ms and re.search(r"require_http_methods\(\s*\[[^\]]*\]", body): # Django: the allowed methods are in the decorator + ms = [m.strip(" \"'") for m in re.search(r"require_http_methods\(\s*\[([^\]]*)\]", body)[1].split(",")] + elif "ANY" in ms and (re.search(r"@require_POST\b|@csrf_exempt\b|\brequest\.POST\b|\brequest\.method\s*==\s*[\"']POST", body)): ms = ["POST"] + if not STATE & set(ms) or PUBLIC.search(route or ""): continue + if not (sessionish(body) or seg(route) in realms): continue + exempt = EXEMPT.search(body) + if not exempt and (glob or DEFENCE.search(body) or any(HDR.search(l) and CMP.search(NOVALUE.sub("", l)) for l in body.split("\n"))): continue + what = "csrf_exempt" if exempt else "no anti-forgery token or Origin check" + rows.append((shown(root, rel), last_stmt(lines, a, b), "missing-csrf-protection", "%s %s in a cookie-session file: %s (cross-site form post can act as the logged-in user)" % ("/".join(sorted(STATE & set(ms))), route or "handler", what))) + return sorted(set(rows)), n + + +def main(argv): + """Print the rows for the directory argv[1] and the summary line on stderr; return 0, or 2 on a usage error.""" + if len(argv) != 2 or not os.path.isdir(argv[1]): + print("usage: csrf_cookie_map.py DIR", file=sys.stderr) + return 2 + rows, n = analyze(argv[1]) + for r in rows: print("%s\t%d\t%s\t%s" % r) + print("csrf-cookie: %d handlers, %d leads; silence is not proof of a CSRF defence or of cookie flags" % (n, len(rows)) if n or rows else "csrf-cookie: no HTTP handler or cookie found", file=sys.stderr) + return 0 + + +if __name__ == "__main__": sys.exit(main(sys.argv)) diff --git a/.claude/skills/deep-code-review/scripts/review_checks.sh b/.claude/skills/deep-code-review/scripts/review_checks.sh index 79056f178..b9ea636e2 100755 --- a/.claude/skills/deep-code-review/scripts/review_checks.sh +++ b/.claude/skills/deep-code-review/scripts/review_checks.sh @@ -24,7 +24,7 @@ # zstd, xz, 7z, lz4, bzip2, avro, pdf, zlib; the list and its ceilings are in committed_personal_data.py). gitleaks looks for secrets, not for exported personal data. # Built-in too, base mode only (a --full scan has no diff): sibling_sweep.py lists the unchanged call sites, in non-test code, of a function whose call arguments the diff changed elsewhere (tool `sibling-sweep`, # rule `unchanged-sibling-call`, message starts "lead:"): the sibling route a fix may have missed. Leads to open, never findings; a name with more than 25 call sites is skipped; scope and ceilings are in its docstring. -# `--full` scans every tracked file (base = git's empty tree) instead of a diff; it also runs tenant_scope_check.py (SKIPPED without a *.prisma) and route_auth_map.py (tool `route-auth`, rule `missing-auth`: a state-changing HTTP handler with no authentication evidence; SKIPPED without handlers), header_config.py (tool `header-config`: a security header the repo config never names, a lead to confirm with dynamic_probe.py; SKIPPED without a supported web app; a package.json, .conf file or directory it could not read gives not-checked rows instead) and attempt_limit_map.py (tool `attempt-limit`, rule `missing-attempt-limit`: a password, one-time-code or reset-code check with no attempt-limit evidence in its file or package, a lead to confirm with dynamic_probe.py --rate-endpoint; SKIPPED without a credential check or sign-in route) and cost_limit_map.py (tool `cost-limit`, rules `missing-cost-limit` and `unbounded-body`: an LLM or paid-API proxy, upload, search, export or client-sized-page handler with no rate or quota limit evidence in its file or package, or a handler that reads the whole request body, or a body-parser limit of 10 MB or more, with no byte cap; a lead to confirm with dynamic_probe.py --rate-endpoint; SKIPPED without an HTTP handler). gitleaks runs once over the working tree, then (tool `gitleaks-history`) over the last REVIEW_HISTORY_MAX commits of HEAD (default 1000; 0 = skip, listed as "history not scanned"), so a secret removed from the tree but still in history is reported. gitleaks drops +# `--full` scans every tracked file (base = git's empty tree) instead of a diff; it also runs tenant_scope_check.py (SKIPPED without a *.prisma) and route_auth_map.py (tool `route-auth`, rule `missing-auth`: a state-changing HTTP handler with no authentication evidence; SKIPPED without handlers), header_config.py (tool `header-config`: a security header the repo config never names, a lead to confirm with dynamic_probe.py; SKIPPED without a supported web app; a package.json, .conf file or directory it could not read gives not-checked rows instead) and attempt_limit_map.py (tool `attempt-limit`, rule `missing-attempt-limit`: a password, one-time-code or reset-code check with no attempt-limit evidence in its file or package, a lead to confirm with dynamic_probe.py --rate-endpoint; SKIPPED without a credential check or sign-in route) and cost_limit_map.py (tool `cost-limit`, rules `missing-cost-limit` and `unbounded-body`: an LLM or paid-API proxy, upload, search, export or client-sized-page handler with no rate or quota limit evidence in its file or package, or a handler that reads the whole request body, or a body-parser limit of 10 MB or more, with no byte cap; a lead to confirm with dynamic_probe.py --rate-endpoint; SKIPPED without an HTTP handler) and csrf_cookie_map.py (tool `csrf-cookie`, rules `missing-csrf-protection` and `missing-cookie-flags`: a cookie-session state-changing handler with no anti-forgery token, Origin check or CSRF layer, or a session cookie set without Secure, HttpOnly or SameSite; a lead to confirm by reading the handler; SKIPPED without an HTTP handler or cookie). gitleaks runs once over the working tree, then (tool `gitleaks-history`) over the last REVIEW_HISTORY_MAX commits of HEAD (default 1000; 0 = skip, listed as "history not scanned"), so a secret removed from the tree but still in history is reported. gitleaks drops # fingerprints listed in the repo's .gitleaksignore (as of BASE, HEAD under --full). # gitleaks generic-api-key hits tagged likely-fixture collapse to one summary row per top fixture dir when it has >3 (every other rule, and name-only matches, stay rows); REVIEW_FIXTURE_ROWS=all lists every hit. # `--history` also runs gitleaks over BASE..HEAD (`--full-history`: the whole history). node_modules, vendor, build @@ -906,6 +906,14 @@ if [ "$full" = 1 ]; then while IFS=$'\t' read -r f l r m; do case "$r" in missing-cost-limit|unbounded-body) add cost-limit "$f" "$l" "$r" "$m" ;; esac; done <"$out" fi fi + # csrf_cookie_map.py: missing-csrf-protection rows (a cookie-session POST/PUT/PATCH/DELETE handler with no anti-forgery token, Origin check or CSRF layer) and missing-cookie-flags rows (a session cookie set without Secure, HttpOnly or SameSite). SKIPPED when it finds no handler or cookie. + if have python3 && run_one csrf-cookie python3 -I "$here/csrf_cookie_map.py" "$PWD" && scan_ok csrf-cookie; then + if grep -q 'csrf-cookie: no HTTP handler or cookie found' "$out"; then skip csrf-cookie "SKIPPED: no HTTP handler or cookie" + else + grep -E '^csrf-cookie: ' "$out" >&2 || true + while IFS=$'\t' read -r f l r m; do case "$r" in missing-csrf-protection|missing-cookie-flags) add csrf-cookie "$f" "$l" "$r" "$m" ;; esac; done <"$out" + fi + fi fi lease_drop diff --git a/SHA256SUMS b/SHA256SUMS index cc1b9196c..edf949aba 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -204,8 +204,8 @@ d98f3e4380da3496061ba63be7beebe75017ab4ee1734eda9a3e798e19007b0e .claude/skills 6108f7f8d13cefb9a23ca3960cc3bc73200f8ef88fe39c9d1a9b49b9ec7222f1 .claude/skills/contribution/scripts/learning_to_pr.py 92d22cc5d0a60ba6bdb1f4a9b597823dec5b8412cec09a5be6cf93b3973f4226 .claude/skills/contribution/scripts/prefile_check.sh 18f20db537ab784460ad33cf218f7a01ac0a172fc38413f14c0e19e1ce6821cc .claude/skills/contribution/scripts/share_learning.py -bc69ecec590695919313e2941c15ea4d491389a53cb62320fbff32991709b19a .claude/skills/deep-code-review/INDEX-scripts.md -176281847ae2ae12546a97ed02ee92fee375ed34656f47081f7071b6ae56972e .claude/skills/deep-code-review/INDEX.md +65af84d4e57f60408205332c1f7bad54996de78b9f1c967eabe0f6576e860227 .claude/skills/deep-code-review/INDEX-scripts.md +8c38d686f926990fad7d66a7421859062ae9d857a1a255ab6680134853f4029f .claude/skills/deep-code-review/INDEX.md 1a38985224918c0c83beb751783699a63cf5442539f912e21ee62771e94d15bf .claude/skills/deep-code-review/SKILL.md 18d837980a4f0f3aa9dc21aa9e9ff7e31da488e0ad0315baeac160650d47a8bd .claude/skills/deep-code-review/VERSION b97d95bc93cc23a8bc689e2e23db261a138367bcbc69d2f8a0452d5c2c6dfb68 .claude/skills/deep-code-review/evals/evals.json @@ -353,9 +353,9 @@ b7b85757362758f393b6ddaaafed0f8a5e5075c9a74b604d3a80fca0301bdd71 .claude/skills 0de8627b98293ea5f2b2869d6aac8ec6fd2015336dc4c2e17cd3c5b8f251455b .claude/skills/deep-code-review/references/ux-writes.md 034c0fe0b35fc11bc46b4ae8d3651ff80f9ed28d43b8aa3373927ba37ea6b23f .claude/skills/deep-code-review/references/web-fetch.md b05798db39365a53e913dee3910c1193de2560b00ef2ed47c91ec1608ce2a96f .claude/skills/deep-code-review/references/web-render.md -7dbc74119a9a0349c9c770ef4ad684eb1540ec6102c140f7d7173bd4524413fb .claude/skills/deep-code-review/references/whole-project-report.md +e5cbba5896ea7861aa73704feddc302f8026230f830eaa709f8679a9f399e464 .claude/skills/deep-code-review/references/whole-project-report.md a125d270e13807ed494e48746d374b82318e9e04eeeafb3db004729938dee039 .claude/skills/deep-code-review/scripts/app_pentest.sh -c2aa40171ecf23f38f7c4279bdb0afe28c6c7493ebc4112f0b62bee813b65254 .claude/skills/deep-code-review/scripts/attempt_limit_map.py +4a5ffb66e6f636f15085c4edc5f02ce9ae7513b5292467d249fd9fa34f32e1ee .claude/skills/deep-code-review/scripts/attempt_limit_map.py b4d0333271317c881d175dca1d06092cc1dd4859e33f0b375eb870a152a80e6c .claude/skills/deep-code-review/scripts/binaries_gate.py 47bb118346969518b3688f08fe1c28202d4b7c9d5ac8b7d09e1240af931121cb .claude/skills/deep-code-review/scripts/ci_cost_advisor.py a0301aaa1b602fd8ca44955eaf66b17893905f99aee8fe7d8db0be981bcc25c2 .claude/skills/deep-code-review/scripts/ci_cost_lint.py @@ -364,6 +364,7 @@ ed0f0c1eebfdca4dcbaafbf5c2f7b5cc93884de38715b57db894e0f210a811f9 .claude/skills 6632d4fa969875bb8a26fd8fd1677c3a5eaeeadbea00cb28c88a22d3d9dd4138 .claude/skills/deep-code-review/scripts/context_pack.py 1e278d17eebac5688697ac8932e7b6f638343b55aecb8536bf7761bdf2c939ef .claude/skills/deep-code-review/scripts/cost_limit_map.py c5b40f3f0d3fb174e6c9490150c7b85723de33f95d3fab87d60214d4939401a8 .claude/skills/deep-code-review/scripts/coverage_ledger.py +bfadb28e6ee88993a3dfccf05e7d219cb97f70d3a7b714bcfb6cce5c54f1d720 .claude/skills/deep-code-review/scripts/csrf_cookie_map.py ab34c3abf14ca8fcbb1a5e95c4837634b2523ea31f9459b3b284cde9ae7eea56 .claude/skills/deep-code-review/scripts/dependency_currency.py 36c1447a65135496c519397c04c6a74ef066bd01399d593907e598b8d2038498 .claude/skills/deep-code-review/scripts/derived_numbers.py 662031286d4a29aff2e1aaa5cb4fa287ab99f9c7b5124085ea47da3dc66622cc .claude/skills/deep-code-review/scripts/design_drift.py @@ -403,7 +404,7 @@ e2903a566deee3423cc377b000475b30d6698ccebd640cb62b86b6d2001c4822 .claude/skills b01cae69d80ca560cc414c1c70ef0ddfdbb910da5b68df4e9d46cf0daf3f8b16 .claude/skills/deep-code-review/scripts/provision_tools.sh e1d1d2eab715ef280b8c211a9da15ebe6b87969de89d7028d7f1cc82d64fc1f0 .claude/skills/deep-code-review/scripts/reaper_lint.py 8545b85530f9c456880faf1d5613e7106467a20c58c97bdff2d745e7e86c2585 .claude/skills/deep-code-review/scripts/report_contract_lint.py -270a967799de09cb74b79effe32cfce8ae600716fc418ebe2ef231391209b822 .claude/skills/deep-code-review/scripts/review_checks.sh +c617f80ad484368178f0c7aba3e6439ff512564cb36ed2d02df26b24346d2894 .claude/skills/deep-code-review/scripts/review_checks.sh 8c87c02a050a975e453b52ecacbaf01481c7134466a9c67feaf409d22e36d9f7 .claude/skills/deep-code-review/scripts/review_feedback.py 3d0cee729ca0dc743ebef83b96e6bff55c167445570635a800caa0c0a84e6843 .claude/skills/deep-code-review/scripts/route_auth_map.py 859c67d6a6a781c873f47d5662d403da2321da53e6994ca3d0ccdbf74afd39ac .claude/skills/deep-code-review/scripts/score_review.py diff --git a/changelog.d/g6-csrf-cookie-routes.md b/changelog.d/g6-csrf-cookie-routes.md new file mode 100644 index 000000000..9c843a25d --- /dev/null +++ b/changelog.d/g6-csrf-cookie-routes.md @@ -0,0 +1,13 @@ +### Added +- `csrf_cookie_map.py` (wired into `review_checks.sh --full` as tool `csrf-cookie`, rules `missing-csrf-protection` and `missing-cookie-flags`) finds cookie-session state-changing handlers with no anti-forgery token, Origin check or CSRF layer, and session cookies set without Secure, HttpOnly or SameSite, across Express/Next, Flask, Django, Go and Spring. A handler counts as cookie-session when its own text reads a session cookie or when its first path segment is a "cookie realm" (some route there sets a session cookie); Django `@csrf_exempt` is flagged even when `CsrfViewMiddleware` is on; login, signup, webhook, callback and oauth routes are skipped. CSRF rows are reported at the handler's last statement (where the change commits), cookie rows at the set call (Java: the `addCookie` line). Heuristic: file-level cookie evidence, one repo-wide CSRF layer clears every handler, and flags set in app config read as missing. +- `csrf_cookie_map.py` review fixes (tests in `scripts/test_csrf_cookie_review.py`): a Spring `csrf(c -> c.disable())` or `csrf(AbstractHttpConfigurer::disable)` anywhere overrides the Spring Security cover whatever the file order (the pom marker is no longer a cover); a Django `@csrf_exempt` view with no method check counts as POST; an Origin/Referer/Sec-Fetch-Site read with no comparison is not a defence; only session-named cookies (not `theme`) make a handler or path realm cookie-session; csrf/xsrf-named cookies and cookies with a variable or spread options argument get no flags row; SameSite=Strict/Lax on every session cookie in the repo counts as CSRF cover. +- `csrf_cookie_map.py` round-2 fixes (tests in `scripts/test_csrf_cookie_round2.py`): an Origin/Referer compare against `undefined`/`null`/`None` is not a defence; only session-named or dynamic cookies with SameSite Strict/Lax give the repo cover; the csrf-disable scan runs on comment-and-string-masked text. `attempt_limit_map.units` maps two `path(...)` calls on one line each to their own view and no longer folds sibling one-line Spring handlers into the class annotation line, while a multi-line annotation that opens with `({` (`@RolesAllowed({`, `@ApiResponses(value = {`) stays in its handler's unit, so `route_auth_map` and `cost_limit_map` still see the guard (output on the six dev fixtures is byte-identical). + +### Changed +- `attempt_limit_map.units` also resolves a Django `path(...)` registration that is not at the start of its line (`urlpatterns=[path(...)]`). +- `attempt_limit_map.units(..., innermost=True)` follows a Go registration `HandleFunc(p, requireCookie(h))` to `h` instead of the wrapper; the default is unchanged, so the rate-limit and cost tools behave as before. +- `whole-project-report.md` asks for one finding per vulnerable site (CSRF anchored on the committing line, one cookie finding per set call, no groups or ranges), vulnerable sites only in the Files cell, and gates, helpers and token tables under `evidence:`. + +Measured on the burned G6 dev set (tool level, six fixtures, `truth.json` positives hit within 3 lines, decoy rows flagged; the new script was built against these fixtures, so treat the numbers as an upper bound for unseen apps): csrf 0/12 positives and 0/8 decoys flagged before, 12/12 and 0/8 after, 0 unmatched rows; cookie_flags 0/12 and 0/8 before, 12/12 and 0/8 after, 0 unmatched rows; routes (`route_auth_map.py` HIGH rows, class-agnostic part match) 3/30 positives with 2 decoys flagged, unchanged: a name-based `guard`/`withRole` identity rule cleared a decoy but broke the transitive-guard mutation tests and lost a hit, so it was dropped; route authn precision is addressed only by the report labeling rules. The same-day agentic run missed csrf and cookie_flags positives mostly because findings were grouped or cited a bare file name or the handler signature, and flagged routes FPs because gate, helper and token-table files sat in the Files cell; those are labeling gaps the reference now closes, not measured here. + +size-budget-raise: .claude/skills/deep-code-review/references/whole-project-report.md 3386→4167 one finding per vulnerable site, vulnerable-only Files cell and a pointer to csrf-cookie rows diff --git a/scripts/ci-tests.d/csrf-cookie.sh b/scripts/ci-tests.d/csrf-cookie.sh new file mode 100644 index 000000000..9a0e29da2 --- /dev/null +++ b/scripts/ci-tests.d/csrf-cookie.sh @@ -0,0 +1,4 @@ +# Registers the csrf-cookie suites with CI. +python3 scripts/test_csrf_cookie_map.py +python3 scripts/test_csrf_cookie_review.py +python3 scripts/test_csrf_cookie_round2.py diff --git a/scripts/size-budgets.tsv b/scripts/size-budgets.tsv index d2d8123fe..21f5ff993 100644 --- a/scripts/size-budgets.tsv +++ b/scripts/size-budgets.tsv @@ -208,11 +208,11 @@ README.md 16118 .claude/skills/product-discovery/references/full-map.md 12384 .claude/skills/growth-analytics/references/full-map.md 10661 .claude/skills/positioning/references/full-map.md 9520 -.claude/skills/INDEX.md 17210 +.claude/skills/INDEX.md 17306 .claude/skills/agentic-delivery/INDEX.md 4672 .claude/skills/agentic-delivery/INDEX-scripts.md 17639 -.claude/skills/deep-code-review/INDEX.md 20702 -.claude/skills/deep-code-review/INDEX-scripts.md 7760 +.claude/skills/deep-code-review/INDEX.md 20703 +.claude/skills/deep-code-review/INDEX-scripts.md 7934 .claude/skills/agentic-delivery/references/pipeline-optimizer.md 21785 .claude/skills/agentic-delivery/references/focus-kit.md 5235 .claude/skills/communication-structure/references/artifact-templates.md 9443 @@ -238,4 +238,4 @@ README.md 16118 .claude/skills/deep-code-review/references/desktop-native-appsec.md 4724 .claude/skills/deep-code-review/references/dynamic-probe.md 2095 .claude/skills/agentic-delivery/references/flow-guards.md 3171 -.claude/skills/deep-code-review/references/whole-project-report.md 3386 +.claude/skills/deep-code-review/references/whole-project-report.md 4167 diff --git a/scripts/test_csrf_cookie_map.py b/scripts/test_csrf_cookie_map.py new file mode 100644 index 000000000..55faffe76 --- /dev/null +++ b/scripts/test_csrf_cookie_map.py @@ -0,0 +1,124 @@ +"""csrf_cookie_map.py (cookie-session handlers with no CSRF defence; session cookies without Secure/HttpOnly/SameSite): Express, Go (wrapped handler), Flask, Spring and Django +positives, defended and fully flagged negatives, the cookie-realm rule, the usage contract and the review_checks.sh --full wiring. Fictional fixtures; one new file per feature.""" +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +sys.dont_write_bytecode = True +ROOT = Path(__file__).resolve().parent.parent +SK = ROOT / ".claude/skills/deep-code-review/scripts" +sys.path.insert(0, str(SK)) +import csrf_cookie_map as C # noqa: E402 + +CSRF, FLAGS = "missing-csrf-protection", "missing-cookie-flags" + + +def rows(files): + """(file, line, rule) rows from analyze() for a fresh temp repo built from {relative path: lines}.""" + with tempfile.TemporaryDirectory() as t: + for rel, lines in files.items(): + p = Path(t) / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text("\n".join(lines) + "\n", encoding="utf-8") + return [(f, ln, r) for f, ln, r, _ in C.analyze(t)[0]] + + +EXPRESS = [ + "const router = require('express').Router();", + "router.get('/web/session/start', (req, res) => {", + " res.cookie('sid', 'x', { path: '/' });", + " res.sendStatus(204);", + "});", + "router.post('/web/account/email', (req, res) => {", + " save(req.body.email);", + " res.sendStatus(204);", + "});", + "router.post('/web/account/phone', (req, res) => {", + " if (req.get('x-csrf-token') !== req.cookies.csrf) return res.sendStatus(403);", + " res.sendStatus(204);", + "});", + "router.post('/api/pay', (req, res) => {", + " res.sendStatus(202);", + "});", + "router.get('/web/session/ok', (req, res) => {", + " res.cookie('sid', 'x', { secure: true, httpOnly: true, sameSite: 'strict' });", + " res.sendStatus(204);", + "});", + "router.get('/web/session/admin', (req, res) => {", + " res.cookie('admin_sid', 'x', { httpOnly: true });", + " res.sendStatus(204);", + "});", +] + + +class CsrfCookieMap(unittest.TestCase): + def test_express(self): + got = rows({"app.js": EXPRESS}) + self.assertIn(("app.js", 8, CSRF), got) # state change, reported at its last statement + self.assertNotIn(("app.js", 12, CSRF), got) # token compared in the handler + self.assertFalse([r for r in got if r[1] in (14, 15)]) # /api realm sets no cookie + self.assertIn(("app.js", 3, FLAGS), got) + self.assertIn(("app.js", 22, FLAGS), got) # httpOnly alone still lacks secure and sameSite + self.assertFalse([r for r in got if r[1] in (18, 19)]) # every flag set + + def test_go_wrapped_handler_is_followed_to_the_inner_function(self): + go = ["package main", "", "func requireCookie(h http.HandlerFunc) http.HandlerFunc {", + "\treturn func(w http.ResponseWriter, r *http.Request) {", "\t\tif _, err := r.Cookie(\"sid\"); err != nil {", "\t\t\treturn", "\t\t}", + "\t\th(w, r)", "\t}", "}", "", "func changeEmail(w http.ResponseWriter, r *http.Request) {", "\t_ = r.FormValue(\"email\")", "\tw.Write(nil)", "}", "", + "func start(w http.ResponseWriter, r *http.Request) {", + "\thttp.SetCookie(w, &http.Cookie{Name: \"sid\", Value: \"x\", Path: \"/\", HttpOnly: true})", "}", "", + "func routes(mux *http.ServeMux) {", "\tmux.HandleFunc(\"POST /web/account/email\", requireCookie(changeEmail))", "\tmux.HandleFunc(\"GET /web/session/start\", start)", "}"] + got = rows({"main.go": go}) + self.assertIn(("main.go", 14, CSRF), got) + self.assertIn(("main.go", 18, FLAGS), got) + + def test_flask_and_django(self): + py = ["from flask import Blueprint, make_response", "bp = Blueprint('x', __name__)", "@bp.get('/web/start')", "def start():", + " resp = make_response('', 204)", " resp.set_cookie('sid', 'x')", " return resp", "@bp.post('/web/email')", "def email():", " return '', 204"] + self.assertEqual([("a.py", 6, FLAGS), ("a.py", 10, CSRF)], rows({"a.py": py})) + dj = ["from django.views.decorators.csrf import csrf_exempt", "from django.views.decorators.http import require_http_methods", "def start(request):", + " r = HttpResponse()", " r.set_cookie('sid', 'x', secure=True, httponly=True, samesite='Lax')", " return r", "@csrf_exempt", + "@require_http_methods(['POST'])", "def change(request):", " return HttpResponse(status=204)", "@require_http_methods(['POST'])", "def ok(request):", " return HttpResponse(status=204)"] + urls = ["from django.urls import path", "from . import v", "urlpatterns = [\n path('web/start', v.start),\n path('web/change', v.change),\n path('web/ok', v.ok),\n]"] + got = rows({"v.py": dj, "urls.py": urls, "settings.py": ["MIDDLEWARE = ['django.middleware.csrf.CsrfViewMiddleware']"]}) + self.assertEqual([("v.py", 10, CSRF)], got) # exempt: flagged despite the middleware; the other POST is covered; every cookie flag is set + + def test_spring_cookie_var_and_header(self): + j = ["class C {", " @GetMapping(\"/web/start\")", " void start(HttpServletResponse resp) {", " Cookie c = new Cookie(\"sid\", \"x\");", " resp.addCookie(c);", + " }", " @GetMapping(\"/web/ok\")", " void ok(HttpServletResponse resp) {", " Cookie c = new Cookie(\"sid\", \"x\");", " c.setSecure(true);", + " c.setHttpOnly(true);", " resp.addHeader(\"Set-Cookie\", c.getName() + \"=\" + c.getValue() + \"; Secure; HttpOnly; SameSite=Strict\");", " }", "}"] + self.assertEqual([("C.java", 5, FLAGS)], rows({"C.java": j})) + + def test_global_csrf_layer_and_public_routes_are_skipped(self): + lib = ["const csurf = require('csurf');"] + login = EXPRESS[:5] + ["router.post('/web/login', (req, res) => {", " res.sendStatus(204);", "});"] + self.assertEqual([("app.js", 3, FLAGS)], rows({"app.js": login})) + self.assertFalse([r for r in rows({"app.js": EXPRESS, "lib.js": lib}) if r[2] == CSRF]) + + def test_usage_and_wiring(self): + p = subprocess.run([sys.executable, "-I", str(SK / "csrf_cookie_map.py")], capture_output=True, text=True) + self.assertEqual((p.returncode, p.stderr), (2, "usage: csrf_cookie_map.py DIR\n")) + env = dict(os.environ, PATH="/usr/bin:/bin") + with tempfile.TemporaryDirectory() as t: + def repo(name, text): + g = Path(t) / name + g.mkdir() + (g / "app.js").write_text(text, encoding="utf-8") + for a in (["init", "-q"], ["add", "-A"], ["-c", "user.email=a@example.com", "-c", "user.name=Acme", "commit", "-qm", "fixture"]): + subprocess.run(["git", "-C", str(g), *a], check=True, capture_output=True, env=env) + return g + + rc = SK / "review_checks.sh" + r = subprocess.run(["bash", str(rc), "--full", "--repo", str(repo("g", "\n".join(EXPRESS) + "\n"))], capture_output=True, text=True, env=env) + got = [(x["file"], x["line"], x["rule"]) for x in json.loads(r.stdout) if x["tool"] == "csrf-cookie"] + self.assertEqual([("app.js", 3, FLAGS), ("app.js", 8, CSRF), ("app.js", 22, FLAGS)], sorted(got, key=lambda g: g[1])) + r = subprocess.run(["bash", str(rc), "--full", "--repo", str(repo("g2", "export const a = 1;\n"))], capture_output=True, text=True, env=env) + self.assertIn("csrf-cookie (SKIPPED: no HTTP handler or cookie)", r.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test_csrf_cookie_review.py b/scripts/test_csrf_cookie_review.py new file mode 100644 index 000000000..ea5cacf26 --- /dev/null +++ b/scripts/test_csrf_cookie_review.py @@ -0,0 +1,76 @@ +"""csrf_cookie_map.py review fixes: Spring csrf disable beats the security cover, Django csrf_exempt without a method check is a POST, an unchecked Origin read is no defence, +only session-named cookies make a cookie realm, csrf-named or variable-option cookies get no flags row, and an all-SameSite session cookie set covers CSRF. Fictional fixtures. +DCR_SCRIPTS= runs the same checks against another copy of the scripts (used to prove each check fails before the fix).""" +import os +import sys +import tempfile +import unittest +from pathlib import Path + +sys.dont_write_bytecode = True +SK = Path(os.environ.get("DCR_SCRIPTS") or Path(__file__).resolve().parent.parent / ".claude/skills/deep-code-review/scripts") +sys.path.insert(0, str(SK)) +import csrf_cookie_map as C # noqa: E402 + +CSRF, FLAGS = "missing-csrf-protection", "missing-cookie-flags" + + +def rows(files): + """(file, line, rule) rows for a fresh temp repo built from {relative path: text}.""" + with tempfile.TemporaryDirectory() as t: + for rel, text in files.items(): + p = Path(t) / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(text, encoding="utf-8") + return [(f, ln, r) for f, ln, r, _ in C.analyze(t)[0]] + + +def rules(files, rule): + return [r for r in rows(files) if r[2] == rule] + + +CTRL = '@RestController class C { @PostMapping("/x") public String x(HttpSession s){ s.setAttribute("a",1); return "ok"; } }\n' +CHAIN = "@Configuration class S { @Bean SecurityFilterChain f(HttpSecurity http) throws Exception { http.csrf(%s); return http.build(); } }\n" + + +class Review(unittest.TestCase): + def test_spring_disable_lambda_and_method_ref_beat_cover_in_any_file_order(self): + for arg in ("c -> c.disable()", "AbstractHttpConfigurer::disable"): + for first, second in (("A.java", "B.java"), ("B.java", "A.java")): + files = {first: CHAIN % arg, second: CTRL, "pom.xml": "spring-boot-starter-security\n"} + self.assertEqual(len(rules(files, CSRF)), 1, (arg, first)) + + def test_spring_security_without_disable_still_covers(self): + self.assertEqual(rules({"A.java": CHAIN % "Customizer.withDefaults()", "B.java": CTRL}, CSRF), []) + + def test_pom_marker_alone_is_no_cover(self): + self.assertEqual(len(rules({"B.java": CTRL, "pom.xml": "spring-boot-starter-security\n"}, CSRF)), 1) + + def test_django_csrf_exempt_any_method_counts_as_post(self): + files = {"settings.py": "MIDDLEWARE=['django.middleware.csrf.CsrfViewMiddleware']\n", "urls.py": "from . import views\nurlpatterns=[path('pay/', views.pay)]\n", + "views.py": "@csrf_exempt\ndef pay(request):\n request.session['a']=1\n return None\n"} + self.assertEqual(len(rules(files, CSRF)), 1) + + def test_origin_read_without_compare_is_flagged_and_compare_is_a_defence(self): + head = "app.post('/api/pay',(req,res)=>{ %s res.json({}); });\napp.get('/api/s',(req,res)=>{ res.cookie('sid', s, opts); res.json({}); });\n" + self.assertEqual(len(rules({"a.js": head % "const o=req.headers.origin;"}, CSRF)), 1) + self.assertEqual(rules({"a.js": head % "if (req.headers.origin !== HOST) return res.sendStatus(403);"}, CSRF), []) + + def test_theme_cookie_makes_no_realm(self): + js = "app.post('/api/prefs',(req,res)=>{ res.cookie('theme','x'); res.json({}); });\napp.post('/api/items',(req,res)=>{ db.save(req.body); res.json({}); });\n" + self.assertEqual(rules({"a.js": js}, CSRF), []) + self.assertEqual(len(rules({"a.js": js.replace("'theme'", "'sid'")}, CSRF)), 2) + + def test_csrf_named_and_variable_option_cookies_get_no_flags_row(self): + js = "app.get('/c',(req,res)=>{ res.cookie('csrf-token', t); res.cookie('sid', s, opts); res.cookie('sid', s, {...base}); res.json({}); });\n" + self.assertEqual(rules({"a.js": js}, FLAGS), []) + self.assertEqual(len(rules({"a.js": "app.get('/c',(req,res)=>{ res.cookie('sid', s); res.json({}); });\n"}, FLAGS)), 1) + + def test_samesite_on_every_session_cookie_covers_csrf_but_one_lax_gap_does_not(self): + h = "app.post('/api/a',(req,res)=>{ db.save(1); res.json({}); });\napp.get('/api/l',(req,res)=>{ res.cookie('sid', s, { secure: true, httpOnly: true, sameSite: 'strict' });%s res.json({}); });\n" + self.assertEqual(rules({"a.js": h % ""}, CSRF), []) + self.assertEqual(len(rules({"a.js": h % " res.cookie('admin_sid', s, { secure: true });"}, CSRF)), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test_csrf_cookie_round2.py b/scripts/test_csrf_cookie_round2.py new file mode 100644 index 000000000..782f7c0ea --- /dev/null +++ b/scripts/test_csrf_cookie_round2.py @@ -0,0 +1,63 @@ +"""csrf_cookie_map.py round-2 fixes: an Origin compare against undefined/null is no defence, only session-named cookies give SameSite cover, two path() calls on one line +each map to their own view, a commented-out csrf disable does not count, and a dense one-line Spring class anchors the lead on the right handler. Fictional fixtures. +DCR_SCRIPTS= runs the checks against another copy of the scripts (used to prove each check fails before the fix).""" +import sys +import tempfile +import unittest +from pathlib import Path + +sys.dont_write_bytecode = True +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from test_csrf_cookie_review import CHAIN, CSRF, rows, rules # noqa: E402 +import attempt_limit_map as A # noqa: E402 + + +class Round2(unittest.TestCase): + def test_origin_compared_with_undefined_or_null_is_no_defence(self): + h = "app.post('/api/pay',(req,res)=>{ %s res.json({}); });\napp.get('/api/s',(req,res)=>{ res.cookie('sid', s, opts); res.json({}); });\n" + for bad in ("if (req.headers.origin !== undefined) ok();", "if (req.headers.origin === null) no();"): + self.assertEqual(len(rules({"a.js": h % bad}, CSRF)), 1, bad) + self.assertEqual(rules({"a.js": h % "if (req.headers.origin !== 'https://app.example.com') return;"}, CSRF), []) + self.assertEqual(rules({"a.js": h % "if (!ALLOWED.includes(req.headers.origin)) return;"}, CSRF), []) + + def test_samesite_cover_needs_a_session_named_cookie(self): + js = ("app.get('/p',(req,res)=>{ res.cookie('theme','x',{ sameSite: 'lax' }); res.json({}); });\n" + "app.post('/api/a',(req,res)=>{ const s = req.cookies.sid; db.save(s); res.json({}); });\n") + self.assertEqual(len(rules({"a.js": js}, CSRF)), 1) + self.assertEqual(rules({"a.js": js.replace("'theme'", "'sid'").replace("{ sameSite: 'lax' }", "{ secure: true, httpOnly: true, sameSite: 'lax' }")}, CSRF), []) + + def test_two_path_calls_on_one_line_map_to_their_own_view(self): + with tempfile.TemporaryDirectory() as t: + Path(t, "urls.py").write_text("urlpatterns=[path('pay/',views.pay), path('o/',views.other)]\n") + Path(t, "views.py").write_text("def pay(request):\n return 1\n\ndef other(request):\n return 2\n") + got = {u[3]: u[0] for u in A.units(t, {}, True)["views.py"]} + self.assertEqual(got, {"/pay": 1, "/o": 4}) + + def test_commented_disable_does_not_remove_the_cover(self): + ctrl = '@RestController class C { @PostMapping("/x") public String x(HttpSession s){ s.setAttribute("a",1); return "ok"; } }\n' + files = {"A.java": "// http.csrf(c -> c.disable());\n" + CHAIN % "Customizer.withDefaults()", "B.java": ctrl} + self.assertEqual(rules(files, CSRF), []) + + def test_dense_spring_class_anchors_on_the_third_handler(self): + j = ('@RestController class C {\n' + ' @PostMapping("/a") public String a(HttpSession s){ s.setAttribute("a",1); return http.csrf(); }\n' + ' @PostMapping("/b") public String b(HttpSession s){ s.setAttribute("b",1); return csrfOk(); }\n' + ' @PostMapping("/c") public String c(HttpServletRequest r){ r.getSession(); r.getHeader("Origin"); return "ok"; }\n}\n') + with tempfile.TemporaryDirectory() as t: + Path(t, "C.java").write_text(j) + got = [(r[1], r[3]) for r in __import__("csrf_cookie_map").analyze(t)[0]] + self.assertEqual([(ln, "/c" in m) for ln, m in got], [(4, True)]) + + def test_multiline_annotation_with_open_brace_stays_in_its_handler(self): + for ann, first in (('@RolesAllowed({\n "A","B"})', 3), ('@ApiResponses(value = {\n @ApiResponse(code = 200)\n})', 3)): + j = ('@RestController class C {\n @PostMapping("/one") public String one(){ return "1"; }\n %s\n @PostMapping("/doc") public String doc(){ return "2"; }\n}\n') % ann + with tempfile.TemporaryDirectory() as t: + Path(t, "C.java").write_text(j) + us = A.units(t, {}, True)["C.java"] + by = {u[3]: u for u in us} + self.assertEqual(by["/doc"][0], 3, ann) + self.assertEqual(by["/one"][1], 2, ann) + + +if __name__ == "__main__": + unittest.main()