Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(mcp): bind OAuth2 tokens to the MCP resource audience (P1a PR 3) (#21101)
Vincent Huangf7dd87d2a594
diff --git a/backend/api/auth/auth.go b/backend/api/auth/auth.goindex c6d1ec0d2f..7fb87495cf 100644--- a/backend/api/auth/auth.go+++ b/backend/api/auth/auth.go@@ -4,6 +4,7 @@ package authimport ("context""errors"+ "log/slog""net/http""slices""strings"@@ -36,11 +37,26 @@ const (AccessTokenAudience = "bb.user.access"// MFATempTokenAudience is the audience for MFA temporary tokens.MFATempTokenAudience = "bb.user.mfa-temp"- // OAuth2AccessTokenAudience is the audience for OAuth2 access tokens.+ // 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.OAuth2AccessTokenAudience = "bb.oauth2.access"- apiTokenDuration = 1 * time.Hour+ // 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,+ // so consumers that need to recognize "an MCP token, whatever the deployment"+ // (the general API interceptor, the SwitchWorkspace guard) key on this claim+ // instead of the audience.+ TokenUseMCP = "mcp"+ apiTokenDuration = 1 * time.Hour// DefaultAccessTokenDuration is the default access token expiration duration.DefaultAccessTokenDuration = 1 * time.Hour+ // OAuth2AccessTokenDuration is the lifetime of OAuth2 (MCP) access tokens,+ // minted by the oauth2 token endpoint. It also bounds how long legacy+ // bb.oauth2.access acceptance at /mcp outlives an upgrade: nothing mints+ // that audience anymore, so acceptance drains no later than one of these+ // lifetimes after the last legacy-capable replica leaves service.+ OAuth2AccessTokenDuration = 1 * time.Hour// DefaultRefreshTokenDuration is the default refresh token expiration duration.DefaultRefreshTokenDuration = 7 * 24 * time.Hour@@ -90,7 +106,7 @@ func (in *APIAuthInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFun}ctx = context.WithValue(ctx, common.AuthContextKey, authContext)- user, workspaceID, err := in.getUserConnect(ctx, accessTokenStr)+ user, workspaceID, err := in.getUserConnect(ctx, accessTokenStr, req.Spec().Procedure)if err != nil {if IsAuthenticationSkipped(req.Spec().Procedure, authContext) {return next(ctx, req)@@ -125,7 +141,7 @@ func (in *APIAuthInterceptor) WrapStreamingHandler(next connect.StreamingHandler}ctx = context.WithValue(ctx, common.AuthContextKey, authContext)- user, claims, err := in.authenticate(ctx, accessTokenStr)+ user, claims, err := in.authenticate(ctx, accessTokenStr, conn.Spec().Procedure)if err != nil {if IsAuthenticationSkipped(conn.Spec().Procedure, authContext) {return next(ctx, conn)@@ -162,9 +178,37 @@ func (c *authStreamingConn) Receive(msg any) error {return c.StreamingHandlerConn.Receive(msg)}+// 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",+ 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.-func (in *APIAuthInterceptor) authenticate(ctx context.Context, accessTokenStr string) (*store.UserMessage, *claimsMessage, error) {+// 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) {if accessTokenStr == "" {return nil, nil, errs.New("access token not found")}@@ -187,14 +231,17 @@ func (in *APIAuthInterceptor) authenticate(ctx context.Context, accessTokenStr sreturn nil, nil, errs.New("failed to parse claim")}- // Accept both user access tokens (bb.user.access) and OAuth2 access tokens (bb.oauth2.access)- if !audienceContains(claims.Audience, AccessTokenAudience) && !audienceContains(claims.Audience, OAuth2AccessTokenAudience) {- return nil, nil, errs.Errorf(- "invalid access token, audience mismatch, got %q, expected %q or %q",- claims.Audience,- AccessTokenAudience,- OAuth2AccessTokenAudience,- )+ mcpToken, err := checkTokenAudience(claims)+ if 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, ",")))}account, err := in.store.GetAccountByEmail(ctx, claims.Subject)@@ -272,8 +319,8 @@ func (in *APIAuthInterceptor) verifyWorkspaceMembership(ctx context.Context, wor}// authenticateConnect is a ConnectRPC-specific version that returns ConnectRPC errors.-func (in *APIAuthInterceptor) authenticateConnect(ctx context.Context, accessTokenStr string) (*store.UserMessage, *claimsMessage, error) {- user, claims, err := in.authenticate(ctx, accessTokenStr)+func (in *APIAuthInterceptor) authenticateConnect(ctx context.Context, accessTokenStr, procedure string) (*store.UserMessage, *claimsMessage, error) {+ user, claims, err := in.authenticate(ctx, accessTokenStr, procedure)if err != nil {return nil, nil, connect.NewError(connect.CodeUnauthenticated, err)}@@ -282,8 +329,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 string) (*store.UserMessage, string, error) {- user, claims, err := in.authenticateConnect(ctx, accessTokenStr)+func (in *APIAuthInterceptor) getUserConnect(ctx context.Context, accessTokenStr, procedure string) (*store.UserMessage, string, error) {+ user, claims, err := in.authenticateConnect(ctx, accessTokenStr, procedure)if err != nil {return nil, "", err}@@ -324,8 +371,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.func (in *APIAuthInterceptor) AuthenticateToken(ctx context.Context, accessTokenStr string) (*store.UserMessage, string, time.Time, error) {- user, claims, err := in.authenticate(ctx, accessTokenStr)+ user, claims, err := in.authenticate(ctx, accessTokenStr, "/lsp")if err != nil {return nil, "", time.Time{}, err}diff --git a/backend/api/auth/auth_test.go b/backend/api/auth/auth_test.gonew file mode 100644index 0000000000..6e2c552428--- /dev/null+++ b/backend/api/auth/auth_test.go@@ -0,0 +1,46 @@+package auth++import (+ "testing"++ "github.com/golang-jwt/jwt/v5"+ "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.+func TestCheckTokenAudience(t *testing.T) {+ claimsWith := func(aud string, tokenUse string) *claimsMessage {+ return &claimsMessage{+ RegisteredClaims: jwt.RegisteredClaims{Audience: jwt.ClaimStrings{aud}},+ TokenUse: tokenUse,+ }+ }++ t.Run("web session audience is accepted and not flagged", func(t *testing.T) {+ mcpToken, 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("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("unknown audience without token_use is refused", func(t *testing.T) {+ _, err := checkTokenAudience(claimsWith("wrong.audience", ""))+ require.Error(t, err)+ require.Contains(t, err.Error(), "audience mismatch")+ })+}diff --git a/backend/api/auth/tokens.go b/backend/api/auth/tokens.goindex 1cc094bc22..69705cd4e1 100644--- a/backend/api/auth/tokens.go+++ b/backend/api/auth/tokens.go@@ -31,6 +31,10 @@ type claimsMessage struct {jwt.RegisteredClaimsWorkspaceID string `json:"workspace_id,omitempty"`LoginMethod string `json:"login_method,omitempty"`+ // TokenUse is set to TokenUseMCP on OAuth2 MCP tokens and absent on web+ // session tokens. Declared here rather than on oauth2ClaimsMessage because+ // this is the type every verifier parses into.+ TokenUse string `json:"token_use,omitempty"`}// oauth2ClaimsMessage extends claimsMessage with OAuth2-specific fields.@@ -88,9 +92,15 @@ func generateTokenWithLoginMethod(userEmail string, workspaceID string, aud stri// GenerateOAuth2AccessToken generates an access token for OAuth2 clients.// The clientID is included in the token claims for audit purposes.-func GenerateOAuth2AccessToken(userEmail, clientID, workspaceID, secret string, duration time.Duration) (string, error) {+//+// audience is the canonical MCP resource URI stored on the grant at consent+// time. It is the caller's value on purpose: minting from the stored grant+// 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) {expirationTime := time.Now().Add(duration)- return generateOAuth2Token(userEmail, clientID, workspaceID, OAuth2AccessTokenAudience, expirationTime, []byte(secret))+ return generateOAuth2Token(userEmail, clientID, workspaceID, audience, expirationTime, []byte(secret))}// ExpiredTokenClaims holds the claims extracted from an expired JWT.@@ -98,6 +108,7 @@ type ExpiredTokenClaims struct {Subject stringWorkspaceID stringAudience []string+ TokenUse string}// ExtractClaimsFromExpiredToken parses a JWT (even if expired) and returns key claims.@@ -121,6 +132,7 @@ func ExtractClaimsFromExpiredToken(tokenString, secret string) (*ExpiredTokenClaSubject: claims.Subject,WorkspaceID: claims.WorkspaceID,Audience: claims.Audience,+ TokenUse: claims.TokenUse,}, nil}@@ -137,6 +149,7 @@ func generateOAuth2Token(userEmail, clientID, workspaceID, aud string, expiratioSubject: userEmail,},WorkspaceID: workspaceID,+ TokenUse: TokenUseMCP,},}diff --git a/backend/api/auth/tokens_test.go b/backend/api/auth/tokens_test.gonew file mode 100644index 0000000000..724a0302dd--- /dev/null+++ b/backend/api/auth/tokens_test.go@@ -0,0 +1,74 @@+package auth++import (+ "testing"+ "time"++ "github.com/golang-jwt/jwt/v5"+ "github.com/stretchr/testify/require"+)++const (+ testSecret = "test-secret"+ testResource = "https://bb.example.com/mcp"+)++// TestGenerateOAuth2AccessTokenClaims pins the P1a PR 3 token shape: the+// audience is the canonical MCP resource URI the grant was consented for (passed+// in by the token endpoint from the stored grant, never recomputed from live+// config), and token_use marks the token as an MCP credential so the general+// 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)+ 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, []any{testResource}, claims["aud"],+ "audience must be the stored canonical resource URI, not the fixed bb.oauth2.access string")+ require.Equal(t, TokenUseMCP, claims["token_use"])+ require.Equal(t, "[email protected]", claims["sub"])+ require.Equal(t, "client-A", claims["client_id"])+ require.Equal(t, "ws-test", claims["workspace_id"])+}++// TestWebTokensCarryNoTokenUse pins that only OAuth2 MCP tokens get the+// token_use claim; a web session token must not be mistakable for one.+func TestWebTokensCarryNoTokenUse(t *testing.T) {+ tokenStr, err := GenerateAccessToken("[email protected]", "ws-test", 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, []any{AccessTokenAudience}, claims["aud"])+ require.NotContains(t, claims, "token_use")+}++// TestExtractClaimsFromExpiredTokenTokenUse verifies the expired-token+// extraction used by SwitchWorkspace surfaces token_use, because that guard can+// 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)+ require.NoError(t, err)++ claims, err := ExtractClaimsFromExpiredToken(tokenStr, testSecret)+ require.NoError(t, err)+ require.Equal(t, TokenUseMCP, claims.TokenUse)+ require.Equal(t, []string{testResource}, []string(claims.Audience))++ webToken, err := GenerateAccessToken("[email protected]", "ws-test", testSecret, time.Hour)+ require.NoError(t, err)+ webClaims, err := ExtractClaimsFromExpiredToken(webToken, testSecret)+ require.NoError(t, err)+ require.Empty(t, webClaims.TokenUse)+}diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.goindex b4cd7dda6c..21c69f2b8b 100644--- a/backend/api/mcp/server.go+++ b/backend/api/mcp/server.go@@ -10,6 +10,7 @@ import ("sync""time"+ "connectrpc.com/connect""github.com/golang-jwt/jwt/v5""github.com/labstack/echo/v5""github.com/modelcontextprotocol/go-sdk/mcp"@@ -138,29 +139,6 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {return s.unauthorized(c, "invalid token")}- // Validate audience - accept both user access tokens and OAuth2 access tokens- aud, ok := claims["aud"]- if !ok {- return s.unauthorized(c, "invalid token: missing audience")- }-- validAudience := false- switch v := aud.(type) {- case string:- validAudience = v == auth.OAuth2AccessTokenAudience || v == auth.AccessTokenAudience- case []any:- for _, a := range v {- if str, ok := a.(string); ok && (str == auth.OAuth2AccessTokenAudience || str == auth.AccessTokenAudience) {- validAudience = true- break- }- }- default:- }- if !validAudience {- return s.unauthorized(c, "invalid token: audience mismatch")- }-// Extract user email from subjectsub, ok := claims["sub"].(string)if !ok || sub == "" {@@ -171,12 +149,30 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {clientID = ""}- // Extract workspace ID from token claims.+ // 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")+ }+ allowed, err := s.audienceAllowed(c.Request().Context(), aud, workspaceID)+ if err != nil {+ // Infra failure reading the trusted config, not a verdict on the+ // token: a 401 here would tell a compliant client to discard a+ // perfectly good token mid-outage. 503 says retry instead.+ slog.Error("failed to resolve the MCP resource audience; cannot verify the token", log.BBError(err))+ return echo.NewHTTPError(http.StatusServiceUnavailable, "cannot verify token audience; retry shortly")+ }+ if !allowed {+ return s.unauthorized(c, "invalid token: audience mismatch")+ }+// Enforce the workspace MCP capability ceiling before dispatching to any// tool. DISABLED — and, until per-tool enforcement lands in a later// phase, the not-yet-enforceable READ_ONLY ceiling — reject the@@ -198,10 +194,120 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {}}+// mcpResourcePath is the path of the MCP endpoint. Appended to the trusted+// external URL it forms the canonical MCP resource URI — the audience every+// OAuth2 access token is minted with since P1a PR 3 (mirrors the constant of+// the same name in the oauth2 package, which stores that URI on the grant).+const mcpResourcePath = "/mcp"+// RegisterRoutes registers the MCP server routes with Echo.func (s *Server) RegisterRoutes(e *echo.Echo) {// MCP Streamable HTTP endpoint with authentication- e.Any("/mcp", echo.WrapHandler(s.httpHandler), s.authMiddleware)+ e.Any(mcpResourcePath, echo.WrapHandler(s.httpHandler), s.authMiddleware)+}++// audienceAllowed reports whether a bearer token's audience admits it to /mcp.+//+// The durable rule is a single audience: the canonical MCP resource URI derived+// from the trusted live config (never from request headers). Tokens are minted+// from the grant's stored resource, so rotating the external URL makes them+// mismatch here — a clean 401 at use time that drives the client to+// re-authorize, by design (grants must not silently rebind to a URL the user+// never consented to).+//+// Legacy bb.oauth2.access tokens are admitted while their own exp claim keeps+// them alive — deliberately with no clock gate. This release never mints that+// audience, but replicas running the previous release keep minting it until+// they leave service (the grant gates only constrain new-code replicas), so+// any process-local window races a rolling deploy: it can close before the+// last old-replica mint expires, 401-ing valid tokens depending on which+// replica serves the request. Keying on token expiry instead gives the exact+// bound: legacy acceptance drains no later than one access-token lifetime+// after the last legacy-capable replica leaves service. Remove the acceptance+// entirely in a later release, once no supported mixed-version deployment can+// still mint the audience.+//+// Plain bb.user.access session tokens pasted into MCP clients manually are+// admitted for now — see the acceptance branch in decideAudience for the+// retirement gating.+//+// If no trusted external URL is configured, there is no expected audience and+// resource-bound tokens fail closed; after the window such a deployment+// rejects everything at /mcp until the external URL is set, matching the PR 2+// rule that MCP OAuth requires a configured external URL. A transient failure+// reading the config is different: it returns an error rather than a false+// verdict, so the caller reports a server problem instead of blaming the token.+func (s *Server) audienceAllowed(ctx context.Context, aud any, workspaceID string) (bool, error) {+ expected, resolveErr := s.expectedMCPAudience(ctx, workspaceID)+ return decideAudience(aud, expected, resolveErr)+}++// decideAudience is the pure decision behind audienceAllowed, split out so the+// resolver-failure branches are unit-testable without a failing store.+func decideAudience(aud any, expected string, resolveErr error) (bool, error) {+ switch {+ case resolveErr == nil:+ if audienceMatches(aud, expected) {+ return true, nil+ }+ case connect.CodeOf(resolveErr) == connect.CodeFailedPrecondition:+ // Deliberately unconfigured (GetEffectiveExternalURL's "isn't setup+ // yet"): no expected audience exists, so fall through to the legacy+ // audiences rather than erroring.+ slog.Warn("no external URL is configured; only legacy-audience tokens can authenticate at /mcp",+ log.BBError(resolveErr))+ default:+ // Infra failure reading the trusted config: not a verdict on the token.+ return false, resolveErr+ }+ // Plain web-session tokens stay accepted at /mcp for now: bb.user.access is+ // minted by every web login, so no migration window can retire it, and the+ // spec gates the hard cut on a scoped service-account / workload-identity+ // flow existing first (spec §"Deferred product decisions"; proposal §6.5+ // names the service-account token proxy as the dependent). PR 5/6 replaces+ // this acceptance with a rejection once that credential ships, bringing its+ // own tests.+ if audienceMatches(aud, auth.AccessTokenAudience) {+ return true, nil+ }+ // Unexpired legacy tokens only: the JWT exp check upstream has already+ // rejected the rest, and this release mints none, so this branch drains on+ // its own (see audienceAllowed).+ return audienceMatches(aud, auth.OAuth2AccessTokenAudience), nil+}++// expectedMCPAudience resolves the audience /mcp accepts: the trusted external+// URL (flag or workspace setting, per utils.GetEffectiveExternalURL) plus the+// /mcp path. Request-derived values must never feed this — a Host header is+// attacker-controlled and would let anyone mint a matching binding.+func (s *Server) expectedMCPAudience(ctx context.Context, workspaceID string) (string, error) {+ if workspaceID == "" && !s.profile.SaaS {+ if id, err := s.store.GetWorkspaceID(ctx); err == nil {+ workspaceID = id+ }+ }+ externalURL, err := utils.GetEffectiveExternalURL(ctx, s.store, s.profile, workspaceID)+ if err != nil {+ return "", err+ }+ return externalURL + mcpResourcePath, nil+}++// audienceMatches reports whether a JWT aud claim (string or array form)+// contains exactly want.+func audienceMatches(aud any, want string) bool {+ switch v := aud.(type) {+ case string:+ return v == want+ case []any:+ for _, a := range v {+ if str, ok := a.(string); ok && str == want {+ return true+ }+ }+ default:+ }+ return false}// unauthorized writes a 401 with an RFC 9728 / MCP-authorization-spec@@ -296,7 +402,7 @@ func (s *Server) buildResourceMetadataURL(c *echo.Context) string {ctx := c.Request().Context()if s.profile.ExternalURL != "" {- return strings.TrimSuffix(s.profile.ExternalURL, "/") + resourceMetadataPath+ return s.profile.ExternalURL + resourceMetadataPath}workspaceID := ""if !s.profile.SaaS {@@ -304,8 +410,8 @@ func (s *Server) buildResourceMetadataURL(c *echo.Context) string {workspaceID = ws}}- if externalURL, err := utils.GetEffectiveExternalURL(ctx, s.store, s.profile, workspaceID); err == nil && externalURL != "" {- return strings.TrimSuffix(externalURL, "/") + resourceMetadataPath+ if externalURL, err := utils.GetEffectiveExternalURL(ctx, s.store, s.profile, workspaceID); err == nil {+ return externalURL + resourceMetadataPath}req := c.Request()diff --git a/backend/api/mcp/server_test.go b/backend/api/mcp/server_test.goindex 01b6ff945d..50901a09ae 100644--- a/backend/api/mcp/server_test.go+++ b/backend/api/mcp/server_test.go@@ -8,8 +8,10 @@ import ("testing""time"+ "connectrpc.com/connect""github.com/golang-jwt/jwt/v5""github.com/labstack/echo/v5"+ "github.com/pkg/errors""github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/api/auth"@@ -20,8 +22,9 @@ import (func TestMCPAuthMiddleware(t *testing.T) {secret := "test-secret-key"// ExternalURL short-circuits utils.GetEffectiveExternalURL away from- // the nil store; it's also the canonical URL the WWW-Authenticate- // resource_metadata pointer should resolve to.+ // the nil store, and the minted tokens carry a workspace so no singleton+ // workspace lookup runs either; it's also the canonical URL the+ // WWW-Authenticate resource_metadata pointer should resolve to.profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}tests := []struct {@@ -121,7 +124,7 @@ func TestMCPAuthMiddleware(t *testing.T) {func TestMCPAuthMiddlewareValidToken(t *testing.T) {secret := "test-secret-key"- profile := &config.Profile{Mode: common.ReleaseModeDev}+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}e := echo.New()req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))@@ -149,7 +152,7 @@ func TestMCPAuthMiddlewareValidToken(t *testing.T) {func TestMCPAuthMiddlewareOAuthContext(t *testing.T) {secret := "test-secret-key"- profile := &config.Profile{Mode: common.ReleaseModeDev}+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}e := echo.New()req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))@@ -248,14 +251,193 @@ func TestMCPUnauthenticatedRejectedEndToEnd(t *testing.T) {require.Equal(t, http.StatusUnauthorized, resp.StatusCode)}+// TestMCPAuthMiddlewareAudienceMatrix is the P1a PR 3 audience boundary. The+// durably accepted audience is the live-config MCP resource URI (external URL+// + /mcp, trusted config only — never request headers). Legacy bb.oauth2.access+// tokens are accepted while they remain unexpired: this release never mints+// that audience, so acceptance drains no later than one access-token lifetime+// after the last legacy-capable replica leaves service (the expired-token 401+// in TestMCPAuthMiddleware is the other half of that invariant). Plain+// bb.user.access session tokens are accepted until the scoped service-account+// flow lands (spec "Deferred product decisions"; proposal §6.5).+func TestMCPAuthMiddlewareAudienceMatrix(t *testing.T) {+ secret := "test-secret-key"++ mintResourceToken := func(t *testing.T, resource string) string {+ t.Helper()+ token, err := auth.GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", resource, secret, time.Hour)+ require.NoError(t, err)+ return token+ }++ tests := []struct {+ name string+ // externalURL is the trusted live config. The unconfigured ("") case+ // needs a store to resolve, so it lives in TestDecideAudience.+ externalURL string+ token func(t *testing.T) string+ expectedStatus int+ }{+ {+ name: "matching resource audience is accepted",+ externalURL: "https://bb.example.com",+ token: func(t *testing.T) string { return mintResourceToken(t, "https://bb.example.com/mcp") },+ expectedStatus: http.StatusOK,+ },+ {+ name: "rotated external URL kills outstanding resource tokens",+ externalURL: "https://new.example.com",+ // The token was minted from a grant stored under the old URL; the+ // middleware compares against live config, so rotation 401s it at+ // use time and the client re-authorizes.+ token: func(t *testing.T) string { return mintResourceToken(t, "https://old.example.com/mcp") },+ expectedStatus: http.StatusUnauthorized,+ },+ {+ name: "bare-origin audience is not the canonical resource",+ externalURL: "https://bb.example.com",+ token: func(t *testing.T) string { return mintResourceToken(t, "https://bb.example.com") },+ expectedStatus: http.StatusUnauthorized,+ },+ {+ // Unexpired legacy tokens (minted by a pre-upgrade replica, which+ // during a rolling deploy can outlive any single process's start)+ // are accepted; their own exp claim is what retires them.+ name: "unexpired legacy oauth2 audience is accepted",+ externalURL: "https://bb.example.com",+ token: func(t *testing.T) string { return generateValidToken(t, secret) },+ expectedStatus: http.StatusOK,+ },+ {+ // bb.user.access retirement is gated on the scoped service-account+ // flow landing first (PR 5/6).+ name: "plain user audience is accepted",+ externalURL: "https://bb.example.com",+ token: func(t *testing.T) string { return generateUserAudienceToken(t, secret) },+ expectedStatus: http.StatusOK,+ },+ }++ 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)+ require.NoError(t, err)++ e := echo.New()+ req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Authorization", "Bearer "+tc.token(t))+ rec := httptest.NewRecorder()+ c := e.NewContext(req, rec)++ handler := s.authMiddleware(func(c *echo.Context) error {+ return c.String(http.StatusOK, "success")+ })+ err = handler(c)+ if err != nil {+ echo.DefaultHTTPErrorHandler(true)(c, err)+ }++ require.Equal(t, tc.expectedStatus, rec.Code, rec.Body.String())+ if tc.expectedStatus == http.StatusUnauthorized {+ require.Contains(t, strings.ToLower(rec.Body.String()), "audience")+ // Containment: even audience-mismatch challenges must not+ // advertise the scope vocabulary before P1b enforcement.+ wwwAuth := rec.Header().Get("WWW-Authenticate")+ require.NotEmpty(t, wwwAuth)+ require.NotContains(t, wwwAuth, "scope=")+ require.NotContains(t, wwwAuth, "mcp:read")+ }+ })+ }+}++// TestDecideAudience covers the resolver branches the HTTP matrix cannot reach+// without a DB-backed store: a deliberately unconfigured deployment admits only+// the legacy audiences (resource-bound tokens fail closed), while an infra+// failure reading the trusted config surfaces as an error — a server problem,+// never a verdict against the token.+func TestDecideAudience(t *testing.T) {+ const expected = "https://bb.example.com/mcp"+ unconfigured := connect.NewError(connect.CodeFailedPrecondition, errors.New("external URL isn't setup yet"))+ infraDown := connect.NewError(connect.CodeInternal, errors.New("failed to get workspace setting: db unreachable"))++ t.Run("matching expected audience is allowed", func(t *testing.T) {+ allowed, err := decideAudience(expected, expected, nil)+ require.NoError(t, err)+ require.True(t, allowed)+ })++ t.Run("unknown audience is refused", func(t *testing.T) {+ allowed, err := decideAudience("https://old.example.com/mcp", expected, nil)+ require.NoError(t, err)+ require.False(t, allowed)+ })++ t.Run("legacy oauth2 audience is accepted while its token lives", func(t *testing.T) {+ // No clock gate: this release never mints bb.oauth2.access, so the+ // population drains by each token's own exp — no later than one+ // access-token lifetime after the last legacy-capable replica leaves+ // service. A process-start window would race rolling deploys.+ allowed, err := decideAudience(auth.OAuth2AccessTokenAudience, expected, nil)+ require.NoError(t, err)+ require.True(t, allowed)+ })++ t.Run("unconfigured external URL still admits legacy audiences", func(t *testing.T) {+ allowed, err := decideAudience(auth.OAuth2AccessTokenAudience, "", unconfigured)+ require.NoError(t, err)+ require.True(t, allowed)+ })++ t.Run("unconfigured external URL fails closed for resource tokens", func(t *testing.T) {+ // No trusted config means no expected audience to compare against; the+ // request-derived host must never substitute for it.+ allowed, err := decideAudience("https://bb.example.com/mcp", "", unconfigured)+ require.NoError(t, err)+ require.False(t, allowed)+ })++ t.Run("plain user audience is accepted", func(t *testing.T) {+ allowed, err := decideAudience(auth.AccessTokenAudience, expected, nil)+ require.NoError(t, err)+ require.True(t, allowed)+ })++ t.Run("infra failure is reported as an error, not a token verdict", func(t *testing.T) {+ allowed, err := decideAudience(expected, "", infraDown)+ require.Error(t, err)+ require.False(t, allowed)+ })+}++func generateUserAudienceToken(t *testing.T, secret string) string {+ t.Helper()+ claims := jwt.MapClaims{+ "iss": "bytebase",+ "sub": "[email protected]",+ "aud": auth.AccessTokenAudience,+ "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 generateValidToken(t *testing.T, secret string) string {t.Helper()claims := jwt.MapClaims{- "iss": "bytebase",- "sub": "[email protected]",- "aud": auth.OAuth2AccessTokenAudience,- "exp": time.Now().Add(time.Hour).Unix(),- "iat": time.Now().Unix(),+ "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"@@ -282,6 +464,11 @@ func generateOAuth2MCPToken(t *testing.T, secret, clientID, workspaceID string)return tokenStr}+// generateExpiredToken mints an expired legacy-audience (bb.oauth2.access)+// token. The middleware matrix accepts that audience with no clock gate, so+// the "expired token returns 401" row above is the other half of the drain+// invariant: JWT expiry validation, not a window, is what retires the legacy+// population.func generateExpiredToken(t *testing.T, secret string) string {t.Helper()claims := jwt.MapClaims{@@ -301,11 +488,12 @@ func generateExpiredToken(t *testing.T, secret string) string {func generateTokenWithWrongAudience(t *testing.T, secret string) string {t.Helper()claims := jwt.MapClaims{- "iss": "bytebase",- "sub": "[email protected]",- "aud": "wrong.audience",- "exp": time.Now().Add(time.Hour).Unix(),- "iat": time.Now().Unix(),+ "iss": "bytebase",+ "sub": "[email protected]",+ "aud": "wrong.audience",+ "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"diff --git a/backend/api/mcp/tool_reauthorize.go b/backend/api/mcp/tool_reauthorize.goindex de5278456b..0868efd993 100644--- a/backend/api/mcp/tool_reauthorize.go+++ b/backend/api/mcp/tool_reauthorize.go@@ -32,10 +32,6 @@ func (s *Server) handleReauthorize(ctx context.Context, _ *mcp.CallToolRequest,Message: "reauthorize requires an MCP OAuth access token",}), nil, nil}- if s.store == nil {- return formatToolError(errors.New("store is not configured")), nil, nil- }-if err := s.store.DeleteOAuth2RefreshTokensByUserAndClient(ctx, userEmail, clientID); err != nil {return formatToolError(errors.Wrap(err, "failed to revoke OAuth refresh tokens")), nil, nil}diff --git a/backend/api/oauth2/grant_test.go b/backend/api/oauth2/grant_test.goindex 115aeed302..bdd71a3ba5 100644--- a/backend/api/oauth2/grant_test.go+++ b/backend/api/oauth2/grant_test.go@@ -19,6 +19,8 @@ import ("github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/api/auth"+ "github.com/bytebase/bytebase/backend/api/mcp"+ "github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -130,13 +132,19 @@ func TestResourceScopeGrantLifecycle(t *testing.T) {require.Equal(t, testResource, got.Config.Resource)})- t.Run("no resource and no scope still consents (clients that predate both)", func(t *testing.T) {+ t.Run("no resource requested: the grant is bound to this server's MCP resource", func(t *testing.T) {+ // Since PR 3 every new grant is resource-bound, because its tokens carry+ // the resource as their audience: an unbound grant would mint tokens no+ // audience check accepts once the legacy window closes, sending the+ // client into a re-auth loop. A client that never sends `resource`+ // (mandatory for MCP clients per RFC 8707, but not every DCR client is+ // one) is defaulted to the only resource this server would accept anyway.code := consentOK(t, configured, url.Values{})got, err := st.GetOAuth2AuthorizationCode(ctx, testClientID, code)require.NoError(t, err)- require.Empty(t, got.Config.Resource)- require.Empty(t, got.Config.Scope)+ require.Equal(t, testResource, got.Config.Resource)+ require.Empty(t, got.Config.Scope, "only the resource is defaulted; scope stays exactly as requested")})rejections := []struct {@@ -178,10 +186,15 @@ func TestResourceScopeGrantLifecycle(t *testing.T) {require.Contains(t, description, "external URL isn't setup yet")})- t.Run("no configured external URL: a request without a resource still works", func(t *testing.T) {+ t.Run("no configured external URL: consent without a resource gets the setup error too", func(t *testing.T) {+ // PR 2 let a resource-less request through on an unconfigured instance;+ // PR 3 binds every grant, and the binding needs the trusted URL. Failing+ // consent with the actionable setup pointer beats minting tokens that+ // can only ever 401 at /mcp.unconfigured := newTestService(st, "")- require.NotEmpty(t, consentOK(t, unconfigured, url.Values{}),- "resource binding is opt-in, so today's clients must not break on an unconfigured instance")+ redirect := consent(t, unconfigured, url.Values{})+ require.Equal(t, "server_error", redirect.Query().Get("error"))+ require.Contains(t, redirect.Query().Get("error_description"), "external URL isn't setup yet")})t.Run("the workspace setting is trusted too, not only the flag", func(t *testing.T) {@@ -303,45 +316,187 @@ func TestResourceScopeGrantLifecycle(t *testing.T) {"the canonical form must survive rotation, not drift back to what the client sent")})- t.Run("a grant with no consented resource survives a resource-bearing exchange", func(t *testing.T) {- // This is the upgrade path. A code or refresh token issued before 3.22.1- // has no stored resource, and RFC 8707 clients keep sending `resource` on- // every exchange and refresh — so rejecting the parameter here would fail- // in-flight codes and every live session at its next refresh. The- // parameter is accepted and ignored, and the grant must stay UNBOUND:- // accepting a binding here would be a resource the user never consented- // to, and would let PR 3 mint an MCP-audience token off a legacy grant.- code := consentOK(t, configured, url.Values{})+ t.Run("legacy unbound grants are refused at the token endpoint with re-auth guidance", func(t *testing.T) {+ // Rows created before 3.22.1 carry no resource in Config. PR 2 kept them+ // redeemable as a deliberate interim; PR 3 retires them: tokens are now+ // audience-bound to the grant's stored resource, so an unbound grant has+ // nothing valid to mint. invalid_grant is what makes RFC-compliant+ // clients discard the grant and rerun the OAuth flow, and the+ // description points at the reauthorize tool as the in-band recovery.+ challenge := sha256.Sum256([]byte(testCodeVerifier))+ const legacyCode = "bb_code_legacy_unbound"+ _, err := st.CreateOAuth2AuthorizationCode(ctx, &store.OAuth2AuthorizationCodeMessage{+ Code: legacyCode,+ ClientID: testClientID,+ UserEmail: testUserEmail,+ Workspace: testWorkspace,+ Config: &storepb.OAuth2AuthorizationCodeConfig{+ RedirectUri: testRedirectURI,+ CodeChallenge: base64.RawURLEncoding.EncodeToString(challenge[:]),+ CodeChallengeMethod: "S256",+ },+ ExpiresAt: time.Now().Add(10 * time.Minute),+ })+ require.NoError(t, err)- first := tokenOK(t, configured, url.Values{+ exchanged := postToken(t, configured, url.Values{"grant_type": {"authorization_code"},- "code": {code},+ "code": {legacyCode},"redirect_uri": {testRedirectURI},"code_verifier": {testCodeVerifier},"client_id": {testClientID},- "resource": {testResource},- "scope": {"mcp:read-write"},})- require.Empty(t, first.Scope, "an unbound grant must not adopt the scope the client asked for")+ require.Equal(t, http.StatusBadRequest, exchanged.Code)+ require.Equal(t, "invalid_grant", errorCode(t, exchanged))+ require.Contains(t, errorDescription(t, exchanged), "re-authorize")+ require.Contains(t, errorDescription(t, exchanged), "reauthorize tool")++ const legacyRefresh = "bb_refresh_legacy_unbound"+ _, err = st.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{+ TokenHash: auth.HashToken(legacyRefresh),+ ClientID: testClientID,+ UserEmail: testUserEmail,+ Workspace: testWorkspace,+ Config: &storepb.OAuth2RefreshTokenConfig{},+ ExpiresAt: time.Now().Add(24 * time.Hour),+ })+ require.NoError(t, err)- stored, err := st.GetOAuth2RefreshToken(ctx, testClientID, auth.HashToken(first.RefreshToken))+ refreshed := postToken(t, configured, url.Values{+ "grant_type": {"refresh_token"},+ "refresh_token": {legacyRefresh},+ "client_id": {testClientID},+ })+ require.Equal(t, http.StatusBadRequest, refreshed.Code)+ require.Equal(t, "invalid_grant", errorCode(t, refreshed))+ require.Contains(t, errorDescription(t, refreshed), "reauthorize tool")++ // Refusal happens before consumption: the row is left for the expiry+ // sweep (or the user's reauthorize) rather than burned by a refresh+ // that issued nothing.+ row, err := st.GetOAuth2RefreshToken(ctx, testClientID, auth.HashToken(legacyRefresh))require.NoError(t, err)- require.NotNil(t, stored)- require.Empty(t, stored.Config.GetResource(), "the requested resource must be ignored, never bound to a grant that never consented to one")- require.Empty(t, stored.Config.GetScope())+ require.NotNil(t, row)- // And the same on refresh, so a legacy session keeps working indefinitely- // until PR 3 retires it deliberately.- second := tokenOK(t, configured, url.Values{+ // A bound grant with no scope is not legacy — only a missing resource+ // marks the retired population.+ boundCode := consentOK(t, configured, url.Values{"resource": {testResource}})+ bound := tokenOK(t, configured, url.Values{+ "grant_type": {"authorization_code"},+ "code": {boundCode},+ "redirect_uri": {testRedirectURI},+ "code_verifier": {testCodeVerifier},+ "client_id": {testClientID},+ })+ tokenOK(t, configured, url.Values{+ "grant_type": {"refresh_token"},+ "refresh_token": {bound.RefreshToken},+ "client_id": {testClientID},+ })+ })++ t.Run("rotating the external URL kills outstanding tokens at /mcp until re-consent", func(t *testing.T) {+ code := consentOK(t, configured, url.Values{"resource": {testResource}})+ first := tokenOK(t, configured, url.Values{+ "grant_type": {"authorization_code"},+ "code": {code},+ "redirect_uri": {testRedirectURI},+ "code_verifier": {testCodeVerifier},+ "client_id": {testClientID},+ })+ require.NotEqual(t, http.StatusUnauthorized, mcpStatus(t, st, "https://bb.example.com", first.AccessToken),+ "a token bound to the live resource must be admitted at /mcp")++ // Rotate the trusted external URL. The middleware computes its expected+ // audience from live config, so the outstanding token dies at use time+ // with a clean 401 — never silently rebinds.+ require.Equal(t, http.StatusUnauthorized, mcpStatus(t, st, "https://bb-new.example.com", first.AccessToken))++ // The token endpoint, by contrast, mints from the grant's STORED+ // resource, never live config: refresh succeeds but hands back a token+ // still bound to the consented (old) resource, equally dead at /mcp.+ rotated := newTestService(st, "https://bb-new.example.com")+ second := tokenOK(t, rotated, url.Values{"grant_type": {"refresh_token"},"refresh_token": {first.RefreshToken},"client_id": {testClientID},- "resource": {testResource},})- rotated, err := st.GetOAuth2RefreshToken(ctx, testClientID, auth.HashToken(second.RefreshToken))+ require.Equal(t, http.StatusUnauthorized, mcpStatus(t, st, "https://bb-new.example.com", second.AccessToken))++ // Recovery is a fresh consent under the new URL — here without a+ // resource parameter, so this also proves the defaulted binding works+ // end to end.+ codeB := consentOK(t, rotated, url.Values{})+ third := tokenOK(t, rotated, url.Values{+ "grant_type": {"authorization_code"},+ "code": {codeB},+ "redirect_uri": {testRedirectURI},+ "code_verifier": {testCodeVerifier},+ "client_id": {testClientID},+ })+ require.NotEqual(t, http.StatusUnauthorized, mcpStatus(t, st, "https://bb-new.example.com", third.AccessToken))+ })++ t.Run("the /mcp middleware trusts the workspace-setting external URL tier", func(t *testing.T) {+ // The audience matrix and the rotation chain drive the --external-url+ // flag tier only; the normal self-hosted shape configures the URL in+ // Settings. A regression that silently drops the setting tier from the+ // middleware would 401 every MCP request on such deployments while the+ // consent-side tests stay green.+ _, err := st.UpsertSetting(ctx, &store.SettingMessage{+ Name: storepb.SettingName_WORKSPACE_PROFILE,+ Workspace: testWorkspace,+ Value: &storepb.WorkspaceProfileSetting{ExternalUrl: "https://bb.example.com"},+ })require.NoError(t, err)- require.NotNil(t, rotated)- require.Empty(t, rotated.Config.GetResource())+ t.Cleanup(func() {+ _, err := st.UpsertSetting(ctx, &store.SettingMessage{+ Name: storepb.SettingName_WORKSPACE_PROFILE,+ Workspace: testWorkspace,+ Value: &storepb.WorkspaceProfileSetting{},+ })+ require.NoError(t, err)+ })++ fromSetting := newTestService(st, "")+ code := consentOK(t, fromSetting, url.Values{"resource": {testResource}})+ got := tokenOK(t, fromSetting, url.Values{+ "grant_type": {"authorization_code"},+ "code": {code},+ "redirect_uri": {testRedirectURI},+ "code_verifier": {testCodeVerifier},+ "client_id": {testClientID},+ })+ require.NotEqual(t, http.StatusUnauthorized, mcpStatus(t, st, "", got.AccessToken),+ "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.+ _, err := st.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{+ Workspace: testWorkspace,+ Member: common.FormatUserEmail(testUserEmail),+ Roles: []string{"roles/workspaceMember"},+ })+ require.NoError(t, err)++ code := consentOK(t, configured, url.Values{"resource": {testResource}})+ got := tokenOK(t, configured, url.Values{+ "grant_type": {"authorization_code"},+ "code": {code},+ "redirect_uri": {testRedirectURI},+ "code_verifier": {testCodeVerifier},+ "client_id": {testClientID},+ })++ 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)})t.Run("a requested scope set is consented as its maximum", func(t *testing.T) {@@ -453,6 +608,34 @@ func errorCode(t *testing.T, rec *httptest.ResponseRecorder) string {return body["error"]}+func errorDescription(t *testing.T, rec *httptest.ResponseRecorder) string {+ t.Helper()+ var body map[string]string+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))+ return body["error_description"]+}++// mcpStatus posts an MCP initialize request to a freshly wired /mcp endpoint+// whose trusted external URL is externalURL, and returns the HTTP status. 401+// means the auth middleware refused the token; anything else means the token+// 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)+ require.NoError(t, err)+ e := echo.New()+ srv.RegisterRoutes(e)++ body := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}`+ req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Accept", "application/json, text/event-stream")+ req.Header.Set("Authorization", "Bearer "+accessToken)+ rec := httptest.NewRecorder()+ e.ServeHTTP(rec, req)+ return rec.Code+}+// redirectTargetOf pulls the callback URL out of the meta-refresh page the// authorize handler returns (it renders HTML rather than a 302 to sidestep CSP// form-action restrictions).diff --git a/backend/api/oauth2/oauth2.go b/backend/api/oauth2/oauth2.goindex d91fd09c02..389d941f17 100644--- a/backend/api/oauth2/oauth2.go+++ b/backend/api/oauth2/oauth2.go@@ -30,8 +30,11 @@ const (refreshTokenPrefix = "bb_refresh_"authCodePrefix = "bb_code_"- authCodeExpiry = 10 * time.Minute- accessTokenExpiry = 1 * time.Hour+ authCodeExpiry = 10 * time.Minute+ // accessTokenExpiry aliases the shared constant so the /mcp middleware's+ // legacy-audience migration window (one access-token lifetime from process+ // start) stays exactly as long as the tokens it exists for.+ accessTokenExpiry = auth.OAuth2AccessTokenDurationrefreshTokenExpiry = 30 * 24 * time.HourclientInactiveExpiry = 30 * 24 * time.Hourdiff --git a/backend/api/oauth2/resource.go b/backend/api/oauth2/resource.goindex 3e2f200e59..52a87127b5 100644--- a/backend/api/oauth2/resource.go+++ b/backend/api/oauth2/resource.go@@ -46,9 +46,16 @@ type oauth2Failure struct {}// parseGrantParams extracts and validates the `resource` (RFC 8707) and `scope`-// (RFC 6749) parameters of an authorization request. Both are optional — clients-// that send neither still consent successfully — but a value that is present is-// validated strictly, and multiple occurrences of either are rejected.+// (RFC 6749) parameters of an authorization request. Both parameters are+// optional, and a value that is present is validated strictly; multiple+// occurrences of either are rejected.+//+// The resulting grant is always resource-bound (P1a PR 3): the stored resource+// becomes the access token's audience, so a client that omits `resource`+// (mandatory for MCP clients per RFC 8707, but not every DCR client is one) is+// bound to the canonical MCP resource — the only value validateResource would+// accept anyway. Leaving such a grant unbound instead would mint tokens no+// audience check accepts once the legacy migration window closes.func (s *Service) parseGrantParams(ctx context.Context, values url.Values, workspaceID string) (grantParams, *oauth2Failure) {resource, err := singleValue(values, "resource")if err != nil {@@ -62,19 +69,21 @@ func (s *Service) parseGrantParams(ctx context.Context, values url.Values, worksif err != nil {return grantParams{}, &oauth2Failure{code: "invalid_scope", description: err.Error()}}- if resource == "" {- return grantParams{scope: scope}, nil- }- // GetEffectiveExternalURL reports "not configured" as an error, never as an- // empty string. Fail closed, never fall back to the request.+ // Every consent needs the trusted external URL now that every grant is+ // bound. GetEffectiveExternalURL reports "not configured" as an error, never+ // as an empty string. Fail closed with the actionable setup error, never+ // fall back to the request.externalURL, err := utils.GetEffectiveExternalURL(ctx, s.store, s.profile, workspaceID)if err != nil {- slog.Error("rejected an MCP OAuth resource binding because no external URL is configured",+ slog.Error("rejected an MCP OAuth consent because no external URL is configured",slog.String("resource", resource))return grantParams{}, &oauth2Failure{code: "server_error", description: err.Error()}}+ if resource == "" {+ return grantParams{resource: externalURL + mcpResourcePath, scope: scope}, nil+ }canonical, err := validateResource(resource, externalURL)if err != nil {return grantParams{}, &oauth2Failure{code: "invalid_target", description: err.Error()}@@ -107,14 +116,12 @@ func checkConsentedResource(values url.Values, consented string) *oauth2Failureif err != nil {return &oauth2Failure{code: "invalid_target", description: err.Error()}}- // Codes and refresh tokens issued before 3.22.1 read back with no resource,- // and RFC 8707 clients send `resource` on every exchange *and* every refresh.- // Rejecting it would fail each in-flight code and every live session at its- // next refresh, for up to a refresh-token lifetime after upgrade. Accept it- // without binding: the stored value stays empty and is what gets carried- // forward, so an unbound grant cannot acquire a binding here. Retiring that- // population is PR 3's job (spec §"PR 3": legacy refresh grants require- // re-consent), and it needs the audience change to do it coherently.+ // Codes and refresh tokens issued before 3.22.1 read back with no resource.+ // The parameter check accepts anything for them so the refusal such a grant+ // gets is the deliberate one: the legacy gate right after these checks+ // (legacyGrantFailure) refuses the grant itself with re-auth guidance,+ // rather than a confusing mismatch error against a value that was never+ // consented. An unbound grant still cannot acquire a binding here.if consented == "" {return nil}diff --git a/backend/api/oauth2/token.go b/backend/api/oauth2/token.goindex c9e809442e..ba30c2a54f 100644--- a/backend/api/oauth2/token.go+++ b/backend/api/oauth2/token.go@@ -214,9 +214,27 @@ func (s *Service) validateAuthorizationCode(ctx context.Context, client *store.Oif failure := checkConsentedScope(formValues, authCode.Config.Scope); failure != nil {return nil, failure}+ if authCode.Config.Resource == "" {+ return nil, legacyGrantFailure()+ }return authCode, nil}+// legacyGrantFailure refuses a grant stored without a resource binding — a row+// created before resource persistence (3.22.1), since consent now binds every+// grant. Access tokens carry the grant's resource as their audience, so an+// unbound grant has nothing valid to mint. invalid_grant makes an RFC-compliant+// client discard the grant and rerun the OAuth flow; the description adds the+// in-band recovery for MCP clients (the reauthorize tool exists for exactly+// this). Callers run it before consuming the grant, so the row is left to the+// expiry sweep instead of being burned by a refusal that issued nothing.+func legacyGrantFailure() *oauth2Failure {+ return &oauth2Failure{+ code: "invalid_grant",+ description: "this grant predates MCP resource binding and can no longer be used; re-authorize to get a new grant (run the reauthorize tool in an MCP session, or remove and reconnect this MCP server)",+ }+}+// tokenFailure renders a helper's refusal as an RFC 6749 token-endpoint error.// server_error is the only 500-class code these helpers produce; every other// code is a client error.@@ -236,45 +254,11 @@ func (s *Service) handleRefreshTokenGrant(c *echo.Context, client *store.OAuth2Creturn oauth2Error(c, http.StatusBadRequest, "unauthorized_client", "client not authorized for refresh_token grant")}- // Validate refresh token- if req.RefreshToken == "" {- return oauth2Error(c, http.StatusBadRequest, "invalid_request", "refresh_token is required")- }-- tokenHash := auth.HashToken(req.RefreshToken)- refreshToken, err := s.store.GetOAuth2RefreshToken(ctx, client.ClientID, tokenHash)- if err != nil {- return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup refresh token")- }- if refreshToken == nil {- return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid refresh token")- }-- // Validate token belongs to this client BEFORE deleting- // This prevents DoS where attacker with stolen token invalidates it for legitimate client- if refreshToken.ClientID != client.ClientID {- return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "refresh token was not issued to this client")- }-- // Validate not expired- if time.Now().After(refreshToken.ExpiresAt) {- // Delete expired token- if err := s.store.DeleteOAuth2RefreshToken(ctx, client.ClientID, tokenHash); err != nil {- slog.Warn("failed to delete expired OAuth2 refresh token", log.BBError(err))- }- return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "refresh token has expired")- }-- // A refresh re-issues the grant as consented: the stored resource and scope- // are carried forward verbatim, and a request naming different ones is- // rejected rather than honored. Checked before the token is consumed so a- // rejected refresh leaves the client able to retry correctly.- if failure := checkConsentedResource(formValues, refreshToken.Config.GetResource()); failure != nil {- return tokenFailure(c, failure)- }- if failure := checkConsentedScope(formValues, refreshToken.Config.GetScope()); failure != nil {+ refreshToken, failure := s.validateRefreshTokenGrant(ctx, client, req, formValues)+ if failure != nil {return tokenFailure(c, failure)}+ tokenHash := auth.HashToken(req.RefreshToken)// Consume the refresh token after validations pass. This atomic delete is// the single-use rotation gate: concurrent refreshes race here so only the@@ -314,6 +298,56 @@ func (s *Service) handleRefreshTokenGrant(c *echo.Context, client *store.OAuth2C})}+// validateRefreshTokenGrant looks up the refresh token and runs every check+// that must pass before it may be consumed: client binding, expiry, the+// consented resource/scope match, and the legacy resource-binding gate.+// Returning a failure leaves the token intact so the client can correct its+// request and retry — or, when the grant itself is retired, re-authorize.+func (s *Service) validateRefreshTokenGrant(ctx context.Context, client *store.OAuth2ClientMessage, req *tokenRequest, formValues url.Values) (*store.OAuth2RefreshTokenMessage, *oauth2Failure) {+ if req.RefreshToken == "" {+ return nil, &oauth2Failure{code: "invalid_request", description: "refresh_token is required"}+ }++ tokenHash := auth.HashToken(req.RefreshToken)+ refreshToken, err := s.store.GetOAuth2RefreshToken(ctx, client.ClientID, tokenHash)+ if err != nil {+ return nil, &oauth2Failure{code: "server_error", description: "failed to lookup refresh token"}+ }+ if refreshToken == nil {+ return nil, &oauth2Failure{code: "invalid_grant", description: "invalid refresh token"}+ }++ // Validate token belongs to this client BEFORE deleting+ // This prevents DoS where attacker with stolen token invalidates it for legitimate client+ if refreshToken.ClientID != client.ClientID {+ return nil, &oauth2Failure{code: "invalid_grant", description: "refresh token was not issued to this client"}+ }++ // Validate not expired+ if time.Now().After(refreshToken.ExpiresAt) {+ // Delete expired token+ if err := s.store.DeleteOAuth2RefreshToken(ctx, client.ClientID, tokenHash); err != nil {+ slog.Warn("failed to delete expired OAuth2 refresh token", log.BBError(err))+ }+ return nil, &oauth2Failure{code: "invalid_grant", description: "refresh token has expired"}+ }++ // A refresh re-issues the grant as consented: the stored resource and scope+ // are carried forward verbatim, and a request naming different ones is+ // rejected rather than honored. Checked before the token is consumed so a+ // rejected refresh leaves the client able to retry correctly.+ if failure := checkConsentedResource(formValues, refreshToken.Config.GetResource()); failure != nil {+ return nil, failure+ }+ if failure := checkConsentedScope(formValues, refreshToken.Config.GetScope()); failure != nil {+ return nil, failure+ }+ if refreshToken.Config.GetResource() == "" {+ return nil, legacyGrantFailure()+ }+ return refreshToken, nil+}+// workspaceResolutionError maps the typed errors from resolveBoundWorkspace// onto RFC 6749 OAuth2 error responses. Membership failure is invalid_grant// (400); everything else is an internal failure surfaced as server_error@@ -395,7 +429,9 @@ func (s *Service) issueTokens(c *echo.Context, client *store.OAuth2ClientMessage// Generate access token (JWT) with the workspace_id claim that// downstream APIs (gRPC services, MCP middleware) use to scope requests.- accessToken, err := auth.GenerateOAuth2AccessToken(grant.userEmail, client.ClientID, grant.workspaceID, s.secret, accessTokenExpiry)+ // 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)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.goindex b8f4a0272a..212109c15c 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, 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@@ -134,6 +134,7 @@ func TestIssueTokensPlacesWorkspaceInJWT(t *testing.T) {require.Equal(t, workspaceID, claims["workspace_id"])require.Equal(t, userEmail, claims["sub"])require.Equal(t, clientID, claims["client_id"])- // `aud` is serialized as a single-element array by jwt.ClaimStrings.- require.Equal(t, []any{auth.OAuth2AccessTokenAudience}, claims["aud"])+ // `aud` is serialized as a single-element array by jwt.ClaimStrings. Since+ // P1a PR 3 it carries the grant's stored canonical resource URI.+ require.Equal(t, []any{testResource}, claims["aud"])}diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.goindex 644a84028d..65213d45ff 100644--- a/backend/api/v1/auth_service.go+++ b/backend/api/v1/auth_service.go@@ -1194,6 +1194,14 @@ 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@@ -1219,7 +1227,7 @@ func (s *AuthService) SwitchWorkspace(ctx context.Context, req *connect.Request[accessTokenStr, _ := auth.GetTokenFromHeaders(req.Header())if accessTokenStr != "" {tokenClaims, err := auth.ExtractClaimsFromExpiredToken(accessTokenStr, s.secret)- if err == nil && slices.Contains(tokenClaims.Audience, auth.OAuth2AccessTokenAudience) {+ if err == nil && isMCPBoundToken(tokenClaims) {return nil, connect.NewError(connect.CodePermissionDenied, errors.New("OAuth2 tokens cannot be used to switch workspaces"))}}diff --git a/backend/api/v1/auth_service_test.go b/backend/api/v1/auth_service_test.goindex 8fe629da81..ca93432ce0 100644--- a/backend/api/v1/auth_service_test.go+++ b/backend/api/v1/auth_service_test.go@@ -41,6 +41,37 @@ 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) {+ 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))+ })+}+func TestLoginAuthMethodRequiresPasswordReset(t *testing.T) {emailCode := "123456"tests := []struct {