Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(sessions): 放行 embed 运行时读取自身会话,修复追问建议 500 与刷新丢对话

sunmh59cbe5833042
diff --git a/internal/application/service/session.go b/internal/application/service/session.go
index f6663e961..801bb5bba 100644
--- a/internal/application/service/session.go
+++ b/internal/application/service/session.go
@@ -41,6 +41,13 @@ func runtimeMayBypassAdminConsoleRead(
case types.PrincipalAPITenant, types.PrincipalAPIExternalUser:
ownerID := types.SessionOwnerIDFromContext(ctx)
return types.IsAPISessionOwnerID(session.UserID) && session.UserID == ownerID
+ case types.PrincipalEmbedSession:
+ // An embed widget runs as a Viewer but is the legitimate owner of its own
+ // channel session (verified upstream by ensureEmbedSession, including the
+ // signed handle). Allow it to read exactly the session it owns; the owner
+ // scope in repo.Get already confines it to that single row.
+ ownerID := types.SessionOwnerIDFromContext(ctx)
+ return session.UserID == ownerID
default:
return false
}
diff --git a/internal/application/service/session_user_scope_test.go b/internal/application/service/session_user_scope_test.go
index ceeb336c3..d2e938df9 100644
--- a/internal/application/service/session_user_scope_test.go
+++ b/internal/application/service/session_user_scope_test.go
@@ -400,6 +400,63 @@ func TestGetSessionAllowsIMRuntimeToReadIMSession(t *testing.T) {
require.Equal(t, "feishu", got.IMPlatform)
}
+func TestGetSessionAllowsEmbedRuntimeToReadOwnEmbedSession(t *testing.T) {
+ svc, db := newTestSessionService(t)
+ require.NoError(t, db.AutoMigrate(&testListSessionsIMChannelSession{}))
+
+ // An embed-widget session: description marks the channel, user_id is the
+ // per-session principal's storage id (see CreateEmbedSession).
+ principal := types.EmbedSessionPrincipal(1, "ch-1", "sess-1")
+ ownSession := &types.Session{
+ TenantID: 1,
+ Title: "embed chat",
+ Description: types.EmbedSessionMarkerPrefix + "ch-1",
+ UserID: principal.StorageID(),
+ }
+ require.NoError(t, db.Create(ownSession).Error)
+
+ // The embed widget authenticates as a Viewer (embed_auth.go) but is the
+ // legitimate owner of its own channel session — symmetric to the IM and
+ // API-tenant runtimes above.
+ ctx := context.WithValue(
+ testSessionScopeContext(1, "system-1"),
+ types.TenantRoleContextKey,
+ types.TenantRoleViewer,
+ )
+ ctx = types.WithPrincipal(ctx, principal)
+
+ got, err := svc.GetSession(ctx, ownSession.ID)
+ require.NoError(t, err)
+ require.Equal(t, ownSession.ID, got.ID)
+}
+
+func TestGetSessionDeniesEmbedRuntimeFromReadingForeignEmbedSession(t *testing.T) {
+ svc, db := newTestSessionService(t)
+ require.NoError(t, db.AutoMigrate(&testListSessionsIMChannelSession{}))
+
+ // A session owned by a different embed session principal.
+ owner := types.EmbedSessionPrincipal(1, "ch-1", "sess-other")
+ foreignSession := &types.Session{
+ TenantID: 1,
+ Title: "foreign embed chat",
+ Description: types.EmbedSessionMarkerPrefix + "ch-1",
+ UserID: owner.StorageID(),
+ }
+ require.NoError(t, db.Create(foreignSession).Error)
+
+ // A different embed session principal must not read it — the owner scope
+ // keeps each visitor's conversation isolated even after the bypass is granted.
+ ctx := context.WithValue(
+ testSessionScopeContext(1, "system-1"),
+ types.TenantRoleContextKey,
+ types.TenantRoleViewer,
+ )
+ ctx = types.WithPrincipal(ctx, types.EmbedSessionPrincipal(1, "ch-1", "sess-attacker"))
+
+ _, err := svc.GetSession(ctx, foreignSession.ID)
+ require.ErrorIs(t, err, apperrors.ErrSessionNotFound)
+}
+
// testListSessionsIMChannelSession lets QueryPaged's LEFT JOIN resolve against a
// real table in the in-memory SQLite database.
type testListSessionsIMChannelSession struct {
diff --git a/internal/handler/message_suggestion.go b/internal/handler/message_suggestion.go
index 539eae426..b195a65a4 100644
--- a/internal/handler/message_suggestion.go
+++ b/internal/handler/message_suggestion.go
@@ -136,6 +136,11 @@ func (h *MessageSuggestionHandler) writeError(c *gin.Context, err error) {
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
c.Error(apperrors.NewNotFoundError("suggestions not found"))
+ // apperrors.ErrSessionNotFound is a bare errors.New (not wrapping
+ // gorm.ErrRecordNotFound), so it needs its own branch to surface as a 404
+ // instead of falling through to a misleading 500.
+ case errors.Is(err, apperrors.ErrSessionNotFound):
+ c.Error(apperrors.NewNotFoundError("session not found"))
case strings.Contains(err.Error(), "completed assistant"):
c.Error(apperrors.NewBadRequestError(err.Error()))
case strings.Contains(err.Error(), "invalid suggestion event"),
diff --git a/internal/handler/message_suggestion_test.go b/internal/handler/message_suggestion_test.go
new file mode 100644
index 000000000..76f18ea39
--- /dev/null
+++ b/internal/handler/message_suggestion_test.go
@@ -0,0 +1,32 @@
+package handler
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+// When the suggestion pipeline bubbles up a session-not-found (e.g. an embed
+// Viewer whose session read was rejected), the response must be a 404, not a
+// misleading 500. apperrors.ErrSessionNotFound is a bare errors.New and so is
+// not caught by the gorm.ErrRecordNotFound branch on its own.
+func TestMessageSuggestionWriteErrorMapsSessionNotFoundTo404(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ h := NewMessageSuggestionHandler(nil)
+
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
+
+ h.writeError(c, apperrors.ErrSessionNotFound)
+
+ require.Len(t, c.Errors, 1)
+ var appErr *apperrors.AppError
+ require.ErrorAs(t, c.Errors[0].Err, &appErr)
+ require.Equal(t, apperrors.ErrNotFound, appErr.Code)
+ require.Equal(t, http.StatusNotFound, appErr.HTTPCode)
+}