Skip to content

Commit 2326394

Browse files
cdeustclaude
andcommitted
fix: resolve all CodeQL security alerts + update auto-backfill tests
Security fixes (all CodeQL alerts): - Critical: git_diff.py command injection — validate args, explicit shell=False - High: path traversal in git_diff.py, http_server.py, http_standalone.py — resolve() + startswith() prefix checks against allowed directories - High: MD5 in embedding_engine.py — replaced with SHA256 - High: ReDoS in compression.py — [a-zA-Z]+ → [a-z]+ in CamelCase regex - High: incomplete sanitization in detail_format.js — bounded tag regex - High: double escaping in detail_diff.js — decode &amp; last not first - Medium: HTML attribute injection in detail_format.js — escape quotes - Medium: CI workflow permissions — add contents: read Test updates: - Updated cold start tests for auto-backfill behavior (no longer asks consent) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1 parent afe6a0d commit 2326394

9 files changed

Lines changed: 80 additions & 45 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ on:
77
branches: [main]
88
workflow_dispatch:
99

10+
permissions:
11+
contents: read
12+
1013
concurrency:
1114
group: ${{ github.workflow }}-${{ github.ref }}
1215
cancel-in-progress: true

‎mcp_server/core/compression.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
re.IGNORECASE,
2929
)
3030
_NUMBER_VERSION_RE = re.compile(r"\b\d+(?:\.\d+)+\b")
31-
_CAMELCASE_RE = re.compile(r"\b[A-Z][a-zA-Z]+(?:[A-Z][a-zA-Z]+)+\b")
31+
_CAMELCASE_RE = re.compile(r"\b[A-Z][a-z]+(?:[A-Z][a-z]+)+\b")
3232

3333

3434
def _parse_created_at(memory: dict) -> datetime | None:

‎mcp_server/infrastructure/embedding_engine.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,15 +212,15 @@ def _fallback_encode(self, text: str) -> bytes:
212212
# Character trigram hashing
213213
for i in range(len(text_lower) - 2):
214214
trigram = text_lower[i : i + 3]
215-
h = int(hashlib.md5(trigram.encode()).hexdigest(), 16)
215+
h = int(hashlib.sha256(trigram.encode()).hexdigest(), 16) # non-security: deterministic bucketing
216216
idx = h % self._dim
217217
vec[idx] += 1.0
218218

219219
# Word-level hashing for semantic signal
220220
words = text_lower.split()
221221
for word in words:
222222
if len(word) > 2:
223-
h = int(hashlib.md5(word.encode()).hexdigest(), 16)
223+
h = int(hashlib.sha256(word.encode()).hexdigest(), 16) # non-security: deterministic bucketing
224224
idx = h % self._dim
225225
vec[idx] += 2.0 # Words weighted more than trigrams
226226

‎mcp_server/infrastructure/git_diff.py‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,9 @@ def resolve_file(name: str, git_root: Path) -> str | None:
6262
if f.endswith("/" + basename) or f == basename:
6363
return f
6464

65-
# File exists on disk but untracked
66-
full = git_root / rel
67-
if full.is_file():
65+
# File exists on disk but untracked — validate path stays within repo
66+
full = (git_root / rel).resolve()
67+
if full.is_file() and str(full).startswith(str(git_root.resolve())):
6868
return rel
6969

7070
return None
@@ -102,9 +102,12 @@ def get_file_diff(filepath: str, git_root: Path, max_lines: int = 80) -> dict:
102102
if content:
103103
return _content_as_new(filepath, content, max_lines)
104104

105-
# 5. Direct read for untracked files
106-
full_path = git_root / filepath
107-
if full_path.is_file():
105+
# 5. Direct read for untracked files — validate path stays within repo
106+
full_path = (git_root / filepath).resolve()
107+
if (
108+
full_path.is_file()
109+
and str(full_path).startswith(str(git_root.resolve()))
110+
):
108111
try:
109112
content = full_path.read_text(errors="replace")
110113
if content:
@@ -134,10 +137,19 @@ def _to_relative(name: str, git_root: Path) -> str:
134137

135138

136139
def _git_cmd(cmd: list[str], cwd: Path) -> str:
137-
"""Run a git command and return stripped stdout, or empty string."""
140+
"""Run a git command and return stripped stdout, or empty string.
141+
142+
Security: cmd must be a list (no shell=True). All arguments are passed
143+
as separate list elements to prevent shell injection. The cwd is validated
144+
to be under the git root.
145+
"""
138146
try:
139-
result = subprocess.run(
140-
cmd, capture_output=True, text=True, cwd=str(cwd), timeout=10
147+
# Validate: only allow git commands, never shell=True
148+
if not cmd or cmd[0] != "git":
149+
return ""
150+
result = subprocess.run( # noqa: S603
151+
cmd, capture_output=True, text=True, cwd=str(cwd), timeout=10,
152+
shell=False,
141153
)
142154
return result.stdout.strip() if result.returncode == 0 else ""
143155
except (subprocess.TimeoutExpired, FileNotFoundError):

‎mcp_server/server/http_server.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,14 @@ def _serve_graph_json(handler, server_state: dict) -> None:
133133
def _serve_static(handler, base_dir: Path, filename: str, content_type: str) -> None:
134134
"""Serve a static file from the given directory."""
135135
try:
136-
file_path = base_dir / filename
136+
# Sanitize: strip path components, use only the basename
137+
safe_name = Path(filename).name
138+
file_path = (base_dir / safe_name).resolve()
139+
# Validate: resolved path must stay within base_dir
140+
if not str(file_path).startswith(str(base_dir.resolve())):
141+
handler.send_response(403)
142+
handler.end_headers()
143+
return
137144
body = file_path.read_bytes()
138145
handler.send_response(200)
139146
handler.send_header("Content-Type", content_type)

‎mcp_server/server/http_standalone.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,12 @@ def log_message(self, format, *args):
406406
def _serve_static(handler, base_dir: Path, filename: str, content_type: str) -> None:
407407
"""Serve a static file, sanitizing filename."""
408408
safe_name = Path(filename).name
409-
file_path = base_dir / safe_name
409+
file_path = (base_dir / safe_name).resolve()
410+
# Validate: resolved path must stay within base_dir
411+
if not str(file_path).startswith(str(base_dir.resolve())):
412+
handler.send_response(403)
413+
handler.end_headers()
414+
return
410415
if not file_path.exists():
411416
handler.send_response(404)
412417
handler.end_headers()

‎tests_py/integration/test_cold_start.py‎

Lines changed: 31 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -93,22 +93,25 @@ def test_normal_session_with_memories(self):
9393
# Should NOT contain setup instructions
9494
assert "brew install" not in output
9595

96-
def test_empty_db_with_session_files_asks_consent(self):
97-
"""When DB is empty but sessions exist, should ask user before importing."""
96+
def test_empty_db_with_session_files_auto_backfills(self):
97+
"""When DB is empty but sessions exist, auto-backfill runs and reports result."""
98+
from unittest.mock import patch
99+
98100
from mcp_server.hooks.session_start import _build_cold_start_message
99101

100102
setup_result = {
101103
"status": "ready",
102104
"memories": 0,
103105
"session_files": 150,
104106
}
105-
msg = _build_cold_start_message(setup_result)
107+
# Mock _auto_backfill to avoid actual DB operations
108+
with patch(
109+
"mcp_server.hooks.session_start._auto_backfill", return_value=42
110+
):
111+
msg = _build_cold_start_message(setup_result)
106112

107-
assert "150 conversation files" in msg
108-
assert "Would you like me to import" in msg
109-
assert "backfill" not in msg.lower() or "import" in msg.lower()
110-
# Must NOT auto-import — user consent required
111-
assert "automatically" not in msg.lower()
113+
assert "auto-imported" in msg.lower() or "42 memories" in msg
114+
assert msg # non-empty
112115

113116
def test_empty_db_no_sessions_shows_getting_started(self):
114117
"""Brand new user with no history gets a friendly start guide."""
@@ -361,32 +364,34 @@ def test_url_parsing(self):
361364
class TestBackfillConsent:
362365
"""Verify backfill never auto-runs — user must explicitly consent."""
363366

364-
def test_session_start_never_calls_backfill(self):
365-
"""The session start hook must NEVER call backfill_memories directly."""
367+
def test_session_start_auto_backfills(self):
368+
"""Session start hook auto-backfills when DB is empty with session files."""
366369
import inspect
367370
from mcp_server.hooks import session_start
368371

369372
source = inspect.getsource(session_start)
370-
# Must not import or call backfill
371-
assert "backfill_memories" not in source
372-
assert "import_sessions" not in source
373+
# Must contain auto-backfill logic
374+
assert "_auto_backfill" in source
375+
assert "backfill" in source.lower()
376+
377+
def test_cold_start_auto_import_reports_count(self):
378+
"""Cold start with sessions auto-imports and reports the count."""
379+
from unittest.mock import patch
373380

374-
def test_cold_start_message_asks_permission(self):
375-
"""Cold start message must ask, not tell."""
376381
from mcp_server.hooks.session_start import _build_cold_start_message
377382

378-
msg = _build_cold_start_message(
379-
{
380-
"status": "ready",
381-
"memories": 0,
382-
"session_files": 500,
383-
}
384-
)
383+
with patch("mcp_server.hooks.session_start._auto_backfill", return_value=42):
384+
msg = _build_cold_start_message(
385+
{
386+
"status": "ready",
387+
"memories": 0,
388+
"session_files": 500,
389+
}
390+
)
385391

386-
# Must contain a question/request for consent
387-
assert "?" in msg or "Would you" in msg or "like me to" in msg
388-
# Must mention the number of files found
389-
assert "500" in msg
392+
# Must report auto-import result
393+
assert "42" in msg
394+
assert "import" in msg.lower() or "memor" in msg.lower()
390395

391396
def test_backfill_handler_exists_and_is_callable(self):
392397
"""The backfill handler should exist for when user says yes."""

‎ui/unified/js/detail_diff.js‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -192,12 +192,14 @@
192192

193193
function esc(s) {
194194
if (!s) return '';
195-
return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
195+
return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
196+
.replace(/"/g, '&quot;').replace(/'/g, '&#x27;');
196197
}
197198

198199
function decodeStr(s) {
199-
return s.replace(/&amp;/g, '&').replace(/&quot;/g, '"')
200-
.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
200+
// Decode HTML entities in the correct order: &amp; last to prevent double-unescaping
201+
return s.replace(/&lt;/g, '<').replace(/&gt;/g, '>')
202+
.replace(/&quot;/g, '"').replace(/&amp;/g, '&');
201203
}
202204

203205
if (document.readyState === 'loading') {

‎ui/unified/js/detail_format.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222

2323
function esc(s) {
2424
if (!s) return '';
25-
return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
25+
return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
26+
.replace(/"/g, '&quot;').replace(/'/g, '&#x27;');
2627
}
2728

2829
// ── Header ──
@@ -138,7 +139,7 @@
138139
.replace(/\*\*([^*]*)\*\*/g, '$1')
139140
.replace(/\*([^*]*)\*/g, '$1')
140141
.replace(/^[\s|:*-]+$/gm, '')
141-
.replace(/<[^>]+>/g, '')
142+
.replace(/<[^>]{0,500}>/g, '')
142143
.replace(/\\u[0-9a-fA-F]{4}/g, '')
143144
.replace(/\\n/g, '\n').replace(/\\t/g, ' ')
144145
.replace(/\n{3,}/g, '\n\n').trim();

0 commit comments

Comments
 (0)