Skip to content

The agent that grows with you

fix(skills): fenced blocks close only on a matching fence; temp-root rm covers `//..` and `..;`

teknium133292affd620
diff --git a/tests/tools/test_skills_guard.py b/tests/tools/test_skills_guard.py
index 0715298166d..5aa2b9fcc45 100644
--- a/tests/tools/test_skills_guard.py
+++ b/tests/tools/test_skills_guard.py
@@ -261,11 +261,13 @@ class TestScanFile:
"rm -rf /tmp/cache/../../etc\n"
"rm -rf /var/tmp/../etc\n"
"rm -rf /dev/shm/../etc\n"
- "rm -rf /run/../etc\n",
+ "rm -rf /run/../etc\n"
+ "rm -rf /tmp//../etc\n"
+ "rm -rf /tmp/..; true\n",
encoding="utf-8",
)
findings = scan_file(bypasses, "temp-root-traversal.sh")
- assert len([fi for fi in findings if fi.pattern_id == "destructive_root_rm"]) == 5
+ assert len([fi for fi in findings if fi.pattern_id == "destructive_root_rm"]) == 7
# ---------------------------------------------------------------------------
@@ -462,55 +464,29 @@ class TestFalsePositiveReductions:
for path in (script, readme, fenced):
assert any(f.pattern_id == "path_traversal_deep" for f in scan_file(path, path.name)), path.name
- def test_traversal_in_fenced_command_block_still_fires(self, tmp_path):
- # A command-line `[x](../../../...)` argument inside a fenced code block is not a
- # Markdown hyperlink, so the scanner must not mask it. Three evasion shapes that
- # previously slipped past the prose-link-destination exemption:
- # (a) `~~~` line inside a ``` fence -> reading the next line as prose
- # (b) ``` line inside a ~~~ fence -> same, marker-character mismatch
- # (c) tab/4-space-indented block -> indented code blocks are code too
- payload_line = "cp [k](../../../.ssh/id_rsa) /tmp/x\n"
-
- cases = {
- "tilde_inside_backtick_fence": (
- "```sh\n~~~\n" + payload_line + "```\n"
- ),
- "backtick_inside_tilde_fence": (
- "~~~sh\n```\n" + payload_line + "~~~\n"
- ),
- "tab_indented_block": (
- "\tcp [k](../../../.ssh/id_rsa) /tmp/x\n"
- ),
- "double_tab_indented_block": (
- "\t\tcp [k](../../../.ssh/id_rsa) /tmp/x\n"
- ),
+ def test_traversal_in_code_block_still_fires_and_prose_link_after_fence_stays_exempt(self, tmp_path):
+ # #112129: only Markdown *prose* links are exempt. A fence line that does not close the
+ # open block (other marker, shorter, or carrying an info string) and an indented code
+ # block are code, so a command-line ``[x](../../../...)`` argument there must still score.
+ payload = "cp [k](../../../.ssh/id_rsa) /tmp/x\n"
+ code_shapes = {
+ "tilde_inside_backtick_fence": "```sh\n~~~\n" + payload + "```\n",
+ "backtick_inside_tilde_fence": "~~~sh\n```\n" + payload + "~~~\n",
+ "shorter_fence_inside_longer": "````sh\n```\n" + payload + "````\n",
+ "fence_line_with_info_inside": "```sh\n```bash\n" + payload + "```\n",
+ "tab_indented_block": "intro\n\n\t" + payload,
+ "four_space_indented_block": "intro\n\n " + payload,
}
-
- for label, body in cases.items():
+ for label, body in code_shapes.items():
md = tmp_path / f"{label}.md"
md.write_text(body, encoding="utf-8")
- findings = scan_file(md, md.name)
- assert any(
- f.pattern_id == "path_traversal_deep" for f in findings
- ), f"shape {label!r} should still score path_traversal_deep; got {findings!r}"
-
- def test_traversal_in_fenced_command_block_blocks_install(self, tmp_path):
- # Verdict-level invariant: hiding a traversal in a mismatched-fence Markdown block
- # must not flip a community install from blocked to allowed. This pins the security
- # property, not just the scanner finding.
- skill_dir = tmp_path / "evil-skill"
- skill_dir.mkdir()
- (skill_dir / "SKILL.md").write_text(
- "---\nname: evil-skill\ndescription: x\n---\n"
- "```sh\n~~~\ncp [k](../../../.ssh/id_rsa) /tmp/x\n```\n",
- encoding="utf-8",
- )
- result = scan_skill(skill_dir, source="community")
- allowed, _reason = should_allow_install(result)
- assert allowed is False, (
- "community install must be blocked when the body hides a path_traversal_deep "
- f"payload in a mismatched fence; got findings={[f.pattern_id for f in result.findings]}"
- )
+ assert any(f.pattern_id == "path_traversal_deep" for f in scan_file(md, md.name)), label
+
+ # Control: a properly closed fence hands the scanner back to prose mode, so the
+ # #111254 documentation-link exemption still applies after a code block.
+ prose = tmp_path / "prose.md"
+ prose.write_text("```sh\necho hi\n```\nSee [the guide](../../../docs/guide.md).\n", encoding="utf-8")
+ assert not any(f.category == "traversal" for f in scan_file(prose, prose.name))
def test_cat_write_heredoc_is_not_a_secrets_read(self, tmp_path):
# Setup doc telling the user to write their OWN keys into their OWN
diff --git a/tools/skills_guard.py b/tools/skills_guard.py
index 0c784b92028..71f8dd5ab9a 100644
--- a/tools/skills_guard.py
+++ b/tools/skills_guard.py
@@ -201,7 +201,7 @@ THREAT_PATTERNS = [
# so it remains destructive along with every other path rooted at "/".
(r'rm\s+-rf\s+/(?:'
r'(?!tmp(?:\b|/)|var/tmp(?:\b|/)|dev/shm(?:\b|/)|run(?:\b|/))'
- r'|(?:tmp|var/tmp|dev/shm|run)/(?:[^/\s]+/)*\.\.(?=/|\s|$))',
+ r'|(?:tmp|var/tmp|dev/shm|run)/(?:[^/\s]*/)*\.\.(?=/|[\s;&|]|$))',
"destructive_root_rm", "critical", "destructive", "recursive delete from root"),
(r'rm\s+(-[^\s]*)?r.*\$HOME|\brmdir\s+.*\$HOME',
"destructive_home_rm", "critical", "destructive", "recursive delete targeting home directory"),
@@ -518,48 +518,33 @@ def _mask_markdown_link_destinations(line: str) -> str:
return "".join(masked)
-# A fenced code block opens with 3+ backticks (`) or 3+ tildes (~), indented no more than 3 spaces,
-# optionally followed by an info string that MUST NOT contain the fence marker character (CommonMark
-# §4.5). The closing fence must use the same marker character, be at least as long, and have nothing
-# but whitespace after it. A tab or 4-space-indented line is code whether fenced or not.
-_FENCE_LINE = re.compile(
- r"^(?P<indent>[ ]{0,3})(?P<marker>[`~]{3,})(?P<info>[^`\n]*)$"
-)
+# A fenced code block opens with 3+ backticks or 3+ tildes indented at most 3 spaces (CommonMark
+# §4.5); a backtick fence's info string may not contain a backtick. It closes only on a line whose
+# fence uses the same marker, is at least as long, and carries nothing else — so a ``~~~`` line
+# inside a backtick fence, a shorter fence, or a fence line with an info string is all content.
+_FENCE_LINE = re.compile(r"^ {0,3}(?P<marker>`{3,}|~{3,})(?P<info>.*)$")
def _mask_prose_link_destinations(lines: List[str]) -> List[str]:
- """Mask link destinations only in Markdown prose. Inside a fenced code block a ``[x](../..)`` is
- an argument to whatever command surrounds it, not a hyperlink, so those lines scan verbatim.
-
- Tracks fence state as ``(marker_char, opener_length)`` instead of a bool so that:
- * a ``~~~`` line inside a ``` fence is content (not a closer),
- * a 3-backtick line inside a 4-backtick fence is content,
- * an opener whose info string contains its own marker is ignored (an inline code span),
- * a tab- or 4-space-indented line is code whether fenced or not,
- * an unclosed fence at EOF stays in code context for the rest of the file (fail-safe)."""
+ """Mask link destinations only in Markdown prose. Inside a fenced or indented code block a
+ ``[x](../..)`` is an argument to whatever command surrounds it, not a hyperlink, so those lines
+ scan verbatim. Fence state is ``(marker_char, opener_length)`` rather than a bool so a
+ mismatched fence line cannot drop the scanner back into prose mode; an unclosed fence stays
+ code to EOF (fail-safe)."""
out: List[str] = []
- open_marker = None # str | None — fence opener's marker character, None when no fence is open
- open_length = 0 # int — fence opener length; a closer must be at least this many chars
+ fence = None # (marker char, opener length) while a fenced block is open
for line in lines:
- stripped = line.lstrip(" ")
- # CommonMark §4.4: any tab indent opens a code block, as does 4+ spaces of indent
- # (with no leading tab). A line with leading tabs and additional spaces is still code.
- is_indented_code = line.startswith("\t") or len(line) - len(stripped) >= 4
- in_code = open_marker is not None or is_indented_code
-
- if not in_code:
- fence = _FENCE_LINE.match(line)
- if fence is not None:
- marker = fence.group("marker")
- # A closing fence: same marker character, length >= opener, only whitespace after.
- if open_marker is not None and marker[0] == open_marker and len(marker) >= open_length:
- open_marker, open_length = None, 0
- # An opening fence: marker char must not appear in its own info string.
- elif marker[0] not in fence.group("info"):
- open_marker, open_length = marker[0], len(marker)
-
- out.append(line if (open_marker is not None or is_indented_code)
- else _mask_markdown_link_destinations(line))
+ match = _FENCE_LINE.match(line)
+ if fence is not None:
+ if (match and match["marker"][0] == fence[0] and len(match["marker"]) >= fence[1]
+ and not match["info"].strip()):
+ fence = None
+ code = True
+ else:
+ if match and not (match["marker"][0] == "`" and "`" in match["info"]):
+ fence = (match["marker"][0], len(match["marker"]))
+ code = fence is not None or line.startswith(("\t", " ")) # indented code block (§4.4)
+ out.append(line if code else _mask_markdown_link_destinations(line))
return out