Skip to content

Commit 06cba37

Browse files
Dumbrisclaude
andauthored
fix(scope): selectable-profile predicate on /mcp/p and set_profile with one non-disclosing refusal (Spec 105 PR D, FR-003/004) (#1283)
* test(scope): Spec 105 PR D red phase — selectable-profile predicate on /mcp/p and set_profile (FR-003/004, FR003-G1..G8) Failing tests for Phase 4 (T035-T040), all RED on HEAD by assertion: - T035: generalise mintPinnedToken → mintAgentToken(t, env, name, allowed, perms, pin); mintPinnedToken stays as a thin wrapper for the pre-105 pin tests (H1 reuses the generalised minter). - T036 (G1/G2/G5): TestProfile_ScopedUnpinnedRefusalUniform — research-srv-only unpinned token: /mcp/p/deploy (HEAD 200), /mcp/p/nonexistent, /mcp/p, /mcp/p/ and deleted /mcp/p/deploy (HEAD 404 + `available`) must share one 404 status+body with no `available`; /mcp/p/research positive control. - T037 (G3/G4): TestProfile_PinnedRefusalUniform (HEAD 403/403/404) and TestProfile_PinnedRefusalIndependentOfFleet (HEAD "no profiles configured" before the gate); anonymous no-profiles branch kept as admin control. - T038 (G6): TestHandleSetProfile_URLScopeGovernsReportedServers — set_profile on a URL-scoped endpoint stores the selection but reports URL profile ∩ token. - T039 (G7): TestSetProfileClearPinnedReportsEmptyActiveProfile — clearing a pinned selection reports active_profile == "". - T040 (G8/D1): TestHandleSetProfile_PinnedZeroReachRefusedLikeDeletedPin (empty/ghost/disjoint pin refused with the deleted-pin body, no mutation) and TestProfile_PinnedZeroReachURLRefusedUniformly (/mcp/p/<zero-reach pin> uniform 404; HEAD 200). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(scope): Spec 105 PR D — selectable-profile predicate on /mcp/p and set_profile (FR-003/004, FR003-G1..G8, D1) profileMiddleware (T041): scoped callers (auth.IsScopedCaller — agent tokens and server-edition users) are admitted through /mcp/p/<slug>, /mcp/p and /mcp/p/ only when the slug is in selectableProfileNames; every other outcome — missing, deleted, configured-but-unreachable, empty profile, pin mismatch, zero-reach pin, slug-less path, empty fleet — is answered by ONE constructor (profileNotSelectable: 404 {"error":"unknown profile '<slug>'"}, no `available`, no pin). The no-profiles branch now runs after the gate; the pre-105 403 pin branch is gone (a pinned agent is always a scoped caller). Admin / anonymous callers keep the two pre-105 404 branches (SC-005). handleSetProfile (T042): one selectable check for every non-empty slug; `servers` is the effective scope after the update via resolveActiveProfile (pin > URL > session) ∩ token — on a URL-scoped endpoint the URL profile, not the stored selection; `active_profile` is the stored selection, so a cleared pinned selection reports "". selectableProfileNames' pin branch now requires reach (D1): an empty/ghost/disjoint pin is refused with the deleted-pin body and the session is not mutated. Docs (T043): docs/features/profiles.md set_profile payload semantics and the scoped /mcp/p refusal; docs/features/agent-tokens.md pin section (404, not 403; zero-reach pin ≡ deleted pin). Inverted pinned tests (T044), never deleted: TestProfile_PinnedTokenURLEnforcement (403+pin text → uniform 404 without pin), TestSetProfileClearReportsPinnedScope and TestHandleSetProfile_PinnedTokenClearIntersectsAllowedServers (active_profile "" on clear), TestHandleSetProfile_PinnedTokenSelectsDisjointPin (→ refuses, no mutation). Admin controls kept: TestProfile_404NoProfiles/404UnknownSlug, TestHandleSetProfile_AdminUnchanged, the anonymous `available` control in TestProfile_DeletedPinDoesNotEnumerateProfiles. Verified: go test -race (CI -skip regex) ./internal/server/... ok; go test -tags server -race ./internal/serveredition/... ok; both editions build; gofmt/vet clean on touched files; goldens untouched. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scope): PR D critique round 1 — admin set_profile parity, single-snapshot resolver, operator log on profile-URL refusals, fail-closed nil-config auth Findings confirmed and fixed (red-test-first; verdict table in .review-tmp/critique-r1.md): - A1/A2 (SC-005): handleSetProfile rendered `servers` from ProfileScope's map-backed set — nondeterministic order, duplicates dropped — for every caller, and applied FR-003's URL-precedence reporting to administrators too. Administrators now short-circuit to the pre-105 payload (selected profile's EffectiveServers / allServerNames on clear, byte-for-byte); scoped callers render the effective scope in profile-declared order. Admin controls now require.Equal exact slices on a 5-server fixture and an admin URL-scope leg is added. - S4/N7: resolveActiveProfileIn(ctx, cfg) / profileScopeForSlugIn(cfg, slug) — the handler admits, stores and reports from ONE config snapshot. - S1: profileMiddleware logs every scoped refusal (agent_name, profile, remote_addr) — the gate answers before the logging handler, so this is the only trace a token probing /mcp/p/<slug> leaves. - N5: mcpAuthMiddleware refuses (503) an agent token when no configuration is published instead of forwarding it with no AuthContext (absent context reads as administrator downstream). - Tests: assertUniformProfileRefusal pins the error text; vacuous NotContains removed; duplicate pin-clear test folded into the inverted original. - Docs: server-edition-user over-claim removed; deleted-pin warning attributed correctly; pin-mismatch message documented. Deferred with rationale: resolver collapse of a zero-reach pin (PR C fixture), pin-naming mismatch text (PR G), client-choosable session id (Spec 058 US3). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scope): PR D codex round 1 — constant-traversal selectable-profile predicate selectableProfileNames returned on the first reachable pin but walked the whole profile slice for a deleted or zero-reach pin. profileMiddleware and handleSetProfile consult it before issuing the uniform refusal, so a pinned caller could tell "pin alive, slug mismatched" from "pin gone / zero reach" by the work its own refusal cost — a timing-class oracle on pin existence (spec Definitions: non-disclosing = status, body AND timing class). The predicate is now forEachProfileSelectable: it visits every configured profile in order, computes reach for each one whenever the caller is scoped or pinned, applies the pin as a filter and never returns early; selectableProfileNames accumulates through it into a pre-sized slice so even the result allocation is constant. Administrator semantics are unchanged (every configured profile, empty and ghost ones included — SC-005); the orphaned profileNames helper is removed. Tests: TestSelectableProfileNames_PinOutcomesDoSameWork (AllocsPerRun parity across reachable / zero-reach / deleted pin on an equal-sized fleet — 2/1/0 before, equal after) and TestForEachProfileSelectable_VisitsEveryProfileRegardlessOfOutcome (traversal counter over eight caller kinds, picks == selectableProfileNames). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scope): PR D codex round 2 — O(1)-in-the-fleet profile-URL gate The uniform /mcp/p/<slug> refusal computed the whole selectable-profile list (one reach pass per configured profile) before refusing, so a scoped token's refusal cost zero iterations over an empty fleet and one per profile over a populated one — same 404 body, work proportional to the number of hidden profiles (FR-004 timing class; 1.7 µs vs 0.9 ms at 10 000 profiles through the middleware). - profileIndex: immutable slug → profile map per config snapshot, cached by snapshot pointer (profileIndexCache, atomic.Pointer on Server). - profileIndex.selectable evaluates the selectable rule for the requested slug (and the pin) only: same lookups and one allocation-free reach computation (profileHasReach, shared with forEachProfileSelectable) on every branch — absent, not selectable, deleted pin, zero-reach pin, pin mismatch, no profiles. - profileMiddleware → serveProfileURL(w, r, cfg, next): the gate after the snapshot read, so fleet tests run on a bare Server (a live runtime over 4 097 profiles spends the test building per-profile indexes). set_profile keeps selectableProfileNames; the URL gate never calls it. - Tests: refusal allocation parity over 0/1/4 097-profile fleets; lookup- hook traversal seam (gate resolves ⊆ {slug, pin}, mutation-tested); wiring through the seam; pure-predicate zero-alloc and list-equivalence; cache-per-snapshot. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scope): PR D codex round 3 — precomputed per-profile reach, O(1) set_profile refusal, warmed index Codex round 3 on Spec 105 PR D (FR-003/FR-004, research D1): three findings, all confirmed by trace and throwaway timing probe, fixed red-test-first. 1. The warmed URL gate still told a deleted pin from an existing zero-reach one by work: profileHasReach scanned the candidate's declared list for every configured server (nil for a missing profile, the real list for an existing one) — 9.3 ms vs 3.2 µs over 4 096 servers. Reach is now precomputed per profile when the per-snapshot index is built (one bitset over the configured servers' positions, plus an all-zero placeholder for a slug the snapshot lacks); profileIndex.reach reads one bit and runs the credential check unconditionally per configured server, so a missing, deleted, empty or 4 096-server candidate costs the same (24.7 µs each). 2. set_profile decided the requested slug through the whole selectable list (one reach computation per configured profile) — 0.3 µs over one profile, 63 µs over 4 097, byte-identical body. It now decides the requested slug alone through the same index (profileIndexFor → the main Server's cache in production); a scoped caller's refusal is the list-free `unknown profile '<slug>'`, administrators keep the pre-105 `available:` affordance (SC-005). Traversal-counter seam: every scoped refusal over a 1- or 4 097-profile fleet resolves ⊆ {slug, pin}. 3. Prior item: the index was still built lazily by the first request after startup or a reload (one insertion per hidden profile). Server now warms it at construction and on every config.saved / config.reloaded / servers.changed event; the lazy build stays as the fallback for the event-delivery window. Tests: TestProfileIndex_ReachIsPrecomputedAtBuild, TestHandleSetProfile_ScopedRefusalTouchesOnlySlugAndPin, TestHandleSetProfile_AdminUnknownSlugKeepsAvailableList, TestProfileIndex_WarmedBeforeFirstRequest; the list-carrying scoped assertions inverted per SC-007 (never deleted). Docs: profiles.md set_profile bullet + §404 responses; tasks.md T041/T042; verdict table in .review-tmp/critique-r1.md "Codex round 3". Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scope): PR D review round 4 — reach costs the reader's grant, never the fleet profileIndex.reach walked every configured server and ran the credential check on each, so a scoped token's uniform refusal on /mcp/p/<slug> and on set_profile cost one iteration over a one-server fleet and 4 096 over a fleet with 4 095 hidden servers — same 404, same zero allocations (so the allocation-parity guards were blind), 36 ns vs 25 µs: the operator's server population was a timing oracle (FR-004; spec Definitions: non-disclosing = status, body AND timing class; codex review round 4). Reach is now O(|reader grant|): the index precomputes per snapshot a server name → position map, the per-profile membership bitset and a per-profile non-empty flag. A reader that may see every server (administrator, absent context, wildcard entry) does one test — is the candidate's set non-empty; a restricted reader walks its OWN allowed_servers and does one O(1) membership test per entry against the candidate's precomputed set, never returning early, so the count is the grant size whatever the fleet, the candidate (present, absent, empty, 4 098-server) or the outcome. After: 29–31 ns over 1 and 4 096 hidden servers alike. Traversal-counter seam profileIndex.reachHook (one call per membership test). Red tests: TestProfileMiddleware_RefusalReachCostsTheGrantNotTheFleet over the new "4096 hidden servers" fleet shape in profile_url_gate_test.go (the round-2 allocation-parity and lookup-seam tests replay over it too), TestProfileIndex_ReachCostsTheGrantNotTheFleet, and the set_profile leg TestHandleSetProfile_ScopedRefusalReachCostsTheGrantNotTheFleet. Docs: profiles.md (set_profile and profile-URL cost statements), tasks.md T041. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scope): PR D review round 5 — index every snapshot before publication; two-slot cache no request can roll back Prior item P (round 3/4 residual): the profile index was warmed from the config EVENT, which configsvc delivers after snapshot.Store, so a request in the publication-to-event window built the fleet-sized index inline — a window a token with server-write permission can open itself. configsvc gains AddPrePublishObserver, a read-only observer list distinct from the #937 admission gate's single SetPrePublishHook slot: observers run inside updateLocked after the gate hook and before snapshot.Store, on the exact *Config that will be published. NewServer registers the index build there; the construction-time warm (the initial snapshot is stored without observers) and the event warm (belt-and-braces) stay. Finding 1: profileIndexCache.For stored whatever snapshot its caller captured, so a stalled request holding an older snapshot evicted the warmed index for the current one and the next request rebuilt 4 096 hidden profiles. The cache is now two-slot: warm (written only by the warm path) and lazy (For's fallback, which never touches warm); the previous warm index is demoted into lazy so a request that captured its snapshot just before a publication still finds it. Tests: configsvc observer ordering (sees the gated config before Current() moves and before subscribers are notified; nil-safe), zero lazy builds across N reloads over a live runtime with an observer-order seam, and the rollback regression. research.md D17 records the decision. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scope): PR D review round 6 — requests take the profile index and its snapshot as one pair; observers may register observers Codex round 6 on the Spec 105 PR D profile work (two findings). 1. MUST-FIX: the two-slot index cache still let a request build a fleet-sized profile index inline — a request that captured snapshot A and paused across two publications (warm C, lazy B) rebuilt A on resume, while the empty-fleet equivalent built nothing (FR-004 timing class). Structural fix: the request path never captures a config snapshot of its own. profileIndexCache.Current() hands out the warm index, which carries the config it was built from (idx.cfg); profileMiddleware passes that index to serveProfileURL and handleSetProfile takes profileIndexCurrent() and decides over its cfg — admission, server list and effective scope alike. The previous-warm demotion is gone (a request holds the index it was handed); For stays as the bare-test-server build slot only, never writing the warm slot. Because the pre-publish observer warms the slot before snapshot.Store, a request may hold the index of the gated config about to be published, one publication ahead of runtime.Config() for microseconds — documented as acceptable. 2. SHOULD: runPrePublishObservers held observersMu.RLock across the callbacks under updateMu, so an observer registering another observer deadlocked. The list is now cloned under the read lock and released before observers run; AddPrePublishObserver documents that observers run under the update mutex and must not publish (Update / UpdateIfCurrent / ReloadFromFile re-enter by design). Tests (red first): TestProfileRequests_ServeTheIndexAboutToBePublished (URL gate and set_profile, from inside a publication, admit the profile that exists only in the config being published; zero builds), TestProfileIndexCache_PausedRequestKeepsTheIndexItWasHanded, TestProfileRequests_NeverBuildTheIndexOverARuntime (lazyBuilds seam stays 0 on both caches across every request entry and three reloads), TestService_PrePublishObserverMayRegisterAnObserver. research.md D17 updated: the request path takes the index+snapshot pair; no request builds. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scope): PR D review round 8 — request-visible profile index tracks the published snapshot, not the one ahead of it The warm (index, cfg) pair became request-visible the instant the pre-publish observer ran, before configsvc stored the snapshot, so a request could be admitted against the NEXT config while resolveActiveProfile's pin tier — reading runtime.Config() independently downstream — still answered the previous one: admission and the effective scope could split across two snapshots within one request. profileIndexCache now keeps the last two prepared pairs (warm, previous) and Published(cfg) returns whichever matches the caller's own runtime.Config() read, never the unconditional latest one; profileMiddleware and profileIndexCurrent call it instead of Current(). serveProfileURL also injects the admitted pair's cfg into the request context, and resolveActiveProfile reads it in preference to a fresh live read, so a reload landing between admission and a downstream pin resolution can't split the two either. TestProfileRequests_ServeTheIndexAboutToBePublished is rewritten (and renamed) to assert the opposite of its old behaviour; TestProfileMiddleware_InjectsAdmittedSnapshotForDownstreamResolution is new. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(server): let background initialization settle before profile gate tests run The profile-gate fixture returned while the runtime's background initialization was still writing index.bleve under the test's TempDir, so shutdown and the TempDir cleanup raced it (shuffle lane: "directory not empty"; Windows: "file is being used by another process"). Wait for PhaseReady first, as server_logs_missing_file_test already does. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(server): measure the pin-outcome allocation parity without process-wide noise testing.AllocsPerRun counts every malloc in the process, so a goroutine still winding down from an earlier test inflated one case (CI read 48 against 12). Build the index outside the window and take the minimum over a few samples of the predicate alone — noise only ever adds. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scope): PR D review round 9 — set_profile decides with the URL gate's admitted (index, snapshot) pair, and a pin mismatch refuses like any other non-selectable profile MUST-FIX 1: handleSetProfile called profileIndexCurrent(), which read runtime.Config() independently even on a /mcp/p/<slug> request whose gate had already admitted a specific (index, cfg) pair and injected only cfg into the context. A reload landing between admission and the set_profile call could hand set_profile a different snapshot than the one the URL gate used for the same request. serveProfileURL now injects the whole admitted *profileIndex pair (withProfileRequestIndex); profileIndexCurrent(ctx) and resolveActiveProfile both prefer it outright — no build, no Published()/runtime.Config() read — falling back to the existing Published/For chain only for the base /mcp endpoint, which admits no snapshot of its own. MUST-FIX 2: a profile-pinned token asking for a different, otherwise selectable profile was refused by an early branch ("agent token is pinned to profile '<pin>' and cannot switch to '<slug>'") before any index lookup, distinguishable in body and work from the uniform "unknown profile '<slug>'" a deleted, zero-reach or disjoint profile receives. That branch let a caller confirm from the wording alone that it is pinned, and to what. It is removed; a pin mismatch now falls through to profileIndex.selectable, the same predicate and body as every other non-selectable outcome (contracts/refusals.md's `set_profile <not selectable>` row already documented this as one format string). Tests: TestProfileMiddleware_SetProfileDecidesWithTheAdmittedIndexNotAFreshRead (new — a profile present only at admission stays selectable after a reload removes it live, and a profile present only in the reload stays refused, both within the one admitted request); TestHandleSetProfile_PinnedRejectsOtherSlug and TestHandleSetProfile_ScopedRefusalTouchesOnlySlugAndPin updated for the uniform body; TestHandleSetProfile_ScopedRefusalReachCostsTheGrantNotTheFleet extended with the pin-mismatch case. docs/features/profiles.md and specs/105-agent-scope-hardening/research.md (D1, D17) updated to match. Verification: gofmt clean; go build (both editions, -o /dev/null); GOOS=linux/windows go vet ./internal/server/...; go test -race -count=1 on ./internal/server/... (standard -skip regex, 400s), ./internal/runtime/... (5 packages) and -tags server ./internal/serveredition/... (7 packages) — all green. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scope): PR D review round 11 — acquire the profile-index pair atomically, never a stale read-then-match profileMiddleware and set_profile's base-/mcp path (profileIndexCurrent) each read runtime.Config()/currentConfig() once and only then called Published(cfg) against that frozen read, falling back to For(cfg) on a miss. A request paused across two publications between those two steps missed both the warm and previous prepared pairs and fell back to a fleet-sized inline build — the same timing-class disclosure D17 exists to close, just relocated from the admission race (rounds 7-9) to the acquisition race between a request's own config read and the cache lookup. profileIndexCache.Acquire(readCfg) closes it structurally: it loops a bounded number of times (8), re-reading readCfg() and matching it via Published on every iteration instead of freezing one read that may already be stale by the time it is used. Each iteration is O(1), so even a publication storm costs O(retries), never a build. A genuine miss (nil) is left for the caller: serveProfileURL and profileIndexCurrent refuse a scoped caller uniformly and O(1) on nil (no lookup, no disclosure, no build) and fall back to a fresh For build for an administrator-shaped caller, whose timing is not contract-bound (SC-005). For/Current remain only the bare-test-server fallback and the caches' own warm-path mechanics. research.md D17 extended with the round-11 acquisition rule. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(scope): PR D review round 13 — refute the synchronous observer-cost finding with a file:line trace and measurement The round-13 reviewer finding claimed a write-capable agent's config mutation (upstream_servers add) builds the profile index synchronously inside the pre-publish observer, making its latency scale with hidden profiles/servers — a D17/SC-005 non-disclosing-refusal concern. Traced instead: Runtime.applyConfigLocked already runs DetectConfigChanges (walks and JSON-diffs the whole Servers slice, twice, sometimes three times), config.SaveConfig (marshals the entire config to disk) and upstreamManager.SetGlobalConfig (walks every live client) before configSvc.Update ever runs the pre-publish observer that builds the profile index. The config-publishing path was already O(fleet) end to end; the observer adds a bounded constant factor to a timing class that predates this PR. Measured at 4096 profiles/servers: newProfileIndex (the observer) = 437 µs/op vs SaveConfig = 19.42 ms/op and one DetectConfigChanges pass = 9.81 ms/op (called 2-3x per apply) — well under 1.1% of the pre-existing work, so the maintainer's move-the-bitset-out-of-the- observer branch does not fire. Also confirmed the profiles×servers bitset is not a droppable dead artifact: idx.reach reads it via an O(1) bit test on every scoped call, the mechanism that keeps profile selectability O(reader grant) rather than O(fleet) (D1) — so it stays. No production code changed. research.md D17 records the refutation verbatim; .review-tmp/critique-r1.md carries the full file:line trace and benchmark; .review-tmp/pr-d-body.md carries the same "Retained effects" text for the eventual PR body. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(scope): admitted scoped reads render servers from the profile index, never a fleet walk (Spec 105 PR D review round 14 — MUST-FIX) After O(1) admission, successful scoped reads still materialized their effective server set by rebuilding a fleet-sized "known servers" set on every call: /mcp/p/<slug>, resolveActiveProfileIn's pin/session tiers (every scoped retrieve_tools/describe_tool/call_tool_*/code_execution call under a pinned or session profile), and set_profile's success payload (including the cleared-session case, which additionally walked every configured server a second time to apply the credential). profileIndex.EffectiveServersFor(profileName, allowed) intersects the reader's own grant against the index's precomputed serverPos/members data instead: O(len(allowed)) for a restricted grant, never O(len(cfg. Servers)). All four cited call sites now use it (or its int-keyed sibling effectiveServersForCandidate, reusing an admission lookup the gate already paid for); administrators keep the unchanged, fleet-proportional path (SC-005). scopeServersIn/callerVisibleServers are now dead and removed. profileIndex.position also gained a bounds check against idx.cfg. Profiles' CURRENT length: two existing tests mutate *config.Config in place after an index is built/cached, which the new EffectiveServersFor call sites exposed as an out-of-range panic on a stale cached position. The check is a no-op for any snapshot that is never mutated in place. research.md D17 records the round; golangci-lint (stuck on Go 1.25 since round 6) upgraded to 2.13.2 so the v2 lint pass could actually run locally. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(scope): resolveActiveProfile decides straight from the admitted pair (Spec 105 PR D review round 15 — MUST-FIX) resolveActiveProfile extracted only injected.cfg from the context-carried (index, snapshot) pair and handed it to resolveActiveProfileIn, which resolved the index a SECOND, independent time via profileIndexFor(cfg) — an O(1) Published(cfg) match that falls back to a fleet-sized For(cfg) rebuild on a miss. A request admitted with pair A that then paused while two more publications landed would find A evicted from both the warm and previous cache slots by the time resolveActiveProfile ran, rebuilding the whole fleet inline for what must stay an O(1) decision — exactly the pair-acquisition bypass rounds 11/13 closed on the admission path (profileIndexCurrent/Acquire), reopened here on the downstream resolution path a paused request reaches next. resolveActiveProfile now calls resolveActiveProfileFromIndex directly with the already-resolved pair when profileRequestIndexFromContext succeeds, bypassing resolveActiveProfileIn/profileIndexFor(cfg) entirely on that path; the profileIndexFor(cfg) route is reached only for the no-injected-pair case (plain /mcp, no URL admission), unchanged. A second round-12 finding argued resolveActiveProfileIn's pin/session tiers should intersect the profile's declared membership with the caller's own AllowedServers instead of a hardcoded wildcard, to bound the per-call cost by the caller's grant rather than the profile's (possibly much larger) declared population. Refuted: round 14 already tried and reverted exactly this change (recorded in its own research.md D17 entry), and reproducing it this round breaks the same tested contract (TestResolveActiveProfile_PinHighestPrecedence, a pin context with no AllowedServers asserting full pin-profile reach) — the reproduction and the full downstream-consumer trace are recorded in research.md D17 and .review-tmp/critique-r1.md under "Review round 15"; no production code changed for that finding. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(scope): cache producer/reader stamp intersects an agent token's own grant with its profile (Spec 105 PR D review round 17 — MUST-FIX) cacheAuthorizationWith stamped cache.Authorization.ProfileServers from the resolver's wildcard-derived FULL profile membership, unintersected with the caller's own AllowedServers. CouldHaveProduced/coversAll then compares that stamped set on redemption, so a profile member entirely outside an agent token's own grant — a server it never had, and never will have, access to — entered the comparison: removing that hidden member later revoked the SAME token's cache access to its own, still-authorized server, turning the token's own cache hit/miss into an observable side-channel for an unrelated server's continued existence in the profile (SC-005-class disclosure through the cache layer; round 16's trace of a consumer round 15's refutation did not reach). Fix: a new resolveActiveProfileWithIndex seam returns the (index, snapshot) pair a (name, scope) pair was resolved against, so cacheAuthorizationWith can stamp an agent caller's ProfileServers via idx.EffectiveServersFor(profileName, ac.AllowedServers) — the same O(len(caller-grant)) helper handleSetProfile's own scoped-visible path already uses — instead of re-deriving a possibly different snapshot's index or walking the profile's declared size. Non-agent scoped callers (no AllowedServers of their own) keep the resolver's full-membership semantic; resolveActiveProfileIn/resolveActiveProfileFromIndex's own ProfileScope construction is untouched, per round 15's standing verdict. Red tests first: a reproduction of the reviewer's exact scenario (token grant {github}, profile {github,weather}, narrowed to {github} after caching — access must NOT be revoked) and a companion (the token's own grant server removed from the profile — access must still be revoked). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(scope): merge-driven collisions + cross-model review round 1 fixes Merge-driven fixes (Spec 107 PR-C, #1293, landed in main same day as this PR's own commits): - mintAgentToken (profile_integration_test.go) collided with an unrelated, same-named, server-tagged helper in mcp_auth_forced_test.go (Spec 107 PR-C). Renamed this PR's own helper to mintProfileAgentToken — only used within its own file, no functional change. - mcp_session_never_reaches_test.go (Spec 107 PR-C, server-tagged) called the pre-round-17 3-arg cacheAuthorizationWith signature; updated both call sites to the 4-arg (ctx, profileName, scope, idx) signature this PR's round 17 fix introduced. Cross-model review round 1 (codex gpt-5.6-sol) findings, verified and fixed: - cache_authz.go: round 17's caller-intersected ProfileServers stamp only special-cased AuthTypeAgent. Spec 107 PR-C's IdP-group grants give a plain OAuth AuthTypeUser its own restricted AllowedServers via the same CanAccessServer rule (nil/empty = deny-all), so a scoped server-edition user reopened round 17's exact cache side-channel (SC-005-class: removing a profile member outside a caller's own grant could revoke the caller's still-authorized cached access). Widened the intersection to every caller-bounded type (isAgent -> callerBounded). - profile_tool.go effectiveServersForCandidate: the restricted-grant branch walked the profile's own declared list (O(profile size)) to reproduce "profile-declared order, duplicates kept", contradicting its own documented O(len(allowed)) invariant and reopening the exact SC-005 timing-disclosure class rounds 14-17 closed for every other admitted-read path. Fixed via a new declaredOccurrences precomputed index (server name -> ordered declared positions per profile, built once per snapshot alongside members/serverPos), so a restricted grant now costs O(len(allowed)) instead of O(profile size). - handleSetProfile: SetActiveProfile (session write) and the later effective-scope render (session read, via resolveActiveProfileFromIndex's tier 3) were not atomic, so a concurrent set_profile on the SAME session could make one call's response report ITS OWN slug in active_profile with a DIFFERENT call's servers snapshot in the servers field, an FR-003 consistency violation under concurrency. Added resolveEffectiveProfileForJustSetSlug, which resolves tier 3 from the slug this call itself just wrote instead of re-reading the session store, closing the race for this call site only. - mcp_read_cache_authz_test.go: TestReadCache_..._OwnGrantMemberRemovalStillRevokes asserted the administrator-only "not readable with this credential" wording on a scoped (pinned agent) reader; readCacheRefusal's own documented non-disclosing contract remaps that case to the uniform "cache key not found" body for every non-administrator caller. Fixed the assertion; this was a pre-existing test bug, reproduced identically before this round's other changes, not a regression from them. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(scope): dedupe caller grant before expanding declaredOccurrences Cross-model review round 2 finding: the round-1 fix for effectiveServersForCandidate's restricted-grant timing oracle (declaredOccurrences) multiplied a name's occurrences by BOTH the number of times it appears in the profile's own declared list AND the number of times it appears in the caller's own (unvalidated, possibly repeating) AllowedServers — e.g. declared [A,B,A] + grant [A,A] produced [A,A,A,A] instead of [A,A]. The prior grant-map-based walk deduped `allowed` implicitly (Go map keys), so only declared's own duplicate count drove the output; this restores that exact contract via a dedupeSeen guard. Added TestProfileIndex_EffectiveServersForRestrictedGrant_DuplicatesFollowDeclaredOnly pinning both halves: declared duplicates are kept, grant duplicates are not multiplicative. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(scope): resolve only the profile name for set_profile's slug-race fix Cross-model review round 2 findings on the resolveEffectiveProfileForJustSetSlug fix (previous commit): - Its only caller discards the *ProfileScope return value, but profileScopeFromIndex always resolves the WILDCARD-derived full profile membership to build it — O(profile size) work paid for a value nothing used. Changed the function to return only the name, using idx.position's O(1) existence check for the pin/slug tiers instead of building a scope. - The stale-pin branch had dropped the operator warning log resolveActiveProfileFromIndex's own stale-pin branch emits, silently changing observability. Restored it. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent 96d8b97 commit 06cba37

20 files changed

Lines changed: 3805 additions & 267 deletions

‎ROADMAP.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -888,7 +888,7 @@ graph LR
888888
| Web UI + macOS app UX audit | In progress | P0 | — | | |
889889
| Release qualification gate (auto-QA matrix blocks the tag) | In progress | P0 | — | [081-release-qa-gate](./specs/081-release-qa-gate/) | |
890890
| Action log / transparency — info at a glance | In progress | P1 | — | | |
891-
| Agent-token scope hardening: every MCP request authorized by its own scope (spec 105) | In progress | P1 | 31/109 (28%) | [105-agent-scope-hardening](./specs/105-agent-scope-hardening/) | |
891+
| Agent-token scope hardening: every MCP request authorized by its own scope (spec 105) | In progress | P1 | 42/109 (39%) | [105-agent-scope-hardening](./specs/105-agent-scope-hardening/) | |
892892
| Token-efficiency benchmark: measured savings, published results | In progress | P1 | 62/64 (97%) | [103-token-bench](./specs/103-token-bench/) | |
893893
| Telemetry identity & data quality (machine_id + CI-filter hardening) | In progress | P1 | — | | |
894894
| Telemetry v7: honest funnel + churn instrumentation | In progress | P1 | — | [080-telemetry-v7-churn](./specs/080-telemetry-v7-churn/) | |
@@ -1034,6 +1034,6 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—`
10341034
| [102-schema-deferred](./specs/102-schema-deferred/) | `shipped` | 89/89 (100%) |
10351035
| [103-token-bench](./specs/103-token-bench/) | `shipped` | 62/64 (97%) |
10361036
| [104-auto-routing-mode](./specs/104-auto-routing-mode/) | — | — |
1037-
| [105-agent-scope-hardening](./specs/105-agent-scope-hardening/) | `in-flight` | 31/109 (28%) |
1037+
| [105-agent-scope-hardening](./specs/105-agent-scope-hardening/) | `in-flight` | 42/109 (39%) |
10381038
| [106-security-residual-fixes](./specs/106-security-residual-fixes/) | `shipped` | 18/19 (95%) |
10391039
| [107-server-edition-sso-hardening](./specs/107-server-edition-sso-hardening/) | `in-flight` | 102/126 (81%) |

‎docs/features/agent-tokens.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -534,8 +534,8 @@ mcpproxy token create \
534534

535535
Server-side enforcement (no client cooperation required):
536536

537-
- **`set_profile("other")` is rejected** — a pinned token cannot switch its session to a different profile (switching to its own pinned profile, or clearing, is allowed).
538-
- **`/mcp/p/<other>` returns `403`** — connecting to any profile URL other than the pinned one is forbidden; the pinned profile's own URL works.
537+
- **`set_profile("other")` is rejected** — a pinned token cannot switch its session to a different profile (switching to its own pinned profile while it still has reach, or clearing, is allowed; clearing reports `active_profile: ""` and the pin's servers).
538+
- **`/mcp/p/<other>` returns `404`** — connecting to any profile URL other than the pinned one is refused with the same non-disclosing `unknown profile` body every other non-selectable slug produces (see [404 responses](./profiles.md#404-responses)); the pinned profile's own URL works while the pin has reach.
539539
- **The pin is the highest-precedence resolver source**, above an explicit `/mcp/p/<slug>` URL scope and above a session `set_profile` selection.
540540
- **Every dispatch surface resolves it** — `retrieve_tools`, `describe_tool`, `call_tool_*`, the `code_execution` sandbox, direct-routing mode (`server__tool`) and [preflight](./tools-preflight.md) all bound themselves by the pin, so no routing mode is a way around it.
541541

@@ -548,7 +548,7 @@ Resolution precedence (highest wins):
548548
4. none (no profile filtering — all allowed servers)
549549
```
550550

551-
**Validation & config changes**: the pinned slug must name a configured profile at creation time (creation is rejected otherwise). If the profile is **later removed** from the configuration, the pin resolves to a **deny-all scope**: the token sees no upstream servers and no tools, on the MCP session path and in [preflight](./tools-preflight.md#disclosure-tiers) alike. The request is logged with a warning naming the removed profile, not hard-failed at the transport. The pin is a restriction the operator applied, so losing the profile it names must never hand the token a wider view than it had the day before — re-create the profile, or re-mint the token against a live one, to restore it. Pinning composes with server scoping and permission tiers: a request must satisfy **all** of them.
551+
**Validation & config changes**: the pinned slug must name a configured profile at creation time (creation is rejected otherwise). If the profile is **later removed** from the configuration, the pin resolves to a **deny-all scope**: the token sees no upstream servers and no tools, on the MCP session path and in [preflight](./tools-preflight.md#disclosure-tiers) alike. A pin with **zero reach** — the profile still exists but is empty, names only unconfigured servers, or no longer overlaps the token's `allowed_servers` — is treated exactly like a deleted one on `set_profile` and `/mcp/p/<pin>`, so the token cannot tell whether its own pin still exists. A request under a **deleted** pin is logged with a warning naming the removed profile, not hard-failed at the transport; a refused `/mcp/p/<pin>` initialization (deleted or zero-reach alike) is logged as `profile URL refused for scoped caller`. The pin is a restriction the operator applied, so losing the profile it names must never hand the token a wider view than it had the day before — re-create the profile, or re-mint the token against a live one, to restore it. Pinning composes with server scoping and permission tiers: a request must satisfy **all** of them.
552552

553553
The pin is shown by `token list` (PROFILE PIN column) and `token show` (Profile Pin field), and is preserved across `token regenerate`.
554554

‎docs/features/profiles.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,9 @@ The `set_profile` MCP tool switches the active profile **inside a live session**
6767

6868
- The selection is keyed by the MCP session id (stable per streamable-HTTP / SSE connection) and persists for the lifetime of that session.
6969
- It applies to subsequent `retrieve_tools`, `call_tool_*`, `code_execution` and direct-mode (`server__tool`) calls on the base `/mcp` endpoint — `retrieve_tools` searches the profile's per-profile index directly.
70-
- Passing an empty string (`""`) clears the selection and returns to all servers (the result lists every configured server). A token with a [`profile_pin`](./agent-tokens.md#profile-pinning) keeps its pin — the result then lists the pinned profile's servers, since that is what the session can still reach.
71-
- The `servers` list is always bounded by the caller's credential, using the same rule that scopes `retrieve_tools`: for an [agent token](./agent-tokens.md) scoped to specific servers it is the intersection of the selection (all servers, the chosen profile, or the pin) with the token's `allowed_servers`, so a token restricted to one server is never told about the others. API-key and socket callers see the full lists.
72-
- An unknown slug is rejected: `unknown profile '<slug>' (available: research, deploy)`. For an agent token the `available:` list names only the profiles that token may select — its pin, or the profiles overlapping its `allowed_servers` — not the whole catalogue, and a profile entirely outside the token's reach is rejected with that same error rather than confirmed as existing.
70+
- Passing an empty string (`""`) clears the selection and returns to all servers. `active_profile` always reports the **stored session selection** — `""` after a clear, even for a token with a [`profile_pin`](./agent-tokens.md#profile-pinning) — while `servers` reports the **effective scope** the session can actually reach after the update: the pin's servers for a pinned token (nothing once the pinned profile has been deleted), the URL profile on a `/mcp/p/<slug>` endpoint, otherwise the selection or every configured server.
71+
- The `servers` list is always bounded by the caller's credential, using the same rule that scopes `retrieve_tools`: for an [agent token](./agent-tokens.md) scoped to specific servers it is the intersection of the effective profile (resolved pin > URL > session, see [Resolution precedence](#resolution-precedence)) with the token's `allowed_servers`, so a token restricted to one server is never told about the others. On a `/mcp/p/<slug>` endpoint the URL still governs the request, so `set_profile("other")` there stores `other` as `active_profile` but reports `<slug> ∩ allowed_servers` in `servers`. API-key and socket callers see the full lists.
72+
- An unknown slug is rejected. An administrator (API key, socket, anonymous back-compat) gets the discovery affordance: `unknown profile '<slug>' (available: research, deploy)`. An agent token gets `unknown profile '<slug>'` with no list at all: it may select only the profiles overlapping its `allowed_servers` (or its pin while the pin still has reach), and a profile entirely outside its reach (an empty profile, a profile whose servers are all outside `allowed_servers`, or the token's own pin once it no longer exists or no longer overlaps the token's servers) is rejected with that same error rather than confirmed as existing. A pinned token asking for any profile OTHER than its pin (see [profile pinning](./agent-tokens.md#profile-pinning)) is rejected with that same `unknown profile '<slug>'` error too — never a distinct "pinned to..." message, which would let the token confirm from the wording alone that it is pinned, and to what, from a refusal aimed at a different slug. The check looks only at the requested slug (and the token's pin) and tests the token's own `allowed_servers` against that profile's precomputed server set — its cost does not depend on how many other profiles are configured, on how many servers the requested profile declares or on how many servers are configured at all, only on the size of the token's own grant — so a token cannot learn which profiles or servers exist, or whether it is pinned, from `set_profile`, by body or by timing.
7373
- Session state is cleared automatically on session close.
7474

7575
`set_profile` is available on the default `/mcp` server and the `call_tool` / `code_execution` routing-mode servers.
@@ -136,7 +136,11 @@ Profile changes take effect for new connections on the next config reload. In-fl
136136

137137
## 404 responses
138138

139+
For API-key, socket and (when `require_mcp_auth` is off) unauthenticated callers:
140+
139141
| Condition | Body |
140142
|-----------|------|
141143
| No profiles configured | `{"error":"no profiles configured"}` |
142144
| Unknown slug | `{"error":"unknown profile '<slug>'","available":["research","deploy"]}` |
145+
146+
An [agent token](./agent-tokens.md) may initialize through `/mcp/p/<slug>` only when that profile is one it could select with `set_profile` — its servers overlap the token's `allowed_servers`, or it is the token's pin and the pin still has reach. Every other request — a missing or deleted slug, a configured profile outside the token's reach, an empty profile, a pin mismatch, the slug-less `/mcp/p` and `/mcp/p/`, and an empty fleet — receives one and the same `404 {"error":"unknown profile '<slug>'"}` with no `available` list, and the check itself looks only at the requested slug (and the token's pin), testing the token's own `allowed_servers` against that profile's precomputed server set — its cost does not depend on how many other profiles are configured, on how many servers the requested profile declares, on how many servers are configured at all, or on whether this is the first request after a reload (the profile index is rebuilt when the configuration changes, not on demand); it scales only with the size of the token's own grant — so a scoped caller cannot learn which profiles or servers exist from the profile URL, by body or by timing. The refusal is silent towards the agent only: each one is logged (`profile URL refused for scoped caller`, with the token name, the requested slug and the remote address) so an operator can spot a token probing the slug space.

‎internal/runtime/configsvc/service.go‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package configsvc
33
import (
44
"context"
55
"fmt"
6+
"slices"
67
"sync"
78
"sync/atomic"
89
"time"
@@ -54,6 +55,13 @@ type Service struct {
5455
// #937 admission gate so a poisoned server can never be reconciled and
5556
// indexed in the window between "config parsed" and "config gated".
5657
prePublish atomic.Value // func(*config.Config) *config.Config
58+
59+
// prePublishObservers run after prePublish, on the exact *Config that is
60+
// about to be stored — while nothing else can observe it. Read-only: they
61+
// build state keyed on that pointer (Spec 105's profile index) so it is
62+
// ready before the first reader can capture the snapshot.
63+
observersMu sync.RWMutex
64+
prePublishObservers []func(*config.Config)
5765
}
5866

5967
// NewService creates a new configuration service with the given initial config.
@@ -106,6 +114,46 @@ func (s *Service) SetPrePublishHook(hook func(*config.Config) *config.Config) {
106114
s.prePublish.Store(hook)
107115
}
108116

117+
// AddPrePublishObserver registers a read-only observer of every configuration
118+
// on its way into the snapshot. Observers run inside the update, after the
119+
// pre-publish hook has produced the final config and before the snapshot is
120+
// stored or any subscriber is notified — so they see the exact *Config that
121+
// will be published, at a moment nothing else can. They must not mutate it,
122+
// and because they run under the update mutex they must be cheap (an index
123+
// build of one insertion per entry, not I/O). Distinct from the single
124+
// SetPrePublishHook slot, which the #937 admission gate owns.
125+
//
126+
// Observers run with the update mutex held and MUST NOT publish: a call to
127+
// Update, UpdateIfCurrent or ReloadFromFile from inside an observer is a
128+
// re-entrant publish and deadlocks by design, exactly like the pre-publish
129+
// hook. Registering a further observer from inside one is allowed — the
130+
// list is not locked while observers run — and that observer first runs on
131+
// the next publication.
132+
//
133+
// Nil observers and a nil service are ignored. Safe to call at any time,
134+
// including from an observer.
135+
func (s *Service) AddPrePublishObserver(observe func(*config.Config)) {
136+
if s == nil || observe == nil {
137+
return
138+
}
139+
s.observersMu.Lock()
140+
defer s.observersMu.Unlock()
141+
s.prePublishObservers = append(s.prePublishObservers, observe)
142+
}
143+
144+
// runPrePublishObservers runs every observer registered when it is called on
145+
// cfg (called with updateMu held, before the snapshot is stored). The list is
146+
// copied under the read lock and released before any observer runs, so an
147+
// observer may register another without deadlocking.
148+
func (s *Service) runPrePublishObservers(cfg *config.Config) {
149+
s.observersMu.RLock()
150+
observers := slices.Clone(s.prePublishObservers)
151+
s.observersMu.RUnlock()
152+
for _, observe := range observers {
153+
observe(cfg)
154+
}
155+
}
156+
109157
// runPrePublishHook applies the installed hook, if any.
110158
func (s *Service) runPrePublishHook(cfg *config.Config) *config.Config {
111159
v := s.prePublish.Load()
@@ -148,6 +196,7 @@ func (s *Service) UpdateIfCurrent(expected, newConfig *config.Config, updateType
148196
func (s *Service) updateLocked(newConfig *config.Config, updateType UpdateType, source string) {
149197

150198
newConfig = s.runPrePublishHook(newConfig)
199+
s.runPrePublishObservers(newConfig)
151200

152201
current := s.Current()
153202
s.version++

‎internal/runtime/configsvc/service_test.go‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,3 +399,110 @@ func TestService_Close(t *testing.T) {
399399
t.Error("Subscriber channel not closed after service close")
400400
}
401401
}
402+
403+
// TestService_PrePublishObserverSeesTheConfigBeforePublication pins the
404+
// contract AddPrePublishObserver offers a derived-index builder (Spec 105
405+
// PR D, the profile index): the observer runs on the exact *config.Config
406+
// about to be published — after the pre-publish hook has produced it —
407+
// while Current() still answers the previous snapshot and before any
408+
// subscriber has been notified. A builder keyed on that pointer therefore
409+
// has its index ready before a single reader can capture the snapshot.
410+
func TestService_PrePublishObserverSeesTheConfigBeforePublication(t *testing.T) {
411+
initial := &config.Config{Listen: "127.0.0.1:8080"}
412+
svc := NewService(initial, "/tmp/config.json", zap.NewNop())
413+
414+
// The #937 admission gate replaces the incoming config; the observer must
415+
// see the gated one, never the caller's.
416+
gated := &config.Config{Listen: "127.0.0.1:9090"}
417+
svc.SetPrePublishHook(func(*config.Config) *config.Config { return gated })
418+
419+
ctx, cancel := context.WithCancel(context.Background())
420+
defer cancel()
421+
updates := svc.Subscribe(ctx)
422+
<-updates // initial snapshot
423+
424+
type observation struct {
425+
seen, current *config.Config
426+
notified bool
427+
}
428+
observed := make(chan observation, 1)
429+
svc.AddPrePublishObserver(func(cfg *config.Config) {
430+
o := observation{seen: cfg, current: svc.Current().Config}
431+
select {
432+
case <-updates:
433+
o.notified = true
434+
default:
435+
}
436+
observed <- o
437+
})
438+
439+
require.NoError(t, svc.Update(&config.Config{Listen: "incoming"}, UpdateTypeModify, "test"))
440+
441+
select {
442+
case o := <-observed:
443+
require.Same(t, gated, o.seen, "the observer must see the config the gate hook produced")
444+
require.Same(t, initial, o.current, "the observer must run before Current() moves to the new snapshot")
445+
require.False(t, o.notified, "the observer must run before subscribers are notified")
446+
default:
447+
t.Fatal("the observer must run synchronously inside Update")
448+
}
449+
require.Same(t, gated, svc.Current().Config)
450+
select {
451+
case u := <-updates:
452+
require.Same(t, gated, u.Snapshot.Config)
453+
case <-time.After(time.Second):
454+
t.Fatal("subscribers must still be notified after the observer ran")
455+
}
456+
}
457+
458+
// TestService_PrePublishObserverNilSafe: a nil observer and a nil service
459+
// are both ignored, and every registered observer runs on every update.
460+
func TestService_PrePublishObserverNilSafe(t *testing.T) {
461+
var none *Service
462+
none.AddPrePublishObserver(func(*config.Config) {})
463+
464+
svc := NewService(&config.Config{Listen: "127.0.0.1:8080"}, "/tmp/config.json", zap.NewNop())
465+
svc.AddPrePublishObserver(nil)
466+
runs := 0
467+
svc.AddPrePublishObserver(func(*config.Config) { runs++ })
468+
svc.AddPrePublishObserver(func(*config.Config) { runs++ })
469+
470+
require.NoError(t, svc.Update(&config.Config{Listen: "a"}, UpdateTypeModify, "one"))
471+
require.NoError(t, svc.Update(&config.Config{Listen: "b"}, UpdateTypeModify, "two"))
472+
require.Equal(t, 4, runs, "each observer runs once per update; nil ones are skipped")
473+
}
474+
475+
// TestService_PrePublishObserverMayRegisterAnObserver (Spec 105 PR D codex
476+
// round 6, finding 2): observers run under the update mutex, so the observer
477+
// list must not be held locked while they run — an observer that registers a
478+
// follow-up observer deadlocked on observersMu. The list is copied under the
479+
// read lock and released before any observer is invoked; an observer added
480+
// during a publication first runs on the NEXT one.
481+
func TestService_PrePublishObserverMayRegisterAnObserver(t *testing.T) {
482+
svc := NewService(&config.Config{Listen: "127.0.0.1:8080"}, "/tmp/config.json", zap.NewNop())
483+
484+
var registered sync.Once
485+
innerRuns := 0
486+
svc.AddPrePublishObserver(func(*config.Config) {
487+
registered.Do(func() {
488+
svc.AddPrePublishObserver(func(*config.Config) { innerRuns++ })
489+
})
490+
})
491+
492+
update := func(listen string) {
493+
t.Helper()
494+
done := make(chan error, 1)
495+
go func() { done <- svc.Update(&config.Config{Listen: listen}, UpdateTypeModify, "test") }()
496+
select {
497+
case err := <-done:
498+
require.NoError(t, err)
499+
case <-time.After(5 * time.Second):
500+
t.Fatal("Update deadlocked: an observer registering another observer must not block publication")
501+
}
502+
}
503+
504+
update("one")
505+
require.Equal(t, 0, innerRuns, "an observer registered during a publication runs from the next one on")
506+
update("two")
507+
require.Equal(t, 1, innerRuns, "the observer registered by another observer must run on the next publication")
508+
}

0 commit comments

Comments
 (0)