Skip to content

Commit 68fb71a

Browse files
committed
fix(security): a resolved domain is never resolved twice; a replica refresh finds this session's own row (GHSA-7848-qh48-mx2w)
Codex on #969. Where a directory name is an alias of one project and the canonical domain of another repository family, re-resolving a canonical refused the family its own writes and let the aliased project change the family's rows. The replica lookup read one row (LIMIT 1): another project's replica hid this session's own and each sync inserted one more row. Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_018kyZYsWnKSjpX4oNV19PCF Signed-off-by: Claude <[email protected]>
1 parent 7eb8a39 commit 68fb71a

7 files changed

Lines changed: 119 additions & 25 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ adheres to [Semantic Versioning](https://semver.org/).
1717
A write stores the domain the check resolved, never the raw argument: `ingest_prd`
1818
and `ingest_document` kept a name that resolves to the session's project but can
1919
also be another repository family's domain.
20+
A domain that is an identity already (resolved from a path, stored on a row) is
21+
never resolved through the name aliases a second time: where a directory name is
22+
also another family's domain, that family keeps its own writes and the aliased
23+
project cannot change its rows. A memory-replica refresh reads every replica of
24+
the block, so another project's row no longer hides this session's own.
2025
A global memory reaches every project, so an explicit `is_global=true` (in
2126
`remember` or `anchor`) needs `CORTEX_CROSS_PROJECT_WRITES=*`; a global scope the
2227
detector infers without it is kept local and reported (`global_reason`). `anchor`,

‎mcp_server/handlers/_write_scope.py‎

Lines changed: 37 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import os
2222
from collections.abc import Mapping
23+
from typing import NoReturn
2324

2425
from mcp_server.errors import ValidationError
2526
from mcp_server.shared.domain_mapping import (
@@ -45,9 +46,16 @@ def _allowed(environ: Mapping[str, str]) -> frozenset[str]:
4546
return frozenset(d.strip().lower() for d in raw.split(",") if d.strip())
4647

4748

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."""
50-
target = resolve_explicit_domain(domain or "")
49+
def _refused_domain(target: str, environ: Mapping[str, str]) -> tuple[str, str] | None:
50+
"""(target, session) when the canonical `target` is another project's domain.
51+
52+
`target` is a domain identity already: resolved from a path, read from a stored
53+
row, or resolved once from a name the caller gave. It is never resolved again
54+
here. A directory name can be an alias of one project and the canonical of
55+
another repository family; resolving a canonical a second time would turn that
56+
family's domain into the aliased project, refuse the family its own writes and
57+
let the aliased project change the family's rows.
58+
"""
5159
if not target or target not in project_domains():
5260
return None
5361
session = session_domain(environ)
@@ -68,11 +76,29 @@ def require_writable_domain(
6876
under the raw name would reach that family's hot memories. A name that resolves
6977
to no known project is a shared domain and is returned as given.
7078
"""
71-
refused = _refused_domain(domain, environ)
72-
if refused is None:
73-
target = resolve_explicit_domain(domain or "")
74-
return target if target in project_domains() else (domain or "")
75-
target, session = refused
79+
target = resolve_explicit_domain(domain or "")
80+
if _refused_domain(target, environ) is not None:
81+
_refuse(target, tool, environ)
82+
return target if target in project_domains() else (domain or "")
83+
84+
85+
def require_writable_canonical(
86+
domain: str, tool: str, environ: Mapping[str, str] = os.environ
87+
) -> None:
88+
"""Raise ValidationError when the already resolved `domain` is another project's.
89+
90+
For a domain that is an identity already (resolved from a path by `remember` or
91+
`seed_project`, or stored on a row): it is compared as it is, never resolved
92+
through the name aliases a second time (see `_refused_domain`).
93+
"""
94+
target = (domain or "").strip().lower()
95+
if _refused_domain(target, environ) is not None:
96+
_refuse(target, tool, environ)
97+
98+
99+
def _refuse(target: str, tool: str, environ: Mapping[str, str]) -> NoReturn:
100+
"""Raise the refusal of a write into `target`, another project's domain."""
101+
session = session_domain(environ)
76102
where = f"this session's project ({session!r})" if session else "no known project"
77103
raise ValidationError(
78104
f"{tool}: domain {target!r} belongs to another project than {where}; "
@@ -127,11 +153,12 @@ def require_writable_memory(
127153
f"project; set {ALLOW_ENV}={EVERY_PROJECT} in the environment to allow it",
128154
{"tool": tool, "field": "memory_id", "memory_id": row.get("id")},
129155
)
130-
require_writable_domain(row.get("domain") or "", tool, environ)
156+
require_writable_canonical(row.get("domain") or "", tool, environ)
131157

132158

133159
def memory_writable(row: Mapping, environ: Mapping[str, str] = os.environ) -> bool:
134160
"""Whether a write may pick ``row`` as its target (merge, replica refresh)."""
135161
if row.get("is_global") and not _every_project(environ):
136162
return False
137-
return _refused_domain(row.get("domain") or "", environ) is None
163+
target = (row.get("domain") or "").strip().lower()
164+
return _refused_domain(target, environ) is None

‎mcp_server/handlers/remember.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@
5151
from mcp_server.handlers._write_scope import (
5252
KEPT_LOCAL,
5353
global_scope,
54-
require_writable_domain,
54+
require_writable_canonical,
5555
require_writable_memory,
5656
)
5757
from mcp_server.infrastructure.memory_exact import find_exact
@@ -180,7 +180,8 @@ def _resolved_origin(args: dict[str, Any], write_class: str) -> str:
180180

181181
def _prepare_request(args: dict, store: MemoryStore, write_class: str) -> GateRequest:
182182
domain = _resolve_domain(args.get("directory", ""), args.get("domain", ""))
183-
require_writable_domain(domain, "remember") # GHSA-7848-qh48-mx2w
183+
# GHSA-7848-qh48-mx2w: `domain` is resolved already, it is checked as it is.
184+
require_writable_canonical(domain, "remember")
184185
origin = _resolved_origin(args, write_class)
185186
return GateRequest(
186187
args["content"],

‎mcp_server/handlers/remember_helpers.py‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -388,24 +388,29 @@ def try_block_replica_upsert(
388388
"SELECT id, domain, is_global FROM memories "
389389
"WHERE tags @> %s::jsonb "
390390
"AND tags @> '[\"memory-replica\"]'::jsonb "
391-
"LIMIT 1",
391+
"ORDER BY id",
392392
(vpath_json,),
393393
).fetchall()
394394
except Exception as exc: # noqa: BLE001 — mechanism boundary — failure is observable via silent_failure ("remember_helpers.block_supersede_select")
395395
# source: ADR-0438
396396
silent_failure.note("remember_helpers.block_supersede_select", exc)
397397
return False, None
398398

399-
if not rows:
400-
return False, None
401399
# GHSA-7848-qh48-mx2w: a replica of another project's or a global memory this
402-
# session may not change is not refreshed; the write proceeds as a new row.
403-
if not memory_writable(
404-
{"domain": rows[0].get("domain"), "is_global": rows[0].get("is_global")}
405-
):
400+
# session may not change is not refreshed. Every replica of the block is read,
401+
# not the first one: another project's row must not hide this session's own,
402+
# or each sync would insert one more row (replicas bypass exact deduplication).
403+
writable = [
404+
row
405+
for row in rows
406+
if memory_writable(
407+
{"domain": row.get("domain"), "is_global": row.get("is_global")}
408+
)
409+
]
410+
if not writable:
406411
return False, None
407412

408-
existing_id = rows[0]["id"]
413+
existing_id = writable[0]["id"]
409414

410415
# Refresh content, embedding, tags, source; preserve heat and is_protected.
411416

‎mcp_server/handlers/seed_project.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
from mcp_server.infrastructure.memory_store import MemoryStore, get_shared_store
3131
from mcp_server.handlers._tool_meta import NON_IDEMPOTENT_WRITE
3232
from mcp_server.handlers.seed_project_constants import is_transient_seed_root
33-
from mcp_server.handlers._write_scope import require_writable_domain
33+
from mcp_server.handlers._write_scope import require_writable_canonical
3434

3535
_store: MemoryStore | None = None
3636

@@ -123,7 +123,7 @@ def _parse_args(args: dict[str, Any] | None) -> tuple[Path, str, int, bool]:
123123
# directory wins over the argument) is resolved once here, checked, and is the
124124
# one the handler purges, writes and reports: never the raw argument.
125125
domain = _remember_domain(str(root), domain) or domain
126-
require_writable_domain(domain, "seed_project")
126+
require_writable_canonical(domain, "seed_project")
127127
max_kb = int(args.get("max_file_size_kb", 64))
128128
dry_run = args.get("dry_run", False)
129129
return root, domain, max_kb * 1024, dry_run

‎tests_py/handlers/test_ghsa_7848_global_and_existing.py‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,11 +117,13 @@ async def test_curation_never_merges_into_another_projects_memory(
117117

118118

119119
class _ReplicaStore:
120-
def __init__(self, row):
121-
self.row, self.updates = row, []
120+
def __init__(self, *rows):
121+
self.rows, self.updates, self.selects = list(rows), [], []
122122

123123
def _execute(self, sql, params=()):
124-
rows = [self.row] if sql.lstrip().startswith("SELECT") else []
124+
rows = self.rows if sql.lstrip().startswith("SELECT") else []
125+
if sql.lstrip().startswith("SELECT"):
126+
self.selects.append(sql)
125127
if not sql.lstrip().startswith("SELECT"):
126128
self.updates.append(params)
127129
return type("Cursor", (), {"fetchall": lambda _self: rows})()
@@ -142,6 +144,20 @@ def test_a_replica_of_a_row_this_session_may_not_change_is_not_refreshed(project
142144
assert store.updates == []
143145

144146

147+
def test_another_projects_replica_does_not_hide_this_sessions_own(projects):
148+
# Codex on PR #969: with LIMIT 1 the other project's row was the only one read,
149+
# so every sync from beta inserted one more row instead of refreshing its own.
150+
store = _ReplicaStore(
151+
{"id": 7, "domain": "alpha", "is_global": False},
152+
{"id": 9, "domain": "beta", "is_global": False},
153+
)
154+
tags = ["memory-replica", "vpath:/x.md"]
155+
assert try_block_replica_upsert(MARKER, None, tags, "user", store) == (True, 9)
156+
assert len(store.updates) == 1 and 9 in store.updates[0]
157+
# Every replica of the block is read, in a stable order: no LIMIT hides one.
158+
assert store.selects[0].endswith("'[\"memory-replica\"]'::jsonb ORDER BY id")
159+
160+
145161
def test_seed_project_checks_the_domain_remember_will_use(projects):
146162
# directory inside alpha wins over domain=beta in remember: refused up front.
147163
with pytest.raises(ValidationError, match=r"^seed_project: domain 'alpha'"):

‎tests_py/handlers/test_ghsa_7848_resolved_domain.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
import pytest
1212

13+
from mcp_server.errors import ValidationError
1314
from mcp_server.handlers import _write_scope
1415
from mcp_server.shared import domain_mapping
1516
from tests_py.handlers.test_ghsa_7848_cross_project_write import (
@@ -74,3 +75,42 @@ async def persist(path, parsed, prov, domain):
7475
page.write_text("<h1>Onboarding</h1><p>welcome</p>", encoding="utf-8")
7576
await ingest_document.handler({"path": str(page), "domain": "family"})
7677
assert seen == ["beta"]
78+
79+
80+
# Codex on PR #969: a directory name can be an alias of one project (`family` is the
81+
# directory of the repository whose domain is `beta`) and the canonical domain of
82+
# another repository family (`family-one`, `family-two`). A domain that is an
83+
# identity already (from a path, from a stored row) is never resolved a second time.
84+
@pytest.fixture
85+
def collision(aliased, monkeypatch):
86+
"""`family` is both an alias of `beta` and another family's canonical domain."""
87+
monkeypatch.setattr(
88+
_write_scope, "project_domains", lambda: frozenset({"alpha", "beta", "family"})
89+
)
90+
return aliased
91+
92+
93+
def test_a_family_writes_in_its_own_domain_despite_the_alias(collision, monkeypatch):
94+
monkeypatch.setattr(_write_scope, "session_domain", lambda environ=None: "family")
95+
_write_scope.require_writable_canonical("family", "remember")
96+
assert _write_scope.memory_writable({"domain": "family"}) is True
97+
98+
99+
def test_the_aliased_project_cannot_change_the_familys_rows(collision):
100+
row = {"id": 3, "domain": "family", "is_global": False}
101+
assert _write_scope.memory_writable(row) is False
102+
with pytest.raises(ValidationError, match=r"^anchor: domain 'family' belongs"):
103+
_write_scope.require_writable_memory(row, "anchor")
104+
with pytest.raises(ValidationError, match=r"^remember: domain 'family' belongs"):
105+
_write_scope.require_writable_canonical(" Family ", "remember")
106+
107+
108+
def test_the_alias_given_as_a_name_still_resolves_to_the_sessions_project(collision):
109+
assert _write_scope.require_writable_domain("family", "ingest_prd") == "beta"
110+
111+
112+
def test_a_resolved_domain_of_no_known_project_stays_writable(collision):
113+
_write_scope.require_writable_canonical("team-notes", "remember")
114+
_write_scope.require_writable_canonical("", "remember")
115+
_write_scope.require_writable_canonical(None, "remember")
116+
_write_scope.require_writable_canonical("beta", "remember")

0 commit comments

Comments
 (0)