← Back to Pull requests

VC-53793: Replace recursive wildcard matching with iterative algorithm #925

Merged
wallrj-cyberark merged 2 files (93 lines) on Jun 12, 2026 12:28 UTC
View on GitHub
wallrj-cyberark wallrj-cyberark commented on Jun 09, 2026 16:40 UTC
Author

Summary

  • Replace recursive matchRunes with an iterative backtrack-checkpoint algorithm that runs in O(nm), fixing exponential backtracking with multiple wildcards

  • Add Test_WildcardMatches_BacktrackingDoesNotHang regression test
  • Motivation

    This hardens approver-policy against CWE-770 (allocation of resources without limits or throttling). A security assessment identified two DoS variants in approver-policy:

    1. CEL comprehension DoS — fixed in cert-manager/approver-policy#923
    2. Wildcard backtracking DoS — fixed in this PR

    The matchRunes function (originally adapted from minio) used recursive backtracking to match wildcards. With multiple wildcards in a pattern (e.g. aaaaaaaa!), the worst case is O(2^n) — a pattern with 8 wildcards against a 50-character string explores ~2^50 branches, hanging the reconcile worker indefinitely.

    The exponential cost is driven by the number of in the pattern, which comes from a CertificateRequestPolicy (allowed..values and selector.issuerRef fields) — a privileged, cluster-scoped resource. The realistic risk is therefore an administrator inadvertently configuring a pathological pattern, rather than an attacker authoring a malicious CRP. Note the matched string comes from CertificateRequests (a far less privileged, namespaced operation), so once such a pattern exists, a low-privileged requester can supply crafted values that hit the worst case — escalating a misconfiguration into a cluster-wide approval DoS.

    The fix replaces the recursive algorithm with an iterative "backtrack checkpoint" technique: when a is encountered, the pattern and string positions are recorded as a checkpoint. On mismatch, execution backtracks to the checkpoint (advancing the string position by one) instead of forking into two recursive branches.

    Correctness / prior art

    This is not a bespoke algorithm — it is the standard greedy wildcard matcher with a single backtracking checkpoint (the "two-pointer" linear glob matcher). On each we record only the most recent checkpoint (starPx/starSx) and, on a later mismatch, rewind the text pointer one past that checkpoint rather than forking. It runs in O(nm); only the most recent ever needs remembering.

    References that establish correctness and the security motivation:

  • Russ Cox, "Glob Matching Can Be Simple And Fast Too" — presents the same checkpoint algorithm, explains why recursive matching is exponential (n^e for e stars), and frames it as a DoS class with real CVEs (CVE-2001-1501, CVE-2010-2632). Notes the same technique backs Go's path/filepath.Match, glibc's glob(3) and vsftpd.

  • Wikipedia, "Matching wildcards" (non-recursive section) — "only one such saved set [of pointers] is needed since just one successful match is required"; attributes iterative implementations to Dogan Kurt and Kirk J. Krauss (Dr. Dobb's, 2008).

  • LeetCode #44 "Wildcard Matching" — the canonical accepted O(m·n) greedy solution is structurally identical to this implementation.
  • Note on upstream minio: minio never fixed this. Both the originally-copied version and the current minio/pkg still use recursive backtracking and remain vulnerable. We deliberately diverge: unlike minio we support only (not ?) and match on runes rather than bytes, so this matcher should not be re-synced from upstream. This is documented in the file header.

    Test plan

  • All existing Test_WildcardSubset, Test_WildcardContains, Test_WildcardMatches tests pass — the fix is internal to matchRunes only

  • Test_WildcardMatches_BacktrackingDoesNotHang completes instantly and fails fast (bounded 5s select) if the exponential algorithm is ever reinstated, rather than hanging until the global CI timeout

  • make verify passes (incl. golangci-lint)
  • Generated with Claude (Opus 4.8)

    Diff: 93 lines (+74 / -19) across 2 files Reviewer: erikgb Review duration: 4067m
    All Vouch review confidence checks passed
    Residual risk 0.03 = Change Risk (0.32) × (1 − Review Confidence (0.92)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.32 · 93 lines diff across 2 files
    0.32
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    91%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.272
    Real PR Conversation Timeline
    11 items
    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Jun 10, 2026 11:47 UTC
    Reviewer

    Pull request overview

    This PR hardens pkg/internal/util wildcard matching against worst-case exponential backtracking by replacing the prior recursive matchRunes implementation with an iterative “checkpoint/backtrack” matcher, and adds a regression test to ensure pathological multi- patterns don’t reintroduce reconcile-worker hangs (CWE-770 / VC-53793).

    Changes:

  • Replaced recursive wildcard matching with an iterative backtracking-checkpoint algorithm in matchRunes.

  • Expanded in-file provenance/docs to note intentional divergence from upstream minio wildcard code and the security motivation.

  • Added a regression test that time-bounds a previously-pathological wildcard pattern to prevent future performance regressions.
  • Reviewed changes

    Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

    | File | Description |
    | ---- | ----------- |
    | pkg/internal/util/wildcard.go | Rewrites matchRunes to an iterative checkpoint/backtrack wildcard matcher and documents the rationale/security context. |
    | pkg/internal/util/wildcard_test.go | Adds a regression test that fails fast if wildcard matching regresses to an exponential-time implementation. |

    ---

    💡 <a href="/cert-manager/approver-policy/new/main?filename=.github/instructions/.instructions.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add Copilot custom instructions</a> for smarter, more guided reviews. <a href="https://docs.github.com/en/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn how to get started</a>.

    erikgb erikgb commented on code on Jun 10, 2026 11:52 UTC
    Code Review
    pkg/internal/util/wildcard.go:1
    @@ -15,7 +15,15 @@ limitations under the License.
     */
     
     // !!
    -// Modified from https://github.com/minio/minio/blob/RELEASE.2020-06-22T03-12-50Z.hotfix/pkg/wildcard/match.go
    +// Originally adapted from https://github.com/minio/minio/blob/RELEASE.2020-06-22T03-12-50Z.hotfix/pkg/wildcard/match.go
    +//
    +// The matcher has since been rewritten (see matchRunes below). The upstream
    +// minio implementation — including the current version in
    +// https://github.com/minio/pkg/blob/master/wildcard/match.go — still uses
    +// recursive backtracking and remains vulnerable to the exponential
    +// worst case fixed here (CWE-770 / VC-53793). We deliberately do not track

    I don't like references to things that are not publicly available. Not in the PR description, and at least not in the code. So I suggest removing VC-53793, which is an internal/closed Palo Alto reference.

    wallrj-cyberark wallrj-cyberark commented on code on Jun 10, 2026 13:41 UTC
    Code Review
    pkg/internal/util/wildcard.go:1
    @@ -15,7 +15,15 @@ limitations under the License.
     */
     
     // !!
    -// Modified from https://github.com/minio/minio/blob/RELEASE.2020-06-22T03-12-50Z.hotfix/pkg/wildcard/match.go
    +// Originally adapted from https://github.com/minio/minio/blob/RELEASE.2020-06-22T03-12-50Z.hotfix/pkg/wildcard/match.go
    +//
    +// The matcher has since been rewritten (see matchRunes below). The upstream
    +// minio implementation — including the current version in
    +// https://github.com/minio/pkg/blob/master/wildcard/match.go — still uses
    +// recursive backtracking and remains vulnerable to the exponential
    +// worst case fixed here (CWE-770 / VC-53793). We deliberately do not track

    Good point, thanks — agreed that closed/internal references don't belong in a public repository. I've removed the VC-53793 reference from the code, the PR description, and the commit message, keeping the public CWE-770 reference instead.

    Generated with Claude (Opus 4.8)

    wallrj-cyberark wallrj-cyberark commented on code on Jun 10, 2026 14:24 UTC
    Code Review
    pkg/internal/util/wildcard_test.go:1
    @@ -304,3 +306,29 @@ func Test_WildcardMatches(t *testing.T) {
     		})
     	}
     }
    +
    +// Test_WildcardMatches_BacktrackingDoesNotHang verifies that patterns with
    +// multiple wildcards do not cause exponential backtracking. The pattern
    +// "*a*a*a*a*a*a*a*a*!" against a string of 50 'a' characters would explore
    +// ~2^50 branches with the old recursive algorithm; the iterative replacement
    +// handles it in O(n*m). If the iterative algorithm is accidentally reverted,
    +// the call below will not return and the bounded select fails the test with an
    +// actionable message, rather than hanging until the global test timeout fires.
    +func Test_WildcardMatches_BacktrackingDoesNotHang(t *testing.T) {

    Test evidence — this guard was verified against the previous implementation.

    I ran this exact test against the old recursive matchRunes from main (keeping the new test file, swapping only the source), then against the new iterative implementation:

    # Old recursive implementation (git restore --source=main -- pkg/internal/util/wildcard.go)
    $ go test ./pkg/internal/util/ -run Test_WildcardMatches_BacktrackingDoesNotHang -v
    === RUN   Test_WildcardMatches_BacktrackingDoesNotHang
        wildcard_test.go:332: WildcardMatches("*a*a*a*a*a*a*a*a*!", ...) did not return within 5s; exponential backtracking has regressed
    --- FAIL: Test_WildcardMatches_BacktrackingDoesNotHang (5.00s)
    FAIL
    
    # New iterative implementation
    $ go test ./pkg/internal/util/ -run Test_WildcardMatches_BacktrackingDoesNotHang -v
    === RUN   Test_WildcardMatches_BacktrackingDoesNotHang
    --- PASS: Test_WildcardMatches_BacktrackingDoesNotHang (0.00s)
    PASS
    

    So the guard fails fast (5.00s, via the bounded select) on the vulnerable code and passes instantly on the fix — confirming it would catch a regression rather than silently hanging CI.

    Generated with Claude (Opus 4.8)

    wallrj-cyberark wallrj-cyberark commented on code on Jun 10, 2026 15:22 UTC
    Code Review
    pkg/internal/util/wildcard.go:1
    @@ -65,27 +73,47 @@ func WildcardMatches(pattern, str string) bool {
     	return matchRunes([]rune(pattern), []rune(str))
     }
     
    -// matchRunes will return whether the given rune slice matches the given
    -// pattern using wildcards ('*').
    +// matchRunes returns whether str matches pattern using '*' wildcards.
    +// It uses an iterative backtrack-checkpoint algorithm that runs in O(n*m)
    +// time, replacing the original recursive implementation which was O(2^n)
    +// with multiple wildcards. See CWE-770.
    +//
    +// This is the standard greedy wildcard matcher: on each '*' we record a single
    +// checkpoint (starPx/starSx) and, on a later mismatch, rewind str one past that
    +// checkpoint rather than forking into two recursive calls. Only the most recent
    +// '*' needs remembering. The same technique backs Go's path/filepath.Match,
    +// glibc's glob(3) and many other production matchers. References:
    +//   - Russ Cox, "Glob Matching Can Be Simple And Fast Too" https://research.swtch.com/glob
    +//   - https://en.wikipedia.org/wiki/Matching_wildcards (non-recursive section)
     func matchRunes(pattern, str []rune) bool {

    For reviewers: here is an interactive, step-through animation of this matchRunes algorithm — it highlights the executing source line on the left while the px/sx pointers and the checkpoint move on the right, with play/pause/scrub and editable pattern/text inputs:

    https://gistpreview.github.io/?e52c57571c31e955950e861d25e3bb22

    It makes the key property easy to see: only a single checkpoint is kept and grown by one character on each mismatch (O(n·m)), rather than the old recursive fork at every .

    Generated with Claude (Opus 4.8)

    inteon inteon commented on code on Jun 10, 2026 15:38 UTC
    Code Review
    pkg/internal/util/wildcard.go:1
    @@ -15,7 +15,15 @@ limitations under the License.
     */
     
     // !!
    -// Modified from https://github.com/minio/minio/blob/RELEASE.2020-06-22T03-12-50Z.hotfix/pkg/wildcard/match.go
    +// Originally adapted from https://github.com/minio/minio/blob/RELEASE.2020-06-22T03-12-50Z.hotfix/pkg/wildcard/match.go

    This URL does not work for me

    wallrj-cyberark wallrj-cyberark commented on code on Jun 10, 2026 16:29 UTC
    Code Review
    pkg/internal/util/wildcard.go:1
    @@ -15,7 +15,15 @@ limitations under the License.
     */
     
     // !!
    -// Modified from https://github.com/minio/minio/blob/RELEASE.2020-06-22T03-12-50Z.hotfix/pkg/wildcard/match.go
    +// Originally adapted from https://github.com/minio/minio/blob/RELEASE.2020-06-22T03-12-50Z.hotfix/pkg/wildcard/match.go

    Thanks — you're right, that URL was 404. The original had a bogus .hotfix suffix on the tag; the real release tag is RELEASE.2020-06-22T03-12-50Z. Fixed in 93811b7:

    https://github.com/minio/minio/blob/RELEASE.2020-06-22T03-12-50Z/pkg/wildcard/match.go

    While there I also tidied the surrounding note: minio/minio is now archived, so I dropped the "still vulnerable" framing and just record the provenance plus why we intentionally diverge (iterative rewrite, -only, rune-based) — and corrected the second link (minio/pkg master → main).

    Generated with Claude (Opus 4.8)*

    wallrj-cyberark wallrj-cyberark commented on Jun 10, 2026 16:51 UTC
    Author

    This test failure looks like an unrelated flake, not a regression from this PR.

  • The failing spec is in the readiness controller integration suite (pkg/internal/controllers/test/ready.go:363: "…after enqueue event but for wrong name, should not change returning not-ready"), which is unrelated to the wildcard matcher this PR changes (pkg/internal/util/wildcard.go). The util unit tests all passed, and the latest push only edited comments/links.

  • The spec waitForNotReadys, then flips the fake reconciler to ready (i++) and sends an enqueue event for the wrong name, asserting via Consistently that the policy stays not-ready. The build log shows a residual reconcile of the real policy (reconcileID="7eaa082a-...", originating from the initial Create's watch sources) landing just after i++ — it returns ready=true and trips the assertion. That reconcile is leftover post-create churn, not the wrong-name event, so the outcome is timing-dependent.

  • test was green on the previous commit of this branch; only comment/URL text has changed since.
  • /retest

    Generated with Claude (Opus 4.8)

    inteon inteon commented on Jun 12, 2026 12:20 UTC
    Contributor

    I was not able to find a way to break this algorithm.

    /approve
    /lgtm

    cert-manager-prow[bot] cert-manager-prow[bot] commented on Jun 12, 2026 12:20 UTC
    Bot

    [APPROVALNOTIFIER] This PR is APPROVED

    This pull-request has been approved by: <a href="https://github.com/cert-manager/approver-policy/pull/925#issuecomment-4691207622" title="LGTM">inteon</a>

    The full list of commands accepted by this bot can be found here.

    The pull request process is described here

    <details >
    Needs approval from an approver in each of these files:

  • ~~OWNERS~~ [inteon]
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":[]} -->

    Reviewers
    Assignees
    wallrj-cyberark wallrj-cyberark
    Labels
    risk: low confidence: 91.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 31.6% (LOW) · Higher = larger blast radius
    31.6%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 91.9% · Lower = rushed or shallow review
    91.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 2.6% · Safe to merge
    2.6%