An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lock: Bound publish-service sessions with expiry, reuse, and eviction https://github.com/siyuan-note/siyuan/security/advisories/GHSA-f4vj-ppp2-5hg4
Daniel43608aeee677
diff --git a/kernel/model/auth.go b/kernel/model/auth.goindex f99023212e..667522a651 100644--- a/kernel/model/auth.go+++ b/kernel/model/auth.go@@ -22,6 +22,7 @@ import ("net/http""slices""sync"+ "time""github.com/golang-jwt/jwt/v5""github.com/google/uuid"@@ -35,7 +36,13 @@ type Account struct {Token string}type AccountsMap map[string]*Account // username -> account-type SessionsMap map[string]string // sessionID -> username++// PublishSession 发布服务会话,记录所属用户名与最近活跃时间。+type PublishSession struct {+ Username string+ LastActive time.Time+}+type ClaimsKeyType stringconst (@@ -50,12 +57,19 @@ const (kernelPluginAudience = "siyuan-kernel-plugin" // 内核插件 token 的受众ClaimsKeyRole string = "role"++ // publishSessionTTL 发布服务会话空闲过期时长,超过后需要重新认证+ publishSessionTTL = 7 * 24 * time.Hour+ // publishSessionGlobalCap 发布服务会话全局上限,超出后淘汰最久未活跃的会话+ publishSessionGlobalCap = 4096+ // publishSessionPerAccountCap 单账户会话上限,超出后淘汰该账户最久未活跃的会话+ publishSessionPerAccountCap = 32)var (accountsMap = AccountsMap{}accountsLock = sync.RWMutex{}- sessionsMap = SessionsMap{}+ sessionsMap = map[string]*PublishSession{}sessionLock = sync.Mutex{}jwtKey = make([]byte, 32)@@ -92,8 +106,24 @@ func GetBasicAuthAccount(username string) *Account {return &accountCopy}+// GetBasicAuthUsernameBySessionID 返回会话对应的用户名;会话不存在或已过期时返回空字符串。func GetBasicAuthUsernameBySessionID(sessionID string) string {- return sessionsMap[sessionID]+ sessionLock.Lock()+ defer sessionLock.Unlock()++ session := sessionsMap[sessionID]+ if nil == session {+ return ""+ }+ if publishSessionTTL < time.Since(session.LastActive) {+ // 会话空闲超时,删除并视为无效+ delete(sessionsMap, sessionID)+ return ""+ }++ // 刷新最近活跃时间,用于过期与淘汰判定+ session.LastActive = time.Now()+ return session.Username}func GetNewSessionID() string {@@ -101,10 +131,38 @@ func GetNewSessionID() string {return sessionID}-func AddSession(sessionID, username string) {+// AddSession 为指定用户注册发布服务会话并返回实际生效的会话 ID。+// 同一用户已有有效会话时复用其 ID,避免重复认证导致会话无限增长+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-f4vj-ppp2-5hg4;+// 同时按空闲时长清理过期会话,并在超出全局或单账户上限时淘汰最久未活跃的会话。+func AddSession(username string) string {sessionLock.Lock()defer sessionLock.Unlock()- sessionsMap[sessionID] = username++ now := time.Now()+ purgeExpiredPublishSessions(now)++ // 复用该用户已有的有效会话+ for id, session := range sessionsMap {+ if session.Username == username {+ session.LastActive = now+ return id+ }+ }++ // 单账户会话数达到上限时,淘汰该账户最久未活跃的会话+ if publishSessionPerAccountCap <= countPublishSessionsByUsername(username) {+ evictOldestPublishSessionByUsername(username)+ }++ // 全局会话数达到上限时,淘汰最久未活跃的会话+ if publishSessionGlobalCap <= len(sessionsMap) {+ evictOldestPublishSession()+ }++ sessionID := GetNewSessionID()+ sessionsMap[sessionID] = &PublishSession{Username: username, LastActive: now}+ return sessionID}func DeleteSession(sessionID string) {@@ -113,6 +171,53 @@ func DeleteSession(sessionID string) {delete(sessionsMap, sessionID)}+// purgeExpiredPublishSessions 删除空闲超过 publishSessionTTL 的会话,调用方需持有 sessionLock。+func purgeExpiredPublishSessions(now time.Time) {+ for id, session := range sessionsMap {+ if publishSessionTTL < now.Sub(session.LastActive) {+ delete(sessionsMap, id)+ }+ }+}++// evictOldestPublishSession 淘汰最久未活跃的会话,调用方需持有 sessionLock。+func evictOldestPublishSession() {+ oldestID := ""+ oldestTime := time.Time{}+ for id, session := range sessionsMap {+ if "" == oldestID || session.LastActive.Before(oldestTime) {+ oldestID, oldestTime = id, session.LastActive+ }+ }+ delete(sessionsMap, oldestID)+}++// evictOldestPublishSessionByUsername 淘汰指定账户最久未活跃的会话,调用方需持有 sessionLock。+func evictOldestPublishSessionByUsername(username string) {+ oldestID := ""+ oldestTime := time.Time{}+ for id, session := range sessionsMap {+ if session.Username != username {+ continue+ }+ if "" == oldestID || session.LastActive.Before(oldestTime) {+ oldestID, oldestTime = id, session.LastActive+ }+ }+ delete(sessionsMap, oldestID)+}++// countPublishSessionsByUsername 统计指定账户的会话数,调用方需持有 sessionLock。+func countPublishSessionsByUsername(username string) int {+ count := 0+ for _, session := range sessionsMap {+ if session.Username == username {+ count+++ }+ }+ return count+}+func InitPublishAccounts() {if nil == Conf.Publish {Conf.Publish = conf.NewPublish()diff --git a/kernel/model/auth_test.go b/kernel/model/auth_test.goindex 32f2a14d84..5f9b340560 100644--- a/kernel/model/auth_test.go+++ b/kernel/model/auth_test.go@@ -18,8 +18,10 @@ package modelimport ("errors"+ "strconv""sync""testing"+ "time""github.com/golang-jwt/jwt/v5""github.com/siyuan-note/siyuan/kernel/conf"@@ -39,6 +41,107 @@ func preserveAuthState(t *testing.T) {})}+func resetPublishSessions(t *testing.T) {+ t.Helper()+ sessionLock.Lock()+ original := sessionsMap+ sessionsMap = map[string]*PublishSession{}+ sessionLock.Unlock()+ t.Cleanup(func() {+ sessionLock.Lock()+ sessionsMap = original+ sessionLock.Unlock()+ })+}++func TestAddPublishSessionReusesSessionForSameUsername(t *testing.T) {+ resetPublishSessions(t)++ first := AddSession("alice")+ if second := AddSession("alice"); second != first {+ t.Fatalf("session ID = %q, want reused %q", second, first)+ }++ sessionLock.Lock()+ size := len(sessionsMap)+ sessionLock.Unlock()+ if 1 != size {+ t.Fatalf("session registry size = %d, want 1", size)+ }+}++func TestPublishSessionExpiresAfterInactivity(t *testing.T) {+ resetPublishSessions(t)++ sessionID := AddSession("alice")+ sessionLock.Lock()+ sessionsMap[sessionID].LastActive = time.Now().Add(-publishSessionTTL - time.Second)+ sessionLock.Unlock()++ if username := GetBasicAuthUsernameBySessionID(sessionID); "" != username {+ t.Fatalf("expired session username = %q, want empty", username)+ }++ sessionLock.Lock()+ _, exists := sessionsMap[sessionID]+ sessionLock.Unlock()+ if exists {+ t.Fatal("expired session was not removed from the registry")+ }+}++func TestPublishSessionGlobalCapEvictsOldest(t *testing.T) {+ resetPublishSessions(t)++ base := time.Now()+ ids := make([]string, publishSessionGlobalCap)+ for i := range ids {+ ids[i] = AddSession("user-" + strconv.Itoa(i))+ }+ sessionLock.Lock()+ for i, id := range ids {+ sessionsMap[id].LastActive = base.Add(time.Duration(i) * time.Second)+ }+ sessionLock.Unlock()++ newID := AddSession("overflow")+ sessionLock.Lock()+ defer sessionLock.Unlock()+ if publishSessionGlobalCap != len(sessionsMap) {+ t.Fatalf("session registry size = %d, want %d", len(sessionsMap), publishSessionGlobalCap)+ }+ if _, ok := sessionsMap[ids[0]]; ok {+ t.Fatal("oldest session was not evicted when exceeding the global cap")+ }+ if _, ok := sessionsMap[ids[len(ids)-1]]; !ok {+ t.Fatal("most recently active session was unexpectedly evicted")+ }+ if _, ok := sessionsMap[newID]; !ok {+ t.Fatal("new session was not registered")+ }+}++func TestPublishSessionPerAccountCapEvictsOldest(t *testing.T) {+ resetPublishSessions(t)++ base := time.Now()+ sessionLock.Lock()+ for i := 0; i < publishSessionPerAccountCap; i++ {+ sessionsMap["id-"+strconv.Itoa(i)] = &PublishSession{+ Username: "alice",+ LastActive: base.Add(time.Duration(i) * time.Second),+ }+ }+ evictOldestPublishSessionByUsername("alice")+ if publishSessionPerAccountCap-1 != len(sessionsMap) {+ t.Fatalf("session registry size = %d, want %d", len(sessionsMap), publishSessionPerAccountCap-1)+ }+ if _, ok := sessionsMap["id-0"]; ok {+ t.Fatal("oldest session of the account was not evicted")+ }+ sessionLock.Unlock()+}+func TestIsPublishServiceToken(t *testing.T) {tests := []struct {name stringdiff --git a/kernel/server/proxy/publish.go b/kernel/server/proxy/publish.goindex 755f0d2660..4d5ec57e72 100644--- a/kernel/server/proxy/publish.go+++ b/kernel/server/proxy/publish.go@@ -236,15 +236,14 @@ func (PublishServiceTransport) RoundTrip(request *http.Request) (response *http.}util.AuthThrottleReset(ip)- // set session cookie- sessionID := model.GetNewSessionID()+ // set session cookie,同一账户已有有效会话时复用其 ID,避免重复认证导致会话无限增长+ sessionID := model.AddSession(username)cookie := &http.Cookie{Name: model.SessionIdCookieName,Value: sessionID,Path: "/",HttpOnly: true,}- model.AddSession(sessionID, username)// set JWTrequest.Header.Set(model.XAuthTokenKey, account.Token)