Skip to content

feat: audit session registration events with client surface (#53) - #54

Merged
OBenner merged 2 commits into
mainfrom
feat/53-audit-session-registration
Nov 15, 2026
Merged

OBenner merged 2 commits into
mainfrom
feat/53-audit-session-registration

Conversation

@OBenner

@OBenner OBenner commented Nov 15, 2026

Copy link
Copy Markdown
Owner

What

Closes the audit gap from #53: POST /v1/sessions/register wrote nothing to the security audit log, so the origin of a session that bound a role was not provable (the "Эй"/local_54c4eafa incident).

  • AuditedAction += registerSession.
  • The register route records accept (REGISTERED; detail: session id, generation, protocol version, surface) and deny (DUPLICATE_SESSION / INCOMPATIBLE_PROTOCOL; detail: error message + attempted session id and surface).
  • registerSchema gains an optional additive surface?: string (≤128 chars). It is written only to the audit detail at the http-server layer — the session-store schema is untouched. Protocol v1 envelope unchanged.
  • Built-in adapters report their surface: kimi-work, opencode, claude, codex-hook.
  • README audit paragraph updated (same commit, per CONTRIBUTING).

Design decisions (agreed with CTO, Synloq message 777f54dc)

  • Heartbeat lease renewals are deliberately NOT audited — volume vs. signal is poor and the lease is already visible in doctor/status. Pinned by a test: after a registration, a heartbeat adds no audit line.
  • Malformed-JSON register attempts (SynloqError INVALID_INPUT from readJson) are audited as deny without session detail; zod schema rejections follow the existing replaceSession pattern and are not audited.

Tests

New in test/cli/serve-audit.test.ts (8/8 green in file): accepted registration carries session/generation/surface; denied duplicate carries attempted session id and surface; denied incompatible protocol; heartbeat writes nothing. Exact-payload mocks in kimi-work/opencode/codex-hook tests now pin the surface.

pnpm verify: 83 files / 736 tests, format/typecheck/build green.

Review split (per CTO)

  • arch: wire-visible hunk — src/transport/http-server.ts registerSchema (optional additive surface) and src/transport/http-client.ts SessionRegistrationRequest.
  • dev: everything else.

Known limitations

  • surface is client-reported and unauthenticated beyond the role token — it is a forensic hint, not proof of the client binary.
  • Audit remains append-only JSONL per project; no store schema change.

Every /v1/sessions/register attempt now lands in the security audit log:
accepted bindings (accept/REGISTERED with session id, generation, protocol
version, and the client-reported surface) and refusals (deny with
DUPLICATE_SESSION / INCOMPATIBLE_PROTOCOL and the attempted session id), so
"who bound this role, when, from which surface" is answerable from the log.

Design decisions (agreed with CTO):
- registerSchema gains an optional additive 'surface' field; it is written
  only to the audit detail and never persisted to the session store.
- Heartbeat lease renewals are deliberately NOT audited: volume vs. signal
  is poor and the lease is already visible in doctor/status.
- Built-in adapters report their surface: kimi-work, opencode, claude,
  codex-hook.

@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-хунка registerSchema/SessionRegistrationRequest — он у arch).

Принято по существу.

  1. Accept/deny-обёртка register корректна: accept пишет sessionId/generation/protocol/surface; deny — только SynloqError (malformed JSON → INVALID_INPUT из readJson аудируется, detail = message без попытки), zod-отказы сознательно пропускаются — консистентно с replaceSession (там та же дисциплина: error instanceof SynloqError, audit до sendJson). Порядок «audit до response» совпадает с replaceSession — отказ аудита обломает регистрацию одинаково в обоих маршрутах, ок.
  2. Surface разведён правильно по всем четырём путям регистрации: kimi-work (runKimiWorkAdapter), opencode (runOpenCodeAdapter), claude (startStandaloneAdapter — проверил, что хунок в claude-ветке после runClaudeAdapter, opencode-ветка возвращается раньше и регистрируется внутри runOpenCodeAdapter), codex-hook.
  3. Тесты: 4 новых кейса (accept с surface, deny DUPLICATE_SESSION с attempted sessionId + surface, deny INCOMPATIBLE_PROTOCOL, пиннинг «heartbeat не аудируется») + exact-payload моки во всех трёх клиентских тестах. Покрытие заявленное — есть.
  4. Merge-совместимость с #55 (feat/45-stored-ping): git merge-tree — конфликтов нет в обоих порядках.
  5. Локальный pnpm verify на 7166ada зелёный: 83 файла / 736 тестов.

Запрошенные правки (minor, одним фикс-коммитом):

  1. README — оговорка про surface неполная. Сейчас: «the client-reported surface». Нужна явная честная формулировка, что surface — client-reported hint, не доказательство принадлежности клиента (любой клиент может назваться чем угодно; после инцидента с сессией «Эй» это именно то, что читатель лога должен понимать). Одно предложение в тот же абзац.
  2. Тесты (опционально, но желательно) — два пиннинга дисциплины обёртки: (а) malformed JSON → deny-запись с reasonCode INVALID_INPUT; (б) zod-отказ валидного JSON (например, unknown key при strict) → записи НЕТ. Сейчас обе грани реализованы, но тестами не закреплены.
  3. CI — job «Format, typecheck, test, build» упал при зелёном локальном verify; прошу re-run. Если падение повторится — посмотри, не codex-probe ли это (5-секундный таймаут spawn node под нагрузкой, flaky; наблюдал то же на своём PR #55).

@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.

Review scope: wire hunk only — registerSchema optional surface (src/transport/http-server.ts) and SessionRegistrationRequest (src/transport/http-client.ts). Rest is with dev.

Verdict: the wire change is sound. APPROVE from the architecture side.

  1. Additivity / backward compatibility. Old client → new server: clean (field optional, omitted by old clients). New client → old server: would fail — the old schema is .strict() and rejects unknown keys. This is consistent with our existing policy (strict payloads, single-dist contour: relay and adapters ship from the same dist and move together), so acceptable — but worth remembering that registration payloads are not cross-version tolerant in the old→new direction.
  2. Bound. z.string().min(1).max(128).optional() — present as required. ✓
  3. Envelope v1. Untouched — the field lives in the session-registration transport payload, not in the message envelope. No spec impact, no double-approve needed. ✓
  4. No state shape change. surface is not passed to sessions.register() and never persisted — audit-detail only. No migration concerns. ✓

Two minor observations (non-blocking, for the record):

  • surface is any string, not an enum of known surfaces. Acceptable: it is explicitly a client-reported audit hint, and JSON.stringify escaping prevents JSONL line injection. Just don't build logic on its values without normalizing first.
  • Registration attempts that fail schema validation (ZodError, not SynloqError) are not audited — the deny-record covers only SynloqError rejections. "Every registration attempt is audited" is therefore true for well-formed-but-refused requests, not for malformed ones. Fine for #53's goal; note it before anyone reads the log as a complete intrusion record.

Review nits from dev:
- malformed JSON on /v1/sessions/register is audited as deny/INVALID_INPUT;
- zod schema rejections are deliberately not audited (consistent with
  replace-session) — pinned by a test asserting no audit file is created;
- README states verbatim that surface is a client-reported hint, not proof
  of the client binary.
@OBenner
OBenner merged commit 8d8e505 into main Nov 15, 2026
5 of 6 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.

1 participant