Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions schema/rules.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
"minimum": 1,
"description": "Format version of this file; absent means 1. becwright refuses a file stamped newer than it understands."
},
"global_exclude": {
"type": "array",
"items": { "type": "string", "minLength": 1 },
"description": "Global glob patterns of files to exclude from all file-based rules."
},
"rules": {
"type": "array",
"description": "The rules (BECs) enforced on every commit.",
Expand Down
16 changes: 13 additions & 3 deletions src/becwright/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def is_advisory(self) -> bool:
return self.severity == "advisory"


def _to_rule(raw: dict) -> Rule:
def _to_rule(raw: dict, global_exclude: list[str] | None = None) -> Rule:
if not isinstance(raw, dict):
raise RulesError(f"each rule must be a mapping, got {type(raw).__name__}.")
for field in ("id", "check"):
Expand All @@ -60,11 +60,16 @@ def _to_rule(raw: dict) -> Rule:
f"rule '{raw['id']}': invalid target {target!r} "
f"(use one of: {', '.join(_VALID_TARGETS)})."
)

exclude_list = list(raw.get("exclude", []))
if global_exclude:
exclude_list.extend(global_exclude)

return Rule(
id=raw["id"],
paths=tuple(raw.get("paths", [])),
check=raw["check"],
exclude=tuple(raw.get("exclude", [])),
exclude=tuple(exclude_list),
intent=(raw.get("intent") or "").strip(),
why_it_matters=(raw.get("why_it_matters") or "").strip(),
rejected_alternatives=tuple(raw.get("rejected_alternatives", [])),
Expand All @@ -83,7 +88,12 @@ def load_rules(rules_path: Path) -> list[Rule]:
if not isinstance(data, dict) or not isinstance(data.get("rules", []), list):
raise RulesError(f"{rules_path}: expected a top-level 'rules:' list.")
_check_schema_version(data.get("schema_version"), rules_path)
return [_to_rule(r) for r in data["rules"]] if data.get("rules") else []

global_exclude = data.get("global_exclude", [])
if not isinstance(global_exclude, list) or not all(isinstance(x, str) for x in global_exclude):
raise RulesError(f"{rules_path}: global_exclude must be a list of glob patterns.")

return [_to_rule(r, global_exclude) for r in data["rules"]] if data.get("rules") else []
Comment on lines +91 to +96

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Runtime validation should reject empty strings in global_exclude.

The schema enforces "minLength": 1 on each item, but the runtime check at line 93 only validates isinstance(x, str). An empty string glob pattern in global_exclude would pass runtime validation and could match all files, silently disabling every file-based rule. Align the runtime check with the schema contract.

🛡️ Proposed fix
     global_exclude = data.get("global_exclude", [])
-    if not isinstance(global_exclude, list) or not all(isinstance(x, str) for x in global_exclude):
+    if not isinstance(global_exclude, list) or not all(isinstance(x, str) and x for x in global_exclude):
         raise RulesError(f"{rules_path}: global_exclude must be a list of glob patterns.")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
global_exclude = data.get("global_exclude", [])
if not isinstance(global_exclude, list) or not all(isinstance(x, str) for x in global_exclude):
raise RulesError(f"{rules_path}: global_exclude must be a list of glob patterns.")
return [_to_rule(r, global_exclude) for r in data["rules"]] if data.get("rules") else []
global_exclude = data.get("global_exclude", [])
if not isinstance(global_exclude, list) or not all(isinstance(x, str) and x for x in global_exclude):
raise RulesError(f"{rules_path}: global_exclude must be a list of glob patterns.")
return [_to_rule(r, global_exclude) for r in data["rules"]] if data.get("rules") else []
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/becwright/rules.py` around lines 91 - 96, The runtime validation in
rules.py for global_exclude only checks that each item is a string, so empty
glob patterns can slip through despite the schema’s minLength contract. Update
the validation in the rules-loading path that builds global_exclude to reject
empty strings as well, keeping the check aligned with _to_rule and the
surrounding RulesError handling so invalid patterns fail fast before returning
the rule list.



def _check_schema_version(value, rules_path: Path) -> None:
Expand Down
20 changes: 20 additions & 0 deletions tests/test_cli_and_git.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,25 @@ def test_mcp_subcommand_without_extra(monkeypatch):
assert cli.main(["mcp"]) == 2


def test_check_respects_global_exclude(tmp_path, monkeypatch, capsys):
_init_repo(tmp_path)
(tmp_path / ".bec").mkdir()

src_posix = _SRC.as_posix()
check = f'"{sys.executable}" -c "import sys; sys.path.insert(0, \'{src_posix}\'); from becwright.checks.forbid import main; sys.exit(main())" --pattern "breakpoint"'

(tmp_path / ".bec" / "rules.yaml").write_text(
"global_exclude:\n - 'ignored/**'\n"
"rules:\n - id: no-bp\n paths: ['**/*.py']\n"
f" check: |-\n {check}\n severity: blocking\n", encoding="utf-8")

(tmp_path / "ignored").mkdir()
(tmp_path / "ignored" / "app.py").write_text("breakpoint()\n", encoding="utf-8")
_git(tmp_path, "add", "ignored/app.py")

monkeypatch.chdir(tmp_path)
assert cli.main(["check"]) == 0
assert "All good" in capsys.readouterr().out
def test_cli_custom_help(capsys):
assert cli.main([]) == 0
out = capsys.readouterr().out
Expand All @@ -535,3 +554,4 @@ def test_cli_custom_help(capsys):
out2 = capsys.readouterr().out
assert "Usage: becwright" in out2


32 changes: 32 additions & 0 deletions tests/test_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,35 @@ def test_non_positive_schema_version_raises(tmp_path):
path = _write(tmp_path, 'schema_version: 0\nrules:\n - id: r1\n check: "true"\n')
with pytest.raises(RulesError, match="schema_version"):
load_rules(path)


def test_global_exclude_merges_with_rule_exclude(tmp_path):
path = _write(
tmp_path,
'global_exclude:\n - "vendor/**"\n - "build/**"\n'
'rules:\n - id: r1\n check: "true"\n exclude: ["local/exclude.py"]\n'
)
rules = load_rules(path)
assert len(rules) == 1
assert rules[0].exclude == ("local/exclude.py", "vendor/**", "build/**")


def test_global_exclude_not_list_raises(tmp_path):
path = _write(
tmp_path,
'global_exclude: "not-a-list"\n'
'rules:\n - id: r1\n check: "true"\n'
)
with pytest.raises(RulesError, match="global_exclude must be a list"):
load_rules(path)


def test_global_exclude_non_string_elements_raises(tmp_path):
path = _write(
tmp_path,
'global_exclude:\n - 123\n'
'rules:\n - id: r1\n check: "true"\n'
)
with pytest.raises(RulesError, match="global_exclude must be a list"):
load_rules(path)

Loading