Skip to content

Commit a0cd381

Browse files
committed
fix(security): pin every GHSA-7848 scope decision the mutation gate left open
Check `unit`, run 42377328684 (job 128417628663): the tests passed, then the mutation gate found 52 genuine survivors in _write_scope, anchor, remember and remember_helpers. Root causes: - The details of the global refusals, and the environment each check reads, were never asserted. - memory_writable called require_writable_memory with a tool name it then discarded, and anchor passed a reason string global_scope threw away: both only produced equivalent mutants. The refusal is now decided by a predicate (_refused_domain), and require_global_allowed raises the global refusal, called by global_scope and directly by anchor. - remember computes the scope twice (exact-duplicate record, then the write), so each refusal masked the other. The tests now drive the paths where only one decides: an explicit global replay of a local note, a detected or explicit global replay, and a superseding global write. - The curation loop's skip of an unwritable candidate was not distinguished from stopping the loop. tests_py/invariants/test_I2_canonical_writer.py: the anchor writer moved to line 157 (the import grew by three lines). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018kyZYqpV8QEumVvQXENjQN
1 parent 10b5afb commit a0cd381

5 files changed

Lines changed: 267 additions & 19 deletions

File tree

‎mcp_server/handlers/_write_scope.py‎

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -45,17 +45,26 @@ def _allowed(environ: Mapping[str, str]) -> frozenset[str]:
4545
return frozenset(d.strip().lower() for d in raw.split(",") if d.strip())
4646

4747

48-
def require_writable_domain(
49-
domain: str, tool: str, environ: Mapping[str, str] = os.environ
50-
) -> None:
51-
"""Raise ValidationError when `domain` is another project's than the session's."""
48+
def _refused_domain(domain: str, environ: Mapping[str, str]) -> tuple[str, str] | None:
49+
"""(target, session) when `domain` is another project's than the session's."""
5250
target = resolve_explicit_domain(domain or "")
5351
if not target or target not in project_domains():
54-
return
52+
return None
5553
session = session_domain(environ)
5654
allowed = _allowed(environ)
5755
if target == session or "*" in allowed or target in allowed:
56+
return None
57+
return target, session
58+
59+
60+
def require_writable_domain(
61+
domain: str, tool: str, environ: Mapping[str, str] = os.environ
62+
) -> None:
63+
"""Raise ValidationError when `domain` is another project's than the session's."""
64+
refused = _refused_domain(domain, environ)
65+
if refused is None:
5866
return
67+
target, session = refused
5968
where = f"this session's project ({session!r})" if session else "no known project"
6069
raise ValidationError(
6170
f"{tool}: domain {target!r} belongs to another project than {where}; "
@@ -75,6 +84,16 @@ def _every_project(environ: Mapping[str, str]) -> bool:
7584
return EVERY_PROJECT in _allowed(environ)
7685

7786

87+
def require_global_allowed(tool: str, environ: Mapping[str, str] = os.environ) -> None:
88+
"""Raise ValidationError unless the user allows writes into every project."""
89+
if not _every_project(environ):
90+
raise ValidationError(
91+
f"{tool}: is_global=true writes into every project's memory; "
92+
f"set {ALLOW_ENV}={EVERY_PROJECT} in the environment to allow it",
93+
{"tool": tool, "field": "is_global"},
94+
)
95+
96+
7897
def global_scope(
7998
scope: tuple[bool, str],
8099
explicit: bool,
@@ -86,11 +105,7 @@ def global_scope(
86105
if not is_global or _every_project(environ):
87106
return is_global, reason
88107
if explicit:
89-
raise ValidationError(
90-
f"{tool}: is_global=true writes into every project's memory; "
91-
f"set {ALLOW_ENV}={EVERY_PROJECT} in the environment to allow it",
92-
{"tool": tool, "field": "is_global"},
93-
)
108+
require_global_allowed(tool, environ)
94109
return False, KEPT_LOCAL
95110

96111

@@ -109,8 +124,6 @@ def require_writable_memory(
109124

110125
def memory_writable(row: Mapping, environ: Mapping[str, str] = os.environ) -> bool:
111126
"""Whether a write may pick ``row`` as its target (merge, replica refresh)."""
112-
try:
113-
require_writable_memory(row, "", environ)
114-
except ValidationError:
127+
if row.get("is_global") and not _every_project(environ):
115128
return False
116-
return True
129+
return _refused_domain(row.get("domain") or "", environ) is None

‎mcp_server/handlers/anchor.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@
1717
from mcp_server.infrastructure.memory_config import get_memory_settings
1818
from mcp_server.infrastructure.memory_store import MemoryStore, get_shared_store
1919
from mcp_server.handlers._tool_meta import IDEMPOTENT_WRITE
20-
from mcp_server.handlers._write_scope import global_scope, require_writable_memory
20+
from mcp_server.handlers._write_scope import (
21+
require_global_allowed,
22+
require_writable_memory,
23+
)
2124
import json as _json
2225

2326
# ── Schema ────────────────────────────────────────────────────────────────────
@@ -122,8 +125,8 @@ def _build_anchor_content(content: str, reason: str) -> str:
122125
def _require_anchor_allowed(mem: dict[str, Any], args: dict[str, Any]) -> None:
123126
"""Anchoring rewrites the memory's content and scope (GHSA-7848-qh48-mx2w)."""
124127
require_writable_memory(mem, "anchor")
125-
if args.get("is_global", False):
126-
global_scope((True, "explicit"), True, "anchor")
128+
if args.get("is_global"):
129+
require_global_allowed("anchor")
127130

128131

129132
async def handler(args: dict[str, Any] | None = None) -> dict[str, Any]:

‎mcp_server/handlers/remember.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ def _prepare_request(args: dict, store: MemoryStore, write_class: str) -> GateRe
192192

193193
def _exact_record(args: dict[str, Any], request: GateRequest) -> dict[str, Any]:
194194
options = request.options
195-
explicit = bool(args.get("is_global", False))
195+
explicit = bool(args.get("is_global"))
196196
is_global, _ = global_scope(
197197
resolve_global_scope(request.content, request.tags, explicit=explicit),
198198
explicit,
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
"""Each GHSA-7848 refusal reports its exact fields, and each scope decision is pinned.
2+
3+
The mutation gate of #940 (`unit`, run 42377328684) left survivors in four places:
4+
the `details` of the global refusals, the environment each check reads, the scope
5+
`remember` matches an exact duplicate on, the refusal of a superseding global write,
6+
and the curation loop that skips a candidate this session may not change. Each test
7+
below fails on one of those mutations; the session runs in `beta`.
8+
"""
9+
10+
from __future__ import annotations
11+
12+
import subprocess
13+
14+
import pytest
15+
16+
from mcp_server.errors import ValidationError
17+
from mcp_server.handlers import _write_scope, anchor, remember
18+
from mcp_server.handlers.remember import handler as remember_handler
19+
from mcp_server.handlers.remember_helpers import try_curation
20+
from mcp_server.shared import domain_mapping
21+
from tests_py.handlers import test_ghsa_7848_cross_project_write as _base
22+
23+
projects = _base.projects
24+
ALLOW = _write_scope.ALLOW_ENV
25+
SESSION = _write_scope.SESSION_ENV
26+
GLOBAL_REFUSAL = (
27+
"{tool}: is_global=true writes into every project's memory; "
28+
f"set {ALLOW}=* in the environment to allow it"
29+
)
30+
# Detected as global by its content alone, and by its tags alone.
31+
BY_CONTENT = ("Always use tabs in every project.", [])
32+
BY_TAGS = ("beta keeps its build notes here", ["global", "shared", "universal"])
33+
34+
35+
def _refused(call):
36+
with pytest.raises(ValidationError) as caught:
37+
call()
38+
return caught.value
39+
40+
41+
def _beta(projects):
42+
return {SESSION: str(projects / "beta")}
43+
44+
45+
# ── The refusals and the environment they read ──────────────────────────────
46+
47+
48+
def test_the_global_refusal_names_its_tool_and_field(projects):
49+
env = _beta(projects)
50+
for call in (
51+
lambda: _write_scope.require_global_allowed("t", env),
52+
lambda: _write_scope.global_scope((True, "explicit"), True, "t", env),
53+
):
54+
error = _refused(call)
55+
assert str(error) == GLOBAL_REFUSAL.format(tool="t")
56+
assert error.details == {"tool": "t", "field": "is_global"}
57+
58+
59+
def test_global_scope_reads_the_environment_it_is_given(projects, monkeypatch):
60+
monkeypatch.setenv(ALLOW, "*") # the process allows it; the argument does not
61+
env = _beta(projects)
62+
_refused(lambda: _write_scope.global_scope((True, "r"), True, "t", env))
63+
detected = _write_scope.global_scope((True, "r"), False, "t", env)
64+
assert detected == (False, _write_scope.KEPT_LOCAL)
65+
star = {**env, ALLOW: "*"}
66+
assert _write_scope.global_scope((True, "r"), True, "t", star) == (True, "r")
67+
assert _write_scope.global_scope((False, "r"), True, "t", env) == (False, "r")
68+
69+
70+
def test_a_global_memory_refusal_names_the_memory(projects):
71+
row = {"id": 42, "domain": "beta", "is_global": True}
72+
error = _refused(
73+
lambda: _write_scope.require_writable_memory(row, "t", _beta(projects))
74+
)
75+
assert str(error) == (
76+
"t: memory 42 is global, so changing it reaches every project; "
77+
f"set {ALLOW}=* in the environment to allow it"
78+
)
79+
assert error.details == {"tool": "t", "field": "memory_id", "memory_id": 42}
80+
81+
82+
@pytest.mark.parametrize(
83+
"row",
84+
[
85+
{"id": 7, "domain": "alpha", "is_global": False},
86+
{"id": 7, "domain": "beta", "is_global": True},
87+
],
88+
ids=["other-project", "global"],
89+
)
90+
def test_a_memory_check_reads_the_environment_it_is_given(projects, monkeypatch, row):
91+
monkeypatch.setenv(ALLOW, "*") # the process allows it; the argument does not
92+
env = _beta(projects)
93+
_refused(lambda: _write_scope.require_writable_memory(row, "t", env))
94+
assert _write_scope.memory_writable(row, env) is False
95+
96+
97+
def test_a_memory_with_no_domain_stays_writable_next_to_a_placeholder_project(
98+
projects,
99+
):
100+
subprocess.run(["git", "init", "-q", str(projects / "xxxx")], check=True)
101+
domain_mapping._build_registry.cache_clear()
102+
env = _beta(projects)
103+
for row in ({"id": 1, "domain": None}, {"id": 2, "domain": "beta"}):
104+
_write_scope.require_writable_memory(row, "t", env)
105+
assert _write_scope.memory_writable(row, env) is True
106+
107+
108+
# ── anchor ──────────────────────────────────────────────────────────────────
109+
110+
111+
@pytest.mark.asyncio
112+
async def test_anchor_refuses_a_global_scope_with_the_exact_refusal(projects):
113+
own = await remember_handler({"content": "beta anchor note", "force": True})
114+
with pytest.raises(ValidationError) as caught:
115+
await anchor.handler({"memory_id": own["memory_id"], "is_global": True})
116+
assert str(caught.value) == GLOBAL_REFUSAL.format(tool="anchor")
117+
assert caught.value.details == {"tool": "anchor", "field": "is_global"}
118+
119+
120+
# ── remember: the exact-duplicate scope and the superseding write ───────────
121+
122+
123+
@pytest.mark.asyncio
124+
async def test_an_explicit_global_replay_is_refused_not_matched_as_a_duplicate(
125+
projects,
126+
):
127+
note = "beta release checklist lives in the wiki"
128+
await remember_handler({"content": note, "force": True})
129+
with pytest.raises(ValidationError) as caught:
130+
await remember_handler({"content": note, "is_global": True, "force": True})
131+
assert str(caught.value) == GLOBAL_REFUSAL.format(tool="remember")
132+
133+
134+
@pytest.mark.asyncio
135+
@pytest.mark.parametrize(
136+
("content", "tags"), [BY_CONTENT, BY_TAGS], ids=["content", "tags"]
137+
)
138+
async def test_a_detected_global_memory_is_its_own_exact_duplicate(
139+
projects, monkeypatch, content, tags
140+
):
141+
monkeypatch.setenv(ALLOW, "*")
142+
first = await remember_handler({"content": content, "tags": tags, "force": True})
143+
assert first["stored"] is True
144+
assert first["is_global"] is True
145+
replay = await remember_handler({"content": content, "tags": tags, "force": True})
146+
assert replay["reason"] == "exact_duplicate"
147+
assert replay["memory_id"] == first["memory_id"]
148+
149+
150+
@pytest.mark.asyncio
151+
async def test_an_explicit_global_memory_is_its_own_exact_duplicate(
152+
projects, monkeypatch
153+
):
154+
monkeypatch.setenv(ALLOW, "*")
155+
args = {"content": "beta shares this one", "is_global": True, "force": True}
156+
first = await remember_handler(dict(args))
157+
replay = await remember_handler(dict(args))
158+
assert replay["reason"] == "exact_duplicate"
159+
assert replay["memory_id"] == first["memory_id"]
160+
161+
162+
@pytest.mark.asyncio
163+
async def test_a_superseding_global_write_is_refused(projects):
164+
own = await remember_handler({"content": "beta uses port 8080", "force": True})
165+
with pytest.raises(ValidationError) as caught:
166+
await remember_handler(
167+
{
168+
"content": "beta uses port 9090",
169+
"supersedes_id": own["memory_id"],
170+
"is_global": True,
171+
"force": True,
172+
}
173+
)
174+
assert str(caught.value) == GLOBAL_REFUSAL.format(tool="remember")
175+
assert caught.value.details == {"tool": "remember", "field": "is_global"}
176+
177+
178+
@pytest.mark.asyncio
179+
async def test_a_write_that_is_not_stored_reports_no_scope(projects, monkeypatch):
180+
refused = {"stored": False, "action": "superseded_conflict"}
181+
monkeypatch.setattr(
182+
remember, "insert_and_post_process", lambda *a, **k: dict(refused)
183+
)
184+
content, tags = BY_CONTENT # kept local: a scope would be reported if stored
185+
result = await remember_handler({"content": content, "tags": tags, "force": True})
186+
assert result == refused
187+
188+
189+
# ── curation skips, and does not stop at, a memory it may not change ────────
190+
191+
192+
class _Engine:
193+
def similarity(self, a, b) -> float: # noqa: ARG002 — stub contract
194+
return 0.99 # high enough for the merge branch
195+
196+
def encode(self, text: str): # noqa: ARG002 — only hit on merge
197+
return b"\x00" * 4
198+
199+
200+
class _Store:
201+
"""Two near-identical candidates: alpha's ranked first, then beta's."""
202+
203+
def __init__(self) -> None:
204+
self.merged_into: list[int] = []
205+
row = {"content": "deploy target is server one", "embedding": b"\x01"}
206+
self._rows = {
207+
1: {**row, "id": 1, "domain": "alpha", "superseded_by_id": None},
208+
2: {**row, "id": 2, "domain": "beta", "superseded_by_id": None},
209+
}
210+
for r in self._rows.values():
211+
r.update(compression_level=0, heat=0.5, is_global=False)
212+
213+
def search_vectors(self, embedding, top_k=3, min_heat=0.0): # noqa: ARG002
214+
return [(1, 0.01), (2, 0.02)]
215+
216+
def get_memories_by_ids(self, ids):
217+
return {mid: self._rows[mid] for mid in ids if mid in self._rows}
218+
219+
def update_memory_compression(self, mid, *args, **kwargs): # noqa: ARG002
220+
self.merged_into.append(mid)
221+
222+
def update_memory_heat(self, mid, heat): # noqa: ARG002
223+
pass
224+
225+
226+
def test_curation_skips_another_projects_candidate_and_merges_the_next(projects):
227+
store = _Store()
228+
action, target = try_curation(
229+
"deploy target is server one", b"\x01", False, store, _Engine(), [], 0.5
230+
)
231+
assert (action, target) == ("merge", 2)
232+
assert store.merged_into == [2]

‎tests_py/invariants/test_I2_canonical_writer.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555
("infrastructure/pg_store_heat.py", 66),
5656
("infrastructure/sqlite_store.py", 555),
5757
# Anchor pin.
58-
("handlers/anchor.py", 154),
58+
("handlers/anchor.py", 157),
5959
# Atomic cue boost: the project-scoped file cues moved from the hook in
6060
# ADR-1086, and the pipeline impact bump moved from its hook (ADR-0493,
6161
# issue #750) so SQLite runs it too. One UPDATE serves both.

0 commit comments

Comments
 (0)