summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-11-12 23:23:59 +0000
committerClaude <noreply@anthropic.com>2026-11-13 00:34:06 +0000
commit2d02bcafc3530606c2f59760eccb14ae08e1c0ce (patch)
tree31ad7e08714a7ac8fdf20cc5efd74b59202e32d4 /plugins
parentf75f5b25ae94f4332be4ff5f18435741d2589bdb (diff)
security-guidance: fewer false edit warnings on ordinary JavaScriptmhegazy/sg-fewer-false-pattern-warnings
Four edit rules matched their word without looking at what stands next to it: - eval: Playwright's and Puppeteer's page.$eval('selector', function) and $$eval got the eval() warning. They run the function they are given. Left out only when the selector is a plain string and the function is written out in the call. AngularJS scope.$eval(expr) and every other $eval( still warn. - new Function: the whole word is needed, so new FunctionRegistry() is quiet. - innerHTML and outerHTML: an assignment is needed, so == and === are quiet. Nothing warns that did not warn before. Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/patterns.py30
-rw-r--r--plugins/security-guidance/tests/test_pattern_false_positives.py96
2 files changed, 121 insertions, 5 deletions
diff --git a/plugins/security-guidance/hooks/patterns.py b/plugins/security-guidance/hooks/patterns.py
index 46224164..689f9c77 100644
--- a/plugins/security-guidance/hooks/patterns.py
+++ b/plugins/security-guidance/hooks/patterns.py
@@ -48,6 +48,22 @@ def _call_args():
_CALL_ARGS = _call_args()
+
+def _page_function_call():
+ """Regex for Playwright's and Puppeteer's `$eval('selector', function`, read
+ from its "eval(". It runs the function, so nothing is evaluated from a string.
+
+ Both have to be written out in the call: a string with nothing put into it,
+ then a function. AngularJS `scope.$eval(expr)` and any other `$eval(` do not
+ match. Every repeat is bounded.
+ """
+ selector = r"\x22[^\x22\\\n]{0,300}\x22|\x27[^\x27\\\n]{0,300}\x27|`[^`$\\]{0,300}`"
+ arrow = r"(?:[\w$]{1,60}|\([^()]{0,200}\))\s{0,20}(?::[^=\n]{0,60})?=>"
+ return rf"eval\(\s{{0,200}}(?:{selector})\s{{0,20}},\s{{0,200}}(?:async\b\s{{0,20}})?(?:function\b|{arrow})"
+
+
+_PAGE_FUNCTION_CALL = _page_function_call()
+
# Security patterns configuration
SECURITY_PATTERNS = [
{
@@ -119,15 +135,18 @@ Only use exec() if you absolutely need shell features and the input is guarantee
# JS-only construct: gate to JS/TS files so docs/.md and other prose
# mentioning "new Function" don't trip the warning.
"path_filter": lambda p: p.endswith(_JS_EXTS),
- "substrings": ["new Function"],
+ # The whole word: `new FunctionRegistry()` is another class. The two names
+ # code gives to Function itself still count.
+ "regex": r"new Function(?:Constructor|Ctor)?(?![\w$])",
"reminder": "\u26a0\ufe0f Security Warning: Using new Function() with string interpolation is a CODE INJECTION vulnerability. If any variable is concatenated or interpolated into the function body string, an attacker controlling that variable can execute arbitrary code. Use safe alternatives: for property access use obj[key] or array.reduce((o, k) => o[k], root); for computation use a safe expression parser. NEVER interpolate untrusted strings into new Function() bodies.",
},
{
"ruleName": "eval_injection",
# Lookbehind excludes `.` so method calls like PyTorch model.eval(),
- # redis.eval(), spec.eval() don't match. Skip doc/prose files.
+ # redis.eval(), spec.eval() don't match. Playwright's page.$eval('selector',
+ # function) is left out too. Skip doc/prose files.
"path_filter": lambda p: not p.endswith(_DOC_EXTS),
- "regex": r"(?<![a-zA-Z0-9_\.])eval\(",
+ "regex": rf"(?<![a-zA-Z0-9_\.])(?!(?<=\$){_PAGE_FUNCTION_CALL})eval\(",
"reminder": "⚠️ Security Warning: eval() executes arbitrary code and is a major security risk. Use JSON.parse() for data, ast.literal_eval() for Python literals, or a safe expression parser. If this is safe or is explicitly needed, briefly document that in a comment before continuing.",
},
{
@@ -150,7 +169,8 @@ Only use exec() if you absolutely need shell features and the input is guarantee
# docs/example HTML, playground/self-contained skills that hardcode
# innerHTML strings with zero user input (#410).
"path_filter": lambda p: p.endswith(_JS_EXTS),
- "substrings": [".innerHTML =", ".innerHTML="],
+ # An assignment, not a `==` or `===` comparison.
+ "regex": r"\.innerHTML ?=(?!=)",
"reminder": "⚠️ Security Warning: Setting innerHTML with untrusted content can lead to XSS vulnerabilities. Use textContent for plain text or safe DOM methods for HTML content. If you need HTML support, consider using an HTML sanitizer library such as DOMPurify.",
},
{
@@ -253,7 +273,7 @@ Additionally, validate user inputs:
"ruleName": "outerHTML_xss",
# Browser DOM API: only meaningful in JS/TS source.
"path_filter": lambda p: p.endswith(_JS_EXTS),
- "substrings": [".outerHTML =", ".outerHTML="],
+ "regex": r"\.outerHTML ?=(?!=)",
"reminder": "⚠️ Security Warning: Use textContent or sanitize with DOMPurify. outerHTML assignment is an XSS sink equivalent to innerHTML.",
},
{
diff --git a/plugins/security-guidance/tests/test_pattern_false_positives.py b/plugins/security-guidance/tests/test_pattern_false_positives.py
new file mode 100644
index 00000000..5a816bac
--- /dev/null
+++ b/plugins/security-guidance/tests/test_pattern_false_positives.py
@@ -0,0 +1,96 @@
+"""Ordinary code that the edit warnings used to fire on, next to the real uses
+that still have to."""
+import time
+
+import pytest
+
+import security_reminder_hook as hook
+
+EVAL, FUNCTION, INNER, OUTER = (
+ "eval_injection", "new_function_injection", "innerHTML_xss", "outerHTML_xss")
+
+
+def fired(path, content):
+ return [rule for rule, _ in hook.check_patterns(path, content)]
+
+
+QUIET = [
+ ("t.js", "await page.$$eval('.btn', ns => ns.length)\n"),
+ ("t.js", "await page.$eval('#id', e => e.tagName)\n"),
+ ("t.ts", "await page.$eval('a', (el: HTMLLinkElement) => el.href)\n"),
+ ("t.ts", "await page.$eval('a', (el): string => el.href)\n"),
+ ("t.js", "await page.$eval(\n '.row',\n async function (el) { return el.id }\n)\n"),
+ ("t.js", "await frame.$$eval(`.row a`, (els, min) => els.length > min, 3)\n"),
+ ("t.js", "await handle.$eval('[a=\"b\"]', async ({ href }) => href)\n"),
+ ("t.js", "const r = new FunctionRegistry()\n"),
+ ("t.tsx", "const c = new FunctionComponent()\n"),
+ ("t.js", "return new Function_(a)\n"),
+ ("t.js", "if (el.innerHTML === expected) { pass() }\n"),
+ ("t.js", "if (el.innerHTML == expected) { pass() }\n"),
+ ("t.js", "if (el.innerHTML=== expected) { pass() }\n"),
+ ("t.js", "expect(el.outerHTML === golden).toBe(true)\n"),
+]
+
+CAUGHT = [
+ (EVAL, "c.js", "const v = eval(userInput)\n"),
+ (EVAL, "c.py", "v = eval(user_input)\n"),
+ # AngularJS evaluates an expression string, on whatever the scope is called.
+ (EVAL, "c.js", "$scope.$eval(attrs.expr)\n"),
+ (EVAL, "c.js", "scope.$eval(userInput)\n"),
+ (EVAL, "c.js", "this.$eval(expr)\n"),
+ (EVAL, "c.js", "element.scope().$eval(expr)\n"),
+ (EVAL, "c.js", "scope.$parent.$eval(expr, { $event: ev })\n"),
+ (EVAL, "c.js", "scope.$eval(expr, locals)\n"),
+ (EVAL, "c.js", "const $eval = eval; $eval(code)\n"),
+ # A page function given as a string, or by name.
+ (EVAL, "c.js", "await page.$eval('a', 'e => ' + body)\n"),
+ (EVAL, "c.js", "await page.$eval('a', readHref)\n"),
+ # An expression or selector that is not a constant.
+ (EVAL, "c.js", "scope.$eval(expr, () => x)\n"),
+ (EVAL, "c.js", "$eval(code, x => 1)\n"),
+ (EVAL, "c.js", "scope.$eval('cb(' + x + ')', cb => 1)\n"),
+ (EVAL, "c.js", "scope.$eval(`cb(${x})`, cb => 1)\n"),
+ # An eval inside or after the page function call.
+ (EVAL, "c.js", "await page.$eval('a', el => eval(el.dataset.code))\n"),
+ (EVAL, "c.js", "await page.$eval(eval(sel), el => el.id)\n"),
+ (EVAL, "c.js", "await page.$eval('a', el => el.id)\nscope.$eval(expr)\n"),
+ (EVAL, "c.js", "await page.$eval('a', el => el.id)\neval(code)\n"),
+ # The shape only excuses `$eval(`.
+ (EVAL, "c.js", "eval('a', el => el.id)\n"),
+ (FUNCTION, "c.js", "const f = new Function('a', body)\n"),
+ (FUNCTION, "c.js", "const f = new Function ('a', body)\n"),
+ (FUNCTION, "c.ts", "const f = new Function<any>(body)\n"),
+ (FUNCTION, "c.js", "const f = new Function`return 1`\n"),
+ (FUNCTION, "c.js", "Reflect.apply(new Function, null, [])\n"),
+ (FUNCTION, "c.js", "new Function"),
+ (FUNCTION, "c.js", "new FunctionConstructor(body)\n"),
+ (FUNCTION, "c.js", "new FunctionRegistry(); new Function(body)\n"),
+ (INNER, "c.js", "el.innerHTML = html\n"),
+ (INNER, "c.js", "el.innerHTML=html\n"),
+ (INNER, "c.js", "el.innerHTML =\n html\n"),
+ (INNER, "c.js", "el.innerHTML ="),
+ (INNER, "c.js", "if (el.innerHTML === a) el.innerHTML = b\n"),
+ (OUTER, "c.js", "el.outerHTML = html\n"),
+ (OUTER, "c.js", "el.outerHTML=html\n"),
+ (OUTER, "c.js", "if (el.outerHTML !== a && el.outerHTML === c) el.outerHTML = b\n"),
+]
+
+
+@pytest.mark.parametrize("path,content", QUIET)
+def test_ordinary_code_gets_no_warning(path, content):
+ assert fired(path, content) == []
+
+
+@pytest.mark.parametrize("rule,path,content", CAUGHT)
+def test_real_use_still_warns_once(rule, path, content):
+ assert fired(path, content).count(rule) == 1
+
+
+@pytest.mark.parametrize("path,unit", [
+ ("t.js", "$eval("), ("t.js", "$eval('"), ("t.js", "$eval(`"), ("t.js", "$eval('a',("),
+ ("t.js", "$eval('a' "), ("t.js", "$eval('a',(b): "), ("t.js", ".innerHTML "),
+])
+def test_repeated_openings_stay_quick(path, unit):
+ start = time.monotonic()
+ hook.check_patterns(path, unit * (200_000 // len(unit)))
+ assert time.monotonic() - start < 5