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:
@@ -74,3 +74,17 @@ func (r *systemSettingRepository) Upsert(ctx context.Context, s *types.SystemSet
|
||||
}).
|
||||
Create(s).Error
|
||||
}
|
||||
|
||||
// Delete removes the row by key. The boolean return indicates whether
|
||||
// a row was actually deleted, so the service layer can audit only real
|
||||
// deletions (vs the idempotent no-op when the key was already absent).
|
||||
// gorm's RowsAffected is 0 for "no match" — we keep that as (false, nil)
|
||||
// rather than translating to gorm.ErrRecordNotFound so the caller's
|
||||
// happy path is a single nil check on err.
|
||||
func (r *systemSettingRepository) Delete(ctx context.Context, key string) (bool, error) {
|
||||
res := r.db.WithContext(ctx).Where("key = ?", key).Delete(&types.SystemSetting{})
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
@@ -162,3 +162,24 @@ func (r *tenantRepository) AdjustStorageUsed(ctx context.Context, tenantID uint6
|
||||
return tx.Save(&tenant).Error
|
||||
})
|
||||
}
|
||||
|
||||
// BulkSetStorageQuota writes quotaBytes to storage_quota for every
|
||||
// tenant in one statement. We don't WHERE-filter (the action is
|
||||
// "apply globally"), so the affected count equals the row count of
|
||||
// the tenants table.
|
||||
//
|
||||
// No transaction here: the operation is a single statement and we
|
||||
// don't want to hold a long lock just to update a single column. If
|
||||
// a concurrent CreateTenant lands in the middle, the new row gets
|
||||
// the new default via the system-setting resolver in the handler —
|
||||
// no risk of the new tenant being skipped.
|
||||
func (r *tenantRepository) BulkSetStorageQuota(ctx context.Context, quotaBytes int64) (int64, error) {
|
||||
res := r.db.WithContext(ctx).
|
||||
Model(&types.Tenant{}).
|
||||
Where("1 = 1"). // GORM refuses unconditional UPDATEs without an explicit WHERE
|
||||
Update("storage_quota", quotaBytes)
|
||||
if res.Error != nil {
|
||||
return 0, res.Error
|
||||
}
|
||||
return res.RowsAffected, nil
|
||||
}
|
||||
|
||||
@@ -167,6 +167,15 @@ func (r *userRepository) ListSystemAdmins(ctx context.Context, offset, limit int
|
||||
// RevokeSystemAdmin revokes system-admin privileges inside a transaction.
|
||||
// It locks the current admin rows before counting so concurrent revokes
|
||||
// cannot both observe "two admins" and leave the platform with zero.
|
||||
//
|
||||
// Return contract:
|
||||
// - (user, nil): revoke actually happened; user.IsSystemAdmin == false
|
||||
// - (user, ErrUserNotSystemAdmin): target was already not an admin;
|
||||
// no row was written. Caller should treat as idempotent success but
|
||||
// MUST distinguish it from a real revoke for audit purposes — the
|
||||
// surfaced `user` is the unchanged DB row.
|
||||
// - (nil, ErrCannotRevokeSelf | ErrLastSystemAdmin | ErrUserNotFound | …):
|
||||
// hard rejection; no row written.
|
||||
func (r *userRepository) RevokeSystemAdmin(ctx context.Context, userID, actorID string) (*types.User, error) {
|
||||
if userID == actorID {
|
||||
return nil, ErrCannotRevokeSelf
|
||||
@@ -213,8 +222,12 @@ func (r *userRepository) RevokeSystemAdmin(ctx context.Context, userID, actorID
|
||||
revoked = &user
|
||||
return nil
|
||||
})
|
||||
// Propagate ErrUserNotSystemAdmin up to the handler alongside the
|
||||
// (unchanged) user row. The handler treats it as idempotent success
|
||||
// but emits an audit row with changed=false so a probing pattern
|
||||
// ("revoke every random user id we know") still leaves a trail.
|
||||
if errors.Is(err, ErrUserNotSystemAdmin) {
|
||||
return revoked, nil
|
||||
return revoked, err
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -95,11 +95,24 @@ type settingSpec struct {
|
||||
// the new value, no in-memory state bound at init time we cannot
|
||||
// re-derive)".
|
||||
var registry = map[string]settingSpec{
|
||||
"file.max_size_mb": {
|
||||
Type: "int",
|
||||
EnvName: "MAX_FILE_SIZE_MB",
|
||||
Default: int64(50),
|
||||
},
|
||||
// NOTE: file.max_size_mb is intentionally NOT registered. Although
|
||||
// the Go upload handlers accept a runtime override via
|
||||
// systemSettingSvc.GetInt, the actual upload limit is gated end-to-end
|
||||
// by three independent layers:
|
||||
// 1. nginx client_max_body_size (templated at container startup
|
||||
// from the MAX_FILE_SIZE_MB env var; envsubst writes the
|
||||
// computed value into nginx.conf; nginx is never reloaded
|
||||
// during the container's lifetime).
|
||||
// 2. docreader gRPC max_send/recv_message_length (read from the
|
||||
// MAX_FILE_SIZE_MB env at python startup).
|
||||
// 3. The frontend client-side check (utils/index.ts) reads
|
||||
// window.__RUNTIME_CONFIG__.MAX_FILE_SIZE_MB which is
|
||||
// written into /usr/share/nginx/html/config.js by the
|
||||
// docker-entrypoint at container start.
|
||||
// Surfacing a UI knob whose effect is silently capped by nginx /
|
||||
// docreader / the in-page bundle is worse than not having it.
|
||||
// Keep MAX_FILE_SIZE_MB as a deploy-time env var until all four
|
||||
// layers can be reconfigured in lockstep without restarts.
|
||||
"ssrf.whitelist": {
|
||||
Type: "string_list",
|
||||
EnvName: "SSRF_WHITELIST",
|
||||
@@ -117,6 +130,37 @@ var registry = map[string]settingSpec{
|
||||
Description: "自助注册模式。self_serve = 任何人可注册账号;invite_only = 关闭公网注册," +
|
||||
"仅 Owner/Admin 可邀请。修改后立即生效,但谨慎对待 self_serve(公网会接受 spam)。",
|
||||
},
|
||||
// tenant.max_owned_per_user caps how many tenants a single non-superuser
|
||||
// can create (and Own) via self-service POST /tenants. Read on every
|
||||
// request — UI edits take effect immediately, no restart required. The
|
||||
// EnvName is the same WEKNORA_TENANT_MAX_OWNED_PER_USER that
|
||||
// applyAuthAndTenantDefaults parses at boot, so a deployment that
|
||||
// hasn't created a DB row keeps reading from env exactly as before.
|
||||
// 0 = use the in-code default (10); negative = disable the cap entirely.
|
||||
"tenant.max_owned_per_user": {
|
||||
Type: "int",
|
||||
EnvName: "WEKNORA_TENANT_MAX_OWNED_PER_USER",
|
||||
Default: int64(10),
|
||||
Category: "tenant",
|
||||
Description: "每个非超管用户通过自助创建可拥有的最大租户数。每次创建租户时实时读取," +
|
||||
"修改后立即生效。0 表示使用内置默认值 10;负数表示完全关闭限制(不建议在公开部署使用)。",
|
||||
},
|
||||
// tenant.default_storage_quota_gb is the default storage quota (in GB)
|
||||
// applied to a newly-created tenant when the caller doesn't specify
|
||||
// one explicitly. Read at create time only — changing the value does
|
||||
// NOT retroactively resize already-existing tenants (they keep the
|
||||
// quota stored on their row at creation; superusers can edit
|
||||
// individual tenants via the existing tenant-update path).
|
||||
// 0 or negative = use the in-code default (10 GB).
|
||||
"tenant.default_storage_quota_gb": {
|
||||
Type: "int",
|
||||
EnvName: "WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB",
|
||||
Default: int64(10),
|
||||
Category: "tenant",
|
||||
Description: "新建租户时默认分配的存储配额(GB),包含向量、原文、文本、索引等。" +
|
||||
"仅在创建时读取,修改后只对之后新建的租户生效,不会回写已存在的租户。" +
|
||||
"0 或负数表示使用内置默认值 10GB。",
|
||||
},
|
||||
}
|
||||
|
||||
// systemSettingService wires the repository, audit log, and (P2)
|
||||
@@ -721,20 +765,36 @@ func (s *systemSettingService) Update(ctx context.Context, key string, rawValue
|
||||
// Enum check: only meaningful for "string". Compare the decoded
|
||||
// string against the registry-declared whitelist. Done after
|
||||
// encodeForType so we know the raw value passed type validation.
|
||||
//
|
||||
// Use a local name `str` rather than `s` to avoid shadowing the
|
||||
// outer `*systemSettingService` receiver — the previous version
|
||||
// relied on the shadow being unused inside the block, which was a
|
||||
// trap for future edits.
|
||||
if len(spec.Enum) > 0 && spec.Type == "string" {
|
||||
s, _ := rawValue.(string)
|
||||
str, _ := rawValue.(string)
|
||||
allowed := false
|
||||
for _, opt := range spec.Enum {
|
||||
if s == opt {
|
||||
if str == opt {
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
return nil, fmt.Errorf("invalid value for %q: %q not in %v", key, s, spec.Enum)
|
||||
return nil, fmt.Errorf("invalid value for %q: %q not in %v", key, str, spec.Enum)
|
||||
}
|
||||
}
|
||||
|
||||
// Per-key structural validation. encodeForType already enforces the
|
||||
// value_type contract (int / string / bool / string_list); this hook
|
||||
// is for keys whose value carries an internal grammar that, if
|
||||
// silently malformed, would either fail to take effect at runtime
|
||||
// (e.g. SSRF whitelist parser drops bad CIDRs) or actively
|
||||
// mis-classify input. Reject with 400 so the UI can show a clear
|
||||
// inline error instead of "saved" + nothing happens.
|
||||
if err := validateRegistryEntry(key, rawValue); err != nil {
|
||||
return nil, fmt.Errorf("invalid value for %q: %w", key, err)
|
||||
}
|
||||
|
||||
// Capture pre-image for the audit log — pulled fresh, not from
|
||||
// any cache, so concurrent admin edits race-fairly (last writer
|
||||
// wins, audit reflects what was actually replaced).
|
||||
@@ -780,6 +840,15 @@ func (s *systemSettingService) Update(ctx context.Context, key string, rawValue
|
||||
// the upsert already succeeded. Return the optimistic value.
|
||||
persisted = row
|
||||
}
|
||||
// Mirror the registry-derived enrichment that List/Get apply.
|
||||
// Without this, the persisted row hands back an empty Enum field
|
||||
// to the API client, which causes the management UI to swap a
|
||||
// t-select for a plain text input on the post-save patch and
|
||||
// display the raw enum value (e.g. "self_serve") until the next
|
||||
// full reload. Other registry-only fields (Type via ValueType is
|
||||
// already on the row; Description/Category are persisted) don't
|
||||
// need the same fix-up because they're stored on the row itself.
|
||||
persisted.Enum = spec.Enum
|
||||
|
||||
// Update local cache inline so this replica's next read sees the
|
||||
// new value without waiting for the pubsub roundtrip. Other replicas
|
||||
@@ -796,6 +865,52 @@ func (s *systemSettingService) Update(ctx context.Context, key string, rawValue
|
||||
return persisted, nil
|
||||
}
|
||||
|
||||
// Reset deletes the DB override for `key` so the resolver falls back
|
||||
// to ENV / built-in default. Idempotent — deleting a key that was
|
||||
// never persisted is treated as success (no audit row written, since
|
||||
// nothing actually changed) so retries from the UI can't pile up
|
||||
// noise. Mirrors Update's cache+pubsub+audit+side-effect plumbing on
|
||||
// the success path so other replicas drop the entry too.
|
||||
//
|
||||
// Unknown keys still 400 — we don't want a typo on the URL to silently
|
||||
// pretend it cleared something.
|
||||
func (s *systemSettingService) Reset(ctx context.Context, key string) error {
|
||||
spec, ok := registry[key]
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown setting key %q", key)
|
||||
}
|
||||
|
||||
// Capture pre-image for the audit log before the row vanishes.
|
||||
prev, _ := s.repo.Get(ctx, key)
|
||||
|
||||
deleted, err := s.repo.Delete(ctx, key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete system setting %q: %w", key, err)
|
||||
}
|
||||
|
||||
// Drop from the local cache regardless of `deleted` so a stale
|
||||
// entry from before the row existed (shouldn't happen, but cheap
|
||||
// to defend) gets cleared too.
|
||||
s.mu.Lock()
|
||||
delete(s.cache, key)
|
||||
s.mu.Unlock()
|
||||
|
||||
// Side-effect bridges and pubsub fire even for no-op resets so
|
||||
// peers that may have a stale cached row converge. publishChange
|
||||
// is best-effort; reload() on the peer side handles "row absent"
|
||||
// by deleting the cache entry, which is what we want here.
|
||||
s.dispatchSideEffects(ctx, key)
|
||||
s.publishChange(ctx, key)
|
||||
|
||||
// Only emit an audit row on real deletions. The new_value field
|
||||
// is intentionally null to flag this as a reset (vs an Update
|
||||
// which always writes a concrete new_value).
|
||||
if deleted && prev != nil {
|
||||
s.emitChangeAudit(ctx, key, spec.Type, prev.Value, nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SubscribeRedis starts a single goroutine that subscribes to the
|
||||
// pubsub channel and refreshes the local cache when peers publish
|
||||
// changes. Idempotent (subOnce). When Redis is nil (lite mode) returns
|
||||
@@ -1013,3 +1128,75 @@ func encodeForType(declared string, rawValue any) (types.JSON, error) {
|
||||
return nil, errors.New("unknown declared type: " + declared)
|
||||
}
|
||||
}
|
||||
|
||||
// validateRegistryEntry runs key-specific structural validation that
|
||||
// goes beyond the type contract enforced by encodeForType. It is called
|
||||
// by Update right after the type/enum checks; nil error means the value
|
||||
// is acceptable for persistence.
|
||||
//
|
||||
// Adding new validators:
|
||||
// - keep them strict (reject silently-broken input rather than fixing
|
||||
// it server-side — the user should see what they typed),
|
||||
// - keep them deterministic (no DNS lookups, no env reads),
|
||||
// - keep error messages user-facing (the handler surfaces them as the
|
||||
// 400 body verbatim).
|
||||
func validateRegistryEntry(key string, rawValue any) error {
|
||||
switch key {
|
||||
case "ssrf.whitelist":
|
||||
// Coerce into the same shape encodeForType produced. We don't
|
||||
// look at the encoded JSON because that's already canonicalised
|
||||
// — easier to validate the raw input the user typed.
|
||||
entries, err := coerceToStringSlice(rawValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return utils.ValidateSSRFWhitelistEntries(entries)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// coerceToStringSlice mirrors the input shapes accepted by
|
||||
// encodeForType for "string_list": []any of strings, []string, or a
|
||||
// comma-separated string. Returns the trimmed, empty-stripped result.
|
||||
//
|
||||
// Kept private because the only caller is validateRegistryEntry; the
|
||||
// main encode path has its own (slightly different) coercion that
|
||||
// preserves rejection of non-string elements at a specific index for
|
||||
// clearer error messages.
|
||||
func coerceToStringSlice(rawValue any) ([]string, error) {
|
||||
switch v := rawValue.(type) {
|
||||
case []any:
|
||||
out := make([]string, 0, len(v))
|
||||
for i, item := range v {
|
||||
s, ok := item.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("expected string at index %d, got %T", i, item)
|
||||
}
|
||||
s = strings.TrimSpace(s)
|
||||
if s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
case []string:
|
||||
out := make([]string, 0, len(v))
|
||||
for _, s := range v {
|
||||
s = strings.TrimSpace(s)
|
||||
if s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
case string:
|
||||
out := make([]string, 0, 4)
|
||||
for _, s := range strings.Split(v, ",") {
|
||||
s = strings.TrimSpace(s)
|
||||
if s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("expected string array, got %T", rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,6 +335,23 @@ func (s *tenantService) ListAllTenants(ctx context.Context) ([]*types.Tenant, er
|
||||
return tenants, nil
|
||||
}
|
||||
|
||||
// BulkSetStorageQuota delegates to the repository. Validation is
|
||||
// minimal — quotaBytes <= 0 is rejected because the storage-quota
|
||||
// enforcement in knowledge_create.go treats <=0 as "unlimited", which
|
||||
// is never what a SystemAdmin pressing "apply default" intends.
|
||||
func (s *tenantService) BulkSetStorageQuota(ctx context.Context, quotaBytes int64) (int64, error) {
|
||||
if quotaBytes <= 0 {
|
||||
return 0, errors.New("quota must be positive")
|
||||
}
|
||||
affected, err := s.repo.BulkSetStorageQuota(ctx, quotaBytes)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"quota_bytes": quotaBytes})
|
||||
return 0, err
|
||||
}
|
||||
logger.Infof(ctx, "Bulk set storage_quota=%d on %d tenants", quotaBytes, affected)
|
||||
return affected, 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)
|
||||
|
||||
Reference in New Issue
Block a user