diff --git a/frontend/src/api/organization/index.ts b/frontend/src/api/organization/index.ts index 3ffabc5a..43ddbc10 100644 --- a/frontend/src/api/organization/index.ts +++ b/frontend/src/api/organization/index.ts @@ -470,11 +470,11 @@ export async function listMembers(orgId: string): Promise> { +export async function updateMemberRole(orgId: string, tenantId: number, req: UpdateMemberRoleRequest): Promise> { try { - const response = await put(`/api/v1/organizations/${orgId}/members/${userId}`, req) + const response = await put(`/api/v1/organizations/${orgId}/members/${tenantId}`, req) return response as unknown as ApiResponse } catch (error: any) { return { success: false, message: error.message || 'Failed to update member role' } @@ -482,11 +482,11 @@ export async function updateMemberRole(orgId: string, userId: string, req: Updat } /** - * Remove member + * Remove member (member is identified by tenant_id) */ -export async function removeMember(orgId: string, userId: string): Promise> { +export async function removeMember(orgId: string, tenantId: number): Promise> { try { - const response = await del(`/api/v1/organizations/${orgId}/members/${userId}`) + const response = await del(`/api/v1/organizations/${orgId}/members/${tenantId}`) return response as unknown as ApiResponse } catch (error: any) { return { success: false, message: error.message || 'Failed to remove member' } diff --git a/frontend/src/stores/organization.ts b/frontend/src/stores/organization.ts index acd18082..d53b896e 100644 --- a/frontend/src/stores/organization.ts +++ b/frontend/src/stores/organization.ts @@ -294,15 +294,15 @@ export const useOrganizationStore = defineStore('organization', () => { } /** - * Update a member's role + * Update a member's role (member identified by tenant_id) */ - async function changeMemberRole(orgId: string, userId: string, role: 'admin' | 'editor' | 'viewer') { + async function changeMemberRole(orgId: string, tenantId: number, role: 'admin' | 'editor' | 'viewer') { loading.value = true error.value = null try { - const response = await updateMemberRole(orgId, userId, { role }) + const response = await updateMemberRole(orgId, tenantId, { role }) if (response.success) { - const member = currentMembers.value.find(m => m.user_id === userId) + const member = currentMembers.value.find(m => m.tenant_id === tenantId) if (member) { member.role = role } @@ -320,15 +320,15 @@ export const useOrganizationStore = defineStore('organization', () => { } /** - * Remove a member from organization + * Remove a member from organization (member identified by tenant_id) */ - async function kickMember(orgId: string, userId: string) { + async function kickMember(orgId: string, tenantId: number) { loading.value = true error.value = null try { - const response = await removeMember(orgId, userId) + const response = await removeMember(orgId, tenantId) if (response.success) { - currentMembers.value = currentMembers.value.filter(m => m.user_id !== userId) + currentMembers.value = currentMembers.value.filter(m => m.tenant_id !== tenantId) return true } else { error.value = response.message || 'Failed to remove member' diff --git a/frontend/src/views/organization/OrganizationSettingsModal.vue b/frontend/src/views/organization/OrganizationSettingsModal.vue index a09c1d24..80bf2883 100644 --- a/frontend/src/views/organization/OrganizationSettingsModal.vue +++ b/frontend/src/views/organization/OrganizationSettingsModal.vue @@ -1172,8 +1172,8 @@ const handleSave = async () => { const handleRoleChange = async (member: OrganizationMember, newRole: string) => { if (!props.orgId) return try { - const res = await updateMemberRole(props.orgId, member.user_id, { - role: newRole as 'admin' | 'editor' | 'viewer' + const res = await updateMemberRole(props.orgId, member.tenant_id, { + role: newRole as 'admin' | 'editor' | 'viewer' }) if (res.success) { MessagePlugin.success(t('organization.roleUpdated')) @@ -1196,7 +1196,7 @@ const confirmRemoveMember = async () => { if (!removingMember.value || !props.orgId) return try { - const res = await removeMember(props.orgId, removingMember.value.user_id) + const res = await removeMember(props.orgId, removingMember.value.tenant_id) if (res.success) { MessagePlugin.success(t('organization.memberRemoved')) showRemoveDialog.value = false diff --git a/internal/application/repository/agent_share.go b/internal/application/repository/agent_share.go index c4811943..b9fd2189 100644 --- a/internal/application/repository/agent_share.go +++ b/internal/application/repository/agent_share.go @@ -166,16 +166,18 @@ func (r *agentShareRepository) CountByOrganizations(ctx context.Context, orgIDs return out, nil } -// ListSharedAgentsForUser lists all agents shared to organizations that the user belongs to -func (r *agentShareRepository) ListSharedAgentsForUser(ctx context.Context, userID string) ([]*types.AgentShare, error) { +// ListSharedAgentsForTenant lists all agents shared to organizations that the +// caller's tenant participates in. Plan 3 of #1303 keys this on tenant rather +// than user. +func (r *agentShareRepository) ListSharedAgentsForTenant(ctx context.Context, tenantID uint64) ([]*types.AgentShare, error) { var shares []*types.AgentShare err := r.db.WithContext(ctx). Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL"). Preload("Agent"). Preload("Organization"). - Joins("JOIN organization_members ON organization_members.organization_id = agent_shares.organization_id"). + Joins("JOIN organization_tenant_members otm ON otm.organization_id = agent_shares.organization_id"). Joins("JOIN organizations ON organizations.id = agent_shares.organization_id AND organizations.deleted_at IS NULL"). - Where("organization_members.user_id = ?", userID). + Where("otm.tenant_id = ?", tenantID). Where("agent_shares.deleted_at IS NULL"). Order("agent_shares.created_at DESC"). Find(&shares).Error @@ -185,13 +187,15 @@ func (r *agentShareRepository) ListSharedAgentsForUser(ctx context.Context, user return shares, nil } -// GetShareByAgentIDForUser returns one share for the given agentID that the user can access (user in org), excluding source_tenant_id == excludeTenantID. Single query. -func (r *agentShareRepository) GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error) { +// GetShareByAgentIDForTenant returns one share for the given agentID that the +// tenant can reach (tenant participates in some org with the share), excluding +// source_tenant_id == excludeTenantID. Single query. +func (r *agentShareRepository) GetShareByAgentIDForTenant(ctx context.Context, tenantID uint64, agentID string, excludeTenantID uint64) (*types.AgentShare, error) { var share types.AgentShare err := r.db.WithContext(ctx). - Joins("JOIN organization_members ON organization_members.organization_id = agent_shares.organization_id"). + Joins("JOIN organization_tenant_members otm ON otm.organization_id = agent_shares.organization_id"). Where("agent_shares.agent_id = ?", agentID). - Where("organization_members.user_id = ?", userID). + Where("otm.tenant_id = ?", tenantID). Where("agent_shares.source_tenant_id != ?", excludeTenantID). Where("agent_shares.deleted_at IS NULL"). First(&share).Error diff --git a/internal/application/repository/kbshare.go b/internal/application/repository/kbshare.go index 6c86879e..59183528 100644 --- a/internal/application/repository/kbshare.go +++ b/internal/application/repository/kbshare.go @@ -145,19 +145,19 @@ func (r *kbShareRepository) ListByOrganizations(ctx context.Context, orgIDs []st return shares, nil } -// ListSharedKBsForUser lists all knowledge bases shared to organizations that the user belongs to. +// ListSharedKBsForTenant lists all knowledge bases shared to organizations that the tenant participates in. // Excludes shares for soft-deleted organizations and soft-deleted knowledge bases. -func (r *kbShareRepository) ListSharedKBsForUser(ctx context.Context, userID string) ([]*types.KnowledgeBaseShare, error) { +func (r *kbShareRepository) ListSharedKBsForTenant(ctx context.Context, tenantID uint64) ([]*types.KnowledgeBaseShare, error) { var shares []*types.KnowledgeBaseShare - // Get shares for organizations that the user is a member of; exclude deleted orgs and deleted KBs + // Get shares for organizations the tenant is a member of; exclude deleted orgs and deleted KBs. err := r.db.WithContext(ctx). Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL"). Preload("KnowledgeBase"). Preload("Organization"). - Joins("JOIN organization_members ON organization_members.organization_id = kb_shares.organization_id"). + Joins("JOIN organization_tenant_members otm ON otm.organization_id = kb_shares.organization_id"). Joins("JOIN organizations ON organizations.id = kb_shares.organization_id AND organizations.deleted_at IS NULL"). - Where("organization_members.user_id = ?", userID). + Where("otm.tenant_id = ?", tenantID). Where("kb_shares.deleted_at IS NULL"). Order("kb_shares.created_at DESC"). Find(&shares).Error diff --git a/internal/application/repository/organization.go b/internal/application/repository/organization.go index e73e2b01..8aea0676 100644 --- a/internal/application/repository/organization.go +++ b/internal/application/repository/organization.go @@ -18,7 +18,12 @@ var ( ErrInviteCodeExpired = errors.New("invite code has expired") ) -// organizationRepository implements OrganizationRepository interface +// organizationRepository implements OrganizationRepository. +// +// Plan 3 of #1303 lifts membership from per-user to per-tenant (see +// migration 000045). All "member" methods on this repo now operate on +// the (org, tenant) tuple; the underlying table is +// organization_tenant_members. type organizationRepository struct { db *gorm.DB } @@ -60,14 +65,13 @@ func (r *organizationRepository) GetByInviteCode(ctx context.Context, inviteCode return &org, nil } -// ListByUserID lists organizations that a user belongs to -func (r *organizationRepository) ListByUserID(ctx context.Context, userID string) ([]*types.Organization, error) { +// ListByTenantID lists organizations whose tenant participates as a member. +func (r *organizationRepository) ListByTenantID(ctx context.Context, tenantID uint64) ([]*types.Organization, error) { var orgs []*types.Organization - // Get organizations where user is a member err := r.db.WithContext(ctx). - Joins("JOIN organization_members ON organization_members.organization_id = organizations.id"). - Where("organization_members.user_id = ?", userID). + Joins("JOIN organization_tenant_members otm ON otm.organization_id = organizations.id"). + Where("otm.tenant_id = ?", tenantID). Order("organizations.created_at DESC"). Find(&orgs).Error @@ -108,12 +112,14 @@ func (r *organizationRepository) Delete(ctx context.Context, id string) error { return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.Organization{}).Error } -// AddMember adds a member to an organization -func (r *organizationRepository) AddMember(ctx context.Context, member *types.OrganizationMember) error { - // Check if member already exists +// 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.OrganizationMember{}). - Where("organization_id = ? AND user_id = ?", member.OrganizationID, member.UserID). + r.db.WithContext(ctx).Model(&types.OrganizationTenantMember{}). + Where("organization_id = ? AND tenant_id = ?", member.OrganizationID, member.TenantID). Count(&count) if count > 0 { @@ -123,11 +129,11 @@ func (r *organizationRepository) AddMember(ctx context.Context, member *types.Or return r.db.WithContext(ctx).Create(member).Error } -// RemoveMember removes a member from an organization -func (r *organizationRepository) RemoveMember(ctx context.Context, orgID string, userID string) error { +// RemoveTenantMember removes the (org, tenant) membership row. +func (r *organizationRepository) RemoveTenantMember(ctx context.Context, orgID string, tenantID uint64) error { result := r.db.WithContext(ctx). - Where("organization_id = ? AND user_id = ?", orgID, userID). - Delete(&types.OrganizationMember{}) + Where("organization_id = ? AND tenant_id = ?", orgID, tenantID). + Delete(&types.OrganizationTenantMember{}) if result.Error != nil { return result.Error @@ -138,11 +144,11 @@ func (r *organizationRepository) RemoveMember(ctx context.Context, orgID string, return nil } -// UpdateMemberRole updates a member's role in an organization -func (r *organizationRepository) UpdateMemberRole(ctx context.Context, orgID string, userID string, role types.OrgMemberRole) error { +// UpdateTenantMemberRole updates the role for a (org, tenant) membership. +func (r *organizationRepository) UpdateTenantMemberRole(ctx context.Context, orgID string, tenantID uint64, role types.OrgMemberRole) error { result := r.db.WithContext(ctx). - Model(&types.OrganizationMember{}). - Where("organization_id = ? AND user_id = ?", orgID, userID). + Model(&types.OrganizationTenantMember{}). + Where("organization_id = ? AND tenant_id = ?", orgID, tenantID). Update("role", role) if result.Error != nil { @@ -154,11 +160,11 @@ func (r *organizationRepository) UpdateMemberRole(ctx context.Context, orgID str return nil } -// ListMembers lists all members of an organization -func (r *organizationRepository) ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error) { - var members []*types.OrganizationMember +// ListTenantMembers lists all tenant memberships for an organization. +func (r *organizationRepository) ListTenantMembers(ctx context.Context, orgID string) ([]*types.OrganizationTenantMember, error) { + var members []*types.OrganizationTenantMember err := r.db.WithContext(ctx). - Preload("User"). + Preload("RepresentativeUser"). Where("organization_id = ?", orgID). Order("created_at ASC"). Find(&members).Error @@ -169,11 +175,14 @@ func (r *organizationRepository) ListMembers(ctx context.Context, orgID string) return members, nil } -// GetMember gets a specific member of an organization -func (r *organizationRepository) GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error) { - var member types.OrganizationMember +// GetTenantMember returns the (org, tenant) membership row, or +// ErrOrgMemberNotFound when missing. This is the canonical permission +// check primitive — callers compose this with the share permission +// to compute effective access. +func (r *organizationRepository) GetTenantMember(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationTenantMember, error) { + var member types.OrganizationTenantMember err := r.db.WithContext(ctx). - Where("organization_id = ? AND user_id = ?", orgID, userID). + Where("organization_id = ? AND tenant_id = ?", orgID, tenantID). First(&member).Error if err != nil { @@ -185,19 +194,20 @@ func (r *organizationRepository) GetMember(ctx context.Context, orgID string, us return &member, nil } -// ListMembersByUserForOrgs returns one member record per org where the user is a member (batch). -func (r *organizationRepository) ListMembersByUserForOrgs(ctx context.Context, userID string, orgIDs []string) (map[string]*types.OrganizationMember, error) { +// ListTenantMembersByTenantForOrgs returns one membership row per org where +// the tenant participates (batch). +func (r *organizationRepository) ListTenantMembersByTenantForOrgs(ctx context.Context, tenantID uint64, orgIDs []string) (map[string]*types.OrganizationTenantMember, error) { if len(orgIDs) == 0 { - return make(map[string]*types.OrganizationMember), nil + return make(map[string]*types.OrganizationTenantMember), nil } - var members []*types.OrganizationMember + var members []*types.OrganizationTenantMember err := r.db.WithContext(ctx). - Where("user_id = ? AND organization_id IN ?", userID, orgIDs). + Where("tenant_id = ? AND organization_id IN ?", tenantID, orgIDs). Find(&members).Error if err != nil { return nil, err } - out := make(map[string]*types.OrganizationMember, len(members)) + out := make(map[string]*types.OrganizationTenantMember, len(members)) for _, m := range members { if m != nil { out[m.OrganizationID] = m @@ -206,11 +216,11 @@ func (r *organizationRepository) ListMembersByUserForOrgs(ctx context.Context, u return out, nil } -// CountMembers counts the number of members in an organization -func (r *organizationRepository) CountMembers(ctx context.Context, orgID string) (int64, error) { +// CountTenantMembers counts the number of tenant members in an organization. +func (r *organizationRepository) CountTenantMembers(ctx context.Context, orgID string) (int64, error) { var count int64 err := r.db.WithContext(ctx). - Model(&types.OrganizationMember{}). + Model(&types.OrganizationTenantMember{}). Where("organization_id = ?", orgID). Count(&count).Error return count, err @@ -252,11 +262,15 @@ func (r *organizationRepository) GetJoinRequestByID(ctx context.Context, id stri return &request, nil } -// GetPendingJoinRequest gets a pending join request for a user in an organization (any type) -func (r *organizationRepository) GetPendingJoinRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error) { +// GetPendingJoinRequestByTenant returns a pending request for the given +// (org, tenant). After Plan 3 the dedup key is per-tenant, not per-user +// — the user requesting and the user reviewing may be different humans +// in the same tenant, but the resource being granted is tenant-level +// access. +func (r *organizationRepository) GetPendingJoinRequestByTenant(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationJoinRequest, error) { var request types.OrganizationJoinRequest err := r.db.WithContext(ctx). - Where("organization_id = ? AND user_id = ? AND status = ?", orgID, userID, types.JoinRequestStatusPending). + Where("organization_id = ? AND tenant_id = ? AND status = ?", orgID, tenantID, types.JoinRequestStatusPending). First(&request).Error if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { @@ -267,11 +281,12 @@ func (r *organizationRepository) GetPendingJoinRequest(ctx context.Context, orgI return &request, nil } -// GetPendingRequestByType gets a pending request for a user filtered by request type -func (r *organizationRepository) GetPendingRequestByType(ctx context.Context, orgID string, userID string, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error) { +// GetPendingRequestByTenantAndType narrows the (org, tenant) pending +// dedup query to a specific request_type (join | upgrade). +func (r *organizationRepository) GetPendingRequestByTenantAndType(ctx context.Context, orgID string, tenantID uint64, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error) { var request types.OrganizationJoinRequest err := r.db.WithContext(ctx). - Where("organization_id = ? AND user_id = ? AND status = ? AND request_type = ?", orgID, userID, types.JoinRequestStatusPending, requestType). + Where("organization_id = ? AND tenant_id = ? AND status = ? AND request_type = ?", orgID, tenantID, types.JoinRequestStatusPending, requestType). First(&request).Error if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { diff --git a/internal/application/service/agent_share.go b/internal/application/service/agent_share.go index 40216b1d..73ea26b0 100644 --- a/internal/application/service/agent_share.go +++ b/internal/application/service/agent_share.go @@ -49,7 +49,11 @@ func agentRequiresRerankModel(agent *types.CustomAgent) bool { return false } -// agentShareService implements AgentShareService interface +// agentShareService implements AgentShareService. +// +// Plan 3 of #1303: visibility and access checks key on the caller's +// tenant. callerTenantRole flows through every read path so the 3-D +// cap (tenant Viewer → at most OrgRoleViewer) lands consistently. type agentShareService struct { shareRepo interfaces.AgentShareRepository disabledRepo interfaces.TenantDisabledSharedAgentRepository @@ -75,7 +79,8 @@ func NewAgentShareService( } } -// ShareAgent shares an agent to an organization +// ShareAgent shares an agent to an organization. Permission is forced to +// OrgRoleViewer (cross-tenant agent edit is not part of v1). func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.AgentShare, error) { logger.Infof(ctx, "Sharing agent %s to organization %s", agentID, orgID) @@ -87,10 +92,6 @@ func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgI return nil, ErrNotAgentOwner } - // Require agent to be fully configured before sharing (same rules as for - // conversation — see session_agent_qa.go). Rerank model is only required - // when the `knowledge_search` tool is enabled; Wiki-only agents - // (wiki_search / wiki_read_page) don't call the reranker at runtime. if agent.Config.ModelID == "" { return nil, ErrAgentNotConfigured } @@ -106,18 +107,19 @@ func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgI return nil, err } - member, err := s.orgRepo.GetMember(ctx, orgID, userID) + // Caller's tenant must be an org member with editor+ role to share. + tm, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID) if err != nil { if errors.Is(err, repository.ErrOrgMemberNotFound) { - return nil, ErrUserNotInOrg + return nil, ErrTenantNotInOrg } return nil, err } - if !member.Role.HasPermission(types.OrgRoleEditor) { + if !tm.Role.HasPermission(types.OrgRoleEditor) { return nil, ErrOrgRoleCannotShareAgent } - // 智能体共享仅支持只读,不支持可编辑 + // 智能体共享仅支持只读 permission = types.OrgRoleViewer share := &types.AgentShare{ @@ -151,8 +153,9 @@ func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgI return share, nil } -// RemoveShare removes an agent share -func (s *agentShareService) RemoveShare(ctx context.Context, shareID string, userID string) error { +// RemoveShare removes an agent share. +// Same authz envelope as KB-share remove: original sharer or org admin. +func (s *agentShareService) RemoveShare(ctx context.Context, shareID string, userID string, tenantID uint64) error { share, err := s.shareRepo.GetByID(ctx, shareID) if err != nil { if errors.Is(err, repository.ErrAgentShareNotFound) { @@ -163,8 +166,8 @@ func (s *agentShareService) RemoveShare(ctx context.Context, shareID string, use if share.SharedByUserID == userID { return s.shareRepo.Delete(ctx, shareID) } - member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID) - if err == nil && member.Role == types.OrgRoleAdmin { + tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, tenantID) + if err == nil && tm.Role == types.OrgRoleAdmin { return s.shareRepo.Delete(ctx, shareID) } return ErrAgentSharePermission @@ -180,35 +183,33 @@ func (s *agentShareService) ListSharesByOrganization(ctx context.Context, orgID return s.shareRepo.ListByOrganization(ctx, orgID) } -// ListSharedAgents lists agents shared to the user through organizations, deduplicated by agent ID (keep highest permission) -func (s *agentShareService) ListSharedAgents(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedAgentInfo, error) { - shares, err := s.shareRepo.ListSharedAgentsForUser(ctx, userID) +// ListSharedAgents lists agents reachable from the caller's tenant. +func (s *agentShareService) ListSharedAgents(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.SharedAgentInfo, error) { + shares, err := s.shareRepo.ListSharedAgentsForTenant(ctx, tenantID) if err != nil { return nil, err } agentInfoMap := make(map[string]*types.SharedAgentInfo) for _, share := range shares { - if share.SourceTenantID == currentTenantID { + if share.SourceTenantID == tenantID { continue } if share.Agent == nil { continue } - member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID) + tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, tenantID) if err != nil { continue } - effectivePermission := share.Permission - if !member.Role.HasPermission(share.Permission) { - effectivePermission = member.Role - } + effective := types.MinOrgRole(share.Permission, tm.Role) + effective = applyTenantRoleCap(effective, callerTenantRole) info := &types.SharedAgentInfo{ Agent: share.Agent, ShareID: share.ID, OrganizationID: share.OrganizationID, OrgName: "", - Permission: effectivePermission, + Permission: effective, SourceTenantID: share.SourceTenantID, SharedAt: share.CreatedAt, SharedByUserID: share.SharedByUserID, @@ -225,7 +226,7 @@ func (s *agentShareService) ListSharedAgents(ctx context.Context, userID string, existing, exists := agentInfoMap[key] if !exists { agentInfoMap[key] = info - } else if effectivePermission.HasPermission(existing.Permission) && effectivePermission != existing.Permission { + } else if effective.HasPermission(existing.Permission) && effective != existing.Permission { agentInfoMap[key] = info } } @@ -236,9 +237,9 @@ func (s *agentShareService) ListSharedAgents(ctx context.Context, userID string, } // Set DisabledByMe from tenant_disabled_shared_agents for current tenant - disabledList, err := s.disabledRepo.ListByTenantID(ctx, currentTenantID) + disabledList, err := s.disabledRepo.ListByTenantID(ctx, tenantID) if err != nil { - return result, nil // non-fatal: return list without DisabledByMe + return result, nil } disabledSet := make(map[string]bool) for _, d := range disabledList { @@ -253,12 +254,14 @@ func (s *agentShareService) ListSharedAgents(ctx context.Context, userID string, return result, nil } -// ListSharedAgentsInOrganization returns all agents shared to the given organization (including those shared by the current tenant), for list-page display when a space is selected. -func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedAgentItem, error) { - member, err := s.orgRepo.GetMember(ctx, orgID, userID) +// ListSharedAgentsInOrganization returns all agents shared to the given +// organization (including those shared by the caller's tenant), for list-page +// display when a space is selected. +func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context, orgID string, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.OrganizationSharedAgentItem, error) { + tm, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID) if err != nil { if errors.Is(err, repository.ErrOrgMemberNotFound) { - return nil, ErrUserNotInOrg + return nil, ErrTenantNotInOrg } return nil, err } @@ -274,10 +277,8 @@ func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context, continue } - effectivePermission := share.Permission - if !member.Role.HasPermission(share.Permission) { - effectivePermission = member.Role - } + effective := types.MinOrgRole(share.Permission, tm.Role) + effective = applyTenantRoleCap(effective, callerTenantRole) orgName := "" if share.Organization != nil { @@ -288,7 +289,7 @@ func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context, ShareID: share.ID, OrganizationID: share.OrganizationID, OrgName: orgName, - Permission: effectivePermission, + Permission: effective, SourceTenantID: share.SourceTenantID, SharedAt: share.CreatedAt, SharedByUserID: share.SharedByUserID, @@ -301,13 +302,12 @@ func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context, item := &types.OrganizationSharedAgentItem{ SharedAgentInfo: *info, - IsMine: share.SourceTenantID == currentTenantID, + IsMine: share.SourceTenantID == tenantID, } result = append(result, item) } - // Set DisabledByMe for entries shared by others (mine entries stay false) - disabledList, err := s.disabledRepo.ListByTenantID(ctx, currentTenantID) + disabledList, err := s.disabledRepo.ListByTenantID(ctx, tenantID) if err == nil { disabledSet := make(map[string]bool) for _, d := range disabledList { @@ -323,13 +323,14 @@ func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context, return result, nil } -// ListSharedAgentsInOrganizations returns per-org agent lists (batch); only orgs where user is member. -func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context, orgIDs []string, userID string, currentTenantID uint64) (map[string][]*types.OrganizationSharedAgentItem, error) { +// ListSharedAgentsInOrganizations returns per-org agent lists (batch); only +// orgs where the caller's tenant is a member. +func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context, orgIDs []string, tenantID uint64, callerTenantRole types.TenantRole) (map[string][]*types.OrganizationSharedAgentItem, error) { out := make(map[string][]*types.OrganizationSharedAgentItem) if len(orgIDs) == 0 { return out, nil } - members, err := s.orgRepo.ListMembersByUserForOrgs(ctx, userID, orgIDs) + members, err := s.orgRepo.ListTenantMembersByTenantForOrgs(ctx, tenantID, orgIDs) if err != nil { return nil, err } @@ -344,22 +345,20 @@ func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context, } } disabledSet := make(map[string]bool) - if disabledList, err := s.disabledRepo.ListByTenantID(ctx, currentTenantID); err == nil { + if disabledList, err := s.disabledRepo.ListByTenantID(ctx, tenantID); err == nil { for _, d := range disabledList { disabledSet[fmt.Sprintf("%s_%d", d.AgentID, d.SourceTenantID)] = true } } for orgID, list := range byOrg { - member := members[orgID] + tm := members[orgID] result := make([]*types.OrganizationSharedAgentItem, 0, len(list)) for _, share := range list { if share.Agent == nil { continue } - effectivePermission := share.Permission - if !member.Role.HasPermission(share.Permission) { - effectivePermission = member.Role - } + effective := types.MinOrgRole(share.Permission, tm.Role) + effective = applyTenantRoleCap(effective, callerTenantRole) orgName := "" if share.Organization != nil { orgName = share.Organization.Name @@ -369,7 +368,7 @@ func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context, ShareID: share.ID, OrganizationID: share.OrganizationID, OrgName: orgName, - Permission: effectivePermission, + Permission: effective, SourceTenantID: share.SourceTenantID, SharedAt: share.CreatedAt, SharedByUserID: share.SharedByUserID, @@ -381,7 +380,7 @@ func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context, } item := &types.OrganizationSharedAgentItem{ SharedAgentInfo: *info, - IsMine: share.SourceTenantID == currentTenantID, + IsMine: share.SourceTenantID == tenantID, } if item.Agent != nil && !item.IsMine { item.DisabledByMe = disabledSet[fmt.Sprintf("%s_%d", item.Agent.ID, item.SourceTenantID)] @@ -406,12 +405,18 @@ func (s *agentShareService) SetSharedAgentDisabledByMe(ctx context.Context, tena return s.disabledRepo.Remove(ctx, tenantID, agentID, sourceTenantID) } -// GetSharedAgentForUser returns the shared agent by agentID if the user has access; source tenant is resolved from the user's share. One share lookup + one agent lookup. -func (s *agentShareService) GetSharedAgentForUser(ctx context.Context, userID string, currentTenantID uint64, agentID string) (*types.CustomAgent, error) { +// GetSharedAgentForTenant returns the shared agent by agentID if the caller's +// tenant has access; source tenant is resolved from the share. One share +// lookup + one agent lookup. +// +// callerTenantRole is currently only used for symmetry / future caps on +// agent execution (e.g. tenant Viewers might be banned from +// state-changing tool calls in a follow-up). +func (s *agentShareService) GetSharedAgentForTenant(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole, agentID string) (*types.CustomAgent, error) { if agentID == "" { return nil, ErrAgentShareNotFound } - share, err := s.shareRepo.GetShareByAgentIDForUser(ctx, userID, agentID, currentTenantID) + share, err := s.shareRepo.GetShareByAgentIDForTenant(ctx, tenantID, agentID, tenantID) if err != nil { if errors.Is(err, repository.ErrAgentShareNotFound) { return nil, ErrAgentSharePermission @@ -425,15 +430,18 @@ func (s *agentShareService) GetSharedAgentForUser(ctx context.Context, userID st } return nil, err } + _ = callerTenantRole return agent, nil } -// UserCanAccessKBViaSomeSharedAgent returns true if the user has at least one shared agent that can access the given KB (used when opening KB detail from space list without agent_id). -func (s *agentShareService) UserCanAccessKBViaSomeSharedAgent(ctx context.Context, userID string, currentTenantID uint64, kb *types.KnowledgeBase) (bool, error) { +// TenantCanAccessKBViaSomeSharedAgent returns true if the caller's tenant has +// at least one shared agent that can access the given KB (used when opening KB +// detail from "通过智能体可见" list without agent_id). +func (s *agentShareService) TenantCanAccessKBViaSomeSharedAgent(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole, kb *types.KnowledgeBase) (bool, error) { if kb == nil || kb.ID == "" { return false, nil } - list, err := s.ListSharedAgents(ctx, userID, currentTenantID) + list, err := s.ListSharedAgents(ctx, tenantID, callerTenantRole) if err != nil || len(list) == 0 { return false, err } @@ -487,7 +495,8 @@ func (s *agentShareService) GetShareByAgentAndOrg(ctx context.Context, agentID s return share, nil } -// GetShareByAgentIDForUser returns one share for the given agentID that the user can access (user in org), excluding source_tenant_id == excludeTenantID. -func (s *agentShareService) GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error) { - return s.shareRepo.GetShareByAgentIDForUser(ctx, userID, agentID, excludeTenantID) +// GetShareByAgentIDForTenant returns one share for the given agentID that the +// tenant can reach, excluding source_tenant_id == excludeTenantID. +func (s *agentShareService) GetShareByAgentIDForTenant(ctx context.Context, tenantID uint64, agentID string, excludeTenantID uint64) (*types.AgentShare, error) { + return s.shareRepo.GetShareByAgentIDForTenant(ctx, tenantID, agentID, excludeTenantID) } diff --git a/internal/application/service/kbshare.go b/internal/application/service/kbshare.go index b61bc631..bc47d678 100644 --- a/internal/application/service/kbshare.go +++ b/internal/application/service/kbshare.go @@ -17,11 +17,22 @@ var ( ErrSharePermissionDenied = errors.New("permission denied for this share operation") ErrKBNotFound = errors.New("knowledge base not found") ErrNotKBOwner = errors.New("only knowledge base owner can share") - // ErrOrgRoleCannotShare: only editors and admins in the org can share KBs to that org; viewers cannot + // ErrOrgRoleCannotShare: only editors and admins (in tenant's org role) may share KBs to that org; viewers cannot ErrOrgRoleCannotShare = errors.New("only editors and admins can share knowledge bases to this organization") ) -// kbShareService implements KBShareService interface +// kbShareService implements KBShareService. +// +// Plan 3 of #1303: permission checks resolve "is the *caller's tenant* +// in this org, with what role" rather than "is this user". The 3-D cap +// inside CheckTenantKBPermission encodes: +// +// effective = min(share.Permission, tenant_org_role, tenant_role_cap) +// +// where tenant_role_cap pins tenant Viewers to OrgRoleViewer regardless +// of what the org-level grant said. That keeps the tenant RBAC promise +// — Viewer in your own tenant cannot write — even when the access is +// routed through cross-tenant sharing. type kbShareService struct { shareRepo interfaces.KBShareRepository orgRepo interfaces.OrganizationRepository @@ -47,22 +58,31 @@ func NewKBShareService( } } -// ShareKnowledgeBase shares a knowledge base to an organization +// applyTenantRoleCap applies the third dimension of the cap: a caller +// whose own tenant role is Viewer cannot exceed OrgRoleViewer on any +// shared resource, regardless of what the org-level grant said. Higher +// roles (Contributor / Admin / Owner) pass through unchanged. +func applyTenantRoleCap(p types.OrgMemberRole, callerTenantRole types.TenantRole) types.OrgMemberRole { + if callerTenantRole == types.TenantRoleViewer && p.HasPermission(types.OrgRoleEditor) { + return types.OrgRoleViewer + } + return p +} + +// ShareKnowledgeBase shares a knowledge base to an organization. +// Caller must be in a tenant that owns the KB *and* be a member of the +// target org with at least editor role. func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.KnowledgeBaseShare, error) { logger.Infof(ctx, "Sharing knowledge base %s to organization %s", kbID, orgID) - // Verify knowledge base exists and user is the owner (same tenant) kb, err := s.kbRepo.GetKnowledgeBaseByID(ctx, kbID) if err != nil { return nil, ErrKBNotFound } - - // Check if user's tenant owns the knowledge base if kb.TenantID != tenantID { return nil, ErrNotKBOwner } - // Verify organization exists _, err = s.orgRepo.GetByID(ctx, orgID) if err != nil { if errors.Is(err, repository.ErrOrganizationNotFound) { @@ -71,15 +91,15 @@ func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, or return nil, err } - // Check if user is a member of the organization and has at least editor role (viewers cannot share KBs to the org) - member, err := s.orgRepo.GetMember(ctx, orgID, userID) + // Caller's tenant must be an org member with editor+ role to share. + tm, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID) if err != nil { if errors.Is(err, repository.ErrOrgMemberNotFound) { - return nil, ErrUserNotInOrg + return nil, ErrTenantNotInOrg } return nil, err } - if !member.Role.HasPermission(types.OrgRoleEditor) { + if !tm.Role.HasPermission(types.OrgRoleEditor) { return nil, ErrOrgRoleCannotShare } @@ -100,7 +120,6 @@ func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, or if err := s.shareRepo.Create(ctx, share); err != nil { if errors.Is(err, repository.ErrKBShareAlreadyExists) { - // Update existing share existingShare, err := s.shareRepo.GetByKBAndOrg(ctx, kbID, orgID) if err != nil { return nil, err @@ -119,9 +138,11 @@ func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, or return share, nil } -// UpdateSharePermission updates the permission of a share. -// Allowed if: (1) current user is the sharer, or (2) current user is admin of the target organization. -func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string) error { +// UpdateSharePermission updates a share's permission. +// Allowed if (1) the caller is the original sharer (same user id), or +// (2) the caller's tenant is admin in the target org. The latter lets +// org admins repair shares when the original sharer leaves. +func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string, tenantID uint64) error { share, err := s.shareRepo.GetByID(ctx, shareID) if err != nil { if errors.Is(err, repository.ErrKBShareNotFound) { @@ -130,10 +151,9 @@ func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID stri return err } - // Sharer can always update; org admin can also update (e.g. when sharer left) if share.SharedByUserID != userID { - member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID) - if err != nil || member.Role != types.OrgRoleAdmin { + tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, tenantID) + if err != nil || tm.Role != types.OrgRoleAdmin { return ErrSharePermissionDenied } } @@ -149,9 +169,8 @@ func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID stri } // RemoveShare removes a share. -// Allowed if: (1) current user is the sharer, or (2) current user is admin of the target organization. -// Org admins can unlink any KB shared to their org (e.g. content governance, sharer left). -func (s *kbShareService) RemoveShare(ctx context.Context, shareID string, userID string) error { +// Same authz envelope as UpdateSharePermission: original sharer or org admin. +func (s *kbShareService) RemoveShare(ctx context.Context, shareID string, userID string, tenantID uint64) error { share, err := s.shareRepo.GetByID(ctx, shareID) if err != nil { if errors.Is(err, repository.ErrKBShareNotFound) { @@ -160,14 +179,12 @@ func (s *kbShareService) RemoveShare(ctx context.Context, shareID string, userID return err } - // Sharer can always remove their own share if share.SharedByUserID == userID { return s.shareRepo.Delete(ctx, shareID) } - // Org admin can remove any share targeting their organization - member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID) - if err == nil && member.Role == types.OrgRoleAdmin { + tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, tenantID) + if err == nil && tm.Role == types.OrgRoleAdmin { return s.shareRepo.Delete(ctx, shareID) } @@ -191,46 +208,37 @@ func (s *kbShareService) ListSharesByOrganization(ctx context.Context, orgID str return s.shareRepo.ListByOrganization(ctx, orgID) } -// ListSharedKnowledgeBases lists all knowledge bases shared to the user through organizations -// It filters out knowledge bases that belong to the user's own tenant -// It deduplicates knowledge bases that are shared to multiple organizations the user belongs to -func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedKnowledgeBaseInfo, error) { - shares, err := s.shareRepo.ListSharedKBsForUser(ctx, userID) +// ListSharedKnowledgeBases lists all knowledge bases reachable from the +// caller's tenant via cross-tenant org shares. Permission per KB is +// computed via the 3-D cap. +func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.SharedKnowledgeBaseInfo, error) { + shares, err := s.shareRepo.ListSharedKBsForTenant(ctx, tenantID) if err != nil { return nil, err } - // Use a map to deduplicate by knowledge base ID, keeping the one with highest permission kbInfoMap := make(map[string]*types.SharedKnowledgeBaseInfo) for _, share := range shares { - // Skip knowledge bases that belong to the user's own tenant - // (user already has full ownership of these) - if share.SourceTenantID == currentTenantID { + if share.SourceTenantID == tenantID { continue } - - // Skip if knowledge base is nil if share.KnowledgeBase == nil { continue } kbID := share.KnowledgeBase.ID - // Get user's role in the organization - member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID) + tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, tenantID) if err != nil { - continue // Skip if user is not a member anymore + continue } - // Effective permission is the lower of share permission and user's org role - effectivePermission := share.Permission - if !member.Role.HasPermission(share.Permission) { - effectivePermission = member.Role - } + // 3-D cap: share × tenant_org_role × tenant_role_cap. + effective := types.MinOrgRole(share.Permission, tm.Role) + effective = applyTenantRoleCap(effective, callerTenantRole) kb := share.KnowledgeBase - // Calculate knowledge/chunk count based on type switch kb.Type { case types.KnowledgeBaseTypeDocument: knowledgeCount, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, share.SourceTenantID, kb.ID) @@ -253,7 +261,7 @@ func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, userID st ShareID: share.ID, OrganizationID: share.OrganizationID, OrgName: "", - Permission: effectivePermission, + Permission: effective, SourceTenantID: share.SourceTenantID, SharedAt: share.CreatedAt, } @@ -262,25 +270,16 @@ func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, userID st info.OrgName = share.Organization.Name } - // Check if we already have this knowledge base existing, exists := kbInfoMap[kbID] if !exists { - // First time seeing this KB, add it kbInfoMap[kbID] = info } else { - // KB already exists, keep the one with higher permission - // Permission hierarchy: admin(3) > editor(2) > viewer(1) - // If current permission is higher than existing, replace - // This handles the case where a user belongs to multiple orgs with different permissions - if effectivePermission.HasPermission(existing.Permission) && effectivePermission != existing.Permission { - // Current permission is higher, replace with higher permission + if effective.HasPermission(existing.Permission) && effective != existing.Permission { kbInfoMap[kbID] = info } - // If existing permission is higher or equal, keep existing (no change needed) } } - // Convert map to slice result := make([]*types.SharedKnowledgeBaseInfo, 0, len(kbInfoMap)) for _, info := range kbInfoMap { result = append(result, info) @@ -289,12 +288,14 @@ func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, userID st return result, nil } -// ListSharedKnowledgeBasesInOrganization returns all knowledge bases shared to the given organization (including those shared by the current tenant), for list-page display when a space is selected. -func (s *kbShareService) ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error) { - member, err := s.orgRepo.GetMember(ctx, orgID, userID) +// ListSharedKnowledgeBasesInOrganization returns all knowledge bases shared to +// the given organization (including those shared from the caller's tenant) for +// list-page display when the user picks a space. +func (s *kbShareService) ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.OrganizationSharedKnowledgeBaseItem, error) { + tm, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID) if err != nil { if errors.Is(err, repository.ErrOrgMemberNotFound) { - return nil, ErrUserNotInOrg + return nil, ErrTenantNotInOrg } return nil, err } @@ -310,10 +311,8 @@ func (s *kbShareService) ListSharedKnowledgeBasesInOrganization(ctx context.Cont continue } - effectivePermission := share.Permission - if !member.Role.HasPermission(share.Permission) { - effectivePermission = member.Role - } + effective := types.MinOrgRole(share.Permission, tm.Role) + effective = applyTenantRoleCap(effective, callerTenantRole) kb := share.KnowledgeBase switch kb.Type { @@ -337,23 +336,24 @@ func (s *kbShareService) ListSharedKnowledgeBasesInOrganization(ctx context.Cont ShareID: share.ID, OrganizationID: share.OrganizationID, OrgName: orgName, - Permission: effectivePermission, + Permission: effective, SourceTenantID: share.SourceTenantID, SharedAt: share.CreatedAt, }, - IsMine: share.SourceTenantID == currentTenantID, + IsMine: share.SourceTenantID == tenantID, } result = append(result, item) } return result, nil } -// ListSharedKnowledgeBaseIDsByOrganizations returns per-org direct shared KB IDs (batch); only orgs where user is member. -func (s *kbShareService) ListSharedKnowledgeBaseIDsByOrganizations(ctx context.Context, orgIDs []string, userID string) (map[string][]string, error) { +// ListSharedKnowledgeBaseIDsByOrganizations returns per-org direct shared KB +// IDs (batch); only orgs where the caller's tenant is a member. +func (s *kbShareService) ListSharedKnowledgeBaseIDsByOrganizations(ctx context.Context, orgIDs []string, tenantID uint64) (map[string][]string, error) { if len(orgIDs) == 0 { return make(map[string][]string), nil } - members, err := s.orgRepo.ListMembersByUserForOrgs(ctx, userID, orgIDs) + members, err := s.orgRepo.ListTenantMembersByTenantForOrgs(ctx, tenantID, orgIDs) if err != nil { return nil, err } @@ -401,59 +401,55 @@ func (s *kbShareService) GetShareByKBAndOrg(ctx context.Context, kbID string, or return share, nil } -// CheckUserKBPermission checks a user's permission for a knowledge base -// Returns: permission level, isShared, error -func (s *kbShareService) CheckUserKBPermission(ctx context.Context, kbID string, userID string) (types.OrgMemberRole, bool, error) { - // Get all shares for this knowledge base +// CheckTenantKBPermission resolves the caller's effective permission on a KB +// reached via org sharing. Returns (effectiveRole, isShared, err). +// +// effectiveRole is the maximum role across all shares of this KB into orgs +// where the caller's tenant is a member, capped by the 3-D rule. Empty +// when isShared is false. +func (s *kbShareService) CheckTenantKBPermission(ctx context.Context, kbID string, callerTenantID uint64, callerTenantRole types.TenantRole) (types.OrgMemberRole, bool, error) { shares, err := s.shareRepo.ListByKnowledgeBase(ctx, kbID) if err != nil { return "", false, err } - var highestPermission types.OrgMemberRole + var highest types.OrgMemberRole isShared := false for _, share := range shares { - // Check if user is a member of the organization - member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID) + tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, callerTenantID) if err != nil { - continue // User is not a member of this org + continue } isShared = true - // Effective permission is the lower of share permission and user's org role - effectivePermission := share.Permission - if !member.Role.HasPermission(share.Permission) { - effectivePermission = member.Role - } + effective := types.MinOrgRole(share.Permission, tm.Role) + effective = applyTenantRoleCap(effective, callerTenantRole) - // Keep the highest permission - if highestPermission == "" || effectivePermission.HasPermission(highestPermission) { - highestPermission = effectivePermission + if highest == "" || effective.HasPermission(highest) { + highest = effective } } - return highestPermission, isShared, nil + return highest, isShared, nil } -// HasKBPermission checks if a user has at least the required permission level for a knowledge base -func (s *kbShareService) HasKBPermission(ctx context.Context, kbID string, userID string, requiredRole types.OrgMemberRole) (bool, error) { - permission, isShared, err := s.CheckUserKBPermission(ctx, kbID, userID) +// HasTenantKBPermission is a thin "do I have at least N" wrapper over +// CheckTenantKBPermission for callers that don't need the granular role. +func (s *kbShareService) HasTenantKBPermission(ctx context.Context, kbID string, callerTenantID uint64, callerTenantRole types.TenantRole, requiredRole types.OrgMemberRole) (bool, error) { + role, isShared, err := s.CheckTenantKBPermission(ctx, kbID, callerTenantID, callerTenantRole) if err != nil { return false, err } - if !isShared { return false, nil } - - return permission.HasPermission(requiredRole), nil + return role.HasPermission(requiredRole), nil } // GetKBSourceTenant gets the source tenant ID for a shared knowledge base func (s *kbShareService) GetKBSourceTenant(ctx context.Context, kbID string) (uint64, error) { - // First check if there are any shares for this KB shares, err := s.shareRepo.ListByKnowledgeBase(ctx, kbID) if err != nil { return 0, err @@ -463,7 +459,6 @@ func (s *kbShareService) GetKBSourceTenant(ctx context.Context, kbID string) (ui return shares[0].SourceTenantID, nil } - // If not shared, get the tenant from the knowledge base itself kb, err := s.kbRepo.GetKnowledgeBaseByID(ctx, kbID) if err != nil { return 0, ErrKBNotFound diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.go index ed484cb9..484c124d 100644 --- a/internal/application/service/knowledge.go +++ b/internal/application/service/knowledge.go @@ -340,6 +340,9 @@ func (s *knowledgeService) GetKnowledgeBatchWithSharedAccess(ctx context.Context if !ok || userID == "" { return ownList, nil } + // Plan 3: shared-KB permission is keyed on (tenant, tenant_role) + // rather than user. callerTenantRole drives the 3-D cap. + callerTenantRole := types.TenantRoleFromContext(ctx) for _, id := range ids { if foundSet[id] { continue @@ -348,7 +351,7 @@ func (s *knowledgeService) GetKnowledgeBatchWithSharedAccess(ctx context.Context if err != nil || k == nil || k.KnowledgeBaseID == "" { continue } - hasPermission, err := s.kbShareService.HasKBPermission(ctx, k.KnowledgeBaseID, userID, types.OrgRoleViewer) + hasPermission, err := s.kbShareService.HasTenantKBPermission(ctx, k.KnowledgeBaseID, tenantID, callerTenantRole, types.OrgRoleViewer) if err != nil || !hasPermission { continue } @@ -496,10 +499,13 @@ func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string, } } - // Shared knowledge bases (document type only) + // Shared knowledge bases (document type only). Plan 3 of #1303 keys + // the share lookup on (tenantID, callerTenantRole); userID is no + // longer load-bearing for org-share access. if userIDVal := ctx.Value(types.UserIDContextKey); userIDVal != nil { if userID, ok := userIDVal.(string); ok && userID != "" { - sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, userID, tenantID) + callerTenantRole := types.TenantRoleFromContext(ctx) + sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, tenantID, callerTenantRole) if err == nil { for _, info := range sharedList { if info != nil && info.KnowledgeBase != nil && info.KnowledgeBase.Type == types.KnowledgeBaseTypeDocument { diff --git a/internal/application/service/knowledge_faq.go b/internal/application/service/knowledge_faq.go index eff997e7..463e2fdf 100644 --- a/internal/application/service/knowledge_faq.go +++ b/internal/application/service/knowledge_faq.go @@ -40,10 +40,11 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context, if userIDVal == nil { return nil, werrors.NewForbiddenError("无权访问该知识库") } - userID := userIDVal.(string) + _ = userIDVal.(string) // userID retained only for legacy log fields + callerTenantRole := types.TenantRoleFromContext(ctx) - // Check if user has at least viewer permission through organization sharing - hasPermission, err := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer) + // Check if the caller's tenant has at least viewer permission via org sharing. + hasPermission, err := s.kbShareService.HasTenantKBPermission(ctx, kbID, tenantID, callerTenantRole, types.OrgRoleViewer) if err != nil || !hasPermission { return nil, werrors.NewForbiddenError("无权访问该知识库") } diff --git a/internal/application/service/knowledge_shared_access_test.go b/internal/application/service/knowledge_shared_access_test.go index a163b93e..be0e2121 100644 --- a/internal/application/service/knowledge_shared_access_test.go +++ b/internal/application/service/knowledge_shared_access_test.go @@ -21,10 +21,10 @@ type fakeKBShareService struct { func (f *fakeKBShareService) ShareKnowledgeBase(context.Context, string, string, string, uint64, types.OrgMemberRole) (*types.KnowledgeBaseShare, error) { return nil, errors.New("not implemented") } -func (f *fakeKBShareService) UpdateSharePermission(context.Context, string, types.OrgMemberRole, string) error { +func (f *fakeKBShareService) UpdateSharePermission(context.Context, string, types.OrgMemberRole, string, uint64) error { return errors.New("not implemented") } -func (f *fakeKBShareService) RemoveShare(context.Context, string, string) error { +func (f *fakeKBShareService) RemoveShare(context.Context, string, string, uint64) error { return errors.New("not implemented") } func (f *fakeKBShareService) ListSharesByKnowledgeBase(context.Context, string, uint64) ([]*types.KnowledgeBaseShare, error) { @@ -33,13 +33,13 @@ func (f *fakeKBShareService) ListSharesByKnowledgeBase(context.Context, string, func (f *fakeKBShareService) ListSharesByOrganization(context.Context, string) ([]*types.KnowledgeBaseShare, error) { return nil, errors.New("not implemented") } -func (f *fakeKBShareService) ListSharedKnowledgeBases(context.Context, string, uint64) ([]*types.SharedKnowledgeBaseInfo, error) { +func (f *fakeKBShareService) ListSharedKnowledgeBases(context.Context, uint64, types.TenantRole) ([]*types.SharedKnowledgeBaseInfo, error) { return nil, errors.New("not implemented") } -func (f *fakeKBShareService) ListSharedKnowledgeBasesInOrganization(context.Context, string, string, uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error) { +func (f *fakeKBShareService) ListSharedKnowledgeBasesInOrganization(context.Context, string, uint64, types.TenantRole) ([]*types.OrganizationSharedKnowledgeBaseItem, error) { return nil, errors.New("not implemented") } -func (f *fakeKBShareService) ListSharedKnowledgeBaseIDsByOrganizations(context.Context, []string, string) (map[string][]string, error) { +func (f *fakeKBShareService) ListSharedKnowledgeBaseIDsByOrganizations(context.Context, []string, uint64) (map[string][]string, error) { return nil, errors.New("not implemented") } func (f *fakeKBShareService) GetShare(context.Context, string) (*types.KnowledgeBaseShare, error) { @@ -48,10 +48,10 @@ func (f *fakeKBShareService) GetShare(context.Context, string) (*types.Knowledge func (f *fakeKBShareService) GetShareByKBAndOrg(context.Context, string, string) (*types.KnowledgeBaseShare, error) { return nil, errors.New("not implemented") } -func (f *fakeKBShareService) CheckUserKBPermission(context.Context, string, string) (types.OrgMemberRole, bool, error) { +func (f *fakeKBShareService) CheckTenantKBPermission(context.Context, string, uint64, types.TenantRole) (types.OrgMemberRole, bool, error) { return "", false, errors.New("not implemented") } -func (f *fakeKBShareService) HasKBPermission(ctx context.Context, kbID string, userID string, requiredRole types.OrgMemberRole) (bool, error) { +func (f *fakeKBShareService) HasTenantKBPermission(ctx context.Context, kbID string, callerTenantID uint64, callerTenantRole types.TenantRole, requiredRole types.OrgMemberRole) (bool, error) { return f.allowedKBs[kbID], nil } func (f *fakeKBShareService) GetKBSourceTenant(context.Context, string) (uint64, error) { diff --git a/internal/application/service/knowledgebase_search_shared.go b/internal/application/service/knowledgebase_search_shared.go index f690d15e..c7a0aec5 100644 --- a/internal/application/service/knowledgebase_search_shared.go +++ b/internal/application/service/knowledgebase_search_shared.go @@ -55,13 +55,14 @@ func (s *knowledgeBaseService) fetchKnowledgeDataWithShared(ctx context.Context, } logger.Infof(ctx, "[fetchKnowledgeDataWithShared] Looking up %d missing knowledge IDs with userID=%s", len(missingIDs), userID) + callerTenantRole := types.TenantRoleFromContext(ctx) for _, id := range missingIDs { k, err := s.kgRepo.GetKnowledgeByIDOnly(ctx, id) if err != nil || k == nil || k.KnowledgeBaseID == "" { logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Knowledge %s not found or has no KB", id) continue } - hasPermission, err := s.kbShareService.HasKBPermission(ctx, k.KnowledgeBaseID, userID, types.OrgRoleViewer) + hasPermission, err := s.kbShareService.HasTenantKBPermission(ctx, k.KnowledgeBaseID, tenantID, callerTenantRole, types.OrgRoleViewer) if err != nil { logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Permission check error for KB %s: %v", k.KnowledgeBaseID, err) continue @@ -110,6 +111,7 @@ func (s *knowledgeBaseService) listChunksByIDWithShared(ctx context.Context, } logger.Infof(ctx, "[listChunksByIDWithShared] Looking up %d missing chunks with userID=%s", len(missing), userID) + callerTenantRole := types.TenantRoleFromContext(ctx) crossChunks, err := s.chunkRepo.ListChunksByIDOnly(ctx, missing) if err != nil { logger.Warnf(ctx, "[listChunksByIDWithShared] Failed to fetch chunks by ID only: %v", err) @@ -121,7 +123,7 @@ func (s *knowledgeBaseService) listChunksByIDWithShared(ctx context.Context, if c == nil || c.KnowledgeBaseID == "" { continue } - hasPermission, err := s.kbShareService.HasKBPermission(ctx, c.KnowledgeBaseID, userID, types.OrgRoleViewer) + hasPermission, err := s.kbShareService.HasTenantKBPermission(ctx, c.KnowledgeBaseID, tenantID, callerTenantRole, types.OrgRoleViewer) if err != nil { logger.Debugf(ctx, "[listChunksByIDWithShared] Permission check error for KB %s: %v", c.KnowledgeBaseID, err) continue diff --git a/internal/application/service/organization.go b/internal/application/service/organization.go index 386a0938..9a868de4 100644 --- a/internal/application/service/organization.go +++ b/internal/application/service/organization.go @@ -18,7 +18,7 @@ import ( // Default invite code validity in days; allowed values: 0 (never), 1, 7, 30 const DefaultInviteCodeValidityDays = 7 -// DefaultMemberLimit is the default max members per organization (0 = unlimited) +// DefaultMemberLimit is the default max tenant-members per organization (0 = unlimited) const DefaultMemberLimit = 200 // ValidInviteCodeValidityDays are the allowed values for invite_code_validity_days @@ -27,9 +27,9 @@ var ValidInviteCodeValidityDays = map[int]bool{0: true, 1: true, 7: true, 30: tr var ( ErrOrgNotFound = errors.New("organization not found") ErrOrgPermissionDenied = errors.New("permission denied for this organization") - ErrCannotRemoveOwner = errors.New("cannot remove organization owner") - ErrCannotChangeOwnerRole = errors.New("cannot change organization owner role") - ErrUserNotInOrg = errors.New("user is not a member of this organization") + ErrCannotRemoveOwner = errors.New("cannot remove organization owner tenant") + ErrCannotChangeOwnerRole = errors.New("cannot change organization owner tenant role") + ErrTenantNotInOrg = errors.New("tenant is not a member of this organization") ErrInvalidRole = errors.New("invalid role") ErrInviteCodeExpired = errors.New("invite code has expired") ErrInvalidValidityDays = errors.New("invite_code_validity_days must be 0, 1, 7, or 30") @@ -37,7 +37,12 @@ var ( ErrOrgMemberLimitTooLow = errors.New("member limit cannot be lower than current member count") ) -// organizationService implements OrganizationService interface +// organizationService implements OrganizationService. +// +// Plan 3 of #1303: a "member" of an org is a tenant, identified by +// (org_id, tenant_id). The user_id of the requester is recorded only as +// the representative for UI/audit; permission decisions ride on the +// tenant's role inside the org. type organizationService struct { orgRepo interfaces.OrganizationRepository userRepo interfaces.UserRepository @@ -69,9 +74,10 @@ func resolveInviteExpiry(validityDays int, now time.Time) *time.Time { return &t } -// CreateOrganization creates a new organization +// CreateOrganization creates a new organization. The creator's tenant +// is enrolled at admin role and userID is recorded as the representative. func (s *organizationService) CreateOrganization(ctx context.Context, userID string, tenantID uint64, req *types.CreateOrganizationRequest) (*types.Organization, error) { - logger.Infof(ctx, "Creating organization: %s by user: %s", req.Name, userID) + logger.Infof(ctx, "Creating organization: %s by user: %s in tenant: %d", req.Name, userID, tenantID) validityDays := DefaultInviteCodeValidityDays if req.InviteCodeValidityDays != nil { @@ -108,19 +114,24 @@ func (s *organizationService) CreateOrganization(ctx context.Context, userID str return nil, err } - // Add the creator as admin member - member := &types.OrganizationMember{ - ID: uuid.New().String(), - OrganizationID: org.ID, - UserID: userID, - TenantID: tenantID, - Role: types.OrgRoleAdmin, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), + // Enrol the creator's tenant as admin. Owner tenant is encoded by + // (Organization.OwnerID points to a user, the user's tenant is the + // owning tenant); the membership row gives that tenant the same + // role plumbing as everyone else for join/leave/role-change UX. + joinedAt := now + member := &types.OrganizationTenantMember{ + ID: uuid.New().String(), + OrganizationID: org.ID, + TenantID: tenantID, + Role: types.OrgRoleAdmin, + RepresentativeUserID: userID, + JoinedAt: &joinedAt, + CreatedAt: now, + UpdatedAt: now, } - if err := s.orgRepo.AddMember(ctx, member); err != nil { - logger.Errorf(ctx, "Failed to add creator as member: %v", err) + if err := s.orgRepo.AddTenantMember(ctx, member); err != nil { + logger.Errorf(ctx, "Failed to add creator tenant as member: %v", err) // Rollback organization creation _ = s.orgRepo.Delete(ctx, org.ID) return nil, err @@ -157,15 +168,16 @@ func (s *organizationService) GetOrganizationByInviteCode(ctx context.Context, i return org, nil } -// ListUserOrganizations lists all organizations that a user belongs to -func (s *organizationService) ListUserOrganizations(ctx context.Context, userID string) ([]*types.Organization, error) { - return s.orgRepo.ListByUserID(ctx, userID) +// ListTenantOrganizations lists all organizations the tenant participates in. +func (s *organizationService) ListTenantOrganizations(ctx context.Context, tenantID uint64) ([]*types.Organization, error) { + return s.orgRepo.ListByTenantID(ctx, tenantID) } -// UpdateOrganization updates an organization -func (s *organizationService) UpdateOrganization(ctx context.Context, id string, userID string, req *types.UpdateOrganizationRequest) (*types.Organization, error) { - // Check if user is admin - isAdmin, err := s.IsOrgAdmin(ctx, id, userID) +// UpdateOrganization updates an organization. Operator's tenant must be +// admin in this org; the operator user identity is logged for audit but +// not used as the permission key. +func (s *organizationService) UpdateOrganization(ctx context.Context, id string, userID string, tenantID uint64, req *types.UpdateOrganizationRequest) (*types.Organization, error) { + isAdmin, err := s.IsTenantOrgAdmin(ctx, id, tenantID) if err != nil { return nil, err } @@ -204,7 +216,7 @@ func (s *organizationService) UpdateOrganization(ctx context.Context, id string, return nil, errors.New("member_limit must be >= 0") } if *req.MemberLimit > 0 { - count, err := s.orgRepo.CountMembers(ctx, id) + count, err := s.orgRepo.CountTenantMembers(ctx, id) if err != nil { return nil, err } @@ -216,6 +228,7 @@ func (s *organizationService) UpdateOrganization(ctx context.Context, id string, } org.UpdatedAt = time.Now() + _ = userID // recorded by the caller for audit; not used here if err := s.orgRepo.Update(ctx, org); err != nil { return nil, err } @@ -223,8 +236,9 @@ func (s *organizationService) UpdateOrganization(ctx context.Context, id string, return org, nil } -// SearchSearchableOrganizations returns searchable (discoverable) organizations for the current user -func (s *organizationService) SearchSearchableOrganizations(ctx context.Context, userID string, query string, limit int) (*types.ListSearchableOrganizationsResponse, error) { +// SearchSearchableOrganizations returns searchable (discoverable) organizations +// keyed on the caller's tenant — IsAlreadyMember reflects tenant-level membership. +func (s *organizationService) SearchSearchableOrganizations(ctx context.Context, tenantID uint64, query string, limit int) (*types.ListSearchableOrganizationsResponse, error) { if limit <= 0 { limit = 20 } @@ -237,7 +251,7 @@ func (s *organizationService) SearchSearchableOrganizations(ctx context.Context, agentShareCounts := make(map[string]int) memberOrgIDs := make(map[string]bool) for _, org := range orgs { - if mc, err := s.orgRepo.CountMembers(ctx, org.ID); err == nil { + if mc, err := s.orgRepo.CountTenantMembers(ctx, org.ID); err == nil { memberCounts[org.ID] = mc } shares, _ := s.shareRepo.ListByOrganization(ctx, org.ID) @@ -245,7 +259,7 @@ func (s *organizationService) SearchSearchableOrganizations(ctx context.Context, if agentShares, err := s.agentShareRepo.ListByOrganization(ctx, org.ID); err == nil { agentShareCounts[org.ID] = len(agentShares) } - _, err := s.orgRepo.GetMember(ctx, org.ID, userID) + _, err := s.orgRepo.GetTenantMember(ctx, org.ID, tenantID) memberOrgIDs[org.ID] = (err == nil) } items := make([]types.SearchableOrganizationItem, 0, len(orgs)) @@ -269,7 +283,9 @@ func (s *organizationService) SearchSearchableOrganizations(ctx context.Context, }, nil } -// JoinByOrganizationID joins a searchable organization by ID (no invite code required) +// JoinByOrganizationID joins a searchable organization by ID (no invite +// code required). Plan 3: the *tenant* joins, with the calling user as +// representative. func (s *organizationService) JoinByOrganizationID(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.Organization, error) { org, err := s.orgRepo.GetByID(ctx, orgID) if err != nil { @@ -279,17 +295,15 @@ func (s *organizationService) JoinByOrganizationID(ctx context.Context, orgID st return nil, err } if !org.Searchable { - return nil, ErrOrgPermissionDenied // or a dedicated "org not discoverable" error + return nil, ErrOrgPermissionDenied } - _, err = s.orgRepo.GetMember(ctx, orgID, userID) + _, err = s.orgRepo.GetTenantMember(ctx, orgID, tenantID) if err == nil { - return org, nil // already member + return org, nil // tenant already member; idempotent } - // Validate requested role if provided if requestedRole != "" && !requestedRole.IsValid() { return nil, ErrInvalidRole } - // Default to viewer if not specified if requestedRole == "" { requestedRole = types.OrgRoleViewer } @@ -300,27 +314,28 @@ func (s *organizationService) JoinByOrganizationID(ctx context.Context, orgID st } return org, nil } - // Searchable direct join: do not validate invite code or expiry (product copy: no invite code required). if err := s.joinAsViewerWithChecks(ctx, org, userID, tenantID); err != nil { return nil, err } - logger.Infof(ctx, "User %s joined organization %s via searchable join", userID, org.ID) + logger.Infof(ctx, "Tenant %d joined organization %s via searchable join (rep user %s)", tenantID, org.ID, userID) return org, nil } -// DeleteOrganization deletes an organization -func (s *organizationService) DeleteOrganization(ctx context.Context, id string, userID string) error { +// DeleteOrganization deletes an organization. Only the owner user may delete. +// (We keep the user-level check here intentionally — Org ownership is +// product-defined as the user who created it, not the tenant they were +// in at the time.) +func (s *organizationService) DeleteOrganization(ctx context.Context, id string, userID string, tenantID uint64) error { org, err := s.orgRepo.GetByID(ctx, id) if err != nil { return err } - // Only owner can delete organization if org.OwnerID != userID { return ErrOrgPermissionDenied } + _ = tenantID // accepted for handler symmetry; not part of the gate - // Remove all KB shares for this org so members no longer see associated knowledge bases if err := s.shareRepo.DeleteByOrganizationID(ctx, id); err != nil { logger.Warnf(ctx, "Failed to delete KB shares for organization %s: %v", id, err) } @@ -331,8 +346,8 @@ func (s *organizationService) DeleteOrganization(ctx context.Context, id string, return s.orgRepo.Delete(ctx, id) } -// AddMember adds a member to an organization -func (s *organizationService) AddMember(ctx context.Context, orgID string, userID string, tenantID uint64, role types.OrgMemberRole) error { +// AddTenantMember enrols a tenant as a member of an organization. +func (s *organizationService) AddTenantMember(ctx context.Context, orgID string, tenantID uint64, representativeUserID string, role types.OrgMemberRole) error { if !role.IsValid() { return ErrInvalidRole } @@ -342,7 +357,7 @@ func (s *organizationService) AddMember(ctx context.Context, orgID string, userI return err } if org.MemberLimit > 0 { - count, errCount := s.orgRepo.CountMembers(ctx, orgID) + count, errCount := s.orgRepo.CountTenantMembers(ctx, orgID) if errCount != nil { return errCount } @@ -351,57 +366,60 @@ func (s *organizationService) AddMember(ctx context.Context, orgID string, userI } } - member := &types.OrganizationMember{ - ID: uuid.New().String(), - OrganizationID: orgID, - UserID: userID, - TenantID: tenantID, - Role: role, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), + now := time.Now() + member := &types.OrganizationTenantMember{ + ID: uuid.New().String(), + OrganizationID: orgID, + TenantID: tenantID, + Role: role, + RepresentativeUserID: representativeUserID, + JoinedAt: &now, + CreatedAt: now, + UpdatedAt: now, } - return s.orgRepo.AddMember(ctx, member) + return s.orgRepo.AddTenantMember(ctx, member) } -// RemoveMember removes a member from an organization. -// When operatorUserID == memberUserID, it is "leave" (self-removal) and does not require admin. -// When removing another member, operator must be admin. -func (s *organizationService) RemoveMember(ctx context.Context, orgID string, memberUserID string, operatorUserID string) error { - // Check if trying to remove owner +// RemoveTenantMember removes a tenant from an organization. +// When operatorTenantID == memberTenantID, it's "leave" (self-removal). +// Otherwise the operator's tenant must be admin in the org. +func (s *organizationService) RemoveTenantMember(ctx context.Context, orgID string, memberTenantID uint64, operatorUserID string, operatorTenantID uint64) error { org, err := s.orgRepo.GetByID(ctx, orgID) if err != nil { return err } - if org.OwnerID == memberUserID { + // Owner-tenant resolution: derive owner tenant from Organization.OwnerID's + // own tenant. If the OwnerID-user has been deleted (very rare during the + // org's lifetime) we fall through and refuse the destructive action. + if isOwnerTenant, err := s.isOwnerTenant(ctx, org, memberTenantID); err == nil && isOwnerTenant { return ErrCannotRemoveOwner } - // Self-removal (leave): allow any member to leave - if operatorUserID == memberUserID { - return s.orgRepo.RemoveMember(ctx, orgID, memberUserID) + if operatorTenantID == memberTenantID { + // Self-removal: any tenant can leave on their own behalf. + return s.orgRepo.RemoveTenantMember(ctx, orgID, memberTenantID) } - // Removing another member: require operator to be admin - isAdmin, err := s.IsOrgAdmin(ctx, orgID, operatorUserID) + isAdmin, err := s.IsTenantOrgAdmin(ctx, orgID, operatorTenantID) if err != nil { return err } if !isAdmin { return ErrOrgPermissionDenied } + _ = operatorUserID - return s.orgRepo.RemoveMember(ctx, orgID, memberUserID) + return s.orgRepo.RemoveTenantMember(ctx, orgID, memberTenantID) } -// UpdateMemberRole updates a member's role -func (s *organizationService) UpdateMemberRole(ctx context.Context, orgID string, memberUserID string, role types.OrgMemberRole, operatorUserID string) error { +// UpdateTenantMemberRole updates the role for a (org, tenant) membership. +func (s *organizationService) UpdateTenantMemberRole(ctx context.Context, orgID string, memberTenantID uint64, role types.OrgMemberRole, operatorUserID string, operatorTenantID uint64) error { if !role.IsValid() { return ErrInvalidRole } - // Check if operator is admin - isAdmin, err := s.IsOrgAdmin(ctx, orgID, operatorUserID) + isAdmin, err := s.IsTenantOrgAdmin(ctx, orgID, operatorTenantID) if err != nil { return err } @@ -409,39 +427,39 @@ func (s *organizationService) UpdateMemberRole(ctx context.Context, orgID string return ErrOrgPermissionDenied } - // Check if trying to change owner's role org, err := s.orgRepo.GetByID(ctx, orgID) if err != nil { return err } - if org.OwnerID == memberUserID { + if isOwnerTenant, err := s.isOwnerTenant(ctx, org, memberTenantID); err == nil && isOwnerTenant { return ErrCannotChangeOwnerRole } + _ = operatorUserID - return s.orgRepo.UpdateMemberRole(ctx, orgID, memberUserID, role) + return s.orgRepo.UpdateTenantMemberRole(ctx, orgID, memberTenantID, role) } -// ListMembers lists all members of an organization -func (s *organizationService) ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error) { - return s.orgRepo.ListMembers(ctx, orgID) +// ListTenantMembers lists all tenant memberships for an organization. +func (s *organizationService) ListTenantMembers(ctx context.Context, orgID string) ([]*types.OrganizationTenantMember, error) { + return s.orgRepo.ListTenantMembers(ctx, orgID) } -// GetMember gets a specific member of an organization -func (s *organizationService) GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error) { - member, err := s.orgRepo.GetMember(ctx, orgID, userID) +// GetTenantMember returns the (org, tenant) membership row. +func (s *organizationService) GetTenantMember(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationTenantMember, error) { + member, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID) if err != nil { if errors.Is(err, repository.ErrOrgMemberNotFound) { - return nil, ErrUserNotInOrg + return nil, ErrTenantNotInOrg } return nil, err } return member, nil } -// GenerateInviteCode generates a new invite code for an organization -func (s *organizationService) GenerateInviteCode(ctx context.Context, orgID string, userID string) (string, error) { - // Check if user is admin - isAdmin, err := s.IsOrgAdmin(ctx, orgID, userID) +// GenerateInviteCode generates a new invite code for an organization. +// Operator's tenant must be admin in the org. +func (s *organizationService) GenerateInviteCode(ctx context.Context, orgID string, userID string, tenantID uint64) (string, error) { + isAdmin, err := s.IsTenantOrgAdmin(ctx, orgID, tenantID) if err != nil { return "", err } @@ -458,7 +476,6 @@ func (s *organizationService) GenerateInviteCode(ctx context.Context, orgID stri if validityDays != 0 && !ValidInviteCodeValidityDays[validityDays] { validityDays = DefaultInviteCodeValidityDays } - // 0 = never expire (expiresAt nil); 1/7/30 = that many days inviteCode := generateInviteCode() now := time.Now() @@ -466,13 +483,16 @@ func (s *organizationService) GenerateInviteCode(ctx context.Context, orgID stri if err := s.orgRepo.UpdateInviteCode(ctx, orgID, inviteCode, expiresAt); err != nil { return "", err } + _ = userID return inviteCode, nil } -// joinAsViewerWithChecks adds the user as viewer when not already a member (enforces member limit). -func (s *organizationService) joinAsViewerWithChecks(ctx context.Context, org *types.Organization, userID string, tenantID uint64) error { - _, err := s.orgRepo.GetMember(ctx, org.ID, userID) +// joinAsViewerWithChecks adds the tenant as viewer when not already a +// member (enforces member limit). representativeUserID is the user +// kicking off the join; recorded for audit only. +func (s *organizationService) joinAsViewerWithChecks(ctx context.Context, org *types.Organization, representativeUserID string, tenantID uint64) error { + _, err := s.orgRepo.GetTenantMember(ctx, org.ID, tenantID) if err == nil { return nil } @@ -481,7 +501,7 @@ func (s *organizationService) joinAsViewerWithChecks(ctx context.Context, org *t } if org.MemberLimit > 0 { - count, errCount := s.orgRepo.CountMembers(ctx, org.ID) + count, errCount := s.orgRepo.CountTenantMembers(ctx, org.ID) if errCount != nil { return errCount } @@ -490,20 +510,22 @@ func (s *organizationService) joinAsViewerWithChecks(ctx context.Context, org *t } } - member := &types.OrganizationMember{ - ID: uuid.New().String(), - OrganizationID: org.ID, - UserID: userID, - TenantID: tenantID, - Role: types.OrgRoleViewer, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), + now := time.Now() + member := &types.OrganizationTenantMember{ + ID: uuid.New().String(), + OrganizationID: org.ID, + TenantID: tenantID, + Role: types.OrgRoleViewer, + RepresentativeUserID: representativeUserID, + JoinedAt: &now, + CreatedAt: now, + UpdatedAt: now, } - return s.orgRepo.AddMember(ctx, member) + return s.orgRepo.AddTenantMember(ctx, member) } -// JoinByInviteCode allows a user to join an organization via invite code +// JoinByInviteCode allows a tenant to join via invite code. func (s *organizationService) JoinByInviteCode(ctx context.Context, inviteCode string, userID string, tenantID uint64) (*types.Organization, error) { org, err := s.orgRepo.GetByInviteCode(ctx, inviteCode) if err != nil { @@ -516,7 +538,6 @@ func (s *organizationService) JoinByInviteCode(ctx context.Context, inviteCode s return nil, err } - // check if the organization need approval if org.RequireApproval { logger.Infof(ctx, "Organization %s requires approval", org.ID) return nil, ErrOrgPermissionDenied @@ -526,13 +547,13 @@ func (s *organizationService) JoinByInviteCode(ctx context.Context, inviteCode s return nil, err } - logger.Infof(ctx, "User %s joined organization %s via invite code", userID, org.ID) + logger.Infof(ctx, "Tenant %d joined organization %s via invite code (rep user %s)", tenantID, org.ID, userID) return org, nil } -// IsOrgAdmin checks if a user is an admin of an organization -func (s *organizationService) IsOrgAdmin(ctx context.Context, orgID string, userID string) (bool, error) { - member, err := s.orgRepo.GetMember(ctx, orgID, userID) +// IsTenantOrgAdmin reports whether the tenant has admin role in the org. +func (s *organizationService) IsTenantOrgAdmin(ctx context.Context, orgID string, tenantID uint64) (bool, error) { + member, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID) if err != nil { if errors.Is(err, repository.ErrOrgMemberNotFound) { return false, nil @@ -542,18 +563,33 @@ func (s *organizationService) IsOrgAdmin(ctx context.Context, orgID string, user return member.Role == types.OrgRoleAdmin, nil } -// GetUserRoleInOrg gets a user's role in an organization -func (s *organizationService) GetUserRoleInOrg(ctx context.Context, orgID string, userID string) (types.OrgMemberRole, error) { - member, err := s.orgRepo.GetMember(ctx, orgID, userID) +// GetTenantRoleInOrg gets a tenant's role in an organization. +func (s *organizationService) GetTenantRoleInOrg(ctx context.Context, orgID string, tenantID uint64) (types.OrgMemberRole, error) { + member, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID) if err != nil { if errors.Is(err, repository.ErrOrgMemberNotFound) { - return "", ErrUserNotInOrg + return "", ErrTenantNotInOrg } return "", err } return member.Role, nil } +// isOwnerTenant returns true when the given tenant is the home tenant of +// org.OwnerID. The owner tenant is undeletable / unchangeable in the +// org membership table — that lets us preserve the "owner can never be +// orphaned" invariant without adding a separate column. +func (s *organizationService) isOwnerTenant(ctx context.Context, org *types.Organization, tenantID uint64) (bool, error) { + if s.userRepo == nil || org == nil { + return false, nil + } + owner, err := s.userRepo.GetUserByID(ctx, org.OwnerID) + if err != nil || owner == nil { + return false, err + } + return owner.TenantID == tenantID, nil +} + // generateInviteCode generates a random 16-character invite code func generateInviteCode() string { bytes := make([]byte, 8) @@ -569,20 +605,20 @@ var ( ErrPendingRequestExists = errors.New("pending request already exists") ErrJoinRequestNotFound = errors.New("join request not found") ErrCannotUpgradeToSameRole = errors.New("cannot request upgrade to same or lower role") - ErrAlreadyAdmin = errors.New("user is already an admin") + ErrAlreadyAdmin = errors.New("tenant is already an admin") ) -// SubmitJoinRequest submits a request to join an organization +// SubmitJoinRequest submits a request for the caller's tenant to join an organization. +// Dedup is now per-tenant: any user from a tenant already with a pending join +// request is rejected (the same tenant can't queue two simultaneous joins). func (s *organizationService) SubmitJoinRequest(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.OrganizationJoinRequest, error) { - logger.Infof(ctx, "User %s submitting join request for organization %s", userID, orgID) + logger.Infof(ctx, "Tenant %d (rep user %s) submitting join request for organization %s", tenantID, userID, orgID) - // Check if there's already a pending join request - existing, err := s.orgRepo.GetPendingRequestByType(ctx, orgID, userID, types.JoinRequestTypeJoin) + existing, err := s.orgRepo.GetPendingRequestByTenantAndType(ctx, orgID, tenantID, types.JoinRequestTypeJoin) if err == nil && existing != nil { return nil, ErrPendingRequestExists } - // Reject if organization is already at member limit org, err := s.orgRepo.GetByID(ctx, orgID) if err != nil { if errors.Is(err, repository.ErrOrganizationNotFound) { @@ -591,7 +627,7 @@ func (s *organizationService) SubmitJoinRequest(ctx context.Context, orgID strin return nil, err } if org.MemberLimit > 0 { - count, errCount := s.orgRepo.CountMembers(ctx, orgID) + count, errCount := s.orgRepo.CountTenantMembers(ctx, orgID) if errCount != nil { return nil, errCount } @@ -600,7 +636,6 @@ func (s *organizationService) SubmitJoinRequest(ctx context.Context, orgID strin } } - // Default to viewer if role is empty or invalid if requestedRole == "" || !requestedRole.IsValid() { requestedRole = types.OrgRoleViewer } @@ -622,7 +657,7 @@ func (s *organizationService) SubmitJoinRequest(ctx context.Context, orgID strin return nil, err } - logger.Infof(ctx, "Join request %s created for organization %s by user %s", request.ID, orgID, userID) + logger.Infof(ctx, "Join request %s created for organization %s by tenant %d", request.ID, orgID, tenantID) return request, nil } @@ -637,8 +672,9 @@ func (s *organizationService) CountPendingJoinRequests(ctx context.Context, orgI } // ReviewJoinRequest reviews a join request or upgrade request (approve or reject). -// When approving, assignRole overrides the applicant's requested role if set; otherwise uses request.RequestedRole or viewer. -func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID string, requestID string, approved bool, reviewerID string, message string, assignRole *types.OrgMemberRole) error { +// On approve the targeted tenant gets the assigned role; reviewerTenantID is +// only used for audit (the gate is the route-level Admin guard). +func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID string, requestID string, approved bool, reviewerID string, reviewerTenantID uint64, message string, assignRole *types.OrgMemberRole) error { request, err := s.orgRepo.GetJoinRequestByID(ctx, requestID) if err != nil { return ErrJoinRequestNotFound @@ -655,7 +691,6 @@ func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID strin if approved { status = types.JoinRequestStatusApproved - // Role to assign: admin override > applicant's requested role > viewer role := types.OrgRoleViewer if assignRole != nil && assignRole.IsValid() { role = *assignRole @@ -663,21 +698,18 @@ func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID strin role = request.RequestedRole } - // Handle based on request type if request.RequestType == types.JoinRequestTypeUpgrade { - // Upgrade: update existing member's role - if err := s.orgRepo.UpdateMemberRole(ctx, request.OrganizationID, request.UserID, role); err != nil { + if err := s.orgRepo.UpdateTenantMemberRole(ctx, request.OrganizationID, request.TenantID, role); err != nil { return err } - logger.Infof(ctx, "Upgrade request %s approved, user %s role updated to %s in organization %s", requestID, request.UserID, role, request.OrganizationID) + logger.Infof(ctx, "Upgrade request %s approved, tenant %d role updated to %s in organization %s", requestID, request.TenantID, role, request.OrganizationID) } else { - // Join: check member limit then add new member org, errOrg := s.orgRepo.GetByID(ctx, request.OrganizationID) if errOrg != nil { return errOrg } if org.MemberLimit > 0 { - count, errCount := s.orgRepo.CountMembers(ctx, request.OrganizationID) + count, errCount := s.orgRepo.CountTenantMembers(ctx, request.OrganizationID) if errCount != nil { return errCount } @@ -685,58 +717,56 @@ func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID strin return ErrOrgMemberLimitReached } } - member := &types.OrganizationMember{ - ID: uuid.New().String(), - OrganizationID: request.OrganizationID, - UserID: request.UserID, - TenantID: request.TenantID, - Role: role, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), + now := time.Now() + member := &types.OrganizationTenantMember{ + ID: uuid.New().String(), + OrganizationID: request.OrganizationID, + TenantID: request.TenantID, + Role: role, + RepresentativeUserID: request.UserID, + JoinedAt: &now, + CreatedAt: now, + UpdatedAt: now, } - if err := s.orgRepo.AddMember(ctx, member); err != nil { + if err := s.orgRepo.AddTenantMember(ctx, member); err != nil { return err } - logger.Infof(ctx, "Join request %s approved, user %s added to organization %s with role %s", requestID, request.UserID, request.OrganizationID, role) + logger.Infof(ctx, "Join request %s approved, tenant %d added to organization %s with role %s", requestID, request.TenantID, request.OrganizationID, role) } } else { status = types.JoinRequestStatusRejected - logger.Infof(ctx, "Request %s rejected for user %s", requestID, request.UserID) + logger.Infof(ctx, "Request %s rejected for tenant %d", requestID, request.TenantID) } + _ = reviewerTenantID return s.orgRepo.UpdateJoinRequestStatus(ctx, requestID, status, reviewerID, message) } -// RequestRoleUpgrade submits a request to upgrade role in an organization +// RequestRoleUpgrade submits a request to upgrade the caller's tenant's role. func (s *organizationService) RequestRoleUpgrade(ctx context.Context, orgID string, userID string, tenantID uint64, requestedRole types.OrgMemberRole, message string) (*types.OrganizationJoinRequest, error) { - logger.Infof(ctx, "User %s submitting role upgrade request for organization %s to role %s", userID, orgID, requestedRole) + logger.Infof(ctx, "Tenant %d (rep user %s) requesting role upgrade for organization %s to role %s", tenantID, userID, orgID, requestedRole) - // Check if user is a member - member, err := s.orgRepo.GetMember(ctx, orgID, userID) + member, err := s.orgRepo.GetTenantMember(ctx, orgID, tenantID) if err != nil { if errors.Is(err, repository.ErrOrgMemberNotFound) { - return nil, ErrUserNotInOrg + return nil, ErrTenantNotInOrg } return nil, err } - // Validate the requested role if !requestedRole.IsValid() { return nil, ErrInvalidRole } - // Check if already admin if member.Role == types.OrgRoleAdmin { return nil, ErrAlreadyAdmin } - // Check if requested role is higher than current role if !requestedRole.HasPermission(member.Role) || requestedRole == member.Role { return nil, ErrCannotUpgradeToSameRole } - // Check if there's already a pending upgrade request - existing, err := s.orgRepo.GetPendingRequestByType(ctx, orgID, userID, types.JoinRequestTypeUpgrade) + existing, err := s.orgRepo.GetPendingRequestByTenantAndType(ctx, orgID, tenantID, types.JoinRequestTypeUpgrade) if err == nil && existing != nil { return nil, ErrPendingRequestExists } @@ -759,13 +789,13 @@ func (s *organizationService) RequestRoleUpgrade(ctx context.Context, orgID stri return nil, err } - logger.Infof(ctx, "Role upgrade request %s created for organization %s by user %s (from %s to %s)", request.ID, orgID, userID, member.Role, requestedRole) + logger.Infof(ctx, "Role upgrade request %s created for organization %s by tenant %d (from %s to %s)", request.ID, orgID, tenantID, member.Role, requestedRole) return request, nil } -// GetPendingUpgradeRequest gets a pending upgrade request for a user in an organization -func (s *organizationService) GetPendingUpgradeRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error) { - request, err := s.orgRepo.GetPendingRequestByType(ctx, orgID, userID, types.JoinRequestTypeUpgrade) +// GetPendingUpgradeRequest gets a pending upgrade request for a tenant in an organization +func (s *organizationService) GetPendingUpgradeRequest(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationJoinRequest, error) { + request, err := s.orgRepo.GetPendingRequestByTenantAndType(ctx, orgID, tenantID, types.JoinRequestTypeUpgrade) if err != nil { if errors.Is(err, repository.ErrJoinRequestNotFound) { return nil, ErrJoinRequestNotFound diff --git a/internal/application/service/session_knowledge_qa.go b/internal/application/service/session_knowledge_qa.go index eddeb3b3..419b7852 100644 --- a/internal/application/service/session_knowledge_qa.go +++ b/internal/application/service/session_knowledge_qa.go @@ -389,7 +389,8 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent( userIDVal := ctx.Value(types.UserIDContextKey) if userIDVal != nil { if userID, ok := userIDVal.(string); ok && userID != "" && s.kbShareService != nil { - sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, userID, tenantID) + callerTenantRole := types.TenantRoleFromContext(ctx) + sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, tenantID, callerTenantRole) if err != nil { logger.Warnf(ctx, "Failed to list shared knowledge bases: %v", err) } else { @@ -455,6 +456,7 @@ func (s *sessionService) buildSearchTargets( fullKBSet := make(map[string]bool) // First pass: batch-fetch KBs, then resolve tenant per ID (tenant scope already set by caller) + callerTenantRole := types.TenantRoleFromContext(ctx) if len(knowledgeBaseIDs) > 0 { kbs, _ := s.knowledgeBaseService.GetKnowledgeBasesByIDsOnly(ctx, knowledgeBaseIDs) kbByID := make(map[string]*types.KnowledgeBase, len(kbs)) @@ -472,7 +474,7 @@ func (s *sessionService) buildSearchTargets( } else if kb.TenantID == tenantID { kbTenantMap[kbID] = tenantID } else if s.kbShareService != nil && userID != "" { - hasAccess, _ := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer) + hasAccess, _ := s.kbShareService.HasTenantKBPermission(ctx, kbID, tenantID, callerTenantRole, types.OrgRoleViewer) if hasAccess { kbTenantMap[kbID] = kb.TenantID } else { diff --git a/internal/application/service/tag.go b/internal/application/service/tag.go index 83c13daa..b288e32d 100644 --- a/internal/application/service/tag.go +++ b/internal/application/service/tag.go @@ -84,10 +84,11 @@ func (s *knowledgeTagService) ListTags( if userIDVal == nil { return nil, werrors.NewForbiddenError("无权访问该知识库") } - userID := userIDVal.(string) + _ = userIDVal.(string) + callerTenantRole := types.TenantRoleFromContext(ctx) - // Check if user has at least viewer permission through organization sharing - hasPermission, err := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer) + // Check whether the caller's tenant has at least viewer permission via org sharing. + hasPermission, err := s.kbShareService.HasTenantKBPermission(ctx, kbID, tenantID, callerTenantRole, types.OrgRoleViewer) if err != nil || !hasPermission { return nil, werrors.NewForbiddenError("无权访问该知识库") } diff --git a/internal/handler/chunk.go b/internal/handler/chunk.go index 551548e2..99b2dca9 100644 --- a/internal/handler/chunk.go +++ b/internal/handler/chunk.go @@ -34,6 +34,7 @@ func (h *ChunkHandler) effectiveCtxForKnowledge(c *gin.Context, knowledgeID stri return nil, errors.NewUnauthorizedError("Unauthorized") } userID, userExists := c.Get(types.UserIDContextKey.String()) + callerTenantRole := types.TenantRoleFromContext(ctx) knowledge, err := h.kgService.GetKnowledgeByIDOnly(ctx, knowledgeID) if err != nil { @@ -46,7 +47,7 @@ func (h *ChunkHandler) effectiveCtxForKnowledge(c *gin.Context, knowledgeID stri return nil, errors.NewForbiddenError("Permission denied to access this knowledge") } if h.kbShareService != nil { - permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, knowledge.KnowledgeBaseID, userID.(string)) + permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, knowledge.KnowledgeBaseID, tenantID, callerTenantRole) if permErr == nil && isShared { if !permission.HasPermission(requiredPermission) { return nil, errors.NewForbiddenError("Insufficient permission for this operation") @@ -56,11 +57,12 @@ func (h *ChunkHandler) effectiveCtxForKnowledge(c *gin.Context, knowledgeID stri } if requiredPermission == types.OrgRoleViewer && h.agentShareService != nil { kbRef := &types.KnowledgeBase{ID: knowledge.KnowledgeBaseID, TenantID: knowledge.TenantID} - can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kbRef) + can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kbRef) if err == nil && can { return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil } } + _ = userID return nil, errors.NewForbiddenError("Permission denied to access this knowledge") } diff --git a/internal/handler/faq.go b/internal/handler/faq.go index 11a0f6ff..7070349b 100644 --- a/internal/handler/faq.go +++ b/internal/handler/faq.go @@ -47,6 +47,7 @@ func (h *FAQHandler) effectiveCtxForKB(c *gin.Context, kbID string, requiredPerm return nil, errors.NewUnauthorizedError("Unauthorized") } userID, userExists := c.Get(types.UserIDContextKey.String()) + callerTenantRole := types.TenantRoleFromContext(ctx) kbID = secutils.SanitizeForLog(kbID) if kbID == "" { return nil, errors.NewBadRequestError("Knowledge base ID cannot be empty") @@ -67,24 +68,26 @@ func (h *FAQHandler) effectiveCtxForKB(c *gin.Context, kbID string, requiredPerm if kb.TenantID == tenantID { return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil } - if userExists && h.kbShareService != nil { - permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string)) + if h.kbShareService != nil { + permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, kbID, tenantID, callerTenantRole) if permErr == nil && isShared && permission.HasPermission(requiredPermission) { sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID) if srcErr == nil { - logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d", - userID.(string), kbID, permission, sourceTenantID) + logger.Infof(ctx, "Tenant %d accessing shared KB %s with permission %s, source tenant: %d", + tenantID, kbID, permission, sourceTenantID) return context.WithValue(ctx, types.TenantIDContextKey, sourceTenantID), nil } } } - if requiredPermission == types.OrgRoleViewer && userExists && h.agentShareService != nil { - can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb) + if requiredPermission == types.OrgRoleViewer && h.agentShareService != nil { + can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kb) if err == nil && can { - logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID) + logger.Infof(ctx, "Tenant %d accessing KB %s via some shared agent", tenantID, kbID) return context.WithValue(ctx, types.TenantIDContextKey, kb.TenantID), nil } } + _ = userID + _ = userExists logger.Warnf(ctx, "Permission denied to access KB %s", kbID) return nil, errors.NewForbiddenError("Permission denied to access this knowledge base") } diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.go index 7d88b6e0..a6821029 100644 --- a/internal/handler/knowledge.go +++ b/internal/handler/knowledge.go @@ -70,6 +70,7 @@ func (h *KnowledgeHandler) validateKnowledgeBaseAccessWithKBID(c *gin.Context, k return nil, "", 0, "", errors.NewUnauthorizedError("Unauthorized") } userID, userExists := c.Get(types.UserIDContextKey.String()) + callerTenantRole := types.TenantRoleFromContext(ctx) kbID = secutils.SanitizeForLog(kbID) if kbID == "" { return nil, "", 0, "", errors.NewBadRequestError("Knowledge base ID cannot be empty") @@ -89,24 +90,26 @@ func (h *KnowledgeHandler) validateKnowledgeBaseAccessWithKBID(c *gin.Context, k if kb.TenantID == tenantID { return kb, kbID, tenantID, types.OrgRoleAdmin, nil } - if userExists && h.kbShareService != nil { - permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string)) + if h.kbShareService != nil { + permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, kbID, tenantID, callerTenantRole) if permErr == nil && isShared { sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID) if srcErr == nil { - logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d", - userID.(string), kbID, permission, sourceTenantID) + logger.Infof(ctx, "Tenant %d accessing shared KB %s with permission %s, source tenant: %d", + tenantID, kbID, permission, sourceTenantID) return kb, kbID, sourceTenantID, permission, nil } } } - if userExists && h.agentShareService != nil { - can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb) + if h.agentShareService != nil { + can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kb) if err == nil && can { - logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID) + logger.Infof(ctx, "Tenant %d accessing KB %s via some shared agent", tenantID, kbID) return kb, kbID, kb.TenantID, types.OrgRoleViewer, nil } } + _ = userID + _ = userExists logger.Warnf(ctx, "Permission denied to access KB %s, tenant ID: %d, KB tenant: %d", kbID, tenantID, kb.TenantID) return nil, kbID, 0, "", errors.NewForbiddenError("Permission denied to access this knowledge base") } @@ -120,6 +123,7 @@ func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, k return nil, ctx, errors.NewUnauthorizedError("Unauthorized") } userID, userExists := c.Get(types.UserIDContextKey.String()) + callerTenantRole := types.TenantRoleFromContext(ctx) knowledge, err := h.kgService.GetKnowledgeByIDOnly(ctx, knowledgeID) if err != nil { @@ -132,18 +136,18 @@ func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, k } // Shared KB: check organization permission - if userExists && h.kbShareService != nil { - permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, knowledge.KnowledgeBaseID, userID.(string)) + if h.kbShareService != nil { + permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, knowledge.KnowledgeBaseID, tenantID, callerTenantRole) if permErr == nil && isShared && permission.HasPermission(requiredPermission) { effectiveTenantID := knowledge.TenantID return knowledge, context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID), nil } } // Shared agent: request passes agent_id, or user has any shared agent that can access this KB - if userExists && h.agentShareService != nil && requiredPermission == types.OrgRoleViewer { + if h.agentShareService != nil && requiredPermission == types.OrgRoleViewer { agentID := c.Query("agent_id") if agentID != "" { - agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID.(string), tenantID, agentID) + agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, tenantID, callerTenantRole, agentID) if err == nil && agent != nil { if knowledge.TenantID != agent.TenantID { return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge") @@ -166,12 +170,14 @@ func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, k } } else { kbRef := &types.KnowledgeBase{ID: knowledge.KnowledgeBaseID, TenantID: knowledge.TenantID} - can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kbRef) + can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kbRef) if err == nil && can { return knowledge, context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil } } } + _ = userID + _ = userExists return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge") } @@ -1083,12 +1089,14 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) { c.Error(errors.NewUnauthorizedError("Unauthorized")) return } - agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, agentID) + callerTenantRole := types.TenantRoleFromContext(ctx) + agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID) if err != nil || agent == nil { logger.Warnf(ctx, "GetKnowledgeBatch: invalid or inaccessible shared agent %s: %v", agentID, err) c.Error(errors.NewForbiddenError("Invalid or inaccessible shared agent").WithDetails(err.Error())) return } + _ = userID effectiveTenantID = agent.TenantID agentAllowedKBIDs = resolveAgentAllowedKBIDs(agent) @@ -1509,13 +1517,14 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) { c.Error(errors.NewUnauthorizedError("user ID not found")) return } - userID, _ := userIDVal.(string) + _ = userIDVal currentTenantID := c.GetUint64(types.TenantIDContextKey.String()) if currentTenantID == 0 { c.Error(errors.NewUnauthorizedError("tenant ID not found")) return } - agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, agentID) + callerTenantRole := types.TenantRoleFromContext(ctx) + agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID) if err != nil { if goerrors.Is(err, service.ErrAgentShareNotFound) || goerrors.Is(err, service.ErrAgentSharePermission) || goerrors.Is(err, service.ErrAgentNotFoundForShare) { c.Error(errors.NewForbiddenError("no permission for this shared agent")) diff --git a/internal/handler/knowledgebase.go b/internal/handler/knowledgebase.go index fdfc5550..08717c53 100644 --- a/internal/handler/knowledgebase.go +++ b/internal/handler/knowledgebase.go @@ -270,6 +270,7 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ // Get user ID from context (needed for shared KB permission check) userID, userExists := c.Get(types.UserIDContextKey.String()) + callerTenantRole := types.TenantRoleFromContext(ctx) // Get knowledge base ID from URL parameter id := secutils.SanitizeForLog(c.Param("id")) @@ -299,26 +300,26 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ } // Check 2: If not owner, check organization shared access - if userExists && h.kbShareService != nil { - // Check if user has shared access through organization - permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, id, userID.(string)) + if h.kbShareService != nil { + // Check if caller's tenant has shared access through organization + permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, id, tenantID.(uint64), callerTenantRole) if permErr == nil && isShared { - // User has shared access, get the source tenant ID for embedding queries + // Tenant has shared access, get the source tenant ID for embedding queries sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, id) if srcErr == nil { - logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d", - userID.(string), id, permission, sourceTenantID) + logger.Infof(ctx, "Tenant %d accessing shared KB %s with permission %s, source tenant: %d", + tenantID.(uint64), id, permission, sourceTenantID) return kb, id, sourceTenantID, permission, nil } } } - // Check 3: Shared agent — allow if request has agent_id (and agent can access this KB) OR user has any shared agent that can access this KB (e.g. opened from "通过智能体可见" list without agent_id) - if userExists && h.agentShareService != nil { + // Check 3: Shared agent — allow if request has agent_id (and agent can access this KB) OR caller's tenant has any shared agent that can access this KB (e.g. opened from "通过智能体可见" list without agent_id) + if h.agentShareService != nil { currentTenantID := tenantID.(uint64) agentID := c.Query("agent_id") if agentID != "" { - agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID.(string), currentTenantID, agentID) + agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID) if err == nil && agent != nil { if kb.TenantID != agent.TenantID { logger.Warnf(ctx, "Shared agent tenant mismatch, KB %s tenant: %d, agent tenant: %d", id, kb.TenantID, agent.TenantID) @@ -327,12 +328,12 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ if mode == "none" { // no-op, fall through } else if mode == "all" { - logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=all)", userID.(string), id, agentID) + logger.Infof(ctx, "Tenant %d accessing KB %s via shared agent %s (mode=all)", currentTenantID, id, agentID) return kb, id, kb.TenantID, types.OrgRoleViewer, nil } else if mode == "selected" { for _, allowedID := range agent.Config.KnowledgeBases { if allowedID == id { - logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=selected)", userID.(string), id, agentID) + logger.Infof(ctx, "Tenant %d accessing KB %s via shared agent %s (mode=selected)", currentTenantID, id, agentID) return kb, id, kb.TenantID, types.OrgRoleViewer, nil } } @@ -340,14 +341,16 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ } } } else { - // No agent_id in query: allow if user has any shared agent that can access this KB (e.g. from space list "通过智能体可见") - can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), currentTenantID, kb) + // No agent_id in query: allow if caller's tenant has any shared agent that can access this KB (e.g. from space list "通过智能体可见") + can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, currentTenantID, callerTenantRole, kb) if err == nil && can { - logger.Infof(ctx, "User %s accessing KB %s via some shared agent (no agent_id in query)", userID.(string), id) + logger.Infof(ctx, "Tenant %d accessing KB %s via some shared agent (no agent_id in query)", currentTenantID, id) return kb, id, kb.TenantID, types.OrgRoleViewer, nil } } } + _ = userID + _ = userExists // No permission: not owner and no shared access logger.Warnf( @@ -416,13 +419,14 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) { c.Error(apperrors.NewUnauthorizedError("user ID not found")) return } - userID, _ := userIDVal.(string) + _ = userIDVal currentTenantID := c.GetUint64(types.TenantIDContextKey.String()) if currentTenantID == 0 { c.Error(apperrors.NewUnauthorizedError("tenant ID not found")) return } - agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, agentID) + callerTenantRole := types.TenantRoleFromContext(ctx) + agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID) if err != nil { if stderrors.Is(err, service.ErrAgentShareNotFound) || stderrors.Is(err, service.ErrAgentSharePermission) || stderrors.Is(err, service.ErrAgentNotFoundForShare) { c.Error(apperrors.NewForbiddenError("no permission for this shared agent")) diff --git a/internal/handler/organization.go b/internal/handler/organization.go index 97ec6cd3..d00a8a21 100644 --- a/internal/handler/organization.go +++ b/internal/handler/organization.go @@ -122,10 +122,10 @@ func (h *OrganizationHandler) GetOrganization(c *gin.Context) { }) } -// ListMyOrganizations lists organizations that the current user belongs to. +// ListMyOrganizations lists organizations that the current tenant belongs to. // Response includes resource_counts (per-org KB/agent counts) for list sidebar so frontend does not need a separate GET /me/resource-counts. // @Summary 获取我的组织列表 -// @Description 获取当前用户所属的所有组织,并附带各空间内知识库/智能体数量 +// @Description 获取当前租户所属的所有组织,并附带各空间内知识库/智能体数量 // @Tags 组织管理 // @Produce json // @Success 200 {object} types.ListOrganizationsResponse @@ -136,7 +136,7 @@ func (h *OrganizationHandler) ListMyOrganizations(c *gin.Context) { userID := c.GetString(types.UserIDContextKey.String()) tenantID := c.GetUint64(types.TenantIDContextKey.String()) - orgs, err := h.orgService.ListUserOrganizations(ctx, userID) + orgs, err := h.orgService.ListTenantOrganizations(ctx, tenantID) if err != nil { logger.Errorf(ctx, "Failed to list organizations: %v", err) c.Error(apperrors.NewInternalServerError("Failed to list organizations").WithDetails(err.Error())) @@ -184,16 +184,18 @@ func (h *OrganizationHandler) buildResourceCountsByOrg(ctx context.Context, orgs logger.Warnf(ctx, "buildResourceCountsByOrg CountByOrganizations: %v", err) return nil } - directKBIDsByOrg, err := h.shareService.ListSharedKnowledgeBaseIDsByOrganizations(ctx, orgIDs, userID) + directKBIDsByOrg, err := h.shareService.ListSharedKnowledgeBaseIDsByOrganizations(ctx, orgIDs, tenantID) if err != nil { logger.Warnf(ctx, "buildResourceCountsByOrg ListSharedKnowledgeBaseIDsByOrganizations: %v", err) return nil } - agentListByOrg, err := h.agentShareService.ListSharedAgentsInOrganizations(ctx, orgIDs, userID, tenantID) + callerTenantRole := types.TenantRoleFromContext(ctx) + agentListByOrg, err := h.agentShareService.ListSharedAgentsInOrganizations(ctx, orgIDs, tenantID, callerTenantRole) if err != nil { logger.Warnf(ctx, "buildResourceCountsByOrg ListSharedAgentsInOrganizations: %v", err) return nil } + _ = userID byOrgKB := make(map[string]int) tenantKBCache := make(map[uint64][]string) // cache ListKnowledgeBasesByTenantID by tenantID for _, o := range orgs { @@ -286,6 +288,7 @@ func (h *OrganizationHandler) UpdateOrganization(c *gin.Context) { orgID := c.Param("id") userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) var req types.UpdateOrganizationRequest if err := c.ShouldBindJSON(&req); err != nil { @@ -293,7 +296,7 @@ func (h *OrganizationHandler) UpdateOrganization(c *gin.Context) { return } - org, err := h.orgService.UpdateOrganization(ctx, orgID, userID, &req) + org, err := h.orgService.UpdateOrganization(ctx, orgID, userID, tenantID, &req) if err != nil { logger.Errorf(ctx, "Failed to update organization: %v", err) if errors.Is(err, service.ErrInvalidValidityDays) { @@ -328,8 +331,9 @@ func (h *OrganizationHandler) DeleteOrganization(c *gin.Context) { orgID := c.Param("id") userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) - if err := h.orgService.DeleteOrganization(ctx, orgID, userID); err != nil { + if err := h.orgService.DeleteOrganization(ctx, orgID, userID, tenantID); err != nil { logger.Errorf(ctx, "Failed to delete organization: %v", err) c.Error(apperrors.NewForbiddenError("Permission denied or organization not found")) return @@ -341,9 +345,9 @@ func (h *OrganizationHandler) DeleteOrganization(c *gin.Context) { }) } -// ListMembers lists all members of an organization +// ListMembers lists all tenant-members of an organization // @Summary 获取组织成员列表 -// @Description 获取组织的所有成员 +// @Description 获取组织的所有成员(按租户) // @Tags 组织管理 // @Produce json // @Param id path string true "组织ID" @@ -355,7 +359,7 @@ func (h *OrganizationHandler) ListMembers(c *gin.Context) { orgID := c.Param("id") - members, err := h.orgService.ListMembers(ctx, orgID) + members, err := h.orgService.ListTenantMembers(ctx, orgID) if err != nil { logger.Errorf(ctx, "Failed to list members: %v", err) c.Error(apperrors.NewInternalServerError("Failed to list members").WithDetails(err.Error())) @@ -366,15 +370,15 @@ func (h *OrganizationHandler) ListMembers(c *gin.Context) { for _, m := range members { resp := types.OrganizationMemberResponse{ ID: m.ID, - UserID: m.UserID, + UserID: m.RepresentativeUserID, Role: string(m.Role), TenantID: m.TenantID, JoinedAt: m.CreatedAt, } - if m.User != nil { - resp.Username = m.User.Username - resp.Email = m.User.Email - resp.Avatar = m.User.Avatar + if m.RepresentativeUser != nil { + resp.Username = m.RepresentativeUser.Username + resp.Email = m.RepresentativeUser.Email + resp.Avatar = m.RepresentativeUser.Avatar } response = append(response, resp) } @@ -388,25 +392,31 @@ func (h *OrganizationHandler) ListMembers(c *gin.Context) { }) } -// UpdateMemberRole updates a member's role +// UpdateMemberRole updates a tenant-member's role // @Summary 更新成员角色 -// @Description 更新组织成员的角色(需要管理员权限) +// @Description 更新组织成员(租户)的角色(需要管理员权限) // @Tags 组织管理 // @Accept json // @Produce json -// @Param id path string true "组织ID" -// @Param user_id path string true "用户ID" -// @Param request body types.UpdateMemberRoleRequest true "角色信息" +// @Param id path string true "组织ID" +// @Param tenant_id path string true "成员租户ID" +// @Param request body types.UpdateMemberRoleRequest true "角色信息" // @Success 200 {object} map[string]interface{} // @Failure 403 {object} apperrors.AppError // @Security Bearer -// @Router /organizations/{id}/members/{user_id} [put] +// @Router /organizations/{id}/members/{tenant_id} [put] func (h *OrganizationHandler) UpdateMemberRole(c *gin.Context) { ctx := c.Request.Context() orgID := c.Param("id") - memberUserID := c.Param("user_id") + memberTenantIDStr := c.Param("tenant_id") + memberTenantID, err := strconv.ParseUint(memberTenantIDStr, 10, 64) + if err != nil { + c.Error(apperrors.NewValidationError("Invalid tenant ID")) + return + } operatorUserID := c.GetString(types.UserIDContextKey.String()) + operatorTenantID := c.GetUint64(types.TenantIDContextKey.String()) var req types.UpdateMemberRoleRequest if err := c.ShouldBindJSON(&req); err != nil { @@ -414,7 +424,7 @@ func (h *OrganizationHandler) UpdateMemberRole(c *gin.Context) { return } - if err := h.orgService.UpdateMemberRole(ctx, orgID, memberUserID, req.Role, operatorUserID); err != nil { + if err := h.orgService.UpdateTenantMemberRole(ctx, orgID, memberTenantID, req.Role, operatorUserID, operatorTenantID); err != nil { logger.Errorf(ctx, "Failed to update member role: %v", err) c.Error(apperrors.NewForbiddenError("Permission denied or invalid operation")) return @@ -426,24 +436,30 @@ func (h *OrganizationHandler) UpdateMemberRole(c *gin.Context) { }) } -// RemoveMember removes a member from an organization +// RemoveMember removes a tenant-member from an organization // @Summary 移除成员 -// @Description 从组织中移除成员(需要管理员权限) +// @Description 从组织中移除成员租户(需要管理员权限) // @Tags 组织管理 -// @Param id path string true "组织ID" -// @Param user_id path string true "用户ID" +// @Param id path string true "组织ID" +// @Param tenant_id path string true "成员租户ID" // @Success 200 {object} map[string]interface{} // @Failure 403 {object} apperrors.AppError // @Security Bearer -// @Router /organizations/{id}/members/{user_id} [delete] +// @Router /organizations/{id}/members/{tenant_id} [delete] func (h *OrganizationHandler) RemoveMember(c *gin.Context) { ctx := c.Request.Context() orgID := c.Param("id") - memberUserID := c.Param("user_id") + memberTenantIDStr := c.Param("tenant_id") + memberTenantID, err := strconv.ParseUint(memberTenantIDStr, 10, 64) + if err != nil { + c.Error(apperrors.NewValidationError("Invalid tenant ID")) + return + } operatorUserID := c.GetString(types.UserIDContextKey.String()) + operatorTenantID := c.GetUint64(types.TenantIDContextKey.String()) - if err := h.orgService.RemoveMember(ctx, orgID, memberUserID, operatorUserID); err != nil { + if err := h.orgService.RemoveTenantMember(ctx, orgID, memberTenantID, operatorUserID, operatorTenantID); err != nil { logger.Errorf(ctx, "Failed to remove member: %v", err) c.Error(apperrors.NewForbiddenError("Permission denied or invalid operation")) return @@ -470,8 +486,9 @@ func (h *OrganizationHandler) GenerateInviteCode(c *gin.Context) { orgID := c.Param("id") userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) - code, err := h.orgService.GenerateInviteCode(ctx, orgID, userID) + code, err := h.orgService.GenerateInviteCode(ctx, orgID, userID, tenantID) if err != nil { logger.Errorf(ctx, "Failed to generate invite code: %v", err) c.Error(apperrors.NewForbiddenError("Permission denied")) @@ -498,7 +515,7 @@ func (h *OrganizationHandler) PreviewByInviteCode(c *gin.Context) { ctx := c.Request.Context() inviteCode := c.Param("code") - userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) // Get organization by invite code org, err := h.orgService.GetOrganizationByInviteCode(ctx, inviteCode) @@ -508,7 +525,7 @@ func (h *OrganizationHandler) PreviewByInviteCode(c *gin.Context) { } // Get member count - members, _ := h.orgService.ListMembers(ctx, org.ID) + members, _ := h.orgService.ListTenantMembers(ctx, org.ID) memberCount := len(members) // Get shared knowledge bases count @@ -518,8 +535,8 @@ func (h *OrganizationHandler) PreviewByInviteCode(c *gin.Context) { agentShares, _ := h.agentShareService.ListSharesByOrganization(ctx, org.ID) agentShareCount := len(agentShares) - // Check if user is already a member - _, memberErr := h.orgService.GetMember(ctx, org.ID, userID) + // Check if caller's tenant is already a member + _, memberErr := h.orgService.GetTenantMember(ctx, org.ID, tenantID) isAlreadyMember := memberErr == nil c.JSON(http.StatusOK, gin.H{ @@ -616,10 +633,10 @@ func (h *OrganizationHandler) SubmitJoinRequest(c *gin.Context) { return } - // Check if user is already a member - _, memberErr := h.orgService.GetMember(ctx, org.ID, userID) + // Check if caller's tenant is already a member + _, memberErr := h.orgService.GetTenantMember(ctx, org.ID, tenantID) if memberErr == nil { - c.Error(apperrors.NewValidationError("You are already a member of this organization")) + c.Error(apperrors.NewValidationError("Your tenant is already a member of this organization")) return } @@ -665,7 +682,7 @@ func (h *OrganizationHandler) SubmitJoinRequest(c *gin.Context) { // @Router /organizations/search [get] func (h *OrganizationHandler) SearchOrganizations(c *gin.Context) { ctx := c.Request.Context() - userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) query := c.Query("q") limit := 20 if l := c.Query("limit"); l != "" { @@ -673,7 +690,7 @@ func (h *OrganizationHandler) SearchOrganizations(c *gin.Context) { limit = n } } - resp, err := h.orgService.SearchSearchableOrganizations(ctx, userID, query, limit) + resp, err := h.orgService.SearchSearchableOrganizations(ctx, tenantID, query, limit) if err != nil { logger.Errorf(ctx, "Failed to search organizations: %v", err) c.Error(apperrors.NewInternalServerError("Failed to search organizations")) @@ -816,6 +833,7 @@ func (h *OrganizationHandler) LeaveOrganization(c *gin.Context) { orgID := c.Param("id") userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) // Check if user is the owner org, err := h.orgService.GetOrganization(ctx, orgID) @@ -829,8 +847,8 @@ func (h *OrganizationHandler) LeaveOrganization(c *gin.Context) { return } - // Remove the user from the organization - if err := h.orgService.RemoveMember(ctx, orgID, userID, userID); err != nil { + // Remove the caller's tenant from the organization (self-leave) + if err := h.orgService.RemoveTenantMember(ctx, orgID, tenantID, userID, tenantID); err != nil { logger.Errorf(ctx, "Failed to leave organization: %v", err) c.Error(apperrors.NewInternalServerError("Failed to leave organization")) return @@ -856,10 +874,10 @@ func (h *OrganizationHandler) ListJoinRequests(c *gin.Context) { ctx := c.Request.Context() orgID := c.Param("id") - userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) - // Check admin - isAdmin, err := h.orgService.IsOrgAdmin(ctx, orgID, userID) + // Check admin: caller's tenant must be admin in the org + isAdmin, err := h.orgService.IsTenantOrgAdmin(ctx, orgID, tenantID) if err != nil || !isAdmin { c.Error(apperrors.NewForbiddenError("Only organization admins can view join requests")) return @@ -928,9 +946,10 @@ func (h *OrganizationHandler) ReviewJoinRequest(c *gin.Context) { orgID := c.Param("id") requestID := c.Param("request_id") userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) - // Check admin - isAdmin, err := h.orgService.IsOrgAdmin(ctx, orgID, userID) + // Check admin: caller's tenant must be admin in the org + isAdmin, err := h.orgService.IsTenantOrgAdmin(ctx, orgID, tenantID) if err != nil || !isAdmin { c.Error(apperrors.NewForbiddenError("Only organization admins can review join requests")) return @@ -950,7 +969,7 @@ func (h *OrganizationHandler) ReviewJoinRequest(c *gin.Context) { assignRole = &req.Role } - if err := h.orgService.ReviewJoinRequest(ctx, orgID, requestID, req.Approved, userID, req.Message, assignRole); err != nil { + if err := h.orgService.ReviewJoinRequest(ctx, orgID, requestID, req.Approved, userID, tenantID, req.Message, assignRole); err != nil { logger.Errorf(ctx, "Failed to review join request: %v", err) if errors.Is(err, service.ErrOrgMemberLimitReached) { c.Error(apperrors.NewValidationError("空间成员已满,无法通过该加入申请")) @@ -1090,6 +1109,7 @@ func (h *OrganizationHandler) UpdateSharePermission(c *gin.Context) { shareID := c.Param("share_id") userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) var req types.UpdateSharePermissionRequest if err := c.ShouldBindJSON(&req); err != nil { @@ -1097,7 +1117,7 @@ func (h *OrganizationHandler) UpdateSharePermission(c *gin.Context) { return } - if err := h.shareService.UpdateSharePermission(ctx, shareID, req.Permission, userID); err != nil { + if err := h.shareService.UpdateSharePermission(ctx, shareID, req.Permission, userID, tenantID); err != nil { logger.Errorf(ctx, "Failed to update share permission: %v", err) c.Error(apperrors.NewForbiddenError("Permission denied")) return @@ -1124,8 +1144,9 @@ func (h *OrganizationHandler) RemoveShare(c *gin.Context) { shareID := c.Param("share_id") userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) - if err := h.shareService.RemoveShare(ctx, shareID, userID); err != nil { + if err := h.shareService.RemoveShare(ctx, shareID, userID, tenantID); err != nil { logger.Errorf(ctx, "Failed to remove share: %v", err) c.Error(apperrors.NewForbiddenError("Permission denied")) return @@ -1150,12 +1171,12 @@ func (h *OrganizationHandler) ListOrgShares(c *gin.Context) { ctx := c.Request.Context() orgID := c.Param("id") - userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) - // Check if user is a member and get their role for effective-permission calculation - member, err := h.orgService.GetMember(ctx, orgID, userID) + // Check if caller's tenant is a member and get its role for effective-permission calculation + member, err := h.orgService.GetTenantMember(ctx, orgID, tenantID) if err != nil { - c.Error(apperrors.NewForbiddenError("You are not a member of this organization")) + c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization")) return } myRoleInOrg := member.Role @@ -1224,10 +1245,10 @@ func (h *OrganizationHandler) ListOrgShares(c *gin.Context) { func (h *OrganizationHandler) ListSharedKnowledgeBases(c *gin.Context) { ctx := c.Request.Context() - userID := c.GetString(types.UserIDContextKey.String()) tenantID := types.MustTenantIDFromContext(ctx) + callerTenantRole := types.TenantRoleFromContext(ctx) - sharedKBs, err := h.shareService.ListSharedKnowledgeBases(ctx, userID, tenantID) + sharedKBs, err := h.shareService.ListSharedKnowledgeBases(ctx, tenantID, callerTenantRole) if err != nil { logger.Errorf(ctx, "Failed to list shared knowledge bases: %v", err) c.Error(apperrors.NewInternalServerError("Failed to list shared knowledge bases")) @@ -1314,7 +1335,8 @@ func (h *OrganizationHandler) RemoveAgentShare(c *gin.Context) { ctx := c.Request.Context() shareID := c.Param("share_id") userID := c.GetString(types.UserIDContextKey.String()) - if err := h.agentShareService.RemoveShare(ctx, shareID, userID); err != nil { + tenantID := c.GetUint64(types.TenantIDContextKey.String()) + if err := h.agentShareService.RemoveShare(ctx, shareID, userID, tenantID); err != nil { logger.Errorf(ctx, "Failed to remove agent share: %v", err) c.Error(apperrors.NewForbiddenError("Permission denied")) return @@ -1338,10 +1360,10 @@ func (h *OrganizationHandler) RemoveAgentShare(c *gin.Context) { func (h *OrganizationHandler) ListOrgAgentShares(c *gin.Context) { ctx := c.Request.Context() orgID := c.Param("id") - userID := c.GetString(types.UserIDContextKey.String()) - member, err := h.orgService.GetMember(ctx, orgID, userID) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) + member, err := h.orgService.GetTenantMember(ctx, orgID, tenantID) if err != nil { - c.Error(apperrors.NewForbiddenError("You are not a member of this organization")) + c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization")) return } myRoleInOrg := member.Role @@ -1409,9 +1431,9 @@ func (h *OrganizationHandler) ListOrgAgentShares(c *gin.Context) { // @Router /shared-agents [get] func (h *OrganizationHandler) ListSharedAgents(c *gin.Context) { ctx := c.Request.Context() - userID := c.GetString(types.UserIDContextKey.String()) tenantID := c.GetUint64(types.TenantIDContextKey.String()) - list, err := h.agentShareService.ListSharedAgents(ctx, userID, tenantID) + callerTenantRole := types.TenantRoleFromContext(ctx) + list, err := h.agentShareService.ListSharedAgents(ctx, tenantID, callerTenantRole) if err != nil { logger.Errorf(ctx, "Failed to list shared agents: %v", err) c.Error(apperrors.NewInternalServerError("Failed to list shared agents")) @@ -1421,8 +1443,8 @@ func (h *OrganizationHandler) ListSharedAgents(c *gin.Context) { } // listSpaceKnowledgeBasesInOrganization returns merged list of direct shared KBs and agent-carried KBs in the org (for list and count). -func (h *OrganizationHandler) listSpaceKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, tenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error) { - directList, err := h.shareService.ListSharedKnowledgeBasesInOrganization(ctx, orgID, userID, tenantID) +func (h *OrganizationHandler) listSpaceKnowledgeBasesInOrganization(ctx context.Context, orgID string, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.OrganizationSharedKnowledgeBaseItem, error) { + directList, err := h.shareService.ListSharedKnowledgeBasesInOrganization(ctx, orgID, tenantID, callerTenantRole) if err != nil { return nil, err } @@ -1434,7 +1456,7 @@ func (h *OrganizationHandler) listSpaceKnowledgeBasesInOrganization(ctx context. } } - agentList, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, userID, tenantID) + agentList, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, tenantID, callerTenantRole) if err != nil { return directList, nil } @@ -1552,13 +1574,13 @@ func (h *OrganizationHandler) listSpaceKnowledgeBasesInOrganization(ctx context. func (h *OrganizationHandler) ListOrganizationSharedKnowledgeBases(c *gin.Context) { ctx := c.Request.Context() orgID := c.Param("id") - userID := c.GetString(types.UserIDContextKey.String()) tenantID := c.GetUint64(types.TenantIDContextKey.String()) + callerTenantRole := types.TenantRoleFromContext(ctx) - list, err := h.listSpaceKnowledgeBasesInOrganization(ctx, orgID, userID, tenantID) + list, err := h.listSpaceKnowledgeBasesInOrganization(ctx, orgID, tenantID, callerTenantRole) if err != nil { - if errors.Is(err, service.ErrUserNotInOrg) { - c.Error(apperrors.NewForbiddenError("You are not a member of this organization")) + if errors.Is(err, service.ErrTenantNotInOrg) { + c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization")) return } logger.Errorf(ctx, "Failed to list organization shared knowledge bases: %v", err) @@ -1580,13 +1602,13 @@ func (h *OrganizationHandler) ListOrganizationSharedKnowledgeBases(c *gin.Contex func (h *OrganizationHandler) ListOrganizationSharedAgents(c *gin.Context) { ctx := c.Request.Context() orgID := c.Param("id") - userID := c.GetString(types.UserIDContextKey.String()) tenantID := c.GetUint64(types.TenantIDContextKey.String()) + callerTenantRole := types.TenantRoleFromContext(ctx) - list, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, userID, tenantID) + list, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, tenantID, callerTenantRole) if err != nil { - if errors.Is(err, service.ErrUserNotInOrg) { - c.Error(apperrors.NewForbiddenError("You are not a member of this organization")) + if errors.Is(err, service.ErrTenantNotInOrg) { + c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization")) return } logger.Errorf(ctx, "Failed to list organization shared agents: %v", err) @@ -1621,13 +1643,14 @@ func (h *OrganizationHandler) SetSharedAgentDisabledByMe(c *gin.Context) { if err == nil && agent != nil && agent.TenantID == tid { sourceTenantID = tid } else { - share, err := h.agentShareService.GetShareByAgentIDForUser(ctx, uid, req.AgentID, tid) + share, err := h.agentShareService.GetShareByAgentIDForTenant(ctx, tid, req.AgentID, tid) if err != nil || share == nil { c.Error(apperrors.NewForbiddenError("No access to this agent")) return } sourceTenantID = share.SourceTenantID } + _ = uid if err := h.agentShareService.SetSharedAgentDisabledByMe(ctx, tid, req.AgentID, sourceTenantID, req.Disabled); err != nil { logger.Errorf(ctx, "SetSharedAgentDisabledByMe failed: %v", err) c.Error(apperrors.NewInternalServerError("Failed to update preference")) @@ -1638,6 +1661,7 @@ func (h *OrganizationHandler) SetSharedAgentDisabledByMe(c *gin.Context) { // toOrgResponse converts an organization to response format func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Organization, currentUserID string) types.OrganizationResponse { + currentTenantID := types.MustTenantIDFromContext(ctx) resp := types.OrganizationResponse{ ID: org.ID, Name: org.Name, @@ -1653,8 +1677,8 @@ func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Orga UpdatedAt: org.UpdatedAt, } - // Get member count - if members, err := h.orgService.ListMembers(ctx, org.ID); err == nil { + // Get member count (per-tenant) + if members, err := h.orgService.ListTenantMembers(ctx, org.ID); err == nil { resp.MemberCount = len(members) } @@ -1667,9 +1691,9 @@ func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Orga resp.AgentShareCount = len(agentShares) } - // Get current user's role in this organization + // Get current tenant's role in this organization isAdmin := false - if role, err := h.orgService.GetUserRoleInOrg(ctx, org.ID, currentUserID); err == nil { + if role, err := h.orgService.GetTenantRoleInOrg(ctx, org.ID, currentTenantID); err == nil { resp.MyRole = string(role) isAdmin = (role == types.OrgRoleAdmin) } @@ -1681,8 +1705,8 @@ func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Orga } } - // Check if current user has pending upgrade request - if _, err := h.orgService.GetPendingUpgradeRequest(ctx, org.ID, currentUserID); err == nil { + // Check if current tenant has pending upgrade request + if _, err := h.orgService.GetPendingUpgradeRequest(ctx, org.ID, currentTenantID); err == nil { resp.HasPendingUpgrade = true } @@ -1706,10 +1730,10 @@ func (h *OrganizationHandler) SearchUsersForInvite(c *gin.Context) { orgID := c.Param("id") query := c.Query("q") - userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) - // Check admin permission - isAdmin, err := h.orgService.IsOrgAdmin(ctx, orgID, userID) + // Check admin permission: caller's tenant must be org admin + isAdmin, err := h.orgService.IsTenantOrgAdmin(ctx, orgID, tenantID) if err != nil || !isAdmin { c.Error(apperrors.NewForbiddenError("Only organization admins can invite members")) return @@ -1739,17 +1763,17 @@ func (h *OrganizationHandler) SearchUsersForInvite(c *gin.Context) { return } - // Get existing members - existingMembers, _ := h.orgService.ListMembers(ctx, orgID) - existingMemberIDs := make(map[string]bool) + // Get existing tenant members; exclude users whose tenant is already a member + existingMembers, _ := h.orgService.ListTenantMembers(ctx, orgID) + existingTenantIDs := make(map[uint64]bool) for _, m := range existingMembers { - existingMemberIDs[m.UserID] = true + existingTenantIDs[m.TenantID] = true } - // Filter out existing members and build response + // Filter out users whose tenant is already a member var result []gin.H for _, u := range users { - if existingMemberIDs[u.ID] { + if existingTenantIDs[u.TenantID] { continue } result = append(result, gin.H{ @@ -1787,9 +1811,10 @@ func (h *OrganizationHandler) InviteMember(c *gin.Context) { orgID := c.Param("id") userID := c.GetString(types.UserIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) - // Check admin permission - isAdmin, err := h.orgService.IsOrgAdmin(ctx, orgID, userID) + // Check admin permission: caller's tenant must be org admin + isAdmin, err := h.orgService.IsTenantOrgAdmin(ctx, orgID, tenantID) if err != nil || !isAdmin { c.Error(apperrors.NewForbiddenError("Only organization admins can invite members")) return @@ -1814,15 +1839,15 @@ func (h *OrganizationHandler) InviteMember(c *gin.Context) { return } - // Check if already a member - _, memberErr := h.orgService.GetMember(ctx, orgID, req.UserID) + // Check if invitee's tenant is already a member of this org + _, memberErr := h.orgService.GetTenantMember(ctx, orgID, invitedUser.TenantID) if memberErr == nil { - c.Error(apperrors.NewValidationError("User is already a member of this organization")) + c.Error(apperrors.NewValidationError("User's tenant is already a member of this organization")) return } - // Add member - if err := h.orgService.AddMember(ctx, orgID, req.UserID, invitedUser.TenantID, req.Role); err != nil { + // Add tenant member with the invited user as representative + if err := h.orgService.AddTenantMember(ctx, orgID, invitedUser.TenantID, req.UserID, req.Role); err != nil { logger.Errorf(ctx, "Failed to add member: %v", err) if errors.Is(err, service.ErrOrgMemberLimitReached) { c.Error(apperrors.NewValidationError("该空间成员已满,无法添加新成员")) diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index 363dfbf4..4d898c85 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -250,8 +250,8 @@ func (h *Handler) resolveAgent(ctx context.Context, c *gin.Context, agentID stri userIDVal, _ := c.Get(types.UserIDContextKey.String()) currentTenantID := c.GetUint64(types.TenantIDContextKey.String()) if h.agentShareService != nil && userIDVal != nil && currentTenantID != 0 { - userID, _ := userIDVal.(string) - agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, agentID) + callerTenantRole := types.TenantRoleFromContext(ctx) + agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID) if err == nil && agent != nil { effectiveTenantID = agent.TenantID customAgent = agent diff --git a/internal/handler/tag.go b/internal/handler/tag.go index 95f4f5bd..623eecb2 100644 --- a/internal/handler/tag.go +++ b/internal/handler/tag.go @@ -51,6 +51,7 @@ func (h *TagHandler) effectiveCtxForKB(c *gin.Context, kbID string) (context.Con return nil, errors.NewUnauthorizedError("Unauthorized") } userID, userExists := c.Get(types.UserIDContextKey.String()) + callerTenantRole := types.TenantRoleFromContext(ctx) kbID = secutils.SanitizeForLog(kbID) if kbID == "" { return nil, errors.NewBadRequestError("Knowledge base ID cannot be empty") @@ -69,24 +70,26 @@ func (h *TagHandler) effectiveCtxForKB(c *gin.Context, kbID string) (context.Con if kb.TenantID == tenantID { return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil } - if userExists && h.kbShareService != nil { - permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string)) + if h.kbShareService != nil { + permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, kbID, tenantID, callerTenantRole) if permErr == nil && isShared { sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID) if srcErr == nil { - logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d", - userID.(string), kbID, permission, sourceTenantID) + logger.Infof(ctx, "Tenant %d accessing shared KB %s with permission %s, source tenant: %d", + tenantID, kbID, permission, sourceTenantID) return context.WithValue(ctx, types.TenantIDContextKey, sourceTenantID), nil } } } - if userExists && h.agentShareService != nil { - can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb) + if h.agentShareService != nil { + can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kb) if err == nil && can { - logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID) + logger.Infof(ctx, "Tenant %d accessing KB %s via some shared agent", tenantID, kbID) return context.WithValue(ctx, types.TenantIDContextKey, kb.TenantID), nil } } + _ = userID + _ = userExists logger.Warnf(ctx, "Permission denied to access KB %s", kbID) return nil, errors.NewForbiddenError("Permission denied to access this knowledge base") } diff --git a/internal/router/router.go b/internal/router/router.go index 6df64f7c..f91f8bd9 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -801,28 +801,28 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza // Organization routes orgs := r.Group("/organizations") { - // Create organization - orgs.POST("", orgHandler.CreateOrganization) + // Create organization (Admin+ in caller's tenant only) + orgs.POST("", g.Admin(), orgHandler.CreateOrganization) // List my organizations orgs.GET("", orgHandler.ListMyOrganizations) // Preview organization by invite code (without joining) orgs.GET("/preview/:code", orgHandler.PreviewByInviteCode) - // Join organization by invite code - orgs.POST("/join", orgHandler.JoinByInviteCode) - // Submit join request (for organizations that require approval) - orgs.POST("/join-request", orgHandler.SubmitJoinRequest) + // Join organization by invite code (Admin+ in caller's tenant only) + orgs.POST("/join", g.Admin(), orgHandler.JoinByInviteCode) + // Submit join request (for organizations that require approval) (Admin+) + orgs.POST("/join-request", g.Admin(), orgHandler.SubmitJoinRequest) // Search searchable (discoverable) organizations orgs.GET("/search", orgHandler.SearchOrganizations) - // Join searchable organization by ID (no invite code) - orgs.POST("/join-by-id", orgHandler.JoinByOrganizationID) + // Join searchable organization by ID (no invite code) (Admin+) + orgs.POST("/join-by-id", g.Admin(), orgHandler.JoinByOrganizationID) // Get organization by ID orgs.GET("/:id", orgHandler.GetOrganization) // Update organization orgs.PUT("/:id", orgHandler.UpdateOrganization) // Delete organization orgs.DELETE("/:id", orgHandler.DeleteOrganization) - // Leave organization - orgs.POST("/:id/leave", orgHandler.LeaveOrganization) + // Leave organization (Admin+ in caller's tenant only) + orgs.POST("/:id/leave", g.Admin(), orgHandler.LeaveOrganization) // Request role upgrade (for existing members) orgs.POST("/:id/request-upgrade", orgHandler.RequestRoleUpgrade) // Generate invite code @@ -833,10 +833,10 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza orgs.POST("/:id/invite", orgHandler.InviteMember) // List members orgs.GET("/:id/members", orgHandler.ListMembers) - // Update member role - orgs.PUT("/:id/members/:user_id", orgHandler.UpdateMemberRole) - // Remove member - orgs.DELETE("/:id/members/:user_id", orgHandler.RemoveMember) + // Update member role (path parameter is the member tenant_id) + orgs.PUT("/:id/members/:tenant_id", orgHandler.UpdateMemberRole) + // Remove member (path parameter is the member tenant_id) + orgs.DELETE("/:id/members/:tenant_id", orgHandler.RemoveMember) // List join requests (admin only) orgs.GET("/:id/join-requests", orgHandler.ListJoinRequests) // Review join request (admin only) diff --git a/internal/types/interfaces/organization.go b/internal/types/interfaces/organization.go index 2ed51108..dd07a15b 100644 --- a/internal/types/interfaces/organization.go +++ b/internal/types/interfaces/organization.go @@ -7,99 +7,126 @@ import ( "github.com/Tencent/WeKnora/internal/types" ) -// OrganizationService defines the organization service interface +// OrganizationService defines the organization service interface. +// +// Plan 3 of #1303: organization membership is per-tenant, not per-user. +// Adding/removing/updating "members" therefore takes a tenant_id, and +// permission checks key on (org, tenant). RepresentativeUserID is +// informational and not load-bearing. type OrganizationService interface { // Organization CRUD CreateOrganization(ctx context.Context, userID string, tenantID uint64, req *types.CreateOrganizationRequest) (*types.Organization, error) GetOrganization(ctx context.Context, id string) (*types.Organization, error) GetOrganizationByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error) - ListUserOrganizations(ctx context.Context, userID string) ([]*types.Organization, error) - UpdateOrganization(ctx context.Context, id string, userID string, req *types.UpdateOrganizationRequest) (*types.Organization, error) - DeleteOrganization(ctx context.Context, id string, userID string) error + ListTenantOrganizations(ctx context.Context, tenantID uint64) ([]*types.Organization, error) + UpdateOrganization(ctx context.Context, id string, userID string, tenantID uint64, req *types.UpdateOrganizationRequest) (*types.Organization, error) + DeleteOrganization(ctx context.Context, id string, userID string, tenantID uint64) error - // Member Management - AddMember(ctx context.Context, orgID string, userID string, tenantID uint64, role types.OrgMemberRole) error - RemoveMember(ctx context.Context, orgID string, memberUserID string, operatorUserID string) error - UpdateMemberRole(ctx context.Context, orgID string, memberUserID string, role types.OrgMemberRole, operatorUserID string) error - ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error) - GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error) + // Member Management (Plan 3: members are tenants) + // AddTenantMember adds a tenant to the org with the given role; representativeUserID + // is only used for display labelling. + AddTenantMember(ctx context.Context, orgID string, tenantID uint64, representativeUserID string, role types.OrgMemberRole) error + RemoveTenantMember(ctx context.Context, orgID string, memberTenantID uint64, operatorUserID string, operatorTenantID uint64) error + UpdateTenantMemberRole(ctx context.Context, orgID string, memberTenantID uint64, role types.OrgMemberRole, operatorUserID string, operatorTenantID uint64) error + ListTenantMembers(ctx context.Context, orgID string) ([]*types.OrganizationTenantMember, error) + GetTenantMember(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationTenantMember, error) // Invite Code - GenerateInviteCode(ctx context.Context, orgID string, userID string) (string, error) + GenerateInviteCode(ctx context.Context, orgID string, userID string, tenantID uint64) (string, error) JoinByInviteCode(ctx context.Context, inviteCode string, userID string, tenantID uint64) (*types.Organization, error) // Searchable organizations (discovery) - SearchSearchableOrganizations(ctx context.Context, userID string, query string, limit int) (*types.ListSearchableOrganizationsResponse, error) + SearchSearchableOrganizations(ctx context.Context, tenantID uint64, query string, limit int) (*types.ListSearchableOrganizationsResponse, error) JoinByOrganizationID(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.Organization, error) // Join Requests (for organizations that require approval) SubmitJoinRequest(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.OrganizationJoinRequest, error) ListJoinRequests(ctx context.Context, orgID string) ([]*types.OrganizationJoinRequest, error) CountPendingJoinRequests(ctx context.Context, orgID string) (int64, error) - ReviewJoinRequest(ctx context.Context, orgID string, requestID string, approved bool, reviewerID string, message string, assignRole *types.OrgMemberRole) error + ReviewJoinRequest(ctx context.Context, orgID string, requestID string, approved bool, reviewerID string, reviewerTenantID uint64, message string, assignRole *types.OrgMemberRole) error - // Role Upgrade Requests (for existing members to request higher permissions) + // Role Upgrade Requests (for existing tenants to request higher permissions) RequestRoleUpgrade(ctx context.Context, orgID string, userID string, tenantID uint64, requestedRole types.OrgMemberRole, message string) (*types.OrganizationJoinRequest, error) - GetPendingUpgradeRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error) + GetPendingUpgradeRequest(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationJoinRequest, error) - // Permission Check - IsOrgAdmin(ctx context.Context, orgID string, userID string) (bool, error) - GetUserRoleInOrg(ctx context.Context, orgID string, userID string) (types.OrgMemberRole, error) + // Permission Check (drive purely off the requesting tenant) + IsTenantOrgAdmin(ctx context.Context, orgID string, tenantID uint64) (bool, error) + GetTenantRoleInOrg(ctx context.Context, orgID string, tenantID uint64) (types.OrgMemberRole, error) } -// OrganizationRepository defines the organization repository interface +// OrganizationRepository defines the organization repository interface. +// +// Members are stored per-tenant in `organization_tenant_members`. type OrganizationRepository interface { // Organization CRUD Create(ctx context.Context, org *types.Organization) error GetByID(ctx context.Context, id string) (*types.Organization, error) GetByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error) - ListByUserID(ctx context.Context, userID string) ([]*types.Organization, error) + ListByTenantID(ctx context.Context, tenantID uint64) ([]*types.Organization, error) ListSearchable(ctx context.Context, query string, limit int) ([]*types.Organization, error) Update(ctx context.Context, org *types.Organization) error Delete(ctx context.Context, id string) error - // Member operations - AddMember(ctx context.Context, member *types.OrganizationMember) error - RemoveMember(ctx context.Context, orgID string, userID string) error - UpdateMemberRole(ctx context.Context, orgID string, userID string, role types.OrgMemberRole) error - ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error) - GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error) - ListMembersByUserForOrgs(ctx context.Context, userID string, orgIDs []string) (map[string]*types.OrganizationMember, error) - CountMembers(ctx context.Context, orgID string) (int64, error) + // Tenant member operations + AddTenantMember(ctx context.Context, member *types.OrganizationTenantMember) 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) + GetTenantMember(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationTenantMember, error) + ListTenantMembersByTenantForOrgs(ctx context.Context, tenantID uint64, orgIDs []string) (map[string]*types.OrganizationTenantMember, error) + CountTenantMembers(ctx context.Context, orgID string) (int64, error) // Invite code UpdateInviteCode(ctx context.Context, orgID string, inviteCode string, expiresAt *time.Time) error - // Join requests + // Join requests (still keyed on the *requesting* user, but a single + // pending request per (org, tenant) since the approve action grants + // the whole tenant access). CreateJoinRequest(ctx context.Context, request *types.OrganizationJoinRequest) error GetJoinRequestByID(ctx context.Context, id string) (*types.OrganizationJoinRequest, error) - GetPendingJoinRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error) - GetPendingRequestByType(ctx context.Context, orgID string, userID string, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error) + GetPendingJoinRequestByTenant(ctx context.Context, orgID string, tenantID uint64) (*types.OrganizationJoinRequest, error) + GetPendingRequestByTenantAndType(ctx context.Context, orgID string, tenantID uint64, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error) ListJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) ([]*types.OrganizationJoinRequest, error) CountJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) (int64, error) UpdateJoinRequestStatus(ctx context.Context, id string, status types.JoinRequestStatus, reviewedBy string, reviewMessage string) error } -// KBShareService defines the knowledge base sharing service interface +// KBShareService defines the knowledge base sharing service interface. +// +// Plan 3 of #1303: permission resolution keys on the caller's tenant +// (not user). The 3-dimension cap is applied inside CheckTenantKBPermission +// and is the canonical permission gate for shared KBs: +// +// effective = min(share.Permission, tenant_org_role, tenant_role_cap) +// +// where tenant_role_cap pins tenant Viewers to OrgRoleViewer regardless +// of the org-level grant — Viewer in your own tenant must always be +// read-only on shared resources. type KBShareService interface { // Share Management ShareKnowledgeBase(ctx context.Context, kbID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.KnowledgeBaseShare, error) - UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string) error - RemoveShare(ctx context.Context, shareID string, userID string) error + UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string, tenantID uint64) error + RemoveShare(ctx context.Context, shareID string, userID string, tenantID uint64) error // Query // ListSharesByKnowledgeBase lists shares for a KB; tenantID must own the KB (authz check). ListSharesByKnowledgeBase(ctx context.Context, kbID string, tenantID uint64) ([]*types.KnowledgeBaseShare, error) ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error) - ListSharedKnowledgeBases(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedKnowledgeBaseInfo, error) - ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error) + ListSharedKnowledgeBases(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.SharedKnowledgeBaseInfo, error) + ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.OrganizationSharedKnowledgeBaseItem, error) // ListSharedKnowledgeBaseIDsByOrganizations returns per-org direct shared KB IDs (batch, for sidebar count). - ListSharedKnowledgeBaseIDsByOrganizations(ctx context.Context, orgIDs []string, userID string) (map[string][]string, error) + ListSharedKnowledgeBaseIDsByOrganizations(ctx context.Context, orgIDs []string, tenantID uint64) (map[string][]string, error) GetShare(ctx context.Context, shareID string) (*types.KnowledgeBaseShare, error) GetShareByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error) - // Permission Check - CheckUserKBPermission(ctx context.Context, kbID string, userID string) (types.OrgMemberRole, bool, error) - HasKBPermission(ctx context.Context, kbID string, userID string, requiredRole types.OrgMemberRole) (bool, error) + // Permission Check (Plan 3: tenant-keyed). Returns the effective + // OrgMemberRole the caller can use against the shared KB after the + // 3-D cap, plus a bool indicating whether *any* share matches the + // caller's tenant. callerTenantRole is the caller's tenant-RBAC + // role and is used to apply the Viewer cap. + CheckTenantKBPermission(ctx context.Context, kbID string, callerTenantID uint64, callerTenantRole types.TenantRole) (types.OrgMemberRole, bool, error) + // HasTenantKBPermission is a thin "do I have at least N" wrapper over + // CheckTenantKBPermission. + HasTenantKBPermission(ctx context.Context, kbID string, callerTenantID uint64, callerTenantRole types.TenantRole, requiredRole types.OrgMemberRole) (bool, error) // Get source tenant for cross-tenant embedding GetKBSourceTenant(ctx context.Context, kbID string) (uint64, error) @@ -129,34 +156,38 @@ type KBShareRepository interface { ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.KnowledgeBaseShare, error) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) - // Query for user's accessible shared knowledge bases - ListSharedKBsForUser(ctx context.Context, userID string) ([]*types.KnowledgeBaseShare, error) + // Query for tenant's accessible shared knowledge bases + ListSharedKBsForTenant(ctx context.Context, tenantID uint64) ([]*types.KnowledgeBaseShare, error) // Count shares CountSharesByKnowledgeBaseID(ctx context.Context, kbID string) (int64, error) CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error) } -// AgentShareService defines the agent sharing service interface +// AgentShareService defines the agent sharing service interface. +// +// Plan 3 of #1303: visibility and access checks key on the caller's +// tenant. callerTenantRole flows through so the 3-D cap (tenant Viewer +// → at most OrgRoleViewer) can be applied consistently. type AgentShareService interface { ShareAgent(ctx context.Context, agentID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.AgentShare, error) - RemoveShare(ctx context.Context, shareID string, userID string) error + RemoveShare(ctx context.Context, shareID string, userID string, tenantID uint64) error ListSharesByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error) ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error) - ListSharedAgents(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedAgentInfo, error) - ListSharedAgentsInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedAgentItem, error) + ListSharedAgents(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.SharedAgentInfo, error) + ListSharedAgentsInOrganization(ctx context.Context, orgID string, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.OrganizationSharedAgentItem, error) // ListSharedAgentsInOrganizations returns per-org agent list (batch, for sidebar count merge). - ListSharedAgentsInOrganizations(ctx context.Context, orgIDs []string, userID string, currentTenantID uint64) (map[string][]*types.OrganizationSharedAgentItem, error) - // SetSharedAgentDisabledByMe sets whether the current tenant has "disabled" this shared agent for their conversation dropdown (per-user preference). + ListSharedAgentsInOrganizations(ctx context.Context, orgIDs []string, tenantID uint64, callerTenantRole types.TenantRole) (map[string][]*types.OrganizationSharedAgentItem, error) + // SetSharedAgentDisabledByMe sets whether the current tenant has "disabled" this shared agent for their conversation dropdown (per-tenant preference; will be revisited in a follow-up PR). SetSharedAgentDisabledByMe(ctx context.Context, tenantID uint64, agentID string, sourceTenantID uint64, disabled bool) error - // GetSharedAgentForUser returns the shared agent by agentID if the user has access (source tenant is resolved from share); used to resolve KB scope for @ mention. - GetSharedAgentForUser(ctx context.Context, userID string, currentTenantID uint64, agentID string) (*types.CustomAgent, error) - // UserCanAccessKBViaSomeSharedAgent returns true if the user has at least one shared agent that can access the given KB (for opening KB detail from "通过智能体可见" list without passing agent_id). - UserCanAccessKBViaSomeSharedAgent(ctx context.Context, userID string, currentTenantID uint64, kb *types.KnowledgeBase) (bool, error) + // GetSharedAgentForTenant returns the shared agent by agentID if the caller's tenant has access; used to resolve KB scope for @ mention. + GetSharedAgentForTenant(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole, agentID string) (*types.CustomAgent, error) + // TenantCanAccessKBViaSomeSharedAgent returns true if the caller's tenant has at least one shared agent that can access the given KB (for opening KB detail from "通过智能体可见" list without passing agent_id). + TenantCanAccessKBViaSomeSharedAgent(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole, kb *types.KnowledgeBase) (bool, error) GetShare(ctx context.Context, shareID string) (*types.AgentShare, error) GetShareByAgentAndOrg(ctx context.Context, agentID string, orgID string) (*types.AgentShare, error) - // GetShareByAgentIDForUser returns one share for the given agentID that the user can access, excluding source_tenant_id == excludeTenantID (e.g. current tenant to get shared-from-other only). - GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error) + // GetShareByAgentIDForTenant returns one share for the given agentID that the tenant can access, excluding source_tenant_id == excludeTenantID (e.g. caller's own tenant to get shared-from-other only). + GetShareByAgentIDForTenant(ctx context.Context, tenantID uint64, agentID string, excludeTenantID uint64) (*types.AgentShare, error) // CountByOrganizations returns share counts per organization (for sidebar); excludes deleted agents CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) } @@ -173,10 +204,10 @@ type AgentShareRepository interface { ListByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error) ListByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error) ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.AgentShare, error) - ListSharedAgentsForUser(ctx context.Context, userID string) ([]*types.AgentShare, error) + ListSharedAgentsForTenant(ctx context.Context, tenantID uint64) ([]*types.AgentShare, error) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) - // GetShareByAgentIDForUser returns one share for the given agentID that the user can access (user in org), excluding source_tenant_id == excludeTenantID. - GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error) + // GetShareByAgentIDForTenant returns one share for the given agentID that the tenant can access (tenant in org), excluding source_tenant_id == excludeTenantID. + GetShareByAgentIDForTenant(ctx context.Context, tenantID uint64, agentID string, excludeTenantID uint64) (*types.AgentShare, error) } // TenantDisabledSharedAgentRepository stores per-tenant "disabled" agents (hidden from conversation dropdown; own and shared) diff --git a/internal/types/organization.go b/internal/types/organization.go index e0cf5f7e..bfbeb455 100644 --- a/internal/types/organization.go +++ b/internal/types/organization.go @@ -38,6 +38,25 @@ func (r OrgMemberRole) HasPermission(required OrgMemberRole) bool { return roleLevel[r] >= roleLevel[required] } +// MinOrgRole returns whichever of a / b is the lower role on the +// admin > editor > viewer ladder. Used to apply caps when combining +// (a) the share's grant, (b) the tenant's role inside the org, and +// (c) the caller's tenant-RBAC ceiling. A zero/empty role is treated +// as "less than viewer" so it short-circuits to whatever the other +// argument is. +func MinOrgRole(a, b OrgMemberRole) OrgMemberRole { + if a == "" { + return b + } + if b == "" { + return a + } + if a.HasPermission(b) { + return b + } + return a +} + // Organization represents a collaboration organization for cross-tenant sharing type Organization struct { // Unique identifier of the organization @@ -70,9 +89,9 @@ type Organization struct { DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"` // Associations (not stored in database) - Owner *User `json:"owner,omitempty" gorm:"foreignKey:OwnerID"` - Members []OrganizationMember `json:"members,omitempty" gorm:"foreignKey:OrganizationID"` - Shares []KnowledgeBaseShare `json:"shares,omitempty" gorm:"foreignKey:OrganizationID"` + Owner *User `json:"owner,omitempty" gorm:"foreignKey:OwnerID"` + Members []OrganizationTenantMember `json:"members,omitempty" gorm:"foreignKey:OrganizationID"` + Shares []KnowledgeBaseShare `json:"shares,omitempty" gorm:"foreignKey:OrganizationID"` } // TableName returns the table name for GORM @@ -80,31 +99,29 @@ func (Organization) TableName() string { return "organizations" } -// OrganizationMember represents a member of an organization -type OrganizationMember struct { - // Unique identifier - ID string `json:"id" gorm:"type:varchar(36);primaryKey"` - // Organization ID - OrganizationID string `json:"organization_id" gorm:"type:varchar(36);not null;index"` - // User ID of the member - UserID string `json:"user_id" gorm:"type:varchar(36);not null;index"` - // Tenant ID that the member belongs to - TenantID uint64 `json:"tenant_id" gorm:"not null;index"` - // Role in the organization (admin/editor/viewer) - Role OrgMemberRole `json:"role" gorm:"type:varchar(32);not null;default:'viewer'"` - // Creation time - CreatedAt time.Time `json:"created_at"` - // Last updated time - UpdatedAt time.Time `json:"updated_at"` +// OrganizationTenantMember represents a tenant participating in an +// organization. Plan 3 of #1303 lifts the "Org member" abstraction from +// per-user (`organization_members`) to per-tenant (this table). The +// representative_user_id is informational only — the user who first +// brought this tenant into the org — and is used purely for UI/audit +// labels. Permission checks are driven exclusively by (org, tenant, role). +type OrganizationTenantMember struct { + ID string `json:"id" gorm:"type:varchar(36);primaryKey"` + OrganizationID string `json:"organization_id" gorm:"type:varchar(36);not null;index"` + TenantID uint64 `json:"tenant_id" gorm:"not null;index"` + Role OrgMemberRole `json:"role" gorm:"type:varchar(32);not null;default:'viewer'"` + RepresentativeUserID string `json:"representative_user_id" gorm:"type:varchar(36);default:''"` + JoinedAt *time.Time `json:"joined_at"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` - // Associations (not stored in database) - Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"` - User *User `json:"user,omitempty" gorm:"foreignKey:UserID"` + Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"` + RepresentativeUser *User `json:"representative_user,omitempty" gorm:"foreignKey:RepresentativeUserID"` } // TableName returns the table name for GORM -func (OrganizationMember) TableName() string { - return "organization_members" +func (OrganizationTenantMember) TableName() string { + return "organization_tenant_members" } // JoinRequestStatus represents the status of a join request diff --git a/migrations/sqlite/000000_init.down.sql b/migrations/sqlite/000000_init.down.sql index 951bbe6c..b503a722 100644 --- a/migrations/sqlite/000000_init.down.sql +++ b/migrations/sqlite/000000_init.down.sql @@ -2,7 +2,7 @@ DROP TABLE IF EXISTS tenant_disabled_shared_agents; DROP TABLE IF EXISTS agent_shares; DROP TABLE IF EXISTS organization_join_requests; DROP TABLE IF EXISTS kb_shares; -DROP TABLE IF EXISTS organization_members; +DROP TABLE IF EXISTS organization_tenant_members; DROP TABLE IF EXISTS organizations; DROP TABLE IF EXISTS custom_agents; DROP TABLE IF EXISTS mcp_tool_approvals; diff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sql index 53960e6f..26b2f6e5 100644 --- a/migrations/sqlite/000000_init.up.sql +++ b/migrations/sqlite/000000_init.up.sql @@ -392,20 +392,20 @@ CREATE TABLE IF NOT EXISTS organizations ( CREATE INDEX IF NOT EXISTS idx_organizations_owner_id ON organizations(owner_id); CREATE INDEX IF NOT EXISTS idx_organizations_deleted_at ON organizations(deleted_at); -CREATE TABLE IF NOT EXISTS organization_members ( +CREATE TABLE IF NOT EXISTS organization_tenant_members ( id VARCHAR(36) PRIMARY KEY, organization_id VARCHAR(36) NOT NULL REFERENCES organizations(id) ON DELETE CASCADE, - user_id VARCHAR(36) NOT NULL, tenant_id INTEGER NOT NULL, role VARCHAR(32) NOT NULL DEFAULT 'viewer', + representative_user_id VARCHAR(36) NOT NULL DEFAULT '', + joined_at DATETIME, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ); -CREATE UNIQUE INDEX IF NOT EXISTS idx_org_members_org_user ON organization_members(organization_id, user_id); -CREATE INDEX IF NOT EXISTS idx_org_members_user_id ON organization_members(user_id); -CREATE INDEX IF NOT EXISTS idx_org_members_tenant_id ON organization_members(tenant_id); -CREATE INDEX IF NOT EXISTS idx_org_members_role ON organization_members(role); +CREATE UNIQUE INDEX IF NOT EXISTS idx_org_tenant_members_unique ON organization_tenant_members(organization_id, tenant_id); +CREATE INDEX IF NOT EXISTS idx_org_tenant_members_by_tenant ON organization_tenant_members(tenant_id); +CREATE INDEX IF NOT EXISTS idx_org_tenant_members_role ON organization_tenant_members(organization_id, role); CREATE TABLE IF NOT EXISTS kb_shares ( id VARCHAR(36) PRIMARY KEY, diff --git a/migrations/versioned/000045_org_tenant_members.down.sql b/migrations/versioned/000045_org_tenant_members.down.sql new file mode 100644 index 00000000..817ffbca --- /dev/null +++ b/migrations/versioned/000045_org_tenant_members.down.sql @@ -0,0 +1,27 @@ +-- Reverse migration for 000045_org_tenant_members. +-- +-- Restore organization_members from the parked _pre_plan3 table and drop +-- the new tenant-scoped table. Because we only RENAMEd the original on +-- the way up, no data is lost on rollback — the legacy rows are still +-- intact under the renamed table. +-- +-- If the parked table no longer exists (e.g. a later destructive +-- migration already dropped it), this script falls through gracefully: +-- the IF EXISTS guards leave the database in whatever state it was in. + +DO $$ BEGIN RAISE NOTICE '[Migration 000045] Reverting Plan 3'; END $$; + +-- Move legacy table back into place. +ALTER TABLE IF EXISTS organization_members_pre_plan3 RENAME TO organization_members; + +-- Restore index names so the application code can find them by their +-- documented identifiers. +ALTER INDEX IF EXISTS idx_org_members_org_user_pre_plan3 RENAME TO idx_org_members_org_user; +ALTER INDEX IF EXISTS idx_org_members_user_id_pre_plan3 RENAME TO idx_org_members_user_id; +ALTER INDEX IF EXISTS idx_org_members_tenant_id_pre_plan3 RENAME TO idx_org_members_tenant_id; +ALTER INDEX IF EXISTS idx_org_members_role_pre_plan3 RENAME TO idx_org_members_role; + +-- Drop the new table. The unique/secondary indexes go with it. +DROP TABLE IF EXISTS organization_tenant_members; + +DO $$ BEGIN RAISE NOTICE '[Migration 000045] Plan 3 reverted'; END $$; diff --git a/migrations/versioned/000045_org_tenant_members.up.sql b/migrations/versioned/000045_org_tenant_members.up.sql new file mode 100644 index 00000000..4e142e7e --- /dev/null +++ b/migrations/versioned/000045_org_tenant_members.up.sql @@ -0,0 +1,126 @@ +-- Migration: 000045_org_tenant_members +-- +-- Plan 3 of issue #1303: lift "organization membership" from per-user to +-- per-tenant. Today `organization_members` is keyed on (org_id, user_id) — +-- if Alice (tenant T) joins Org X, her tenant-mate Bob has no visibility +-- into anything shared into Org X. That breaks the company-level +-- collaboration mental model ("our company is in this org") and creates +-- inconsistency with `tenant_disabled_shared_agents`, which is already +-- tenant-scoped. +-- +-- The new table `organization_tenant_members` is keyed on (org_id, +-- tenant_id). One row says "tenant T participates in Org O at role R, +-- represented by user U". `representative_user_id` is purely for UI/audit +-- ("who from this tenant brought us here"); permission checks use only +-- (org_id, tenant_id, role). +-- +-- Backfill policy: collapse all `organization_members` rows for the same +-- (org, tenant) into a single new row. Role = the highest role observed +-- across the group (admin > editor > viewer). representative_user_id = +-- the earliest joiner. `RAISE NOTICE` flags any (org, tenant) that had +-- conflicting roles so operators can audit the resolved choice. +-- +-- The old `organization_members` table is RENAMEd to +-- `organization_members_pre_plan3` so a `down.sql` rollback can restore +-- it. A future destructive migration (gated on +-- `weknora.allow_destructive_migration`) will DROP it once the new model +-- is settled. + +DO $$ BEGIN RAISE NOTICE '[Migration 000045] Starting Plan 3: org members → org tenant members'; END $$; + +-- 1. New table. +DO $$ BEGIN RAISE NOTICE '[Migration 000045] Creating table: organization_tenant_members'; END $$; +CREATE TABLE IF NOT EXISTS organization_tenant_members ( + id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(), + organization_id VARCHAR(36) NOT NULL REFERENCES organizations(id) ON DELETE CASCADE, + tenant_id INTEGER NOT NULL, + role VARCHAR(32) NOT NULL DEFAULT 'viewer', + representative_user_id VARCHAR(36) NOT NULL DEFAULT '', + joined_at TIMESTAMP WITH TIME ZONE, + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_org_tenant_members_unique + ON organization_tenant_members (organization_id, tenant_id); + +CREATE INDEX IF NOT EXISTS idx_org_tenant_members_by_tenant + ON organization_tenant_members (tenant_id); + +CREATE INDEX IF NOT EXISTS idx_org_tenant_members_role + ON organization_tenant_members (organization_id, role); + +COMMENT ON TABLE organization_tenant_members IS 'Plan 3: Tenants (not users) are organization members.'; +COMMENT ON COLUMN organization_tenant_members.role IS 'Tenant role inside the org: admin | editor | viewer.'; +COMMENT ON COLUMN organization_tenant_members.representative_user_id IS 'Display-only: the user who first brought this tenant into the org.'; + +-- 2. Surface conflicting roles before backfilling so operators see them +-- in the migration log. The collapse strategy is "max role wins" +-- (admin > editor > viewer); this is a permission *promotion* for +-- any user who was at a lower role inside their tenant, so we shout +-- loudly when it happens. +DO $$ +DECLARE + rec RECORD; +BEGIN + FOR rec IN + SELECT organization_id, tenant_id, + COUNT(*) AS user_count, + ARRAY_AGG(DISTINCT role) AS observed_roles, + CASE + WHEN BOOL_OR(role = 'admin') THEN 'admin' + WHEN BOOL_OR(role = 'editor') THEN 'editor' + ELSE 'viewer' + END AS resolved_role + FROM organization_members + GROUP BY organization_id, tenant_id + LOOP + IF rec.user_count > 1 AND ARRAY_LENGTH(rec.observed_roles, 1) > 1 THEN + RAISE NOTICE '[Migration 000045] dedup org=% tenant=% chose role=% from observed=%, user_count=%', + rec.organization_id, rec.tenant_id, rec.resolved_role, rec.observed_roles, rec.user_count; + END IF; + END LOOP; +END $$; + +-- 3. Backfill the new table from the old one. +DO $$ BEGIN RAISE NOTICE '[Migration 000045] Backfilling organization_tenant_members from organization_members'; END $$; +INSERT INTO organization_tenant_members ( + organization_id, tenant_id, role, representative_user_id, joined_at, created_at, updated_at +) +SELECT + om.organization_id, + om.tenant_id, + CASE + WHEN BOOL_OR(om.role = 'admin') THEN 'admin' + WHEN BOOL_OR(om.role = 'editor') THEN 'editor' + ELSE 'viewer' + END AS role, + -- Representative: earliest joiner in the group, fallback to lowest user_id + -- so the choice is deterministic across re-runs. + (SELECT om2.user_id + FROM organization_members om2 + WHERE om2.organization_id = om.organization_id + AND om2.tenant_id = om.tenant_id + ORDER BY om2.created_at ASC, om2.user_id ASC + LIMIT 1) AS representative_user_id, + MIN(om.created_at) AS joined_at, + CURRENT_TIMESTAMP, + CURRENT_TIMESTAMP +FROM organization_members om +GROUP BY om.organization_id, om.tenant_id +ON CONFLICT DO NOTHING; + +-- 4. Park the old table so `down.sql` can restore it. We do NOT drop it +-- here so a botched rollout can be reversed without re-creating data. +-- A follow-up destructive migration removes it in a later release. +DO $$ BEGIN RAISE NOTICE '[Migration 000045] Renaming organization_members → organization_members_pre_plan3'; END $$; +ALTER TABLE organization_members RENAME TO organization_members_pre_plan3; + +-- The unique-index name must move with the table; renaming the table does +-- not rename the indices in older PG versions, so do it explicitly. +ALTER INDEX IF EXISTS idx_org_members_org_user RENAME TO idx_org_members_org_user_pre_plan3; +ALTER INDEX IF EXISTS idx_org_members_user_id RENAME TO idx_org_members_user_id_pre_plan3; +ALTER INDEX IF EXISTS idx_org_members_tenant_id RENAME TO idx_org_members_tenant_id_pre_plan3; +ALTER INDEX IF EXISTS idx_org_members_role RENAME TO idx_org_members_role_pre_plan3; + +DO $$ BEGIN RAISE NOTICE '[Migration 000045] Plan 3 setup ready'; END $$;