Skip to content

Stop install-hooks on a malformed settings section or PreToolUse entry - #164

Merged
felladrin merged 3 commits into
mainfrom
reject-malformed-settings-shapes
Nov 6, 2026
Merged

felladrin merged 3 commits into
mainfrom
reject-malformed-settings-shapes

Conversation

@felladrin

@felladrin felladrin commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Currently, keyfence install-hooks claude-code (with or without --remove) crashes with an AttributeError when a section of settings.json has the wrong type: hooks or permissions that is not an object, or PreToolUse, UserPromptSubmit or deny that is not a list. Worse, when deny is an object and the keyfence hook is installed, --remove rewrites 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:

error: permissions.deny in /work/.claude/settings.json is not a list; fix it, then run this again

There is no safe way to add rules to a deny that is an object, so the user fixes the file instead of keyfence guessing.

They also stop on a PreToolUse entry that Claude Code cannot load: an entry that is not an object, has no hooks list, or holds a hook that is not an object. Claude Code applies nothing in a file that holds one (claude doctor says "nothing it sits in is applied"), so installing there would report a protection that is not in effect. aminueza found this in the review.

error: hooks.PreToolUse[0] in /work/.claude/settings.json is not an object; fix it, then run this again

A malformed entry under UserPromptSubmit is different: Claude Code ignores only that entry, so keyfence leaves it in place.

How to test

  1. pytest tests/test_hooks.py tests/test_cli.py -k "wrong_type or cannot_load" (25 cases, all fail on main).
  2. In an empty directory, write {"permissions": {"deny": {"a": 1}}} to .claude/settings.json, then run keyfence install-hooks claude-code --project. It prints the first error above, exits 1, and the file is unchanged.
  3. Write {"hooks": {"PreToolUse": ["x"]}} instead and run the same command. It prints the second error, exits 1, and the file is unchanged. --remove and --remove --force do the same.
  4. Write {"hooks": {"UserPromptSubmit": ["x"]}} instead, then run keyfence install-hooks claude-code --project and keyfence install-hooks claude-code --project --remove. Both exit 0, --remove reports 42 rules removed, and the file is back to {"hooks": {"UserPromptSubmit": ["x"]}}.
Implementation record
File Change
keyfence/hooks.py New _read_settings(): checks that the top level, hooks and permissions are objects, that PreToolUse, UserPromptSubmit and deny are lists, and that every PreToolUse entry is an object whose hooks is a list of objects. It raises a ValueError naming the key otherwise. install() and uninstall() read the file through it. New _entry_hooks(): the dict hooks inside an entry, or [] for an entry that is not an object or whose hooks is not a list. _is_ours() and _sync_command() use it, so a malformed UserPromptSubmit entry is skipped.
plugin/hooks/guard.py Byte-identical copy of keyfence/hooks.py.
tests/test_hooks.py Every wrong-type section stops install and uninstall before any write (12 cases, including the deny-object rewrite). Each malformed PreToolUse entry (the three shapes from the review, plus one with no hooks key) stops install and uninstall with the file byte-for-byte unchanged and no record file (8 cases). Malformed UserPromptSubmit entries are left in place by install, a second install and --remove.
tests/test_cli.py The CLI prints the error and exits 1 for install, --remove and --remove --force, and leaves the file alone: a deny object, and the three PreToolUse shapes from the review.
CHANGELOG.md Unreleased entry.

Decisions:

  • Stop with an error, not skip or overwrite, for a section of the wrong type: overwriting loses the user's data, and skipping would install the hook without the deny rules and report success.
  • Stop for a malformed PreToolUse entry too: Claude Code applies nothing in that file, so neither the hook nor the rules would be in effect. claude doctor reports it on 2.1.311 (here) and on 2.1.317 (in the review).
  • A PreToolUse entry with no hooks key also stops. claude doctor 2.1.311 reports {"matcher": "Read"} with the same "nothing it sits in is applied" text. An empty "hooks": [] passes, and claude doctor accepts it.
  • Skip, not stop, for a malformed UserPromptSubmit entry: claude doctor reports "matcher ignored" for that entry only.
  • The entry check runs in _read_settings() after the section checks, so hooks is already an object and PreToolUse a list. Its only callers are install() and uninstall(); --remove stops like a wrong-type section, because the file needs a fix before Claude Code applies any of it.
  • The errors name the exact key (hooks.PreToolUse[0].hooks[1]) in the same wording as the section errors.
  • The error is a ValueError, because cli.main already prints those as error: ... with exit 1, the same path an invalid JSON file takes.

Verification at ad36111 (with main at 64e6f0d merged in), 2026-11-05, macOS, Python 3.12.15:

  • pytest with the coverage gate (keyfence proxy and CA variables cleared from the shell) exits 0, 1281 passed, coverage 98.66%.
  • The 25 cases in step 1 fail on main (64e6f0d), run against an export of main with these test files.
  • Removing each entry check in turn (entry not an object, hooks not a list, hook not an object, no hooks key) fails exactly the tests for that shape. Extending the check to UserPromptSubmit fails the test that keeps those entries.
  • Steps 2 to 4 were run through the CLI with the results as written.
  • install, --remove, --remove --force, --list and doctor were run on the review's four shapes before and after this change. For the three PreToolUse shapes, all three install-hooks commands now stop, and --list and doctor say "not installed".

Not changed here:

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 aminueza left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

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. main fails 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 main reproduced. --remove rewrites "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_hooks filters; reading through json.loads in install or uninstall; reverting _sync_command.
  • Suite. 1263 passed, coverage 98.63%, guard.py byte-identical. The same 5 failures, local to my machine, also fail on main.

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.
@felladrin felladrin changed the title Stop install-hooks on a settings section of the wrong type Stop install-hooks on a malformed settings section or PreToolUse entry Nov 5, 2026
@felladrin

Copy link
Copy Markdown
Collaborator Author

Done: a malformed PreToolUse entry now stops install, --remove and --remove --force with an error that names the entry, before any write. UserPromptSubmit entries are still left in place, the test is split as you suggested, and the CHANGELOG and the description are updated.

Two differences from your snippet:

  • The error uses the same wording as the section errors and names the exact key (hooks.PreToolUse[0].hooks[1] in ... is not an object; fix it, then run this again).
  • An entry with no hooks key also stops. Your snippet defaults it to [], but claude doctor (2.1.311 here) reports {"matcher": "Read"} with the same "nothing it sits in is applied" text. An empty "hooks": [] still passes.

Your four shapes, at ad36111:

shape install, --remove, --remove --force --list, doctor
{"hooks":{"PreToolUse":["x"]}} exit 1, hooks.PreToolUse[0] ... is not an object, file unchanged not installed
{"hooks":{"PreToolUse":[{"hooks":"y"}]}} exit 1, hooks.PreToolUse[0].hooks ... is not a list, file unchanged not installed
{"hooks":{"PreToolUse":[{"matcher":"Read","hooks":[null,"z"]}]}} exit 1, hooks.PreToolUse[0].hooks[0] ... is not an object, file unchanged not installed
{"hooks":{"UserPromptSubmit":["x"]}} install exit 0, then --remove leaves only the "x" entry installed (after install)

Suite: 1281 passed, coverage 98.66%, guard.py byte-identical.

By the way, --list and doctor still say "installed" on a file that an earlier keyfence already installed into, next to a malformed PreToolUse entry (they read the file with their own code in doctor.py). #165 makes doctor read through _read_settings(), so the check here covers that once #165 is on top. Your claude doctor follow-up, for the shapes keyfence does not check, is #166.

@aminueza aminueza left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

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, --list or doctor.
  • The three PreToolUse shapes 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.

@felladrin
felladrin merged commit 968c51b into main Nov 6, 2026
11 checks passed
@felladrin
felladrin deleted the reject-malformed-settings-shapes branch November 6, 2026 16:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants