Repository navigation
Stop install-hooks on a malformed settings section or PreToolUse entry - #164
Conversation
install() and uninstall() assumed every section of settings.json had the type Claude Code documents, and raised AttributeError when one did not. uninstall() was worse with a deny object: it iterated the object's keys and, when it removed the hook, wrote them back as a list. Both now read the file through _read_settings(), which checks the top level, hooks, permissions, the two hook events and deny, and raises a ValueError naming the key before anything is written; the CLI already prints a ValueError as "error: ..." and exits 1. There is no safe way to add rules to a deny that is an object, so stopping beats a rewrite. Inside a list of the right type, a hook entry that is not an object, or whose hooks field is not a list, is not keyfence's, so _is_ours() and _sync_command() skip it and it stays in place, as non-string deny entries do.
aminueza
left a comment
There was a problem hiding this comment.
Stopping on a section of the wrong type is right, and the data-loss fix is real. One decision needs to change: a malformed hook entry under PreToolUse must stop install too, the same way a wrong-type section does. Leaving it in place makes keyfence report a protection that Claude Code does not apply.
What holds
I ran 15 malformed shapes through install, --remove, --remove --force, --list and doctor, comparing main with #163, #164 and #165 merged in that order. The merge is clean.
- No tracebacks.
mainfails with a traceback on 11 of the 15 shapes. The merged tree has none, every error names the key, and the file is untouched on every error. - Data loss on
mainreproduced.--removerewrites"deny": {"a": 1}as["a"]when the hook is installed. Now it stops before writing. - Teeth. Each of these mutations fails a new test: removing the top-level, section or list checks; dropping the
_entry_hooksfilters; reading throughjson.loadsininstalloruninstall; reverting_sync_command. - Suite. 1263 passed, coverage 98.63%,
guard.pybyte-identical. The same 5 failures, local to my machine, also fail onmain.
Blocking: a malformed PreToolUse entry voids the file in Claude Code
The description says an entry of the wrong type "cannot be keyfence's, and leaving it is what Claude Code sees anyway". For PreToolUse, Claude Code 2.1.317 does not skip the entry; it skips the whole file. claude doctor in a directory holding each shape:
| shape | claude doctor |
this branch |
|---|---|---|
{"hooks":{"PreToolUse":["x"]}} |
"a PreToolUse/PermissionRequest hook that cannot be loaded may be what guards the permissions declared beside it, so nothing it sits in is applied until the entry is fixed or removed" | Hook installed; keyfence doctor: ok Claude Code hook: installed (project) |
{"hooks":{"PreToolUse":[{"hooks":"y"}]}} |
same | same |
{"hooks":{"PreToolUse":[{"matcher":"Read","hooks":[null,"z"]}]}} |
same, for each bad hook | same |
{"hooks":{"UserPromptSubmit":["x"]}} |
"matcher ignored": only that entry | installs; correct |
So for the three PreToolUse shapes, keyfence writes its hook and 42 deny rules into a file Claude Code does not apply, and both install-hooks and doctor say it is protected. On main these shapes ended in a traceback, which at least did not claim success. The PR's own reasoning for sections applies here: "skipping would install the hook without the deny rules and report success". Here neither the hook nor the rules apply.
_entry_hooks already detects exactly these shapes, so the check can sit in _read_settings. This passes everything except the two tests that assert the current behaviour:
for index, entry in enumerate(data.get("hooks", {}).get("PreToolUse", [])):
nested = entry.get("hooks", []) if isinstance(entry, dict) else None
if not isinstance(nested, list) or not all(isinstance(hook, dict) for hook in nested):
raise ValueError(f"hooks.PreToolUse[{index}] in {path} is not a hook Claude Code can load, so it applies "
"nothing in that file; fix it, then run this again")With it, the two PreToolUse shapes I tried stop with that error, the file stays untouched, and doctor says "not installed". UserPromptSubmit keeps today's behaviour. test_a_hook_entry_of_the_wrong_type_is_left_in_place_by_install_and_remove then needs to split: UserPromptSubmit entries are left in place, and PreToolUse entries stop install and --remove. Please also update the CHANGELOG sentence about entries being left in place.
Not from this PR, worth a follow-up
Any other PreToolUse entry Claude Code cannot load voids the file the same way. Examples are a numeric matcher, or a command hook without command; claude doctor reports both with the same "nothing it sits in is applied" text. keyfence cannot mirror the whole schema, and main already installs into such files. A line after install, or a doctor hint, pointing to claude doctor would cover the rest.
A PreToolUse entry that is not an object, has no hooks list, or holds a
hook that is not an object makes Claude Code apply nothing in the file
that holds it ("nothing it sits in is applied", claude doctor on 2.1.311
and 2.1.317). install-hooks left such an entry in place and wrote the
hook and the deny rules beside it, so it and keyfence doctor reported a
protection that was not in effect.
_read_settings now raises a ValueError naming the entry, in the same
wording as the wrong-type section errors, so install and --remove stop
before any write. A malformed UserPromptSubmit entry is still left in
place: Claude Code ignores only that entry there.
|
Done: a malformed Two differences from your snippet:
Your four shapes, at ad36111:
Suite: 1281 passed, coverage 98.66%, By the way, |
aminueza
left a comment
There was a problem hiding this comment.
Re-checked at ad36111. The PreToolUse change is in, and I confirmed both of your extensions against two Claude Code versions (2.1.269 and 2.1.317, with the same messages and the same verdicts):
| shape | claude doctor |
this branch |
|---|---|---|
{"matcher": "Read"} (no hooks) |
Hook matcher "hooks" must be an array of hook entries; received undefined … "nothing it sits in is applied" |
stops; right to stop |
{"matcher": "Read", "hooks": []} |
no line | passes |
null inside a UserPromptSubmit entry |
entry ignored. |
left in place |
My 15-shape QA on the full stack (#164 + #165 + #167) shows:
- No tracebacks in
install,--remove,--remove --force,--listordoctor. - The three
PreToolUseshapes stop before any write, naming the exact key. - Every error leaves the file untouched.
guard.py is byte-identical. The suite passes, 1281 tests with the earlier 5 failures gone, once a working keyfence is on PATH. The 4 test_docker.py failures I reported before came from a keyfence that was not resolvable on my machine, not from the code. CI is green on all 11 checks.
Ready to merge.
Currently,
keyfence install-hooks claude-code(with or without--remove) crashes with anAttributeErrorwhen a section ofsettings.jsonhas the wrong type:hooksorpermissionsthat is not an object, orPreToolUse,UserPromptSubmitordenythat is not a list. Worse, whendenyis an object and the keyfence hook is installed,--removerewrites it as the list of its keys ({"a": 1}becomes["a"]) and says nothing.This PR makes both commands stop with an error that names the key, before they write anything:
There is no safe way to add rules to a
denythat is an object, so the user fixes the file instead of keyfence guessing.They also stop on a
PreToolUseentry that Claude Code cannot load: an entry that is not an object, has nohookslist, or holds a hook that is not an object. Claude Code applies nothing in a file that holds one (claude doctorsays "nothing it sits in is applied"), so installing there would report a protection that is not in effect. aminueza found this in the review.A malformed entry under
UserPromptSubmitis different: Claude Code ignores only that entry, so keyfence leaves it in place.How to test
pytest tests/test_hooks.py tests/test_cli.py -k "wrong_type or cannot_load"(25 cases, all fail onmain).{"permissions": {"deny": {"a": 1}}}to.claude/settings.json, then runkeyfence install-hooks claude-code --project. It prints the first error above, exits 1, and the file is unchanged.{"hooks": {"PreToolUse": ["x"]}}instead and run the same command. It prints the second error, exits 1, and the file is unchanged.--removeand--remove --forcedo the same.{"hooks": {"UserPromptSubmit": ["x"]}}instead, then runkeyfence install-hooks claude-code --projectandkeyfence install-hooks claude-code --project --remove. Both exit 0,--removereports 42 rules removed, and the file is back to{"hooks": {"UserPromptSubmit": ["x"]}}.Implementation record
keyfence/hooks.py_read_settings(): checks that the top level,hooksandpermissionsare objects, thatPreToolUse,UserPromptSubmitanddenyare lists, and that everyPreToolUseentry is an object whosehooksis a list of objects. It raises aValueErrornaming the key otherwise.install()anduninstall()read the file through it. New_entry_hooks(): the dict hooks inside an entry, or[]for an entry that is not an object or whosehooksis not a list._is_ours()and_sync_command()use it, so a malformedUserPromptSubmitentry is skipped.plugin/hooks/guard.pykeyfence/hooks.py.tests/test_hooks.pyinstallanduninstallbefore any write (12 cases, including the deny-object rewrite). Each malformedPreToolUseentry (the three shapes from the review, plus one with nohookskey) stopsinstallanduninstallwith the file byte-for-byte unchanged and no record file (8 cases). MalformedUserPromptSubmitentries are left in place by install, a second install and--remove.tests/test_cli.py--removeand--remove --force, and leaves the file alone: adenyobject, and the threePreToolUseshapes from the review.CHANGELOG.mdDecisions:
PreToolUseentry too: Claude Code applies nothing in that file, so neither the hook nor the rules would be in effect.claude doctorreports it on 2.1.311 (here) and on 2.1.317 (in the review).PreToolUseentry with nohookskey also stops.claude doctor2.1.311 reports{"matcher": "Read"}with the same "nothing it sits in is applied" text. An empty"hooks": []passes, andclaude doctoraccepts it.UserPromptSubmitentry:claude doctorreports "matcher ignored" for that entry only._read_settings()after the section checks, sohooksis already an object andPreToolUsea list. Its only callers areinstall()anduninstall();--removestops like a wrong-type section, because the file needs a fix before Claude Code applies any of it.hooks.PreToolUse[0].hooks[1]) in the same wording as the section errors.ValueError, becausecli.mainalready prints those aserror: ...with exit 1, the same path an invalid JSON file takes.Verification at ad36111 (with
mainat 64e6f0d merged in), 2026-11-05, macOS, Python 3.12.15:pytestwith the coverage gate (keyfence proxy and CA variables cleared from the shell) exits 0, 1281 passed, coverage 98.66%.main(64e6f0d), run against an export ofmainwith these test files.hooksnot a list, hook not an object, nohookskey) fails exactly the tests for that shape. Extending the check toUserPromptSubmitfails the test that keeps those entries.install,--remove,--remove --force,--listanddoctorwere run on the review's four shapes before and after this change. For the threePreToolUseshapes, all three install-hooks commands now stop, and--listanddoctorsay "not installed".Not changed here:
keyfence doctorandinstall-hooks --listread the file with their own code inkeyfence/doctor.py. On a file that an earlier keyfence already installed into, next to a malformedPreToolUseentry, they still say "installed", whileinstall-hooksnow stops with the error. Read a malformed settings file in doctor like one that is not JSON #165 makesdoctorread through_read_settings(), so the check here makes it say "not installed" there.PreToolUseentries that Claude Code cannot load (a numericmatcher, a command hook withoutcommand) are not checked: keyfence cannot mirror the whole schema. Pointing toclaude doctorfor those is install-hooks and doctor report the Claude Code hook as installed when Claude Code does not apply the settings file #166.