Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(organization): implement tenant-based access control for organization visibility

wizardchen3d30a9d84207
diff --git a/internal/handler/organization.go b/internal/handler/organization.go
index 82c2884ad..a68370842 100644
--- a/internal/handler/organization.go
+++ b/internal/handler/organization.go
@@ -115,6 +115,7 @@ func (h *OrganizationHandler) GetOrganization(c *gin.Context) {
orgID := c.Param("id")
userID := c.GetString(types.UserIDContextKey.String())
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
org, err := h.orgService.GetOrganization(ctx, orgID)
if err != nil {
@@ -123,6 +124,21 @@ func (h *OrganizationHandler) GetOrganization(c *gin.Context) {
return
}
+ // Membership / visibility gate. Without this, any authenticated
+ // user could enumerate organizations by guessing UUIDs and learn
+ // names / owner_id / counts. We allow access when either:
+ // 1. the caller's tenant is a member of the org, or
+ // 2. the org has opted in to discovery (Searchable = true), which
+ // is the same surface area returned by GET /organizations/search.
+ // Anything else returns 404 (not 403) so we don't even confirm the
+ // org's existence to non-members of private orgs.
+ if !org.Searchable {
+ if _, err := h.orgService.GetTenantMember(ctx, orgID, tenantID); err != nil {
+ c.Error(apperrors.NewNotFoundError("Organization not found"))
+ return
+ }
+ }
+
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": h.toOrgResponse(ctx, org, userID),
@@ -365,6 +381,17 @@ func (h *OrganizationHandler) ListMembers(c *gin.Context) {
ctx := c.Request.Context()
orgID := c.Param("id")
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+
+ // Member roster is sensitive: it surfaces every tenant in the org
+ // plus the representative user (username/email/avatar). Only orgs
+ // the caller's tenant actually belongs to may be listed; non-members
+ // get 403 — mirrors ListOrgShares / ListOrgAgentShares which already
+ // gate on GetTenantMember.
+ if _, err := h.orgService.GetTenantMember(ctx, orgID, tenantID); err != nil {
+ c.Error(apperrors.NewForbiddenError("Your tenant is not a member of this organization"))
+ return
+ }
members, err := h.orgService.ListTenantMembers(ctx, orgID)
if err != nil {
diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go
index be27e63ab..ec8421cc0 100644
--- a/internal/handler/tenant.go
+++ b/internal/handler/tenant.go
@@ -34,7 +34,7 @@ type TenantHandler struct {
// the creator as Owner of the tenant they just created (self-service create).
// - config: Application configuration
//
-// Returns a pointer to the newly created TenantHandler
+// # Returns a pointer to the newly created TenantHandler
//
// Note on RBAC: cross-tenant gating (CanAccessAllTenants /
// EnableCrossTenantAccess) and per-tenant path matching (URL :id ==
@@ -228,6 +228,54 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
c.Error(errors.NewInternalServerError("Failed to finalise tenant ownership").WithDetails(err.Error()))
return
}
+
+ // Quota TOCTOU guard. The earlier ownedCount check is racy:
+ // N concurrent CreateTenant calls all read ownedCount < cap,
+ // all proceed, all insert. Re-count AFTER the Owner membership
+ // is committed; if we landed over the cap, roll back this
+ // tenant + its membership so the bound holds in steady state.
+ // We only do this for non-superusers (the only path that has
+ // a cap) — superusers are exempt above.
+ if !caller.CanAccessAllTenants {
+ memberships, listErr := h.memberService.ListByUser(ctx, caller.ID)
+ if listErr != nil {
+ logger.Errorf(ctx, "Post-create quota recount failed for user %s tenant %d: %v",
+ caller.ID, createdTenant.ID, listErr)
+ } else {
+ ownedNow := 0
+ for _, m := range memberships {
+ if m != nil && m.Role == types.TenantRoleOwner {
+ ownedNow++
+ }
+ }
+ cap := defaultMaxOwnedTenantsPerUser
+ if h.config != nil && h.config.Tenant != nil && h.config.Tenant.MaxOwnedPerUser != 0 {
+ cap = h.config.Tenant.MaxOwnedPerUser
+ }
+ if cap > 0 && ownedNow > cap {
+ logger.Warnf(ctx,
+ "User %s exceeded tenant quota after concurrent create (%d/%d), rolling back tenant %d",
+ caller.ID, ownedNow, cap, createdTenant.ID,
+ )
+ if rmErr := h.memberService.RemoveMember(ctx, caller.ID, createdTenant.ID); rmErr != nil {
+ logger.Errorf(ctx,
+ "Rollback RemoveMember failed for user %s tenant %d: %v",
+ caller.ID, createdTenant.ID, rmErr,
+ )
+ }
+ if delErr := h.service.DeleteTenant(ctx, createdTenant.ID); delErr != nil {
+ logger.Errorf(ctx,
+ "Rollback DeleteTenant failed for over-quota tenant %d: %v",
+ createdTenant.ID, delErr,
+ )
+ }
+ c.Error(errors.NewTooManyRequestsError(
+ "reached self-service tenant quota; contact an administrator to raise the limit",
+ ))
+ return
+ }
+ }
+ }
}
logger.Infof(