Skip to content

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

feat(mcp): reject MCP tokens on the general API, carry grant state in AuthContext (P1a PR 5a) (#21123)

Vincent Huang88ebfc5345fa
diff --git a/backend/api/auth/auth.go b/backend/api/auth/auth.go
index 4ce1de2670..fd39f59c35 100644
--- a/backend/api/auth/auth.go
+++ b/backend/api/auth/auth.go
@@ -39,8 +39,9 @@ const (
MFATempTokenAudience = "bb.user.mfa-temp"
// OAuth2AccessTokenAudience is the audience OAuth2 access tokens carried
// before they were bound to the MCP resource URI (P1a PR 3). No longer
- // minted; still recognized so tokens issued by a pre-upgrade release keep
- // working until they expire.
+ // minted; still recognized at /mcp so tokens issued by a pre-upgrade
+ // release keep working there until they expire. The general API refuses
+ // it like any other MCP-minted token.
OAuth2AccessTokenAudience = "bb.oauth2.access"
// TokenUseMCP is the token_use claim value marking a token as an MCP OAuth2
// credential. The audience of such a token is a per-deployment resource URI,
@@ -106,7 +107,7 @@ func (in *APIAuthInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFun
}
ctx = context.WithValue(ctx, common.AuthContextKey, authContext)
- user, workspaceID, err := in.getUserConnect(ctx, accessTokenStr, req.Spec().Procedure)
+ user, workspaceID, err := in.getUserConnect(ctx, accessTokenStr)
if err != nil {
if IsAuthenticationSkipped(req.Spec().Procedure, authContext) {
return next(ctx, req)
@@ -141,7 +142,7 @@ func (in *APIAuthInterceptor) WrapStreamingHandler(next connect.StreamingHandler
}
ctx = context.WithValue(ctx, common.AuthContextKey, authContext)
- user, claims, err := in.authenticate(ctx, accessTokenStr, conn.Spec().Procedure)
+ user, claims, err := in.authenticate(ctx, accessTokenStr)
if err != nil {
if IsAuthenticationSkipped(conn.Spec().Procedure, authContext) {
return next(ctx, conn)
@@ -178,37 +179,53 @@ func (c *authStreamingConn) Receive(msg any) error {
return c.StreamingHandlerConn.Receive(msg)
}
+// isMCPProvenance reports whether parsed claims identify a token minted by
+// the MCP authorization server: the modern shape carries token_use=mcp
+// (whatever audience it also carries), and the legacy pre-PR-3 shape is
+// recognized by its bb.oauth2.access audience, which nothing else ever
+// minted. The general-API rejection and IsMCPOriginatedToken (behind
+// SwitchWorkspace's guard) key on this one definition — keep them keying on
+// it: two security decision points drifting apart is how one surface ends up
+// admitting what the other refuses.
+func isMCPProvenance(tokenUse string, audience jwt.ClaimStrings) bool {
+ return tokenUse == TokenUseMCP || audienceContains(audience, OAuth2AccessTokenAudience)
+}
+
// checkTokenAudience decides whether a token's audience admits it to the
-// general (non-/mcp) API. The fixed audiences — web sessions and OAuth2 tokens
-// minted before the audience became the MCP resource URI — pass unflagged. An
-// MCP resource-bound token is recognized by token_use (its audience varies per
-// deployment) and reported as mcpToken so the caller can audit-log it.
-// Anything else is refused.
-func checkTokenAudience(claims *claimsMessage) (mcpToken bool, err error) {
- if audienceContains(claims.Audience, AccessTokenAudience) || audienceContains(claims.Audience, OAuth2AccessTokenAudience) {
- return false, nil
- }
- if claims.TokenUse == TokenUseMCP {
- // Admitted and audit-logged, not rejected: until PR 4's private
- // in-memory transport lands, /mcp tool calls reach this interceptor
- // carrying the inbound bearer, so rejecting here would break every MCP
- // tool call. PR 5 replaces this admission with a rejection after that
- // cutover (spec §"PR 3" / §"PR 5").
- return true, nil
- }
- return false, errs.Errorf(
- "invalid access token, audience mismatch, got %q, expected %q or %q",
+// general (non-/mcp) API. An MCP token (isMCPProvenance) is refused outright:
+// since PR 4's private in-memory transport, /mcp tool traffic authenticates
+// with the internal delegated credential, so nothing legitimate presents one
+// here anymore and admitting it would keep it a universal API bearer (P1a PR
+// 5, retiring PR 3's audit-only admission; the legacy audience keeps draining
+// at /mcp only, where old-replica tool traffic genuinely needs it during a
+// rolling upgrade). Web session tokens pass; anything else is refused.
+func checkTokenAudience(claims *claimsMessage) error {
+ if isMCPProvenance(claims.TokenUse, claims.Audience) {
+ // Warn rather than refuse silently: the audit-only observation window
+ // the spec planned never shipped in a release, so this is the only
+ // server-side signal that an integration was relying on the old
+ // admission. Denial auditing proper is PR 5b.
+ slog.Warn("refused an MCP token on the general API",
+ slog.String("principal", claims.Subject),
+ slog.String("workspace", claims.WorkspaceID),
+ slog.String("audience", strings.Join(claims.Audience, ",")),
+ slog.String("token_use", claims.TokenUse))
+ return errs.New("MCP tokens are only accepted at /mcp; use a service account for the API")
+ }
+ if audienceContains(claims.Audience, AccessTokenAudience) {
+ return nil
+ }
+ return errs.Errorf(
+ "invalid access token, audience mismatch, got %q, expected %q",
claims.Audience,
AccessTokenAudience,
- OAuth2AccessTokenAudience,
)
}
// authenticate is the shared authentication logic that validates JWT tokens.
// Returns the user and claims, or an error. This is the single source of truth
-// for token validation. procedure names the RPC (or surface) being
-// authenticated; it only feeds the audit log for MCP tokens on the general API.
-func (in *APIAuthInterceptor) authenticate(ctx context.Context, accessTokenStr, procedure string) (*store.UserMessage, *claimsMessage, error) {
+// for token validation.
+func (in *APIAuthInterceptor) authenticate(ctx context.Context, accessTokenStr string) (*store.UserMessage, *claimsMessage, error) {
if accessTokenStr == "" {
return nil, nil, errs.New("access token not found")
}
@@ -231,18 +248,9 @@ func (in *APIAuthInterceptor) authenticate(ctx context.Context, accessTokenStr,
return nil, nil, errs.New("failed to parse claim")
}
- mcpToken, err := checkTokenAudience(claims)
- if err != nil {
+ if err := checkTokenAudience(claims); err != nil {
return nil, nil, err
}
- if mcpToken {
- slog.Info("MCP resource-bound token used on the general API (audit-only this release)",
- slog.String("token_use", claims.TokenUse),
- slog.String("method", procedure),
- slog.String("principal", claims.Subject),
- slog.String("workspace", claims.WorkspaceID),
- slog.String("audience", strings.Join(claims.Audience, ",")))
- }
user, err := resolvePrincipal(ctx, in.store, in.profile, claims.Subject, claims.WorkspaceID)
if err != nil {
@@ -331,8 +339,8 @@ func verifyWorkspaceMembership(ctx context.Context, stores *store.Store, profile
}
// authenticateConnect is a ConnectRPC-specific version that returns ConnectRPC errors.
-func (in *APIAuthInterceptor) authenticateConnect(ctx context.Context, accessTokenStr, procedure string) (*store.UserMessage, *claimsMessage, error) {
- user, claims, err := in.authenticate(ctx, accessTokenStr, procedure)
+func (in *APIAuthInterceptor) authenticateConnect(ctx context.Context, accessTokenStr string) (*store.UserMessage, *claimsMessage, error) {
+ user, claims, err := in.authenticate(ctx, accessTokenStr)
if err != nil {
return nil, nil, connect.NewError(connect.CodeUnauthenticated, err)
}
@@ -341,8 +349,8 @@ func (in *APIAuthInterceptor) authenticateConnect(ctx context.Context, accessTok
// getUserConnect is a ConnectRPC-specific version that returns ConnectRPC errors.
// Returns the user and workspace ID from the token claims.
-func (in *APIAuthInterceptor) getUserConnect(ctx context.Context, accessTokenStr, procedure string) (*store.UserMessage, string, error) {
- user, claims, err := in.authenticateConnect(ctx, accessTokenStr, procedure)
+func (in *APIAuthInterceptor) getUserConnect(ctx context.Context, accessTokenStr string) (*store.UserMessage, string, error) {
+ user, claims, err := in.authenticateConnect(ctx, accessTokenStr)
if err != nil {
return nil, "", err
}
@@ -383,9 +391,9 @@ func GetUserEmailAndLoginMethodFromMFATempToken(token, secret string) (string, s
// AuthenticateToken validates a JWT access token and returns the user and token expiry.
// This is a non-ConnectRPC version that returns regular errors instead of ConnectRPC errors.
-// Its only caller is the LSP websocket handshake, hence the fixed surface label.
+// Its only caller is the LSP websocket handshake.
func (in *APIAuthInterceptor) AuthenticateToken(ctx context.Context, accessTokenStr string) (*store.UserMessage, string, time.Time, error) {
- user, claims, err := in.authenticate(ctx, accessTokenStr, "/lsp")
+ user, claims, err := in.authenticate(ctx, accessTokenStr)
if err != nil {
return nil, "", time.Time{}, err
}
diff --git a/backend/api/auth/auth_test.go b/backend/api/auth/auth_test.go
index 6e2c552428..95ccb683a0 100644
--- a/backend/api/auth/auth_test.go
+++ b/backend/api/auth/auth_test.go
@@ -7,11 +7,11 @@ import (
"github.com/stretchr/testify/require"
)
-// TestCheckTokenAudience pins the general-API audience policy for P1a PR 3:
-// the fixed audiences keep working, an MCP resource-bound token (token_use=mcp)
-// is admitted but flagged for audit logging, and everything else is refused.
-// PR 5 replaces the admission with a rejection once PR 4's private transport
-// stops /mcp tool calls from carrying the inbound bearer here.
+// TestCheckTokenAudience pins the general-API audience policy for P1a PR 5:
+// the fixed audiences keep working, an MCP token (token_use=mcp) is refused
+// outright — since PR 4's private transport, /mcp tool traffic never presents
+// it here, so any appearance is a leaked or misused token, not tool traffic —
+// and everything else is refused as an audience mismatch.
func TestCheckTokenAudience(t *testing.T) {
claimsWith := func(aud string, tokenUse string) *claimsMessage {
return &claimsMessage{
@@ -20,26 +20,40 @@ func TestCheckTokenAudience(t *testing.T) {
}
}
- t.Run("web session audience is accepted and not flagged", func(t *testing.T) {
- mcpToken, err := checkTokenAudience(claimsWith(AccessTokenAudience, ""))
+ t.Run("web session audience is accepted", func(t *testing.T) {
+ err := checkTokenAudience(claimsWith(AccessTokenAudience, ""))
require.NoError(t, err)
- require.False(t, mcpToken)
})
- t.Run("legacy oauth2 audience is accepted and not flagged", func(t *testing.T) {
- mcpToken, err := checkTokenAudience(claimsWith(OAuth2AccessTokenAudience, ""))
- require.NoError(t, err)
- require.False(t, mcpToken)
+ t.Run("legacy oauth2 audience is refused: it is MCP-minted too", func(t *testing.T) {
+ // bb.oauth2.access was only ever minted by the MCP authorization
+ // server (pre-PR-3, before tokens carried token_use), so it is an MCP
+ // token by provenance and gets the same refusal. Unlike at /mcp, no
+ // legitimate traffic drains through here: the pre-PR-4 loopback
+ // transport dialed its own replica, so even mid-rolling-upgrade no old
+ // replica ever lands a legacy bearer on this chain.
+ err := checkTokenAudience(claimsWith(OAuth2AccessTokenAudience, ""))
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "only accepted at /mcp")
})
- t.Run("mcp resource-bound token is admitted but flagged for auditing", func(t *testing.T) {
- mcpToken, err := checkTokenAudience(claimsWith(testResource, TokenUseMCP))
- require.NoError(t, err)
- require.True(t, mcpToken)
+ t.Run("mcp resource-bound token is refused", func(t *testing.T) {
+ err := checkTokenAudience(claimsWith(testResource, TokenUseMCP))
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "only accepted at /mcp")
+ })
+
+ t.Run("token_use=mcp is refused even with the accepted fixed audience", func(t *testing.T) {
+ // Nothing mints this combination; if one ever appears, the MCP marker
+ // must win over the audience allowlist — the rejection keys on what the
+ // token IS, not on which audience it also happens to carry.
+ err := checkTokenAudience(claimsWith(AccessTokenAudience, TokenUseMCP))
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "only accepted at /mcp")
})
t.Run("unknown audience without token_use is refused", func(t *testing.T) {
- _, err := checkTokenAudience(claimsWith("wrong.audience", ""))
+ err := checkTokenAudience(claimsWith("wrong.audience", ""))
require.Error(t, err)
require.Contains(t, err.Error(), "audience mismatch")
})
diff --git a/backend/api/auth/internal_credential.go b/backend/api/auth/internal_credential.go
index 0afee90ee6..01dbab7323 100644
--- a/backend/api/auth/internal_credential.go
+++ b/backend/api/auth/internal_credential.go
@@ -114,7 +114,7 @@ func IsMCPOriginatedToken(tokenStr, secret string) bool {
if err != nil {
return false
}
- return claims.TokenUse == TokenUseMCP || audienceContains(claims.Audience, OAuth2AccessTokenAudience)
+ return isMCPProvenance(claims.TokenUse, claims.Audience)
}
// VerifyInternalMCPToken validates a delegated credential and returns its
diff --git a/backend/api/auth/internal_credential_test.go b/backend/api/auth/internal_credential_test.go
index 36548ea571..0e5dfef227 100644
--- a/backend/api/auth/internal_credential_test.go
+++ b/backend/api/auth/internal_credential_test.go
@@ -33,8 +33,10 @@ func TestInternalMCPCredentialRoundTrip(t *testing.T) {
}
// 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.
+// bb.user.access at /mcp, pre-scope OAuth2 tokens) mint a credential with
+// empty scope and resource, carried verbatim into common.AuthContext — P1b,
+// not this layer, resolves what empty grant state may do
+// (common.DelegatedGrant).
func TestInternalMCPCredentialEmptyGrantState(t *testing.T) {
cred := testDelegatedCredential()
cred.Scope = ""
@@ -88,23 +90,22 @@ func TestGeneralAPIRejectsInternalMCPCredential(t *testing.T) {
require.NoError(t, err)
in := New(nil, testSecret, nil, nil, nil)
- _, _, err = in.authenticate(context.Background(), tokenStr, "/bytebase.v1.SQLService/Query")
+ _, _, err = in.authenticate(context.Background(), tokenStr)
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.
+// part of that — the claim is absent, so the audience mismatch branch refuses
+// it rather than the MCP rejection (which keys on token_use == TokenUseMCP).
func TestCheckTokenAudienceRejectsInternalCredential(t *testing.T) {
claims := &claimsMessage{
RegisteredClaims: jwt.RegisteredClaims{
Audience: jwt.ClaimStrings{internalMCPAudience},
},
}
- _, err := checkTokenAudience(claims)
- require.Error(t, err)
+ require.Error(t, checkTokenAudience(claims))
}
// TestVerifyInternalMCPTokenRejectsPublicTokens is the mirror boundary: the
diff --git a/backend/api/auth/internal_interceptor.go b/backend/api/auth/internal_interceptor.go
index e22ebc3394..d00909b16f 100644
--- a/backend/api/auth/internal_interceptor.go
+++ b/backend/api/auth/internal_interceptor.go
@@ -58,6 +58,16 @@ func (in *InternalMCPAuthInterceptor) WrapUnary(next connect.UnaryFunc) connect.
if err != nil {
return nil, err
}
+ // The credential's grant state travels verbatim into the AuthContext —
+ // this is the contract P1b's enforcement keys on (see
+ // common.DelegatedGrant for the empty-state semantics). Grant state
+ // only: the principal is re-resolved below, and RBAC downstream.
+ authContext.DelegatedGrant = &common.DelegatedGrant{
+ Scope: cred.Scope,
+ Resource: cred.Resource,
+ ClientID: cred.ClientID,
+ CorrelationID: cred.CorrelationID,
+ }
ctx = context.WithValue(ctx, common.AuthContextKey, authContext)
user, err := resolvePrincipal(ctx, in.store, in.profile, cred.Principal, cred.WorkspaceID)
diff --git a/backend/api/auth/internal_interceptor_livestate_test.go b/backend/api/auth/internal_interceptor_livestate_test.go
new file mode 100644
index 0000000000..4bfd1b9ca1
--- /dev/null
+++ b/backend/api/auth/internal_interceptor_livestate_test.go
@@ -0,0 +1,223 @@
+package auth
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/emptypb"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/component/config"
+ "github.com/bytebase/bytebase/backend/migrator"
+ "github.com/bytebase/bytebase/backend/store"
+
+ _ "github.com/bytebase/bytebase/backend/plugin/db/pg"
+)
+
+const (
+ liveWorkspace = "ws-live"
+ liveUserEmail = "[email protected]"
+ liveClientID = "client-A"
+ liveResource = "https://bb.example.com/mcp"
+)
+
+// procedureRequest overrides a request's Spec so the interceptor sees a real
+// registered procedure — getAuthContext resolves it through the proto registry,
+// which connect.NewRequest alone leaves empty.
+type procedureRequest struct {
+ connect.AnyRequest
+ procedure string
+}
+
+func (r *procedureRequest) Spec() connect.Spec {
+ return connect.Spec{Procedure: r.procedure}
+}
+
+func newProcedureRequest(t *testing.T, bearer string) *procedureRequest {
+ t.Helper()
+ req := connect.NewRequest(&emptypb.Empty{})
+ req.Header().Set("Authorization", "Bearer "+bearer)
+ return &procedureRequest{AnyRequest: req, procedure: "/bytebase.v1.SQLService/Query"}
+}
+
+// newLiveStore boots a migrated store with one workspace and one member, so
+// resolvePrincipal has real state to re-resolve against.
+func newLiveStore(t *testing.T) *store.Store {
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+
+ db := container.GetDB()
+ require.NoError(t, migrator.MigrateSchema(ctx, db))
+ _, err := db.ExecContext(ctx, fmt.Sprintf(`
+ INSERT INTO workspace (resource_id) VALUES ('%s');
+ INSERT INTO principal (name, email, password_hash) VALUES ('live', '%s', 'unused');
+ `, liveWorkspace, liveUserEmail))
+ require.NoError(t, err)
+
+ pgURL := fmt.Sprintf(
+ "host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort(),
+ )
+ st, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+
+ _, err = st.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{
+ Workspace: liveWorkspace,
+ Member: common.FormatUserEmail(liveUserEmail),
+ Roles: []string{"roles/workspaceMember"},
+ })
+ require.NoError(t, err)
+ return st
+}
+
+// TestInternalInterceptorPopulatesDelegatedGrant pins the AuthContext contract
+// P1b keys on: every internal-chain request carries the verified credential's
+// grant state — scope, resource, client, correlation — verbatim, and the two
+// empty-scope states stay distinguishable (see common.DelegatedGrant). The
+// public chain carries none.
+func TestInternalInterceptorPopulatesDelegatedGrant(t *testing.T) {
+ st := newLiveStore(t)
+ in := NewInternalMCPAuthInterceptor(st, testSecret, &config.Profile{})
+
+ capture := func(t *testing.T, interceptor connect.Interceptor, bearer string) *common.AuthContext {
+ t.Helper()
+ var captured *common.AuthContext
+ next := func(ctx context.Context, _ connect.AnyRequest) (connect.AnyResponse, error) {
+ captured, _ = common.GetAuthContextFromContext(ctx)
+ return nil, nil
+ }
+ _, err := interceptor.WrapUnary(next)(context.Background(), newProcedureRequest(t, bearer))
+ require.NoError(t, err)
+ require.NotNil(t, captured)
+ return captured
+ }
+
+ rows := []struct {
+ name string
+ cred DelegatedMCPCredential
+ }{
+ {
+ name: "a consented grant travels verbatim",
+ cred: DelegatedMCPCredential{
+ Principal: liveUserEmail,
+ WorkspaceID: liveWorkspace,
+ ClientID: liveClientID,
+ CorrelationID: "corr-1",
+ Scope: "mcp:read-only",
+ Resource: liveResource,
+ },
+ },
+ {
+ name: "legacy pre-grant session: scope and resource both empty",
+ cred: DelegatedMCPCredential{
+ Principal: liveUserEmail,
+ WorkspaceID: liveWorkspace,
+ CorrelationID: "corr-2",
+ },
+ },
+ {
+ // A grant that recorded no scope: a scope-less consent (permanent
+ // population) or a PR-3-era mint during a rolling upgrade
+ // (transient, and its grant DID record a scope). The populated
+ // resource is what keeps it distinguishable from the genuinely
+ // pre-grant row above — collapsing the two could widen a consented
+ // read-only session to full legacy semantics.
+ name: "grant-backed token: resource present, scope empty",
+ cred: DelegatedMCPCredential{
+ Principal: liveUserEmail,
+ WorkspaceID: liveWorkspace,
+ ClientID: liveClientID,
+ CorrelationID: "corr-3",
+ Resource: liveResource,
+ },
+ },
+ }
+ for _, row := range rows {
+ t.Run(row.name, func(t *testing.T) {
+ token, err := GenerateInternalMCPToken(row.cred, testSecret)
+ require.NoError(t, err)
+
+ captured := capture(t, in, token)
+ require.NotNil(t, captured.DelegatedGrant,
+ "every internal-chain request must carry its delegated grant state")
+ require.Equal(t, row.cred.Scope, captured.DelegatedGrant.Scope)
+ require.Equal(t, row.cred.Resource, captured.DelegatedGrant.Resource)
+ require.Equal(t, row.cred.ClientID, captured.DelegatedGrant.ClientID)
+ require.Equal(t, row.cred.CorrelationID, captured.DelegatedGrant.CorrelationID)
+ })
+ }
+
+ t.Run("the public chain carries no delegated grant", func(t *testing.T) {
+ webToken, err := GenerateAccessToken(liveUserEmail, liveWorkspace, testSecret, time.Hour)
+ require.NoError(t, err)
+
+ pub := New(st, testSecret, nil, nil, &config.Profile{})
+ captured := capture(t, pub, webToken)
+ require.Nil(t, captured.DelegatedGrant,
+ "a public-chain request must leave the delegated grant zero-valued")
+ })
+}
+
+// TestInternalChainMembershipRevocationTakesEffectNextRequest pins the
+// property the delegated credential rests on: it carries identity and grant
+// state only, so authorization-relevant state — here workspace membership — is
+// re-resolved against the store on EVERY internal request. Revoking membership
+// must bite on the very next request with the SAME still-valid credential: no
+// re-consent, no token expiry involved. If a refactor ever starts trusting the
+// credential for authorization state, this goes red.
+func TestInternalChainMembershipRevocationTakesEffectNextRequest(t *testing.T) {
+ ctx := context.Background()
+ st := newLiveStore(t)
+ in := NewInternalMCPAuthInterceptor(st, testSecret, &config.Profile{})
+
+ token, err := GenerateInternalMCPToken(DelegatedMCPCredential{
+ Principal: liveUserEmail,
+ WorkspaceID: liveWorkspace,
+ ClientID: liveClientID,
+ CorrelationID: "corr-live",
+ Scope: "mcp:read-only",
+ Resource: liveResource,
+ }, testSecret)
+ require.NoError(t, err)
+
+ call := func() (reached bool, err error) {
+ next := func(_ context.Context, _ connect.AnyRequest) (connect.AnyResponse, error) {
+ reached = true
+ return nil, nil
+ }
+ _, err = in.WrapUnary(next)(context.Background(), newProcedureRequest(t, token))
+ return reached, err
+ }
+
+ reached, err := call()
+ require.NoError(t, err)
+ require.True(t, reached)
+
+ setRoles := func(roles []string) {
+ _, err := st.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{
+ Workspace: liveWorkspace,
+ Member: common.FormatUserEmail(liveUserEmail),
+ Roles: roles,
+ })
+ require.NoError(t, err)
+ }
+
+ setRoles(nil) // revoke the membership entirely
+ reached, err = call()
+ require.Error(t, err, "the same credential must stop working the moment membership is revoked")
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ require.False(t, reached, "no handler may run for a revoked member")
+
+ // Live in both directions, not a one-way latch: restoring membership
+ // restores service with the unchanged credential.
+ setRoles([]string{"roles/workspaceMember"})
+ reached, err = call()
+ require.NoError(t, err)
+ require.True(t, reached)
+}
diff --git a/backend/api/mcp/internal_transport_test.go b/backend/api/mcp/internal_transport_test.go
index 4fa572d51a..164f238772 100644
--- a/backend/api/mcp/internal_transport_test.go
+++ b/backend/api/mcp/internal_transport_test.go
@@ -85,8 +85,8 @@ func TestMCPAuthMiddlewareMintsDelegatedCredential(t *testing.T) {
// 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.
+// EMPTY grant state — no scope, no resource. PR 5 carries that state verbatim
+// into common.AuthContext; P1b resolves it (common.DelegatedGrant).
func TestMCPAuthMiddlewareLegacySessionEmptyGrantState(t *testing.T) {
secret := "test-secret-key"
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.go
index 3af3134306..f5a1c0c7c8 100644
--- a/backend/api/mcp/server.go
+++ b/backend/api/mcp/server.go
@@ -197,10 +197,10 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
// 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.
+ // copied verbatim from the inbound token — empty for legacy sessions
+ // (common.DelegatedGrant documents the empty-state semantics; P1b
+ // resolves them). Identity only, no roles: downstream authorization
+ // re-resolves live exactly as for a public request.
delegated := auth.DelegatedMCPCredential{
Principal: sub,
WorkspaceID: workspaceID,
@@ -495,13 +495,11 @@ func grantScope(claims jwt.MapClaims) string {
// (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.
+// Resource is therefore what distinguishes a grant-backed session with an
+// empty scope (a scope-less consent, or a PR-3-era token predating the scope
+// claim) from a genuinely pre-grant one, which carries neither.
+// common.DelegatedGrant — where PR 5 carries both values verbatim — documents
+// why the two must never collapse.
func grantResource(claims jwt.MapClaims, aud any) string {
tokenUse, ok := claims["token_use"].(string)
if !ok || tokenUse != auth.TokenUseMCP {
diff --git a/backend/api/oauth2/grant_test.go b/backend/api/oauth2/grant_test.go
index 0538b921d7..a780ca7a6d 100644
--- a/backend/api/oauth2/grant_test.go
+++ b/backend/api/oauth2/grant_test.go
@@ -471,11 +471,14 @@ func TestResourceScopeGrantLifecycle(t *testing.T) {
"an empty flag must resolve the audience from the workspace setting")
})
- t.Run("an MCP token still authenticates on the general API (audit-only this release)", func(t *testing.T) {
- // Until PR 4's private transport, /mcp tool calls forward the inbound
- // bearer to the general API, so this admission is what keeps every MCP
- // tool call working. PR 5 flips rejectMCPTokenOnGeneralAPI to retire it;
- // this test is the tripwire against flipping it early by accident.
+ t.Run("an MCP token is refused on the general API but keeps serving /mcp", func(t *testing.T) {
+ // PR 4's private transport took /mcp tool traffic off the general API,
+ // so PR 5 retired the audit-only admission this subtest used to pin: an
+ // MCP token is refused outright on the general API — even for a
+ // principal with a valid workspace membership, which is why the policy
+ // patch stays — while /mcp keeps accepting the same token. A regression
+ // that re-admits it would make every MCP token a universal API bearer
+ // again.
_, err := st.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{
Workspace: testWorkspace,
Member: common.FormatUserEmail(testUserEmail),
@@ -492,11 +495,13 @@ func TestResourceScopeGrantLifecycle(t *testing.T) {
"client_id": {testClientID},
})
+ require.Equal(t, http.StatusOK, mcpStatus(t, st, "https://bb.example.com", got.AccessToken),
+ "the same token must keep working at /mcp")
+
interceptor := auth.New(st, testSecret, nil, nil, &config.Profile{})
- user, workspaceID, _, err := interceptor.AuthenticateToken(ctx, got.AccessToken)
- require.NoError(t, err)
- require.Equal(t, testUserEmail, user.Email)
- require.Equal(t, testWorkspace, workspaceID)
+ _, _, _, err = interceptor.AuthenticateToken(ctx, got.AccessToken)
+ require.Error(t, err, "an MCP token must not authenticate on the general API")
+ require.Contains(t, err.Error(), "only accepted at /mcp")
})
t.Run("a requested scope set is consented as its maximum", func(t *testing.T) {
diff --git a/backend/api/v1/acl.go b/backend/api/v1/acl.go
index ce49c95c3f..f7cff88428 100644
--- a/backend/api/v1/acl.go
+++ b/backend/api/v1/acl.go
@@ -187,11 +187,15 @@ func (in *ACLInterceptor) doACLCheck(ctx context.Context, request any, fullMetho
// Example: "bb.roles.update" -> "bb.roles.create"
createPerm := strings.Replace(string(authContext.Permission), ".update", ".create", 1)
- // Create a new auth context for create permission check
+ // Create a new auth context for create permission check. It must keep
+ // carrying the delegated grant state: this secondary check is the same
+ // request, and shedding the marker would let a future grant-keyed gate
+ // evaluate an MCP-originated request as public-chain.
createAuthContext := &common.AuthContext{
- Permission: permission.Permission(createPerm),
- AuthMethod: authContext.AuthMethod,
- Resources: authContext.Resources,
+ Permission: permission.Permission(createPerm),
+ AuthMethod: authContext.AuthMethod,
+ Resources: authContext.Resources,
+ DelegatedGrant: authContext.DelegatedGrant,
}
ok, extra, err := doIAMPermissionCheck(ctx, in.iamManager, fullMethod, user, createAuthContext)
if err != nil {
diff --git a/backend/common/context.go b/backend/common/context.go
index 6bf43ce61e..e9f4043884 100644
--- a/backend/common/context.go
+++ b/backend/common/context.go
@@ -84,12 +84,55 @@ type Resource struct {
ID string
}
+// DelegatedGrant is the OAuth2 grant state of the delegated MCP credential a
+// request arrived with on the internal MCP transport. It is grant identity,
+// not authorization state: roles and membership are re-resolved live per
+// request, and nothing enforces on these values yet — P1b's capability gate is
+// the consumer this shape is the contract for.
+//
+// Scope and Resource are the grant's STORED values, copied verbatim from the
+// verified credential, and their empty states are load-bearing:
+//
+// - Scope and Resource both empty: a genuinely pre-grant legacy session — a
+// plain web-session token at /mcp, or an OAuth2 token from before grants
+// recorded scope and resource.
+// - Scope empty, Resource present: a grant that recorded no scope. Two
+// indistinguishable origins: a client that omitted `scope` at consent — a
+// permanent, steady-state population — or, transiently, a token minted by
+// a PR-3-era replica during a rolling upgrade, whose grant DID record a
+// consented scope that the claim predates. Neither may be collapsed into
+// the pre-grant case: that could widen a consented read-only session to
+// full legacy semantics. P1b resolves this state most-restrictively.
+//
+// No store lookup recovers a missing scope, deliberately: the steady-state
+// population has nothing to recover (the grant stored none), the transient
+// one self-drains within an access-token lifetime and its refresh-token row
+// is keyed by a (client_id, token_hash) the credential does not carry, and
+// nothing enforces on the value yet.
+type DelegatedGrant struct {
+ // Scope is the consented permission-set name (e.g. "mcp:read-only");
+ // empty in the two states above.
+ Scope string
+ // Resource is the grant's stored MCP resource URI.
+ Resource string
+ // ClientID is the OAuth2 client the grant was consented to.
+ ClientID string
+ // CorrelationID identifies the delegation this request rode in on. It is
+ // minted at the /mcp boundary and session-scoped in practice: tool
+ // handlers run on their session's initialize-time identity.
+ CorrelationID string
+}
+
type AuthContext struct {
Audit bool
AllowWithoutCredential bool
Permission string
AuthMethod AuthMethod
Resources []*Resource
+ // DelegatedGrant carries the grant state of the delegated MCP credential
+ // on internal-chain requests; nil on the public chain. Presence, not any
+ // field value, marks a request as MCP-originated.
+ DelegatedGrant *DelegatedGrant
}
func GetAuthContextFromContext(ctx context.Context) (*AuthContext, bool) {
diff --git a/backend/tests/mcp_token_boundary_test.go b/backend/tests/mcp_token_boundary_test.go
new file mode 100644
index 0000000000..2cad5884b0
--- /dev/null
+++ b/backend/tests/mcp_token_boundary_test.go
@@ -0,0 +1,159 @@
+package tests
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "html"
+ "io"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"
+
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+// mintMCPOAuthToken runs the full OAuth2 flow a real MCP client performs
+// against the live server — RFC 7591 dynamic client registration, PKCE
+// consent, code exchange — and returns the resource-bound access token.
+func mintMCPOAuthToken(t *testing.T, ctl *controller) string {
+ t.Helper()
+ httpClient := &http.Client{}
+ redirectURI := "http://localhost/cb"
+
+ resp, err := httpClient.Post(ctl.rootURL+"/api/oauth2/register", "application/json",
+ strings.NewReader(`{"client_name":"bb-e2e","redirect_uris":["http://localhost/cb"],"grant_types":["authorization_code"],"token_endpoint_auth_method":"none"}`))
+ require.NoError(t, err)
+ defer resp.Body.Close()
+ var reg struct {
+ ClientID string `json:"client_id"`
+ }
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&reg))
+ require.NotEmpty(t, reg.ClientID)
+
+ // 43-128 chars per RFC 7636.
+ verifier := "e2eVerifier_e2eVerifier_e2eVerifier_e2eVerifier"
+ challenge := sha256.Sum256([]byte(verifier))
+ form := url.Values{
+ "client_id": {reg.ClientID},
+ "redirect_uri": {redirectURI},
+ "state": {"e2e-state"},
+ "code_challenge": {base64.RawURLEncoding.EncodeToString(challenge[:])},
+ "code_challenge_method": {"S256"},
+ "action": {"allow"},
+ "resource": {ctl.rootURL + "/mcp"},
+ "scope": {"mcp:read-only"},
+ }
+ req, err := http.NewRequest(http.MethodPost, ctl.rootURL+"/api/oauth2/authorize", strings.NewReader(form.Encode()))
+ require.NoError(t, err)
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Authorization", "Bearer "+ctl.authInterceptor.token)
+ consentResp, err := httpClient.Do(req)
+ require.NoError(t, err)
+ defer consentResp.Body.Close()
+ consentBody, err := io.ReadAll(consentResp.Body)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, consentResp.StatusCode, string(consentBody))
+
+ // The authorize handler renders a meta-refresh page instead of a 302 to
+ // sidestep CSP form-action restrictions; the callback URL carries the code.
+ matches := regexp.MustCompile(`content="0;url=([^"]+)"`).FindStringSubmatch(string(consentBody))
+ require.Len(t, matches, 2, "expected a meta-refresh redirect, got: %s", string(consentBody))
+ callback, err := url.Parse(html.UnescapeString(matches[1]))
+ require.NoError(t, err)
+ require.Empty(t, callback.Query().Get("error"), callback.Query().Get("error_description"))
+ code := callback.Query().Get("code")
+ require.NotEmpty(t, code)
+
+ tokenResp, err := httpClient.PostForm(ctl.rootURL+"/api/oauth2/token", url.Values{
+ "grant_type": {"authorization_code"},
+ "code": {code},
+ "redirect_uri": {redirectURI},
+ "code_verifier": {verifier},
+ "client_id": {reg.ClientID},
+ })
+ require.NoError(t, err)
+ defer tokenResp.Body.Close()
+ tokenBody, err := io.ReadAll(tokenResp.Body)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, tokenResp.StatusCode, string(tokenBody))
+ var token struct {
+ AccessToken string `json:"access_token"`
+ }
+ require.NoError(t, json.Unmarshal(tokenBody, &token))
+ require.NotEmpty(t, token.AccessToken)
+ return token.AccessToken
+}
+
+// TestMCPTokenIsRejectedOnGeneralAPI is the P1a PR 5 boundary e2e: a real
+// resource-bound MCP OAuth2 token — minted by the live server through the full
+// registration/consent/exchange flow — keeps driving its MCP session's tool
+// calls, while the very same bearer is refused by the public v1 API. Tool
+// traffic is unaffected because since PR 4 it authenticates with the delegated
+// credential minted at the /mcp boundary, never with this token; anything
+// presenting an MCP token to the general API is therefore a leaked or misused
+// token, and refusing it is what ends the token's life as a universal API
+// bearer.
+func TestMCPTokenIsRejectedOnGeneralAPI(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)
+
+ mcpToken := mintMCPOAuthToken(t, ctl)
+
+ 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: mcpToken}},
+ }, nil)
+ a.NoError(err)
+ defer session.Close()
+
+ // call_api reports internal-API failures in its structured output (it never
+ // sets IsError), so the assertion that tool calls keep working must be on
+ // the status the internal chain actually returned.
+ callTool := func() {
+ result, err := session.CallTool(ctx, &mcp.CallToolParams{
+ Name: "call_api",
+ Arguments: map[string]any{"operationId": "ProjectService/ListProjects"},
+ })
+ a.NoError(err)
+ raw, err := json.Marshal(result.StructuredContent)
+ a.NoError(err)
+ var out struct {
+ Status int `json:"status"`
+ Error string `json:"error"`
+ }
+ a.NoError(json.Unmarshal(raw, &out))
+ a.Equal(http.StatusOK, out.Status,
+ "tool calls must keep working for an MCP-audience token: %s", out.Error)
+ }
+ callTool()
+
+ // The very same bearer on the public v1 API is refused before any identity
+ // resolution — the principal behind it is a workspace admin, so anything
+ // but Unauthenticated here would mean the token still works as an API key.
+ asMCPToken := v1connect.NewProjectServiceClient(ctl.client, ctl.rootURL,
+ connect.WithInterceptors(&authInterceptor{token: mcpToken}))
+ _, err = asMCPToken.ListProjects(ctx, connect.NewRequest(&v1pb.ListProjectsRequest{}))
+ a.Error(err, "an MCP token must not be a general API bearer")
+ a.Equal(connect.CodeUnauthenticated, connect.CodeOf(err))
+ a.Contains(err.Error(), "only accepted at /mcp")
+
+ // The refusal is a property of the public surface, not damage to the MCP
+ // session: the same token's tool calls still work afterwards.
+ callTool()
+}