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: clean server code (#8175)
Danny Xu00c15bc4e506
diff --git a/backend/api/v1/debug_interceptor.go b/backend/api/v1/debug_interceptor.goindex e2fbf57592..9eac4d4415 100644--- a/backend/api/v1/debug_interceptor.go+++ b/backend/api/v1/debug_interceptor.go@@ -14,19 +14,27 @@ import ("github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"+ "github.com/bytebase/bytebase/backend/component/config"api "github.com/bytebase/bytebase/backend/legacyapi"+ "github.com/bytebase/bytebase/backend/metric"+ metricPlugin "github.com/bytebase/bytebase/backend/plugin/metric"+ "github.com/bytebase/bytebase/backend/runner/metricreport"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")// DebugInterceptor is the v1 debug interceptor for gRPC server.type DebugInterceptor struct {errorRecordRing *api.ErrorRecordRing+ profile *config.Profile+ metricReporter *metricreport.Reporter}// NewDebugInterceptor returns a new v1 API debug interceptor.-func NewDebugInterceptor(errorRecordRing *api.ErrorRecordRing) *DebugInterceptor {+func NewDebugInterceptor(errorRecordRing *api.ErrorRecordRing, profile *config.Profile, metricReporter *metricreport.Reporter) *DebugInterceptor {return &DebugInterceptor{errorRecordRing: errorRecordRing,+ profile: profile,+ metricReporter: metricReporter,}}@@ -85,4 +93,12 @@ func (in *DebugInterceptor) debugInterceptorDo(ctx context.Context, request any,}in.errorRecordRing.Ring = in.errorRecordRing.Ring.Next()}+ in.profile.LastActiveTs = time.Now().Unix()+ in.metricReporter.Report(ctx, &metricPlugin.Metric{+ Name: metric.APIRequestMetricName,+ Value: 1,+ Labels: map[string]any{+ "method": fullMethod,+ },+ })}diff --git a/backend/server/acl.go b/backend/server/acl.godeleted file mode 100644index 0dc16f4dab..0000000000--- a/backend/server/acl.go+++ /dev/null@@ -1,77 +0,0 @@-package server--import (- "fmt"- "net/http"- "strings"-- "github.com/casbin/casbin/v2"- "github.com/pkg/errors"-- "github.com/labstack/echo/v4"-- "github.com/bytebase/bytebase/backend/common"- api "github.com/bytebase/bytebase/backend/legacyapi"-)--const (- roleContextKey = "role"-)--func getRoleContextKey() string {- return roleContextKey-}--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 OpenAPI SQL endpoint- if common.HasPrefixes(c.Path(), fmt.Sprintf("%s/sql", openAPIPrefix)) {- return next(c)- }-- method := c.Request().Method-- if readonly && method != "GET" {- return echo.NewHTTPError(http.StatusMethodNotAllowed, "Server is in readonly mode")- }-- // Gets principal id from the context.- principalID := c.Get(getPrincipalIDContextKey()).(int)-- user, err := s.store.GetUserByID(ctx, principalID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to process authorize request.").SetInternal(err)- }- if user == nil {- return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("User ID is not a member: %d", principalID))- }- if user.MemberDeleted {- return echo.NewHTTPError(http.StatusUnauthorized, "This user has been deactivated by the admin")- }-- role := user.Role- // If admin feature is not enabled, then we treat all user as OWNER.- if s.licenseService.IsFeatureEnabled(api.FeatureRBAC) != nil {- role = api.Owner- }-- // Performs the ACL check.- pass, err := ce.Enforce(string(role), path, method)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to process authorize request.").SetInternal(err)- }- if !pass {- return echo.NewHTTPError(http.StatusForbidden).SetInternal(- errors.Errorf("rejected by the ACL policy; %s %s u%d/%s", method, path, principalID, role))- }-- // Stores role into context.- c.Set(getRoleContextKey(), role)-- return next(c)- }-}diff --git a/backend/server/acl_casbin_model.conf b/backend/server/acl_casbin_model.confdeleted file mode 100644index def33bdb38..0000000000--- a/backend/server/acl_casbin_model.conf+++ /dev/null@@ -1,11 +0,0 @@-[request_definition]-r = sub, obj, act--[policy_definition]-p = sub, obj, act--[policy_effect]-e = some(where (p.eft == allow)) # Passes auth if any of the policies allows--[matchers]-m = r.sub == p.sub && keyMatch4(r.obj, p.obj) && r.act == p.actdiff --git a/backend/server/acl_casbin_policy_dba.csv b/backend/server/acl_casbin_policy_dba.csvdeleted file mode 100644index 7ab2447d3c..0000000000--- a/backend/server/acl_casbin_policy_dba.csv+++ /dev/null@@ -1,19 +0,0 @@-p, DBA, /database/{databaseID}/edit, POST-p, DBA, /issue, POST-p, DBA, /issues, POST-p, DBA, /issue, GET-p, DBA, /issue/{issueID}, GET-p, DBA, /issue/{issueID}, PATCH-p, DBA, /issue/{issueID}/status, PATCH-p, DBA, /issue/{issueID}/subscriber, GET-p, DBA, /issue/{issueID}/subscriber, POST-p, DBA, /issue/{issueID}/subscriber/{subscriberID}, DELETE-p, DBA, /pipeline/{pipelineID}/stage/{stageID}/status, PATCH-p, DBA, /pipeline/{pipelineID}/task/all, PATCH-p, DBA, /pipeline/{pipelineID}/task/{taskID}, PATCH-p, DBA, /pipeline/{pipelineID}/task/{taskID}/status, PATCH-p, DBA, /pipeline/{pipelineID}/task/{taskID}/check, POST-p, DBA, /sql/ping, POST-p, DBA, /sql/sync-schema, POST-p, DBA, /sql/execute, POST-p, DBA, /sql/execute/admin, POST\ No newline at end of filediff --git a/backend/server/acl_casbin_policy_developer.csv b/backend/server/acl_casbin_policy_developer.csvdeleted file mode 100644index b20928174e..0000000000--- a/backend/server/acl_casbin_policy_developer.csv+++ /dev/null@@ -1,18 +0,0 @@-p, DEVELOPER, /database/{databaseID}/edit, POST-p, DEVELOPER, /issue, POST-p, DEVELOPER, /issues, POST-p, DEVELOPER, /issue, GET-p, DEVELOPER, /issue/{issueID}, GET-p, DEVELOPER, /issue/{issueID}, PATCH-p, DEVELOPER, /issue/{issueID}/status, PATCH-p, DEVELOPER, /issue/{issueID}/subscriber, GET-p, DEVELOPER, /issue/{issueID}/subscriber, POST-p, DEVELOPER, /issue/{issueID}/subscriber/{subscriberID}, DELETE-p, DEVELOPER, /pipeline/{pipelineID}/stage/{stageID}/status, PATCH-p, DEVELOPER, /pipeline/{pipelineID}/task/all, PATCH-p, DEVELOPER, /pipeline/{pipelineID}/task/{taskID}, PATCH-p, DEVELOPER, /pipeline/{pipelineID}/task/{taskID}/status, PATCH-p, DEVELOPER, /pipeline/{pipelineID}/task/{taskID}/check, POST-p, DEVELOPER, /sql/ping, POST-p, DEVELOPER, /sql/sync-schema, POST-p, DEVELOPER, /sql/execute, POST\ No newline at end of filediff --git a/backend/server/acl_casbin_policy_owner.csv b/backend/server/acl_casbin_policy_owner.csvdeleted file mode 100644index 972dc59309..0000000000--- a/backend/server/acl_casbin_policy_owner.csv+++ /dev/null@@ -1,19 +0,0 @@-p, OWNER, /database/{databaseID}/edit, POST-p, OWNER, /issue, POST-p, OWNER, /issues, POST-p, OWNER, /issue, GET-p, OWNER, /issue/{issueID}, GET-p, OWNER, /issue/{issueID}, PATCH-p, OWNER, /issue/{issueID}/status, PATCH-p, OWNER, /issue/{issueID}/subscriber, GET-p, OWNER, /issue/{issueID}/subscriber, POST-p, OWNER, /issue/{issueID}/subscriber/{subscriberID}, DELETE-p, OWNER, /pipeline/{pipelineID}/stage/{stageID}/status, PATCH-p, OWNER, /pipeline/{pipelineID}/task/all, PATCH-p, OWNER, /pipeline/{pipelineID}/task/{taskID}, PATCH-p, OWNER, /pipeline/{pipelineID}/task/{taskID}/status, PATCH-p, OWNER, /pipeline/{pipelineID}/task/{taskID}/check, POST-p, OWNER, /sql/ping, POST-p, OWNER, /sql/sync-schema, POST-p, OWNER, /sql/execute, POST-p, OWNER, /sql/execute/admin, POST\ No newline at end of filediff --git a/backend/server/jwt.go b/backend/server/jwt.godeleted file mode 100644index fc5fedd04f..0000000000--- a/backend/server/jwt.go+++ /dev/null@@ -1,167 +0,0 @@-package server--import (- "errors"- "fmt"- "net/http"- "strconv"- "strings"-- "github.com/golang-jwt/jwt/v4"- "github.com/labstack/echo/v4"- pkgerrors "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/api/auth"- "github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/store"-)--const (- // Context section- // The key name used to store principal id in the context- // principal id is extracted from the jwt token subject field.- principalIDContextKey = "principal-id"-)--// Claims creates a struct that will be encoded to a JWT.-// We add jwt.RegisteredClaims as an embedded type, to provide fields such as name.-type Claims struct {- Name string `json:"name"`- jwt.RegisteredClaims-}--func getPrincipalIDContextKey() string {- return principalIDContextKey-}--func extractTokenFromHeader(c echo.Context) (string, error) {- 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-}--func findAccessToken(c echo.Context) (string, error) {- if common.HasPrefixes(c.Path(), openAPIPrefix) {- return extractTokenFromHeader(c)- }-- cookie, err := c.Cookie(auth.AccessTokenCookieName)- if err != nil {- // TODO(ed): support trigger the schema sync via terraform in a quick but dirty way.- // We should support trigger the sync via OpenAPI later.- if c.Path() == "/api/sql/sync-schema" {- return extractTokenFromHeader(c)- }- 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(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- if common.HasPrefixes(path, "/auth", "/actuator") {- return next(c)- }-- method := c.Request().Method-- // Skip GET /feature request- if common.HasPrefixes(path, "/feature") && method == "GET" {- return next(c)- }-- // Skips OpenAPI SQL endpoint- if common.HasPrefixes(c.Path(), fmt.Sprintf("%s/sql", openAPIPrefix)) {- return next(c)- }-- token, err := findAccessToken(c)- if err != nil {- return echo.NewHTTPError(http.StatusUnauthorized, "Missing access token")- }-- claims := &Claims{}- _, err = jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (any, 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)- }- if kid, ok := t.Header["kid"].(string); ok {- if kid == "v1" {- return []byte(secret), nil- }- }- return nil, pkgerrors.Errorf("unexpected access token kid=%v", t.Header["kid"])- })-- if !audienceContains(claims.Audience, fmt.Sprintf(auth.AccessTokenAudienceFmt, mode)) {- return echo.NewHTTPError(http.StatusUnauthorized,- fmt.Sprintf("Invalid access token, audience mismatch, got %q, expected %q. you may send request to the wrong environment",- claims.Audience,- fmt.Sprintf(auth.AccessTokenAudienceFmt, mode),- ))- }-- if err != nil {- var ve *jwt.ValidationError- if errors.As(err, &ve) {- // If expiration error is the only error, we will clear the err- // and generate new access token and refresh token- if ve.Errors == jwt.ValidationErrorExpired {- return echo.NewHTTPError(http.StatusUnauthorized, "access token expired")- }- }- }-- // We either have a valid access token or we will attempt to generate new access token and refresh token- if err == nil {- ctx := c.Request().Context()- principalID, err := strconv.Atoi(claims.Subject)- if err != nil {- return echo.NewHTTPError(http.StatusUnauthorized, "Malformed ID in the token.")- }-- // Even if there is no error, we still need to make sure the user still exists.- user, err := principalStore.GetUserByID(ctx, principalID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to find user ID: %d", principalID)).SetInternal(err)- }- if user == nil {- return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Failed to find user ID: %d", principalID))- }-- // Stores principalID into context.- c.Set(getPrincipalIDContextKey(), principalID)- return next(c)- }-- return &echo.HTTPError{- Code: http.StatusUnauthorized,- Message: "Invalid or expired access token",- Internal: err,- }- }-}--func audienceContains(audience jwt.ClaimStrings, token string) bool {- for _, v := range audience {- if v == token {- return true- }- }- return false-}diff --git a/backend/server/database.go b/backend/server/legacy_database.gosimilarity index 100%rename from backend/server/database.gorename to backend/server/legacy_database.godiff --git a/backend/server/issue.go b/backend/server/legacy_issue.gosimilarity index 100%rename from backend/server/issue.gorename to backend/server/legacy_issue.godiff --git a/backend/server/issue_subscriber.go b/backend/server/legacy_issue_subscriber.gosimilarity index 100%rename from backend/server/issue_subscriber.gorename to backend/server/legacy_issue_subscriber.godiff --git a/backend/server/task.go b/backend/server/legacy_task.gosimilarity index 99%rename from backend/server/task.gorename to backend/server/legacy_task.goindex c0b7f1a5d2..1cc4dfd030 100644--- a/backend/server/task.go+++ b/backend/server/legacy_task.go@@ -29,7 +29,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {taskPatch := &api.TaskPatch{ID: taskID,- UpdaterID: c.Get(getPrincipalIDContextKey()).(int),+ UpdaterID: api.SystemBotID,}if err := jsonapi.UnmarshalPayload(c.Request().Body, taskPatch); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformed update task request").SetInternal(err)diff --git a/backend/server/server.go b/backend/server/server.goindex 84295118bf..d3551ee7af 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -15,8 +15,6 @@ import (// embed will embeds the acl policy._ "embed"- "github.com/casbin/casbin/v2"- "github.com/casbin/casbin/v2/model""github.com/google/uuid"grpcRuntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime""github.com/improbable-eng/grpc-web/go/grpcweb"@@ -25,8 +23,6 @@ import ("github.com/labstack/echo/v4""github.com/labstack/echo/v4/middleware""github.com/pkg/errors"- scas "github.com/qiangmzsx/string-adapter/v2"- echoSwagger "github.com/swaggo/echo-swagger""github.com/tmc/grpc-websocket-proxy/wsproxy""google.golang.org/grpc""google.golang.org/grpc/codes"@@ -56,7 +52,6 @@ import ("github.com/bytebase/bytebase/backend/plugin/advisor"advisorDb "github.com/bytebase/bytebase/backend/plugin/advisor/db""github.com/bytebase/bytebase/backend/plugin/app/feishu"- metricPlugin "github.com/bytebase/bytebase/backend/plugin/metric"bbs3 "github.com/bytebase/bytebase/backend/plugin/storage/s3""github.com/bytebase/bytebase/backend/resources/mongoutil""github.com/bytebase/bytebase/backend/resources/mysqlutil"@@ -139,9 +134,7 @@ 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"+ webhookAPIPrefix = "/hook"maxStacksize = 8 * 1024gracefulShutdownPeriod = 10 * time.Second)@@ -196,37 +189,6 @@ type Server struct {cancel context.CancelFunc}-//go:embed acl_casbin_model.conf-var casbinModel string--//go:embed acl_casbin_policy_owner.csv-var casbinOwnerPolicy string--//go:embed acl_casbin_policy_dba.csv-var casbinDBAPolicy string--//go:embed acl_casbin_policy_developer.csv-var casbinDeveloperPolicy string--// Use following cmd to generate swagger doc-// swag init -g ./backend/server.go -d ./backend/server --output docs/openapi --parseDependency--// @title Bytebase OpenAPI-// @version 1.0-// @description The OpenAPI for bytebase.-// @termsOfService https://www.bytebase.com/terms--// @contact.name API Support-// @contact.url https://github.com/bytebase/bytebase/-// @contact.email [email protected]--// @license.name MIT-// @license.url https://github.com/bytebase/bytebase/blob/main/LICENSE--// @host localhost:8080-// @BasePath /v1/-// @schemes http-// NewServer creates a server.func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {s := &Server{@@ -379,6 +341,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {e.Debug = profile.Debuge.HideBanner = truee.HidePort = true+ e.Use(recoverMiddleware)grpcSkipper := func(c echo.Context) bool {// Skip grpc and webhook calls.return strings.HasPrefix(c.Request().URL.Path, "/bytebase.v1.") ||@@ -406,31 +369,6 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {},}))- // MetricReporter middleware.- e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {- return func(c echo.Context) error {- defer func() {- // only update for authorized request- id, ok := c.Get(getPrincipalIDContextKey()).(int)- if !ok || id <= 0 {- return- }- s.profile.LastActiveTs = time.Now().Unix()- ctx := c.Request().Context()-- s.metricReporter.Report(ctx, &metricPlugin.Metric{- Name: metric.APIRequestMetricName,- Value: 1,- Labels: map[string]any{- "path": c.Request().URL.Path,- "method": c.Request().Method,- },- })- }()- return next(c)- }- })-embedFrontend(e)s.e = e@@ -490,45 +428,10 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {s.initMetricReporter()}- // Middleware- //- // API slogger middleware.- e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{- Skipper: func(c echo.Context) bool {- if s.profile.Mode == common.ReleaseModeProd && !s.profile.Debug {- return true- }- return !common.HasPrefixes(c.Path(), internalAPIPrefix, openAPIPrefix, webhookAPIPrefix)- },- Format: `{"time":"${time_rfc3339}",` +- `"method":"${method}","uri":"${uri}",` +- `"status":${status},"error":"${error}"}` + "\n",- }))- // Panic recovery middleware.- e.Use(recoverMiddleware)- e.GET("/swagger/*", echoSwagger.WrapHandler)-webhookGroup := e.Group(webhookAPIPrefix)s.registerWebhookRoutes(webhookGroup)apiGroup := e.Group(internalAPIPrefix)- // API JWT authentication middleware.- apiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {- return JWTMiddleware(internalAPIPrefix, s.store, next, profile.Mode, config.secret)- })-- m, err := model.NewModelFromString(casbinModel)- if err != nil {- return nil, err- }- sa := scas.NewAdapter(strings.Join([]string{casbinOwnerPolicy, casbinDBAPolicy, casbinDeveloperPolicy}, "\n"))- ce, err := casbin.NewEnforcer(m, sa)- if err != nil {- return nil, err- }- apiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {- return aclMiddleware(s, internalAPIPrefix, ce, next, profile.Readonly)- })s.registerDatabaseRoutes(apiGroup)s.registerIssueRoutes(apiGroup)s.registerIssueSubscriberRoutes(apiGroup)@@ -542,7 +445,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {// Setup the gRPC and grpc-gateway.authProvider := auth.New(s.store, s.secret, tokenDuration, s.licenseService, profile.Mode)aclProvider := v1.NewACLInterceptor(s.store, s.secret, s.licenseService, profile.Mode)- debugProvider := v1.NewDebugInterceptor(&s.errorRecordRing)+ debugProvider := v1.NewDebugInterceptor(&s.errorRecordRing, &profile, s.metricReporter)onPanic := func(p any) error {stack := make([]byte, maxStacksize)stack = stack[:runtime.Stack(stack, true)]diff --git a/backend/server/server_frontend_embed.go b/backend/server/server_frontend_embed.goindex be2afaf2c8..ae3ae2a296 100644--- a/backend/server/server_frontend_embed.go+++ b/backend/server/server_frontend_embed.go@@ -9,6 +9,8 @@ import ("github.com/labstack/echo/v4""github.com/labstack/echo/v4/middleware"++ "github.com/bytebase/bytebase/backend/common")//go:embed dist/assets/*@@ -28,7 +30,7 @@ func embedFrontend(e *echo.Echo) {// Use echo static middleware to serve the built dist folder// refer: https://github.com/labstack/echo/blob/master/middleware/static.goe.Use(middleware.StaticWithConfig(middleware.StaticConfig{- Skipper: DefaultAPIRequestSkipper,+ Skipper: defaultAPIRequestSkipper,HTML5: true,Filesystem: getFileSystem("dist"),}))@@ -41,8 +43,14 @@ func embedFrontend(e *echo.Echo) {}})g.Use(middleware.StaticWithConfig(middleware.StaticConfig{- Skipper: DefaultAPIRequestSkipper,+ Skipper: defaultAPIRequestSkipper,HTML5: true,Filesystem: getFileSystem("dist/assets"),}))}++// defaultAPIRequestSkipper is echo skipper for api requests.+func defaultAPIRequestSkipper(c echo.Context) bool {+ path := c.Path()+ return common.HasPrefixes(path, "/api", "/v1", "/hook")+}diff --git a/backend/server/skipper.go b/backend/server/skipper.godeleted file mode 100644index b89dc8659a..0000000000--- a/backend/server/skipper.go+++ /dev/null@@ -1,13 +0,0 @@-package server--import (- "github.com/labstack/echo/v4"-- "github.com/bytebase/bytebase/backend/common"-)--// DefaultAPIRequestSkipper is echo skipper for api requests.-func DefaultAPIRequestSkipper(c echo.Context) bool {- path := c.Path()- return common.HasPrefixes(path, "/api", "/v1", "/hook")-}diff --git a/backend/server/sql_test.go b/backend/server/sql_test.godeleted file mode 100644index 85204edcaa..0000000000--- a/backend/server/sql_test.go+++ /dev/null@@ -1,101 +0,0 @@-package server--import (- "testing"-- parser "github.com/bytebase/bytebase/backend/plugin/parser/sql"-)--func TestValidateSQLSelectStatement(t *testing.T) {- engines := []parser.EngineType{parser.MySQL, parser.Postgres, parser.MariaDB, parser.MSSQL, parser.Oracle, parser.TiDB, parser.Standard}- tests := []struct {- sqlStatement string- want bool- }{- {- sqlStatement: " seLeCT * FROM test",- want: true,- },- {- sqlStatement: " \n \r SELEct * from test ",- want: true,- },- {- sqlStatement: "SELECT\n*\nFROM\ntest",- want: true,- },- {- sqlStatement: "SELECT * FROM test",- want: true,- },- {- sqlStatement: "select *",- want: true,- },- {- sqlStatement: "select ",- want: false,- },- {- sqlStatement: "select",- want: false,- },- {- sqlStatement: "explain select",- want: true,- },- {- sqlStatement: "explain \n select",- want: true,- },- {- sqlStatement: "\n explain \n \r select",- want: true,- },- {- sqlStatement: "explain select *",- want: true,- },- {- sqlStatement: " explain select ",- want: true,- },- {- sqlStatement: "asd explain selectasd ",- want: false,- },- {- sqlStatement: "SELECTfoo",- want: false,- },- {- sqlStatement: "insert into asd",- want: false,- },- {- sqlStatement: "SETEST * FROM test",- want: false,- },- {- sqlStatement: " asdexplain selectasd ",- want: false,- },- {- sqlStatement: "",- want: false,- },- {- sqlStatement: "SETEST 1; INSERT INTO tbl(num) VALUES(113);",- want: false,- },- }-- for _, test := range tests {- for _, engine := range engines {- result := parser.ValidateSQLForEditor(engine, test.sqlStatement)- if result != test.want {- t.Errorf("Validate SQLStatement %q: got result %v, want %v, for engine %s.", test.sqlStatement, result, test.want, engine)- }- }- }-}diff --git a/go.mod b/go.modindex 52c5760ec7..2e4e6367c8 100644--- a/go.mod+++ b/go.mod@@ -17,7 +17,6 @@ require (github.com/bytebase/mysql-parser v0.0.0-20230612050356-4592d9ba30dagithub.com/bytebase/plsql-parser v0.0.0-20230706061841-c93470b91beegithub.com/bytebase/snowsql-parser v0.0.0-20230706111031-cafd8faa2dc9- github.com/casbin/casbin/v2 v2.71.1github.com/cenkalti/backoff/v4 v4.2.1github.com/coreos/go-oidc v2.2.1+incompatiblegithub.com/dgraph-io/ristretto v0.1.1-0.20220403145359-8e850b710d6d@@ -51,7 +50,6 @@ require (github.com/pingcap/tidb v1.1.0-beta.0.20220825063022-5263a0abda61github.com/pingcap/tidb/parser v0.0.0-20221101143359-5b0be9af540egithub.com/pkg/errors v0.9.1- github.com/qiangmzsx/string-adapter/v2 v2.2.0github.com/redis/go-redis/v9 v9.0.5github.com/sashabaranov/go-openai v1.9.0github.com/segmentio/analytics-go v3.1.0+incompatible@@ -144,7 +142,6 @@ require (cloud.google.com/go/longrunning v0.5.1 // indirectgithub.com/BurntSushi/toml v1.2.1 // indirectgithub.com/ClickHouse/ch-go v0.57.0 // indirect- github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible // indirectgithub.com/KyleBanks/depth v1.2.1 // indirectgithub.com/andybalholm/brotli v1.0.5 // indirectgithub.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.10 // indirectdiff --git a/go.sum b/go.sumindex 88818e83bf..08683b2dce 100644--- a/go.sum+++ b/go.sum@@ -46,7 +46,6 @@ github.com/HdrHistogram/hdrhistogram-go v1.1.2 h1:5IcZpTvzydCQeHzK4Ef/D5rrSqwxobgithub.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo=github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c h1:RGWPOewvKIROun94nF7v2cua9qP+thov/7M50KEoeSU=github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c/go.mod h1:X0CRv0ky0k6m906ixxpzmDRLvX58TFUKS2eePweuyxk=-github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible h1:1G1pk05UrOh0NlF1oeaaix1x8XzrfjIDK47TY0Zehcw=github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=@@ -165,8 +164,6 @@ github.com/bytebase/tidb/parser v0.0.0-20230329095902-fe196d3c77d0/go.mod h1:wjvgithub.com/bytebase/tsql-parser v0.0.0-20230717060948-f266bf0280e2 h1:o0jnYa8jLE9kgkDcCw89xIqGUrk+T4ZHjmmHwI8+8mM=github.com/bytebase/tsql-parser v0.0.0-20230717060948-f266bf0280e2/go.mod h1:RGdpxRQZHTqMjTKZUKGGZduIXu2lPyboIuWsqV7drX8=github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=-github.com/casbin/casbin/v2 v2.71.1 h1:LRHyqM0S1LzM/K59PmfUIN0ZJfLgcOjL4OhOQI/FNXU=-github.com/casbin/casbin/v2 v2.71.1/go.mod h1:vByNa/Fchek0KZUgG5wEsl7iFsiviAYKRtgrQfcJqHg=github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=github.com/cenkalti/backoff/v4 v4.1.1/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM=@@ -374,9 +371,6 @@ github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4ergithub.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=-github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4=-github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=-github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=@@ -835,8 +829,6 @@ github.com/prometheus/procfs v0.3.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4Ogithub.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=github.com/prometheus/procfs v0.9.0 h1:wzCHvIvM5SxWqYvwgVL7yJY8Lz3PKn49KQtpgMYJfhI=github.com/prometheus/procfs v0.9.0/go.mod h1:+pB4zwohETzFnmlpe6yd2lSc+0/46IYZRB/chUwxUZY=-github.com/qiangmzsx/string-adapter/v2 v2.2.0 h1:YorFwrG270/ZgCNvD5SCWB8vLpVsk3T9xGIDLSSqaSQ=-github.com/qiangmzsx/string-adapter/v2 v2.2.0/go.mod h1:29JjVZ+CIMXhExZyL+swYShd4vRvQyQ/6jM0ML5u6NI=github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=github.com/redis/go-redis/v9 v9.0.5 h1:CuQcn5HIEeK7BgElubPP8CGtE0KakrnbBSTLjathl5o=github.com/redis/go-redis/v9 v9.0.5/go.mod h1:WqMKv5vnQbRuZstUwxQI195wHy+t4PuXDOjzMvcuQHk=@@ -1259,7 +1251,6 @@ golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=-golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=