Skip to content

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

feat: implement license API (#484)

ecmadao24d1a153d775
diff --git a/enterprise/api/license.go b/enterprise/api/license.go
index db08499f36..c481e878a3 100644
--- a/enterprise/api/license.go
+++ b/enterprise/api/license.go
@@ -1,17 +1,58 @@
package api
+import (
+ "fmt"
+ "time"
+
+ "github.com/bytebase/bytebase/api"
+)
+
+// validPlans is a string array of valid plan types.
+var validPlans = []api.PlanType{
+ api.TEAM,
+ api.ENTERPRISE,
+}
+
// License is the API message for enterprise license.
type License struct {
- Audience string `jsonapi:"attr,audience"`
- InstanceCount int `jsonapi:"attr,instanceCount"`
- ExpiresTs int64 `jsonapi:"attr,expiresTs"`
- Plan string `jsonapi:"attr,plan"`
+ Audience string `jsonapi:"attr,audience"`
+ InstanceCount int `jsonapi:"attr,instanceCount"`
+ ExpiresTs int64 `jsonapi:"attr,expiresTs"`
+ Plan api.PlanType `jsonapi:"attr,plan"`
+}
+
+// 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()) {
+ return fmt.Errorf("license has expired at %v", expireTime)
+ }
+
+ if err := l.validPlanType(); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (l *License) validPlanType() error {
+ for _, plan := range validPlans {
+ if plan == l.Plan {
+ return nil
+ }
+ }
+
+ return fmt.Errorf("plan %q is not valid, expect %s or %s",
+ l.Plan.String(),
+ api.TEAM.String(),
+ api.ENTERPRISE.String(),
+ )
}
// LicenseService is the service for enterprise license.
type LicenseService interface {
// StoreLicense will store license into file.
StoreLicense(tokenString string) error
- // ParseLicense will valid and parse license from file.
- ParseLicense() (*License, error)
+ // LoadLicense will load license from file and validate it.
+ LoadLicense() (*License, error)
}
diff --git a/enterprise/api/subscription.go b/enterprise/api/subscription.go
new file mode 100644
index 0000000000..79f105ce03
--- /dev/null
+++ b/enterprise/api/subscription.go
@@ -0,0 +1,15 @@
+package api
+
+import "github.com/bytebase/bytebase/api"
+
+// SubscriptionPatch is the API message for update the subscription.
+type SubscriptionPatch struct {
+ License string `jsonapi:"attr,license"`
+}
+
+// Subscription is the API message for subscription.
+type Subscription struct {
+ InstanceCount int `jsonapi:"attr,instanceCount"`
+ ExpiresTs int64 `jsonapi:"attr,expiresTs"`
+ Plan api.PlanType `jsonapi:"attr,plan"`
+}
diff --git a/enterprise/config/config.go b/enterprise/config/config.go
index bc04af3d12..a4932b1614 100644
--- a/enterprise/config/config.go
+++ b/enterprise/config/config.go
@@ -55,6 +55,6 @@ func NewConfig(l *zap.Logger, dataDir string, mode string) (*Config, error) {
Version: keyID,
Issuer: issuer,
MinimumInstance: minimumInstance,
- StorePath: fmt.Sprintf("file:%s/%s", dataDir, storefile),
+ StorePath: fmt.Sprintf("%s/%s", dataDir, storefile),
}, nil
}
diff --git a/enterprise/service/license.go b/enterprise/service/license.go
index d838a2bdcb..dc4b3cec40 100644
--- a/enterprise/service/license.go
+++ b/enterprise/service/license.go
@@ -3,8 +3,6 @@ package service
import (
"fmt"
"io/ioutil"
- "strings"
- "time"
"github.com/bytebase/bytebase/api"
enterpriseAPI "github.com/bytebase/bytebase/enterprise/api"
@@ -19,12 +17,6 @@ type licenseService struct {
config *config.Config
}
-// validPlans is a string array of valid plan types.
-var validPlans = []string{
- api.TEAM.String(),
- api.ENTERPRISE.String(),
-}
-
// NewLicenseService will create a new enterprise license service.
func NewLicenseService(l *zap.Logger, dataDir string, mode string) (*licenseService, error) {
config, err := config.NewConfig(l, dataDir, mode)
@@ -43,8 +35,8 @@ func (s *licenseService) StoreLicense(tokenString string) error {
return s.writeLicense(tokenString)
}
-// ParseLicense will valid and parse license from file.
-func (s *licenseService) ParseLicense() (*enterpriseAPI.License, error) {
+// LoadLicense will load license from file and validate it.
+func (s *licenseService) LoadLicense() (*enterpriseAPI.License, error) {
tokenString, err := s.readLicense()
if err != nil {
return nil, err
@@ -90,9 +82,6 @@ func (s *licenseService) parseClaims(claims jwt.MapClaims) (*enterpriseAPI.Licen
if !ok {
return nil, fmt.Errorf("exp is not valid, found '%v'", claims["exp"])
}
- if exp <= time.Now().Unix() {
- return nil, fmt.Errorf("license has expired at %v", time.Unix(exp, 0))
- }
iss, ok := claims["iss"].(string)
if !ok || iss != s.config.Issuer {
@@ -108,8 +97,10 @@ func (s *licenseService) parseClaims(claims jwt.MapClaims) (*enterpriseAPI.Licen
if !ok {
return nil, fmt.Errorf("plan is not valid, found '%v'", claims["plan"])
}
- if err := validPlanType(plan); err != nil {
- return nil, err
+
+ planType, err := convertPlanType(plan)
+ if err != nil {
+ return nil, fmt.Errorf("plan type %q is not valid", planType)
}
aud, ok := claims["aud"].(string)
@@ -117,12 +108,18 @@ func (s *licenseService) parseClaims(claims jwt.MapClaims) (*enterpriseAPI.Licen
return nil, fmt.Errorf("aud is not valid, found '%v'", claims["aud"])
}
- return &enterpriseAPI.License{
+ license := &enterpriseAPI.License{
InstanceCount: instance,
ExpiresTs: exp,
- Plan: plan,
+ Plan: planType,
Audience: aud,
- }, nil
+ }
+
+ if err := license.Valid(); err != nil {
+ return nil, err
+ }
+
+ return license, nil
}
func (s *licenseService) readLicense() (string, error) {
@@ -138,15 +135,15 @@ func (s *licenseService) writeLicense(token string) error {
return ioutil.WriteFile(s.config.StorePath, []byte(token), 0644)
}
-func validPlanType(candidate string) error {
- for _, plan := range validPlans {
- if plan == candidate {
- return nil
- }
+func convertPlanType(candidate string) (api.PlanType, error) {
+ switch candidate {
+ case api.TEAM.String():
+ return api.TEAM, nil
+ case api.ENTERPRISE.String():
+ return api.ENTERPRISE, nil
+ case api.FREE.String():
+ return api.FREE, nil
+ default:
+ return api.FREE, fmt.Errorf("cannot conver plan type %q", candidate)
}
-
- return fmt.Errorf("plan %q is not valid, expect one of %s",
- candidate,
- strings.Join(validPlans, ", "),
- )
}
diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csv
index 56ac95fdae..94b96d633a 100644
--- a/server/acl_casbin_policy_dba.csv
+++ b/server/acl_casbin_policy_dba.csv
@@ -85,3 +85,5 @@ p, DBA, /savedquery, GET
p, DBA, /savedquery/{id}, GET
p, DBA, /savedquery/{id}, PATCH_SELF
p, DBA, /savedquery/{id}, DELETE_SELF
+p, DBA, /subscription, GET
+p, DBA, /subscription, PATCH
diff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csv
index 04a24e4cfb..bfa447bd9c 100644
--- a/server/acl_casbin_policy_developer.csv
+++ b/server/acl_casbin_policy_developer.csv
@@ -75,3 +75,4 @@ p, DEVELOPER, /savedquery, GET
p, DEVELOPER, /savedquery/{id}, GET
p, DEVELOPER, /savedquery/{id}, PATCH_SELF
p, DEVELOPER, /savedquery/{id}, DELETE_SELF
+p, DEVELOPER, /subscription, GET
diff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csv
index 22785d8020..14b27d8ab5 100644
--- a/server/acl_casbin_policy_owner.csv
+++ b/server/acl_casbin_policy_owner.csv
@@ -91,3 +91,5 @@ p, OWNER, /savedquery, GET
p, OWNER, /savedquery/{id}, GET
p, OWNER, /savedquery/{id}, PATCH_SELF
p, OWNER, /savedquery/{id}, DELETE_SELF
+p, OWNER, /subscription, GET
+p, OWNER, /subscription, PATCH
diff --git a/server/plan.go b/server/plan.go
index a60e44c54f..c33e6fdb76 100644
--- a/server/plan.go
+++ b/server/plan.go
@@ -40,5 +40,11 @@ func (s *Server) registerPlanRoutes(g *echo.Group) {
}
func (s *Server) feature(feature api.FeatureType) bool {
- return api.FeatureMatrix[feature][s.plan]
+ plan := api.TEAM
+ license, _ := s.loadLicense()
+ if license != nil {
+ plan = license.Plan
+ }
+
+ return api.FeatureMatrix[feature][plan]
}
diff --git a/server/server.go b/server/server.go
index f48b197adf..55181cb41d 100644
--- a/server/server.go
+++ b/server/server.go
@@ -241,6 +241,7 @@ func NewServer(logger *zap.Logger, version string, host string, port int, fronte
s.registerPlanRoutes(apiGroup)
s.registerLabelRoutes(apiGroup)
s.registerSavedQueryRoutes(apiGroup)
+ s.registerSubscriptionRoutes(apiGroup)
allRoutes, err := json.MarshalIndent(e.Routes(), "", " ")
if err != nil {
diff --git a/server/subscription.go b/server/subscription.go
new file mode 100644
index 0000000000..224551d903
--- /dev/null
+++ b/server/subscription.go
@@ -0,0 +1,77 @@
+package server
+
+import (
+ "net/http"
+ "time"
+
+ enterprise "github.com/bytebase/bytebase/enterprise/api"
+ enterpriseAPI "github.com/bytebase/bytebase/enterprise/api"
+ "github.com/google/jsonapi"
+ "github.com/labstack/echo/v4"
+ "go.uber.org/zap"
+)
+
+func (s *Server) registerSubscriptionRoutes(g *echo.Group) {
+ g.GET("/subscription", func(c echo.Context) error {
+ 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,
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, subscription); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal subscription response").SetInternal(err)
+ }
+ return nil
+ })
+
+ g.PATCH("/subscription", func(c echo.Context) error {
+ patch := &enterpriseAPI.SubscriptionPatch{}
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, patch); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create subscription request").SetInternal(err)
+ }
+
+ if err := s.LicenseService.StoreLicense(patch.License); err != nil {
+ 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,
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, subscription); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal subscription response").SetInternal(err)
+ }
+ return nil
+ })
+}
+
+// loadLicense will get and parse valid license from file.
+func (server *Server) loadLicense() (*enterprise.License, error) {
+ license, err := server.LicenseService.LoadLicense()
+ if err != nil {
+ server.l.Warn("Failed to load license", zap.String("error", err.Error()))
+ return nil, err
+ }
+
+ server.l.Info(
+ "Load valid license",
+ zap.String("plan", license.Plan.String()),
+ zap.Time("expiresAt", time.Unix(license.ExpiresTs, 0)),
+ zap.Int("instanceCount", license.InstanceCount),
+ )
+
+ return license, nil
+}