Skip to content

fix(repo): repo security reads repeated rm -r, git -C push chains, long flag words, curl, pip install and path parts in linear time - #1353

Open
antonwolfy wants to merge 5 commits into
intel:mainfrom
antonwolfy:fix/linear-security-scans
Open

antonwolfy wants to merge 5 commits into
intel:mainfrom
antonwolfy:fix/linear-security-scans

Conversation

@antonwolfy

Copy link
Copy Markdown
Contributor

Summary

Four open issues about the command rules of dokimi repo security (dokimi/dokimi/repos/security.py): a line of one repeated keyword takes quadratic time, because each repeat starts a scan that reads the rest of the segment (or of the word). Measured as the CPU time at 16n over that at n (n=150, tests/growth_timing.py; linear is about 16, the limit of the tests 64):

Issue Input On main Here
#688 RULES['destructive-delete'] on "rm -r " * n 250 16.0
#688 the same on "rm -rf " * n (0.64 s for 3000 repeats) 251 16.0
#688 RULES['secret-read'] on "a/" * n (one word) 246 15.4
#688 the same on "~/" * n 239 15.4
#688 the same on "/etc" * n 220 15.7
#1267 RULES['history-rewrite'] on "git " + "-C push " * n 218 16.1
#1267 the same on "git " + "-C reset " * n 180 16.0
#1267 _PUSH_NO_VERIFY on "git " + "-C push " * n 120 15.7
#1267 _COMMIT_NO_VERIFY on "git " + "-C commit " * n 231 15.8
#1268 RULES['history-rewrite'] on "git push -" + "f" * n + "1" 224 14.4
#1269 RULES['pipe-to-shell'] on "curl x " * n 176 15.6
#1269 the same on "wget x " * n 183 16.1
#1269 RULES['unpinned-install'] on "pip install " * n 258 16.1

The git -c scan of history-rewrite and hook-bypass (16.2 and 16.0) and the secret-read scan of a line of repeated a/ words (15.7), two parts of #688, were already linear on main (#1270). This PR adds a growth test for each so they stay so.

What each fix does, and the option taken where an issue lists several:

Closes #688

Closes #1267

Closes #1268

Closes #1269

The same quadratic scans in other rules, found while searching for sites with these causes, are tracked in #1349 (history-rewrite and hook-bypass on git followed by a newline and a chain of -C push), #1350 (destructive-delete on a long flag word), #1351 (destructive-delete on a chain of words that end in rm) and #1352 (pipe-to-shell on a long path after the pipe).

Changes

  • dokimi/dokimi/repos/security_patterns.py (new): the pattern of destructive-delete (RM_RECURSIVE), the anchors of pipe-to-shell (DOWNLOAD) and unpinned-install (PIP_INSTALL, PIP_STUCK) and the start of a path inside a word for secret-read (SECRET_WORD_START), with the constants they use (BLANKS, SYSTEM_DIRS, CLEANUP_PARTS, PIP_URL_OPTS) moved from security.py. security.py was at 799 of its 800 lines and the growth ratchet only shrinks.
  • security.py: pipe-to-shell starts at the first download of each segment, unpinned-install at the first pip install after the start of its segment or after an option word -i=.
  • security.py: the opener of history-rewrite and of the commit and push branches of hook-bypass is lazy, takes -C as a word first, and is atomic, so it is cut at its first end (_first_in_segment, _COMMIT_OPT_LOCAL_WORD_FIRST, _GIT_PUSH). The push branch's opener is read on one line: an opener with a newline in its whitespace is the across-lines branch's.
  • security.py: the force flag of history-rewrite (_PUSH_FORCE) takes the flag word possessively after a lookahead for the f.
  • security.py: secret-read starts its path scan at the first / of a word (SECRET_WORD_START).
  • dokimi/tests/test_security_linear_scans.py (new): for each rule a table of lines and a random-lines comparison against a copy of the old pattern, and growth tests. It is a new file because tests/test_linear_scan_sites.py would pass the 1000-line cap; it imports CASES and _security_search from there. No existing test changed.
  • Five changelog fragments (Fixed): one per issue, and one more for the secret-read part of repo security: keyword scans for rm -rf, git -c and a/ are quadratic in repeats on one line #688.

Risk

None for what the rules match: each pattern finds the same lines as before, pinned by the tables and by random-lines comparisons with a copy of the old pattern. The scan only asks whether a pattern matches (security.py:344), so the span of a match, which now starts at the segment (or at the word, for secret-read), is not used. The patterns use atomic groups and possessive quantifiers, which need Python 3.11, the minimum the package requires.

Testing

On Linux, at 53e9ace4 (on main 1673824):

  • make ci-local: 38 passed, 0 failed, 15 skipped (the docker and network catalog smoke, the pinned Claude Code fidelity run, jobs that run on a schedule or not on a pull request, the other CI matrix legs, conda-forge, the fuzz run, semgrep). 30341 tests passed, 23 skipped; changed-line coverage 100% (18 lines); mutation of changed lines 36 of 36 killed.
  • On main's code the first version of the new test file gave 19 failed, 169 passed: each growth test failed its limit (the first, curl x repeated: assert 201.2 < 64); the tables and the random comparisons passed, as they compare a pattern with its own copy. The secret-read tests added since (40 selected) give 6 failed, 34 passed on the code before their commit: the six growth tests (assert 235.2 < 64 and the like).
  • 23 breaks of the change, one each in a copy, each fail the test that pins it (the table of lines, the random comparison or a growth test); a 24th, which lets the push branch's opener span lines, leaves the results the same, as the across-lines branch covers those openers.
  • Not run: the matrix legs on Python 3.11, 3.12 and 3.14 (this run is on 3.13), the docker and network steps.

Open questions

None.

Revert

A plain revert restores the quadratic scans and the old position of the patterns in security.py. Nothing is stored.

Checklist

  • Tests added/updated and pytest passes
  • ruff, mypy, and schema checks pass
  • Docs updated (or N/A) — see the docs-drift checklist in CONTRIBUTING.md [N/A: no page states the scan's complexity]
  • Self-reviewed per "Before opening a PR" in AGENTS.md
  • Each new raise/exit and test names the doc, contract or issue it traces to
  • No ad-hoc run artifacts committed
  • New files carry the SPDX license header (or are exempt in .github/.licenserc.yaml)

…tel#688)

The destructive-delete rule started its scan at every `rm` and read the words after the recursive flag up to the end of the segment for a target, so a line of repeated `rm -r` or `rm -rf` was read once per `rm` (0.64 s for 3000 repeats of `rm -rf `).

The rule now reads from the first `rm` of each segment that has a recursive flag, and takes the first recursive flag of that `rm` only: a later `rm` or flag of the same segment finds its target only where that one does. A flag word that holds a `;`, `&` or `|` ends the segment inside the flags, so a second branch reads those chains from each `rm` as before. The lines the rule matches are the same, which a table and a random-lines comparison against the old pattern pin.

The pattern moves to `repos/security_patterns.py` with the constants it uses (`BLANKS`, `SYSTEM_DIRS`, `CLEANUP_PARTS`): `repos/security.py` is at its length cap. The tests of the linear scans are in a new file for the same reason: `tests/test_linear_scan_sites.py` is near its cap.

The `git -c` scans of history-rewrite and hook-bypass (intel#1270) are already linear, as is the secret-read scan of a line of repeated `a/ ` words: growth tests keep them so. This commit does not change those rules.

Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
…n linear time (intel#1267)

In `git -C push -C push ...` the option `-C` may take `push` as its argument or leave it as the subcommand, so the opener had one end at every `push` of the chain and the rest of the segment was scanned for the closer from each end: a chain of `-C push`, `-C reset` or `-C commit` was quadratic in history-rewrite, the push branch and the commit branch of hook-bypass.

The opener now takes `-C` as a word of its own before it takes the next word as its argument, and is cut at its first end. A later end finds its closers only where the first does, because the closers read the same segment (or line) to its end, so the lines the rules match are the same. The issue's first option, refusing the subcommand's name as the argument of `-C`, changes results: `git -C push\npush -f` (`-C` takes `push`, the second `push` is on the next line) stops matching in history-rewrite, so it is not taken. The push branch's opener is read on one line only: an opener with a newline in its whitespace is the across-lines branch's, which ends on a later line.

A table of lines (including `git -C push push -f`, `git -C reset reset --hard`, `git -C commit commit --no-verify` and the newline variants) and a random-lines comparison against the old patterns pin the results; growth tests pin the chains.

Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
…inear time (intel#1268)

The force flag of history-rewrite, `\s-[a-z]*f[a-z]*\b`, tried every split of a long letter word around its `f` when the word ends in a character that is no word boundary (`git push -fff...f1`), which is quadratic in the word.

The flag is now `\s-(?=[a-z]*f)[a-z]++\b`: a lookahead finds the `f` once and the letters are taken possessively. The word can only end at the end of its letters, since a `\b` after an earlier letter never holds, so the possessive form gives the same hit as the old flag on `-fff1`, `-ff-x`, `-f_` and the other words of the table, and on random words of letters, digits, `_`, `-` and non-ASCII letters.

Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
…n linear time (intel#1269)

Both rules started at every opener word (`curl`, `wget`, `pip install`) and read the rest of the segment for their tail, so a line of repeated openers with no tail was read once per opener.

pipe-to-shell now starts at the first download of each segment (up to `|`, `;` or `&`): a later download reaches the same `|`, so it finds the tail only where the first does. unpinned-install starts at the first `pip install` followed by a blank, after the start of its segment (a newline, `;`, `&`, `|`) or after an option word such as `-i=` that no word can follow (a later `pip install` reads the words after it again, so that point is a start of its own). The first `pip install` after such a point reads the same words as a later one and finds the same tail. Starting at the first opener of the segment alone would have lost `pip install -i= pip install https://x`.

The lines the rules match are the same: tables and random-lines comparisons against the old patterns pin them, and growth tests pin the repeated openers. The anchors are in `repos/security_patterns.py`, with `PIP_URL_OPTS` moved there from `repos/security.py`.

Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
…time (intel#688)

The `secret-read` rule started its `/\S*?/.name` scan at every `/` of a word, so a word of repeated path parts (`a/a/a/...`, `~/~/...`, `/etc/etc/...`) was read again to its end from each `/`: quadratic in the length of the word. The intel#1270 `a/ ` timing used separate words and did not show it.

The scan now starts at the word's start and takes its first `/` only (`SECRET_WORD_START`, possessive over the characters before it): the first `/` of a word reaches every `/.name` that a later `/` does, so the lines it matches are the same. A table of words and a random-lines comparison against the old pattern pin that, and growth tests cover `a/`, `~/` and `/etc` repeated in one word.

Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
@exai-bot

exai-bot commented Nov 27, 2026 •

Copy link
Copy Markdown

🔍 OpenCodeReview found 3 issue(s) in this PR.

CI at `53e9ace`: 1 failing, 24 passing, 4 skipped

CI has one failed test check; the other 28 checks passed or were skipped. The failure occurs in unchanged process-runner code during a 512 MiB allocation test, not in the modified security rules; the available evidence does not establish whether this is a runner/resource transient or a reproducible existing failure.

Check Status Assessment
Tests (py3.14) failing at step Run tests Cause unclear. The capped allocation succeeded as expected, but the subsequent uncapped child exceeded pytest's 60-second timeout while the parent was polling it. Neither this test nor the process runner changed, and the traceback does not execute the modified security rules; there is no baseline run or...

By label: 1 should fix, 2 not shown by a run

Label Location Finding
should fix security.py:162-165 Impact: repeated installs can still make this synchronous security scan take quadratic work, leaving #1269 incompletely fixed.
not shown by a run security.py:162-165 Impact: the repeated-install scan remains quadratic.
not shown by a run security.py:164 Impact: repeated installs still cause quadratic work in the synchronous security scan, leaving #1269 incompletely fixed.
Review details
  • Commit reviewed: 53e9ace against merge base 1673824
  • Coverage: 8 files in 1 groups
  • Engine: OpenCodeReview v1.13.5-exai.4.8f73eada, us.openai.gpt-6.1-sol
  • Usage: 453k tokens (308k from cache), 2m21s
  • Tool calls: 23 (11 file_read, 3 code_comment, 3 linked_items, 2 ci_status, 2 code_search, 2 local_check_results)
  • Linear-time security scans, shared patterns, tests, and changelogs: 8 files
  • ⏭️ Skipped (overlap with history): 1 comment(s)

Comment on lines +162 to +165
_rx(r"(?:^|[\n;&|]|" + PIP_STUCK + r")(?:(?!" + PIP_INSTALL + r")(?!" + PIP_STUCK + r")[^\n;&|])*" + PIP_INSTALL
+ r"(?:" + BLANKS + r"(?:(?:" + PIP_URL_OPTS + r")(?:" + BLANKS
+ r"|=)[^\s;&|]+|(?!(?:" + PIP_URL_OPTS + r")(?:[\s=;&|]|$))[^\s;&|]+))*?"
+ BLANKS + r"(?:[^\s;&|]*git\+|[\"']?https?://|--break-system-packages\b)")),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

performance · should fix
Impact: repeated installs can still make this synchronous security scan take quadratic work, leaving #1269 incompletely fixed.

Trigger: RULES['unpinned-install'].pattern.search('pip install -i -i= ' * n).

Evidence: the option/value branch consumes -i -i= as one pair, so each opener reads the entire remaining suffix without finding a target. Nevertheless, every -i= also satisfies the new PIP_STUCK restart anchor, which retries from the next pip install; the suffix lengths sum to Θ(n²). The existing growth cases cover pip install -i= but not this paired-option shape.

Workaround: cap command-line length pending a fix. Make restarts account for options consumed as values (or scan/tokenize each segment once), and add this shape to the growth tests.

Should fix: A run shows it, and the code before this change fails the same way.

Shown by running: exit 1 (at the head) · exit 1 (at the merge base) · exit 0 (at the head with the fix)

python proof_c1.py

What the proof does: Times the unpinned-install pattern on 'pip install -i -i= ' * n at n and 16n and fails if the CPU-time ratio reaches the growth limit.

The problem shows as the output QUADRATIC_GROWTH.

Script: dokimi/proof_c1.py (17 lines).

ratio 260.2140768174964
QUADRATIC_GROWTH ratio 260.2

+ _BLANKS + r"(?:[^\s;&|]*git\+|[\"']?https?://|--break-system-packages\b)")),
_rx(r"(?:^|[\n;&|]|" + PIP_STUCK + r")(?:(?!" + PIP_INSTALL + r")(?!" + PIP_STUCK + r")[^\n;&|])*" + PIP_INSTALL
+ r"(?:" + BLANKS + r"(?:(?:" + PIP_URL_OPTS + r")(?:" + BLANKS
+ r"|=)[^\s;&|]+|(?!(?:" + PIP_URL_OPTS + r")(?:[\s=;&|]|$))[^\s;&|]+))*?"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

performance · not shown by a run
Impact: repeated installs still cause quadratic work in the synchronous security scan, leaving #1269 incompletely fixed.

Trigger: RULES['unpinned-install'].pattern.search('pip install -i -i= ' * n).

Evidence: this option/value branch consumes -i -i= together, letting each opener scan the entire remaining suffix without a target. Every -i= also satisfies the new PIP_STUCK anchor, retrying from the next opener; the suffix lengths sum to Θ(n²). Existing growth cases omit this paired-option shape.

Workaround: cap command-line length pending correction. Make restarts account for options consumed as values, or scan each segment once, and add this input to the growth tests.

Not shown by a run: The proof step did not check this finding.

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.18%. Comparing base (1673824) to head (53e9ace).
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1353      +/-   ##
==========================================
- Coverage   96.19%   96.18%   -0.01%     
==========================================
  Files         499      500       +1     
  Lines       66465    66476      +11     
  Branches    11542    11542              
==========================================
+ Hits        63933    63941       +8     
  Misses       1563     1563              
- Partials      969      972       +3     
Files with missing lines Coverage Δ
dokimi/dokimi/repos/security.py 94.33% <100.00%> (-0.03%) ⬇️
dokimi/dokimi/repos/security_patterns.py 100.00% <100.00%> (ø)

... and 6 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants