Skip to content

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

Add config table

天舟3fcf923b17e3
diff --git a/.air.toml b/.air.toml
index 75ed926ff8..ce03a380ac 100644
--- a/.air.toml
+++ b/.air.toml
@@ -2,7 +2,7 @@ root = "."
tmp_dir = ".air"
[build]
- bin = "./.air/bytebase --port 8080 --data ./data --secret ./data/secret"
+ bin = "./.air/bytebase --port 8080 --data ./data"
cmd = "go build -o ./.air/bytebase ./bin/server/main.go"
delay = 1000
exclude_dir = [".air", "vendor"]
diff --git a/.air_debug.toml b/.air_debug.toml
index 197f23ee28..721e6ea53f 100644
--- a/.air_debug.toml
+++ b/.air_debug.toml
@@ -2,7 +2,7 @@ root = "."
tmp_dir = ".air"
[build]
- bin = "./.air/bytebase --port 8080 --debug --data ./data --secret ./data/secret"
+ bin = "./.air/bytebase --port 8080 --debug --data ./data"
cmd = "go build --tags \"sqlite_trace\" -o ./.air/bytebase ./bin/server/main.go"
delay = 1000
exclude_dir = [".air", "vendor"]
diff --git a/.air_demo.toml b/.air_demo.toml
index efebe78ee0..6ab751dc8b 100644
--- a/.air_demo.toml
+++ b/.air_demo.toml
@@ -2,7 +2,7 @@ root = "."
tmp_dir = ".air"
[build]
- bin = "./.air/bytebase --demo --port 8080 --data ./data --secret ./data/secret"
+ bin = "./.air/bytebase --demo --port 8080 --data ./data"
cmd = "go build -o ./.air/bytebase ./bin/server/main.go"
delay = 1000
exclude_dir = [".air", "vendor"]
diff --git a/api/config.go b/api/config.go
new file mode 100644
index 0000000000..82f85d555f
--- /dev/null
+++ b/api/config.go
@@ -0,0 +1,36 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+)
+
+type Config struct {
+ Name string
+ Value string
+ Description string
+}
+
+type ConfigCreate struct {
+ CreatorId int
+ Name string
+ Value string
+ Description string
+}
+
+type ConfigFind struct {
+ Name string
+}
+
+func (find *ConfigFind) String() string {
+ str, err := json.Marshal(*find)
+ if err != nil {
+ return err.Error()
+ }
+ return string(str)
+}
+
+type ConfigService interface {
+ CreateConfigIfNotExist(ctx context.Context, create *ConfigCreate) (*Config, error)
+ FindConfig(ctx context.Context, find *ConfigFind) (*Config, error)
+}
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index 46eeee2e8c..3eee6748a8 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -2,10 +2,7 @@ package cmd
import (
"context"
- "errors"
"fmt"
- "io/fs"
- "io/ioutil"
"net/http"
"os"
"os/signal"
@@ -14,6 +11,7 @@ import (
"time"
"github.com/bytebase/bytebase"
+ "github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/server"
"github.com/bytebase/bytebase/store"
"github.com/spf13/cobra"
@@ -22,7 +20,9 @@ import (
// -----------------------------------Global constant BEGIN----------------------------------------
const (
+ // Length for the secret used to sign the JWT auth token
SECRET_LENGTH = 32
+
// http://patorjk.com/software/taag/#p=display&f=ANSI%20Shadow&t=Bytebase
GREETING_BANNER = `
██████╗ ██╗ ██╗████████╗███████╗██████╗ █████╗ ███████╗███████╗
@@ -53,13 +53,12 @@ ________________________________________________________________________________
// -----------------------------------Command Line Config BEGIN------------------------------------
var (
// Used for flags.
- host string
- port int
- dataDir string
- secretFile string
- secret string
- demo bool
- debug bool
+ host string
+ port int
+ dataDir string
+ secret string
+ demo bool
+ debug bool
logger *zap.Logger
@@ -106,7 +105,6 @@ func init() {
rootCmd.PersistentFlags().StringVar(&host, "host", "http://localhost", "host where Bytebase is running. e.g. https://bytebase.example.com")
rootCmd.PersistentFlags().IntVar(&port, "port", 8080, "port where Bytebase is running e.g. 8080")
rootCmd.PersistentFlags().StringVar(&dataDir, "data", ".", "directory where Bytebase stores data.")
- rootCmd.PersistentFlags().StringVar(&secretFile, "secret", "./bytebase_secret", "file path storing the secret to sign the JWT for authentication. If file does not exist, Bytebase will generate a 32 byte random string consisting of numbers and letters.")
rootCmd.PersistentFlags().BoolVar(&demo, "demo", false, "whether to run in demo mode. Demo mode uses demo data and is read-only.")
rootCmd.PersistentFlags().BoolVar(&debug, "debug", false, "whether to enable debug level logging.")
}
@@ -125,6 +123,12 @@ type profile struct {
forceResetSeed bool
}
+// retrieved via the ConfigService upon startup
+type config struct {
+ // secret used to sign the JWT auth token
+ secret string
+}
+
type main struct {
profile *profile
@@ -148,29 +152,6 @@ func preStart() error {
return error
}
- secretFile, err = filepath.Abs(secretFile)
- if err != nil {
- return err
- }
- if _, err := os.Stat(secretFile); err == nil {
- data, err := ioutil.ReadFile(secretFile)
- if err != nil {
- return fmt.Errorf("unable to read secret, error: %w", err)
- }
- secret = string(data)
- } else if errors.Is(err, fs.ErrNotExist) {
- logger.Info(fmt.Sprintf("Secret file does not exist on the specified path %s. Generating a new one...\n", secretFile))
- secret = bytebase.RandomString(SECRET_LENGTH)
- if err := ioutil.WriteFile(secretFile, []byte(secret), 0600); err != nil {
- if errors.Is(err, os.ErrNotExist) {
- return fmt.Errorf("unable to save secret, please make sure the parent directory exists: %s", filepath.Dir(secretFile))
- }
- return fmt.Errorf("unable to save secret, error: %w", err)
- }
- logger.Info(fmt.Sprintf("Successfully saved secret at %s\n", secretFile))
- } else {
- return fmt.Errorf("unable to stat secret file: %s, error: %w", secretFile, err)
- }
return nil
}
@@ -212,7 +193,6 @@ func newMain() *main {
fmt.Printf("port=%d\n", port)
fmt.Printf("dsn=%s\n", activeProfile.dsn)
fmt.Printf("seedDir=%s\n", activeProfile.seedDir)
- fmt.Printf("secret=%s\n", secretFile)
fmt.Printf("demo=%t\n", demo)
fmt.Printf("debug=%t\n", debug)
fmt.Println("-----Config END-------")
@@ -223,15 +203,40 @@ func newMain() *main {
}
}
+func initConfig(configService api.ConfigService) (*config, error) {
+ result := &config{}
+ {
+ configCreate := &api.ConfigCreate{
+ CreatorId: api.SYSTEM_BOT_ID,
+ Name: "bb.auth.secret",
+ Value: bytebase.RandomString(SECRET_LENGTH),
+ Description: "Random string used to sign the JWT auth token.",
+ }
+ config, err := configService.CreateConfigIfNotExist(context.Background(), configCreate)
+ if err != nil {
+ return nil, err
+ }
+ result.secret = config.Value
+ }
+
+ return result, nil
+}
+
func (m *main) Run() error {
db := store.NewDB(m.l, m.profile.dsn, m.profile.seedDir, m.profile.forceResetSeed)
if err := db.Open(); err != nil {
return fmt.Errorf("cannot open db: %w", err)
}
+ configService := store.NewConfigService(m.l, db)
+ config, err := initConfig(configService)
+ if err != nil {
+ return fmt.Errorf("failed to init config: %w", err)
+ }
+
m.db = db
- server := server.NewServer(m.l, host, port, m.profile.mode, secret, demo, debug)
+ server := server.NewServer(m.l, host, port, m.profile.mode, config.secret, demo, debug)
server.PrincipalService = store.NewPrincipalService(m.l, db)
server.MemberService = store.NewMemberService(m.l, db)
server.ProjectService = store.NewProjectService(m.l, db)
diff --git a/store/config.go b/store/config.go
new file mode 100644
index 0000000000..cd8a399ae0
--- /dev/null
+++ b/store/config.go
@@ -0,0 +1,158 @@
+package store
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase"
+ "github.com/bytebase/bytebase/api"
+ "go.uber.org/zap"
+)
+
+var (
+ _ api.ConfigService = (*ConfigService)(nil)
+)
+
+// ConfigService represents a service for managing config.
+type ConfigService struct {
+ l *zap.Logger
+ db *DB
+}
+
+// NewConfigService returns a new instance of ConfigService.
+func NewConfigService(logger *zap.Logger, db *DB) *ConfigService {
+ return &ConfigService{l: logger, db: db}
+}
+
+// CreateConfigIfNotExist creates a new config only if the named config does not exist.
+func (s *ConfigService) CreateConfigIfNotExist(ctx context.Context, create *api.ConfigCreate) (*api.Config, error) {
+ // We do a find followed by a create if NOT found. Though SQLite supports UPSERT ON CONFLICT DO NOTHING syntax, it doesn't
+ // support RETURNING in such case. So we have to use separate SELECT and INSERT anyway.
+ find := &api.ConfigFind{
+ Name: create.Name,
+ }
+ config, err := s.FindConfig(ctx, find)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ config, err = createConfig(ctx, tx, create)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return config, nil
+ }
+ return nil, err
+ }
+
+ return config, nil
+}
+
+// FindConfig retrieves a single config based on find.
+// Returns ENOTFOUND if no matching record.
+// Returns ECONFLICT if finding more than 1 matching records.
+func (s *ConfigService) FindConfig(ctx context.Context, find *api.ConfigFind) (*api.Config, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := findConfigList(ctx, tx, find)
+ if err != nil {
+ return nil, err
+ } else if len(list) == 0 {
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("config not found: %v", find)}
+ } else if len(list) > 1 {
+ return nil, &bytebase.Error{Code: bytebase.ECONFLICT, Message: fmt.Sprintf("found %d activities with filter %v, expect 1. ", len(list), find)}
+ }
+ return list[0], nil
+}
+
+// createConfig creates a new config.
+func createConfig(ctx context.Context, tx *Tx, create *api.ConfigCreate) (*api.Config, error) {
+ // Insert row into database.
+ row, err := tx.QueryContext(ctx, `
+ INSERT INTO config (
+ creator_id,
+ updater_id,
+ name,
+ value,
+ description
+ )
+ VALUES (?, ?, ?, ?, ?)
+ RETURNING name, value, description
+ `,
+ create.CreatorId,
+ create.CreatorId,
+ create.Name,
+ create.Value,
+ create.Description,
+ )
+
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ row.Next()
+ var config api.Config
+ if err := row.Scan(
+ &config.Name,
+ &config.Value,
+ &config.Description,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return &config, nil
+}
+
+func findConfigList(ctx context.Context, tx *Tx, find *api.ConfigFind) (_ []*api.Config, err error) {
+ // Build WHERE clause.
+ where, args := []string{"name = ?"}, []interface{}{find.Name}
+
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ name,
+ value,
+ description
+ FROM config
+ WHERE `+strings.Join(where, " AND "),
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer rows.Close()
+
+ // Iterate over result set and deserialize rows into list.
+ list := make([]*api.Config, 0)
+ for rows.Next() {
+ var config api.Config
+ if err := rows.Scan(
+ &config.Name,
+ &config.Value,
+ &config.Description,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ list = append(list, &config)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return list, nil
+}
diff --git a/store/migration/10001__init_schema.sql b/store/migration/10001__init_schema.sql
index 10cb908742..e136a363fe 100644
--- a/store/migration/10001__init_schema.sql
+++ b/store/migration/10001__init_schema.sql
@@ -56,6 +56,39 @@ VALUES
''
);
+-- Config
+CREATE TABLE config (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ row_status TEXT NOT NULL CHECK (
+ row_status IN ('NORMAL', 'ARCHIVED', 'PENDING_DELETE')
+ ) DEFAULT 'NORMAL',
+ creator_id INTEGER NOT NULL REFERENCES principal (id),
+ created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
+ updater_id INTEGER NOT NULL REFERENCES principal (id),
+ updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
+ name TEXT NOT NULL UNIQUE,
+ value TEXT NOT NULL,
+ description TEXT NOT NULL
+);
+
+INSERT INTO
+ sqlite_sequence (name, seq)
+VALUES
+ ('config', 100);
+
+CREATE TRIGGER IF NOT EXISTS `trigger_update_config_modification_time`
+AFTER
+UPDATE
+ ON `config` FOR EACH ROW BEGIN
+UPDATE
+ `config`
+SET
+ updated_ts = (strftime('%s', 'now'))
+WHERE
+ rowid = old.rowid;
+
+END;
+
-- Member
CREATE TABLE member (
id INTEGER PRIMARY KEY AUTOINCREMENT,
diff --git a/store/sqlite.go b/store/sqlite.go
index 1690ea5e82..0022a12fb9 100644
--- a/store/sqlite.go
+++ b/store/sqlite.go
@@ -107,7 +107,7 @@ func (db *DB) Open() (err error) {
}
if err := db.migrate(); err != nil {
- return fmt.Errorf("migrate: %w", err)
+ return fmt.Errorf("failed to migrate: %w", err)
}
majorAfterMigration, minorAfterMigration, err := db.version()
@@ -116,7 +116,7 @@ func (db *DB) Open() (err error) {
}
if err := db.seed(majorBeforeMigration, minorBeforeMigration, majorAfterMigration, minorAfterMigration); err != nil {
- return fmt.Errorf("seed: %w", err)
+ return fmt.Errorf("failed to seed: %w", err)
}
return nil