diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-16 16:36:35 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-16 16:36:35 +0000 |
| commit | d6b6f0bbab91d36963deef987a22e5ae457534f7 (patch) | |
| tree | e49bb4632f8ad402b88d12b97542786c5f05450b /plugins | |
| parent | ea10b213686c90bb1984b2016937310e05336cf3 (diff) | |
security-guidance: skip an unusable security-patterns file on its ownmhegazy/sg-patterns-file-shape
A security-patterns file that parsed to a list or a scalar, was not UTF-8, or held a non-list patterns value raised inside the loader, and every user rule from every location was dropped with only a debug-log line. Each file is now read on its own: an unusable one is skipped and logged, and the rules from the other locations still load.
Refs anthropics/claude-code#87627
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/extensibility.py | 61 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_patterns_file_shape.py | 116 |
2 files changed, 167 insertions, 10 deletions
diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py index cb3e0a8d..ed332c99 100644 --- a/plugins/security-guidance/hooks/extensibility.py +++ b/plugins/security-guidance/hooks/extensibility.py @@ -175,13 +175,16 @@ def _load_user_patterns(cwd: Optional[str]) -> List[Dict[str, Any]]: # try each supported extension. for ext in (".yaml", ".yml", ".json"): candidate = path + ext - data = _read_config(candidate) - if data is None: + # One unusable file is skipped on its own, so the rules from the + # other locations still load. + try: + found = _rules_from_file(candidate, label) + except Exception as e: + debug_log(f"extensibility: skipping {candidate}: {type(e).__name__}: {e}") continue - for entry in (data or {}).get("patterns", []): - rule = _validate_pattern(entry, source=label) - if rule: - rules.append(rule) + if found is None: + continue + rules.extend(found) break # found one extension; don't double-load .yaml AND .json if len(rules) >= PATTERN_MAX_RULES: break @@ -191,8 +194,32 @@ def _load_user_patterns(cwd: Optional[str]) -> List[Dict[str, Any]]: return rules +def _rules_from_file(path: str, label: str) -> Optional[List[Dict[str, Any]]]: + """The valid rules in one config file, or None when the file is missing + or does not hold a mapping with a ``patterns`` list.""" + data = _read_config(path) + if data is None: + return None + entries = data.get("patterns", []) + if entries is None: + entries = [] + if not isinstance(entries, list): + debug_log( + f"extensibility: skipping {path}: 'patterns' must be a list, " + f"got {type(entries).__name__}" + ) + return None + rules = [] + for entry in entries: + rule = _validate_pattern(entry, source=label) + if rule: + rules.append(rule) + return rules + + def _read_config(path: str) -> Optional[Dict[str, Any]]: - """Read a YAML or JSON config file. Returns None on missing/malformed.""" + """Read a YAML or JSON config file. Returns None on missing/malformed, + and when the file parses to something other than a mapping.""" try: with open(path, encoding="utf-8") as f: raw = f.read() @@ -202,7 +229,7 @@ def _read_config(path: str) -> Optional[Dict[str, Any]]: return None if path.endswith(".json"): try: - return json.loads(raw) + return _mapping_or_none(path, json.loads(raw)) except ValueError as e: debug_log(f"extensibility: skipping {path}: invalid JSON: {e}") return None @@ -213,12 +240,26 @@ def _read_config(path: str) -> Optional[Dict[str, Any]]: debug_log(f"extensibility: skipping {path}: PyYAML not installed (use .json)") return None try: - return yaml.safe_load(raw) + return _mapping_or_none(path, yaml.safe_load(raw)) except yaml.YAMLError as e: # type: ignore debug_log(f"extensibility: skipping {path}: invalid YAML: {e}") return None +def _mapping_or_none(path: str, data: Any) -> Optional[Dict[str, Any]]: + """A config file must hold a mapping. A scalar or a list is valid YAML or + JSON too (e.g. the pattern list written without its ``patterns:`` key); + skip that one file so the other locations still load.""" + if isinstance(data, dict): + return data + if data is not None: + debug_log( + f"extensibility: skipping {path}: expected a mapping, " + f"got {type(data).__name__}" + ) + return None + + def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]: """Validate one user pattern entry. Returns a rule dict in the same shape as the built-in SECURITY_PATTERNS, or None if invalid (logged).""" @@ -250,7 +291,7 @@ def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]: try: rule["regex"] = regex re.compile(regex) - except re.error as e: + except (re.error, OverflowError, RecursionError) as e: debug_log(f"extensibility: skipping {name}: invalid regex: {e}") return None diff --git a/plugins/security-guidance/tests/test_patterns_file_shape.py b/plugins/security-guidance/tests/test_patterns_file_shape.py new file mode 100644 index 00000000..a63494b6 --- /dev/null +++ b/plugins/security-guidance/tests/test_patterns_file_shape.py @@ -0,0 +1,116 @@ +"""A security-patterns file that parses to something other than a mapping is +skipped on its own; rules from the other locations still load.""" +import json + +import pytest + +import extensibility + +from conftest import run_hook + +VALID = {"patterns": [{"rule_name": "demo_rule", "regex": "AKIA[0-9A-Z]{16}", + "reminder": "DEMO_RULE_REMINDER"}]} + + +@pytest.fixture +def project(tmp_path, monkeypatch): + home = tmp_path / "home" + home.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) + monkeypatch.setattr(extensibility, "_user_patterns", []) + monkeypatch.setattr(extensibility, "_guidance_block", "") + proj = tmp_path / "proj" + (proj / ".claude").mkdir(parents=True) + (proj / ".claude" / "security-patterns.json").write_text(json.dumps(VALID)) + return proj + + +def loaded(proj): + extensibility.load_for_session(str(proj)) + return [r["ruleName"] for r in extensibility.user_patterns()] + + +def rule(name="x", **kw): + return dict(VALID["patterns"][0], rule_name=name, **kw) + + +WRONG_SHAPE_JSON = [ + json.dumps([rule()]), + "5", + '"just a string"', + '{"patterns": 5}', + '{"patterns": "demo"}', + '{"patterns": {"rule_name": "x"}}', + '{"patterns": {}}', + '{"patterns": null}', + "{not json", + json.dumps({"patterns": [rule(regex="a{99999999999}")]}), +] + + +@pytest.mark.parametrize("body", WRONG_SHAPE_JSON) +def test_wrong_shape_local_json_keeps_the_project_rules(project, body): + (project / ".claude" / "security-patterns.local.json").write_text(body) + assert loaded(project) == ["user:demo_rule"] + + +@pytest.mark.parametrize("body", [ + "just a bare scalar\n", + "- rule_name: x\n regex: a\n reminder: r\n", + "patterns: 5\n", + "a: [1\n", + "when: 2001-13-45\n", +]) +def test_wrong_shape_local_yaml_keeps_the_project_rules(project, body): + pytest.importorskip("yaml") + (project / ".claude" / "security-patterns.local.yaml").write_text(body) + assert loaded(project) == ["user:demo_rule"] + + +def test_file_that_is_not_utf8_keeps_the_project_rules(project): + body = json.dumps({"patterns": [rule("local_rule")]}).encode("utf-16") + (project / ".claude" / "security-patterns.local.json").write_bytes(body) + assert loaded(project) == ["user:demo_rule"] + + +@pytest.mark.parametrize("body", ["- a\n- b\n", "patterns: 5\n"]) +def test_unusable_yaml_does_not_hide_the_json_next_to_it(project, body): + pytest.importorskip("yaml") + (project / ".claude" / "security-patterns.yaml").write_text(body) + assert loaded(project) == ["user:demo_rule"] + + +def test_one_bad_rule_does_not_drop_the_rest_of_its_file(project): + local = {"patterns": [rule("bad", regex="a{99999999999}"), rule("local_rule")]} + (project / ".claude" / "security-patterns.local.json").write_text(json.dumps(local)) + assert loaded(project) == ["user:demo_rule", "user:local_rule"] + + +def test_rules_from_a_valid_local_file_still_load(project): + local = {"patterns": [rule("local_rule")]} + (project / ".claude" / "security-patterns.local.json").write_text(json.dumps(local)) + assert loaded(project) == ["user:demo_rule", "user:local_rule"] + + +def test_wrong_shape_file_is_named_in_the_debug_log(project, monkeypatch): + lines = [] + monkeypatch.setattr(extensibility, "debug_log", lines.append) + (project / ".claude" / "security-patterns.local.json").write_text("[1, 2]") + assert loaded(project) == ["user:demo_rule"] + assert any("security-patterns.local.json" in l and "got list" in l for l in lines) + + +def test_edit_hook_still_warns_with_a_wrong_shape_file_present(project, hook_env): + (project / ".claude" / "security-patterns.local.json").write_text("[1, 2]") + env = dict(hook_env, HOME=str(project.parent / "home"), CLAUDE_PROJECT_DIR=str(project)) + env.pop("CLAUDE_CONFIG_DIR", None) + payload = { + "session_id": "s1", "hook_event_name": "PostToolUse", "tool_name": "Write", + "tool_input": {"file_path": str(project / "cfg.py"), + "content": "KEY = 'AKIAABCDEFGHIJKLMNOP'\n"}, + "cwd": str(project), "tool_response": {}, + } + _rc, stdout, stderr = run_hook(payload, env) + assert "DEMO_RULE_REMINDER" in stdout + stderr |
