feat(rbac): lift org membership from per-user to per-tenant (Plan 3, #1303)
Before this change, the `organization_members` table keyed on user_id — joining an org as a Viewer in tenant T meant only that one user got visibility on shared KBs/agents, while the rest of T (including its Owner) saw nothing. The mismatch surfaced as confusing UX bugs: "my colleague shared this with us, why can't I see it?" This change replaces `organization_members` with `organization_tenant_members`. Membership and Org-RBAC role now key on (org_id, tenant_id); `representative_user_id` stays as a display-only label of the user who first brought the tenant in. Permission resolution gains a 3-D cap so tenant-RBAC stays honest under cross-tenant sharing: 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. A Viewer in their own tenant cannot edit a shared KB even if the org granted Editor — preserves the "Viewer = read-only everywhere" promise. Migration 000045 backfills `organization_tenant_members` from the old table by collapsing each (org, tenant) group to its max role, then renames the old table to `organization_members_pre_plan3` for safe rollback. Sqlite mirror (Lite mode) is fresh-bootstrap: the init schema replaces the old table directly. Routes: member-management URLs change from `:user_id` to `:tenant_id`. Org create / join / leave now require Admin+ in the caller's tenant — joining an Org affects everyone in T, so the decision can't sit with a Viewer. Frontend: OrganizationSettingsModal + store update to address members by tenant_id.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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("无权访问该知识库")
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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("无权访问该知识库")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user