Skip to content

feat(auth,server): client-credential token model and dispatch gating (Spec 108-c) - #1389

Merged
github-actions[bot] merged 4 commits into
mainfrom
108-c-client-credentials
Sep 26, 2026
Merged

github-actions[bot] merged 4 commits into
mainfrom
108-c-client-credentials

Conversation

@Dumbris

@Dumbris Dumbris commented Sep 26, 2026

Copy link
Copy Markdown
Member

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.go and internal/runtime/binding_guard.go (the FR-008a binding guard and PUT /clients/{id}/binding), the CLI connect_cmd.go flags, 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)

  • Token model (internal/auth): AgentToken.Kind/ClientID/ProfileMode/PendingHash/PendingPrefix/RotationStartedAt, the mcp_cli_ secret prefix + generator, AuthContext.TokenKind/ClientID/ProfileMode. ValidateTokenInvariants is the one fail-closed FR-021 check, run at mint time and — via storage.ValidateAgentToken — on every authentication, returning the exact malformed credential record text on any violation (missing/unknown kind, mismatched secret-vs-record kind, bad client_id, name mismatch, non-wildcard allowed_servers, incomplete permissions, locked-without-pin, client-only fields set on a regular token).
  • Storage (internal/storage/client_credentials.go): MintClientCredential (replaces a revoked/expired kind=client record for the same client id in one transaction; refuses to touch a grandfathered kind=agent token with ErrClientCredentialConflict; refuses to mint over an active credential with ErrClientCredentialActive), staged rotation (StageClientCredentialRotation / FinalizeClientCredentialRotation — idempotent — / RollbackClientCredentialRotation, both secrets valid during the overlap via a pending-hash index), ForgetClientCredential. CreateAgentToken now refuses a new regular token named client-<id> (FR-021); a grandfathered pre-108 record is unaffected.
  • Dispatch: MCP auth middleware (internal/server/server.go) recognises mcp_cli_ and validates it through the same door as mcp_agt_. REST (internal/httpapi/server.go) refuses every client credential with 403 {"error":"client credentials are valid on MCP endpoints only"} (FR-023) — recognised by prefix before any store lookup, and by kind after it as defence in depth — across every carrier (header, bearer, ?apikey=) and route family, including /events.
  • Resolver (internal/server/profile_resolver_v3.go, new): ProfileResolution (data-model.md §4) and the FR-020 precedence pin > url > session > binding > anonymous > none, with FR-022 switchable_to admission (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).
  • SessionInfo gains TokenName/ClientID/Profile/ProfileSource + SessionStore.SessionsForToken (the FR-026/FR-027 notification fan-out seam).
  • A confirming test that a kind=client AuthContext is non-admin under AuthorizeServerOp (falls out of AgentToken.AuthContext() always setting Type=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: the CredentialMinter wiring so connect mints a client credential instead of writing the admin API key, --keyless, credential_state on ClientStatus, the POST /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 across connect.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) and clients_service.go (assign/lock/unlock/rotate/forget/list, client.binding_changed, profile_change records) plus the new PUT /clients/{id}/binding route (T032/T033a/T040/T040a).
  • CLI connect_cmd.go --profile/--lock/--switchable/--keyless flags (T041).
  • Web UI / macOS connect component and ConnectClientView.swift changes (T042).
  • The runtime crash-injection reconciler for staged rotation (T028a's harder half — stage/finalize/rollback themselves are implemented and tested; the background process that inspects a client's on-disk config to decide finalize-vs-rollback after a crash is not).
  • profileIndex.selectable (internal/server/profile_tool.go) is not modified — ResolveProfileV3 is additive and not yet wired into the live retrieve_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.md checkboxes 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 under AuthorizeServerOp.
  • internal/storage/client_credentials_test.go — mint/replace/conflict/rotation/rollback/forget, the storage-level malformed-record rejection, the new regular-token client- 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 ./... and go 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-existing staticcheck warnings 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.
  • Frontend/macOS: not touched by this PR, so not run.

Spec

specs/108-profiles-v3/{spec,plan,tasks,data-model}.md, contracts/{rest-api,refusals}.md — Spec 108-c "client-credentials".

… (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).
@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: 108-c-client-credentials

Available Artifacts

  • archive-darwin-amd64 (30 MB)
  • archive-darwin-arm64 (27 MB)
  • archive-linux-amd64 (18 MB)
  • archive-linux-arm64 (16 MB)
  • archive-windows-amd64 (30 MB)
  • archive-windows-arm64 (26 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (24 MB)
  • installer-dmg-darwin-arm64 (22 MB)
  • smart-mcp-proxymcpproxy-goMJMOV6.dockerbuild (0 MB)

How to Download

Option 1: GitHub Web UI (easiest)

  1. Go to the workflow run page linked above
  2. Scroll to the bottom "Artifacts" section
  3. Click on the artifact you want to download

Option 2: GitHub CLI

gh run download 36258257562 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

@codecov-commenter

codecov-commenter commented Sep 26, 2026 •

Copy link
Copy Markdown

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

Codecov Report

❌ Patch coverage is 74.63768% with 105 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/storage/client_credentials.go 59.91% 46 Missing and 45 partials ⚠️
internal/auth/agent_token.go 88.05% 4 Missing and 4 partials ⚠️
internal/server/session_store.go 84.61% 2 Missing and 2 partials ⚠️
internal/server/profile_resolver_v3.go 96.49% 1 Missing and 1 partial ⚠️

📢 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).
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

Deploying mcpproxy-docs with  Cloudflare Pages  Cloudflare Pages

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

View logs

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved (Model B): Paperclip review verdicts = ACCEPT and qa-gate green at this head SHA. Arming auto-merge; GitHub merges when all required checks pass.

@github-actions
github-actions Bot merged commit 74df81e into main Sep 26, 2026
58 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants