Skip to content

Commit 219c013

Browse files
mnriemCopilot
andcommitted
Validate every hook event and align resolver priorities
Reject symlinked extension configuration parents before migration, validate non-target hook fields in native and Python dispatch, and bound priority normalization across all three runtimes. Add negative, ordering, and symlink regressions. Assisted-by: GitHub Copilot (model: GPT-6 Sol, autonomous) Co-authored-by: Copilot App <[email protected]>
1 parent 2865187 commit 219c013

7 files changed

Lines changed: 119 additions & 56 deletions

File tree

‎docs/reference/extensions.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,8 @@ Extension manifests reject invalid hook priorities during installation. For exis
327327
328328
Core commands run two hook dispatchers, one before and one after their main work, using the project's selected `sh`, `ps`, or `py` script type. Each variant resolves hooks independently and returns JSON containing the event and an ordered `hooks` array (`extension`, `command`, `optional`, `description`, `prompt`, `priority`). An absent configuration or event returns an empty array. An unreadable or invalid configuration returns an `error` and a nonzero exit code; agents must report that no hooks were checked, including mandatory hooks, and then continue the core command. The dispatchers determine the order but do not execute agent commands. The Python variant needs Python 3 with PyYAML when `.specify/extensions.yml` exists; Bash and PowerShell do not use Python or PyYAML.
329329
330+
All three dispatchers validate hook fields across every configured event before returning the requested event. Priorities are truncated to integers in the range `1` through `2147483647`; values outside this range, booleans, and non-integer strings fall back to `10`. Quoted integer strings are accepted, but quoted decimal strings are not.
331+
330332
The native Bash and PowerShell resolvers support the CLI's pretty-printed `.specify/extensions.yml` layout: a `hooks:` mapping, event names indented two spaces, list items under each event, and single-line scalar fields (including quoted strings and common escapes). Other YAML constructs such as anchors, flow-style hook lists, and block scalars are not supported; these variants reject them explicitly rather than silently skipping hooks. The CLI writes hook configuration in this canonical layout without wrapping long scalar values; installing or upgrading shared infrastructure rewrites existing valid YAML to this layout so configurations produced by older versions remain usable (YAML comments and formatting are not retained). The Python variant accepts general YAML through PyYAML. A hook `condition` must be a string or null in all variants.
331333
332334
## FAQ

‎scripts/bash/pre-hooks.sh‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -110,40 +110,44 @@ hook_field() {
110110
fi
111111
fi
112112
if [[ $key == description || $key == prompt ]]; then
113-
if [[ $HOOK_QUOTED == false && $HOOK_SCALAR =~ ^(true|false|[0-9]+)$ ]]; then
113+
if [[ $HOOK_QUOTED == false && -n $HOOK_SCALAR ]] &&
114+
hook_typed_scalar "$HOOK_SCALAR"; then
114115
HOOK_ERROR="$key must be a string"
115116
return
116117
fi
117118
fi
119+
[[ $target == true ]] || return
118120
case $key in
119121
extension) HOOK_EXT[index]=$HOOK_SCALAR ;;
120122
command) HOOK_CMD[index]=$HOOK_SCALAR ;;
121123
enabled) HOOK_ENABLED[index]=$HOOK_SCALAR ;;
122124
optional) HOOK_OPTIONAL[index]=$HOOK_SCALAR ;;
123125
condition) HOOK_CONDITION[index]=$HOOK_SCALAR ;;
124-
priority) HOOK_PRIORITY[index]=$HOOK_SCALAR ;;
126+
priority) HOOK_PRIORITY[index]=$HOOK_SCALAR; HOOK_PRIORITY_QUOTED[index]=$HOOK_QUOTED ;;
125127
description) HOOK_DESCRIPTION[index]=$HOOK_SCALAR ;;
126128
prompt) HOOK_PROMPT[index]=$HOOK_SCALAR ;;
127129
esac
128130
}
129131

130132
hook_priority() {
131-
local raw=$1 whole
133+
local raw=$1 quoted=$2 whole
132134
HOOK_RANK=10
133135
[[ $raw =~ ^\+?[0-9]+(\.[0-9]+)?$ ]] || return
136+
[[ $quoted == true && $raw == *.* ]] && return
134137
whole=${raw%%.*}
135138
whole=${whole#+}
136-
(( ${#whole} <= 15 )) || return
139+
while [[ $whole == 0* && ${#whole} -gt 1 ]]; do whole=${whole#0}; done
140+
(( ${#whole} <= 10 )) || return
137141
HOOK_RANK=$((10#$whole))
138-
(( HOOK_RANK >= 1 )) || HOOK_RANK=10
142+
(( HOOK_RANK >= 1 && HOOK_RANK <= 2147483647 )) || HOOK_RANK=10
139143
}
140144

141145
resolve_hooks() {
142146
local phase=$1 command=$2 event config line spaces indent text key value
143147
local section="" target=false empty=false item_indent=-1 index=0 seen=false seen_hooks=false seen_event=false
144148
local i n chosen first=true
145149
local -a HOOK_EXT HOOK_CMD HOOK_ENABLED HOOK_OPTIONAL HOOK_CONDITION
146-
local -a HOOK_PRIORITY HOOK_DESCRIPTION HOOK_PROMPT HOOK_RANKS HOOK_USED
150+
local -a HOOK_PRIORITY HOOK_PRIORITY_QUOTED HOOK_DESCRIPTION HOOK_PROMPT HOOK_RANKS HOOK_USED
147151
event="${phase}_${command}"
148152
if [[ ! $event =~ ^(before|after)_[a-z][a-z0-9_]*$ ]]; then
149153
hook_error "" "Invalid hook event: $event"
@@ -226,10 +230,10 @@ resolve_hooks() {
226230
HOOK_ENABLED[index]=true
227231
HOOK_OPTIONAL[index]=true
228232
HOOK_PRIORITY[index]=10
229-
hook_field "${text:2}"
230233
fi
234+
hook_field "${text:2}"
231235
elif (( item_indent >= 0 && indent == item_indent + 2 )); then
232-
if [[ $target == true ]]; then hook_field "$text"; fi
236+
hook_field "$text"
233237
else
234238
HOOK_ERROR="Unsupported YAML hook layout"
235239
fi
@@ -242,7 +246,7 @@ resolve_hooks() {
242246
if [[ -z ${HOOK_EXT[i]} || -z ${HOOK_CMD[i]} ]]; then
243247
HOOK_ERROR="hooks.$event needs extension and command"; break
244248
fi
245-
hook_priority "${HOOK_PRIORITY[i]}"
249+
hook_priority "${HOOK_PRIORITY[i]}" "${HOOK_PRIORITY_QUOTED[i]}"
246250
HOOK_RANKS[i]=$HOOK_RANK
247251
done
248252
fi

‎scripts/powershell/pre-hooks.ps1‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,12 @@ function Add-HookField {
3838
if ($key -in @('enabled', 'optional') -and ($parsed.Quoted -or $value -notin @('true', 'false'))) {
3939
throw "$key must be a boolean"
4040
}
41-
if ($key -in @('prompt', 'description') -and -not $parsed.Quoted -and $value -match '^(true|false|[0-9]+)$') {
41+
if ($key -in @('prompt', 'description') -and -not $parsed.Quoted -and
42+
(Test-HookTypedScalar $value)) {
4243
throw "$key must be a string"
4344
}
4445
$Hook[$key] = $value
46+
if ($key -eq 'priority') { $Hook.priority_quoted = $parsed.Quoted }
4547
}
4648

4749
function Test-HookTypedScalar {
@@ -53,12 +55,13 @@ function Test-HookTypedScalar {
5355
}
5456

5557
function Get-HookPriority {
56-
param([string]$Raw)
58+
param([string]$Raw, [bool]$Quoted)
5759
if ($Raw -notmatch '^[+-]?[0-9]+(\.[0-9]+)?$') { return 10 }
60+
if ($Quoted -and $Raw.Contains('.')) { return 10 }
5861
$number = 0.0
5962
if (-not [double]::TryParse($Raw, [Globalization.NumberStyles]::Float,
6063
[Globalization.CultureInfo]::InvariantCulture, [ref]$number)) { return 10 }
61-
if ($number -lt 1 -or $number -gt [int]::MaxValue) { return 10 }
64+
if ($number -lt 1 -or [Math]::Truncate($number) -gt [int]::MaxValue) { return 10 }
6265
return [int][Math]::Truncate($number)
6366
}
6467

@@ -130,15 +133,13 @@ function Resolve-HookConfig {
130133
}
131134
if ($indent -in @(2, 4) -and $body.StartsWith('- ') -and -not $empty) {
132135
$itemIndent = $indent
133-
if ($target) {
134-
$hook = @{ enabled = 'true'; optional = 'true'; priority = '10' }
135-
$hooks.Add($hook)
136-
Add-HookField $hook $body.Substring(2) $Event
137-
}
136+
$hook = @{ enabled = 'true'; optional = 'true'; priority = '10'; priority_quoted = $false }
137+
if ($target) { $hooks.Add($hook) }
138+
Add-HookField $hook $body.Substring(2) $Event
138139
continue
139140
}
140141
if ($itemIndent -ge 0 -and $indent -eq $itemIndent + 2) {
141-
if ($target) { Add-HookField $hook $body $Event }
142+
Add-HookField $hook $body $Event
142143
continue
143144
}
144145
throw "Unsupported YAML hook layout"
@@ -156,7 +157,7 @@ function Resolve-HookConfig {
156157
optional = $hook.optional -eq 'true'
157158
description = if ($hook.description) { $hook.description } else { '' }
158159
prompt = if ($hook.prompt) { $hook.prompt } else { '' }
159-
priority = Get-HookPriority $hook.priority
160+
priority = Get-HookPriority $hook.priority $hook.priority_quoted
160161
index = $i
161162
})
162163
}

‎scripts/python/pre_hooks.py‎

Lines changed: 36 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -33,43 +33,43 @@ def resolve(event: str, project_root: Path) -> dict:
3333
if not isinstance(config, dict) or not isinstance(config.get("hooks", {}), dict):
3434
raise ValueError("Invalid .specify/extensions.yml: expected a hooks mapping")
3535

36-
entries = config.get("hooks", {}).get(event, [])
37-
if not isinstance(entries, list):
38-
raise ValueError(f"Invalid .specify/extensions.yml: hooks.{event} must be a list")
39-
4036
hooks = []
41-
for index, entry in enumerate(entries):
42-
if not isinstance(entry, dict):
43-
raise ValueError(f"Invalid .specify/extensions.yml: hooks.{event}[{index}] must be a mapping")
44-
if "enabled" in entry and not isinstance(entry["enabled"], bool):
45-
raise ValueError(f"Invalid .specify/extensions.yml: hooks.{event}[{index}].enabled must be a boolean")
46-
if "optional" in entry and not isinstance(entry["optional"], bool):
47-
raise ValueError(f"Invalid .specify/extensions.yml: hooks.{event}[{index}].optional must be a boolean")
48-
if entry.get("condition") is not None and not isinstance(entry["condition"], str):
49-
raise ValueError(f"Invalid .specify/extensions.yml: hooks.{event}[{index}].condition must be a string or null")
50-
if entry.get("enabled") is False or entry.get("condition"):
51-
continue
52-
extension, command = entry.get("extension"), entry.get("command")
53-
if not isinstance(extension, str) or not extension or not isinstance(command, str) or not command:
54-
raise ValueError(f"Invalid .specify/extensions.yml: hooks.{event}[{index}] needs extension and command")
55-
for field in ("description", "prompt"):
56-
if entry.get(field) is not None and not isinstance(entry[field], str):
57-
raise ValueError(f"Invalid .specify/extensions.yml: hooks.{event}[{index}].{field} must be a string")
58-
priority = entry.get("priority", 10)
59-
try:
60-
priority = int(priority) if not isinstance(priority, bool) else 10
61-
except (TypeError, ValueError, OverflowError):
62-
priority = 10
63-
if priority < 1:
64-
priority = 10
65-
hooks.append({
66-
"extension": extension,
67-
"command": command,
68-
"optional": entry.get("optional", True),
69-
"description": entry.get("description") or "",
70-
"prompt": entry.get("prompt") or "",
71-
"priority": priority,
72-
})
37+
for hook_event, entries in config.get("hooks", {}).items():
38+
if not isinstance(entries, list):
39+
raise ValueError(f"Invalid .specify/extensions.yml: hooks.{hook_event} must be a list")
40+
for index, entry in enumerate(entries):
41+
label = f"hooks.{hook_event}[{index}]"
42+
if not isinstance(entry, dict):
43+
raise ValueError(f"Invalid .specify/extensions.yml: {label} must be a mapping")
44+
for field in ("enabled", "optional"):
45+
if field in entry and not isinstance(entry[field], bool):
46+
raise ValueError(f"Invalid .specify/extensions.yml: {label}.{field} must be a boolean")
47+
for field in ("condition", "description", "prompt"):
48+
if entry.get(field) is not None and not isinstance(entry[field], str):
49+
raise ValueError(f"Invalid .specify/extensions.yml: {label}.{field} must be a string or null")
50+
for field in ("extension", "command"):
51+
if field in entry and (not isinstance(entry[field], str) or not entry[field]):
52+
raise ValueError(f"Invalid .specify/extensions.yml: {label} needs extension and command")
53+
if hook_event != event or entry.get("enabled") is False or entry.get("condition"):
54+
continue
55+
extension, command = entry.get("extension"), entry.get("command")
56+
if not extension or not command:
57+
raise ValueError(f"Invalid .specify/extensions.yml: {label} needs extension and command")
58+
priority = entry.get("priority", 10)
59+
try:
60+
priority = int(priority) if not isinstance(priority, bool) else 10
61+
except (TypeError, ValueError, OverflowError):
62+
priority = 10
63+
if priority < 1 or priority > 2147483647:
64+
priority = 10
65+
hooks.append({
66+
"extension": extension,
67+
"command": command,
68+
"optional": entry.get("optional", True),
69+
"description": entry.get("description") or "",
70+
"prompt": entry.get("prompt") or "",
71+
"priority": priority,
72+
})
7373
hooks.sort(key=lambda hook: hook["priority"])
7474
return {"event": event, "hooks": hooks}
7575

‎src/specify_cli/extensions/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5733,7 +5733,7 @@ def represent_string(dumper: yaml.SafeDumper, value: str):
57335733

57345734
def migrate_project_config(self) -> None:
57355735
"""Rewrite existing hook configuration for the native script resolvers."""
5736-
if self.config_file.is_symlink():
5736+
if self.config_file.parent.is_symlink() or self.config_file.is_symlink():
57375737
raise ValueError("Refusing to migrate symlinked .specify/extensions.yml")
57385738
if not self.config_file.exists():
57395739
return

‎tests/specify_cli/integrations/test_command_upgrade.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,22 @@ def test_upgrade_does_not_write_symlinked_hook_config(self, tmp_path):
8686
assert "Refusing to migrate symlinked" in result.output
8787
assert external.read_text(encoding="utf-8") == legacy
8888

89+
def test_hook_config_migration_rejects_symlinked_parent(self, tmp_path):
90+
from specify_cli.extensions import HookExecutor
91+
92+
project = tmp_path / "project"
93+
project.mkdir()
94+
external = tmp_path / "external"
95+
external.mkdir()
96+
config = external / "extensions.yml"
97+
legacy = "hooks:\n before_plan: []\n"
98+
config.write_text(legacy, encoding="utf-8")
99+
(project / ".specify").symlink_to(external, target_is_directory=True)
100+
101+
with pytest.raises(ValueError, match="symlinked"):
102+
HookExecutor(project).migrate_project_config()
103+
assert config.read_text(encoding="utf-8") == legacy
104+
89105
def test_upgrade_invalid_manifest_reports_cli_error(self, tmp_path):
90106
project = _init_project(tmp_path, "claude")
91107
_write_invalid_manifest(project, "claude")

‎tests/test_hook_dispatch_scripts.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,21 @@ def test_native_parsers_reject_unsupported_or_invalid_yaml(tmp_path, variant, ph
392392
assert data["error"]
393393

394394

395+
@pytest.mark.parametrize("variant", ["sh", "ps", "py"])
396+
@pytest.mark.parametrize("phase", ["pre", "post"])
397+
@pytest.mark.parametrize("field", ["extension: 'unterminated", "optional: 'false'", "condition: false"])
398+
def test_non_target_event_fields_are_validated(tmp_path, variant, phase, field):
399+
if variant == "ps" and not shutil.which("pwsh"):
400+
pytest.skip("PowerShell not installed")
401+
event = f"{'before' if phase == 'pre' else 'after'}_tasks"
402+
write_config(tmp_path, f"hooks:\n {event}:\n - extension: git\n"
403+
f" command: speckit.git.commit\n {field}\n")
404+
code, data = run_hook(tmp_path, phase, variant=variant)
405+
assert code == 1
406+
assert data["hooks"] == []
407+
assert data["error"]
408+
409+
395410
@pytest.mark.parametrize("variant", ["sh", "ps"])
396411
def test_native_invalid_event_is_valid_json(tmp_path, variant):
397412
if variant == "ps" and not shutil.which("pwsh"):
@@ -414,3 +429,28 @@ def test_priority_normalization_matches_across_runtimes(tmp_path, variant, prior
414429
code, data = run_hook(tmp_path, variant=variant)
415430
assert code == 0
416431
assert data["hooks"][0]["priority"] == expected
432+
433+
434+
@pytest.mark.parametrize("variant", ["sh", "ps", "py"])
435+
@pytest.mark.parametrize("priority,expected", [
436+
(2147483647, 2147483647),
437+
(2147483648, 10),
438+
(2147483647.9, 2147483647),
439+
(10**16, 10),
440+
("00000000000000000005", 5),
441+
("2.8", 10),
442+
])
443+
def test_priority_range_and_coercion_parity(tmp_path, variant, priority, expected):
444+
if variant == "ps" and not shutil.which("pwsh"):
445+
pytest.skip("PowerShell not installed")
446+
write_config(tmp_path, yaml.safe_dump({"hooks": {"before_plan": [
447+
{"extension": "high", "command": "speckit.high.run", "priority": priority},
448+
{"extension": "default", "command": "speckit.default.run"},
449+
]}}, sort_keys=False))
450+
code, data = run_hook(tmp_path, variant=variant)
451+
assert code == 0
452+
assert data == run_hook(tmp_path)[1]
453+
assert [hook["extension"] for hook in data["hooks"]] == (
454+
["default", "high"] if expected > 10 else ["high", "default"]
455+
)
456+
assert next(hook for hook in data["hooks"] if hook["extension"] == "high")["priority"] == expected

0 commit comments

Comments
 (0)