Skip to content

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

fix(oauth2): bind workspace to token at consent time for SaaS MCP (#20360)

Danny Xud8fa9ea56cd9
diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.go
index 5ab90e88f6..34901b1a12 100644
--- a/backend/api/mcp/server.go
+++ b/backend/api/mcp/server.go
@@ -2,6 +2,7 @@
package mcp
import (
+ "fmt"
"net/http"
"strings"
"time"
@@ -14,6 +15,7 @@ import (
"github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/component/config"
"github.com/bytebase/bytebase/backend/store"
+ "github.com/bytebase/bytebase/backend/utils"
)
// Server is the MCP server for Bytebase.
@@ -71,18 +73,23 @@ func (s *Server) registerTools() {
}
// authMiddleware validates OAuth2 bearer tokens for MCP requests.
+//
+// On 401, it emits an RFC 9728 / MCP-authorization-spec compliant
+// WWW-Authenticate header pointing at the protected-resource-metadata URL.
+// MCP clients (Claude Code, Cursor, etc.) use this header to bootstrap the
+// OAuth flow without out-of-band configuration.
func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
// Extract Authorization header
authHeader := c.Request().Header.Get("Authorization")
if authHeader == "" {
- return echo.NewHTTPError(http.StatusUnauthorized, "authorization required")
+ return s.unauthorized(c, "authorization required")
}
// Validate Bearer format
parts := strings.Fields(authHeader)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
- return echo.NewHTTPError(http.StatusUnauthorized, "authorization header format must be Bearer {token}")
+ return s.unauthorized(c, "authorization header format must be Bearer {token}")
}
tokenStr := parts[1]
@@ -90,28 +97,28 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
claims := jwt.MapClaims{}
token, err := jwt.ParseWithClaims(tokenStr, claims, func(t *jwt.Token) (any, error) {
if t.Method.Alg() != jwt.SigningMethodHS256.Name {
- return nil, echo.NewHTTPError(http.StatusUnauthorized, "invalid token signing method")
+ return nil, errors.New("invalid token signing method")
}
if kid, ok := t.Header["kid"].(string); ok && kid == "v1" {
return []byte(s.secret), nil
}
- return nil, echo.NewHTTPError(http.StatusUnauthorized, "invalid token key id")
+ return nil, errors.New("invalid token key id")
})
if err != nil {
if strings.Contains(err.Error(), "expired") {
- return echo.NewHTTPError(http.StatusUnauthorized, "token expired")
+ return s.unauthorized(c, "token expired")
}
- return echo.NewHTTPError(http.StatusUnauthorized, "invalid token")
+ return s.unauthorized(c, "invalid token")
}
if !token.Valid {
- return echo.NewHTTPError(http.StatusUnauthorized, "invalid token")
+ return s.unauthorized(c, "invalid token")
}
// Validate audience - accept both user access tokens and OAuth2 access tokens
aud, ok := claims["aud"]
if !ok {
- return echo.NewHTTPError(http.StatusUnauthorized, "invalid token: missing audience")
+ return s.unauthorized(c, "invalid token: missing audience")
}
validAudience := false
@@ -128,13 +135,13 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
default:
}
if !validAudience {
- return echo.NewHTTPError(http.StatusUnauthorized, "invalid token: audience mismatch")
+ return s.unauthorized(c, "invalid token: audience mismatch")
}
// Extract user email from subject
sub, ok := claims["sub"].(string)
if !ok || sub == "" {
- return echo.NewHTTPError(http.StatusUnauthorized, "invalid token: missing subject")
+ return s.unauthorized(c, "invalid token: missing subject")
}
// Extract workspace ID from token claims.
@@ -158,3 +165,62 @@ func (s *Server) RegisterRoutes(e *echo.Echo) {
// MCP Streamable HTTP endpoint with authentication
e.Any("/mcp", echo.WrapHandler(s.httpHandler), s.authMiddleware)
}
+
+// unauthorized writes a 401 with an RFC 9728 / MCP-authorization-spec
+// WWW-Authenticate header so compliant MCP clients can auto-discover the
+// 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)
+ c.Response().Header().Set(
+ "WWW-Authenticate",
+ fmt.Sprintf(
+ `Bearer realm="OAuth", resource_metadata=%q, error="invalid_token", error_description=%q`,
+ resourceMetadataURL, errDescription,
+ ),
+ )
+ return echo.NewHTTPError(http.StatusUnauthorized, errDescription)
+}
+
+// buildResourceMetadataURL returns the absolute URL of the protected resource
+// metadata document for the /mcp endpoint. The `/mcp` path suffix matters:
+// 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 {
+ const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp"
+
+ ctx := c.Request().Context()
+ if s.profile.ExternalURL != "" {
+ return strings.TrimSuffix(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 && externalURL != "" {
+ return strings.TrimSuffix(externalURL, "/") + resourceMetadataPath
+ }
+
+ req := c.Request()
+ scheme := "https"
+ if req.TLS == nil {
+ scheme = "http"
+ }
+ if proto := req.Header.Get("X-Forwarded-Proto"); proto != "" {
+ scheme = proto
+ }
+ return fmt.Sprintf("%s://%s%s", scheme, req.Host, resourceMetadataPath)
+}
diff --git a/backend/api/mcp/server_test.go b/backend/api/mcp/server_test.go
index 3f9ef20627..047cb864b2 100644
--- a/backend/api/mcp/server_test.go
+++ b/backend/api/mcp/server_test.go
@@ -18,7 +18,10 @@ import (
func TestMCPAuthMiddleware(t *testing.T) {
secret := "test-secret-key"
- profile := &config.Profile{Mode: common.ReleaseModeDev}
+ // 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.
+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
tests := []struct {
name string
@@ -84,6 +87,22 @@ func TestMCPAuthMiddleware(t *testing.T) {
require.Equal(t, tc.expectedStatus, rec.Code)
require.Contains(t, strings.ToLower(rec.Body.String()), strings.ToLower(tc.expectedBody))
+
+ // Every 401 must carry an RFC 9728 / MCP-authorization-spec
+ // WWW-Authenticate header so unauthenticated clients can
+ // auto-discover the authorization server.
+ wwwAuth := rec.Header().Get("WWW-Authenticate")
+ require.NotEmpty(t, wwwAuth, "401 response missing WWW-Authenticate header")
+ require.Contains(t, wwwAuth, "Bearer")
+ require.Contains(t, wwwAuth, `realm="OAuth"`)
+ require.Contains(t, wwwAuth, "resource_metadata=")
+ require.Contains(t, wwwAuth, `error="invalid_token"`)
+ // The resource_metadata URL must (a) use the configured external
+ // URL rather than the inbound request Host (proxied-deployment
+ // phishing-pivot fix) and (b) include the /mcp path suffix so
+ // RFC 9728 §3.3 strict clients receive metadata whose `resource`
+ // field matches the URL they were accessing.
+ require.Contains(t, wwwAuth, "https://bb.example.com/.well-known/oauth-protected-resource/mcp")
})
}
}
diff --git a/backend/api/oauth2/authorize.go b/backend/api/oauth2/authorize.go
index c8a3520207..f80a952f84 100644
--- a/backend/api/oauth2/authorize.go
+++ b/backend/api/oauth2/authorize.go
@@ -18,6 +18,15 @@ import (
"github.com/bytebase/bytebase/backend/store"
)
+// sessionClaims is the subset of session JWT claims we need at the OAuth2
+// authorize step. workspace_id carries the workspace the user is currently
+// acting in; that workspace becomes the one bound to the issued authorization
+// code (and ultimately the OAuth2 access token).
+type sessionClaims struct {
+ jwt.RegisteredClaims
+ WorkspaceID string `json:"workspace_id,omitempty"`
+}
+
func (s *Service) handleAuthorizeGet(c *echo.Context) error {
ctx := c.Request().Context()
@@ -29,21 +38,15 @@ func (s *Service) handleAuthorizeGet(c *echo.Context) error {
codeChallenge := c.QueryParam("code_challenge")
codeChallengeMethod := c.QueryParam("code_challenge_method")
- // Validate response_type
if responseType != "code" {
return oauth2Error(c, http.StatusBadRequest, "unsupported_response_type", "only 'code' response type is supported")
}
- // Validate client_id
if clientID == "" {
return oauth2Error(c, http.StatusBadRequest, "invalid_request", "client_id is required")
}
- workspaceID, err := s.getWorkspaceFromRequest(c)
- if err != nil {
- return oauth2Error(c, http.StatusBadRequest, "invalid_request", "workspace is required")
- }
- client, err := s.store.GetOAuth2Client(ctx, workspaceID, clientID)
+ client, err := s.store.GetOAuth2Client(ctx, clientID)
if err != nil {
return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup client")
}
@@ -51,7 +54,6 @@ func (s *Service) handleAuthorizeGet(c *echo.Context) error {
return oauth2Error(c, http.StatusBadRequest, "invalid_client", "client not found")
}
- // Validate redirect_uri
if redirectURI == "" {
return oauth2Error(c, http.StatusBadRequest, "invalid_request", "redirect_uri is required")
}
@@ -59,7 +61,7 @@ func (s *Service) handleAuthorizeGet(c *echo.Context) error {
return oauth2Error(c, http.StatusBadRequest, "invalid_redirect_uri", "redirect_uri not registered")
}
- // Validate PKCE (required)
+ // PKCE is required
if codeChallenge == "" {
return oauth2ErrorRedirect(c, redirectURI, state, "invalid_request", "code_challenge is required")
}
@@ -67,8 +69,9 @@ func (s *Service) handleAuthorizeGet(c *echo.Context) error {
return oauth2ErrorRedirect(c, redirectURI, state, "invalid_request", "code_challenge_method must be S256")
}
- // Redirect to frontend consent page
- // The frontend will handle login if needed and display consent UI
+ // Redirect to frontend consent page.
+ // The frontend handles login if needed and binds consent to the user's
+ // currently active workspace (see handleAuthorizePost).
consentURL := fmt.Sprintf("/oauth2/consent?client_id=%s&redirect_uri=%s&state=%s&code_challenge=%s&code_challenge_method=%s",
url.QueryEscape(clientID),
url.QueryEscape(redirectURI),
@@ -82,7 +85,6 @@ func (s *Service) handleAuthorizeGet(c *echo.Context) error {
func (s *Service) handleAuthorizePost(c *echo.Context) error {
ctx := c.Request().Context()
- // Parse form values
clientID := c.FormValue("client_id")
redirectURI := c.FormValue("redirect_uri")
state := c.FormValue("state")
@@ -90,23 +92,15 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
codeChallengeMethod := c.FormValue("code_challenge_method")
action := c.FormValue("action")
- workspaceID, err := s.getWorkspaceFromRequest(c)
- if err != nil {
- return oauth2Error(c, http.StatusBadRequest, "invalid_request", "workspace is required")
- }
-
- // Validate client
- client, err := s.store.GetOAuth2Client(ctx, workspaceID, clientID)
+ client, err := s.store.GetOAuth2Client(ctx, clientID)
if err != nil || client == nil {
return oauth2Error(c, http.StatusBadRequest, "invalid_client", "client not found")
}
- // Validate redirect_uri
if !validateRedirectURI(redirectURI, client.Config.RedirectUris) {
return oauth2Error(c, http.StatusBadRequest, "invalid_redirect_uri", "redirect_uri not registered")
}
- // Handle denial
if action == "deny" {
return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "user denied the request")
}
@@ -120,8 +114,10 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "user not authenticated")
}
- // Validate the access token and extract user email
- claims := &jwt.RegisteredClaims{}
+ // Parse the session token to get the user and their active workspace.
+ // The workspace_id claim is the workspace the user is currently in;
+ // that's the workspace OAuth consent is granted for.
+ claims := &sessionClaims{}
_, err = jwt.ParseWithClaims(accessToken, claims, func(t *jwt.Token) (any, error) {
if t.Method.Alg() != jwt.SigningMethodHS256.Name {
return nil, errors.Errorf("unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)
@@ -137,11 +133,39 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "invalid session")
}
- // Validate audience
if !audienceContains(claims.Audience, auth.AccessTokenAudience) {
return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "invalid token audience")
}
+ // Resolve the workspace to bind this 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.
+ workspaceID := claims.WorkspaceID
+ if workspaceID == "" {
+ if s.profile.SaaS {
+ return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "session is missing workspace claim")
+ }
+ // Self-hosted: there's exactly one workspace.
+ workspaceID, err = s.store.GetWorkspaceID(ctx)
+ if err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to resolve workspace")
+ }
+ }
+ if workspaceID == "" {
+ return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "no workspace in session")
+ }
+
+ // Legacy clients registered before the 3.18.2 migration are pinned to a
+ // workspace via oauth2_client.workspace. Refuse to mint a token for a
+ // different workspace via that client — the user is in a workspace it
+ // wasn't authorized for. Post-migration clients have client.Workspace
+ // empty (workspace-agnostic) and bind freely.
+ if client.Workspace != "" && client.Workspace != workspaceID {
+ return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "client is registered to a different workspace; switch workspaces and try again")
+ }
+
user, err := s.store.GetUserByEmail(ctx, claims.Subject)
if err != nil {
return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "failed to find user")
@@ -150,13 +174,11 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "user not found")
}
- // Generate authorization code
code, err := generateAuthCode()
if err != nil {
return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to generate code")
}
- // Store authorization code
codeConfig := &storepb.OAuth2AuthorizationCodeConfig{
RedirectUri: redirectURI,
CodeChallenge: codeChallenge,
@@ -166,18 +188,17 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
Code: code,
ClientID: clientID,
UserEmail: user.Email,
+ Workspace: workspaceID,
Config: codeConfig,
ExpiresAt: time.Now().Add(authCodeExpiry),
}); err != nil {
return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to store code")
}
- // Update client last active
- if err := s.store.UpdateOAuth2ClientLastActiveAt(ctx, client.Workspace, clientID); err != nil {
+ if err := s.store.UpdateOAuth2ClientLastActiveAt(ctx, clientID); err != nil {
slog.Warn("failed to update OAuth2 client last active", slog.String("clientID", clientID), log.BBError(err))
}
- // Build redirect URL with code
u, err := url.Parse(redirectURI)
if err != nil {
return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to parse redirect URI")
@@ -190,8 +211,8 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
u.RawQuery = q.Encode()
redirectURL := u.String()
- // Return HTML page that redirects to callback URL
- // This avoids CSP form-action restrictions
+ // Return HTML page that redirects to callback URL.
+ // This avoids CSP form-action restrictions.
return c.HTML(http.StatusOK, buildRedirectHTML(redirectURL))
}
diff --git a/backend/api/oauth2/discovery.go b/backend/api/oauth2/discovery.go
index 4218b5f6e6..a27925b643 100644
--- a/backend/api/oauth2/discovery.go
+++ b/backend/api/oauth2/discovery.go
@@ -38,7 +38,20 @@ type protectedResourceMetadata struct {
func (s *Service) getBaseURL(c *echo.Context) string {
ctx := c.Request().Context()
- workspaceID, _ := s.getWorkspaceFromRequest(c)
+ // 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)
if err != nil {
slog.Warn("failed to get external url for OAuth2", log.BBError(err))
@@ -62,7 +75,7 @@ func (s *Service) getBaseURL(c *echo.Context) string {
func (s *Service) handleDiscovery(c *echo.Context) error {
baseURL := s.getBaseURL(c)
- oauthBase := s.getOAuthBasePath(c, baseURL)
+ oauthBase := fmt.Sprintf("%s/api/oauth2", baseURL)
metadata := &authorizationServerMetadata{
Issuer: baseURL,
AuthorizationEndpoint: fmt.Sprintf("%s/authorize", oauthBase),
@@ -77,24 +90,31 @@ func (s *Service) handleDiscovery(c *echo.Context) error {
return c.JSON(http.StatusOK, metadata)
}
-// getOAuthBasePath returns the base path for OAuth2 endpoints.
-// In self-hosted mode, it uses legacy paths that don't require a workspace ID.
-// In SaaS mode, the discovery endpoint cannot resolve a workspace ID (the route
-// has no :workspaceID param), so it falls back to templated URLs. SaaS workspace
-// discovery requires a separate mechanism (e.g., workspace-scoped well-known endpoint).
-func (s *Service) getOAuthBasePath(_ *echo.Context, baseURL string) string {
- if !s.profile.SaaS {
- return fmt.Sprintf("%s/api/oauth2", baseURL)
- }
- return fmt.Sprintf("%s/api/workspaces/:workspaceID/oauth2", baseURL)
-}
-
// handleProtectedResourceMetadata returns RFC 9728 protected resource metadata.
// This tells clients which authorization server protects this resource.
+//
+// RFC 9728 §3.3 requires the `resource` value to match the resource the client
+// is accessing. We support both:
+// - GET /.well-known/oauth-protected-resource → resource = baseURL
+// - GET /.well-known/oauth-protected-resource/<path> → resource = baseURL + /<path>
+//
+// 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)
+
+ const wellKnownPrefix = "/.well-known/oauth-protected-resource"
+ resource := baseURL
+ if subPath := strings.TrimPrefix(c.Request().URL.Path, wellKnownPrefix); subPath != "" && subPath != "/" {
+ // Ensure leading slash and trim any trailing slash.
+ if !strings.HasPrefix(subPath, "/") {
+ subPath = "/" + subPath
+ }
+ resource = baseURL + strings.TrimRight(subPath, "/")
+ }
+
metadata := &protectedResourceMetadata{
- Resource: baseURL,
+ Resource: resource,
AuthorizationServers: []string{baseURL},
BearerMethodsSupported: []string{"header"},
}
diff --git a/backend/api/oauth2/discovery_test.go b/backend/api/oauth2/discovery_test.go
new file mode 100644
index 0000000000..d717152d25
--- /dev/null
+++ b/backend/api/oauth2/discovery_test.go
@@ -0,0 +1,74 @@
+package oauth2
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/labstack/echo/v5"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/component/config"
+)
+
+// TestProtectedResourceMetadataMatchesRequestedResource verifies the
+// path-suffix routing required by RFC 9728 §3.3: the `resource` field in
+// the metadata document must match the URL the client is accessing.
+//
+// GET /.well-known/oauth-protected-resource → resource: <base>
+// GET /.well-known/oauth-protected-resource/mcp → resource: <base>/mcp
+//
+// The /mcp form is what the MCP server's WWW-Authenticate header points at,
+// so strict clients fetch and validate the document against the same URL
+// they were originally trying to reach.
+func TestProtectedResourceMetadataMatchesRequestedResource(t *testing.T) {
+ s := &Service{
+ // ExternalURL short-circuits the workspace-lookup path so we don't
+ // need a real store. This is the canonical base for the test.
+ profile: &config.Profile{ExternalURL: "https://bb.example.com"},
+ }
+
+ cases := []struct {
+ name string
+ path string
+ wantResource string
+ }{
+ {
+ name: "base path returns origin",
+ path: "/.well-known/oauth-protected-resource",
+ wantResource: "https://bb.example.com",
+ },
+ {
+ name: "mcp suffix returns resource with /mcp",
+ path: "/.well-known/oauth-protected-resource/mcp",
+ wantResource: "https://bb.example.com/mcp",
+ },
+ {
+ name: "trailing slash is normalized away",
+ path: "/.well-known/oauth-protected-resource/mcp/",
+ wantResource: "https://bb.example.com/mcp",
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodGet, tc.path, nil)
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+
+ require.NoError(t, s.handleProtectedResourceMetadata(c))
+ require.Equal(t, http.StatusOK, rec.Code)
+
+ var got protectedResourceMetadata
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
+ require.Equal(t, tc.wantResource, got.Resource,
+ "strict RFC 9728 clients reject metadata whose resource field "+
+ "does not match the URL they requested")
+ // Authorization servers stays at the origin regardless — the AS
+ // is a property of the deployment, not the specific resource path.
+ require.Equal(t, []string{"https://bb.example.com"}, got.AuthorizationServers)
+ })
+ }
+}
diff --git a/backend/api/oauth2/oauth2.go b/backend/api/oauth2/oauth2.go
index a4e0572006..6061f1a291 100644
--- a/backend/api/oauth2/oauth2.go
+++ b/backend/api/oauth2/oauth2.go
@@ -15,8 +15,6 @@ import (
"github.com/labstack/echo/v5"
"golang.org/x/crypto/bcrypt"
- "github.com/pkg/errors"
-
"github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/config"
@@ -50,39 +48,33 @@ func NewService(store *store.Store, profile *config.Profile, secret string) *Ser
}
func (s *Service) RegisterRoutes(e *echo.Echo) {
- // Workspace-scoped OAuth2 routes (SaaS and self-hosted).
+ // RFC 8414 / RFC 9728 discovery endpoints (host-global, no workspace).
e.GET("/.well-known/oauth-authorization-server", s.handleDiscovery)
e.GET("/.well-known/oauth-authorization-server/*", s.handleDiscovery)
e.GET("/.well-known/oauth-protected-resource", s.handleProtectedResourceMetadata)
e.GET("/.well-known/oauth-protected-resource/*", s.handleProtectedResourceMetadata)
+ // Primary OAuth2 routes. Workspace binding now lives on the issued
+ // authorization code / refresh token (set at consent time from the
+ // user's session), not on the URL or the client. Same routes serve
+ // self-hosted and SaaS.
+ e.POST("/api/oauth2/register", s.handleRegister)
+ e.GET("/api/oauth2/authorize", s.handleAuthorizeGet)
+ e.POST("/api/oauth2/authorize", s.handleAuthorizePost)
+ e.GET("/api/oauth2/clients/:clientID", s.handleGetClient)
+ e.POST("/api/oauth2/token", s.handleToken)
+ e.POST("/api/oauth2/revoke", s.handleRevoke)
+
+ // Workspace-scoped routes are kept for backward compatibility with any
+ // client that hardcoded the older URL shape. The :workspaceID segment
+ // is now informational — workspace resolution comes from the session
+ // at consent time, just like the unscoped routes above.
e.POST("/api/workspaces/:workspaceID/oauth2/register", s.handleRegister)
e.GET("/api/workspaces/:workspaceID/oauth2/authorize", s.handleAuthorizeGet)
e.POST("/api/workspaces/:workspaceID/oauth2/authorize", s.handleAuthorizePost)
e.GET("/api/workspaces/:workspaceID/oauth2/clients/:clientID", s.handleGetClient)
e.POST("/api/workspaces/:workspaceID/oauth2/token", s.handleToken)
e.POST("/api/workspaces/:workspaceID/oauth2/revoke", s.handleRevoke)
-
- // Legacy routes (self-hosted only, disabled in SaaS mode).
- if !s.profile.SaaS {
- e.POST("/api/oauth2/register", s.handleRegister)
- e.GET("/api/oauth2/authorize", s.handleAuthorizeGet)
- e.POST("/api/oauth2/authorize", s.handleAuthorizePost)
- e.GET("/api/oauth2/clients/:clientID", s.handleGetClient)
- e.POST("/api/oauth2/token", s.handleToken)
- e.POST("/api/oauth2/revoke", s.handleRevoke)
- }
-}
-
-// getWorkspaceFromRequest extracts workspace ID from URL param or falls back to store for legacy routes.
-func (s *Service) getWorkspaceFromRequest(c *echo.Context) (string, error) {
- if ws := c.Param("workspaceID"); ws != "" {
- return ws, nil
- }
- if s.profile.SaaS {
- return "", errors.New("workspace ID required in URL for SaaS mode")
- }
- return s.store.GetWorkspaceID(c.Request().Context())
}
// handleGetClient returns public client info for the consent page.
@@ -90,12 +82,7 @@ func (s *Service) handleGetClient(c *echo.Context) error {
ctx := c.Request().Context()
clientID := c.Param("clientID")
- workspaceID, err := s.getWorkspaceFromRequest(c)
- if err != nil {
- return oauth2Error(c, http.StatusBadRequest, "invalid_request", "workspace is required")
- }
-
- client, err := s.store.GetOAuth2Client(ctx, workspaceID, clientID)
+ client, err := s.store.GetOAuth2Client(ctx, clientID)
if err != nil {
return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup client")
}
diff --git a/backend/api/oauth2/register.go b/backend/api/oauth2/register.go
index 5df68f7502..7dbdcc2546 100644
--- a/backend/api/oauth2/register.go
+++ b/backend/api/oauth2/register.go
@@ -10,6 +10,17 @@ import (
"github.com/bytebase/bytebase/backend/store"
)
+// 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.
+const (
+ maxClientNameLen = 200
+ maxRedirectURIs = 5
+ maxRedirectURILen = 2048
+)
+
type clientRegistrationRequest struct {
ClientName string `json:"client_name"`
RedirectURIs []string `json:"redirect_uris"`
@@ -26,6 +37,10 @@ type clientRegistrationResponse struct {
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
}
+// handleRegister implements RFC 7591 Dynamic Client Registration. The endpoint
+// is unauthenticated — clients are workspace-agnostic and get bound to a
+// workspace when the user grants consent at /authorize. This matches the
+// pattern used by Linear, Atlassian, Notion, and Cloudflare MCP servers.
func (s *Service) handleRegister(c *echo.Context) error {
ctx := c.Request().Context()
@@ -34,22 +49,28 @@ func (s *Service) handleRegister(c *echo.Context) error {
return oauth2Error(c, http.StatusBadRequest, "invalid_client_metadata", "failed to parse request body")
}
- // Validate client_name
if req.ClientName == "" {
return oauth2Error(c, http.StatusBadRequest, "invalid_client_metadata", "client_name is required")
}
+ if len(req.ClientName) > maxClientNameLen {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_client_metadata", "client_name is too long")
+ }
- // Validate redirect_uris
if len(req.RedirectURIs) == 0 {
return oauth2Error(c, http.StatusBadRequest, "invalid_client_metadata", "redirect_uris is required")
}
+ if len(req.RedirectURIs) > maxRedirectURIs {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_client_metadata", "too many redirect_uris")
+ }
for _, uri := range req.RedirectURIs {
+ if len(uri) > maxRedirectURILen {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_redirect_uri", "redirect URI is too long")
+ }
if !isAllowedDynamicClientRedirectURI(uri) {
return oauth2Error(c, http.StatusBadRequest, "invalid_redirect_uri", "redirect URI must be a localhost URL or a whitelisted app scheme (cursor://, vscode://, vscode-insiders://, jetbrains://gateway/...)")
}
}
- // Validate grant_types (default to authorization_code)
if len(req.GrantTypes) == 0 {
req.GrantTypes = []string{"authorization_code"}
}
@@ -60,7 +81,6 @@ func (s *Service) handleRegister(c *echo.Context) error {
}
}
- // Validate token_endpoint_auth_method (default to none for public clients)
if req.TokenEndpointAuthMethod == "" {
req.TokenEndpointAuthMethod = "none"
}
@@ -69,25 +89,27 @@ func (s *Service) handleRegister(c *echo.Context) error {
return oauth2Error(c, http.StatusBadRequest, "invalid_client_metadata", "unsupported token_endpoint_auth_method")
}
- // Generate credentials
clientID, err := generateClientID()
if err != nil {
return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to generate client ID")
}
- 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")
- }
- // Store client
- workspaceID, err := s.getWorkspaceFromRequest(c)
- if err != nil {
- return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to get workspace")
+ // 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,
@@ -96,7 +118,6 @@ func (s *Service) handleRegister(c *echo.Context) error {
}
if _, err := s.store.CreateOAuth2Client(ctx, &store.OAuth2ClientMessage{
ClientID: clientID,
- Workspace: workspaceID,
ClientSecretHash: secretHash,
Config: config,
}); err != nil {
@@ -110,7 +131,7 @@ func (s *Service) handleRegister(c *echo.Context) error {
GrantTypes: req.GrantTypes,
TokenEndpointAuthMethod: req.TokenEndpointAuthMethod,
}
- // Only include client_secret for confidential clients
+ // Only include client_secret for confidential clients.
if req.TokenEndpointAuthMethod != "none" {
resp.ClientSecret = clientSecret
}
diff --git a/backend/api/oauth2/revoke.go b/backend/api/oauth2/revoke.go
index a8075c1e22..c6bff11ee7 100644
--- a/backend/api/oauth2/revoke.go
+++ b/backend/api/oauth2/revoke.go
@@ -33,12 +33,7 @@ func (s *Service) handleRevoke(c *echo.Context) error {
return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "client authentication required")
}
- workspaceID, err := s.getWorkspaceFromRequest(c)
- if err != nil {
- return oauth2Error(c, http.StatusBadRequest, "invalid_request", "workspace is required")
- }
-
- client, err := s.store.GetOAuth2Client(ctx, workspaceID, clientID)
+ client, err := s.store.GetOAuth2Client(ctx, clientID)
if err != nil {
return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup client")
}
diff --git a/backend/api/oauth2/token.go b/backend/api/oauth2/token.go
index f45e457c77..181fb8d380 100644
--- a/backend/api/oauth2/token.go
+++ b/backend/api/oauth2/token.go
@@ -1,6 +1,7 @@
package oauth2
import (
+ "context"
"encoding/base64"
"fmt"
"log/slog"
@@ -10,6 +11,7 @@ import (
"time"
"github.com/labstack/echo/v5"
+ "github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/common/log"
@@ -47,12 +49,7 @@ func (s *Service) handleToken(c *echo.Context) error {
return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "client authentication required")
}
- workspaceID, err := s.getWorkspaceFromRequest(c)
- if err != nil {
- return oauth2Error(c, http.StatusBadRequest, "invalid_request", "workspace is required")
- }
-
- client, err := s.store.GetOAuth2Client(ctx, workspaceID, clientID)
+ client, err := s.store.GetOAuth2Client(ctx, clientID)
if err != nil {
return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup client")
}
@@ -155,8 +152,15 @@ func (s *Service) handleAuthorizationCodeGrant(c *echo.Context, client *store.OA
return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "user not found")
}
- // Generate tokens
- return s.issueTokens(c, client, user.Email)
+ // 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.
+ workspaceID, err := s.resolveBoundWorkspace(ctx, authCode.Workspace, client.Workspace, user.Email)
+ if err != nil {
+ return workspaceResolutionError(c, err)
+ }
+
+ return s.issueTokens(c, client, user.Email, workspaceID)
}
func (s *Service) handleRefreshTokenGrant(c *echo.Context, client *store.OAuth2ClientMessage, req *tokenRequest) error {
@@ -207,15 +211,100 @@ func (s *Service) handleRefreshTokenGrant(c *echo.Context, client *store.OAuth2C
return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "user not found")
}
- // Issue new tokens
- return s.issueTokens(c, client, user.Email)
+ // Preserve the workspace binding from the refresh token. Fall back paths
+ // mirror the auth-code grant for pre-migration tokens. 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.
+ workspaceID, err := s.resolveBoundWorkspace(ctx, refreshToken.Workspace, client.Workspace, user.Email)
+ if err != nil {
+ return workspaceResolutionError(c, err)
+ }
+
+ return s.issueTokens(c, client, user.Email, workspaceID)
+}
+
+// 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
+// (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, errWorkspaceNotMember) {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "user is no longer a member of the workspace")
+ }
+ slog.Error("OAuth2 workspace resolution failed", log.BBError(err))
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to resolve workspace")
+}
+
+// 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.
+var errWorkspaceNotMember = errors.New("user is no longer a member of the consented workspace")
+
+// 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.
+//
+// On SaaS only: returns errWorkspaceNotMember if the user is not currently a
+// member of the resolved workspace. All other errors are internal failures.
+func (s *Service) resolveBoundWorkspace(ctx context.Context, issuedWorkspace, clientWorkspace, userEmail string) (string, error) {
+ return resolveBoundWorkspace(ctx, s.store, s.profile.SaaS, issuedWorkspace, clientWorkspace, userEmail)
+}
+
+func resolveBoundWorkspace(ctx context.Context, resolver workspaceResolver, saas bool, issuedWorkspace, clientWorkspace, userEmail string) (string, error) {
+ workspaceID := issuedWorkspace
+ if workspaceID == "" {
+ 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")
+ }
+
+ // Self-hosted: every user belongs to the singleton workspace implicitly,
+ // skip the IAM round-trip. SaaS: verify the user is still a member.
+ if !saas {
+ return workspaceID, nil
+ }
+ ws, err := resolver.FindWorkspace(ctx, &store.FindWorkspaceMessage{
+ WorkspaceID: &workspaceID,
+ Email: userEmail,
+ })
+ if err != nil {
+ return "", errors.Wrap(err, "failed to verify workspace membership")
+ }
+ if ws == nil {
+ return "", errWorkspaceNotMember
+ }
+ return workspaceID, nil
}
-func (s *Service) issueTokens(c *echo.Context, client *store.OAuth2ClientMessage, userEmail string) error {
+// issueTokens issues a new OAuth2 access token (and refresh token, when the
+// grant supports it) bound to the given workspace. The workspace is sourced
+// from the authorization code or refresh token being exchanged, not from the
+// client — clients are workspace-agnostic.
+func (s *Service) issueTokens(c *echo.Context, client *store.OAuth2ClientMessage, userEmail, workspaceID string) error {
ctx := c.Request().Context()
- // Generate access token (JWT)
- accessToken, err := auth.GenerateOAuth2AccessToken(userEmail, client.ClientID, client.Workspace, s.secret, accessTokenExpiry)
+ // Generate access token (JWT) with the workspace_id claim that
+ // downstream APIs (gRPC services, MCP middleware) use to scope requests.
+ accessToken, err := auth.GenerateOAuth2AccessToken(userEmail, client.ClientID, workspaceID, s.secret, accessTokenExpiry)
if err != nil {
return oauth2Error(c, http.StatusInternalServerError, "server_error", fmt.Sprintf("failed to generate access token with error: %v", err))
}
@@ -230,19 +319,20 @@ func (s *Service) issueTokens(c *echo.Context, client *store.OAuth2ClientMessage
return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to generate refresh token")
}
- // Store refresh token
+ // Store refresh token with the workspace binding preserved so a
+ // subsequent /token refresh re-issues for the same workspace.
if _, err := s.store.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{
TokenHash: auth.HashToken(refreshTokenStr),
ClientID: client.ClientID,
UserEmail: userEmail,
+ Workspace: workspaceID,
ExpiresAt: now.Add(refreshTokenExpiry),
}); err != nil {
return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to store refresh token")
}
}
- // Update client last active
- if err := s.store.UpdateOAuth2ClientLastActiveAt(ctx, client.Workspace, client.ClientID); err != nil {
+ if err := s.store.UpdateOAuth2ClientLastActiveAt(ctx, client.ClientID); err != nil {
slog.Warn("failed to update OAuth2 client last active", slog.String("clientID", client.ClientID), log.BBError(err))
}
diff --git a/backend/api/oauth2/token_test.go b/backend/api/oauth2/token_test.go
new file mode 100644
index 0000000000..b8f4a0272a
--- /dev/null
+++ b/backend/api/oauth2/token_test.go
@@ -0,0 +1,139 @@
+package oauth2
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ pkgerrors "github.com/pkg/errors"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// 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
+ return r.findResult, r.findErr
+}
+
+func TestResolveBoundWorkspace(t *testing.T) {
+ ctx := context.Background()
+
+ t.Run("self-hosted skips membership check and returns issued workspace", func(t *testing.T) {
+ r := &fakeWorkspaceResolver{}
+ got, err := resolveBoundWorkspace(ctx, r, false, "ws-issued", "", "[email protected]")
+ require.NoError(t, err)
+ require.Equal(t, "ws-issued", got)
+ 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("falls back from issued to client workspace before singleton", func(t *testing.T) {
+ r := &fakeWorkspaceResolver{singleton: "ws-singleton"}
+ 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")
+ })
+
+ t.Run("SaaS member returns workspace", func(t *testing.T) {
+ r := &fakeWorkspaceResolver{findResult: &store.WorkspaceMessage{ResourceID: "ws-issued"}}
+ got, err := resolveBoundWorkspace(ctx, r, true, "ws-issued", "", "[email protected]")
+ require.NoError(t, err)
+ require.Equal(t, "ws-issued", got)
+ require.Equal(t, 1, r.findCallCount)
+ require.NotNil(t, r.lastFind.WorkspaceID)
+ require.Equal(t, "ws-issued", *r.lastFind.WorkspaceID)
+ require.Equal(t, "[email protected]", r.lastFind.Email)
+ })
+
+ t.Run("SaaS non-member returns errWorkspaceNotMember sentinel", func(t *testing.T) {
+ r := &fakeWorkspaceResolver{findResult: nil}
+ _, err := resolveBoundWorkspace(ctx, r, true, "ws-issued", "", "[email protected]")
+ require.Error(t, err)
+ require.ErrorIs(t, err, errWorkspaceNotMember,
+ "caller relies on errors.Is(errWorkspaceNotMember) to map this to invalid_grant 400")
+ })
+
+ t.Run("SaaS FindWorkspace internal error is not membership failure", func(t *testing.T) {
+ r := &fakeWorkspaceResolver{findErr: errors.New("db unreachable")}
+ _, err := resolveBoundWorkspace(ctx, r, true, "ws-issued", "", "[email protected]")
+ require.Error(t, err)
+ 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")
+ })
+}
+
+// TestIssueTokensPlacesWorkspaceInJWT verifies the in-memory propagation of
+// the workspace argument through GenerateOAuth2AccessToken into the JWT
+// workspace_id claim. This is the last hop of the consent → token binding:
+//
+// auth code (workspace col) → handler reads it via resolveBoundWorkspace
+// → s.issueTokens(c, client, userEmail, workspaceID)
+// → auth.GenerateOAuth2AccessToken(... , workspaceID, ...)
+// → JWT.workspace_id claim
+//
+// The store-side round-trip is exercised by store_test.TestOAuth2WorkspaceBinding.
+func TestIssueTokensPlacesWorkspaceInJWT(t *testing.T) {
+ const secret = "test-secret"
+ const userEmail = "[email protected]"
+ const clientID = "client-xyz"
+ const workspaceID = "ws-consent-bound"
+
+ tokenStr, err := auth.GenerateOAuth2AccessToken(userEmail, clientID, workspaceID, secret, time.Hour)
+ require.NoError(t, err)
+
+ // Decode the token (signature-verified) and assert the workspace_id
+ // claim equals what we passed in. Anything else means the consent-time
+ // binding got dropped on the way to the wire.
+ claims := jwt.MapClaims{}
+ _, err = jwt.ParseWithClaims(tokenStr, claims, func(_ *jwt.Token) (any, error) {
+ return []byte(secret), nil
+ })
+ require.NoError(t, err)
+ 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"])
+}
diff --git a/backend/migrator/migration/3.18/0002##oauth2_workspace_on_token.sql b/backend/migrator/migration/3.18/0002##oauth2_workspace_on_token.sql
new file mode 100644
index 0000000000..062475331e
--- /dev/null
+++ b/backend/migrator/migration/3.18/0002##oauth2_workspace_on_token.sql
@@ -0,0 +1,14 @@
+-- Move workspace binding from oauth2_client to oauth2_authorization_code and
+-- oauth2_refresh_token. The workspace is now selected by the user at consent
+-- time (Pattern A: token = workspace), so clients can be registered without
+-- prior workspace context — enabling unauthenticated Dynamic Client
+-- Registration on SaaS (RFC 7591). The discovery endpoint can then return
+-- workspace-agnostic /api/oauth2/* URLs that work for any caller.
+
+ALTER TABLE oauth2_client ALTER COLUMN workspace DROP NOT NULL;
+
+ALTER TABLE oauth2_authorization_code
+ ADD COLUMN IF NOT EXISTS workspace text REFERENCES workspace(resource_id);
+
+ALTER TABLE oauth2_refresh_token
+ ADD COLUMN IF NOT EXISTS workspace text REFERENCES workspace(resource_id);
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sql
index 302c0d3fbf..d0f65cc864 100644
--- a/backend/migrator/migration/LATEST.sql
+++ b/backend/migrator/migration/LATEST.sql
@@ -600,7 +600,10 @@ CREATE TABLE task_run_log (
CREATE TABLE oauth2_client (
client_id text PRIMARY KEY,
- workspace text NOT NULL REFERENCES workspace(resource_id),
+ -- workspace is nullable: clients registered via unauthenticated DCR are
+ -- workspace-agnostic and get bound to a workspace at consent time on the
+ -- issued authorization code / refresh token.
+ workspace text REFERENCES workspace(resource_id),
client_secret_hash text NOT NULL,
config jsonb NOT NULL,
last_active_at timestamptz NOT NULL DEFAULT now()
@@ -610,6 +613,9 @@ CREATE TABLE oauth2_authorization_code (
code text PRIMARY KEY,
client_id text NOT NULL REFERENCES oauth2_client(client_id) ON DELETE CASCADE,
user_email text NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,
+ -- Workspace selected at consent time. Carried through into the issued
+ -- access token's workspace_id claim.
+ workspace text REFERENCES workspace(resource_id),
config jsonb NOT NULL,
expires_at timestamptz NOT NULL
);
@@ -618,6 +624,9 @@ CREATE TABLE oauth2_refresh_token (
token_hash text PRIMARY KEY,
client_id text NOT NULL REFERENCES oauth2_client(client_id) ON DELETE CASCADE,
user_email text NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,
+ -- Workspace inherited from the authorization code that originally issued
+ -- this refresh token; preserved across refresh.
+ workspace text REFERENCES workspace(resource_id),
expires_at timestamptz NOT NULL
);
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index 51ed14f3fa..42850e8dbe 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -15,8 +15,8 @@ import (
func TestLatestVersion(t *testing.T) {
files, err := getSortedVersionedFiles()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.18.1"), *files[len(files)-1].version)
- require.Equal(t, "migration/3.18/0001##policy_composite_pk.sql", files[len(files)-1].path)
+ require.Equal(t, semver.MustParse("3.18.2"), *files[len(files)-1].version)
+ require.Equal(t, "migration/3.18/0002##oauth2_workspace_on_token.sql", files[len(files)-1].path)
}
func TestVersionUnique(t *testing.T) {
diff --git a/backend/store/oauth2_authorization_code.go b/backend/store/oauth2_authorization_code.go
index 9c6153f31c..ddeec1d5fa 100644
--- a/backend/store/oauth2_authorization_code.go
+++ b/backend/store/oauth2_authorization_code.go
@@ -17,6 +17,12 @@ type OAuth2AuthorizationCodeMessage struct {
Code string
ClientID string
UserEmail string
+ // Workspace is the workspace the user was acting in when they granted
+ // consent. It is propagated into the issued access token's workspace_id
+ // claim. Empty only for codes created before the workspace column
+ // migration (3.18.2); handlers fall back to the client's workspace in
+ // that case.
+ Workspace string
Config *storepb.OAuth2AuthorizationCodeConfig
ExpiresAt time.Time
}
@@ -27,10 +33,15 @@ func (s *Store) CreateOAuth2AuthorizationCode(ctx context.Context, create *OAuth
return nil, errors.Wrap(err, "failed to marshal config")
}
+ var workspaceArg any
+ if create.Workspace != "" {
+ workspaceArg = create.Workspace
+ }
+
q := qb.Q().Space(`
- INSERT INTO oauth2_authorization_code (code, client_id, user_email, config, expires_at)
- VALUES (?, ?, ?, ?, ?)
- `, create.Code, create.ClientID, create.UserEmail, configBytes, create.ExpiresAt)
+ INSERT INTO oauth2_authorization_code (code, client_id, user_email, workspace, config, expires_at)
+ VALUES (?, ?, ?, ?, ?, ?)
+ `, create.Code, create.ClientID, create.UserEmail, workspaceArg, configBytes, create.ExpiresAt)
query, args, err := q.ToSQL()
if err != nil {
@@ -45,7 +56,7 @@ func (s *Store) CreateOAuth2AuthorizationCode(ctx context.Context, create *OAuth
func (s *Store) GetOAuth2AuthorizationCode(ctx context.Context, clientID, code string) (*OAuth2AuthorizationCodeMessage, error) {
q := qb.Q().Space(`
- SELECT code, client_id, user_email, config, expires_at
+ SELECT code, client_id, user_email, workspace, config, expires_at
FROM oauth2_authorization_code
WHERE code = ? AND client_id = ?
`, code, clientID)
@@ -56,15 +67,17 @@ func (s *Store) GetOAuth2AuthorizationCode(ctx context.Context, clientID, code s
}
msg := &OAuth2AuthorizationCodeMessage{}
+ var workspace sql.NullString
var configBytes []byte
if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan( // NOSONAR: query is parameterized via qb.Query
- &msg.Code, &msg.ClientID, &msg.UserEmail, &configBytes, &msg.ExpiresAt,
+ &msg.Code, &msg.ClientID, &msg.UserEmail, &workspace, &configBytes, &msg.ExpiresAt,
); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return nil, errors.Wrap(err, "failed to get OAuth2 authorization code")
}
+ msg.Workspace = workspace.String
msg.Config = &storepb.OAuth2AuthorizationCodeConfig{}
if err := common.ProtojsonUnmarshaler.Unmarshal(configBytes, msg.Config); err != nil {
diff --git a/backend/store/oauth2_client.go b/backend/store/oauth2_client.go
index ce481d237d..79bf663496 100644
--- a/backend/store/oauth2_client.go
+++ b/backend/store/oauth2_client.go
@@ -2,6 +2,7 @@ package store
import (
"context"
+ "database/sql"
"time"
"github.com/pkg/errors"
@@ -13,29 +14,32 @@ import (
)
type OAuth2ClientMessage struct {
- ClientID string
+ ClientID string
+ // Workspace is empty for clients registered via unauthenticated DCR
+ // (the workspace is bound to the issued authorization code / refresh
+ // token at consent time instead).
Workspace string
ClientSecretHash string
Config *storepb.OAuth2ClientConfig
LastActiveAt time.Time
}
-type FindOAuth2ClientMessage struct {
- ClientID *string
- Workspace string
-}
-
func (s *Store) CreateOAuth2Client(ctx context.Context, create *OAuth2ClientMessage) (*OAuth2ClientMessage, error) {
configBytes, err := protojson.Marshal(create.Config)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal config")
}
+ var workspaceArg any
+ if create.Workspace != "" {
+ workspaceArg = create.Workspace
+ }
+
q := qb.Q().Space(`
INSERT INTO oauth2_client (client_id, workspace, client_secret_hash, config, last_active_at)
VALUES (?, ?, ?, ?, NOW())
RETURNING last_active_at
- `, create.ClientID, create.Workspace, create.ClientSecretHash, configBytes)
+ `, create.ClientID, workspaceArg, create.ClientSecretHash, configBytes)
query, args, err := q.ToSQL()
if err != nil {
@@ -48,64 +52,46 @@ func (s *Store) CreateOAuth2Client(ctx context.Context, create *OAuth2ClientMess
return create, nil
}
-func (s *Store) GetOAuth2Client(ctx context.Context, workspace, clientID string) (*OAuth2ClientMessage, error) {
- clients, err := s.listOAuth2Clients(ctx, &FindOAuth2ClientMessage{ClientID: &clientID, Workspace: workspace})
- if err != nil {
- return nil, err
- }
- if len(clients) == 0 {
- return nil, nil
- }
- return clients[0], nil
-}
-
-func (s *Store) listOAuth2Clients(ctx context.Context, find *FindOAuth2ClientMessage) ([]*OAuth2ClientMessage, error) {
+// GetOAuth2Client looks up a client by client_id (the table's primary key).
+// Workspace is no longer a lookup key — clients are workspace-agnostic since
+// DCR runs unauthenticated.
+func (s *Store) GetOAuth2Client(ctx context.Context, clientID string) (*OAuth2ClientMessage, error) {
q := qb.Q().Space(`
SELECT client_id, workspace, client_secret_hash, config, last_active_at
FROM oauth2_client
- WHERE workspace = ?
- `, find.Workspace)
-
- if v := find.ClientID; v != nil {
- q.And("client_id = ?", *v)
- }
+ WHERE client_id = ?
+ `, clientID)
query, args, err := q.ToSQL()
if err != nil {
return nil, err
}
- rows, err := s.GetDB().QueryContext(ctx, query, args...) // NOSONAR: query is parameterized via qb.Query
- if err != nil {
- return nil, errors.Wrap(err, "failed to query OAuth2 clients")
- }
- defer rows.Close()
-
- var clients []*OAuth2ClientMessage
- for rows.Next() {
- client := &OAuth2ClientMessage{}
- var configBytes []byte
- if err := rows.Scan(&client.ClientID, &client.Workspace, &client.ClientSecretHash, &configBytes, &client.LastActiveAt); err != nil {
- return nil, errors.Wrap(err, "failed to scan OAuth2 client")
- }
- client.Config = &storepb.OAuth2ClientConfig{}
- if err := common.ProtojsonUnmarshaler.Unmarshal(configBytes, client.Config); err != nil {
- return nil, errors.Wrap(err, "failed to unmarshal config")
+ client := &OAuth2ClientMessage{}
+ var workspace sql.NullString
+ var configBytes []byte
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan( // NOSONAR: query is parameterized via qb.Query
+ &client.ClientID, &workspace, &client.ClientSecretHash, &configBytes, &client.LastActiveAt,
+ ); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
}
- clients = append(clients, client)
+ return nil, errors.Wrap(err, "failed to query OAuth2 client")
}
- if err := rows.Err(); err != nil {
- return nil, errors.Wrap(err, "failed to iterate OAuth2 clients")
+ client.Workspace = workspace.String
+ client.Config = &storepb.OAuth2ClientConfig{}
+ if err := common.ProtojsonUnmarshaler.Unmarshal(configBytes, client.Config); err != nil {
+ return nil, errors.Wrap(err, "failed to unmarshal config")
}
- return clients, nil
+ return client, nil
}
-func (s *Store) UpdateOAuth2ClientLastActiveAt(ctx context.Context, workspace, clientID string) error {
+func (s *Store) UpdateOAuth2ClientLastActiveAt(ctx context.Context, clientID string) error {
q := qb.Q().Space(`
UPDATE oauth2_client
SET last_active_at = NOW()
- WHERE client_id = ? AND workspace = ?
- `, clientID, workspace)
+ WHERE client_id = ?
+ `, clientID)
query, args, err := q.ToSQL()
if err != nil {
@@ -118,11 +104,11 @@ func (s *Store) UpdateOAuth2ClientLastActiveAt(ctx context.Context, workspace, c
return nil
}
-func (s *Store) DeleteOAuth2Client(ctx context.Context, workspace, clientID string) error {
+func (s *Store) DeleteOAuth2Client(ctx context.Context, clientID string) error {
q := qb.Q().Space(`
DELETE FROM oauth2_client
- WHERE client_id = ? AND workspace = ?
- `, clientID, workspace)
+ WHERE client_id = ?
+ `, clientID)
query, args, err := q.ToSQL()
if err != nil {
diff --git a/backend/store/oauth2_refresh_token.go b/backend/store/oauth2_refresh_token.go
index d93e78397e..4e48227ab1 100644
--- a/backend/store/oauth2_refresh_token.go
+++ b/backend/store/oauth2_refresh_token.go
@@ -14,14 +14,24 @@ type OAuth2RefreshTokenMessage struct {
TokenHash string
ClientID string
UserEmail string
+ // Workspace is the workspace the original consent was granted for.
+ // Preserved across refresh so re-issued access tokens carry the same
+ // workspace_id claim. Empty only for refresh tokens created before the
+ // 3.18.2 migration.
+ Workspace string
ExpiresAt time.Time
}
func (s *Store) CreateOAuth2RefreshToken(ctx context.Context, create *OAuth2RefreshTokenMessage) (*OAuth2RefreshTokenMessage, error) {
+ var workspaceArg any
+ if create.Workspace != "" {
+ workspaceArg = create.Workspace
+ }
+
q := qb.Q().Space(`
- INSERT INTO oauth2_refresh_token (token_hash, client_id, user_email, expires_at)
- VALUES (?, ?, ?, ?)
- `, create.TokenHash, create.ClientID, create.UserEmail, create.ExpiresAt)
+ INSERT INTO oauth2_refresh_token (token_hash, client_id, user_email, workspace, expires_at)
+ VALUES (?, ?, ?, ?, ?)
+ `, create.TokenHash, create.ClientID, create.UserEmail, workspaceArg, create.ExpiresAt)
query, args, err := q.ToSQL()
if err != nil {
@@ -36,7 +46,7 @@ func (s *Store) CreateOAuth2RefreshToken(ctx context.Context, create *OAuth2Refr
func (s *Store) GetOAuth2RefreshToken(ctx context.Context, clientID, tokenHash string) (*OAuth2RefreshTokenMessage, error) {
q := qb.Q().Space(`
- SELECT token_hash, client_id, user_email, expires_at
+ SELECT token_hash, client_id, user_email, workspace, expires_at
FROM oauth2_refresh_token
WHERE token_hash = ? AND client_id = ?
`, tokenHash, clientID)
@@ -47,14 +57,16 @@ func (s *Store) GetOAuth2RefreshToken(ctx context.Context, clientID, tokenHash s
}
msg := &OAuth2RefreshTokenMessage{}
+ var workspace sql.NullString
if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(
- &msg.TokenHash, &msg.ClientID, &msg.UserEmail, &msg.ExpiresAt,
+ &msg.TokenHash, &msg.ClientID, &msg.UserEmail, &workspace, &msg.ExpiresAt,
); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return nil, errors.Wrap(err, "failed to get OAuth2 refresh token")
}
+ msg.Workspace = workspace.String
return msg, nil
}
diff --git a/backend/store/oauth2_workspace_test.go b/backend/store/oauth2_workspace_test.go
new file mode 100644
index 0000000000..d99334a697
--- /dev/null
+++ b/backend/store/oauth2_workspace_test.go
@@ -0,0 +1,129 @@
+package store_test
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ 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"
+)
+
+// TestOAuth2WorkspaceBinding exercises the workspace round-trip on
+// oauth2_authorization_code and oauth2_refresh_token via the real store.
+// This is the persistence half of the consent → token workspace binding
+// flow (the in-memory propagation through handleAuthorizePost /
+// handleAuthorizationCodeGrant / issueTokens / GenerateOAuth2AccessToken
+// is covered by the unit tests in backend/api/oauth2/token_test.go and
+// the helper-package unit tests below).
+//
+// Covers:
+// - Non-empty workspace persists across write/read
+// - Legacy empty-workspace path: a code or refresh token with no workspace
+// (pre-3.18.2 row) survives the migration's nullable column and reads
+// back as "" so the handler's fallback chain to client.Workspace /
+// singleton can take over.
+func TestOAuth2WorkspaceBinding(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))
+
+ // Seed the minimal fixtures needed by the FK constraints on the OAuth2
+ // tables: a workspace and a principal.
+ _, 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', '{}'::jsonb);
+ `)
+ require.NoError(t, err)
+
+ pgURL := fmt.Sprintf(
+ "host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort(),
+ )
+ s, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+
+ t.Run("auth code round-trips workspace bound at consent time", func(t *testing.T) {
+ _, err := s.CreateOAuth2AuthorizationCode(ctx, &store.OAuth2AuthorizationCodeMessage{
+ Code: "code-with-ws",
+ ClientID: "client-A",
+ UserEmail: "[email protected]",
+ Workspace: "ws-test",
+ Config: &storepb.OAuth2AuthorizationCodeConfig{RedirectUri: "http://localhost/cb"},
+ ExpiresAt: time.Now().Add(10 * time.Minute),
+ })
+ require.NoError(t, err)
+
+ got, err := s.GetOAuth2AuthorizationCode(ctx, "client-A", "code-with-ws")
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ require.Equal(t, "ws-test", got.Workspace,
+ "workspace written at consent time must round-trip through the DB into the issued code")
+ })
+
+ t.Run("auth code with empty workspace stays empty for legacy fallback", func(t *testing.T) {
+ // Simulates a pre-3.18.2 auth code created before the workspace
+ // column existed. The migration added the column as nullable, so
+ // existing rows have NULL and Get returns "".
+ _, err := s.CreateOAuth2AuthorizationCode(ctx, &store.OAuth2AuthorizationCodeMessage{
+ Code: "code-no-ws",
+ ClientID: "client-A",
+ UserEmail: "[email protected]",
+ Workspace: "", // explicitly empty
+ Config: &storepb.OAuth2AuthorizationCodeConfig{RedirectUri: "http://localhost/cb"},
+ ExpiresAt: time.Now().Add(10 * time.Minute),
+ })
+ require.NoError(t, err)
+
+ got, err := s.GetOAuth2AuthorizationCode(ctx, "client-A", "code-no-ws")
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ require.Empty(t, got.Workspace,
+ "empty workspace must persist as NULL and read back as \"\" so the handler's fallback chain (client.Workspace → singleton) can run")
+ })
+
+ t.Run("refresh token preserves workspace across refresh", func(t *testing.T) {
+ _, err := s.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{
+ TokenHash: "rt-hash-1",
+ ClientID: "client-A",
+ UserEmail: "[email protected]",
+ Workspace: "ws-test",
+ ExpiresAt: time.Now().Add(30 * 24 * time.Hour),
+ })
+ require.NoError(t, err)
+
+ got, err := s.GetOAuth2RefreshToken(ctx, "client-A", "rt-hash-1")
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ require.Equal(t, "ws-test", got.Workspace,
+ "refresh token must carry the workspace binding so a /token refresh re-issues for the same workspace")
+ })
+
+ t.Run("refresh token with empty workspace stays empty", func(t *testing.T) {
+ _, err := s.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{
+ TokenHash: "rt-hash-2",
+ ClientID: "client-A",
+ UserEmail: "[email protected]",
+ Workspace: "",
+ ExpiresAt: time.Now().Add(30 * 24 * time.Hour),
+ })
+ require.NoError(t, err)
+
+ got, err := s.GetOAuth2RefreshToken(ctx, "client-A", "rt-hash-2")
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ require.Empty(t, got.Workspace)
+ })
+}
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index a601fbd0e8..3690943ace 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -1565,9 +1565,14 @@
"oauth2": {
"consent": {
"description": "{{clientName}} is requesting access to your account",
+ "error-client-not-found": "Client not found",
+ "error-load-failed": "Failed to load client information",
+ "error-missing-params": "Missing required OAuth2 parameters",
+ "error-switch-failed": "Failed to switch workspace",
"permission-access": "Access your Bytebase account with your permissions",
"permissions": "This application will be able to:",
- "title": "Authorization Request"
+ "title": "Authorization Request",
+ "workspace-label": "Granting access to workspace"
}
},
"plan": {
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 49cee64a64..8ff276a5a2 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -1557,9 +1557,14 @@
"oauth2": {
"consent": {
"description": "{{clientName}} está solicitando acceso a tu cuenta",
+ "error-client-not-found": "Cliente no encontrado",
+ "error-load-failed": "Error al cargar la información del cliente",
+ "error-missing-params": "Faltan parámetros obligatorios de OAuth2",
+ "error-switch-failed": "Error al cambiar de workspace",
"permission-access": "Acceder a tu cuenta de Bytebase con tus permisos",
"permissions": "Esta aplicación podrá:",
- "title": "Solicitud de autorización"
+ "title": "Solicitud de autorización",
+ "workspace-label": "Concediendo acceso al workspace"
}
},
"plan": {
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 534054770d..c62e298b9b 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -1557,9 +1557,14 @@
"oauth2": {
"consent": {
"description": "{{clientName}} があなたのアカウントへのアクセスを要求しています",
+ "error-client-not-found": "クライアントが見つかりません",
+ "error-load-failed": "クライアント情報の読み込みに失敗しました",
+ "error-missing-params": "必須の OAuth2 パラメータが不足しています",
+ "error-switch-failed": "ワークスペースの切り替えに失敗しました",
"permission-access": "あなたの権限で Bytebase アカウントにアクセス",
"permissions": "このアプリケーションは以下のことができます:",
- "title": "認証リクエスト"
+ "title": "認証リクエスト",
+ "workspace-label": "アクセスを許可するワークスペース"
}
},
"plan": {
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 18eb559894..721b2db9ac 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -1557,9 +1557,14 @@
"oauth2": {
"consent": {
"description": "{{clientName}} đang yêu cầu truy cập vào tài khoản của bạn",
+ "error-client-not-found": "Không tìm thấy client",
+ "error-load-failed": "Tải thông tin client thất bại",
+ "error-missing-params": "Thiếu các tham số OAuth2 bắt buộc",
+ "error-switch-failed": "Chuyển workspace thất bại",
"permission-access": "Truy cập tài khoản Bytebase của bạn với quyền hạn của bạn",
"permissions": "Ứng dụng này sẽ có thể:",
- "title": "Yêu cầu ủy quyền"
+ "title": "Yêu cầu ủy quyền",
+ "workspace-label": "Cấp quyền truy cập vào workspace"
}
},
"plan": {
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index e163bb9c76..abb9bdd907 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -1557,9 +1557,14 @@
"oauth2": {
"consent": {
"description": "{{clientName}} 正在请求访问您的账户",
+ "error-client-not-found": "未找到客户端",
+ "error-load-failed": "加载客户端信息失败",
+ "error-missing-params": "缺少必需的 OAuth2 参数",
+ "error-switch-failed": "切换工作空间失败",
"permission-access": "使用您的权限访问您的 Bytebase 账户",
"permissions": "此应用程序将能够:",
- "title": "授权请求"
+ "title": "授权请求",
+ "workspace-label": "授权访问的工作空间"
}
},
"plan": {
diff --git a/frontend/src/react/pages/auth/OAuth2ConsentPage.test.tsx b/frontend/src/react/pages/auth/OAuth2ConsentPage.test.tsx
index d99fb28a9f..5694f4bcc9 100644
--- a/frontend/src/react/pages/auth/OAuth2ConsentPage.test.tsx
+++ b/frontend/src/react/pages/auth/OAuth2ConsentPage.test.tsx
@@ -1,4 +1,4 @@
-import type { ReactElement } from "react";
+import type { ReactElement, ReactNode } from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
@@ -10,7 +10,21 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),
useAuthStore: vi.fn(),
+ useActuatorV1Store: vi.fn(),
+ useWorkspaceV1Store: vi.fn(),
isLoggedIn: { value: true },
+ isSaaSMode: { value: false },
+ currentWorkspace: {
+ value: { name: "workspaces/ws-1", title: "Acme Corp" } as
+ | {
+ name: string;
+ title: string;
+ }
+ | undefined,
+ },
+ workspaceList: { value: [] as { name: string; title: string }[] },
+ fetchWorkspaceList: vi.fn(async () => {}),
+ switchWorkspaceWithoutRedirect: vi.fn(async () => {}),
routerReplace: vi.fn(),
routerBack: vi.fn(),
currentRoute: {
@@ -26,6 +40,21 @@ mocks.useAuthStore.mockImplementation(() => ({
return mocks.isLoggedIn.value;
},
}));
+mocks.useActuatorV1Store.mockImplementation(() => ({
+ get isSaaSMode() {
+ return mocks.isSaaSMode.value;
+ },
+}));
+mocks.useWorkspaceV1Store.mockImplementation(() => ({
+ get currentWorkspace() {
+ return mocks.currentWorkspace.value;
+ },
+ get workspaceList() {
+ return mocks.workspaceList.value;
+ },
+ fetchWorkspaceList: mocks.fetchWorkspaceList,
+ switchWorkspaceWithoutRedirect: mocks.switchWorkspaceWithoutRedirect,
+}));
vi.mock("@/react/hooks/useVueState", () => ({
useVueState: mocks.useVueState,
@@ -33,6 +62,45 @@ vi.mock("@/react/hooks/useVueState", () => ({
vi.mock("@/store", () => ({
useAuthStore: mocks.useAuthStore,
+ useActuatorV1Store: mocks.useActuatorV1Store,
+ useWorkspaceV1Store: mocks.useWorkspaceV1Store,
+}));
+
+// Test-only Select stub: Base UI's Select renders its popup through a portal,
+// which makes click-through-portal flows fragile in jsdom. We swap in a native
+// <select> here so we can exercise the consent page's switch wiring directly.
+// The real Select component is covered by its own tests.
+vi.mock("@/react/components/ui/select", () => ({
+ Select: ({
+ value,
+ onValueChange,
+ children,
+ disabled,
+ }: {
+ value: string;
+ onValueChange?: (v: string) => void;
+ children: ReactNode;
+ disabled?: boolean;
+ }) => (
+ <select
+ data-testid="workspace-select"
+ value={value}
+ disabled={disabled}
+ onChange={(e) => onValueChange?.(e.target.value)}
+ >
+ {children}
+ </select>
+ ),
+ SelectTrigger: ({ children }: { children: React.ReactNode }) => (
+ <>{children}</>
+ ),
+ SelectValue: () => null,
+ SelectContent: ({ children }: { children: React.ReactNode }) => (
+ <>{children}</>
+ ),
+ SelectItem: ({ value, children }: { value: string; children: ReactNode }) => (
+ <option value={value}>{children}</option>
+ ),
}));
vi.mock("@/router", () => ({
@@ -87,6 +155,12 @@ const flushPromises = () =>
beforeEach(async () => {
vi.clearAllMocks();
mocks.isLoggedIn.value = true;
+ mocks.isSaaSMode.value = false;
+ mocks.currentWorkspace.value = {
+ name: "workspaces/ws-1",
+ title: "Acme Corp",
+ };
+ mocks.workspaceList.value = [];
mocks.currentRoute.value.query = {};
mocks.currentRoute.value.fullPath = "/oauth2/consent";
globalThis.fetch = mocks.fetchImpl as typeof fetch;
@@ -115,8 +189,10 @@ describe("OAuth2ConsentPage", () => {
);
render();
await flushPromises();
+ // The component now resolves error text via the i18n key. Our t() mock
+ // returns the key as-is, so we assert on the key rather than English.
expect(container.textContent).toContain(
- "Missing required OAuth2 parameters"
+ "oauth2.consent.error-missing-params"
);
unmount();
});
@@ -169,6 +245,152 @@ describe("OAuth2ConsentPage", () => {
unmount();
});
+ test("shows current workspace title on the consent card", async () => {
+ mocks.currentRoute.value.query = {
+ client_id: "c1",
+ redirect_uri: "https://app/callback",
+ state: "s",
+ code_challenge: "ch",
+ code_challenge_method: "S256",
+ };
+ mocks.fetchImpl.mockResolvedValue({
+ ok: true,
+ json: async () => ({ client_name: "Acme" }),
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <OAuth2ConsentPage />
+ );
+ render();
+ await flushPromises();
+ expect(container.textContent).toContain("oauth2.consent.workspace-label");
+ expect(container.textContent).toContain("Acme Corp");
+ // Self-hosted (default in this test) does NOT prefetch the workspace list.
+ expect(mocks.fetchWorkspaceList).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ test("prefetches workspace list and shows picker on SaaS with multiple workspaces", async () => {
+ mocks.isSaaSMode.value = true;
+ mocks.workspaceList.value = [
+ { name: "workspaces/ws-1", title: "Acme Corp" },
+ { name: "workspaces/ws-2", title: "Side Project" },
+ ];
+ mocks.currentRoute.value.query = {
+ client_id: "c1",
+ redirect_uri: "https://app/callback",
+ state: "s",
+ code_challenge: "ch",
+ code_challenge_method: "S256",
+ };
+ mocks.fetchImpl.mockResolvedValue({
+ ok: true,
+ json: async () => ({ client_name: "Acme" }),
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <OAuth2ConsentPage />
+ );
+ render();
+ await flushPromises();
+ expect(mocks.fetchWorkspaceList).toHaveBeenCalledTimes(1);
+ // Picker trigger renders the current workspace title.
+ expect(container.textContent).toContain("Acme Corp");
+ unmount();
+ });
+
+ test("picking a different workspace calls SwitchWorkspace and reloads", async () => {
+ mocks.isSaaSMode.value = true;
+ mocks.workspaceList.value = [
+ { name: "workspaces/ws-1", title: "Acme Corp" },
+ { name: "workspaces/ws-2", title: "Side Project" },
+ ];
+ mocks.currentRoute.value.query = {
+ client_id: "c1",
+ redirect_uri: "https://app/callback",
+ state: "s",
+ code_challenge: "ch",
+ code_challenge_method: "S256",
+ };
+ mocks.fetchImpl.mockResolvedValue({
+ ok: true,
+ json: async () => ({ client_name: "Acme" }),
+ });
+
+ // Stub globalThis.location.reload so the test doesn't actually navigate.
+ // window === globalThis in jsdom, so this also stubs the value the
+ // component reads via globalThis.location.reload().
+ const reload = vi.fn();
+ Object.defineProperty(globalThis, "location", {
+ writable: true,
+ value: { ...globalThis.location, reload },
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <OAuth2ConsentPage />
+ );
+ render();
+ await flushPromises();
+
+ const select = container.querySelector<HTMLSelectElement>(
+ 'select[data-testid="workspace-select"]'
+ );
+ expect(select).not.toBeNull();
+ expect(select?.value).toBe("workspaces/ws-1");
+
+ await act(async () => {
+ select!.value = "workspaces/ws-2";
+ select!.dispatchEvent(new Event("change", { bubbles: true }));
+ await Promise.resolve();
+ });
+ await flushPromises();
+
+ // Verifies the consent page calls the workspace store's
+ // *withoutRedirect* variant, which posts on the store's own channel —
+ // crucially, that variant does NOT fire the store's onmessage handler
+ // in this tab, so we don't race-redirect to the landing page and lose
+ // the OAuth query params.
+ expect(mocks.switchWorkspaceWithoutRedirect).toHaveBeenCalledTimes(1);
+ expect(mocks.switchWorkspaceWithoutRedirect).toHaveBeenCalledWith(
+ "workspaces/ws-2"
+ );
+ expect(reload).toHaveBeenCalledTimes(1);
+ unmount();
+ });
+
+ test("picking the same workspace is a no-op", async () => {
+ mocks.isSaaSMode.value = true;
+ mocks.workspaceList.value = [
+ { name: "workspaces/ws-1", title: "Acme Corp" },
+ { name: "workspaces/ws-2", title: "Side Project" },
+ ];
+ mocks.currentRoute.value.query = {
+ client_id: "c1",
+ redirect_uri: "https://app/callback",
+ state: "s",
+ code_challenge: "ch",
+ code_challenge_method: "S256",
+ };
+ mocks.fetchImpl.mockResolvedValue({
+ ok: true,
+ json: async () => ({ client_name: "Acme" }),
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <OAuth2ConsentPage />
+ );
+ render();
+ await flushPromises();
+
+ const select = container.querySelector<HTMLSelectElement>(
+ 'select[data-testid="workspace-select"]'
+ );
+ await act(async () => {
+ // Re-dispatching the same value should not trigger a switch.
+ select!.dispatchEvent(new Event("change", { bubbles: true }));
+ await Promise.resolve();
+ });
+ expect(mocks.switchWorkspaceWithoutRedirect).not.toHaveBeenCalled();
+ unmount();
+ });
+
test("deny creates a programmatic form and submits it", async () => {
mocks.currentRoute.value.query = {
client_id: "c1",
diff --git a/frontend/src/react/pages/auth/OAuth2ConsentPage.tsx b/frontend/src/react/pages/auth/OAuth2ConsentPage.tsx
index 4565e09e3a..cbf97cd576 100644
--- a/frontend/src/react/pages/auth/OAuth2ConsentPage.tsx
+++ b/frontend/src/react/pages/auth/OAuth2ConsentPage.tsx
@@ -1,12 +1,19 @@
-import { Check, Loader2 } from "lucide-react";
+import { Building2, Check, Loader2 } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { BytebaseLogo } from "@/react/components/BytebaseLogo";
import { Button } from "@/react/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/react/components/ui/select";
import { useVueState } from "@/react/hooks/useVueState";
import { router } from "@/router";
import { AUTH_SIGNIN_MODULE } from "@/router/auth";
-import { useAuthStore } from "@/store";
+import { useActuatorV1Store, useAuthStore, useWorkspaceV1Store } from "@/store";
const AUTHORIZE_URL = "/api/oauth2/authorize";
@@ -17,7 +24,22 @@ export function OAuth2ConsentPage() {
const [error, setError] = useState("");
const [clientName, setClientName] = useState("");
- const isLoggedIn = useVueState(() => useAuthStore().isLoggedIn);
+ // Pinia store singletons are resolved once at the top of the component so
+ // the useVueState selector closures don't repeat the use*-prefixed call —
+ // which trips the React-hooks-in-callback lint rule (typescript:S6440)
+ // despite Pinia memoizing the factory.
+ const authStore = useAuthStore();
+ const actuatorStore = useActuatorV1Store();
+ const workspaceStore = useWorkspaceV1Store();
+
+ const isLoggedIn = useVueState(() => authStore.isLoggedIn);
+ // Workspace context shown on the consent card. On SaaS, every Bytebase
+ // user belongs to at least one workspace; on self-hosted there's a single
+ // implicit workspace. We display it so the user can confirm which
+ // workspace this OAuth grant will be bound to.
+ const isSaaSMode = useVueState(() => actuatorStore.isSaaSMode);
+ const currentWorkspace = useVueState(() => workspaceStore.currentWorkspace);
+ const workspaceList = useVueState(() => workspaceStore.workspaceList);
const query = router.currentRoute.value.query;
const clientId = (query.client_id as string) || "";
@@ -40,7 +62,7 @@ export function OAuth2ConsentPage() {
}
if (!clientId || !redirectUri || !codeChallenge || !codeChallengeMethod) {
- setError("Missing required OAuth2 parameters");
+ setError(t("oauth2.consent.error-missing-params"));
setLoading(false);
return;
}
@@ -52,19 +74,56 @@ export function OAuth2ConsentPage() {
);
if (!response.ok) {
const data = await response.json();
- setError(data.error_description || "Client not found");
+ setError(
+ data.error_description || t("oauth2.consent.error-client-not-found")
+ );
setLoading(false);
return;
}
const data = await response.json();
setClientName(data.client_name || clientId);
} catch {
- setError("Failed to load client information");
+ setError(t("oauth2.consent.error-load-failed"));
}
setLoading(false);
})();
}, []);
+ // Prefetch workspace list on SaaS so the picker can render. This runs in
+ // its own effect keyed on `isSaaSMode` because actuator's serverInfo may
+ // still be loading when the consent page first mounts; running this here
+ // (instead of inside the bootstrap effect with `[]` deps) lets us pick up
+ // the SaaS signal the moment it resolves true. Failure is non-fatal — the
+ // current workspace is still shown without a picker.
+ const prefetchRef = useRef(false);
+ useEffect(() => {
+ if (!isSaaSMode || prefetchRef.current) return;
+ prefetchRef.current = true;
+ workspaceStore.fetchWorkspaceList().catch(() => {});
+ }, [isSaaSMode, workspaceStore]);
+
+ // Switch the active workspace in-place, preserving the consent flow.
+ // Uses the workspace store's withoutRedirect variant so that
+ // (a) the bb-workspace-switch channel notification is posted on the
+ // store's own channel instance, so the store's onmessage listener
+ // in *this* tab does NOT fire (BroadcastChannel excludes the
+ // source object) — without this we'd race-redirect to the landing
+ // page and lose the OAuth query params;
+ // (b) other tabs still receive the broadcast and refresh as usual.
+ // We then reload the consent URL ourselves so the session cookie carries
+ // the new workspace_id into the upcoming POST /api/oauth2/authorize.
+ const onSwitchWorkspace = async (workspaceName: string | null) => {
+ if (!workspaceName || workspaceName === currentWorkspace?.name) return;
+ setSubmitting(true);
+ try {
+ await workspaceStore.switchWorkspaceWithoutRedirect(workspaceName);
+ globalThis.location.reload();
+ } catch {
+ setError(t("oauth2.consent.error-switch-failed"));
+ setSubmitting(false);
+ }
+ };
+
const goBack = () => {
router.back();
};
@@ -118,13 +177,52 @@ export function OAuth2ConsentPage() {
{t("oauth2.consent.description", { clientName })}
</p>
</div>
+ {currentWorkspace && (
+ <div className="bg-control-bg rounded-sm p-4 flex items-center gap-3">
+ <Building2 className="size-5 text-control-light shrink-0" />
+ <div className="flex-1 min-w-0">
+ <p className="text-xs text-control-light">
+ {t("oauth2.consent.workspace-label")}
+ </p>
+ {isSaaSMode && workspaceList.length > 1 ? (
+ <Select
+ value={currentWorkspace.name}
+ onValueChange={onSwitchWorkspace}
+ disabled={submitting}
+ >
+ <SelectTrigger size="sm" className="mt-1 w-full">
+ <SelectValue>
+ {(name) => {
+ const ws = workspaceList.find(
+ (w) => w.name === name
+ );
+ return ws?.title || ws?.name || name || "";
+ }}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {workspaceList.map((ws) => (
+ <SelectItem key={ws.name} value={ws.name}>
+ {ws.title || ws.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ <p className="text-sm text-main truncate">
+ {currentWorkspace.title || currentWorkspace.name}
+ </p>
+ )}
+ </div>
+ </div>
+ )}
<div className="bg-control-bg rounded-sm p-4">
<p className="text-sm text-control-light mb-2">
{t("oauth2.consent.permissions")}
</p>
<ul className="text-sm text-main space-y-1">
<li className="flex items-center gap-2">
- <Check className="w-4 h-4 text-success" />
+ <Check className="size-4 text-success" />
{t("oauth2.consent.permission-access")}
</li>
</ul>
diff --git a/frontend/src/react/stores/app/workspace.ts b/frontend/src/react/stores/app/workspace.ts
index 26b281e948..d16a61f4c9 100644
--- a/frontend/src/react/stores/app/workspace.ts
+++ b/frontend/src/react/stores/app/workspace.ts
@@ -13,6 +13,10 @@ import {
settingNamePrefix,
workspaceNamePrefix,
} from "@/react/lib/resourceName";
+import {
+ broadcastWorkspaceSwitch,
+ workspaceSwitchChannel,
+} from "@/store/workspaceSwitchChannel";
import { defaultAppProfile } from "@/types/appProfile";
import {
hasFeature as checkFeature,
@@ -43,11 +47,14 @@ import type { Environment } from "@/types/v1/environment";
import { formatAbsoluteDateTime } from "@/utils/datetime";
import type { AppSliceCreator, WorkspaceSlice } from "./types";
-// Notify other tabs when the user switches workspace.
-const workspaceSwitchChannel = new BroadcastChannel("bb-workspace-switch");
-workspaceSwitchChannel.onmessage = () => {
+// Listen on the shared cross-tab channel (see store/workspaceSwitchChannel.ts).
+// Using `addEventListener` rather than `onmessage = ...` allows the Vue-side
+// store to register its own handler on the same object, and source-object
+// exclusion correctly suppresses both handlers when a post originates from
+// this tab (e.g. the OAuth2 consent page's in-place switch).
+workspaceSwitchChannel.addEventListener("message", () => {
window.location.href = "/";
-};
+});
const workspaceProfileSettingName = `${settingNamePrefix}${
Setting_SettingName[Setting_SettingName.WORKSPACE_PROFILE]
@@ -184,7 +191,7 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
})
);
// Notify other tabs to reload with the new workspace.
- workspaceSwitchChannel.postMessage(workspaceName);
+ broadcastWorkspaceSwitch(workspaceName);
// Full-reload to the landing page to reset all frontend state.
window.location.href = "/";
},
diff --git a/frontend/src/store/modules/v1/workspace.ts b/frontend/src/store/modules/v1/workspace.ts
index cdf8c7e2ab..0c9ba08674 100644
--- a/frontend/src/store/modules/v1/workspace.ts
+++ b/frontend/src/store/modules/v1/workspace.ts
@@ -10,6 +10,10 @@ import {
import { router } from "@/router";
import { WORKSPACE_ROUTE_LANDING } from "@/router/dashboard/workspaceRoutes";
import { userNamePrefix, workspaceNamePrefix } from "@/store/modules/v1/common";
+import {
+ broadcastWorkspaceSwitch,
+ workspaceSwitchChannel,
+} from "@/store/workspaceSwitchChannel";
import { ALL_USERS_USER_EMAIL } from "@/types";
import { SwitchWorkspaceRequestSchema } from "@/types/proto-es/v1/auth_service_pb";
import type { IamPolicy } from "@/types/proto-es/v1/iam_policy_pb";
@@ -25,14 +29,18 @@ import { getUserListInBinding, isBindingPolicyExpired } from "@/utils";
import { useActuatorV1Store } from "./actuator";
import { composePolicyBindings } from "./projectIamPolicy";
-// Notify other tabs when the user switches workspace.
-const workspaceSwitchChannel = new BroadcastChannel("bb-workspace-switch");
-workspaceSwitchChannel.onmessage = () => {
+// Listen on the shared cross-tab channel. Using `addEventListener` instead of
+// `onmessage = ...` lets the React-side store register its own handler on the
+// same channel object — and crucially, posts made through that same object
+// (e.g. from the OAuth2 consent page via `switchWorkspaceWithoutRedirect`)
+// will NOT trigger either listener in the sending tab thanks to source-object
+// exclusion.
+workspaceSwitchChannel.addEventListener("message", () => {
// Another tab switched workspace — full-reload to the landing page
// to pick up the new cookie and reset all frontend state.
const landingPath = router.resolve({ name: WORKSPACE_ROUTE_LANDING }).href;
window.location.href = landingPath;
-};
+});
export const useWorkspaceV1Store = defineStore("workspace_v1", () => {
const _workspaceIamPolicy = ref<IamPolicy>(create(IamPolicySchema, {}));
@@ -233,15 +241,25 @@ export const useWorkspaceV1Store = defineStore("workspace_v1", () => {
workspaceList.value = resp.workspaces;
};
- const switchWorkspace = async (workspaceName: string) => {
+ // switchWorkspaceWithoutRedirect performs the server-side switch and
+ // notifies other tabs, but leaves navigation to the caller. Posting via
+ // the shared `broadcastWorkspaceSwitch` helper uses the single
+ // workspaceSwitchChannel instance both the Vue and React stores listen
+ // on, so source-object exclusion suppresses both in-tab listeners — the
+ // caller (e.g. the OAuth2 consent page) is free to handle its own page
+ // lifecycle via location.reload() without losing the consent URL.
+ const switchWorkspaceWithoutRedirect = async (workspaceName: string) => {
await authServiceClientConnect.switchWorkspace(
create(SwitchWorkspaceRequestSchema, {
workspace: workspaceName,
web: true,
})
);
- // Notify other tabs to reload with the new workspace.
- workspaceSwitchChannel.postMessage(workspaceName);
+ broadcastWorkspaceSwitch(workspaceName);
+ };
+
+ const switchWorkspace = async (workspaceName: string) => {
+ await switchWorkspaceWithoutRedirect(workspaceName);
// Full-reload to the landing page to reset all frontend state.
// Reloading the current URL would fail if the page is project-scoped
// (the project likely doesn't exist in the target workspace).
@@ -263,5 +281,6 @@ export const useWorkspaceV1Store = defineStore("workspace_v1", () => {
fetchCurrentWorkspace,
fetchWorkspaceList,
switchWorkspace,
+ switchWorkspaceWithoutRedirect,
};
});
diff --git a/frontend/src/store/workspaceSwitchChannel.ts b/frontend/src/store/workspaceSwitchChannel.ts
new file mode 100644
index 0000000000..a538ae319b
--- /dev/null
+++ b/frontend/src/store/workspaceSwitchChannel.ts
@@ -0,0 +1,22 @@
+// Single BroadcastChannel instance shared by both the Vue and React workspace
+// stores for cross-tab "workspace switched" notifications.
+//
+// Centralizing this matters for BroadcastChannel's source-object exclusion
+// rule: a message posted via `channel.postMessage(...)` is NOT delivered to
+// listeners attached to that same channel object — but IS delivered to any
+// other channel objects with the same name (even in the same tab). Before
+// this module existed, the Vue store and the React store each created their
+// own channel object, so a switch posted from one store reached the other's
+// listener in the same tab and could navigate the consent flow out from
+// underneath itself.
+//
+// With a single shared instance, all in-tab listeners attached to it are
+// correctly excluded when the consent page or any other caller broadcasts.
+
+export const workspaceSwitchChannel = new BroadcastChannel(
+ "bb-workspace-switch"
+);
+
+export const broadcastWorkspaceSwitch = (workspaceName: string) => {
+ workspaceSwitchChannel.postMessage(workspaceName);
+};