Skip to content

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

fix(mcp): refuse workspace-token mint for MCP-originated callers (#21142)

Vincent Huang682a13b856de
diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.go
index ed10230bf9..f837d399dd 100644
--- a/backend/api/v1/auth_service.go
+++ b/backend/api/v1/auth_service.go
@@ -1214,15 +1214,8 @@ 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 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 auth.IsMCPOriginatedToken(accessTokenStr, s.secret) {
- return nil, connect.NewError(connect.CodePermissionDenied, errors.New("OAuth2 tokens cannot be used to switch workspaces"))
+ if err := s.rejectMCPOriginatedTokenMint(ctx, req.Header(), "switch workspaces"); err != nil {
+ return nil, err
}
// Verify the user is a member of the target workspace.
@@ -1284,10 +1277,58 @@ func (s *AuthService) SwitchWorkspace(ctx context.Context, req *connect.Request[
return s.switchWorkspaceInternal(ctx, user, workspaceID, request.Web, req.Header())
}
+// rejectMCPOriginatedTokenMint refuses a request that originated from an MCP
+// session. Every path into switchWorkspaceInternal hands the
+// caller a plain bb.user.access token in the response body when there is no
+// refresh cookie — and an MCP session never has one. That token is not
+// audience-bound to the MCP resource, survives revocation of the OAuth grant,
+// and ignores the workspace MCP kill switch, so an MCP session must not be
+// able to obtain one, for its own workspace or any other. An MCP session is
+// also bound to a specific workspace via the grant.
+//
+// It recognizes MCP origin two independent ways. The AuthContext is the
+// structural one: the internal interceptor stamps the delegated grant on every
+// request arriving on the internal MCP transport, and presence alone marks the
+// request (see common.DelegatedGrant), so this holds even for a caller that
+// forwards no headers. The bearer check then covers the public chain, where
+// the AuthContext carries no grant.
+//
+// The bearer half asks auth rather than reading an audience itself. Audience
+// stopped being the recognizer: the delegated credential is signed with a
+// derived key, so its claims do not verify under the raw secret at all
+// (TestSwitchWorkspaceMCPRecognition pins that), and since P1a PR 3 an
+// external MCP token's audience is a per-deployment resource URI that cannot
+// be matched by value, leaving token_use to identify it. auth.IsMCPOriginatedToken
+// holds both recognizers.
+//
+// Callers must run this BEFORE any mutation — leaving or deleting a workspace
+// and only then refusing the token would strand the caller.
+func (s *AuthService) rejectMCPOriginatedTokenMint(ctx context.Context, reqHeaders http.Header, action string) error {
+ authCtx, ok := common.GetAuthContextFromContext(ctx)
+ mcpOriginated := ok && authCtx.DelegatedGrant != nil
+ if !mcpOriginated {
+ accessTokenStr, _ := auth.GetTokenFromHeaders(reqHeaders)
+ mcpOriginated = auth.IsMCPOriginatedToken(accessTokenStr, s.secret)
+ }
+ if mcpOriginated {
+ return connect.NewError(connect.CodePermissionDenied, errors.Errorf("MCP sessions cannot %s", action))
+ }
+ return nil
+}
+
// switchWorkspaceInternal generates new tokens for the target workspace and
// returns a LoginResponse with cookies set. Used by SwitchWorkspace,
// LeaveWorkspace, and DeleteWorkspace.
func (s *AuthService) switchWorkspaceInternal(ctx context.Context, user *store.UserMessage, workspaceID string, web bool, reqHeaders http.Header) (*connect.Response[v1pb.LoginResponse], error) {
+ // Each caller already refuses MCP-originated requests up front, where the
+ // refusal still precedes that caller's mutations. Repeating it at the mint
+ // costs nothing and makes the boundary structural: a future caller that
+ // forgets cannot reopen the escape. This function acquired two unguarded
+ // callers once already.
+ if err := s.rejectMCPOriginatedTokenMint(ctx, reqHeaders, "obtain a workspace token"); err != nil {
+ return nil, err
+ }
+
token, err := s.generateLoginToken(ctx, user, workspaceID)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to generate token"))
diff --git a/backend/api/v1/auth_service_test.go b/backend/api/v1/auth_service_test.go
index 09aed72c54..f517217ea9 100644
--- a/backend/api/v1/auth_service_test.go
+++ b/backend/api/v1/auth_service_test.go
@@ -1,14 +1,19 @@
package v1
import (
+ "context"
+ "net/http"
"testing"
"time"
+ "connectrpc.com/connect"
"github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/require"
"github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/store"
)
func TestExtractDomain(t *testing.T) {
@@ -182,3 +187,50 @@ func TestLegacyMFATempTokenDefaultsToPasswordLoginAuthMethod(t *testing.T) {
require.Equal(t, loginAuthMethodPassword, method)
require.True(t, method.requiresPasswordReset())
}
+
+// TestSwitchWorkspaceInternalRefusesMCPCaller pins the refusal at the mint.
+// The three handlers that reach switchWorkspaceInternal each refuse
+// MCP-originated callers up front, where the refusal still precedes their
+// mutations; the check inside switchWorkspaceInternal is the one that keeps a
+// future caller from reopening the escape the way LeaveWorkspace and
+// DeleteWorkspace did. Because the handlers refuse first, no e2e reaches it,
+// so it needs its own pin.
+//
+// The AuthService here deliberately carries a nil store: the guard has to
+// return before generateLoginToken touches it, so a regression panics rather
+// than quietly minting a token.
+func TestSwitchWorkspaceInternalRefusesMCPCaller(t *testing.T) {
+ const secret = "test-secret"
+ s := &AuthService{secret: secret}
+ user := &store.UserMessage{Email: "[email protected]"}
+
+ delegated, err := auth.GenerateInternalMCPToken(auth.DelegatedMCPCredential{
+ Principal: "[email protected]",
+ WorkspaceID: "ws-test",
+ ClientID: "client-A",
+ }, secret)
+ require.NoError(t, err)
+ mcpHeaders := http.Header{}
+ mcpHeaders.Set("Authorization", "Bearer "+delegated)
+
+ resp, err := s.switchWorkspaceInternal(context.Background(), user, "ws-test", false, mcpHeaders)
+ require.Nil(t, resp, "an MCP-originated caller must never reach the mint")
+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
+
+ // A caller that forwards no headers must be refused just the same: on the
+ // internal transport the AuthContext carries the delegated grant, and its
+ // presence — not any field value — marks the request MCP-originated.
+ ctx := context.WithValue(context.Background(), common.AuthContextKey,
+ &common.AuthContext{DelegatedGrant: &common.DelegatedGrant{}})
+ resp, err = s.switchWorkspaceInternal(ctx, user, "ws-test", false, http.Header{})
+ require.Nil(t, resp, "the grant in the AuthContext must refuse on its own")
+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
+
+ // Control: a plain web session on the public chain carries no grant and is
+ // not MCP-originated, so the guard lets it through to the mint.
+ webToken, err := auth.GenerateAccessToken("[email protected]", "ws-test", secret, time.Hour)
+ require.NoError(t, err)
+ webHeaders := http.Header{}
+ webHeaders.Set("Authorization", "Bearer "+webToken)
+ require.NoError(t, s.rejectMCPOriginatedTokenMint(context.Background(), webHeaders, "obtain a workspace token"))
+}
diff --git a/backend/api/v1/workspace_service.go b/backend/api/v1/workspace_service.go
index 27c5013a5d..df331148db 100644
--- a/backend/api/v1/workspace_service.go
+++ b/backend/api/v1/workspace_service.go
@@ -259,6 +259,10 @@ func (s *WorkspaceService) GetIamPolicy(ctx context.Context, _ *connect.Request[
// Cancels any active Stripe subscription before deleting, then switches
// to the next available workspace and returns new auth tokens.
func (s *WorkspaceService) DeleteWorkspace(ctx context.Context, req *connect.Request[v1pb.DeleteWorkspaceRequest]) (*connect.Response[v1pb.LoginResponse], error) {
+ if err := s.authService.rejectMCPOriginatedTokenMint(ctx, req.Header(), "delete workspaces"); err != nil {
+ return nil, err
+ }
+
if !s.profile.SaaS {
return nil, connect.NewError(connect.CodeFailedPrecondition, errors.New("workspace deletion is only supported in SaaS mode"))
}
@@ -316,6 +320,10 @@ func (s *WorkspaceService) DeleteWorkspace(ctx context.Context, req *connect.Req
// LeaveWorkspace removes the calling user from a workspace's IAM bindings,
// then switches to the next available workspace.
func (s *WorkspaceService) LeaveWorkspace(ctx context.Context, req *connect.Request[v1pb.LeaveWorkspaceRequest]) (*connect.Response[v1pb.LoginResponse], error) {
+ if err := s.authService.rejectMCPOriginatedTokenMint(ctx, req.Header(), "leave workspaces"); err != nil {
+ return nil, err
+ }
+
user, ok := GetUserFromContext(ctx)
if !ok || user == nil {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("user not found"))
diff --git a/backend/tests/mcp_workspace_token_escape_test.go b/backend/tests/mcp_workspace_token_escape_test.go
new file mode 100644
index 0000000000..20d382d271
--- /dev/null
+++ b/backend/tests/mcp_workspace_token_escape_test.go
@@ -0,0 +1,264 @@
+package tests
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/stretchr/testify/require"
+
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+// mcpCallResult is the slice of call_api's structured output these tests care
+// about: the status the agent sees, the error text, and any token the response
+// body carried.
+type mcpCallResult struct {
+ Status int `json:"status"`
+ Error string `json:"error"`
+ Response struct {
+ Token string `json:"token"`
+ } `json:"response"`
+}
+
+// callAPIViaMCP drives one call_api tool call over a live /mcp session bound to
+// bearer, exactly as an agent would, and decodes what that agent gets back.
+func callAPIViaMCP(ctx context.Context, t *testing.T, ctl *controller, bearer, operationID string, body map[string]any) mcpCallResult {
+ t.Helper()
+ a := require.New(t)
+
+ session := openMCPSession(ctx, t, ctl, bearer)
+ defer session.Close()
+
+ result, err := session.CallTool(ctx, &mcp.CallToolParams{
+ Name: "call_api",
+ Arguments: map[string]any{
+ "operationId": operationID,
+ "body": body,
+ },
+ })
+ a.NoError(err)
+
+ raw, err := json.Marshal(result.StructuredContent)
+ a.NoError(err)
+ var out mcpCallResult
+ a.NoError(json.Unmarshal(raw, &out))
+ // A tool-level failure — a mistyped operationId, a transport error — leaves
+ // StructuredContent nil, which decodes to a zero status rather than an
+ // error. Without this the test would report a status mismatch that has
+ // nothing to do with the guard it exists to check.
+ a.NotEqual(0, out.Status, "call_api returned no status: %s", out.Error)
+ return out
+}
+
+// workspaceHasMember reports whether any binding in the workspace IAM policy
+// still names email. Matching on the substring keeps this independent of the
+// member-identifier spelling the API happens to use. The probe runs as bearer
+// rather than as the subject, so it still answers after the subject has lost
+// its membership.
+func workspaceHasMember(ctx context.Context, t *testing.T, ctl *controller, bearer, workspace, email string) bool {
+ t.Helper()
+ previous := ctl.authInterceptor.token
+ ctl.authInterceptor.token = bearer
+ defer func() { ctl.authInterceptor.token = previous }()
+
+ policy, err := ctl.workspaceServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{
+ Resource: workspace,
+ }))
+ require.NoError(t, err)
+ for _, binding := range policy.Msg.Bindings {
+ for _, member := range binding.Members {
+ if strings.Contains(member, email) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// TestMCPCannotLeaveWorkspace pins the sibling of the SwitchWorkspace boundary
+// escape that TestMCPCannotMintPlainUserToken covers. LeaveWorkspace ends in
+// AuthService.switchWorkspaceInternal, which puts a plain bb.user.access token
+// in the response body whenever the caller has no refresh cookie — and an MCP
+// session never has one. That token is not audience-bound to the MCP resource,
+// survives revocation of the OAuth grant, and ignores the workspace MCP kill
+// switch.
+//
+// The guard has to run before the IAM mutation, not after: leaving the
+// workspace and only then refusing the token would strand the caller. That
+// ordering is what the membership assertion below pins — with the guard
+// removed this test fails twice over, on the status and on the destroyed
+// membership.
+func TestMCPCannotLeaveWorkspace(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)
+ workspaceName := workspace.Msg.Name
+
+ // LeaveWorkspace refuses the last admin. Seating a second admin is what
+ // makes the guard — rather than that precondition — the reason the MCP
+ // call fails: with the guard removed the leave goes through.
+ const secondAdminEmail = "[email protected]"
+ const secondAdminPassword = "1024bytebase"
+ _, err = ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{
+ User: &v1pb.User{
+ Email: secondAdminEmail,
+ Password: secondAdminPassword,
+ Title: "second admin",
+ },
+ }))
+ a.NoError(err)
+ _, err = ctl.addMemberToWorkspaceIAM(ctx, workspaceName, "user:"+secondAdminEmail, "roles/workspaceAdmin")
+ a.NoError(err)
+
+ // The second admin's own session probes the IAM policy: it survives the
+ // unguarded outcome, where the caller has just deleted its own membership
+ // and can no longer read anything.
+ loginResp, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
+ Email: secondAdminEmail,
+ Password: secondAdminPassword,
+ }))
+ a.NoError(err)
+ secondAdminToken := loginResp.Msg.Token
+ demoToken := ctl.authInterceptor.token
+
+ a.True(workspaceHasMember(ctx, t, ctl, secondAdminToken, workspaceName, "[email protected]"),
+ "precondition: the calling user is a member before the MCP attempt")
+
+ out := callAPIViaMCP(ctx, t, ctl, demoToken,
+ "WorkspaceService/LeaveWorkspace", map[string]any{"name": workspaceName})
+ stillMember := workspaceHasMember(ctx, t, ctl, secondAdminToken, workspaceName, "[email protected]")
+ t.Logf("MCP LeaveWorkspace → status=%d error=%q token=%q stillMember=%v",
+ out.Status, out.Error, out.Response.Token, stillMember)
+
+ a.Equal(http.StatusForbidden, out.Status,
+ "an MCP session must be refused before it can leave a workspace")
+ a.Contains(out.Error, "MCP sessions cannot leave workspaces",
+ "the refusal must come from the MCP guard, not from some other precondition")
+ // This fixture has a single workspace, so switchWorkspaceInternal's nextWS
+ // is always nil and the mint is out of reach even unguarded: the assertion
+ // states the invariant but cannot fail here. The load-bearing pins are the
+ // status and the membership below.
+ a.Empty(out.Response.Token,
+ "an MCP session must never receive a plain user access token")
+ a.True(stillMember,
+ "the guard must run before the IAM mutation — the caller must still be a member")
+
+ // The guard must not cost a normal caller the ability to leave. The second
+ // admin holds an ordinary session token, so this is the non-MCP path.
+ ctl.authInterceptor.token = secondAdminToken
+ _, err = ctl.workspaceServiceClient.LeaveWorkspace(ctx, connect.NewRequest(&v1pb.LeaveWorkspaceRequest{
+ Name: workspaceName,
+ }))
+ ctl.authInterceptor.token = demoToken
+ a.NoError(err, "a normal session must still be able to leave the workspace")
+ a.False(workspaceHasMember(ctx, t, ctl, demoToken, workspaceName, secondAdminEmail),
+ "the normal leave must actually remove the caller's bindings")
+}
+
+// TestMCPCannotDeleteWorkspace is the DeleteWorkspace half of the same escape.
+// DeleteWorkspace ends in the same switchWorkspaceInternal token mint, and the
+// guard sits ahead of every check in the handler — including the SaaS-only
+// precondition. That placement is what the assertion pins: this build is
+// self-hosted, so with the guard removed the MCP call reaches the SaaS check
+// and comes back FailedPrecondition rather than PermissionDenied.
+func TestMCPCannotDeleteWorkspace(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)
+ workspaceName := workspace.Msg.Name
+
+ out := callAPIViaMCP(ctx, t, ctl, ctl.authInterceptor.token,
+ "WorkspaceService/DeleteWorkspace", map[string]any{"name": workspaceName})
+ t.Logf("MCP DeleteWorkspace → status=%d error=%q token=%q",
+ out.Status, out.Error, out.Response.Token)
+
+ a.Equal(http.StatusForbidden, out.Status,
+ "an MCP session must be refused before any deletion work happens")
+ a.Contains(out.Error, "MCP sessions cannot delete workspaces",
+ "the refusal must come from the MCP guard, ahead of the SaaS precondition")
+ // As in the leave test, the mint is unreachable on a self-hosted fixture,
+ // so this states the invariant rather than discriminating on it.
+ a.Empty(out.Response.Token,
+ "an MCP session must never receive a plain user access token")
+
+ // A normal caller is not intercepted by the guard: it reaches the handler
+ // and is turned away by the deployment-mode check instead.
+ _, err = ctl.workspaceServiceClient.DeleteWorkspace(ctx, connect.NewRequest(&v1pb.DeleteWorkspaceRequest{
+ Name: workspaceName,
+ }))
+ a.Error(err)
+ a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err),
+ "a normal session must reach the handler, not the MCP guard")
+}
+
+// TestMCPOAuthSessionCannotLeaveOrDeleteWorkspace covers the other admission
+// path. The two tests above ride the legacy admission — a plain web-session
+// token pasted into an MCP client — while this one runs the flow a real MCP
+// client performs: RFC 7591 dynamic client registration, PKCE consent, code
+// exchange. Both admissions reach these handlers, so both have to be refused.
+//
+// The grant here consents to mcp:read-only and still reaches two mutating
+// handlers, because nothing enforces the consented scope yet (see
+// common.DelegatedGrant — P1b's capability gate is the intended consumer). A
+// read-only grant is therefore no substitute for this guard.
+func TestMCPOAuthSessionCannotLeaveOrDeleteWorkspace(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)
+
+ oauthToken, _ := mintMCPOAuthToken(t, ctl, ctl.authInterceptor.token)
+
+ for _, tc := range []struct {
+ operation string
+ refusal string
+ }{
+ {"WorkspaceService/LeaveWorkspace", "MCP sessions cannot leave workspaces"},
+ {"WorkspaceService/DeleteWorkspace", "MCP sessions cannot delete workspaces"},
+ } {
+ out := callAPIViaMCP(ctx, t, ctl, oauthToken, tc.operation,
+ map[string]any{"name": workspace.Msg.Name})
+ t.Logf("MCP OAuth %s → status=%d error=%q", tc.operation, out.Status, out.Error)
+
+ a.Equal(http.StatusForbidden, out.Status,
+ "a real MCP OAuth session must be refused by %s", tc.operation)
+ a.Contains(out.Error, tc.refusal,
+ "the refusal must come from the MCP guard")
+ a.Empty(out.Response.Token,
+ "an MCP session must never receive a plain user access token")
+ }
+}