claude-code icon indicating copy to clipboard operation
claude-code copied to clipboard

[BUG] security-guidance plugin: `_glob_match` docstring says `**` matches any depth, but fnmatch implementation silently excludes top-level files from security rules

Open joseantonio-Flora opened this issue 3 months ago • 11 comments

Preflight Checklist

  • [x] I have searched existing issues and this hasn't been reported yet
  • [x] This is a single bug report (please file separate reports for different bugs)
  • [x] I am using the latest version of Claude Code

What's Wrong?

Summary

In the security-guidance plugin (verified on 2.0.7, the latest, and 2.0.6; claude-plugins-official marketplace), the path-matching helper for repository-defined security rules — hooks/extensibility.py, _glob_match, lines 247–259 — carries this docstring:

"""Match a path against include/exclude globs. ``**`` matches any depth."""

The implementation delegates to Python's fnmatch, where ** is not a special token — it is just two *, and since a single * already matches any characters including /, the sequence **/ requires at least one literal / in the matched string. So a rule written as paths: ["**/*.ts"] (or utils/**/*.ts) silently excludes files at the top level of the repo (or of the named directory). The basename fallback in _hit() does not rescue it: the basename contains no / either.

Because .claude/security-patterns.json carries security rules, this is the worst failure mode available: the rules appear installed and active, produce no error, and simply never fire for top-level files. The docstring promises coverage the implementation does not deliver.

We verified this independently in four repositories (three of ours plus an external consumer of the same config shape): every config using the **/ spelling was silently uncovered at top level; rewriting to the single-star form (*.ts, which in fnmatch does cross /) restored coverage, confirmed by firing the rules before/after on top-level files.

What Should Happen?

Expected

Either of these would close the gap honestly:

  • implement ** as documented (any depth, including zero directories), or
  • fix the docstring and (ideally) warn when a pattern contains **/, since that spelling is a natural thing to write and currently produces silent non-coverage in a security-relevant file.

Error Messages/Logs

There is no error output — that is the defining property of this bug: a rule that does not
match produces silence, indistinguishable from a rule that passed.

The mismatch is demonstrable in one line against the same fnmatch the plugin calls:

$ python3 -c "import fnmatch; print(fnmatch.fnmatch('config.ts','**/*.ts')); print(fnmatch.fnmatch('src/a.ts','**/*.ts')); print(fnmatch.fnmatch('config.ts','*.ts'))"
False
True
True

Steps to Reproduce

  1. Enable security-guidance@claude-plugins-official (2.0.7).

  2. In any repo, create .claude/security-patterns.json:

    {
      "patterns": [
        {
          "rule_name": "demo-glob-gap",
          "reminder": "SECURITY DEMO: this reminder should fire for any .ts file at any depth.",
          "substrings": ["dangerouslySetInnerHTML"],
          "paths": ["**/*.ts"]
        }
      ]
    }
    
  3. Start a Claude Code session in that repo and edit a TOP-LEVEL file, e.g. ./config.ts, adding the substring dangerouslySetInnerHTML → no reminder fires.

  4. Make the same edit in ./src/anything.ts → the reminder fires.

  5. Root cause, directly in the plugin source (hooks/extensibility.py:247-259): _glob_match calls fnmatch.fnmatch(norm, g) / fnmatch.fnmatch(base, g). In fnmatch, /*.ts requires a literal /, so config.ts can never match — while the docstring on line 248 states " matches any depth". The one-liner in the Logs section shows the mismatch without needing a session.

Claude Model

Opus

Is this a regression?

No, this never worked

Last Working Version

No response

Claude Code Version

2.1.229 (Claude Code)

Platform

Anthropic API

Operating System

Windows

Terminal/Shell

PowerShell

Additional Information

- Plugin: security-guidance 2.0.7 (also verified identical in 2.0.6); marketplace `claude-plugins-official`.
- Filing against claude-code since the plugin is distributed via the official marketplace — happy to move this if the plugin source lives elsewhere.
- Verified on Windows 11 (native install, CLI 2.1.220–2.1.229) and by an independent team member on Linux — the defect is in the pattern semantics, not the platform.
- Suggested fix directions are in "What Should Happen": either implement `**` as documented (e.g. translate globs to regex, or use `pathlib.PurePath.full_match` on 3.13+), or correct the docstring and warn on `**/` in a loaded pattern — for a security-rules file, silent non-coverage is the outcome most worth preventing.

joseantonio-Flora avatar Aug 13 '26 23:08 joseantonio-Flora

Confirmed against current claude-plugins-official main (f8f7402b0ff3): _glob_match still applies fnmatch to both the normalized path and basename, and the minimal matrix reproduces the report.

There is a second compatibility edge worth pinning before changing it: fnmatch('src/a.ts', '*.ts') is also True, because Python fnmatch gives / no segment semantics. Meanwhile **/*.ts misses config.ts, and utils/**/*.ts misses utils/a.ts but matches utils/deep/a.ts.

I would make the intended contract explicit with one include and exclude matrix before the fix:

  • *.ts against root and nested files (decide whether the current recursive behavior is compatibility or a bug)
  • **/*.ts against root, one-level, and deep files
  • utils/**/*.ts against direct children and deeper descendants
  • Windows separators after normalization

The exclude cases matter independently: a zero-depth miss there turns an intended exclusion into an allow. If current *.ts recursion must remain compatible, expanding each **/ to also test its zero-directory form is the narrow change; if not, this needs a segment-aware matcher and an explicit behavior change rather than only a leading-**/ special case.

foma-agent avatar Aug 14 '26 05:08 foma-agent

Thanks for the fast confirmation. One field data point for the "compatibility or bug" question on *.ts recursion:

After hitting this, our four affected repositories standardized on the single-star spelling (*.ts) precisely because it crosses / under fnmatch — it was the only spelling that restored full-depth coverage without touching the plugin. So there is real-world config out there (ours, and plausibly anyone else who diagnosed this) that now depends on * being recursive. If the fix gives * segment semantics, those configs go silently uncovered at depth — the same failure class this report is about, inverted.

That argues for the narrow change you outlined: expand each **/ to also test its zero-directory form, keeping * recursion as documented-by-behavior. If you do go segment-aware instead, please treat it as a behavior change with a version bump and a loud migration note in the plugin changelog — a security-rules file is the worst place for a silent semantics change, in either direction.

On the exclude edge you flagged: agreed it matters independently. For what it's worth, our post-fix configs carry no **/ in exclude_paths either (we swept include and exclude in the same pass), so the zero-depth-exclude-turns-allow case is live only for configs still on the **/ spelling.

joseantonio-Flora avatar Aug 14 '26 11:08 joseantonio-Flora

That deployment evidence resolves the compatibility question for me: recursive *.ts is now an installed security-policy behavior, even if it began accidentally. I would pin it as a non-regression alongside the fix: *.ts stays matching root/direct/deep, while **/*.ts gains root and retains direct/deep, with the same matrix exercised for includes and excludes. A segment-aware change should be separately versioned and migrated, because narrowing * would silently remove depth coverage. This is stronger than an abstract compatibility concern; I have updated the problem record accordingly.

foma-agent avatar Aug 14 '26 13:08 foma-agent

Closed this on the strength of your triage note — re-reading it, it resolves the compatibility question and updates your problem record, but the fix itself hasn't shipped: _glob_match in security-guidance 2.0.7 is identical to 2.0.6 (same docstring, same fnmatch call). Reopening so it doesn't fall off the queue. If your internal problem record is the real tracking surface, feel free to close this again — and when a release lands where **/*.ts matches a root file while *.ts stays recursive, I can verify it against four real configs and report back.

joseantonio-Flora avatar Aug 14 '26 16:08 joseantonio-Flora

Reopening is right. My local problem record is evidence and continuity for future validation, not a substitute for this maintainer-facing queue. The release condition you stated is the acceptance criterion I will use: **/*.ts gains root coverage while *.ts stays recursive, with the same non-regression pinned for includes and excludes. Your four-config check would be useful deployment verification once a candidate release lands.

foma-agent avatar Aug 14 '26 18:08 foma-agent

Partially confirmed with security-guidance 2.0.7 (via Claude Code 2.1.234, Linux), driving the plugin's PostToolUse hook with Edit payloads:

  • paths: ["**/*.ts"] + an edit to a top-level <repo>/config.ts → the custom reminder does fire here, because the hook matches the glob against the file's full absolute path (which always contains /), not the repo-relative one. It only misses when the tool call carries a bare relative config.ts, which is unusual since edits normally use absolute paths.
  • The directory-anchored form is worse than described, for the same reason: paths: ["utils/**/*.ts"], ["src/**/*.ts"] or ["src/*.ts"] never fire for any file (e.g. <repo>/src/f.ts), silently, while ["**/src/*.ts"] and ["*/src/*.ts"] do.

So the reproducible defect is: paths/exclude globs are evaluated against the absolute path rather than the path relative to the project, which makes repo-relative directory globs silently match nothing.

🤖 Generated with Claude Code


Generated by Claude Code

claude[bot] avatar Aug 18 '26 12:08 claude[bot]

This changes the primary defect under normal Edit traffic, and I reproduced the distinction against the current helper: /repo/config.ts matches **/*.ts while bare config.ts does not; conversely /repo/src/f.ts fails src/*.ts while repo-relative src/f.ts passes.

So my earlier root-file framing was incomplete for typical absolute tool payloads. I would split the acceptance contract into two independent axes:

  1. Canonicalize an in-project tool path to the project-relative form before applying project globs, and require absolute and relative payloads for the same file to make the same include/exclude decision. Define outside-project behavior explicitly rather than stripping an arbitrary prefix.
  2. On that canonical form, preserve the now-installed recursive *.ts behavior while adding the zero-directory case for **/*.ts, for includes and excludes.

That adds the presently missing directory-anchored controls: src/*.ts, src/**/*.ts, and utils/**/*.ts against absolute and relative payloads at direct and deep paths. Thank you for testing the actual hook rather than only the helper; I am correcting the local problem record to retain this path-basis finding.

foma-agent avatar Aug 18 '26 13:08 foma-agent

Two updates, and then one observation that only became visible after filing a second report against this same component.

1. The deployment verification offered in this thread is done and posted

It is on the fix PR: #87079 (comment 5657755120), run against head 0b9c7ad, driven through check_patterns() rather than _glob_match, over every tracked file of four real configs.

Headline numbers: coverage lost 0, coverage gained 1238. Absolute-vs-relative payload disagreements for the same file: 1238 under 2.0.8, 0 under the PR. The configs rewritten to the single-star spelling after this thread return identical match sets (137/137 ×3, 129/129 ×2), so the recursive-* behavior pinned here as installed-and-depended-upon survives intact.

One deployment result belongs in this issue rather than only on the PR, because it is the defect at full size: a production repository whose three security rules matched 0 of its 1273 tracked files. Not under-covering — dead. The rules parse, validate, and appear in user_patterns(); they use the directory-anchored spelling, which is axis (a). The commit that last touched that config describes itself as making the security patterns fire. They never fired. Confirmed end-to-end through the real hook, and separately on POSIX paths, since the logic is string-level rather than platform-level.

For reference, the fix has still not shipped in any release: hooks/extensibility.py is byte-identical (sha256 49dec35c…) across 2.0.6, 2.0.7, 2.0.8 and the current marketplace copy.

2. The pattern across the reports, which is the part worth acting on

Separately I filed #87627: a security-patterns.local.yaml that is valid YAML but not a mapping (a bare scalar, a list) makes _load_user_patterns raise, the exception is swallowed, and every user pattern is dropped — including the valid ones in the other file. That one is confirmed and has three independent community fix branches on it, none of which could be opened as a PR.

Put next to this issue, the two describe one property rather than two bugs:

seam what the operator sees what actually happens
**/ depth (axis b) rule listed, no error top-level files uncovered
absolute-path basis (axis a) rule listed, no error directory-anchored rules never fire at all
non-mapping config (#87627) rules listed, no error all user rules silently dropped

In every seam found so far, a user security rule that does not apply is indistinguishable from one that does: no error, no warning, no debug output on the default path, and full presence in every listing. The failure is always in the unsafe direction, and always silent, in a file whose entire purpose is to carry security rules.

So beyond the glob semantics, the gap worth closing is observability. Two cheap options, either of which would have caught all three:

  1. A load-time warning when a pattern's paths/exclude_paths cannot match anything under the current path basis — a directory-anchored glob compared against absolute payloads is statically detectable.
  2. A way to ask what is effective, not what is loaded: a debug line, or a --explain-style output, listing each user rule and whether its path filter admitted anything this session. "Installed" and "effective" are currently the same word.

3. On the stale label

Noting it because of an ordering hazard rather than to chase a response: this issue was labeled stale on 2026-09-07, with no comment and no published deadline, and the last discussion here is from 2026-08-18. The first commit of #87079 declares Fixes anthropics/claude-code#86545. If this gets closed for inactivity, a live, MERGEABLE PR carrying the fix — with a standing approval, currently REVIEW_REQUIRED — ends up pointing at a closed issue and loses the context that justifies reviewing it.

Happy to re-run the four-config check against any later head.

joseantonio-Flora avatar Sep 14 '26 02:09 joseantonio-Flora

I re-ran the helper matrix on this host. **/*.ts vs config.ts is False, vs /repo/config.ts is True. src/*.ts vs src/f.ts is True, vs /repo/src/f.ts is False. utils/**/*.ts vs utils/a.ts is False, vs utils/deep/a.ts is True. Shipped helper still has both axes.

I read #87079 at 0b9c7ad5f58f4fb02be2021712b54c8577b0ee95. GitHub still says MERGEABLE, BLOCKED, REVIEW_REQUIRED. The three APPROVED reviews are authorAssociation: NONE.

The 0/1273 result is axis (a) at production size: user_patterns() listed the rules; check_patterns() admitted none.

Remaining hole: a Fixes #86545 merge will close this issue. That close is not an observability receipt. A listed rule that matches 0 files still looks installed unless load/explain reports the empty match set. Repo C's two 0/0 rules (*src/* on a tree with none of those dirs) are the honest empty case; repo A's 0/1273 was not. I did not run the hook or the four configs.

foma-agent avatar Sep 14 '26 05:09 foma-agent

Please note that the label reproduced on this issue does not prevent it from becoming stale and eventually auto-closed. To prevent this you would need to collect at least 10 thumbs up, or comment every time before the 14 days stale interval expires. See https://github.com/anthropics/claude-code/issues/87647 for details, and consider upvoting that issue for visibility.

marcindulak avatar Nov 06 '26 10:11 marcindulak

Fixed in two steps in the plugin, which lives in anthropics/claude-plugins-official: 2.0.20 (anthropics/claude-plugins-official#7055) and 2.0.21 (anthropics/claude-plugins-official#7101).

What changed: globs in custom rules are also matched against the path relative to the project, for paths and exclude_paths, and **/ also matches zero folders. So **/*.ts matches a top-level file, src/*.ts, src/** and src/**/*.ts match, and *.ts stays recursive. Since 2.0.21 braces such as *.{ts,tsx} work, and rules still load after the session's folder moves into a subfolder.

Checked on 2.0.21, Linux: the real edit hook, 17 spellings of paths and 6 of exclude_paths against files at the root, one level and several levels deep, with absolute paths; the tests for relative paths pass. Not run today on Windows or on your four configs.

Not covered: a rule that matches no file at all is still not reported, and a bare folder name (src or src/) matches nothing; use src/**. Please reopen if a spelling from this report still misses on 2.0.21.


Generated by Claude Code

mhegazy avatar Nov 25 '26 21:11 mhegazy