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: Prevent replaying solved login CAPTCHA challenges
Daniel92a16fdaaa6c
diff --git a/kernel/model/session.go b/kernel/model/session.goindex 534dd0eb12..d7e7e77774 100644--- a/kernel/model/session.go+++ b/kernel/model/session.go@@ -28,7 +28,6 @@ import ("sync""time"- "github.com/88250/gulu"ginSessions "github.com/gin-contrib/sessions""github.com/gin-gonic/gin""github.com/gorilla/websocket"@@ -67,7 +66,6 @@ func LogoutAuth(c *gin.Context, request apicontract.EmptyRequest) (ret apicontrafunc LoginAuth(c *gin.Context, request apicontract.SystemLoginAuthRequest) (ret apicontract.Response[apicontract.Null]) {ret = apicontract.Success(apicontract.Null{})- var inputCaptcha stringsession := util.GetSession(c)workspaceSession := util.GetWorkspaceSession(session)if util.NeedCaptcha() {@@ -79,13 +77,14 @@ func LoginAuth(c *gin.Context, request apicontract.SystemLoginAuthRequest) (retlogging.LogWarnf("invalid captcha")return}- inputCaptcha = request.Captcha- if !strings.EqualFold(workspaceSession.Captcha, inputCaptcha) {+ // 挑战在服务端一次性消费,旧签名 Cookie 重放时挑战已不存在+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-23g4-vqq8-5764+ if !util.ConsumeCaptchaChallenge(workspaceSession.CaptchaID, request.Captcha) {ret = apicontract.Failure[apicontract.Null](1, Conf.Language(22))logging.LogWarnf("invalid captcha")- workspaceSession.Captcha = gulu.Rand.String(7) // https://github.com/siyuan-note/siyuan/issues/13147+ workspaceSession.CaptchaID = ""if err := session.Save(c); err != nil {logging.LogError("save session failed: " + err.Error())session.Clear(c)@@ -94,6 +93,7 @@ func LoginAuth(c *gin.Context, request apicontract.SystemLoginAuthRequest) (ret}return}+ workspaceSession.CaptchaID = ""}if request.AuthCodeError() != nil {@@ -108,7 +108,7 @@ func LoginAuth(c *gin.Context, request apicontract.SystemLoginAuthRequest) (retlogging.LogWarnf("invalid auth code [ip=%s]", util.GetRemoteAddr(c.Request))util.WrongAuthCount++- workspaceSession.Captcha = gulu.Rand.String(7)+ workspaceSession.CaptchaID = ""if util.NeedCaptcha() {code = 1 // 需要渲染验证码}@@ -126,7 +126,7 @@ func LoginAuth(c *gin.Context, request apicontract.SystemLoginAuthRequest) (retworkspaceSession.OIDCSessionVersion = ""util.WrongAuthCount = 0util.AuthThrottleReset(c.ClientIP())- workspaceSession.Captcha = gulu.Rand.String(7)+ workspaceSession.CaptchaID = ""maxAge := 0 // Default session expiration (browser session)if request.RememberMe {@@ -170,7 +170,12 @@ func GetCaptcha(c *gin.Context, request apicontract.EmptyRequest) apicontract.Resession := util.GetSession(c)workspaceSession := util.GetWorkspaceSession(session)- workspaceSession.Captcha = img.Text+ captchaID := util.NewCaptchaChallenge(img.Text)+ if "" == captchaID {+ logging.LogError("generates captcha challenge failed")+ return apicontract.EmptyHTTPResponse[apicontract.BinaryContent](http.StatusInternalServerError)+ }+ workspaceSession.CaptchaID = captchaIDif err = session.Save(c); err != nil {logging.LogError("save session failed: " + err.Error())return apicontract.EmptyHTTPResponse[apicontract.BinaryContent](http.StatusInternalServerError)diff --git a/kernel/model/session_test.go b/kernel/model/session_test.goindex bf1f4f8154..abad29416d 100644--- a/kernel/model/session_test.go+++ b/kernel/model/session_test.go@@ -17,14 +17,20 @@package modelimport (+ "bytes"+ "encoding/json"+ "io""net/http""net/http/httptest""net/url"+ "strconv"+ "strings""testing"ginSessions "github.com/gin-contrib/sessions""github.com/gin-contrib/sessions/cookie""github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/util")@@ -473,3 +479,194 @@ func TestCheckAuthLoopbackProxy(t *testing.T) {})}}++const loginAuthTestAccessCode = "test-access-auth-code"++// newLoginAuthTestEngine 初始化登录接口测试环境,返回带会话中间件的引擎和来源 IP。+func newLoginAuthTestEngine(t *testing.T) (engine *gin.Engine, store ginSessions.Store, clientIP string) {+ t.Helper()++ originalConf, originalWorkspaceDir, originalWrongAuthCount, originalLangs := Conf, util.WorkspaceDir, util.WrongAuthCount, util.Langs+ Conf = NewAppConf()+ Conf.AccessAuthCode = loginAuthTestAccessCode+ Conf.Lang = "en"+ util.WorkspaceDir = "test-login-auth-workspace"+ util.WrongAuthCount = 0+ util.Langs = map[string]map[int]string{"en": {+ 21: "captcha required",+ 22: "invalid captcha",+ 83: "invalid auth code",+ 156: "unauthorized",+ 258: "save failed",+ 354: "too many attempts",+ }}+ clientIP = "192.0.2.70"+ t.Cleanup(func() {+ Conf, util.WorkspaceDir, util.WrongAuthCount, util.Langs = originalConf, originalWorkspaceDir, originalWrongAuthCount, originalLangs+ })++ gin.SetMode(gin.TestMode)+ engine = gin.New()+ store = cookie.NewStore([]byte("test-session-cookie-key"))+ engine.Use(ginSessions.Sessions("siyuan", store))+ engine.POST("/api/system/loginAuth", func(c *gin.Context) {+ body := struct {+ AuthCode string `json:"authCode"`+ Captcha string `json:"captcha"`+ }{}+ if err := json.NewDecoder(c.Request.Body).Decode(&body); err != nil {+ c.Status(http.StatusBadRequest)+ return+ }+ c.JSON(http.StatusOK, LoginAuth(c, apicontract.SystemLoginAuthRequest{AuthCode: body.AuthCode, Captcha: body.Captcha}))+ })+ engine.POST("/api/system/probeAdmin", CheckAuth, func(c *gin.Context) {+ c.Status(http.StatusNoContent)+ })+ return+}++// loginTestRequest 发送一次带会话 Cookie 的请求,返回响应和响应中签发的会话 Cookie。+func loginTestRequest(t *testing.T, engine *gin.Engine, clientIP, method, path string, body any, sessionCookie *http.Cookie) (*httptest.ResponseRecorder, *http.Cookie) {+ t.Helper()++ var reader io.Reader+ if nil != body {+ data, err := json.Marshal(body)+ if err != nil {+ t.Fatal(err)+ }+ reader = bytes.NewReader(data)+ }+ request := httptest.NewRequest(method, "http://127.0.0.1:6806"+path, reader)+ request.RemoteAddr = clientIP + ":1234"+ if nil != body {+ request.Header.Set("Content-Type", "application/json")+ }+ if nil != sessionCookie {+ request.AddCookie(sessionCookie)+ }+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, request)++ var next *http.Cookie+ for _, responseCookie := range recorder.Result().Cookies() {+ if "siyuan" == responseCookie.Name {+ next = responseCookie+ }+ }+ return recorder, next+}++// loginTestLogin 提交一次登录请求。+func loginTestLogin(t *testing.T, engine *gin.Engine, clientIP, authCode, captcha string, sessionCookie *http.Cookie) (int, string, *http.Cookie) {+ t.Helper()++ recorder, next := loginTestRequest(t, engine, clientIP, http.MethodPost, "/api/system/loginAuth", map[string]string{+ "authCode": authCode,+ "captcha": captcha,+ }, sessionCookie)+ result := struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ }{}+ if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {+ t.Fatalf("decode login response %q: %v", recorder.Body.String(), err)+ }+ return result.Code, result.Msg, next+}++// TestLoginAuthCaptchaChallengeSingleUse 验证验证码挑战在服务端一次性消费,旧签名 Cookie 重放不能再次通过验证码校验。+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-23g4-vqq8-5764+func TestLoginAuthCaptchaChallengeSingleUse(t *testing.T) {+ engine, _, clientIP := newLoginAuthTestEngine(t)+ engine.GET("/test/challenge", func(c *gin.Context) {+ session := util.GetSession(c)+ util.GetWorkspaceSession(session).CaptchaID = util.NewCaptchaChallenge("ABCD")+ if err := session.Save(c); err != nil {+ c.Status(http.StatusInternalServerError)+ return+ }+ c.Status(http.StatusNoContent)+ })++ var sessionCookie *http.Cookie+ for i := 1; i <= 4; i++ {+ if _, _, sessionCookie = loginTestLogin(t, engine, clientIP, "wrong-"+strconv.Itoa(i), "", sessionCookie); nil == sessionCookie {+ t.Fatal("login did not issue the session cookie")+ }+ }+ if util.WrongAuthCount <= 3 {+ t.Fatalf("captcha threshold not reached: %d", util.WrongAuthCount)+ }++ _, challengeCookie := loginTestRequest(t, engine, clientIP, http.MethodGet, "/test/challenge", nil, sessionCookie)+ if nil == challengeCookie {+ t.Fatal("challenge request did not issue the session cookie")+ }++ if code, msg, _ := loginTestLogin(t, engine, clientIP, "wrong-5", "ABCD", challengeCookie); 1 != code || "invalid auth code" != msg {+ t.Fatalf("first captcha use = %d %q, want code 1 and invalid auth code", code, msg)+ }+ if code, msg, _ := loginTestLogin(t, engine, clientIP, "wrong-6", "ABCD", challengeCookie); 1 != code || "invalid captcha" != msg {+ t.Fatalf("replayed captcha = %d %q, want code 1 and invalid captcha", code, msg)+ }++ _, challengeCookie = loginTestRequest(t, engine, clientIP, http.MethodGet, "/test/challenge", nil, sessionCookie)+ code, msg, authCookie := loginTestLogin(t, engine, clientIP, loginAuthTestAccessCode, "abcd", challengeCookie)+ if 0 != code {+ t.Fatalf("login with a new challenge = %d %q", code, msg)+ }+ if nil == authCookie {+ t.Fatal("login did not issue the authenticated cookie")+ }+ if recorder, _ := loginTestRequest(t, engine, clientIP, http.MethodPost, "/api/system/probeAdmin", nil, authCookie); http.StatusNoContent != recorder.Code {+ t.Fatalf("authenticated request = %d, want %d", recorder.Code, http.StatusNoContent)+ }+ if recorder, _ := loginTestRequest(t, engine, clientIP, http.MethodPost, "/api/system/probeAdmin", nil, challengeCookie); http.StatusUnauthorized != recorder.Code {+ t.Fatalf("request with the stale cookie = %d, want %d", recorder.Code, http.StatusUnauthorized)+ }+}++// TestGetCaptchaStoresChallengeID 验证验证码答案只保存在服务端,会话中仅保存挑战 ID。+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-23g4-vqq8-5764+func TestGetCaptchaStoresChallengeID(t *testing.T) {+ engine, store, clientIP := newLoginAuthTestEngine(t)+ engine.GET("/api/system/getCaptcha", func(c *gin.Context) {+ if content := GetCaptcha(c, apicontract.EmptyRequest{}).Binary(); nil != content {+ c.Data(content.Status, content.ContentType, content.Bytes)+ return+ }+ c.Status(http.StatusInternalServerError)+ })++ recorder, sessionCookie := loginTestRequest(t, engine, clientIP, http.MethodGet, "/api/system/getCaptcha", nil, nil)+ if http.StatusOK != recorder.Code {+ t.Fatalf("getCaptcha = %d, want %d", recorder.Code, http.StatusOK)+ }+ if nil == sessionCookie {+ t.Fatal("getCaptcha did not issue the session cookie")+ }++ request := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:6806/", nil)+ request.AddCookie(sessionCookie)+ session, err := store.Get(request, "siyuan")+ if err != nil {+ t.Fatal(err)+ }+ raw, ok := session.Values["data"].(string)+ if !ok {+ t.Fatal("session data is missing from the cookie")+ }+ data := &util.SessionData{}+ if err = json.Unmarshal([]byte(raw), data); err != nil {+ t.Fatal(err)+ }+ workspaceSession := data.Workspaces[util.WorkspaceDir]+ if nil == workspaceSession || "" == workspaceSession.CaptchaID {+ t.Fatal("captcha challenge ID is missing from the session")+ }+ if strings.Contains(raw, `"Captcha":`) {+ t.Fatalf("captcha answer is still stored in the session: %s", raw)+ }+}diff --git a/kernel/util/captcha.go b/kernel/util/captcha.gonew file mode 100644index 0000000000..16a1ef0cfe--- /dev/null+++ b/kernel/util/captcha.go@@ -0,0 +1,105 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package util++import (+ "crypto/subtle"+ "encoding/hex"+ "strings"+ "sync"+ "time"+)++const (+ captchaChallengeTTL = 5 * time.Minute+ captchaChallengeMaxEntries = 10000+ captchaChallengeSweepPeriod = time.Minute+)++// captchaChallenge 保存验证码答案和过期时间,答案只保留在服务端内存中。+type captchaChallenge struct {+ answer string+ expires time.Time+}++var (+ captchaChallengeLock = sync.Mutex{}+ captchaChallenges = map[string]*captchaChallenge{} // key: 挑战 ID+ captchaChallengeLastSweep = time.Time{}+)++// NewCaptchaChallenge 保存验证码答案并返回随机挑战 ID,调用方只应把 ID 写入会话;生成失败时返回空字符串。+func NewCaptchaChallenge(answer string) string {+ idBytes, err := randomBytes(16)+ if err != nil {+ return ""+ }+ id := hex.EncodeToString(idBytes)+ now := time.Now()++ captchaChallengeLock.Lock()+ defer captchaChallengeLock.Unlock()++ sweepCaptchaChallengesLocked(now)+ if captchaChallengeMaxEntries <= len(captchaChallenges) {+ // 达到条数上限后淘汰一个旧挑战,避免公开接口被用于无限占用内存+ for key := range captchaChallenges {+ delete(captchaChallenges, key)+ break+ }+ }+ captchaChallenges[id] = &captchaChallenge{answer: normalizeCaptchaAnswer(answer), expires: now.Add(captchaChallengeTTL)}+ return id+}++// ConsumeCaptchaChallenge 校验验证码并立即删除挑战,同一挑战只能使用一次;+// ID 未知、挑战已过期或答案错误时返回 false。+func ConsumeCaptchaChallenge(id, answer string) bool {+ if "" == id {+ return false+ }++ now := time.Now()+ captchaChallengeLock.Lock()+ sweepCaptchaChallengesLocked(now)+ challenge := captchaChallenges[id]+ delete(captchaChallenges, id)+ captchaChallengeLock.Unlock()++ if nil == challenge || now.After(challenge.expires) {+ return false+ }+ return 1 == subtle.ConstantTimeCompare([]byte(challenge.answer), []byte(normalizeCaptchaAnswer(answer)))+}++// normalizeCaptchaAnswer 统一验证码大小写和首尾空白,保持与大小写不敏感的输入兼容。+func normalizeCaptchaAnswer(answer string) string {+ return strings.ToUpper(strings.TrimSpace(answer))+}++// sweepCaptchaChallengesLocked 按固定间隔清理过期挑战,调用方须持有 captchaChallengeLock。+func sweepCaptchaChallengesLocked(now time.Time) {+ if now.Sub(captchaChallengeLastSweep) < captchaChallengeSweepPeriod {+ return+ }+ captchaChallengeLastSweep = now+ for id, challenge := range captchaChallenges {+ if now.After(challenge.expires) {+ delete(captchaChallenges, id)+ }+ }+}diff --git a/kernel/util/captcha_test.go b/kernel/util/captcha_test.gonew file mode 100644index 0000000000..2dffd44dcd--- /dev/null+++ b/kernel/util/captcha_test.go@@ -0,0 +1,157 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package util++import (+ "sync"+ "sync/atomic"+ "testing"+ "time"+)++// TestCaptchaChallengeSingleUse 验证同一验证码挑战只能消费一次。+func TestCaptchaChallengeSingleUse(t *testing.T) {+ resetCaptchaChallengesForTest(t)++ id := NewCaptchaChallenge("ABCD")+ if "" == id {+ t.Fatal("challenge ID is empty")+ }+ if !ConsumeCaptchaChallenge(id, "abcd") {+ t.Fatal("case-insensitive answer should be accepted")+ }+ if ConsumeCaptchaChallenge(id, "ABCD") {+ t.Fatal("consumed challenge was accepted again")+ }+}++// TestCaptchaChallengeWrongAnswer 验证答案错误时挑战同样被删除,不能在原挑战上重试。+func TestCaptchaChallengeWrongAnswer(t *testing.T) {+ resetCaptchaChallengesForTest(t)++ id := NewCaptchaChallenge("ABCD")+ if ConsumeCaptchaChallenge(id, "WXYZ") {+ t.Fatal("wrong answer was accepted")+ }+ if ConsumeCaptchaChallenge(id, "ABCD") {+ t.Fatal("challenge survived a wrong answer")+ }+}++// TestCaptchaChallengeExpiry 验证过期挑战被拒绝并清理。+func TestCaptchaChallengeExpiry(t *testing.T) {+ resetCaptchaChallengesForTest(t)++ id := NewCaptchaChallenge("ABCD")+ captchaChallengeLock.Lock()+ captchaChallenges[id].expires = time.Now().Add(-time.Second)+ captchaChallengeLock.Unlock()++ if ConsumeCaptchaChallenge(id, "ABCD") {+ t.Fatal("expired challenge was accepted")+ }+ captchaChallengeLock.Lock()+ _, exists := captchaChallenges[id]+ captchaChallengeLock.Unlock()+ if exists {+ t.Fatal("expired challenge was not removed")+ }+}++// TestCaptchaChallengeUnknownID 验证未知或空挑战 ID 一律拒绝。+func TestCaptchaChallengeUnknownID(t *testing.T) {+ resetCaptchaChallengesForTest(t)++ if ConsumeCaptchaChallenge("", "ABCD") {+ t.Fatal("empty challenge ID was accepted")+ }+ if ConsumeCaptchaChallenge("unknown-challenge-id", "ABCD") {+ t.Fatal("unknown challenge ID was accepted")+ }+}++// TestCaptchaChallengeBounded 验证挑战条数不超过上限,达到上限后仍能签发新挑战。+func TestCaptchaChallengeBounded(t *testing.T) {+ resetCaptchaChallengesForTest(t)++ for range captchaChallengeMaxEntries {+ NewCaptchaChallenge("ABCD")+ }+ id := NewCaptchaChallenge("ABCD")+ if "" == id {+ t.Fatal("challenge was not issued at the entry limit")+ }+ captchaChallengeLock.Lock()+ count := len(captchaChallenges)+ captchaChallengeLock.Unlock()+ if captchaChallengeMaxEntries < count {+ t.Fatalf("challenge entries exceeded the cap: %d", count)+ }+ if !ConsumeCaptchaChallenge(id, "ABCD") {+ t.Fatal("challenge issued at the entry limit is unusable")+ }+}++// TestCaptchaChallengeSweep 验证定期清理会删除过期挑战。+func TestCaptchaChallengeSweep(t *testing.T) {+ resetCaptchaChallengesForTest(t)++ id := NewCaptchaChallenge("ABCD")+ captchaChallengeLock.Lock()+ captchaChallenges[id].expires = time.Now().Add(-time.Second)+ captchaChallengeLastSweep = time.Now().Add(-2 * captchaChallengeSweepPeriod)+ captchaChallengeLock.Unlock()++ NewCaptchaChallenge("EFGH")+ captchaChallengeLock.Lock()+ _, exists := captchaChallenges[id]+ captchaChallengeLock.Unlock()+ if exists {+ t.Fatal("expired challenge was not swept")+ }+}++// TestCaptchaChallengeConcurrentConsume 验证并发提交同一挑战时只有一个请求成功。+func TestCaptchaChallengeConcurrentConsume(t *testing.T) {+ resetCaptchaChallengesForTest(t)++ id := NewCaptchaChallenge("ABCD")+ const consumers = 8+ success := atomic.Int32{}+ wg := sync.WaitGroup{}+ for range consumers {+ wg.Add(1)+ go func() {+ defer wg.Done()+ if ConsumeCaptchaChallenge(id, "ABCD") {+ success.Add(1)+ }+ }()+ }+ wg.Wait()+ if 1 != success.Load() {+ t.Fatalf("concurrent consumers succeeded %d times, want 1", success.Load())+ }+}++func resetCaptchaChallengesForTest(t *testing.T) {+ t.Helper()+ captchaChallengeLock.Lock()+ captchaChallenges = map[string]*captchaChallenge{}+ captchaChallengeLastSweep = time.Time{}+ captchaChallengeLock.Unlock()+}diff --git a/kernel/util/session.go b/kernel/util/session.goindex ebaa4c4a47..ffd6acac08 100644--- a/kernel/util/session.go+++ b/kernel/util/session.go@@ -159,7 +159,7 @@ type WorkspaceSession struct {AccessAuthCode stringOIDCSessionVersion stringOIDCBinding string- Captcha string+ CaptchaID string // 服务端验证码挑战 ID,验证码答案不写入会话}func (sd *SessionData) Clear(c *gin.Context) {