Repository navigation
feat(profile): v3 policy fields + FR-009a rollout gate (Spec 108-a) - #1380
Merged
Merged
Conversation
…dependency Spec 108's internal/profile.IntrinsicTier adapts this one function to classify a tool's tier (research D30); 108-a merges after 109-a per plan.md, so this file is carried here verbatim until 109-a's own PR (#1378) lands, at which point the merge is a no-op on this file.
Extend config.ProfileConfig with the six v3 policy fields (max_tier, unannotated, tools, code_execution, management_tools, switchable_to) plus display-only title/description (FR-001), IsLegacy()/ EffectiveUnannotated() (FR-002/FR-003), and Config.AnonymousProfile (FR-008). ValidateProfiles (FR-007) gains the new fatal/warning rules of data-model.md §1 and is now also wired into the write-surface gate (ValidateDetailed), not only the boot path. FR-009a rollout gate: PolicyEnforcementReady stays false until 108-d lands the last execution gate, so no build between 108-a and 108-d can admit a v3 policy field it cannot yet enforce. Tests use SetPolicyEnforcementReadyForTest to exercise the fields early. FR-009 pinned by a reflection test over ProfileConfig's JSON tags: the profile object stays edition-neutral.
internal/profile.CompiledPolicy/Compile/Decide (FR-010): one pure
decision predicate over (server, tool, intrinsic tier) -> admitted /
excluded(reason), matching contracts/enforcement-matrix.md exactly
(deny beats allow, allow bypasses the tier cap, unannotated handling,
stale classification ignored for annotated tools). Fingerprint hashes
exactly the six FR-001 policy fields, stable regardless of slice/map
order.
IntrinsicTier adapts Spec 109-a's contracts.AnnotationTier exhaustively
(research D30) - the one tier mapping every surface shares; a T005a
grep guard keeps this package from reading DestructiveHint/ReadOnlyHint
itself.
internal/profile/glob.go: the FR-004 "server:tool" matcher ('*' only,
anchored, case-sensitive).
internal/profile/contract.go: the wire enums every surface (REST, CLI,
MCP, Web UI, macOS) shares (FR-032, FR-052), plus the T003 shared
golden contract fixtures under testdata/contract/.
…Annotations seam profileIndex now compiles one profile.CompiledPolicy per profile alongside its existing server-reach bitset, taken with the snapshot as one immutable pair (Spec 105 D17 pattern) - PolicyFor/PolicyAt mirror lookup/profileAt. A legacy profile compiles cheaply (no allow/deny/ classify to build), the "fast path" a legacy snapshot takes. EffectiveAnnotations (mcp_visibility.go) is the T013 seam every enforcement path will read a tool's effective annotations through - a thin wrapper over resolveExactToolIdentity, the same identity seam every dispatch path already uses, so discovery and execution can never classify a tool from two different sources. Also the documented hook for per-server annotation_overrides (#1323). profiles_v3_fixture_test.go / profile_index_policy_test.go: the shared Spec 108 test fixture (three fake upstreams + the enforcement-matrix profiles) and its first consumer, pinning that the compiled policy resolves identically over a raw config and a live proxy+runtime.
cmd/generate-types now emits the internal/profile/contract.go enums (unannotated policy, decision reasons, resolution sources, block reasons, explain steps, fix actions, credential states, surfaces, warning codes) so the frontend and every future 108 UI component reference the same wire spellings the backend defines (FR-001, FR-032). Regenerated frontend/src/types/contracts.ts.
…s boot error zcode review round 1 (108-a): the write-surface hook landed inside validateDetailedCore, which Validate() (the boot path) also runs before calling ValidateProfiles a second time itself to capture warnings. That made a fatal profile error surface on boot as "profiles: profiles[0]: ..." (ValidationError-wrapped) instead of the validator's own exact text - a behavior change for every pre-existing Spec 057 profile error, not only the new v3 ones - and ran the validator twice on every boot/reload. Move the hook into ValidateDetailed itself, which validateDetailedCore does not participate in on the boot path, so each door runs ValidateProfiles exactly once and the boot path's raw error text is unchanged.
…sensitivity, dedup
zcode review round 2 (108-a, chunk 2: policy.go/glob.go/contract.go +
profileIndex/EffectiveAnnotations):
- config.ValidateProfiles now rejects a '*' in a tools.classify KEY:
classify is an exact server:tool identity (data-model.md's own
ProfileToolRules.Classify comment), and Decide looks it up by exact
map key, so a glob there could never match anything and would fail
silently. profile.Compile re-guards the same rule and also drops an
invalid (non-empty, unrecognised) classify tier value instead of
storing TierUnannotated for it, rather than trusting a not-yet-
validated caller (a future profile-editor "Try it" preview).
- CompiledPolicy.Fingerprint now includes an explicit ToolsSet flag: an
absent `tools` object and a present-but-empty `{}` one compile to the
same enforcement (no rules either way) but ProfileConfig.IsLegacy()
disagrees about them (Tools != nil is non-legacy regardless of
contents) - which flips retrieve_tools' hidden_by_profile presence
(FR-011). The fingerprint must track that flip too so FR-027's
snapshot-diff edit detection can't miss it.
- IntrinsicTier's contracts.Tier adapter is now a named helper
(tierFromContractsTier) IntrinsicTier itself calls, so the T005a
out-of-range test exercises the real mapping instead of a hand-copied
mirror that could drift from it silently.
- EffectiveAnnotations delegates to the pre-existing
lookupExactToolAnnotations instead of reimplementing its body, and
its doc no longer overstates what `found` certifies (annotation
CURRENCY is dispatch's certified()/epoch-pinning job, not this seam's).
- profileIndex.PolicyAt now mirrors profileAt's exact bounds guard
(live cfg.Profiles length, not just the constructed policies slice),
closing a theoretical stale-policy read for a directly-passed
candidate outside PolicyFor's position() seam.
- Corrected the T003 effective_tools.json/profile_full.json goldens: the
fixture had classification_stale backwards (an unannotated tool with
an APPLIED classify entry was marked stale; nothing demonstrated a
genuinely stale one). profile_full.json now also classifies the
already-annotated github:list_issues, which is the real stale case.
One reviewer claim rejected after verification: the review asserted an
"FR-003a EffectiveCodeExecution" deliverable was missing from this PR;
no such requirement or field exists anywhere in spec.md/data-model.md/
tasks.md (grepped the spec branch) - not applied.
…e_execution default
High: ValidateProfiles' FR-009a rollout gate never checked
Config.AnonymousProfile, contradicting data-model.md §1's second gated
row ("non-empty anonymous_profile while the gate is closed -> fatal").
profiles_rollout_gate_test.go's "anonymous_profile still loads" subtest
pinned the wrong, permissive behavior. Fixed: ValidateProfiles now
rejects any non-empty AnonymousProfile while PolicyEnforcementReady()
is false, regardless of whether the name is known, unknown, or the
config has zero profiles. The pinned test now asserts the fatal error
instead, plus new cases for the unknown-name and zero-profiles variants.
Medium: the FR-009a test-only override had no protection against being
invoked from non-test code (tasks.md T009: const gate + atomic.Bool
override + EnablePolicyForTest(tb testing.TB) panicking unless
testing.Testing()). Fixed within the actual package layout:
PolicyEnforcementReady is now a function backed by an unexported const
base (never independently assignable, unlike the old exported var) plus
an unexported atomic.Bool test override; EnablePolicyForTest(tb
testing.TB) panics when called outside a test binary and registers its
own tb.Cleanup, replacing SetPolicyEnforcementReadyForTest at every call
site. Added TestEnablePolicyForTest_PanicsOutsideATestBinary, which
`go build`s internal/config/testdata/overrideprobe (a plain `main`
package calling EnablePolicyForTest(nil)) and asserts the resulting
binary panics and exits non-zero, proving the override is unreachable
outside a test binary.
Deviation from the literal T009 design, with reason: the gate stays in
package config, not internal/profile, because internal/profile already
imports internal/config (for ToolAnnotations) - config importing profile
back to reach a profile.policyGateOpen() would cycle. This constraint
predates this change (already documented on PolicyEnforcementReady) and
is architectural, not a shortcut. The fix satisfies the review's actual
concern - no non-test call site can open the gate - without the
AST-parsing test that assumed a rollout_gate.go file in package profile,
since that split isn't achievable here.
Medium: CompiledPolicy.CodeExecution carried the raw
ProfileConfig.CodeExecution *bool through Compile unchanged instead of
the fail-closed default data-model.md §1/§2 (FR-003a) requires: unset ->
false under a read/write max_tier, true (global gate decides) under
destructive/legacy. Added ProfileConfig.EffectiveCodeExecution()
implementing that matrix, wired it into Compile (CompiledPolicy.CodeExecution
is now a plain bool holding the effective value, not *bool), and added
the required default-matrix coverage in both
internal/config/profiles_v3_test.go and internal/profile/policy_test.go.
All three findings verified against the code and fixed; none rejected.
Local verification: go build ./...; go vet ./internal/config/...
./internal/profile/...; go test -race ./internal/config/...
./internal/profile/... (pass); go test -race -tags server -timeout 20m
-skip "E2E|Binary|MCPProtocol|TestInfoEndpoint|TestGracefulShutdownNoPanic|TestSocketInfoEndpoint"
./internal/serveredition/... ./internal/config/... ./internal/oauth/...
./internal/server/... ./internal/httpapi/... ./internal/storage/... (all
pass, internal/server 519s); golangci-lint v2 (.github/.golangci.yml)
bare and --build-tags server, both clean of any issue in a file this
change touches (pre-existing, unrelated issues remain in
zero_value_preservation_test.go, diagnostics_fixers_test.go,
e2e_config_auto_refresh_test.go, socket_e2e_test.go,
serveredition/auth/oidc_jwks*.go). No frontend, native macOS, REST
contract or built-in-tool-schema change, so no swagger/contracts.ts
regen or goldens update needed.
T004a (FR-009a rollout gate) listed three "override cannot ship" artifacts. Round 2 added only the go-build override-panic probe (TestEnablePolicyForTest_PanicsOutsideATestBinary). The AST-check item stays deviated per round 1's commit message (package config vs internal/profile import-cycle constraint - unchanged, legitimate). This round adds the third, still-missing artifact: a binary-level check. TestServeRejectsV3PolicyFieldsAtStartup builds the real ./cmd/mcpproxy binary and runs `serve` against a scratch --data-dir/--config (high port, scratch HOME) with a v3 policy field (max_tier) and then a bare anonymous_profile, asserting exit code 4 and the exact data-model.md section 1 refusal text on stderr, with a handful of plausible-looking MCPPROXY_* env vars set to arbitrary values to demonstrate no runtime input opens the gate. Verified by flipping policyEnforcementReadyBase to true locally: the probe binary then starts a full server instead of exiting 4, proving the test is not vacuous. Findings disposition: - T004a item 3 (binary-level exit-code-4 check missing): CONFIRMED, fixed.
anonymous_profile, max_tier, unannotated, code_execution, management_tools, switchable_to and tools (allow/deny/classify) were added to config.ProfileConfig/config.Config in this branch but the committed oas/swagger.yaml and oas/docs.go were never regenerated, so make swagger-verify (the pre-push hook) failed.
Deploying mcpproxy-docs with
|
| Latest commit: |
c94aa74
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://32946886.mcpproxy-docs.pages.dev |
| Branch Preview URL: | https://108-a-profile-policy-model.mcpproxy-docs.pages.dev |
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
TestServeRejectsV3PolicyFieldsAtStartup and
TestEnablePolicyForTest_PanicsOutsideATestBinary go-build a helper
binary into a bare TempDir path and exec it directly. go build -o
<path-without-extension> on Windows does not append .exe, and Go's
os/exec refuses to run an absolute path lacking a recognized
executable extension ("executable file not found in %PATH%"), so
both subtests of the first test failed on windows-latest CI. Append
.exe to the binary path on GOOS=windows before building/running it.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Contributor
📦 Build ArtifactsWorkflow Run: View Run Available Artifacts
How to DownloadOption 1: GitHub Web UI (easiest)
Option 2: GitHub CLI gh run download 36244283721 --repo smart-mcp-proxy/mcpproxy-go
|
…model # Conflicts: # internal/contracts/tier.go # oas/docs.go
Six findings from the latest zcode round, all confirmed and fixed
test-first (no false positives to reject):
- T004a item (1), high: the go/ast structural test proving the FR-009a
rollout gate cannot be opened by any runtime input was still missing
(only the go-build panic probe and the binary serve exit-code-4 probe
had landed on a prior round). Adds
internal/config/rollout_gate_ast_test.go: parses profiles.go's AST and
asserts PolicyEnforcementReady reads only policyEnforcementReadyBase /
policyEnforcementTestOverride / testing.Testing(), that the base flag
is a const, that the file carries no //go:build line, and that
EnablePolicyForTest/policyEnforcementTestOverride are referenced from
no production file other than profiles.go and the dedicated override
probe. Verified against injected regressions (os.Getenv branch, a var
instead of const, a leaking reference) before confirming it green.
- Title/description length limits were counted with len() (bytes), not
runes, so a 45-character Cyrillic title (90 UTF-8 bytes) was rejected
under the 80-*character* limit. Switched to
utf8.RuneCountInString and added rune-vs-byte regression tests.
- TestValidateProfiles_WiredIntoBothDoors's "valid config passes both
doors" subtest asserted on a fresh DefaultConfig() instead of the cfg
built two lines above, making it vacuous for a non-empty Profiles
slice. Fixed to assert on cfg.ValidateDetailed().
- internal/profile/contract_test.go's "stable across allow/deny slice
order" fingerprint test only reordered Allow; Deny had a single
element with no non-trivial reorder. Split into separate allow/deny
subtests with a two-element Deny fixture; verified the new subtest
fails when fingerprintOf stops sorting Deny.
- No test exercised PATCH /config or POST /config/apply with a v3
policy field or anonymous_profile while the FR-009a gate is closed.
Adds internal/httpapi/config_profile_v3_rollout_gate_test.go: a fake
controller whose ApplyConfig runs the real config.ValidateDetailed
(mirroring internal/runtime.Runtime.applyConfigLocked's first step),
proving both REST write doors reject v3 fields/anonymous_profile with
the exact FR-009a text and never call through to persistence, with a
legacy-profile control on each door.
- The enforcement-matrix fixture tool files for
preflight_fixture_server.js (internal/server/testdata/profiles_v3/
{github,notion,filesystem}.tools.json), required by quickstart.md's
108-a live-QA recipe, did not exist. Added them (descriptions equal
tool names per the matrix's BM25-determinism note, annotations per
contracts/enforcement-matrix.md) plus
internal/server/profiles_v3_node_fixture_test.go, which parses and
pins their shape against the matrix table so a hand-edit cannot drift
the live fixture away from the Go-side one; smoke-tested against the
real preflight_fixture_server.js over stdio.
Verified: go build (default and -tags server), go vet, golangci-lint
--config .github/.golangci.yml (bare and --build-tags server, no new
findings), go test -race on internal/config, internal/profile,
internal/httpapi, internal/storage, internal/server,
internal/serveredition/... (default and -tags server with the CI skip
regex) — all green. No frontend/REST-contract/macOS changes in this
diff, so those gates are unaffected.
7 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Spec 108 (Profiles v3) foundation PR —
108-aof thea → (b ∥ c) → d → e → f → (g ∥ h ∥ i ∥ k) → j → lmerge order (spec:specs/108-profiles-v3/, tasks Phase 2T001-T015, FR-001–FR-009, FR-009a, FR-052; spec docs are in the not-yet-merged #1379).This PR parses and validates the new v3 profile-policy fields and adds one pure decision predicate. Nothing is enforced yet — the FR-009a rollout gate keeps every v3 field (and
anonymous_profile) rejected at config load outside test binaries, so no release can ship an unenforced policy while the profile is mid-rollout across 108-a…108-l.108-b/108-cwire the predicate into discovery/dispatch and credentials.User-visible changes per surface
ProfileConfiggainstitle,description,max_tier,unannotated,tools(allow/deny/classify),code_execution,management_tools,switchable_to;Configgainsanonymous_profile. A legacy profile ({name, servers}only) round-trips byte-identically —IsLegacy()stays true until any one of the six policy fields is set.mcpproxy serve/PATCH /config/POST /config/apply: until 108-d ships enforcement, setting any of the six v3 policy fields, or a non-emptyanonymous_profile, is a fatal validation error (exit code 4) with the exact message fromdata-model.md§1 — this is intentional (FR-009a), not a regression; it prevents an operator from configuring a policy that nothing enforces yet.oas/swagger.yamlandoas/docs.gonow document the newProfileConfig/Configfields (config.ProfileToolRulesschema added). No endpoint behavior changes in this PR.frontend/src/types/contracts.tsgains the Spec 108 enums (tiers, decision reasons, resolution sources, block reasons, explain steps, fix actions, credential states, surfaces, warning codes) viacmd/generate-types, so 108-d onward's UI work references the same wire spellings the backend defines; nothing consumes them yet.internal/profilepackage (policy.go,glob.go,contract.go) compiles a profile's v3 fields into aCompiledPolicyand evaluates it viaDecide, but it is only reachable through the test-only override (profile.EnablePolicyForTest) until later PRs wire it into request paths.profileIndex(ininternal/server/profile_tool.go) compiles policies alongside the existing profile snapshot and exposes anEffectiveAnnotationsseam (internal/server/mcp_visibility.go) as the single source of tool-tier annotations for all future enforcement, discovery and the explainer.Findings fixed (zcode review, rounds 1–2)
anonymous_profilegate:ValidateProfiles' FR-009a check didn't reject a non-emptyConfig.AnonymousProfilewhile the gate is closed, contradictingdata-model.md§1. Fixed — now fatal regardless of whether the name is known/unknown/profiles are empty.PolicyEnforcementReadywas an exported, independently-assignable var. Replaced with an unexported const base +atomic.Booloverride behindEnablePolicyForTest(tb testing.TB), which panics outside a test binary; added ago build-based probe (internal/config/testdata/overrideprobe) proving the override is unreachable from production code, plus a binary-level check that runs the realmcpproxy serveagainst a scratch instance and asserts exit code 4 + exact refusal text for both a v3 field and a bareanonymous_profile.EffectiveCodeExecutionfail-open default:CompiledPolicy.CodeExecutioncarried the raw*boolthrough unchanged instead of the FR-003a default matrix (off underread/writemax_tier, global-gate-decides underdestructive/legacy). AddedProfileConfig.EffectiveCodeExecution()implementing the matrix;CompiledPolicy.CodeExecutionis now the effectivebool, not the raw pointer.tools.classifyglob-in-key:classifyis an exactserver:toolidentity map, but nothing rejected a*in a key, which would silently never match.ValidateProfilesandCompilenow both guard it (defense in depth); an invalid, unrecognised classify value is dropped rather than trusted.tools: {}vs absent: both compile to the same enforcement butIsLegacy()treats a present-but-emptytoolsobject as non-legacy (flipshidden_by_profilepresence, FR-011).CompiledPolicy.Fingerprintnow carries an explicitToolsSetflag so FR-027's snapshot-diff edit detection can't miss the flip.IntrinsicTier'scontracts.Tiermapping was hand-copied instead of calling one named helper, so a test could exercise a mirror that drifts from the real mapping. ExtractedtierFromContractsTier.ValidateProfiles/ re-wrapped boot error: the v3 hook landed invalidateDetailedCore, which the boot path (Validate()) also calls internally before invokingValidateProfilesagain — running the validator twice per boot/reload and wrapping the boot path's raw error text as"profiles: profiles[0]: ...", changing behavior for every pre-existing Spec 057 profile error. Moved the hook intoValidateDetaileditself, whichvalidateDetailedCoredoesn't participate in on the boot path.make swagger-verify(the pre-push hook) failed because the newProfileConfig/Configfields above were never reflected in the committedoas/swagger.yaml/oas/docs.go. Regenerated and committed both.Tests added
internal/config/profiles_v3_test.go— legacy round-trip byte-identity, per-field parsing/validation messages,IsLegacy()semantics, FR-009 reflection guard (JSON tag set is exactly the FR-001 fields, default +-tags server),switchable_tonil-vs-empty-list round trip through the real config save path.internal/config/profiles_rollout_gate_test.go— FR-009a fatal-gate matrix (six policy fields +anonymous_profile) through config load,PATCH /config,POST /config/apply; includesTestEnablePolicyForTest_PanicsOutsideATestBinary(buildsinternal/config/testdata/overrideprobeas a plain binary) andTestServeRejectsV3PolicyFieldsAtStartup(builds and runs the realmcpproxybinary against a scratch instance, asserts exit code 4).internal/profile/policy_test.go— enforcement-matrix table (allow/deny/classify precedence, deny-beats-allow, unknown-server warning, stale classification ignored,IntrinsicTier/EffectiveUnannotated/EffectiveCodeExecutiondefaults).internal/profile/intrinsic_tier_contract_test.go— one tier mapping shared with Spec 109-a'scontracts.AnnotationTierverified across every annotation-hint combination, including out-of-range fail-closed behavior; grep guard against a second, drifting annotation-reading path.internal/profile/glob_test.go,internal/profile/contract_test.go— glob matcher (anchored, case-sensitive,server:toolidentity incl./and__) and enum encode/decode + fingerprint stability.internal/server/profile_index_policy_test.go—profileIndex.PolicyFor/PolicyAtresolve correctly (by name, by position, legacy fast path, unknown profile), including over the live fixture with real upstreams, and a compiled-policy/snapshot pair taken together is immune to a later edit on a second index.internal/server/profiles_v3_fixture_test.go— shared three-upstream/three-profile fixture +anonCtx()helper for downstream PRs.How this was verified live
Ran the full config/profile/contracts unit suites and the profile-tagged subset of
internal/server(go test -race) on this branch againstorigin/mainHEAD; all passed except one pre-existing, unrelated flake (TestProfile_UpstreamServersListFiltered, a legacy-SSE-transport timing test untouched by this diff — confirmed to pass reliably in isolation, and confirmed viagit diffthat this PR does not touch that test file). Built both editions (go build ./...andgo build -tags server) clean. Rangolangci-lint(.github/.golangci.yml) bare and with--build-tags serverover every changed package — zero issues in any file this PR touches (all flagged issues are pre-existing, in files this PR does not modify). Regeneratedfrontend/src/types/contracts.tsviacmd/generate-typesand diffed it byte-for-byte against the committed file (identical) to confirm the generator output matches what's checked in. Ranmake swagger-verify; it failed on the pre-existing state (new config fields undocumented), somake swaggerwas run and the regeneratedoas/swagger.yaml/oas/docs.gocommitted, after whichswagger-verifypassed. No live macOS/CLI/Web-UI walkthrough was needed for this PR — it adds no enforcement and no reachable surface change (the FR-009a gate keeps the new fields rejected outside test binaries), so there is nothing yet for those surfaces to exercise; that verification lands with 108-b/108-c/108-d.