From 59cbe583304256541e7b7d04b8e88dddada8f688 Mon Sep 17 00:00:00 2001 From: sunmh Date: Thu, 30 Jul 2026 13:55:20 +0800 Subject: [PATCH] =?UTF-8?q?fix(sessions):=20=E6=94=BE=E8=A1=8C=20embed=20?= =?UTF-8?q?=E8=BF=90=E8=A1=8C=E6=97=B6=E8=AF=BB=E5=8F=96=E8=87=AA=E8=BA=AB?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=EF=BC=8C=E4=BF=AE=E5=A4=8D=E8=BF=BD=E9=97=AE?= =?UTF-8?q?=E5=BB=BA=E8=AE=AE=20500=20=E4=B8=8E=E5=88=B7=E6=96=B0=E4=B8=A2?= =?UTF-8?q?=E5=AF=B9=E8=AF=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/application/service/session.go | 7 +++ .../service/session_user_scope_test.go | 57 +++++++++++++++++++ internal/handler/message_suggestion.go | 5 ++ internal/handler/message_suggestion_test.go | 32 +++++++++++ 4 files changed, 101 insertions(+) create mode 100644 internal/handler/message_suggestion_test.go diff --git a/internal/application/service/session.go b/internal/application/service/session.go index f6663e96..801bb5bb 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 ceeb336c..d2e938df 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 539eae42..b195a65a 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 00000000..76f18ea3 --- /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) +}