Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(mcp): private in-memory transport + delegated credential (P1a PR 4) (#21116)

Vincent Huangafed9981b053
diff --git a/backend/api/auth/auth.go b/backend/api/auth/auth.go
index 7fb87495cf..4ce1de2670 100644
--- a/backend/api/auth/auth.go
+++ b/backend/api/auth/auth.go
@@ -244,40 +244,52 @@ func (in *APIAuthInterceptor) authenticate(ctx context.Context, accessTokenStr,
slog.String("audience", strings.Join(claims.Audience, ",")))
}
- account, err := in.store.GetAccountByEmail(ctx, claims.Subject)
+ user, err := resolvePrincipal(ctx, in.store, in.profile, claims.Subject, claims.WorkspaceID)
if err != nil {
- return nil, nil, errs.Errorf("failed to find principal %q in the access token", claims.Subject)
+ return nil, nil, err
+ }
+ return user, claims, nil
+}
+
+// resolvePrincipal turns a verified token's identity claims into a live user:
+// account lookup, deactivation check, workspace-membership verification, and
+// principal resolution. Shared by the public interceptor and the internal MCP
+// interceptor so both surfaces re-resolve identity state identically on every
+// request — a credential is never trusted for anything beyond who and where.
+func resolvePrincipal(ctx context.Context, stores *store.Store, profile *config.Profile, subject, workspaceID string) (*store.UserMessage, error) {
+ account, err := stores.GetAccountByEmail(ctx, subject)
+ if err != nil {
+ return nil, errs.Errorf("failed to find principal %q in the access token", subject)
}
if account == nil {
- return nil, nil, errs.Errorf("principal %q not exists in the access token", claims.Subject)
+ return nil, errs.Errorf("principal %q not exists in the access token", subject)
}
if account.MemberDeleted {
- return nil, nil, errs.Errorf("principal %q has been deactivated by administrators", account.Email)
+ return nil, errs.Errorf("principal %q has been deactivated by administrators", account.Email)
}
// Verify workspace membership.
// We always require workspace_id in the claims even for non-SaaS (single workspace) mode
- if claims.WorkspaceID == "" {
- return nil, nil, errs.New("empty workspace in the token")
+ if workspaceID == "" {
+ return nil, errs.New("empty workspace in the token")
}
- if err := in.verifyWorkspaceMembership(ctx, claims.WorkspaceID, account); err != nil {
- return nil, nil, err
+ if err := verifyWorkspaceMembership(ctx, stores, profile, workspaceID, account); err != nil {
+ return nil, err
}
// Convert to UserMessage for context storage.
- user, err := in.store.ResolvePrincipalAsUser(ctx, account)
+ user, err := stores.ResolvePrincipalAsUser(ctx, account)
if err != nil {
- return nil, nil, err
+ return nil, err
}
if user == nil {
- return nil, nil, errs.Errorf("user %q not found", account.Email)
+ return nil, errs.Errorf("user %q not found", account.Email)
}
-
- return user, claims, nil
+ return user, nil
}
// verifyWorkspaceMembership checks that the account is a member of the workspace.
-func (in *APIAuthInterceptor) verifyWorkspaceMembership(ctx context.Context, workspaceID string, account *store.AccountMessage) error {
+func verifyWorkspaceMembership(ctx context.Context, stores *store.Store, profile *config.Profile, workspaceID string, account *store.AccountMessage) error {
switch account.Type {
case storepb.PrincipalType_SERVICE_ACCOUNT, storepb.PrincipalType_WORKLOAD_IDENTITY:
// Service accounts and workload identities have workspace on their record.
@@ -289,7 +301,7 @@ func (in *APIAuthInterceptor) verifyWorkspaceMembership(ctx context.Context, wor
case storepb.PrincipalType_END_USER:
// END_USER membership is verified via workspace IAM policy.
// Check direct membership, group membership, and allUsers.
- iamPolicy, err := in.store.GetWorkspaceIamPolicy(ctx, workspaceID)
+ iamPolicy, err := stores.GetWorkspaceIamPolicy(ctx, workspaceID)
if err != nil {
return errs.Wrap(err, "failed to get workspace IAM policy")
}
@@ -299,12 +311,12 @@ func (in *APIAuthInterceptor) verifyWorkspaceMembership(ctx context.Context, wor
if member == userMember {
return nil
}
- if member == common.AllUsers && !in.profile.SaaS {
+ if member == common.AllUsers && !profile.SaaS {
return nil
}
// Check group membership.
if strings.HasPrefix(member, common.GroupPrefix) {
- groupMembers, _ := in.store.GetGroupMembersSnapshot(ctx, workspaceID, member)
+ groupMembers, _ := stores.GetGroupMembersSnapshot(ctx, workspaceID, member)
if groupMembers != nil && groupMembers[userMember] {
return nil
}
diff --git a/backend/api/auth/internal_credential.go b/backend/api/auth/internal_credential.go
new file mode 100644
index 0000000000..0afee90ee6
--- /dev/null
+++ b/backend/api/auth/internal_credential.go
@@ -0,0 +1,147 @@
+package auth
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ errs "github.com/pkg/errors"
+)
+
+const (
+ // internalMCPAudience is the audience of the delegated credential minted at
+ // the /mcp boundary for the private in-memory transport, and the only claim
+ // that marks it as internal. No public listener ever accepts it. A separate
+ // token_use would say nothing the audience does not: unlike the external MCP
+ // token, whose audience is a per-deployment resource URI that no verifier
+ // can match against a constant, this audience IS a constant.
+ internalMCPAudience = "bb.mcp.internal"
+ // internalMCPTokenDuration is the delegated credential's lifetime. It is
+ // request-scale: minted per inbound MCP request, it only needs to cover one
+ // tool execution (worst case a multi-call change tool with plan-check
+ // polling), never a session.
+ internalMCPTokenDuration = 5 * time.Minute
+)
+
+// DelegatedMCPCredential is the claim set of the credential minted at the /mcp
+// boundary and carried on the private in-memory transport. Identity + grant
+// state only: Scope and Resource are the grant's STORED values copied verbatim
+// (empty for legacy sessions), and no roles are baked in — downstream
+// authorization re-resolves membership and RBAC live, exactly as for a public
+// request. This claim shape is the contract PR 5 parses into common.AuthContext.
+type DelegatedMCPCredential struct {
+ Principal string
+ WorkspaceID string
+ ClientID string
+ CorrelationID string
+ Scope string
+ Resource string
+}
+
+// internalMCPClaimsMessage is the JWT claim layout of the delegated credential.
+type internalMCPClaimsMessage struct {
+ claimsMessage
+ ClientID string `json:"client_id,omitempty"`
+ CorrelationID string `json:"correlation_id,omitempty"`
+ Scope string `json:"scope,omitempty"`
+ GrantResource string `json:"grant_resource,omitempty"`
+}
+
+// internalMCPSigningKey derives the internal credential's signing key from the
+// server secret.
+//
+// This is one of two independent layers separating internal from public
+// credentials; the audience check is the other, and either alone is sufficient
+// (verified by mutation: signing these with the raw secret leaves every
+// public-surface rejection test green, and it fails only the wire-shape test
+// that pins this derivation). Keep both. The credential shares the public kid,
+// so a public verifier will try it, hand back the raw secret, and fail on the
+// signature before it ever reads a claim.
+//
+// The derivation also means a leaked internal credential can never be
+// re-signed into a public one.
+func internalMCPSigningKey(secret string) []byte {
+ mac := hmac.New(sha256.New, []byte(secret))
+ mac.Write([]byte(internalMCPAudience + ":" + keyID))
+ return mac.Sum(nil)
+}
+
+// GenerateInternalMCPToken mints the delegated credential for one MCP request.
+func GenerateInternalMCPToken(cred DelegatedMCPCredential, secret string) (string, error) {
+ return generateInternalMCPTokenWithExpiry(cred, secret, time.Now().Add(internalMCPTokenDuration))
+}
+
+func generateInternalMCPTokenWithExpiry(cred DelegatedMCPCredential, secret string, expirationTime time.Time) (string, error) {
+ claims := &internalMCPClaimsMessage{
+ claimsMessage: claimsMessage{
+ RegisteredClaims: jwt.RegisteredClaims{
+ Audience: jwt.ClaimStrings{internalMCPAudience},
+ ExpiresAt: jwt.NewNumericDate(expirationTime),
+ IssuedAt: jwt.NewNumericDate(time.Now()),
+ Issuer: issuer,
+ Subject: cred.Principal,
+ },
+ WorkspaceID: cred.WorkspaceID,
+ },
+ ClientID: cred.ClientID,
+ CorrelationID: cred.CorrelationID,
+ Scope: cred.Scope,
+ GrantResource: cred.Resource,
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ token.Header["kid"] = keyID
+ return token.SignedString(internalMCPSigningKey(secret))
+}
+
+// IsMCPOriginatedToken reports whether a bearer identifies MCP-originated
+// traffic — either an external MCP OAuth2 token or the delegated credential
+// minted at the /mcp boundary for the internal transport.
+//
+// Guards that must not serve MCP sessions have to ask this rather than
+// inspecting claims themselves: since P1a PR 3 the external token's audience is
+// a per-deployment resource URI (so token_use is the recognizer), and since PR
+// 4 tool traffic presents the delegated credential instead, which is signed
+// with a derived key and therefore invisible to ExtractClaimsFromExpiredToken.
+func IsMCPOriginatedToken(tokenStr, secret string) bool {
+ if tokenStr == "" {
+ return false
+ }
+ if _, err := VerifyInternalMCPToken(tokenStr, secret); err == nil {
+ return true
+ }
+ claims, err := ExtractClaimsFromExpiredToken(tokenStr, secret)
+ if err != nil {
+ return false
+ }
+ return claims.TokenUse == TokenUseMCP || audienceContains(claims.Audience, OAuth2AccessTokenAudience)
+}
+
+// VerifyInternalMCPToken validates a delegated credential and returns its
+// claims. It accepts ONLY the internal credential: the derived key rejects
+// everything minted for a public surface, and the audience is checked on top.
+func VerifyInternalMCPToken(tokenStr, secret string) (*DelegatedMCPCredential, error) {
+ claims := &internalMCPClaimsMessage{}
+ if _, err := jwt.ParseWithClaims(tokenStr, claims, func(t *jwt.Token) (any, error) {
+ if t.Method.Alg() != jwt.SigningMethodHS256.Name {
+ return nil, errs.Errorf("unexpected internal credential signing method=%v", t.Header["alg"])
+ }
+ if kid, ok := t.Header["kid"].(string); ok && kid == keyID {
+ return internalMCPSigningKey(secret), nil
+ }
+ return nil, errs.Errorf("unexpected internal credential kid=%v", t.Header["kid"])
+ }); err != nil {
+ return nil, errs.Wrap(err, "invalid internal MCP credential")
+ }
+ if !audienceContains(claims.Audience, internalMCPAudience) {
+ return nil, errs.Errorf("internal MCP credential audience mismatch, got %q", claims.Audience)
+ }
+ return &DelegatedMCPCredential{
+ Principal: claims.Subject,
+ WorkspaceID: claims.WorkspaceID,
+ ClientID: claims.ClientID,
+ CorrelationID: claims.CorrelationID,
+ Scope: claims.Scope,
+ Resource: claims.GrantResource,
+ }, nil
+}
diff --git a/backend/api/auth/internal_credential_test.go b/backend/api/auth/internal_credential_test.go
new file mode 100644
index 0000000000..36548ea571
--- /dev/null
+++ b/backend/api/auth/internal_credential_test.go
@@ -0,0 +1,159 @@
+package auth
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/stretchr/testify/require"
+)
+
+func testDelegatedCredential() DelegatedMCPCredential {
+ return DelegatedMCPCredential{
+ Principal: "[email protected]",
+ WorkspaceID: "ws-test",
+ ClientID: "client-A",
+ CorrelationID: "corr-123",
+ Scope: "mcp:read-only",
+ Resource: testResource,
+ }
+}
+
+// TestInternalMCPCredentialRoundTrip pins the delegated credential shape: every
+// claim the P1b contract keys on (principal, workspace, client_id, correlation
+// ID, grant scope + resource) survives a mint/verify round trip verbatim.
+func TestInternalMCPCredentialRoundTrip(t *testing.T) {
+ tokenStr, err := GenerateInternalMCPToken(testDelegatedCredential(), testSecret)
+ require.NoError(t, err)
+
+ got, err := VerifyInternalMCPToken(tokenStr, testSecret)
+ require.NoError(t, err)
+ require.Equal(t, testDelegatedCredential(), *got)
+}
+
+// TestInternalMCPCredentialEmptyGrantState pins that legacy sessions (plain
+// bb.user.access at /mcp, pre-scope OAuth2 tokens) mint a credential with empty
+// scope and resource — PR 5, not this PR, assigns their LEGACY_FULL semantics.
+func TestInternalMCPCredentialEmptyGrantState(t *testing.T) {
+ cred := testDelegatedCredential()
+ cred.Scope = ""
+ cred.Resource = ""
+ tokenStr, err := GenerateInternalMCPToken(cred, testSecret)
+ require.NoError(t, err)
+
+ got, err := VerifyInternalMCPToken(tokenStr, testSecret)
+ require.NoError(t, err)
+ require.Empty(t, got.Scope)
+ require.Empty(t, got.Resource)
+ require.Equal(t, "[email protected]", got.Principal)
+}
+
+// TestInternalMCPCredentialWireShape pins what separates the internal
+// credential from every public one: a signing key derived from the secret, and
+// a dedicated audience. Each layer independently refuses in both directions, so
+// this test is the only place the derivation itself is pinned — the
+// public-surface rejection tests stay green on the audience check alone.
+//
+// There is deliberately no token_use: unlike the external MCP token, whose
+// per-deployment resource audience cannot be matched against a constant, this
+// audience is a constant and already says "internal". The kid is shared with
+// public tokens, so it discriminates nothing; that is what the derived key and
+// audience are for.
+func TestInternalMCPCredentialWireShape(t *testing.T) {
+ tokenStr, err := GenerateInternalMCPToken(testDelegatedCredential(), testSecret)
+ require.NoError(t, err)
+
+ parser := jwt.NewParser()
+ token, _, err := parser.ParseUnverified(tokenStr, jwt.MapClaims{})
+ require.NoError(t, err)
+ claims, ok := token.Claims.(jwt.MapClaims)
+ require.True(t, ok)
+ require.Equal(t, []any{internalMCPAudience}, claims["aud"])
+ require.NotContains(t, claims, "token_use",
+ "the audience identifies the credential; a token_use would be redundant")
+
+ _, err = jwt.ParseWithClaims(tokenStr, jwt.MapClaims{}, func(_ *jwt.Token) (any, error) {
+ return []byte(testSecret), nil
+ })
+ require.Error(t, err, "internal credential must not verify under the raw shared secret")
+}
+
+// TestGeneralAPIRejectsInternalMCPCredential is the public-surface boundary
+// test for the v1 API: the interceptor's authenticate path must refuse the
+// internal credential outright. The kid gate fires before any store access, so
+// a nil-store interceptor suffices.
+func TestGeneralAPIRejectsInternalMCPCredential(t *testing.T) {
+ tokenStr, err := GenerateInternalMCPToken(testDelegatedCredential(), testSecret)
+ require.NoError(t, err)
+
+ in := New(nil, testSecret, nil, nil, nil)
+ _, _, err = in.authenticate(context.Background(), tokenStr, "/bytebase.v1.SQLService/Query")
+ require.Error(t, err, "the general API must never accept the internal MCP credential")
+}
+
+// TestCheckTokenAudienceRejectsInternalCredential covers the second boundary
+// layer on the general API: even if the internal credential's signature were
+// somehow accepted, its audience admits it nowhere. Carrying no token_use is
+// part of that — the claim is absent, so the MCP admission branch (which keys
+// on token_use == TokenUseMCP) cannot fire either.
+func TestCheckTokenAudienceRejectsInternalCredential(t *testing.T) {
+ claims := &claimsMessage{
+ RegisteredClaims: jwt.RegisteredClaims{
+ Audience: jwt.ClaimStrings{internalMCPAudience},
+ },
+ }
+ _, err := checkTokenAudience(claims)
+ require.Error(t, err)
+}
+
+// TestVerifyInternalMCPTokenRejectsPublicTokens is the mirror boundary: the
+// internal transport accepts ONLY the internal credential. Web session tokens
+// and OAuth2 MCP tokens (both kid "v1") must be refused, as must expired
+// internal credentials and garbage.
+func TestVerifyInternalMCPTokenRejectsPublicTokens(t *testing.T) {
+ webToken, err := GenerateAccessToken("[email protected]", "ws-test", testSecret, time.Hour)
+ require.NoError(t, err)
+ _, err = VerifyInternalMCPToken(webToken, testSecret)
+ require.Error(t, err, "web session token must be refused on the internal transport")
+
+ mcpToken, err := GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", testResource, "mcp:read-only", testSecret, time.Hour)
+ require.NoError(t, err)
+ _, err = VerifyInternalMCPToken(mcpToken, testSecret)
+ require.Error(t, err, "external MCP OAuth2 token must be refused on the internal transport")
+
+ expired := testDelegatedCredential()
+ expiredStr, err := generateInternalMCPTokenWithExpiry(expired, testSecret, time.Now().Add(-time.Minute))
+ require.NoError(t, err)
+ _, err = VerifyInternalMCPToken(expiredStr, testSecret)
+ require.Error(t, err, "expired internal credential must be refused")
+
+ _, err = VerifyInternalMCPToken("not-a-jwt", testSecret)
+ require.Error(t, err)
+}
+
+// TestOAuth2AccessTokenCarriesScope pins the enabler this PR adds to the public
+// OAuth2 token: the grant's stored scope travels on the access token verbatim
+// (RFC 9068 shape), so the /mcp boundary can copy it onto the delegated
+// credential without a store lookup. Empty scope (legacy grants) omits the
+// claim.
+func TestOAuth2AccessTokenCarriesScope(t *testing.T) {
+ tokenStr, err := GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", testResource, "mcp:read-only", testSecret, time.Hour)
+ require.NoError(t, err)
+
+ claims := jwt.MapClaims{}
+ _, err = jwt.ParseWithClaims(tokenStr, claims, func(_ *jwt.Token) (any, error) {
+ return []byte(testSecret), nil
+ })
+ require.NoError(t, err)
+ require.Equal(t, "mcp:read-only", claims["scope"])
+
+ emptyScope, err := GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", testResource, "", testSecret, time.Hour)
+ require.NoError(t, err)
+ claims = jwt.MapClaims{}
+ _, err = jwt.ParseWithClaims(emptyScope, claims, func(_ *jwt.Token) (any, error) {
+ return []byte(testSecret), nil
+ })
+ require.NoError(t, err)
+ require.NotContains(t, claims, "scope")
+}
diff --git a/backend/api/auth/internal_interceptor.go b/backend/api/auth/internal_interceptor.go
new file mode 100644
index 0000000000..e22ebc3394
--- /dev/null
+++ b/backend/api/auth/internal_interceptor.go
@@ -0,0 +1,88 @@
+package auth
+
+import (
+ "context"
+ "time"
+
+ "connectrpc.com/connect"
+ errs "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/config"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// InternalMCPAuthInterceptor guards the private in-memory transport that
+// carries /mcp tool traffic to the internal API handler chain. It accepts ONLY
+// the delegated credential minted at the /mcp boundary: public bearer tokens
+// are refused here, and the public chain — whose keyfunc only knows kid "v1" —
+// symmetrically refuses the internal credential.
+//
+// Identity and grant state ride the credential; authorization does not. The
+// principal is re-resolved against the store and workspace membership on every
+// request, and the downstream ACL interceptor re-resolves RBAC live, exactly
+// as for a public request.
+//
+// Unlike the public interceptor, allow_without_credential RPCs get no
+// authentication skip: every internal request carries a freshly minted
+// credential, so an invalid one is a bug and fails closed.
+type InternalMCPAuthInterceptor struct {
+ store *store.Store
+ secret string
+ profile *config.Profile
+}
+
+// NewInternalMCPAuthInterceptor returns the auth interceptor for the internal
+// MCP handler chain.
+func NewInternalMCPAuthInterceptor(store *store.Store, secret string, profile *config.Profile) *InternalMCPAuthInterceptor {
+ return &InternalMCPAuthInterceptor{
+ store: store,
+ secret: secret,
+ profile: profile,
+ }
+}
+
+// WrapUnary implements the ConnectRPC interceptor interface for unary RPCs.
+func (in *InternalMCPAuthInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
+ return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
+ tokenStr, err := GetTokenFromHeaders(req.Header())
+ if err != nil {
+ return nil, connect.NewError(connect.CodeUnauthenticated, err)
+ }
+ cred, err := VerifyInternalMCPToken(tokenStr, in.secret)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeUnauthenticated, err)
+ }
+
+ authContext, err := getAuthContext(req.Spec().Procedure)
+ if err != nil {
+ return nil, err
+ }
+ ctx = context.WithValue(ctx, common.AuthContextKey, authContext)
+
+ user, err := resolvePrincipal(ctx, in.store, in.profile, cred.Principal, cred.WorkspaceID)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeUnauthenticated, err)
+ }
+
+ in.profile.LastActiveTS.Store(time.Now().Unix())
+ ctx = context.WithValue(ctx, common.UserContextKey, user)
+ ctx = context.WithValue(ctx, common.WorkspaceIDContextKey, cred.WorkspaceID)
+ return next(ctx, req)
+ }
+}
+
+// WrapStreamingClient implements the ConnectRPC interceptor interface for streaming clients.
+func (*InternalMCPAuthInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
+ return func(ctx context.Context, spec connect.Spec) connect.StreamingClientConn {
+ return next(ctx, spec)
+ }
+}
+
+// WrapStreamingHandler rejects streaming outright: no MCP tool streams, so a
+// streaming call on the internal transport is a bug and fails closed.
+func (*InternalMCPAuthInterceptor) WrapStreamingHandler(connect.StreamingHandlerFunc) connect.StreamingHandlerFunc {
+ return func(_ context.Context, _ connect.StreamingHandlerConn) error {
+ return connect.NewError(connect.CodeUnimplemented, errs.New("streaming is not supported on the internal MCP transport"))
+ }
+}
diff --git a/backend/api/auth/internal_interceptor_test.go b/backend/api/auth/internal_interceptor_test.go
new file mode 100644
index 0000000000..d0d5e751a5
--- /dev/null
+++ b/backend/api/auth/internal_interceptor_test.go
@@ -0,0 +1,63 @@
+package auth
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/emptypb"
+)
+
+// callInternalUnary runs a request through the internal interceptor with a
+// recording next, returning the error and whether next was reached.
+func callInternalUnary(t *testing.T, authHeader string) (nextCalled bool, err error) {
+ t.Helper()
+ in := NewInternalMCPAuthInterceptor(nil, testSecret, nil)
+ req := connect.NewRequest(&emptypb.Empty{})
+ if authHeader != "" {
+ req.Header().Set("Authorization", authHeader)
+ }
+ next := func(_ context.Context, _ connect.AnyRequest) (connect.AnyResponse, error) {
+ nextCalled = true
+ return nil, nil
+ }
+ _, err = in.WrapUnary(next)(context.Background(), req)
+ return nextCalled, err
+}
+
+// TestInternalInterceptorRejectsPublicTokens pins the accept-ONLY-the-internal-
+// credential rule: web session tokens and external OAuth2 MCP tokens must never
+// reach a handler through the private transport. Rejection happens before any
+// store access, so a nil store proves the ordering too.
+func TestInternalInterceptorRejectsPublicTokens(t *testing.T) {
+ webToken, err := GenerateAccessToken("[email protected]", "ws-test", testSecret, time.Hour)
+ require.NoError(t, err)
+ mcpToken, err := GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", testResource, "mcp:read-only", testSecret, time.Hour)
+ require.NoError(t, err)
+
+ for name, header := range map[string]string{
+ "no credential": "",
+ "malformed header": "NotBearer x",
+ "web session token": "Bearer " + webToken,
+ "external MCP OAuth token": "Bearer " + mcpToken,
+ "garbage": "Bearer not-a-jwt",
+ } {
+ t.Run(name, func(t *testing.T) {
+ nextCalled, err := callInternalUnary(t, header)
+ require.False(t, nextCalled, "handler must not be reached")
+ require.Error(t, err)
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ })
+ }
+}
+
+// TestInternalInterceptorRejectsStreaming pins that the private transport is
+// unary-only: no MCP tool streams, so a streaming call through it is a bug and
+// fails closed.
+func TestInternalInterceptorRejectsStreaming(t *testing.T) {
+ in := NewInternalMCPAuthInterceptor(nil, testSecret, nil)
+ err := in.WrapStreamingHandler(nil)(context.Background(), nil)
+ require.Error(t, err)
+}
diff --git a/backend/api/auth/tokens.go b/backend/api/auth/tokens.go
index 69705cd4e1..8a61c2e2d0 100644
--- a/backend/api/auth/tokens.go
+++ b/backend/api/auth/tokens.go
@@ -41,6 +41,10 @@ type claimsMessage struct {
type oauth2ClaimsMessage struct {
claimsMessage
ClientID string `json:"client_id,omitempty"`
+ // Scope echoes the grant's stored scope verbatim (RFC 9068 shape) so the
+ // /mcp boundary can copy the grant state onto the delegated credential
+ // without a store lookup. Absent on legacy grants that stored no scope.
+ Scope string `json:"scope,omitempty"`
}
// GenerateAPIToken generates an API token.
@@ -98,9 +102,11 @@ func generateTokenWithLoginMethod(userEmail string, workspaceID string, aud stri
// rather than live config means rotating the external URL invalidates
// outstanding tokens at /mcp (audience mismatch, clean 401 driving a re-auth)
// instead of quietly rebinding them to a resource the user never approved.
-func GenerateOAuth2AccessToken(userEmail, clientID, workspaceID, audience, secret string, duration time.Duration) (string, error) {
+//
+// scope is the grant's stored scope, carried verbatim like the audience.
+func GenerateOAuth2AccessToken(userEmail, clientID, workspaceID, audience, scope, secret string, duration time.Duration) (string, error) {
expirationTime := time.Now().Add(duration)
- return generateOAuth2Token(userEmail, clientID, workspaceID, audience, expirationTime, []byte(secret))
+ return generateOAuth2Token(userEmail, clientID, workspaceID, audience, scope, expirationTime, []byte(secret))
}
// ExpiredTokenClaims holds the claims extracted from an expired JWT.
@@ -137,9 +143,10 @@ func ExtractClaimsFromExpiredToken(tokenString, secret string) (*ExpiredTokenCla
}
// generateOAuth2Token creates a JWT token with OAuth2-specific claims including client_id.
-func generateOAuth2Token(userEmail, clientID, workspaceID, aud string, expirationTime time.Time, secret []byte) (string, error) {
+func generateOAuth2Token(userEmail, clientID, workspaceID, aud, scope string, expirationTime time.Time, secret []byte) (string, error) {
claims := &oauth2ClaimsMessage{
ClientID: clientID,
+ Scope: scope,
claimsMessage: claimsMessage{
RegisteredClaims: jwt.RegisteredClaims{
Audience: jwt.ClaimStrings{aud},
diff --git a/backend/api/auth/tokens_test.go b/backend/api/auth/tokens_test.go
index 724a0302dd..66704276f9 100644
--- a/backend/api/auth/tokens_test.go
+++ b/backend/api/auth/tokens_test.go
@@ -20,7 +20,7 @@ const (
// API interceptor can recognize it without knowing every deployment's resource
// URI.
func TestGenerateOAuth2AccessTokenClaims(t *testing.T) {
- tokenStr, err := GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", testResource, testSecret, time.Hour)
+ tokenStr, err := GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", testResource, "", testSecret, time.Hour)
require.NoError(t, err)
claims := jwt.MapClaims{}
@@ -58,7 +58,7 @@ func TestWebTokensCarryNoTokenUse(t *testing.T) {
// no longer key on the fixed bb.oauth2.access audience once tokens carry a
// per-deployment resource URI instead.
func TestExtractClaimsFromExpiredTokenTokenUse(t *testing.T) {
- tokenStr, err := GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", testResource, testSecret, -time.Minute)
+ tokenStr, err := GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", testResource, "", testSecret, -time.Minute)
require.NoError(t, err)
claims, err := ExtractClaimsFromExpiredToken(tokenStr, testSecret)
diff --git a/backend/api/mcp/boundary_revalidation_test.go b/backend/api/mcp/boundary_revalidation_test.go
new file mode 100644
index 0000000000..53e58c6e51
--- /dev/null
+++ b/backend/api/mcp/boundary_revalidation_test.go
@@ -0,0 +1,301 @@
+package mcp
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/labstack/echo/v5"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/config"
+)
+
+// swappingTransport presents whatever bearer is currently stored, so a test can
+// change the client's credential mid-session.
+type swappingTransport struct {
+ token atomic.Pointer[string]
+}
+
+func (t *swappingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ req = req.Clone(req.Context())
+ if token := t.token.Load(); token != nil {
+ req.Header.Set("Authorization", "Bearer "+*token)
+ }
+ return http.DefaultTransport.RoundTrip(req)
+}
+
+const revalidationSecret = "test-secret-key"
+
+// TestBoundaryRevalidatesEveryRequest pins the invariant the delegated
+// credential rests on: authMiddleware guards the whole /mcp route, so EVERY
+// JSON-RPC POST — not just initialize — re-validates the live bearer before any
+// tool runs. Minting internal credentials from the session identity is
+// therefore not a way around token expiry or revocation: a session whose
+// credential has gone bad cannot reach a tool at all.
+func TestBoundaryRevalidatesEveryRequest(t *testing.T) {
+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
+
+ newSession := func(t *testing.T) (*mcp.ClientSession, *swappingTransport, *int32, *Server) {
+ t.Helper()
+ var toolHits int32
+ stub := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ atomic.AddInt32(&toolHits, 1)
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprint(w, `{}`)
+ })
+ s, err := NewServer(nil, profile, revalidationSecret, stub)
+ require.NoError(t, err)
+
+ e := echo.New()
+ s.RegisterRoutes(e)
+ ts := httptest.NewServer(e)
+ t.Cleanup(ts.Close)
+
+ valid := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour)
+ transport := &swappingTransport{}
+ transport.token.Store(&valid)
+
+ client := mcp.NewClient(&mcp.Implementation{Name: "probe", Version: "0"}, nil)
+ session, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{
+ Endpoint: ts.URL + "/mcp",
+ HTTPClient: &http.Client{Transport: transport},
+ MaxRetries: -1,
+ }, nil)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = session.Close() })
+ return session, transport, &toolHits, s
+ }
+
+ callTool := func(ctx context.Context, session *mcp.ClientSession) error {
+ _, err := session.CallTool(ctx, &mcp.CallToolParams{
+ Name: "call_api",
+ Arguments: map[string]any{"operationId": "SQLService/Query"},
+ })
+ return err
+ }
+
+ t.Run("expired bearer on an established session cannot reach a tool", func(t *testing.T) {
+ session, transport, toolHits, _ := newSession(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ // The session is live: a tool call works while the bearer is valid.
+ require.NoError(t, callTool(ctx, session))
+ require.Equal(t, int32(1), atomic.LoadInt32(toolHits))
+
+ expired := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", -time.Minute)
+ transport.token.Store(&expired)
+
+ require.Error(t, callTool(ctx, session),
+ "an expired bearer must be refused at the boundary, session or no session")
+ require.Equal(t, int32(1), atomic.LoadInt32(toolHits),
+ "no internal API call may be made for a request the boundary refused")
+ })
+
+ t.Run("revoked bearer on an established session cannot reach a tool", func(t *testing.T) {
+ session, transport, toolHits, s := newSession(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ require.NoError(t, callTool(ctx, session))
+ require.Equal(t, int32(1), atomic.LoadInt32(toolHits))
+
+ // What the reauthorize tool does to the caller's own token.
+ s.revokedAccessTokens.Store(*transport.token.Load(), struct{}{})
+
+ require.Error(t, callTool(ctx, session),
+ "a revoked bearer must be refused at the boundary")
+ require.Equal(t, int32(1), atomic.LoadInt32(toolHits))
+ })
+
+ // The session identity is captured at initialize and reused for the whole
+ // session (the SDK gives tool handlers the initialize request's context), so
+ // the boundary admitting a DIFFERENT valid bearer mid-session would run the
+ // internal call under the original principal. Substituting another user's
+ // valid token would then execute as the session's user; substituting a token
+ // for a workspace where MCP is still enabled would sidestep the kill switch
+ // on the session's own workspace. The session must be bound to the identity
+ // it was opened with.
+ t.Run("a different principal's valid bearer cannot take over the session", func(t *testing.T) {
+ session, transport, toolHits, _ := newSession(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ require.NoError(t, callTool(ctx, session))
+ require.Equal(t, int32(1), atomic.LoadInt32(toolHits))
+
+ other := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour)
+ transport.token.Store(&other)
+
+ require.Error(t, callTool(ctx, session),
+ "a bearer for a different principal must not drive an established session")
+ require.Equal(t, int32(1), atomic.LoadInt32(toolHits),
+ "no internal call may run under the session's original identity for a substituted bearer")
+ })
+
+ t.Run("a bearer for a different workspace cannot take over the session", func(t *testing.T) {
+ session, transport, toolHits, _ := newSession(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ require.NoError(t, callTool(ctx, session))
+
+ otherWorkspace := mintMCPToken(t, "[email protected]", "client-A", "ws-other", "mcp:read-only", time.Hour)
+ transport.token.Store(&otherWorkspace)
+
+ require.Error(t, callTool(ctx, session),
+ "a bearer bound to another workspace must not drive this session")
+ require.Equal(t, int32(1), atomic.LoadInt32(toolHits))
+ })
+
+ t.Run("a different OAuth client cannot take over the session", func(t *testing.T) {
+ session, transport, toolHits, _ := newSession(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ require.NoError(t, callTool(ctx, session))
+
+ // Same user, different registered client: a separate grant, so a
+ // separate session.
+ otherClient := mintMCPToken(t, "[email protected]", "client-B", "ws-test", "mcp:read-only", time.Hour)
+ transport.token.Store(&otherClient)
+
+ require.Error(t, callTool(ctx, session),
+ "a bearer issued to another OAuth client must not drive this session")
+ require.Equal(t, int32(1), atomic.LoadInt32(toolHits))
+ })
+
+ t.Run("a narrowed re-consent cannot ride the old session", func(t *testing.T) {
+ session, transport, toolHits, _ := newSession(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ require.NoError(t, callTool(ctx, session))
+
+ // Same user, same client: only the consented scope changed. The session
+ // still holds the wider grant state, so it must not keep serving.
+ reconsented := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-write", time.Hour)
+ transport.token.Store(&reconsented)
+
+ require.Error(t, callTool(ctx, session),
+ "a re-consented grant must re-initialize rather than inherit the old session's state")
+ require.Equal(t, int32(1), atomic.LoadInt32(toolHits))
+ })
+
+ // The binding must key on identity, not on the token string: a routine
+ // refresh mints a new token with the same principal, workspace, client,
+ // resource and scope, and must keep working.
+ t.Run("a refreshed bearer for the same identity keeps working", func(t *testing.T) {
+ session, transport, toolHits, _ := newSession(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ require.NoError(t, callTool(ctx, session))
+
+ refreshed := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", 2*time.Hour)
+ require.NotEqual(t, *transport.token.Load(), refreshed)
+ transport.token.Store(&refreshed)
+
+ require.NoError(t, callTool(ctx, session),
+ "refreshing a token must not break an open session")
+ require.Equal(t, int32(2), atomic.LoadInt32(toolHits))
+ })
+}
+
+// forwardedTransport presents a fixed bearer and a settable X-Forwarded-For, so
+// a test can move an established session to a different client IP.
+type forwardedTransport struct {
+ token string
+ ip atomic.Pointer[string]
+}
+
+func (t *forwardedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ req = req.Clone(req.Context())
+ req.Header.Set("Authorization", "Bearer "+t.token)
+ if ip := t.ip.Load(); ip != nil {
+ req.Header.Set("X-Forwarded-For", *ip)
+ }
+ return http.DefaultTransport.RoundTrip(req)
+}
+
+// TestInternalRequestUsesLiveCallerIP pins that audit sees where a tool call
+// came from NOW, not where the session was opened from. Tool handlers run on
+// the initialize request's context, so a caller IP read from that context is
+// frozen for the session's life: a client that changes network mid-session
+// (wifi to cellular, VPN toggle, proxy rotation) would have every later action
+// attributed to the address it first connected from.
+//
+// The session identity is still pinned — a moving IP must not end the session,
+// which is what makes taking the live address safe: it cannot be a different
+// principal's.
+func TestInternalRequestUsesLiveCallerIP(t *testing.T) {
+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
+
+ var capturedIP atomic.Pointer[string]
+ stub := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ ip := r.Header.Get("X-Real-IP")
+ capturedIP.Store(&ip)
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprint(w, `{}`)
+ })
+ s, err := NewServer(nil, profile, revalidationSecret, stub)
+ require.NoError(t, err)
+
+ e := echo.New()
+ s.RegisterRoutes(e)
+ ts := httptest.NewServer(e)
+ defer ts.Close()
+
+ transport := &forwardedTransport{
+ token: mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour),
+ }
+ first := "203.0.113.7"
+ transport.ip.Store(&first)
+
+ client := mcp.NewClient(&mcp.Implementation{Name: "probe", Version: "0"}, nil)
+ session, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{
+ Endpoint: ts.URL + "/mcp",
+ HTTPClient: &http.Client{Transport: transport},
+ MaxRetries: -1,
+ }, nil)
+ require.NoError(t, err)
+ defer session.Close()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ callTool := func() error {
+ _, err := session.CallTool(ctx, &mcp.CallToolParams{
+ Name: "call_api",
+ Arguments: map[string]any{"operationId": "SQLService/Query"},
+ })
+ return err
+ }
+
+ require.NoError(t, callTool())
+ require.Equal(t, first, *capturedIP.Load())
+
+ // The same client, same credential, now reaching us from a different address.
+ second := "198.51.100.22"
+ transport.ip.Store(&second)
+
+ require.NoError(t, callTool(), "an IP change must not end the session")
+ require.Equal(t, second, *capturedIP.Load(),
+ "audit must attribute the call to where it came from now, not to the session's first address")
+}
+
+// mintMCPToken mints an MCP OAuth2 access token bound to this deployment's
+// canonical resource URI.
+func mintMCPToken(t *testing.T, email, clientID, workspaceID, scope string, ttl time.Duration) string {
+ t.Helper()
+ token, err := auth.GenerateOAuth2AccessToken(email, clientID, workspaceID, "https://bb.example.com/mcp", scope, revalidationSecret, ttl)
+ require.NoError(t, err)
+ return token
+}
diff --git a/backend/api/mcp/internal_transport_test.go b/backend/api/mcp/internal_transport_test.go
new file mode 100644
index 0000000000..4fa572d51a
--- /dev/null
+++ b/backend/api/mcp/internal_transport_test.go
@@ -0,0 +1,257 @@
+package mcp
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/labstack/echo/v5"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/config"
+)
+
+// runAuthMiddleware pushes one authenticated request through authMiddleware and
+// returns a credential minted from the delegated identity the next handler
+// observed in context — the same thing apiRequest does on every internal call.
+func runAuthMiddleware(t *testing.T, s *Server, bearer string) (credential string, status int) {
+ t.Helper()
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+
+ handler := s.authMiddleware(func(c *echo.Context) error {
+ identity, ok := getDelegatedIdentity(c.Request().Context())
+ if ok {
+ minted, err := auth.GenerateInternalMCPToken(identity, s.secret)
+ require.NoError(t, err)
+ credential = minted
+ }
+ return c.String(http.StatusOK, "success")
+ })
+ if err := handler(c); err != nil {
+ echo.DefaultHTTPErrorHandler(true)(c, err)
+ }
+ return credential, rec.Code
+}
+
+// TestMCPAuthMiddlewareMintsDelegatedCredential pins the PR 4 boundary
+// behavior: every admitted /mcp request mints a fresh internal credential
+// carrying the principal, workspace, client_id, a correlation ID, and the
+// grant's stored scope + resource copied verbatim from the inbound token. The
+// inbound bearer is replaced, not wrapped.
+func TestMCPAuthMiddlewareMintsDelegatedCredential(t *testing.T) {
+ secret := "test-secret-key"
+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
+ s, err := NewServer(nil, profile, secret, nil)
+ require.NoError(t, err)
+
+ inbound, err := auth.GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", "https://bb.example.com/mcp", "mcp:read-only", secret, time.Hour)
+ require.NoError(t, err)
+
+ credential, status := runAuthMiddleware(t, s, inbound)
+ require.Equal(t, http.StatusOK, status)
+ require.NotEmpty(t, credential, "an admitted request must mint a delegated credential")
+ require.NotEqual(t, inbound, credential, "the credential replaces the inbound bearer, never wraps or reuses it")
+
+ cred, err := auth.VerifyInternalMCPToken(credential, secret)
+ require.NoError(t, err)
+ require.Equal(t, "[email protected]", cred.Principal)
+ require.Equal(t, "ws-test", cred.WorkspaceID)
+ require.Equal(t, "client-A", cred.ClientID)
+ require.NotEmpty(t, cred.CorrelationID)
+ require.Equal(t, "mcp:read-only", cred.Scope, "the grant's stored scope travels verbatim")
+ require.Equal(t, "https://bb.example.com/mcp", cred.Resource, "the resource-bound audience is the grant's stored resource")
+
+ // Minting is per MCP request: a second request gets its own credential and
+ // correlation ID.
+ second, status := runAuthMiddleware(t, s, inbound)
+ require.Equal(t, http.StatusOK, status)
+ secondCred, err := auth.VerifyInternalMCPToken(second, secret)
+ require.NoError(t, err)
+ require.NotEqual(t, cred.CorrelationID, secondCred.CorrelationID)
+}
+
+// TestMCPAuthMiddlewareLegacySessionEmptyGrantState pins that legacy sessions
+// keep working through tools: a plain bb.user.access web token and a legacy
+// bb.oauth2.access token both mint a credential from their principal with
+// EMPTY grant state — no scope, no resource. PR 5, not this PR, assigns their
+// synthetic LEGACY_FULL semantics.
+func TestMCPAuthMiddlewareLegacySessionEmptyGrantState(t *testing.T) {
+ secret := "test-secret-key"
+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
+ s, err := NewServer(nil, profile, secret, nil)
+ require.NoError(t, err)
+
+ for name, bearer := range map[string]string{
+ "plain user session token": generateUserAudienceToken(t, secret),
+ "legacy oauth2 mcp token": generateValidToken(t, secret),
+ "legacy oauth2 with client": generateOAuth2MCPToken(t, secret, "client-A", "ws-test"),
+ } {
+ t.Run(name, func(t *testing.T) {
+ credential, status := runAuthMiddleware(t, s, bearer)
+ require.Equal(t, http.StatusOK, status)
+ require.NotEmpty(t, credential)
+
+ cred, err := auth.VerifyInternalMCPToken(credential, secret)
+ require.NoError(t, err)
+ require.Equal(t, "[email protected]", cred.Principal)
+ require.Empty(t, cred.Scope, "legacy sessions have no stored grant scope")
+ require.Empty(t, cred.Resource, "a legacy fixed audience is not a grant resource")
+ require.NotEmpty(t, cred.CorrelationID)
+ })
+ }
+}
+
+// TestApiRequestMintsCredentialPerCall is the session-lifetime pin. The MCP SDK
+// hands every tool handler the context of the request that CREATED the session
+// (go-sdk v1.6.1 streamable.go: server.Connect(req.Context(), ...)), so anything
+// the boundary stashes in that context is frozen at session start. A credential
+// minted there would carry a fixed expiry and brick every tool call once its
+// short TTL elapsed — while the session stays open, since /mcp never re-runs
+// the middleware for it. Minting inside apiRequest instead keeps the TTL
+// genuinely request-scale: each internal call gets a freshly minted credential.
+func TestApiRequestMintsCredentialPerCall(t *testing.T) {
+ const secret = "test-secret-key"
+ var credentials []string
+ s := newTestServerWithMock(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ credentials = append(credentials, strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprint(w, `{}`)
+ }))
+ s.secret = secret
+
+ // The context a tool handler sees: the session's, established once.
+ ctx := withDelegatedIdentity(context.Background(), auth.DelegatedMCPCredential{
+ Principal: "[email protected]",
+ WorkspaceID: "ws-test",
+ CorrelationID: "corr-1",
+ })
+
+ _, err := s.apiRequest(ctx, "/api/test", nil)
+ require.NoError(t, err)
+ // JWT expiry has one-second resolution, so separate the calls enough that a
+ // call-time mint is observably later than a session-time one.
+ time.Sleep(1100 * time.Millisecond)
+ _, err = s.apiRequest(ctx, "/api/test", nil)
+ require.NoError(t, err)
+
+ require.Len(t, credentials, 2)
+ first, _, err := jwt.NewParser().ParseUnverified(credentials[0], jwt.MapClaims{})
+ require.NoError(t, err)
+ second, _, err := jwt.NewParser().ParseUnverified(credentials[1], jwt.MapClaims{})
+ require.NoError(t, err)
+ firstExp, err := first.Claims.GetExpirationTime()
+ require.NoError(t, err)
+ secondExp, err := second.Claims.GetExpirationTime()
+ require.NoError(t, err)
+ require.True(t, secondExp.After(firstExp.Time),
+ "each internal call must mint a fresh credential; a session-frozen one expires mid-session")
+
+ // Both must still be valid credentials carrying the session's identity.
+ for _, credential := range credentials {
+ cred, err := auth.VerifyInternalMCPToken(credential, secret)
+ require.NoError(t, err)
+ require.Equal(t, "[email protected]", cred.Principal)
+ require.Equal(t, "corr-1", cred.CorrelationID, "the boundary's correlation ID travels on every call")
+ }
+}
+
+// TestInternalRequestCarriesCallerIP pins that audit keeps seeing who made an
+// MCP-originated call. The audit interceptor derives caller IP from
+// X-Real-IP -> X-Forwarded-For -> peer address; on an in-memory request all
+// three are empty unless the boundary carries the inbound caller's IP forward,
+// so audit rows for MCP actions would record no origin at all. (The retired
+// loopback transport did no better: it recorded the 127.0.0.1 socket, never the
+// real client.)
+func TestInternalRequestCarriesCallerIP(t *testing.T) {
+ const secret = "test-secret-key"
+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
+
+ tests := []struct {
+ name string
+ headers map[string]string
+ remoteAddr string
+ want string
+ }{
+ {
+ name: "X-Real-IP wins",
+ headers: map[string]string{"X-Real-IP": "203.0.113.7", "X-Forwarded-For": "198.51.100.9"},
+ remoteAddr: "10.0.0.1:4444",
+ want: "203.0.113.7",
+ },
+ {
+ name: "X-Forwarded-For is next",
+ headers: map[string]string{"X-Forwarded-For": "198.51.100.9"},
+ remoteAddr: "10.0.0.1:4444",
+ want: "198.51.100.9",
+ },
+ {
+ name: "peer address is the fallback, without its port",
+ remoteAddr: "10.0.0.1:4444",
+ want: "10.0.0.1",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ var capturedIP string
+ stub := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ capturedIP = r.Header.Get("X-Real-IP")
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprint(w, `{}`)
+ })
+ s, err := NewServer(nil, profile, secret, stub)
+ require.NoError(t, err)
+
+ inbound, err := auth.GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", "https://bb.example.com/mcp", "mcp:read-only", secret, time.Hour)
+ require.NoError(t, err)
+
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))
+ req.Header.Set("Authorization", "Bearer "+inbound)
+ for k, v := range tc.headers {
+ req.Header.Set(k, v)
+ }
+ req.RemoteAddr = tc.remoteAddr
+ c := e.NewContext(req, httptest.NewRecorder())
+
+ handler := s.authMiddleware(func(c *echo.Context) error {
+ _, err := s.apiRequest(c.Request().Context(), "/api/test", nil)
+ return err
+ })
+ require.NoError(t, handler(c))
+ require.Equal(t, tc.want, capturedIP)
+ })
+ }
+}
+
+// TestMCPAuthMiddlewareRejectsInternalCredential is the /mcp half of the hard
+// boundary: the public /mcp listener must never accept the internal credential
+// it mints for the private transport. A leaked credential is useless here.
+func TestMCPAuthMiddlewareRejectsInternalCredential(t *testing.T) {
+ secret := "test-secret-key"
+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
+ s, err := NewServer(nil, profile, secret, nil)
+ require.NoError(t, err)
+
+ internal, err := auth.GenerateInternalMCPToken(auth.DelegatedMCPCredential{
+ Principal: "[email protected]",
+ WorkspaceID: "ws-test",
+ }, secret)
+ require.NoError(t, err)
+
+ credential, status := runAuthMiddleware(t, s, internal)
+ require.Equal(t, http.StatusUnauthorized, status)
+ require.Empty(t, credential, "the handler must not run for an internal credential")
+}
diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.go
index 21c69f2b8b..3af3134306 100644
--- a/backend/api/mcp/server.go
+++ b/backend/api/mcp/server.go
@@ -5,6 +5,7 @@ import (
"context"
"fmt"
"log/slog"
+ "net"
"net/http"
"strings"
"sync"
@@ -12,7 +13,9 @@ import (
"connectrpc.com/connect"
"github.com/golang-jwt/jwt/v5"
+ "github.com/google/uuid"
"github.com/labstack/echo/v5"
+ mcpauth "github.com/modelcontextprotocol/go-sdk/auth"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/pkg/errors"
@@ -27,12 +30,17 @@ import (
// Server is the MCP server for Bytebase.
type Server struct {
mcpServer *mcp.Server
- httpHandler *mcp.StreamableHTTPHandler
+ httpHandler http.Handler
store *store.Store
profile *config.Profile
secret string
openAPIIndex *OpenAPIIndex
+ // internalClient carries tool API calls to the internal handler chain over
+ // the private in-memory transport, authenticated by the delegated
+ // credential minted in authMiddleware.
+ internalClient *http.Client
+
revokedAccessTokens sync.Map // map[string]struct{}
// planCheckPollBudgetOverride lets tests shorten the plan-check poll budget.
@@ -40,8 +48,9 @@ type Server struct {
planCheckPollBudgetOverride time.Duration
}
-// NewServer creates a new MCP server.
-func NewServer(store *store.Store, profile *config.Profile, secret string) (*Server, error) {
+// NewServer creates a new MCP server. internalAPI is the internal API handler
+// chain tool calls dispatch to in memory; it is never bound to a listener.
+func NewServer(store *store.Store, profile *config.Profile, secret string, internalAPI http.Handler) (*Server, error) {
mcpServer := mcp.NewServer(&mcp.Implementation{
Name: "bytebase",
Version: profile.Version,
@@ -54,11 +63,12 @@ func NewServer(store *store.Store, profile *config.Profile, secret string) (*Ser
}
s := &Server{
- mcpServer: mcpServer,
- store: store,
- profile: profile,
- secret: secret,
- openAPIIndex: openAPIIndex,
+ mcpServer: mcpServer,
+ store: store,
+ profile: profile,
+ secret: secret,
+ openAPIIndex: openAPIIndex,
+ internalClient: newInternalAPIClient(internalAPI),
}
s.registerTools()
@@ -75,10 +85,28 @@ func NewServer(store *store.Store, profile *config.Profile, secret string) (*Ser
// the token — not network position — is the security boundary, and the
// rebinding threat targets unauthenticated, browser-reached localhost
// servers, which Bytebase is not.
- s.httpHandler = mcp.NewStreamableHTTPHandler(func(_ *http.Request) *mcp.Server {
+ streamable := mcp.NewStreamableHTTPHandler(func(_ *http.Request) *mcp.Server {
return s.mcpServer
}, &mcp.StreamableHTTPOptions{DisableLocalhostProtection: true})
+ // Refresh per-request metadata that would otherwise be frozen at session
+ // start. The SDK runs tool handlers on the initialize request's context, but
+ // hands each JSON-RPC request's own HTTP headers to receiving middleware, so
+ // this is where a long-lived session picks up where its current request came
+ // from. Identity stays pinned to the session (see below), which is what
+ // makes trusting the live address safe: it cannot belong to another
+ // principal.
+ mcpServer.AddReceivingMiddleware(liveRequestMetadata)
+
+ // Pin each session to the identity it was opened with. The SDK captures
+ // TokenInfo.UserID when a session is created and rejects later requests
+ // carrying a different one, but only when a TokenInfo reaches it — and the
+ // context key is settable solely through this middleware. Without it the
+ // check is inert, and since tool handlers run on the initialize request's
+ // context, a substituted-but-valid bearer would be admitted while the tool
+ // executed under the session's original identity.
+ s.httpHandler = mcpauth.RequireBearerToken(s.verifySessionBinding, nil)(streamable)
+
return s, nil
}
@@ -139,28 +167,11 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return s.unauthorized(c, "invalid token")
}
- // Extract user email from subject
- sub, ok := claims["sub"].(string)
- if !ok || sub == "" {
- return s.unauthorized(c, "invalid token: missing subject")
- }
- clientID, ok := claims["client_id"].(string)
- if !ok {
- clientID = ""
- }
-
- // Extract workspace ID from token claims. Read before the audience
- // check because resolving the expected audience needs the workspace to
- // look up the trusted external URL.
- workspaceID, ok := claims["workspace_id"].(string)
- if !ok {
- workspaceID = ""
- }
-
- aud, ok := claims["aud"]
- if !ok {
- return s.unauthorized(c, "invalid token: missing audience")
+ identity, errMsg := extractTokenIdentity(claims)
+ if errMsg != "" {
+ return s.unauthorized(c, errMsg)
}
+ sub, clientID, workspaceID, aud := identity.sub, identity.clientID, identity.workspaceID, identity.aud
allowed, err := s.audienceAllowed(c.Request().Context(), aud, workspaceID)
if err != nil {
// Infra failure reading the trusted config, not a verdict on the
@@ -182,12 +193,40 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return echo.NewHTTPError(http.StatusForbidden, "MCP access is disabled for this workspace by policy")
}
+ // Establish the delegated identity that carries this request's principal
+ // and grant state onto the private in-memory transport. The inbound
+ // bearer stops at this boundary: internal API requests mint their own
+ // credential from this identity and never see the bearer. Grant state is
+ // copied verbatim from the inbound token — empty for legacy sessions (PR
+ // 5 assigns their synthetic LEGACY_FULL semantics). Identity only, no
+ // roles: downstream authorization re-resolves live exactly as for a
+ // public request.
+ delegated := auth.DelegatedMCPCredential{
+ Principal: sub,
+ WorkspaceID: workspaceID,
+ ClientID: clientID,
+ CorrelationID: uuid.NewString(),
+ Scope: grantScope(claims),
+ Resource: grantResource(claims, aud),
+ }
+
// Store access token and workspace ID in request context for MCP tools.
ctx := c.Request().Context()
ctx = withAccessToken(ctx, tokenStr)
ctx = withUserEmail(ctx, sub)
ctx = withOAuth2ClientID(ctx, clientID)
ctx = withWorkspaceID(ctx, workspaceID)
+ ctx = withDelegatedIdentity(ctx, delegated)
+ // Normalize the resolved address onto the request so the per-request
+ // path sees it too: receiving middleware gets each request's headers,
+ // but never its peer address.
+ resolvedIP := callerIP(c.Request())
+ c.Request().Header.Set(headerRealIP, resolvedIP)
+ ctx = withCallerIP(ctx, resolvedIP)
+ ctx = withSessionBinding(ctx, sessionBinding{
+ fingerprint: sessionFingerprint(delegated),
+ expiry: bearerExpiry(claims),
+ })
c.SetRequest(c.Request().WithContext(ctx))
return next(c)
@@ -200,6 +239,12 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
// the same name in the oauth2 package, which stores that URI on the grant).
const mcpResourcePath = "/mcp"
+// Caller-IP headers, in the precedence the audit interceptor reads them.
+const (
+ headerRealIP = "X-Real-IP"
+ headerForwardedFor = "X-Forwarded-For"
+)
+
// RegisterRoutes registers the MCP server routes with Echo.
func (s *Server) RegisterRoutes(e *echo.Echo) {
// MCP Streamable HTTP endpoint with authentication
@@ -293,6 +338,192 @@ func (s *Server) expectedMCPAudience(ctx context.Context, workspaceID string) (s
return externalURL + mcpResourcePath, nil
}
+// sessionFingerprint is the identity a /mcp session is pinned to for its whole
+// life. Two bearers may drive the same session only if they agree on every
+// field: principal, workspace, OAuth client, and the grant's stored resource
+// and scope.
+//
+// Substituting any of them is a different session: another user's token would
+// otherwise execute as the session's principal, a token for another workspace
+// would sidestep the kill switch on the session's own workspace, and a
+// re-consented grant would keep riding the state consented earlier. The
+// correlation ID is deliberately excluded — it is per request, not per session.
+//
+// The separator cannot appear in any component, so distinct identities cannot
+// collide by concatenation.
+func sessionFingerprint(identity auth.DelegatedMCPCredential) string {
+ return strings.Join([]string{
+ identity.Principal,
+ identity.WorkspaceID,
+ identity.ClientID,
+ identity.Resource,
+ identity.Scope,
+ }, "\x00")
+}
+
+// liveRequestMetadata overlays the current request's caller IP and bearer onto
+// the context the tool handler runs with. Tool handlers otherwise see only what
+// the session was opened with, which goes stale in two ways that matter:
+//
+// - the caller IP, so a client that changed network mid-session would have
+// every later action audited against its first address; and
+// - the bearer, so reauthorize would revoke the token the caller already
+// replaced by refreshing, leaving the one in its hand working until expiry.
+//
+// The headers come from the live JSON-RPC request. authMiddleware has already
+// normalized the peer address into X-Real-IP, so a direct connection resolves
+// here too, and it has already validated the bearer, so this only carries a
+// value that was accepted moments ago. If a request arrives without them, the
+// session's values stand.
+func liveRequestMetadata(next mcp.MethodHandler) mcp.MethodHandler {
+ return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
+ if extra := req.GetExtra(); extra != nil && extra.Header != nil {
+ if ip := headerCallerIP(extra.Header); ip != "" {
+ ctx = withCallerIP(ctx, ip)
+ }
+ if token, err := auth.GetTokenFromHeaders(extra.Header); err == nil && token != "" {
+ ctx = withAccessToken(ctx, token)
+ }
+ }
+ return next(ctx, method, req)
+ }
+}
+
+// headerCallerIP reads the caller IP from request headers, in the order the
+// audit interceptor applies: the proxy-set single IP first, then the standard
+// forwarding chain.
+func headerCallerIP(header http.Header) string {
+ if ip := header.Get(headerRealIP); ip != "" {
+ return ip
+ }
+ return header.Get(headerForwardedFor)
+}
+
+// callerIP resolves who made this /mcp request: the forwarding headers if
+// present, otherwise the peer address, whose port is dropped so the value reads
+// as an IP either way. Same precedence the audit interceptor applies to a
+// request that reaches the v1 API directly.
+//
+// The forwarding headers are client-controllable, exactly as they are on that
+// direct path. Reading them preserves the existing trust model rather than
+// introducing one.
+func callerIP(r *http.Request) string {
+ if ip := headerCallerIP(r.Header); ip != "" {
+ return ip
+ }
+ if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
+ return host
+ }
+ return r.RemoteAddr
+}
+
+// bearerExpiry reads the inbound token's expiry. The JWT parse upstream has
+// already rejected expired and malformed tokens, so this only re-surfaces the
+// value for the SDK, which requires a non-zero future expiration.
+func bearerExpiry(claims jwt.MapClaims) time.Time {
+ exp, err := claims.GetExpirationTime()
+ if err != nil || exp == nil {
+ return time.Time{}
+ }
+ return exp.Time
+}
+
+// verifySessionBinding hands the SDK the identity behind the current request so
+// it can enforce session ownership. The bearer itself was already validated by
+// authMiddleware, which runs first and puts the resolved identity on the
+// request context; this only translates that into the SDK's shape.
+func (*Server) verifySessionBinding(_ context.Context, _ string, req *http.Request) (*mcpauth.TokenInfo, error) {
+ binding, ok := getSessionBinding(req.Context())
+ if !ok {
+ // Unreachable through the registered route: authMiddleware establishes
+ // the binding before this runs. Fail closed rather than leave a session
+ // unpinned if that ever stops being true.
+ return nil, mcpauth.ErrInvalidToken
+ }
+ return &mcpauth.TokenInfo{
+ UserID: binding.fingerprint,
+ Expiration: binding.expiry,
+ }, nil
+}
+
+// tokenIdentity is the identity material authMiddleware works with after a
+// token verifies: subject, optional client and workspace, and the audience.
+// The workspace is extracted before the audience check because resolving the
+// expected audience needs it to look up the trusted external URL.
+type tokenIdentity struct {
+ sub string
+ clientID string
+ workspaceID string
+ aud any
+}
+
+// extractTokenIdentity pulls the identity claims out of a verified token. A
+// missing subject or audience is a token defect (non-empty error message);
+// client_id and workspace_id are optional.
+func extractTokenIdentity(claims jwt.MapClaims) (*tokenIdentity, string) {
+ sub, ok := claims["sub"].(string)
+ if !ok || sub == "" {
+ return nil, "invalid token: missing subject"
+ }
+ aud, ok := claims["aud"]
+ if !ok {
+ return nil, "invalid token: missing audience"
+ }
+ identity := &tokenIdentity{sub: sub, aud: aud}
+ if clientID, ok := claims["client_id"].(string); ok {
+ identity.clientID = clientID
+ }
+ if workspaceID, ok := claims["workspace_id"].(string); ok {
+ identity.workspaceID = workspaceID
+ }
+ return identity, ""
+}
+
+// grantScope extracts the grant's stored scope from the inbound token's claims.
+// The scope claim is minted onto OAuth2 access tokens verbatim from the grant;
+// legacy tokens (plain sessions, pre-scope OAuth2) have none — empty grant
+// state, by design.
+func grantScope(claims jwt.MapClaims) string {
+ if scope, ok := claims["scope"].(string); ok {
+ return scope
+ }
+ return ""
+}
+
+// grantResource extracts the grant's stored resource from the inbound token.
+// For MCP OAuth2 tokens the resource-bound audience IS the stored resource
+// (PR 3 mints it from the grant verbatim). The legacy fixed audiences are not
+// resources, so legacy tokens yield empty grant state.
+//
+// Resource is therefore what distinguishes the two kinds of empty scope, and PR
+// 5 must key on it: a token minted by a PR-3-era replica during the upgrade
+// window is resource-bound but predates the scope claim, so it arrives with a
+// resource and no scope even though its grant DID record a consented scope.
+// Treating that as the synthetic LEGACY_FULL grant would silently widen a
+// read-only session to workspace admin. Genuinely pre-grant sessions carry
+// neither.
+func grantResource(claims jwt.MapClaims, aud any) string {
+ tokenUse, ok := claims["token_use"].(string)
+ if !ok || tokenUse != auth.TokenUseMCP {
+ return ""
+ }
+ if audienceMatches(aud, auth.OAuth2AccessTokenAudience) || audienceMatches(aud, auth.AccessTokenAudience) {
+ return ""
+ }
+ switch v := aud.(type) {
+ case string:
+ return v
+ case []any:
+ for _, a := range v {
+ if str, ok := a.(string); ok {
+ return str
+ }
+ }
+ default:
+ }
+ return ""
+}
+
// audienceMatches reports whether a JWT aud claim (string or array form)
// contains exactly want.
func audienceMatches(aud any, want string) bool {
diff --git a/backend/api/mcp/server_killswitch_test.go b/backend/api/mcp/server_killswitch_test.go
index b86f8b425f..18dd1b893d 100644
--- a/backend/api/mcp/server_killswitch_test.go
+++ b/backend/api/mcp/server_killswitch_test.go
@@ -82,7 +82,7 @@ func TestMCPKillSwitchEndToEnd(t *testing.T) {
secret := "test-secret-key"
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
- srv, err := NewServer(s, profile, secret)
+ srv, err := NewServer(s, profile, secret, nil)
require.NoError(t, err)
statusFor := func(workspaceID string) int {
@@ -144,7 +144,7 @@ func TestMCPKillSwitchBypassesSettingCache(t *testing.T) {
secret := "test-secret-key"
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
- srv, err := NewServer(s, profile, secret)
+ srv, err := NewServer(s, profile, secret, nil)
require.NoError(t, err)
statusFor := func() int {
diff --git a/backend/api/mcp/server_test.go b/backend/api/mcp/server_test.go
index 50901a09ae..f8262d266b 100644
--- a/backend/api/mcp/server_test.go
+++ b/backend/api/mcp/server_test.go
@@ -77,7 +77,7 @@ func TestMCPAuthMiddleware(t *testing.T) {
c := e.NewContext(req, rec)
// Create server with auth
- s, err := NewServer(nil, profile, secret)
+ s, err := NewServer(nil, profile, secret, nil)
require.NoError(t, err)
handler := s.authMiddleware(func(c *echo.Context) error {
return c.String(http.StatusOK, "success")
@@ -135,7 +135,7 @@ func TestMCPAuthMiddlewareValidToken(t *testing.T) {
// Create server with auth - note: we pass nil store since we're testing middleware only
// A full integration test would require a real store
- s, err := NewServer(nil, profile, secret)
+ s, err := NewServer(nil, profile, secret, nil)
require.NoError(t, err)
handler := s.authMiddleware(func(c *echo.Context) error {
// Verify access token is set in request context
@@ -161,7 +161,7 @@ func TestMCPAuthMiddlewareOAuthContext(t *testing.T) {
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
- s, err := NewServer(nil, profile, secret)
+ s, err := NewServer(nil, profile, secret, nil)
require.NoError(t, err)
handler := s.authMiddleware(func(c *echo.Context) error {
ctx := c.Request().Context()
@@ -192,7 +192,7 @@ func TestMCPProxiedPublicHostNotRejected(t *testing.T) {
secret := "test-secret-key"
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
- s, err := NewServer(nil, profile, secret)
+ s, err := NewServer(nil, profile, secret, nil)
require.NoError(t, err)
e := echo.New()
@@ -231,7 +231,7 @@ func TestMCPUnauthenticatedRejectedEndToEnd(t *testing.T) {
secret := "test-secret-key"
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
- s, err := NewServer(nil, profile, secret)
+ s, err := NewServer(nil, profile, secret, nil)
require.NoError(t, err)
e := echo.New()
@@ -265,7 +265,7 @@ func TestMCPAuthMiddlewareAudienceMatrix(t *testing.T) {
mintResourceToken := func(t *testing.T, resource string) string {
t.Helper()
- token, err := auth.GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", resource, secret, time.Hour)
+ token, err := auth.GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", resource, "", secret, time.Hour)
require.NoError(t, err)
return token
}
@@ -321,7 +321,7 @@ func TestMCPAuthMiddlewareAudienceMatrix(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: tc.externalURL}
- s, err := NewServer(nil, profile, secret)
+ s, err := NewServer(nil, profile, secret, nil)
require.NoError(t, err)
e := echo.New()
diff --git a/backend/api/mcp/tool_http.go b/backend/api/mcp/tool_http.go
index 07b500939e..9c72dd84c9 100644
--- a/backend/api/mcp/tool_http.go
+++ b/backend/api/mcp/tool_http.go
@@ -6,10 +6,15 @@ import (
"encoding/json"
"fmt"
"io"
+ "log/slog"
"net/http"
"time"
"github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/common/stacktrace"
)
// apiResponse holds the HTTP response from an internal API call.
@@ -19,8 +24,17 @@ type apiResponse struct {
Headers http.Header
}
-// apiRequest executes an HTTP POST to an internal Bytebase API endpoint.
-// It handles URL building, auth forwarding, Connect-RPC headers, and JSON marshaling.
+// internalAPIBaseURL is the nominal URL of the internal API handler chain. The
+// in-memory transport never dials it — it exists only to satisfy http.Request.
+const internalAPIBaseURL = "https://mcp-internal.bytebase.invalid"
+
+// internalAPIUserAgent identifies MCP-originated calls in audit records.
+const internalAPIUserAgent = "bytebase-mcp/internal"
+
+// apiRequest executes a Connect-RPC POST against the internal API handler
+// chain. Requests ride the private in-memory transport and authenticate with
+// the delegated credential minted at the /mcp boundary — never the inbound
+// bearer, which stops at that boundary (P1a PR 4).
func (s *Server) apiRequest(ctx context.Context, path string, body any) (*apiResponse, error) {
var bodyBytes []byte
var err error
@@ -33,21 +47,42 @@ func (s *Server) apiRequest(ctx context.Context, path string, body any) (*apiRes
bodyBytes = []byte("{}")
}
- url := fmt.Sprintf("http://localhost:%d%s", s.profile.Port, path)
- httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(bodyBytes))
+ // Per-request bound via the context (not http.Client.Timeout, whose cancel
+ // machinery only reaches the standard transport; the in-memory transport
+ // honors context cancellation).
+ ctx, cancel := context.WithTimeout(ctx, internalAPITimeout)
+ defer cancel()
+
+ httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, internalAPIBaseURL+path, bytes.NewReader(bodyBytes))
if err != nil {
return nil, errors.Wrap(err, "failed to create HTTP request")
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Connect-Protocol-Version", "1")
+ // The in-memory transport adds no User-Agent of its own (net/http writes one
+ // only when marshaling to the wire), and the audit interceptor records the
+ // header. Name the surface explicitly rather than let audit rows for MCP
+ // actions go blank.
+ httpReq.Header.Set("User-Agent", internalAPIUserAgent)
+ // Audit derives the caller IP from X-Real-IP first. An in-memory request has
+ // no peer address to fall back to, so without this the origin of every
+ // MCP-originated action would be blank.
+ if ip := getCallerIP(ctx); ip != "" {
+ httpReq.Header.Set(headerRealIP, ip)
+ }
- if token := getAccessToken(ctx); token != "" {
- httpReq.Header.Set("Authorization", "Bearer "+token)
+ // Mint the credential for this call. Per call, not per session: see
+ // delegatedIdentityKey.
+ if identity, ok := getDelegatedIdentity(ctx); ok {
+ credential, err := auth.GenerateInternalMCPToken(identity, s.secret)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to mint the delegated credential")
+ }
+ httpReq.Header.Set("Authorization", "Bearer "+credential)
}
- client := &http.Client{Timeout: 30 * time.Second}
- resp, err := client.Do(httpReq)
+ resp, err := s.internalClient.Do(httpReq)
if err != nil {
return nil, errors.Wrap(err, "failed to execute API request")
}
@@ -65,6 +100,106 @@ func (s *Server) apiRequest(ctx context.Context, path string, body any) (*apiRes
}, nil
}
+// internalAPITimeout bounds one internal API call, matching the 30s
+// http.Client timeout of the retired loopback transport.
+const internalAPITimeout = 30 * time.Second
+
+// newInternalAPIClient builds the HTTP client for the private transport. Its
+// RoundTripper dispatches directly to the internal handler chain in memory, so
+// internal requests — and the delegated credential they carry — never touch a
+// socket.
+func newInternalAPIClient(handler http.Handler) *http.Client {
+ return &http.Client{
+ Transport: &internalRoundTripper{handler: handler},
+ }
+}
+
+// internalRoundTripper serves each request with the internal handler chain
+// in-process instead of dialing anything.
+type internalRoundTripper struct {
+ handler http.Handler
+}
+
+func (t *internalRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
+ if t.handler == nil {
+ return nil, errors.New("internal MCP API transport is not configured")
+ }
+ if req.Body != nil {
+ defer req.Body.Close()
+ }
+ rec := &responseRecorder{header: make(http.Header), status: http.StatusOK}
+ // Serve on a goroutine so cancellation aborts the call like a dropped
+ // connection would on a real transport. An abandoned handler keeps running
+ // until it observes req.Context() itself — the same semantics a server
+ // gives a disconnected client — and nothing reads its recorder afterwards.
+ //
+ // Recover here as well: on a real listener net/http contains a panic that
+ // escapes the handler, and the retired loopback transport had echo's
+ // recover middleware on top of that. Without this, such a panic would take
+ // the process down. connect's own WithRecover handles panics inside the
+ // RPC; this covers everything outside it (routing, unknown paths).
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ defer func() {
+ if p := recover(); p != nil {
+ stack := stacktrace.TakeStacktrace(20 /* n */, 3 /* skip */)
+ slog.Error("internal MCP transport panic", "path", req.URL.Path,
+ log.BBError(errors.Errorf("error: %v\n%s", p, stack)))
+ rec.panicked = true
+ }
+ }()
+ t.handler.ServeHTTP(rec, req)
+ }()
+ select {
+ case <-req.Context().Done():
+ return nil, req.Context().Err()
+ case <-done:
+ }
+ if rec.panicked {
+ return nil, errors.New("internal API request panicked")
+ }
+ return &http.Response{
+ StatusCode: rec.status,
+ Status: fmt.Sprintf("%d %s", rec.status, http.StatusText(rec.status)),
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ Header: rec.header,
+ Body: io.NopCloser(bytes.NewReader(rec.body.Bytes())),
+ ContentLength: int64(rec.body.Len()),
+ Request: req,
+ }, nil
+}
+
+// responseRecorder is the minimal in-memory http.ResponseWriter behind the
+// internal transport (net/http/httptest is test-only). Connect unary responses
+// are fully buffered, which is all the tools need.
+type responseRecorder struct {
+ header http.Header
+ body bytes.Buffer
+ status int
+ wroteHeader bool
+ panicked bool
+}
+
+func (r *responseRecorder) Header() http.Header {
+ return r.header
+}
+
+func (r *responseRecorder) Write(b []byte) (int, error) {
+ r.wroteHeader = true
+ return r.body.Write(b)
+}
+
+func (r *responseRecorder) WriteHeader(status int) {
+ if r.wroteHeader {
+ return
+ }
+ r.wroteHeader = true
+ r.status = status
+}
+
// parseError extracts the error message from an API error response body.
func parseError(body json.RawMessage) string {
var errMap map[string]any
@@ -110,6 +245,66 @@ func getAccessToken(ctx context.Context) string {
return ""
}
+// Context key for the delegated identity established at the /mcp boundary.
+// Internal API requests mint their credential from this — never from the
+// inbound access token, which stops at the boundary.
+//
+// The context carries the identity, not a minted credential, because the MCP
+// SDK hands every tool handler the context of the request that CREATED the
+// session. A credential minted at the boundary would therefore be frozen at
+// session start, and its request-scale TTL would expire mid-session while the
+// session stayed open.
+type delegatedIdentityKey struct{}
+
+// withDelegatedIdentity adds the delegated identity to the context.
+func withDelegatedIdentity(ctx context.Context, identity auth.DelegatedMCPCredential) context.Context {
+ return context.WithValue(ctx, delegatedIdentityKey{}, identity)
+}
+
+// getDelegatedIdentity retrieves the delegated identity from the context.
+func getDelegatedIdentity(ctx context.Context) (auth.DelegatedMCPCredential, bool) {
+ identity, ok := ctx.Value(delegatedIdentityKey{}).(auth.DelegatedMCPCredential)
+ return identity, ok
+}
+
+// Context key for the inbound caller's IP, carried onto internal requests so
+// audit records where an MCP-originated action actually came from.
+type callerIPKey struct{}
+
+// withCallerIP adds the inbound caller's IP to the context.
+func withCallerIP(ctx context.Context, ip string) context.Context {
+ return context.WithValue(ctx, callerIPKey{}, ip)
+}
+
+// getCallerIP retrieves the inbound caller's IP from the context.
+func getCallerIP(ctx context.Context) string {
+ if ip, ok := ctx.Value(callerIPKey{}).(string); ok {
+ return ip
+ }
+ return ""
+}
+
+// Context key for the session binding: the identity fingerprint the /mcp
+// session is pinned to, plus the bearer's own expiry. Established per request
+// by authMiddleware and read by the SDK session-ownership check.
+type sessionBindingKey struct{}
+
+type sessionBinding struct {
+ fingerprint string
+ expiry time.Time
+}
+
+// withSessionBinding adds the session binding to the context.
+func withSessionBinding(ctx context.Context, binding sessionBinding) context.Context {
+ return context.WithValue(ctx, sessionBindingKey{}, binding)
+}
+
+// getSessionBinding retrieves the session binding from the context.
+func getSessionBinding(ctx context.Context) (sessionBinding, bool) {
+ binding, ok := ctx.Value(sessionBindingKey{}).(sessionBinding)
+ return binding, ok
+}
+
// Context key for storing the authenticated user email.
type userEmailKey struct{}
diff --git a/backend/api/mcp/tool_http_test.go b/backend/api/mcp/tool_http_test.go
index 9572dc27d3..f2f5d64285 100644
--- a/backend/api/mcp/tool_http_test.go
+++ b/backend/api/mcp/tool_http_test.go
@@ -4,44 +4,94 @@ import (
"context"
"encoding/json"
"fmt"
+ "io"
"net/http"
- "net/http/httptest"
- "strconv"
"strings"
"testing"
"github.com/stretchr/testify/require"
+ "github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/component/config"
)
-// newTestServerWithMock creates a *Server backed by a mock HTTP server.
-// The mock server is automatically closed when the test completes.
+// newTestServerWithMock creates a *Server whose internal transport dispatches
+// to the given handler in memory — the same shape production uses, no socket.
func newTestServerWithMock(t *testing.T, handler http.Handler) *Server {
t.Helper()
- mock := httptest.NewServer(handler)
- t.Cleanup(mock.Close)
- // Parse port from URL like "http://127.0.0.1:PORT".
- parts := strings.Split(mock.URL, ":")
- port, _ := strconv.Atoi(parts[len(parts)-1])
return &Server{
- profile: &config.Profile{Port: port},
+ profile: &config.Profile{},
+ internalClient: newInternalAPIClient(handler),
}
}
-func TestApiRequest_AuthForwarding(t *testing.T) {
+// TestApiRequest_DelegatedCredentialReplacesInboundBearer is the PR 4
+// bearer-elimination pin, replacing the retired TestApiRequest_AuthForwarding
+// (which asserted the loopback design: the inbound bearer forwarded verbatim).
+// Internal requests carry the minted delegated credential, and the inbound
+// bearer string must not appear anywhere in the request.
+func TestApiRequest_DelegatedCredentialReplacesInboundBearer(t *testing.T) {
+ const inboundBearer = "inbound-public-bearer-token"
var capturedAuth string
+ var capturedHeaders http.Header
s := newTestServerWithMock(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedAuth = r.Header.Get("Authorization")
+ capturedHeaders = r.Header.Clone()
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, `{}`)
}))
- ctx := withAccessToken(context.Background(), "test-token-123")
+ s.secret = "test-secret-key"
+ ctx := withAccessToken(context.Background(), inboundBearer)
+ ctx = withDelegatedIdentity(ctx, auth.DelegatedMCPCredential{
+ Principal: "[email protected]",
+ WorkspaceID: "ws-test",
+ CorrelationID: "corr-1",
+ })
resp, err := s.apiRequest(ctx, "/api/test", nil)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Status)
- require.Equal(t, "Bearer test-token-123", capturedAuth)
+
+ // Assert on the test goroutine: the handler ran on the transport's.
+ for name, values := range capturedHeaders {
+ for _, v := range values {
+ require.NotContains(t, v, inboundBearer,
+ "inbound bearer leaked into internal request header %s", name)
+ }
+ }
+
+ credential := strings.TrimPrefix(capturedAuth, "Bearer ")
+ require.NotEqual(t, capturedAuth, credential, "internal requests must carry a bearer credential")
+ cred, err := auth.VerifyInternalMCPToken(credential, s.secret)
+ require.NoError(t, err)
+ require.Equal(t, "[email protected]", cred.Principal)
+}
+
+// TestApiRequest_InMemoryDispatch pins the transport shape: the request
+// reaches the internal handler with its connect headers and body intact, and
+// the response round-trips — all without a listener.
+func TestApiRequest_InMemoryDispatch(t *testing.T) {
+ var capturedPath, capturedProto, capturedContentType string
+ var capturedBody []byte
+ s := newTestServerWithMock(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ capturedPath = r.URL.Path
+ capturedProto = r.Header.Get("Connect-Protocol-Version")
+ capturedContentType = r.Header.Get("Content-Type")
+ capturedBody, _ = io.ReadAll(r.Body)
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprint(w, `{"ok":true}`)
+ }))
+
+ resp, err := s.apiRequest(context.Background(), "/bytebase.v1.SQLService/Query", map[string]any{"statement": "SELECT 1"})
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, resp.Status)
+ require.Equal(t, "/bytebase.v1.SQLService/Query", capturedPath)
+ require.Equal(t, "1", capturedProto)
+ require.Equal(t, "application/json", capturedContentType)
+ require.JSONEq(t, `{"statement":"SELECT 1"}`, string(capturedBody))
+ require.JSONEq(t, `{"ok":true}`, string(resp.Body))
+ require.Equal(t, "application/json", resp.Headers.Get("Content-Type"))
}
func TestApiRequest_ErrorParsing(t *testing.T) {
diff --git a/backend/api/mcp/tool_reauthorize.go b/backend/api/mcp/tool_reauthorize.go
index 0868efd993..0b6e116995 100644
--- a/backend/api/mcp/tool_reauthorize.go
+++ b/backend/api/mcp/tool_reauthorize.go
@@ -35,6 +35,12 @@ func (s *Server) handleReauthorize(ctx context.Context, _ *mcp.CallToolRequest,
if err := s.store.DeleteOAuth2RefreshTokensByUserAndClient(ctx, userEmail, clientID); err != nil {
return formatToolError(errors.Wrap(err, "failed to revoke OAuth refresh tokens")), nil, nil
}
+ // This is the bearer on the request being served, not the one the session
+ // was opened with (liveRequestMetadata overlays it), so a caller that
+ // refreshed mid-session revokes the token it actually holds. Tokens minted
+ // earlier for the same grant are not listed here; they expire on their own,
+ // and the refresh grants deleted above stop any more being issued.
+ //
// MCP sessions are currently process-local and already require requests to
// stay on the same replica. This marker follows that constraint. If MCP gains
// multi-replica session support, move the reauthorization state to shared storage.
diff --git a/backend/api/mcp/tool_reauthorize_test.go b/backend/api/mcp/tool_reauthorize_test.go
index c871151fca..fde55f7a72 100644
--- a/backend/api/mcp/tool_reauthorize_test.go
+++ b/backend/api/mcp/tool_reauthorize_test.go
@@ -10,6 +10,7 @@ import (
"time"
"github.com/labstack/echo/v5"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/stretchr/testify/require"
"github.com/bytebase/bytebase/backend/api/auth"
@@ -23,8 +24,11 @@ import (
_ "github.com/bytebase/bytebase/backend/plugin/db/pg"
)
-func TestReauthorizeRejectsCurrentAccessToken(t *testing.T) {
- ctx := context.Background()
+// newReauthorizeTestServer boots a store-backed MCP server with one OAuth2
+// client, one principal, and one live refresh grant — the state the reauthorize
+// tool operates on.
+func newReauthorizeTestServer(ctx context.Context, t *testing.T) (*Server, *store.Store, string) {
+ t.Helper()
container := testcontainer.GetTestPgContainer(ctx, t)
t.Cleanup(func() { container.Close(ctx) })
@@ -56,34 +60,89 @@ func TestReauthorizeRejectsCurrentAccessToken(t *testing.T) {
})
require.NoError(t, err)
- const secret = "test-secret-key"
- s, err := NewServer(st, &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}, secret)
+ s, err := NewServer(st, &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}, revalidationSecret, nil)
require.NoError(t, err)
+ return s, st, refreshToken
+}
+
+// probeAuthMiddleware reports the status the /mcp boundary gives a bearer.
+func probeAuthMiddleware(t *testing.T, s *Server, bearer string) int {
+ t.Helper()
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+ handler := s.authMiddleware(func(c *echo.Context) error {
+ return c.String(http.StatusOK, "success")
+ })
+ if err := handler(c); err != nil {
+ echo.DefaultHTTPErrorHandler(true)(c, err)
+ }
+ return rec.Code
+}
+
+func TestReauthorizeRejectsCurrentAccessToken(t *testing.T) {
+ ctx := context.Background()
+ s, st, refreshToken := newReauthorizeTestServer(ctx, t)
+ const secret = revalidationSecret
accessToken := generateOAuth2MCPToken(t, secret, "client-A", "ws-test")
reauthorizeCtx := withAccessToken(ctx, accessToken)
reauthorizeCtx = withUserEmail(reauthorizeCtx, "[email protected]")
reauthorizeCtx = withOAuth2ClientID(reauthorizeCtx, "client-A")
reauthorizeCtx = withWorkspaceID(reauthorizeCtx, "ws-test")
- _, _, err = s.handleReauthorize(reauthorizeCtx, nil, ReauthorizeInput{})
+ _, _, err := s.handleReauthorize(reauthorizeCtx, nil, ReauthorizeInput{})
require.NoError(t, err)
stored, err := st.GetOAuth2RefreshToken(ctx, "client-A", auth.HashToken(refreshToken))
require.NoError(t, err)
require.Nil(t, stored)
+ require.Equal(t, http.StatusUnauthorized, probeAuthMiddleware(t, s, accessToken))
+}
+
+// TestReauthorizeRejectsRefreshedAccessToken pins that reauthorize revokes the
+// bearer the caller is actually holding.
+//
+// Tool handlers run on the initialize request's context, so a token read from
+// that context is the one the session was opened with. A client that refreshed
+// mid-session (same identity, so the session survives by design) would have
+// reauthorize revoke the token it already discarded, while the token it is
+// using keeps passing the boundary until it expires — deleting the refresh
+// grants but never producing the OAuth challenge the tool promises.
+func TestReauthorizeRejectsRefreshedAccessToken(t *testing.T) {
+ ctx := context.Background()
+ s, _, _ := newReauthorizeTestServer(ctx, t)
+
e := echo.New()
- req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))
- req.Header.Set("Authorization", "Bearer "+accessToken)
- rec := httptest.NewRecorder()
- c := e.NewContext(req, rec)
- handler := s.authMiddleware(func(c *echo.Context) error {
- return c.String(http.StatusOK, "success")
- })
- if err := handler(c); err != nil {
- echo.DefaultHTTPErrorHandler(true)(c, err)
- }
+ s.RegisterRoutes(e)
+ ts := httptest.NewServer(e)
+ defer ts.Close()
+
+ // Same identity, so the refreshed token keeps the session alive.
+ opened := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour)
+ refreshed := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", 2*time.Hour)
+ require.NotEqual(t, opened, refreshed)
+
+ transport := &swappingTransport{}
+ transport.token.Store(&opened)
+ client := mcp.NewClient(&mcp.Implementation{Name: "probe", Version: "0"}, nil)
+ session, err := client.Connect(ctx, &mcp.StreamableClientTransport{
+ Endpoint: ts.URL + "/mcp",
+ HTTPClient: &http.Client{Transport: transport},
+ MaxRetries: -1,
+ }, nil)
+ require.NoError(t, err)
+ defer session.Close()
+
+ transport.token.Store(&refreshed)
+ callCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ result, err := session.CallTool(callCtx, &mcp.CallToolParams{Name: "reauthorize"})
+ require.NoError(t, err)
+ require.False(t, result.IsError, "reauthorize must succeed: %v", result.Content)
- require.Equal(t, http.StatusUnauthorized, rec.Code)
- require.Contains(t, rec.Header().Get("WWW-Authenticate"), `error="invalid_token"`)
+ require.Equal(t, http.StatusUnauthorized, probeAuthMiddleware(t, s, refreshed),
+ "the bearer the caller reauthorized with must stop working")
}
diff --git a/backend/api/mcp/tool_search_test.go b/backend/api/mcp/tool_search_test.go
index 94b9179d75..e7ccb499a7 100644
--- a/backend/api/mcp/tool_search_test.go
+++ b/backend/api/mcp/tool_search_test.go
@@ -14,7 +14,7 @@ import (
func TestSearchAPIListServices(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test listing all services (no parameters)
@@ -32,7 +32,7 @@ func TestSearchAPIListServices(t *testing.T) {
func TestSearchAPIByService(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test browsing a specific service
@@ -52,7 +52,7 @@ func TestSearchAPIByService(t *testing.T) {
func TestSearchAPIByServiceNotFound(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test browsing a non-existent service
@@ -70,7 +70,7 @@ func TestSearchAPIByServiceNotFound(t *testing.T) {
func TestSearchAPIDetailMode(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test detail mode with full operationId
@@ -89,7 +89,7 @@ func TestSearchAPIDetailMode(t *testing.T) {
func TestSearchAPIDetailModeShortFormat(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test detail mode with short operationId format (Service/Method)
@@ -108,7 +108,7 @@ func TestSearchAPIDetailModeShortFormat(t *testing.T) {
func TestSearchAPIDetailModeWithResponse(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test detail mode shows response schema
@@ -125,7 +125,7 @@ func TestSearchAPIDetailModeWithResponse(t *testing.T) {
func TestSearchAPIDetailModeNotFound(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test detail mode with unknown operationId
@@ -142,7 +142,7 @@ func TestSearchAPIDetailModeNotFound(t *testing.T) {
func TestSearchAPIServiceShowsAll(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test browsing a service shows all endpoints (no limit)
@@ -161,7 +161,7 @@ func TestSearchAPIServiceShowsAll(t *testing.T) {
func TestSearchAPISchemaLookup(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test schema lookup with full name
@@ -180,7 +180,7 @@ func TestSearchAPISchemaLookup(t *testing.T) {
func TestSearchAPISchemaLookupShortName(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test schema lookup with short name
@@ -198,7 +198,7 @@ func TestSearchAPISchemaLookupShortName(t *testing.T) {
func TestSearchAPISchemaLookupNotFound(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test schema lookup with unknown name
@@ -215,7 +215,7 @@ func TestSearchAPISchemaLookupNotFound(t *testing.T) {
func TestSearchAPISchemaLookupEnum(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test enum schema lookup
@@ -232,7 +232,7 @@ func TestSearchAPISchemaLookupEnum(t *testing.T) {
func TestSearchAPIProtobufDescriptionTruncation(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test that protobuf types have short descriptions
diff --git a/backend/api/mcp/tool_skill_test.go b/backend/api/mcp/tool_skill_test.go
index 1a8e6271f4..55ba5ad6bc 100644
--- a/backend/api/mcp/tool_skill_test.go
+++ b/backend/api/mcp/tool_skill_test.go
@@ -13,7 +13,7 @@ import (
func TestGetSkillListSkills(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test listing all skills (no parameters)
@@ -30,7 +30,7 @@ func TestGetSkillListSkills(t *testing.T) {
func TestGetSkillSpecificSkill(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test getting query skill
@@ -49,7 +49,7 @@ func TestGetSkillSpecificSkill(t *testing.T) {
func TestGetSkillNotFound(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
// Test getting non-existent skill
@@ -67,7 +67,7 @@ func TestGetSkillNotFound(t *testing.T) {
func TestGetSkillAllSkillsLoadable(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret")
+ s, err := NewServer(nil, profile, "test-secret", nil)
require.NoError(t, err)
skills := []string{"query", "database-change", "grant-permission"}
diff --git a/backend/api/oauth2/grant_test.go b/backend/api/oauth2/grant_test.go
index bdd71a3ba5..0538b921d7 100644
--- a/backend/api/oauth2/grant_test.go
+++ b/backend/api/oauth2/grant_test.go
@@ -621,7 +621,7 @@ func errorDescription(t *testing.T, rec *httptest.ResponseRecorder) string {
// got through to the MCP handler.
func mcpStatus(t *testing.T, st *store.Store, externalURL, accessToken string) int {
t.Helper()
- srv, err := mcp.NewServer(st, &config.Profile{ExternalURL: externalURL}, testSecret)
+ srv, err := mcp.NewServer(st, &config.Profile{ExternalURL: externalURL}, testSecret, nil)
require.NoError(t, err)
e := echo.New()
srv.RegisterRoutes(e)
diff --git a/backend/api/oauth2/token.go b/backend/api/oauth2/token.go
index ba30c2a54f..ca8b176d19 100644
--- a/backend/api/oauth2/token.go
+++ b/backend/api/oauth2/token.go
@@ -431,7 +431,7 @@ func (s *Service) issueTokens(c *echo.Context, client *store.OAuth2ClientMessage
// downstream APIs (gRPC services, MCP middleware) use to scope requests.
// The audience is the grant's stored canonical resource, so the token is
// only accepted at the /mcp endpoint the user consented to.
- accessToken, err := auth.GenerateOAuth2AccessToken(grant.userEmail, client.ClientID, grant.workspaceID, grant.resource, s.secret, accessTokenExpiry)
+ accessToken, err := auth.GenerateOAuth2AccessToken(grant.userEmail, client.ClientID, grant.workspaceID, grant.resource, grant.scope, s.secret, accessTokenExpiry)
if err != nil {
return oauth2Error(c, http.StatusInternalServerError, "server_error", fmt.Sprintf("failed to generate access token with error: %v", err))
}
diff --git a/backend/api/oauth2/token_test.go b/backend/api/oauth2/token_test.go
index 212109c15c..ec83f2b2aa 100644
--- a/backend/api/oauth2/token_test.go
+++ b/backend/api/oauth2/token_test.go
@@ -120,7 +120,7 @@ func TestIssueTokensPlacesWorkspaceInJWT(t *testing.T) {
const clientID = "client-xyz"
const workspaceID = "ws-consent-bound"
- tokenStr, err := auth.GenerateOAuth2AccessToken(userEmail, clientID, workspaceID, testResource, secret, time.Hour)
+ tokenStr, err := auth.GenerateOAuth2AccessToken(userEmail, clientID, workspaceID, testResource, "", secret, time.Hour)
require.NoError(t, err)
// Decode the token (signature-verified) and assert the workspace_id
diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.go
index 65213d45ff..ed10230bf9 100644
--- a/backend/api/v1/auth_service.go
+++ b/backend/api/v1/auth_service.go
@@ -1194,14 +1194,6 @@ func (s *AuthService) resolveWorkspaceForLogin(ctx context.Context, user *store.
}
}
-// isMCPBoundToken reports whether extracted claims identify an MCP OAuth2
-// access token: the current generation by its token_use claim (the audience is
-// a per-deployment resource URI, so it cannot be matched by value here), the
-// pre-3.23 generation by the fixed legacy audience.
-func isMCPBoundToken(claims *auth.ExpiredTokenClaims) bool {
- return claims.TokenUse == auth.TokenUseMCP || slices.Contains(claims.Audience, auth.OAuth2AccessTokenAudience)
-}
-
// SwitchWorkspace switches the current user's active workspace and issues new tokens.
func (s *AuthService) SwitchWorkspace(ctx context.Context, req *connect.Request[v1pb.SwitchWorkspaceRequest]) (*connect.Response[v1pb.LoginResponse], error) {
request := req.Msg
@@ -1222,14 +1214,15 @@ func (s *AuthService) SwitchWorkspace(ctx context.Context, req *connect.Request[
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("only end users can switch workspaces"))
}
- // Reject OAuth2 tokens — they are bound to a specific workspace via the OAuth client
- // and must not be used to mint plain user tokens for other workspaces.
+ // Reject MCP-originated calls — an MCP session is bound to a specific
+ // workspace via the OAuth grant and must not be able to mint plain user
+ // tokens, for its own workspace or any other. Since P1a PR 4 tool traffic
+ // arrives on the internal transport carrying the delegated credential, so
+ // this asks auth (which recognizes both that credential and an external MCP
+ // token) rather than extracting claims itself.
accessTokenStr, _ := auth.GetTokenFromHeaders(req.Header())
- if accessTokenStr != "" {
- tokenClaims, err := auth.ExtractClaimsFromExpiredToken(accessTokenStr, s.secret)
- if err == nil && isMCPBoundToken(tokenClaims) {
- return nil, connect.NewError(connect.CodePermissionDenied, errors.New("OAuth2 tokens cannot be used to switch workspaces"))
- }
+ if auth.IsMCPOriginatedToken(accessTokenStr, s.secret) {
+ return nil, connect.NewError(connect.CodePermissionDenied, errors.New("OAuth2 tokens cannot be used to switch workspaces"))
}
// Verify the user is a member of the target workspace.
diff --git a/backend/api/v1/auth_service_test.go b/backend/api/v1/auth_service_test.go
index ca93432ce0..09aed72c54 100644
--- a/backend/api/v1/auth_service_test.go
+++ b/backend/api/v1/auth_service_test.go
@@ -4,6 +4,7 @@ import (
"testing"
"time"
+ "github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/require"
"github.com/bytebase/bytebase/backend/api/auth"
@@ -41,35 +42,63 @@ func TestExtractDomain(t *testing.T) {
}
}
-// TestIsMCPBoundToken pins the SwitchWorkspace guard predicate through the real
-// mint -> extract pipeline. For every token minted after P1a PR 3 the token_use
-// clause is the only one that fires (the audience is a per-deployment resource
-// URI, not the fixed legacy string), so dropping it would let a workspace-bound
-// MCP token mint plain user tokens for other workspaces.
-func TestIsMCPBoundToken(t *testing.T) {
+// TestSwitchWorkspaceMCPRecognition pins the SwitchWorkspace guard predicate
+// across both MCP credential generations. An MCP session must never mint a
+// plain user token: that token is not audience-bound to the MCP resource, does
+// not die with the OAuth grant, and ignores the workspace MCP kill switch.
+//
+// The delegated-credential row is the P1a PR 4 half. Tool traffic now rides the
+// internal transport, so the bearer this guard sees is the delegated
+// credential, not the client's MCP token — and it is signed with a derived key,
+// invisible to the raw-secret extraction the guard used to do (asserted below).
+// Recognizing only extractable claims would fail OPEN for every MCP session.
+func TestSwitchWorkspaceMCPRecognition(t *testing.T) {
const secret = "test-secret"
- t.Run("current MCP token is caught via token_use", func(t *testing.T) {
- tokenStr, err := auth.GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", "https://bb.example.com/mcp", secret, time.Hour)
- require.NoError(t, err)
- claims, err := auth.ExtractClaimsFromExpiredToken(tokenStr, secret)
- require.NoError(t, err)
- require.True(t, isMCPBoundToken(claims))
- })
-
- t.Run("legacy oauth2 token is caught via the fixed audience", func(t *testing.T) {
- require.True(t, isMCPBoundToken(&auth.ExpiredTokenClaims{
- Audience: []string{auth.OAuth2AccessTokenAudience},
- }))
- })
-
- t.Run("web session token is not caught", func(t *testing.T) {
- tokenStr, err := auth.GenerateAccessToken("[email protected]", "ws-test", secret, time.Hour)
- require.NoError(t, err)
- claims, err := auth.ExtractClaimsFromExpiredToken(tokenStr, secret)
- require.NoError(t, err)
- require.False(t, isMCPBoundToken(claims))
- })
+ delegated, err := auth.GenerateInternalMCPToken(auth.DelegatedMCPCredential{
+ Principal: "[email protected]",
+ WorkspaceID: "ws-test",
+ ClientID: "client-A",
+ }, secret)
+ require.NoError(t, err)
+ _, extractErr := auth.ExtractClaimsFromExpiredToken(delegated, secret)
+ require.Error(t, extractErr, "the delegated credential must not verify under the raw secret")
+ require.True(t, auth.IsMCPOriginatedToken(delegated, secret),
+ "the delegated credential must be recognized as MCP-originated")
+
+ // Current external MCP token: recognized by token_use, since its audience is
+ // a per-deployment resource URI that cannot be matched by value.
+ mcpToken, err := auth.GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", "https://bb.example.com/mcp", "", secret, time.Hour)
+ require.NoError(t, err)
+ require.True(t, auth.IsMCPOriginatedToken(mcpToken, secret))
+
+ // Pre-3.23 external token: recognized by the fixed legacy audience.
+ require.True(t, auth.IsMCPOriginatedToken(mustLegacyOAuth2Token(t, secret), secret))
+
+ webToken, err := auth.GenerateAccessToken("[email protected]", "ws-test", secret, time.Hour)
+ require.NoError(t, err)
+ require.False(t, auth.IsMCPOriginatedToken(webToken, secret),
+ "a web session token must stay eligible to switch workspaces")
+ require.False(t, auth.IsMCPOriginatedToken("", secret))
+ require.False(t, auth.IsMCPOriginatedToken("not-a-jwt", secret))
+}
+
+// mustLegacyOAuth2Token mints a pre-PR-3 fixed-audience OAuth2 token.
+func mustLegacyOAuth2Token(t *testing.T, secret string) string {
+ t.Helper()
+ claims := jwt.MapClaims{
+ "iss": "bytebase",
+ "sub": "[email protected]",
+ "aud": auth.OAuth2AccessTokenAudience,
+ "workspace_id": "ws-test",
+ "exp": time.Now().Add(time.Hour).Unix(),
+ "iat": time.Now().Unix(),
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ token.Header["kid"] = "v1"
+ tokenStr, err := token.SignedString([]byte(secret))
+ require.NoError(t, err)
+ return tokenStr
}
func TestLoginAuthMethodRequiresPasswordReset(t *testing.T) {
diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.go
index 4293b7ada2..b2a1c71324 100644
--- a/backend/server/grpc_routes.go
+++ b/backend/server/grpc_routes.go
@@ -51,7 +51,7 @@ func configureGrpcRouters(
iamManager *iam.Manager,
secret string,
sampleInstanceManager *sampleinstance.Manager,
-) error {
+) (http.Handler, error) {
// Note: the gateway response modifier takes the token duration on server startup. If the value is changed,
// the user has to restart the server to take the latest value.
gatewayMarshaler := &grpcruntime.HTTPBodyMarshaler{
@@ -144,106 +144,72 @@ func configureGrpcRouters(
),
)
- connectHandlers := make(map[string]http.Handler)
-
- aiPath, aiHandler := v1connect.NewAIServiceHandler(aiService, handlerOpts)
- connectHandlers[aiPath] = aiHandler
-
- accessGrantPath, accessGrantHandler := v1connect.NewAccessGrantServiceHandler(accessGrantService, handlerOpts)
- connectHandlers[accessGrantPath] = accessGrantHandler
-
- actuatorPath, actuatorHandler := v1connect.NewActuatorServiceHandler(actuatorService, handlerOpts)
- connectHandlers[actuatorPath] = actuatorHandler
-
- auditLogPath, auditLogHandler := v1connect.NewAuditLogServiceHandler(auditLogService, handlerOpts)
- connectHandlers[auditLogPath] = auditLogHandler
-
- authPath, authHandler := v1connect.NewAuthServiceHandler(authService, handlerOpts)
- connectHandlers[authPath] = authHandler
-
- celPath, celHandler := v1connect.NewCelServiceHandler(celService, handlerOpts)
- connectHandlers[celPath] = celHandler
-
- changelogPath, changelogHandler := v1connect.NewChangelogServiceHandler(changelogService, handlerOpts)
- connectHandlers[changelogPath] = changelogHandler
-
- databaseCatalogPath, databaseCatalogHandler := v1connect.NewDatabaseCatalogServiceHandler(databaseCatalogService, handlerOpts)
- connectHandlers[databaseCatalogPath] = databaseCatalogHandler
-
- databaseGroupPath, databaseGroupHandler := v1connect.NewDatabaseGroupServiceHandler(databaseGroupService, handlerOpts)
- connectHandlers[databaseGroupPath] = databaseGroupHandler
-
- databasePath, databaseHandler := v1connect.NewDatabaseServiceHandler(databaseService, handlerOpts)
- connectHandlers[databasePath] = databaseHandler
-
- groupPath, groupHandler := v1connect.NewGroupServiceHandler(groupService, handlerOpts)
- connectHandlers[groupPath] = groupHandler
-
- identityProviderPath, identityProviderHandler := v1connect.NewIdentityProviderServiceHandler(identityProviderService, handlerOpts)
- connectHandlers[identityProviderPath] = identityProviderHandler
-
- instanceRolePath, instanceRoleHandler := v1connect.NewInstanceRoleServiceHandler(instanceRoleService, handlerOpts)
- connectHandlers[instanceRolePath] = instanceRoleHandler
-
- instancePath, instanceHandler := v1connect.NewInstanceServiceHandler(instanceService, handlerOpts)
- connectHandlers[instancePath] = instanceHandler
-
- issuePath, issueHandler := v1connect.NewIssueServiceHandler(issueService, handlerOpts)
- connectHandlers[issuePath] = issueHandler
-
- orgPolicyPath, orgPolicyHandler := v1connect.NewOrgPolicyServiceHandler(orgPolicyService, handlerOpts)
- connectHandlers[orgPolicyPath] = orgPolicyHandler
-
- planPath, planHandler := v1connect.NewPlanServiceHandler(planService, handlerOpts)
- connectHandlers[planPath] = planHandler
-
- projectPath, projectHandler := v1connect.NewProjectServiceHandler(projectService, handlerOpts)
- connectHandlers[projectPath] = projectHandler
-
- queryHistoryPath, queryHistoryHandler := v1connect.NewQueryHistoryServiceHandler(queryHistoryService, handlerOpts)
- connectHandlers[queryHistoryPath] = queryHistoryHandler
-
- releasePath, releaseHandler := v1connect.NewReleaseServiceHandler(releaseService, handlerOpts)
- connectHandlers[releasePath] = releaseHandler
-
- reviewConfigPath, reviewConfigHandler := v1connect.NewReviewConfigServiceHandler(reviewConfigService, handlerOpts)
- connectHandlers[reviewConfigPath] = reviewConfigHandler
-
- revisionPath, revisionHandler := v1connect.NewRevisionServiceHandler(revisionService, handlerOpts)
- connectHandlers[revisionPath] = revisionHandler
-
- rolePath, roleHandler := v1connect.NewRoleServiceHandler(roleService, handlerOpts)
- connectHandlers[rolePath] = roleHandler
-
- rolloutPath, rolloutHandler := v1connect.NewRolloutServiceHandler(rolloutService, handlerOpts)
- connectHandlers[rolloutPath] = rolloutHandler
-
- settingPath, settingHandler := v1connect.NewSettingServiceHandler(settingService, handlerOpts)
- connectHandlers[settingPath] = settingHandler
-
- sheetPath, sheetHandler := v1connect.NewSheetServiceHandler(sheetService, handlerOpts)
- connectHandlers[sheetPath] = sheetHandler
-
- sqlPath, sqlHandler := v1connect.NewSQLServiceHandler(sqlService, handlerOpts)
- connectHandlers[sqlPath] = sqlHandler
-
- subscriptionPath, subscriptionHandler := v1connect.NewSubscriptionServiceHandler(subscriptionService, handlerOpts)
- connectHandlers[subscriptionPath] = subscriptionHandler
-
- userPath, userHandler := v1connect.NewUserServiceHandler(userService, handlerOpts)
- connectHandlers[userPath] = userHandler
-
- serviceAccountPath, serviceAccountHandler := v1connect.NewServiceAccountServiceHandler(serviceAccountService, handlerOpts)
- connectHandlers[serviceAccountPath] = serviceAccountHandler
-
- workloadIdentityPath, workloadIdentityHandler := v1connect.NewWorkloadIdentityServiceHandler(workloadIdentityService, handlerOpts)
- connectHandlers[workloadIdentityPath] = workloadIdentityHandler
-
- worksheetPath, worksheetHandler := v1connect.NewWorksheetServiceHandler(worksheetService, handlerOpts)
- connectHandlers[worksheetPath] = worksheetHandler
-
- workspacePath, workspaceHandler := v1connect.NewWorkspaceServiceHandler(workspaceService, handlerOpts)
- connectHandlers[workspacePath] = workspaceHandler
+ // registerServiceHandlers builds one connect handler per v1 service with the
+ // given interceptor chain. Called twice: once for the public chain and once
+ // for the internal MCP chain — same service instances, different auth.
+ registerServiceHandlers := func(opts connect.HandlerOption) map[string]http.Handler {
+ handlers := make(map[string]http.Handler)
+ add := func(path string, handler http.Handler) {
+ handlers[path] = handler
+ }
+ add(v1connect.NewAIServiceHandler(aiService, opts))
+ add(v1connect.NewAccessGrantServiceHandler(accessGrantService, opts))
+ add(v1connect.NewActuatorServiceHandler(actuatorService, opts))
+ add(v1connect.NewAuditLogServiceHandler(auditLogService, opts))
+ add(v1connect.NewAuthServiceHandler(authService, opts))
+ add(v1connect.NewCelServiceHandler(celService, opts))
+ add(v1connect.NewChangelogServiceHandler(changelogService, opts))
+ add(v1connect.NewDatabaseCatalogServiceHandler(databaseCatalogService, opts))
+ add(v1connect.NewDatabaseGroupServiceHandler(databaseGroupService, opts))
+ add(v1connect.NewDatabaseServiceHandler(databaseService, opts))
+ add(v1connect.NewGroupServiceHandler(groupService, opts))
+ add(v1connect.NewIdentityProviderServiceHandler(identityProviderService, opts))
+ add(v1connect.NewInstanceRoleServiceHandler(instanceRoleService, opts))
+ add(v1connect.NewInstanceServiceHandler(instanceService, opts))
+ add(v1connect.NewIssueServiceHandler(issueService, opts))
+ add(v1connect.NewOrgPolicyServiceHandler(orgPolicyService, opts))
+ add(v1connect.NewPlanServiceHandler(planService, opts))
+ add(v1connect.NewProjectServiceHandler(projectService, opts))
+ add(v1connect.NewQueryHistoryServiceHandler(queryHistoryService, opts))
+ add(v1connect.NewReleaseServiceHandler(releaseService, opts))
+ add(v1connect.NewReviewConfigServiceHandler(reviewConfigService, opts))
+ add(v1connect.NewRevisionServiceHandler(revisionService, opts))
+ add(v1connect.NewRoleServiceHandler(roleService, opts))
+ add(v1connect.NewRolloutServiceHandler(rolloutService, opts))
+ add(v1connect.NewSettingServiceHandler(settingService, opts))
+ add(v1connect.NewSheetServiceHandler(sheetService, opts))
+ add(v1connect.NewSQLServiceHandler(sqlService, opts))
+ add(v1connect.NewSubscriptionServiceHandler(subscriptionService, opts))
+ add(v1connect.NewUserServiceHandler(userService, opts))
+ add(v1connect.NewServiceAccountServiceHandler(serviceAccountService, opts))
+ add(v1connect.NewWorkloadIdentityServiceHandler(workloadIdentityService, opts))
+ add(v1connect.NewWorksheetServiceHandler(worksheetService, opts))
+ add(v1connect.NewWorkspaceServiceHandler(workspaceService, opts))
+ return handlers
+ }
+
+ connectHandlers := registerServiceHandlers(handlerOpts)
+
+ // The internal MCP handler chain: the same service handlers behind an auth
+ // interceptor that accepts ONLY the delegated credential minted at the /mcp
+ // boundary. It is reachable exclusively through the in-memory transport
+ // handed to the MCP server — never bound to a listener, so the internal
+ // credential never touches a socket. ACL and audit run exactly as on the
+ // public chain: the credential carries identity + grant state, while
+ // authorization is re-resolved live per request.
+ internalHandlerOpts := connect.WithHandlerOptions(
+ connect.WithRecover(onPanic),
+ connect.WithInterceptors(
+ validateInterceptor,
+ auth.NewInternalMCPAuthInterceptor(stores, secret, profile),
+ apiv1.NewACLInterceptor(stores, secret, iamManager, profile),
+ apiv1.NewAuditInterceptor(stores, secret, profile),
+ ),
+ )
+ internalMCPMux := http.NewServeMux()
+ for path, handler := range registerServiceHandlers(internalHandlerOpts) {
+ internalMCPMux.Handle(path, handler)
+ }
// grpc reflection handlers.
reflector := grpcreflect.NewStaticReflector(
@@ -297,107 +263,107 @@ func configureGrpcRouters(
),
)
if err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterAIServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterAccessGrantServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterActuatorServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterAuditLogServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterAuthServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterCelServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterChangelogServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterDatabaseCatalogServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterDatabaseGroupServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterDatabaseServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterGroupServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterIdentityProviderServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterInstanceRoleServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterInstanceServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterIssueServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterOrgPolicyServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterPlanServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterProjectServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterQueryHistoryServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterReleaseServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterReviewConfigServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterRevisionServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterRoleServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterRolloutServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterSettingServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterSheetServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterSQLServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterSubscriptionServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterUserServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterServiceAccountServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterWorkloadIdentityServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterWorksheetServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
if err := v1pb.RegisterWorkspaceServiceHandler(ctx, mux, grpcConn); err != nil {
- return err
+ return nil, err
}
// Register echo routes for mux and connectHandlers
e.GET("/v1:adminExecute", echo.WrapHandler(wsproxy.WebsocketProxy(
@@ -413,5 +379,5 @@ func configureGrpcRouters(
e.Any(path+"*", echo.WrapHandler(handler))
}
- return nil
+ return internalMCPMux, nil
}
diff --git a/backend/server/server.go b/backend/server/server.go
index 5f78d01c46..f5b745b5b4 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -235,16 +235,17 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
directorySyncServer := directorysync.NewService(s.store, s.licenseService, s.iamManager, profile)
oauth2Service := oauth2.NewService(stores, profile, secret)
- mcpServer, err := mcp.NewServer(stores, profile, secret)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to create MCP server")
- }
stripeWebhookHandler := stripeapi.NewWebhookHandler(s.store, s.licenseService, profile.StripeWebhookSecret)
- if err := configureGrpcRouters(ctx, s.echoServer, s.store, sheetManager, s.dbFactory, s.licenseService, s.profile, s.bus, s.schemaSyncer, s.webhookManager, s.iamManager, secret, s.sampleInstanceManager); err != nil {
+ internalMCPHandler, err := configureGrpcRouters(ctx, s.echoServer, s.store, sheetManager, s.dbFactory, s.licenseService, s.profile, s.bus, s.schemaSyncer, s.webhookManager, s.iamManager, secret, s.sampleInstanceManager)
+ if err != nil {
return nil, errors.Wrapf(err, "failed to configure gRPC routers")
}
+ mcpServer, err := mcp.NewServer(stores, profile, secret, internalMCPHandler)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to create MCP server")
+ }
configureEchoRouters(s.echoServer, s.lspServer, directorySyncServer, oauth2Service, mcpServer, stripeWebhookHandler, s.store, s.licenseService, profile)
serverStarted = true
diff --git a/backend/tests/mcp_tool_parity_test.go b/backend/tests/mcp_tool_parity_test.go
new file mode 100644
index 0000000000..5d7506d134
--- /dev/null
+++ b/backend/tests/mcp_tool_parity_test.go
@@ -0,0 +1,148 @@
+package tests
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/stretchr/testify/require"
+
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+// bearerTransport injects the controller's session token into MCP client
+// requests, the way a user pastes a token into an MCP client.
+type bearerTransport struct {
+ token string
+}
+
+func (t *bearerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ req = req.Clone(req.Context())
+ req.Header.Set("Authorization", "Bearer "+t.token)
+ return http.DefaultTransport.RoundTrip(req)
+}
+
+// TestMCPToolCallParity is the P1a PR 4 behavior-parity pin. A tool call
+// through /mcp must behave exactly like the same principal's direct v1 call:
+// the delegated credential minted at the boundary establishes the same
+// identity on the internal in-memory chain, and RBAC resolves live
+// downstream. The session here is a plain bb.user.access web token — the
+// legacy admission — so this also pins that legacy sessions keep working
+// through tools with empty grant state.
+func TestMCPToolCallParity(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ // Parity baseline: the principal's direct v1 API view.
+ direct, err := ctl.projectServiceClient.ListProjects(ctx, connect.NewRequest(&v1pb.ListProjectsRequest{}))
+ a.NoError(err)
+ var directNames []string
+ for _, p := range direct.Msg.Projects {
+ directNames = append(directNames, p.Name)
+ }
+ a.NotEmpty(directNames)
+
+ // The same principal through MCP: initialize a real session against /mcp
+ // and run the call_api tool. Every internal hop rides the in-memory
+ // transport with the minted credential — if the internal chain rejected it
+ // or established a different principal, this call would fail or diverge.
+ client := mcp.NewClient(&mcp.Implementation{Name: "bb-e2e", Version: "0"}, nil)
+ session, err := client.Connect(ctx, &mcp.StreamableClientTransport{
+ Endpoint: ctl.rootURL + "/mcp",
+ HTTPClient: &http.Client{Transport: &bearerTransport{token: ctl.authInterceptor.token}},
+ }, nil)
+ a.NoError(err)
+ defer session.Close()
+
+ result, err := session.CallTool(ctx, &mcp.CallToolParams{
+ Name: "call_api",
+ Arguments: map[string]any{"operationId": "ProjectService/ListProjects"},
+ })
+ a.NoError(err)
+ a.False(result.IsError, "call_api must succeed through the internal transport: %v", result.Content)
+
+ raw, err := json.Marshal(result.StructuredContent)
+ a.NoError(err)
+ var out struct {
+ Status int `json:"status"`
+ Response struct {
+ Projects []struct {
+ Name string `json:"name"`
+ } `json:"projects"`
+ } `json:"response"`
+ }
+ a.NoError(json.Unmarshal(raw, &out))
+ a.Equal(http.StatusOK, out.Status)
+
+ var mcpNames []string
+ for _, p := range out.Response.Projects {
+ mcpNames = append(mcpNames, p.Name)
+ }
+ a.ElementsMatch(directNames, mcpNames,
+ "the MCP tool call must see exactly the projects the same principal sees directly")
+}
+
+// TestMCPCannotMintPlainUserToken pins the boundary escape that riding the
+// internal transport would otherwise open. SwitchWorkspace hands back a plain
+// bb.user.access token, which is not audience-bound to the MCP resource, does
+// not die with the OAuth grant, and ignores the workspace MCP kill switch. Its
+// guard used to recognize MCP callers by extracting claims from the forwarded
+// bearer; the delegated credential is signed with a derived key and cannot be
+// extracted that way, so the guard has to recognize it explicitly or fail open
+// for every MCP session.
+func TestMCPCannotMintPlainUserToken(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ workspace, err := ctl.workspaceServiceClient.GetWorkspace(ctx, connect.NewRequest(&v1pb.GetWorkspaceRequest{
+ Name: "workspaces/-",
+ }))
+ a.NoError(err)
+
+ client := mcp.NewClient(&mcp.Implementation{Name: "bb-e2e", Version: "0"}, nil)
+ session, err := client.Connect(ctx, &mcp.StreamableClientTransport{
+ Endpoint: ctl.rootURL + "/mcp",
+ HTTPClient: &http.Client{Transport: &bearerTransport{token: ctl.authInterceptor.token}},
+ }, nil)
+ a.NoError(err)
+ defer session.Close()
+
+ result, err := session.CallTool(ctx, &mcp.CallToolParams{
+ Name: "call_api",
+ Arguments: map[string]any{
+ "operationId": "AuthService/SwitchWorkspace",
+ "body": map[string]any{"workspace": workspace.Msg.Name},
+ },
+ })
+ a.NoError(err)
+
+ raw, err := json.Marshal(result.StructuredContent)
+ a.NoError(err)
+ var out struct {
+ Status int `json:"status"`
+ Response struct {
+ Token string `json:"token"`
+ } `json:"response"`
+ }
+ a.NoError(json.Unmarshal(raw, &out))
+
+ a.NotEqual(http.StatusOK, out.Status,
+ "an MCP session must not be able to switch workspaces")
+ a.Empty(out.Response.Token,
+ "an MCP session must never receive a plain user access token")
+}