Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: openapi for instance and auth login (#3387)
ecmadao084d709e0a0a
diff --git a/api/v1/auth.go b/api/v1/auth.gonew file mode 100644index 0000000000..2668ad1833--- /dev/null+++ b/api/v1/auth.go@@ -0,0 +1,16 @@+package v1++// Login is the API message for logins.+type Login struct {+ // Domain specific fields+ Email string `json:"email"`+ Password string `json:"password"`+}++// LoginResponse is the API message for user login response.+type LoginResponse struct {+ ID int `json:"id"`+ Name string `json:"name"`+ Email string `json:"email"`+ Token string `json:"token"`+}diff --git a/api/v1/docs.go b/api/v1/docs.gonew file mode 100644index 0000000000..480ebb893c--- /dev/null+++ b/api/v1/docs.go@@ -0,0 +1,2 @@+// Package v1 is the API message for OpenAPI in V1 version.+package v1diff --git a/api/v1/instance.go b/api/v1/instance.gonew file mode 100644index 0000000000..b857738737--- /dev/null+++ b/api/v1/instance.go@@ -0,0 +1,22 @@+package v1++import (+ "github.com/bytebase/bytebase/plugin/db"+)++// Instance is the API message for an instance.+type Instance struct {+ ID int `jsonapi:"primary,instance" json:"id"`++ // Related fields+ Environment string `json:"environment"`++ // Domain specific fields+ Name string `json:"name"`+ Engine db.Type `json:"engine"`+ EngineVersion string `json:"engineVersion"`+ ExternalLink string `json:"externalLink"`+ Host string `json:"host"`+ Port string `json:"port"`+ Username string `json:"username"`+}diff --git a/server/acl.go b/server/acl.goindex 902019d4c3..0b677a0a20 100644--- a/server/acl.go+++ b/server/acl.go@@ -159,21 +159,20 @@ func enforceWorkspaceDeveloperSheetRouteACL(plan api.PlanType, path string, methreturn nil}-func aclMiddleware(s *Server, ce *casbin.Enforcer, next echo.HandlerFunc, readonly bool) echo.HandlerFunc {+func aclMiddleware(s *Server, pathPrefix string, ce *casbin.Enforcer, next echo.HandlerFunc, readonly bool) echo.HandlerFunc {return func(c echo.Context) error {ctx := c.Request().Context()++ path := strings.TrimPrefix(c.Request().URL.Path, pathPrefix)+// Skips auth, actuator, plan- if common.HasPrefixes(c.Path(), "/api/auth", "/api/actuator", "/api/plan", "/api/oauth") {+ if common.HasPrefixes(path, "/auth", "/actuator", "/plan", "/oauth") {return next(c)}method := c.Request().Method// Skip GET /subscription request- if common.HasPrefixes(c.Path(), "/api/subscription") && method == "GET" {- return next(c)- }- // Skip OpenAPI request- if common.HasPrefixes(c.Path(), openAPIPrefix) {+ if common.HasPrefixes(path, "/subscription") && method == "GET" {return next(c)}@@ -195,8 +194,6 @@ func aclMiddleware(s *Server, ce *casbin.Enforcer, next echo.HandlerFunc, readonreturn echo.NewHTTPError(http.StatusUnauthorized, "This user has been deactivated by the admin")}- path := strings.TrimPrefix(c.Request().URL.Path, "/api")-role := member.Role// If admin feature is not enabled, then we treat all user as OWNER.if !s.feature(api.FeatureRBAC) {@@ -214,7 +211,7 @@ func aclMiddleware(s *Server, ce *casbin.Enforcer, next echo.HandlerFunc, readon// XXX_SELF and try again. Because XXX is a superset of XXX_SELF, thus we only try XXX_SELF after// XXX fails.if method == "GET" || method == "PATCH" || method == "DELETE" {- if isSelf, err := isOperatingSelf(ctx, c, s, principalID, method); err != nil {+ if isSelf, err := isOperatingSelf(ctx, c, s, principalID, method, path); err != nil {return err} else if isSelf {method += "_SELF"@@ -273,26 +270,26 @@ func aclMiddleware(s *Server, ce *casbin.Enforcer, next echo.HandlerFunc, readon}}-func isOperatingSelf(ctx context.Context, c echo.Context, s *Server, curPrincipalID int, method string) (bool, error) {+func isOperatingSelf(ctx context.Context, c echo.Context, s *Server, curPrincipalID int, method string, path string) (bool, error) {switch method {case http.MethodGet:- return isGettingSelf(ctx, c, s, curPrincipalID)+ return isGettingSelf(ctx, c, s, curPrincipalID, path)case http.MethodPatch, http.MethodDelete:- return isUpdatingSelf(ctx, c, s, curPrincipalID)+ return isUpdatingSelf(ctx, c, s, curPrincipalID, path)default:return false, nil}}-func isGettingSelf(_ context.Context, c echo.Context, _ *Server, curPrincipalID int) (bool, error) {- if strings.HasPrefix(c.Path(), "/api/inbox/user") {+func isGettingSelf(_ context.Context, c echo.Context, _ *Server, curPrincipalID int, path string) (bool, error) {+ if strings.HasPrefix(path, "/inbox/user") {userID, err := strconv.Atoi(c.Param("userID"))if err != nil {return false, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("User ID is not a number: %s", c.Param("userID"))).SetInternal(err)}return userID == curPrincipalID, nil- } else if strings.HasPrefix(c.Path(), "/api/bookmark/user") {+ } else if strings.HasPrefix(path, "/bookmark/user") {userID, err := strconv.Atoi(c.Param("userID"))if err != nil {return false, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("User ID is not a number: %s", c.Param("userID"))).SetInternal(err)@@ -304,14 +301,14 @@ func isGettingSelf(_ context.Context, c echo.Context, _ *Server, curPrincipalIDreturn false, nil}-func isUpdatingSelf(ctx context.Context, c echo.Context, s *Server, curPrincipalID int) (bool, error) {+func isUpdatingSelf(ctx context.Context, c echo.Context, s *Server, curPrincipalID int, path string) (bool, error) {const defaultErrMsg = "Failed to process authorize request."- if strings.HasPrefix(c.Path(), "/api/principal") {+ if strings.HasPrefix(path, "/principal") {pathPrincipalID := c.Param("principalID")if pathPrincipalID != "" {return pathPrincipalID == strconv.Itoa(curPrincipalID), nil}- } else if strings.HasPrefix(c.Path(), "/api/activity") {+ } else if strings.HasPrefix(path, "/activity") {if activityIDStr := c.Param("activityID"); activityIDStr != "" {activityID, err := strconv.Atoi(activityIDStr)if err != nil {@@ -328,7 +325,7 @@ func isUpdatingSelf(ctx context.Context, c echo.Context, s *Server, curPrincipalreturn activity.CreatorID == curPrincipalID, nil}- } else if strings.HasPrefix(c.Path(), "/api/bookmark") {+ } else if strings.HasPrefix(path, "/bookmark") {if bookmarkIDStr := c.Param("bookmarkID"); bookmarkIDStr != "" {bookmarkID, err := strconv.Atoi(bookmarkIDStr)if err != nil {@@ -345,7 +342,7 @@ func isUpdatingSelf(ctx context.Context, c echo.Context, s *Server, curPrincipalreturn bookmark.CreatorID == curPrincipalID, nil}- } else if strings.HasPrefix(c.Path(), "/api/inbox") {+ } else if strings.HasPrefix(path, "/inbox") {if inboxIDStr := c.Param("inboxID"); inboxIDStr != "" {inboxID, err := strconv.Atoi(inboxIDStr)if err != nil {@@ -362,7 +359,7 @@ func isUpdatingSelf(ctx context.Context, c echo.Context, s *Server, curPrincipalreturn inbox.ReceiverID == curPrincipalID, nil}- } else if strings.HasPrefix(c.Path(), "/api/sheet") {+ } else if strings.HasPrefix(path, "/sheet") {if idStr := c.Param("id"); idStr != "" {id, err := strconv.Atoi(idStr)if err != nil {diff --git a/server/jwt.go b/server/jwt.goindex bd0c9a6e6c..8fbfd80c60 100644--- a/server/jwt.go+++ b/server/jwt.go@@ -5,6 +5,7 @@ import ("fmt""net/http""strconv"+ "strings""time""github.com/golang-jwt/jwt/v4"@@ -162,33 +163,59 @@ func removeUserCookie(c echo.Context) {c.SetCookie(cookie)}+func findAccessToken(c echo.Context) (string, error) {+ if common.HasPrefixes(c.Path(), openAPIPrefix) {+ authHeader := c.Request().Header.Get("Authorization")+ if authHeader == "" {+ return "", nil+ }++ authHeaderParts := strings.Fields(authHeader)+ if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {+ return "", common.Errorf(common.Invalid, "Authorization header format must be Bearer {token}")+ }++ return authHeaderParts[1], nil+ }++ cookie, err := c.Cookie(accessTokenCookieName)+ if err != nil {+ return "", err+ }++ return cookie.Value, nil+}+// JWTMiddleware validates the access token.// If the access token is about to expire or has expired and the request has a valid refresh token, it// will try to generate new access token and refresh token.-func JWTMiddleware(principalStore *store.Store, next echo.HandlerFunc, mode common.ReleaseMode, secret string) echo.HandlerFunc {+func JWTMiddleware(pathPrefix string, principalStore *store.Store, next echo.HandlerFunc, mode common.ReleaseMode, secret string) echo.HandlerFunc {return func(c echo.Context) error {+ path := strings.TrimPrefix(c.Request().URL.Path, pathPrefix)+// Skips auth, actuator, plan- if common.HasPrefixes(c.Path(), "/api/auth", "/api/actuator", "/api/plan") {+ if common.HasPrefixes(path, "/auth", "/actuator", "/plan") {return next(c)}method := c.Request().Method// Skip GET /subscription request- if common.HasPrefixes(c.Path(), "/api/subscription") && method == "GET" {+ if common.HasPrefixes(c.Path(), "/subscription") && method == "GET" {return next(c)}- // Skip OpenAPI request- if common.HasPrefixes(c.Path(), openAPIPrefix) {++ // Skips OpenAPI SQL endpoint+ if common.HasPrefixes(c.Path(), fmt.Sprintf("%s/sql", openAPIPrefix)) {return next(c)}- cookie, err := c.Cookie(accessTokenCookieName)+ token, err := findAccessToken(c)if err != nil {return echo.NewHTTPError(http.StatusUnauthorized, "Missing access token")}claims := &Claims{}- accessToken, err := jwt.ParseWithClaims(cookie.Value, claims, func(t *jwt.Token) (interface{}, error) {+ accessToken, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (interface{}, error) {if t.Method.Alg() != jwt.SigningMethodHS256.Name {return nil, pkgerrors.Errorf("unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)}diff --git a/server/openapi_auth.go b/server/openapi_auth.gonew file mode 100644index 0000000000..b6a83ee27c--- /dev/null+++ b/server/openapi_auth.go@@ -0,0 +1,69 @@+package server++import (+ "encoding/json"+ "fmt"+ "io"+ "net/http"++ "github.com/labstack/echo/v4"+ "golang.org/x/crypto/bcrypt"++ "github.com/bytebase/bytebase/api"+ openAPIV1 "github.com/bytebase/bytebase/api/v1"+)++func (s *Server) registerOpenAPIRoutesForAuth(g *echo.Group) {+ g.POST("/auth/login", s.openAPIUserLogin)+}++func (s *Server) openAPIUserLogin(c echo.Context) error {+ ctx := c.Request().Context()+ login := &openAPIV1.Login{}+ body, err := io.ReadAll(c.Request().Body)+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Failed to read request body").SetInternal(err)+ }+ if err := json.Unmarshal(body, login); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Malformed login request").SetInternal(err)+ }++ user, err := s.store.GetPrincipalByEmail(ctx, login.Email)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user").SetInternal(err)+ }+ if user == nil {+ return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("User not found: %s", login.Email))+ }++ // Compare the stored hashed password, with the hashed version of the password that was received.+ if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(login.Password)); err != nil {+ // If the two passwords don't match, return a 401 status.+ return echo.NewHTTPError(http.StatusUnauthorized, "Incorrect password").SetInternal(err)+ }++ // test the status of this user+ member, err := s.store.GetMemberByPrincipalID(ctx, user.ID)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user").SetInternal(err)+ }+ if member == nil {+ return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Member not found: %s", user.Email))+ }+ if member.RowStatus == api.Archived {+ return echo.NewHTTPError(http.StatusUnauthorized, "This user has been deactivated by the admin")+ }++ accessToken, err := generateAccessToken(user, s.profile.Mode, s.secret)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access token").SetInternal(err)+ }++ response := &openAPIV1.LoginResponse{+ ID: user.ID,+ Name: user.Name,+ Email: user.Email,+ Token: accessToken,+ }+ return c.JSON(http.StatusOK, response)+}diff --git a/server/openapi_instance.go b/server/openapi_instance.gonew file mode 100644index 0000000000..219163b3e4--- /dev/null+++ b/server/openapi_instance.go@@ -0,0 +1,48 @@+package server++import (+ "net/http"++ "github.com/labstack/echo/v4"++ "github.com/bytebase/bytebase/api"+ openAPIV1 "github.com/bytebase/bytebase/api/v1"+)++func (s *Server) registerOpenAPIRoutesForInstance(g *echo.Group) {+ g.GET("/instance", s.listInstance)+}++func (s *Server) listInstance(c echo.Context) error {+ ctx := c.Request().Context()+ instanceFind := &api.InstanceFind{}+ if rowStatusStr := c.QueryParam("rowstatus"); rowStatusStr != "" {+ rowStatus := api.RowStatus(rowStatusStr)+ instanceFind.RowStatus = &rowStatus+ }+ instanceList, err := s.store.FindInstance(ctx, instanceFind)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch instance list").SetInternal(err)+ }++ var response []*openAPIV1.Instance+ for _, instance := range instanceList {+ response = append(response, convertToOpenAPIInstance(instance))+ }++ return c.JSON(http.StatusOK, response)+}++func convertToOpenAPIInstance(instance *api.Instance) *openAPIV1.Instance {+ return &openAPIV1.Instance{+ ID: instance.ID,+ Environment: instance.Environment.Name,+ Name: instance.Name,+ Engine: instance.Engine,+ EngineVersion: instance.EngineVersion,+ ExternalLink: instance.ExternalLink,+ Host: instance.Host,+ Port: instance.Port,+ Username: instance.Username,+ }+}diff --git a/server/openapi.go b/server/openapi_sql.gosimilarity index 99%rename from server/openapi.gorename to server/openapi_sql.goindex 0dda1eff37..2bde10d538 100644--- a/server/openapi.go+++ b/server/openapi_sql.go@@ -40,7 +40,7 @@ func (c *catalogService) GetFinder() *catalog.Finder {return c.finder}-func (s *Server) registerOpenAPIRoutes(g *echo.Group) {+func (s *Server) registerOpenAPIRoutesForSQL(g *echo.Group) {g.POST("/sql/advise", s.sqlCheckController)g.POST("/sql/schema/diff", schemaDiff)}diff --git a/server/server.go b/server/server.goindex 903c86039e..3c23f72db2 100644--- a/server/server.go+++ b/server/server.go@@ -38,8 +38,14 @@ import ("github.com/bytebase/bytebase/store")-// openAPIPrefix is the API prefix for Bytebase OpenAPI.-const openAPIPrefix = "/v1"+const (+ // internalAPIPrefix is the API prefix for Bytebase internal, used by the UX.+ internalAPIPrefix = "/api"+ // webhookAPIPrefix is the API prefix for Bytebase webhook.+ webhookAPIPrefix = "/hook"+ // openAPIPrefix is the API prefix for Bytebase OpenAPI.+ openAPIPrefix = "/v1"+)// Server is the Bytebase server.type Server struct {@@ -311,7 +317,7 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {if s.profile.Mode == common.ReleaseModeProd && !s.profile.Debug {return true}- return !common.HasPrefixes(c.Path(), "/api", "/hook")+ return !common.HasPrefixes(c.Path(), internalAPIPrefix, openAPIPrefix, webhookAPIPrefix)},Format: `{"time":"${time_rfc3339}",` +`"method":"${method}","uri":"${uri}",` +@@ -320,18 +326,12 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {e.Use(recoverMiddleware)e.GET("/swagger/*", echoSwagger.WrapHandler)- webhookGroup := e.Group("/hook")+ webhookGroup := e.Group(webhookAPIPrefix)s.registerWebhookRoutes(webhookGroup)- openAPIGroup := e.Group(openAPIPrefix)- openAPIGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {- return openAPIMetricMiddleware(s, next)- })- s.registerOpenAPIRoutes(openAPIGroup)-- apiGroup := e.Group("/api")+ apiGroup := e.Group(internalAPIPrefix)apiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {- return JWTMiddleware(s.store, next, prof.Mode, config.secret)+ return JWTMiddleware(internalAPIPrefix, s.store, next, prof.Mode, config.secret)})m, err := model.NewModelFromString(casbinModel)@@ -344,7 +344,7 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {return nil, err}apiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {- return aclMiddleware(s, ce, next, prof.Readonly)+ return aclMiddleware(s, internalAPIPrefix, ce, next, prof.Readonly)})s.registerDebugRoutes(apiGroup)s.registerSettingRoutes(apiGroup)@@ -379,6 +379,10 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {e.GET("/healthz", func(c echo.Context) error {return c.String(http.StatusOK, "OK!\n")})++ // Register open API routes+ s.registerOpenAPIRoutes(e, ce, prof)+// Register pprof endpoints.pprof.Register(e)// Register prometheus metrics endpoint.@@ -396,6 +400,30 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {return s, nil}+func (s *Server) registerOpenAPIRoutes(e *echo.Echo, ce *casbin.Enforcer, prof Profile) {+ openAPIGroup := e.Group(openAPIPrefix)++ openAPIGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {+ return JWTMiddleware(openAPIPrefix, s.store, next, prof.Mode, s.secret)+ })+ openAPIGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {+ return aclMiddleware(s, openAPIPrefix, ce, next, prof.Readonly)+ })+ openAPIGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {+ return openAPIMetricMiddleware(s, next)+ })++ s.registerOpenAPIRoutesForSQL(openAPIGroup)+ s.registerOpenAPIRoutesForAuth(openAPIGroup)+ s.registerOpenAPIRoutesForInstance(openAPIGroup)++ openAPIGroup.GET("/healthz", func(c echo.Context) error {+ return c.JSON(http.StatusOK, map[string]string{+ "content": "OK",+ })+ })+}+// initSubscription will initial the subscription cache in memory.func (s *Server) initSubscription(ctx context.Context) {s.subscription = s.loadSubscription(ctx)