Skip to content

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

feat: init enterprise (#465)

ecmadao796f0cd63fbf
diff --git a/api/plan.go b/api/plan.go
index a0cf385b6b..58f0a8724c 100644
--- a/api/plan.go
+++ b/api/plan.go
@@ -36,6 +36,19 @@ const (
ENTERPRISE
)
+// String returns the string format of plan type.
+func (p PlanType) String() string {
+ switch p {
+ case FREE:
+ return "FREE"
+ case TEAM:
+ return "TEAM"
+ case ENTERPRISE:
+ return "ENTERPRISE"
+ }
+ return ""
+}
+
// FeatureMatrix is a map from the a particular feature to the respective enablement of a particular plan
var FeatureMatrix = map[FeatureType][3]bool{
"bb.admin": {false, true, true},
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index dd37ecb2d5..7071c6d859 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -13,6 +13,7 @@ import (
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
+ enterprise "github.com/bytebase/bytebase/enterprise/service"
"github.com/bytebase/bytebase/server"
"github.com/bytebase/bytebase/store"
"github.com/spf13/cobra"
@@ -331,6 +332,12 @@ func (m *Main) Run(ctx context.Context) error {
s.ActivityManager = server.NewActivityManager(s, s.ActivityService)
+ licenseService, err := enterprise.NewLicenseService(m.l, dataDir, m.profile.mode)
+ if err != nil {
+ return err
+ }
+ s.LicenseService = licenseService
+
m.server = s
fmt.Printf(greetingBanner, fmt.Sprintf("Version %s has started at %s:%d", version, host, m.profile.port))
diff --git a/enterprise/README.md b/enterprise/README.md
new file mode 100644
index 0000000000..1f34e96c4f
--- /dev/null
+++ b/enterprise/README.md
@@ -0,0 +1,3 @@
+# Bytebase enterprise
+
+This directory contains Bytebase Enterprise code.
diff --git a/enterprise/api/license.go b/enterprise/api/license.go
new file mode 100644
index 0000000000..db08499f36
--- /dev/null
+++ b/enterprise/api/license.go
@@ -0,0 +1,17 @@
+package api
+
+// 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"`
+}
+
+// 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)
+}
diff --git a/enterprise/config/config.go b/enterprise/config/config.go
new file mode 100644
index 0000000000..bc04af3d12
--- /dev/null
+++ b/enterprise/config/config.go
@@ -0,0 +1,60 @@
+package config
+
+import (
+ "embed"
+ "fmt"
+ "io/fs"
+
+ "go.uber.org/zap"
+)
+
+//go:embed keys
+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
+ // Version is the JWT key version.
+ Version string
+ // Issuer is the license issuer, it should always be "bytebase".
+ Issuer string
+ // MinimumInstance is the minimum instance count in each plan.
+ MinimumInstance int
+ // StorePath is the file path to store license.
+ StorePath string
+}
+
+const (
+ // keyID is the license key version.
+ keyID = "v1"
+ // issuer is the license issuer.
+ issuer = "bytebase"
+ // minimumInstance is the minimum instance count in subscribed plan.
+ minimumInstance = 5
+)
+
+// NewConfig will create a new enterprise config instance.
+func NewConfig(l *zap.Logger, dataDir string, mode string) (*Config, error) {
+ l.Info("get project env", zap.String("env", mode))
+
+ filename := fmt.Sprintf("keys/%s.pub.pem", mode)
+ licensePubKey, err := fs.ReadFile(keysFS, fmt.Sprintf("keys/%s.pub.pem", mode))
+ if err != nil {
+ return nil, fmt.Errorf("cannot read license public key for env %s", mode)
+ }
+ l.Info("load public pem", zap.String("file", filename))
+
+ storefile := "license"
+ if mode != "release" {
+ storefile = fmt.Sprintf("license_%s", mode)
+ }
+
+ return &Config{
+ PublicKey: string(licensePubKey),
+ Version: keyID,
+ Issuer: issuer,
+ MinimumInstance: minimumInstance,
+ StorePath: fmt.Sprintf("file:%s/%s", dataDir, storefile),
+ }, nil
+}
diff --git a/enterprise/config/keys/README.md b/enterprise/config/keys/README.md
new file mode 100644
index 0000000000..596fb7d84b
--- /dev/null
+++ b/enterprise/config/keys/README.md
@@ -0,0 +1,42 @@
+# License
+
+## Intro
+
+These public keys are used to decrypt JWT license.
+
+## Create license
+
+We can use `openssl` to generate RSA key
+
+```bash
+# Create private key
+openssl genrsa -out private.pem 2048
+
+# Use private key to generate public key
+openssl rsa -in private.pem -outform PEM -pubout -out public.pem
+```
+
+## Usage
+
+### Load keys in config
+
+The `enterprise/config/config.go` will load keys depends on environment.
+
+### Decrypt
+
+In `enterprise/service/license.go`, we will use public key to parse JWT
+
+```go
+token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
+ if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
+ return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
+ }
+
+ key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(env.Conf.LicensePubKey))
+ if err != nil {
+ return nil, err
+ }
+
+ return key
+}
+```
diff --git a/enterprise/config/keys/dev.pub.pem b/enterprise/config/keys/dev.pub.pem
new file mode 100644
index 0000000000..63d183a71d
--- /dev/null
+++ b/enterprise/config/keys/dev.pub.pem
@@ -0,0 +1,9 @@
+-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwOnNEhoNLnBiv9+Vw3NH
+o2hRZNp8eehBfJaoTdsF7GLYWZKcBjvSB/RuVdWdFJ2/X4QTkcJeKFN6q3w+86dY
+HKqrVzBxSxeIj1YMhyCNO4uECdrzBp8kcG7m8mN8r5glMMLE8ShAstPFCzKWbGw9
+aHFs3a5nQfWjn5X2SbfGLm1BhHzatDM6Cvmnt8NDSLqVjbPzT1TKH0owljYEIZwY
+m6BBHXyIQLmzsbb9yPVotYMn2cz4OUShwNW8LbXr8mjk+8lw3OcUn3W5CoF33aD4
+nsFFtgrlXmmgdaCP22bBha6iHz0Ff31lmuDZIYjaOAeTqyUxEV78Tg04ht6Kgmeu
+owIDAQAB
+-----END PUBLIC KEY-----
diff --git a/enterprise/config/keys/local.pub.pem b/enterprise/config/keys/local.pub.pem
new file mode 100644
index 0000000000..d193d7e07a
--- /dev/null
+++ b/enterprise/config/keys/local.pub.pem
@@ -0,0 +1,9 @@
+-----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/config/keys/release.pub.pem b/enterprise/config/keys/release.pub.pem
new file mode 100644
index 0000000000..159f979ee5
--- /dev/null
+++ b/enterprise/config/keys/release.pub.pem
@@ -0,0 +1,9 @@
+-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0y+LxgmnEbrjiK89LfD9
+63S2fO7j5VbNh/j6qq1Mnrch8x+9YES1C6CMOg1k6gy6iFUJXAVLcmaSXItoBemZ
+6fc8dTQ4Otsz/cPfz5gZR5+eXg/mww4IM9bPgOSJerAfUAXlH+CVrTOogid6Zs0C
+gFdyitLbo1IoyVJnHRQHvie2zCBN9BB48D9x9kT3zT6EUnEJgcqao5Lj5xVMDEjI
+w1ww5ac4cIGv1ovs1InHhrqobvkk+zAA8OntifCZ7yt07/DJejpgVE8DI+CmTwDS
+0SWCG9nvEwFqLmrFlrHS5TTXLKaYUeUyosNzjvQwnKwQJOl4R2Bphs5sMhPDAzp2
+1wIDAQAB
+-----END PUBLIC KEY-----
diff --git a/enterprise/service/license.go b/enterprise/service/license.go
new file mode 100644
index 0000000000..d838a2bdcb
--- /dev/null
+++ b/enterprise/service/license.go
@@ -0,0 +1,152 @@
+package service
+
+import (
+ "fmt"
+ "io/ioutil"
+ "strings"
+ "time"
+
+ "github.com/bytebase/bytebase/api"
+ enterpriseAPI "github.com/bytebase/bytebase/enterprise/api"
+ "github.com/bytebase/bytebase/enterprise/config"
+ "github.com/golang-jwt/jwt/v4"
+ "go.uber.org/zap"
+)
+
+// licenseService is the service for enterprise license.
+type licenseService struct {
+ l *zap.Logger
+ 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)
+ if err != nil {
+ return nil, err
+ }
+
+ return &licenseService{
+ config: config,
+ l: l,
+ }, nil
+}
+
+// StoreLicense will store license into file.
+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) {
+ tokenString, err := s.readLicense()
+ if err != nil {
+ return nil, err
+ }
+
+ token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
+ if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
+ return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
+ }
+
+ kid, ok := token.Header["kid"].(string)
+ if !ok || kid != s.config.Version {
+ return nil, fmt.Errorf("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, err
+ }
+
+ return key, nil
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ claims, ok := token.Claims.(jwt.MapClaims)
+ if !ok || !token.Valid {
+ return nil, fmt.Errorf("invalid token")
+ }
+
+ return s.parseClaims(claims)
+}
+
+// parseClaims will valid and parse JWT claims to license instance.
+func (s *licenseService) parseClaims(claims jwt.MapClaims) (*enterpriseAPI.License, error) {
+ err := claims.Valid()
+ if err != nil {
+ return nil, err
+ }
+
+ exp, ok := claims["exp"].(int64)
+ 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 {
+ return nil, 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 {
+ return nil, fmt.Errorf("license instance count '%v' is not valid, minimum instance requirement is %d", claims["instance"], s.config.MinimumInstance)
+ }
+
+ plan, ok := claims["plan"].(string)
+ if !ok {
+ return nil, fmt.Errorf("plan is not valid, found '%v'", claims["plan"])
+ }
+ if err := validPlanType(plan); err != nil {
+ return nil, err
+ }
+
+ aud, ok := claims["aud"].(string)
+ if !ok || aud == "" {
+ return nil, fmt.Errorf("aud is not valid, found '%v'", claims["aud"])
+ }
+
+ return &enterpriseAPI.License{
+ InstanceCount: instance,
+ ExpiresTs: exp,
+ Plan: plan,
+ Audience: aud,
+ }, nil
+}
+
+func (s *licenseService) readLicense() (string, error) {
+ token, err := ioutil.ReadFile(s.config.StorePath)
+ if err != nil {
+ return "", fmt.Errorf("cannot read license from %s, error %w", s.config.StorePath, err)
+ }
+
+ return string(token), nil
+}
+
+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
+ }
+ }
+
+ return fmt.Errorf("plan %q is not valid, expect one of %s",
+ candidate,
+ strings.Join(validPlans, ", "),
+ )
+}
diff --git a/server/server.go b/server/server.go
index 21afc2c1cc..f48b197adf 100644
--- a/server/server.go
+++ b/server/server.go
@@ -13,6 +13,7 @@ import (
_ "embed"
"github.com/bytebase/bytebase/api"
+ enterprise "github.com/bytebase/bytebase/enterprise/api"
"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/model"
"github.com/labstack/echo/v4"
@@ -65,6 +66,7 @@ type Server struct {
LabelService api.LabelService
DeploymentConfigService api.DeploymentConfigService
SavedQueryService api.SavedQueryService
+ LicenseService enterprise.LicenseService
e *echo.Echo