Skip to content

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

refactor: mcp auth (#21099)

ecmadaob58767773f7b
diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.go
index 932a6bd56d..b4cd7dda6c 100644
--- a/backend/api/mcp/server.go
+++ b/backend/api/mcp/server.go
@@ -7,6 +7,7 @@ import (
"log/slog"
"net/http"
"strings"
+ "sync"
"time"
"github.com/golang-jwt/jwt/v5"
@@ -31,6 +32,8 @@ type Server struct {
secret string
openAPIIndex *OpenAPIIndex
+ revokedAccessTokens sync.Map // map[string]struct{}
+
// planCheckPollBudgetOverride lets tests shorten the plan-check poll budget.
// Zero means use the default (planCheckPollBudget).
planCheckPollBudgetOverride time.Duration
@@ -86,6 +89,7 @@ func (s *Server) registerTools() {
s.registerQueryTool()
s.registerSchemaTool()
s.registerChangeTool()
+ s.registerReauthorizeTool()
}
// authMiddleware validates OAuth2 bearer tokens for MCP requests.
@@ -108,6 +112,9 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return s.unauthorized(c, "authorization header format must be Bearer {token}")
}
tokenStr := parts[1]
+ if _, revoked := s.revokedAccessTokens.Load(tokenStr); revoked {
+ return s.unauthorized(c, "token revoked")
+ }
// Parse and validate JWT
claims := jwt.MapClaims{}
@@ -159,6 +166,10 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
if !ok || sub == "" {
return s.unauthorized(c, "invalid token: missing subject")
}
+ clientID, ok := claims["client_id"].(string)
+ if !ok {
+ clientID = ""
+ }
// Extract workspace ID from token claims.
workspaceID, ok := claims["workspace_id"].(string)
@@ -178,6 +189,8 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
// Store access token and workspace ID in request context for MCP tools.
ctx := c.Request().Context()
ctx = withAccessToken(ctx, tokenStr)
+ ctx = withUserEmail(ctx, sub)
+ ctx = withOAuth2ClientID(ctx, clientID)
ctx = withWorkspaceID(ctx, workspaceID)
c.SetRequest(c.Request().WithContext(ctx))
diff --git a/backend/api/mcp/server_test.go b/backend/api/mcp/server_test.go
index 1adf67540a..01b6ff945d 100644
--- a/backend/api/mcp/server_test.go
+++ b/backend/api/mcp/server_test.go
@@ -147,6 +147,32 @@ func TestMCPAuthMiddlewareValidToken(t *testing.T) {
require.Equal(t, http.StatusOK, rec.Code)
}
+func TestMCPAuthMiddlewareOAuthContext(t *testing.T) {
+ secret := "test-secret-key"
+ profile := &config.Profile{Mode: common.ReleaseModeDev}
+
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+generateOAuth2MCPToken(t, secret, "client-A", "ws-test"))
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+
+ s, err := NewServer(nil, profile, secret)
+ require.NoError(t, err)
+ handler := s.authMiddleware(func(c *echo.Context) error {
+ ctx := c.Request().Context()
+ require.Equal(t, "[email protected]", getUserEmail(ctx))
+ require.Equal(t, "client-A", getOAuth2ClientID(ctx))
+ require.Equal(t, "ws-test", getWorkspaceID(ctx))
+ return c.String(http.StatusOK, "success")
+ })
+
+ err = handler(c)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, rec.Code)
+}
+
// TestMCPProxiedPublicHostNotRejected is the BYT-9693 regression. Behind a
// same-host reverse proxy (proxy_pass http://127.0.0.1:8080), the connection
// Bytebase accepts has a loopback LocalAddr while the proxy preserves the public
@@ -238,6 +264,24 @@ func generateValidToken(t *testing.T, secret string) string {
return tokenStr
}
+func generateOAuth2MCPToken(t *testing.T, secret, clientID, workspaceID 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(),
+ "client_id": clientID,
+ "workspace_id": workspaceID,
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ token.Header["kid"] = "v1"
+ tokenStr, err := token.SignedString([]byte(secret))
+ require.NoError(t, err)
+ return tokenStr
+}
+
func generateExpiredToken(t *testing.T, secret string) string {
t.Helper()
claims := jwt.MapClaims{
diff --git a/backend/api/mcp/tool_http.go b/backend/api/mcp/tool_http.go
index bff9e1b36d..07b500939e 100644
--- a/backend/api/mcp/tool_http.go
+++ b/backend/api/mcp/tool_http.go
@@ -110,6 +110,38 @@ func getAccessToken(ctx context.Context) string {
return ""
}
+// Context key for storing the authenticated user email.
+type userEmailKey struct{}
+
+// withUserEmail adds the authenticated user email to the context.
+func withUserEmail(ctx context.Context, email string) context.Context {
+ return context.WithValue(ctx, userEmailKey{}, email)
+}
+
+// getUserEmail retrieves the authenticated user email from the context.
+func getUserEmail(ctx context.Context) string {
+ if email, ok := ctx.Value(userEmailKey{}).(string); ok {
+ return email
+ }
+ return ""
+}
+
+// Context key for storing the OAuth2 client ID.
+type oauth2ClientIDKey struct{}
+
+// withOAuth2ClientID adds the OAuth2 client ID to the context.
+func withOAuth2ClientID(ctx context.Context, id string) context.Context {
+ return context.WithValue(ctx, oauth2ClientIDKey{}, id)
+}
+
+// getOAuth2ClientID retrieves the OAuth2 client ID from the context.
+func getOAuth2ClientID(ctx context.Context) string {
+ if id, ok := ctx.Value(oauth2ClientIDKey{}).(string); ok {
+ return id
+ }
+ return ""
+}
+
// Context key for storing the workspace ID.
type workspaceIDKey struct{}
diff --git a/backend/api/mcp/tool_reauthorize.go b/backend/api/mcp/tool_reauthorize.go
new file mode 100644
index 0000000000..de5278456b
--- /dev/null
+++ b/backend/api/mcp/tool_reauthorize.go
@@ -0,0 +1,59 @@
+package mcp
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/pkg/errors"
+)
+
+// ReauthorizeInput is the input for the reauthorize tool.
+type ReauthorizeInput struct{}
+
+const reauthorizeDescription = `Log out the current MCP OAuth connection so the client can run OAuth again.
+
+Use this when you need to change the connected Bytebase account or SaaS workspace. After this tool succeeds, retry the MCP request or reconnect; the server will return the normal OAuth challenge.`
+
+func (s *Server) registerReauthorizeTool() {
+ mcp.AddTool(s.mcpServer, &mcp.Tool{
+ Name: "reauthorize",
+ Description: reauthorizeDescription,
+ }, s.handleReauthorize)
+}
+
+func (s *Server) handleReauthorize(ctx context.Context, _ *mcp.CallToolRequest, _ ReauthorizeInput) (*mcp.CallToolResult, any, error) {
+ accessToken := getAccessToken(ctx)
+ userEmail := getUserEmail(ctx)
+ clientID := getOAuth2ClientID(ctx)
+ if accessToken == "" || userEmail == "" || clientID == "" {
+ return formatToolError(&toolError{
+ Code: "NOT_OAUTH_SESSION",
+ 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
+ }
+ // MCP sessions are currently process-local and already require requests to
+ // stay on the same replica. This marker follows that constraint. If MCP gains
+ // multi-replica session support, move the reauthorization state to shared storage.
+ s.revokedAccessTokens.Store(accessToken, struct{}{})
+
+ workspaceID := getWorkspaceID(ctx)
+ message := "OAuth refresh grant revoked. Retry or reconnect this MCP server to run OAuth again."
+ if workspaceID != "" {
+ message = fmt.Sprintf("%s The previous grant was for workspace %q.", message, workspaceID)
+ }
+ output := map[string]any{
+ "reauthorizationRequired": true,
+ "workspace": workspaceID,
+ }
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{&mcp.TextContent{Text: message}},
+ }, output, nil
+}
diff --git a/backend/api/mcp/tool_reauthorize_test.go b/backend/api/mcp/tool_reauthorize_test.go
new file mode 100644
index 0000000000..c871151fca
--- /dev/null
+++ b/backend/api/mcp/tool_reauthorize_test.go
@@ -0,0 +1,89 @@
+package mcp
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/labstack/echo/v5"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/component/config"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/migrator"
+ "github.com/bytebase/bytebase/backend/store"
+
+ _ "github.com/bytebase/bytebase/backend/plugin/db/pg"
+)
+
+func TestReauthorizeRejectsCurrentAccessToken(t *testing.T) {
+ 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, `
+ INSERT INTO workspace (resource_id) VALUES ('ws-test');
+ INSERT INTO principal (name, email, password_hash) VALUES ('demo', '[email protected]', 'unused');
+ INSERT INTO oauth2_client (client_id, workspace, client_secret_hash, config)
+ VALUES ('client-A', NULL, 'unused-hash', '{"clientName":"test","redirectUris":["http://localhost/cb"],"grantTypes":["authorization_code","refresh_token"],"tokenEndpointAuthMethod":"none"}'::jsonb);
+ `)
+ 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)
+
+ refreshToken := "refresh-token"
+ _, err = st.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{
+ TokenHash: auth.HashToken(refreshToken),
+ ClientID: "client-A",
+ UserEmail: "[email protected]",
+ Workspace: "ws-test",
+ Config: &storepb.OAuth2RefreshTokenConfig{},
+ ExpiresAt: time.Now().Add(time.Hour),
+ })
+ require.NoError(t, err)
+
+ const secret = "test-secret-key"
+ s, err := NewServer(st, &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}, secret)
+ require.NoError(t, err)
+
+ accessToken := generateOAuth2MCPToken(t, secret, "client-A", "ws-test")
+ reauthorizeCtx := withAccessToken(ctx, accessToken)
+ reauthorizeCtx = withUserEmail(reauthorizeCtx, "[email protected]")
+ reauthorizeCtx = withOAuth2ClientID(reauthorizeCtx, "client-A")
+ reauthorizeCtx = withWorkspaceID(reauthorizeCtx, "ws-test")
+ _, _, err = s.handleReauthorize(reauthorizeCtx, nil, ReauthorizeInput{})
+ require.NoError(t, err)
+
+ stored, err := st.GetOAuth2RefreshToken(ctx, "client-A", auth.HashToken(refreshToken))
+ require.NoError(t, err)
+ require.Nil(t, stored)
+
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))
+ req.Header.Set("Authorization", "Bearer "+accessToken)
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+ handler := s.authMiddleware(func(c *echo.Context) error {
+ return c.String(http.StatusOK, "success")
+ })
+ if err := handler(c); err != nil {
+ echo.DefaultHTTPErrorHandler(true)(c, err)
+ }
+
+ require.Equal(t, http.StatusUnauthorized, rec.Code)
+ require.Contains(t, rec.Header().Get("WWW-Authenticate"), `error="invalid_token"`)
+}
diff --git a/backend/api/oauth2/authorize.go b/backend/api/oauth2/authorize.go
index efd3bc6815..e495a5cad4 100644
--- a/backend/api/oauth2/authorize.go
+++ b/backend/api/oauth2/authorize.go
@@ -70,11 +70,18 @@ func (s *Service) handleAuthorizeGet(c *echo.Context) error {
return oauth2ErrorRedirect(c, redirectURI, state, "invalid_request", "code_challenge_method must be S256")
}
- // Validate the resource/scope the client is asking for before showing a
- // consent screen for something we would refuse to issue.
- params, failure := s.parseGrantParams(ctx, c.QueryParams())
- if failure != nil {
- return oauth2ErrorRedirect(c, redirectURI, state, failure.code, failure.description)
+ values := c.QueryParams()
+ resource, err := singleValue(values, "resource")
+ if err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "invalid_target", err.Error())
+ }
+ requestedScope, err := singleValue(values, "scope")
+ if err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "invalid_scope", err.Error())
+ }
+ scope, err := canonicalizeScope(requestedScope)
+ if err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "invalid_scope", err.Error())
}
// Redirect to frontend consent page.
@@ -88,8 +95,8 @@ func (s *Service) handleAuthorizeGet(c *echo.Context) error {
url.QueryEscape(state),
url.QueryEscape(codeChallenge),
url.QueryEscape(codeChallengeMethod),
- url.QueryEscape(params.resource),
- url.QueryEscape(params.scope),
+ url.QueryEscape(resource),
+ url.QueryEscape(scope),
)
return c.Redirect(http.StatusFound, consentURL)
}
@@ -117,6 +124,11 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "user denied the request")
}
+ consenting, failure := s.resolveConsentingUser(c, client)
+ if failure != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, failure.code, failure.description)
+ }
+
// Re-validate resource/scope here rather than trusting what the consent page
// posted back: this endpoint is reachable directly, so the GET's validation
// is not a guarantee about the POST.
@@ -124,12 +136,7 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
if err != nil {
return oauth2ErrorRedirect(c, redirectURI, state, "invalid_request", "failed to parse request")
}
- params, failure := s.parseGrantParams(ctx, formValues)
- if failure != nil {
- return oauth2ErrorRedirect(c, redirectURI, state, failure.code, failure.description)
- }
-
- consenting, failure := s.resolveConsentingUser(c, client)
+ params, failure := s.parseGrantParams(ctx, formValues, consenting.workspaceID)
if failure != nil {
return oauth2ErrorRedirect(c, redirectURI, state, failure.code, failure.description)
}
diff --git a/backend/api/oauth2/grant_test.go b/backend/api/oauth2/grant_test.go
index e97066abd1..115aeed302 100644
--- a/backend/api/oauth2/grant_test.go
+++ b/backend/api/oauth2/grant_test.go
@@ -70,6 +70,35 @@ func TestResourceScopeGrantLifecycle(t *testing.T) {
configured := newTestService(st, "https://bb.example.com")
+ t.Run("authorization starts without an existing browser session", func(t *testing.T) {
+ entryService := newTestService(st, "")
+ entryService.profile.SaaS = true
+ challenge := sha256.Sum256([]byte(testCodeVerifier))
+ query := url.Values{
+ "response_type": {"code"},
+ "client_id": {testClientID},
+ "redirect_uri": {testRedirectURI},
+ "state": {"test-state"},
+ "code_challenge": {base64.RawURLEncoding.EncodeToString(challenge[:])},
+ "code_challenge_method": {"S256"},
+ "resource": {testResource},
+ }
+ req := httptest.NewRequest(http.MethodGet, "/api/oauth2/authorize?"+query.Encode(), nil)
+ rec := httptest.NewRecorder()
+ e := echo.New()
+ c := e.NewContext(req, rec)
+ require.NoError(t, entryService.handleAuthorizeGet(c))
+ response, err := echo.UnwrapResponse(c.Response())
+ require.NoError(t, err)
+ require.Equal(t, http.StatusFound, response.Status)
+
+ location, err := url.Parse(response.Header().Get("Location"))
+ require.NoError(t, err)
+ require.Equal(t, "/oauth2/consent", location.Path)
+ require.Equal(t, testClientID, location.Query().Get("client_id"))
+ require.Equal(t, testResource, location.Query().Get("resource"))
+ })
+
t.Run("configured external URL: matching resource and known scope are consented", func(t *testing.T) {
code := consentOK(t, configured, url.Values{"resource": {testResource}, "scope": {"mcp:read-only"}})
@@ -116,7 +145,6 @@ func TestResourceScopeGrantLifecycle(t *testing.T) {
wantCode string
}{
{"resource on another host", url.Values{"resource": {"https://evil.example.com/mcp"}}, "invalid_target"},
- {"noncanonical resource", url.Values{"resource": {"https://bb.example.com:443/mcp"}}, "invalid_target"},
{"resource parameter repeated", url.Values{"resource": {testResource, testResource}}, "invalid_target"},
{"unknown scope", url.Values{"scope": {"mcp:admin"}}, "invalid_scope"},
{"scope parameter repeated", url.Values{"scope": {"mcp:read-only", "mcp:read-write"}}, "invalid_scope"},
@@ -128,16 +156,26 @@ func TestResourceScopeGrantLifecycle(t *testing.T) {
})
}
+ t.Run("default port resource is consented as the canonical resource", func(t *testing.T) {
+ code := consentOK(t, configured, url.Values{"resource": {"https://bb.example.com:443/mcp"}})
+ got, err := st.GetOAuth2AuthorizationCode(ctx, testClientID, code)
+ require.NoError(t, err)
+ require.Equal(t, testResource, got.Config.Resource)
+ })
+
t.Run("no configured external URL: a resource request gets the actionable setup error", func(t *testing.T) {
- // The ship gate of proposal v2 §6.2 — self-hosted instances running on
- // the request-Host fallback break here, and the error has to tell the
- // admin exactly what to set rather than fail generically.
+ _, err := st.UpsertSetting(ctx, &store.SettingMessage{
+ Name: storepb.SettingName_WORKSPACE_PROFILE,
+ Workspace: testWorkspace,
+ Value: &storepb.WorkspaceProfileSetting{},
+ })
+ require.NoError(t, err)
+
unconfigured := newTestService(st, "")
redirect := consent(t, unconfigured, url.Values{"resource": {testResource}})
require.Equal(t, "server_error", redirect.Query().Get("error"))
description := redirect.Query().Get("error_description")
- require.Contains(t, description, "--external-url")
- require.Contains(t, description, "External URL")
+ 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) {
diff --git a/backend/api/oauth2/resource.go b/backend/api/oauth2/resource.go
index 8690e6a0d4..3e2f200e59 100644
--- a/backend/api/oauth2/resource.go
+++ b/backend/api/oauth2/resource.go
@@ -9,7 +9,7 @@ import (
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/utils"
)
@@ -19,19 +19,6 @@ import (
// our RFC 9728 metadata document publishes.
const mcpResourcePath = "/mcp"
-// externalURLSetupError is returned when a client asks to bind a token to a
-// resource but the deployment has no configured external URL. It names the two
-// places an admin can set one, because the fix is entirely on the server side
-// and the client operator can do nothing about it.
-const externalURLSetupError = "MCP OAuth requires a configured external URL. Start the server with --external-url https://<your-bytebase-host>, or set Settings > General > External URL " +
- "(https://docs.bytebase.com/get-started/self-host/external-url), then reconnect. The request Host header is deliberately not trusted for resource binding."
-
-// errExternalURLNotConfigured is returned by trustedExternalURL when no trusted
-// external URL is available, so resource validation is never handed an empty base
-// to interpret. Mapped to the actionable configuration error above at the call
-// site; every other validation failure is a client error.
-var errExternalURLNotConfigured = errors.New("no configured external URL to validate the resource against")
-
// scopeLadder is the P1a scope vocabulary — one scope per predefined permission
// set — ordered narrowest to widest. Vocabulary per proposal v2 §4; the
// Metadata-only tier is deferred, so there are two rungs.
@@ -44,7 +31,7 @@ var scopeLadder = []string{"mcp:read-only", "mcp:read-write"}
// grantParams is the validated resource/scope pair consented for one grant.
type grantParams struct {
- // resource is canonical (see canonicalizeResourceURI) or empty.
+ // resource is canonical or empty.
resource string
// scope is the single mode the requested scope set resolved to, or empty.
scope string
@@ -58,54 +45,11 @@ type oauth2Failure struct {
description string
}
-// trustedExternalURL returns the canonical external URL configured for this
-// deployment: the --external-url flag, else the workspace setting. It returns
-// errExternalURLNotConfigured when neither is available, so callers never have to
-// interpret an empty string.
-//
-// Unlike getBaseURL this deliberately has no request-derived tier. Host and
-// X-Forwarded-Proto are client-controlled, so a header-derived value would let a
-// caller choose the audience its own token is bound to — which is the entire
-// property the resource binding exists to establish.
-func (s *Service) trustedExternalURL(ctx context.Context) (string, error) {
- if s.profile.ExternalURL != "" {
- return strings.TrimSuffix(s.profile.ExternalURL, "/"), nil
- }
- // The workspace ID is only resolved on self-hosted, and that is a correctness
- // requirement rather than an assumption that SaaS passes the flag:
- //
- // - GetWorkspaceID is a singleton lookup (`... WHERE deleted = FALSE LIMIT 1`),
- // so on SaaS it returns an arbitrary workspace. Feeding that to
- // GetEffectiveExternalURL would validate this grant's resource against an
- // unrelated tenant's setting.
- // - On SaaS the setting cannot hold a value anyway: writes to
- // workspace_profile.external_url are rejected outright in SaaS mode
- // (setting_service.go), so the flag is the only source that can exist.
- //
- // Same tier order as getBaseURL and mcp's buildResourceMetadataURL, minus
- // their request-derived tail. Unifying the three is BOT-32.
- workspaceID := ""
- if !s.profile.SaaS {
- if ws, err := s.store.GetWorkspaceID(ctx); err == nil {
- workspaceID = ws
- }
- }
- // GetEffectiveExternalURL reports "not configured" as an error, never as an
- // empty string. A lookup failure is treated identically — fail closed, never
- // fall back to the request — with the cause logged rather than returned.
- externalURL, err := utils.GetEffectiveExternalURL(ctx, s.store, s.profile, workspaceID)
- if err != nil {
- slog.Warn("failed to resolve trusted external URL for OAuth2 resource binding", log.BBError(err))
- return "", errExternalURLNotConfigured
- }
- return strings.TrimSuffix(externalURL, "/"), nil
-}
-
// 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.
-func (s *Service) parseGrantParams(ctx context.Context, values url.Values) (grantParams, *oauth2Failure) {
+func (s *Service) parseGrantParams(ctx context.Context, values url.Values, workspaceID string) (grantParams, *oauth2Failure) {
resource, err := singleValue(values, "resource")
if err != nil {
return grantParams{}, &oauth2Failure{code: "invalid_target", description: err.Error()}
@@ -122,13 +66,16 @@ func (s *Service) parseGrantParams(ctx context.Context, values url.Values) (gran
return grantParams{scope: scope}, nil
}
- trustedBaseURL, err := s.trustedExternalURL(ctx)
+ // GetEffectiveExternalURL reports "not configured" as an error, never as an
+ // empty string. Fail closed, 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.String("resource", resource))
- return grantParams{}, &oauth2Failure{code: "server_error", description: externalURLSetupError}
+ return grantParams{}, &oauth2Failure{code: "server_error", description: err.Error()}
}
- canonical, err := validateResource(resource, trustedBaseURL)
+
+ canonical, err := validateResource(resource, externalURL)
if err != nil {
return grantParams{}, &oauth2Failure{code: "invalid_target", description: err.Error()}
}
@@ -156,7 +103,7 @@ func checkConsentedResource(values url.Values, consented string) *oauth2Failure
if requested == "" {
return nil
}
- canonical, err := canonicalizeResourceURI(requested)
+ canonical, err := common.NormalizeExternalURL(requested)
if err != nil {
return &oauth2Failure{code: "invalid_target", description: err.Error()}
}
@@ -233,9 +180,8 @@ func singleValue(values url.Values, name string) (string, error) {
}
// validateResource checks that a client-supplied resource indicator names this
-// server and returns the form to consent to. trustedBaseURL comes from
-// trustedExternalURL, which reports an unconfigured deployment as an error, so it
-// is always a real URL here.
+// server and returns the form to consent to. externalURL comes from deployment
+// config and is already normalized.
//
// Accepted inputs: the canonical MCP resource URI (<base>/mcp) and the bare
// origin (<base>) — the two values our own RFC 9728 metadata documents publish,
@@ -245,55 +191,18 @@ func singleValue(values url.Values, name string) (string, error) {
// access token's audience to this stored value, and two accepted spellings of one
// resource would mean two audiences to accept at /mcp — forever, since grants are
// long-lived. Normalizing at the door keeps the audience single-valued.
-func validateResource(resource, trustedBaseURL string) (string, error) {
- base, err := canonicalizeResourceURI(trustedBaseURL)
- if err != nil {
- return "", errors.Wrapf(err, "configured external URL %q is not a usable absolute URL", trustedBaseURL)
- }
- mcpResource := base + mcpResourcePath
- canonical, err := canonicalizeResourceURI(resource)
+func validateResource(resource, externalURL string) (string, error) {
+ mcpResource := externalURL + mcpResourcePath
+ canonical, err := common.NormalizeExternalURL(resource)
if err != nil {
return "", err
}
- if canonical != base && canonical != mcpResource {
+ if canonical != externalURL && canonical != mcpResource {
return "", errors.Errorf("resource %q is not this server's MCP resource; expected %q", canonical, mcpResource)
}
return mcpResource, nil
}
-// canonicalizeResourceURI normalizes the two differences a resource URI may
-// carry without changing which resource it names: scheme and host case, and a
-// trailing slash. Everything else is left exactly as sent — a port, a
-// percent-encoded path, a different path — so a noncanonical value fails the
-// comparison in validateResource instead of being quietly accepted as equal.
-//
-// Query strings, fragments, and userinfo are rejected outright: RFC 8707 §2
-// resource URIs must not carry a fragment, and none of the three ever appear in
-// a legitimate MCP resource identifier.
-func canonicalizeResourceURI(resource string) (string, error) {
- u, err := url.Parse(resource)
- if err != nil {
- return "", errors.Wrap(err, "resource is not a valid URI")
- }
- scheme := strings.ToLower(u.Scheme)
- if scheme != "http" && scheme != "https" {
- return "", errors.Errorf("resource must be an absolute http(s) URI, got %q", resource)
- }
- if u.Host == "" {
- return "", errors.Errorf("resource must name a host, got %q", resource)
- }
- if u.User != nil {
- return "", errors.New("resource must not carry userinfo")
- }
- if u.RawQuery != "" || u.ForceQuery {
- return "", errors.New("resource must not carry a query string")
- }
- if u.Fragment != "" || u.RawFragment != "" {
- return "", errors.New("resource must not carry a fragment")
- }
- return scheme + "://" + strings.ToLower(u.Host) + strings.TrimSuffix(u.EscapedPath(), "/"), nil
-}
-
// canonicalizeScope reduces a requested scope set to the one mode a grant can be
// bound to: the requested maximum, the highest rung named. Returns "" for an
// empty or whitespace-only request.
diff --git a/backend/api/oauth2/resource_test.go b/backend/api/oauth2/resource_test.go
index a24f0a8a1e..ca402e4ddd 100644
--- a/backend/api/oauth2/resource_test.go
+++ b/backend/api/oauth2/resource_test.go
@@ -6,8 +6,6 @@ import (
"testing"
"github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/backend/component/config"
)
const testTrustedBase = "https://bb.example.com"
@@ -28,6 +26,7 @@ func TestValidateResource(t *testing.T) {
{"canonical MCP resource URI", "https://bb.example.com/mcp", "https://bb.example.com/mcp"},
{"trailing slash is stripped", "https://bb.example.com/mcp/", "https://bb.example.com/mcp"},
{"scheme and host case are normalized", "HTTPS://BB.Example.COM/mcp", "https://bb.example.com/mcp"},
+ {"default port is stripped", "https://bb.example.com:443/mcp", "https://bb.example.com/mcp"},
// Our own RFC 9728 document at the unsuffixed well-known path publishes
// the bare origin as `resource`, so a client that read it must not be
// rejected for using the value we advertised — but it is stored as the
@@ -51,10 +50,6 @@ func TestValidateResource(t *testing.T) {
{"different scheme", "http://bb.example.com/mcp"},
{"different path", "https://bb.example.com/v1/sql"},
{"path case differs (paths are case-sensitive)", "https://bb.example.com/MCP"},
- // Not normalized on purpose: adding :443 to a URI we never published is
- // a noncanonical value, and quietly treating it as equal would widen
- // what counts as "this server".
- {"explicit default port", "https://bb.example.com:443/mcp"},
{"nondefault port", "https://bb.example.com:8443/mcp"},
{"percent-encoded path separator", "https://bb.example.com%2Fmcp"},
{"query string", "https://bb.example.com/mcp?x=1"},
@@ -72,24 +67,13 @@ func TestValidateResource(t *testing.T) {
})
}
- t.Run("a trailing slash on the configured URL does not change what is accepted", func(t *testing.T) {
- got, err := validateResource("https://bb.example.com/mcp", "https://bb.example.com/")
- require.NoError(t, err)
- require.Equal(t, "https://bb.example.com/mcp", got)
- })
-
- t.Run("a mixed-case configured URL still matches a canonical resource", func(t *testing.T) {
- got, err := validateResource("https://bb.example.com/mcp", "https://BB.Example.com")
- require.NoError(t, err)
- require.Equal(t, "https://bb.example.com/mcp", got)
- })
-
t.Run("every accepted spelling collapses to one stored value", func(t *testing.T) {
stored := map[string]struct{}{}
for _, in := range []string{
"https://bb.example.com/mcp",
"https://bb.example.com/mcp/",
"HTTPS://BB.Example.COM/mcp",
+ "https://bb.example.com:443/mcp",
"https://bb.example.com",
"https://bb.example.com/",
} {
@@ -188,7 +172,7 @@ func TestCheckConsentedResource(t *testing.T) {
{"bare origin with trailing slash matches", url.Values{"resource": {"https://bb.example.com/"}}, consented, ""},
{"bare origin of a different host still fails", url.Values{"resource": {"https://evil.example.com"}}, consented, "invalid_target"},
{"different resource", url.Values{"resource": {"https://evil.example.com/mcp"}}, consented, "invalid_target"},
- {"noncanonical value that is not equivalent", url.Values{"resource": {"https://bb.example.com:443/mcp"}}, consented, "invalid_target"},
+ {"default port is equivalent", url.Values{"resource": {"https://bb.example.com:443/mcp"}}, consented, ""},
{"malformed value", url.Values{"resource": {"not a uri"}}, consented, "invalid_target"},
{"repeated value", url.Values{"resource": {consented, consented}}, consented, "invalid_target"},
// A grant with no stored resource predates the column (or the client never
@@ -256,16 +240,3 @@ func TestCheckConsentedScope(t *testing.T) {
})
}
}
-
-// TestTrustedExternalURLUsesTheFlagOnly is the negative control for the whole
-// PR: getBaseURL falls back to the request Host, and that fallback must never
-// reach resource validation, because a client controls it and could then name
-// the audience of its own token. trustedExternalURL takes no request at all —
-// there is nothing to fall back to.
-func TestTrustedExternalURLUsesTheFlagOnly(t *testing.T) {
- s := &Service{profile: &config.Profile{ExternalURL: "https://bb.example.com/"}}
- got, err := s.trustedExternalURL(t.Context())
- require.NoError(t, err)
- require.Equal(t, "https://bb.example.com", got,
- "the flag is the trusted tier and its trailing slash is normalized away")
-}
diff --git a/backend/common/util.go b/backend/common/util.go
index c653bbbe8a..85a55f6a31 100644
--- a/backend/common/util.go
+++ b/backend/common/util.go
@@ -6,9 +6,9 @@ import (
"encoding/base64"
"fmt"
"math/big"
+ "net/url"
"reflect"
"regexp"
- "strconv"
"strings"
"unicode/utf8"
@@ -121,30 +121,45 @@ func Unobfuscate(dst, seed string) (string, error) {
}
// NormalizeExternalURL will format the external url.
-func NormalizeExternalURL(url string) (string, error) {
- r := strings.TrimSpace(url)
+func NormalizeExternalURL(externalURL string) (string, error) {
+ r := strings.TrimSpace(externalURL)
r = strings.TrimSuffix(r, "/")
- if !HasPrefixes(r, "http://", "https://") {
- return "", errors.Errorf("%s must start with http:// or https://", url)
+ u, err := url.Parse(r)
+ if err != nil {
+ return "", errors.Wrapf(err, "%s malformed", externalURL)
}
- parts := strings.Split(r, ":")
- if len(parts) > 3 {
- return "", errors.Errorf("%s malformed", url)
+ scheme := strings.ToLower(u.Scheme)
+ if scheme != "http" && scheme != "https" {
+ return "", errors.Errorf("%s must start with http:// or https://", externalURL)
}
- if len(parts) == 3 {
- port, err := strconv.Atoi(parts[2])
- if err != nil {
- return "", errors.Errorf("%s has non integer port", url)
- }
+ if u.Host == "" {
+ return "", errors.Errorf("%s must name a host", externalURL)
+ }
+ if u.User != nil {
+ return "", errors.Errorf("%s must not carry userinfo", externalURL)
+ }
+ if u.RawQuery != "" || u.ForceQuery {
+ return "", errors.Errorf("%s must not carry a query string", externalURL)
+ }
+ if u.Fragment != "" || u.RawFragment != "" {
+ return "", errors.Errorf("%s must not carry a fragment", externalURL)
+ }
+
+ host := strings.ToLower(u.Host)
+ port := u.Port()
+ if port != "" {
// The external URL is used as the redirectURL in the get token process of OAuth, and the
// RedirectURL needs to be consistent with the RedirectURL in the get code process.
// The frontend gets it through window.location.origin in the get code
// process, so port 80/443 need to be cropped.
- if port == 80 || port == 443 {
- r = strings.Join(parts[0:2], ":")
+ if (scheme == "http" && port == "80") || (scheme == "https" && port == "443") {
+ host = strings.ToLower(u.Hostname())
+ if strings.Contains(host, ":") {
+ host = "[" + host + "]"
+ }
}
}
- return r, nil
+ return scheme + "://" + host + strings.TrimSuffix(u.EscapedPath(), "/"), nil
}
// ValidatePhone validates the phone number.
diff --git a/backend/common/util_test.go b/backend/common/util_test.go
index 461fb92791..7cf755b92e 100644
--- a/backend/common/util_test.go
+++ b/backend/common/util_test.go
@@ -197,6 +197,11 @@ func TestNormalizeExternalURL(t *testing.T) {
want: "https://localhost:3000",
wantErr: false,
},
+ {
+ url: "HTTPS://LOCALHOST:443/mcp/",
+ want: "https://localhost/mcp",
+ wantErr: false,
+ },
// Missing http:// or https://
{
url: "localhost:3000",
@@ -209,6 +214,21 @@ func TestNormalizeExternalURL(t *testing.T) {
want: "",
wantErr: true,
},
+ {
+ url: "https://user@localhost",
+ want: "",
+ wantErr: true,
+ },
+ {
+ url: "https://localhost?x=1",
+ want: "",
+ wantErr: true,
+ },
+ {
+ url: "https://localhost#fragment",
+ want: "",
+ wantErr: true,
+ },
}
for _, tt := range tests {
t.Run(tt.url, func(t *testing.T) {