Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: optimize hub plugin and inline validation (#18356)
Danny Xub59fb2819672
diff --git a/backend/api/v1/setting_service.go b/backend/api/v1/setting_service.goindex 6c1ae85a70..8509056a27 100644--- a/backend/api/v1/setting_service.go+++ b/backend/api/v1/setting_service.go@@ -522,7 +522,7 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *connect.Req}), nil}- setting, err := s.store.UpsertSetting(ctx, &store.SetSettingMessage{+ setting, err := s.store.UpsertSetting(ctx, &store.SettingMessage{Name: apiSettingName,Value: storeSettingValue,})diff --git a/backend/enterprise/config/config.go b/backend/enterprise/config/config.goindex 2462dcde68..675212c51e 100644--- a/backend/enterprise/config/config.go+++ b/backend/enterprise/config/config.go@@ -2,10 +2,12 @@package configimport (+ "crypto/rsa""embed""fmt""io/fs"+ "github.com/golang-jwt/jwt/v5""github.com/pkg/errors""github.com/bytebase/bytebase/backend/common"@@ -16,8 +18,8 @@ var keysFS embed.FS// Config is the API message for enterprise config.type Config struct {- // PublicKey is the key we used to decrypt license.- PublicKey string+ // PublicKey is the parsed RSA public key.+ PublicKey *rsa.PublicKey// Version is the JWT key version.Version string// Issuer is the license issuer, it should always be "bytebase".@@ -44,8 +46,13 @@ func NewConfig(mode common.ReleaseMode) (*Config, error) {return nil, errors.Errorf("cannot read license public key for env %s", mode)}+ key, err := jwt.ParseRSAPublicKeyFromPEM(licensePubKey)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to parse license public key for env %s", mode)+ }+return &Config{- PublicKey: string(licensePubKey),+ PublicKey: key,Version: keyID,Issuer: issuer,Audience: audience,diff --git a/backend/enterprise/plugin/hub/hub.go b/backend/enterprise/plugin/hub/hub.goindex e0882013bd..ea83092515 100644--- a/backend/enterprise/plugin/hub/hub.go+++ b/backend/enterprise/plugin/hub/hub.go@@ -39,26 +39,7 @@ type claims struct {jwt.RegisteredClaims}-var validPlans = map[v1pb.PlanType]bool{- v1pb.PlanType_FREE: true,- v1pb.PlanType_TEAM: true,- v1pb.PlanType_ENTERPRISE: true,-}-// validateSubscription validates if the subscription is expired or has correct plan type.-func validateSubscription(s *v1pb.Subscription) error {- if !validPlans[s.Plan] {- return errors.Errorf("plan %q is not valid, expect %s or %s",- s.Plan.String(),- v1pb.PlanType_TEAM.String(),- v1pb.PlanType_ENTERPRISE.String(),- )- }- if s.ExpiresTime != nil && s.ExpiresTime.AsTime().Before(time.Now()) {- return errors.Errorf("license has expired at %v", s.ExpiresTime.AsTime())- }- return nil-}// NewProvider will create a new hub license provider.func NewProvider(providerConfig *plugin.ProviderConfig) (plugin.LicenseProvider, error) {@@ -76,70 +57,69 @@ func NewProvider(providerConfig *plugin.ProviderConfig) (plugin.LicenseProvider,// StoreLicense will store the hub license.func (p *Provider) StoreLicense(ctx context.Context, license string) error {if license != "" {- if _, err := p.parseLicense(ctx, license); err != nil {+ systemSetting, err := p.store.GetSystemSetting(ctx)+ if err != nil {+ return errors.Wrapf(err, "failed to get system setting")+ }+ if _, err := p.parseLicense(license, systemSetting.WorkspaceId); err != nil {return err}}- return p.store.UpsertEnterpriseLicense(ctx, license)+ return p.store.UpdateLicense(ctx, license)}// LoadSubscription will load the hub subscription.func (p *Provider) LoadSubscription(ctx context.Context) *v1pb.Subscription {- license, err := p.findEnterpriseLicense(ctx)+ systemSetting, err := p.store.GetSystemSetting(ctx)if err != nil {- slog.Debug("failed to load enterprise license", log.BBError(err))+ slog.Debug("failed to load enterprise license", log.BBError(errors.Wrapf(err, "failed to get system setting")))+ return nil}- if license == nil {+ if systemSetting.License == "" {return nil}- if err := validateSubscription(license); err != nil {- slog.Debug("license is invalid", log.BBError(err))+ license, err := p.parseLicense(systemSetting.License, systemSetting.WorkspaceId)+ if err != nil {+ slog.Debug("failed to load enterprise license", log.BBError(errors.Wrapf(err, "failed to parse enterprise license")))return nil}++ slog.Debug(+ "Load valid license",+ slog.String("plan", license.Plan.String()),+ slog.Time("expiresAt", license.ExpiresTime.AsTime()),+ slog.Int("activeInstances", int(license.ActiveInstances)),+ slog.Int("instances", int(license.Instances)),+ slog.Int("seats", int(license.Seats)),+ )+return license}-func (p *Provider) parseLicense(ctx context.Context, license string) (*v1pb.Subscription, error) {+func (p *Provider) parseLicense(license, workspaceID string) (*v1pb.Subscription, error) {claim := &claims{}- if err := parseJWTToken(license, p.config.Version, p.config.PublicKey, claim); err != nil {- return nil, common.Wrap(err, common.Invalid)- }+ token, err := jwt.ParseWithClaims(license, claim, func(token *jwt.Token) (any, error) {+ if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {+ return nil, common.Errorf(common.Invalid, "unexpected signing method: %v", token.Header["alg"])+ }- return p.parseClaims(ctx, claim)-}+ kid, ok := token.Header["kid"].(string)+ if !ok || kid != p.config.Version {+ return nil, common.Errorf(common.Invalid, "version '%v' is not valid. expect %s", token.Header["kid"], p.config.Version)+ }-func (p *Provider) findEnterpriseLicense(ctx context.Context) (*v1pb.Subscription, error) {- // Find enterprise license.- systemSetting, err := p.store.GetSystemSetting(ctx)+ return p.config.PublicKey, nil+ })if err != nil {- return nil, errors.Wrapf(err, "failed to get system setting")- }- licenseStr := systemSetting.License- if licenseStr != "" {- license, err := p.parseLicense(ctx, licenseStr)- if err != nil {- return nil, errors.Wrapf(err, "failed to parse enterprise license")- }- if license != nil {- slog.Debug(- "Load valid license",- slog.String("plan", license.Plan.String()),- slog.Time("expiresAt", license.ExpiresTime.AsTime()),- slog.Int("activeInstances", int(license.ActiveInstances)),- slog.Int("instances", int(license.Instances)),- slog.Int("seats", int(license.Seats)),- )- return license, nil- }+ return nil, common.Wrap(err, common.Invalid)}- return nil, nil-}+ if !token.Valid {+ return nil, common.Errorf(common.Invalid, "invalid token")+ }-// parseClaims will valid and parse JWT claims to license instance.-func (p *Provider) parseClaims(ctx context.Context, claim *claims) (*v1pb.Subscription, error) {if p.config.Issuer != claim.Issuer {return nil, common.Errorf(common.Invalid, "iss is not valid, expect %s but found '%v'", p.config.Issuer, claim.Issuer)}@@ -154,22 +134,30 @@ func (p *Provider) parseClaims(ctx context.Context, claim *claims) (*v1pb.SubscrplanType := v1pb.PlanType(v)if claim.WorkspaceID != "" && planType == v1pb.PlanType_ENTERPRISE && !claim.Trialing {- systemSetting, err := p.store.GetSystemSetting(ctx)- if err != nil {- return nil, errors.Wrapf(err, "failed to get system setting")- }- workspaceID := systemSetting.WorkspaceIdif workspaceID != claim.WorkspaceID {return nil, common.Errorf(common.Invalid, "the workspace id not match")}}+ switch planType {+ case v1pb.PlanType_FREE, v1pb.PlanType_TEAM, v1pb.PlanType_ENTERPRISE:+ default:+ return nil, errors.Errorf("plan %q is not valid, expect %s or %s",+ planType.String(),+ v1pb.PlanType_TEAM.String(),+ v1pb.PlanType_ENTERPRISE.String(),+ )+ }+var expiresTime *timestamppb.Timestampif claim.ExpiresAt != nil && !claim.ExpiresAt.IsZero() {expiresTime = timestamppb.New(claim.ExpiresAt.Time)}+ if expiresTime != nil && expiresTime.AsTime().Before(time.Now()) {+ return nil, errors.Errorf("license has expired at %v", expiresTime.AsTime())+ }- license := &v1pb.Subscription{+ return &v1pb.Subscription{ActiveInstances: int32(claim.ActiveInstances),Instances: int32(claim.Instances),Seats: int32(claim.Seats),@@ -177,36 +165,5 @@ func (p *Provider) parseClaims(ctx context.Context, claim *claims) (*v1pb.SubscrPlan: planType,Trialing: claim.Trialing,OrgName: claim.OrgName,- }-- return license, nil-}--func parseJWTToken(tokenString, expectVersion, publicKey string, claims jwt.Claims) error {- token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (any, error) {- if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {- return nil, common.Errorf(common.Invalid, "unexpected signing method: %v", token.Header["alg"])- }-- kid, ok := token.Header["kid"].(string)- if !ok || kid != expectVersion {- return nil, common.Errorf(common.Invalid, "version '%v' is not valid. expect %s", token.Header["kid"], expectVersion)- }-- key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(publicKey))- if err != nil {- return nil, common.Wrap(err, common.Invalid)- }-- return key, nil- })- if err != nil {- return common.Wrap(err, common.Invalid)- }-- if !token.Valid {- return common.Errorf(common.Invalid, "invalid token")- }-- return nil+ }, nil}diff --git a/backend/store/setting.go b/backend/store/setting.goindex a04542d35a..19072562a9 100644--- a/backend/store/setting.go+++ b/backend/store/setting.go@@ -13,12 +13,6 @@ import (storepb "github.com/bytebase/bytebase/backend/generated-go/store")-// SetSettingMessage is the message for updating setting.-type SetSettingMessage struct {- Name storepb.SettingName- Value proto.Message-}-// SettingMessage is the message of setting.type SettingMessage struct {Name storepb.SettingName@@ -97,33 +91,27 @@ func (s *Store) GetSystemSetting(ctx context.Context) (*storepb.SystemSetting, ereturn val, nil}-// UpsertEnterpriseLicense updates the enterprise license in SYSTEM setting.-func (s *Store) UpsertEnterpriseLicense(ctx context.Context, license string) error {+// UpdateLicense updates the license in SYSTEM setting.+func (s *Store) UpdateLicense(ctx context.Context, license string) error {setting, err := s.GetSetting(ctx, storepb.SettingName_SYSTEM)if err != nil {return errors.Wrap(err, "failed to get system setting")}-- var systemSetting *storepb.SystemSetting- if setting != nil {- val, ok := setting.Value.(*storepb.SystemSetting)- if !ok {- return errors.Errorf("invalid setting value type for %s", storepb.SettingName_SYSTEM)- }- systemSetting = val- } else {- systemSetting = &storepb.SystemSetting{}+ if setting == nil {+ return errors.Errorf("system setting not found")+ }+ systemSetting, ok := setting.Value.(*storepb.SystemSetting)+ if !ok {+ return errors.Errorf("invalid system setting value type for %s", storepb.SettingName_SYSTEM)}systemSetting.License = license-- if _, err := s.UpsertSetting(ctx, &SetSettingMessage{+ if _, err := s.UpsertSetting(ctx, &SettingMessage{Name: storepb.SettingName_SYSTEM,Value: systemSetting,}); err != nil {return errors.Wrap(err, "failed to upsert system setting")}-return nil}@@ -306,7 +294,7 @@ func (s *Store) ListSettings(ctx context.Context, find *FindSettingMessage) ([]*}// UpsertSetting upserts the setting by name.-func (s *Store) UpsertSetting(ctx context.Context, update *SetSettingMessage) (*SettingMessage, error) {+func (s *Store) UpsertSetting(ctx context.Context, update *SettingMessage) (*SettingMessage, error) {valueBytes, err := protojson.Marshal(update.Value)if err != nil {return nil, errors.Wrap(err, "failed to marshal setting value")