Repository navigation
feat(auth,server): client-credential token model and dispatch gating (Spec 108-c) - #1389
Merged
Merged
Conversation
… (Spec 108-c) Adds the Spec 108 client-credential primitives: AgentToken.Kind/ClientID/ ProfileMode/PendingHash/PendingPrefix/RotationStartedAt, the mcp_cli_ secret prefix and generator, AuthContext.TokenKind/ClientID/ProfileMode, and the FR-021 fail-closed invariant check (ValidateTokenInvariants), wired into storage.ValidateAgentToken so every authentication - not only mint - refuses a malformed record with the exact "malformed credential record" text. Storage gains MintClientCredential (replaces a revoked/expired kind=client record for the same client id in one transaction, refuses to touch a grandfathered kind=agent token, refuses to replace an active credential), staged rotation (StageClientCredentialRotation / FinalizeClientCredentialRotation / RollbackClientCredentialRotation, both secrets valid during the overlap, finalize idempotent) and ForgetClientCredential. Tasks: T027, T027a (pure half), T028, T028a (storage half; the runtime crash-injection reconciler is a follow-up), T034 (token/context fields).
…EST gate (Spec 108-c) MCP auth middleware (internal/server/server.go) now recognises the mcp_cli_ prefix and dispatches client credentials through the same storage.ValidateAgentToken door as regular agent tokens, so the FR-021 invariant check applies uniformly. REST (internal/httpapi/server.go) refuses every client credential with 403 "client credentials are valid on MCP endpoints only" (FR-023), recognised by the mcp_cli_ prefix before any store lookup and, in defence of depth, by kind=client after it - covering every carrier (X-API-Key, Authorization: Bearer, ?apikey=) and every route family including /events. Adds internal/server/profile_resolver_v3.go: ProfileResolution (data-model.md S4) and the FR-020 precedence (pin > url > session > binding > anonymous > none) with FR-022 switchable_to admission, as a new, independently tested resolver (T029/T036's resolution half). It is additive: wiring it into the live per-request enforcement path (retrieve_tools, set_profile admission, call_tool_*) is 108-d's FR-009a-gated execution cutover, per tasks.md's own PR boundary, and is not done here. Also: storage.CreateAgentToken refuses a new regular token named "client-<id>" (FR-021, grandfathered pre-108 records are unaffected); SessionInfo gains TokenName/ClientID/Profile/ProfileSource plus SessionsForToken (T039, session/server-instance map deferred); a confirming test that a client credential's AuthContext is non-admin under AuthorizeServerOp (T037a). Tasks: T027 (round-trip), T027b, T028 (regular-token client- prefix guard), T030, T034, T037, T037a. T029/T033/T036 partially addressed (resolver-level tests only; see PR description for what remains for 108-c/108-d).
Contributor
📦 Build ArtifactsWorkflow Run: View Run Available Artifacts
How to DownloadOption 1: GitHub Web UI (easiest)
Option 2: GitHub CLI gh run download 36258257562 --repo smart-mcp-proxy/mcpproxy-go
|
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
F1 (medium): POST /api/v1/tokens/{name}/regenerate resolved a client-<id>
record with no Kind filter and would overwrite its secret with a fresh
mcp_agt_ token while leaving Kind="client" untouched, permanently bricking
the credential (ValidateTokenInvariants then fails closed on every future
authentication, and MintClientCredential refuses to replace a non-revoked,
non-expired record, so there is no self-heal).
storage.RegenerateAgentTokenForOwner now refuses a kind=client record with a
new ErrClientCredentialRegenerateRefused sentinel, checked before the
Revoked branch; the REST handler translates it into an actionable 409.
Covered by storage and httpapi tests reproducing the exact bricking
trigger, confirmed to fail without the guard.
F2 (medium): the FR-023 defence-in-depth check in handleAgentTokenAuth
("refuse a client credential by Kind after the store lookup") had zero
test coverage, because every existing REST test presents an
mcp_cli_-prefixed secret, which the earlier prefix gate intercepts before
the store is ever consulted. Added
TestAPIKeyAuth_KindClientRecordViaAgentPrefix_Rejected, which presents an
mcp_agt_-shaped secret whose mocked store lookup still resolves to a
kind=client record, isolating and pinning that second, independent guard.
No production change was needed; confirmed the new test fails if the
branch is removed.
F3 (medium): FR-021's "expiry <= 365 days (default 365)" invariant was not
enforced anywhere for kind=client records. auth.ValidateTokenInvariants now
rejects a zero, past, or >365-day expiry (measured from CreatedAt) on every
authentication, not only at mint time; storage.MintClientCredential rejects
an out-of-bounds expiresAt at mint time so a caller gets an immediate,
actionable error instead of a credential that fails closed on first use.
Covered by new invariant-table rows and
TestMintClientCredential_RejectsExpiryOutOfBounds (the finding's exact
trigger: ten years out, zero-value, already-past).
F4 (medium): profile_resolver_v3_test.go never drove a URL or session scope
through ResolveProfileV3, leaving FR-020's url>session precedence, the
admission-refused fall-through, stale-selection clearing, and "a locked
credential may never switch" all uncovered — deleting the url/session
tiers left the suite green. Added TestResolveProfileV3_URLTier and
TestResolveProfileV3_SessionTier; confirmed both fail when the tiers are
removed. No production change was needed.
All four findings verified as genuine; none rejected as false positives.
Verified locally: go build ./...; go vet ./...; go test -race on
internal/auth, internal/storage, internal/httpapi (with the CI -skip
regex) and internal/server (with the CI -skip regex); golangci-lint v2
against .github/.golangci.yml, bare and --build-tags server, across the
full repo (no new findings in touched files, only pre-existing canaries).
Deploying mcpproxy-docs with
|
| Latest commit: |
28bf7b2
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://e1a61fc4.mcpproxy-docs.pages.dev |
| Branch Preview URL: | https://108-c-client-credentials.mcpproxy-docs.pages.dev |
4 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
Foundational backend slice of Spec 108-c (per-client credentials and profile binding), scoped down from the full PR to what could be implemented and verified with confidence in this session. It lands the security-critical, fail-closed core: the client-credential token model, storage-layer minting and staged rotation, dispatch gating (MCP accepts it, REST refuses it), and a new, independently tested profile-resolution engine for the pin/binding/anonymous tiers.
This PR is a partial implementation of 108-c. The pieces that need the largest, most delicate changes to mature, heavily-optimized files —
internal/connect/connect.go(CredentialMinter wiring so connect stops writing the admin API key),internal/runtime/clients_service.goandinternal/runtime/binding_guard.go(the FR-008a binding guard andPUT /clients/{id}/binding), the CLIconnect_cmd.goflags, and the Web UI / macOS surfaces — are not included. Attempting all of them in one pass risked shipping under-tested changes to security-sensitive, subtly-raced code (staged rotation with crash recovery, JSON/TOML config writers with comment-guard and precondition-token races) rather than a smaller, well-verified increment. See "What's not in this PR" below.What's implemented (tested)
internal/auth):AgentToken.Kind/ClientID/ProfileMode/PendingHash/PendingPrefix/RotationStartedAt, themcp_cli_secret prefix + generator,AuthContext.TokenKind/ClientID/ProfileMode.ValidateTokenInvariantsis the one fail-closed FR-021 check, run at mint time and — viastorage.ValidateAgentToken— on every authentication, returning the exactmalformed credential recordtext on any violation (missing/unknown kind, mismatched secret-vs-record kind, bad client_id, name mismatch, non-wildcardallowed_servers, incomplete permissions, locked-without-pin, client-only fields set on a regular token).internal/storage/client_credentials.go):MintClientCredential(replaces a revoked/expiredkind=clientrecord for the same client id in one transaction; refuses to touch a grandfatheredkind=agenttoken withErrClientCredentialConflict; refuses to mint over an active credential withErrClientCredentialActive), staged rotation (StageClientCredentialRotation/FinalizeClientCredentialRotation— idempotent — /RollbackClientCredentialRotation, both secrets valid during the overlap via a pending-hash index),ForgetClientCredential.CreateAgentTokennow refuses a new regular token namedclient-<id>(FR-021); a grandfathered pre-108 record is unaffected.internal/server/server.go) recognisesmcp_cli_and validates it through the same door asmcp_agt_. REST (internal/httpapi/server.go) refuses every client credential with403 {"error":"client credentials are valid on MCP endpoints only"}(FR-023) — recognised by prefix before any store lookup, and bykindafter it as defence in depth — across every carrier (header, bearer,?apikey=) and route family, including/events.internal/server/profile_resolver_v3.go, new):ProfileResolution(data-model.md §4) and the FR-020 precedencepin > url > session > binding > anonymous > none, with FR-022switchable_toadmission (checked against the caller's own bound base, so a two-hop A→B→C chain cannot escalate past what A itself allows) and FR-020's dangling-base-never-falls-through rule for pin/binding/anonymous. Independently tested (precedence table, switchable_to admission table, anonymous confinement under the FR-009a test override, dangling-base deny-all).SessionInfogainsTokenName/ClientID/Profile/ProfileSource+SessionStore.SessionsForToken(the FR-026/FR-027 notification fan-out seam).kind=clientAuthContextis non-admin underAuthorizeServerOp(falls out ofAgentToken.AuthContext()always settingType=AuthTypeAgent, so no code change was needed there — this locks it in).What's not in this PR (left for a follow-up)
internal/connect: theCredentialMinterwiring so connect mints a client credential instead of writing the admin API key,--keyless,credential_stateonClientStatus, thePOST /connect/{client}body fields, and the admin-only gate on the three connect reads (T031/T038/T030a/T030b).connect.go's credential resolution (entryParams) is a single choke point but is called from 7 sites acrossconnect.go/preview.go/undo.go/token.go, each with its own race/precondition-token subtleties documented in-file; wiring a per-call profile/mode through it correctly needs its own focused pass with the existing 12-file connect test suite run end-to-end.internal/runtime:binding_guard.go(BindingBypassable/BindingGuardActive/BindingGuardDelta) andclients_service.go(assign/lock/unlock/rotate/forget/list,client.binding_changed,profile_changerecords) plus the newPUT /clients/{id}/bindingroute (T032/T033a/T040/T040a).connect_cmd.go--profile/--lock/--switchable/--keylessflags (T041).ConnectClientView.swiftchanges (T042).profileIndex.selectable(internal/server/profile_tool.go) is not modified —ResolveProfileV3is additive and not yet wired into the liveretrieve_tools/set_profile/call_tool_*enforcement path. Per tasks.md's own PR boundary, execution enforcement is 108-d's FR-009a-gated cutover; this PR builds and tests the resolution machinery 108-d wires in.tasks.mdcheckboxes are updated only for the sub-tasks genuinely completed above; T029/T033/T036 are intentionally left unchecked (partially addressed — resolver-level tests only, not the full request-level/URL-gate scenarios those tasks describe).Tests added
internal/auth/agent_token_kind_test.go— Kind/ClientID/ProfileMode round-trip,ValidateAnyTokenFormat, the full FR-021 malformed-record table.internal/auth/server_op_client_test.go— client credential is non-admin underAuthorizeServerOp.internal/storage/client_credentials_test.go— mint/replace/conflict/rotation/rollback/forget, the storage-level malformed-record rejection, the new regular-tokenclient-prefix guard.internal/httpapi/client_credential_rest_test.go— FR-023 403 across route families and carriers.internal/server/profile_resolver_v3_test.go,internal/server/anonymous_profile_test.go— resolver precedence, switchable_to admission, anonymous confinement, dangling bases.internal/server/session_store_client_identity_test.go— identity/profile fields,SessionsForToken.Local verification
go build ./...andgo build -tags server -o /dev/null ./cmd/mcpproxy/...— clean.go vet ./...— clean.golangci-lint run --config .github/.golangci.yml ./...(bare and--build-tags server, on the touched packages) — 0 new issues (7 pre-existingstaticcheckwarnings elsewhere, unrelated to this change).go test ./internal/auth/... ./internal/storage/... ./internal/httpapi/... ./internal/connect/... ./cmd/...— all green.go test -skip "E2E|Binary|MCPProtocol|..." ./internal/server/...— green on every test this PR touches or added; the full package (hundreds of pre-existing tests spinning real servers/upstreams) takes several minutes even filtered, matching this repo's documented characteristic for that package.Spec
specs/108-profiles-v3/{spec,plan,tasks,data-model}.md,contracts/{rest-api,refusals}.md— Spec 108-c "client-credentials".