Skip to content

fix(test): restore the registry SSRF allow-policy after loopback fixtures - #1222

Merged
Dumbris merged 1 commit into
smart-mcp-proxy:mainfrom
loloDawit:fix/ssrf-guard-test-isolation
Sep 8, 2026
Merged

Dumbris merged 1 commit into
smart-mcp-proxy:mainfrom
loloDawit:fix/ssrf-guard-test-isolation

Conversation

@loloDawit

@loloDawit loloDawit commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Description

Test-only change. No production code is modified and no runtime behaviour changes.

TestBuildRegistrySourceEntry_RejectsSSRFLiteralIP — the MCP-1076 / CWE-918 regression test — can pass without exercising the guard it covers. Reproduction on main (3.9s, two tests):

$ go test ./internal/server/ -count=2 \
    -run 'TestBuildRegistrySourceEntry_RejectsSSRFLiteralIP|TestHandleUpstreamServers_AddFromRegistry_HappyPath'
--- FAIL: TestBuildRegistrySourceEntry_RejectsSSRFLiteralIP (0.00s)
    Error Trace: internal/server/add_registry_source_test.go:52
    Error:       An error is expected but got nil.
    Messages:    must reject SSRF target "https://169.254.169.254/v0.1/servers"

buildRegistrySourceEntry accepts the cloud-metadata endpoint. The same command at -count=1 passes.

Root cause

The allow-policy is process-global (internal/registries/ssrf.go:42):

var registryAllowPrivateFetch atomic.Bool

Its only writer is SetAllowPrivateRegistryFetch, reached through SetRegistriesFromConfig (registry_data.go:66). Two fixtures disable the policy so they can serve a loopback httptest registry, and neither restores it:

  • internal/server/mcp_add_from_registry_test.go — startTestRegistry
  • internal/server/consistency_official_test.go — startOfficialTestRegistry

Both register t.Cleanup(srv.Close) for the httptest server, but nothing for the global. Every later test in the binary then runs with the policy disabled, so all five assertions in add_registry_source_test.go:43 (metadata endpoint, loopback, two RFC1918 ranges, IPv6 loopback) succeed without reaching the guard.

startTestRegistry's doc comment records the assumption behind this — "tests run sequentially so the last writer wins." That holds only for tests that write the policy; tests that read it observe whatever the last fixture left. The comment is corrected here.

Why the suite passes today

At -count=1, Go runs tests in file order, and add_registry_source_test.go sorts ahead of both consistency_official_test.go and mcp_add_from_registry_test.go, so the assertion runs before either fixture. -shuffle is not used in .github/workflows/, so no lane exercises a different order.

The order is incidental, not a property anything enforces. On unfixed main, running the victim alongside the two fixtures under -shuffle fails on 2 of 5 seeds at -count=1:

seed=1 -> ok
seed=2 -> ok
seed=3 -> --- FAIL: TestBuildRegistrySourceEntry_RejectsSSRFLiteralIP
seed=4 -> ok
seed=5 -> --- FAIL: TestBuildRegistrySourceEntry_RejectsSSRFLiteralIP

-count>1 also fails it, as does adopting t.Parallel(), or adding another policy-disabling fixture in a file sorting ahead of add_registry_source_test.go. With this change, all five seeds pass.

Production behaviour

Unaffected. add_registry_source.go:139, remove_registry_source.go:63 and edit_registry_source.go:103 each do updatedConfig := *currentConfig, a struct copy that carries AllowPrivateRegistryFetch forward, so the CRUD paths propagate the operator's setting rather than resetting it. The defect is confined to the test binary.

The scope is therefore test reliability, on a CWE-918 guard: a future change that broke isBlockedIP would not be caught by the test written to catch it.

Fix

t.Cleanup(func() { registries.SetRegistriesFromConfig(nil) }) in both fixtures. A nil config restores the default catalog and re-enables the policy in one exported call, which also clears the second value leaked from the same line: the testreg / officialreg entry pointing at a closed httptest URL. TestSetRegistriesFromConfig_NilConfigUsesDefaults already pins those semantics.

This follows withGuardActive in internal/registries/ssrf_test.go:21-31, which does save-and-restore for the same flag within its own package.

TestRegistryFixturesRestoreSSRFPolicy is the regression test. It resets the policy itself before running each fixture in a nested subtest, so it detects the leak independently of test order and without -shuffle.

Verified failing before the fix (both fixtures, t.Cleanup lines removed):

--- FAIL: TestRegistryFixturesRestoreSSRFPolicy/startTestRegistry
    Messages: startTestRegistry did not restore the SSRF allow-policy: the cloud-metadata endpoint was accepted
--- FAIL: TestRegistryFixturesRestoreSSRFPolicy/startOfficialTestRegistry
    Messages: startOfficialTestRegistry did not restore the SSRF allow-policy: the cloud-metadata endpoint was accepted

Not included

-shuffle=on in a CI lane. It would prevent this class from recurring, but it may surface unrelated order dependencies elsewhere in the tree, which should not be resolved as part of this fix. Happy to open it separately.

Pre-existing, not addressed here

TestGetServerLogs_MissingFileReturnsEmptyNotError also fails under -race -count=2, and it is unrelated to this change: the same command on unmodified main at 4e304ba0 reproduces both failures.

# clean main
--- FAIL: TestBuildRegistrySourceEntry_RejectsSSRFLiteralIP     (fixed by this PR)
--- FAIL: TestGetServerLogs_MissingFileReturnsEmptyNotError     (pre-existing)

newLogsTestServer registers a server with AddServerConfig only, while NewServer starts config-as-source-of-truth reconciliation in the background; the server is absent from the config, so the reconciler removes it and GetServerLogs can observe "server not found". It passes 30/30 in isolation under -race, so it needs full-package timing to surface. Same class as this PR, different subsystem — happy to file it separately.

Testing

  • I have tested these changes locally
  • I have added/updated tests that prove my fix is effective
  • All existing tests pass
Check Result
TestRegistryFixturesRestoreSSRFPolicy fails on unfixed code (both subtests), passes with the fix
Minimal repro above, -count=2 FAIL → ok
Same three tests, -shuffle= seeds 1-5, -count=1 2/5 fail on main; 5/5 pass here
go test -race -count=2 ./internal/server/..., CI's skip set TestBuildRegistrySourceEntry_RejectsSSRFLiteralIP no longer fails; 0 data races. One unrelated pre-existing failure — see below
./scripts/test-api-e2e.sh 65/65 passed, 0 failed
go vet ./internal/server/ clean
gofmt clean
golangci-lint v2.13.2, .github/.golangci.yml 5 issues in ./internal/server/..., byte-identical to clean main at 4e304ba0 (1 govet inline hint, 4 SA1019 deprecated-field uses in existing test files). None in the three files changed here.

…ures

The registry SSRF allow-policy (MCP-1076 / CWE-918) is process-global state in
internal/registries. Two fixtures disable it so they can serve a loopback
httptest registry, and neither restores it:

  internal/server/mcp_add_from_registry_test.go  startTestRegistry
  internal/server/consistency_official_test.go   startOfficialTestRegistry

Every later test in the binary then runs with the guard disabled.
TestBuildRegistrySourceEntry_RejectsSSRFLiteralIP is the affected case: with the
policy left open, buildRegistrySourceEntry accepts
https://169.254.169.254/v0.1/servers, the cloud-metadata endpoint the test
exists to reject, and all five of its assertions pass without exercising the
guard.

The suite passes today only because add_registry_source_test.go sorts ahead of
both fixtures, so the assertion runs first. -count=2, -shuffle=on, or a new test
file sorting between them each make it fail.

Restore the default catalog and the allow-policy on cleanup, matching
withGuardActive in internal/registries/ssrf_test.go. Production behaviour is
unchanged: the registry CRUD paths clone the live config
(updatedConfig := *currentConfig), so the flag is carried forward rather than
reset.

Add TestRegistryFixturesRestoreSSRFPolicy, which resets the policy itself before
running each fixture and therefore detects the leak independently of test order.
@loloDawit
loloDawit force-pushed the fix/ssrf-guard-test-isolation branch from 356c731 to 54f8cf6 Compare September 8, 2026 00:17
@Dumbris
Dumbris enabled auto-merge (squash) September 8, 2026 17:47
@Dumbris

Dumbris commented Sep 8, 2026

Copy link
Copy Markdown
Member

Thank you for this, Dawit — merged (auto-merge armed, it lands as soon as the last CI job finishes). This was a real find: the two loopback registry fixtures left the process-global SSRF allow-policy disabled, so TestBuildRegistrySourceEntry_RejectsSSRFLiteralIP only passed because its file happened to sort ahead of them in the run order. I reproduced the -count=2 failure on main, confirmed the LIFO t.Cleanup restore fixes it across the shuffle seeds, and checked that the regression test still fails when the guard itself is removed, so the fix removed the ordering coupling without weakening what the test covers. The writeup made it an easy review — much appreciated.

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@Dumbris
Dumbris merged commit 429856e into smart-mcp-proxy:main Sep 8, 2026
38 checks passed
Dumbris added a commit that referenced this pull request Sep 9, 2026
…ail in CI (#1230)

* ci: add an advisory go test -shuffle=on lane so order-coupled tests fail in CI

The registry SSRF regression test only passed because its file sorted
ahead of the two fixtures that flipped the process-global allow-policy
(#1222). Nothing in .github/workflows/ ran with -shuffle, so no lane
could see a different order.

Add 'Unit Tests (shuffle)': the required ubuntu lane's flags and
provisioning (skip regex, -race, tscg shim, frontend embed, tiktoken
warm-up) plus -shuffle=on, without coverage. It is not in the
branch-protection required list, so a newly exposed order coupling in
an unrelated package cannot block a PR while the tail of such tests is
found. Each package prints its seed as '-test.shuffle <n>'; re-run with
-count=1 -shuffle=<n> to reproduce.

* fix(test): isolate TestScanForPII_V7FieldViolations from the global BlockedValues

Service.Start reaches PopulateBlockedValues, a sync.Once that appends
the real hostname and home-dir basename to the package-global
BlockedValues and is never undone. Five test files call Start, and this
was the one ScanForPII test that did not snapshot the global, so under
-shuffle a basename such as "user" tripped rule 2 (blocked_value) on
the "terminated by user" payload before rule 7 could report
v7_field_invalid.

Found by the new shuffle lane's first local run
(-shuffle=1788926312892506000). Same save-and-restore the neighbouring
ScanForPII tests already use.

* fix(review): correct the shuffle-lane replay note about -count=1

-shuffle is not a cacheable go test flag, so a seed replay is never served
from the result cache; the note claimed the opposite. Reword to say why
-count=1 is still kept and what the seed does and does not reproduce.
Dumbris added a commit that referenced this pull request Sep 16, 2026
…al-cache fixture

The loopback-registry fixture sets AllowPrivateRegistryFetch through the
runtime config, which flips the process-wide allow-policy; under the
shuffle lane TestBuildRegistrySourceEntry_RejectsSSRFLiteralIP then ran
after it and accepted a literal IP. Same LIFO cleanup as #1222.

Co-Authored-By: Claude Opus 5 <[email protected]>
Dumbris added a commit that referenced this pull request Sep 16, 2026
…al-cache fixture

The loopback-registry fixture sets AllowPrivateRegistryFetch through the
runtime config, which flips the process-wide allow-policy; under the
shuffle lane TestBuildRegistrySourceEntry_RejectsSSRFLiteralIP then ran
after it and accepted a literal IP. Same LIFO cleanup as #1222.

Co-Authored-By: Claude Opus 5 <[email protected]>
Dumbris added a commit that referenced this pull request Sep 18, 2026
…r, kind-first authorization, monotone child provenance (Spec 105 PR B, FR-001/002) (#1282)

* test(scope): Spec 105 PR B red phase — legacy/internal cache refusal, kind-first gate, monotone child provenance, non-disclosing read_cache (T021–T027)

Failing tests for FR-001/FR-002 gaps FR001-G1..G7, all asserting against
HEAD (bac8f6b) behaviour:

- G1 internal/cache/manager_legacy_test.go (new): nil-producer / version-0 /
  unknown-version / stamped-but-unversioned records refused for every caller
  kind (admin, admin_user, anonymous, agent, user), evicted on first refused
  redemption, absent after bbolt close+reopen, stats consistent with the
  bucket; per-key invalidation. Handler-level admin/anonymous/user refusal in
  internal/server/mcp_read_cache_scope_test.go (new).
- G2 internal/cache/manager_internal_test.go (new): "internal"-stamped
  registry/npm entries refused for every read_cache caller WITHOUT eviction
  (Peek/Get still serve). Writer stamps pinned in
  internal/runtime/registry_cache_stamp_test.go (real SearchRegistryServers
  against a loopback registry) and
  internal/experiments/guesser_cache_stamp_test.go (cacheInfo). Handler-level
  admin refusal + agent/user live≡absent parity + no eviction.
- G3 TestExpiredRecords extended: expired entry absent after the expiring
  Get, in-memory and persisted stats agree with the bucket (rollback bug).
- G4 recursive child carries the PARENT producer (MCP + REST): producing
  agent reads the child an administrator minted.
- G5 agent refusal collapses unauthorized/not-found/expired into one body
  ("cache key not found") on handleReadCache and CallToolDirect.
- G6 TestAuthorization_CallerKindFirst (D5): profile-bound / empty-profile /
  deleted-profile administrators redeem any snapshot; agents never redeem an
  administrator snapshot; deny-all guard applies to agent readers only.
- G7 internal/server/scope_cache_fixtures_test.go (new): upgrade fixture
  with a real restart on the same data dir (SC-004), fresh internal entry,
  recursive child on REST, spec's named profiled-admin → pinned-agent child
  fixture, pinned-token REST dispatch-vs-redemption body parity, and the
  held-call narrowing fixture (regression pin — passes on HEAD).

Not touched (T031, implementation phase): the pre-D5 cells in
TestAuthorization_CouldHaveProduced, TestGetRecordsAs_LegacyEntryWithoutProducer,
and the "not readable with this credential" assertions in
mcp_read_cache_authz_test.go / mcp_call_tool_direct_test.go still pin the
pre-feature behaviour and must be inverted alongside the implementation.

Co-Authored-By: Claude Opus 5 <[email protected]>

* feat(scope): Spec 105 PR B — legacy/internal cache refusal, kind-first gate, monotone child provenance, non-disclosing read_cache (T028–T032)

FR-001/FR-002 implementation turning the T021–T027 red tests green:

- internal/cache: Record.Version (RecordVersion=1, stamped by every Store);
  HasCurrentProvenance; CallerKindInternal; ErrKeyNotFound/ErrKeyExpired/
  ErrLegacyProvenance/ErrInternalEntry (the last two errors.Is
  ErrUnauthorizedRead). getGuarded commits every path that deletes or records
  a stat (miss, expiry, legacy invalidation) by returning nil from the bbolt
  Update closure and surfacing the verdict outside, so the delete is durable
  and m.stats agrees with the bucket (G1, G3). On the gated door an entry with
  no producer, no version or an unrecognised version is refused for EVERY
  caller kind and evicted; an internal entry is refused without eviction
  (G2). ReadCacheResponse.Producer (json:"-") carries the paged entry's
  snapshot.
- CouldHaveProduced is ordered caller kind first (D5, G6): an administrator
  reader qualifies for any snapshot regardless of its own profile binding;
  a non-administrator never for an administrator snapshot; the deny-all
  guard, profile-set, pin, server-set and permission checks apply between
  agent snapshots only; internal producers match nobody.
  Unrestricted() renamed IsAdministrator().
- Writers: runtime registry search and the repository guesser stamp
  CallerKindInternal (G2, T029).
- handleReadCache: a re-truncated page is stamped with the PARENT entry's
  snapshot (childPageProducer), never the redeemer's (G4); readCacheRefusal
  collapses unauthorized/expired/internal/legacy into the not-found body for
  non-administrator callers (G5) while the activity record keeps the real
  reason and administrators get the reason; storage faults stay distinct.
  CallToolDirect inherits both through the shared handler.
- T031 inversions (never deleted): the four pre-D5 admin cells in
  TestAuthorization_CouldHaveProduced, TestGetRecordsAs_LegacyEntryWithoutProducer
  (every caller refused + invalidated), the "not readable with this
  credential" assertions in mcp_read_cache_authz_test.go (now body parity
  with the nonexistent-key answer plus an administrator liveness control),
  and TestCallToolDirect_ReadCachePagesStoredRecords (seeds a stamped record).
- Docs: agent-tokens.md and routing-modes.md describe kind-first ordering,
  monotone child provenance, the non-disclosing body, legacy and internal
  entries. tasks.md T021–T032 ticked; ROADMAP.md regenerated.

Verified: go test -race ./internal/cache/... ./internal/runtime/...
./internal/experiments/... ./internal/httpapi/...; full ./internal/server
with the CI skip regex; -tags server builds and serveredition suites;
goldens untouched; gofmt clean on touched files.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(scope): PR B critique round 1 — refusals commit like a miss (timing class), unknown kinds are legacy, stats never drift, expired internal entries kept

Critique 1 (security):
- (1) MUST-FIX: a scoped read_cache refusal returned its error from the
  bbolt Update closure, so the transaction rolled back with no disk write
  (~5 us) while a miss committed a stats write (~13 ms): a ~3000x timing
  oracle that told a narrow token whether a live entry (a broader token's
  page, or a guessable registry/guesser key) sat behind the key. Every
  refusal now takes the committing branch as a miss; verdicts leave the
  closure through `verdict`, and the closure errors only on storage faults.
  Pinned structurally via bbolt TxStats.Write parity with a miss.
- (2) "unrecognised provenance" was decided on Version only; an entry stamped
  with a caller kind this binary does not know was served to admin and
  anonymous readers. HasCurrentProvenance now requires a known kind.
- (3) stats were decremented before saveStats ran, so a failed write left
  the in-memory counters disagreeing with the rolled-back bucket. Manager.update
  snapshots and restores the stats on a failed closure; saveStats errors
  instead of nil-dereferencing a missing stats bucket.
- (6, with critique 2 #6) an undecodable record (e.g. a version that
  overflows uint8 after a downgrade) is unrecognised provenance on the gated
  door: refused for every caller with the legacy sentinel and invalidated,
  as cleanup already treats it. The ungated Get is unchanged.
- (4) documented: pre-upgrade registry/guesser entries carry no stamp and are
  invalidated once by the first probe; (5) anonymous body is spec-conformant
  (spec.md:37) and is now pinned as the SC-005 parity control.

Critique 2 (parity/tests):
- (4) the gated door evicted an EXPIRED internal entry (expiry ran before the
  internal check) although the registry reader serves it as Stale until
  cleanup; provenance class is now decided before expiry.
- (1) the FR-001 named fixture pins parent-stamping (ProfileScoped/Profile),
  (2) administrator reason bodies and the anonymous parity body are asserted
  (mutation M2 now bites), plus ErrLegacyProvenance/ErrInternalEntry sentinels
  at the cache level, (3) the upgrade fixture re-seeds before every leg,
  (5) REST legs assert the not-found substring, (7) appctx CacheManagerAdapter.Set
  stamps internal instead of writing a legacy entry, (8) handler comment
  reworded for kind-first, (9)+docs: committed expiry eviction, one-time
  invalidation of entries from any earlier release.

Verified: -race on internal/cache, runtime, experiments, httpapi, appctx,
internal/server (with the standard skip list) and the -tags server suites;
goldens byte-identical.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(scope): PR B codex round 1 — empty server grant is deny-all on cache redemption

Codex round 1 (both chunks, one defect): an agent reader whose token
carries no AllowedServers is deny-all on every dispatch gate
(auth.CanAccessServer, serverInScope), but cache.CouldHaveProduced let
coversServers([], []) succeed, so an empty-grant agent could redeem an
agent-produced entry whose snapshot also carried an empty grant — on the
MCP read_cache tool and on the /api/v1/tools/call read_cache branch
alike. An empty grant is reachable: token creation normalises it to ["*"],
but a server-edition rotation that narrows the grant persists nil.

The agent branch of the gated predicate now opens with the empty-grant
deny-all guard, alongside the existing empty-profile one: such a reader
could have produced no entry, its own identically-stamped one included.
Refusal body and timing class are the not-found ones already in place.

Tests: nine new cells in TestAuthorization_CallerKindFirst (nil and []
grants, own entry, another empty-grant agent's, unscoped agent, admin;
broad agent and administrators still read the empty-grant entry), and
fixture (f) TestScopeCacheFixture_EmptyGrantAgentIsDenyAllOnRedemption:
CanAccessServer + REST direct dispatch refused as premise, administrator
control reads the record, MCP and REST live key ≡ absent key with the
not-found body, no eviction.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(scope): PR B codex round 2 — deny-all producer snapshots, commit-failure stats, header-only refusals

Codex round 2 on Spec 105 PR B (FR-001/FR-002), three cache findings and
one server finding, all confirmed by probe before fixing:

1. A current-version agent PRODUCER snapshot with an empty server grant, or
   bounded to an empty effective profile, could have authorized no tool, yet
   containment against the empty set let any broader agent redeem it.
   CouldHaveProduced now rejects such producer snapshots for agent readers
   before containment; administrators still qualify for any snapshot.

2. Manager.update restored the in-memory stats only when the closure
   failed. A commit failure after a successful closure (disk full at fsync)
   left the record on disk with the counters already decremented. The
   snapshot is now taken before db.Update and restored on any error, under
   a mutex so it is taken under the same exclusion the transaction runs
   under; a dbUpdate seam lets a test fail the commit after the closure.

3. Refusals were payload-proportional: every existing key was fully
   JSON-decoded (multi-MB FullContent) before provenance, expiry or the
   guard ran, while a miss was not — a timing class the spec's
   non-disclosing refusal forbids. MarshalBinary now writes a small frame
   header (version, producer, expiry, size) in front of the record; the
   gated door decides every verdict short of admission on that header
   alone and decodes the record only after admission. UnmarshalBinary
   accepts framed and pre-frame bare-JSON values. Expired entries are no
   longer evicted by the gated read — refused like a miss and left to the
   cleanup sweep — so only the FR-002 invalidating refusals delete, and
   that delete is pinned as payload-independent.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(scope): PR B codex round 3 — header/body agreement, write-time header bound, pre-frame size accounting

Three confirmed findings on the framed cache record (Spec 105 FR-001/FR-002):

- UnmarshalBinary now requires the frame header to agree exactly with the
  body it fronts (Version, ExpiresAt, TotalSize, deep Producer). The gated
  read admits on the header alone, so a crafted a-only header in front of an
  administrator/broader/legacy body was served to the a-only reader, and a
  future-expiry header over an expired body was decoded and evicted after
  admission. A disagreeing value is undecodable: refused for every caller,
  invalidated (folding out the header's size), never served.
- maxRecordHeaderLen raised 64 KiB -> 1 MiB, sized so an authorization naming
  several thousand servers in both grant and profile fits, and MarshalBinary
  refuses a header over the bound BEFORE persisting. Previously a legitimate
  large snapshot was stored, then refused and deleted on its producer's own
  first redemption; now StoreAs returns errRecordHeaderOversize and the
  truncator serves the payload uncached.
- Invalidating a pre-frame bare-JSON record folded 0 into TotalSizeBytes;
  it now folds out the value's length (known without decoding, an upper
  bound on the content) and evict clamps the total at zero.

Red tests in manager_frame_integrity_test.go; verdict table appended to
.review-tmp/critique-r1.md under "Codex round 3".

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(cache): guard the frame allocation size against overflow (CodeQL)

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(scope): PR B codex round 4 — user containment, content-addressed snapshots, exact pre-frame accounting

Codex round 4 (specs/105, PR B), three confirmed findings:

1. User-kind snapshots kept only the user id and redemption compared only
   the principal, so a server-edition user narrowed since producing an
   entry (grant, permission tier or profile) still redeemed it. Users are
   bounded by the same dispatch gates as agent tokens, so the snapshot now
   carries AllowedServers/Permissions/ProfilePin and the read gate applies
   the same containment on top of identity equality (necessary, never
   sufficient). Shared rule: IsScoped/DenyAll/kindVerdict/containedBy.

2. The 1 MiB frame-header bound refused legitimate snapshots (configuration
   bounds neither server count nor name length), and a live-key refusal
   JSON-decoded the whole header on every probe — a fleet-sized timing
   oracle a miss did not share. The frame header is now FIXED-SIZE (52
   bytes: version, kind code, deny-all bit, expiry, size, snapshot SHA-256);
   each distinct producer snapshot is stored once in a content-addressed
   `cache_snapshots` bucket, written in the same transaction as the record
   and pruned by cleanup; the gate decides kind, version, expiry and
   deny-all on the header and loads the snapshot — through a small LRU,
   O(1) after the first probe — only for same-kind containment. No size
   bound remains: a 5,000-server snapshot round-trips and is redeemable by
   its producer, warm and after a restart.

3. Pre-frame invalidation folded out the raw record length (escaped JSON)
   and clamped the aggregate at zero, understating unrelated live entries.
   The legacy path — one-shot, every caller — now decodes the bare-JSON
   value and folds out exactly len(FullContent); the clamp is gone.

Every finding was reproduced by a probe and pinned by a red test proven
against pre-fix HEAD. Docs: agent-tokens.md.

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(server): restore the registry SSRF allow-policy after the internal-cache fixture

The loopback-registry fixture sets AllowPrivateRegistryFetch through the
runtime config, which flips the process-wide allow-policy; under the
shuffle lane TestBuildRegistrySourceEntry_RejectsSSRFLiteralIP then ran
after it and accepted a literal IP. Same LIFO cleanup as #1222.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(scope): PR B review round 5 — header-only read gate (research D16), no legacy decode

Codex round 5 (specs/105, PR B), one root behind both findings: any
refusal that must LOAD the producer snapshot (round 4's content-addressed
snapshot was O(1) only while its 128-entry LRU was warm — a restart or
129 distinct snapshots made the first same-kind refusal read and JSON-
decode a fleet-sized snapshot) or DECODE the legacy value (round 4's
one-shot preFramePayloadSize) does work proportional to hidden state,
which the spec's non-disclosing refusal forbids in the timing class.
Measured before the fix: cold scope refusal against a 5,000-server
producer 1,657,864 B vs a 58,104 B miss; legacy 4 MB refusal 8,500,992 B.

Structural answer, recorded as research.md D16: the gated door decides
in O(1) from the fixed 52-byte header alone — it admits (a) an
administrator reader (FR-001 kind first), (b) an unrestricted agent
(wildcard grant, no pin, no profile) whose tier set covers the
producer's tier bits, now carried in the header's formerly reserved
byte, or (c) a reader whose effective-authorization DIGEST (SHA-256 of
the canonical snapshot: kind, principal, sorted AllowedServers, sorted
Permissions, pin, ProfileScoped, sorted ProfileServers — the profile
name excluded) equals the producer digest in the header; every other
reader is refused without loading anything. Reader facts are computed
once before the transaction so a miss and a refusal do the same work;
CouldHaveProduced is the same `admits` over the same facts. A strictly
wider but bounded reader is now refused: FR-001 obliges refusing
non-supersets, not admitting supersets, so the cells that pinned its
admission are inverted with names stating the new contract (three
agent cells, three user cells, one server-level user cell). The
snapshots bucket stays, keyed by the digest, for administrator
diagnostics only; the LRU, loadSnapshot and producerView are gone.
Frame magic \x02 -> \x03 (never in a release).

Legacy (pre-frame / corrupt-frame) entries are refused and deleted
WITHOUT decoding: the entry count is folded out exactly, the size is
left to the existing cleanup sweep, which now recomputes TotalEntries
and TotalSizeBytes from the bucket it already walks, so the statistics
are eventually consistent while the refusal stays O(1).

Tests (red first): the allocation matrix probes every refusal through a
reopened manager and gains the cold 5,000-server producer and the
pre-frame 4 MB legacy cells (after: wide = small = miss = 25,112 B);
digest-equal, reordered-list, renamed-profile and unrestricted readers
admitted cold; strictly-wider readers refused; the snapshots bucket
proven diagnostics-only; the sweep restores exact stats after a legacy
invalidation and reconciles arbitrary drift. Docs: agent-tokens.md.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(scope): PR B review round 6 — reserved header bits are unrecognised provenance; admitted readers never get the refusal shape

Codex round 6, cache finding 1: decodeHeaderBytes accepted flag bits
outside recordFlagDenyAll and tier bits outside the emitted mask. With
the digest preserved, an unknown tier bit was admitted on digest
equality and caught only by the header/body agreement check after a
payload-sized decode — the timing class round 5 removed — and an
unknown flag bit was invisible to both the decoder and agreesWith, so
the record was served. The decoder now rejects any reserved bit as
errRecordFrameCorrupt, so the gate classifies such a frame as
unrecognised provenance on the existing O(1) refuse-and-invalidate
path before admission. permBitKnown names the emitted union.

Server finding 1: an admitted (digest-equal / wildcard / admin) reader
whose body proved undecodable or header-disagreeing received the
not-found refusal shape after the body decode. By contract the
non-disclosing definition covers callers the gate refuses, and this
reader was admitted on the header — but so that every response wearing
the refusal shape is one the header decided, the branch now yields the
admitted-class ErrEntryUnreadable (not an ErrUnauthorizedRead, not a
miss), still invalidated, rendered for every caller kind as "cache
entry is unreadable … and has been invalidated". contracts/refusals.md
states the rule.

Tests: TestGetRecordsAs_UnknownHeaderBitsAreUnrecognisedProvenance (a
4 MB entry with one header byte flipped, probed cold by its producer
and an administrator: legacy verdict, invalidated, within the miss
allocation budget; exhaustive decoder sweep), the scoped-reader
malformed-body case beside the administrator one in
manager_legacy_test.go, the admitted-body fixtures retargeted to
ErrEntryUnreadable, and
TestReadCache_AdmittedReaderOfUnreadableEntryGetsDistinctBody at the
handler.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Dumbris added a commit that referenced this pull request Oct 20, 2026
## What

Experiment E5: when an **external** contributor's PR is merged, a bot
posts **one** thank-you comment with an optional, copy-paste share
snippet, and release notes credit external contributors.

- `.github/workflows/contributor-thanks.yml` — `pull_request_target:
closed` (merged only) + `workflow_dispatch` for manual dry runs.
- `scripts/contributors.sh` — `thanks <pr>` and `release <prev-tag>
<ref>`; `scripts/test-contributors.sh` — 26 offline checks.
- `release.yml` — new "Collect contributors" step; a `## Contributors`
section is appended after the LLM-written notes (deterministic, so a
name is never dropped or invented). Existing tooling did not credit
anyone: notes are LLM-summarised commit subjects, git-cliff
`CHANGELOG.md` has no author section.
- `CONTRIBUTING.md` — short "Recognition" note.

Skipped: author `Dumbris`, `algis-dumbris`, any `[bot]`/Bot type, and
association OWNER/MEMBER. Posted as `github-actions[bot]`, never as
Algis. Nothing is posted on the contributor's behalf.

## Comment wording — please approve (rendered for PR #1222, first-time
author)

````text
<!-- contributor-thanks:v1 -->   (hidden marker, used for idempotency)
Thank you @loloDawit! Your PR "fix(test): restore the registry SSRF allow-policy after loopback fixtures" is merged and will ship in the next release.

This is your first merged contribution to MCPProxy. Welcome, and congratulations!      <- only if first-time

If you would like to mention it, here is a snippet you can copy and edit:

```text
My PR to MCPProxy, an open-source MCP proxy for Claude Code, Codex and
Cursor, just got merged:
#1222
Repo: https://github.com/smart-mcp-proxy/mcpproxy-go
```

Sharing genuinely helps a small open-source project get found. It is entirely optional, and we are grateful either way.
````

679 chars with the first-time line (~600 without); ASCII only. "next
release" is used because the release isn't known at merge time. The PR
title is sanitised (one line, `@` neutralised, backticks/brackets/angle
brackets stripped, 120 chars max).

Release-notes section (example, `release v0.70.0 v0.71.1` run
read-only):
```
## Contributors

Thank you to our external contributors for this release: @sb123sb123, @mvanhorn, @AdamMagued, ... @rudycelekli
```

## Rollout — nothing posts until Algis flips it

Every run is a **dry run** (comment printed in the job log, nothing
posted) until the repo variable `CONTRIBUTOR_THANKS_LIVE` is `true`:
`gh variable set CONTRIBUTOR_THANKS_LIVE --body true -R
smart-mcp-proxy/mcpproxy-go`
Manual dry run for any merged PR: Actions > Contributor Thanks > Run
workflow (it only posts if the variable is `true` AND `dry_run` is
unchecked).

## Security (`pull_request_target`)

Checks out only the default branch (`sparse-checkout:
scripts/contributors.sh`, `persist-credentials: false`); never PR head
code. PR data comes via the API, is passed through env/quoted args only,
never interpolated into shell. `permissions: {}` at top, job gets
`contents: read, pull-requests: write, issues: write`. Per-PR
concurrency group + marker check (bot-authored comments only) for
idempotency.

## Testing

- `bash scripts/test-contributors.sh` — 26/26 (eligibility, template,
length < 900, no non-ASCII, hostile titles).
- Read-only dry runs against real PRs: #1222 (first-time=true), #1664
(repeat, first=false), #1690 (maintainer -> skipped). `release v0.70.0
v0.71.1` produced the list above.
- `actionlint` clean on `contributor-thanks.yml`; `release.yml` has the
same pre-existing 53 findings before and after (none from the new step).
`shellcheck -x` clean. `yamllint` not installed. `act` not installed.
**No comment was posted anywhere.**

## Cross-model review (opencode `github-copilot/gpt-6.1-sol`, high)

- Round 1 (the first attempt exited without a verdict — treated as
UNREVIEWED and re-run with a tighter brief): 2 P2 findings, both fixed:
(1) any commenter could suppress the thanks by pasting the marker → only
`github-actions[bot]` comments count; (2) search-index
lag/`incomplete_results` could mis-flag first-time → incomplete =
not-first (residual race for two first-timer PRs merged within index lag
documented and accepted).
- Round 2: **VERDICT: CLEAN** (also ran mocked-API scenarios: empty
comments, human marker, bot marker, later page, incomplete search).

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

---------

Co-authored-by: Claude Sonnet 5.5 <[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.

3 participants