Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Improve JWT lifecycle and publish token validation (#18692)

Yingyi / 颖逸b960e2caad66
diff --git a/kernel/harmony/kernel.go b/kernel/harmony/kernel.go
index c30422bb08..dfb3cea598 100644
--- a/kernel/harmony/kernel.go
+++ b/kernel/harmony/kernel.go
@@ -121,11 +121,13 @@ func GetExportFileName(exportPath *C.char) *C.char {
//export StartKernelFast
func StartKernelFast(container, appDir, workspaceBaseDir, localIPs *C.char) {
+ model.InitJwtKey()
go server.Serve(true, model.Conf.CookieKey)
}
//export StartKernel
func StartKernel(container, appDir, workspaceBaseDir, timezoneID, localIPs, lang, osVer *C.char) {
+ model.InitJwtKey()
SetTimezone(container, appDir, timezoneID)
util.Mode = "prod"
util.MobileOSVer = C.GoString(osVer)
diff --git a/kernel/mobile/kernel.go b/kernel/mobile/kernel.go
index 926ae64571..05a528cb5b 100644
--- a/kernel/mobile/kernel.go
+++ b/kernel/mobile/kernel.go
@@ -263,10 +263,12 @@ func VerifyAppStoreTransaction(accountToken, transactionID string) (retCode int)
}
func StartKernelFast(container, appDir, workspaceBaseDir, localIPs string) {
+ model.InitJwtKey()
go server.Serve(true, model.Conf.CookieKey)
}
func StartKernel(container, appDir, workspaceBaseDir, timezoneID, localIPs, lang, osVer string) {
+ model.InitJwtKey()
SetTimezone(container, appDir, timezoneID)
util.Mode = "prod"
util.MobileOSVer = osVer
diff --git a/kernel/model/auth.go b/kernel/model/auth.go
index 0d8e9170bb..f99023212e 100644
--- a/kernel/model/auth.go
+++ b/kernel/model/auth.go
@@ -18,6 +18,7 @@ package model
import (
"crypto/rand"
+ "errors"
"net/http"
"slices"
"sync"
@@ -46,19 +47,33 @@ const (
iss = "siyuan-kernel" // token 的发行者
publishServiceAudience = "siyuan-publish-server" // 发布服务 token 的受众
+ kernelPluginAudience = "siyuan-kernel-plugin" // 内核插件 token 的受众
ClaimsKeyRole string = "role"
)
var (
- accountsMap = AccountsMap{}
- sessionsMap = SessionsMap{}
- sessionLock = sync.Mutex{}
+ accountsMap = AccountsMap{}
+ accountsLock = sync.RWMutex{}
+ sessionsMap = SessionsMap{}
+ sessionLock = sync.Mutex{}
- jwtKey = make([]byte, 32)
+ jwtKey = make([]byte, 32)
+ jwtKeyOnce sync.Once
+
+ ErrInvalidPublishServiceToken = errors.New("invalid publish service token")
)
-func InitJwtKey() error {
+func InitJwtKey() {
+ jwtKeyOnce.Do(func() {
+ err := refreshJwtKey()
+ if err != nil {
+ logging.LogFatalf(logging.ExitCodeFatal, "initialize JWT signing key failed: %s", err)
+ }
+ })
+}
+
+func refreshJwtKey() error {
if _, err := rand.Read(jwtKey); err != nil {
logging.LogErrorf("generate JWT signing key failed: %s", err)
return err
@@ -67,7 +82,14 @@ func InitJwtKey() error {
}
func GetBasicAuthAccount(username string) *Account {
- return accountsMap[username]
+ accountsLock.RLock()
+ defer accountsLock.RUnlock()
+ account := accountsMap[username]
+ if account == nil {
+ return nil
+ }
+ accountCopy := *account
+ return &accountCopy
}
func GetBasicAuthUsernameBySessionID(sessionID string) string {
@@ -100,26 +122,29 @@ func InitPublishAccounts() {
// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-rp9f-c2fj-h648
Conf.Publish.Auth = conf.NewPublish().Auth
}
- accountsMap = AccountsMap{
+ accounts := AccountsMap{
"": &Account{}, // 匿名用户
}
for _, account := range Conf.Publish.Auth.Accounts {
- accountsMap[account.Username] = &Account{
+ accounts[account.Username] = &Account{
Username: account.Username,
Password: account.Password,
}
}
- InitPublishJWT()
-}
-
-func InitPublishJWT() {
- if _, err := rand.Read(jwtKey); err != nil {
- logging.LogErrorf("generate JWT signing key failed: %s", err)
+ if err := refreshPublishJWT(accounts); err != nil {
+ logging.LogErrorf("JWT signature failed: %s", err)
return
}
- for username, account := range accountsMap {
+ // 账户及其 token 发布后保持不可变,更新时整体替换完整快照,避免请求读取到构建中的状态。
+ accountsLock.Lock()
+ accountsMap = accounts
+ accountsLock.Unlock()
+}
+
+func refreshPublishJWT(accounts AccountsMap) error {
+ for username, account := range accounts {
// REF: https://golang-jwt.github.io/jwt/usage/create/
t := jwt.NewWithClaims(
jwt.SigningMethodHS256,
@@ -133,12 +158,12 @@ func InitPublishJWT() {
},
)
if token, err := t.SignedString(jwtKey); err != nil {
- logging.LogErrorf("JWT signature failed: %s", err)
- return
+ return err
} else {
account.Token = token
}
}
+ return nil
}
// CreatePluginJWT 为指定名称的内核插件创建一个 JWT,包含管理员权限。插件使用这个 JWT 调用内核 API。
@@ -148,7 +173,7 @@ func CreatePluginJWT(name string) (string, error) {
jwt.MapClaims{
"iss": iss,
"sub": name,
- "aud": "siyuan-kernel-plugin",
+ "aud": kernelPluginAudience,
"jti": uuid.New().String(),
ClaimsKeyRole: RoleAdministrator,
@@ -162,15 +187,26 @@ func CreatePluginJWT(name string) (string, error) {
}
}
-func ParseJWT(tokenString string) (*jwt.Token, error) {
+func ParseJWT(tokenString string) (token *jwt.Token, err error) {
// REF: https://golang-jwt.github.io/jwt/usage/parse/
- return jwt.Parse(
+ token, err = jwt.Parse(
tokenString,
func(token *jwt.Token) (any, error) {
return jwtKey, nil
},
jwt.WithIssuer(iss),
)
+ if err != nil {
+ return
+ }
+
+ if IsPublishServiceToken(token) {
+ if !IsValidPublishServiceToken(token) {
+ err = ErrInvalidPublishServiceToken
+ return
+ }
+ }
+ return
}
func ParseXAuthToken(r *http.Request) *jwt.Token {
@@ -209,3 +245,23 @@ func IsPublishServiceToken(token *jwt.Token) bool {
audience, err := claims.GetAudience()
return err == nil && slices.Contains(audience, publishServiceAudience)
}
+
+// IsValidPublishServiceToken 检查 token 是否来自发布服务且有效
+func IsValidPublishServiceToken(token *jwt.Token) bool {
+ if !IsPublishServiceToken(token) {
+ return false
+ }
+
+ claims := GetTokenClaims(token)
+ username, ok := claims["sub"].(string)
+ if !ok {
+ return false
+ }
+
+ account := GetBasicAuthAccount(username)
+ if account == nil || account.Token != token.Raw {
+ return false
+ }
+
+ return true
+}
diff --git a/kernel/model/auth_test.go b/kernel/model/auth_test.go
index 9b8b1168fc..32f2a14d84 100644
--- a/kernel/model/auth_test.go
+++ b/kernel/model/auth_test.go
@@ -17,12 +17,28 @@
package model
import (
+ "errors"
+ "sync"
"testing"
"github.com/golang-jwt/jwt/v5"
"github.com/siyuan-note/siyuan/kernel/conf"
)
+func preserveAuthState(t *testing.T) {
+ t.Helper()
+ originalConf := Conf
+ accountsLock.RLock()
+ originalAccounts := accountsMap
+ accountsLock.RUnlock()
+ t.Cleanup(func() {
+ Conf = originalConf
+ accountsLock.Lock()
+ accountsMap = originalAccounts
+ accountsLock.Unlock()
+ })
+}
+
func TestIsPublishServiceToken(t *testing.T) {
tests := []struct {
name string
@@ -78,12 +94,8 @@ func TestIsPublishServiceToken(t *testing.T) {
}
func TestInitPublishAccountsWithNilAuth(t *testing.T) {
- originalConf := Conf
- originalAccounts := accountsMap
- defer func() {
- Conf = originalConf
- accountsMap = originalAccounts
- }()
+ InitJwtKey()
+ preserveAuthState(t)
Conf = NewAppConf()
Conf.Publish = &conf.Publish{Enable: true, Port: 6808}
@@ -99,3 +111,70 @@ func TestInitPublishAccountsWithNilAuth(t *testing.T) {
t.Fatal("InitPublishAccounts should default Publish.Auth when it is nil")
}
}
+
+func TestJWTLifecycle(t *testing.T) {
+ InitJwtKey()
+ preserveAuthState(t)
+
+ pluginToken, err := CreatePluginJWT("test-plugin")
+ if err != nil {
+ t.Fatalf("CreatePluginJWT failed: %v", err)
+ }
+ InitJwtKey()
+ if _, err = ParseJWT(pluginToken); err != nil {
+ t.Fatalf("plugin JWT became invalid after repeated key initialization: %v", err)
+ }
+
+ Conf = NewAppConf()
+ InitPublishAccounts()
+ firstPublishAccount := GetBasicAuthAccount("")
+ if firstPublishAccount == nil {
+ t.Fatal("anonymous publish account is missing")
+ }
+ if _, err = ParseJWT(firstPublishAccount.Token); err != nil {
+ t.Fatalf("current publish JWT is invalid: %v", err)
+ }
+
+ InitPublishAccounts()
+ if _, err = ParseJWT(pluginToken); err != nil {
+ t.Fatalf("plugin JWT became invalid after publish account initialization: %v", err)
+ }
+ if _, err = ParseJWT(firstPublishAccount.Token); !errors.Is(err, ErrInvalidPublishServiceToken) {
+ t.Fatalf("stale publish JWT error = %v, want %v", err, ErrInvalidPublishServiceToken)
+ }
+ refreshedPublishAccount := GetBasicAuthAccount("")
+ if refreshedPublishAccount == nil {
+ t.Fatal("refreshed anonymous publish account is missing")
+ }
+ if _, err = ParseJWT(refreshedPublishAccount.Token); err != nil {
+ t.Fatalf("refreshed publish JWT is invalid: %v", err)
+ }
+}
+
+func TestConcurrentPublishAccountRefreshAndJWTParsing(t *testing.T) {
+ InitJwtKey()
+ preserveAuthState(t)
+
+ Conf = NewAppConf()
+ InitPublishAccounts()
+ account := GetBasicAuthAccount("")
+ if account == nil {
+ t.Fatal("anonymous publish account is missing")
+ }
+
+ var wait sync.WaitGroup
+ wait.Add(2)
+ go func() {
+ defer wait.Done()
+ for i := 0; i < 100; i++ {
+ InitPublishAccounts()
+ }
+ }()
+ go func() {
+ defer wait.Done()
+ for i := 0; i < 100; i++ {
+ _, _ = ParseJWT(account.Token)
+ }
+ }()
+ wait.Wait()
+}