Skip to content

feat: relay-wide long-poll cap and audit trail for cap rejections (M2/M4) - #93

Merged
OBenner merged 2 commits into
mainfrom
feat/m2m4-relay-hardening
Nov 16, 2026
Merged

OBenner merged 2 commits into
mainfrom
feat/m2m4-relay-hardening

Conversation

@OBenner

@OBenner OBenner commented Nov 16, 2026

Copy link
Copy Markdown
Owner

Контекст

Приоритеты CTO по docs/security/review-2026-11-12.md: (a) M2 — лимит конкурентных long-poll на relay (bounded, fail-closed, с диагностикой); (b) M4 — полный audit log.

Аудит покрытия M4 по коду HEAD 82bd914: auth failures (401 → authenticate/deny), operator pause/resume, replaceSession, token issue/rotate/revoke, registerSession (с surface), claim, directory degraded/recovered, deny по send/reply/inbox/acknowledge/getMessage — всё уже записывается предыдущими волнами (#3, #42, #53, #36). Фактических пробелов осталось два, оба вокруг M2.

Изменения

1. Relay-wide cap на конкурентные long-poll (M2, bounded)

Per-identity cap 2 (9b622e8) ограничивает суммарно 2 × roles, но manifest hot-reloadable (#36) — роли могут добавляться без рестарта relay, и глобальная граница плывёт. Добавлен ProtectionLimits.maxConcurrentLongPollsGlobal (default 32): суммарный счётчик по всем идентичностям, тот же RATE_LIMITED поверх → 429 (существующий mapError).

2. Audit-диагностика отказов капа (M2, «с диагностикой»)

Отклонённый acquire — DoS-релевантное событие — раньше не оставлял следа. Теперь HTTP-слой записывает longPoll/deny/RATE_LIMITED с маршрутом в detail (GET /v1/inbox / GET /v1/deliveries/next) до закрытия запроса. AuditedAction расширен аддитивно ("longPoll"); локальный jsonl, протокол v1 и wire-контракты не тронуты. Отказы request-bounded — флуда лога через них нет. Doctor видит события через существующий audit tail (#3).

Осознанно НЕ сделано

Per-message authz-отказы (403) на /v1/deliveries/{authorize,receipt,failure} не аудируются: пространство message-id — неперебираемые UUID, легитимные клиенты туда не попадают, шум/сигнал сомнителен (решение согласовано с dev в треде 53aef786).

Тесты

  • test/relay/protection.test.ts: relay-wide cap заполняется разными идентичностями, 4-й acquire → RATE_LIMITED, release переоткрывает окно.
  • test/transport/http.test.ts: 3-й параллельный inbox long-poll → 429 + ровно одна audit-строка longPoll с маршрутом; то же для delivery-маршрута; instant polls (waitMs=0) не трогают кап и не пишут в audit.
  • Полный pnpm verify зелёный: 104 файла / 905 тестов, format/typecheck/build чистые.

Документация

  • README: абзац про аудит дополнен — long-poll rejections записываются с маршрутом.
  • docs/backlog.md: строка M2 закрыта с учётом hardening.

Ограничения

  • Капы in-memory per relay-процесс (как и существующие bucket'ы): при restart/re-election окно сбрасывается — принятое поведение local-first (зафиксировано ещё в review §5).
  • Global default 32 выбран как дешёвый headroom для локальной команды; конфигурабельности наружу (env/flag) нет — как у остальных лимитов.

…/M4)

Two gaps remained after the per-identity long-poll cap (9b622e8):

1. The per-identity cap alone does not bound the total: the participant
   manifest is hot-reloadable (issue #36), so 2 x roles grows without a
   relay restart. Add maxConcurrentLongPollsGlobal (default 32) checked
   across all identities, same RATE_LIMITED rejection.

2. A rejected acquire was invisible: the DoS-relevant event left no
   trace. The HTTP layer now records a longPoll/deny audit event with
   the route that hit the cap before failing the request closed
   (additive AuditedAction extension, local jsonl only, protocol v1
   untouched). Rejections are request-bounded, so the log cannot be
   flooded through them.

Tests: relay-wide cap unit test (fills across identities, release
reopens), HTTP tests pin the audit line for both long-poll routes and
the silence of instant polls.

Deliberately not audited: per-message authorization refusals on the
delivery routes (message ids are unguessable UUIDs; noise/signal not
worth it).
@OBenner

OBenner commented Nov 16, 2026

Copy link
Copy Markdown
Owner Author

Review (dev) — ACCEPT

Checked against the agreed plan (G1 audit as core, G2 global cap included, G3 explicitly out):

  • G1: RATE_LIMITED from acquireLongPoll is now recorded before the fail-closed response — action: "longPoll", decision: "deny", reasonCode: RATE_LIMITED, route in detail (GET /v1/inbox / GET /v1/deliveries/next). The DoS-relevant signal is finally visible in the audit tail that doctor already shows.
  • G2: maxConcurrentLongPollsGlobal (default 32) sits on top of the per-identity cap with the same RATE_LIMITED semantics; the in-code rationale (hot-reloadable manifest from [P1] Add-role without restart + plugin update UX: registry hot-reload, installed≠source detection, upstream plugin reload #36 makes 2×roles unbounded) is correct.
  • G3: message-level authz on delivery endpoints intentionally not audited — recorded in the PR body as agreed (UUID message-id space is not probeable, legitimate clients never hit it).
  • Hygiene: AuditedAction += "longPoll" is additive and local; no protocol v1, session or wire changes. waitMs <= 0 bypass stays un-audited — correct, it never hangs a connection.

Verified independently in a detached review worktree: protection + http suites 56/56, full pnpm verify 104 files / 905 tests PASS.

Non-blocking note: caps are in-memory per relay process (reset on restart/re-election) — documented in the PR as accepted local-first behavior, consistent with the security review.

Passing to CTO for final.

@OBenner
OBenner merged commit 79da5cd into main Nov 16, 2026
3 checks passed
@OBenner
OBenner deleted the feat/m2m4-relay-hardening branch November 16, 2026 15:31
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.

1 participant