Skip to content

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

feat: refresh subscription license (#4790)

ecmadao28795ef5c367
diff --git a/backend/enterprise/config/config.go b/backend/enterprise/config/config.go
index 52437583f3..3d6354de3f 100644
--- a/backend/enterprise/config/config.go
+++ b/backend/enterprise/config/config.go
@@ -24,6 +24,10 @@ type Config struct {
Issuer string
// Audience is the license audience, it should always be "bb.license".
Audience string
+ // HubAPIURL is the API URL for Bytebase hub.
+ HubAPIURL string
+ // Mode can be "prod" or "dev"
+ Mode common.ReleaseMode
}
const (
@@ -39,8 +43,8 @@ const (
MaximumInstanceForFreePlan = 10
)
-// NewConfig will create a new enterprise config instance.
-func NewConfig(mode common.ReleaseMode) (*Config, error) {
+// getConfig will create a new enterprise config instance.
+func getConfig(mode common.ReleaseMode) (*Config, error) {
licensePubKey, err := fs.ReadFile(keysFS, fmt.Sprintf("keys/%s.pub.pem", mode))
if err != nil {
return nil, errors.Errorf("cannot read license public key for env %s", mode)
@@ -51,5 +55,6 @@ func NewConfig(mode common.ReleaseMode) (*Config, error) {
Version: keyID,
Issuer: issuer,
Audience: audience,
+ Mode: mode,
}, nil
}
diff --git a/backend/enterprise/config/config_dev.go b/backend/enterprise/config/config_dev.go
new file mode 100644
index 0000000000..7fbfe06fbd
--- /dev/null
+++ b/backend/enterprise/config/config_dev.go
@@ -0,0 +1,19 @@
+//go:build !release
+// +build !release
+
+package config
+
+import (
+ "github.com/bytebase/bytebase/backend/common"
+)
+
+// NewConfig will create a new enterprise config instance.
+func NewConfig(mode common.ReleaseMode) (*Config, error) {
+ config, err := getConfig(mode)
+ if err != nil {
+ return nil, err
+ }
+
+ config.HubAPIURL = "https://bytebase-hub-backend-dev.onrender.com"
+ return config, nil
+}
diff --git a/backend/enterprise/config/config_release.go b/backend/enterprise/config/config_release.go
new file mode 100644
index 0000000000..1f5fce2121
--- /dev/null
+++ b/backend/enterprise/config/config_release.go
@@ -0,0 +1,19 @@
+//go:build release
+// +build release
+
+package config
+
+import (
+ "github.com/bytebase/bytebase/backend/common"
+)
+
+// NewConfig will create a new enterprise config instance.
+func NewConfig(mode common.ReleaseMode) (*Config, error) {
+ config, err := getConfig(mode)
+ if err != nil {
+ return nil, err
+ }
+
+ config.HubAPIURL = "https://bytebase-hub-backend-prod.onrender.com"
+ return config, nil
+}
diff --git a/backend/enterprise/service/license.go b/backend/enterprise/service/license.go
index ef3ec5b2a6..31499a060a 100644
--- a/backend/enterprise/service/license.go
+++ b/backend/enterprise/service/license.go
@@ -20,9 +20,9 @@ import (
// LicenseService is the service for enterprise license.
type LicenseService struct {
- config *config.Config
- store *store.Store
-
+ config *config.Config
+ store *store.Store
+ provider *LicenseProvider
cachedSubscription *enterpriseAPI.Subscription
}
@@ -45,8 +45,9 @@ func NewLicenseService(mode common.ReleaseMode, store *store.Store) (*LicenseSer
}
return &LicenseService{
- store: store,
- config: config,
+ store: store,
+ config: config,
+ provider: NewLicenseProvider(config, store),
}, nil
}
@@ -75,10 +76,7 @@ func (s *LicenseService) LoadSubscription(ctx context.Context) enterpriseAPI.Sub
return *s.cachedSubscription
}
- license, err := s.loadLicense(ctx)
- if err != nil {
- log.Error("failed to load license", zap.Error(err))
- }
+ license := s.loadLicense(ctx)
if license == nil {
return enterpriseAPI.Subscription{
Plan: api.FREE,
@@ -138,22 +136,78 @@ func (s *LicenseService) RefreshCache(ctx context.Context) {
s.LoadSubscription(ctx)
}
+func (s *LicenseService) fetchLicense(ctx context.Context) (*enterpriseAPI.License, error) {
+ license, err := s.provider.FetchLicense(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if license == "" {
+ return nil, errors.Errorf("cannot fetch the license")
+ }
+ result, err := s.parseLicense(license)
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := s.store.PatchSetting(ctx, &api.SettingPatch{
+ UpdaterID: api.SystemBotID,
+ Name: api.SettingEnterpriseLicense,
+ Value: license,
+ }); err != nil {
+ return nil, errors.Wrapf(err, "failed to store the license")
+ }
+
+ s.RefreshCache(ctx)
+
+ return result, nil
+}
+
// loadLicense will load license and validate it.
-func (s *LicenseService) loadLicense(ctx context.Context) (*enterpriseAPI.License, error) {
+func (s *LicenseService) loadLicense(ctx context.Context) *enterpriseAPI.License {
+ license, err := s.findEnterpriseLicense(ctx)
+
+ if err != nil {
+ log.Debug("failed to load enterprise license", zap.Error(err))
+ license, err = s.findTrialingLicense(ctx)
+ if err != nil {
+ log.Debug("failed to load trialing license", zap.Error(err))
+ }
+ }
+
+ if err != nil {
+ log.Debug("failed to load license", zap.Error(err))
+ }
+
+ if license == nil && s.config.Mode == common.ReleaseModeDev {
+ license, err = s.fetchLicense(ctx)
+ if err != nil {
+ log.Debug("failed to fetch license", zap.Error(err))
+ }
+ }
+
+ return license
+}
+
+func (s *LicenseService) parseLicense(license string) (*enterpriseAPI.License, error) {
+ claims := &Claims{}
+ if err := parseJWTToken(license, s.config.Version, s.config.PublicKey, claims); err != nil {
+ return nil, common.Wrap(err, common.Invalid)
+ }
+
+ return s.parseClaims(claims)
+}
+
+func (s *LicenseService) findEnterpriseLicense(ctx context.Context) (*enterpriseAPI.License, error) {
// Find enterprise license.
settingName := api.SettingEnterpriseLicense
- settings, err := s.store.FindSetting(ctx, &api.SettingFind{
+ setting, err := s.store.GetSetting(ctx, &api.SettingFind{
Name: &settingName,
})
if err != nil {
return nil, errors.Wrapf(err, "failed to load enterprise license from settings")
}
- tokenString := ""
- if len(settings) > 0 {
- tokenString = settings[0].Value
- }
- if tokenString != "" {
- license, err := s.parseLicense(tokenString)
+ if setting != nil && setting.Value != "" {
+ license, err := s.parseLicense(setting.Value)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse enterprise license")
}
@@ -163,68 +217,36 @@ func (s *LicenseService) loadLicense(ctx context.Context) (*enterpriseAPI.Licens
zap.String("plan", license.Plan.String()),
zap.Time("expiresAt", time.Unix(license.ExpiresTs, 0)),
zap.Int("instanceCount", license.InstanceCount),
+ zap.Int("seat", license.Seat),
)
return license, nil
}
}
- // Find free trial license.
- settingName = api.SettingEnterpriseTrial
- settings, err = s.store.FindSetting(ctx, &api.SettingFind{
+ return nil, errors.Errorf("cannot find the enterprise license")
+}
+
+func (s *LicenseService) findTrialingLicense(ctx context.Context) (*enterpriseAPI.License, error) {
+ settingName := api.SettingEnterpriseTrial
+ setting, err := s.store.GetSetting(ctx, &api.SettingFind{
Name: &settingName,
})
if err != nil {
return nil, errors.Wrapf(err, "failed to load trial license from settings")
}
- if len(settings) != 0 {
+ if setting != nil && setting.Value != "" {
var data enterpriseAPI.License
- if err := json.Unmarshal([]byte(settings[0].Value), &data); err != nil {
+ if err := json.Unmarshal([]byte(setting.Value), &data); err != nil {
return nil, errors.Wrapf(err, "failed to parse trial license")
}
return &data, nil
}
- // No license or trial license found.
- return nil, nil
-}
-
-func (s *LicenseService) parseLicense(license string) (*enterpriseAPI.License, error) {
- claims := &Claims{}
- token, err := jwt.ParseWithClaims(license, claims, func(token *jwt.Token) (interface{}, 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 != s.config.Version {
- return nil, common.Errorf(common.Invalid, "version '%v' is not valid. expect %s", token.Header["kid"], s.config.Version)
- }
-
- key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(s.config.PublicKey))
- if err != nil {
- return nil, common.Wrap(err, common.Invalid)
- }
-
- return key, nil
- })
- if err != nil {
- return nil, common.Wrap(err, common.Invalid)
- }
-
- if !token.Valid {
- return nil, common.Errorf(common.Invalid, "invalid token")
- }
-
- return s.parseClaims(claims)
+ return nil, errors.Errorf("cannot find the trialing license")
}
// parseClaims will valid and parse JWT claims to license instance.
func (s *LicenseService) parseClaims(claims *Claims) (*enterpriseAPI.License, error) {
- err := claims.Valid()
- if err != nil {
- return nil, common.Wrap(err, common.Invalid)
- }
-
verifyIssuer := claims.VerifyIssuer(s.config.Issuer, true)
if !verifyIssuer {
return nil, common.Errorf(common.Invalid, "iss is not valid, expect %s but found '%v'", s.config.Issuer, claims.Issuer)
diff --git a/backend/enterprise/service/provider.go b/backend/enterprise/service/provider.go
new file mode 100644
index 0000000000..cdba74639e
--- /dev/null
+++ b/backend/enterprise/service/provider.go
@@ -0,0 +1,126 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/golang-jwt/jwt/v4"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/enterprise/config"
+ api "github.com/bytebase/bytebase/backend/legacyapi"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+const (
+ fetchLicenseInterval = time.Duration(1) * time.Minute
+)
+
+// getLicenseResponse is the API message for getting license response from the hub.
+type getLicenseResponse struct {
+ License string `json:"license"`
+}
+
+// internalTokenClaims is the token claims for internal API call.
+type internalTokenClaims struct {
+ PrincipalID int64 `json:"principalId"`
+ OrgID string `json:"orgId"`
+ WorkspaceID string `json:"workspaceId"`
+ jwt.RegisteredClaims
+}
+
+// LicenseProvider is the service to fetch license from the hub.
+type LicenseProvider struct {
+ config *config.Config
+ store *store.Store
+ client *http.Client
+ lastFetchTime int64
+}
+
+// NewLicenseProvider will create a new license provider.
+func NewLicenseProvider(config *config.Config, store *store.Store) *LicenseProvider {
+ return &LicenseProvider{
+ store: store,
+ config: config,
+ client: &http.Client{
+ Timeout: 30 * time.Second,
+ },
+ lastFetchTime: 0,
+ }
+}
+
+// FetchLicense will fetch the license from the hub.
+func (p *LicenseProvider) FetchLicense(ctx context.Context) (string, error) {
+ nextFetchTime := p.lastFetchTime + int64(fetchLicenseInterval.Seconds())
+ if time.Now().Unix() < nextFetchTime {
+ log.Debug(fmt.Sprintf("skip fetching license until %d", nextFetchTime))
+ return "", nil
+ }
+
+ settingName := api.SettingAgentToken
+ setting, err := p.store.GetSetting(ctx, &api.SettingFind{
+ Name: &settingName,
+ })
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to find the hub token from settings")
+ }
+ if setting == nil || setting.Value == "" {
+ return "", errors.Wrapf(err, "hub token not found")
+ }
+ claims, err := p.parseJWTToken(setting.Value)
+ if err != nil {
+ return "", errors.Wrapf(err, "invalid internal token")
+ }
+
+ defer func() {
+ p.lastFetchTime = time.Now().Unix()
+ }()
+
+ return p.requestLicense(ctx, setting.Value, claims)
+}
+
+func (p *LicenseProvider) requestLicense(ctx context.Context, token string, claims *internalTokenClaims) (string, error) {
+ url := fmt.Sprintf("%s/v1/orgs/%s/workspaces/%s/license", p.config.HubAPIURL, claims.OrgID, claims.WorkspaceID)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return "", errors.Wrapf(err, "construct GET %s", url)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
+ resp, err := p.client.Do(req)
+ if err != nil {
+ return "", errors.Wrapf(err, "GET %s", url)
+ }
+
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return "", errors.Wrapf(err, "read body of GET %s", url)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return "", errors.Errorf("non-200 GET status code %d with body %q", resp.StatusCode, b)
+ }
+
+ var response getLicenseResponse
+ if err := json.Unmarshal(b, &response); err != nil {
+ return "", errors.Wrapf(err, "unmarshal body from GET %s", url)
+ }
+
+ return response.License, nil
+}
+
+func (p *LicenseProvider) parseJWTToken(tokenStr string) (*internalTokenClaims, error) {
+ claims := &internalTokenClaims{}
+ if err := parseJWTToken(tokenStr, p.config.Version, p.config.PublicKey, claims); err != nil {
+ return nil, common.Wrap(err, common.Invalid)
+ }
+
+ return claims, nil
+}
diff --git a/backend/enterprise/service/utils.go b/backend/enterprise/service/utils.go
new file mode 100644
index 0000000000..f34370c109
--- /dev/null
+++ b/backend/enterprise/service/utils.go
@@ -0,0 +1,36 @@
+package service
+
+import (
+ "github.com/golang-jwt/jwt"
+
+ "github.com/bytebase/bytebase/backend/common"
+)
+
+func parseJWTToken(tokenString, expectVersion, publicKey string, claims jwt.Claims) error {
+ token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, 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 claims.Valid()
+}
diff --git a/backend/legacyapi/setting.go b/backend/legacyapi/setting.go
index ecfe61caba..14bfde0a1f 100644
--- a/backend/legacyapi/setting.go
+++ b/backend/legacyapi/setting.go
@@ -22,6 +22,9 @@ const (
SettingAppIM SettingName = "bb.app.im"
// SettingWatermark is the setting name for watermark displaying.
SettingWatermark SettingName = "bb.workspace.watermark"
+ // SettingAgentToken is the setting name for the agent token to call the internal API.
+ // For now we will call the hub to fetch the subscription license.
+ SettingAgentToken SettingName = "bb.agent.token"
)
// IMType is the type of IM.
diff --git a/go.mod b/go.mod
index e116952c67..7f3ce3eb16 100644
--- a/go.mod
+++ b/go.mod
@@ -16,6 +16,7 @@ require (
github.com/coreos/go-oidc v2.2.1+incompatible
github.com/github/gh-ost v1.1.5
github.com/go-sql-driver/mysql v1.6.0
+ github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/golang-jwt/jwt/v4 v4.4.2
github.com/google/go-cmp v0.5.9
github.com/google/jsonapi v1.0.0
@@ -115,7 +116,6 @@ require (
github.com/go-openapi/swag v0.22.3 // indirect
github.com/goccy/go-json v0.9.11 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
- github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golang/snappy v0.0.4 // indirect