WeKnora/internal/handler/session/temporary_document_engine_t...

76 lines
2.5 KiB
Go
Raw Normal View History

fix(security): close the low-severity shared-space findings (#3416) * fix(security): close the low-severity shared-space findings Verified and fixed from the shared-space permission review: - Embed channels kept knowledge_ids, tag_ids, mentioned_items, skill_names and summary_model_id from anonymous visitors. Mentions are only scoped for shared agents, so a visitor could query any KB (and pick any model) of the channel workspace by ID. The payload now drops them; the widget never sends them. - PUT /knowledgebase/:kb_id/wiki/issues/:issue_id/status updated any issue by ID. The update is now scoped to the path's KB (404 otherwise). - A direct org invite let the inviter attach any user of the target workspace (or any user by ID) as its representative, whose username and email the roster then showed to all members. Direct adds attach no representative, and the roster returns emails only for the caller's own workspace. - COS and KS3 dropped the bucket (and COS the region) segment when turning a path into an object key, while the tenant check scans every segment: cos://42/<region>/prefix/7/... passed as tenant 42 and read tenant 7's object from a shared bucket. Both must now match the service's config. - Shared agent listings returned the full agent to receivers. Prompts and the creator's user ID are withheld; capabilities and scope stay visible. - Temporary document uploads let the caller pick the parser engine (and its credentials) of a shared agent's workspace; only the agent's rules choose one there now. - Suggested questions used request / message-snapshot knowledge_ids without a permission check. Each document is now resolved to its KB and checked like KB IDs, including a shared agent's scope. - IM channels accepted any knowledge_base_id (and any agent ID on create). Both must belong to the channel's workspace, the KB also to a restricted API key's allow-list. - KB-restricted API keys could list org-shared KBs outside their allow-list in the organization views; those listings are now filtered. - With enable_rbac=false, RequireKBAccess let cross-workspace denials through. That switch is for roles inside a workspace; the guard now always denies another workspace's KB, since handlers behind it load by ID without a tenant filter. - The org member limit was counted before and enforced apart from the insert; it is now checked in the insert's transaction with the organization row locked (SQLite serializes writers instead). - The UpdateOrganization route comment and API doc said owner-only; the service and UI allow org admins. Comment and doc corrected. Documented, not changed: issued /r/ and presigned links stay valid until they expire after a share is revoked. * fix(security): address review of the low-severity shared-space fixes - Embed payloads also drop question_origin. It selects a KB like an @mention for agents that retrieve only when mentioned, and the widget never sends it; the selection stays inside the agent's scope, but an anonymous visitor should not pick among its KBs. suggestion_attribution is kept (the widget sends it and it is validated). - The receiver view of a shared agent also withholds the follow-up suggestion instruction, a prompt like the others. Starter questions are shown to receivers anyway, and the sharer's name is displayed by design. - Follow-up suggestion generation moves into the agent's workspace with types.WithExecutionTenant instead of a bare tenant rewrite, so the caller is pinned before the document permission check runs. The auth middleware and the shared run already pinned it; this removes the dependency on that. - KS3 CopyFile copies only from the service's own bucket (as COS and S3 do); another bucket's path is a cross-backend copy. Tests cover the dropped question_origin, the follow-up instruction and the /shared-agents listing, a follow-up context with the tenant switched, a repeated wiki issue status update, and the KS3 copy source.
2026-09-18 14:58:46 +00:00
package session
import (
"bytes"
"context"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type engineTestSessions struct{ interfaces.SessionService }
func (engineTestSessions) GetOwnedSession(context.Context, string) (*types.Session, error) {
return &types.Session{ID: "session-1", TenantID: 7}, nil
}
type engineTestDocuments struct {
interfaces.TemporaryDocumentService
options types.TemporaryDocumentCreateOptions
}
func (d *engineTestDocuments) Create(
_ context.Context, _ uint64, _, _, _ string, _ int64, _ io.Reader, options types.TemporaryDocumentCreateOptions,
) (*types.TemporaryDocument, error) {
d.options = options
return &types.TemporaryDocument{ID: "doc-1"}, nil
}
func uploadWithEngine(t *testing.T, h *Handler, agentID string) {
t.Helper()
body := &bytes.Buffer{}
form := multipart.NewWriter(body)
part, err := form.CreateFormFile("file", "report.pdf")
require.NoError(t, err)
_, _ = part.Write([]byte("%PDF-1.4"))
require.NoError(t, form.WriteField("parser_engine", "mineru_cloud"))
require.NoError(t, form.WriteField("agent_id", agentID))
require.NoError(t, form.Close())
c, ctx := newResolveAgentTestContext(7)
c.Params = gin.Params{{Key: "session_id", Value: "session-1"}}
req := httptest.NewRequest(http.MethodPost, "/", body).WithContext(ctx)
req.Header.Set("Content-Type", form.FormDataContentType())
c.Request = req
h.UploadTemporaryDocument(c)
require.Empty(t, c.Errors)
}
// A shared agent parses in its owner's workspace; the caller must not pick
// which of the owner's parser engines (and credentials) runs.
func TestUploadTemporaryDocumentIgnoresCallerEngineForSharedAgents(t *testing.T) {
shared := &engineTestDocuments{}
h := &Handler{
sessionService: engineTestSessions{},
temporaryDocuments: shared,
agentShareService: &resolveAgentShareStub{agent: &types.CustomAgent{ID: "shared-agent", TenantID: 84}},
customAgentService: &resolveOwnAgentStub{err: context.Canceled},
}
uploadWithEngine(t, h, "shared-agent")
require.Equal(t, uint64(84), shared.options.ResourceTenantID)
require.Empty(t, shared.options.ParserEngine)
own := &engineTestDocuments{}
h.temporaryDocuments = own
h.customAgentService = &resolveOwnAgentStub{agent: &types.CustomAgent{ID: "own-agent", TenantID: 7}}
uploadWithEngine(t, h, "own-agent")
require.Equal(t, "mineru_cloud", own.options.ParserEngine, "the caller's own workspace keeps its choice")
}