Skip to content

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

feat(mcp): bind OAuth2 grants to a trusted canonical resource and scope

Vincent Huang110c1edbc002
diff --git a/backend/api/oauth2/authorize.go b/backend/api/oauth2/authorize.go
index f80a952f84..efd3bc6815 100644
--- a/backend/api/oauth2/authorize.go
+++ b/backend/api/oauth2/authorize.go
@@ -1,6 +1,7 @@
package oauth2
import (
+ "context"
"fmt"
"log/slog"
"net/http"
@@ -69,15 +70,26 @@ func (s *Service) handleAuthorizeGet(c *echo.Context) error {
return oauth2ErrorRedirect(c, redirectURI, state, "invalid_request", "code_challenge_method must be S256")
}
+ // Validate the resource/scope the client is asking for before showing a
+ // consent screen for something we would refuse to issue.
+ params, failure := s.parseGrantParams(ctx, c.QueryParams())
+ if failure != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, failure.code, failure.description)
+ }
+
// 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",
+ // currently active workspace (see handleAuthorizePost). The canonical
+ // resource is forwarded (not the raw value) so the consent POST persists
+ // exactly what was validated here.
+ consentURL := fmt.Sprintf("/oauth2/consent?client_id=%s&redirect_uri=%s&state=%s&code_challenge=%s&code_challenge_method=%s&resource=%s&scope=%s",
url.QueryEscape(clientID),
url.QueryEscape(redirectURI),
url.QueryEscape(state),
url.QueryEscape(codeChallenge),
url.QueryEscape(codeChallengeMethod),
+ url.QueryEscape(params.resource),
+ url.QueryEscape(params.scope),
)
return c.Redirect(http.StatusFound, consentURL)
}
@@ -105,20 +117,104 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "user denied the request")
}
- // Get current user from session
+ // Re-validate resource/scope here rather than trusting what the consent page
+ // posted back: this endpoint is reachable directly, so the GET's validation
+ // is not a guarantee about the POST.
+ formValues, err := c.FormValues()
+ if err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "invalid_request", "failed to parse request")
+ }
+ params, failure := s.parseGrantParams(ctx, formValues)
+ if failure != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, failure.code, failure.description)
+ }
+
+ consenting, failure := s.resolveConsentingUser(c, client)
+ if failure != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, failure.code, failure.description)
+ }
+
+ code, err := generateAuthCode()
+ if err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to generate code")
+ }
+
+ codeConfig := &storepb.OAuth2AuthorizationCodeConfig{
+ RedirectUri: redirectURI,
+ CodeChallenge: codeChallenge,
+ CodeChallengeMethod: codeChallengeMethod,
+ Resource: params.resource,
+ Scope: params.scope,
+ }
+ if _, err := s.store.CreateOAuth2AuthorizationCode(ctx, &store.OAuth2AuthorizationCodeMessage{
+ Code: code,
+ ClientID: clientID,
+ UserEmail: consenting.email,
+ Workspace: consenting.workspaceID,
+ Config: codeConfig,
+ ExpiresAt: time.Now().Add(authCodeExpiry),
+ }); err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to store code")
+ }
+
+ 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))
+ }
+
+ redirectURL, err := buildCodeRedirectURL(redirectURI, code, state)
+ if err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to parse redirect URI")
+ }
+
+ // Return HTML page that redirects to callback URL.
+ // This avoids CSP form-action restrictions.
+ return c.HTML(http.StatusOK, buildRedirectHTML(redirectURL))
+}
+
+// consentingUser is the authenticated user behind a consent POST and the
+// workspace their grant binds to.
+type consentingUser struct {
+ email string
+ workspaceID string
+}
+
+// resolveConsentingUser authenticates the browser session that submitted the
+// consent form and resolves which workspace the grant is for.
+func (s *Service) resolveConsentingUser(c *echo.Context, client *store.OAuth2ClientMessage) (consentingUser, *oauth2Failure) {
+ ctx := c.Request().Context()
+
accessToken, err := auth.GetTokenFromHeaders(c.Request().Header)
if err != nil {
- return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", err.Error())
+ return consentingUser{}, &oauth2Failure{code: "access_denied", description: err.Error()}
}
if accessToken == "" {
- return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "user not authenticated")
+ return consentingUser{}, &oauth2Failure{code: "access_denied", description: "user not authenticated"}
+ }
+ claims, failure := s.parseSessionClaims(accessToken)
+ if failure != nil {
+ return consentingUser{}, failure
+ }
+ workspaceID, failure := s.consentWorkspace(ctx, claims, client)
+ if failure != nil {
+ return consentingUser{}, failure
}
- // 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.
+ user, err := s.store.GetUserByEmail(ctx, claims.Subject)
+ if err != nil {
+ return consentingUser{}, &oauth2Failure{code: "access_denied", description: "failed to find user"}
+ }
+ if user == nil {
+ return consentingUser{}, &oauth2Failure{code: "access_denied", description: "user not found"}
+ }
+ return consentingUser{email: user.Email, workspaceID: workspaceID}, nil
+}
+
+// parseSessionClaims verifies the session JWT behind a consent POST and returns
+// its claims. The workspace_id claim is the workspace the user is currently in;
+// that's the workspace OAuth consent is granted for.
+func (s *Service) parseSessionClaims(accessToken string) (*sessionClaims, *oauth2Failure) {
claims := &sessionClaims{}
- _, err = jwt.ParseWithClaims(accessToken, claims, func(t *jwt.Token) (any, error) {
+ if _, 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)
}
@@ -128,33 +224,35 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
}
}
return nil, errors.Errorf("unexpected access token kid=%v", t.Header["kid"])
- })
- if err != nil {
- return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "invalid session")
+ }); err != nil {
+ return nil, &oauth2Failure{code: "access_denied", description: "invalid session"}
}
-
if !audienceContains(claims.Audience, auth.AccessTokenAudience) {
- return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "invalid token audience")
+ return nil, &oauth2Failure{code: "access_denied", description: "invalid token audience"}
}
+ return claims, nil
+}
- // 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.
+// 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) {
workspaceID := claims.WorkspaceID
if workspaceID == "" {
if s.profile.SaaS {
- return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "session is missing workspace claim")
+ return "", &oauth2Failure{code: "access_denied", description: "session is missing workspace claim"}
}
// Self-hosted: there's exactly one workspace.
- workspaceID, err = s.store.GetWorkspaceID(ctx)
+ singleton, err := s.store.GetWorkspaceID(ctx)
if err != nil {
- return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to resolve workspace")
+ return "", &oauth2Failure{code: "server_error", description: "failed to resolve workspace"}
}
+ workspaceID = singleton
}
if workspaceID == "" {
- return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "no workspace in session")
+ return "", &oauth2Failure{code: "access_denied", description: "no workspace in session"}
}
// Legacy clients registered before the 3.18.2 migration are pinned to a
@@ -163,45 +261,17 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
// 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")
- }
- if user == nil {
- return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "user not found")
- }
-
- code, err := generateAuthCode()
- if err != nil {
- return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to generate code")
- }
-
- codeConfig := &storepb.OAuth2AuthorizationCodeConfig{
- RedirectUri: redirectURI,
- CodeChallenge: codeChallenge,
- CodeChallengeMethod: codeChallengeMethod,
- }
- if _, err := s.store.CreateOAuth2AuthorizationCode(ctx, &store.OAuth2AuthorizationCodeMessage{
- 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")
- }
-
- 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))
+ return "", &oauth2Failure{code: "access_denied", description: "client is registered to a different workspace; switch workspaces and try again"}
}
+ return workspaceID, nil
+}
+// buildCodeRedirectURL appends the issued code (and state, when present) to the
+// client's registered redirect URI.
+func buildCodeRedirectURL(redirectURI, code, state string) (string, error) {
u, err := url.Parse(redirectURI)
if err != nil {
- return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to parse redirect URI")
+ return "", err
}
q := u.Query()
q.Set("code", code)
@@ -209,11 +279,7 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
q.Set("state", state)
}
u.RawQuery = q.Encode()
- redirectURL := u.String()
-
- // Return HTML page that redirects to callback URL.
- // This avoids CSP form-action restrictions.
- return c.HTML(http.StatusOK, buildRedirectHTML(redirectURL))
+ return u.String(), nil
}
// audienceContains checks if the audience claim contains the given token.
diff --git a/backend/api/oauth2/grant_test.go b/backend/api/oauth2/grant_test.go
new file mode 100644
index 0000000000..d8ec5ed1b0
--- /dev/null
+++ b/backend/api/oauth2/grant_test.go
@@ -0,0 +1,332 @@
+package oauth2
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "html"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/labstack/echo/v5"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/component/config"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/migrator"
+ "github.com/bytebase/bytebase/backend/store"
+
+ _ "github.com/bytebase/bytebase/backend/plugin/db/pg"
+)
+
+const (
+ testSecret = "test-secret"
+ testUserEmail = "[email protected]"
+ testWorkspace = "ws-test"
+ testClientID = "client-A"
+ testRedirectURI = "http://localhost/cb"
+ // 43-128 chars per RFC 7636.
+ testCodeVerifier = "kVerifier_kVerifier_kVerifier_kVerifier_kVer"
+ testResource = "https://bb.example.com/mcp"
+)
+
+// 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
+// silently disappears: the code row must carry what was consented, the token
+// endpoint must compare against it, and every refresh must re-issue the same
+// grant rather than whatever the client asks for.
+func TestResourceScopeGrantLifecycle(t *testing.T) {
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+
+ db := container.GetDB()
+ require.NoError(t, migrator.MigrateSchema(ctx, db))
+
+ _, err := db.ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('ws-test');
+ INSERT INTO principal (name, email, password_hash) VALUES ('demo', '[email protected]', 'unused');
+ INSERT INTO oauth2_client (client_id, workspace, client_secret_hash, config)
+ VALUES ('client-A', NULL, 'unused-hash', '{"clientName":"test","redirectUris":["http://localhost/cb"],"grantTypes":["authorization_code","refresh_token"],"tokenEndpointAuthMethod":"none"}'::jsonb);
+ `)
+ require.NoError(t, err)
+
+ pgURL := fmt.Sprintf(
+ "host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort(),
+ )
+ st, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+
+ configured := newTestService(st, "https://bb.example.com")
+
+ t.Run("configured external URL: matching resource and known scope are consented", func(t *testing.T) {
+ code := consentOK(t, configured, url.Values{"resource": {testResource}, "scope": {"mcp:read-only"}})
+
+ got, err := st.GetOAuth2AuthorizationCode(ctx, testClientID, code)
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ require.Equal(t, testResource, got.Config.Resource)
+ require.Equal(t, "mcp:read-only", got.Config.Scope)
+ })
+
+ t.Run("resource is stored canonicalized, not as sent", func(t *testing.T) {
+ code := consentOK(t, configured, url.Values{"resource": {"HTTPS://BB.Example.com/mcp/"}})
+
+ got, err := st.GetOAuth2AuthorizationCode(ctx, testClientID, code)
+ require.NoError(t, err)
+ require.Equal(t, testResource, got.Config.Resource,
+ "the token endpoint compares against this value, so it must already be canonical")
+ })
+
+ t.Run("no resource and no scope still consents (clients that predate both)", func(t *testing.T) {
+ code := consentOK(t, configured, url.Values{})
+
+ got, err := st.GetOAuth2AuthorizationCode(ctx, testClientID, code)
+ require.NoError(t, err)
+ require.Empty(t, got.Config.Resource)
+ require.Empty(t, got.Config.Scope)
+ })
+
+ rejections := []struct {
+ name string
+ params url.Values
+ wantCode string
+ }{
+ {"resource on another host", url.Values{"resource": {"https://evil.example.com/mcp"}}, "invalid_target"},
+ {"noncanonical resource", url.Values{"resource": {"https://bb.example.com:443/mcp"}}, "invalid_target"},
+ {"multiple resources", url.Values{"resource": {testResource, testResource}}, "invalid_target"},
+ {"unknown scope", url.Values{"scope": {"mcp:admin"}}, "invalid_scope"},
+ {"multiple scopes", url.Values{"scope": {"mcp:read-only", "mcp:read-write"}}, "invalid_scope"},
+ }
+ for _, tc := range rejections {
+ t.Run("consent rejected: "+tc.name, func(t *testing.T) {
+ redirect := consent(t, configured, tc.params)
+ require.Equal(t, tc.wantCode, redirect.Query().Get("error"))
+ })
+ }
+
+ t.Run("no configured external URL: a resource request gets the actionable setup error", func(t *testing.T) {
+ // The ship gate of proposal v2 §6.2 — self-hosted instances running on
+ // the request-Host fallback break here, and the error has to tell the
+ // admin exactly what to set rather than fail generically.
+ unconfigured := newTestService(st, "")
+ redirect := consent(t, unconfigured, url.Values{"resource": {testResource}})
+ require.Equal(t, "server_error", redirect.Query().Get("error"))
+ description := redirect.Query().Get("error_description")
+ require.Contains(t, description, "--external-url")
+ require.Contains(t, description, "External URL")
+ })
+
+ t.Run("no configured external URL: a request without a resource still works", func(t *testing.T) {
+ unconfigured := newTestService(st, "")
+ require.NotEmpty(t, consentOK(t, unconfigured, url.Values{}),
+ "resource binding is opt-in, so today's clients must not break on an unconfigured instance")
+ })
+
+ t.Run("the workspace setting is trusted too, not only the flag", func(t *testing.T) {
+ // Self-hosted instances configure the external URL in Settings rather
+ // than on the command line, so the DB tier has to validate resources
+ // exactly like the flag does.
+ _, err := st.UpsertSetting(ctx, &store.SettingMessage{
+ Name: storepb.SettingName_WORKSPACE_PROFILE,
+ Workspace: testWorkspace,
+ Value: &storepb.WorkspaceProfileSetting{ExternalUrl: "https://bb.example.com"},
+ })
+ require.NoError(t, err)
+ t.Cleanup(func() {
+ _, err := st.UpsertSetting(ctx, &store.SettingMessage{
+ Name: storepb.SettingName_WORKSPACE_PROFILE,
+ Workspace: testWorkspace,
+ Value: &storepb.WorkspaceProfileSetting{},
+ })
+ require.NoError(t, err)
+ })
+
+ fromSetting := newTestService(st, "")
+ code := consentOK(t, fromSetting, url.Values{"resource": {testResource}})
+ got, err := st.GetOAuth2AuthorizationCode(ctx, testClientID, code)
+ require.NoError(t, err)
+ require.Equal(t, testResource, got.Config.Resource)
+
+ redirect := consent(t, fromSetting, url.Values{"resource": {"https://evil.example.com/mcp"}})
+ require.Equal(t, "invalid_target", redirect.Query().Get("error"))
+ })
+
+ t.Run("token exchange and refresh carry the grant forward unchanged", func(t *testing.T) {
+ code := consentOK(t, configured, url.Values{"resource": {testResource}, "scope": {"mcp:read-write"}})
+
+ // Exchange, echoing the resource back the way RFC 8707 clients do.
+ first := tokenOK(t, configured, url.Values{
+ "grant_type": {"authorization_code"},
+ "code": {code},
+ "redirect_uri": {testRedirectURI},
+ "code_verifier": {testCodeVerifier},
+ "client_id": {testClientID},
+ "resource": {testResource},
+ })
+ require.Equal(t, "mcp:read-write", first.Scope, "the consented scope must be echoed (RFC 6749 §5.1)")
+ require.NotEmpty(t, first.RefreshToken)
+
+ stored, err := st.GetOAuth2RefreshToken(ctx, testClientID, auth.HashToken(first.RefreshToken))
+ require.NoError(t, err)
+ require.NotNil(t, stored)
+ require.Equal(t, testResource, stored.Resource)
+ require.Equal(t, "mcp:read-write", stored.Scope)
+
+ // A refresh that names a wider scope is refused, and refusal happens
+ // before consumption so the client can retry correctly.
+ widened := postToken(t, configured, url.Values{
+ "grant_type": {"refresh_token"},
+ "refresh_token": {first.RefreshToken},
+ "client_id": {testClientID},
+ "scope": {"mcp:read-only"},
+ })
+ require.Equal(t, http.StatusBadRequest, widened.Code)
+ require.Equal(t, "invalid_scope", errorCode(t, widened))
+
+ mismatched := postToken(t, configured, url.Values{
+ "grant_type": {"refresh_token"},
+ "refresh_token": {first.RefreshToken},
+ "client_id": {testClientID},
+ "resource": {"https://evil.example.com/mcp"},
+ })
+ require.Equal(t, http.StatusBadRequest, mismatched.Code)
+ require.Equal(t, "invalid_target", errorCode(t, mismatched))
+
+ // The rejected attempts left the grant usable, and the honest refresh
+ // re-issues the same resource and scope.
+ second := tokenOK(t, configured, url.Values{
+ "grant_type": {"refresh_token"},
+ "refresh_token": {first.RefreshToken},
+ "client_id": {testClientID},
+ })
+ require.Equal(t, "mcp:read-write", second.Scope)
+
+ rotated, err := st.GetOAuth2RefreshToken(ctx, testClientID, auth.HashToken(second.RefreshToken))
+ require.NoError(t, err)
+ require.NotNil(t, rotated)
+ require.Equal(t, testResource, rotated.Resource)
+ require.Equal(t, "mcp:read-write", rotated.Scope)
+ })
+
+ t.Run("token exchange rejects a resource the grant never consented to", func(t *testing.T) {
+ code := consentOK(t, configured, url.Values{})
+
+ rec := postToken(t, configured, url.Values{
+ "grant_type": {"authorization_code"},
+ "code": {code},
+ "redirect_uri": {testRedirectURI},
+ "code_verifier": {testCodeVerifier},
+ "client_id": {testClientID},
+ "resource": {testResource},
+ })
+ require.Equal(t, http.StatusBadRequest, rec.Code)
+ require.Equal(t, "invalid_target", errorCode(t, rec))
+
+ // Rejected before consumption: the code survives for a correct retry.
+ still, err := st.GetOAuth2AuthorizationCode(ctx, testClientID, code)
+ require.NoError(t, err)
+ require.NotNil(t, still, "a rejected exchange must not burn the authorization code")
+ })
+}
+
+func newTestService(st *store.Store, externalURL string) *Service {
+ return NewService(st, &config.Profile{ExternalURL: externalURL}, testSecret)
+}
+
+// consent posts an approved consent form and returns the callback URL the
+// handler redirects the browser to (carrying either `code` or `error`).
+func consent(t *testing.T, s *Service, extra url.Values) *url.URL {
+ t.Helper()
+
+ challenge := sha256.Sum256([]byte(testCodeVerifier))
+ form := url.Values{
+ "client_id": {testClientID},
+ "redirect_uri": {testRedirectURI},
+ "state": {"state-1"},
+ "code_challenge": {base64.RawURLEncoding.EncodeToString(challenge[:])},
+ "code_challenge_method": {"S256"},
+ "action": {"allow"},
+ }
+ for name, values := range extra {
+ form[name] = values
+ }
+
+ sessionToken, err := auth.GenerateAccessToken(testUserEmail, testWorkspace, testSecret, time.Hour)
+ require.NoError(t, err)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/oauth2/authorize", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Authorization", "Bearer "+sessionToken)
+ rec := httptest.NewRecorder()
+
+ e := echo.New()
+ s.RegisterRoutes(e)
+ e.ServeHTTP(rec, req)
+ require.Equal(t, http.StatusOK, rec.Code)
+
+ return redirectTargetOf(t, rec.Body.String())
+}
+
+// consentOK asserts the consent succeeded and returns the issued code.
+func consentOK(t *testing.T, s *Service, extra url.Values) string {
+ t.Helper()
+ redirect := consent(t, s, extra)
+ require.Empty(t, redirect.Query().Get("error"), redirect.Query().Get("error_description"))
+ code := redirect.Query().Get("code")
+ require.NotEmpty(t, code)
+ return code
+}
+
+func postToken(t *testing.T, s *Service, form url.Values) *httptest.ResponseRecorder {
+ t.Helper()
+
+ req := httptest.NewRequest(http.MethodPost, "/api/oauth2/token", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ rec := httptest.NewRecorder()
+
+ e := echo.New()
+ s.RegisterRoutes(e)
+ e.ServeHTTP(rec, req)
+ return rec
+}
+
+func tokenOK(t *testing.T, s *Service, form url.Values) tokenResponse {
+ t.Helper()
+ rec := postToken(t, s, form)
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+ var got tokenResponse
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
+ require.NotEmpty(t, got.AccessToken)
+ return got
+}
+
+func errorCode(t *testing.T, rec *httptest.ResponseRecorder) string {
+ t.Helper()
+ var body map[string]string
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
+ return body["error"]
+}
+
+// redirectTargetOf pulls the callback URL out of the meta-refresh page the
+// authorize handler returns (it renders HTML rather than a 302 to sidestep CSP
+// form-action restrictions).
+func redirectTargetOf(t *testing.T, body string) *url.URL {
+ t.Helper()
+ matches := regexp.MustCompile(`content="0;url=([^"]+)"`).FindStringSubmatch(body)
+ require.Len(t, matches, 2, "expected a meta-refresh redirect, got: %s", body)
+ parsed, err := url.Parse(html.UnescapeString(matches[1]))
+ require.NoError(t, err)
+ return parsed
+}
diff --git a/backend/api/oauth2/resource.go b/backend/api/oauth2/resource.go
new file mode 100644
index 0000000000..28594b9e00
--- /dev/null
+++ b/backend/api/oauth2/resource.go
@@ -0,0 +1,249 @@
+package oauth2
+
+import (
+ "context"
+ "log/slog"
+ "net/url"
+ "slices"
+ "strings"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/utils"
+)
+
+// mcpResourcePath is the path of the MCP endpoint (registered as `/mcp` by the
+// mcp package). Appended to the configured external URL it forms the canonical
+// resource URI that RFC 8707 clients name in the `resource` parameter, and that
+// our RFC 9728 metadata document publishes.
+const mcpResourcePath = "/mcp"
+
+// externalURLSetupError is returned when a client asks to bind a token to a
+// resource but the deployment has no configured external URL. It names the two
+// places an admin can set one, because the fix is entirely on the server side
+// and the client operator can do nothing about it.
+const externalURLSetupError = "MCP OAuth requires a configured external URL. Start the server with --external-url https://<your-bytebase-host>, or set Settings > General > External URL " +
+ "(https://docs.bytebase.com/get-started/self-host/external-url), then reconnect. The request Host header is deliberately not trusted for resource binding."
+
+// errExternalURLNotConfigured signals that resource validation could not run
+// because no trusted external URL is configured. Mapped to the actionable
+// configuration error at the call site; every other validation failure is a
+// client error.
+var errExternalURLNotConfigured = errors.New("no configured external URL to validate the resource against")
+
+// knownScopes is the P1a scope vocabulary: one scope per predefined permission
+// set. P1a persists and echoes the consented scope; enforcement is P1b, and the
+// consent-time picker that lets a user choose between them lands with it. Until
+// then an unknown scope is rejected rather than silently dropped, so a client
+// never believes it holds something we did not grant.
+var knownScopes = []string{"mcp:read-only", "mcp:read-write"}
+
+// grantParams is the validated resource/scope pair consented for one grant.
+type grantParams struct {
+ // resource is canonical (see canonicalizeResourceURI) or empty.
+ resource string
+ // scope is the client's scope string, stored verbatim, or empty.
+ scope string
+}
+
+// oauth2Failure carries an RFC 6749 error code plus a description so a helper
+// can report why it refused without deciding how to render it — /authorize
+// redirects its errors, /token returns a JSON body.
+type oauth2Failure struct {
+ code string
+ description string
+}
+
+// trustedExternalURL returns the canonical external URL configured for this
+// deployment: the --external-url flag, else the workspace setting. It returns
+// "" when neither is configured.
+//
+// Unlike getBaseURL this deliberately has no request-derived tier. Host and
+// X-Forwarded-Proto are client-controlled, so a header-derived value would let a
+// caller choose the audience its own token is bound to — which is the entire
+// property the resource binding exists to establish.
+func (s *Service) trustedExternalURL(ctx context.Context) string {
+ if s.profile.ExternalURL != "" {
+ return strings.TrimSuffix(s.profile.ExternalURL, "/")
+ }
+ // On self-hosted, resolve the singleton workspace so the DB-backed
+ // workspace_profile.external_url setting can be found. On SaaS there is no
+ // singleton — the CLI flag is required.
+ 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 {
+ // Not configured is the common case here and is reported to the caller
+ // as the actionable setup error; a lookup failure is logged and treated
+ // the same way (fail closed, never fall back to the request).
+ slog.Warn("failed to resolve trusted external URL for OAuth2 resource binding", log.BBError(err))
+ return ""
+ }
+ return strings.TrimSuffix(externalURL, "/")
+}
+
+// parseGrantParams extracts and validates the `resource` (RFC 8707) and `scope`
+// (RFC 6749) parameters of an authorization request. Both are optional — clients
+// that send neither still consent successfully — but a value that is present is
+// validated strictly, and multiple occurrences of either are rejected.
+func (s *Service) parseGrantParams(ctx context.Context, values url.Values) (grantParams, *oauth2Failure) {
+ resource, err := singleValue(values, "resource")
+ if err != nil {
+ return grantParams{}, &oauth2Failure{code: "invalid_target", description: err.Error()}
+ }
+ scope, err := singleValue(values, "scope")
+ if err != nil {
+ return grantParams{}, &oauth2Failure{code: "invalid_scope", description: err.Error()}
+ }
+ if err := validateScope(scope); err != nil {
+ return grantParams{}, &oauth2Failure{code: "invalid_scope", description: err.Error()}
+ }
+ if resource == "" {
+ return grantParams{scope: scope}, nil
+ }
+
+ canonical, err := validateResource(resource, s.trustedExternalURL(ctx))
+ if errors.Is(err, errExternalURLNotConfigured) {
+ slog.Error("rejected an MCP OAuth resource binding because no external URL is configured",
+ slog.String("resource", resource))
+ return grantParams{}, &oauth2Failure{code: "server_error", description: externalURLSetupError}
+ }
+ if err != nil {
+ return grantParams{}, &oauth2Failure{code: "invalid_target", description: err.Error()}
+ }
+ return grantParams{resource: canonical, scope: scope}, nil
+}
+
+// checkConsentedResource verifies a token request's `resource` against the value
+// the grant was consented for. Omitting it is allowed (the consented value
+// stands); naming a different one — or one that was never consented — is not,
+// because the token would then be bound somewhere the user never approved.
+func checkConsentedResource(values url.Values, consented string) *oauth2Failure {
+ requested, err := singleValue(values, "resource")
+ if err != nil {
+ return &oauth2Failure{code: "invalid_target", description: err.Error()}
+ }
+ if requested == "" {
+ return nil
+ }
+ canonical, err := canonicalizeResourceURI(requested)
+ if err != nil {
+ return &oauth2Failure{code: "invalid_target", description: err.Error()}
+ }
+ if canonical != consented {
+ return &oauth2Failure{
+ code: "invalid_target",
+ description: "resource does not match the resource this grant was authorized for",
+ }
+ }
+ return nil
+}
+
+// checkConsentedScope verifies a token request's `scope` against the consented
+// scope. Omitting it is allowed (the consented scope stands); anything else must
+// match exactly. Narrowing is not supported here either: the grant record is the
+// authority, and changing what a session may do happens on the grant page, never
+// by asking for a different scope at the token endpoint.
+func checkConsentedScope(values url.Values, consented string) *oauth2Failure {
+ requested, err := singleValue(values, "scope")
+ if err != nil {
+ return &oauth2Failure{code: "invalid_scope", description: err.Error()}
+ }
+ if requested == "" || requested == consented {
+ return nil
+ }
+ return &oauth2Failure{
+ code: "invalid_scope",
+ description: "scope cannot be changed when exchanging or refreshing a token; reconnect to authorize a different scope",
+ }
+}
+
+// singleValue returns the sole value of name, "" when absent, and an error when
+// it appears more than once. A repeated parameter is ambiguous — one value would
+// end up bound to the token and the other silently dropped — so RFC 6749 §3.1
+// forbids it and we reject rather than pick.
+func singleValue(values url.Values, name string) (string, error) {
+ got := values[name]
+ if len(got) > 1 {
+ return "", errors.Errorf("%s must appear at most once, got %d values", name, len(got))
+ }
+ if len(got) == 0 {
+ return "", nil
+ }
+ return got[0], nil
+}
+
+// validateResource canonicalizes a client-supplied resource indicator and checks
+// that it names this server. trustedBaseURL must come from the configured
+// external URL; an empty one means we cannot prove anything about the value and
+// yields errExternalURLNotConfigured.
+//
+// Accepted: the canonical MCP resource URI (<base>/mcp) and the bare origin
+// (<base>) — the two values our own RFC 9728 metadata documents publish.
+func validateResource(resource, trustedBaseURL string) (string, error) {
+ if trustedBaseURL == "" {
+ return "", errExternalURLNotConfigured
+ }
+ base, err := canonicalizeResourceURI(trustedBaseURL)
+ if err != nil {
+ return "", errors.Wrapf(err, "configured external URL %q is not a usable absolute URL", trustedBaseURL)
+ }
+ canonical, err := canonicalizeResourceURI(resource)
+ if err != nil {
+ return "", err
+ }
+ if canonical != base && canonical != base+mcpResourcePath {
+ return "", errors.Errorf("resource %q is not this server's MCP resource; expected %q", canonical, base+mcpResourcePath)
+ }
+ return canonical, nil
+}
+
+// canonicalizeResourceURI normalizes the two differences a resource URI may
+// carry without changing which resource it names: scheme and host case, and a
+// trailing slash. Everything else is left exactly as sent — a port, a
+// percent-encoded path, a different path — so a noncanonical value fails the
+// comparison in validateResource instead of being quietly accepted as equal.
+//
+// Query strings, fragments, and userinfo are rejected outright: RFC 8707 §2
+// resource URIs must not carry a fragment, and none of the three ever appear in
+// a legitimate MCP resource identifier.
+func canonicalizeResourceURI(resource string) (string, error) {
+ u, err := url.Parse(resource)
+ if err != nil {
+ return "", errors.Wrap(err, "resource is not a valid URI")
+ }
+ scheme := strings.ToLower(u.Scheme)
+ if scheme != "http" && scheme != "https" {
+ return "", errors.Errorf("resource must be an absolute http(s) URI, got %q", resource)
+ }
+ if u.Host == "" {
+ return "", errors.Errorf("resource must name a host, got %q", resource)
+ }
+ if u.User != nil {
+ return "", errors.New("resource must not carry userinfo")
+ }
+ if u.RawQuery != "" || u.ForceQuery {
+ return "", errors.New("resource must not carry a query string")
+ }
+ if u.Fragment != "" || u.RawFragment != "" {
+ return "", errors.New("resource must not carry a fragment")
+ }
+ return scheme + "://" + strings.ToLower(u.Host) + strings.TrimSuffix(u.EscapedPath(), "/"), nil
+}
+
+// validateScope accepts an empty scope (the common case today — no client asks
+// for one) and otherwise requires every space-delimited token to be a scope we
+// actually define.
+func validateScope(scope string) error {
+ for token := range strings.FieldsSeq(scope) {
+ if !slices.Contains(knownScopes, token) {
+ return errors.Errorf("unknown scope %q; supported scopes are %s", token, strings.Join(knownScopes, " "))
+ }
+ }
+ return nil
+}
diff --git a/backend/api/oauth2/resource_test.go b/backend/api/oauth2/resource_test.go
new file mode 100644
index 0000000000..8909e69bcf
--- /dev/null
+++ b/backend/api/oauth2/resource_test.go
@@ -0,0 +1,202 @@
+package oauth2
+
+import (
+ "net/url"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/component/config"
+)
+
+const testTrustedBase = "https://bb.example.com"
+
+// TestValidateResource is the rule space of the resource binding: which values
+// name this server's MCP endpoint, and which are refused. The whole point of the
+// check is that the answer comes from the *configured* external URL, so the
+// unconfigured case is a first-class outcome here rather than an edge case.
+func TestValidateResource(t *testing.T) {
+ t.Run("no configured external URL is a configuration failure, not a client error", func(t *testing.T) {
+ _, err := validateResource("https://bb.example.com/mcp", "")
+ require.ErrorIs(t, err, errExternalURLNotConfigured,
+ "callers key on this sentinel to return the actionable setup error instead of a generic OAuth failure")
+ })
+
+ accepted := []struct {
+ name string
+ in string
+ want string
+ }{
+ {"canonical MCP resource URI", "https://bb.example.com/mcp", "https://bb.example.com/mcp"},
+ {"trailing slash is stripped", "https://bb.example.com/mcp/", "https://bb.example.com/mcp"},
+ {"scheme and host case are normalized", "HTTPS://BB.Example.COM/mcp", "https://bb.example.com/mcp"},
+ // Our own RFC 9728 document at the unsuffixed well-known path publishes
+ // the bare origin as `resource`, so a client that read it must not be
+ // rejected for using the value we advertised.
+ {"bare origin", "https://bb.example.com", "https://bb.example.com"},
+ {"bare origin with trailing slash", "https://bb.example.com/", "https://bb.example.com"},
+ }
+ for _, tc := range accepted {
+ t.Run("accepted: "+tc.name, func(t *testing.T) {
+ got, err := validateResource(tc.in, testTrustedBase)
+ require.NoError(t, err)
+ require.Equal(t, tc.want, got)
+ })
+ }
+
+ rejected := []struct {
+ name string
+ in string
+ }{
+ {"different host", "https://evil.example.com/mcp"},
+ {"different scheme", "http://bb.example.com/mcp"},
+ {"different path", "https://bb.example.com/v1/sql"},
+ {"path case differs (paths are case-sensitive)", "https://bb.example.com/MCP"},
+ // Not normalized on purpose: adding :443 to a URI we never published is
+ // a noncanonical value, and quietly treating it as equal would widen
+ // what counts as "this server".
+ {"explicit default port", "https://bb.example.com:443/mcp"},
+ {"nondefault port", "https://bb.example.com:8443/mcp"},
+ {"percent-encoded path separator", "https://bb.example.com%2Fmcp"},
+ {"query string", "https://bb.example.com/mcp?x=1"},
+ {"fragment", "https://bb.example.com/mcp#frag"},
+ {"userinfo", "https://[email protected]/mcp"},
+ {"relative reference", "/mcp"},
+ {"non-http scheme", "urn:example:mcp"},
+ {"no host", "https:///mcp"},
+ {"empty is not valid once present", " "},
+ }
+ for _, tc := range rejected {
+ t.Run("rejected: "+tc.name, func(t *testing.T) {
+ _, err := validateResource(tc.in, testTrustedBase)
+ require.Error(t, err)
+ require.NotErrorIs(t, err, errExternalURLNotConfigured,
+ "a client-supplied bad value must not be reported as a server misconfiguration")
+ })
+ }
+
+ t.Run("a trailing slash on the configured URL does not change what is accepted", func(t *testing.T) {
+ got, err := validateResource("https://bb.example.com/mcp", "https://bb.example.com/")
+ require.NoError(t, err)
+ require.Equal(t, "https://bb.example.com/mcp", got)
+ })
+
+ t.Run("a mixed-case configured URL still matches a canonical resource", func(t *testing.T) {
+ got, err := validateResource("https://bb.example.com/mcp", "https://BB.Example.com")
+ require.NoError(t, err)
+ require.Equal(t, "https://bb.example.com/mcp", got)
+ })
+}
+
+func TestValidateScope(t *testing.T) {
+ t.Run("empty scope is allowed", func(t *testing.T) {
+ // The consent-time picker is P1b; until it exists every real client
+ // sends no scope at all, and rejecting that would break MCP entirely.
+ require.NoError(t, validateScope(""))
+ })
+ for _, scope := range knownScopes {
+ t.Run("known scope "+scope, func(t *testing.T) {
+ require.NoError(t, validateScope(scope))
+ })
+ }
+ for _, scope := range []string{"mcp:admin", "openid", "mcp:read-only extra", "MCP:READ-ONLY", "mcp:readonly"} {
+ t.Run("unknown scope "+scope, func(t *testing.T) {
+ require.Error(t, validateScope(scope),
+ "an unrecognized scope must be refused, not silently dropped — a client would otherwise believe it holds something we never granted")
+ })
+ }
+}
+
+func TestSingleValue(t *testing.T) {
+ t.Run("absent is empty", func(t *testing.T) {
+ got, err := singleValue(url.Values{}, "resource")
+ require.NoError(t, err)
+ require.Empty(t, got)
+ })
+ t.Run("single value is returned", func(t *testing.T) {
+ got, err := singleValue(url.Values{"resource": {"https://bb.example.com/mcp"}}, "resource")
+ require.NoError(t, err)
+ require.Equal(t, "https://bb.example.com/mcp", got)
+ })
+ t.Run("repeated value is rejected", func(t *testing.T) {
+ _, err := singleValue(url.Values{"resource": {"https://bb.example.com/mcp", "https://evil.example.com/mcp"}}, "resource")
+ require.Error(t, err,
+ "picking one of two values would bind the token to a resource the caller may not have meant")
+ })
+}
+
+// TestCheckConsentedResource covers the token endpoint's half: the request may
+// omit the resource, but it may never name a different one than was consented.
+func TestCheckConsentedResource(t *testing.T) {
+ const consented = "https://bb.example.com/mcp"
+
+ cases := []struct {
+ name string
+ values url.Values
+ consented string
+ wantCode string
+ }{
+ {"omitted keeps the consented resource", url.Values{}, consented, ""},
+ {"exact match", url.Values{"resource": {consented}}, consented, ""},
+ {"noncanonical but equivalent match", url.Values{"resource": {"HTTPS://BB.example.com/mcp/"}}, consented, ""},
+ {"different resource", url.Values{"resource": {"https://evil.example.com/mcp"}}, consented, "invalid_target"},
+ {"noncanonical value that is not equivalent", url.Values{"resource": {"https://bb.example.com:443/mcp"}}, consented, "invalid_target"},
+ {"malformed value", url.Values{"resource": {"not a uri"}}, consented, "invalid_target"},
+ {"repeated value", url.Values{"resource": {consented, consented}}, consented, "invalid_target"},
+ // A grant consented without a resource cannot acquire one at the token
+ // endpoint — that would be a resource binding the user never approved.
+ {"resource on a grant that consented none", url.Values{"resource": {consented}}, "", "invalid_target"},
+ {"omitted on a grant that consented none", url.Values{}, "", ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ failure := checkConsentedResource(tc.values, tc.consented)
+ if tc.wantCode == "" {
+ require.Nil(t, failure)
+ return
+ }
+ require.NotNil(t, failure)
+ require.Equal(t, tc.wantCode, failure.code)
+ })
+ }
+}
+
+// TestCheckConsentedScope pins the never-widened rule: a refresh re-issues the
+// consented scope, and asking for anything else fails instead of being honored.
+func TestCheckConsentedScope(t *testing.T) {
+ cases := []struct {
+ name string
+ values url.Values
+ consented string
+ wantCode string
+ }{
+ {"omitted keeps the consented scope", url.Values{}, "mcp:read-only", ""},
+ {"exact match", url.Values{"scope": {"mcp:read-only"}}, "mcp:read-only", ""},
+ {"widening is rejected", url.Values{"scope": {"mcp:read-write"}}, "mcp:read-only", "invalid_scope"},
+ {"narrowing is rejected too (the grant record is the authority)", url.Values{"scope": {"mcp:read-only"}}, "mcp:read-write", "invalid_scope"},
+ {"scope on a grant that consented none", url.Values{"scope": {"mcp:read-only"}}, "", "invalid_scope"},
+ {"repeated value", url.Values{"scope": {"mcp:read-only", "mcp:read-write"}}, "mcp:read-only", "invalid_scope"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ failure := checkConsentedScope(tc.values, tc.consented)
+ if tc.wantCode == "" {
+ require.Nil(t, failure)
+ return
+ }
+ require.NotNil(t, failure)
+ require.Equal(t, tc.wantCode, failure.code)
+ })
+ }
+}
+
+// TestTrustedExternalURLUsesTheFlagOnly is the negative control for the whole
+// PR: getBaseURL falls back to the request Host, and that fallback must never
+// reach resource validation, because a client controls it and could then name
+// the audience of its own token. trustedExternalURL takes no request at all —
+// there is nothing to fall back to.
+func TestTrustedExternalURLUsesTheFlagOnly(t *testing.T) {
+ s := &Service{profile: &config.Profile{ExternalURL: "https://bb.example.com/"}}
+ require.Equal(t, "https://bb.example.com", s.trustedExternalURL(t.Context()),
+ "the flag is the trusted tier and its trailing slash is normalized away")
+}
diff --git a/backend/api/oauth2/token.go b/backend/api/oauth2/token.go
index 178e0afaf6..478fab3959 100644
--- a/backend/api/oauth2/token.go
+++ b/backend/api/oauth2/token.go
@@ -6,6 +6,7 @@ import (
"fmt"
"log/slog"
"net/http"
+ "net/url"
"slices"
"strings"
"time"
@@ -33,6 +34,19 @@ type tokenResponse struct {
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token,omitempty"`
+ // Scope echoes the scope the grant was consented for (RFC 6749 §5.1), so a
+ // client can see what it actually holds rather than what it asked for.
+ Scope string `json:"scope,omitempty"`
+}
+
+// issuedGrant is the consented state one access/refresh token pair is minted
+// from. The resource and scope travel unchanged from the authorization code
+// through every refresh — a refresh re-issues a grant, it never widens one.
+type issuedGrant struct {
+ userEmail string
+ workspaceID string
+ resource string
+ scope string
}
func (s *Service) handleToken(c *echo.Context) error {
@@ -42,6 +56,12 @@ func (s *Service) handleToken(c *echo.Context) error {
if err := c.Bind(&req); err != nil {
return oauth2Error(c, http.StatusBadRequest, "invalid_request", "failed to parse request")
}
+ // Bind keeps only the first value of a repeated parameter; the raw values are
+ // what the resource/scope checks need in order to reject repeats outright.
+ formValues, err := c.FormValues()
+ if err != nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "failed to parse request")
+ }
// Authenticate client
clientID, clientSecret := s.extractClientCredentials(c, &req)
@@ -68,9 +88,9 @@ func (s *Service) handleToken(c *echo.Context) error {
// Handle grant types
switch req.GrantType {
case "authorization_code":
- return s.handleAuthorizationCodeGrant(c, client, &req)
+ return s.handleAuthorizationCodeGrant(c, client, &req, formValues)
case "refresh_token":
- return s.handleRefreshTokenGrant(c, client, &req)
+ return s.handleRefreshTokenGrant(c, client, &req, formValues)
default:
return oauth2Error(c, http.StatusBadRequest, "unsupported_grant_type", "grant_type must be authorization_code or refresh_token")
}
@@ -92,7 +112,7 @@ func (*Service) extractClientCredentials(c *echo.Context, req *tokenRequest) (cl
return req.ClientID, req.ClientSecret
}
-func (s *Service) handleAuthorizationCodeGrant(c *echo.Context, client *store.OAuth2ClientMessage, req *tokenRequest) error {
+func (s *Service) handleAuthorizationCodeGrant(c *echo.Context, client *store.OAuth2ClientMessage, req *tokenRequest, formValues url.Values) error {
ctx := c.Request().Context()
// Validate grant type is allowed
@@ -100,23 +120,69 @@ func (s *Service) handleAuthorizationCodeGrant(c *echo.Context, client *store.OA
return oauth2Error(c, http.StatusBadRequest, "unauthorized_client", "client not authorized for authorization_code grant")
}
- // Validate code
+ authCode, failure := s.validateAuthorizationCode(ctx, client, req, formValues)
+ if failure != nil {
+ return tokenFailure(c, failure)
+ }
+
+ // Consume the code after all validations pass. This atomic delete is the
+ // single-use gate: PKCE is verified above so a failed verifier never burns
+ // the code, and concurrent redemptions race here so only the caller that
+ // actually claims the row proceeds to issue tokens. A consume failure aborts
+ // issuance rather than warning and continuing (the prior behavior left the
+ // code replayable on a transient error).
+ consumed, err := s.store.ConsumeOAuth2AuthorizationCode(ctx, client.ClientID, req.Code)
+ if err != nil {
+ slog.Error("failed to consume OAuth2 authorization code", slog.String("code", req.Code), log.BBError(err))
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to consume authorization code")
+ }
+ if !consumed {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid or expired code")
+ }
+
+ // Get user
+ user, err := s.store.GetUserByEmail(ctx, authCode.UserEmail)
+ if err != nil || user == nil {
+ 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.
+ workspaceID, err := s.resolveBoundWorkspace(ctx, authCode.Workspace, client.Workspace, user.Email)
+ if err != nil {
+ return workspaceResolutionError(c, err)
+ }
+
+ return s.issueTokens(c, client, issuedGrant{
+ userEmail: user.Email,
+ workspaceID: workspaceID,
+ resource: authCode.Config.Resource,
+ scope: authCode.Config.Scope,
+ })
+}
+
+// validateAuthorizationCode looks up the code and runs every check that must
+// pass before it may be consumed: client binding, expiry, redirect_uri, PKCE,
+// and the consented resource/scope. Returning a failure leaves the code intact
+// so the client can correct its request and retry.
+func (s *Service) validateAuthorizationCode(ctx context.Context, client *store.OAuth2ClientMessage, req *tokenRequest, formValues url.Values) (*store.OAuth2AuthorizationCodeMessage, *oauth2Failure) {
if req.Code == "" {
- return oauth2Error(c, http.StatusBadRequest, "invalid_request", "code is required")
+ return nil, &oauth2Failure{code: "invalid_request", description: "code is required"}
}
authCode, err := s.store.GetOAuth2AuthorizationCode(ctx, client.ClientID, req.Code)
if err != nil {
- return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup code")
+ return nil, &oauth2Failure{code: "server_error", description: "failed to lookup code"}
}
if authCode == nil {
- return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid or expired code")
+ return nil, &oauth2Failure{code: "invalid_grant", description: "invalid or expired code"}
}
// Validate code belongs to this client BEFORE deleting
// This prevents DoS where attacker with stolen code invalidates it for legitimate client
if authCode.ClientID != client.ClientID {
- return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "code was not issued to this client")
+ return nil, &oauth2Failure{code: "invalid_grant", description: "code was not issued to this client"}
}
// Validate code not expired
@@ -125,55 +191,43 @@ func (s *Service) handleAuthorizationCodeGrant(c *echo.Context, client *store.OA
if err := s.store.DeleteOAuth2AuthorizationCode(ctx, client.ClientID, req.Code); err != nil {
slog.Warn("failed to delete expired OAuth2 authorization code", slog.String("code", req.Code), log.BBError(err))
}
- return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "code has expired")
+ return nil, &oauth2Failure{code: "invalid_grant", description: "code has expired"}
}
// Validate redirect_uri matches
if req.RedirectURI != authCode.Config.RedirectUri {
- return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "redirect_uri mismatch")
+ return nil, &oauth2Failure{code: "invalid_grant", description: "redirect_uri mismatch"}
}
// Validate PKCE
if req.CodeVerifier == "" {
- return oauth2Error(c, http.StatusBadRequest, "invalid_request", "code_verifier is required")
+ return nil, &oauth2Failure{code: "invalid_request", description: "code_verifier is required"}
}
if !verifyPKCE(req.CodeVerifier, authCode.Config.CodeChallenge, authCode.Config.CodeChallengeMethod) {
- return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid code_verifier")
+ return nil, &oauth2Failure{code: "invalid_grant", description: "invalid code_verifier"}
}
- // Consume the code after all validations pass. This atomic delete is the
- // single-use gate: PKCE is verified above so a failed verifier never burns
- // the code, and concurrent redemptions race here so only the caller that
- // actually claims the row proceeds to issue tokens. A consume failure aborts
- // issuance rather than warning and continuing (the prior behavior left the
- // code replayable on a transient error).
- consumed, err := s.store.ConsumeOAuth2AuthorizationCode(ctx, client.ClientID, req.Code)
- if err != nil {
- slog.Error("failed to consume OAuth2 authorization code", slog.String("code", req.Code), log.BBError(err))
- return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to consume authorization code")
+ if failure := checkConsentedResource(formValues, authCode.Config.Resource); failure != nil {
+ return nil, failure
}
- if !consumed {
- return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid or expired code")
- }
-
- // Get user
- user, err := s.store.GetUserByEmail(ctx, authCode.UserEmail)
- if err != nil || user == nil {
- return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "user not found")
+ if failure := checkConsentedScope(formValues, authCode.Config.Scope); failure != nil {
+ return nil, failure
}
+ return authCode, nil
+}
- // 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)
+// tokenFailure renders a helper's refusal as an RFC 6749 token-endpoint error.
+// server_error is the only 500-class code these helpers produce; every other
+// code is a client error.
+func tokenFailure(c *echo.Context, failure *oauth2Failure) error {
+ status := http.StatusBadRequest
+ if failure.code == "server_error" {
+ status = http.StatusInternalServerError
}
-
- return s.issueTokens(c, client, user.Email, workspaceID)
+ return oauth2Error(c, status, failure.code, failure.description)
}
-func (s *Service) handleRefreshTokenGrant(c *echo.Context, client *store.OAuth2ClientMessage, req *tokenRequest) error {
+func (s *Service) handleRefreshTokenGrant(c *echo.Context, client *store.OAuth2ClientMessage, req *tokenRequest, formValues url.Values) error {
ctx := c.Request().Context()
// Validate grant type is allowed
@@ -210,6 +264,17 @@ func (s *Service) handleRefreshTokenGrant(c *echo.Context, client *store.OAuth2C
return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "refresh token has expired")
}
+ // A refresh re-issues the grant as consented: the stored resource and scope
+ // are carried forward verbatim, and a request naming different ones is
+ // rejected rather than honored. Checked before the token is consumed so a
+ // rejected refresh leaves the client able to retry correctly.
+ if failure := checkConsentedResource(formValues, refreshToken.Resource); failure != nil {
+ return tokenFailure(c, failure)
+ }
+ if failure := checkConsentedScope(formValues, refreshToken.Scope); failure != nil {
+ return tokenFailure(c, failure)
+ }
+
// Consume the refresh token after validations pass. This atomic delete is
// the single-use rotation gate: concurrent refreshes race here so only the
// caller that actually claims the row issues a new pair. A consume failure
@@ -240,7 +305,12 @@ func (s *Service) handleRefreshTokenGrant(c *echo.Context, client *store.OAuth2C
return workspaceResolutionError(c, err)
}
- return s.issueTokens(c, client, user.Email, workspaceID)
+ return s.issueTokens(c, client, issuedGrant{
+ userEmail: user.Email,
+ workspaceID: workspaceID,
+ resource: refreshToken.Resource,
+ scope: refreshToken.Scope,
+ })
}
// workspaceResolutionError maps the typed errors from resolveBoundWorkspace
@@ -315,15 +385,16 @@ func resolveBoundWorkspace(ctx context.Context, resolver workspaceResolver, saas
}
// 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 {
+// grant supports it) for the given consented grant. Everything in the grant is
+// sourced from the authorization code or refresh token being exchanged, not from
+// the client — clients are workspace-agnostic and cannot pick their own
+// resource or scope here.
+func (s *Service) issueTokens(c *echo.Context, client *store.OAuth2ClientMessage, grant issuedGrant) error {
ctx := c.Request().Context()
// 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)
+ accessToken, err := auth.GenerateOAuth2AccessToken(grant.userEmail, client.ClientID, grant.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))
}
@@ -338,13 +409,15 @@ 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 with the workspace binding preserved so a
- // subsequent /token refresh re-issues for the same workspace.
+ // Store the refresh token with the whole grant preserved so a subsequent
+ // /token refresh re-issues for the same workspace, resource, and scope.
if _, err := s.store.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{
TokenHash: auth.HashToken(refreshTokenStr),
ClientID: client.ClientID,
- UserEmail: userEmail,
- Workspace: workspaceID,
+ UserEmail: grant.userEmail,
+ Workspace: grant.workspaceID,
+ Resource: grant.resource,
+ Scope: grant.scope,
ExpiresAt: now.Add(refreshTokenExpiry),
}); err != nil {
return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to store refresh token")
@@ -360,5 +433,6 @@ func (s *Service) issueTokens(c *echo.Context, client *store.OAuth2ClientMessage
TokenType: "Bearer",
ExpiresIn: int(accessTokenExpiry.Seconds()),
RefreshToken: refreshTokenStr,
+ Scope: grant.scope,
})
}
diff --git a/backend/generated-go/store/oauth2.pb.go b/backend/generated-go/store/oauth2.pb.go
index 569e3d763f..2837ebbb40 100644
--- a/backend/generated-go/store/oauth2.pb.go
+++ b/backend/generated-go/store/oauth2.pb.go
@@ -94,8 +94,15 @@ type OAuth2AuthorizationCodeConfig struct {
RedirectUri string `protobuf:"bytes,1,opt,name=redirect_uri,json=redirectUri,proto3" json:"redirect_uri,omitempty"`
CodeChallenge string `protobuf:"bytes,2,opt,name=code_challenge,json=codeChallenge,proto3" json:"code_challenge,omitempty"`
CodeChallengeMethod string `protobuf:"bytes,3,opt,name=code_challenge_method,json=codeChallengeMethod,proto3" json:"code_challenge_method,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ // The canonical resource URI (RFC 8707) this grant is bound to, validated at
+ // consent time against the configured external URL. Empty for clients that
+ // omit the resource parameter.
+ Resource string `protobuf:"bytes,4,opt,name=resource,proto3" json:"resource,omitempty"`
+ // The scope string consented to, stored verbatim. Empty means no scope was
+ // requested.
+ Scope string `protobuf:"bytes,5,opt,name=scope,proto3" json:"scope,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *OAuth2AuthorizationCodeConfig) Reset() {
@@ -149,6 +156,20 @@ func (x *OAuth2AuthorizationCodeConfig) GetCodeChallengeMethod() string {
return ""
}
+func (x *OAuth2AuthorizationCodeConfig) GetResource() string {
+ if x != nil {
+ return x.Resource
+ }
+ return ""
+}
+
+func (x *OAuth2AuthorizationCodeConfig) GetScope() string {
+ if x != nil {
+ return x.Scope
+ }
+ return ""
+}
+
var File_store_oauth2_proto protoreflect.FileDescriptor
const file_store_oauth2_proto_rawDesc = "" +
@@ -160,11 +181,13 @@ const file_store_oauth2_proto_rawDesc = "" +
"\rredirect_uris\x18\x02 \x03(\tR\fredirectUris\x12\x1f\n" +
"\vgrant_types\x18\x03 \x03(\tR\n" +
"grantTypes\x12;\n" +
- "\x1atoken_endpoint_auth_method\x18\x04 \x01(\tR\x17tokenEndpointAuthMethod\"\x9d\x01\n" +
+ "\x1atoken_endpoint_auth_method\x18\x04 \x01(\tR\x17tokenEndpointAuthMethod\"\xcf\x01\n" +
"\x1dOAuth2AuthorizationCodeConfig\x12!\n" +
"\fredirect_uri\x18\x01 \x01(\tR\vredirectUri\x12%\n" +
"\x0ecode_challenge\x18\x02 \x01(\tR\rcodeChallenge\x122\n" +
- "\x15code_challenge_method\x18\x03 \x01(\tR\x13codeChallengeMethodB\x8e\x01\n" +
+ "\x15code_challenge_method\x18\x03 \x01(\tR\x13codeChallengeMethod\x12\x1a\n" +
+ "\bresource\x18\x04 \x01(\tR\bresource\x12\x14\n" +
+ "\x05scope\x18\x05 \x01(\tR\x05scopeB\x8e\x01\n" +
"\x12com.bytebase.storeB\vOauth2ProtoP\x01Z\x12generated-go/store\xa2\x02\x03BSX\xaa\x02\x0eBytebase.Store\xca\x02\x0eBytebase\\Store\xe2\x02\x1aBytebase\\Store\\GPBMetadata\xea\x02\x0fBytebase::Storeb\x06proto3"
var (
diff --git a/backend/generated-go/store/oauth2_equal.pb.go b/backend/generated-go/store/oauth2_equal.pb.go
index 5a3f0ae458..777a96bd06 100644
--- a/backend/generated-go/store/oauth2_equal.pb.go
+++ b/backend/generated-go/store/oauth2_equal.pb.go
@@ -51,5 +51,11 @@ func (x *OAuth2AuthorizationCodeConfig) Equal(y *OAuth2AuthorizationCodeConfig)
if x.CodeChallengeMethod != y.CodeChallengeMethod {
return false
}
+ if x.Resource != y.Resource {
+ return false
+ }
+ if x.Scope != y.Scope {
+ return false
+ }
return true
}
diff --git a/backend/migrator/migration/3.22/0001##oauth2_resource_scope_on_refresh_token.sql b/backend/migrator/migration/3.22/0001##oauth2_resource_scope_on_refresh_token.sql
new file mode 100644
index 0000000000..5063cbfde1
--- /dev/null
+++ b/backend/migrator/migration/3.22/0001##oauth2_resource_scope_on_refresh_token.sql
@@ -0,0 +1,11 @@
+-- Persist the RFC 8707 resource indicator and the consented OAuth2 scope on
+-- oauth2_refresh_token so a refresh carries the original grant forward
+-- unchanged. The authorization code keeps both in its config JSONB
+-- (OAuth2AuthorizationCodeConfig); the refresh token has flat columns.
+--
+-- Both are nullable: grants issued before this migration have neither, and a
+-- client that omits the resource/scope parameters still consents successfully.
+
+ALTER TABLE oauth2_refresh_token
+ ADD COLUMN IF NOT EXISTS resource text,
+ ADD COLUMN IF NOT EXISTS scope text;
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sql
index a27fb53b9a..49e690f97c 100644
--- a/backend/migrator/migration/LATEST.sql
+++ b/backend/migrator/migration/LATEST.sql
@@ -636,6 +636,11 @@ CREATE TABLE oauth2_refresh_token (
-- Workspace inherited from the authorization code that originally issued
-- this refresh token; preserved across refresh.
workspace text REFERENCES workspace(resource_id),
+ -- Canonical RFC 8707 resource URI and the consented scope string, both
+ -- inherited from the authorization code and carried forward unchanged by
+ -- every refresh. Nullable: clients may omit either parameter.
+ resource text,
+ scope text,
expires_at timestamptz NOT NULL
);
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index 5146bb5a11..686d6d302b 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -17,8 +17,8 @@ import (
func TestLatestVersion(t *testing.T) {
files, err := getSortedVersionedFiles()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.22.0"), *files[len(files)-1].version)
- require.Equal(t, "migration/3.22/0000##retire_export_data.sql", files[len(files)-1].path)
+ require.Equal(t, semver.MustParse("3.22.1"), *files[len(files)-1].version)
+ require.Equal(t, "migration/3.22/0001##oauth2_resource_scope_on_refresh_token.sql", files[len(files)-1].path)
}
func TestVersionUnique(t *testing.T) {
diff --git a/backend/store/oauth2_refresh_token.go b/backend/store/oauth2_refresh_token.go
index ac0e06444b..a7cff82b0a 100644
--- a/backend/store/oauth2_refresh_token.go
+++ b/backend/store/oauth2_refresh_token.go
@@ -19,19 +19,30 @@ type OAuth2RefreshTokenMessage struct {
// workspace_id claim. Empty only for refresh tokens created before the
// 3.18.2 migration.
Workspace string
+ // Resource is the canonical RFC 8707 resource URI the grant is bound to,
+ // validated against the configured external URL at consent time. Empty when
+ // the client omitted the resource parameter (or for pre-3.21.5 tokens).
+ Resource string
+ // Scope is the consented scope string, stored verbatim. Carried forward
+ // unchanged by every refresh — a refresh never widens a grant.
+ Scope string
ExpiresAt time.Time
}
-func (s *Store) CreateOAuth2RefreshToken(ctx context.Context, create *OAuth2RefreshTokenMessage) (*OAuth2RefreshTokenMessage, error) {
- var workspaceArg any
- if create.Workspace != "" {
- workspaceArg = create.Workspace
+// nullIfEmpty maps "" onto a NULL bind argument so the nullable oauth2 columns
+// stay NULL instead of storing an empty string.
+func nullIfEmpty(v string) any {
+ if v == "" {
+ return nil
}
+ return v
+}
+func (s *Store) CreateOAuth2RefreshToken(ctx context.Context, create *OAuth2RefreshTokenMessage) (*OAuth2RefreshTokenMessage, error) {
q := qb.Q().Space(`
- INSERT INTO oauth2_refresh_token (token_hash, client_id, user_email, workspace, expires_at)
- VALUES (?, ?, ?, ?, ?)
- `, create.TokenHash, create.ClientID, create.UserEmail, workspaceArg, create.ExpiresAt)
+ INSERT INTO oauth2_refresh_token (token_hash, client_id, user_email, workspace, resource, scope, expires_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ `, create.TokenHash, create.ClientID, create.UserEmail, nullIfEmpty(create.Workspace), nullIfEmpty(create.Resource), nullIfEmpty(create.Scope), create.ExpiresAt)
query, args, err := q.ToSQL()
if err != nil {
@@ -46,7 +57,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, workspace, expires_at
+ SELECT token_hash, client_id, user_email, workspace, resource, scope, expires_at
FROM oauth2_refresh_token
WHERE token_hash = ? AND client_id = ?
`, tokenHash, clientID)
@@ -57,9 +68,9 @@ func (s *Store) GetOAuth2RefreshToken(ctx context.Context, clientID, tokenHash s
}
msg := &OAuth2RefreshTokenMessage{}
- var workspace sql.NullString
+ var workspace, resource, scope sql.NullString
if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(
- &msg.TokenHash, &msg.ClientID, &msg.UserEmail, &workspace, &msg.ExpiresAt,
+ &msg.TokenHash, &msg.ClientID, &msg.UserEmail, &workspace, &resource, &scope, &msg.ExpiresAt,
); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
@@ -67,6 +78,8 @@ func (s *Store) GetOAuth2RefreshToken(ctx context.Context, clientID, tokenHash s
return nil, errors.Wrap(err, "failed to get OAuth2 refresh token")
}
msg.Workspace = workspace.String
+ msg.Resource = resource.String
+ msg.Scope = scope.String
return msg, nil
}
diff --git a/backend/store/oauth2_workspace_test.go b/backend/store/oauth2_workspace_test.go
index d99334a697..48fe657140 100644
--- a/backend/store/oauth2_workspace_test.go
+++ b/backend/store/oauth2_workspace_test.go
@@ -126,4 +126,67 @@ func TestOAuth2WorkspaceBinding(t *testing.T) {
require.NotNil(t, got)
require.Empty(t, got.Workspace)
})
+
+ // The resource/scope columns (3.21.5) are the durable half of the token
+ // boundary: a refresh reads them back to re-issue the same grant, so a
+ // dropped value would silently widen or unbind the session.
+ t.Run("refresh token round-trips resource and scope", func(t *testing.T) {
+ _, err := s.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{
+ TokenHash: "rt-hash-3",
+ ClientID: "client-A",
+ UserEmail: "[email protected]",
+ Workspace: "ws-test",
+ Resource: "https://bb.example.com/mcp",
+ Scope: "mcp:read-only",
+ ExpiresAt: time.Now().Add(30 * 24 * time.Hour),
+ })
+ require.NoError(t, err)
+
+ got, err := s.GetOAuth2RefreshToken(ctx, "client-A", "rt-hash-3")
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ require.Equal(t, "https://bb.example.com/mcp", got.Resource)
+ require.Equal(t, "mcp:read-only", got.Scope)
+ })
+
+ t.Run("refresh token with no resource or scope stays empty", func(t *testing.T) {
+ // Both parameters are optional, and rows written before 3.21.5 have
+ // NULL — either way the handler must see "" and carry "" forward.
+ _, err := s.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{
+ TokenHash: "rt-hash-4",
+ 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-4")
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ require.Empty(t, got.Resource)
+ require.Empty(t, got.Scope)
+ })
+
+ t.Run("auth code config round-trips resource and scope", func(t *testing.T) {
+ _, err := s.CreateOAuth2AuthorizationCode(ctx, &store.OAuth2AuthorizationCodeMessage{
+ Code: "code-with-resource",
+ ClientID: "client-A",
+ UserEmail: "[email protected]",
+ Workspace: "ws-test",
+ Config: &storepb.OAuth2AuthorizationCodeConfig{
+ RedirectUri: "http://localhost/cb",
+ Resource: "https://bb.example.com/mcp",
+ Scope: "mcp:read-write",
+ },
+ ExpiresAt: time.Now().Add(10 * time.Minute),
+ })
+ require.NoError(t, err)
+
+ got, err := s.GetOAuth2AuthorizationCode(ctx, "client-A", "code-with-resource")
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ require.Equal(t, "https://bb.example.com/mcp", got.Config.Resource)
+ require.Equal(t, "mcp:read-write", got.Config.Scope)
+ })
}
diff --git a/frontend/src/routes/auth/OAuth2ConsentPage.test.tsx b/frontend/src/routes/auth/OAuth2ConsentPage.test.tsx
index ff26146b79..4405a969f1 100644
--- a/frontend/src/routes/auth/OAuth2ConsentPage.test.tsx
+++ b/frontend/src/routes/auth/OAuth2ConsentPage.test.tsx
@@ -429,4 +429,61 @@ describe("OAuth2ConsentPage", () => {
submitSpy.mockRestore();
unmount();
});
+
+ // The consent page is the only hop between /authorize's validation of
+ // `resource`/`scope` and the POST that persists them. Dropping either one
+ // silently unbinds the grant, and the allow and deny paths build their field
+ // lists separately, so both are asserted.
+ test("forwards resource and scope on both the allow and deny paths", async () => {
+ mocks.currentRoute.value.query = {
+ client_id: "c1",
+ redirect_uri: "https://app/callback",
+ state: "s",
+ code_challenge: "ch",
+ code_challenge_method: "S256",
+ resource: "https://bb.example.com/mcp",
+ scope: "mcp:read-only",
+ };
+ mocks.fetchImpl.mockResolvedValue({
+ ok: true,
+ json: async () => ({ client_name: "Acme" }),
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <OAuth2ConsentPage />
+ );
+ render();
+ await flushPromises();
+
+ const allowForm = container.querySelector<HTMLFormElement>(
+ 'form[method="POST"]'
+ );
+ expect(
+ allowForm?.querySelector<HTMLInputElement>('input[name="resource"]')?.value
+ ).toBe("https://bb.example.com/mcp");
+ expect(
+ allowForm?.querySelector<HTMLInputElement>('input[name="scope"]')?.value
+ ).toBe("mcp:read-only");
+
+ const denyBtn = Array.from(
+ container.querySelectorAll<HTMLButtonElement>("button")
+ ).find((b) => b.textContent === "common.deny");
+ let denyFields: Record<string, string> = {};
+ const submitSpy = vi
+ .spyOn(HTMLFormElement.prototype, "submit")
+ .mockImplementation(function (this: HTMLFormElement) {
+ denyFields = Object.fromEntries(
+ Array.from(this.querySelectorAll("input")).map((i) => [
+ i.name,
+ i.value,
+ ])
+ );
+ });
+ act(() => {
+ denyBtn?.click();
+ });
+ expect(denyFields.resource).toBe("https://bb.example.com/mcp");
+ expect(denyFields.scope).toBe("mcp:read-only");
+ submitSpy.mockRestore();
+ unmount();
+ });
});
diff --git a/frontend/src/routes/auth/OAuth2ConsentPage.tsx b/frontend/src/routes/auth/OAuth2ConsentPage.tsx
index 79910efdce..6817515f1d 100644
--- a/frontend/src/routes/auth/OAuth2ConsentPage.tsx
+++ b/frontend/src/routes/auth/OAuth2ConsentPage.tsx
@@ -49,6 +49,11 @@ export function OAuth2ConsentPage() {
const oauthState = (query.state as string) || "";
const codeChallenge = (query.code_challenge as string) || "";
const codeChallengeMethod = (query.code_challenge_method as string) || "";
+ // RFC 8707 resource indicator and RFC 6749 scope, forwarded verbatim from the
+ // /authorize redirect. The backend validated them there and re-validates the
+ // values this page posts back, so this page only has to not drop them.
+ const resource = (query.resource as string) || "";
+ const scope = (query.scope as string) || "";
const initRef = useRef(false);
useEffect(() => {
@@ -146,6 +151,8 @@ export function OAuth2ConsentPage() {
["state", oauthState],
["code_challenge", codeChallenge],
["code_challenge_method", codeChallengeMethod],
+ ["resource", resource],
+ ["scope", scope],
["action", "deny"],
];
for (const [name, value] of fields) {
@@ -248,6 +255,8 @@ export function OAuth2ConsentPage() {
name="code_challenge_method"
value={codeChallengeMethod}
/>
+ <input type="hidden" name="resource" value={resource} />
+ <input type="hidden" name="scope" value={scope} />
<div className="flex gap-x-2">
<Button
type="button"
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index 76681f79ec..f370bf443b 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -3070,6 +3070,8 @@ ReviewSubmission records that an issue entered review.
| redirect_uri | [string](#string) | | |
| code_challenge | [string](#string) | | |
| code_challenge_method | [string](#string) | | |
+| resource | [string](#string) | | The canonical resource URI (RFC 8707) this grant is bound to, validated at consent time against the configured external URL. Empty for clients that omit the resource parameter. |
+| scope | [string](#string) | | The scope string consented to, stored verbatim. Empty means no scope was requested. |
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index ed7e8b3e91..bb715171a7 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -9092,6 +9092,23 @@ Format: environments/prod where prod is the environment resource ID. </p></td>
<td><p> </p></td>
</tr>
+ <tr>
+ <td>resource</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The canonical resource URI (RFC 8707) this grant is bound to, validated at
+consent time against the configured external URL. Empty for clients that
+omit the resource parameter. </p></td>
+ </tr>
+
+ <tr>
+ <td>scope</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The scope string consented to, stored verbatim. Empty means no scope was
+requested. </p></td>
+ </tr>
+
</tbody>
</table>
diff --git a/proto/store/store/oauth2.proto b/proto/store/store/oauth2.proto
index 67c66b0376..2f72403479 100644
--- a/proto/store/store/oauth2.proto
+++ b/proto/store/store/oauth2.proto
@@ -15,4 +15,11 @@ message OAuth2AuthorizationCodeConfig {
string redirect_uri = 1;
string code_challenge = 2;
string code_challenge_method = 3;
+ // The canonical resource URI (RFC 8707) this grant is bound to, validated at
+ // consent time against the configured external URL. Empty for clients that
+ // omit the resource parameter.
+ string resource = 4;
+ // The scope string consented to, stored verbatim. Empty means no scope was
+ // requested.
+ string scope = 5;
}