Files
Enterprise-Knowledge-Base/internal/application/service/tenant.go
T
wizardchen f3d1210577 refactor(rbac): address PR 1 review feedback
Tighten correctness, security and observability of the tenant RBAC
foundation introduced in 3c4cdd70 in response to internal review.

Bugfixes
- custom_agents.runnable_by_viewer: drop the GORM `default:true` tag.
  GORM treats a plain bool's zero value as "unspecified" and silently
  rewrites it to the column default on insert, which would prevent
  admins from ever creating an agent with viewer-runtime disabled. The
  column-level DEFAULT TRUE on the database side still backstops rows
  inserted by raw SQL / migrations.
- TenantMemberRepository.HasAnyMembers: replace `Limit(1).Count(&n)`
  with `Take(&probe)`. GORM's Count ignores Limit and scans the whole
  table, which matters because this runs on the auth middleware's
  hot path for users without a cached membership.
- service/user.LoginWithOIDC: include User, Tenant and Memberships in
  the OIDCCallbackResponse so the OIDC flow returns the same shape as
  password login (previously User and friends were left nil).

Security
- middleware/auth.resolveTenantRole: restrict orphan-tenant
  auto-promotion to the caller's home tenant. Cross-tenant superuser
  visits and JWTs minted for foreign tenants no longer trigger silent
  Owner grants. Two regression tests pin the new behaviour.
- service/user.synthFallbackMembership: default the synthesised role
  to Viewer instead of Owner. The login response only feeds UI; the
  backend re-derives the real role from tenant_members on every
  request, so showing a Viewer UI is preferable to a misleading Owner
  UI that would surface admin controls the backend will then 403.
- migrations/versioned/000043_tenant_rbac.down.sql: gate the destructive
  drop behind a `weknora.allow_destructive_migration` GUC so an
  accidental `migrate down` cannot wipe role data in production.
- frontend/src/stores/auth.ts: comment currentTenantRole as
  rendering-only so future PRs cannot mistake the localStorage-backed
  value for an authorisation signal.

API contract
- Memberships in LoginResponse and OIDCCallbackResponse now serialises
  without omitempty, and buildMembershipsForUser / synthFallbackMembership
  always return a non-nil slice — frontend can rely on JSON `[]`.
- handler/auth.GetCurrentUser includes memberships so /auth/me refreshes
  recover currentTenantRole after a page reload.

Performance
- Add TenantService.GetTenantsByIDs (with the matching repo method) and
  use it inside buildMembershipsForUser to batch tenant-name lookups
  instead of issuing one query per membership.

Observability
- Replace the remaining `log.Printf` calls in middleware/auth with
  contextual logger.Warnf / logger.Infof so role resolution events ride
  the standard request-id / Langfuse trace plumbing. The successful
  auto-promote line is tagged `[audit]` for log mining.

Tests
- internal/application/service/tenant_member_test.go: hand-rolled
  fakeTenantMemberRepo plus 11 cases covering AddMember validation,
  EnsureOwner idempotence, "cannot demote/remove the last Owner",
  same-role no-op, ErrInvalidTenantRole / ErrMembershipNotFound, and
  the TenantRole.HasPermission lattice.
- internal/middleware/auth_role_test.go: fakeMemberService plus 8 cases
  pinning every branch of resolveTenantRole, including the two H1
  regressions (cross-tenant superuser must not auto-promote; orphan
  auto-promote requires the home tenant).
2026-05-18 17:28:58 +08:00

471 lines
14 KiB
Go

package service
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/binary"
"errors"
"io"
"os"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
werrors "github.com/Tencent/WeKnora/internal/errors"
)
var apiKeySecret = func() []byte {
return []byte(os.Getenv("TENANT_AES_KEY"))
}
// ListTenantsParams defines parameters for listing tenants with filtering and pagination
type ListTenantsParams struct {
Page int // Page number for pagination
PageSize int // Number of items per page
Status string // Filter by tenant status
Name string // Filter by tenant name
}
// tenantService implements the TenantService interface
type tenantService struct {
repo interfaces.TenantRepository // Repository for tenant data operations
}
// NewTenantService creates a new tenant service instance
func NewTenantService(repo interfaces.TenantRepository) interfaces.TenantService {
return &tenantService{repo: repo}
}
// CreateTenant creates a new tenant
func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant) (*types.Tenant, error) {
logger.Info(ctx, "Start creating tenant")
if tenant.Name == "" {
logger.Error(ctx, "Tenant name cannot be empty")
return nil, errors.New("tenant name cannot be empty")
}
logger.Infof(ctx, "Creating tenant, name: %s", tenant.Name)
// Create tenant with initial values
tenant.APIKey = s.generateApiKey(0)
tenant.Status = "active"
tenant.CreatedAt = time.Now()
tenant.UpdatedAt = time.Now()
if err := s.validateStorageBucketUniqueness(ctx, tenant); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_name": tenant.Name,
})
return nil, err
}
logger.Info(ctx, "Saving tenant information to database")
if err := s.repo.CreateTenant(ctx, tenant); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_name": tenant.Name,
})
return nil, err
}
logger.Infof(ctx, "Tenant created successfully, ID: %d, generating official API Key", tenant.ID)
plaintextAPIKey := s.generateApiKey(tenant.ID)
tenant.APIKey = plaintextAPIKey
// Manually encrypt APIKey before update, because db.Updates() does not trigger BeforeSave hook
if key := utils.GetAESKey(); key != nil && tenant.APIKey != "" {
if encrypted, err := utils.EncryptAESGCM(tenant.APIKey, key); err == nil {
tenant.APIKey = encrypted
}
}
if err := s.repo.UpdateTenant(ctx, tenant); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenant.ID,
"tenant_name": tenant.Name,
})
return nil, err
}
// Restore plaintext for the response so callers don't see enc:v1: ciphertext.
tenant.APIKey = plaintextAPIKey
logger.Infof(ctx, "Tenant creation and update completed, ID: %d, name: %s", tenant.ID, tenant.Name)
return tenant, nil
}
// GetTenantByID retrieves a tenant by their ID
func (s *tenantService) GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error) {
if id == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
return nil, errors.New("tenant ID cannot be 0")
}
tenant, err := s.repo.GetTenantByID(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": id,
})
return nil, err
}
return tenant, nil
}
// GetTenantsByIDs batches GetTenantByID; returns a map keyed by tenant ID.
func (s *tenantService) GetTenantsByIDs(ctx context.Context, ids []uint64) (map[uint64]*types.Tenant, error) {
return s.repo.GetTenantsByIDs(ctx, ids)
}
// ListTenants retrieves a list of all tenants
func (s *tenantService) ListTenants(ctx context.Context) ([]*types.Tenant, error) {
tenants, err := s.repo.ListTenants(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return nil, err
}
logger.Infof(ctx, "Tenant list retrieved successfully, total: %d", len(tenants))
return tenants, nil
}
// UpdateTenant updates an existing tenant's information
func (s *tenantService) UpdateTenant(ctx context.Context, tenant *types.Tenant) (*types.Tenant, error) {
if tenant.ID == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
return nil, errors.New("tenant ID cannot be 0")
}
logger.Infof(ctx, "Updating tenant, ID: %d, name: %s", tenant.ID, tenant.Name)
if err := s.validateStorageBucketUniqueness(ctx, tenant); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenant.ID,
})
return nil, err
}
// Generate new API key if empty
if tenant.APIKey == "" {
logger.Info(ctx, "API Key is empty, generating new API Key")
tenant.APIKey = s.generateApiKey(tenant.ID)
}
tenant.UpdatedAt = time.Now()
logger.Info(ctx, "Saving tenant information to database")
if err := s.repo.UpdateTenant(ctx, tenant); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenant.ID,
})
return nil, err
}
logger.Infof(ctx, "Tenant updated successfully, ID: %d", tenant.ID)
return tenant, nil
}
// DeleteTenant removes a tenant by their ID
func (s *tenantService) DeleteTenant(ctx context.Context, id uint64) error {
logger.Info(ctx, "Start deleting tenant")
if id == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
return errors.New("tenant ID cannot be 0")
}
logger.Infof(ctx, "Deleting tenant, ID: %d", id)
// Get tenant information for logging
tenant, err := s.repo.GetTenantByID(ctx, id)
if err != nil {
if err.Error() == "record not found" {
logger.Warnf(ctx, "Tenant to be deleted does not exist, ID: %d", id)
} else {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": id,
})
return err
}
} else {
logger.Infof(ctx, "Deleting tenant, ID: %d, name: %s", id, tenant.Name)
}
err = s.repo.DeleteTenant(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": id,
})
return err
}
logger.Infof(ctx, "Tenant deleted successfully, ID: %d", id)
return nil
}
// UpdateAPIKey updates the API key for a specific tenant
func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint64) (string, error) {
logger.Info(ctx, "Start updating tenant API Key")
if id == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
return "", errors.New("tenant ID cannot be 0")
}
tenant, err := s.repo.GetTenantByID(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": id,
})
return "", err
}
logger.Infof(ctx, "Generating new API Key for tenant, ID: %d", id)
plaintextAPIKey := s.generateApiKey(tenant.ID)
tenant.APIKey = plaintextAPIKey
// Manually encrypt APIKey before update, because db.Updates() does not trigger BeforeSave hook
if key := utils.GetAESKey(); key != nil && tenant.APIKey != "" {
if encrypted, err := utils.EncryptAESGCM(tenant.APIKey, key); err == nil {
tenant.APIKey = encrypted
}
}
if err := s.repo.UpdateTenant(ctx, tenant); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": id,
})
return "", err
}
logger.Infof(ctx, "Tenant API Key updated successfully, ID: %d", id)
return plaintextAPIKey, nil
}
// generateApiKey generates a secure API key for tenant authentication
func (r *tenantService) generateApiKey(tenantID uint64) string {
// 1. Convert tenant_id to bytes
idBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(idBytes, uint64(tenantID))
// 2. Encrypt tenant_id using AES-GCM
block, err := aes.NewCipher(apiKeySecret())
if err != nil {
panic("Failed to create AES cipher: " + err.Error())
}
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic("Failed to create GCM cipher: " + err.Error())
}
ciphertext := aesgcm.Seal(nil, nonce, idBytes, nil)
// 3. Combine nonce and ciphertext, then encode with base64
combined := append(nonce, ciphertext...)
encoded := base64.RawURLEncoding.EncodeToString(combined)
// Create final API Key in format: sk-{encrypted_part}
return "sk-" + encoded
}
// ExtractTenantIDFromAPIKey extracts the tenant ID from an API key
func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint64, error) {
// 1. Validate format and extract encrypted part
parts := strings.SplitN(apiKey, "-", 2)
if len(parts) != 2 || parts[0] != "sk" {
return 0, errors.New("invalid API key format")
}
// 2. Decode the base64 part
encryptedData, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return 0, errors.New("invalid API key encoding")
}
// 3. Separate nonce and ciphertext
if len(encryptedData) < 12 {
return 0, errors.New("invalid API key length")
}
nonce, ciphertext := encryptedData[:12], encryptedData[12:]
// 4. Decrypt
block, err := aes.NewCipher(apiKeySecret())
if err != nil {
return 0, errors.New("decryption error")
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return 0, errors.New("decryption error")
}
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return 0, errors.New("API key is invalid or has been tampered with")
}
// 5. Convert back to tenant_id
tenantID := binary.LittleEndian.Uint64(plaintext)
return tenantID, nil
}
// ListAllTenants lists all tenants (for users with cross-tenant access permission)
// This method returns all tenants without filtering, intended for admin users
func (s *tenantService) ListAllTenants(ctx context.Context) ([]*types.Tenant, error) {
tenants, err := s.repo.ListTenants(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return nil, err
}
logger.Infof(ctx, "All tenants list retrieved successfully, total: %d", len(tenants))
return tenants, nil
}
// SearchTenants searches tenants with pagination and filters
func (s *tenantService) SearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]*types.Tenant, int64, error) {
tenants, total, err := s.repo.SearchTenants(ctx, keyword, tenantID, page, pageSize)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"keyword": keyword,
"tenantID": tenantID,
"page": page,
"pageSize": pageSize,
})
return nil, 0, err
}
logger.Infof(ctx, "Tenants search completed, keyword: %s, tenantID: %d, page: %d, pageSize: %d, total: %d, found: %d",
keyword, tenantID, page, pageSize, total, len(tenants))
return tenants, total, nil
}
// GetTenantByIDForUser gets a tenant by ID with permission check
// This method verifies that the user has permission to access the tenant
func (s *tenantService) GetTenantByIDForUser(ctx context.Context, tenantID uint64, userID string) (*types.Tenant, error) {
tenant, err := s.repo.GetTenantByID(ctx, tenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
"user_id": userID,
})
return nil, err
}
return tenant, nil
}
func (s *tenantService) GetWeKnoraCloudCredentials(ctx context.Context) *types.WeKnoraCloudCredentials {
// Try to get tenant info from context first (already loaded by middleware).
// CredentialsConfig.Scan handles decryption, so credentials are ready to use.
if tenant, ok := types.TenantInfoFromContext(ctx); ok {
if creds := tenant.Credentials.GetWeKnoraCloud(); creds != nil {
return creds
}
}
// Fallback: load tenant from repo by tenantID
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
return nil
}
tenant, err := s.repo.GetTenantByID(ctx, tenantID)
if err != nil || tenant == nil {
return nil
}
return tenant.Credentials.GetWeKnoraCloud()
}
func (s *tenantService) validateStorageBucketUniqueness(ctx context.Context, tenant *types.Tenant) error {
if tenant.StorageEngineConfig == nil {
return nil
}
// Fetch existing tenant from DB to compare
var oldTenant *types.Tenant
if tenant.ID != 0 {
var err error
oldTenant, err = s.repo.GetTenantByID(ctx, tenant.ID)
if err != nil && err.Error() != "tenant not found" && err.Error() != "record not found" {
return err
}
}
// Fetch ALL tenants to check for collision.
allTenants, err := s.repo.ListTenants(ctx)
if err != nil {
return err
}
// Helper to get bucket names from a StorageEngineConfig
getBuckets := func(cfg *types.StorageEngineConfig) map[string]string {
if cfg == nil {
return nil
}
res := make(map[string]string)
if cfg.MinIO != nil && cfg.MinIO.BucketName != "" {
res["minio"] = cfg.MinIO.BucketName
}
if cfg.COS != nil && cfg.COS.BucketName != "" {
res["cos"] = cfg.COS.BucketName
}
if cfg.TOS != nil && cfg.TOS.BucketName != "" {
res["tos"] = cfg.TOS.BucketName
}
if cfg.S3 != nil && cfg.S3.BucketName != "" {
res["s3"] = cfg.S3.BucketName
}
if cfg.OSS != nil && cfg.OSS.BucketName != "" {
res["oss"] = cfg.OSS.BucketName
}
return res
}
var oldBuckets map[string]string
if oldTenant != nil {
oldBuckets = getBuckets(oldTenant.StorageEngineConfig)
}
newBuckets := getBuckets(tenant.StorageEngineConfig)
// Collect buckets used by other tenants
usedByOthers := make(map[string]map[string]bool) // provider -> set of bucket names
for _, t := range allTenants {
if t.ID == tenant.ID {
continue
}
tb := getBuckets(t.StorageEngineConfig)
for p, b := range tb {
if usedByOthers[p] == nil {
usedByOthers[p] = make(map[string]bool)
}
usedByOthers[p][b] = true
}
}
// Check if any NEW bucket is already used by someone else, AND it's different from the OLD bucket
for p, b := range newBuckets {
oldB := oldBuckets[p]
if b != oldB { // User is trying to change their bucket name or set a new one
if usedByOthers[p] != nil && usedByOthers[p][b] {
return werrors.NewBadRequestError("存储桶名称「" + b + "」已被其他租户使用,为保证数据隔离,请使用其他名称")
}
}
}
return nil
}