Skip to content

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

Add —secret flag to allow user to supply a secret file instead of hardcoded in the code

天舟2bbee3b7244b
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index 44de961267..1667053ae5 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -2,7 +2,10 @@ package cmd
import (
"context"
+ "errors"
"fmt"
+ "io/fs"
+ "io/ioutil"
"net/http"
"os"
"os/signal"
@@ -10,6 +13,7 @@ import (
"strings"
"time"
+ "github.com/bytebase/bytebase"
"github.com/bytebase/bytebase/server"
"github.com/bytebase/bytebase/store"
"github.com/spf13/cobra"
@@ -18,28 +22,28 @@ import (
// -----------------------------------Command Line Config BEGIN------------------------------------
+const (
+ SECRET_LENGTH = 32
+)
+
var (
// Used for flags.
- mode string
- host string
- dataDir string
- port int
+ mode string
+ host string
+ port int
+ dataDir string
+ secretFile string
+ secret string
rootCmd = &cobra.Command{
Use: "bytebase",
Short: "Bytebase server",
Run: func(cmd *cobra.Command, args []string) {
- if mode != "release" && mode != "dev" && mode != "demo" {
- fmt.Fprintln(os.Stderr, fmt.Errorf("invalid --mode %s, expect \"release\" | \"dev\" | \"demo\"", mode))
- os.Exit(1)
- }
- // Trim trailing / in case user supplies
- dir, err := filepath.Abs(strings.TrimRight(dataDir, "/"))
- if err != nil {
+ if err := preStart(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
- dataDir = dir
+
start()
},
}
@@ -53,8 +57,9 @@ func Execute() error {
func init() {
rootCmd.PersistentFlags().StringVar(&mode, "mode", "release", "mode which Bytebase is running under. release | dev | demo")
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().IntVar(&port, "port", 8080, "port where Bytebase is running e.g. 8080")
rootCmd.PersistentFlags().StringVar(&dataDir, "data", "./data", "directory where Bytebase stores data.")
+ rootCmd.PersistentFlags().StringVar(&secretFile, "secret", "./data/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.")
}
// -----------------------------------Command Line Config END--------------------------------------
@@ -76,6 +81,40 @@ type main struct {
db *store.DB
}
+func preStart() error {
+ if mode != "release" && mode != "dev" && mode != "demo" {
+ return fmt.Errorf("invalid --mode %s, expect \"release\" | \"dev\" | \"demo\"", mode)
+ }
+ // Trim trailing / in case user supplies
+ dir, err := filepath.Abs(strings.TrimRight(dataDir, "/"))
+ if err != nil {
+ return err
+ }
+ dataDir = dir
+
+ 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) {
+ fmt.Printf("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 {
+ return fmt.Errorf("unable to save secret, error: %w", err)
+ }
+ fmt.Printf("Successfully saved secret at %s\n", secretFile)
+ } else {
+ return fmt.Errorf("unable to stat secret file: %s, error: %w", secretFile, err)
+ }
+ return nil
+}
+
func start() {
m := newMain()
@@ -132,6 +171,7 @@ func newMain() *main {
fmt.Printf("host=%s\n", host)
fmt.Printf("port=%d\n", port)
fmt.Printf("data=%s\n", activeProfile.dsn)
+ fmt.Printf("secret=%s\n", secretFile)
fmt.Println("-----Config END-------")
logger, err := activeProfile.logConfig.Build()
@@ -154,7 +194,7 @@ func (m *main) Run() error {
m.db = db
- server := server.NewServer(m.l, m.profile.mode, host, port)
+ server := server.NewServer(m.l, m.profile.mode, host, port, secret)
server.PrincipalService = store.NewPrincipalService(m.l, db)
server.MemberService = store.NewMemberService(m.l, db)
server.ProjectService = store.NewProjectService(m.l, db)
diff --git a/bin/server/main.go b/bin/server/main.go
index 27e7df0c4f..eab6cbab52 100644
--- a/bin/server/main.go
+++ b/bin/server/main.go
@@ -1,9 +1,13 @@
package main
import (
+ "math/rand"
+ "time"
+
"github.com/bytebase/bytebase/bin/server/cmd"
)
func main() {
+ rand.Seed(time.Now().UnixNano())
cmd.Execute()
}
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index e4d772cb63..0c754f8dda 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -105,6 +105,14 @@ axios.interceptors.response.use(
},
(error) => {
if (error.response) {
+ // When server returns 401, it means the current login user's token becomes invalid.
+ // Thus we force a logout.
+ if (error.response.status == 401) {
+ store.dispatch("auth/logout").then(() => {
+ router.push({ name: "auth.signin" });
+ });
+ }
+
if (error.response.data.message) {
store.dispatch("notification/pushNotification", {
module: "bytebase",
diff --git a/server/auth.go b/server/auth.go
index 270e82705a..1707b633a8 100644
--- a/server/auth.go
+++ b/server/auth.go
@@ -37,7 +37,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
}
// If password is correct, generate tokens and set cookies.
- if err := GenerateTokensAndSetCookies(user, c); err != nil {
+ if err := GenerateTokensAndSetCookies(c, user, s.secret); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access token").SetInternal(err)
}
@@ -90,7 +90,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to signup.").SetInternal(err)
}
- if err := GenerateTokensAndSetCookies(user, c); err != nil {
+ if err := GenerateTokensAndSetCookies(c, user, s.secret); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access token.").SetInternal(err)
}
diff --git a/server/jwt.go b/server/jwt.go
index d48cdd2e29..b82a4d4600 100644
--- a/server/jwt.go
+++ b/server/jwt.go
@@ -25,13 +25,10 @@ const (
accessTokenCookieName = "access-token"
refreshTokenCookieName = "refresh-token"
- // Signing key section
+ // Signing key section. For now, this is only used for signing, not for verifying since we only
+ // have 1 version. But it will be used to maintain backward compatibility if we change the signing mechanism.
keyId = "v1"
- // TODO: Uses better keys
- jwtSecretKey = "some-secret-key"
- jwtRefreshSecretKey = "some-refresh-secret-key"
-
// Expiration section
refreshThresholdDuration = 1 * time.Hour
accessTokenDuration = 24 * time.Hour
@@ -56,53 +53,39 @@ type Claims struct {
jwt.StandardClaims
}
-func getJWTSecret(kid string) string {
- if kid == keyId {
- return jwtSecretKey
- }
- return ""
-}
-
-func getRefreshJWTSecret(kid string) string {
- if kid == keyId {
- return jwtRefreshSecretKey
- }
- return ""
-}
-
func GetPrincipalIdContextKey() string {
return principalIdContextKey
}
// GenerateTokensAndSetCookies generates jwt token and saves it to the http-only cookie.
-func GenerateTokensAndSetCookies(user *api.Principal, c echo.Context) error {
- accessToken, err := generateAccessToken(user)
+func GenerateTokensAndSetCookies(c echo.Context, user *api.Principal, secret string) error {
+ accessToken, err := generateAccessToken(user, secret)
if err != nil {
return fmt.Errorf("failed to generate access token: %w", err)
}
cookieExp := time.Now().Add(cookieExpDuration)
- setTokenCookie(accessTokenCookieName, accessToken, cookieExp, c)
- setUserCookie(user, cookieExp, c)
+ setTokenCookie(c, accessTokenCookieName, accessToken, cookieExp)
+ setUserCookie(c, user, cookieExp)
// We generate here a new refresh token and saving it to the cookie.
- refreshToken, err := generateRefreshToken(user)
+ refreshToken, err := generateRefreshToken(user, secret)
if err != nil {
return fmt.Errorf("failed to generate refresh token: %w", err)
}
- setTokenCookie(refreshTokenCookieName, refreshToken, cookieExp, c)
+ setTokenCookie(c, refreshTokenCookieName, refreshToken, cookieExp)
return nil
}
-func generateAccessToken(user *api.Principal) (string, error) {
+func generateAccessToken(user *api.Principal, secret string) (string, error) {
expirationTime := time.Now().Add(accessTokenDuration)
- return generateToken(user, accessTokenAudience, expirationTime, []byte(getJWTSecret(keyId)))
+ return generateToken(user, accessTokenAudience, expirationTime, []byte(secret))
}
-func generateRefreshToken(user *api.Principal) (string, error) {
+func generateRefreshToken(user *api.Principal, secret string) (string, error) {
expirationTime := time.Now().Add(refreshTokenDuration)
- return generateToken(user, refreshTokenAudience, expirationTime, []byte(getRefreshJWTSecret(keyId)))
+ return generateToken(user, refreshTokenAudience, expirationTime, []byte(secret))
}
// Pay attention to this function. It holds the main JWT token generation logic.
@@ -134,7 +117,7 @@ func generateToken(user *api.Principal, aud string, expirationTime time.Time, se
}
// Here we are creating a new cookie, which will store the valid JWT token.
-func setTokenCookie(name, token string, expiration time.Time, c echo.Context) {
+func setTokenCookie(c echo.Context, name, token string, expiration time.Time) {
cookie := new(http.Cookie)
cookie.Name = name
cookie.Value = token
@@ -147,7 +130,7 @@ func setTokenCookie(name, token string, expiration time.Time, c echo.Context) {
}
// Purpose of this cookie is to store the user's name.
-func setUserCookie(user *api.Principal, expiration time.Time, c echo.Context) {
+func setUserCookie(c echo.Context, user *api.Principal, expiration time.Time) {
cookie := new(http.Cookie)
cookie.Name = "user"
cookie.Value = strconv.Itoa(user.ID)
@@ -159,7 +142,7 @@ func setUserCookie(user *api.Principal, expiration time.Time, c echo.Context) {
// JWTMiddleware validates the access token.
// If the access token is about to expire or has expired and the request has a valid refresh token, it
// will try to generate new access token and refresh token.
-func JWTMiddleware(l *zap.Logger, p api.PrincipalService, next echo.HandlerFunc) echo.HandlerFunc {
+func JWTMiddleware(l *zap.Logger, p api.PrincipalService, next echo.HandlerFunc, secret string) echo.HandlerFunc {
return func(c echo.Context) error {
// Skips auth, webhook end point
if strings.HasPrefix(c.Path(), "/api/auth") {
@@ -177,8 +160,8 @@ func JWTMiddleware(l *zap.Logger, p api.PrincipalService, next echo.HandlerFunc)
return nil, fmt.Errorf("unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)
}
if kid, ok := t.Header["kid"].(string); ok {
- if key := getJWTSecret(kid); key != "" {
- return []byte(key), nil
+ if kid == "v1" {
+ return []byte(secret), nil
}
}
return nil, fmt.Errorf("unexpected access token kid=%v", t.Header["kid"])
@@ -233,8 +216,8 @@ func JWTMiddleware(l *zap.Logger, p api.PrincipalService, next echo.HandlerFunc)
return nil, fmt.Errorf("unexpected refresh token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)
}
if kid, ok := t.Header["kid"].(string); ok {
- if key := getRefreshJWTSecret(kid); key != "" {
- return []byte(key), nil
+ if kid == "v1" {
+ return []byte(secret), nil
}
}
return nil, fmt.Errorf("unexpected refresh token kid=%v", t.Header["kid"])
@@ -249,7 +232,7 @@ func JWTMiddleware(l *zap.Logger, p api.PrincipalService, next echo.HandlerFunc)
// If we have a valid refresh token, we will generate new access token and refresh token
if refreshToken != nil && refreshToken.Valid {
l.Info(generateReason)
- if err := GenerateTokensAndSetCookies(user, c); err != nil {
+ if err := GenerateTokensAndSetCookies(c, user, secret); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to refresh expired token. User Id %d", principalId)).SetInternal(err)
}
}
diff --git a/server/server.go b/server/server.go
index b4bdded284..daabccfede 100644
--- a/server/server.go
+++ b/server/server.go
@@ -48,6 +48,7 @@ type Server struct {
host string
port int
startedTs int64
+ secret string
}
//go:embed dist
@@ -77,7 +78,7 @@ func getFileSystem() http.FileSystem {
return http.FS(fsys)
}
-func NewServer(logger *zap.Logger, mode, host string, port int) *Server {
+func NewServer(logger *zap.Logger, mode, host string, port int, secret string) *Server {
e := echo.New()
// Catch-all route to return index.html, this is to prevent 404 when accessing non-root url.
@@ -96,6 +97,7 @@ func NewServer(logger *zap.Logger, mode, host string, port int) *Server {
host: host,
port: port,
startedTs: time.Now().Unix(),
+ secret: secret,
}
scheduler := NewTaskScheduler(logger, s)
@@ -129,7 +131,7 @@ func NewServer(logger *zap.Logger, mode, host string, port int) *Server {
apiGroup := e.Group("/api")
apiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
- return JWTMiddleware(logger, s.PrincipalService, next)
+ return JWTMiddleware(logger, s.PrincipalService, next, secret)
})
apiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
diff --git a/util.go b/util.go
index bc995b67af..0f57e61fbe 100644
--- a/util.go
+++ b/util.go
@@ -1,6 +1,9 @@
package bytebase
-import "sort"
+import (
+ "math/rand"
+ "sort"
+)
func FindString(strings []string, search string) int {
sort.Strings(strings)
@@ -10,3 +13,13 @@ func FindString(strings []string, search string) int {
}
return i
}
+
+var letters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
+
+func RandomString(n int) string {
+ b := make([]rune, n)
+ for i := range b {
+ b[i] = letters[rand.Intn(len(letters))]
+ }
+ return string(b)
+}