Skip to content

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

10.2 KB
Raw Blame
package oauth2

import (
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/base64"
	"html"
	"log/slog"
	"net/http"
	"net/url"
	"path"
	"slices"
	"strings"
	"time"

	"github.com/labstack/echo/v5"
	"github.com/labstack/echo/v5/middleware"
	"golang.org/x/crypto/bcrypt"

	"github.com/bytebase/bytebase/backend/api/auth"
	"github.com/bytebase/bytebase/backend/common/log"
	"github.com/bytebase/bytebase/backend/component/config"
	"github.com/bytebase/bytebase/backend/store"
)

const (
	clientIDPrefix     = "bb_oauth_"
	refreshTokenPrefix = "bb_refresh_"
	authCodePrefix     = "bb_code_"

	authCodeExpiry = 10 * time.Minute
	// accessTokenExpiry aliases the shared constant so the /mcp middleware's
	// legacy-audience migration window (one access-token lifetime from process
	// start) stays exactly as long as the tokens it exists for.
	accessTokenExpiry    = auth.OAuth2AccessTokenDuration
	refreshTokenExpiry   = 30 * 24 * time.Hour
	clientInactiveExpiry = 30 * 24 * time.Hour

	// maxOAuth2BodyBytes caps request bodies on the OAuth2 POST routes. Echo's
	// default JSON deserializer buffers the whole body in memory before
	// unmarshalling, and /register is unauthenticated, so bodies must be
	// bounded before Bind. OAuth2 payloads (RFC 7591 client metadata, RFC 6749
	// token/revoke forms) are at most a few KB; 64 KB is generous.
	maxOAuth2BodyBytes = 64 << 10
)

type Service struct {
	store   *store.Store
	profile *config.Profile
	secret  string

	// mcpCeiling is narrowed to an interface so a test can make the read fail.
	mcpCeiling mcpCeilingReader
}

func NewService(stores *store.Store, profile *config.Profile, secret string) *Service {
	return &Service{
		store:      stores,
		profile:    profile,
		secret:     secret,
		mcpCeiling: stores,
	}
}

func (s *Service) RegisterRoutes(e *echo.Echo) {
	// RFC 8414 / RFC 9728 discovery endpoints (host-global, no workspace).
	e.GET("/.well-known/oauth-authorization-server", s.handleDiscovery)
	e.GET("/.well-known/oauth-authorization-server/*", s.handleDiscovery)
	e.GET("/.well-known/oauth-protected-resource", s.handleProtectedResourceMetadata)
	e.GET("/.well-known/oauth-protected-resource/*", s.handleProtectedResourceMetadata)

	// Primary OAuth2 routes. Workspace binding now lives on the issued
	// authorization code / refresh token (set at consent time from the
	// user's session), not on the URL or the client. Same routes serve
	// self-hosted and SaaS.
	bodyLimit := middleware.BodyLimit(maxOAuth2BodyBytes)
	e.POST("/api/oauth2/register", s.handleRegister, bodyLimit)
	e.GET("/api/oauth2/authorize", s.handleAuthorizeGet)
	e.POST("/api/oauth2/authorize", s.handleAuthorizePost, bodyLimit)
	e.GET("/api/oauth2/clients/:clientID", s.handleGetClient)
	e.POST("/api/oauth2/token", s.handleToken, bodyLimit)
	e.POST("/api/oauth2/revoke", s.handleRevoke, bodyLimit)

	// Workspace-scoped routes are kept for backward compatibility with any
	// client that hardcoded the older URL shape. The :workspaceID segment
	// is now informational — workspace resolution comes from the session
	// at consent time, just like the unscoped routes above.
	e.POST("/api/workspaces/:workspaceID/oauth2/register", s.handleRegister, bodyLimit)
	e.GET("/api/workspaces/:workspaceID/oauth2/authorize", s.handleAuthorizeGet)
	e.POST("/api/workspaces/:workspaceID/oauth2/authorize", s.handleAuthorizePost, bodyLimit)
	e.GET("/api/workspaces/:workspaceID/oauth2/clients/:clientID", s.handleGetClient)
	e.POST("/api/workspaces/:workspaceID/oauth2/token", s.handleToken, bodyLimit)
	e.POST("/api/workspaces/:workspaceID/oauth2/revoke", s.handleRevoke, bodyLimit)
}

// 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 generateClientID() (string, error) {
	// Use 24 bytes for client ID (shorter than refresh tokens)
	bytes := make([]byte, 24)
	if _, err := rand.Read(bytes); err != nil {
		return "", err
	}
	return clientIDPrefix + base64.RawURLEncoding.EncodeToString(bytes), nil
}

func generateAuthCode() (string, error) {
	token, err := auth.GenerateOpaqueToken()
	if err != nil {
		return "", err
	}
	return authCodePrefix + token, nil
}

func generateRefreshToken() (string, error) {
	token, err := auth.GenerateOpaqueToken()
	if err != nil {
		return "", err
	}
	return refreshTokenPrefix + token, nil
}

func verifySecret(hash, secret string) bool {
	return bcrypt.CompareHashAndPassword([]byte(hash), []byte(secret)) == nil
}

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
	}
	if parsed.Scheme != "http" && parsed.Scheme != "https" {
		return false
	}
	host := parsed.Hostname()
	return host == "localhost" || host == "127.0.0.1" || host == "::1"
}

func isAllowedDynamicClientRedirectURI(uri string) bool {
	parsed, err := url.Parse(uri)
	if err != nil {
		return false
	}

	switch parsed.Scheme {
	case "http", "https":
		return isLocalhostURI(uri) || isAllowedHostedRedirectURI(parsed)
	case "cursor", "vscode", "vscode-insiders":
		return true
	case "jetbrains":
		return parsed.Host == "gateway" && parsed.Path != "" && parsed.Path != "/"
	default:
		return false
	}
}

// isAllowedHostedRedirectURI whitelists the fixed, vendor-controlled OAuth
// callback URLs used by popular hosted MCP clients (web/desktop apps that
// connect to remote MCP servers). These serve the same role as the cursor://,
// vscode://, and jetbrains://gateway/... schemes above. Each entry is pinned to
// an exact host (plus an exact or prefix path) so an attacker still cannot
// register an arbitrary https:// redirect URI and exfiltrate authorization
// codes.
func isAllowedHostedRedirectURI(u *url.URL) bool {
	if u.Scheme != "https" {
		return false
	}
	// Only the default https port is the real vendor callback; reject any other
	// port so a code can't be steered to a non-OAuth service on the vendor host.
	if port := u.Port(); port != "" && port != "443" {
		return false
	}
	// Reject "."/".." path segments (u.Path is already percent-decoded, so this
	// also covers %2e%2e). Otherwise a prefix match like /connector/oauth/../evil
	// passes here, but the browser normalizes it and delivers the code to a
	// different path on the vendor host than the pinned callback.
	if u.Path != path.Clean(u.Path) {
		return false
	}
	// Hosts are case-insensitive (RFC 3986); normalize via Hostname()+ToLower so
	// the exact-match cases below hold. Paths stay case-sensitive (matched verbatim).
	switch strings.ToLower(u.Hostname()) {
	case "claude.ai":
		// Claude.ai web, Claude Desktop, mobile, and Cowork.
		return u.Path == "/api/mcp/auth_callback"
	case "chatgpt.com":
		// ChatGPT connectors: per-connector path (current) and legacy fixed path.
		return strings.HasPrefix(u.Path, "/connector/oauth/") || u.Path == "/connector_platform_oauth_redirect"
	case "vscode.dev", "insiders.vscode.dev":
		// VS Code for the Web (complements the vscode:// scheme above).
		return u.Path == "/redirect"
	case "antigravity.google":
		// Google Antigravity.
		return u.Path == "/oauth-callback"
	case "www.cursor.com":
		// Cursor IDE and Cursor CLI (cursor-agent) route MCP OAuth through this
		// fixed cloud callback. The cursor:// scheme above predates this flow and
		// is no longer used for DCR, so the scheme entry alone doesn't help.
		return u.Path == "/agents/mcp/oauth/callback"
	default:
		return false
	}
}

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 {
	target, err := oauth2ErrorRedirectURL(redirectURI, state, errorCode, description)
	if err != nil {
		slog.Error("failed to parse redirect URI for OAuth2 error redirect", slog.String("redirectURI", redirectURI), log.BBError(err))
		return oauth2Error(c, http.StatusInternalServerError, errorCode, description)
	}
	// Return HTML page that redirects to callback URL
	// This avoids CSP form-action restrictions
	return c.HTML(http.StatusOK, buildRedirectHTML(target))
}

// oauth2ErrorRedirectURL builds the client callback carrying an RFC 6749 error.
// Split out so a refusal that renders its own page can still offer the link
// back, rather than deciding between telling the user and telling the client.
func oauth2ErrorRedirectURL(redirectURI, state, errorCode, description string) (string, error) {
	u, err := url.Parse(redirectURI)
	if err != nil {
		return "", err
	}
	q := u.Query()
	q.Set("error", errorCode)
	q.Set("error_description", description)
	if state != "" {
		q.Set("state", state)
	}
	u.RawQuery = q.Encode()
	return u.String(), nil
}

// 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>`
}