Skip to content

feat: project-scope all id-based message-store lookups (#51) - #57

Merged
OBenner merged 2 commits into
mainfrom
feat/51-message-store-project-filter
Nov 15, 2026
Merged

OBenner merged 2 commits into
mainfrom
feat/51-message-store-project-filter

Conversation

@OBenner

@OBenner OBenner commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

What

Closes #51 — the P3 defense-in-depth gap from the Claude Desktop live run triage: id-based message-store lookups had no project filter, so the invariant "an id is unique within the database file" held by discipline only.

  • findById(id, project) → WHERE id = ? AND project = ?; same for the public getMessage(id, project) and countThreadSince(threadId, project, since).
  • The filter-less helpers setDeliveryState and resetSubmittedForRetry (no wire-input production callers) gain a project parameter too, so no id-based path remains unscoped.
  • Redundant caller-side row.project !== project comparisons dropped where the scoped query already guarantees them (authorizeDelivery, completionClaim, reportDeliveryFailure, quarantineDelivery, acknowledge, relay-service.getMessage, HTTP receipt/failure routes — the latter also as a review-nit follow-up commit).

Observable behavior changes (fail-closed)

  • Cross-project reads/acks that used to answer UNAUTHORIZED now answer NOT_FOUND — consistent with the existing no-existence-leak policy (reply to a foreign thread is already NOT_FOUND). Conformance expectations in test/relay/relay-service.test.ts and test/storage/message-store.test.ts updated with comments.
  • quarantineDelivery for a cross-project id now throws NOT_FOUND ("message not found") instead of INVALID_INPUT ("quarantine recipient does not match") — same no-existence-leak rationale; recipient-mismatch within the same project still throws INVALID_INPUT.

Tests

  • New store-level conformance case (test/storage/message-store.test.ts, "cross-project isolation"): an id from project A is invisible from project B across getMessage / countThreadSince / acknowledge / setDeliveryState / resetSubmittedForRetry; a message with the same thread id exists in project B to prove the filter is the project column, not the thread.
  • All existing call sites updated to the new signatures (mechanical; type-pinned).

pnpm verify after rebase on main 761c1af (includes the merged #60 requireWriter): 86 files / 761 tests, format/typecheck/build green. The rebase conflict in relay-service.ts was resolved keeping both change sets (requireWriter + project-scoped lookups).

Docs

Threat-model acceptance item: docs/security/threat-model-2026-11-12.md is a dated historical record and is never edited retroactively (CONTRIBUTING), so the "project isolation is structural at the store layer" note landed as a bullet in the README security/operations notes instead. If a refreshed threat-model document is wanted, that is a separate docs task.

Out of scope

  • No schema/migration changes; the project column already exists.
  • Service-level RelayService.getMessage(identity, id) signature unchanged.

@OBenner OBenner left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ревью dev (скоуп: всё, кроме wire — wire здесь не затронут).

Вердикт: принять по коду, но до мержа нужен rebase + зелёный CI.

Проверено по ветке локально (4a5fb14):

  1. Call-site'ы: все вызовы getMessage/setDeliveryState/countThreadSince/resetSubmittedForRetry в src обновлены на project-scoped сигнатуры, ни одного одноаргументного вызова не осталось (проверено grep по дереву + typecheck). Снятые caller-side проверки row.project !== project не теряют семантику — findById(id, project) теперь делает их по построению.
  2. Смена контракта UNAUTHORIZED → NOT_FOUND для кросс-проектных read/ack: согласен. Fail-closed, no-existence-leak, консистентно с политикой reply (чужой тред уже NOT_FOUND). Обновлённые ожидания в relay-service.test.ts и message-store.test.ts помечены комментариями — честно.
  3. Conformance-тест доказывает именно project-фильтр: одинаковый threadId в двух проектах, countThreadSince возвращает по 1 на проект (не 2), getMessage кросс-проект → undefined, кросс-проектные write'ы бросают и не трогают исходное сообщение. Это ровно то, что требовалось.
  4. Края проверены: completeDeliveryReceipt — !before в evidence-ветке учтён; reportDeliveryFailure — !row → UNAUTHORIZED до любого разыменования.

Неблокирующие ниты:

  • http-server.ts: проверки existing.project !== project (строки ~367/~397) теперь недостижимы — scoped-запрос гарантирует. Оставить как defense-in-depth допустимо, но это мёртвый код; можно пометить комментарием или снять при следующем касании.
  • quarantineDelivery: кросс-проектный вызов раньше давал INVALID_INPUT, теперь NOT_FOUND — та же fail-closed логика, ок, но в PR body явно названы только UNAUTHORIZED→NOT_FOUND; упомянуть бы и этот класс.

Два блокера до мержа:

  1. CI «Format, typecheck, test, build» — failure. Локальный pnpm verify на 4a5fb14 полностью зелёный (83 файла / 733 теста). Похоже на окружение/flaky, не на код. Нужен повторный прогон — самый простой способ заодно решает пункт 2.
  2. Конфликт с main (0c1812c) в src/relay/relay-service.ts — пересечение со смерженным #60 (single-writer, requireWriter рядом с твоими хунками send/reply/getMessage). Ребейз/merge main в ветку, резолв тривиальный по смыслу (оба набора правок сохраняются), пуш перезапустит CI.

Defense in depth: 'an id is unique within the database file' held by
discipline; now it holds structurally. Every id-based lookup carries the
project in the query (WHERE id = ? AND project = ?):

- findById(id, project), getMessage(id, project),
  countThreadSince(threadId, project, since);
- the filter-less helpers setDeliveryState and resetSubmittedForRetry gain a
  project parameter too, so no id-based path remains unscoped;
- redundant caller-side project comparisons dropped where the scoped query
  already guarantees them.

Observable change, fail-closed and consistent with the existing
no-existence-leak policy: cross-project reads/acks that used to answer
UNAUTHORIZED now answer NOT_FOUND.

Tests: store-level conformance case pins that an id from project A is
invisible from project B across getMessage/countThreadSince/acknowledge/
setDeliveryState/resetSubmittedForRetry, with a same-thread-id message in
the other project to prove the filter is the project column; existing
call-site expectations updated to the new signatures.

pnpm verify: 83 files / 733 tests, format/typecheck/build green.
… routes (#51)

Review nit from dev: getMessage(messageId, project) is project-scoped in
the query since the previous commit, so the existing.project comparison can
never fire.
@OBenner
OBenner force-pushed the feat/51-message-store-project-filter branch from 4a5fb14 to 20f38f8 Compare November 15, 2026 16:49
@OBenner
OBenner merged commit 409c024 into main Nov 15, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[P3] Harden message-store: project-scope filter on id lookups (defense in depth)

1 participant