Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support change subscription in dev env (#530)
ecmadaodfc05de9c923
diff --git a/enterprise/api/license.go b/enterprise/api/license.goindex c481e878a3..dae41195b9 100644--- a/enterprise/api/license.go+++ b/enterprise/api/license.go@@ -23,8 +23,7 @@ type License struct {// Valid will check if license expired or has correct plan type.func (l *License) Valid() error {- expireTime := time.Unix(l.ExpiresTs, 0)- if expireTime.Before(time.Now()) {+ if expireTime := time.Unix(l.ExpiresTs, 0); expireTime.Before(time.Now()) {return fmt.Errorf("license has expired at %v", expireTime)}diff --git a/enterprise/config/keys/dev.pub.pem b/enterprise/config/keys/dev.pub.pemindex 63d183a71d..d193d7e07a 100644--- a/enterprise/config/keys/dev.pub.pem+++ b/enterprise/config/keys/dev.pub.pem@@ -1,9 +1,9 @@-----BEGIN PUBLIC KEY------MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwOnNEhoNLnBiv9+Vw3NH-o2hRZNp8eehBfJaoTdsF7GLYWZKcBjvSB/RuVdWdFJ2/X4QTkcJeKFN6q3w+86dY-HKqrVzBxSxeIj1YMhyCNO4uECdrzBp8kcG7m8mN8r5glMMLE8ShAstPFCzKWbGw9-aHFs3a5nQfWjn5X2SbfGLm1BhHzatDM6Cvmnt8NDSLqVjbPzT1TKH0owljYEIZwY-m6BBHXyIQLmzsbb9yPVotYMn2cz4OUShwNW8LbXr8mjk+8lw3OcUn3W5CoF33aD4-nsFFtgrlXmmgdaCP22bBha6iHz0Ff31lmuDZIYjaOAeTqyUxEV78Tg04ht6Kgmeu+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqL2T+Q2U+XoShxOCLL6w+Roe6+FgS6huDpqtkNjUz8xJlzusgoQdx5s5ucG1XMBXjFqmM/LKGO2tRgL0W/ywb+yFPFaNkp096WRy0jIksrKCFvLtTKMqsjvV+NUtDLgC7CPShlAyPWKZgfBiNEIKcw+8FEWynQxzfmb5Lh9iJzNohjm899n7urV3PcTnXhs9A7w24YyB1ykTjLnZssWS9h2+EAsVkbj2yzWYCVWOmmO7s/LBFM+EUxcyYmkcB/y/sgGVMjo9z8F7v4ebO+Vk4t2E+3RRrlseJFEZcNAfZoxt25Cl4VYWOj8LQeAOybG4l8Eb9lN4Xmic0T1gr+ABRcCKfowIDAQAB-----END PUBLIC KEY-----diff --git a/enterprise/config/keys/local.pub.pem b/enterprise/config/keys/local.pub.pemdeleted file mode 100644index d193d7e07a..0000000000--- a/enterprise/config/keys/local.pub.pem+++ /dev/null@@ -1,9 +0,0 @@------BEGIN PUBLIC KEY------MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqL2T+Q2U+XoShxOCLL6w-Roe6+FgS6huDpqtkNjUz8xJlzusgoQdx5s5ucG1XMBXjFqmM/LKGO2tRgL0W/ywb-yFPFaNkp096WRy0jIksrKCFvLtTKMqsjvV+NUtDLgC7CPShlAyPWKZgfBiNEIKcw-8FEWynQxzfmb5Lh9iJzNohjm899n7urV3PcTnXhs9A7w24YyB1ykTjLnZssWS9h2-EAsVkbj2yzWYCVWOmmO7s/LBFM+EUxcyYmkcB/y/sgGVMjo9z8F7v4ebO+Vk4t2E-3RRrlseJFEZcNAfZoxt25Cl4VYWOj8LQeAOybG4l8Eb9lN4Xmic0T1gr+ABRcCKf-owIDAQAB------END PUBLIC KEY-----diff --git a/enterprise/service/license.go b/enterprise/service/license.goindex 2da0673b02..988a827fc3 100644--- a/enterprise/service/license.go+++ b/enterprise/service/license.go@@ -79,18 +79,18 @@ func (s *licenseService) parseClaims(claims jwt.MapClaims) (*enterpriseAPI.Licenreturn nil, common.Errorf(common.Invalid, err)}- exp, ok := claims["exp"].(int64)+ exp, ok := claims["exp"].(float64)if !ok {return nil, common.Errorf(common.Invalid, fmt.Errorf("exp is not valid, found '%v'", claims["exp"]))}- iss, ok := claims["iss"].(string)- if !ok || iss != s.config.Issuer {+ verifyIssuer := claims.VerifyIssuer(s.config.Issuer, true)+ if !verifyIssuer {return nil, common.Errorf(common.Invalid, fmt.Errorf("iss is not valid, expect %s but found '%v'", s.config.Issuer, claims["iss"]))}- instance, ok := claims["instance"].(int)- if !ok || instance < s.config.MinimumInstance {+ instance, ok := claims["instance"].(float64)+ if !ok || int(instance) < s.config.MinimumInstance {return nil, common.Errorf(common.Invalid, fmt.Errorf("license instance count '%v' is not valid, minimum instance requirement is %d", claims["instance"], s.config.MinimumInstance))}@@ -110,8 +110,8 @@ func (s *licenseService) parseClaims(claims jwt.MapClaims) (*enterpriseAPI.Licen}license := &enterpriseAPI.License{- InstanceCount: instance,- ExpiresTs: exp,+ InstanceCount: int(instance),+ ExpiresTs: int64(exp),Plan: planType,Audience: aud,}diff --git a/frontend/.env.dev b/frontend/.env.devindex c0d6652113..b7e6294adf 100644--- a/frontend/.env.dev+++ b/frontend/.env.dev@@ -1 +1,2 @@NODE_ENV=development+BB_DEV_LICENSE=eyJhbGciOiJSUzI1NiIsImtpZCI6InYxIiwic2F0IjoiNTYxNTQzMjUiLCJzaWQiOiIxNzMzMjY5NCIsInR5cCI6IkpXVCJ9.eyJhdWQiOiI5MjUyMzA4MCIsImV4cCI6MzMxNjkzOTIwMDAsImlhdCI6MTY0MzQ2Mzg4MiwiaW5zdGFuY2UiOjk5OTksImlzcyI6ImJ5dGViYXNlIiwicGxhbiI6IlRFQU0iLCJzdWIiOiJPUkdBTklaQVRJT04ifQ.lKaJ-xFrJTBeRPWIzLrvy17beMffCwD9DQhZrgNnyRSkIOwtsHR8VHNy_2vU6RdqGJdZzopf6YPpueRy6KD_R3q5TDr1dbeKT9ug_ELXd4pLt-5c63mCHggCg19yEbSmzmwibQ9KPkbG-KL8ZfGp_SD0bScnpfrTCpb8GNfh-3JCmdlC0dYX8-2QbGrDeDt2yOPI2UK-cCzvgrYXMIKwuGtK2s5iBRa5OMxmOUww16rVLLHiJ4zz0YR1VG2-IM5fIeadRpPc1DqBeeKqwR-FaUJvIg_grG5IeixBcwPH7_ovk2RiZEFri-EdEOfrK_GMUpxp7_Wyy1-J6xaq0eW1fwdiff --git a/frontend/src/importMeta.d.ts b/frontend/src/importMeta.d.tsindex d78d96a25d..0ff387afcd 100644--- a/frontend/src/importMeta.d.ts+++ b/frontend/src/importMeta.d.ts@@ -67,4 +67,5 @@ interface ImportMetaEnv {DEV: boolean;PROD: boolean;SSR: boolean;+ BB_DEV_LICENSE: string;}diff --git a/frontend/src/store/modules/subscription.ts b/frontend/src/store/modules/subscription.tsindex 3c62f96b0a..760cab34be 100644--- a/frontend/src/store/modules/subscription.ts+++ b/frontend/src/store/modules/subscription.ts@@ -58,17 +58,6 @@ const actions = {commit("setSubscription", subscription);return subscription;},-- // TODO: this is a mock function, should remove this before GA- async changePlan({ commit }: any, newPlan: PlanType) {- const subscription: Subscription = {- instanceCount: 5,- plan: newPlan,- expiresTs: new Date().getTime() / 1000 + 24 * 60 * 60,- };- console.debug(`set subscription: ${JSON.stringify(subscription)}`);- commit("setSubscription", subscription);- },};const mutations = {diff --git a/frontend/src/views/DashboardHeader.vue b/frontend/src/views/DashboardHeader.vueindex 915782a493..04ee7a77d4 100644--- a/frontend/src/views/DashboardHeader.vue+++ b/frontend/src/views/DashboardHeader.vue@@ -67,13 +67,6 @@>{{ $t("setting.plan.team") }}</div>- <!-- <div- class="bar-link"- :class="currentPlan == 2 ? 'underline' : ''"- @click.prevent="switchToEnterprise"- >- {{ $t('setting.plan.enterprise') }}- </div>--></div><divv-if="!isRelease"@@ -192,7 +185,7 @@ import { useStore } from "vuex";import { useI18n } from "vue-i18n";import ProfileDropdown from "../components/ProfileDropdown.vue";-import { InboxSummary, PlanType, UNKNOWN_ID } from "../types";+import { InboxSummary, UNKNOWN_ID } from "../types";import { isDBAOrOwner, isDev } from "../utils";import { useLanguage } from "../composables/useLanguage";@@ -270,18 +263,15 @@ export default defineComponent({});};- // TODO: Do we still need this?- // Maybe we need to change the UX, redirect user to subscription page?const switchToFree = () => {- store.dispatch("subscription/changePlan", PlanType.FREE);+ store.dispatch("subscription/patchSubscription", "");};const switchToTeam = () => {- store.dispatch("subscription/changePlan", PlanType.TEAM);- };-- const switchToEnterprise = () => {- store.dispatch("subscription/changePlan", PlanType.ENTERPRISE);+ store.dispatch(+ "subscription/patchSubscription",+ import.meta.env.BB_DEV_LICENSE+ );};const kbarActions = computed(() => [@@ -373,7 +363,6 @@ export default defineComponent({switchToDeveloper,switchToFree,switchToTeam,- switchToEnterprise,toggleLocales,};},diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 747e2105cf..31dbb761f6 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -59,5 +59,6 @@ export default defineConfig(() => {global: true,environment: "node",},+ envPrefix: "BB_",};});diff --git a/server/plan.go b/server/plan.godeleted file mode 100644index c8bc7bee8e..0000000000--- a/server/plan.go+++ /dev/null@@ -1,45 +0,0 @@-package server--import (- "net/http"-- "github.com/bytebase/bytebase/api"- "github.com/google/jsonapi"- "github.com/labstack/echo/v4"-)--func (s *Server) registerPlanRoutes(g *echo.Group) {- g.GET("/plan", func(c echo.Context) error {- plan := &api.Plan{- Type: s.plan,- }- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, plan); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal plan response").SetInternal(err)- }- return nil- })-- g.PATCH("/plan", func(c echo.Context) error {- planPatch := &api.PlanPatch{}- if err := jsonapi.UnmarshalPayload(c.Request().Body, planPatch); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted update plan request").SetInternal(err)- }-- s.plan = planPatch.Type-- plan := &api.Plan{- Type: s.plan,- }- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, plan); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal plan response").SetInternal(err)- }- return nil- })-}--func (s *Server) feature(feature api.FeatureType) bool {- subscription := s.loadSubscription()- return api.FeatureMatrix[feature][subscription.Plan]-}diff --git a/server/server.go b/server/server.goindex 965837f3ef..76b7dd5041 100644--- a/server/server.go+++ b/server/server.go@@ -67,7 +67,7 @@ type Server struct {DeploymentConfigService api.DeploymentConfigServiceSavedQueryService api.SavedQueryServiceLicenseService enterprise.LicenseService- SheetService api.SheetService+ SheetService api.SheetServicee *echo.Echo@@ -82,7 +82,6 @@ type Server struct {secret stringreadonly booldemo bool- plan api.PlanTypedataDir string}@@ -126,7 +125,6 @@ func NewServer(logger *zap.Logger, version string, host string, port int, frontesecret: secret,readonly: readonly,demo: demo,- plan: api.TEAM,dataDir: dataDir,}@@ -239,7 +237,6 @@ func NewServer(logger *zap.Logger, version string, host string, port int, frontes.registerBookmarkRoutes(apiGroup)s.registerSQLRoutes(apiGroup)s.registerVCSRoutes(apiGroup)- s.registerPlanRoutes(apiGroup)s.registerLabelRoutes(apiGroup)s.registerSavedQueryRoutes(apiGroup)s.registerSubscriptionRoutes(apiGroup)diff --git a/server/subscription.go b/server/subscription.goindex b23a4f8322..74b0a40610 100644--- a/server/subscription.go+++ b/server/subscription.go@@ -6,7 +6,6 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"- enterprise "github.com/bytebase/bytebase/enterprise/api"enterpriseAPI "github.com/bytebase/bytebase/enterprise/api""github.com/google/jsonapi""github.com/labstack/echo/v4"@@ -34,15 +33,7 @@ func (s *Server) registerSubscriptionRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create license").SetInternal(err)}- license, err := s.loadLicense()- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Failed to load subscription").SetInternal(err)- }- subscription := &enterpriseAPI.Subscription{- Plan: license.Plan,- ExpiresTs: license.ExpiresTs,- InstanceCount: license.InstanceCount,- }+ subscription := s.loadSubscription()c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)if err := jsonapi.MarshalPayload(c.Response().Writer, subscription); err != nil {@@ -54,9 +45,9 @@ func (s *Server) registerSubscriptionRoutes(g *echo.Group) {// loadLicense will load current subscription by license.// Return subscription with free plan if no license found.-func (server *Server) loadSubscription() *enterprise.Subscription {+func (server *Server) loadSubscription() *enterpriseAPI.Subscription {subscription := &enterpriseAPI.Subscription{- Plan: api.TEAM,+ Plan: api.FREE,// -1 means not expire, just for free planExpiresTs: -1,InstanceCount: 5,@@ -68,18 +59,13 @@ func (server *Server) loadSubscription() *enterprise.Subscription {ExpiresTs: license.ExpiresTs,InstanceCount: license.InstanceCount,}- } else {- // increase instance quota for dev environment.- if server.mode == "dev" {- subscription.InstanceCount = subscription.InstanceCount * 2- }}return subscription}// loadLicense will get and parse valid license from file.-func (server *Server) loadLicense() (*enterprise.License, error) {+func (server *Server) loadLicense() (*enterpriseAPI.License, error) {license, err := server.LicenseService.LoadLicense()if err != nil {if common.ErrorCode(err) == common.NotFound {@@ -99,3 +85,8 @@ func (server *Server) loadLicense() (*enterprise.License, error) {return license, nil}++func (s *Server) feature(feature api.FeatureType) bool {+ subscription := s.loadSubscription()+ return api.FeatureMatrix[feature][subscription.Plan]+}diff --git a/tests/fake/license b/tests/fake/licensenew file mode 100644index 0000000000..01139bf322--- /dev/null+++ b/tests/fake/license@@ -0,0 +1 @@+eyJhbGciOiJSUzI1NiIsImtpZCI6InYxIiwic2F0IjoiNTYxNTQzMjUiLCJzaWQiOiIxNzMzMjY5NCIsInR5cCI6IkpXVCJ9.eyJhdWQiOiI5MjUyMzA4MCIsImV4cCI6MzMxNjkzOTIwMDAsImlhdCI6MTY0MzQ2Mzg4MiwiaW5zdGFuY2UiOjk5OTksImlzcyI6ImJ5dGViYXNlIiwicGxhbiI6IlRFQU0iLCJzdWIiOiJPUkdBTklaQVRJT04ifQ.lKaJ-xFrJTBeRPWIzLrvy17beMffCwD9DQhZrgNnyRSkIOwtsHR8VHNy_2vU6RdqGJdZzopf6YPpueRy6KD_R3q5TDr1dbeKT9ug_ELXd4pLt-5c63mCHggCg19yEbSmzmwibQ9KPkbG-KL8ZfGp_SD0bScnpfrTCpb8GNfh-3JCmdlC0dYX8-2QbGrDeDt2yOPI2UK-cCzvgrYXMIKwuGtK2s5iBRa5OMxmOUww16rVLLHiJ4zz0YR1VG2-IM5fIeadRpPc1DqBeeKqwR-FaUJvIg_grG5IeixBcwPH7_ovk2RiZEFri-EdEOfrK_GMUpxp7_Wyy1-J6xaq0eW1fwdiff --git a/tests/schema_update_test.go b/tests/schema_update_test.goindex 53a0265005..2d73cc3149 100644--- a/tests/schema_update_test.go+++ b/tests/schema_update_test.go@@ -2,17 +2,23 @@ package testsimport ("context"+ "embed""encoding/json""fmt"+ "io/fs""testing""github.com/bytebase/bytebase/api"+ enterpriseAPI "github.com/bytebase/bytebase/enterprise/api""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/vcs""github.com/bytebase/bytebase/plugin/vcs/gitlab""github.com/kr/pretty")+//go:embed fake+var fakeFS embed.FS+func TestSchemaUpdate(t *testing.T) {ctx := context.Background()ctl := &controller{}@@ -26,6 +32,17 @@ func TestSchemaUpdate(t *testing.T) {t.Fatal(err)}+ license, err := fs.ReadFile(fakeFS, "fake/license")+ if err != nil {+ t.Fatal(err)+ }+ err = ctl.switchPlan(&enterpriseAPI.SubscriptionPatch{+ License: string(license),+ })+ if err != nil {+ t.Fatal(err)+ }+// Create a project.project, err := ctl.createProject(api.ProjectCreate{Name: "Test Project",diff --git a/tests/tests.go b/tests/tests.goindex b6cd42c2e5..2810da8e00 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -15,6 +15,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/bin/server/cmd"+ enterpriseAPI "github.com/bytebase/bytebase/enterprise/api""github.com/bytebase/bytebase/tests/fake""github.com/google/jsonapi")@@ -334,6 +335,20 @@ func (ctl *controller) getDatabases(databaseFind api.DatabaseFind) ([]*api.Databreturn databases, nil}+func (ctl *controller) switchPlan(patch *enterpriseAPI.SubscriptionPatch) error {+ buf := new(bytes.Buffer)+ if err := jsonapi.MarshalPayload(buf, patch); err != nil {+ return fmt.Errorf("failed to marshal subscription patch, error: %w", err)+ }++ _, err := ctl.patch("/subscription", buf)+ if err != nil {+ return err+ }++ return nil+}+// addInstance adds an instance.func (ctl *controller) addInstance(instanceCreate api.InstanceCreate) (*api.Instance, error) {buf := new(bytes.Buffer)