Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@

## 2024-05-18 - Pre-compiling regex lists in class body
**Learning:** When optimizing repeated regex matching in list comprehensions with `any()`, pre-compiling individual patterns into a tuple of `re.Pattern` objects provides a reliable speedup. In Python 3, list comprehensions created inside a class body do not have access to the class's scope. A generator expression converted to a tuple (e.g., `tuple(re.compile(p) for p in _PATTERNS)`) must be used instead of a list comprehension to avoid `NameError`.
**Action:** Always use generator expressions converted to tuples when pre-compiling regexes based on other class attributes directly within a class body definition.
65 changes: 38 additions & 27 deletions libs/safety_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import shutil
import tempfile
from dataclasses import dataclass, field
from typing import Dict, List, Optional
from typing import Dict, Optional


# =========================
Expand Down Expand Up @@ -180,6 +180,32 @@ class ExecutionSafetyManager:
r"\bbash\b",
]

_WRITE_PATTERNS_COMPILED = tuple(re.compile(p, re.IGNORECASE) for p in _WRITE_PATTERNS)
_WRITE_ON_HANDLE_PATTERNS_COMPILED = tuple(re.compile(p, re.IGNORECASE) for p in _WRITE_ON_HANDLE_PATTERNS)
_SENSITIVE_POSIX_PREFIXES_COMPILED = tuple(re.compile(p, re.IGNORECASE) for p in _SENSITIVE_POSIX_PREFIXES)
_DESTRUCTIVE_PATTERNS_COMPILED = tuple(re.compile(p) for p in _DESTRUCTIVE_PATTERNS)
_SHELL_PATTERNS_COMPILED = tuple(re.compile(p) for p in _SHELL_PATTERNS)

_WINDOWS_DRIVE_PATTERN = re.compile(r"[a-z]:[\\/]")
_QUOTED_POSIX_PATTERN = re.compile(r"""["']/[^"'\s]""")
_POSIX_SYSTEM_PREFIXES_COMPILED = tuple(re.compile(p, re.IGNORECASE) for p in [
r"/etc/\w+",
r"/tmp/\w+",
r"/var/\w+",
r"/usr/\w+",
r"/root/\w+",
r"/home/\w+/",
r"/proc/\w+",
r"/sys/\w+",
r"/dev/\w+",
r"/boot/\w+",
r"/opt/\w+",
r"/mnt/\w+",
r"/media/\w+",
])
_OPEN_ARGS_PATTERN = re.compile(r"open\s*\(\s*([\"'][^\"']+[\"'])", re.IGNORECASE)
_RD_PATTERN = re.compile(r"\brd\s+/s\s+/q\b")

def __init__(self, unsafe_mode: bool = False):
self.unsafe_mode = unsafe_mode

Expand Down Expand Up @@ -228,7 +254,7 @@ def _has_write_operation(self, code: str) -> bool:
"""Return True if *code* contains any write operation that must be
blocked in SAFE mode.
"""
return any(re.search(p, code, re.IGNORECASE) for p in self._WRITE_PATTERNS)
return any(p.search(code) for p in self._WRITE_PATTERNS_COMPILED)

# =========================
# WRITE-ON-HANDLE DETECTION
Expand All @@ -240,42 +266,27 @@ def _has_write_on_handle(self, code: str) -> bool:
"""Return True if *code* calls .write() on any object (handle check).
This is intentionally only evaluated when an absolute path is present.
"""
return any(re.search(p, code, re.IGNORECASE) for p in self._WRITE_ON_HANDLE_PATTERNS)
return any(p.search(code) for p in self._WRITE_ON_HANDLE_PATTERNS_COMPILED)

# =========================
# HOST ABSOLUTE PATH CHECK
# =========================
def _is_host_absolute_path(self, code: str) -> bool:
"""Return True if *code* references a host absolute path."""
# Windows drive-letter path
if re.search(r"[a-z]:[\\/]", code.lower()):
if self._WINDOWS_DRIVE_PATTERN.search(code.lower()):
return True

# Quoted POSIX absolute path: '/...' or "/..."
if re.search(r"""["']/[^"'\s]""", code):
if self._QUOTED_POSIX_PATTERN.search(code):
return True

# Unquoted well-known POSIX system directory prefixes
_posix_system_prefixes = [
r"/etc/\w+",
r"/tmp/\w+",
r"/var/\w+",
r"/usr/\w+",
r"/root/\w+",
r"/home/\w+/",
r"/proc/\w+",
r"/sys/\w+",
r"/dev/\w+",
r"/boot/\w+",
r"/opt/\w+",
r"/mnt/\w+",
r"/media/\w+",
]
if any(re.search(p, code, re.IGNORECASE) for p in _posix_system_prefixes):
if any(p.search(code) for p in self._POSIX_SYSTEM_PREFIXES_COMPILED):
return True

# open() call whose first positional argument is an absolute path string
open_args = re.findall(r"open\s*\(\s*([\"'][^\"']+[\"'])", code, re.IGNORECASE)
open_args = self._OPEN_ARGS_PATTERN.findall(code)
for arg in open_args:
path = arg.strip("'\"")
if path.startswith("/") or re.match(r"[a-zA-Z]:[\\/]", path):
Expand All @@ -285,7 +296,7 @@ def _is_host_absolute_path(self, code: str) -> bool:

def _is_sensitive_posix_path(self, code: str) -> bool:
"""Return True if *code* references a sensitive POSIX system path."""
return any(re.search(p, code, re.IGNORECASE) for p in self._SENSITIVE_POSIX_PREFIXES)
return any(p.search(code) for p in self._SENSITIVE_POSIX_PREFIXES_COMPILED)

# =========================
# MAIN CHECK
Expand All @@ -297,7 +308,7 @@ def assess_execution(self, code: str, mode: str) -> Decision:
code_lower = code.lower()

# HARD BLOCK WINDOWS RECURSIVE DELETE (CRITICAL FIX)
if re.search(r"\brd\s+/s\s+/q\b", code_lower):
if self._RD_PATTERN.search(code_lower):
return Decision(False, ["Recursive deletion is blocked."])

# UNSAFE MODE - still detect dangerous operations but allow with warnings
Expand Down Expand Up @@ -326,15 +337,15 @@ def assess_execution(self, code: str, mode: str) -> Decision:
# (shutdown, reboot, mkfs, dd, format, diskpart) in addition to
# filesystem deletes.
# =========================
if any(re.search(p, code_lower) for p in self._DESTRUCTIVE_PATTERNS):
if any(p.search(code_lower) for p in self._DESTRUCTIVE_PATTERNS_COMPILED):
return Decision(False, ["Destructive operation blocked."])

# =========================
# SHELL BLOCK
# BUG FIX #2: Uses _SHELL_PATTERNS with \b word-boundary regex instead
# of plain substring `in` check to avoid false positives.
# =========================
if any(re.search(p, code_lower) for p in self._SHELL_PATTERNS):
if any(p.search(code_lower) for p in self._SHELL_PATTERNS_COMPILED):
return Decision(False, ["Shell execution is blocked."])

# =========================
Expand Down Expand Up @@ -370,7 +381,7 @@ def is_dangerous_operation(self, code: str) -> bool:
if not code or not code.strip():
return False
code_lower = code.lower()
return any(re.search(p, code_lower) for p in self._DESTRUCTIVE_PATTERNS)
return any(p.search(code_lower) for p in self._DESTRUCTIVE_PATTERNS_COMPILED)

# =========================
# ARTIFACT EXPORT
Expand Down
Loading