diff --git a/.env.example b/.env.example index 493a6894..906c4602 100644 --- a/.env.example +++ b/.env.example @@ -557,7 +557,7 @@ SYSTEM_SIGNING_KEY= # WEKNORA_AUTH_DEFAULT_TENANT_MODE=create_personal # 是否允许普通用户登录后主动创建空间(默认 true;false 仅能邀请加入,超管不受影响)。 # WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED=true -# 启用空间级 RBAC(true 默认强制鉴权 / false 观察模式仅记录不拦截)。 +# 启用空间级 RBAC(true 默认强制鉴权 / false 观察模式:空间内角色检查仅记录不拦截;跨空间访问始终拦截)。 # WEKNORA_TENANT_ENABLE_RBAC=true # 启用跨空间访问(需配合用户的 CanAccessAllTenants 权限;默认 false)。如需跨空间管理员,需要手动修改数据库,为对应用户授予跨空间管理权限 # WEKNORA_TENANT_ENABLE_CROSS_TENANT_ACCESS=false diff --git a/internal/agent/tools/wiki_update_issue.go b/internal/agent/tools/wiki_update_issue.go index 55b2ce91..41440290 100644 --- a/internal/agent/tools/wiki_update_issue.go +++ b/internal/agent/tools/wiki_update_issue.go @@ -60,12 +60,13 @@ func (t *wikiUpdateIssueTool) Execute(ctx context.Context, args json.RawMessage) if len(t.kbIDs) == 0 { return &types.ToolResult{Success: false, Error: "No knowledge bases available"}, nil } - if _, err := resolveWikiIssue(ctx, t.wikiService, params.IssueID, t.kbIDs); err != nil { + issue, err := resolveWikiIssue(ctx, t.wikiService, params.IssueID, t.kbIDs) + if err != nil { return &types.ToolResult{Success: false, Error: err.Error()}, nil } // Update only after the issue has been proven to belong to an allowed KB. - err := t.wikiService.UpdateIssueStatus(ctx, params.IssueID, params.Status) + err = t.wikiService.UpdateIssueStatus(ctx, issue.KnowledgeBaseID, params.IssueID, params.Status) if err != nil { return &types.ToolResult{Success: false, Error: "Failed to update issue status: " + err.Error()}, nil } diff --git a/internal/application/repository/organization.go b/internal/application/repository/organization.go index 8aea0676..43c105f8 100644 --- a/internal/application/repository/organization.go +++ b/internal/application/repository/organization.go @@ -8,12 +8,14 @@ import ( "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "gorm.io/gorm" + "gorm.io/gorm/clause" ) var ( ErrOrganizationNotFound = errors.New("organization not found") ErrOrgMemberNotFound = errors.New("organization member not found") ErrOrgMemberAlreadyExists = errors.New("member already exists in organization") + ErrOrgMemberLimitReached = errors.New("organization member limit reached") ErrInviteCodeNotFound = errors.New("invite code not found") ErrInviteCodeExpired = errors.New("invite code has expired") ) @@ -115,18 +117,45 @@ func (r *organizationRepository) Delete(ctx context.Context, id string) error { // AddTenantMember inserts a new (org, tenant) membership row. Returns // ErrOrgMemberAlreadyExists if a row already exists for this tuple — the // service layer treats that as a no-op when the caller is just confirming -// an idempotent join. -func (r *organizationRepository) AddTenantMember(ctx context.Context, member *types.OrganizationTenantMember) error { - var count int64 - r.db.WithContext(ctx).Model(&types.OrganizationTenantMember{}). - Where("organization_id = ? AND tenant_id = ?", member.OrganizationID, member.TenantID). - Count(&count) - - if count > 0 { - return ErrOrgMemberAlreadyExists - } - - return r.db.WithContext(ctx).Create(member).Error +// an idempotent join — and ErrOrgMemberLimitReached when a positive +// memberLimit is already reached. +func (r *organizationRepository) AddTenantMember( + ctx context.Context, member *types.OrganizationTenantMember, memberLimit int, +) error { + return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + // A positive limit is checked in the same transaction as the insert, + // with the organization row locked, so concurrent joins cannot all + // pass the count. SQLite has no row locks; it serializes writers, + // and a stale read fails to upgrade to a write instead. + if memberLimit > 0 && tx.Name() != "sqlite" { + var org types.Organization + if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id"). + Where("id = ?", member.OrganizationID).First(&org).Error; err != nil { + return err + } + } + var existing int64 + if err := tx.Model(&types.OrganizationTenantMember{}). + Where("organization_id = ? AND tenant_id = ?", member.OrganizationID, member.TenantID). + Count(&existing).Error; err != nil { + return err + } + if existing > 0 { + return ErrOrgMemberAlreadyExists + } + if memberLimit > 0 { + var count int64 + if err := tx.Model(&types.OrganizationTenantMember{}). + Where("organization_id = ?", member.OrganizationID). + Count(&count).Error; err != nil { + return err + } + if count >= int64(memberLimit) { + return ErrOrgMemberLimitReached + } + } + return tx.Create(member).Error + }) } // RemoveTenantMember removes the (org, tenant) membership row. diff --git a/internal/application/repository/organization_member_limit_test.go b/internal/application/repository/organization_member_limit_test.go new file mode 100644 index 00000000..ce0c7b74 --- /dev/null +++ b/internal/application/repository/organization_member_limit_test.go @@ -0,0 +1,39 @@ +package repository + +import ( + "context" + "fmt" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +// The member limit is enforced with the insert, not by a separate count the +// caller did earlier, so concurrent joins cannot exceed it. +func TestAddTenantMemberEnforcesLimitWithTheInsert(t *testing.T) { + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.Exec(`CREATE TABLE organization_tenant_members ( + id TEXT PRIMARY KEY, organization_id TEXT, tenant_id INTEGER, role TEXT, + representative_user_id TEXT, joined_at DATETIME, created_at DATETIME, updated_at DATETIME + )`).Error) + repo := &organizationRepository{db: db} + add := func(tenantID uint64, limit int) error { + return repo.AddTenantMember(context.Background(), &types.OrganizationTenantMember{ + ID: fmt.Sprintf("m-%d", tenantID), OrganizationID: "org", TenantID: tenantID, Role: types.OrgRoleViewer, + }, limit) + } + + require.NoError(t, add(1, 2)) + require.NoError(t, add(2, 2)) + require.ErrorIs(t, add(3, 2), ErrOrgMemberLimitReached) + require.ErrorIs(t, add(2, 0), ErrOrgMemberAlreadyExists) + require.NoError(t, add(3, 0), "no limit") + + var count int64 + require.NoError(t, db.Model(&types.OrganizationTenantMember{}).Count(&count).Error) + require.Equal(t, int64(3), count) +} diff --git a/internal/application/repository/wiki_page.go b/internal/application/repository/wiki_page.go index 1df87e95..a868d933 100644 --- a/internal/application/repository/wiki_page.go +++ b/internal/application/repository/wiki_page.go @@ -17,6 +17,9 @@ import ( // ErrWikiPageNotFound is returned when a wiki page is not found var ErrWikiPageNotFound = errors.New("wiki page not found") +// ErrWikiIssueNotFound means no issue with that ID belongs to the knowledge base. +var ErrWikiIssueNotFound = errors.New("wiki issue not found") + // ErrWikiPageConflict is returned when an optimistic lock conflict is detected var ErrWikiPageConflict = errors.New("wiki page version conflict") @@ -1418,8 +1421,17 @@ func (r *wikiPageRepository) ListIssues(ctx context.Context, kbID string, slug s return issues, nil } -func (r *wikiPageRepository) UpdateIssueStatus(ctx context.Context, issueID string, status string) error { - return r.db.WithContext(ctx).Model(&types.WikiPageIssue{}). - Where("id = ?", issueID). - Update("status", status).Error +func (r *wikiPageRepository) UpdateIssueStatus(ctx context.Context, kbID string, issueID string, status string) error { + // Scoped to the knowledge base the caller was authorized for: issue IDs are + // listed to readers, so an ID alone must not reach another KB's issue. + result := r.db.WithContext(ctx).Model(&types.WikiPageIssue{}). + Where("id = ? AND knowledge_base_id = ?", issueID, kbID). + Update("status", status) + if result.Error != nil { + return result.Error + } + if result.RowsAffected == 0 { + return ErrWikiIssueNotFound + } + return nil } diff --git a/internal/application/repository/wiki_page_test.go b/internal/application/repository/wiki_page_test.go index f2150233..c2651ed9 100644 --- a/internal/application/repository/wiki_page_test.go +++ b/internal/application/repository/wiki_page_test.go @@ -758,3 +758,28 @@ func TestDeleteByKnowledgeBaseIDScopesSoftAndHardDeletes(t *testing.T) { require.NoError(t, err) require.Len(t, otherIssues, 1) } + +// Issue IDs are listed to readers of a KB; updating one must be scoped to the +// KB the caller was authorized for. +func TestUpdateIssueStatus_ScopedToKnowledgeBase(t *testing.T) { + db := setupWikiPagesTestDB(t) + require.NoError(t, db.Create(&types.WikiPageIssue{ + ID: "issue-1", TenantID: 7, KnowledgeBaseID: "kb-a", Slug: "page", Status: "pending", + }).Error) + repo := &wikiPageRepository{db: db} + status := func() string { + var got string + require.NoError(t, db.Raw(`SELECT status FROM wiki_page_issues WHERE id = 'issue-1'`).Scan(&got).Error) + return got + } + + err := repo.UpdateIssueStatus(context.Background(), "kb-b", "issue-1", "resolved") + require.ErrorIs(t, err, ErrWikiIssueNotFound) + assert.Equal(t, "pending", status()) + + require.NoError(t, repo.UpdateIssueStatus(context.Background(), "kb-a", "issue-1", "resolved")) + assert.Equal(t, "resolved", status()) + // Setting the same status again is not "not found": both supported + // databases count matched rows, and updated_at changes anyway. + require.NoError(t, repo.UpdateIssueStatus(context.Background(), "kb-a", "issue-1", "resolved")) +} diff --git a/internal/application/service/agent_share.go b/internal/application/service/agent_share.go index 98e5f330..bc9c7b86 100644 --- a/internal/application/service/agent_share.go +++ b/internal/application/service/agent_share.go @@ -71,6 +71,35 @@ func isBuiltinAgent(agent *types.CustomAgent) bool { return agent != nil && (agent.IsBuiltin || types.IsBuiltinAgentID(agent.ID)) } +// receiverAgentView is the copy of a shared agent that other workspaces see. +// Receivers use the agent's capabilities and resource scope (models, KBs, MCP, +// web search), but its prompts are the owner's work and the creator's user +// ID identifies a person in another workspace, so both are withheld. Runs +// load the agent separately (GetSharedAgentForTenant) and are unaffected. +func receiverAgentView(agent *types.CustomAgent) *types.CustomAgent { + if agent == nil { + return nil + } + view := *agent + view.CreatedBy = "" + view.Config.SystemPrompt = "" + view.Config.SystemPromptID = "" + view.Config.ContextTemplate = "" + view.Config.ContextTemplateID = "" + view.Config.RewritePromptSystem = "" + view.Config.RewritePromptUser = "" + view.Config.FallbackPrompt = "" + view.Config.IntentPrompts = nil + if suggestions := view.Config.QuestionSuggestions; suggestions != nil { + // Starter questions are shown to receivers anyway; the instruction + // for generating follow-ups is a prompt like the others. + copied := *suggestions + copied.FollowUps.AdditionalInstruction = "" + view.Config.QuestionSuggestions = &copied + } + return &view +} + // agentShareService implements AgentShareService. // // Plan 3 of #1303: visibility and access checks key on the caller's @@ -312,6 +341,7 @@ func (s *agentShareService) ListSharedAgents(ctx context.Context, tenantID uint6 effective := types.MinOrgRole(share.Permission, tm.Role) effective = applyTenantRoleCap(effective, callerTenantRole) info := s.sharedAgentInfo(ctx, share, effective, webSearchReadyCache) + info.Agent = receiverAgentView(info.Agent) key := fmt.Sprintf("%s_%d", share.AgentID, share.SourceTenantID) existing, exists := agentInfoMap[key] if !exists { @@ -372,6 +402,9 @@ func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context, effective = applyTenantRoleCap(effective, callerTenantRole) info := s.sharedAgentInfo(ctx, share, effective, webSearchReadyCache) + if share.SourceTenantID != tenantID { + info.Agent = receiverAgentView(info.Agent) + } item := &types.OrganizationSharedAgentItem{ SharedAgentInfo: *info, @@ -434,6 +467,9 @@ func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context, effective := types.MinOrgRole(share.Permission, tm.Role) effective = applyTenantRoleCap(effective, callerTenantRole) info := s.sharedAgentInfo(ctx, share, effective, webSearchReadyCache) + if share.SourceTenantID != tenantID { + info.Agent = receiverAgentView(info.Agent) + } item := &types.OrganizationSharedAgentItem{ SharedAgentInfo: *info, IsMine: share.SourceTenantID == tenantID, diff --git a/internal/application/service/agent_share_builtin_test.go b/internal/application/service/agent_share_builtin_test.go index 47b38630..ec38a9d8 100644 --- a/internal/application/service/agent_share_builtin_test.go +++ b/internal/application/service/agent_share_builtin_test.go @@ -63,3 +63,105 @@ func TestGetSharedAgentForTenantRefusesBuiltinAgents(t *testing.T) { require.Nil(t, agent) } } + +type receiverViewOrgRepo struct { + interfaces.OrganizationRepository +} + +func (receiverViewOrgRepo) GetTenantMember(context.Context, string, uint64) (*types.OrganizationTenantMember, error) { + return &types.OrganizationTenantMember{Role: types.OrgRoleViewer}, nil +} + +type receiverViewShareRepo struct { + interfaces.AgentShareRepository + shares []*types.AgentShare +} + +func (r receiverViewShareRepo) ListByOrganization(context.Context, string) ([]*types.AgentShare, error) { + return r.shares, nil +} + +type receiverViewDisabledRepo struct { + interfaces.TenantDisabledSharedAgentRepository +} + +func (receiverViewDisabledRepo) ListByTenantID(context.Context, uint64) ([]*types.TenantDisabledSharedAgent, error) { + return nil, nil +} + +// Other workspaces see what a shared agent can do and reach, not its prompts +// or its creator; the sharing workspace still gets the full config to edit. +func TestSharedAgentListsWithholdPromptsFromReceivers(t *testing.T) { + agent := func(tenantID uint64) *types.CustomAgent { + return &types.CustomAgent{ + ID: "agent", TenantID: tenantID, CreatedBy: "owner-user", + Config: types.CustomAgentConfig{ + SystemPrompt: "secret prompt", RewritePromptSystem: "secret rewrite", + KBSelectionMode: "selected", KnowledgeBases: []string{"kb-1"}, ModelID: "model-1", + QuestionSuggestions: &types.QuestionSuggestionConfig{ + Starters: types.StarterSuggestionConfig{Items: []string{"What is new?"}}, + FollowUps: types.FollowUpSuggestionConfig{AdditionalInstruction: "secret follow-up instruction"}, + }, + }, + } + } + svc := &agentShareService{ + orgRepo: receiverViewOrgRepo{}, + disabledRepo: receiverViewDisabledRepo{}, + shareRepo: receiverViewShareRepo{shares: []*types.AgentShare{ + {AgentID: "agent", SourceTenantID: 84, Permission: types.OrgRoleViewer, Agent: agent(84)}, + {AgentID: "agent", SourceTenantID: 7, Permission: types.OrgRoleViewer, Agent: agent(7)}, + }}, + } + + items, err := svc.ListSharedAgentsInOrganization(context.Background(), "org", 7, types.TenantRoleAdmin) + require.NoError(t, err) + require.Len(t, items, 2) + for _, item := range items { + if item.IsMine { + require.Equal(t, "secret prompt", item.Agent.Config.SystemPrompt) + require.Equal(t, "secret follow-up instruction", + item.Agent.Config.QuestionSuggestions.FollowUps.AdditionalInstruction) + continue + } + require.Empty(t, item.Agent.Config.SystemPrompt) + require.Empty(t, item.Agent.Config.RewritePromptSystem) + require.Empty(t, item.Agent.Config.QuestionSuggestions.FollowUps.AdditionalInstruction) + require.Equal(t, []string{"What is new?"}, item.Agent.Config.QuestionSuggestions.Starters.Items, + "starter questions are shown to receivers anyway") + require.Empty(t, item.Agent.CreatedBy) + require.Equal(t, []string{"kb-1"}, item.Agent.Config.KnowledgeBases, "the scope stays visible") + require.Equal(t, "model-1", item.Agent.Config.ModelID) + } +} + +type receiverViewTenantShareRepo struct { + interfaces.AgentShareRepository + shares []*types.AgentShare +} + +func (r receiverViewTenantShareRepo) ListSharedAgentsForTenant(context.Context, uint64) ([]*types.AgentShare, error) { + return r.shares, nil +} + +// /shared-agents lists only other workspaces' agents, all as receiver views. +func TestListSharedAgentsWithholdsPrompts(t *testing.T) { + agent := &types.CustomAgent{ + ID: "agent", TenantID: 84, CreatedBy: "owner-user", + Config: types.CustomAgentConfig{SystemPrompt: "secret prompt", ModelID: "model-1"}, + } + svc := &agentShareService{ + orgRepo: receiverViewOrgRepo{}, + disabledRepo: receiverViewDisabledRepo{}, + shareRepo: receiverViewTenantShareRepo{shares: []*types.AgentShare{ + {AgentID: "agent", SourceTenantID: 84, Permission: types.OrgRoleViewer, Agent: agent}, + }}, + } + + infos, err := svc.ListSharedAgents(context.Background(), 7, types.TenantRoleAdmin) + require.NoError(t, err) + require.Len(t, infos, 1) + require.Empty(t, infos[0].Agent.Config.SystemPrompt) + require.Empty(t, infos[0].Agent.CreatedBy) + require.Equal(t, "model-1", infos[0].Agent.Config.ModelID) +} diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.go index b2ed591f..3700df96 100644 --- a/internal/application/service/custom_agent.go +++ b/internal/application/service/custom_agent.go @@ -582,6 +582,7 @@ func (s *customAgentService) getSuggestedQuestions( if err := types.AuthorizeTenantAPIKeyOptionalTagIDs(ctx, scopeTagIDs); err != nil { return nil, err } + knowledgeIDs = s.readableSuggestionKnowledgeIDs(ctx, knowledgeIDs) // Get tenant ID from context tenantID, ok := types.TenantIDFromContext(ctx) @@ -1121,6 +1122,40 @@ func wikiSuggestionFromPage(page *types.WikiPage, locale string) string { } } +// maxSuggestionKnowledgeIDs bounds the per-document lookups below; a +// suggestion scope is a handful of @mentioned or retrieved documents. +const maxSuggestionKnowledgeIDs = 50 + +// readableSuggestionKnowledgeIDs keeps the documents the caller may read. +// KB IDs are filtered the same way in groupKBIDsByEffectiveTenant, but +// document IDs (from the request or a message snapshot, which records them +// before a shared agent's scope is applied) reach a tenant's chunks directly: +// each is resolved to its KB and checked, including a shared agent's scope. +func (s *customAgentService) readableSuggestionKnowledgeIDs(ctx context.Context, knowledgeIDs []string) []string { + if len(knowledgeIDs) == 0 { + return knowledgeIDs + } + if s.knowledgeRepo == nil { + return nil + } + if len(knowledgeIDs) > maxSuggestionKnowledgeIDs { + knowledgeIDs = knowledgeIDs[:maxSuggestionKnowledgeIDs] + } + permissions := access.NewKBPermissions(ctx, s.kbShareService) + readable := make([]string, 0, len(knowledgeIDs)) + for _, id := range knowledgeIDs { + knowledge, err := s.knowledgeRepo.GetKnowledgeByIDOnly(ctx, id) + if err != nil || knowledge == nil { + continue + } + ok, err := permissions.Check(knowledge.KnowledgeBaseID, knowledge.TenantID, types.OrgRoleViewer) + if err == nil && ok { + readable = append(readable, id) + } + } + return readable +} + // groupKBIDsByEffectiveTenant resolves each kbID to the tenant whose chunk // rows back that KB, so cross-tenant shares can be queried correctly: // - In-tenant KBs map to the caller's tenant id. diff --git a/internal/application/service/custom_agent_suggestion_scope_test.go b/internal/application/service/custom_agent_suggestion_scope_test.go index 215325ee..7874ab07 100644 --- a/internal/application/service/custom_agent_suggestion_scope_test.go +++ b/internal/application/service/custom_agent_suggestion_scope_test.go @@ -2,8 +2,10 @@ package service import ( "context" + "errors" "testing" + "github.com/Tencent/WeKnora/internal/application/access" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/stretchr/testify/assert" @@ -143,3 +145,46 @@ func TestExcludeSuggestionStrings_TagScopeOverridesSameKnowledgeBase(t *testing. got := excludeSuggestionStrings([]string{"kb-with-tag", "kb-explicit"}, []string{"kb-with-tag"}) assert.Equal(t, []string{"kb-explicit"}, got) } + +type suggestionDocRepo struct { + interfaces.KnowledgeRepository + docs map[string]*types.Knowledge +} + +func (r *suggestionDocRepo) GetKnowledgeByIDOnly(_ context.Context, id string) (*types.Knowledge, error) { + if doc, ok := r.docs[id]; ok { + return doc, nil + } + return nil, errors.New("not found") +} + +// Document IDs in a suggestion scope reach a tenant's chunks directly, so each +// must be readable by the caller, as KB IDs already are: a shared agent's +// message snapshot records them before the agent's scope is applied. +func TestReadableSuggestionKnowledgeIDs(t *testing.T) { + svc := &customAgentService{knowledgeRepo: &suggestionDocRepo{docs: map[string]*types.Knowledge{ + "own-doc": {ID: "own-doc", TenantID: 7, KnowledgeBaseID: "own-kb"}, + "scoped-doc": {ID: "scoped-doc", TenantID: 84, KnowledgeBaseID: "agent-kb"}, + "unscoped-doc": {ID: "unscoped-doc", TenantID: 84, KnowledgeBaseID: "other-kb"}, + }}} + caller := types.WithCaller(context.Background(), + types.Caller{TenantID: 7, UserID: "u", Role: types.TenantRoleAdmin}) + ids := []string{"own-doc", "scoped-doc", "unscoped-doc", "missing-doc"} + + assert.Equal(t, []string{"own-doc"}, svc.readableSuggestionKnowledgeIDs(caller, ids)) + + sharedRun := access.WithSharedAgent(caller, &types.CustomAgent{ + ID: "agent", TenantID: 84, + Config: types.CustomAgentConfig{KBSelectionMode: "selected", KnowledgeBases: []string{"agent-kb"}}, + }) + assert.Equal(t, []string{"own-doc", "scoped-doc"}, svc.readableSuggestionKnowledgeIDs(sharedRun, ids)) + + // Follow-up generation moves execution into the agent's workspace; with + // the caller pinned, its documents still need the agent's grant. + followUp := types.WithExecutionTenant(sharedRun, 84) + assert.Equal(t, []string{"own-doc", "scoped-doc"}, svc.readableSuggestionKnowledgeIDs(followUp, ids)) + uncaptured := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7)) + assert.Equal(t, []string{"own-doc"}, + svc.readableSuggestionKnowledgeIDs(types.WithExecutionTenant(uncaptured, 84), ids), + "execution in the agent's workspace does not make its documents the caller's") +} diff --git a/internal/application/service/file/cos.go b/internal/application/service/file/cos.go index 442584f2..5bcc0b0e 100644 --- a/internal/application/service/file/cos.go +++ b/internal/application/service/file/cos.go @@ -173,6 +173,16 @@ func (s *cosFileService) parseCosObjectName(filePath string) (string, error) { rest := strings.TrimPrefix(filePath, cosScheme) parts := strings.SplitN(rest, "/", 3) if len(parts) == 3 { + // Bucket and region are not part of the object key, but the + // tenant check (ParseTenantIDFromStoragePath) scans them too: an + // unchecked numeric bucket or region would pass as the caller's + // tenant while the key reads another tenant's object. + if s.bucketName != "" && parts[0] != s.bucketName { + return "", fmt.Errorf("bucket mismatch in path: got %s, want %s", parts[0], s.bucketName) + } + if s.region != "" && parts[1] != s.region { + return "", fmt.Errorf("region mismatch in path: got %s, want %s", parts[1], s.region) + } return parts[2], nil } return rest, nil diff --git a/internal/application/service/file/cos_parse_test.go b/internal/application/service/file/cos_parse_test.go index ab577836..3c2630d5 100644 --- a/internal/application/service/file/cos_parse_test.go +++ b/internal/application/service/file/cos_parse_test.go @@ -27,3 +27,24 @@ func TestParseCosObjectName_RejectsMinioScheme(t *testing.T) { require.Error(t, err) assert.Contains(t, err.Error(), "minio") } + +// The tenant check scans every path segment, so a numeric bucket or region +// segment could pass as the caller's tenant (42 here) while the object key +// reads tenant 7's file from the shared bucket. Both must match the service. +func TestParseCosObjectName_RejectsForeignBucketOrRegion(t *testing.T) { + svc := &cosFileService{ + bucketURL: "https://weknora-1250000000.cos.ap-shanghai.myqcloud.com/", + bucketName: "weknora-1250000000", + region: "ap-shanghai", + } + for _, path := range []string{ + "cos://42/ap-shanghai/weknora/7/knowledge/secret.pdf", + "cos://weknora-1250000000/42/weknora/7/knowledge/secret.pdf", + } { + _, err := svc.parseCosObjectName(path) + require.Error(t, err, path) + } + key, err := svc.parseCosObjectName("cos://weknora-1250000000/ap-shanghai/weknora/42/exports/a.png") + require.NoError(t, err) + assert.Equal(t, "weknora/42/exports/a.png", key) +} diff --git a/internal/application/service/file/ks3.go b/internal/application/service/file/ks3.go index 07b5528c..8954fbcd 100644 --- a/internal/application/service/file/ks3.go +++ b/internal/application/service/file/ks3.go @@ -133,6 +133,19 @@ func parseKS3FilePath(filePath string) (bucket, objectKey string, err error) { return parts[0], parts[1], nil } +// objectKey resolves a ks3:// path of this service's bucket. The bucket is not +// part of the key but the tenant check scans it, so it must match. +func (s *ks3FileService) objectKey(filePath string) (string, error) { + bucket, objectKey, err := parseKS3FilePath(filePath) + if err != nil { + return "", err + } + if bucket != s.bucketName { + return "", fmt.Errorf("bucket mismatch in path: got %s, want %s", bucket, s.bucketName) + } + return objectKey, nil +} + func (s *ks3FileService) SaveFile(ctx context.Context, file *multipart.FileHeader, tenantID uint64, knowledgeID string) (string, error) { ext := filepath.Ext(file.Filename) objectKey := joinKS3Key(s.pathPrefix, fmt.Sprintf("%d", tenantID), knowledgeID, uuid.New().String()+ext) @@ -188,7 +201,10 @@ func (s *ks3FileService) SaveBytes(ctx context.Context, data []byte, tenantID ui func (s *ks3FileService) CopyFile(ctx context.Context, srcPath string, tenantID uint64, knowledgeID string, ) (string, error) { - srcBucket, srcKey, err := parseKS3FilePath(srcPath) + // Like COS and S3, only this service's bucket is copied server-side; a + // path of another scheme or bucket falls back to a streamed copy through + // its own backend. + srcKey, err := s.objectKey(srcPath) if err != nil { return "", fmt.Errorf("ks3 copy rejected source %q: %w", srcPath, ErrCrossBackendCopy) } @@ -202,7 +218,7 @@ func (s *ks3FileService) CopyFile(ctx context.Context, _, err = s.client.CopyObject(&ks3s3.CopyObjectInput{ Bucket: ks3aws.String(s.bucketName), Key: ks3aws.String(destKey), - SourceBucket: ks3aws.String(srcBucket), + SourceBucket: ks3aws.String(s.bucketName), SourceKey: ks3aws.String(srcKey), }) if err != nil { @@ -215,7 +231,7 @@ func (s *ks3FileService) CopyFile(ctx context.Context, } func (s *ks3FileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) { - _, objectKey, err := parseKS3FilePath(filePath) + objectKey, err := s.objectKey(filePath) if err != nil { return nil, err } @@ -235,7 +251,7 @@ func (s *ks3FileService) GetFile(ctx context.Context, filePath string) (io.ReadC } func (s *ks3FileService) DeleteFile(ctx context.Context, filePath string) error { - _, objectKey, err := parseKS3FilePath(filePath) + objectKey, err := s.objectKey(filePath) if err != nil { return err } @@ -270,7 +286,7 @@ func (s *ks3FileService) CheckConnectivity(ctx context.Context) error { } func (s *ks3FileService) GetFileURL(ctx context.Context, filePath string) (string, error) { - _, objectKey, err := parseKS3FilePath(filePath) + objectKey, err := s.objectKey(filePath) if err != nil { return "", err } diff --git a/internal/application/service/file/ks3_path_test.go b/internal/application/service/file/ks3_path_test.go new file mode 100644 index 00000000..482399c3 --- /dev/null +++ b/internal/application/service/file/ks3_path_test.go @@ -0,0 +1,30 @@ +package file + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The bucket is not part of the KS3 object key, but the tenant check scans it; +// a numeric bucket segment must not pass as the caller's tenant. +func TestKS3ObjectKeyRequiresTheServiceBucket(t *testing.T) { + svc := &ks3FileService{bucketName: "weknora"} + _, err := svc.objectKey("ks3://42/prefix/7/knowledge/secret.pdf") + require.Error(t, err) + + key, err := svc.objectKey("ks3://weknora/prefix/42/exports/a.png") + require.NoError(t, err) + assert.Equal(t, "prefix/42/exports/a.png", key) +} + +// A server-side copy reads only this service's bucket; another bucket's path +// is reported as a cross-backend copy so the caller streams it instead. +func TestKS3CopyFileRejectsForeignBucket(t *testing.T) { + svc := &ks3FileService{bucketName: "weknora"} + _, err := svc.CopyFile(context.Background(), "ks3://other-bucket/prefix/7/knowledge/a.pdf", 42, "k-1") + require.True(t, errors.Is(err, ErrCrossBackendCopy), "err = %v", err) +} diff --git a/internal/application/service/message_suggestion.go b/internal/application/service/message_suggestion.go index c825110d..85e15d46 100644 --- a/internal/application/service/message_suggestion.go +++ b/internal/application/service/message_suggestion.go @@ -346,7 +346,7 @@ func (s *messageSuggestionService) generateWithModel( modelCtx := ctx if message.AgentTenantID != 0 { - modelCtx = context.WithValue(modelCtx, types.TenantIDContextKey, message.AgentTenantID) + modelCtx = types.WithExecutionTenant(modelCtx, message.AgentTenantID) } chatModel, err := s.modelService.GetChatModel(modelCtx, modelID) if err != nil { @@ -413,7 +413,11 @@ func (s *messageSuggestionService) generateFromKnowledge( } knowledgeCtx := ctx if message.AgentTenantID != 0 { - knowledgeCtx = context.WithValue(knowledgeCtx, types.TenantIDContextKey, message.AgentTenantID) + // WithExecutionTenant pins the caller before moving execution into the + // agent's workspace; a bare tenant rewrite would make a context without + // a captured caller read as that workspace, passing every permission + // check on its documents. + knowledgeCtx = types.WithExecutionTenant(knowledgeCtx, message.AgentTenantID) } poolSize := count * 5 if poolSize < 10 { diff --git a/internal/application/service/organization.go b/internal/application/service/organization.go index 3e1fcf87..1cda5f90 100644 --- a/internal/application/service/organization.go +++ b/internal/application/service/organization.go @@ -134,7 +134,7 @@ func (s *organizationService) CreateOrganization(ctx context.Context, userID str UpdatedAt: now, } - if err := s.orgRepo.AddTenantMember(ctx, member); err != nil { + if err := s.orgRepo.AddTenantMember(ctx, member, 0); err != nil { logger.Errorf(ctx, "Failed to add creator tenant as member: %v", err) // Rollback organization creation _ = s.orgRepo.Delete(ctx, org.ID) @@ -362,16 +362,6 @@ func (s *organizationService) AddTenantMember(ctx context.Context, orgID string, if err != nil { return err } - if org.MemberLimit > 0 { - count, errCount := s.orgRepo.CountTenantMembers(ctx, orgID) - if errCount != nil { - return errCount - } - if count >= int64(org.MemberLimit) { - return ErrOrgMemberLimitReached - } - } - now := time.Now() member := &types.OrganizationTenantMember{ ID: uuid.New().String(), @@ -384,7 +374,20 @@ func (s *organizationService) AddTenantMember(ctx context.Context, orgID string, UpdatedAt: now, } - return s.orgRepo.AddTenantMember(ctx, member) + return s.addTenantMemberWithinLimit(ctx, member, org.MemberLimit) +} + +// addTenantMemberWithinLimit inserts a membership with the org's member limit +// enforced atomically by the repository (counting first and inserting later +// let concurrent joins exceed it). +func (s *organizationService) addTenantMemberWithinLimit( + ctx context.Context, member *types.OrganizationTenantMember, memberLimit int, +) error { + err := s.orgRepo.AddTenantMember(ctx, member, memberLimit) + if errors.Is(err, repository.ErrOrgMemberLimitReached) { + return ErrOrgMemberLimitReached + } + return err } // RemoveTenantMember removes a tenant from an organization. @@ -522,16 +525,6 @@ func (s *organizationService) joinAsViewerWithChecks(ctx context.Context, org *t return err } - if org.MemberLimit > 0 { - count, errCount := s.orgRepo.CountTenantMembers(ctx, org.ID) - if errCount != nil { - return errCount - } - if count >= int64(org.MemberLimit) { - return ErrOrgMemberLimitReached - } - } - now := time.Now() member := &types.OrganizationTenantMember{ ID: uuid.New().String(), @@ -544,7 +537,7 @@ func (s *organizationService) joinAsViewerWithChecks(ctx context.Context, org *t UpdatedAt: now, } - return s.orgRepo.AddTenantMember(ctx, member) + return s.addTenantMemberWithinLimit(ctx, member, org.MemberLimit) } // JoinByInviteCode allows a tenant to join via invite code. @@ -741,15 +734,6 @@ func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID strin if errOrg != nil { return errOrg } - if org.MemberLimit > 0 { - count, errCount := s.orgRepo.CountTenantMembers(ctx, request.OrganizationID) - if errCount != nil { - return errCount - } - if count >= int64(org.MemberLimit) { - return ErrOrgMemberLimitReached - } - } now := time.Now() member := &types.OrganizationTenantMember{ ID: uuid.New().String(), @@ -761,7 +745,7 @@ func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID strin CreatedAt: now, UpdatedAt: now, } - if err := s.orgRepo.AddTenantMember(ctx, member); err != nil { + if err := s.addTenantMemberWithinLimit(ctx, member, org.MemberLimit); err != nil { return err } logger.Infof(ctx, "Join request %s approved, tenant %d added to organization %s with role %s", requestID, request.TenantID, request.OrganizationID, role) diff --git a/internal/application/service/wiki_page.go b/internal/application/service/wiki_page.go index cd9f96bd..83fb0990 100644 --- a/internal/application/service/wiki_page.go +++ b/internal/application/service/wiki_page.go @@ -1369,8 +1369,8 @@ func (s *wikiPageService) ListIssues(ctx context.Context, kbID string, slug stri } // UpdateIssueStatus updates an issue's status -func (s *wikiPageService) UpdateIssueStatus(ctx context.Context, issueID string, status string) error { - return s.repo.UpdateIssueStatus(ctx, issueID, status) +func (s *wikiPageService) UpdateIssueStatus(ctx context.Context, kbID string, issueID string, status string) error { + return s.repo.UpdateIssueStatus(ctx, kbID, issueID, status) } // --- Folder tree (wiki_folders) --- diff --git a/internal/handler/embed_channel.go b/internal/handler/embed_channel.go index a0aa6323..47fdec62 100644 --- a/internal/handler/embed_channel.go +++ b/internal/handler/embed_channel.go @@ -701,6 +701,20 @@ func patchEmbedChatPayload(body io.Reader, ch *types.EmbedChannel, agentMode boo // source workspace would switch it to another workspace's share of that ID. delete(payload, types.AgentSourceTenantIDParam) payload["knowledge_base_ids"] = []string{} + // Visitors are anonymous and run as Viewer of the whole channel workspace. + // Explicit targets (documents, tags, @mentions) and a model override are + // only honored within an agent's scope for shared agents, so for a + // channel's own agent they would reach any KB or model of the workspace by + // ID. A question origin selects a KB like an @mention for agents that + // retrieve only when mentioned. The widget never sends any of them; + // retrieval follows the channel agent. (suggestion_attribution is sent, + // and is validated against the session's recorded suggestions.) + payload["knowledge_ids"] = []string{} + payload["tag_ids"] = []string{} + payload["mentioned_items"] = []any{} + payload["skill_names"] = []string{} + delete(payload, "summary_model_id") + delete(payload, "question_origin") clientWebSearch := false if v, ok := payload["web_search_enabled"].(bool); ok { clientWebSearch = v diff --git a/internal/handler/embed_flow_test.go b/internal/handler/embed_flow_test.go index 93694eca..5a42e815 100644 --- a/internal/handler/embed_flow_test.go +++ b/internal/handler/embed_flow_test.go @@ -184,7 +184,9 @@ func TestEmbedExchangeFlowIntegration(t *testing.T) { func TestPatchEmbedChatPayloadInjectsAgentID(t *testing.T) { ch := &types.EmbedChannel{AgentID: "agent-embed-42"} - body := `{"query":"hello","agent_id":"client-override","agent_source_tenant_id":84,"web_search_enabled":true}` + body := `{"query":"hello","agent_id":"client-override","agent_source_tenant_id":84,"web_search_enabled":true,` + + `"knowledge_ids":["doc-x"],"tag_ids":["tag-x"],"mentioned_items":[{"id":"kb-x","type":"kb"}],` + + `"skill_names":["s"],"summary_model_id":"model-x","question_origin":{"knowledge_base_id":"kb-x"}}` patched, err := patchEmbedChatPayload(strings.NewReader(body), ch, false) if err != nil { @@ -214,6 +216,18 @@ func TestPatchEmbedChatPayloadInjectsAgentID(t *testing.T) { if !ok || len(kbIDs) != 0 { t.Fatalf("knowledge_base_ids = %v, want empty slice", payload["knowledge_base_ids"]) } + // Explicit targets and a model override would reach any KB or model of + // the channel workspace by ID. + for _, key := range []string{"knowledge_ids", "tag_ids", "mentioned_items", "skill_names"} { + if values, ok := payload[key].([]any); !ok || len(values) != 0 { + t.Fatalf("%s = %v, want empty", key, payload[key]) + } + } + for _, key := range []string{"summary_model_id", "question_origin"} { + if _, ok := payload[key]; ok { + t.Fatalf("%s = %v, want dropped", key, payload[key]) + } + } } func TestPatchEmbedChatPayloadWebSearchRequiresClientOptIn(t *testing.T) { diff --git a/internal/handler/im.go b/internal/handler/im.go index 1e24c46c..0b1ff541 100644 --- a/internal/handler/im.go +++ b/internal/handler/im.go @@ -81,16 +81,25 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) { } channel := &im.IMChannel{ - TenantID: tenantID, - AgentID: agentID, - Platform: req.Platform, - Name: req.Name, - Mode: req.Mode, - OutputMode: req.OutputMode, - SessionMode: req.SessionMode, - KnowledgeBaseID: req.KnowledgeBaseID, - Credentials: req.Credentials, - Enabled: true, + TenantID: tenantID, + AgentID: agentID, + Platform: req.Platform, + Name: req.Name, + Mode: req.Mode, + OutputMode: req.OutputMode, + SessionMode: req.SessionMode, + Credentials: req.Credentials, + Enabled: true, + } + // The route guard passes an agent it cannot find in this workspace; both + // the agent and the file-saving KB must belong to the channel's workspace. + if err := h.imService.SetChannelAgentID(c.Request.Context(), channel, agentID); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "agent not found"}) + return + } + if err := h.imService.SetChannelKnowledgeBaseID(c.Request.Context(), channel, req.KnowledgeBaseID); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "knowledge base not found"}) + return } if req.Enabled != nil { channel.Enabled = *req.Enabled @@ -233,7 +242,11 @@ func (h *IMHandler) UpdateIMChannel(c *gin.Context) { channel.SessionMode = *req.SessionMode } if req.KnowledgeBaseID != nil { - channel.KnowledgeBaseID = *req.KnowledgeBaseID + ctx := c.Request.Context() + if err := h.imService.SetChannelKnowledgeBaseID(ctx, channel, *req.KnowledgeBaseID); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "knowledge base not found"}) + return + } } if req.Credentials != nil { channel.Credentials = req.Credentials diff --git a/internal/handler/organization.go b/internal/handler/organization.go index a12d24f2..95f6f38d 100644 --- a/internal/handler/organization.go +++ b/internal/handler/organization.go @@ -423,8 +423,12 @@ func (h *OrganizationHandler) ListMembers(c *gin.Context) { } if m.RepresentativeUser != nil { resp.Username = m.RepresentativeUser.Username - resp.Email = m.RepresentativeUser.Email resp.Avatar = m.RepresentativeUser.Avatar + // The roster reaches every member of every workspace; other + // workspaces' users' emails are not part of it. + if m.TenantID == tenantID { + resp.Email = m.RepresentativeUser.Email + } } response = append(response, resp) } @@ -1187,6 +1191,12 @@ func (h *OrganizationHandler) UpdateSharePermission(c *gin.Context) { }) } +// apiKeyMaySeeKB keeps a KB-restricted API key's listings inside its +// allow-list; organization views would otherwise name every shared KB. +func apiKeyMaySeeKB(ctx context.Context, kbID string) bool { + return types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID) == nil +} + // kbShareOnPath binds share_id to the route's :id. The route's ownership guard // is evaluated against :id, so a share of another KB must not be reachable // through an unrelated (or nonexistent) KB path. @@ -1283,6 +1293,9 @@ func (h *OrganizationHandler) ListOrgShares(c *gin.Context) { response := make([]types.KnowledgeBaseShareResponse, 0, len(shares)) for _, s := range shares { + if !apiKeyMaySeeKB(ctx, s.KnowledgeBaseID) { + continue + } // Effective permission for current user = min(share permission, my role in org) effectivePerm := s.Permission if !myRoleInOrg.HasPermission(s.Permission) { @@ -1356,6 +1369,9 @@ func (h *OrganizationHandler) ListSharedKnowledgeBases(c *gin.Context) { // metadata (share_id, organization_id, etc.) is preserved as-is. rows := make([]map[string]interface{}, 0, len(sharedKBs)) for _, info := range sharedKBs { + if info.KnowledgeBase != nil && !apiKeyMaySeeKB(ctx, info.KnowledgeBase.ID) { + continue + } rows = append(rows, sharedKBRow(info, nil)) } @@ -1733,6 +1749,9 @@ func (h *OrganizationHandler) ListOrganizationSharedKnowledgeBases(c *gin.Contex // ("share endpoints never leak vector-store metadata"). rows := make([]map[string]interface{}, 0, len(list)) for _, item := range list { + if item.KnowledgeBase != nil && !apiKeyMaySeeKB(ctx, item.KnowledgeBase.ID) { + continue + } extras := map[string]interface{}{"is_mine": item.IsMine} if item.SourceFromAgent != nil { extras["source_from_agent"] = item.SourceFromAgent @@ -1995,41 +2014,21 @@ func (h *OrganizationHandler) InviteMember(c *gin.Context) { return } - // Plan 3: resolve the (target tenant, representative user) pair. + // Plan 3: resolve the target tenant — preferably from tenant_id, or (the + // pre-Plan-3 SDK contract) from the tenant of user_id. // - // - Preferred: caller supplies tenant_id directly (and optionally - // representative_user_id) — this matches the tenant-centric mental - // model and lets admins invite any user as the rep. - // - Legacy: caller supplies only user_id — handler looks up that - // user's tenant and uses the same user as the rep, preserving the - // pre-Plan-3 SDK contract. + // A direct add enrols a workspace without anyone in it taking part, so no + // user of that workspace is attached as its representative: the roster + // shows a representative's username (and email to their own workspace) + // to members, and the inviter must not pick whose. representative_user_id + // is accepted for compatibility and ignored. targetTenantID := req.TenantID - representativeUserID := req.RepresentativeUserID switch { case targetTenantID != 0: - // Tenant-id path: validate the tenant exists; pick a sensible - // representative when the caller didn't pin one. if _, err := h.tenantService.GetTenantByID(ctx, targetTenantID); err != nil { c.Error(apperrors.NewNotFoundError("Workspace not found")) return } - if representativeUserID == "" { - // Fall back to the legacy user_id field if it was sent, so - // existing clients that learned to send both keep working. - representativeUserID = req.UserID - } - if representativeUserID != "" { - // If a representative is named, sanity-check it belongs to - // the target tenant. We don't hard-fail when it doesn't — - // the membership row is keyed by tenant_id, the rep field - // is informational — but we strip the inconsistent value - // so the audit log doesn't lie. - if u, err := h.userService.GetUserByID(ctx, representativeUserID); err != nil || u == nil || u.TenantID != targetTenantID { - logger.Warnf(ctx, "representative_user_id %s does not belong to tenant %d; dropping", - secutils.SanitizeForLog(representativeUserID), targetTenantID) - representativeUserID = "" - } - } case req.UserID != "": // Legacy path: resolve target tenant from the user. invitedUser, err := h.userService.GetUserByID(ctx, req.UserID) @@ -2038,9 +2037,6 @@ func (h *OrganizationHandler) InviteMember(c *gin.Context) { return } targetTenantID = invitedUser.TenantID - if representativeUserID == "" { - representativeUserID = req.UserID - } default: c.Error(apperrors.NewValidationError("Either tenant_id or user_id is required")) return @@ -2052,8 +2048,8 @@ func (h *OrganizationHandler) InviteMember(c *gin.Context) { return } - // Add tenant member with the chosen representative. - if err := h.orgService.AddTenantMember(ctx, orgID, targetTenantID, representativeUserID, req.Role); err != nil { + // Add the tenant without a representative (see above). + if err := h.orgService.AddTenantMember(ctx, orgID, targetTenantID, "", req.Role); err != nil { logger.Errorf(ctx, "Failed to add member: %v", err) if errors.Is(err, service.ErrOrgMemberLimitReached) { c.Error(apperrors.NewValidationError("该空间成员已满,无法添加新成员")) @@ -2063,10 +2059,9 @@ func (h *OrganizationHandler) InviteMember(c *gin.Context) { return } - logger.Infof(ctx, "User %s invited tenant %d (rep user %s) to organization %s with role %s", + logger.Infof(ctx, "User %s invited tenant %d to organization %s with role %s", secutils.SanitizeForLog(userID), targetTenantID, - secutils.SanitizeForLog(representativeUserID), orgID, req.Role) diff --git a/internal/handler/organization_invite_test.go b/internal/handler/organization_invite_test.go new file mode 100644 index 00000000..a6861567 --- /dev/null +++ b/internal/handler/organization_invite_test.go @@ -0,0 +1,139 @@ +package handler + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/application/repository" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type inviteRepOrg struct { + interfaces.OrganizationService + members []*types.OrganizationTenantMember + representative *string +} + +func (*inviteRepOrg) IsTenantOrgAdmin(context.Context, string, uint64) (bool, error) { + return true, nil +} + +// GetTenantMember reports a caller that is a member of the org when the +// roster is set, and a not-yet-member invite target otherwise. +func (o *inviteRepOrg) GetTenantMember( + _ context.Context, _ string, tenantID uint64, +) (*types.OrganizationTenantMember, error) { + for _, member := range o.members { + if member.TenantID == tenantID { + return member, nil + } + } + return nil, repository.ErrOrgMemberNotFound +} + +func (o *inviteRepOrg) AddTenantMember(_ context.Context, _ string, _ uint64, rep string, _ types.OrgMemberRole) error { + o.representative = &rep + return nil +} + +func (o *inviteRepOrg) ListTenantMembers(context.Context, string) ([]*types.OrganizationTenantMember, error) { + return o.members, nil +} + +type inviteRepTenants struct{ interfaces.TenantService } + +func (inviteRepTenants) GetTenantByID(_ context.Context, id uint64) (*types.Tenant, error) { + return &types.Tenant{ID: id}, nil +} + +func (inviteRepTenants) GetTenantsByIDs(_ context.Context, ids []uint64) (map[uint64]*types.Tenant, error) { + out := map[uint64]*types.Tenant{} + for _, id := range ids { + out[id] = &types.Tenant{ID: id} + } + return out, nil +} + +type inviteRepUsers struct{ interfaces.UserService } + +func (inviteRepUsers) GetUserByID(_ context.Context, id string) (*types.User, error) { + return &types.User{ID: id, TenantID: 42}, nil +} + +func inviteRepContext(body string) (*gin.Context, *httptest.ResponseRecorder) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Params = gin.Params{{Key: "id", Value: "org"}} + c.Request = httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + c.Set(types.TenantIDContextKey.String(), uint64(7)) + return c, recorder +} + +// A direct add must not let the inviter attach a user of the other workspace +// as its representative: the roster would then show that user to members. +func TestInviteMemberAttachesNoRepresentative(t *testing.T) { + for _, body := range []string{ + `{"tenant_id":42,"representative_user_id":"victim","role":"viewer"}`, + `{"user_id":"victim","role":"viewer"}`, + } { + org := &inviteRepOrg{} + h := &OrganizationHandler{orgService: org, tenantService: inviteRepTenants{}, userService: inviteRepUsers{}} + c, _ := inviteRepContext(body) + h.InviteMember(c) + require.Empty(t, c.Errors, body) + require.NotNil(t, org.representative, body) + require.Empty(t, *org.representative, body) + } +} + +// Other workspaces' users' emails are not part of the roster. +func TestListMembersShowsEmailOnlyForOwnWorkspace(t *testing.T) { + org := &inviteRepOrg{members: []*types.OrganizationTenantMember{ + {ID: "m-own", TenantID: 7, RepresentativeUser: &types.User{Username: "me", Email: "me@own.example"}}, + {ID: "m-other", TenantID: 42, RepresentativeUser: &types.User{Username: "them", Email: "them@other.example"}}, + }} + h := &OrganizationHandler{orgService: org, tenantService: inviteRepTenants{}} + c, recorder := inviteRepContext("") + h.ListMembers(c) + require.Empty(t, c.Errors) + require.Contains(t, recorder.Body.String(), "me@own.example") + require.NotContains(t, recorder.Body.String(), "them@other.example") + require.Contains(t, recorder.Body.String(), `"username":"them"`) +} + +type scopedListKBShares struct{ interfaces.KBShareService } + +func (scopedListKBShares) ListSharedKnowledgeBases( + context.Context, uint64, types.TenantRole, +) ([]*types.SharedKnowledgeBaseInfo, error) { + return []*types.SharedKnowledgeBaseInfo{ + {KnowledgeBase: &types.KnowledgeBase{ID: "kb-allowed", Name: "Allowed KB"}}, + {KnowledgeBase: &types.KnowledgeBase{ID: "kb-other", Name: "Other KB"}}, + }, nil +} + +// A KB-restricted API key must not learn about shared KBs outside its +// allow-list from the organization listings. +func TestSharedKnowledgeBaseListRespectsAPIKeyScope(t *testing.T) { + h := &OrganizationHandler{shareService: scopedListKBShares{}} + c, recorder := inviteRepContext("") + ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(7)) + ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{ + KnowledgeBaseIDs: types.StringArray{"kb-allowed"}, + Capabilities: types.StringArray{string(types.APIKeyCapabilityManageSpaces)}, + }) + c.Request = c.Request.WithContext(ctx) + + h.ListSharedKnowledgeBases(c) + require.Empty(t, c.Errors) + require.Contains(t, recorder.Body.String(), "Allowed KB") + require.NotContains(t, recorder.Body.String(), "Other KB") +} diff --git a/internal/handler/session/temporary_document.go b/internal/handler/session/temporary_document.go index 32918417..11d86dfe 100644 --- a/internal/handler/session/temporary_document.go +++ b/internal/handler/session/temporary_document.go @@ -53,6 +53,12 @@ func (h *Handler) UploadTemporaryDocument(c *gin.Context) { options := types.TemporaryDocumentCreateOptions{ParserEngine: strings.TrimSpace(c.PostForm("parser_engine"))} if agent != nil { options.ResourceTenantID = resourceTenantID + // A shared agent parses in its owner's workspace, with the parser + // engines (and credentials) configured there: only the agent's own + // rules may pick one, not the caller. + if resourceTenantID != 0 && resourceTenantID != c.GetUint64(types.TenantIDContextKey.String()) { + options.ParserEngine = "" + } if len(agent.Config.SupportedFileTypes) > 0 && !containsFileType(agent.Config.SupportedFileTypes, ext) { c.Error(apperrors.NewBadRequestError("file type is not supported by this agent")) return diff --git a/internal/handler/session/temporary_document_engine_test.go b/internal/handler/session/temporary_document_engine_test.go new file mode 100644 index 00000000..32415903 --- /dev/null +++ b/internal/handler/session/temporary_document_engine_test.go @@ -0,0 +1,75 @@ +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") +} diff --git a/internal/handler/wiki_page.go b/internal/handler/wiki_page.go index 29106a4d..fb44a997 100644 --- a/internal/handler/wiki_page.go +++ b/internal/handler/wiki_page.go @@ -946,7 +946,7 @@ func (h *WikiPageHandler) ListIssues(c *gin.Context) { // @Security Bearer // @Router /knowledgebase/{kb_id}/wiki/issues/{issue_id}/status [put] func (h *WikiPageHandler) UpdateIssueStatus(c *gin.Context) { - _, _, err := h.validateWikiKB(c) + kbID, _, err := h.validateWikiKB(c) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return @@ -972,7 +972,11 @@ func (h *WikiPageHandler) UpdateIssueStatus(c *gin.Context) { return } - if err := h.wikiService.UpdateIssueStatus(c.Request.Context(), issueID, req.Status); err != nil { + if err := h.wikiService.UpdateIssueStatus(c.Request.Context(), kbID, issueID, req.Status); err != nil { + if stderrors.Is(err, repository.ErrWikiIssueNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "Issue not found"}) + return + } c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } diff --git a/internal/im/channel_kb_scope_test.go b/internal/im/channel_kb_scope_test.go new file mode 100644 index 00000000..c9e88a78 --- /dev/null +++ b/internal/im/channel_kb_scope_test.go @@ -0,0 +1,48 @@ +package im + +import ( + "context" + "errors" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/stretchr/testify/require" +) + +type channelKBLookup struct { + interfaces.KnowledgeBaseService +} + +func (channelKBLookup) GetKnowledgeBaseByIDOnly(_ context.Context, id string) (*types.KnowledgeBase, error) { + switch id { + case "own-kb": + return &types.KnowledgeBase{ID: id, TenantID: 7}, nil + case "foreign-kb": + return &types.KnowledgeBase{ID: id, TenantID: 84}, nil + } + return nil, errors.New("not found") +} + +// IM files are saved into the channel's KB as the channel's workspace, so the +// KB must belong to that workspace (and to a restricted key's allow-list). +func TestSetChannelKnowledgeBaseIDRequiresOwnKB(t *testing.T) { + svc := &Service{kbService: channelKBLookup{}} + channel := &IMChannel{TenantID: 7, KnowledgeBaseID: "own-kb"} + + for _, id := range []string{"foreign-kb", "missing-kb"} { + require.Error(t, svc.SetChannelKnowledgeBaseID(context.Background(), channel, id), id) + require.Equal(t, "own-kb", channel.KnowledgeBaseID, "a rejected ID leaves the binding unchanged") + } + + restricted := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ + KnowledgeBaseIDs: types.StringArray{"other-kb"}, + Capabilities: types.StringArray{string(types.APIKeyCapabilityManageChannels)}, + }) + require.Error(t, svc.SetChannelKnowledgeBaseID(restricted, channel, "own-kb")) + + require.NoError(t, svc.SetChannelKnowledgeBaseID(context.Background(), channel, "")) + require.Empty(t, channel.KnowledgeBaseID) + require.NoError(t, svc.SetChannelKnowledgeBaseID(context.Background(), channel, "own-kb")) + require.Equal(t, "own-kb", channel.KnowledgeBaseID) +} diff --git a/internal/im/service.go b/internal/im/service.go index 777696f8..8050f015 100644 --- a/internal/im/service.go +++ b/internal/im/service.go @@ -3250,6 +3250,30 @@ func (s *Service) SetChannelAgentID(ctx context.Context, channel *IMChannel, age return nil } +// SetChannelKnowledgeBaseID binds the KB that IM files are saved into. It must +// belong to the channel's workspace, which writes into it, and to a KB-restricted +// API key's allow-list; a foreign ID would create records in (and read the +// configuration of) another workspace's KB. An empty ID clears the binding. +func (s *Service) SetChannelKnowledgeBaseID(ctx context.Context, channel *IMChannel, kbID string) error { + kbID = strings.TrimSpace(kbID) + if kbID == "" { + channel.KnowledgeBaseID = "" + return nil + } + if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID); err != nil { + return fmt.Errorf("knowledge base not found") + } + if s.kbService == nil { + return fmt.Errorf("knowledge base not found") + } + kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, kbID) + if err != nil || kb == nil || kb.TenantID != channel.TenantID { + return fmt.Errorf("knowledge base not found") + } + channel.KnowledgeBaseID = kbID + return nil +} + // UpdateChannel updates a channel and restarts it if needed. // Returns a duplicate_bot error if the bot identity is already used by another channel. func (s *Service) UpdateChannel(channel *IMChannel) error { diff --git a/internal/middleware/kb_access.go b/internal/middleware/kb_access.go index 456d5531..102e45a2 100644 --- a/internal/middleware/kb_access.go +++ b/internal/middleware/kb_access.go @@ -175,11 +175,12 @@ func isResourceNotFound(err error) bool { // - OrgRoleAdmin -> share-management routes (only the original // sharer / KB owner / Org admin should pass) // -// When cfg.Tenant.EnableRBAC is false the guard mirrors the sibling -// role/ownership guards: it logs the would-be rejection and lets the -// request through. The point is to keep the rollout window safe — the -// guard runs full enforcement once the flag flips on, with no code -// changes elsewhere. +// The EnableRBAC rollout switch does not apply here. It relaxes the role +// checks inside a workspace, while ResolveKB always grants a KB's own +// workspace, so a denial from it means another workspace's KB without a +// share. Handlers behind this guard load KBs, chunks and wiki pages by ID +// without a tenant filter, so letting a denial through would lift +// workspace isolation for the whole rollout window. func RequireKBAccess( resolveKBID KBIDResolver, requiredPermission types.OrgMemberRole, @@ -204,38 +205,17 @@ func RequireKBAccess( return } - // Rollout window: enforcement off -> log the would-be check and - // pass through. We still resolve the KB (best-effort) so the - // effective-tenant context rewrite still happens for shared - // KBs; that way embedding queries hit the right tenant - // regardless of whether RBAC enforcement is active. - enforcing := rbacEnforcementEnabled(cfg) - grant, err := resolveKBAccess(ctx, c, kbID, requiredPermission, kbService, kbShareService, agentShareService) switch { case stderrors.Is(err, access.ErrUnauthorized): - if !enforcing { - logger.Warnf(ctx, "[rbac] kb-access would 401 (enforcement off): kb=%s", kbID) - c.Next() - return - } _ = c.Error(apperrors.NewUnauthorizedError("Unauthorized")) c.Abort() return case stderrors.Is(err, access.ErrNotFound): - // 404 still fires when enforcement is off — a missing KB is - // not an authorisation event, the client genuinely asked - // for nothing. _ = c.Error(apperrors.NewNotFoundError("knowledge base not found")) c.Abort() return case stderrors.Is(err, access.ErrForbidden): - if !enforcing { - logger.Warnf(ctx, "[rbac] kb-access would 403 (enforcement off): kb=%s required=%s", - kbID, requiredPermission) - c.Next() - return - } _ = c.Error(apperrors.NewForbiddenError("Permission denied to access this knowledge base")) c.Abort() return diff --git a/internal/middleware/kb_access_test.go b/internal/middleware/kb_access_test.go index 57e72203..585b5e2f 100644 --- a/internal/middleware/kb_access_test.go +++ b/internal/middleware/kb_access_test.go @@ -184,8 +184,8 @@ type guardOpts struct { // runGuard fires a single request through the guard and returns the // gin recorder + the kb access (if any) the guard stashed. Defaults -// to EnableRBAC=true; the EnableRBAC=false fail-open path has its own -// dedicated tests further below. +// to EnableRBAC=true; the guard ignores the flag, which the EnableRBAC=false +// tests further below pin down. func runGuard( t *testing.T, tenantID uint64, @@ -504,9 +504,10 @@ func TestRequireKBAccess_AgentShare_SpecificAgent_TenantMismatch(t *testing.T) { // ---------- EnableRBAC=false rollout window ---------- -func TestRequireKBAccess_Forbidden_FailOpenWhenRBACDisabled(t *testing.T) { - // Same scenario as PermissionBelowMin (which aborts when enforcing), - // but with EnableRBAC=false the guard logs and passes through. +func TestRequireKBAccess_Forbidden_EnforcedEvenWhenRBACDisabled(t *testing.T) { + // Same scenario as PermissionBelowMin. The EnableRBAC=false rollout + // window relaxes roles inside a workspace; it must not open another + // workspace's KB, since handlers behind this guard load by ID. gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -529,7 +530,7 @@ func TestRequireKBAccess_Forbidden_FailOpenWhenRBACDisabled(t *testing.T) { cfgRBAC(false), // enforcement off ) guard(c) - require.False(t, c.IsAborted(), "guard must pass through when EnableRBAC is off") + require.True(t, c.IsAborted(), "cross-workspace access stays denied when EnableRBAC is off") _ = rec } diff --git a/internal/router/routes_agent.go b/internal/router/routes_agent.go index 991d7808..88321346 100644 --- a/internal/router/routes_agent.go +++ b/internal/router/routes_agent.go @@ -115,14 +115,14 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza orgs.POST("/join-by-id", g.Admin(), orgHandler.JoinByOrganizationID) // Get organization by ID — Viewer+ orgs.GET("/:id", g.Viewer(), orgHandler.GetOrganization) - // Update organization — Admin+ in caller's tenant. - // Service still gates on "caller's tenant is the org owner"; - // the route guard adds a defence-in-depth layer that stops a - // tenant Viewer/Contributor from ever reaching the service. + // Update organization — Admin+ in caller's tenant. The service + // requires the caller's tenant to be an org admin (not only the + // owner), matching the settings UI; the route guard stops a tenant + // Viewer/Contributor from ever reaching the service. orgs.PUT("/:id", g.Admin(), orgHandler.UpdateOrganization) - // Delete organization — Admin+ in caller's tenant. Same - // rationale as PUT above; deletion is irreversible so the - // route-layer floor is at least as strict. + // Delete organization — Admin+ in caller's tenant; the service + // further requires the org's owner tenant, since deletion is + // irreversible. orgs.DELETE("/:id", g.Admin(), orgHandler.DeleteOrganization) // Leave organization (Admin+ in caller's tenant only) orgs.POST("/:id/leave", g.Admin(), orgHandler.LeaveOrganization) diff --git a/internal/types/interfaces/organization.go b/internal/types/interfaces/organization.go index 8fa5cbc1..65b5cc57 100644 --- a/internal/types/interfaces/organization.go +++ b/internal/types/interfaces/organization.go @@ -67,7 +67,9 @@ type OrganizationRepository interface { Delete(ctx context.Context, id string) error // Tenant member operations - AddTenantMember(ctx context.Context, member *types.OrganizationTenantMember) error + // AddTenantMember inserts the membership; a positive memberLimit is enforced + // atomically with the insert. + AddTenantMember(ctx context.Context, member *types.OrganizationTenantMember, memberLimit int) error RemoveTenantMember(ctx context.Context, orgID string, tenantID uint64) error UpdateTenantMemberRole(ctx context.Context, orgID string, tenantID uint64, role types.OrgMemberRole) error ListTenantMembers(ctx context.Context, orgID string) ([]*types.OrganizationTenantMember, error) diff --git a/internal/types/interfaces/wiki_page.go b/internal/types/interfaces/wiki_page.go index b8aaa412..7db96261 100644 --- a/internal/types/interfaces/wiki_page.go +++ b/internal/types/interfaces/wiki_page.go @@ -237,8 +237,8 @@ type WikiPageService interface { // ListIssues retrieves issues for a knowledge base, optionally filtered by slug and status. ListIssues(ctx context.Context, kbID string, slug string, status string) ([]*types.WikiPageIssue, error) - // UpdateIssueStatus updates the status of an issue (e.g. pending -> resolved/ignored). - UpdateIssueStatus(ctx context.Context, issueID string, status string) error + // UpdateIssueStatus updates the status of an issue of kbID (e.g. pending -> resolved/ignored). + UpdateIssueStatus(ctx context.Context, kbID string, issueID string, status string) error } // WikiPageRepository defines the wiki page data persistence interface. @@ -449,6 +449,7 @@ type WikiPageRepository interface { // ListIssues retrieves issues with optional filtering by slug and status. ListIssues(ctx context.Context, kbID string, slug string, status string) ([]*types.WikiPageIssue, error) - // UpdateIssueStatus updates an issue's status. - UpdateIssueStatus(ctx context.Context, issueID string, status string) error + // UpdateIssueStatus updates the status of an issue of kbID; ErrWikiIssueNotFound + // when no such issue belongs to it. + UpdateIssueStatus(ctx context.Context, kbID string, issueID string, status string) error } diff --git a/internal/types/organization.go b/internal/types/organization.go index a43035d8..6de430ee 100644 --- a/internal/types/organization.go +++ b/internal/types/organization.go @@ -370,21 +370,18 @@ type RequestRoleUpgradeRequest struct { // InviteMemberRequest represents a request to directly invite a workspace to an organization. // // Plan 3 (#1303) moved membership to the workspace level: an invitation enrols a whole -// workspace into the organization, with one user attached purely as the representative -// (display/audit). Callers SHOULD set TenantID and optionally -// RepresentativeUserID. For backward compatibility with older SDK callers that -// still send UserID alone, the handler resolves that user's TenantID and uses -// the user as the representative. +// workspace into the organization. Callers SHOULD set TenantID. For backward +// compatibility with older SDK callers that still send UserID alone, the +// handler resolves that user's TenantID. No representative user is attached. type InviteMemberRequest struct { // TenantID is the workspace to enrol as an org member. Preferred field. TenantID uint64 `json:"tenant_id"` - // RepresentativeUserID identifies the user attached to the OTM row for - // display/audit. Optional: when unset, the handler picks a stable default - // (the user from the legacy UserID field, or the workspace's owner). + // RepresentativeUserID is accepted for compatibility and ignored: a + // direct add attaches no user of the enrolled workspace, since the + // inviter must not choose whose details the roster shows. RepresentativeUserID string `json:"representative_user_id"` // UserID is retained for backward compatibility. When set without - // TenantID, the handler resolves the user's TenantID and uses this - // user as the representative. + // TenantID, the handler resolves the user's TenantID. UserID string `json:"user_id"` Role OrgMemberRole `json:"role" binding:"required"` // Role to assign: admin/editor/viewer } diff --git a/website-docs/01-getting-started/04-configuration.md b/website-docs/01-getting-started/04-configuration.md index 711e655d..2ed2a569 100644 --- a/website-docs/01-getting-started/04-configuration.md +++ b/website-docs/01-getting-started/04-configuration.md @@ -108,7 +108,7 @@ flowchart LR | 名称 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | `enable_cross_tenant_access` | bool | false | 允许具备 `CanAccessAllTenants` 的用户跨空间访问(内网可开) | -| `enable_rbac` | *bool | true | 空间角色强制鉴权;显式 `false` 进入仅记录不拦截的灰度模式(env `WEKNORA_TENANT_ENABLE_RBAC`) | +| `enable_rbac` | *bool | true | 空间角色强制鉴权;显式 `false` 进入灰度模式,空间内的角色检查仅记录不拦截,跨空间访问仍然拦截(env `WEKNORA_TENANT_ENABLE_RBAC`) | | `max_owned_per_user` | int | 0(走 handler 默认) | 单个非超管可自建空间数上限;<0 关闭限制(env `WEKNORA_TENANT_MAX_OWNED_PER_USER`) | | `self_service_creation_enabled` | *bool | true | 普通用户能否自建空间(env `WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED`) | | `default_session_name` / `default_session_title` / `default_session_description` | string | 空 | 新会话默认文案 | diff --git a/website-docs/03-features/01-tenant-auth.md b/website-docs/03-features/01-tenant-auth.md index 7c47d6d7..cf3200ed 100644 --- a/website-docs/03-features/01-tenant-auth.md +++ b/website-docs/03-features/01-tenant-auth.md @@ -321,7 +321,7 @@ flowchart LR 5. ownership 守卫执行 creator 查询:资源不存在 → 放行让 handler 返回 404;查询失败 → 503;creator == 当前用户 → 放行; 6. 否则 403 + 审计日志(`AuditActionAccessDenied = "rbac.access_denied"`)。 -强制执行开关 `TenantConfig.EnableRBAC`:`nil` 或 `true` = 强制(当前默认),`false` = 只记日志不拒绝(发布过渡用);可用环境变量 `WEKNORA_TENANT_ENABLE_RBAC` 覆盖。 +强制执行开关 `TenantConfig.EnableRBAC`:`nil` 或 `true` = 强制(当前默认),`false` = 只记日志不拒绝(发布过渡用);可用环境变量 `WEKNORA_TENANT_ENABLE_RBAC` 覆盖。该开关只作用于空间内的角色检查,知识库访问守卫(`RequireKBAccess`)对跨空间访问始终拦截。 `RequireSystemAdmin`:JWT 用户须 `IsSystemAdmin=true`;API Key 须为 platform key(tenant key 一律 403)。 diff --git a/website-docs/03-features/07-agent.md b/website-docs/03-features/07-agent.md index 6c7732d8..1ca8d760 100644 --- a/website-docs/03-features/07-agent.md +++ b/website-docs/03-features/07-agent.md @@ -40,7 +40,8 @@ - 始终使用智能体配置的模型,请求里的 `summary_model_id` 会被忽略; - 未设置 MCP 选择模式的智能体不使用 MCP 服务; -- 对话记录写入接收方自己空间的对话记录知识库,不会写入来源空间。 +- 对话记录写入接收方自己空间的对话记录知识库,不会写入来源空间; +- 接收方能看到智能体的能力与资源范围(模型、知识库、MCP、联网搜索),看不到提示词和创建人。 启用了技能的智能体共享后,技能在来源空间的沙箱中运行,并带上管理员为技能配置的环境变量,成员可以让智能体读出这些值。共享规则见[空间与权限](01-tenant-auth.md)。 diff --git a/website-docs/03-features/12-im-integration.md b/website-docs/03-features/12-im-integration.md index df426bfe..94c9c2da 100644 --- a/website-docs/03-features/12-im-integration.md +++ b/website-docs/03-features/12-im-integration.md @@ -55,7 +55,7 @@ IM 集成将智能体接入企业微信、飞书、钉钉、Slack、Telegram 等 文件和图片会作为 QA 附件处理:文档内容会提供给模型,图片会在模型支持时直接识别。因此,即使渠道未配置文件知识库,机器人也会基于附件内容正常回复。 -`knowledge_base_id` 只决定是否将附件额外保存到知识库。配置后,保存任务在后台执行,不影响当前 QA 回复,也不会额外发送“已入库”或“解析完成”消息。解析文本最多保留前 500 行且不超过 32 KiB,触及任一限制时模型会得到通用截断提示。附件无法读取、平台不支持下载或文件超过 32 MiB 时,机器人会提示用户改用文字描述或重新发送。 +`knowledge_base_id` 只决定是否将附件额外保存到知识库,必须是渠道所在空间的知识库(受限 API key 还要求在其知识库白名单内),否则创建或更新渠道时返回 400。配置后,保存任务在后台执行,不影响当前 QA 回复,也不会额外发送“已入库”或“解析完成”消息。解析文本最多保留前 500 行且不超过 32 KiB,触及任一限制时模型会得到通用截断提示。附件无法读取、平台不支持下载或文件超过 32 MiB 时,机器人会提示用户改用文字描述或重新发送。 ## 回复中的图片外链(resource:// 改写) diff --git a/website-docs/03-features/13-embed-channel.md b/website-docs/03-features/13-embed-channel.md index f7af022e..efe4dd53 100644 --- a/website-docs/03-features/13-embed-channel.md +++ b/website-docs/03-features/13-embed-channel.md @@ -1,6 +1,6 @@ # 网页嵌入(Embed Channel) -嵌入渠道用于在官网或帮助中心提供知识库问答挂件。创建渠道并绑定智能体后,将生成的脚本加入网页,访客无需 WeKnora 账号即可对话。 +嵌入渠道用于在官网或帮助中心提供知识库问答挂件。创建渠道并绑定智能体后,将生成的脚本加入网页,访客无需 WeKnora 账号即可对话。访客的检索范围和模型完全由渠道绑定的智能体决定:服务端会丢弃请求里的知识库、文档、标签、@提及、技能和模型覆盖。 在「设置 → 网页嵌入」新建渠道,绑定智能体并设置允许嵌入的域名,然后复制接入代码。公开使用前应配置域名白名单和限流,限制访问来源与请求量。 diff --git a/website-docs/03-features/21-file-access.md b/website-docs/03-features/21-file-access.md index c6d43d9d..ea45827c 100644 --- a/website-docs/03-features/21-file-access.md +++ b/website-docs/03-features/21-file-access.md @@ -15,7 +15,7 @@ | **能力短链** | `/r/` | 任何拿到链接的人(**匿名可读**) | WeKnora 签发的 grant,2 小时 | | **存储预签名** | 存储后端直接给的 http(s) 链接 | 任何拿到链接的人(**匿名可读**) | 由存储决定,MinIO 默认 24 小时 | -能力短链和存储预签名链接在有效期内允许持有者匿名读取文件。分享或记录这些链接时,应按文件本身的访问范围处理。 +能力短链和存储预签名链接在有效期内允许持有者匿名读取文件。分享或记录这些链接时,应按文件本身的访问范围处理。撤销组织共享或退出组织不会让已经签发的链接提前失效,它们会一直可用到过期(短链 2 小时,存储预签名最长 24 小时)。 ::: tip 默认访问方式 系统默认返回内部引用,由带凭证的客户端通过鉴权代理读取。外链需要公网可达的存储端点,或配置 `APP_EXTERNAL_URL` 后由 WeKnora 签发访问链接。默认 MinIO 地址 `minio:9000` 仅在容器网络内可达。 diff --git a/website-docs/04-api/02-api-chat.md b/website-docs/04-api/02-api-chat.md index b6202d2c..16c539ac 100644 --- a/website-docs/04-api/02-api-chat.md +++ b/website-docs/04-api/02-api-chat.md @@ -152,7 +152,7 @@ Handler: `internal/handler/session/temporary_document.go` ### POST /api/v1/sessions/:session_id/attachments -用途:上传会话级临时文档(异步解析)。multipart 字段:`file`(必填)、`agent_id`(可选,决定解析引擎/ASR 模型)、`parser_engine`(可选)。 +用途:上传会话级临时文档(异步解析)。multipart 字段:`file`(必填)、`agent_id`(可选,决定解析引擎/ASR 模型)、`parser_engine`(可选;使用共享智能体时忽略,由智能体的解析规则决定)。 响应:202 `{"success":true,"data":{TemporaryDocument}}`(`id,session_id,file_name,file_type,file_size,status(uploaded/processing/ready/failed),resource_ref,...`) diff --git a/website-docs/04-api/02-api-faq-wiki.md b/website-docs/04-api/02-api-faq-wiki.md index 43f7afc5..d7d3c321 100644 --- a/website-docs/04-api/02-api-faq-wiki.md +++ b/website-docs/04-api/02-api-faq-wiki.md @@ -447,7 +447,7 @@ curl $BASE/api/v1/knowledgebase/kb-1/wiki/issues -H "Authorization: Bearer $TOKE ### PUT /api/v1/knowledgebase/:kb_id/wiki/issues/:issue_id/status -用途:更新问题状态。写权限。请求体:`{"status":"pending|ignored|resolved"}`(`binding:"required"`)。 +用途:更新问题状态。写权限。请求体:`{"status":"pending|ignored|resolved"}`(`binding:"required"`)。`issue_id` 必须属于路径中的知识库,否则 404。 响应:200 `{"message":"Issue status updated successfully"}` diff --git a/website-docs/04-api/02-api-org.md b/website-docs/04-api/02-api-org.md index 7228f1c4..9f85e7a3 100644 --- a/website-docs/04-api/02-api-org.md +++ b/website-docs/04-api/02-api-org.md @@ -119,7 +119,7 @@ curl $BASE/api/v1/organizations/org-1 -H "Authorization: Bearer $TOKEN" ### PUT /api/v1/organizations/:id -用途:更新组织(服务层校验调用者空间为组织 owner)。权限:Admin+。请求体字段同创建(均可选)。 +用途:更新组织(服务层校验调用者空间是组织 admin,不限于 owner)。权限:Admin+。请求体字段同创建(均可选)。 响应:200 `{"success":true,"data":{OrganizationResponse}}` @@ -205,7 +205,7 @@ curl "$BASE/api/v1/organizations/org-1/search-users?q=demo" -H "Authorization: B | --- | --- | --- | --- | | `tenant_id` | uint64 | 二选一 | 目标空间 ID(推荐) | | `user_id` | string | 二选一 | 兼容路径:用户 ID(解析为其空间) | -| `representative_user_id` | string | 否 | 该空间的代表用户 | +| `representative_user_id` | string | 否 | 已忽略,仅为兼容保留:直接添加的空间不挂代表用户,避免邀请方指定对方空间里哪位用户的信息出现在成员列表中 | | `role` | string | 是 | 组织内角色 | 响应:200 `{"success":true,"message":"Member added successfully"}` @@ -217,7 +217,7 @@ curl -X POST $BASE/api/v1/organizations/org-1/invite -H "Authorization: Bearer $ ### GET /api/v1/organizations/:id/members -用途:组织成员(空间)列表。权限:Viewer+。 +用途:组织成员(空间)列表。权限:Viewer+。`email` 只对调用方自己空间那一行返回,其他空间只返回用户名和头像。 响应:200 `{"success":true,"data":{"members":[{id,user_id,representative_user_id,role,tenant_id,tenant_name,username,email,avatar,joined_at}],"total":N}}`