Skip to content

Commit cce502b

Browse files
committed
fix(session): harden session-dir slug against path traversal + server-side ACP guard (P0)
Audit P0 #1 + #2. The user-controlled topic became a session-dir path segment via a naive .replace(' ','-') slug in FOUR places, none of which stripped '/', '\\' or '..' — and the dir is later rmtree'd on failure, so a topic like '../../x' was a real escape+delete vector. - New slug_session_dir() collapses everything outside [a-z0-9] to '-' and falls back to 'session' when empty; session_dir_name() routes through it. - Replace the three inline duplicate slugs (web PTY/ttyd _start.py, CLI session/start.py) with the shared helper — root-cause fix, one segment. - Add server-side ACP capability guard in _start_acp_session: a PTY-only agent (Claude Code, Codex) requesting transport=acp now gets a 400 with cause + repair BEFORE any spawn, instead of an opaque failure. - ACP_CAPABLE_AGENTS is the single source of truth; _options.py's picker flags now reference it instead of a duplicated {kiro,gemini,grok} literal. Tests: parametrized traversal cases + empty-slug fallback + ACP-guard rejection for claude/codex + capable-set lock. Held-out gate: the traversal tests fail on the pre-fix slug (verified by revert), pass on the fix.
1 parent 2d462fb commit cce502b

6 files changed

Lines changed: 134 additions & 8 deletions

File tree

‎packages/studyloop/src/studyloop/session/start.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,12 @@ def start_session(
358358
session_dir = Path(resume_session_dir)
359359
is_resuming = True
360360
else:
361-
slug = topic.lower().replace(" ", "-")[:20]
361+
# slug_session_dir strips path traversal from the user-controlled topic
362+
# (this dir is later rmtree'd on failure, so an unsanitised "../.." is a
363+
# real escape vector — shared with the web session-start paths).
364+
from studyloop.web.services.session_start import slug_session_dir
365+
366+
slug = slug_session_dir(topic)
362367
short_id = study_id[:8] if study_id else "unknown"
363368
session_name = f"study-{slug}-{short_id}"
364369
session_dir = SESSION_DIR / "sessions" / session_name

‎packages/studyloop/src/studyloop/web/routes/session/_options.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from studyloop.settings import MAX_ACTIVE_TOPICS
1414
from studyloop.web.routes.session._models import SessionOption
1515
from studyloop.web.routes.session._router import router
16+
from studyloop.web.services.session_start import ACP_CAPABLE_AGENTS
1617

1718
_SESSION_OPTION_INDEX_VERSION = 1
1819
_SESSION_OPTION_INDEX_LOCK = threading.Lock()
@@ -370,7 +371,7 @@ def _agent_options() -> list[dict[str, object]]:
370371
"label": _agent_label(name),
371372
"value": name,
372373
"available": name in detected,
373-
"supports_acp": name in {"kiro", "gemini", "grok"},
374+
"supports_acp": name in ACP_CAPABLE_AGENTS,
374375
"acp_ready": False,
375376
"recommended_transport": "ttyd",
376377
"binary": adapter.binary,
@@ -384,7 +385,7 @@ def _agent_options() -> list[dict[str, object]]:
384385
"label": _agent_label(name),
385386
"value": name,
386387
"available": False,
387-
"supports_acp": name in {"kiro", "gemini", "grok"},
388+
"supports_acp": name in ACP_CAPABLE_AGENTS,
388389
"acp_ready": False,
389390
"recommended_transport": "ttyd",
390391
"binary": _AGENT_FALLBACK_BINARIES[name],

‎packages/studyloop/src/studyloop/web/routes/session/_start.py‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,26 @@ async def _start_acp_session(body: StartSessionRequest) -> JSONResponse:
281281
)
282282
agent = available[0]
283283

284+
# --- ACP capability guard ---
285+
# Fail early (before spawn) if the resolved agent has no ACP transport.
286+
# Claude Code and Codex are PTY-only; forcing ACP on them dead-ends in a
287+
# spawn failure with an opaque message. Surface the cause + repair instead.
288+
from studyloop.web.services.session_start import ACP_CAPABLE_AGENTS
289+
290+
if agent not in ACP_CAPABLE_AGENTS:
291+
return JSONResponse(
292+
{
293+
"error": f"Agent '{agent}' does not support the ACP transport.",
294+
"agent": agent,
295+
"supported_agents": sorted(ACP_CAPABLE_AGENTS),
296+
"repair": (
297+
f"Use transport 'pty' for {agent}, or pick an ACP-capable "
298+
f"agent ({', '.join(sorted(ACP_CAPABLE_AGENTS))})."
299+
),
300+
},
301+
status_code=400,
302+
)
303+
284304
adapter = AGENTS[agent]
285305
# STUDYLOOP_TEST_ACP_CMD bypasses the binary check entirely — the test
286306
# stub (tests/_stub_acp_agent.py) is the argv we spawn, so the real
@@ -558,8 +578,12 @@ def _start_ttyd_session(body: StartSessionRequest) -> JSONResponse:
558578
PARKING_FILE.touch(mode=0o600, exist_ok=True)
559579

560580
# --- Session directory + tmux ---
581+
# slug_session_dir strips path-traversal from the user-controlled topic;
582+
# this session_name becomes a path segment (and is later rmtree'd on
583+
# cleanup), so an unsanitised "../.." here is a real escape vector.
584+
from studyloop.web.services.session_start import slug_session_dir
561585

562-
slug = body.topic.lower().replace(" ", "-")[:20]
586+
slug = slug_session_dir(body.topic)
563587
short_id = study_id[:8]
564588
session_name = f"study-{slug}-{short_id}"
565589
session_dir = SESSION_DIR / "sessions" / session_name

‎packages/studyloop/src/studyloop/web/services/session_start.py‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,40 @@
22

33
from __future__ import annotations
44

5+
import re
56
from typing import TYPE_CHECKING, Literal
67

78
if TYPE_CHECKING:
89
from datetime import datetime
910

1011
TransportName = Literal["pty", "acp", "ttyd"]
1112

13+
# Agents that speak the Agent Client Protocol. Single source of truth shared by
14+
# the session-start ACP guard and the options endpoint (_options.py). Claude
15+
# Code and Codex are PTY-only; only these three have an ACP transport.
16+
ACP_CAPABLE_AGENTS: frozenset[str] = frozenset({"kiro", "gemini", "grok"})
17+
18+
19+
def slug_session_dir(topic: str) -> str:
20+
"""Return a filesystem-safe slug for a user-supplied topic.
21+
22+
The topic is attacker-controlled (POST body), and the slug becomes a path
23+
segment under ``SESSION_DIR/sessions``. Collapse everything outside
24+
``[a-z0-9]`` to ``-`` so path-traversal vectors (``/``, ``\\``, ``..``)
25+
cannot escape the sessions directory. Falls back to ``"session"`` when the
26+
topic slugs to nothing (e.g. all punctuation).
27+
"""
28+
slug = re.sub(r"[^a-z0-9]+", "-", topic.lower()).strip("-")
29+
return slug[:20] or "session"
30+
1231

1332
def session_dir_name(topic: str, study_id: str, *, prefix: str = "pty") -> str:
14-
"""Return the stable session directory name used by web-started sessions."""
15-
slug = topic.lower().replace(" ", "-")[:20]
16-
return f"{prefix}-{slug}-{study_id[:8]}"
33+
"""Return the stable session directory name used by web-started sessions.
34+
35+
``topic`` is user-controlled; :func:`slug_session_dir` guarantees the
36+
returned name is a single safe path segment (no ``/``, ``\\`` or ``..``).
37+
"""
38+
return f"{prefix}-{slug_session_dir(topic)}-{study_id[:8]}"
1739

1840

1941
def build_session_state_payload(

‎packages/studyloop/tests/test_web_session_start_acp.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,43 @@ def test_acp_start_returns_ws_url_and_no_tmux(
188188
# ---------------------------------------------------------------------------
189189

190190

191+
class TestAcpCapabilityGuard:
192+
"""A PTY-only agent (Claude Code, Codex) requesting ACP fails fast (400)."""
193+
194+
@pytest.mark.parametrize("agent", ["claude", "codex"])
195+
def test_acp_start_rejects_pty_only_agent(
196+
self,
197+
client: TestClient,
198+
_stub_db,
199+
agent: str,
200+
) -> None:
201+
with (
202+
patch("studyloop.web.routes.session.is_session_active", return_value=False),
203+
patch(
204+
"studyloop.session.active.acquire",
205+
side_effect=AssertionError("must not spawn a transport for a PTY-only agent"),
206+
),
207+
):
208+
resp = client.post(
209+
"/api/session/start",
210+
json={"topic": "Python", "energy": 5, "agent": agent, "transport": "acp"},
211+
)
212+
213+
assert resp.status_code == 400, resp.text
214+
body = resp.json()
215+
assert agent in body["error"]
216+
assert "ACP" in body["error"]
217+
assert "repair" in body
218+
assert run_async(active.current()) is None
219+
220+
@pytest.mark.parametrize("agent", ["kiro", "gemini", "grok"])
221+
def test_acp_capable_agents_pass_the_guard(self, agent: str) -> None:
222+
"""The guard admits exactly the ACP-capable set (contract lock)."""
223+
from studyloop.web.services.session_start import ACP_CAPABLE_AGENTS
224+
225+
assert agent in ACP_CAPABLE_AGENTS
226+
227+
191228
class TestAcpStartSingleSession:
192229
def test_acp_start_refuses_when_session_already_active(
193230
self,

‎packages/studyloop/tests/test_web_session_start_service.py‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,13 @@
44

55
from datetime import UTC, datetime
66

7-
from studyloop.web.services.session_start import build_session_state_payload, session_dir_name
7+
import pytest
8+
9+
from studyloop.web.services.session_start import (
10+
build_session_state_payload,
11+
session_dir_name,
12+
slug_session_dir,
13+
)
814

915

1016
def test_session_dir_name_is_short_and_stable() -> None:
@@ -13,6 +19,37 @@ def test_session_dir_name_is_short_and_stable() -> None:
1319
)
1420

1521

22+
@pytest.mark.parametrize(
23+
("topic", "forbidden"),
24+
[
25+
("../../etc/passwd", "/"),
26+
("..\\..\\windows", "\\"),
27+
("a/b/c", "/"),
28+
("nested/../escape", ".."),
29+
],
30+
)
31+
def test_slug_session_dir_strips_path_traversal(topic: str, forbidden: str) -> None:
32+
"""A malicious topic must not escape the sessions directory."""
33+
slug = slug_session_dir(topic)
34+
assert "/" not in slug
35+
assert "\\" not in slug
36+
assert ".." not in slug
37+
assert slug # never empty
38+
39+
40+
def test_slug_session_dir_falls_back_when_empty() -> None:
41+
"""A topic that slugs to nothing yields a safe non-empty default."""
42+
assert slug_session_dir("///") == "session"
43+
assert slug_session_dir("...") == "session"
44+
45+
46+
def test_session_dir_name_is_traversal_safe() -> None:
47+
"""The full session-dir name (used as a path segment) is a single segment."""
48+
name = session_dir_name("../../etc/passwd", "abc123456789")
49+
assert "/" not in name
50+
assert ".." not in name
51+
52+
1653
def test_session_dir_name_accepts_transport_prefix() -> None:
1754
assert session_dir_name("Python Decorators", "abc123456789", prefix="acp") == (
1855
"acp-python-decorators-abc12345"

0 commit comments

Comments
 (0)