feat(system): consolidate system admin and settings into one Settings panel

Replace the standalone /platform/system/* routes with a single
"系统设置" section inside the canonical Settings modal. The previous
SystemLayout.vue / SystemAdmins.vue surfaces are removed and their
functionality (system admin roster, global settings) is hosted directly
in SystemSettings.vue under the standard `.section-header` /
`.settings-group` skeleton. Legacy URLs redirect to the modal section
so external bookmarks don't 404.

Backend:
- SystemSettingService.Reset + repo.Delete: drop the DB override for a
  key so the 3-tier resolver falls back to ENV / built-in default.
  Idempotent (resetting a never-persisted key returns nil); emits an
  audit row only on real deletions, invalidates the local cache, and
  publishes to peers via the existing pubsub channel.
- TenantService.BulkSetStorageQuota: overwrite every tenant's
  storage_quota in one statement. Powers POST /system/admin/tenants/
  apply-default-storage-quota; bypasses the per-tenant whitelist on
  PUT /tenants/:id which intentionally forbids storage_quota edits.
- AuditAction{SystemAdminPromoted,SystemAdminRevoked} constants and
  emitAdminAudit() in SystemHandler — promote / revoke now leave an
  audit trail with TenantID=0 and {target_email,target_username,
  idempotent|changed} in details.
- SystemSetting.LastModifiedByName: derived per-request display label
  (username, email fallback) so the UI shows "wizardchen" instead of
  a UUID prefix without storing a denormalised column.

Frontend:
- SystemSettings.vue rewritten against the Settings modal skeleton with
  auto-persisting controls (switch/select @change, input/inputnumber
  @blur, tag-input + per-delta popconfirm for SSRF whitelist and admin
  roster). auth.registration_mode change goes through an inline
  popconfirm; cancel rolls back. Reset / bulk-apply also inline
  popconfirms — no dialog modal for these per-row affordances.
- Priority hint panel surfaces the DB > ENV > default resolver order
  so operators can reason about "I set the env but it doesn't show up".
- Router: /platform/system, /platform/system/settings, /platform/system/
  admins are now compatibility redirects to /platform/settings?section=
  system-global.
- Settings modal sized 900x700 → 1080x780 and content-wrapper 600 → 760
  so the wider tables (members, system settings) breathe; <1100px
  viewport still flexes to the screen.
- i18n: system.globalSettings.* keys for title / description / loading /
  empty / badges / priority hint / per-key labels / reset / bulkApply /
  admins (label, placeholder, save messages, popconfirm copy) across
  zh-CN, en-US, ko-KR, ru-RU.

Misc:
- internal/utils/filesize.go doc: clarify MAX_FILE_SIZE_MB is a
  deploy-time-only knob (nginx + docreader + frontend each cache the
  env at startup); a SystemAdmin UI override would mislead operators
  because nginx would still 413. Until all four layers can hot-reload
  the limit in lockstep, this stays env-only.
- internal/utils/security.go: SSRF whitelist parser/runtime now drives
  off SystemSettingService for live updates; ENV remains the fallback
  for never-overridden deployments.
This commit is contained in:
wizardchen
2026-05-26 20:03:35 +08:00
committed by lyingbug
parent 311a033523
commit 9cce0c8e5e
31 changed files with 2207 additions and 753 deletions
+3 -5
View File
@@ -61,7 +61,6 @@ type InitializationHandler struct {
ollamaService *ollama.OllamaService
documentReader interfaces.DocumentReader
pooler embedding.EmbedderPooler
systemSettingSvc interfaces.SystemSettingService
}
// NewInitializationHandler 创建初始化处理器
@@ -75,7 +74,6 @@ func NewInitializationHandler(
ollamaService *ollama.OllamaService,
documentReader interfaces.DocumentReader,
pooler embedding.EmbedderPooler,
systemSettingSvc interfaces.SystemSettingService,
) *InitializationHandler {
return &InitializationHandler{
config: config,
@@ -87,7 +85,6 @@ func NewInitializationHandler(
ollamaService: ollamaService,
documentReader: documentReader,
pooler: pooler,
systemSettingSvc: systemSettingSvc,
}
}
@@ -2123,8 +2120,9 @@ func (h *InitializationHandler) TestMultimodalFunction(c *gin.Context) {
return
}
// 验证文件大小 — 走 system_settings 三级 resolver(DB > ENV > 50 默认)
maxSizeMB := h.systemSettingSvc.GetInt(ctx, "file.max_size_mb", "MAX_FILE_SIZE_MB", 50)
// 验证文件大小 — MAX_FILE_SIZE_MB env (50MB 默认)。
// 见 utils/filesize.go 注释:故意保留为部署期 env,不做 runtime setting。
maxSizeMB := utils.GetMaxFileSizeMB()
maxSize := maxSizeMB * 1024 * 1024
if header.Size > maxSize {
logger.Error(ctx, "File size too large")
+5 -9
View File
@@ -34,9 +34,6 @@ type KnowledgeHandler struct {
kbShareService interfaces.KBShareService
agentShareService interfaces.AgentShareService
asynqClient interfaces.TaskEnqueuer
// systemSettingSvc consults the platform-wide system_settings table
// for runtime tunables (file size limit etc.), with ENV/default fallback.
systemSettingSvc interfaces.SystemSettingService
}
// NewKnowledgeHandler creates a new knowledge handler instance
@@ -46,7 +43,6 @@ func NewKnowledgeHandler(
kbShareService interfaces.KBShareService,
agentShareService interfaces.AgentShareService,
asynqClient interfaces.TaskEnqueuer,
systemSettingSvc interfaces.SystemSettingService,
) *KnowledgeHandler {
return &KnowledgeHandler{
kgService: kgService,
@@ -54,7 +50,6 @@ func NewKnowledgeHandler(
kbShareService: kbShareService,
agentShareService: agentShareService,
asynqClient: asynqClient,
systemSettingSvc: systemSettingSvc,
}
}
@@ -271,10 +266,11 @@ func (h *KnowledgeHandler) CreateKnowledgeFromFile(c *gin.Context) {
return
}
// Validate file size — 3-tier resolver (DB > ENV > 50 MB default).
// SystemAdmin can update this via the global-settings UI and the
// new value applies on the very next upload (no restart needed).
maxSizeMB := h.systemSettingSvc.GetInt(ctx, "file.max_size_mb", "MAX_FILE_SIZE_MB", 50)
// Validate file size — read MAX_FILE_SIZE_MB env (50MB default).
// Deliberately not a runtime system_setting; see filesize.go for the
// rationale (nginx / docreader / browser bundle all cache this at
// container startup, so a UI knob would silently mismatch).
maxSizeMB := utils.GetMaxFileSizeMB()
maxSize := maxSizeMB * 1024 * 1024
if file.Size > maxSize {
logger.Error(ctx, "File size too large")
-3
View File
@@ -28,7 +28,6 @@ type Handler struct {
fileService interfaces.FileService // Service for file storage (image uploads)
modelService interfaces.ModelService // Service for model management (VLM access)
userService interfaces.UserService // Service for resolving per-user preferences (e.g. enable_memory default)
systemSettingSvc interfaces.SystemSettingService // 3-tier resolver for runtime tunables (file size limit etc.)
attachmentProcessor *AttachmentProcessor // Processor for file attachments
}
@@ -48,7 +47,6 @@ func NewHandler(
userService interfaces.UserService,
documentReader interfaces.DocumentReader,
imageResolver *docparser.ImageResolver,
systemSettingSvc interfaces.SystemSettingService,
) *Handler {
return &Handler{
sessionService: sessionService,
@@ -63,7 +61,6 @@ func NewHandler(
fileService: fileService,
modelService: modelService,
userService: userService,
systemSettingSvc: systemSettingSvc,
attachmentProcessor: NewAttachmentProcessor(
fileService,
documentReader,
+3 -3
View File
@@ -170,9 +170,9 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
if len(request.AttachmentUploads) > 0 {
logger.Infof(ctx, "[%s] processing %d attachment(s)", logPrefix, len(request.AttachmentUploads))
// 3-tier resolver: DB > ENV > 50MB. Edits via the system-admin
// settings UI take effect on the very next request.
maxSizeMB := h.systemSettingSvc.GetInt(ctx, "file.max_size_mb", "MAX_FILE_SIZE_MB", 50)
// MAX_FILE_SIZE_MB env (50MB default). See utils/filesize.go for
// why this is deploy-time-only rather than a runtime setting.
maxSizeMB := secutils.GetMaxFileSizeMB()
maxSize := maxSizeMB * 1024 * 1024
for i, upload := range request.AttachmentUploads {
if upload.FileSize > maxSize {
+282 -27
View File
@@ -2,6 +2,7 @@ package handler
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
@@ -35,6 +36,10 @@ type SystemHandler struct {
tenantSvc interfaces.TenantService
userSvc interfaces.UserService
systemSettingSvc interfaces.SystemSettingService
// auditSvc is optional — when nil, emitAdminAudit no-ops so unit
// tests that wire a partial container still compile. In production
// the dig graph always provides one.
auditSvc interfaces.AuditLogService
}
// NewSystemHandler creates a new system handler
@@ -44,6 +49,7 @@ func NewSystemHandler(cfg *config.Config,
tenantSvc interfaces.TenantService,
userSvc interfaces.UserService,
systemSettingSvc interfaces.SystemSettingService,
auditSvc interfaces.AuditLogService,
) *SystemHandler {
return &SystemHandler{
cfg: cfg,
@@ -52,9 +58,52 @@ func NewSystemHandler(cfg *config.Config,
tenantSvc: tenantSvc,
userSvc: userSvc,
systemSettingSvc: systemSettingSvc,
auditSvc: auditSvc,
}
}
// emitAdminAudit writes one audit row for a system-admin lifecycle event
// (promote / revoke). Best-effort — a nil audit service or a write
// failure does not bubble up to the caller. Mirrors the failure
// semantics of tenantMemberService.emitAudit and the system settings
// audit hook.
//
// `details` may be nil; the JSON `{}` default applies.
func (h *SystemHandler) emitAdminAudit(
ctx context.Context,
action types.AuditAction,
target *types.User,
details map[string]any,
) {
if h.auditSvc == nil {
return
}
actorID, _ := types.UserIDFromContext(ctx)
var detailsJSON types.JSON
if details != nil {
if b, err := json.Marshal(details); err == nil {
detailsJSON = types.JSON(b)
}
}
entry := &types.AuditLog{
// tenant_id=0 marks the row as system-scope. The audit_logs
// table is tenant-scoped; 0 is the convention for platform-wide
// events (matches AuditActionSystemSettingChanged).
TenantID: 0,
ActorUserID: actorID,
ActorRole: "system_admin",
Action: action,
TargetType: "user",
Outcome: types.AuditOutcomeSuccess,
Details: detailsJSON,
}
if target != nil {
entry.TargetID = target.ID
entry.TargetUserID = target.ID
}
_ = h.auditSvc.Log(ctx, entry)
}
// GetSystemInfoResponse defines the response structure for system info
type GetSystemInfoResponse struct {
Version string `json:"version"`
@@ -1017,15 +1066,26 @@ func (h *SystemHandler) ResolveDocumentReader(ctx context.Context, addr string)
return reader
}
// PromoteUserToSystemAdminRequest defines the request for promoting a user to system admin
// PromoteUserToSystemAdminRequest defines the request for promoting a user to system admin.
//
// Either user_id (UUID) or email must be supplied. When both are present
// user_id wins — explicit IDs are unambiguous, an email collision (extremely
// rare in practice but possible during a tenant merge) would otherwise
// silently target the wrong row.
//
// We don't expose a `binding:"required"` tag on either field because gin's
// validator can't express the OR constraint; the handler does the check
// manually and returns 400 with a specific message for each branch.
type PromoteUserToSystemAdminRequest struct {
UserID string `json:"user_id" binding:"required"`
UserID string `json:"user_id"`
Email string `json:"email"`
}
// PromoteUserToSystemAdmin godoc
// @Summary Promote a user to system administrator
// @Description Grant system administrator privileges to a user (SystemAdmin only).
// @Description Idempotent: re-promoting an existing system admin returns 200 with no DB write.
// @Description Identify the user by email (preferred for human operators) or user_id (UUID, for API clients).
// @Tags System Admin
// @Accept json
// @Produce json
@@ -1044,9 +1104,30 @@ func (h *SystemHandler) PromoteUserToSystemAdmin(c *gin.Context) {
return
}
user, err := h.userSvc.GetUserByID(ctx, req.UserID)
userID := strings.TrimSpace(req.UserID)
email := strings.TrimSpace(req.Email)
if userID == "" && email == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Either user_id or email is required"})
return
}
// Resolve user. user_id takes priority when both are sent (see request
// struct doc); otherwise we look up by email. Both branches funnel
// into the same {nil-user / error} 404 so we don't leak whether a
// given email exists in the system to non-admins — though SystemAdmin
// is already a high-trust role, the parity keeps the surface clean.
var (
user *types.User
err error
)
switch {
case userID != "":
user, err = h.userSvc.GetUserByID(ctx, userID)
default:
user, err = h.userSvc.GetUserByEmail(ctx, email)
}
if err != nil {
logger.Errorf(ctx, "Error fetching user %s: %v", req.UserID, err)
logger.Errorf(ctx, "Error fetching user (id=%q email=%q): %v", userID, email, err)
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
return
}
@@ -1056,7 +1137,14 @@ func (h *SystemHandler) PromoteUserToSystemAdmin(c *gin.Context) {
}
if user.IsSystemAdmin {
// Idempotent: re-promoting an existing system admin is a no-op success.
// Idempotent: re-promoting an existing system admin is a no-op
// success. We still emit an audit row so probing the endpoint
// leaves a forensic trail (idempotent=true marks it as noop).
h.emitAdminAudit(ctx, types.AuditActionSystemAdminPromoted, user, map[string]any{
"target_email": user.Email,
"target_username": user.Username,
"idempotent": true,
})
c.JSON(http.StatusOK, user.ToUserInfo())
return
}
@@ -1068,6 +1156,11 @@ func (h *SystemHandler) PromoteUserToSystemAdmin(c *gin.Context) {
}
logger.Infof(ctx, "User %s (ID: %s) promoted to system admin", user.Username, user.ID)
h.emitAdminAudit(ctx, types.AuditActionSystemAdminPromoted, user, map[string]any{
"target_email": user.Email,
"target_username": user.Username,
"idempotent": false,
})
c.JSON(http.StatusOK, user.ToUserInfo())
}
@@ -1103,32 +1196,54 @@ func (h *SystemHandler) RevokeSystemAdmin(c *gin.Context) {
callerID, _ := types.UserIDFromContext(ctx)
user, err := h.userSvc.RevokeSystemAdmin(ctx, req.UserID, callerID)
if err != nil {
switch {
case errors.Is(err, repository.ErrCannotRevokeSelf):
c.JSON(http.StatusBadRequest, gin.H{
"error": "Cannot revoke your own system admin privileges",
})
case errors.Is(err, repository.ErrLastSystemAdmin):
c.JSON(http.StatusBadRequest, gin.H{
"error": "Cannot revoke the last remaining system administrator",
})
case errors.Is(err, repository.ErrUserNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
default:
logger.Errorf(ctx, "Error revoking system admin from user %s: %v", req.UserID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to revoke system admin privileges"})
}
switch {
case err == nil:
// Real revoke — privileges were actually removed.
logger.Infof(ctx, "System admin privileges revoked from user %s (ID: %s)", user.Username, user.ID)
h.emitAdminAudit(ctx, types.AuditActionSystemAdminRevoked, user, map[string]any{
"target_email": user.Email,
"target_username": user.Username,
"changed": true,
})
c.JSON(http.StatusOK, user.ToUserInfo())
return
}
if user == nil {
logger.Errorf(ctx, "RevokeSystemAdmin returned nil user for %s", req.UserID)
case errors.Is(err, repository.ErrUserNotSystemAdmin):
// Idempotent: target was already not an admin. Return 200 so
// callers that re-issue the request after a partial failure
// don't get a confusing 4xx, but mark `changed=false` in the
// audit row so a forensic reader can tell a real revoke from a
// noop probe.
if user == nil {
logger.Errorf(ctx, "RevokeSystemAdmin returned nil user with ErrUserNotSystemAdmin for %s", req.UserID)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to revoke system admin privileges"})
return
}
logger.Infof(ctx, "Revoke noop (user %s was not a system admin)", user.ID)
h.emitAdminAudit(ctx, types.AuditActionSystemAdminRevoked, user, map[string]any{
"target_email": user.Email,
"target_username": user.Username,
"changed": false,
})
c.JSON(http.StatusOK, user.ToUserInfo())
return
case errors.Is(err, repository.ErrCannotRevokeSelf):
c.JSON(http.StatusBadRequest, gin.H{
"error": "Cannot revoke your own system admin privileges",
})
return
case errors.Is(err, repository.ErrLastSystemAdmin):
c.JSON(http.StatusBadRequest, gin.H{
"error": "Cannot revoke the last remaining system administrator",
})
return
case errors.Is(err, repository.ErrUserNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
return
default:
logger.Errorf(ctx, "Error revoking system admin from user %s: %v", req.UserID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to revoke system admin privileges"})
return
}
logger.Infof(ctx, "System admin privileges revoked from user %s (ID: %s)", user.Username, user.ID)
c.JSON(http.StatusOK, user.ToUserInfo())
}
// ListSystemAdminsResponse defines the response structure for listing system admins.
@@ -1229,9 +1344,57 @@ func (h *SystemHandler) ListSystemSettings(c *gin.Context) {
// is safer.
rows = []*types.SystemSetting{}
}
h.enrichSettingsModifiedBy(ctx, rows)
c.JSON(http.StatusOK, rows)
}
// enrichSettingsModifiedBy resolves LastModifiedBy (UUID) → display name
// in a single batch lookup. Failures degrade silently: the UI already
// falls back to the UUID prefix when the name is empty, so a transient
// userSvc error must not break the settings page entirely.
func (h *SystemHandler) enrichSettingsModifiedBy(ctx context.Context, rows []*types.SystemSetting) {
if len(rows) == 0 || h.userSvc == nil {
return
}
idSet := make(map[string]struct{}, len(rows))
for _, r := range rows {
if r != nil && strings.TrimSpace(r.LastModifiedBy) != "" {
idSet[r.LastModifiedBy] = struct{}{}
}
}
if len(idSet) == 0 {
return
}
ids := make([]string, 0, len(idSet))
for id := range idSet {
ids = append(ids, id)
}
users, err := h.userSvc.GetUsersByIDs(ctx, ids)
if err != nil {
logger.Warnf(ctx, "enrichSettingsModifiedBy: GetUsersByIDs failed: %v", err)
return
}
for _, r := range rows {
if r == nil {
continue
}
u, ok := users[r.LastModifiedBy]
if !ok || u == nil {
continue
}
// Username is the canonical display label; fall back to email
// for older rows where username may be empty (legacy seeded
// admins). Both empty → leave LastModifiedByName empty so the
// UI's UUID-prefix fallback kicks in.
switch {
case strings.TrimSpace(u.Username) != "":
r.LastModifiedByName = u.Username
case strings.TrimSpace(u.Email) != "":
r.LastModifiedByName = u.Email
}
}
}
// GetSystemSetting godoc
// @Summary Get a single system setting by key
// @Description Returns the row matching :key. 404 when the key is unknown
@@ -1309,5 +1472,97 @@ func (h *SystemHandler) UpdateSystemSetting(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
h.enrichSettingsModifiedBy(ctx, []*types.SystemSetting{row})
c.JSON(http.StatusOK, row)
}
// ApplyDefaultStorageQuotaToAllTenants godoc
// @Summary Apply the default storage quota to every existing tenant
// @Description Reads the current value of `tenant.default_storage_quota_gb`
// @Description (3-tier resolver: DB > ENV > default) and writes that many
// @Description GiB into storage_quota for every row in tenants. Bypasses
// @Description the per-tenant PUT whitelist, which forbids storage_quota
// @Description edits by Owners. SystemAdmin only.
// @Description Idempotent — running twice with the same setting is a no-op.
// @Tags System Admin
// @Produce json
// @Success 200 {object} map[string]interface{} "{ affected: int64, quota_bytes: int64 }"
// @Failure 500 {object} map[string]interface{} "DB write failed"
// @Router /system/admin/tenants/apply-default-storage-quota [post]
func (h *SystemHandler) ApplyDefaultStorageQuotaToAllTenants(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
// Resolve via the same 3-tier path the CreateTenant handler uses
// so the action's effect mirrors what new tenants would receive.
gb := h.systemSettingSvc.GetInt(
ctx,
"tenant.default_storage_quota_gb",
"WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB",
10,
)
if gb <= 0 {
gb = 10
}
quotaBytes := gb * 1024 * 1024 * 1024
affected, err := h.tenantSvc.BulkSetStorageQuota(ctx, quotaBytes)
if err != nil {
logger.Errorf(ctx, "BulkSetStorageQuota failed: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to apply storage quota"})
return
}
// Audit. We capture quota_bytes (the actual value written) rather
// than the GB literal so the audit row is unambiguous if someone
// later changes the setting's units.
if h.auditSvc != nil {
actorID, _ := types.UserIDFromContext(ctx)
details, _ := json.Marshal(map[string]any{
"quota_bytes": quotaBytes,
"quota_gb": gb,
"affected": affected,
})
_ = h.auditSvc.Log(ctx, &types.AuditLog{
TenantID: 0,
ActorUserID: actorID,
ActorRole: "system_admin",
Action: types.AuditActionSystemSettingChanged,
TargetType: "tenant_storage_quota",
TargetID: "all",
Outcome: types.AuditOutcomeSuccess,
Details: types.JSON(details),
})
}
c.JSON(http.StatusOK, gin.H{
"affected": affected,
"quota_bytes": quotaBytes,
"quota_gb": gb,
})
}
// ResetSystemSetting godoc
// @Summary Reset a system setting to ENV / built-in default
// @Description Removes the DB override for :key so the 3-tier resolver
// @Description falls back to the environment variable (when configured)
// @Description or the in-code default. Idempotent — resetting a key
// @Description that was never persisted returns 200.
// @Tags System Admin
// @Param key path string true "Setting key"
// @Success 200 {object} map[string]interface{} "Reset acknowledged"
// @Failure 400 {object} map[string]interface{} "Unknown key"
// @Failure 500 {object} map[string]interface{} "DB write failed"
// @Router /system/admin/settings/{key} [delete]
func (h *SystemHandler) ResetSystemSetting(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
key := c.Param("key")
if err := h.systemSettingSvc.Reset(ctx, key); err != nil {
// Service surfaces "unknown key" as a plain error string; treat
// every error as 400 so the UI captures it as a toast. A real
// DB failure here is rare and indistinguishable from "bad key"
// at this layer — operators see the message either way.
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
+57 -13
View File
@@ -1,6 +1,7 @@
package handler
import (
"context"
"net/http"
"strconv"
"strings"
@@ -24,6 +25,11 @@ type TenantHandler struct {
memberService interfaces.TenantMemberService
kbService interfaces.KnowledgeBaseService
config *config.Config
// systemSettingSvc resolves runtime tunables for tenant limits
// (currently `tenant.max_owned_per_user`). Reading goes DB > ENV >
// in-code default, so a SystemAdmin's UI override applies on the
// very next CreateTenant call.
systemSettingSvc interfaces.SystemSettingService
}
// NewTenantHandler creates a new tenant handler instance with the provided service
@@ -49,13 +55,15 @@ func NewTenantHandler(
memberService interfaces.TenantMemberService,
kbService interfaces.KnowledgeBaseService,
config *config.Config,
systemSettingSvc interfaces.SystemSettingService,
) *TenantHandler {
return &TenantHandler{
service: service,
userService: userService,
memberService: memberService,
kbService: kbService,
config: config,
service: service,
userService: userService,
memberService: memberService,
kbService: kbService,
config: config,
systemSettingSvc: systemSettingSvc,
}
}
@@ -94,6 +102,25 @@ type updateTenantRequest struct {
// blunting drive-by abuse against POST /tenants (see CreateTenant).
const defaultMaxOwnedTenantsPerUser = 10
// resolveMaxOwnedTenantsPerUser returns the current cap, walking the
// 3-tier resolver: system_settings DB row > WEKNORA_TENANT_MAX_OWNED_PER_USER
// env > config.Tenant.MaxOwnedPerUser (yaml) > defaultMaxOwnedTenantsPerUser.
// We pre-compute the cfg-derived fallback so the SystemSettingService
// receives a single int64 default — its 3-tier resolver layers DB and
// env on top of that.
func (h *TenantHandler) resolveMaxOwnedTenantsPerUser(ctx context.Context) int {
fallback := int64(defaultMaxOwnedTenantsPerUser)
if h.config != nil && h.config.Tenant != nil && h.config.Tenant.MaxOwnedPerUser != 0 {
fallback = int64(h.config.Tenant.MaxOwnedPerUser)
}
return int(h.systemSettingSvc.GetInt(
ctx,
"tenant.max_owned_per_user",
"WEKNORA_TENANT_MAX_OWNED_PER_USER",
fallback,
))
}
// CreateTenant godoc
// @Summary 创建租户
// @Description 创建新的租户。任意已登录用户均可调用以建立自己的新工作区,
@@ -169,10 +196,7 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
ownedCount++
}
}
cap := defaultMaxOwnedTenantsPerUser
if h.config != nil && h.config.Tenant != nil && h.config.Tenant.MaxOwnedPerUser != 0 {
cap = h.config.Tenant.MaxOwnedPerUser
}
cap := h.resolveMaxOwnedTenantsPerUser(ctx)
if cap > 0 && ownedCount >= cap {
logger.Warnf(ctx,
"User %s reached self-service tenant quota (%d/%d)",
@@ -191,6 +215,29 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
}
}
// Apply the system-setting-driven default storage quota when the
// caller didn't specify one (always true for self-serve; sometimes
// true for the superuser branch when the JSON omits storage_quota).
// We resolve at create time on purpose — the on-disk row should
// carry an explicit value, so changing the setting later doesn't
// silently shrink/grow established tenants. Negative values are
// treated as "use default" so a misconfigured setting can't yield
// a negative quota that the storage-used checks would interpret as
// "unlimited" (StorageQuota <= 0 disables enforcement in
// knowledge_create.go).
if tenantData.StorageQuota <= 0 {
gb := h.systemSettingSvc.GetInt(
ctx,
"tenant.default_storage_quota_gb",
"WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB",
10,
)
if gb <= 0 {
gb = 10
}
tenantData.StorageQuota = gb * 1024 * 1024 * 1024
}
logger.Infof(ctx, "Creating tenant, name: %s", secutils.SanitizeForLog(tenantData.Name))
createdTenant, err := h.service.CreateTenant(ctx, &tenantData)
@@ -248,10 +295,7 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
ownedNow++
}
}
cap := defaultMaxOwnedTenantsPerUser
if h.config != nil && h.config.Tenant != nil && h.config.Tenant.MaxOwnedPerUser != 0 {
cap = h.config.Tenant.MaxOwnedPerUser
}
cap := h.resolveMaxOwnedTenantsPerUser(ctx)
if cap > 0 && ownedNow > cap {
logger.Warnf(ctx,
"User %s exceeded tenant quota after concurrent create (%d/%d), rolling back tenant %d",