Skip to content

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

refactor: fail closed on ambiguous workspace and external URL resolution (#21150)

ecmadaoaa5924722a88
diff --git a/backend/api/mcp/boundary_revalidation_test.go b/backend/api/mcp/boundary_revalidation_test.go
index 53e58c6e51..679fd5119a 100644
--- a/backend/api/mcp/boundary_revalidation_test.go
+++ b/backend/api/mcp/boundary_revalidation_test.go
@@ -51,7 +51,7 @@ func TestBoundaryRevalidatesEveryRequest(t *testing.T) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, `{}`)
})
- s, err := NewServer(nil, profile, revalidationSecret, stub)
+ s, err := newServerWithStore(newTestServerStore(), profile, revalidationSecret, stub)
require.NoError(t, err)
e := echo.New()
@@ -246,7 +246,7 @@ func TestInternalRequestUsesLiveCallerIP(t *testing.T) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, `{}`)
})
- s, err := NewServer(nil, profile, revalidationSecret, stub)
+ s, err := newServerWithStore(newTestServerStore(), profile, revalidationSecret, stub)
require.NoError(t, err)
e := echo.New()
diff --git a/backend/api/mcp/internal_transport_test.go b/backend/api/mcp/internal_transport_test.go
index 164f238772..c8534b9a2d 100644
--- a/backend/api/mcp/internal_transport_test.go
+++ b/backend/api/mcp/internal_transport_test.go
@@ -53,7 +53,7 @@ func runAuthMiddleware(t *testing.T, s *Server, bearer string) (credential strin
func TestMCPAuthMiddlewareMintsDelegatedCredential(t *testing.T) {
secret := "test-secret-key"
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
- s, err := NewServer(nil, profile, secret, nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, secret, nil)
require.NoError(t, err)
inbound, err := auth.GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", "https://bb.example.com/mcp", "mcp:read-only", secret, time.Hour)
@@ -90,7 +90,7 @@ func TestMCPAuthMiddlewareMintsDelegatedCredential(t *testing.T) {
func TestMCPAuthMiddlewareLegacySessionEmptyGrantState(t *testing.T) {
secret := "test-secret-key"
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
- s, err := NewServer(nil, profile, secret, nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, secret, nil)
require.NoError(t, err)
for name, bearer := range map[string]string{
@@ -211,7 +211,7 @@ func TestInternalRequestCarriesCallerIP(t *testing.T) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, `{}`)
})
- s, err := NewServer(nil, profile, secret, stub)
+ s, err := newServerWithStore(newTestServerStore(), profile, secret, stub)
require.NoError(t, err)
inbound, err := auth.GenerateOAuth2AccessToken("[email protected]", "client-A", "ws-test", "https://bb.example.com/mcp", "mcp:read-only", secret, time.Hour)
@@ -242,7 +242,7 @@ func TestInternalRequestCarriesCallerIP(t *testing.T) {
func TestMCPAuthMiddlewareRejectsInternalCredential(t *testing.T) {
secret := "test-secret-key"
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
- s, err := NewServer(nil, profile, secret, nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, secret, nil)
require.NoError(t, err)
internal, err := auth.GenerateInternalMCPToken(auth.DelegatedMCPCredential{
diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.go
index f5a1c0c7c8..5cc906a027 100644
--- a/backend/api/mcp/server.go
+++ b/backend/api/mcp/server.go
@@ -31,7 +31,7 @@ import (
type Server struct {
mcpServer *mcp.Server
httpHandler http.Handler
- store *store.Store
+ store serverStore
profile *config.Profile
secret string
openAPIIndex *OpenAPIIndex
@@ -48,9 +48,23 @@ type Server struct {
planCheckPollBudgetOverride time.Duration
}
+type serverStore interface {
+ GetWorkspaceID(context.Context) (string, error)
+ GetWorkspaceProfileSetting(context.Context, string) (*storepb.WorkspaceProfileSetting, error)
+ GetSettingUncached(context.Context, string, storepb.SettingName) (*store.SettingMessage, error)
+ DeleteOAuth2RefreshTokensByUserAndClient(context.Context, string, string) error
+}
+
// NewServer creates a new MCP server. internalAPI is the internal API handler
// chain tool calls dispatch to in memory; it is never bound to a listener.
-func NewServer(store *store.Store, profile *config.Profile, secret string, internalAPI http.Handler) (*Server, error) {
+func NewServer(stores *store.Store, profile *config.Profile, secret string, internalAPI http.Handler) (*Server, error) {
+ if stores == nil {
+ return nil, errors.New("store is required")
+ }
+ return newServerWithStore(stores, profile, secret, internalAPI)
+}
+
+func newServerWithStore(stores serverStore, profile *config.Profile, secret string, internalAPI http.Handler) (*Server, error) {
mcpServer := mcp.NewServer(&mcp.Implementation{
Name: "bytebase",
Version: profile.Version,
@@ -64,7 +78,7 @@ func NewServer(store *store.Store, profile *config.Profile, secret string, inter
s := &Server{
mcpServer: mcpServer,
- store: store,
+ store: stores,
profile: profile,
secret: secret,
openAPIIndex: openAPIIndex,
@@ -326,11 +340,6 @@ func decideAudience(aud any, expected string, resolveErr error) (bool, error) {
// /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
@@ -447,7 +456,7 @@ func (*Server) verifySessionBinding(_ context.Context, _ string, req *http.Reque
}
// tokenIdentity is the identity material authMiddleware works with after a
-// token verifies: subject, optional client and workspace, and the audience.
+// token verifies: subject, workspace, audience, and an optional client.
// The workspace is extracted before the audience check because resolving the
// expected audience needs it to look up the trusted external URL.
type tokenIdentity struct {
@@ -459,7 +468,7 @@ type tokenIdentity struct {
// extractTokenIdentity pulls the identity claims out of a verified token. A
// missing subject or audience is a token defect (non-empty error message);
-// client_id and workspace_id are optional.
+// client_id is optional; workspace_id is required for every access token.
func extractTokenIdentity(claims jwt.MapClaims) (*tokenIdentity, string) {
sub, ok := claims["sub"].(string)
if !ok || sub == "" {
@@ -473,9 +482,11 @@ func extractTokenIdentity(claims jwt.MapClaims) (*tokenIdentity, string) {
if clientID, ok := claims["client_id"].(string); ok {
identity.clientID = clientID
}
- if workspaceID, ok := claims["workspace_id"].(string); ok {
- identity.workspaceID = workspaceID
+ workspaceID, ok := claims["workspace_id"].(string)
+ if !ok || workspaceID == "" {
+ return nil, "invalid token: missing workspace"
}
+ identity.workspaceID = workspaceID
return identity, ""
}
@@ -544,7 +555,11 @@ func audienceMatches(aud any, want string) bool {
// authorization server. The header references the host-global protected
// resource metadata endpoint (served by the oauth2 package).
func (s *Server) unauthorized(c *echo.Context, errDescription string) error {
- resourceMetadataURL := s.buildResourceMetadataURL(c)
+ resourceMetadataURL, err := s.buildResourceMetadataURL(c)
+ if err != nil {
+ slog.Error("failed to resolve external URL for MCP discovery", log.BBError(err))
+ return echo.NewHTTPError(http.StatusServiceUnavailable, "OAuth2 discovery is unavailable").Wrap(err)
+ }
c.Response().Header().Set(
"WWW-Authenticate",
fmt.Sprintf(
@@ -584,14 +599,6 @@ func mcpConnectionAllowed(capability storepb.WorkspaceProfileSetting_MCPCapabili
// out-of-band admin path (direct SQL, another process). A kill switch must
// observe the stored truth on the next request.
func (s *Server) mcpCapability(ctx context.Context, workspaceID string) storepb.WorkspaceProfileSetting_MCPCapability {
- if s.store == nil {
- return storepb.WorkspaceProfileSetting_READ_WRITE
- }
- if workspaceID == "" && !s.profile.SaaS {
- if id, err := s.store.GetWorkspaceID(ctx); err == nil {
- workspaceID = id
- }
- }
setting, err := s.store.GetSettingUncached(ctx, workspaceID, storepb.SettingName_WORKSPACE_PROFILE)
if err != nil {
slog.Warn("failed to read MCP capability policy; failing closed",
@@ -616,40 +623,11 @@ func (s *Server) mcpCapability(ctx context.Context, workspaceID string) storepb.
// RFC 9728 §3.3 requires the document's `resource` field to match the resource
// the client is accessing, and the path-suffixed well-known URL is how the
// metadata handler in the oauth2 package knows to publish `resource=<host>/mcp`.
-//
-// The configured effective external URL is preferred over request-derived
-// host/proto so that proxied deployments (where the inbound Host can differ
-// from the public endpoint) emit the correct public URL to MCP clients.
-// Request-derived values are the last-resort fallback only.
-//
-// The --external-url CLI flag (profile.ExternalURL) short-circuits the lookup;
-// otherwise on self-hosted we resolve the singleton workspace ID first so the
-// DB-backed workspace_profile.external_url setting in GetEffectiveExternalURL
-// can be found. On SaaS there is no singleton — the CLI flag is required.
-func (s *Server) buildResourceMetadataURL(c *echo.Context) string {
+func (s *Server) buildResourceMetadataURL(c *echo.Context) (string, error) {
const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp"
-
- ctx := c.Request().Context()
- if s.profile.ExternalURL != "" {
- return s.profile.ExternalURL + resourceMetadataPath
- }
- workspaceID := ""
- if !s.profile.SaaS {
- if ws, err := s.store.GetWorkspaceID(ctx); err == nil {
- workspaceID = ws
- }
- }
- if externalURL, err := utils.GetEffectiveExternalURL(ctx, s.store, s.profile, workspaceID); err == nil {
- return externalURL + resourceMetadataPath
- }
-
- req := c.Request()
- scheme := "https"
- if req.TLS == nil {
- scheme = "http"
- }
- if proto := req.Header.Get("X-Forwarded-Proto"); proto != "" {
- scheme = proto
+ externalURL, err := utils.GetDiscoveryExternalURL(c.Request().Context(), s.store, s.profile)
+ if err != nil {
+ return "", err
}
- return fmt.Sprintf("%s://%s%s", scheme, req.Host, resourceMetadataPath)
+ return externalURL + resourceMetadataPath, nil
}
diff --git a/backend/api/mcp/server_test.go b/backend/api/mcp/server_test.go
index f8262d266b..c7267c87a8 100644
--- a/backend/api/mcp/server_test.go
+++ b/backend/api/mcp/server_test.go
@@ -77,7 +77,7 @@ func TestMCPAuthMiddleware(t *testing.T) {
c := e.NewContext(req, rec)
// Create server with auth
- s, err := NewServer(nil, profile, secret, nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, secret, nil)
require.NoError(t, err)
handler := s.authMiddleware(func(c *echo.Context) error {
return c.String(http.StatusOK, "success")
@@ -122,6 +122,38 @@ func TestMCPAuthMiddleware(t *testing.T) {
}
}
+func TestNewServerRequiresStore(t *testing.T) {
+ _, err := NewServer(nil, &config.Profile{}, "test-secret", nil)
+ require.Error(t, err)
+}
+
+func TestMCPAuthFailsExplicitlyWithoutExternalURL(t *testing.T) {
+ s := &Server{
+ store: newTestServerStore(),
+ profile: &config.Profile{SaaS: true},
+ }
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodPost, "/mcp", nil)
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+
+ err := s.authMiddleware(func(*echo.Context) error { return nil })(c)
+ require.Error(t, err)
+ var httpErr *echo.HTTPError
+ require.ErrorAs(t, err, &httpErr)
+ require.Equal(t, http.StatusServiceUnavailable, httpErr.Code)
+}
+
+func TestExtractTokenIdentityRequiresWorkspace(t *testing.T) {
+ identity, errMsg := extractTokenIdentity(jwt.MapClaims{
+ "sub": "[email protected]",
+ "aud": "https://bb.example.com/mcp",
+ })
+
+ require.Nil(t, identity)
+ require.Equal(t, "invalid token: missing workspace", errMsg)
+}
+
func TestMCPAuthMiddlewareValidToken(t *testing.T) {
secret := "test-secret-key"
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
@@ -133,9 +165,8 @@ func TestMCPAuthMiddlewareValidToken(t *testing.T) {
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
- // Create server with auth - note: we pass nil store since we're testing middleware only
- // A full integration test would require a real store
- s, err := NewServer(nil, profile, secret, nil)
+ // Use a lightweight store double; production requires the real dependency.
+ s, err := newServerWithStore(newTestServerStore(), profile, secret, nil)
require.NoError(t, err)
handler := s.authMiddleware(func(c *echo.Context) error {
// Verify access token is set in request context
@@ -161,7 +192,7 @@ func TestMCPAuthMiddlewareOAuthContext(t *testing.T) {
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
- s, err := NewServer(nil, profile, secret, nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, secret, nil)
require.NoError(t, err)
handler := s.authMiddleware(func(c *echo.Context) error {
ctx := c.Request().Context()
@@ -192,7 +223,7 @@ func TestMCPProxiedPublicHostNotRejected(t *testing.T) {
secret := "test-secret-key"
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
- s, err := NewServer(nil, profile, secret, nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, secret, nil)
require.NoError(t, err)
e := echo.New()
@@ -231,7 +262,7 @@ func TestMCPUnauthenticatedRejectedEndToEnd(t *testing.T) {
secret := "test-secret-key"
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
- s, err := NewServer(nil, profile, secret, nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, secret, nil)
require.NoError(t, err)
e := echo.New()
@@ -321,7 +352,7 @@ func TestMCPAuthMiddlewareAudienceMatrix(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: tc.externalURL}
- s, err := NewServer(nil, profile, secret, nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, secret, nil)
require.NoError(t, err)
e := echo.New()
diff --git a/backend/api/mcp/store_test.go b/backend/api/mcp/store_test.go
new file mode 100644
index 0000000000..e482f35534
--- /dev/null
+++ b/backend/api/mcp/store_test.go
@@ -0,0 +1,37 @@
+package mcp
+
+import (
+ "context"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+type testServerStore struct {
+ workspaceID string
+ workspaceProfile *storepb.WorkspaceProfileSetting
+ setting *store.SettingMessage
+}
+
+func newTestServerStore() *testServerStore {
+ return &testServerStore{
+ workspaceID: "ws-test",
+ workspaceProfile: &storepb.WorkspaceProfileSetting{},
+ }
+}
+
+func (s *testServerStore) GetWorkspaceID(context.Context) (string, error) {
+ return s.workspaceID, nil
+}
+
+func (s *testServerStore) GetWorkspaceProfileSetting(context.Context, string) (*storepb.WorkspaceProfileSetting, error) {
+ return s.workspaceProfile, nil
+}
+
+func (s *testServerStore) GetSettingUncached(context.Context, string, storepb.SettingName) (*store.SettingMessage, error) {
+ return s.setting, nil
+}
+
+func (*testServerStore) DeleteOAuth2RefreshTokensByUserAndClient(context.Context, string, string) error {
+ return nil
+}
diff --git a/backend/api/mcp/tool_change.go b/backend/api/mcp/tool_change.go
index 2f66a1eb11..5b81a39eef 100644
--- a/backend/api/mcp/tool_change.go
+++ b/backend/api/mcp/tool_change.go
@@ -11,6 +11,8 @@ import (
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/utils"
)
const (
@@ -259,6 +261,7 @@ func (s *Server) handleChange(ctx context.Context, req *mcp.CallToolRequest, inp
}
// Step 10: Build response.
+ externalURL, _ := utils.GetEffectiveExternalURL(ctx, s.store, s.profile, getWorkspaceID(ctx))
output := &ChangeOutput{
Database: resolved.resourceName,
Project: project,
@@ -273,12 +276,12 @@ func (s *Server) handleChange(ctx context.Context, req *mcp.CallToolRequest, inp
RolloutDeferredReason: rolloutDeferredReason,
NextAction: nextAction,
Links: ChangeLinks{
- Issue: s.buildResourceURL(issueName),
- Plan: s.buildResourceURL(planName),
+ Issue: buildResourceURL(externalURL, issueName),
+ Plan: buildResourceURL(externalURL, planName),
},
}
if rolloutCreated {
- output.Links.Rollout = s.buildResourceURL(rolloutName)
+ output.Links.Rollout = buildResourceURL(externalURL, rolloutName)
}
text := formatChangeOutput(output, warnings)
@@ -503,12 +506,11 @@ func planChecksHaveErrors(info *PlanCheckInfo) bool {
}
// buildResourceURL constructs a URL from externalURL and resource name.
-func (s *Server) buildResourceURL(resourceName string) string {
- base := strings.TrimRight(s.profile.ExternalURL, "/")
- if base == "" {
+func buildResourceURL(externalURL, resourceName string) string {
+ if externalURL == "" {
return resourceName
}
- return base + "/" + resourceName
+ return strings.TrimSuffix(externalURL, "/") + "/" + resourceName
}
// formatChangeOutput produces a text header + JSON body.
diff --git a/backend/api/mcp/tool_change_test.go b/backend/api/mcp/tool_change_test.go
index dc65a21575..48484287e7 100644
--- a/backend/api/mcp/tool_change_test.go
+++ b/backend/api/mcp/tool_change_test.go
@@ -11,6 +11,8 @@ import (
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/stretchr/testify/require"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
// --- Change tool test infrastructure ---
@@ -1023,10 +1025,13 @@ func TestChange_Links_Constructed(t *testing.T) {
require.Equal(t, "https://bytebase.example.com/projects/hr-system/rollouts/4004", output.Links.Rollout)
}
-func TestChange_Links_TrailingSlash(t *testing.T) {
+func TestChange_Links_UseWorkspaceExternalURL(t *testing.T) {
mock := newChangeMock(employeeDB())
s := newChangeTestServer(t, mock)
- s.profile.ExternalURL = "https://bytebase.example.com/"
+ s.profile.ExternalURL = ""
+ s.store = &testServerStore{
+ workspaceProfile: &storepb.WorkspaceProfileSetting{ExternalUrl: "https://workspace.example.com"},
+ }
_, structured, err := s.handleChange(testContext(), nil, ChangeInput{
Database: "employee_db",
@@ -1037,8 +1042,7 @@ func TestChange_Links_TrailingSlash(t *testing.T) {
output, ok := structured.(*ChangeOutput)
require.True(t, ok)
- // No double slash.
- require.Equal(t, "https://bytebase.example.com/projects/hr-system/issues/3003", output.Links.Issue)
+ require.Equal(t, "https://workspace.example.com/projects/hr-system/issues/3003", output.Links.Issue)
}
func TestChange_Links_RolloutOmitted(t *testing.T) {
diff --git a/backend/api/mcp/tool_http_test.go b/backend/api/mcp/tool_http_test.go
index f2f5d64285..c29062bed0 100644
--- a/backend/api/mcp/tool_http_test.go
+++ b/backend/api/mcp/tool_http_test.go
@@ -20,6 +20,7 @@ import (
func newTestServerWithMock(t *testing.T, handler http.Handler) *Server {
t.Helper()
return &Server{
+ store: newTestServerStore(),
profile: &config.Profile{},
internalClient: newInternalAPIClient(handler),
}
diff --git a/backend/api/mcp/tool_search_test.go b/backend/api/mcp/tool_search_test.go
index e7ccb499a7..2b2c70a838 100644
--- a/backend/api/mcp/tool_search_test.go
+++ b/backend/api/mcp/tool_search_test.go
@@ -14,7 +14,7 @@ import (
func TestSearchAPIListServices(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test listing all services (no parameters)
@@ -32,7 +32,7 @@ func TestSearchAPIListServices(t *testing.T) {
func TestSearchAPIByService(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test browsing a specific service
@@ -52,7 +52,7 @@ func TestSearchAPIByService(t *testing.T) {
func TestSearchAPIByServiceNotFound(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test browsing a non-existent service
@@ -70,7 +70,7 @@ func TestSearchAPIByServiceNotFound(t *testing.T) {
func TestSearchAPIDetailMode(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test detail mode with full operationId
@@ -89,7 +89,7 @@ func TestSearchAPIDetailMode(t *testing.T) {
func TestSearchAPIDetailModeShortFormat(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test detail mode with short operationId format (Service/Method)
@@ -108,7 +108,7 @@ func TestSearchAPIDetailModeShortFormat(t *testing.T) {
func TestSearchAPIDetailModeWithResponse(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test detail mode shows response schema
@@ -125,7 +125,7 @@ func TestSearchAPIDetailModeWithResponse(t *testing.T) {
func TestSearchAPIDetailModeNotFound(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test detail mode with unknown operationId
@@ -142,7 +142,7 @@ func TestSearchAPIDetailModeNotFound(t *testing.T) {
func TestSearchAPIServiceShowsAll(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test browsing a service shows all endpoints (no limit)
@@ -161,7 +161,7 @@ func TestSearchAPIServiceShowsAll(t *testing.T) {
func TestSearchAPISchemaLookup(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test schema lookup with full name
@@ -180,7 +180,7 @@ func TestSearchAPISchemaLookup(t *testing.T) {
func TestSearchAPISchemaLookupShortName(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test schema lookup with short name
@@ -198,7 +198,7 @@ func TestSearchAPISchemaLookupShortName(t *testing.T) {
func TestSearchAPISchemaLookupNotFound(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test schema lookup with unknown name
@@ -215,7 +215,7 @@ func TestSearchAPISchemaLookupNotFound(t *testing.T) {
func TestSearchAPISchemaLookupEnum(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test enum schema lookup
@@ -232,7 +232,7 @@ func TestSearchAPISchemaLookupEnum(t *testing.T) {
func TestSearchAPIProtobufDescriptionTruncation(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test that protobuf types have short descriptions
diff --git a/backend/api/mcp/tool_skill_test.go b/backend/api/mcp/tool_skill_test.go
index 55ba5ad6bc..cfadb27fe9 100644
--- a/backend/api/mcp/tool_skill_test.go
+++ b/backend/api/mcp/tool_skill_test.go
@@ -13,7 +13,7 @@ import (
func TestGetSkillListSkills(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test listing all skills (no parameters)
@@ -30,7 +30,7 @@ func TestGetSkillListSkills(t *testing.T) {
func TestGetSkillSpecificSkill(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test getting query skill
@@ -49,7 +49,7 @@ func TestGetSkillSpecificSkill(t *testing.T) {
func TestGetSkillNotFound(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
// Test getting non-existent skill
@@ -67,7 +67,7 @@ func TestGetSkillNotFound(t *testing.T) {
func TestGetSkillAllSkillsLoadable(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
- s, err := NewServer(nil, profile, "test-secret", nil)
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
require.NoError(t, err)
skills := []string{"query", "database-change", "grant-permission"}
diff --git a/backend/api/oauth2/authorize.go b/backend/api/oauth2/authorize.go
index e495a5cad4..ba967674c2 100644
--- a/backend/api/oauth2/authorize.go
+++ b/backend/api/oauth2/authorize.go
@@ -1,7 +1,6 @@
package oauth2
import (
- "context"
"fmt"
"log/slog"
"net/http"
@@ -201,7 +200,7 @@ func (s *Service) resolveConsentingUser(c *echo.Context, client *store.OAuth2Cli
if failure != nil {
return consentingUser{}, failure
}
- workspaceID, failure := s.consentWorkspace(ctx, claims, client)
+ workspaceID, failure := s.consentWorkspace(claims, client)
if failure != nil {
return consentingUser{}, failure
}
@@ -241,25 +240,10 @@ func (s *Service) parseSessionClaims(accessToken string) (*sessionClaims, *oauth
}
// consentWorkspace resolves the workspace to bind a consent to.
-//
-// On SaaS the session always carries workspace_id; if it's missing we fail closed
-// rather than fall back to GetWorkspaceID(), which would otherwise pick an
-// arbitrary non-deleted workspace and silently bind the token there.
-func (s *Service) consentWorkspace(ctx context.Context, claims *sessionClaims, client *store.OAuth2ClientMessage) (string, *oauth2Failure) {
+func (*Service) consentWorkspace(claims *sessionClaims, client *store.OAuth2ClientMessage) (string, *oauth2Failure) {
workspaceID := claims.WorkspaceID
if workspaceID == "" {
- if s.profile.SaaS {
- return "", &oauth2Failure{code: "access_denied", description: "session is missing workspace claim"}
- }
- // Self-hosted: there's exactly one workspace.
- singleton, err := s.store.GetWorkspaceID(ctx)
- if err != nil {
- return "", &oauth2Failure{code: "server_error", description: "failed to resolve workspace"}
- }
- workspaceID = singleton
- }
- if workspaceID == "" {
- return "", &oauth2Failure{code: "access_denied", description: "no workspace in session"}
+ return "", &oauth2Failure{code: "access_denied", description: "session is missing workspace claim"}
}
// Legacy clients registered before the 3.18.2 migration are pinned to a
diff --git a/backend/api/oauth2/discovery.go b/backend/api/oauth2/discovery.go
index a27925b643..dfb8864ea5 100644
--- a/backend/api/oauth2/discovery.go
+++ b/backend/api/oauth2/discovery.go
@@ -34,47 +34,20 @@ type protectedResourceMetadata struct {
}
// getBaseURL returns the base URL to use for OAuth2 endpoints.
-// It uses externalURL from profile/setting if configured, otherwise derives from the request.
-func (s *Service) getBaseURL(c *echo.Context) string {
- ctx := c.Request().Context()
-
- // The --external-url CLI flag (profile.ExternalURL) short-circuits the
- // lookup. Otherwise on self-hosted we resolve the singleton workspace ID
- // first so GetEffectiveExternalURL can find the DB-backed
- // workspace_profile.external_url setting. On SaaS there is no singleton
- // — the CLI flag is required.
- if s.profile.ExternalURL != "" {
- return strings.TrimSuffix(s.profile.ExternalURL, "/")
- }
- workspaceID := ""
- if !s.profile.SaaS {
- if ws, err := s.store.GetWorkspaceID(ctx); err == nil {
- workspaceID = ws
- }
- }
- externalURL, err := utils.GetEffectiveExternalURL(ctx, s.store, s.profile, workspaceID)
+func (s *Service) getBaseURL(c *echo.Context) (string, error) {
+ externalURL, err := utils.GetDiscoveryExternalURL(c.Request().Context(), s.store, s.profile)
if err != nil {
- slog.Warn("failed to get external url for OAuth2", log.BBError(err))
- }
- if externalURL != "" {
- return strings.TrimSuffix(externalURL, "/")
- }
-
- // Derive from request as fallback
- req := c.Request()
- scheme := "https"
- if req.TLS == nil {
- scheme = "http"
- }
- // Check X-Forwarded-Proto header for reverse proxy setups
- if proto := req.Header.Get("X-Forwarded-Proto"); proto != "" {
- scheme = proto
+ slog.Error("failed to resolve external URL for OAuth2 discovery", log.BBError(err))
+ return "", echo.NewHTTPError(http.StatusServiceUnavailable, "OAuth2 discovery is unavailable").Wrap(err)
}
- return fmt.Sprintf("%s://%s", scheme, req.Host)
+ return externalURL, nil
}
func (s *Service) handleDiscovery(c *echo.Context) error {
- baseURL := s.getBaseURL(c)
+ baseURL, err := s.getBaseURL(c)
+ if err != nil {
+ return err
+ }
oauthBase := fmt.Sprintf("%s/api/oauth2", baseURL)
metadata := &authorizationServerMetadata{
Issuer: baseURL,
@@ -101,7 +74,10 @@ func (s *Service) handleDiscovery(c *echo.Context) error {
// The path-suffixed form lets the `/mcp` endpoint advertise metadata that
// strict clients validate against the resource URL they actually requested.
func (s *Service) handleProtectedResourceMetadata(c *echo.Context) error {
- baseURL := s.getBaseURL(c)
+ baseURL, err := s.getBaseURL(c)
+ if err != nil {
+ return err
+ }
const wellKnownPrefix = "/.well-known/oauth-protected-resource"
resource := baseURL
diff --git a/backend/api/oauth2/discovery_test.go b/backend/api/oauth2/discovery_test.go
index debb001145..300dee99ac 100644
--- a/backend/api/oauth2/discovery_test.go
+++ b/backend/api/oauth2/discovery_test.go
@@ -103,3 +103,18 @@ func TestDiscoveryOmitsScopesSupported(t *testing.T) {
require.NotContains(t, rec.Body.String(), "mcp:read",
"no scope token may leak into discovery through any other field")
}
+
+func TestDiscoveryFailsWithoutExternalURL(t *testing.T) {
+ s := &Service{profile: &config.Profile{SaaS: true}}
+
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodGet, "/.well-known/oauth-authorization-server", nil)
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+
+ err := s.handleDiscovery(c)
+ require.Error(t, err)
+ var httpErr *echo.HTTPError
+ require.ErrorAs(t, err, &httpErr)
+ require.Equal(t, http.StatusServiceUnavailable, httpErr.Code)
+}
diff --git a/backend/api/oauth2/grant_test.go b/backend/api/oauth2/grant_test.go
index a780ca7a6d..75a19ef8c9 100644
--- a/backend/api/oauth2/grant_test.go
+++ b/backend/api/oauth2/grant_test.go
@@ -41,6 +41,15 @@ const (
testResource = "https://bb.example.com/mcp"
)
+func TestConsentWorkspaceRequiresSessionClaim(t *testing.T) {
+ s := &Service{profile: &config.Profile{}}
+
+ workspaceID, failure := s.consentWorkspace(&sessionClaims{}, &store.OAuth2ClientMessage{})
+
+ require.Empty(t, workspaceID)
+ require.Equal(t, &oauth2Failure{code: "access_denied", description: "session is missing workspace claim"}, failure)
+}
+
// TestResourceScopeGrantLifecycle drives the whole consent → token → refresh
// path against a real store. The pure rule space lives in resource_test.go;
// what this pins is the wiring, which is where a resource/scope binding
diff --git a/backend/api/oauth2/oauth2.go b/backend/api/oauth2/oauth2.go
index 389d941f17..6ed9e03789 100644
--- a/backend/api/oauth2/oauth2.go
+++ b/backend/api/oauth2/oauth2.go
@@ -26,7 +26,6 @@ import (
const (
clientIDPrefix = "bb_oauth_"
- clientSecretPrefix = "bb_secret_"
refreshTokenPrefix = "bb_refresh_"
authCodePrefix = "bb_code_"
@@ -121,14 +120,6 @@ func generateClientID() (string, error) {
return clientIDPrefix + base64.RawURLEncoding.EncodeToString(bytes), nil
}
-func generateClientSecret() (string, error) {
- token, err := auth.GenerateOpaqueToken()
- if err != nil {
- return "", err
- }
- return clientSecretPrefix + token, nil
-}
-
func generateAuthCode() (string, error) {
token, err := auth.GenerateOpaqueToken()
if err != nil {
@@ -145,14 +136,6 @@ func generateRefreshToken() (string, error) {
return refreshTokenPrefix + token, nil
}
-func hashSecret(secret string) (string, error) {
- hash, err := bcrypt.GenerateFromPassword([]byte(secret), bcrypt.DefaultCost)
- if err != nil {
- return "", err
- }
- return string(hash), nil
-}
-
func verifySecret(hash, secret string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(secret)) == nil
}
diff --git a/backend/api/oauth2/register.go b/backend/api/oauth2/register.go
index ade719d02e..ae5e27621f 100644
--- a/backend/api/oauth2/register.go
+++ b/backend/api/oauth2/register.go
@@ -13,8 +13,8 @@ import (
// Bounds on Dynamic Client Registration input. These are loose enough that no
// realistic MCP client trips them, but tight enough that degenerate input
// (megabyte-sized client_name fields, hundreds of redirect URIs) is rejected
-// before any DB or bcrypt work happens — the endpoint is unauthenticated and
-// publicly reachable on SaaS.
+// before any DB work happens — the endpoint is unauthenticated and publicly
+// reachable on SaaS.
const (
maxClientNameLen = 200
maxRedirectURIs = 5
@@ -30,7 +30,6 @@ type clientRegistrationRequest struct {
type clientRegistrationResponse struct {
ClientID string `json:"client_id"`
- ClientSecret string `json:"client_secret,omitempty"`
ClientName string `json:"client_name"`
RedirectURIs []string `json:"redirect_uris"`
GrantTypes []string `json:"grant_types"`
@@ -84,8 +83,7 @@ func (s *Service) handleRegister(c *echo.Context) error {
if req.TokenEndpointAuthMethod == "" {
req.TokenEndpointAuthMethod = "none"
}
- allowedAuthMethods := []string{"none"}
- if !slices.Contains(allowedAuthMethods, req.TokenEndpointAuthMethod) {
+ if req.TokenEndpointAuthMethod != "none" {
return oauth2Error(c, http.StatusBadRequest, "invalid_client_metadata", "unsupported token_endpoint_auth_method")
}
@@ -94,22 +92,6 @@ func (s *Service) handleRegister(c *echo.Context) error {
return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to generate client ID")
}
- // Public clients (token_endpoint_auth_method=none) do not authenticate
- // at the token endpoint and never receive a usable secret, so skip the
- // (expensive) bcrypt round entirely. The token.go grant path already
- // gates secret verification on Config.TokenEndpointAuthMethod != "none".
- var clientSecret, secretHash string
- if req.TokenEndpointAuthMethod != "none" {
- clientSecret, err = generateClientSecret()
- if err != nil {
- return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to generate client secret")
- }
- secretHash, err = hashSecret(clientSecret)
- if err != nil {
- return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to hash client secret")
- }
- }
-
config := &storepb.OAuth2ClientConfig{
ClientName: req.ClientName,
RedirectUris: req.RedirectURIs,
@@ -117,23 +99,17 @@ func (s *Service) handleRegister(c *echo.Context) error {
TokenEndpointAuthMethod: req.TokenEndpointAuthMethod,
}
if _, err := s.store.CreateOAuth2Client(ctx, &store.OAuth2ClientMessage{
- ClientID: clientID,
- ClientSecretHash: secretHash,
- Config: config,
+ ClientID: clientID,
+ Config: config,
}); err != nil {
return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to create client")
}
- resp := &clientRegistrationResponse{
+ return c.JSON(http.StatusCreated, &clientRegistrationResponse{
ClientID: clientID,
ClientName: req.ClientName,
RedirectURIs: req.RedirectURIs,
GrantTypes: req.GrantTypes,
TokenEndpointAuthMethod: req.TokenEndpointAuthMethod,
- }
- // Only include client_secret for confidential clients.
- if req.TokenEndpointAuthMethod != "none" {
- resp.ClientSecret = clientSecret
- }
- return c.JSON(http.StatusCreated, resp)
+ })
}
diff --git a/backend/api/oauth2/register_test.go b/backend/api/oauth2/register_test.go
index d416d26889..6dc1b6ceab 100644
--- a/backend/api/oauth2/register_test.go
+++ b/backend/api/oauth2/register_test.go
@@ -1,6 +1,7 @@
package oauth2
import (
+ "encoding/json"
"net/http"
"net/http/httptest"
"strings"
@@ -12,6 +13,26 @@ import (
"github.com/bytebase/bytebase/backend/component/config"
)
+func TestRegisterRejectsConfidentialClient(t *testing.T) {
+ s := &Service{profile: &config.Profile{ExternalURL: "https://bb.example.com"}}
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodPost, "/api/oauth2/register", strings.NewReader(`{
+ "client_name":"test client",
+ "redirect_uris":["http://localhost/callback"],
+ "grant_types":["authorization_code"],
+ "token_endpoint_auth_method":"client_secret_basic"
+ }`))
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+
+ require.NoError(t, s.handleRegister(c))
+ require.Equal(t, http.StatusBadRequest, rec.Code)
+ var body map[string]string
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
+ require.Equal(t, "invalid_client_metadata", body["error"])
+}
+
// TestRegisterBodyLimit verifies that oversized request bodies are rejected
// before JSON binding. Echo's default JSON deserializer buffers the whole
// body in memory and /register is unauthenticated, so the route-level
diff --git a/backend/api/oauth2/revoke.go b/backend/api/oauth2/revoke.go
index c6bff11ee7..2d534521bb 100644
--- a/backend/api/oauth2/revoke.go
+++ b/backend/api/oauth2/revoke.go
@@ -41,8 +41,8 @@ func (s *Service) handleRevoke(c *echo.Context) error {
return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "client not found")
}
- // Verify client credentials based on token_endpoint_auth_method
- // Public clients (token_endpoint_auth_method: none) don't have secrets
+ // Dynamic registration creates only public clients. Keep secret verification
+ // for confidential clients registered before that restriction.
if client.Config.TokenEndpointAuthMethod != "none" {
if !verifySecret(client.ClientSecretHash, clientSecret) {
return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "invalid client credentials")
diff --git a/backend/api/oauth2/token.go b/backend/api/oauth2/token.go
index ca8b176d19..09bab32b41 100644
--- a/backend/api/oauth2/token.go
+++ b/backend/api/oauth2/token.go
@@ -78,8 +78,8 @@ func (s *Service) handleToken(c *echo.Context) error {
return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "client not found")
}
- // Verify client credentials based on token_endpoint_auth_method
- // Public clients (token_endpoint_auth_method: none) don't have secrets
+ // Dynamic registration creates only public clients. Keep secret verification
+ // for confidential clients registered before that restriction.
if client.Config.TokenEndpointAuthMethod != "none" {
if !verifySecret(client.ClientSecretHash, clientSecret) {
return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "invalid client credentials")
@@ -147,9 +147,8 @@ func (s *Service) handleAuthorizationCodeGrant(c *echo.Context, client *store.OA
return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "user not found")
}
- // Resolve the workspace bound at consent time. Auth codes created before
- // the 3.18.2 migration may have an empty workspace; fall back to the
- // client's legacy workspace, then to the singleton workspace.
+ // Auth codes created before migration 3.18/0002 have no issued workspace,
+ // but their legacy OAuth client workspace was backfilled by 3.17/0009.
workspaceID, err := s.resolveBoundWorkspace(ctx, authCode.Workspace, client.Workspace, user.Email)
if err != nil {
return workspaceResolutionError(c, err)
@@ -280,8 +279,8 @@ func (s *Service) handleRefreshTokenGrant(c *echo.Context, client *store.OAuth2C
return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "user not found")
}
- // Preserve the workspace binding from the refresh token. Fall back paths
- // mirror the auth-code grant for pre-migration tokens. Membership is
+ // Preserve the workspace binding from the refresh token. Legacy tokens fall
+ // back to their client's backfilled workspace. Membership is
// re-checked on every refresh so a user removed from the workspace
// after consent loses access at most one access-token lifetime later
// rather than waiting out the refresh token's 30-day expiry.
@@ -349,10 +348,13 @@ func (s *Service) validateRefreshTokenGrant(ctx context.Context, client *store.O
}
// 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
+// onto RFC 6749 OAuth2 error responses. Invalid grant state and membership
+// failure are invalid_grant (400); infrastructure failures are server_error
// (500) with the wrapped detail logged server-side, not leaked to the client.
func workspaceResolutionError(c *echo.Context, err error) error {
+ if errors.Is(err, errWorkspaceNotBound) {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "grant is not bound to a workspace; re-authorize")
+ }
if errors.Is(err, errWorkspaceNotMember) {
return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "user is no longer a member of the workspace")
}
@@ -362,25 +364,28 @@ func workspaceResolutionError(c *echo.Context, err error) error {
// errWorkspaceNotMember signals that the user has been removed from the
// workspace their OAuth grant was issued for. Mapped to RFC 6749 `invalid_grant`
-// at the call site. All other errors from resolveBoundWorkspace are internal
-// failures that should produce 500/server_error instead.
+// at the call site.
var errWorkspaceNotMember = errors.New("user is no longer a member of the consented workspace")
+// errWorkspaceNotBound signals an invalid grant with neither a consent-time
+// workspace nor the backfilled workspace on its legacy OAuth client.
+var errWorkspaceNotBound = errors.New("no workspace bound to this grant")
+
// workspaceResolver is the slice of store methods resolveBoundWorkspace needs.
// Defining it as an interface keeps the helper independently unit-testable.
type workspaceResolver interface {
- GetWorkspaceID(ctx context.Context) (string, error)
FindWorkspace(ctx context.Context, find *store.FindWorkspaceMessage) (*store.WorkspaceMessage, error)
}
// resolveBoundWorkspace returns the workspace the issued token should bind to,
-// applying the legacy fallback chain (issued.Workspace → client.Workspace →
-// singleton) and then verifying current IAM membership before returning. The
-// membership check is the defense-in-depth guard against issuing a usable
-// token to a user who has been removed from the workspace since consent.
+// falling back to the legacy OAuth client workspace when the grant predates
+// migration 3.18/0002. Migration 3.17/0009 backfilled that client workspace and
+// kept it non-null, so a grant with neither binding is invalid. The membership
+// check is the defense-in-depth guard against issuing a usable token to a user
+// who has been removed from the workspace since consent.
//
-// On SaaS only: returns errWorkspaceNotMember if the user is not currently a
-// member of the resolved workspace. All other errors are internal failures.
+// On SaaS only, it returns errWorkspaceNotMember when the user is no longer a
+// member of the resolved workspace; membership lookup failures remain internal.
func (s *Service) resolveBoundWorkspace(ctx context.Context, issuedWorkspace, clientWorkspace, userEmail string) (string, error) {
return resolveBoundWorkspace(ctx, s.store, s.profile.SaaS, issuedWorkspace, clientWorkspace, userEmail)
}
@@ -391,14 +396,7 @@ func resolveBoundWorkspace(ctx context.Context, resolver workspaceResolver, saas
workspaceID = clientWorkspace
}
if workspaceID == "" {
- singleton, err := resolver.GetWorkspaceID(ctx)
- if err != nil {
- return "", errors.Wrap(err, "failed to resolve workspace")
- }
- workspaceID = singleton
- }
- if workspaceID == "" {
- return "", errors.New("no workspace bound to this grant")
+ return "", errWorkspaceNotBound
}
// Self-hosted: every user belongs to the singleton workspace implicitly,
diff --git a/backend/api/oauth2/token_test.go b/backend/api/oauth2/token_test.go
index ec83f2b2aa..95b74ca6d6 100644
--- a/backend/api/oauth2/token_test.go
+++ b/backend/api/oauth2/token_test.go
@@ -2,12 +2,15 @@ package oauth2
import (
"context"
+ "encoding/json"
"errors"
+ "net/http"
+ "net/http/httptest"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
- pkgerrors "github.com/pkg/errors"
+ "github.com/labstack/echo/v5"
"github.com/stretchr/testify/require"
"github.com/bytebase/bytebase/backend/api/auth"
@@ -17,18 +20,12 @@ import (
// fakeWorkspaceResolver implements workspaceResolver for unit tests so we can
// exercise resolveBoundWorkspace without standing up a real Postgres store.
type fakeWorkspaceResolver struct {
- singleton string
- singletonErr error
findResult *store.WorkspaceMessage
findErr error
findCallCount int
lastFind *store.FindWorkspaceMessage
}
-func (r *fakeWorkspaceResolver) GetWorkspaceID(_ context.Context) (string, error) {
- return r.singleton, r.singletonErr
-}
-
func (r *fakeWorkspaceResolver) FindWorkspace(_ context.Context, find *store.FindWorkspaceMessage) (*store.WorkspaceMessage, error) {
r.findCallCount++
r.lastFind = find
@@ -46,26 +43,18 @@ func TestResolveBoundWorkspace(t *testing.T) {
require.Zero(t, r.findCallCount, "self-hosted must not call FindWorkspace")
})
- t.Run("self-hosted falls back to singleton when both issued and client workspace are empty", func(t *testing.T) {
- r := &fakeWorkspaceResolver{singleton: "ws-singleton"}
- got, err := resolveBoundWorkspace(ctx, r, false, "", "", "[email protected]")
- require.NoError(t, err)
- require.Equal(t, "ws-singleton", got)
+ t.Run("returns invalid grant when neither issued nor client workspace is bound", func(t *testing.T) {
+ r := &fakeWorkspaceResolver{}
+ _, err := resolveBoundWorkspace(ctx, r, false, "", "", "[email protected]")
+ require.ErrorIs(t, err, errWorkspaceNotBound)
+ require.Zero(t, r.findCallCount)
})
- t.Run("falls back from issued to client workspace before singleton", func(t *testing.T) {
- r := &fakeWorkspaceResolver{singleton: "ws-singleton"}
+ t.Run("falls back from issued to legacy client workspace", func(t *testing.T) {
+ r := &fakeWorkspaceResolver{}
got, err := resolveBoundWorkspace(ctx, r, false, "", "ws-client", "[email protected]")
require.NoError(t, err)
- require.Equal(t, "ws-client", got, "client workspace should win over singleton fallback")
- })
-
- t.Run("returns error when no workspace is resolvable", func(t *testing.T) {
- r := &fakeWorkspaceResolver{singleton: ""}
- _, err := resolveBoundWorkspace(ctx, r, false, "", "", "[email protected]")
- require.Error(t, err)
- require.Contains(t, err.Error(), "no workspace bound")
- require.NotErrorIs(t, err, errWorkspaceNotMember, "missing workspace is not a membership failure")
+ require.Equal(t, "ws-client", got)
})
t.Run("SaaS member returns workspace", func(t *testing.T) {
@@ -94,14 +83,18 @@ func TestResolveBoundWorkspace(t *testing.T) {
require.NotErrorIs(t, err, errWorkspaceNotMember,
"internal errors must not be misclassified as membership failure (would 400 instead of 500)")
})
+}
- t.Run("SaaS singleton-lookup error is wrapped and not membership failure", func(t *testing.T) {
- r := &fakeWorkspaceResolver{singletonErr: pkgerrors.New("db down")}
- _, err := resolveBoundWorkspace(ctx, r, true, "", "", "[email protected]")
- require.Error(t, err)
- require.NotErrorIs(t, err, errWorkspaceNotMember)
- require.Contains(t, err.Error(), "failed to resolve workspace")
- })
+func TestWorkspaceResolutionErrorForUnboundGrant(t *testing.T) {
+ e := echo.New()
+ rec := httptest.NewRecorder()
+ c := e.NewContext(httptest.NewRequest(http.MethodPost, "/api/oauth2/token", nil), rec)
+
+ require.NoError(t, workspaceResolutionError(c, errWorkspaceNotBound))
+ require.Equal(t, http.StatusBadRequest, rec.Code)
+ var body map[string]string
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
+ require.Equal(t, "invalid_grant", body["error"])
}
// TestIssueTokensPlacesWorkspaceInJWT verifies the in-memory propagation of
diff --git a/backend/utils/setting.go b/backend/utils/setting.go
index 395002f5b7..b48c0888b8 100644
--- a/backend/utils/setting.go
+++ b/backend/utils/setting.go
@@ -7,14 +7,23 @@ import (
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/component/config"
- "github.com/bytebase/bytebase/backend/store"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
const setupExternalURLError = "external URL isn't setup yet, see https://docs.bytebase.com/get-started/self-host/external-url"
+type externalURLStore interface {
+ GetWorkspaceProfileSetting(context.Context, string) (*storepb.WorkspaceProfileSetting, error)
+}
+
+type discoveryExternalURLStore interface {
+ externalURLStore
+ GetWorkspaceID(context.Context) (string, error)
+}
+
// GetEffectiveExternalURL returns the external URL to use, preferring the command-line flag over the database setting.
// This ensures that when the --external-url flag is set, it takes precedence over any value stored in the database.
-func GetEffectiveExternalURL(ctx context.Context, stores *store.Store, profile *config.Profile, workspaceID string) (string, error) {
+func GetEffectiveExternalURL(ctx context.Context, stores externalURLStore, profile *config.Profile, workspaceID string) (string, error) {
// Use command-line flag value if set, otherwise use database value
externalURL := profile.ExternalURL
if externalURL == "" {
@@ -30,3 +39,26 @@ func GetEffectiveExternalURL(ctx context.Context, stores *store.Store, profile *
}
return externalURL, nil
}
+
+// GetDiscoveryExternalURL resolves the configured external URL for
+// workspace-agnostic discovery endpoints.
+func GetDiscoveryExternalURL(ctx context.Context, stores discoveryExternalURLStore, profile *config.Profile) (string, error) {
+ if profile.ExternalURL != "" {
+ return profile.ExternalURL, nil
+ }
+
+ // A self-hosted deployment has one workspace, so its DB-backed external URL
+ // can be resolved without authentication. SaaS cannot choose a workspace
+ // safely here because discovery requests are unauthenticated.
+ if profile.SaaS {
+ return "", connect.NewError(connect.CodeFailedPrecondition, errors.Errorf(setupExternalURLError))
+ }
+ workspaceID, err := stores.GetWorkspaceID(ctx)
+ if err != nil {
+ return "", connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get workspace"))
+ }
+ if workspaceID == "" {
+ return "", connect.NewError(connect.CodeFailedPrecondition, errors.Errorf(setupExternalURLError))
+ }
+ return GetEffectiveExternalURL(ctx, stores, profile, workspaceID)
+}
diff --git a/backend/utils/setting_test.go b/backend/utils/setting_test.go
new file mode 100644
index 0000000000..eadf155041
--- /dev/null
+++ b/backend/utils/setting_test.go
@@ -0,0 +1,65 @@
+package utils
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/component/config"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+type testDiscoveryExternalURLStore struct {
+ workspaceID string
+ workspaceIDErr error
+ workspaceProfile *storepb.WorkspaceProfileSetting
+}
+
+func (s *testDiscoveryExternalURLStore) GetWorkspaceID(context.Context) (string, error) {
+ return s.workspaceID, s.workspaceIDErr
+}
+
+func (s *testDiscoveryExternalURLStore) GetWorkspaceProfileSetting(context.Context, string) (*storepb.WorkspaceProfileSetting, error) {
+ return s.workspaceProfile, nil
+}
+
+func TestGetDiscoveryExternalURLRequiresConfiguredURL(t *testing.T) {
+ externalURL, err := GetDiscoveryExternalURL(
+ context.Background(),
+ &testDiscoveryExternalURLStore{},
+ &config.Profile{SaaS: true},
+ )
+
+ require.Empty(t, externalURL)
+ require.Error(t, err)
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
+}
+
+func TestGetDiscoveryExternalURLPropagatesWorkspaceLookupError(t *testing.T) {
+ externalURL, err := GetDiscoveryExternalURL(
+ context.Background(),
+ &testDiscoveryExternalURLStore{workspaceIDErr: errors.New("database unavailable")},
+ &config.Profile{},
+ )
+
+ require.Empty(t, externalURL)
+ require.Error(t, err)
+ require.Equal(t, connect.CodeInternal, connect.CodeOf(err))
+}
+
+func TestGetDiscoveryExternalURLUsesWorkspaceSetting(t *testing.T) {
+ externalURL, err := GetDiscoveryExternalURL(
+ context.Background(),
+ &testDiscoveryExternalURLStore{
+ workspaceID: "ws-test",
+ workspaceProfile: &storepb.WorkspaceProfileSetting{ExternalUrl: "https://workspace.example.com"},
+ },
+ &config.Profile{},
+ )
+
+ require.NoError(t, err)
+ require.Equal(t, "https://workspace.example.com", externalURL)
+}