Skip to content

fix: Refuse MCP capability keys from a discovered project config - #5134

Merged
Sinity merged 1 commit into
masterfrom
sec/mcp-capability-boundary
Sep 14, 2026
Merged

Sinity merged 1 commit into
masterfrom
sec/mcp-capability-boundary

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary

A polylogue.toml in the process's current directory could grant the MCP server its privileged write/judge/maintenance tools. Separately, the MCP telemetry outbox had no admission control and retried permanently-invalid records forever.

Finding 1 — project config could open the MCP capability boundary

Threat-model category: untrusted artifact widening a capability boundary.

_user_config_path resolves the user layer as: POLYLOGUE_CONFIG, else the XDG user config, else cwd/polylogue.toml. That last fallback is applied as the user layer unfiltered, and mcp_write_enabled / mcp_judge_enabled / mcp_maintenance_enabled are ordinary bool keys with nothing distinguishing them from cosmetic ones. polylogue-mcp takes all three straight from load_polylogue_config(). The installer's default read-only entry is {"command": "polylogue-mcp", "args": [], "env": {}} — it pins no config path and emits capability variables only when enabled, so it leaves exactly the gap the fallback fills.

Reproduced with POLYLOGUE_CONFIG unset, an empty XDG_CONFIG_HOME, and a cwd polylogue.toml containing [mcp] write_enabled/judge_enabled/maintenance_enabled = true: all three resolved true, with the layer reported as user and the path the hostile file. FastMCP then registers write, run, judge and maintenance, and write(operation="delete_session", confirm=true) supplies its own boolean confirmation.

Why this is in scope for a local single-user tool. The untrusted artifact is not the operator's filesystem — it is a third-party repository the operator's agent checked out, which is the ordinary agent workflow, and a file the operator never authored must not widen a capability boundary. The repo already holds exactly this line elsewhere: the daemon's token loader refuses a token file it does not exclusively own (polylogue-n6pz).

Honest counterweight: an operator who ran polylogue agent install --enable-write already has the variable pinned, and one with an XDG user config never reaches the fallback. The exposed case is the default install with no XDG config — the documented default path.

Solution

_CAPABILITY_CONFIG_KEYS sits beside _BOOL_CONFIG_KEYS, and _apply_toml_layer gained reject_capability_keys: after the merge it reverts any capability key that layer changed and emits a logger.warning naming the rejected keys and the file. A refusal the operator can see, not a silent drop.

The predicate is scoped precisely. explicit_user alone was wrong: the XDG user config is also non-explicit but is operator-owned and must keep working. The refusal applies only to the cwd fallback. (This was found by a test that initially wrote to the wrong XDG path — the fix is a real behavioural correction, not test tuning.)

One authoritative choke point, in config.py; mcp/cli.py stays a plain consumer. installer._mcp_entry additionally pins "1"/"0" for every capability instead of omitting disabled ones — defence in depth, since an absent variable is what lets a lower layer speak at all.

Finding 2 — unbounded telemetry outbox with permanent-poison retry

Threat-model category: self-inflicted disk exhaustion reachable from the read-only surface.

_persist_delivery had no per-record size check, no pending-file count check, and no aggregate byte quota before atomic_replace; the class docstring described the outbox as unbounded by construction. The daemon rejects bodies over 16,384 bytes, more than 256 session ids, or ids over 2,048 chars with 400 — limits the client did not mirror. And _drain_root_once quarantined only 409; a 400 took the generic branch, which retained the file and breaked, abandoning every later record in that root on every pass, forever.

Concrete input, no privileged capability needed: read(ref=<a 100 KB string>). The dispatcher passes the raw argument to telemetry and spools on the failure path too, so the tool call errors yet a ~100 KB record lands durably in pending/, the daemon 400s it forever, legitimate later records never deliver, and repeating grows the outbox without limit.

Solution

In call_log.py only: the daemon's own per-field limits are enforced before persistence (one vocabulary, with a comment pointing at the daemon constants); declared aggregate pending count and byte ceilings shed new records; and quarantine widens to every permanent 4xx (400 <= code < 500 and code != 429) with continue instead of break.

Shedding is proportionate here because telemetry is not archive evidence — but it is counted and visible, never silent: every drop increments McpCallOutboxStatus.records_dropped (surfaced through the existing status projection) and logs a warning.

Verification

devtools test tests/unit/agent_integration/test_installer.py \
             tests/unit/core/test_config_resolution_regression.py \
             tests/unit/mcp/test_mcp_call_log.py \
             tests/unit/core/test_insight_readiness.py
devtools test: PASSED exit=0 diagnosis=pytest_passed

The closure is verified end to end, not only by test: with the fix in place the reproduction above now prints the refusal and resolves write False judge False maint False.

Anti-vacuity, each source change reverted in turn:

  • reject_capability_keys=False: E AssertionError: assert True is False / + where True = PolylogueConfig(...).mcp_write_enabled
  • installer guards restored: E KeyError: 'POLYLOGUE_MCP_WRITE_ENABLED'
  • _validate_event deleted: E Failed: DID NOT RAISE McpCallLogRecordRejectedError
  • size/quota admission deleted: E assert 3 == 2 / + where 3 = McpCallOutboxStatus(pending_count=3, ...).pending_count
  • _is_permanent_rejection narrowed back to code == 409: E AssertionError: assert False

One mutation was initially masked — deleting _validate_event still passed because the byte check caught the oversize case. A 300-session-id test that sits well under the 16 KB budget was added specifically to kill that mutant, and the revert re-run confirms it.

Residuals

  • devtools schema closure polylogue/config.py reports IN. The derived schema identity moves and the archive must reconverge; land before a fresh rebuild starts, never during one. No DDL changed — the fingerprints are AST closures over imported source. Six test_insight_readiness / test_insight_surface_parity tests failed with SchemaSkewError in a long-lived working checkout; they pass in a fresh worktree on this branch, so that was a stale cached archive artifact locally, not a defect here. The other changed files are out.
  • The upstream cause is untouched by design: the MCP dispatcher still forwards a raw session_id argument to telemetry. This stops it becoming durable poison; it does not validate the argument at its source.
  • Quarantine itself is unbounded — a repeated permanent-4xx record accumulates in quarantine/ instead of pending/. It is counted in the outbox status, but nothing prunes it.
  • _MAX_PENDING_RECORDS / _MAX_PENDING_BYTES are chosen by judgment, not mirrored from a daemon constant. _outbox_pressure reads the pending directory on every submit — O(pending) per call, acceptable at a 4096 cap but not free.
  • A caller that constructs MCPCapabilities directly still bypasses config entirely; the guard is at the config layer, not at the capability type.
  • The related finding that MCP telemetry sends the machine bearer to whatever holds loopback 127.0.0.1:8766 is not fixed here. The mechanism is real and the in-tree mitigation exists unused (daemon/uds.py already does SO_PEERCRED), but it requires a hostile second local UID, which does not exist on a single-user workstation. It is latent boundary debt, not an active exposure, and is reported rather than patched.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 15 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 6601db56-8618-4555-b62e-f731e178c016

📥 Commits

Reviewing files that changed from the base of the PR and between 342ba3d and 520709b.

📒 Files selected for processing (6)
  • polylogue/agent_integration/installer.py
  • polylogue/config.py
  • polylogue/mcp/call_log.py
  • tests/unit/agent_integration/test_installer.py
  • tests/unit/core/test_config_resolution_regression.py
  • tests/unit/mcp/test_mcp_call_log.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
🔒 Security Review ✅ Completed 2026-09-14T18:25:38.749549Z 0b9cbbe PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

`_user_config_path` falls back to `polylogue.toml` in the process's current
directory when neither `POLYLOGUE_CONFIG` nor an XDG user config selects a
file, and applies it as the user layer unfiltered. `polylogue-mcp` reads its
capability booleans from that resolved config, so a third-party checkout
carrying `[mcp] write_enabled = true` registered the privileged write, judge
and maintenance tools with no operator opt-in -- and `write(operation=
"delete_session", confirm=true)` supplies its own confirmation. Reproduced
with an isolated XDG home and a cwd config: all three resolved true.

A hostile checkout is not the operator attacking themselves; it is exactly
the artifact an agent clones. The repo already holds this line for the daemon
token, which refuses a file it does not exclusively own.

Capability keys supplied by the *discovered* cwd fallback are now reverted
and logged by name. An explicitly selected config, and the operator-owned XDG
user config, still set them -- `explicit_user` alone was the wrong predicate,
since the XDG path is discovered too. The installer also pins every
capability variable explicitly rather than omitting the disabled ones.

The MCP telemetry outbox gains the admission it never had: the daemon's own
per-field limits are enforced before a record is persisted, aggregate pending
count and byte ceilings shed new records with a counted, logged drop, and
quarantine widens from 409 to every permanent 4xx so one poison record no
longer strands every later record behind it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
@Sinity
Sinity force-pushed the sec/mcp-capability-boundary branch from 0b9cbbe to 520709b Compare September 14, 2026 19:01
@Sinity
Sinity merged commit b642730 into master Sep 14, 2026
3 checks passed
@Sinity
Sinity deleted the sec/mcp-capability-boundary branch September 14, 2026 19:36
Sinity added a commit that referenced this pull request Sep 14, 2026
…ts (#5171)

## Summary

Eleven unrelated failures on `master`, triaged one at a time. **Four
were product defects** and are fixed here; five were stale tests, each
naming the change that made it stale; two are left red with their cause
established.

## Evidence

Full-corpus `verify_all` on frozen `master` (`890a2921e`), job 1570,
receipt `.cache/verify/runs/20260914T200510Z-all-4027943-f8bc83ff`,
22,524 selected, **147 failures with zero schema skew**.

## Per-failure classification

| # | Failure | Classification |
| --- | --- | --- |
| 1 |
`test_verified_backup_avoids_rehashing_scratch_blobs_after_validation` |
**Stale test** (harness blind after #5147) |
| 2 |
`test_discovered_project_toml_capability_keys_are_refused_and_logged` |
**Product defect** (#5134) |
| 3 | `test_seed_demo_archive_creates_ready_queryable_archive` |
**Product defect**, filed — **left red** |
| 4 | `test_seeded_archive_fixture_resolves_through_the_registry` |
Order-dependent, not reproducible |
| 5 | `test_a_session_absent_from_the_index_is_still_tombstoned` |
**Product defect** (inherited from #5154) |
| 6 | `test_archive_ingest_large_zip_artifact_streams_to_blob_reference`
| **Product defect** (#5117) |
| 7a | `test_every_live_declaration...[blob-integrity]` | **Product
defect** |
| 7b | `test_every_live_declaration...[session-fingerprint-stamps]` |
Poisoned shared cache, filed |
| 8 | `test_append_plan_resynthesizes_an_append_kind_head` | **Stale
fixture** (polylogue-u19l) |
| 9 | `test_full_ingest_writes_archive_with_route_observability` |
**Stale test** (#5049) |
| 10 |
`test_tier_prototype_is_atomically_published_and_restored_read_only` |
Order-dependent, not reproducible |
| 11 | `test_declared_devtools_route_runs_the_real_seeded_check` |
**Stale test** (#5097 deleted the route) |

## The four product defects

**(6) A ZIP member's bytes were dropped entirely.** #5117 correctly
threaded `max_record_bytes` into the JSONL classification probe, but
`scan_jsonl_session_artifact`'s oversized-record branch *synthesises* a
`parse_as_session=True` classification ("uninspected oversized provider
JSONL record retained for streaming parse"). That retention rule exists
for a raw whose only other classifier is a weak path heuristic. Used as
*positive* evidence in `_admit_non_session_zip_artifacts`, it overrode
the OriginSpec-declared terminal artifact rule — so a
`subagents/workflows/.../journal.jsonl` member was routed as a session,
refused by polylogue-9ykn for want of positive conversational evidence,
and **the bytes were lost** (`raw_artifacts=0`, `raw_sessions=0`). An
inspection that read nothing has not answered the narrower question this
caller asks. The path rule now stands and the skipped inspection is
named via `sources.zip.artifact_probe_unbounded` — the same posture
#5117 chose for its own ZIP probe ceiling. Verified outside pytest:
`raw_artifacts=1`, `blob_size == len(payload)`.

**(2) A refusal that would not say what it refused.** #5134 emitted
`keys=rejected` (a `list`) on `config.capability_keys_refused`, but
`keys` is not in the structured-log allowlist (`logging_fields.py`), so
`emit` dropped it — and even registered, `_scalar` would have reduced a
list to `<list>`. Registered a `config_keys` token field and emit the
joined names. The field is drawn from a closed set of declared setting
names, never a user value.

**(7a) A first-party control file reported as blob corruption.**
`blob_gc_index_watermark` writes
`.polylogue-index-liveness-watermark.json` into the blob namespace root,
but `BlobStore.iter_namespace` exempted only `.polylogue-blob-namespace`
and `.staging` — so its own control file surfaced as a *critical*
`invalid_namespace_entries` finding telling the operator to "quiesce
blob writers". `blob_store` now owns the reserved-name set (it is the
module that decides what may sit in that root) and the watermark module
imports it, so the two cannot drift.

**(5) A tombstone that committed and then aborted.** #5148 added the
tombstone-without-index-row path; #5154 then made
`ArchiveStore.delete_sessions` resolve every id and raise `KeyError` for
one with no row. The apply committed the durable suppressions and *then*
raised, losing the receipt for a tombstone that had already landed. Only
ids PREPARE recorded in `present_in_index` now reach that call — exactly
the complement of the `tombstoned_without_index_row` set the receipt
already names, and deleting a row that is not there is a no-op anyway.

## The stale tests

**(1)** #5147 (`ae9149902`) replaced `blob_path.read_bytes()` in
`_verify_archive_file_set_backup` with a 1 MiB chunked stream.
`tests/infra/backup_read_counter.py` instruments only `Path.read_bytes`
and `backup._sha256_file`, so the scratch proof read became *invisible*
— the blobs are still read and hashed. The counter now also counts
`Path.open` on blob paths. Anti-vacuity: rereading scratch blobs during
receipt construction doubles `open:scratch`; dropping the restore proof
zeroes it.

**(8)** polylogue-u19l (`f3bbf413a`, carried by #4549) stopped splicing
a synthetic `session_meta` header into Codex append blobs so stored
bytes stay a literal slice of the live file. This one fixture still
wrote `_session_meta + delta` while declaring a 124-byte window over a
185-byte blob, so `verified_reconstructed_prefix_hash` could never match
— every sibling fixture in the file already used literal deltas.
Anti-vacuity: dropping `append_head` from the head-kind guard returns
`None`.

**(9)** #5049 (`73766c276`) added `repair_message_fts_index_sync` to
live full ingest precisely because the `defer_fts=True` contract's
promised repair was never performed — "a freshly ingested 50k-message
session searched as empty" until the next 60s tick. The test still
asserted `indexed == 0`. Anti-vacuity: deleting that call zeroes it.

**(11)** The route it pinned was deliberately deleted by #5097 ("Delete
the dormant verify export command and blob-conservation alias"), whose
no-caller grep missed this test. `devtools verify blob-conservation` now
falls through to the `verify` tier runner, which refuses inside an agent
job and exits 2. The product check is healthy (`referenced_blobs ==
present_blobs == 1`). Retargeted to the one surviving declared route,
`polylogue ops maintenance blob-conservation --output-format json`, and
renamed accordingly.

## Left red, with cause established

**(3) `test_seed_demo_archive_creates_ready_queryable_archive`** — bead
**`polylogue-wrvy2`** (P0, open) is accurate and matches exactly:
`codex-session` declares `topology_capabilities.parent_dispatch.state ==
"structurally-absent"`, so `write.py` never mints
`session_links.parent_tool_use_block_id`, and the `delegations` resolved
branch (`archive_tiers/index.py:1594-1596`) joins on precisely that
column — the row lands as `edge_only`. The bead's open question is
*adjudication*: is the codex capability declaration wrong, or does
`demo/seed.py:845` assert an outcome its own origin forbids? That is a
design decision, not something to settle inside a test-failure sweep.
Confirmed accurate and left red, as instructed.

**(7b) `[session-fingerprint-stamps]`** — not reproducible at head. A
fresh schema-coverage artifact built in-process stamps the current
fingerprints and reports `ok`. The receipt's artifact (`build_id =
git:890a2921`) carries `recipe_id` / `source_semantics_id` /
`archive_schema_id` that no clean process at that commit computes: it
was published into the shared `/realm/tmp/polylogue-seeded-artifacts`
cache by a process with uncommitted product changes, and `build_id`
records the commit but cannot record dirtiness. Filed as
**`polylogue-c4a1o`** (P2).

**(4) and (10)** — pass at head in every run made; the `SchemaSkewError`
appears only in multi-file runs. A prototype-cache hypothesis was
**refuted** empirically: recorded tier prototypes carry an *empty*
`schema_identity` table, so a page copy cannot stamp a stale identity.
Classified as in-process order-sensitive contamination with the
mechanism unlocalised — recorded on `polylogue-c4a1o` as adjacent
evidence, explicitly not as a claim that they share its cause. **Not**
called flaky: no wait is involved.

## Verification

```
devtools test tests/integration/test_backup_verification_read_amplification.py \
              tests/unit/core/test_config_resolution_regression.py \
              tests/unit/sources/test_live_append_cursor_resynthesis.py \
              tests/unit/sources/test_live_batch_support.py \
              tests/unit/storage/test_blob_conservation.py \
              tests/unit/operations/test_mutation_actuators.py \
              tests/unit/pipeline/test_archive_ingest_shared_raw.py \
              tests/unit/maintenance/test_archive_verification.py
devtools test: FAILED exit=1 receipt=.cache/verify/runs/20260914T231245Z-focused-test-159592-60c25774/run.json
  317 passed, 88 failed.
```

Every one of those 88 is the `CHECK constraint failed: native_id IS NOT
NULL OR content_identity IS NOT NULL` class owned by another agent —
parsed from the receipt's `pytest-report.json`, **non-CHECK failures:
0**. They are concentrated in `test_archive_verification.py`, which
builds archives through the affected fixtures. None of the eleven
failures in scope remains red except (3), which is deliberate.

`devtools gate format` / `lint` / `mypy` (2869 files) / `layering` — all
clean.

## Schema closure — **all six product files are IN**

```
IN  polylogue/sources/decoder_zip.py
IN  polylogue/config.py
IN  polylogue/logging_fields.py
IN  polylogue/operations/mutation_actuators.py
IN  polylogue/storage/blob_store.py
IN  polylogue/storage/blob_gc_index_watermark.py
```

**This moves the derived schema identity. It must land before a fresh
rebuild starts, never during one.**

## Residuals

- (3) stays red under `polylogue-wrvy2`; (7b) and the order-dependent
pair under `polylogue-c4a1o`.
- (5) is fixed at the actuator. A session vanishing *between* PREPARE
and APPLY still raises. Whether `delete_sessions` should treat an absent
session as an error at all is arguably the real #5154 question and needs
`archive.py`, which was outside this change's scope.
- (11): `polylogue ops maintenance blob-conservation` prints an `Archive
root: …` banner ahead of its JSON on a `--output-format json` surface.
The test slices from the first brace rather than reaching into
`polylogue/cli/**`; the banner-on-JSON behaviour is untouched and
arguably wrong.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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