Skip to content

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

feat: add OAuth2 authorization server for MCP integration (#18429)

p0nycba19b4be4e6
diff --git a/backend/api/auth/auth.go b/backend/api/auth/auth.go
index 77c97a165a..b1777d2ab0 100644
--- a/backend/api/auth/auth.go
+++ b/backend/api/auth/auth.go
@@ -37,7 +37,9 @@ const (
AccessTokenAudienceFmt = "bb.user.access.%s"
// MFATempTokenAudienceFmt is the format of the MFA temp token audience.
MFATempTokenAudienceFmt = "bb.user.mfa-temp.%s"
- apiTokenDuration = 1 * time.Hour
+ // OAuth2AccessTokenAudience is the audience for OAuth2 access tokens.
+ OAuth2AccessTokenAudience = "bb.oauth2.access"
+ apiTokenDuration = 1 * time.Hour
// DefaultTokenDuration is the default token expiration duration.
DefaultTokenDuration = 7 * 24 * time.Hour
@@ -166,24 +168,43 @@ func (in *APIAuthInterceptor) authenticate(ctx context.Context, accessTokenStr s
return nil, nil, errs.New("failed to parse claim")
}
- if !audienceContains(claims.Audience, fmt.Sprintf(AccessTokenAudienceFmt, in.profile.Mode)) {
+ // Accept both user access tokens (bb.user.access.{mode}) and OAuth2 access tokens (bb.oauth2.access)
+ validUserAudience := fmt.Sprintf(AccessTokenAudienceFmt, in.profile.Mode)
+ isOAuth2Token := audienceContains(claims.Audience, OAuth2AccessTokenAudience)
+ isUserToken := audienceContains(claims.Audience, validUserAudience)
+ if !isUserToken && !isOAuth2Token {
return nil, nil, errs.Errorf(
- "invalid access token, audience mismatch, got %q, expected %q. you may send request to the wrong environment",
+ "invalid access token, audience mismatch, got %q, expected %q or %q. you may send request to the wrong environment",
claims.Audience,
- fmt.Sprintf(AccessTokenAudienceFmt, in.profile.Mode),
+ validUserAudience,
+ OAuth2AccessTokenAudience,
)
}
- principalID, err := strconv.Atoi(claims.Subject)
- if err != nil {
- return nil, nil, errs.Errorf("malformed ID %q in the access token", claims.Subject)
- }
- user, err := in.store.GetUserByID(ctx, principalID)
- if err != nil {
- return nil, nil, errs.Errorf("failed to find user ID %q in the access token", principalID)
- }
- if user == nil {
- return nil, nil, errs.Errorf("user ID %q not exists in the access token", principalID)
+ var user *store.UserMessage
+ var err error
+ if isOAuth2Token {
+ // OAuth2 tokens use email as subject
+ user, err = in.store.GetUserByEmail(ctx, claims.Subject)
+ if err != nil {
+ return nil, nil, errs.Errorf("failed to find user email %q in the access token", claims.Subject)
+ }
+ if user == nil {
+ return nil, nil, errs.Errorf("user email %q not exists in the access token", claims.Subject)
+ }
+ } else {
+ // User tokens use ID as subject
+ principalID, err := strconv.Atoi(claims.Subject)
+ if err != nil {
+ return nil, nil, errs.Errorf("malformed ID %q in the access token", claims.Subject)
+ }
+ user, err = in.store.GetUserByID(ctx, principalID)
+ if err != nil {
+ return nil, nil, errs.Errorf("failed to find user ID %q in the access token", principalID)
+ }
+ if user == nil {
+ return nil, nil, errs.Errorf("user ID %q not exists in the access token", principalID)
+ }
}
if user.MemberDeleted {
return nil, nil, errs.Errorf("user ID %q has been deactivated by administrators", user.ID)
diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.go
new file mode 100644
index 0000000000..f33802768a
--- /dev/null
+++ b/backend/api/mcp/server.go
@@ -0,0 +1,158 @@
+// Package mcp provides an MCP (Model Context Protocol) server for Bytebase.
+package mcp
+
+import (
+ "context"
+ "net/http"
+ "strings"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/labstack/echo/v4"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/component/config"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// EchoInput is the input for the echo tool.
+type EchoInput struct {
+ // The message to echo back.
+ Message string `json:"message"`
+}
+
+// EchoOutput is the output for the echo tool.
+type EchoOutput struct {
+ // The echoed message.
+ Echo string `json:"echo"`
+}
+
+// Server is the MCP server for Bytebase.
+type Server struct {
+ mcpServer *mcp.Server
+ httpHandler *mcp.StreamableHTTPHandler
+ store *store.Store
+ profile *config.Profile
+ secret string
+}
+
+// NewServer creates a new MCP server.
+func NewServer(store *store.Store, profile *config.Profile, secret string) *Server {
+ mcpServer := mcp.NewServer(&mcp.Implementation{
+ Name: "bytebase",
+ Version: "1.0.0",
+ }, nil)
+
+ s := &Server{
+ mcpServer: mcpServer,
+ store: store,
+ profile: profile,
+ secret: secret,
+ }
+ s.registerTools()
+
+ // Create HTTP handler for streamable HTTP transport
+ s.httpHandler = mcp.NewStreamableHTTPHandler(func(_ *http.Request) *mcp.Server {
+ return s.mcpServer
+ }, nil)
+
+ return s
+}
+
+// registerTools registers all MCP tools.
+func (s *Server) registerTools() {
+ // Echo tool for testing
+ mcp.AddTool(s.mcpServer, &mcp.Tool{
+ Name: "echo",
+ Description: "Echo the input message back. Useful for testing the MCP connection.",
+ }, s.handleEcho)
+}
+
+// handleEcho handles the echo tool call.
+func (*Server) handleEcho(_ context.Context, _ *mcp.CallToolRequest, input EchoInput) (*mcp.CallToolResult, EchoOutput, error) {
+ output := EchoOutput{Echo: input.Message}
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{
+ &mcp.TextContent{Text: output.Echo},
+ },
+ }, output, nil
+}
+
+// authMiddleware validates OAuth2 bearer tokens for MCP requests.
+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")
+ }
+
+ // 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}")
+ }
+ tokenStr := parts[1]
+
+ // Parse and validate JWT
+ 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")
+ }
+ 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")
+ })
+ if err != nil {
+ if strings.Contains(err.Error(), "expired") {
+ return echo.NewHTTPError(http.StatusUnauthorized, "token expired")
+ }
+ return echo.NewHTTPError(http.StatusUnauthorized, "invalid token")
+ }
+
+ if !token.Valid {
+ return echo.NewHTTPError(http.StatusUnauthorized, "invalid token")
+ }
+
+ // Validate audience - must be OAuth2 access token
+ aud, ok := claims["aud"]
+ if !ok {
+ return echo.NewHTTPError(http.StatusUnauthorized, "invalid token: missing audience")
+ }
+
+ validAudience := false
+ switch v := aud.(type) {
+ case string:
+ validAudience = v == auth.OAuth2AccessTokenAudience
+ case []any:
+ for _, a := range v {
+ if str, ok := a.(string); ok && str == auth.OAuth2AccessTokenAudience {
+ validAudience = true
+ break
+ }
+ }
+ }
+ if !validAudience {
+ return echo.NewHTTPError(http.StatusUnauthorized, "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")
+ }
+
+ // Store user email in context for downstream handlers
+ c.Set("user_email", sub)
+
+ return next(c)
+ }
+}
+
+// RegisterRoutes registers the MCP server routes with Echo.
+func (s *Server) RegisterRoutes(e *echo.Echo) {
+ // MCP Streamable HTTP endpoint with authentication
+ e.Any("/mcp", echo.WrapHandler(s.httpHandler), s.authMiddleware)
+}
diff --git a/backend/api/mcp/server_test.go b/backend/api/mcp/server_test.go
new file mode 100644
index 0000000000..d0647fe757
--- /dev/null
+++ b/backend/api/mcp/server_test.go
@@ -0,0 +1,163 @@
+package mcp
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/labstack/echo/v4"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/config"
+)
+
+func TestMCPAuthMiddleware(t *testing.T) {
+ secret := "test-secret-key"
+ profile := &config.Profile{Mode: common.ReleaseModeDev}
+
+ tests := []struct {
+ name string
+ authHeader string
+ expectedStatus int
+ expectedBody string
+ }{
+ {
+ name: "no authorization header returns 401",
+ authHeader: "",
+ expectedStatus: http.StatusUnauthorized,
+ expectedBody: "authorization required",
+ },
+ {
+ name: "malformed authorization header returns 401",
+ authHeader: "NotBearer token",
+ expectedStatus: http.StatusUnauthorized,
+ expectedBody: "Bearer",
+ },
+ {
+ name: "invalid token returns 401",
+ authHeader: "Bearer invalid-token",
+ expectedStatus: http.StatusUnauthorized,
+ expectedBody: "invalid",
+ },
+ {
+ name: "expired token returns 401",
+ authHeader: "Bearer " + generateExpiredToken(t, secret),
+ expectedStatus: http.StatusUnauthorized,
+ expectedBody: "expired",
+ },
+ {
+ name: "wrong audience returns 401",
+ authHeader: "Bearer " + generateTokenWithWrongAudience(t, secret),
+ expectedStatus: http.StatusUnauthorized,
+ expectedBody: "audience",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))
+ req.Header.Set("Content-Type", "application/json")
+ if tc.authHeader != "" {
+ req.Header.Set("Authorization", tc.authHeader)
+ }
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+
+ // Create server with auth
+ s := NewServer(nil, profile, secret)
+ handler := s.authMiddleware(func(c echo.Context) error {
+ return c.String(http.StatusOK, "success")
+ })
+
+ err := handler(c)
+ if err != nil {
+ // Echo error handler
+ e.HTTPErrorHandler(err, c)
+ }
+
+ require.Equal(t, tc.expectedStatus, rec.Code)
+ require.Contains(t, strings.ToLower(rec.Body.String()), strings.ToLower(tc.expectedBody))
+ })
+ }
+}
+
+func TestMCPAuthMiddlewareValidToken(t *testing.T) {
+ secret := "test-secret-key"
+ profile := &config.Profile{Mode: common.ReleaseModeDev}
+
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+generateValidToken(t, secret))
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+
+ // Create server with auth - note: we pass nil store since we're testing middleware only
+ // A full integration test would require a real store
+ s := NewServer(nil, profile, secret)
+ handler := s.authMiddleware(func(c echo.Context) error {
+ // Verify user email is set in context
+ email := c.Get("user_email")
+ require.NotNil(t, email)
+ require.Equal(t, "[email protected]", email)
+ return c.String(http.StatusOK, "success")
+ })
+
+ err := handler(c)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, rec.Code)
+}
+
+func generateValidToken(t *testing.T, secret string) string {
+ t.Helper()
+ claims := jwt.MapClaims{
+ "iss": "bytebase",
+ "sub": "[email protected]",
+ "aud": auth.OAuth2AccessTokenAudience,
+ "exp": time.Now().Add(time.Hour).Unix(),
+ "iat": time.Now().Unix(),
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ token.Header["kid"] = "v1"
+ tokenStr, err := token.SignedString([]byte(secret))
+ require.NoError(t, err)
+ return tokenStr
+}
+
+func generateExpiredToken(t *testing.T, secret string) string {
+ t.Helper()
+ claims := jwt.MapClaims{
+ "iss": "bytebase",
+ "sub": "[email protected]",
+ "aud": auth.OAuth2AccessTokenAudience,
+ "exp": time.Now().Add(-time.Hour).Unix(), // expired
+ "iat": time.Now().Add(-2 * time.Hour).Unix(),
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ token.Header["kid"] = "v1"
+ tokenStr, err := token.SignedString([]byte(secret))
+ require.NoError(t, err)
+ return tokenStr
+}
+
+func generateTokenWithWrongAudience(t *testing.T, secret string) string {
+ t.Helper()
+ claims := jwt.MapClaims{
+ "iss": "bytebase",
+ "sub": "[email protected]",
+ "aud": "wrong.audience",
+ "exp": time.Now().Add(time.Hour).Unix(),
+ "iat": time.Now().Unix(),
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ token.Header["kid"] = "v1"
+ tokenStr, err := token.SignedString([]byte(secret))
+ require.NoError(t, err)
+ return tokenStr
+}
diff --git a/backend/api/oauth2/authorize.go b/backend/api/oauth2/authorize.go
new file mode 100644
index 0000000000..bcacda529f
--- /dev/null
+++ b/backend/api/oauth2/authorize.go
@@ -0,0 +1,210 @@
+package oauth2
+
+import (
+ "fmt"
+ "net/http"
+ "net/url"
+ "strconv"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/labstack/echo/v4"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+func (s *Service) handleAuthorizeGet(c echo.Context) error {
+ ctx := c.Request().Context()
+
+ // Parse query parameters
+ responseType := c.QueryParam("response_type")
+ clientID := c.QueryParam("client_id")
+ redirectURI := c.QueryParam("redirect_uri")
+ state := c.QueryParam("state")
+ 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")
+ }
+ client, err := s.store.GetOAuth2Client(ctx, clientID)
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup client")
+ }
+ if client == nil {
+ 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")
+ }
+ if !validateRedirectURI(redirectURI, client.Config.RedirectUris) {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_redirect_uri", "redirect_uri not registered")
+ }
+
+ // Validate PKCE (required)
+ if codeChallenge == "" {
+ return oauth2ErrorRedirect(c, redirectURI, state, "invalid_request", "code_challenge is required")
+ }
+ if codeChallengeMethod != "S256" {
+ 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
+ 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),
+ url.QueryEscape(state),
+ url.QueryEscape(codeChallenge),
+ url.QueryEscape(codeChallengeMethod),
+ )
+ return c.Redirect(http.StatusFound, consentURL)
+}
+
+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")
+ codeChallenge := c.FormValue("code_challenge")
+ codeChallengeMethod := c.FormValue("code_challenge_method")
+ action := c.FormValue("action")
+
+ // Validate client
+ 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")
+ }
+
+ // Get current user from session
+ accessToken := getTokenFromEchoRequest(c)
+ if accessToken == "" {
+ return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "user not authenticated")
+ }
+
+ // Validate the access token and extract user email
+ claims := &jwt.RegisteredClaims{}
+ _, 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)
+ }
+ if kid, ok := t.Header["kid"].(string); ok {
+ if kid == "v1" {
+ return []byte(s.secret), nil
+ }
+ }
+ return nil, errors.Errorf("unexpected access token kid=%v", t.Header["kid"])
+ })
+ if err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "invalid session")
+ }
+
+ // Validate audience
+ if !audienceContains(claims.Audience, fmt.Sprintf(auth.AccessTokenAudienceFmt, common.ReleaseModeProd)) &&
+ !audienceContains(claims.Audience, fmt.Sprintf(auth.AccessTokenAudienceFmt, common.ReleaseModeDev)) {
+ return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "invalid token audience")
+ }
+
+ // Get user from claims
+ principalID, err := strconv.Atoi(claims.Subject)
+ if err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "invalid user ID")
+ }
+
+ user, err := s.store.GetUserByID(ctx, principalID)
+ if err != nil || user == nil {
+ 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,
+ CodeChallengeMethod: codeChallengeMethod,
+ }
+ if _, err := s.store.CreateOAuth2AuthorizationCode(ctx, &store.OAuth2AuthorizationCodeMessage{
+ Code: code,
+ ClientID: clientID,
+ UserID: user.ID,
+ Config: codeConfig,
+ ExpiresAt: time.Now().Add(authCodeExpiry),
+ }); err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to store code")
+ }
+
+ // Update client last active
+ _ = s.store.UpdateOAuth2ClientLastActiveAt(ctx, clientID)
+
+ // Build redirect URL with code
+ u, _ := url.Parse(redirectURI)
+ q := u.Query()
+ q.Set("code", code)
+ if state != "" {
+ 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))
+}
+
+// getTokenFromEchoRequest extracts the access token from an Echo request.
+func getTokenFromEchoRequest(c echo.Context) string {
+ // Check Authorization header first
+ authHeader := c.Request().Header.Get("Authorization")
+ if authHeader != "" {
+ if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
+ return authHeader[7:]
+ }
+ }
+
+ // Check HTTP cookies
+ cookie, err := c.Cookie(auth.AccessTokenCookieName)
+ if err == nil && cookie != nil {
+ return cookie.Value
+ }
+
+ return ""
+}
+
+// audienceContains checks if the audience claim contains the given token.
+func audienceContains(audience jwt.ClaimStrings, token string) bool {
+ for _, aud := range audience {
+ if aud == token {
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/api/oauth2/discovery.go b/backend/api/oauth2/discovery.go
new file mode 100644
index 0000000000..6b9ae28029
--- /dev/null
+++ b/backend/api/oauth2/discovery.go
@@ -0,0 +1,78 @@
+package oauth2
+
+import (
+ "fmt"
+ "net/http"
+ "strings"
+
+ "github.com/labstack/echo/v4"
+)
+
+type authorizationServerMetadata struct {
+ Issuer string `json:"issuer"`
+ AuthorizationEndpoint string `json:"authorization_endpoint"`
+ TokenEndpoint string `json:"token_endpoint"`
+ RegistrationEndpoint string `json:"registration_endpoint"`
+ RevocationEndpoint string `json:"revocation_endpoint"`
+ ResponseTypesSupported []string `json:"response_types_supported"`
+ GrantTypesSupported []string `json:"grant_types_supported"`
+ CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`
+ TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
+}
+
+// protectedResourceMetadata is per RFC 9728 OAuth 2.0 Protected Resource Metadata.
+type protectedResourceMetadata struct {
+ Resource string `json:"resource"`
+ AuthorizationServers []string `json:"authorization_servers"`
+ BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
+ ResourceSigningAlgSupported []string `json:"resource_signing_alg_values_supported,omitempty"`
+ ResourceDocumentation string `json:"resource_documentation,omitempty"`
+}
+
+// getBaseURL returns the base URL to use for OAuth2 endpoints.
+// It uses externalURL from profile/setting if configured, otherwise derives from the request.
+func (s *Service) getBaseURL(c echo.Context) string {
+ ctx := c.Request().Context()
+ if externalURL := s.getExternalURL(ctx); externalURL != "" {
+ return strings.TrimSuffix(externalURL, "/")
+ }
+ // Derive from request as fallback
+ req := c.Request()
+ scheme := "https"
+ if req.TLS == nil {
+ scheme = "http"
+ }
+ // Check X-Forwarded-Proto header for reverse proxy setups
+ if proto := req.Header.Get("X-Forwarded-Proto"); proto != "" {
+ scheme = proto
+ }
+ return fmt.Sprintf("%s://%s", scheme, req.Host)
+}
+
+func (s *Service) handleDiscovery(c echo.Context) error {
+ baseURL := s.getBaseURL(c)
+ metadata := &authorizationServerMetadata{
+ Issuer: baseURL,
+ AuthorizationEndpoint: fmt.Sprintf("%s/api/oauth2/authorize", baseURL),
+ TokenEndpoint: fmt.Sprintf("%s/api/oauth2/token", baseURL),
+ RegistrationEndpoint: fmt.Sprintf("%s/api/oauth2/register", baseURL),
+ RevocationEndpoint: fmt.Sprintf("%s/api/oauth2/revoke", baseURL),
+ ResponseTypesSupported: []string{"code"},
+ GrantTypesSupported: []string{"authorization_code", "refresh_token"},
+ CodeChallengeMethodsSupported: []string{"S256"},
+ TokenEndpointAuthMethodsSupported: []string{"none"},
+ }
+ return c.JSON(http.StatusOK, metadata)
+}
+
+// handleProtectedResourceMetadata returns RFC 9728 protected resource metadata.
+// This tells clients which authorization server protects this resource.
+func (s *Service) handleProtectedResourceMetadata(c echo.Context) error {
+ baseURL := s.getBaseURL(c)
+ metadata := &protectedResourceMetadata{
+ Resource: baseURL,
+ AuthorizationServers: []string{baseURL},
+ BearerMethodsSupported: []string{"header"},
+ }
+ return c.JSON(http.StatusOK, metadata)
+}
diff --git a/backend/api/oauth2/oauth2.go b/backend/api/oauth2/oauth2.go
new file mode 100644
index 0000000000..ebbc9526bc
--- /dev/null
+++ b/backend/api/oauth2/oauth2.go
@@ -0,0 +1,215 @@
+package oauth2
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/base64"
+ "html"
+ "net/http"
+ "net/url"
+ "slices"
+ "time"
+
+ "github.com/labstack/echo/v4"
+ "golang.org/x/crypto/bcrypt"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/config"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+const (
+ clientIDPrefix = "bb_oauth_"
+ clientSecretPrefix = "bb_secret_"
+ refreshTokenPrefix = "bb_refresh_"
+ authCodePrefix = "bb_code_"
+
+ authCodeExpiry = 10 * time.Minute
+ accessTokenExpiry = 1 * time.Hour
+ refreshTokenExpiry = 30 * 24 * time.Hour
+ clientInactiveExpiry = 30 * 24 * time.Hour
+)
+
+type Service struct {
+ store *store.Store
+ profile *config.Profile
+ secret string
+}
+
+func NewService(store *store.Store, profile *config.Profile, secret string) *Service {
+ return &Service{
+ store: store,
+ profile: profile,
+ secret: secret,
+ }
+}
+
+// getExternalURL returns the effective external URL from profile flag or workspace setting.
+func (s *Service) getExternalURL(ctx context.Context) string {
+ setting, err := s.store.GetWorkspaceProfileSetting(ctx)
+ if err != nil {
+ return s.profile.ExternalURL
+ }
+ return common.GetEffectiveExternalURL(s.profile.ExternalURL, setting.ExternalUrl)
+}
+
+func (s *Service) RegisterRoutes(e *echo.Echo) {
+ // .well-known endpoints must stay at root (RFC 8615)
+ 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)
+ // OAuth2 endpoints under /api prefix
+ 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)
+}
+
+// handleGetClient returns public client info for the consent page.
+func (s *Service) handleGetClient(c echo.Context) error {
+ ctx := c.Request().Context()
+ clientID := c.Param("clientID")
+
+ client, err := s.store.GetOAuth2Client(ctx, clientID)
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup client")
+ }
+ if client == nil {
+ return oauth2Error(c, http.StatusNotFound, "invalid_client", "client not found")
+ }
+
+ // Return only public info (no secret)
+ return c.JSON(http.StatusOK, map[string]any{
+ "client_id": client.ClientID,
+ "client_name": client.Config.ClientName,
+ "redirect_uris": client.Config.RedirectUris,
+ })
+}
+
+func generateRandomString(length int) (string, error) {
+ bytes := make([]byte, length)
+ if _, err := rand.Read(bytes); err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(bytes), nil
+}
+
+func generateClientID() (string, error) {
+ random, err := generateRandomString(24)
+ if err != nil {
+ return "", err
+ }
+ return clientIDPrefix + random, nil
+}
+
+func generateClientSecret() (string, error) {
+ random, err := generateRandomString(32)
+ if err != nil {
+ return "", err
+ }
+ return clientSecretPrefix + random, nil
+}
+
+func generateAuthCode() (string, error) {
+ random, err := generateRandomString(32)
+ if err != nil {
+ return "", err
+ }
+ return authCodePrefix + random, nil
+}
+
+func generateRefreshToken() (string, error) {
+ random, err := generateRandomString(32)
+ if err != nil {
+ return "", err
+ }
+ return refreshTokenPrefix + random, nil
+}
+
+func hashSecret(secret string) (string, error) {
+ hash, err := bcrypt.GenerateFromPassword([]byte(secret), bcrypt.DefaultCost)
+ if err != nil {
+ return "", err
+ }
+ return string(hash), nil
+}
+
+func verifySecret(hash, secret string) bool {
+ return bcrypt.CompareHashAndPassword([]byte(hash), []byte(secret)) == nil
+}
+
+func hashToken(token string) string {
+ hash := sha256.Sum256([]byte(token))
+ return base64.RawURLEncoding.EncodeToString(hash[:])
+}
+
+func verifyPKCE(codeVerifier, codeChallenge, method string) bool {
+ if method != "S256" {
+ return false
+ }
+ // RFC 7636: code_verifier must be 43-128 characters
+ if len(codeVerifier) < 43 || len(codeVerifier) > 128 {
+ return false
+ }
+ hash := sha256.Sum256([]byte(codeVerifier))
+ computed := base64.RawURLEncoding.EncodeToString(hash[:])
+ // Use constant-time comparison to prevent timing attacks
+ return subtle.ConstantTimeCompare([]byte(computed), []byte(codeChallenge)) == 1
+}
+
+func validateRedirectURI(uri string, allowedURIs []string) bool {
+ return slices.Contains(allowedURIs, uri)
+}
+
+func isLocalhostURI(uri string) bool {
+ parsed, err := url.Parse(uri)
+ if err != nil {
+ return false
+ }
+ host := parsed.Hostname()
+ return host == "localhost" || host == "127.0.0.1" || host == "::1"
+}
+
+func oauth2Error(c echo.Context, statusCode int, errorCode, description string) error {
+ return c.JSON(statusCode, map[string]string{
+ "error": errorCode,
+ "error_description": description,
+ })
+}
+
+func oauth2ErrorRedirect(c echo.Context, redirectURI, state, errorCode, description string) error {
+ u, _ := url.Parse(redirectURI)
+ q := u.Query()
+ q.Set("error", errorCode)
+ q.Set("error_description", description)
+ if state != "" {
+ q.Set("state", state)
+ }
+ u.RawQuery = q.Encode()
+ // Return HTML page that redirects to callback URL
+ // This avoids CSP form-action restrictions
+ return c.HTML(http.StatusOK, buildRedirectHTML(u.String()))
+}
+
+// buildRedirectHTML creates an HTML page that redirects to the given URL.
+// This is used to work around CSP form-action restrictions.
+func buildRedirectHTML(redirectURL string) string {
+ // HTML escape the URL for safe embedding
+ escaped := html.EscapeString(redirectURL)
+ return `<!DOCTYPE html>
+<html>
+<head>
+<meta http-equiv="refresh" content="0;url=` + escaped + `">
+<title>Redirecting...</title>
+</head>
+<body>
+<p>Redirecting to application...</p>
+<noscript><a href="` + escaped + `">Click here to continue</a></noscript>
+</body>
+</html>`
+}
diff --git a/backend/api/oauth2/register.go b/backend/api/oauth2/register.go
new file mode 100644
index 0000000000..8290f04c31
--- /dev/null
+++ b/backend/api/oauth2/register.go
@@ -0,0 +1,119 @@
+package oauth2
+
+import (
+ "net/http"
+ "net/url"
+ "slices"
+
+ "github.com/labstack/echo/v4"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+type clientRegistrationRequest struct {
+ ClientName string `json:"client_name"`
+ RedirectURIs []string `json:"redirect_uris"`
+ GrantTypes []string `json:"grant_types"`
+ TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
+}
+
+type clientRegistrationResponse struct {
+ ClientID string `json:"client_id"`
+ ClientSecret string `json:"client_secret,omitempty"`
+ ClientName string `json:"client_name"`
+ RedirectURIs []string `json:"redirect_uris"`
+ GrantTypes []string `json:"grant_types"`
+ TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
+}
+
+func (s *Service) handleRegister(c echo.Context) error {
+ ctx := c.Request().Context()
+
+ var req clientRegistrationRequest
+ if err := c.Bind(&req); err != nil {
+ 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")
+ }
+
+ // Validate redirect_uris
+ if len(req.RedirectURIs) == 0 {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_client_metadata", "redirect_uris is required")
+ }
+ for _, uri := range req.RedirectURIs {
+ parsed, err := url.Parse(uri)
+ if err != nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_redirect_uri", "invalid redirect URI format")
+ }
+ // Require HTTPS except for localhost
+ if parsed.Scheme != "https" && !isLocalhostURI(uri) {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_redirect_uri", "redirect URI must use HTTPS (except localhost)")
+ }
+ }
+
+ // Validate grant_types (default to authorization_code)
+ if len(req.GrantTypes) == 0 {
+ req.GrantTypes = []string{"authorization_code"}
+ }
+ allowedGrantTypes := []string{"authorization_code", "refresh_token"}
+ for _, gt := range req.GrantTypes {
+ if !slices.Contains(allowedGrantTypes, gt) {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_client_metadata", "unsupported grant_type: "+gt)
+ }
+ }
+
+ // Validate token_endpoint_auth_method (default to none for public clients)
+ if req.TokenEndpointAuthMethod == "" {
+ req.TokenEndpointAuthMethod = "none"
+ }
+ allowedAuthMethods := []string{"none"}
+ if !slices.Contains(allowedAuthMethods, req.TokenEndpointAuthMethod) {
+ 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
+ config := &storepb.OAuth2ClientConfig{
+ ClientName: req.ClientName,
+ RedirectUris: req.RedirectURIs,
+ GrantTypes: req.GrantTypes,
+ TokenEndpointAuthMethod: req.TokenEndpointAuthMethod,
+ }
+ if _, err := s.store.CreateOAuth2Client(ctx, &store.OAuth2ClientMessage{
+ ClientID: clientID,
+ ClientSecretHash: secretHash,
+ Config: config,
+ }); err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to create client")
+ }
+
+ resp := &clientRegistrationResponse{
+ ClientID: clientID,
+ ClientName: req.ClientName,
+ RedirectURIs: req.RedirectURIs,
+ GrantTypes: req.GrantTypes,
+ TokenEndpointAuthMethod: req.TokenEndpointAuthMethod,
+ }
+ // Only include client_secret for confidential clients
+ if req.TokenEndpointAuthMethod != "none" {
+ resp.ClientSecret = clientSecret
+ }
+ return c.JSON(http.StatusCreated, resp)
+}
diff --git a/backend/api/oauth2/revoke.go b/backend/api/oauth2/revoke.go
new file mode 100644
index 0000000000..df959b8353
--- /dev/null
+++ b/backend/api/oauth2/revoke.go
@@ -0,0 +1,76 @@
+package oauth2
+
+import (
+ "encoding/base64"
+ "net/http"
+ "strings"
+
+ "github.com/labstack/echo/v4"
+)
+
+type revokeRequest struct {
+ Token string `form:"token"`
+ TokenTypeHint string `form:"token_type_hint"`
+ ClientID string `form:"client_id"`
+ ClientSecret string `form:"client_secret"`
+}
+
+func (s *Service) handleRevoke(c echo.Context) error {
+ ctx := c.Request().Context()
+
+ var req revokeRequest
+ if err := c.Bind(&req); err != nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "failed to parse request")
+ }
+
+ // Authenticate client
+ clientID, clientSecret := extractRevokeClientCredentials(c, &req)
+ if clientID == "" {
+ return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "client authentication required")
+ }
+
+ client, err := s.store.GetOAuth2Client(ctx, clientID)
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup client")
+ }
+ if client == nil {
+ return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "client not found")
+ }
+
+ // Verify client credentials based on token_endpoint_auth_method
+ // Public clients (token_endpoint_auth_method: none) don't have secrets
+ if client.Config.TokenEndpointAuthMethod != "none" {
+ if !verifySecret(client.ClientSecretHash, clientSecret) {
+ return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "invalid client credentials")
+ }
+ }
+
+ // Validate token
+ if req.Token == "" {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "token is required")
+ }
+
+ // Try to revoke as refresh token
+ // RFC 7009 says to return 200 even if token is invalid, so we ignore errors
+ tokenHash := hashToken(req.Token)
+ _ = s.store.DeleteOAuth2RefreshToken(ctx, tokenHash)
+
+ // Return success (RFC 7009: always return 200)
+ return c.NoContent(http.StatusOK)
+}
+
+func extractRevokeClientCredentials(c echo.Context, req *revokeRequest) (clientID, clientSecret string) {
+ // Try Basic auth first
+ authHeader := c.Request().Header.Get("Authorization")
+ if strings.HasPrefix(authHeader, "Basic ") {
+ decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHeader, "Basic "))
+ if err == nil {
+ parts := strings.SplitN(string(decoded), ":", 2)
+ if len(parts) == 2 {
+ return parts[0], parts[1]
+ }
+ }
+ }
+ // Fall back to form params
+ return req.ClientID, req.ClientSecret
+}
diff --git a/backend/api/oauth2/token.go b/backend/api/oauth2/token.go
new file mode 100644
index 0000000000..64259d8bbc
--- /dev/null
+++ b/backend/api/oauth2/token.go
@@ -0,0 +1,246 @@
+package oauth2
+
+import (
+ "encoding/base64"
+ "net/http"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/labstack/echo/v4"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+type tokenRequest struct {
+ GrantType string `form:"grant_type"`
+ Code string `form:"code"`
+ RedirectURI string `form:"redirect_uri"`
+ CodeVerifier string `form:"code_verifier"`
+ RefreshToken string `form:"refresh_token"`
+ ClientID string `form:"client_id"`
+ ClientSecret string `form:"client_secret"`
+}
+
+type tokenResponse struct {
+ AccessToken string `json:"access_token"`
+ TokenType string `json:"token_type"`
+ ExpiresIn int `json:"expires_in"`
+ RefreshToken string `json:"refresh_token,omitempty"`
+}
+
+func (s *Service) handleToken(c echo.Context) error {
+ ctx := c.Request().Context()
+
+ var req tokenRequest
+ if err := c.Bind(&req); err != nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "failed to parse request")
+ }
+
+ // Authenticate client
+ clientID, clientSecret := s.extractClientCredentials(c, &req)
+ if clientID == "" {
+ return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "client authentication required")
+ }
+
+ client, err := s.store.GetOAuth2Client(ctx, clientID)
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup client")
+ }
+ if client == nil {
+ return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "client not found")
+ }
+
+ // Verify client credentials based on token_endpoint_auth_method
+ // Public clients (token_endpoint_auth_method: none) don't have secrets
+ if client.Config.TokenEndpointAuthMethod != "none" {
+ if !verifySecret(client.ClientSecretHash, clientSecret) {
+ return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "invalid client credentials")
+ }
+ }
+
+ // Handle grant types
+ switch req.GrantType {
+ case "authorization_code":
+ return s.handleAuthorizationCodeGrant(c, client, &req)
+ case "refresh_token":
+ return s.handleRefreshTokenGrant(c, client, &req)
+ default:
+ return oauth2Error(c, http.StatusBadRequest, "unsupported_grant_type", "grant_type must be authorization_code or refresh_token")
+ }
+}
+
+func (*Service) extractClientCredentials(c echo.Context, req *tokenRequest) (clientID, clientSecret string) {
+ // Try Basic auth first
+ authHeader := c.Request().Header.Get("Authorization")
+ if strings.HasPrefix(authHeader, "Basic ") {
+ decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHeader, "Basic "))
+ if err == nil {
+ parts := strings.SplitN(string(decoded), ":", 2)
+ if len(parts) == 2 {
+ return parts[0], parts[1]
+ }
+ }
+ }
+ // Fall back to form params
+ return req.ClientID, req.ClientSecret
+}
+
+func (s *Service) handleAuthorizationCodeGrant(c echo.Context, client *store.OAuth2ClientMessage, req *tokenRequest) error {
+ ctx := c.Request().Context()
+
+ // Validate grant type is allowed
+ if !slices.Contains(client.Config.GrantTypes, "authorization_code") {
+ return oauth2Error(c, http.StatusBadRequest, "unauthorized_client", "client not authorized for authorization_code grant")
+ }
+
+ // Validate code
+ if req.Code == "" {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "code is required")
+ }
+
+ authCode, err := s.store.GetOAuth2AuthorizationCode(ctx, req.Code)
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup code")
+ }
+ if authCode == nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "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")
+ }
+
+ // Validate code not expired
+ if time.Now().After(authCode.ExpiresAt) {
+ // Delete expired code
+ _ = s.store.DeleteOAuth2AuthorizationCode(ctx, req.Code)
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "code has expired")
+ }
+
+ // Validate redirect_uri matches
+ if req.RedirectURI != authCode.Config.RedirectUri {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "redirect_uri mismatch")
+ }
+
+ // Validate PKCE
+ if req.CodeVerifier == "" {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "code_verifier is required")
+ }
+ if !verifyPKCE(req.CodeVerifier, authCode.Config.CodeChallenge, authCode.Config.CodeChallengeMethod) {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid code_verifier")
+ }
+
+ // Delete code after all validations pass (single use)
+ _ = s.store.DeleteOAuth2AuthorizationCode(ctx, req.Code)
+
+ // Get user
+ user, err := s.store.GetUserByID(ctx, authCode.UserID)
+ if err != nil || user == nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "user not found")
+ }
+
+ // Generate tokens
+ return s.issueTokens(c, client, user.ID, user.Email)
+}
+
+func (s *Service) handleRefreshTokenGrant(c echo.Context, client *store.OAuth2ClientMessage, req *tokenRequest) error {
+ ctx := c.Request().Context()
+
+ // Validate grant type is allowed
+ if !slices.Contains(client.Config.GrantTypes, "refresh_token") {
+ return oauth2Error(c, http.StatusBadRequest, "unauthorized_client", "client not authorized for refresh_token grant")
+ }
+
+ // Validate refresh token
+ if req.RefreshToken == "" {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "refresh_token is required")
+ }
+
+ tokenHash := hashToken(req.RefreshToken)
+ refreshToken, err := s.store.GetOAuth2RefreshToken(ctx, tokenHash)
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup refresh token")
+ }
+ if refreshToken == nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid refresh token")
+ }
+
+ // Validate token belongs to this client BEFORE deleting
+ // This prevents DoS where attacker with stolen token invalidates it for legitimate client
+ if refreshToken.ClientID != client.ClientID {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "refresh token was not issued to this client")
+ }
+
+ // Validate not expired
+ if time.Now().After(refreshToken.ExpiresAt) {
+ // Delete expired token
+ _ = s.store.DeleteOAuth2RefreshToken(ctx, tokenHash)
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "refresh token has expired")
+ }
+
+ // Delete token after validations pass (single use, will issue new one)
+ _ = s.store.DeleteOAuth2RefreshToken(ctx, tokenHash)
+
+ // Get user
+ user, err := s.store.GetUserByID(ctx, refreshToken.UserID)
+ if err != nil || user == nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "user not found")
+ }
+
+ // Issue new tokens
+ return s.issueTokens(c, client, user.ID, user.Email)
+}
+
+func (s *Service) issueTokens(c echo.Context, client *store.OAuth2ClientMessage, userID int, userEmail string) error {
+ ctx := c.Request().Context()
+
+ // Generate access token (JWT)
+ now := time.Now()
+ claims := jwt.MapClaims{
+ "iss": "bytebase",
+ "sub": userEmail,
+ "aud": auth.OAuth2AccessTokenAudience,
+ "exp": now.Add(accessTokenExpiry).Unix(),
+ "iat": now.Unix(),
+ "client_id": client.ClientID,
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ accessToken, err := token.SignedString([]byte(s.secret))
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to generate access token")
+ }
+
+ // Generate refresh token if allowed
+ var refreshTokenStr string
+ if slices.Contains(client.Config.GrantTypes, "refresh_token") {
+ refreshTokenStr, err = generateRefreshToken()
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to generate refresh token")
+ }
+
+ // Store refresh token
+ if _, err := s.store.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{
+ TokenHash: hashToken(refreshTokenStr),
+ ClientID: client.ClientID,
+ UserID: userID,
+ ExpiresAt: now.Add(refreshTokenExpiry),
+ }); err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to store refresh token")
+ }
+ }
+
+ // Update client last active
+ _ = s.store.UpdateOAuth2ClientLastActiveAt(ctx, client.ClientID)
+
+ return c.JSON(http.StatusOK, &tokenResponse{
+ AccessToken: accessToken,
+ TokenType: "Bearer",
+ ExpiresIn: int(accessTokenExpiry.Seconds()),
+ RefreshToken: refreshTokenStr,
+ })
+}
diff --git a/backend/generated-go/store/oauth2.pb.go b/backend/generated-go/store/oauth2.pb.go
new file mode 100644
index 0000000000..4740968fb7
--- /dev/null
+++ b/backend/generated-go/store/oauth2.pb.go
@@ -0,0 +1,217 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// protoc-gen-go v1.36.10
+// protoc (unknown)
+// source: store/oauth2.proto
+
+package store
+
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ reflect "reflect"
+ sync "sync"
+ unsafe "unsafe"
+)
+
+const (
+ // Verify that this generated code is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+ // Verify that runtime/protoimpl is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+type OAuth2ClientConfig struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ ClientName string `protobuf:"bytes,1,opt,name=client_name,json=clientName,proto3" json:"client_name,omitempty"`
+ RedirectUris []string `protobuf:"bytes,2,rep,name=redirect_uris,json=redirectUris,proto3" json:"redirect_uris,omitempty"`
+ GrantTypes []string `protobuf:"bytes,3,rep,name=grant_types,json=grantTypes,proto3" json:"grant_types,omitempty"`
+ TokenEndpointAuthMethod string `protobuf:"bytes,4,opt,name=token_endpoint_auth_method,json=tokenEndpointAuthMethod,proto3" json:"token_endpoint_auth_method,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *OAuth2ClientConfig) Reset() {
+ *x = OAuth2ClientConfig{}
+ mi := &file_store_oauth2_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *OAuth2ClientConfig) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*OAuth2ClientConfig) ProtoMessage() {}
+
+func (x *OAuth2ClientConfig) ProtoReflect() protoreflect.Message {
+ mi := &file_store_oauth2_proto_msgTypes[0]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use OAuth2ClientConfig.ProtoReflect.Descriptor instead.
+func (*OAuth2ClientConfig) Descriptor() ([]byte, []int) {
+ return file_store_oauth2_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *OAuth2ClientConfig) GetClientName() string {
+ if x != nil {
+ return x.ClientName
+ }
+ return ""
+}
+
+func (x *OAuth2ClientConfig) GetRedirectUris() []string {
+ if x != nil {
+ return x.RedirectUris
+ }
+ return nil
+}
+
+func (x *OAuth2ClientConfig) GetGrantTypes() []string {
+ if x != nil {
+ return x.GrantTypes
+ }
+ return nil
+}
+
+func (x *OAuth2ClientConfig) GetTokenEndpointAuthMethod() string {
+ if x != nil {
+ return x.TokenEndpointAuthMethod
+ }
+ return ""
+}
+
+type OAuth2AuthorizationCodeConfig struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ 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
+}
+
+func (x *OAuth2AuthorizationCodeConfig) Reset() {
+ *x = OAuth2AuthorizationCodeConfig{}
+ mi := &file_store_oauth2_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *OAuth2AuthorizationCodeConfig) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*OAuth2AuthorizationCodeConfig) ProtoMessage() {}
+
+func (x *OAuth2AuthorizationCodeConfig) ProtoReflect() protoreflect.Message {
+ mi := &file_store_oauth2_proto_msgTypes[1]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use OAuth2AuthorizationCodeConfig.ProtoReflect.Descriptor instead.
+func (*OAuth2AuthorizationCodeConfig) Descriptor() ([]byte, []int) {
+ return file_store_oauth2_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *OAuth2AuthorizationCodeConfig) GetRedirectUri() string {
+ if x != nil {
+ return x.RedirectUri
+ }
+ return ""
+}
+
+func (x *OAuth2AuthorizationCodeConfig) GetCodeChallenge() string {
+ if x != nil {
+ return x.CodeChallenge
+ }
+ return ""
+}
+
+func (x *OAuth2AuthorizationCodeConfig) GetCodeChallengeMethod() string {
+ if x != nil {
+ return x.CodeChallengeMethod
+ }
+ return ""
+}
+
+var File_store_oauth2_proto protoreflect.FileDescriptor
+
+const file_store_oauth2_proto_rawDesc = "" +
+ "\n" +
+ "\x12store/oauth2.proto\x12\x0ebytebase.store\"\xb8\x01\n" +
+ "\x12OAuth2ClientConfig\x12\x1f\n" +
+ "\vclient_name\x18\x01 \x01(\tR\n" +
+ "clientName\x12#\n" +
+ "\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" +
+ "\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" +
+ "\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 (
+ file_store_oauth2_proto_rawDescOnce sync.Once
+ file_store_oauth2_proto_rawDescData []byte
+)
+
+func file_store_oauth2_proto_rawDescGZIP() []byte {
+ file_store_oauth2_proto_rawDescOnce.Do(func() {
+ file_store_oauth2_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_store_oauth2_proto_rawDesc), len(file_store_oauth2_proto_rawDesc)))
+ })
+ return file_store_oauth2_proto_rawDescData
+}
+
+var file_store_oauth2_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
+var file_store_oauth2_proto_goTypes = []any{
+ (*OAuth2ClientConfig)(nil), // 0: bytebase.store.OAuth2ClientConfig
+ (*OAuth2AuthorizationCodeConfig)(nil), // 1: bytebase.store.OAuth2AuthorizationCodeConfig
+}
+var file_store_oauth2_proto_depIdxs = []int32{
+ 0, // [0:0] is the sub-list for method output_type
+ 0, // [0:0] is the sub-list for method input_type
+ 0, // [0:0] is the sub-list for extension type_name
+ 0, // [0:0] is the sub-list for extension extendee
+ 0, // [0:0] is the sub-list for field type_name
+}
+
+func init() { file_store_oauth2_proto_init() }
+func file_store_oauth2_proto_init() {
+ if File_store_oauth2_proto != nil {
+ return
+ }
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_oauth2_proto_rawDesc), len(file_store_oauth2_proto_rawDesc)),
+ NumEnums: 0,
+ NumMessages: 2,
+ NumExtensions: 0,
+ NumServices: 0,
+ },
+ GoTypes: file_store_oauth2_proto_goTypes,
+ DependencyIndexes: file_store_oauth2_proto_depIdxs,
+ MessageInfos: file_store_oauth2_proto_msgTypes,
+ }.Build()
+ File_store_oauth2_proto = out.File
+ file_store_oauth2_proto_goTypes = nil
+ file_store_oauth2_proto_depIdxs = nil
+}
diff --git a/backend/generated-go/store/oauth2_equal.pb.go b/backend/generated-go/store/oauth2_equal.pb.go
new file mode 100644
index 0000000000..5a3f0ae458
--- /dev/null
+++ b/backend/generated-go/store/oauth2_equal.pb.go
@@ -0,0 +1,55 @@
+// Code generated by protoc-gen-equal-go. DO NOT EDIT.
+// source: store/oauth2.proto
+
+package store
+
+func (x *OAuth2ClientConfig) Equal(y *OAuth2ClientConfig) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.ClientName != y.ClientName {
+ return false
+ }
+ if len(x.RedirectUris) != len(y.RedirectUris) {
+ return false
+ }
+ for i := 0; i < len(x.RedirectUris); i++ {
+ if x.RedirectUris[i] != y.RedirectUris[i] {
+ return false
+ }
+ }
+ if len(x.GrantTypes) != len(y.GrantTypes) {
+ return false
+ }
+ for i := 0; i < len(x.GrantTypes); i++ {
+ if x.GrantTypes[i] != y.GrantTypes[i] {
+ return false
+ }
+ }
+ if x.TokenEndpointAuthMethod != y.TokenEndpointAuthMethod {
+ return false
+ }
+ return true
+}
+
+func (x *OAuth2AuthorizationCodeConfig) Equal(y *OAuth2AuthorizationCodeConfig) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.RedirectUri != y.RedirectUri {
+ return false
+ }
+ if x.CodeChallenge != y.CodeChallenge {
+ return false
+ }
+ if x.CodeChallengeMethod != y.CodeChallengeMethod {
+ return false
+ }
+ return true
+}
diff --git a/backend/migrator/migration/3.13/0024##add_oauth2_tables.sql b/backend/migrator/migration/3.13/0024##add_oauth2_tables.sql
new file mode 100644
index 0000000000..d519665568
--- /dev/null
+++ b/backend/migrator/migration/3.13/0024##add_oauth2_tables.sql
@@ -0,0 +1,25 @@
+CREATE TABLE oauth2_client (
+ client_id TEXT PRIMARY KEY,
+ client_secret_hash TEXT NOT NULL,
+ config JSONB NOT NULL,
+ last_active_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE TABLE oauth2_authorization_code (
+ code TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL REFERENCES oauth2_client(client_id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES principal(id),
+ config JSONB NOT NULL,
+ expires_at TIMESTAMPTZ NOT NULL
+);
+
+CREATE TABLE oauth2_refresh_token (
+ token_hash TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL REFERENCES oauth2_client(client_id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES principal(id),
+ expires_at TIMESTAMPTZ NOT NULL
+);
+
+CREATE INDEX idx_oauth2_authorization_code_expires_at ON oauth2_authorization_code(expires_at);
+CREATE INDEX idx_oauth2_refresh_token_expires_at ON oauth2_refresh_token(expires_at);
+CREATE INDEX idx_oauth2_client_last_active_at ON oauth2_client(last_active_at);
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sql
index 73c765711a..f163e0cdf3 100644
--- a/backend/migrator/migration/LATEST.sql
+++ b/backend/migrator/migration/LATEST.sql
@@ -577,3 +577,30 @@ VALUES (
-- Grant workspace member role to allUsers
INSERT INTO policy (resource_type, resource, type, payload, inherit_from_parent, enforce)
VALUES ('WORKSPACE', '', 'IAM', '{"bindings":[{"role":"roles/workspaceMember","members":["allUsers"]}]}', FALSE, TRUE);
+
+-- OAuth2 tables
+CREATE TABLE oauth2_client (
+ client_id TEXT PRIMARY KEY,
+ client_secret_hash TEXT NOT NULL,
+ config JSONB NOT NULL,
+ last_active_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE TABLE oauth2_authorization_code (
+ code TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL REFERENCES oauth2_client(client_id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES principal(id),
+ config JSONB NOT NULL,
+ expires_at TIMESTAMPTZ NOT NULL
+);
+
+CREATE TABLE oauth2_refresh_token (
+ token_hash TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL REFERENCES oauth2_client(client_id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES principal(id),
+ expires_at TIMESTAMPTZ NOT NULL
+);
+
+CREATE INDEX idx_oauth2_authorization_code_expires_at ON oauth2_authorization_code(expires_at);
+CREATE INDEX idx_oauth2_refresh_token_expires_at ON oauth2_refresh_token(expires_at);
+CREATE INDEX idx_oauth2_client_last_active_at ON oauth2_client(last_active_at);
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index ffb1b58c8d..3478d26d2c 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -12,7 +12,7 @@ import (
func TestLatestVersion(t *testing.T) {
files, err := getSortedVersionedFiles()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.13.23"), *files[len(files)-1].version)
+ require.Equal(t, semver.MustParse("3.13.24"), *files[len(files)-1].version)
}
func TestVersionUnique(t *testing.T) {
diff --git a/backend/server/echo_routes.go b/backend/server/echo_routes.go
index fa27c4743e..6f4b7f552c 100644
--- a/backend/server/echo_routes.go
+++ b/backend/server/echo_routes.go
@@ -14,6 +14,8 @@ import (
directorysync "github.com/bytebase/bytebase/backend/api/directory-sync"
"github.com/bytebase/bytebase/backend/api/lsp"
+ "github.com/bytebase/bytebase/backend/api/mcp"
+ "github.com/bytebase/bytebase/backend/api/oauth2"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/config"
@@ -23,6 +25,8 @@ func configureEchoRouters(
e *echo.Echo,
lspServer *lsp.Server,
directorySyncServer *directorysync.Service,
+ oauth2Service *oauth2.Service,
+ mcpServer *mcp.Server,
profile *config.Profile,
) {
e.Use(recoverMiddleware)
@@ -53,9 +57,6 @@ func configureEchoRouters(
},
}))
- // Embed frontend.
- embedFrontend(e)
-
e.HideBanner = true
e.HidePort = true
@@ -77,6 +78,15 @@ func configureEchoRouters(
hookGroup := e.Group(webhookAPIPrefix)
scimGroup := hookGroup.Group(scimAPIPrefix)
directorySyncServer.RegisterDirectorySyncRoutes(scimGroup)
+
+ // OAuth2 server.
+ oauth2Service.RegisterRoutes(e)
+
+ // MCP server.
+ mcpServer.RegisterRoutes(e)
+
+ // Embed frontend (must be last to serve as fallback for SPA routes).
+ embedFrontend(e)
}
func recoverMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
diff --git a/backend/server/server.go b/backend/server/server.go
index c25a0900c2..22891d93cc 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -17,6 +17,8 @@ import (
directorysync "github.com/bytebase/bytebase/backend/api/directory-sync"
"github.com/bytebase/bytebase/backend/api/lsp"
+ "github.com/bytebase/bytebase/backend/api/mcp"
+ "github.com/bytebase/bytebase/backend/api/oauth2"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/config"
@@ -216,11 +218,13 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
s.lspServer = lsp.NewServer(s.store, profile, secret, s.stateCfg, s.iamManager, s.licenseService)
directorySyncServer := directorysync.NewService(s.store, s.licenseService, s.iamManager, profile)
+ oauth2Service := oauth2.NewService(stores, profile, secret)
+ mcpServer := mcp.NewServer(stores, profile, secret)
if err := configureGrpcRouters(ctx, s.echoServer, s.store, sheetManager, s.dbFactory, s.licenseService, s.profile, s.metricReporter, s.stateCfg, s.schemaSyncer, s.webhookManager, s.iamManager, secret, s.sampleInstanceManager); err != nil {
return nil, errors.Wrapf(err, "failed to configure gRPC routers")
}
- configureEchoRouters(s.echoServer, s.lspServer, directorySyncServer, profile)
+ configureEchoRouters(s.echoServer, s.lspServer, directorySyncServer, oauth2Service, mcpServer, profile)
serverStarted = true
return s, nil
diff --git a/backend/server/server_frontend_embed.go b/backend/server/server_frontend_embed.go
index fdfe6d29fd..a0d7b581e1 100644
--- a/backend/server/server_frontend_embed.go
+++ b/backend/server/server_frontend_embed.go
@@ -106,6 +106,6 @@ func embedFrontend(e *echo.Echo) {
// defaultAPIRequestSkipper is echo skipper for api requests.
func defaultAPIRequestSkipper(c echo.Context) bool {
- path := c.Path()
- return common.HasPrefixes(path, "/api", "/v1", webhookAPIPrefix)
+ path := c.Request().URL.Path
+ return common.HasPrefixes(path, "/api", "/v1", "/.well-known", webhookAPIPrefix)
}
diff --git a/backend/store/oauth2_authorization_code.go b/backend/store/oauth2_authorization_code.go
new file mode 100644
index 0000000000..8ca28befca
--- /dev/null
+++ b/backend/store/oauth2_authorization_code.go
@@ -0,0 +1,109 @@
+package store
+
+import (
+ "context"
+ "database/sql"
+ "time"
+
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/qb"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+type OAuth2AuthorizationCodeMessage struct {
+ Code string
+ ClientID string
+ UserID int
+ Config *storepb.OAuth2AuthorizationCodeConfig
+ ExpiresAt time.Time
+}
+
+func (s *Store) CreateOAuth2AuthorizationCode(ctx context.Context, create *OAuth2AuthorizationCodeMessage) (*OAuth2AuthorizationCodeMessage, error) {
+ configBytes, err := protojson.Marshal(create.Config)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to marshal config")
+ }
+
+ q := qb.Q().Space(`
+ INSERT INTO oauth2_authorization_code (code, client_id, user_id, config, expires_at)
+ VALUES (?, ?, ?, ?, ?)
+ `, create.Code, create.ClientID, create.UserID, configBytes, create.ExpiresAt)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return nil, errors.Wrap(err, "failed to create OAuth2 authorization code")
+ }
+ return create, nil
+}
+
+func (s *Store) GetOAuth2AuthorizationCode(ctx context.Context, code string) (*OAuth2AuthorizationCodeMessage, error) {
+ q := qb.Q().Space(`
+ SELECT code, client_id, user_id, config, expires_at
+ FROM oauth2_authorization_code
+ WHERE code = ?
+ `, code)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ msg := &OAuth2AuthorizationCodeMessage{}
+ var configBytes []byte
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(
+ &msg.Code, &msg.ClientID, &msg.UserID, &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.Config = &storepb.OAuth2AuthorizationCodeConfig{}
+ if err := common.ProtojsonUnmarshaler.Unmarshal(configBytes, msg.Config); err != nil {
+ return nil, errors.Wrap(err, "failed to unmarshal config")
+ }
+ return msg, nil
+}
+
+func (s *Store) DeleteOAuth2AuthorizationCode(ctx context.Context, code string) error {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_authorization_code
+ WHERE code = ?
+ `, code)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to delete OAuth2 authorization code")
+ }
+ return nil
+}
+
+func (s *Store) DeleteExpiredOAuth2AuthorizationCodes(ctx context.Context) (int64, error) {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_authorization_code
+ WHERE expires_at < NOW()
+ `)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return 0, err
+ }
+
+ result, err := s.GetDB().ExecContext(ctx, query, args...)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to delete expired OAuth2 authorization codes")
+ }
+ return result.RowsAffected()
+}
diff --git a/backend/store/oauth2_client.go b/backend/store/oauth2_client.go
new file mode 100644
index 0000000000..996c749544
--- /dev/null
+++ b/backend/store/oauth2_client.go
@@ -0,0 +1,152 @@
+package store
+
+import (
+ "context"
+ "time"
+
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/qb"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+type OAuth2ClientMessage struct {
+ ClientID string
+ ClientSecretHash string
+ Config *storepb.OAuth2ClientConfig
+ LastActiveAt time.Time
+}
+
+type FindOAuth2ClientMessage struct {
+ ClientID *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")
+ }
+
+ q := qb.Q().Space(`
+ INSERT INTO oauth2_client (client_id, client_secret_hash, config, last_active_at)
+ VALUES (?, ?, ?, NOW())
+ RETURNING last_active_at
+ `, create.ClientID, create.ClientSecretHash, configBytes)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(&create.LastActiveAt); err != nil {
+ return nil, errors.Wrap(err, "failed to create OAuth2 client")
+ }
+ return create, nil
+}
+
+func (s *Store) GetOAuth2Client(ctx context.Context, clientID string) (*OAuth2ClientMessage, error) {
+ clients, err := s.ListOAuth2Clients(ctx, &FindOAuth2ClientMessage{ClientID: &clientID})
+ 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) {
+ q := qb.Q().Space(`
+ SELECT client_id, client_secret_hash, config, last_active_at
+ FROM oauth2_client
+ WHERE TRUE
+ `)
+
+ if v := find.ClientID; v != nil {
+ q.And("client_id = ?", *v)
+ }
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := s.GetDB().QueryContext(ctx, query, args...)
+ 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.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")
+ }
+ clients = append(clients, client)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, errors.Wrap(err, "failed to iterate OAuth2 clients")
+ }
+ return clients, nil
+}
+
+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 = ?
+ `, clientID)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to update OAuth2 client last active at")
+ }
+ return nil
+}
+
+func (s *Store) DeleteOAuth2Client(ctx context.Context, clientID string) error {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_client
+ WHERE client_id = ?
+ `, clientID)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to delete OAuth2 client")
+ }
+ return nil
+}
+
+func (s *Store) DeleteExpiredOAuth2Clients(ctx context.Context, expireBefore time.Time) (int64, error) {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_client
+ WHERE last_active_at < ?
+ `, expireBefore)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return 0, err
+ }
+
+ result, err := s.GetDB().ExecContext(ctx, query, args...)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to delete expired OAuth2 clients")
+ }
+ return result.RowsAffected()
+}
diff --git a/backend/store/oauth2_refresh_token.go b/backend/store/oauth2_refresh_token.go
new file mode 100644
index 0000000000..04eb3a1086
--- /dev/null
+++ b/backend/store/oauth2_refresh_token.go
@@ -0,0 +1,111 @@
+package store
+
+import (
+ "context"
+ "database/sql"
+ "time"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common/qb"
+)
+
+type OAuth2RefreshTokenMessage struct {
+ TokenHash string
+ ClientID string
+ UserID int
+ ExpiresAt time.Time
+}
+
+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_id, expires_at)
+ VALUES (?, ?, ?, ?)
+ `, create.TokenHash, create.ClientID, create.UserID, create.ExpiresAt)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return nil, errors.Wrap(err, "failed to create OAuth2 refresh token")
+ }
+ return create, nil
+}
+
+func (s *Store) GetOAuth2RefreshToken(ctx context.Context, tokenHash string) (*OAuth2RefreshTokenMessage, error) {
+ q := qb.Q().Space(`
+ SELECT token_hash, client_id, user_id, expires_at
+ FROM oauth2_refresh_token
+ WHERE token_hash = ?
+ `, tokenHash)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ msg := &OAuth2RefreshTokenMessage{}
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(
+ &msg.TokenHash, &msg.ClientID, &msg.UserID, &msg.ExpiresAt,
+ ); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, errors.Wrap(err, "failed to get OAuth2 refresh token")
+ }
+ return msg, nil
+}
+
+func (s *Store) DeleteOAuth2RefreshToken(ctx context.Context, tokenHash string) error {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_refresh_token
+ WHERE token_hash = ?
+ `, tokenHash)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to delete OAuth2 refresh token")
+ }
+ return nil
+}
+
+func (s *Store) DeleteOAuth2RefreshTokensByUserAndClient(ctx context.Context, userID int, clientID string) error {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_refresh_token
+ WHERE user_id = ? AND client_id = ?
+ `, userID, clientID)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to delete OAuth2 refresh tokens")
+ }
+ return nil
+}
+
+func (s *Store) DeleteExpiredOAuth2RefreshTokens(ctx context.Context) (int64, error) {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_refresh_token
+ WHERE expires_at < NOW()
+ `)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return 0, err
+ }
+
+ result, err := s.GetDB().ExecContext(ctx, query, args...)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to delete expired OAuth2 refresh tokens")
+ }
+ return result.RowsAffected()
+}
diff --git a/docs/plans/2025-12-11-oauth2-server-design.md b/docs/plans/2025-12-11-oauth2-server-design.md
new file mode 100644
index 0000000000..6b3e959e3b
--- /dev/null
+++ b/docs/plans/2025-12-11-oauth2-server-design.md
@@ -0,0 +1,313 @@
+# OAuth2 Server Design for Bytebase
+
+## Overview
+
+Add an OAuth2 Authorization Server to Bytebase enabling third-party applications (starting with MCP servers) to authenticate users and access Bytebase APIs on their behalf.
+
+**Key decisions:**
+
+- Authorization Code + PKCE flow (OAuth 2.1 compliant)
+- Dynamic Client Registration for automated onboarding
+- Tokens inherit full user permissions (no scope filtering)
+- JWT access tokens with existing revocation cache
+- Standard HTTP endpoints (`/oauth2/*`)
+- All state persisted in database
+- Clients expire after 30 days of inactivity
+
+## Architecture
+
+```
+┌─────────────────┐ ┌──────────────────────────────────────────┐
+│ Third-Party │ │ Bytebase │
+│ App (MCP) │ │ │
+│ │ │ ┌─────────────────────────────────────┐ │
+│ 1. Register ───────────▶│ POST /oauth2/register │ │
+│ client │ │ │ (Dynamic Client Registration) │ │
+│ │ │ └─────────────────────────────────────┘ │
+│ │ │ │
+│ 2. Redirect ───────────▶│ GET /oauth2/authorize │ │
+│ user │ │ │ (Shows consent, redirects back) │ │
+│ │ │ └─────────────────────────────────────┘ │
+│ │ │ │
+│ 3. Exchange ───────────▶│ POST /oauth2/token │ │
+│ code │ │ │ (Returns JWT access + refresh) │ │
+│ │ │ └─────────────────────────────────────┘ │
+│ │ │ │
+│ 4. Call API ───────────▶│ Existing gRPC/REST APIs │ │
+│ Bearer token│ │ │ (Auth interceptor validates JWT) │ │
+└─────────────────┘ └──────────────────────────────────────────┘
+```
+
+## Endpoints
+
+| Endpoint | Method | Purpose |
+|----------|--------|---------|
+| `/.well-known/oauth-authorization-server` | GET | Server metadata discovery (RFC 8414) |
+| `/oauth2/register` | POST | Dynamic Client Registration (RFC 7591) |
+| `/oauth2/authorize` | GET | Authorization endpoint - shows consent UI |
+| `/oauth2/authorize` | POST | User grants/denies consent |
+| `/oauth2/token` | POST | Token endpoint - code exchange, refresh |
+| `/oauth2/revoke` | POST | Token revocation (RFC 7009) |
+
+**Discovery metadata** (`/.well-known/oauth-authorization-server`):
+
+```json
+{
+ "issuer": "https://bytebase.example.com",
+ "authorization_endpoint": "https://bytebase.example.com/oauth2/authorize",
+ "token_endpoint": "https://bytebase.example.com/oauth2/token",
+ "registration_endpoint": "https://bytebase.example.com/oauth2/register",
+ "revocation_endpoint": "https://bytebase.example.com/oauth2/revoke",
+ "response_types_supported": ["code"],
+ "grant_types_supported": ["authorization_code", "refresh_token"],
+ "code_challenge_methods_supported": ["S256"],
+ "token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"]
+}
+```
+
+**Not included initially** (can add later):
+
+- `/oauth2/introspect` - Token introspection for external resource servers
+- `/oauth2/userinfo` - OIDC userinfo endpoint
+- `/oauth2/jwks` - Public keys (if switching to asymmetric signing)
+
+## Authorization Flow (Authorization Code + PKCE)
+
+**1. Client Registration** (one-time)
+
+```
+POST /oauth2/register
+Content-Type: application/json
+
+{
+ "client_name": "My MCP Server",
+ "redirect_uris": ["http://localhost:3000/callback"],
+ "grant_types": ["authorization_code", "refresh_token"],
+ "token_endpoint_auth_method": "client_secret_basic"
+}
+
+Response:
+{
+ "client_id": "bb_oauth_xxxxxxxx",
+ "client_secret": "bb_secret_xxxxxxxx",
+ "client_name": "My MCP Server",
+ "redirect_uris": ["http://localhost:3000/callback"],
+ ...
+}
+```
+
+**2. Authorization Request**
+
+```
+GET /oauth2/authorize?
+ response_type=code&
+ client_id=bb_oauth_xxxxxxxx&
+ redirect_uri=http://localhost:3000/callback&
+ state=random_state&
+ code_challenge=BASE64URL(SHA256(verifier))&
+ code_challenge_method=S256
+```
+
+User sees consent screen, logs in if needed, approves.
+
+**3. Authorization Response**
+
+```
+HTTP/1.1 302 Found
+Location: http://localhost:3000/callback?code=AUTH_CODE&state=random_state
+```
+
+**4. Token Exchange**
+
+```
+POST /oauth2/token
+Content-Type: application/x-www-form-urlencoded
+Authorization: Basic base64(client_id:client_secret)
+
+grant_type=authorization_code&
+code=AUTH_CODE&
+redirect_uri=http://localhost:3000/callback&
+code_verifier=ORIGINAL_VERIFIER
+```
+
+**5. Token Response**
+
+```json
+{
+ "access_token": "eyJhbG...",
+ "token_type": "Bearer",
+ "expires_in": 3600,
+ "refresh_token": "bb_refresh_xxxxxxxx"
+}
+```
+
+## Token Design
+
+**Access Token (JWT)**
+
+Same structure as existing Bytebase access tokens for consistency:
+
+```json
+{
+ "iss": "bytebase",
+ "sub": "users/[email protected]",
+ "aud": "bb.oauth2.access",
+ "exp": 1702300800,
+ "iat": 1702297200,
+ "jti": "unique-token-id",
+ "client_id": "bb_oauth_xxxxxxxx"
+}
+```
+
+Key points:
+
+- Signed with HS256 using existing signing key
+- `aud` distinguishes OAuth2 tokens from regular session tokens (`bb.user.access` vs `bb.oauth2.access`)
+- `client_id` claim identifies which OAuth2 client issued the request
+- `jti` enables revocation tracking in existing LRU cache
+- Default expiry: 1 hour
+
+**Refresh Token**
+
+Opaque token stored in database:
+
+- Format: `bb_refresh_xxxxxxxx` (random, not JWT)
+- Linked to user and client
+- Longer expiry: 30 days
+- Single-use: rotated on each refresh
+
+**Validation**
+
+The existing auth interceptor in `backend/api/auth/auth.go` will be extended to:
+
+1. Accept `bb.oauth2.access` audience
+2. Look up user from `sub` claim (same as today)
+3. Check revocation cache using `jti`
+4. User's full permissions apply (no scope filtering)
+
+## Database Schema
+
+**`oauth2_client`**
+
+```sql
+CREATE TABLE oauth2_client (
+ client_id TEXT PRIMARY KEY,
+ client_secret_hash TEXT NOT NULL,
+ config JSONB NOT NULL,
+ last_active_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+```
+
+**`oauth2_authorization_code`**
+
+```sql
+CREATE TABLE oauth2_authorization_code (
+ code TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL REFERENCES oauth2_client(client_id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES principal(id),
+ config JSONB NOT NULL,
+ expires_at TIMESTAMPTZ NOT NULL
+);
+```
+
+**`oauth2_refresh_token`**
+
+```sql
+CREATE TABLE oauth2_refresh_token (
+ token_hash TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL REFERENCES oauth2_client(client_id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES principal(id),
+ expires_at TIMESTAMPTZ NOT NULL
+);
+```
+
+**Proto definitions:**
+
+```protobuf
+message OAuth2ClientConfig {
+ string client_name = 1;
+ repeated string redirect_uris = 2;
+ repeated string grant_types = 3;
+ string token_endpoint_auth_method = 4;
+}
+
+message OAuth2AuthorizationCodeConfig {
+ string redirect_uri = 1;
+ string code_challenge = 2;
+ string code_challenge_method = 3;
+}
+```
+
+**Cleanup:**
+
+- Background job deletes clients where `last_active_at < now() - 30 days`
+- `last_active_at` updated when authorization code is created or token is issued/refreshed
+- Expired authorization codes and refresh tokens cleaned up based on `expires_at`
+
+## Backend Structure
+
+```
+backend/
+├── api/
+│ └── oauth2/
+│ ├── oauth2.go # HTTP handlers for /oauth2/* endpoints
+│ ├── discovery.go # /.well-known/oauth-authorization-server
+│ ├── register.go # POST /oauth2/register (DCR)
+│ ├── authorize.go # GET/POST /oauth2/authorize
+│ ├── token.go # POST /oauth2/token
+│ └── revoke.go # POST /oauth2/revoke
+├── store/
+│ ├── oauth2_client.go # CRUD for oauth2_client
+│ ├── oauth2_authorization_code.go
+│ └── oauth2_refresh_token.go
+└── proto/
+ └── store/
+ └── oauth2.proto # OAuth2ClientConfig, OAuth2AuthorizationCodeConfig
+```
+
+**Registration in server:**
+
+- Mount OAuth2 handlers on the HTTP mux alongside existing routes
+- Handlers use existing `store.Store` for database access
+- Reuse existing auth interceptor logic for validating user sessions during `/oauth2/authorize`
+
+## Security Considerations
+
+**PKCE (required)**
+
+- `code_challenge_method` must be `S256` (reject `plain`)
+- Validate `code_verifier` matches `code_challenge` during token exchange
+
+**Client secrets**
+
+- Store bcrypt hash, never plaintext
+- Generate with sufficient entropy (32+ bytes, base64 encoded)
+
+**Redirect URI validation**
+
+- Exact match against registered URIs (no wildcards)
+- Must use HTTPS in production (allow `http://localhost` for development)
+
+**Token security**
+
+- Authorization codes: single-use, 10-minute expiry
+- Refresh tokens: single-use (rotate on refresh), 30-day expiry
+- Access tokens: 1-hour expiry
+
+**Rate limiting**
+
+- Apply existing rate limiting to `/oauth2/token` endpoint
+- Prevent brute-force on authorization codes
+
+**CSRF protection**
+
+- `state` parameter required on authorization requests
+- Validate `state` matches on callback
+
+## Future Enhancements
+
+- Admin UI for managing OAuth2 clients
+- Token introspection endpoint for external resource servers
+- OIDC userinfo endpoint
+- Asymmetric signing (RS256) with JWKS endpoint
+- Scope-based permission filtering
diff --git a/docs/plans/2025-12-11-oauth2-server-impl.md b/docs/plans/2025-12-11-oauth2-server-impl.md
new file mode 100644
index 0000000000..2fcf70b116
--- /dev/null
+++ b/docs/plans/2025-12-11-oauth2-server-impl.md
@@ -0,0 +1,1712 @@
+# OAuth2 Server Implementation Plan
+
+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
+
+**Goal:** Add OAuth2 Authorization Server to Bytebase enabling third-party apps (MCP servers) to authenticate users via Authorization Code + PKCE flow.
+
+**Architecture:** Standard HTTP endpoints at `/oauth2/*` using Echo framework. JWT access tokens reusing existing auth infrastructure. All state in PostgreSQL with proto-defined JSONB configs.
+
+**Tech Stack:** Go, Echo framework, PostgreSQL, protobuf/protojson, bcrypt, crypto/rand
+
+**Design Doc:** `docs/plans/2025-12-11-oauth2-server-design.md`
+
+---
+
+## Task 1: Proto Definitions
+
+**Files:**
+- Create: `proto/store/oauth2.proto`
+
+**Step 1: Create proto file**
+
+```protobuf
+syntax = "proto3";
+
+package bytebase.store;
+
+option go_package = "generated-go/store";
+
+message OAuth2ClientConfig {
+ string client_name = 1;
+ repeated string redirect_uris = 2;
+ repeated string grant_types = 3;
+ string token_endpoint_auth_method = 4;
+}
+
+message OAuth2AuthorizationCodeConfig {
+ string redirect_uri = 1;
+ string code_challenge = 2;
+ string code_challenge_method = 3;
+}
+```
+
+**Step 2: Generate Go code**
+
+Run: `cd proto && buf generate`
+
+**Step 3: Verify generation**
+
+Run: `ls backend/generated-go/store/oauth2.pb.go`
+Expected: File exists
+
+**Step 4: Commit**
+
+```bash
+but commit <branch> -m "proto: add OAuth2 store proto definitions"
+```
+
+---
+
+## Task 2: Database Migration
+
+**Files:**
+- Create: `backend/migrator/migration/3.13/0020##add_oauth2_tables.sql`
+- Modify: `backend/migrator/migration/LATEST.sql`
+- Modify: `backend/migrator/migrator_test.go:15`
+
+**Step 1: Create migration file**
+
+```sql
+CREATE TABLE oauth2_client (
+ client_id TEXT PRIMARY KEY,
+ client_secret_hash TEXT NOT NULL,
+ config JSONB NOT NULL,
+ last_active_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE TABLE oauth2_authorization_code (
+ code TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL REFERENCES oauth2_client(client_id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES principal(id),
+ config JSONB NOT NULL,
+ expires_at TIMESTAMPTZ NOT NULL
+);
+
+CREATE TABLE oauth2_refresh_token (
+ token_hash TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL REFERENCES oauth2_client(client_id) ON DELETE CASCADE,
+ user_id INTEGER NOT NULL REFERENCES principal(id),
+ expires_at TIMESTAMPTZ NOT NULL
+);
+
+CREATE INDEX idx_oauth2_authorization_code_expires_at ON oauth2_authorization_code(expires_at);
+CREATE INDEX idx_oauth2_refresh_token_expires_at ON oauth2_refresh_token(expires_at);
+CREATE INDEX idx_oauth2_client_last_active_at ON oauth2_client(last_active_at);
+```
+
+**Step 2: Update LATEST.sql**
+
+Add the same table definitions to `backend/migrator/migration/LATEST.sql` after the existing table definitions.
+
+**Step 3: Update migrator_test.go**
+
+Change line 15 from:
+```go
+require.Equal(t, semver.MustParse("3.13.19"), *files[len(files)-1].version)
+```
+to:
+```go
+require.Equal(t, semver.MustParse("3.13.20"), *files[len(files)-1].version)
+```
+
+**Step 4: Run migration tests**
+
+Run: `go test -v -count=1 github.com/bytebase/bytebase/backend/migrator -run ^TestLatestVersion$`
+Expected: PASS
+
+Run: `go test -v -count=1 github.com/bytebase/bytebase/backend/migrator -run ^TestVersionUnique$`
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+but commit <branch> -m "migration: add OAuth2 tables"
+```
+
+---
+
+## Task 3: Store Layer - OAuth2 Client
+
+**Files:**
+- Create: `backend/store/oauth2_client.go`
+
+**Step 1: Create store file**
+
+```go
+package store
+
+import (
+ "context"
+ "time"
+
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/qb"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+type OAuth2ClientMessage struct {
+ ClientID string
+ ClientSecretHash string
+ Config *storepb.OAuth2ClientConfig
+ LastActiveAt time.Time
+}
+
+type FindOAuth2ClientMessage struct {
+ ClientID *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")
+ }
+
+ q := qb.Q().Space(`
+ INSERT INTO oauth2_client (client_id, client_secret_hash, config, last_active_at)
+ VALUES (?, ?, ?, NOW())
+ RETURNING last_active_at
+ `, create.ClientID, create.ClientSecretHash, configBytes)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(&create.LastActiveAt); err != nil {
+ return nil, errors.Wrap(err, "failed to create OAuth2 client")
+ }
+ return create, nil
+}
+
+func (s *Store) GetOAuth2Client(ctx context.Context, clientID string) (*OAuth2ClientMessage, error) {
+ clients, err := s.ListOAuth2Clients(ctx, &FindOAuth2ClientMessage{ClientID: &clientID})
+ 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) {
+ q := qb.Q().Space(`
+ SELECT client_id, client_secret_hash, config, last_active_at
+ FROM oauth2_client
+ WHERE TRUE
+ `)
+
+ if v := find.ClientID; v != nil {
+ q.And("client_id = ?", *v)
+ }
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := s.GetDB().QueryContext(ctx, query, args...)
+ 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.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")
+ }
+ clients = append(clients, client)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, errors.Wrap(err, "failed to iterate OAuth2 clients")
+ }
+ return clients, nil
+}
+
+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 = ?
+ `, clientID)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to update OAuth2 client last active at")
+ }
+ return nil
+}
+
+func (s *Store) DeleteOAuth2Client(ctx context.Context, clientID string) error {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_client
+ WHERE client_id = ?
+ `, clientID)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to delete OAuth2 client")
+ }
+ return nil
+}
+
+func (s *Store) DeleteExpiredOAuth2Clients(ctx context.Context, expireBefore time.Time) (int64, error) {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_client
+ WHERE last_active_at < ?
+ `, expireBefore)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return 0, err
+ }
+
+ result, err := s.GetDB().ExecContext(ctx, query, args...)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to delete expired OAuth2 clients")
+ }
+ return result.RowsAffected()
+}
+```
+
+**Step 2: Lint**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/store/oauth2_client.go`
+Expected: No errors (or only unrelated warnings)
+
+**Step 3: Commit**
+
+```bash
+but commit <branch> -m "store: add OAuth2 client CRUD"
+```
+
+---
+
+## Task 4: Store Layer - Authorization Code
+
+**Files:**
+- Create: `backend/store/oauth2_authorization_code.go`
+
+**Step 1: Create store file**
+
+```go
+package store
+
+import (
+ "context"
+ "time"
+
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/qb"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+type OAuth2AuthorizationCodeMessage struct {
+ Code string
+ ClientID string
+ UserID int
+ Config *storepb.OAuth2AuthorizationCodeConfig
+ ExpiresAt time.Time
+}
+
+func (s *Store) CreateOAuth2AuthorizationCode(ctx context.Context, create *OAuth2AuthorizationCodeMessage) (*OAuth2AuthorizationCodeMessage, error) {
+ configBytes, err := protojson.Marshal(create.Config)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to marshal config")
+ }
+
+ q := qb.Q().Space(`
+ INSERT INTO oauth2_authorization_code (code, client_id, user_id, config, expires_at)
+ VALUES (?, ?, ?, ?, ?)
+ `, create.Code, create.ClientID, create.UserID, configBytes, create.ExpiresAt)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return nil, errors.Wrap(err, "failed to create OAuth2 authorization code")
+ }
+ return create, nil
+}
+
+func (s *Store) GetOAuth2AuthorizationCode(ctx context.Context, code string) (*OAuth2AuthorizationCodeMessage, error) {
+ q := qb.Q().Space(`
+ SELECT code, client_id, user_id, config, expires_at
+ FROM oauth2_authorization_code
+ WHERE code = ?
+ `, code)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ msg := &OAuth2AuthorizationCodeMessage{}
+ var configBytes []byte
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(
+ &msg.Code, &msg.ClientID, &msg.UserID, &configBytes, &msg.ExpiresAt,
+ ); err != nil {
+ if err.Error() == "sql: no rows in result set" {
+ return nil, nil
+ }
+ return nil, errors.Wrap(err, "failed to get OAuth2 authorization code")
+ }
+
+ msg.Config = &storepb.OAuth2AuthorizationCodeConfig{}
+ if err := common.ProtojsonUnmarshaler.Unmarshal(configBytes, msg.Config); err != nil {
+ return nil, errors.Wrap(err, "failed to unmarshal config")
+ }
+ return msg, nil
+}
+
+func (s *Store) DeleteOAuth2AuthorizationCode(ctx context.Context, code string) error {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_authorization_code
+ WHERE code = ?
+ `, code)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to delete OAuth2 authorization code")
+ }
+ return nil
+}
+
+func (s *Store) DeleteExpiredOAuth2AuthorizationCodes(ctx context.Context) (int64, error) {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_authorization_code
+ WHERE expires_at < NOW()
+ `)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return 0, err
+ }
+
+ result, err := s.GetDB().ExecContext(ctx, query, args...)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to delete expired OAuth2 authorization codes")
+ }
+ return result.RowsAffected()
+}
+```
+
+**Step 2: Lint**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/store/oauth2_authorization_code.go`
+Expected: No errors
+
+**Step 3: Commit**
+
+```bash
+but commit <branch> -m "store: add OAuth2 authorization code CRUD"
+```
+
+---
+
+## Task 5: Store Layer - Refresh Token
+
+**Files:**
+- Create: `backend/store/oauth2_refresh_token.go`
+
+**Step 1: Create store file**
+
+```go
+package store
+
+import (
+ "context"
+ "time"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common/qb"
+)
+
+type OAuth2RefreshTokenMessage struct {
+ TokenHash string
+ ClientID string
+ UserID int
+ ExpiresAt time.Time
+}
+
+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_id, expires_at)
+ VALUES (?, ?, ?, ?)
+ `, create.TokenHash, create.ClientID, create.UserID, create.ExpiresAt)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return nil, errors.Wrap(err, "failed to create OAuth2 refresh token")
+ }
+ return create, nil
+}
+
+func (s *Store) GetOAuth2RefreshToken(ctx context.Context, tokenHash string) (*OAuth2RefreshTokenMessage, error) {
+ q := qb.Q().Space(`
+ SELECT token_hash, client_id, user_id, expires_at
+ FROM oauth2_refresh_token
+ WHERE token_hash = ?
+ `, tokenHash)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ msg := &OAuth2RefreshTokenMessage{}
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(
+ &msg.TokenHash, &msg.ClientID, &msg.UserID, &msg.ExpiresAt,
+ ); err != nil {
+ if err.Error() == "sql: no rows in result set" {
+ return nil, nil
+ }
+ return nil, errors.Wrap(err, "failed to get OAuth2 refresh token")
+ }
+ return msg, nil
+}
+
+func (s *Store) DeleteOAuth2RefreshToken(ctx context.Context, tokenHash string) error {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_refresh_token
+ WHERE token_hash = ?
+ `, tokenHash)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to delete OAuth2 refresh token")
+ }
+ return nil
+}
+
+func (s *Store) DeleteOAuth2RefreshTokensByUserAndClient(ctx context.Context, userID int, clientID string) error {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_refresh_token
+ WHERE user_id = ? AND client_id = ?
+ `, userID, clientID)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to delete OAuth2 refresh tokens")
+ }
+ return nil
+}
+
+func (s *Store) DeleteExpiredOAuth2RefreshTokens(ctx context.Context) (int64, error) {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_refresh_token
+ WHERE expires_at < NOW()
+ `)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return 0, err
+ }
+
+ result, err := s.GetDB().ExecContext(ctx, query, args...)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to delete expired OAuth2 refresh tokens")
+ }
+ return result.RowsAffected()
+}
+```
+
+**Step 2: Lint**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/store/oauth2_refresh_token.go`
+Expected: No errors
+
+**Step 3: Commit**
+
+```bash
+but commit <branch> -m "store: add OAuth2 refresh token CRUD"
+```
+
+---
+
+## Task 6: OAuth2 Handler - Utilities
+
+**Files:**
+- Create: `backend/api/oauth2/oauth2.go`
+
+**Step 1: Create main handler file with utilities**
+
+```go
+package oauth2
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "fmt"
+ "net/http"
+ "net/url"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/labstack/echo/v4"
+ "golang.org/x/crypto/bcrypt"
+
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+const (
+ clientIDPrefix = "bb_oauth_"
+ clientSecretPrefix = "bb_secret_"
+ refreshTokenPrefix = "bb_refresh_"
+ authCodePrefix = "bb_code_"
+
+ authCodeExpiry = 10 * time.Minute
+ accessTokenExpiry = 1 * time.Hour
+ refreshTokenExpiry = 30 * 24 * time.Hour
+ clientInactiveExpiry = 30 * 24 * time.Hour
+)
+
+type Service struct {
+ store *store.Store
+ secret string
+ externalURL string
+}
+
+func NewService(store *store.Store, secret, externalURL string) *Service {
+ return &Service{
+ store: store,
+ secret: secret,
+ externalURL: strings.TrimSuffix(externalURL, "/"),
+ }
+}
+
+func (s *Service) RegisterRoutes(g *echo.Group) {
+ g.GET("/.well-known/oauth-authorization-server", s.handleDiscovery)
+ g.POST("/oauth2/register", s.handleRegister)
+ g.GET("/oauth2/authorize", s.handleAuthorizeGet)
+ g.POST("/oauth2/authorize", s.handleAuthorizePost)
+ g.POST("/oauth2/token", s.handleToken)
+ g.POST("/oauth2/revoke", s.handleRevoke)
+}
+
+func generateRandomString(length int) (string, error) {
+ bytes := make([]byte, length)
+ if _, err := rand.Read(bytes); err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(bytes), nil
+}
+
+func generateClientID() (string, error) {
+ random, err := generateRandomString(24)
+ if err != nil {
+ return "", err
+ }
+ return clientIDPrefix + random, nil
+}
+
+func generateClientSecret() (string, error) {
+ random, err := generateRandomString(32)
+ if err != nil {
+ return "", err
+ }
+ return clientSecretPrefix + random, nil
+}
+
+func generateAuthCode() (string, error) {
+ random, err := generateRandomString(32)
+ if err != nil {
+ return "", err
+ }
+ return authCodePrefix + random, nil
+}
+
+func generateRefreshToken() (string, error) {
+ random, err := generateRandomString(32)
+ if err != nil {
+ return "", err
+ }
+ return refreshTokenPrefix + random, nil
+}
+
+func hashSecret(secret string) (string, error) {
+ hash, err := bcrypt.GenerateFromPassword([]byte(secret), bcrypt.DefaultCost)
+ if err != nil {
+ return "", err
+ }
+ return string(hash), nil
+}
+
+func verifySecret(hash, secret string) bool {
+ return bcrypt.CompareHashAndPassword([]byte(hash), []byte(secret)) == nil
+}
+
+func hashToken(token string) string {
+ hash := sha256.Sum256([]byte(token))
+ return base64.RawURLEncoding.EncodeToString(hash[:])
+}
+
+func verifyPKCE(codeVerifier, codeChallenge, method string) bool {
+ if method != "S256" {
+ return false
+ }
+ hash := sha256.Sum256([]byte(codeVerifier))
+ computed := base64.RawURLEncoding.EncodeToString(hash[:])
+ return computed == codeChallenge
+}
+
+func validateRedirectURI(uri string, allowedURIs []string) bool {
+ return slices.Contains(allowedURIs, uri)
+}
+
+func isLocalhostURI(uri string) bool {
+ parsed, err := url.Parse(uri)
+ if err != nil {
+ return false
+ }
+ host := parsed.Hostname()
+ return host == "localhost" || host == "127.0.0.1" || host == "::1"
+}
+
+func oauth2Error(c echo.Context, statusCode int, errorCode, description string) error {
+ return c.JSON(statusCode, map[string]string{
+ "error": errorCode,
+ "error_description": description,
+ })
+}
+
+func oauth2ErrorRedirect(c echo.Context, redirectURI, state, errorCode, description string) error {
+ u, _ := url.Parse(redirectURI)
+ q := u.Query()
+ q.Set("error", errorCode)
+ q.Set("error_description", description)
+ if state != "" {
+ q.Set("state", state)
+ }
+ u.RawQuery = q.Encode()
+ return c.Redirect(http.StatusFound, u.String())
+}
+
+func (s *Service) issuer() string {
+ return s.externalURL
+}
+
+func (s *Service) authorizationEndpoint() string {
+ return fmt.Sprintf("%s/oauth2/authorize", s.externalURL)
+}
+
+func (s *Service) tokenEndpoint() string {
+ return fmt.Sprintf("%s/oauth2/token", s.externalURL)
+}
+
+func (s *Service) registrationEndpoint() string {
+ return fmt.Sprintf("%s/oauth2/register", s.externalURL)
+}
+
+func (s *Service) revocationEndpoint() string {
+ return fmt.Sprintf("%s/oauth2/revoke", s.externalURL)
+}
+```
+
+**Step 2: Lint**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/api/oauth2/oauth2.go`
+Expected: No errors
+
+**Step 3: Commit**
+
+```bash
+but commit <branch> -m "api: add OAuth2 service with utilities"
+```
+
+---
+
+## Task 7: OAuth2 Handler - Discovery
+
+**Files:**
+- Create: `backend/api/oauth2/discovery.go`
+
+**Step 1: Create discovery handler**
+
+```go
+package oauth2
+
+import (
+ "net/http"
+
+ "github.com/labstack/echo/v4"
+)
+
+type authorizationServerMetadata struct {
+ Issuer string `json:"issuer"`
+ AuthorizationEndpoint string `json:"authorization_endpoint"`
+ TokenEndpoint string `json:"token_endpoint"`
+ RegistrationEndpoint string `json:"registration_endpoint"`
+ RevocationEndpoint string `json:"revocation_endpoint"`
+ ResponseTypesSupported []string `json:"response_types_supported"`
+ GrantTypesSupported []string `json:"grant_types_supported"`
+ CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`
+ TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
+}
+
+func (s *Service) handleDiscovery(c echo.Context) error {
+ metadata := &authorizationServerMetadata{
+ Issuer: s.issuer(),
+ AuthorizationEndpoint: s.authorizationEndpoint(),
+ TokenEndpoint: s.tokenEndpoint(),
+ RegistrationEndpoint: s.registrationEndpoint(),
+ RevocationEndpoint: s.revocationEndpoint(),
+ ResponseTypesSupported: []string{"code"},
+ GrantTypesSupported: []string{"authorization_code", "refresh_token"},
+ CodeChallengeMethodsSupported: []string{"S256"},
+ TokenEndpointAuthMethodsSupported: []string{"client_secret_basic", "client_secret_post"},
+ }
+ return c.JSON(http.StatusOK, metadata)
+}
+```
+
+**Step 2: Lint**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/api/oauth2/discovery.go`
+Expected: No errors
+
+**Step 3: Commit**
+
+```bash
+but commit <branch> -m "api: add OAuth2 discovery endpoint"
+```
+
+---
+
+## Task 8: OAuth2 Handler - Dynamic Client Registration
+
+**Files:**
+- Create: `backend/api/oauth2/register.go`
+
+**Step 1: Create DCR handler**
+
+```go
+package oauth2
+
+import (
+ "net/http"
+ "net/url"
+ "slices"
+
+ "github.com/labstack/echo/v4"
+
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+type clientRegistrationRequest struct {
+ ClientName string `json:"client_name"`
+ RedirectURIs []string `json:"redirect_uris"`
+ GrantTypes []string `json:"grant_types"`
+ TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
+}
+
+type clientRegistrationResponse struct {
+ ClientID string `json:"client_id"`
+ ClientSecret string `json:"client_secret"`
+ ClientName string `json:"client_name"`
+ RedirectURIs []string `json:"redirect_uris"`
+ GrantTypes []string `json:"grant_types"`
+ TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
+}
+
+func (s *Service) handleRegister(c echo.Context) error {
+ ctx := c.Request().Context()
+
+ var req clientRegistrationRequest
+ if err := c.Bind(&req); err != nil {
+ 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")
+ }
+
+ // Validate redirect_uris
+ if len(req.RedirectURIs) == 0 {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_client_metadata", "redirect_uris is required")
+ }
+ for _, uri := range req.RedirectURIs {
+ parsed, err := url.Parse(uri)
+ if err != nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_redirect_uri", "invalid redirect URI format")
+ }
+ // Require HTTPS except for localhost
+ if parsed.Scheme != "https" && !isLocalhostURI(uri) {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_redirect_uri", "redirect URI must use HTTPS (except localhost)")
+ }
+ }
+
+ // Validate grant_types (default to authorization_code)
+ if len(req.GrantTypes) == 0 {
+ req.GrantTypes = []string{"authorization_code"}
+ }
+ allowedGrantTypes := []string{"authorization_code", "refresh_token"}
+ for _, gt := range req.GrantTypes {
+ if !slices.Contains(allowedGrantTypes, gt) {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_client_metadata", "unsupported grant_type: "+gt)
+ }
+ }
+
+ // Validate token_endpoint_auth_method (default to client_secret_basic)
+ if req.TokenEndpointAuthMethod == "" {
+ req.TokenEndpointAuthMethod = "client_secret_basic"
+ }
+ allowedAuthMethods := []string{"client_secret_basic", "client_secret_post"}
+ if !slices.Contains(allowedAuthMethods, req.TokenEndpointAuthMethod) {
+ 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
+ config := &storepb.OAuth2ClientConfig{
+ ClientName: req.ClientName,
+ RedirectUris: req.RedirectURIs,
+ GrantTypes: req.GrantTypes,
+ TokenEndpointAuthMethod: req.TokenEndpointAuthMethod,
+ }
+ if _, err := s.store.CreateOAuth2Client(ctx, &store.OAuth2ClientMessage{
+ ClientID: clientID,
+ ClientSecretHash: secretHash,
+ Config: config,
+ }); err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to create client")
+ }
+
+ return c.JSON(http.StatusCreated, &clientRegistrationResponse{
+ ClientID: clientID,
+ ClientSecret: clientSecret,
+ ClientName: req.ClientName,
+ RedirectURIs: req.RedirectURIs,
+ GrantTypes: req.GrantTypes,
+ TokenEndpointAuthMethod: req.TokenEndpointAuthMethod,
+ })
+}
+```
+
+**Step 2: Add missing import**
+
+Add `"github.com/bytebase/bytebase/backend/store"` to imports.
+
+**Step 3: Lint**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/api/oauth2/register.go`
+Expected: No errors
+
+**Step 4: Commit**
+
+```bash
+but commit <branch> -m "api: add OAuth2 dynamic client registration"
+```
+
+---
+
+## Task 9: OAuth2 Handler - Authorization Endpoint
+
+**Files:**
+- Create: `backend/api/oauth2/authorize.go`
+
+**Step 1: Create authorization handler**
+
+```go
+package oauth2
+
+import (
+ "fmt"
+ "net/http"
+ "net/url"
+ "slices"
+ "time"
+
+ "github.com/labstack/echo/v4"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/store"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+func (s *Service) handleAuthorizeGet(c echo.Context) error {
+ ctx := c.Request().Context()
+
+ // Parse query parameters
+ responseType := c.QueryParam("response_type")
+ clientID := c.QueryParam("client_id")
+ redirectURI := c.QueryParam("redirect_uri")
+ state := c.QueryParam("state")
+ 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")
+ }
+ client, err := s.store.GetOAuth2Client(ctx, clientID)
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup client")
+ }
+ if client == nil {
+ 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")
+ }
+ if !validateRedirectURI(redirectURI, client.Config.RedirectUris) {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_redirect_uri", "redirect_uri not registered")
+ }
+
+ // Validate PKCE (required)
+ if codeChallenge == "" {
+ return oauth2ErrorRedirect(c, redirectURI, state, "invalid_request", "code_challenge is required")
+ }
+ if codeChallengeMethod != "S256" {
+ return oauth2ErrorRedirect(c, redirectURI, state, "invalid_request", "code_challenge_method must be S256")
+ }
+
+ // Check if user is logged in
+ accessToken, err := auth.GetTokenFromRequest(c.Request())
+ if err != nil || accessToken == "" {
+ // Redirect to login page with return URL
+ loginURL := fmt.Sprintf("/auth/login?redirect=%s", url.QueryEscape(c.Request().URL.String()))
+ return c.Redirect(http.StatusFound, loginURL)
+ }
+
+ // Return consent page HTML
+ return s.renderConsentPage(c, client.Config.ClientName, clientID, redirectURI, state, codeChallenge, codeChallengeMethod)
+}
+
+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")
+ codeChallenge := c.FormValue("code_challenge")
+ codeChallengeMethod := c.FormValue("code_challenge_method")
+ action := c.FormValue("action")
+
+ // Validate client
+ 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")
+ }
+
+ // Get current user from session
+ accessToken, err := auth.GetTokenFromRequest(c.Request())
+ if err != nil || accessToken == "" {
+ return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "user not authenticated")
+ }
+
+ claims, err := auth.ValidateAccessToken(accessToken, s.secret)
+ if err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "access_denied", "invalid session")
+ }
+
+ // Get user from claims
+ user, err := s.store.GetUserByEmail(ctx, claims.Subject)
+ if err != nil || user == nil {
+ 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,
+ CodeChallengeMethod: codeChallengeMethod,
+ }
+ if _, err := s.store.CreateOAuth2AuthorizationCode(ctx, &store.OAuth2AuthorizationCodeMessage{
+ Code: code,
+ ClientID: clientID,
+ UserID: user.ID,
+ Config: codeConfig,
+ ExpiresAt: time.Now().Add(authCodeExpiry),
+ }); err != nil {
+ return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to store code")
+ }
+
+ // Update client last active
+ _ = s.store.UpdateOAuth2ClientLastActiveAt(ctx, clientID)
+
+ // Redirect with code
+ u, _ := url.Parse(redirectURI)
+ q := u.Query()
+ q.Set("code", code)
+ if state != "" {
+ q.Set("state", state)
+ }
+ u.RawQuery = q.Encode()
+ return c.Redirect(http.StatusFound, u.String())
+}
+
+func (s *Service) renderConsentPage(c echo.Context, clientName, clientID, redirectURI, state, codeChallenge, codeChallengeMethod string) error {
+ html := fmt.Sprintf(`<!DOCTYPE html>
+<html>
+<head>
+ <title>Authorize Application</title>
+ <style>
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: #f5f5f5; }
+ .container { background: white; padding: 2rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); max-width: 400px; width: 100%%; }
+ h1 { margin: 0 0 1rem; font-size: 1.5rem; }
+ p { color: #666; margin: 0 0 1.5rem; }
+ .app-name { font-weight: bold; color: #333; }
+ .buttons { display: flex; gap: 1rem; }
+ button { flex: 1; padding: 0.75rem; border: none; border-radius: 4px; font-size: 1rem; cursor: pointer; }
+ .allow { background: #4f46e5; color: white; }
+ .allow:hover { background: #4338ca; }
+ .deny { background: #e5e5e5; color: #333; }
+ .deny:hover { background: #d4d4d4; }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <h1>Authorize Application</h1>
+ <p><span class="app-name">%s</span> is requesting access to your Bytebase account.</p>
+ <form method="POST" action="/oauth2/authorize">
+ <input type="hidden" name="client_id" value="%s">
+ <input type="hidden" name="redirect_uri" value="%s">
+ <input type="hidden" name="state" value="%s">
+ <input type="hidden" name="code_challenge" value="%s">
+ <input type="hidden" name="code_challenge_method" value="%s">
+ <div class="buttons">
+ <button type="submit" name="action" value="deny" class="deny">Deny</button>
+ <button type="submit" name="action" value="allow" class="allow">Allow</button>
+ </div>
+ </form>
+ </div>
+</body>
+</html>`, clientName, clientID, redirectURI, state, codeChallenge, codeChallengeMethod)
+ return c.HTML(http.StatusOK, html)
+}
+```
+
+**Step 2: Check auth helpers exist**
+
+The code references `auth.GetTokenFromRequest` and `auth.ValidateAccessToken`. These may need to be added or use existing functions. Check `backend/api/auth/auth.go` for existing patterns and adapt as needed.
+
+**Step 3: Lint**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/api/oauth2/authorize.go`
+Expected: No errors (fix any import issues)
+
+**Step 4: Commit**
+
+```bash
+but commit <branch> -m "api: add OAuth2 authorization endpoint"
+```
+
+---
+
+## Task 10: OAuth2 Handler - Token Endpoint
+
+**Files:**
+- Create: `backend/api/oauth2/token.go`
+
+**Step 1: Create token handler**
+
+```go
+package oauth2
+
+import (
+ "encoding/base64"
+ "net/http"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/labstack/echo/v4"
+
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+type tokenRequest struct {
+ GrantType string `form:"grant_type"`
+ Code string `form:"code"`
+ RedirectURI string `form:"redirect_uri"`
+ CodeVerifier string `form:"code_verifier"`
+ RefreshToken string `form:"refresh_token"`
+ ClientID string `form:"client_id"`
+ ClientSecret string `form:"client_secret"`
+}
+
+type tokenResponse struct {
+ AccessToken string `json:"access_token"`
+ TokenType string `json:"token_type"`
+ ExpiresIn int `json:"expires_in"`
+ RefreshToken string `json:"refresh_token,omitempty"`
+}
+
+func (s *Service) handleToken(c echo.Context) error {
+ ctx := c.Request().Context()
+
+ var req tokenRequest
+ if err := c.Bind(&req); err != nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "failed to parse request")
+ }
+
+ // Authenticate client
+ clientID, clientSecret := s.extractClientCredentials(c, &req)
+ if clientID == "" {
+ return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "client authentication required")
+ }
+
+ client, err := s.store.GetOAuth2Client(ctx, clientID)
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup client")
+ }
+ if client == nil {
+ return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "client not found")
+ }
+ if !verifySecret(client.ClientSecretHash, clientSecret) {
+ return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "invalid client credentials")
+ }
+
+ // Handle grant types
+ switch req.GrantType {
+ case "authorization_code":
+ return s.handleAuthorizationCodeGrant(c, client, &req)
+ case "refresh_token":
+ return s.handleRefreshTokenGrant(c, client, &req)
+ default:
+ return oauth2Error(c, http.StatusBadRequest, "unsupported_grant_type", "grant_type must be authorization_code or refresh_token")
+ }
+}
+
+func (s *Service) extractClientCredentials(c echo.Context, req *tokenRequest) (clientID, clientSecret string) {
+ // Try Basic auth first
+ authHeader := c.Request().Header.Get("Authorization")
+ if strings.HasPrefix(authHeader, "Basic ") {
+ decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHeader, "Basic "))
+ if err == nil {
+ parts := strings.SplitN(string(decoded), ":", 2)
+ if len(parts) == 2 {
+ return parts[0], parts[1]
+ }
+ }
+ }
+ // Fall back to form params
+ return req.ClientID, req.ClientSecret
+}
+
+func (s *Service) handleAuthorizationCodeGrant(c echo.Context, client *store.OAuth2ClientMessage, req *tokenRequest) error {
+ ctx := c.Request().Context()
+
+ // Validate grant type is allowed
+ if !slices.Contains(client.Config.GrantTypes, "authorization_code") {
+ return oauth2Error(c, http.StatusBadRequest, "unauthorized_client", "client not authorized for authorization_code grant")
+ }
+
+ // Validate code
+ if req.Code == "" {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "code is required")
+ }
+
+ authCode, err := s.store.GetOAuth2AuthorizationCode(ctx, req.Code)
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup code")
+ }
+ if authCode == nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid or expired code")
+ }
+
+ // Delete code immediately (single use)
+ _ = s.store.DeleteOAuth2AuthorizationCode(ctx, req.Code)
+
+ // Validate code belongs to this client
+ if authCode.ClientID != client.ClientID {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "code was not issued to this client")
+ }
+
+ // Validate code not expired
+ if time.Now().After(authCode.ExpiresAt) {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "code has expired")
+ }
+
+ // Validate redirect_uri matches
+ if req.RedirectURI != authCode.Config.RedirectUri {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "redirect_uri mismatch")
+ }
+
+ // Validate PKCE
+ if req.CodeVerifier == "" {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "code_verifier is required")
+ }
+ if !verifyPKCE(req.CodeVerifier, authCode.Config.CodeChallenge, authCode.Config.CodeChallengeMethod) {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid code_verifier")
+ }
+
+ // Get user
+ user, err := s.store.GetUserByID(ctx, authCode.UserID)
+ if err != nil || user == nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "user not found")
+ }
+
+ // Generate tokens
+ return s.issueTokens(c, client, user.ID, user.Email)
+}
+
+func (s *Service) handleRefreshTokenGrant(c echo.Context, client *store.OAuth2ClientMessage, req *tokenRequest) error {
+ ctx := c.Request().Context()
+
+ // Validate grant type is allowed
+ if !slices.Contains(client.Config.GrantTypes, "refresh_token") {
+ return oauth2Error(c, http.StatusBadRequest, "unauthorized_client", "client not authorized for refresh_token grant")
+ }
+
+ // Validate refresh token
+ if req.RefreshToken == "" {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "refresh_token is required")
+ }
+
+ tokenHash := hashToken(req.RefreshToken)
+ refreshToken, err := s.store.GetOAuth2RefreshToken(ctx, tokenHash)
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup refresh token")
+ }
+ if refreshToken == nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid refresh token")
+ }
+
+ // Delete token immediately (single use, will issue new one)
+ _ = s.store.DeleteOAuth2RefreshToken(ctx, tokenHash)
+
+ // Validate token belongs to this client
+ if refreshToken.ClientID != client.ClientID {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "refresh token was not issued to this client")
+ }
+
+ // Validate not expired
+ if time.Now().After(refreshToken.ExpiresAt) {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "refresh token has expired")
+ }
+
+ // Get user
+ user, err := s.store.GetUserByID(ctx, refreshToken.UserID)
+ if err != nil || user == nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "user not found")
+ }
+
+ // Issue new tokens
+ return s.issueTokens(c, client, user.ID, user.Email)
+}
+
+func (s *Service) issueTokens(c echo.Context, client *store.OAuth2ClientMessage, userID int, userEmail string) error {
+ ctx := c.Request().Context()
+
+ // Generate access token (JWT)
+ now := time.Now()
+ claims := jwt.MapClaims{
+ "iss": "bytebase",
+ "sub": userEmail,
+ "aud": "bb.oauth2.access",
+ "exp": now.Add(accessTokenExpiry).Unix(),
+ "iat": now.Unix(),
+ "client_id": client.ClientID,
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ accessToken, err := token.SignedString([]byte(s.secret))
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to generate access token")
+ }
+
+ // Generate refresh token if allowed
+ var refreshTokenStr string
+ if slices.Contains(client.Config.GrantTypes, "refresh_token") {
+ refreshTokenStr, err = generateRefreshToken()
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to generate refresh token")
+ }
+
+ // Store refresh token
+ if _, err := s.store.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{
+ TokenHash: hashToken(refreshTokenStr),
+ ClientID: client.ClientID,
+ UserID: userID,
+ ExpiresAt: now.Add(refreshTokenExpiry),
+ }); err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to store refresh token")
+ }
+ }
+
+ // Update client last active
+ _ = s.store.UpdateOAuth2ClientLastActiveAt(ctx, client.ClientID)
+
+ return c.JSON(http.StatusOK, &tokenResponse{
+ AccessToken: accessToken,
+ TokenType: "Bearer",
+ ExpiresIn: int(accessTokenExpiry.Seconds()),
+ RefreshToken: refreshTokenStr,
+ })
+}
+```
+
+**Step 2: Lint**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/api/oauth2/token.go`
+Expected: No errors
+
+**Step 3: Commit**
+
+```bash
+but commit <branch> -m "api: add OAuth2 token endpoint"
+```
+
+---
+
+## Task 11: OAuth2 Handler - Revocation Endpoint
+
+**Files:**
+- Create: `backend/api/oauth2/revoke.go`
+
+**Step 1: Create revoke handler**
+
+```go
+package oauth2
+
+import (
+ "encoding/base64"
+ "net/http"
+ "strings"
+
+ "github.com/labstack/echo/v4"
+)
+
+type revokeRequest struct {
+ Token string `form:"token"`
+ TokenTypeHint string `form:"token_type_hint"`
+ ClientID string `form:"client_id"`
+ ClientSecret string `form:"client_secret"`
+}
+
+func (s *Service) handleRevoke(c echo.Context) error {
+ ctx := c.Request().Context()
+
+ var req revokeRequest
+ if err := c.Bind(&req); err != nil {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "failed to parse request")
+ }
+
+ // Authenticate client
+ clientID, clientSecret := s.extractRevokeClientCredentials(c, &req)
+ if clientID == "" {
+ return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "client authentication required")
+ }
+
+ client, err := s.store.GetOAuth2Client(ctx, clientID)
+ if err != nil {
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to lookup client")
+ }
+ if client == nil {
+ return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "client not found")
+ }
+ if !verifySecret(client.ClientSecretHash, clientSecret) {
+ return oauth2Error(c, http.StatusUnauthorized, "invalid_client", "invalid client credentials")
+ }
+
+ // Validate token
+ if req.Token == "" {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_request", "token is required")
+ }
+
+ // Try to revoke as refresh token
+ tokenHash := hashToken(req.Token)
+ if err := s.store.DeleteOAuth2RefreshToken(ctx, tokenHash); err != nil {
+ // Ignore errors - RFC 7009 says to return 200 even if token is invalid
+ }
+
+ // Return success (RFC 7009: always return 200)
+ return c.NoContent(http.StatusOK)
+}
+
+func (s *Service) extractRevokeClientCredentials(c echo.Context, req *revokeRequest) (clientID, clientSecret string) {
+ // Try Basic auth first
+ authHeader := c.Request().Header.Get("Authorization")
+ if strings.HasPrefix(authHeader, "Basic ") {
+ decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHeader, "Basic "))
+ if err == nil {
+ parts := strings.SplitN(string(decoded), ":", 2)
+ if len(parts) == 2 {
+ return parts[0], parts[1]
+ }
+ }
+ }
+ // Fall back to form params
+ return req.ClientID, req.ClientSecret
+}
+```
+
+**Step 2: Lint**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/api/oauth2/revoke.go`
+Expected: No errors
+
+**Step 3: Commit**
+
+```bash
+but commit <branch> -m "api: add OAuth2 revocation endpoint"
+```
+
+---
+
+## Task 12: Register OAuth2 Routes in Server
+
+**Files:**
+- Modify: `backend/server/server.go`
+- Modify: `backend/server/echo_routes.go`
+
+**Step 1: Add OAuth2 service to server struct**
+
+In `backend/server/server.go`, add import and initialize OAuth2 service in `NewServer`:
+
+```go
+import (
+ // ... existing imports
+ "github.com/bytebase/bytebase/backend/api/oauth2"
+)
+
+// In NewServer function, after other service initializations:
+oauth2Service := oauth2.NewService(stores, secret, profile.ExternalURL)
+```
+
+**Step 2: Register OAuth2 routes in echo_routes.go**
+
+In `backend/server/echo_routes.go`, add OAuth2 route registration in `configureEchoRouters`:
+
+```go
+func configureEchoRouters(
+ e *echo.Echo,
+ lspServer *lsp.Server,
+ directorySyncServer *directorysync.Service,
+ oauth2Service *oauth2.Service, // Add parameter
+ profile *config.Profile,
+) {
+ // ... existing code ...
+
+ // OAuth2 routes
+ oauth2Service.RegisterRoutes(e.Group(""))
+}
+```
+
+**Step 3: Update configureEchoRouters call**
+
+In `backend/server/server.go`, update the call to pass oauth2Service.
+
+**Step 4: Lint**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/server/...`
+Expected: No errors
+
+**Step 5: Commit**
+
+```bash
+but commit <branch> -m "server: register OAuth2 routes"
+```
+
+---
+
+## Task 13: Auth Interceptor - Accept OAuth2 Tokens
+
+**Files:**
+- Modify: `backend/api/auth/auth.go`
+
+**Step 1: Update token validation to accept OAuth2 audience**
+
+Find the token validation logic and add `bb.oauth2.access` as a valid audience:
+
+```go
+// In the ValidateAccessToken or similar function, update audience check:
+validAudiences := []string{
+ fmt.Sprintf("bb.user.access.%s", mode),
+ "bb.oauth2.access", // Add this
+}
+```
+
+**Step 2: Lint**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/api/auth/...`
+Expected: No errors
+
+**Step 3: Commit**
+
+```bash
+but commit <branch> -m "auth: accept OAuth2 access tokens"
+```
+
+---
+
+## Task 14: Add Store Helper Methods
+
+**Files:**
+- Modify: `backend/store/user.go` (or principal.go)
+
+**Step 1: Add GetUserByEmail if not exists**
+
+Check if `GetUserByEmail` exists. If not, add:
+
+```go
+func (s *Store) GetUserByEmail(ctx context.Context, email string) (*UserMessage, error) {
+ users, err := s.ListUsers(ctx, &FindUserMessage{Email: &email})
+ if err != nil {
+ return nil, err
+ }
+ if len(users) == 0 {
+ return nil, nil
+ }
+ return users[0], nil
+}
+```
+
+**Step 2: Add GetUserByID if not exists**
+
+```go
+func (s *Store) GetUserByID(ctx context.Context, id int) (*UserMessage, error) {
+ users, err := s.ListUsers(ctx, &FindUserMessage{ID: &id})
+ if err != nil {
+ return nil, err
+ }
+ if len(users) == 0 {
+ return nil, nil
+ }
+ return users[0], nil
+}
+```
+
+**Step 3: Lint**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/store/...`
+Expected: No errors
+
+**Step 4: Commit**
+
+```bash
+but commit <branch> -m "store: add user lookup helpers"
+```
+
+---
+
+## Task 15: Build and Test
+
+**Step 1: Build**
+
+Run: `go build -ldflags "-w -s" -p=16 -o ./bytebase-build/bytebase ./backend/bin/server/main.go`
+Expected: Build succeeds
+
+**Step 2: Run linter on all changes**
+
+Run: `golangci-lint run --allow-parallel-runners ./backend/...`
+Expected: No errors (run repeatedly until clean)
+
+**Step 3: Manual test (optional)**
+
+Start the server and test the OAuth2 flow:
+
+1. Discovery: `curl http://localhost:8080/.well-known/oauth-authorization-server`
+2. Register client: `curl -X POST http://localhost:8080/oauth2/register -H "Content-Type: application/json" -d '{"client_name":"Test","redirect_uris":["http://localhost:3000/callback"]}'`
+3. Open authorize URL in browser
+4. Exchange code for token
+
+**Step 4: Commit**
+
+```bash
+but commit <branch> -m "build: verify OAuth2 implementation compiles"
+```
+
+---
+
+## Summary
+
+| Task | Description | Files |
+|------|-------------|-------|
+| 1 | Proto definitions | `proto/store/oauth2.proto` |
+| 2 | Database migration | `backend/migrator/migration/3.13/0020##...` |
+| 3 | Store: OAuth2 Client | `backend/store/oauth2_client.go` |
+| 4 | Store: Authorization Code | `backend/store/oauth2_authorization_code.go` |
+| 5 | Store: Refresh Token | `backend/store/oauth2_refresh_token.go` |
+| 6 | Handler: Utilities | `backend/api/oauth2/oauth2.go` |
+| 7 | Handler: Discovery | `backend/api/oauth2/discovery.go` |
+| 8 | Handler: DCR | `backend/api/oauth2/register.go` |
+| 9 | Handler: Authorize | `backend/api/oauth2/authorize.go` |
+| 10 | Handler: Token | `backend/api/oauth2/token.go` |
+| 11 | Handler: Revoke | `backend/api/oauth2/revoke.go` |
+| 12 | Server registration | `backend/server/server.go`, `echo_routes.go` |
+| 13 | Auth interceptor | `backend/api/auth/auth.go` |
+| 14 | Store helpers | `backend/store/user.go` |
+| 15 | Build and test | - |
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 4aa8b19f2c..738d889e28 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -57,6 +57,9 @@
"skip": "Skip",
"skipped": "Skipped",
"dismiss": "Dismiss",
+ "allow": "Allow",
+ "deny": "Deny",
+ "go-back": "Go back",
"back": "Back",
"next": "Next",
"edit": "Edit",
@@ -2918,5 +2921,13 @@
},
"last-visit": "Last visit",
"changelog-for-version": "Changelog for {version}"
+ },
+ "oauth2": {
+ "consent": {
+ "title": "Authorization Request",
+ "description": "{clientName} is requesting access to your account",
+ "permissions": "This application will be able to:",
+ "permission-access": "Access your Bytebase account with your permissions"
+ }
}
}
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 98dfb3045c..5e571356d4 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -57,6 +57,9 @@
"skip": "Saltar",
"skipped": "Omitido",
"dismiss": "Descartar",
+ "allow": "Permitir",
+ "deny": "Denegar",
+ "go-back": "Volver",
"back": "Volver",
"next": "Siguiente",
"edit": "Editar",
@@ -2917,5 +2920,13 @@
},
"last-visit": "Última visita",
"changelog-for-version": "Registro de cambios para {version}"
+ },
+ "oauth2": {
+ "consent": {
+ "title": "Solicitud de autorización",
+ "description": "{clientName} está solicitando acceso a tu cuenta",
+ "permissions": "Esta aplicación podrá:",
+ "permission-access": "Acceder a tu cuenta de Bytebase con tus permisos"
+ }
}
}
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index ebac530d2f..b2e914cdc2 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -57,6 +57,9 @@
"skip": "飛び越える",
"skipped": "スキップ",
"dismiss": "閉じる",
+ "allow": "許可",
+ "deny": "拒否",
+ "go-back": "戻る",
"back": "戻る",
"next": "次のステップ",
"edit": "編集",
@@ -2917,5 +2920,13 @@
},
"last-visit": "最終訪問",
"changelog-for-version": "{version} の変更履歴"
+ },
+ "oauth2": {
+ "consent": {
+ "title": "認証リクエスト",
+ "description": "{clientName} があなたのアカウントへのアクセスを要求しています",
+ "permissions": "このアプリケーションは以下のことができます:",
+ "permission-access": "あなたの権限で Bytebase アカウントにアクセス"
+ }
}
}
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 08f0a8d031..b432fd1dc9 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -57,6 +57,9 @@
"skip": "Bỏ qua",
"skipped": "Đã bỏ qua",
"dismiss": "Loại bỏ",
+ "allow": "Cho phép",
+ "deny": "Từ chối",
+ "go-back": "Quay lại",
"back": "Quay lại",
"next": "Tiếp theo",
"edit": "Chỉnh sửa",
@@ -2917,5 +2920,13 @@
},
"last-visit": "Lần truy cập cuối",
"changelog-for-version": "Nhật ký thay đổi cho phiên bản {version}"
+ },
+ "oauth2": {
+ "consent": {
+ "title": "Yêu cầu ủy quyền",
+ "description": "{clientName} đang yêu cầu truy cập vào tài khoản của bạn",
+ "permissions": "Ứng dụng này sẽ có thể:",
+ "permission-access": "Truy cập tài khoản Bytebase của bạn với quyền hạn của bạn"
+ }
}
}
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 2e80e2ce82..3e185bca60 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -57,6 +57,9 @@
"skip": "跳过",
"skipped": "已跳过",
"dismiss": "关闭",
+ "allow": "允许",
+ "deny": "拒绝",
+ "go-back": "返回",
"back": "返回",
"next": "下一步",
"edit": "编辑",
@@ -2917,5 +2920,13 @@
},
"last-visit": "上次访问",
"changelog-for-version": "{version} 的更新日志"
+ },
+ "oauth2": {
+ "consent": {
+ "title": "授权请求",
+ "description": "{clientName} 正在请求访问您的账户",
+ "permissions": "此应用程序将能够:",
+ "permission-access": "使用您的权限访问您的 Bytebase 账户"
+ }
}
}
diff --git a/frontend/src/router/auth.ts b/frontend/src/router/auth.ts
index 838ce14d7b..a67450e367 100644
--- a/frontend/src/router/auth.ts
+++ b/frontend/src/router/auth.ts
@@ -12,8 +12,21 @@ export const AUTH_OAUTH_CALLBACK_MODULE = "auth.oauth.callback";
export const AUTH_OIDC_CALLBACK_MODULE = "auth.oidc.callback";
export const AUTH_IDP_INIT_MODULE = "auth.idp.init";
export const AUTH_2FA_SETUP_MODULE = "auth.2fa.setup";
+export const OAUTH2_CONSENT_MODULE = "oauth2.consent";
const authRoutes: RouteRecordRaw[] = [
+ {
+ path: "/oauth2/consent",
+ component: SplashLayout,
+ children: [
+ {
+ path: "",
+ name: OAUTH2_CONSENT_MODULE,
+ meta: { title: () => t("oauth2.consent.title") },
+ component: () => import("@/views/OAuth2Consent.vue"),
+ },
+ ],
+ },
{
path: "/auth",
name: "auth",
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index e23fee22fc..7fea807003 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -23,6 +23,7 @@ import authRoutes, {
AUTH_OIDC_CALLBACK_MODULE,
AUTH_PASSWORD_RESET_MODULE,
AUTH_SIGNIN_MODULE,
+ OAUTH2_CONSENT_MODULE,
} from "./auth";
import dashboardRoutes from "./dashboard";
import {
@@ -92,6 +93,12 @@ router.beforeEach((to, from, next) => {
return;
}
+ // OAuth2 consent page requires login but should not redirect away
+ if (to.name === OAUTH2_CONSENT_MODULE) {
+ next();
+ return;
+ }
+
const actuatorStore = useActuatorV1Store();
const authStore = useAuthStore();
const routerStore = useRouterStore();
diff --git a/frontend/src/views/OAuth2Consent.vue b/frontend/src/views/OAuth2Consent.vue
new file mode 100644
index 0000000000..019a266dfa
--- /dev/null
+++ b/frontend/src/views/OAuth2Consent.vue
@@ -0,0 +1,192 @@
+<template>
+ <div class="mx-auto w-full max-w-sm">
+ <BytebaseLogo class="mx-auto mb-8" />
+
+ <NCard v-if="state.loading">
+ <div class="flex justify-center py-8">
+ <BBSpin />
+ </div>
+ </NCard>
+
+ <NCard v-else-if="state.error">
+ <div class="text-center py-4">
+ <p class="text-red-600 mb-4">{{ state.error }}</p>
+ <NButton @click="goBack">
+ {{ $t("common.go-back") }}
+ </NButton>
+ </div>
+ </NCard>
+
+ <NCard v-else>
+ <div class="space-y-6">
+ <div class="text-center">
+ <h1 class="text-xl font-semibold text-gray-900 mb-2">
+ {{ $t("oauth2.consent.title") }}
+ </h1>
+ <p class="text-gray-600">
+ {{
+ $t("oauth2.consent.description", {
+ clientName: state.clientName,
+ })
+ }}
+ </p>
+ </div>
+
+ <div class="bg-gray-50 rounded-lg p-4">
+ <p class="text-sm text-gray-500 mb-2">
+ {{ $t("oauth2.consent.permissions") }}
+ </p>
+ <ul class="text-sm text-gray-700 space-y-1">
+ <li class="flex items-center gap-2">
+ <CheckIcon class="w-4 h-4 text-green-500" />
+ {{ $t("oauth2.consent.permission-access") }}
+ </li>
+ </ul>
+ </div>
+
+ <form method="POST" :action="authorizeUrl">
+ <input type="hidden" name="client_id" :value="clientId" />
+ <input type="hidden" name="redirect_uri" :value="redirectUri" />
+ <input type="hidden" name="state" :value="oauthState" />
+ <input type="hidden" name="code_challenge" :value="codeChallenge" />
+ <input
+ type="hidden"
+ name="code_challenge_method"
+ :value="codeChallengeMethod"
+ />
+
+ <div class="flex gap-x-2">
+ <NButton
+ class="flex-1"
+ size="large"
+ :disabled="state.submitting"
+ @click="deny"
+ >
+ {{ $t("common.deny") }}
+ </NButton>
+ <NButton
+ type="primary"
+ class="flex-1"
+ size="large"
+ :loading="state.submitting"
+ attr-type="submit"
+ name="action"
+ value="allow"
+ >
+ {{ $t("common.allow") }}
+ </NButton>
+ </div>
+ </form>
+ </div>
+ </NCard>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { CheckIcon } from "lucide-vue-next";
+import { NButton, NCard } from "naive-ui";
+import { onMounted, reactive } from "vue";
+import { useRoute, useRouter } from "vue-router";
+import { BBSpin } from "@/bbkit";
+import BytebaseLogo from "@/components/BytebaseLogo.vue";
+import { AUTH_SIGNIN_MODULE } from "@/router/auth";
+import { useAuthStore } from "@/store";
+
+interface LocalState {
+ loading: boolean;
+ submitting: boolean;
+ error: string;
+ clientName: string;
+}
+
+const route = useRoute();
+const router = useRouter();
+const authStore = useAuthStore();
+
+const state = reactive<LocalState>({
+ loading: true,
+ submitting: false,
+ error: "",
+ clientName: "",
+});
+
+// Extract query parameters
+const clientId = (route.query.client_id as string) || "";
+const redirectUri = (route.query.redirect_uri as string) || "";
+const oauthState = (route.query.state as string) || "";
+const codeChallenge = (route.query.code_challenge as string) || "";
+const codeChallengeMethod = (route.query.code_challenge_method as string) || "";
+
+const authorizeUrl = "/api/oauth2/authorize";
+
+onMounted(async () => {
+ // Check if user is logged in
+ if (!authStore.isLoggedIn) {
+ // Redirect to login with return URL
+ const returnUrl = route.fullPath;
+ router.replace({
+ name: AUTH_SIGNIN_MODULE,
+ query: { redirect: returnUrl },
+ });
+ return;
+ }
+
+ // Validate required parameters
+ if (!clientId || !redirectUri || !codeChallenge || !codeChallengeMethod) {
+ state.error = "Missing required OAuth2 parameters";
+ state.loading = false;
+ return;
+ }
+
+ // Fetch client info
+ try {
+ const response = await fetch(
+ `/api/oauth2/clients/${encodeURIComponent(clientId)}`
+ );
+ if (!response.ok) {
+ const data = await response.json();
+ state.error = data.error_description || "Client not found";
+ state.loading = false;
+ return;
+ }
+ const data = await response.json();
+ state.clientName = data.client_name || clientId;
+ } catch {
+ state.error = "Failed to load client information";
+ }
+
+ state.loading = false;
+});
+
+const deny = () => {
+ state.submitting = true;
+ // Submit form with deny action
+ const form = document.createElement("form");
+ form.method = "POST";
+ form.action = authorizeUrl;
+
+ const fields = [
+ { name: "client_id", value: clientId },
+ { name: "redirect_uri", value: redirectUri },
+ { name: "state", value: oauthState },
+ { name: "code_challenge", value: codeChallenge },
+ { name: "code_challenge_method", value: codeChallengeMethod },
+ { name: "action", value: "deny" },
+ ];
+
+ for (const field of fields) {
+ const input = document.createElement("input");
+ input.type = "hidden";
+ input.name = field.name;
+ input.value = field.value;
+ form.appendChild(input);
+ }
+
+ document.body.appendChild(form);
+ form.submit();
+};
+
+const goBack = () => {
+ router.back();
+};
+</script>
diff --git a/go.mod b/go.mod
index b628a97ed0..f85baff939 100644
--- a/go.mod
+++ b/go.mod
@@ -68,6 +68,7 @@ require (
github.com/lor00x/goldap v0.0.0-20240304151906-8d785c64d1c8
github.com/mattn/go-sqlite3 v1.14.32
github.com/microsoft/go-mssqldb v1.9.5
+ github.com/modelcontextprotocol/go-sdk v1.1.0
github.com/nyaruka/phonenumbers v1.6.7
github.com/opensearch-project/opensearch-go/v4 v4.5.0
github.com/paulmach/orb v0.12.0
@@ -170,6 +171,7 @@ require (
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551 // indirect
github.com/google/go-querystring v1.1.0 // indirect
+ github.com/google/jsonschema-go v0.3.0 // indirect
github.com/google/s2a-go v0.1.9 // indirect
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
@@ -247,6 +249,7 @@ require (
github.com/vcaesar/cedar v0.20.2 // indirect
github.com/xuri/efp v0.0.1 // indirect
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect
+ github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/detectors/gcp v1.38.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect
diff --git a/go.sum b/go.sum
index 63b744cfb0..954b434701 100644
--- a/go.sum
+++ b/go.sum
@@ -1200,6 +1200,8 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+github.com/google/jsonschema-go v0.3.0 h1:6AH2TxVNtk3IlvkkhjrtbUc4S8AvO0Xii0DxIygDg+Q=
+github.com/google/jsonschema-go v0.3.0/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
@@ -1526,6 +1528,8 @@ github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
+github.com/modelcontextprotocol/go-sdk v1.1.0 h1:Qjayg53dnKC4UZ+792W21e4BpwEZBzwgRW6LrjLWSwA=
+github.com/modelcontextprotocol/go-sdk v1.1.0/go.mod h1:6fM3LCm3yV7pAs8isnKLn07oKtB0MP9LHd3DfAcKw10=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -1838,6 +1842,8 @@ github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBL
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
+github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
+github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yterajima/go-sitemap v0.4.0 h1:JVgmfq4ch/XXIfKjSNlGqZudlPTBagNUgE6B9uBurm4=
github.com/yterajima/go-sitemap v0.4.0/go.mod h1:CRU0eiLdQIFhxLoTQRgXlsPMNbENABe7h/l5+NGFNFw=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index 548780ec1e..ad11a8dcc5 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -176,6 +176,10 @@
- [IssueCommentPayload.TaskPriorBackup.Table](#bytebase-store-IssueCommentPayload-TaskPriorBackup-Table)
- [IssueCommentPayload.TaskUpdate](#bytebase-store-IssueCommentPayload-TaskUpdate)
+- [store/oauth2.proto](#store_oauth2-proto)
+ - [OAuth2AuthorizationCodeConfig](#bytebase-store-OAuth2AuthorizationCodeConfig)
+ - [OAuth2ClientConfig](#bytebase-store-OAuth2ClientConfig)
+
- [store/plan.proto](#store_plan-proto)
- [PlanConfig](#bytebase-store-PlanConfig)
- [PlanConfig.ChangeDatabaseConfig](#bytebase-store-PlanConfig-ChangeDatabaseConfig)
@@ -3076,6 +3080,57 @@ Status represents the current execution state of a task run.
+<a name="store_oauth2-proto"></a>
+<p align="right"><a href="#top">Top</a></p>
+
+## store/oauth2.proto
+
+
+
+<a name="bytebase-store-OAuth2AuthorizationCodeConfig"></a>
+
+### OAuth2AuthorizationCodeConfig
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| redirect_uri | [string](#string) | | |
+| code_challenge | [string](#string) | | |
+| code_challenge_method | [string](#string) | | |
+
+
+
+
+
+
+<a name="bytebase-store-OAuth2ClientConfig"></a>
+
+### OAuth2ClientConfig
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| client_name | [string](#string) | | |
+| redirect_uris | [string](#string) | repeated | |
+| grant_types | [string](#string) | repeated | |
+| token_endpoint_auth_method | [string](#string) | | |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
<a name="store_plan-proto"></a>
<p align="right"><a href="#top">Top</a></p>
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index 7c719123ff..22a31ebb83 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -860,6 +860,25 @@
+ </ul>
+ </li>
+
+
+ <li>
+ <a href="#store%2foauth2.proto">store/oauth2.proto</a>
+ <ul>
+
+ <li>
+ <a href="#bytebase.store.OAuth2AuthorizationCodeConfig"><span class="badge">M</span>OAuth2AuthorizationCodeConfig</a>
+ </li>
+
+ <li>
+ <a href="#bytebase.store.OAuth2ClientConfig"><span class="badge">M</span>OAuth2ClientConfig</a>
+ </li>
+
+
+
+
</ul>
</li>
@@ -8835,6 +8854,103 @@ Format: instances/{instance}/databases/{database}/changelogs/{changelog} </p></t
+ <div class="file-heading">
+ <h2 id="store/oauth2.proto">store/oauth2.proto</h2><a href="#title">Top</a>
+ </div>
+ <p></p>
+
+
+ <h3 id="bytebase.store.OAuth2AuthorizationCodeConfig">OAuth2AuthorizationCodeConfig</h3>
+ <p></p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>redirect_uri</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>code_challenge</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>code_challenge_method</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
+ <h3 id="bytebase.store.OAuth2ClientConfig">OAuth2ClientConfig</h3>
+ <p></p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>client_name</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>redirect_uris</td>
+ <td><a href="#string">string</a></td>
+ <td>repeated</td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>grant_types</td>
+ <td><a href="#string">string</a></td>
+ <td>repeated</td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>token_endpoint_auth_method</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
+
+
+
+
+
+
+
+
<div class="file-heading">
<h2 id="store/plan.proto">store/plan.proto</h2><a href="#title">Top</a>
</div>
diff --git a/proto/store/store/oauth2.proto b/proto/store/store/oauth2.proto
new file mode 100644
index 0000000000..67c66b0376
--- /dev/null
+++ b/proto/store/store/oauth2.proto
@@ -0,0 +1,18 @@
+syntax = "proto3";
+
+package bytebase.store;
+
+option go_package = "generated-go/store";
+
+message OAuth2ClientConfig {
+ string client_name = 1;
+ repeated string redirect_uris = 2;
+ repeated string grant_types = 3;
+ string token_endpoint_auth_method = 4;
+}
+
+message OAuth2AuthorizationCodeConfig {
+ string redirect_uri = 1;
+ string code_challenge = 2;
+ string code_challenge_method = 3;
+}