Skip to content

💫 Toolkit to help you get started with SDD or any other process!

fix: validate collected extension events (#5133)

Danny Wardae5f7500f6e1
diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py
index c397d980a..47f86a5cb 100644
--- a/src/specify_cli/events/__init__.py
+++ b/src/specify_cli/events/__init__.py
@@ -875,12 +875,12 @@ ResolvedEvents = dict[str, list[dict[str, Any]]]
def _normalize_handlers(value: Any) -> list[dict[str, Any]]:
- """Coerce a single handler config or a list of them into a validated list.
+ """Coerce a single handler config or a list of them into a list of mappings.
Accepts both the legacy single-mapping shape (``{command: ...}``) and the
- explicit list shape (``[{command: ...}, ...]``). Drops any entry that is
- not a mapping or lacks a ``command`` with a warning, so a malformed user
- override never reaches installation and crashes on ``cfg.get(...)`` (#21).
+ explicit list shape (``[{command: ...}, ...]``). Drops entries that are
+ not mappings with a warning. The remaining handlers require validation by
+ the caller before installation.
"""
if isinstance(value, dict):
value = [value]
@@ -916,16 +916,15 @@ def _validate_resolved_event(event_name: str, handlers: list[dict[str, Any]]) ->
f"Event '{event_name}' handler missing required non-empty 'command' string"
)
# C10: matcher must be a string (or absent). A non-string matcher such
- # as `matcher: []` passes extension validation but later crashes
- # by_matcher.setdefault(matcher, ...) with TypeError: unhashable type.
+ # as `matcher: []` later crashes by_matcher.setdefault with TypeError.
matcher = handler.get("matcher")
- if matcher is not None and not isinstance(matcher, str):
+ if "matcher" in handler and not isinstance(matcher, str):
raise ValidationError(
f"Event '{event_name}' handler has invalid 'matcher': "
"must be a string"
)
timeout = handler.get("timeout")
- if timeout is not None:
+ if "timeout" in handler:
if not isinstance(timeout, int) or isinstance(timeout, bool) or timeout <= 0:
raise ValidationError(
f"Event '{event_name}' handler has invalid 'timeout': must be a positive integer"
@@ -1093,7 +1092,7 @@ def collect_extension_events(project_root: Path) -> ResolvedEvents:
obsolete name and ``_find_command_template`` could not match it, leaving
the hook silently inert.
"""
- from ..extensions import ExtensionManager
+ from ..extensions import ExtensionManager, ValidationError
events: ResolvedEvents = {}
exts_dir = project_root / ".specify" / "extensions"
@@ -1147,8 +1146,18 @@ def collect_extension_events(project_root: Path) -> ResolvedEvents:
continue
for event, config in runtime.items():
handlers = _normalize_handlers(config)
- if handlers:
- events.setdefault(event, []).extend(handlers)
+ for handler in handlers:
+ try:
+ _validate_resolved_event(event, [handler])
+ except ValidationError as exc:
+ logger.warning(
+ "Extension %s: skipping invalid event handler for '%s': %s",
+ ext_id,
+ event,
+ exc,
+ )
+ continue
+ events.setdefault(event, []).append(handler)
return events
@@ -1932,12 +1941,12 @@ def validate_events(data: dict[str, Any]) -> None:
# C10: matcher must be a string (or absent). A non-string matcher
# such as `matcher: []` would later crash by_matcher.setdefault.
matcher = event_config.get("matcher")
- if matcher is not None and not isinstance(matcher, str):
+ if "matcher" in event_config and not isinstance(matcher, str):
raise ValidationError(
f"Event '{event_name}' has invalid 'matcher': must be a string"
)
timeout = event_config.get("timeout")
- if timeout is not None:
+ if "timeout" in event_config:
if not isinstance(timeout, int) or isinstance(timeout, bool) or timeout <= 0:
raise ValidationError(
f"Event '{event_name}' has invalid 'timeout': must be a positive integer"
diff --git a/tests/specify_cli/events/test_events.py b/tests/specify_cli/events/test_events.py
index bd78cabd9..9c2d07aa6 100644
--- a/tests/specify_cli/events/test_events.py
+++ b/tests/specify_cli/events/test_events.py
@@ -176,6 +176,38 @@ class TestCollectExtensionEvents:
result = collect_extension_events(tmp_path)
assert result == {"pre_tool_use": [{"command": "speckit.my-ext.check"}]}
+ @pytest.mark.parametrize(
+ "invalid",
+ [
+ {"command": "speckit.bad.check", "matcher": ["Bash"]},
+ {"command": "speckit.bad.check", "timeout": "30"},
+ {"command": "speckit.bad.check", "timeout": None},
+ {"command": "speckit.bad.check", "matcher": None},
+ {"matcher": "Bash"},
+ ],
+ ids=["matcher-list", "timeout-string", "timeout-null", "matcher-null", "missing-command"],
+ )
+ def test_unregistered_invalid_handler_does_not_break_install(self, tmp_path, caplog, invalid):
+ ext_dir = tmp_path / ".specify" / "extensions" / "staged"
+ ext_dir.mkdir(parents=True)
+ valid = {"command": "speckit.staged.check", "matcher": "Bash"}
+ (ext_dir / "extension.yml").write_text(
+ json.dumps({"events": {"pre_tool_use": [invalid, valid]}}), encoding="utf-8"
+ )
+
+ resolved = resolve_events("claude", None, tmp_path, None)
+ manifest = MagicMock(spec=IntegrationManifest)
+ manifest.files = {}
+ install_integration_events(ClaudeIntegration(), tmp_path, manifest, resolved)
+
+ assert resolved == {"pre_tool_use": [valid]}
+ config = json.loads((tmp_path / ".claude" / "settings.json").read_text(encoding="utf-8"))
+ hooks = config["hooks"]["PreToolUse"][0]["hooks"]
+ assert len(hooks) == 1
+ assert "speckit.staged.check" in hooks[0]["command"]
+ assert "staged" in caplog.text
+ assert "pre_tool_use" in caplog.text
+
def test_invalid_yaml_skipped(self, tmp_path):
ext_dir = tmp_path / ".specify" / "extensions" / "my-ext"
ext_dir.mkdir(parents=True)
@@ -344,6 +376,14 @@ class TestEventCapableOptionsComposition:
class TestValidateEvents:
"""Test manifest validation."""
+ @pytest.mark.parametrize("field", ["matcher", "timeout"])
+ def test_null_optional_handler_field_rejected(self, field):
+ from specify_cli.extensions import ValidationError
+
+ data = {"events": {"pre_tool_use": {"command": "speckit.test", field: None}}}
+ with pytest.raises(ValidationError, match=field):
+ validate_events(data)
+
def test_unknown_event_rejected(self):
from specify_cli.extensions import ValidationError
data = {"events": {"unknown_event": {"command": "speckit.tdd.validate"}}}
diff --git a/tests/specify_cli/integrations/test_command_upgrade.py b/tests/specify_cli/integrations/test_command_upgrade.py
index 979bb5a29..5f42870d0 100644
--- a/tests/specify_cli/integrations/test_command_upgrade.py
+++ b/tests/specify_cli/integrations/test_command_upgrade.py
@@ -27,6 +27,36 @@ from tests.specify_cli.integrations._helpers import (
)
class TestIntegrationUpgradeDetailed:
+ @pytest.mark.parametrize(
+ "bad_handler",
+ [
+ {"command": "speckit.bad.check", "matcher": ["Bash"]},
+ {"command": "speckit.bad.check", "timeout": "30"},
+ ],
+ ids=["matcher-list", "timeout-string"],
+ )
+ def test_upgrade_skips_invalid_unregistered_extension_events(self, tmp_path, caplog, bad_handler):
+ project = _init_project(tmp_path, "claude")
+ for ext_id, handler in (
+ ("bad", bad_handler),
+ ("good", {"command": "speckit.good.check", "matcher": "Bash"}),
+ ):
+ ext_dir = project / ".specify" / "extensions" / ext_id
+ ext_dir.mkdir(parents=True)
+ (ext_dir / "extension.yml").write_text(
+ json.dumps({"events": {"pre_tool_use": handler}}), encoding="utf-8"
+ )
+
+ result = _run_in_project(project, ["integration", "upgrade", "claude", "--force"])
+
+ assert result.exit_code == 0, result.output
+ config = json.loads((project / ".claude" / "settings.json").read_text(encoding="utf-8"))
+ hooks = config["hooks"]["PreToolUse"]
+ commands = [item["command"] for group in hooks for item in group["hooks"]]
+ assert any("speckit.good.check" in command for command in commands)
+ assert all("speckit.bad.check" not in command for command in commands)
+ assert "bad" in caplog.text and "pre_tool_use" in caplog.text
+
@pytest.mark.parametrize("integration", ["claude", "copilot", "gemini"])
@pytest.mark.parametrize("force", [False, True])
def test_disabling_events_honors_modified_dispatcher_force(self, tmp_path, integration, force):