Skip to content

Commit a627310

Browse files
mnriemCopilot
andcommitted
Validate native hooks before destructive extension updates
Share installation hook validation with archive preflight so invalid opted-in updates fail before removal. Exercise real archives and prove rejected updates preserve all installed files, YAML bytes and cross-extension hook order; retain legacy opt-out acceptance. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <[email protected]>
1 parent b0e8587 commit a627310

6 files changed

Lines changed: 128 additions & 31 deletions

File tree

‎docs/reference/extensions.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,11 @@ not change execution behavior. For projection portability, missing or invalid
368368
priorities and values above `2147483647` use the default `10`; the current
369369
in-process hook reader retains its existing priority handling.
370370
371+
Update archives receive the same opted-in hook validation as installation
372+
before the installed extension is removed. An archive rejected by this
373+
validation leaves the installed files, hook order, and configuration bytes
374+
unchanged.
375+
371376
Opted-in hook configuration and projection writes are direct, not atomic. If
372377
an I/O error interrupts a write, Spec Kit reports the failure, but
373378
`.specify/extensions.yml` or `.specify/hook-dispatch/` may be incomplete.

‎src/specify_cli/extensions/__init__.py‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2405,20 +2405,11 @@ def install_from_directory(
24052405
# Load and validate manifest
24062406
manifest_path = source_dir / "extension.yml"
24072407
manifest = ExtensionManifest(manifest_path)
2408-
from ._hook_projection import projection_enabled, project_hooks
2408+
from ._hook_projection import projection_enabled, validate_manifest_hooks
24092409

24102410
native_hooks = projection_enabled(self.project_root)
24112411
if native_hooks:
2412-
try:
2413-
project_hooks({"hooks": {
2414-
event: [
2415-
{**entry, "extension": manifest.id}
2416-
for entry in coerce_hook_entries(entries)
2417-
]
2418-
for event, entries in manifest.hooks.items()
2419-
}})
2420-
except ValueError as exc:
2421-
raise ValidationError(f"Invalid manifest hooks: {exc}") from exc
2412+
validate_manifest_hooks(manifest)
24222413
HookExecutor(self.project_root).load_project_config_for_update()
24232414

24242415
# Check compatibility

‎src/specify_cli/extensions/_command_update_artifacts.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ def preflight_update_archive(
4949
) -> PreflightResult:
5050
"""Validate an update archive before the installed extension is modified."""
5151
from . import ExtensionManifest
52+
from ._hook_projection import projection_enabled, validate_manifest_hooks
5253

5354
with tempfile.TemporaryDirectory(
5455
prefix="speckit-update-archive-"
@@ -135,6 +136,8 @@ def preflight_update_archive(
135136
manifest_file = Path(manifest_tmpdir) / "extension.yml"
136137
manifest_file.write_bytes(manifest_bytes)
137138
preflight_manifest = ExtensionManifest(manifest_file)
139+
if projection_enabled(manager.project_root):
140+
validate_manifest_hooks(preflight_manifest)
138141
manager.check_compatibility(preflight_manifest, speckit_version)
139142

140143
if preflight_manifest.id != extension_id:

‎src/specify_cli/extensions/_hook_projection.py‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,13 @@
1313

1414
from .._init_options import load_init_options
1515
from ..integrations._file_changes import changing_file, unlink, write_bytes
16-
from . import DEFAULT_HOOK_PRIORITY, normalize_priority
16+
from . import (
17+
DEFAULT_HOOK_PRIORITY,
18+
ExtensionManifest,
19+
ValidationError,
20+
coerce_hook_entries,
21+
normalize_priority,
22+
)
1723

1824
_EVENT = re.compile(r"(before|after)_[a-z0-9][a-z0-9_]*\Z")
1925

@@ -106,6 +112,20 @@ def project_hooks(config: dict[str, Any]) -> dict[str, bytes]:
106112
return projected
107113

108114

115+
def validate_manifest_hooks(manifest: ExtensionManifest) -> None:
116+
"""Validate manifest hooks before an opted-in install or update mutates state."""
117+
try:
118+
project_hooks({"hooks": {
119+
event: [
120+
{**entry, "extension": manifest.id}
121+
for entry in coerce_hook_entries(entries)
122+
]
123+
for event, entries in manifest.hooks.items()
124+
}})
125+
except ValueError as exc:
126+
raise ValidationError(f"Invalid manifest hooks: {exc}") from exc
127+
128+
109129
def load_for_update(config_file: Path) -> dict[str, Any]:
110130
"""Reject malformed existing state before extension lifecycle mutations."""
111131
_check_paths(config_file)

‎tests/specify_cli/extensions/test_command_update.py‎

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,10 @@ def _create_catalog_zip(
9696
zf.writestr(extra_manifest_path, manifest_text)
9797

9898
@pytest.mark.parametrize("native_hooks", [False, True])
99-
def test_update_legacy_event_follows_opt_in_mode(self, tmp_path, native_hooks):
99+
@pytest.mark.parametrize("event", ["custom:after", "before_my-extension_assess"])
100+
def test_update_legacy_event_follows_opt_in_mode(self, tmp_path, native_hooks, event):
101+
from specify_cli.extensions._command_update_artifacts import _archive_extension_directory
102+
100103
project = tmp_path / "project"
101104
project.mkdir()
102105
(project / ".specify").mkdir()
@@ -108,43 +111,56 @@ def test_update_legacy_event_follows_opt_in_mode(self, tmp_path, native_hooks):
108111
manager.install_from_directory(
109112
original_source, "0.1.0", catalog_name="original-catalog"
110113
)
111-
original_entry = manager.registry.get("test-ext")
112-
original_config = yaml.safe_load((project / ".specify/extensions.yml").read_text())
114+
executor = HookExecutor(project)
115+
config = executor.load_project_config_for_update()
116+
config["hooks"]["after_tasks"].append({
117+
"extension": "other-ext", "command": "speckit.other-ext.run",
118+
})
119+
executor.save_project_config(config)
120+
executor.config_file.write_bytes(
121+
b"# Preserve hook order and formatting\r\n"
122+
+ executor.config_file.read_bytes().replace(b"\n", b"\r\n")
123+
)
124+
executor.migrate_project_config()
125+
original_files = {
126+
path.relative_to(project): path.read_bytes()
127+
for path in project.rglob("*") if path.is_file()
128+
}
113129
updated_source = self._create_extension_source(tmp_path, "2.0.0")
114130
manifest_path = updated_source / "extension.yml"
115131
manifest = yaml.safe_load(manifest_path.read_text())
116-
manifest["hooks"] = {"custom:after": {"command": "speckit.test-ext.hello"}}
132+
manifest["hooks"] = {event: {"command": "speckit.test-ext.hello"}}
117133
manifest_path.write_text(yaml.safe_dump(manifest))
118-
zip_path = tmp_path / "test-ext-update.zip"
119-
self._create_catalog_zip(zip_path, "2.0.0")
120-
121-
def install_invalid_update(self_obj, _zip_path, version, *, catalog_name=None):
122-
return self_obj.install_from_directory(
123-
updated_source, version, catalog_name=catalog_name
124-
)
134+
zip_path = _archive_extension_directory(updated_source)
125135

126136
with patch.object(Path, "cwd", return_value=project), \
127137
patch.object(ExtensionCatalog, "get_extension_info", return_value={
128138
"id": "test-ext", "name": "Test Extension", "version": "2.0.0",
129139
"_install_allowed": True,
130140
}), \
131141
patch.object(ExtensionCatalog, "download_extension", return_value=zip_path), \
132-
patch.object(ExtensionManager, "install_from_zip", install_invalid_update):
142+
patch.object(
143+
ExtensionManager, "remove", autospec=True,
144+
side_effect=ExtensionManager.remove,
145+
) as remove:
133146
result = CliRunner().invoke(
134147
app, ["extension", "update", "test-ext"], input="y\n"
135148
)
149+
assert not zip_path.exists()
136150
if native_hooks:
137151
assert result.exit_code == 1, result.output
138152
assert "Rename legacy events" in result.output
139-
assert ExtensionManager(project).registry.get("test-ext") == original_entry
140-
assert yaml.safe_load(
141-
(project / ".specify/extensions.yml").read_text()
142-
) == original_config
143-
assert (project / ".specify/hook-dispatch").exists()
153+
remove.assert_not_called()
154+
assert "Rolling back" not in result.output
155+
assert {
156+
path.relative_to(project): path.read_bytes()
157+
for path in project.rglob("*") if path.is_file()
158+
} == original_files
144159
else:
145160
assert result.exit_code == 0, result.output
161+
remove.assert_called_once()
146162
assert ExtensionManager(project).registry.get("test-ext")["version"] == "2.0.0"
147-
assert "custom:after" in yaml.safe_load(
163+
assert event in yaml.safe_load(
148164
(project / ".specify/extensions.yml").read_text()
149165
)["hooks"]
150166
assert not (project / ".specify/hook-dispatch").exists()

‎tests/specify_cli/extensions/test_command_update_artifacts.py‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import yaml
1717
from pathlib import Path
1818

19-
from specify_cli.extensions import ExtensionManager
19+
from specify_cli.extensions import ExtensionManager, ValidationError
2020

2121

2222
def _create_extension_source(
@@ -65,6 +65,68 @@ def _make_project(tmp_path: Path) -> Path:
6565
return project_dir
6666

6767

68+
@pytest.mark.parametrize("field,value", [
69+
("optional", "yes"), ("enabled", "yes"), ("condition", 42),
70+
("description", False), ("prompt", []), ("command", "speckit.test-ext.hello\0"),
71+
])
72+
def test_archive_preflight_rejects_invalid_native_hook_metadata(tmp_path, field, value):
73+
from specify_cli.extensions._command_update_artifacts import (
74+
_archive_extension_directory,
75+
preflight_update_archive,
76+
)
77+
from tests.specify_cli.extensions._helpers import enable_native_hooks
78+
79+
project = _make_project(tmp_path)
80+
enable_native_hooks(project)
81+
source = _create_extension_source(tmp_path)
82+
manifest_path = source / "extension.yml"
83+
manifest = yaml.safe_load(manifest_path.read_text(encoding="utf-8"))
84+
manifest["hooks"] = {"after_tasks": {
85+
"command": "speckit.test-ext.hello", "enabled": False, field: value,
86+
}}
87+
manifest_path.write_text(yaml.safe_dump(manifest), encoding="utf-8")
88+
archive_path = _archive_extension_directory(source)
89+
try:
90+
with pytest.raises(ValidationError, match="Invalid manifest hooks"):
91+
preflight_update_archive(
92+
ExtensionManager(project), archive_path, "test-ext", "1.0.0", "0.1.0"
93+
)
94+
finally:
95+
archive_path.unlink()
96+
assert not (project / ".specify/extensions/test-ext").exists()
97+
assert not (project / ".specify/hook-dispatch").exists()
98+
99+
100+
@pytest.mark.parametrize("enabled", [False, True])
101+
def test_archive_preflight_accepts_valid_native_hooks_without_publication(tmp_path, enabled):
102+
from specify_cli.extensions._command_update_artifacts import (
103+
_archive_extension_directory,
104+
preflight_update_archive,
105+
)
106+
from tests.specify_cli.extensions._helpers import enable_native_hooks
107+
108+
project = _make_project(tmp_path)
109+
enable_native_hooks(project)
110+
source = _create_extension_source(tmp_path)
111+
manifest_path = source / "extension.yml"
112+
manifest = yaml.safe_load(manifest_path.read_text(encoding="utf-8"))
113+
manifest["hooks"] = {"after_tasks": [{
114+
"command": "speckit.test-ext.hello", "enabled": enabled, "optional": False,
115+
}]}
116+
manifest_path.write_text(yaml.safe_dump(manifest), encoding="utf-8")
117+
archive_path = _archive_extension_directory(source)
118+
try:
119+
result = preflight_update_archive(
120+
ExtensionManager(project), archive_path, "test-ext", "1.0.0", "0.1.0"
121+
)
122+
finally:
123+
archive_path.unlink()
124+
assert result.command_names == ["speckit.test-ext.hello"]
125+
assert result.skill_names == ["speckit-test-ext-hello"]
126+
assert not (project / ".specify/extensions.yml").exists()
127+
assert not (project / ".specify/hook-dispatch").exists()
128+
129+
68130
class TestArchiveExtensionDirectory:
69131
def test_archive_contains_regular_files_only(self, tmp_path):
70132
import zipfile

0 commit comments

Comments
 (0)