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
@@ -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
}
+21
View File
@@ -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
}
+14 -1
View File
@@ -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
+195 -8
View File
@@ -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)
}
}
+17
View File
@@ -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)
+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",
+8 -2
View File
@@ -236,14 +236,20 @@ func Auth(
}
// API-Key 走的是程序化全租户访问,固定授予 Admin 角色:可以做几乎所有事情,
// 但保留 Owner-only 操作(删除租户、修改租户级配置)的边界。
//
// 显式拒绝 SystemAdmin:API key 通常被存放在 CI / IaC / sidecar 里,
// 泄露面比 JWT 大得多。即便 key 关联的 user 在 DB 里恰好是 SystemAdmin
// (例如部署里只有一个用户、自己创建了 tenant 又生成了 API key),
// 也绝不允许通过这条通道走平台级管理操作(promote/revoke、全局设置)。
// 平台管理必须走交互式 JWT 登录,留下可追责的人类身份。
c.Set(types.UserContextKey.String(), user)
c.Set(types.UserIDContextKey.String(), user.ID)
c.Set(types.TenantRoleContextKey.String(), types.TenantRoleAdmin)
c.Set(types.SystemAdminContextKey.String(), user.IsSystemAdmin)
c.Set(types.SystemAdminContextKey.String(), false)
ctx = context.WithValue(ctx, types.UserContextKey, user)
ctx = context.WithValue(ctx, types.UserIDContextKey, user.ID)
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleAdmin)
ctx = context.WithValue(ctx, types.SystemAdminContextKey, user.IsSystemAdmin)
ctx = context.WithValue(ctx, types.SystemAdminContextKey, false)
c.Request = c.Request.WithContext(ctx)
c.Next()
+9
View File
@@ -752,6 +752,15 @@ func RegisterSystemAdminRoutes(r *gin.RouterGroup, handler *handler.SystemHandle
adminRoutes.GET("/settings", handler.ListSystemSettings)
adminRoutes.GET("/settings/:key", handler.GetSystemSetting)
adminRoutes.PUT("/settings/:key", handler.UpdateSystemSetting)
adminRoutes.DELETE("/settings/:key", handler.ResetSystemSetting)
// Bulk action — write the current default-quota setting onto
// every existing tenant. Lives under /tenants instead of
// /settings because it changes tenants, not the setting row.
adminRoutes.POST(
"/tenants/apply-default-storage-quota",
handler.ApplyDefaultStorageQuotaToAllTenants,
)
}
}
+18
View File
@@ -98,6 +98,24 @@ const (
// for now no setting is marked secret). Audit rows always have
// tenant_id=0 because the change is system-scope, not tenant-scope.
AuditActionSystemSettingChanged AuditAction = "system.setting_changed"
// AuditActionSystemAdminPromoted fires when a SystemAdmin grants
// system-administrator privileges to another user via
// POST /api/v1/system/admin/promote. ActorUserID is the promoter,
// TargetUserID is the user being promoted. Details payload carries
// {target_email, target_username, idempotent} — `idempotent=true`
// means the user was already a system admin and no row was written
// (we still emit the row so probing the endpoint leaves a trail).
// TenantID=0 because the change is system-scope.
AuditActionSystemAdminPromoted AuditAction = "system.admin_promoted"
// AuditActionSystemAdminRevoked fires when a SystemAdmin removes
// system-administrator privileges from another user via
// POST /api/v1/system/admin/revoke. Details payload carries
// {target_email, target_username, changed} — `changed=false` covers
// the idempotent path (target was already not an admin) so an audit
// reader can distinguish a real revoke from a noop attempt.
// TenantID=0 because the change is system-scope.
AuditActionSystemAdminRevoked AuditAction = "system.admin_revoked"
)
// AuditOutcome distinguishes successful mutations from middleware-level
@@ -20,6 +20,11 @@ type SystemSettingRepository interface {
// Upsert writes a row keyed by Key. Insert if missing, update if
// present. Used by SystemSettingService.Update on every save.
Upsert(ctx context.Context, s *types.SystemSetting) error
// Delete removes the row by key. Returns (true, nil) if a row was
// deleted, (false, nil) if no row matched (idempotent — service
// layer treats this as a no-op for audit purposes). Real DB errors
// surface as (_, err).
Delete(ctx context.Context, key string) (bool, error)
}
// SystemSettingService exposes both the 3-tier resolver (used by
@@ -70,6 +75,14 @@ type SystemSettingService interface {
// written to last_modified_by + the audit log.
// Returns the persisted row on success.
Update(ctx context.Context, key string, rawValue any) (*types.SystemSetting, error)
// Reset removes the DB override for `key` so the resolver falls
// back to ENV / built-in default. Idempotent: deleting a key that
// was never persisted returns nil. Emits an audit row on actual
// deletions, invalidates the local cache, and publishes to peers.
// Returns an error only when the DB write itself fails; callers
// must NOT translate "no row" into a 404 — that's the success
// path for an idempotent reset.
Reset(ctx context.Context, key string) error
// SubscribeRedis is a P2 hook: when implemented, it will subscribe
// to a "weknora:system_settings:changed" channel and invalidate any
+9
View File
@@ -28,6 +28,13 @@ type TenantService interface {
ExtractTenantIDFromAPIKey(apiKey string) (uint64, error)
// ListAllTenants lists all tenants (for users with cross-tenant access permission)
ListAllTenants(ctx context.Context) ([]*types.Tenant, error)
// BulkSetStorageQuota overwrites every tenant's storage_quota with
// quotaBytes. Returns how many rows were affected. Used by the
// SystemAdmin "apply default to all tenants" action; bypasses the
// per-tenant whitelist on PUT /tenants/:id (which intentionally
// forbids storage_quota edits for Owners). quotaBytes must be > 0;
// callers are responsible for resolving GB→bytes.
BulkSetStorageQuota(ctx context.Context, quotaBytes int64) (int64, error)
// SearchTenants searches tenants with pagination and filters
SearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]*types.Tenant, int64, error)
// GetTenantByIDForUser gets a tenant by ID with permission check
@@ -54,4 +61,6 @@ type TenantRepository interface {
DeleteTenant(ctx context.Context, id uint64) error
// AdjustStorageUsed adjusts the storage used for a tenant
AdjustStorageUsed(ctx context.Context, tenantID uint64, delta int64) error
// BulkSetStorageQuota — see TenantService.BulkSetStorageQuota.
BulkSetStorageQuota(ctx context.Context, quotaBytes int64) (int64, error)
}
+7
View File
@@ -52,6 +52,13 @@ type SystemSetting struct {
// means the UI should render a select with these options. Tagged
// `gorm:"-"` so GORM never tries to read/write the column.
Enum []string `gorm:"-" json:"enum,omitempty"`
// LastModifiedByName is a display label resolved from LastModifiedBy
// (the user's UUID) at handler time — username when available,
// otherwise email. Empty for virtual rows that were never persisted
// (LastModifiedBy=""). Not stored: derived per request so renaming
// a user reflects on the next reload without a backfill job.
LastModifiedByName string `gorm:"-" json:"last_modified_by_name,omitempty"`
}
// TableName pins the schema to migration 000053 — GORM's default
+12 -15
View File
@@ -8,22 +8,19 @@ import (
// GetMaxFileSize returns the maximum file upload size in bytes.
// Default is 50MB, can be configured via MAX_FILE_SIZE_MB environment variable.
//
// This is the legacy ENV-only entry point. Handlers wired with
// interfaces.SystemSettingService should prefer reading the 3-tier
// resolver directly:
// MAX_FILE_SIZE_MB is intentionally a deploy-time-only knob (NOT a
// runtime system_setting). The effective upload limit is gated by
// three other layers that all read this env at startup and cache the
// value:
// - frontend nginx client_max_body_size (envsubst into nginx.conf)
// - docreader gRPC max_send/recv_message_length
// - frontend client-side check via window.__RUNTIME_CONFIG__
//
// mb := h.systemSettingSvc.GetInt(ctx, "file.max_size_mb", "MAX_FILE_SIZE_MB", 50)
// maxBytes := mb * 1024 * 1024
//
// That way SystemAdmin's UI override (DB row in system_settings) takes
// precedence over the ENV value. This function is kept for unit tests
// and any non-handler call sites that don't have the service injected;
// it never sees DB values, only ENV.
//
// We deliberately don't expose a "service-aware" wrapper here because
// internal/types depends on internal/utils — wrapping it would create
// an import cycle. Call sites that have a SystemSettingService should
// just use it directly (it's only one extra line).
// Surfacing a SystemAdmin UI knob whose effect is silently capped by
// any of the above would mislead operators ("I raised it to 200MB but
// nginx still returns 413"). Until all four layers can be reconfigured
// in lockstep without container restarts, every call site must read
// the env directly via this helper.
func GetMaxFileSize() int64 {
if sizeStr := os.Getenv("MAX_FILE_SIZE_MB"); sizeStr != "" {
if size, err := strconv.ParseInt(sizeStr, 10, 64); err == nil && size > 0 {
+69 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"html"
"log"
"net"
"net/http"
"net/url"
@@ -935,6 +936,17 @@ func SetSSRFWhitelistFromRaw(raw string) {
// parseSSRFWhitelistRaw parses a comma-separated whitelist string into
// a config struct. Pure function; no env reads. Always returns a
// non-nil pointer so callers can blindly Load.
//
// Invalid entries (malformed CIDR like "10.0.0.0/333", wildcards
// without a "*." prefix, etc.) are dropped with a `[ssrf-whitelist]`
// log line rather than silently falling through to the exact-host
// branch. Falling through used to turn "10.0.0.0/333" into a literal
// host string that never matches anything — operators would believe
// the entry was active when in reality their SSRF check was unchanged.
//
// Callers that want hard rejection (e.g. ValidateSSRFWhitelistEntries
// for the system_settings Update path) should pre-validate before
// passing the raw string here.
func parseSSRFWhitelistRaw(raw string) *ssrfWhitelistConfig {
cfg := &ssrfWhitelistConfig{
exactHosts: make(map[string]bool),
@@ -947,26 +959,80 @@ func parseSSRFWhitelistRaw(raw string) *ssrfWhitelistConfig {
if entry == "" {
continue
}
// CIDR range
// CIDR range — entries containing '/' are exclusively CIDRs.
// A parse failure must NOT fall through to the exact-host
// branch (which would store "10.0.0.0/333" as a literal
// hostname that can never match anything).
if strings.Contains(entry, "/") {
_, ipNet, err := net.ParseCIDR(entry)
if err == nil {
cfg.cidrNets = append(cfg.cidrNets, ipNet)
if err != nil {
log.Printf("[ssrf-whitelist] dropping invalid CIDR entry %q: %v", entry, err)
continue
}
cfg.cidrNets = append(cfg.cidrNets, ipNet)
continue
}
// Wildcard domain: *.example.com
if strings.HasPrefix(entry, "*.") {
suffix := strings.ToLower(entry[1:]) // ".example.com"
if len(suffix) <= 1 {
log.Printf("[ssrf-whitelist] dropping bare wildcard entry %q (need *.<domain>)", entry)
continue
}
cfg.suffixHosts = append(cfg.suffixHosts, suffix)
continue
}
// Reject mid-string wildcards like "foo.*.bar" — they look
// useful but neither parseSSRFWhitelistRaw nor IsSSRFWhitelisted
// implement glob matching, so the entry would silently never
// match. Surface it loudly.
if strings.Contains(entry, "*") {
log.Printf("[ssrf-whitelist] dropping unsupported wildcard pattern %q (only \"*.\" prefix is supported)", entry)
continue
}
// Exact host or IP
cfg.exactHosts[strings.ToLower(entry)] = true
}
return cfg
}
// ValidateSSRFWhitelistEntries returns nil when every entry in `entries`
// would be accepted by parseSSRFWhitelistRaw, or an error describing
// the first malformed entry. Used by the system_settings Update path
// to give the UI a clear 400 instead of silently dropping bad input
// at parse-time.
//
// Validation rules mirror parseSSRFWhitelistRaw exactly:
// - "<a>/<b>" must be a valid CIDR
// - "*.<domain>" must have a non-empty domain after the prefix
// - mid-string "*" is not supported
// - everything else is treated as an exact host or literal IP
// (we don't pre-resolve DNS here; that's a runtime concern)
func ValidateSSRFWhitelistEntries(entries []string) error {
for _, entry := range entries {
entry = strings.TrimSpace(entry)
if entry == "" {
continue
}
if strings.Contains(entry, "/") {
if _, _, err := net.ParseCIDR(entry); err != nil {
return fmt.Errorf("invalid CIDR %q: %w", entry, err)
}
continue
}
if strings.HasPrefix(entry, "*.") {
if len(entry) <= 2 {
return fmt.Errorf("wildcard entry %q is missing a domain (use *.example.com)", entry)
}
continue
}
if strings.Contains(entry, "*") {
return fmt.Errorf("wildcard pattern %q is not supported (only the \"*.\" prefix is allowed)", entry)
}
}
return nil
}
// mergeSSRFWhitelistRaws joins two comma-separated raw strings, dropping
// the comma when one side is empty. Exposed for the service layer's
// "merge SSRF_WHITELIST_EXTRA into the DB-backed list" code path.