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
+9 -5
View File
@@ -428,12 +428,16 @@ COS_ENABLE_OLD_DOMAIN=true
# NEO4J_PASSWORD=password
# ========== 文件上传大小限制 ==========
# 统一的文件大小限制(MB),默认为50MB
# 影响:单文件上传、gRPC消息大小、Nginx请求体大小
# 统一的文件大小限制(MB),默认为 50MB。
# 影响:单文件上传、docreader gRPC 消息大小、frontend Nginx 请求体大小、
# 前端浏览器侧的客户端校验。
#
# 优先级(自 P1 起):DB 中的 system_settings.file.max_size_mb > 此环境变量 > 默认 50
# SystemAdmin 可以在「系统管理 → 全局设置」面板里实时调整该值,无需重启服务。
# 此处的环境变量仍然作为回退(DB 没有 row 时使用)。
# 这是部署期配置:四个层(Go 后端 / Nginx / docreader / 浏览器 bundle)
# 都在容器启动时读取一次,运行中改 env 不会生效。修改后必须同步重启
# 这四层。曾经尝试做成 system_settings 运行时项,但 Nginx /
# docreader / 浏览器 bundle 不会随之 reload,结果是 UI 改了 200 但
# Nginx 仍按旧值在 50 处直接 413,所以撤回了 UI 入口(见
# internal/utils/filesize.go 注释)。
# MAX_FILE_SIZE_MB=50
# ========== Agent Skills Sandbox 配置 ==========
+55 -3
View File
@@ -1,4 +1,4 @@
import { get, post, put } from '@/utils/request'
import { get, post, put, del } from '@/utils/request'
export interface SystemInfo {
version: string
@@ -251,6 +251,10 @@ export interface ListSystemAdminsResponse {
/**
* Promote a user to system administrator.
*
* Identify the target either by user_id (UUID, for API clients) or
* email (the human-friendly path used by the SystemAdmin UI). Backend
* accepts whichever is provided; user_id wins when both are set.
*
* Backend handler (system.go) returns the updated UserInfo directly as
* the response body — no {data: ...} wrapping. The shared axios
* interceptor in utils/request.ts unwraps response.data at the
@@ -262,8 +266,17 @@ export interface ListSystemAdminsResponse {
* compile (sometimes — vue-tsc is inconsistent on AxiosResponse vs
* inline interface assignability) but is fragile.
*/
export async function promoteUserToSystemAdmin(userId: string): Promise<SystemAdminUser> {
const response = await post('/api/v1/system/admin/promote', { user_id: userId })
export interface PromoteUserToSystemAdminRequest {
/** UUID of the user to promote. Optional; supply this OR `email`. */
user_id?: string
/** Email address of the user to promote. Optional; supply this OR `user_id`. */
email?: string
}
export async function promoteUserToSystemAdmin(
req: PromoteUserToSystemAdminRequest,
): Promise<SystemAdminUser> {
const response = await post('/api/v1/system/admin/promote', req)
return response as unknown as SystemAdminUser
}
@@ -320,6 +333,13 @@ export interface SystemSettingItem {
/** P3+ — currently always false. UI may show "needs restart to take effect" badge when true. */
requires_restart: boolean
last_modified_by: string
/**
* Display label resolved from last_modified_by (UUID) on the server —
* username when known, email as a fallback. Empty/undefined for
* virtual rows that were never persisted; UI then falls back to the
* UUID prefix.
*/
last_modified_by_name?: string
created_at: string
updated_at: string
/**
@@ -367,3 +387,35 @@ export async function updateSystemSetting(
)
return response as unknown as SystemSettingItem
}
/**
* Reset a system setting back to its ENV / built-in default by deleting
* the DB override row. Idempotent — resetting a key that was never
* persisted resolves successfully.
*/
export async function resetSystemSetting(key: string): Promise<void> {
await del(`/api/v1/system/admin/settings/${encodeURIComponent(key)}`)
}
/**
* Result of POST /system/admin/tenants/apply-default-storage-quota.
* `affected` is the count of tenant rows whose storage_quota was
* overwritten; `quota_bytes` is the value written.
*/
export interface ApplyDefaultStorageQuotaResult {
affected: number
quota_bytes: number
quota_gb: number
}
/**
* Apply the current `tenant.default_storage_quota_gb` setting to every
* existing tenant. Reads the resolved setting server-side (DB > ENV >
* default), then writes that quota to every row. SystemAdmin only.
*
* Idempotent: running twice with the same setting has the same effect.
*/
export async function applyDefaultStorageQuotaToAllTenants(): Promise<ApplyDefaultStorageQuotaResult> {
const response = await post('/api/v1/system/admin/tenants/apply-default-storage-quota')
return response as unknown as ApplyDefaultStorageQuotaResult
}
+5 -3
View File
@@ -353,9 +353,11 @@ const handleSettings = () => {
router.push('/platform/settings')
}
// Open platform-wide settings inside the standard Settings modal.
// Administrator-table workflows still live under /platform/system/admins,
// but global tunables belong with the rest of the configuration surface.
// Open the platform administration area inside the standard Settings
// modal. The admin roster lives at the top of the global-settings
// pane (as a tag-input row) so we route straight there; this is the
// only system-admin section now. Gated by SYSTEM_ADMIN_SECTIONS in
// Settings.vue.
const handleSystemAdmin = () => {
menuVisible.value = false
uiStore.openSettings('system-global')
+104 -1
View File
@@ -688,7 +688,7 @@ export default {
parserEngine: 'Parser Engine',
storageEngine: 'Storage Engine',
mcpService: 'MCP Service',
systemSettings: 'System Settings',
versionInfo: 'Version Info',
tenantInfo: 'Tenant Info',
apiInfo: 'API Info',
navGroups: {
@@ -2571,6 +2571,109 @@ export default {
messages: {
fetchFailed: 'Failed to fetch system information',
networkError: 'Network error, please try again later'
},
globalSettings: {
title: 'System Settings',
description: 'Platform-wide runtime configuration. Saves take effect immediately for every tenant. Visible and editable by system administrators only.',
loading: 'Loading...',
empty: 'No configurable system settings available',
badgeRequiresRestart: 'Restart required',
badgeSecret: 'Secret',
badgeOverride: 'Overridden',
badgeOverrideTooltip: 'This value has been saved to the database by an administrator, overriding the environment variable and built-in default.',
modifiedAt: 'Last modified: {value}',
tagInputPlaceholder: 'Press Enter to add an entry, e.g. example.com / *.foo.com / 10.0.0.0/8',
priorityHint: {
title: 'About priority',
tier1: 'Items saved on this page (marked "Overridden") always win — the environment variable is ignored for them.',
tier2: 'Items not saved here fall back to the environment variable, or to the built-in default if no env var is set.',
tier3: 'To put an item back under environment-variable control, click the "Reset" button on its row.',
},
keyLabels: {
auth: {
registration_mode: 'Self-service registration mode',
},
ssrf: {
whitelist: 'SSRF protection allowlist',
},
tenant: {
max_owned_per_user: 'Max tenants owned per user',
default_storage_quota_gb: 'Default storage quota for new tenants (GB)',
},
},
enumLabels: {
auth: {
registration_mode: {
self_serve: 'Self-service (anyone can register)',
invite_only: 'Invite only (public registration disabled)',
},
},
},
confirm: {
header: 'Confirm high-risk action',
confirmBtn: 'Confirm save',
cancelBtn: 'Cancel',
emptyValue: '(empty)',
defaultBody: 'About to change "{label}" to: {value}',
bodyAuthRegistrationMode: 'About to change "{label}" to: {value}\n\nIf switched to self_serve, anyone on the public internet can register an account — please confirm this is intended.',
},
listConfirm: {
ssrf: {
whitelist: {
add: {
header: 'Add SSRF allowlist entry',
body: 'Add {entry} to the SSRF allowlist? Hosts / IPs / CIDRs that match this entry will bypass SSRF protection and may let agents reach internal services. Only add entries you fully trust.',
confirmBtn: 'Add',
},
remove: {
header: 'Remove SSRF allowlist entry',
body: 'Remove {entry} from the SSRF allowlist? After removal this entry will be blocked by SSRF protection again.',
confirmBtn: 'Remove',
},
},
},
},
messages: {
loadFailed: 'Failed to load system settings',
saveSuccess: 'Saved',
saveFailed: 'Save failed',
},
reset: {
label: 'Reset',
tooltip: 'Clear the UI override and fall back to the environment variable or the built-in default',
confirmBtn: 'Confirm reset',
confirmBody: 'Reset "{label}"? This deletes the database override and falls back to the environment variable or the built-in default.',
success: 'Reset to default',
failed: 'Reset failed',
},
admins: {
label: 'System administrators',
description: 'Users with platform-level privileges. Type an email and press Enter to promote a user; click × on a tag to revoke. You (yourself) are an administrator and are not shown in the list — you cannot revoke your own access.',
placeholder: 'Type a user email and press Enter',
loadFailed: 'Failed to load system administrators',
saveSuccess: 'System administrators updated',
saveFailed: 'Failed to update system administrators',
confirm: {
promote: {
header: 'Promote to system administrator',
body: 'Promote {email} to system administrator? This user will gain platform-level privileges: access to every tenant, system settings, and the admin roster itself.',
confirmBtn: 'Promote',
},
revoke: {
header: 'Revoke system administrator',
body: 'Revoke system-administrator privileges from {email}? They will lose access to all system-level features.',
confirmBtn: 'Revoke',
},
},
},
bulkApply: {
label: 'Apply to all existing tenants',
tooltip: 'Saving the value only affects new tenants by default; click here to also overwrite every existing tenant.',
confirmBtn: 'Confirm apply',
confirmBody: 'Overwrite the storage quota of every existing tenant to {value} GB. Tenants whose quota was tuned manually by operations will also be overwritten. Continue?',
success: 'Updated storage quota for {count} tenants to {gb} GB',
failed: 'Failed to apply to all tenants',
},
}
},
mcp: {
+104 -1
View File
@@ -551,7 +551,7 @@ export default {
parserEngine: "파싱 엔진",
storageEngine: "스토리지 엔진",
mcpService: "MCP 서비스",
systemSettings: "시스템 설정",
versionInfo: "버전 정보",
tenantInfo: "테넌트 정보",
apiInfo: "API 정보",
navGroups: {
@@ -1814,6 +1814,109 @@ export default {
fetchFailed: "시스템 정보 가져오기 실패",
networkError: "네트워크 오류, 나중에 다시 시도해주세요",
},
globalSettings: {
title: "시스템 설정",
description: "플랫폼 전역 런타임 설정입니다. 저장하면 모든 테넌트에 즉시 적용됩니다. 시스템 관리자만 보고 수정할 수 있습니다.",
loading: "로딩 중...",
empty: "설정 가능한 시스템 항목이 없습니다",
badgeRequiresRestart: "재시작 필요",
badgeSecret: "민감",
badgeOverride: "재정의됨",
badgeOverrideTooltip: "이 값은 관리자가 DB에 저장하여 환경 변수 및 기본값을 덮어썼습니다.",
modifiedAt: "마지막 수정: {value}",
tagInputPlaceholder: "엔터로 항목 추가. 예: example.com / *.foo.com / 10.0.0.0/8",
priorityHint: {
title: "우선순위 안내",
tier1: "이 페이지에서 저장한 항목(\"재정의됨\" 배지가 붙은 항목)은 항상 우선 적용되며, 환경 변수는 무시됩니다.",
tier2: "여기서 저장하지 않은 항목은 환경 변수를 따르며, 환경 변수도 없으면 내장 기본값을 사용합니다.",
tier3: "특정 항목을 다시 환경 변수 기반으로 되돌리려면 해당 행의 \"초기화\" 버튼을 누르세요.",
},
keyLabels: {
auth: {
registration_mode: "셀프 가입 모드",
},
ssrf: {
whitelist: "SSRF 보호 허용 목록",
},
tenant: {
max_owned_per_user: "사용자당 최대 테넌트 수",
default_storage_quota_gb: "신규 테넌트 기본 저장 용량 (GB)",
},
},
enumLabels: {
auth: {
registration_mode: {
self_serve: "셀프 가입 (누구나 가입 가능)",
invite_only: "초대 전용 (공개 가입 비활성)",
},
},
},
confirm: {
header: "고위험 작업 확인",
confirmBtn: "저장 확인",
cancelBtn: "취소",
emptyValue: "(비어 있음)",
defaultBody: "「{label}」을(를) {value}(으)로 변경하려고 합니다.",
bodyAuthRegistrationMode: "「{label}」을(를) {value}(으)로 변경하려고 합니다.\n\nself_serve로 전환하면 인터넷의 누구나 계정을 만들 수 있습니다. 의도된 동작인지 확인해 주세요.",
},
listConfirm: {
ssrf: {
whitelist: {
add: {
header: "SSRF 화이트리스트 항목 추가",
body: "{entry} 항목을 SSRF 화이트리스트에 추가하시겠습니까? 일치하는 호스트 / IP / 대역은 SSRF 보호를 우회하여 에이전트가 내부 서비스에 접근할 수 있게 됩니다. 신뢰하는 항목만 추가하세요.",
confirmBtn: "추가 확인",
},
remove: {
header: "SSRF 화이트리스트 항목 제거",
body: "{entry} 항목을 SSRF 화이트리스트에서 제거하시겠습니까? 제거 후에는 해당 항목이 다시 SSRF 보호 대상이 됩니다.",
confirmBtn: "제거 확인",
},
},
},
},
messages: {
loadFailed: "시스템 설정을 불러오지 못했습니다",
saveSuccess: "저장되었습니다",
saveFailed: "저장 실패",
},
reset: {
label: "초기화",
tooltip: "UI 재정의 값을 제거하고 환경 변수 또는 내장 기본값으로 되돌립니다",
confirmBtn: "초기화 확인",
confirmBody: "「{label}」을(를) 초기화하시겠습니까? DB에 저장된 재정의 값이 삭제되고 환경 변수 또는 내장 기본값으로 되돌아갑니다.",
success: "기본값으로 초기화되었습니다",
failed: "초기화 실패",
},
admins: {
label: "시스템 관리자",
description: "플랫폼 수준 권한을 가진 사용자입니다. 오른쪽에 이메일을 입력하고 엔터를 누르면 해당 사용자를 관리자로 승격하고, 태그의 ×를 누르면 권한을 회수합니다. 본인은 관리자이지만 목록에 표시되지 않으며 자신의 권한을 회수할 수 없습니다.",
placeholder: "사용자 이메일을 입력하고 엔터를 누르세요",
loadFailed: "시스템 관리자 정보를 불러오지 못했습니다",
saveSuccess: "시스템 관리자가 업데이트되었습니다",
saveFailed: "시스템 관리자 업데이트 실패",
confirm: {
promote: {
header: "시스템 관리자로 승격",
body: "{email} 사용자를 시스템 관리자로 승격하시겠습니까? 이 사용자는 모든 테넌트 접근, 시스템 설정 변경, 관리자 명단 관리 등 플랫폼 수준의 권한을 갖게 됩니다.",
confirmBtn: "승격 확인",
},
revoke: {
header: "시스템 관리자 권한 회수",
body: "{email} 사용자의 시스템 관리자 권한을 회수하시겠습니까? 회수 후에는 시스템 수준 기능에 더 이상 접근할 수 없습니다.",
confirmBtn: "회수 확인",
},
},
},
bulkApply: {
label: "모든 기존 테넌트에 적용",
tooltip: "저장한 값은 기본적으로 새로 생성되는 테넌트에만 적용됩니다. 이 버튼을 누르면 현재 값을 모든 기존 테넌트에도 덮어씁니다.",
confirmBtn: "적용 확인",
confirmBody: "모든 기존 테넌트의 저장 용량을 {value} GB로 덮어씁니다. 운영팀이 개별로 조정한 테넌트의 용량도 함께 덮어쓰여집니다. 계속하시겠습니까?",
success: "{count}개 테넌트의 저장 용량을 {gb} GB로 갱신했습니다",
failed: "모든 테넌트에 적용 실패",
},
},
},
mcp: {
testResult: {
+104 -1
View File
@@ -653,7 +653,7 @@ export default {
mcpService: 'Сервис MCP',
conversationConfig: 'Настройки диалога',
conversationStrategy: 'Стратегия диалога',
systemSettings: 'Настройки системы',
versionInfo: 'Информация о версии',
tenantInfo: 'Информация о арендаторе',
apiInfo: 'Информация API',
navGroups: {
@@ -1607,6 +1607,109 @@ export default {
messages: {
fetchFailed: 'Не удалось получить информацию о системе',
networkError: 'Ошибка сети, попробуйте позже'
},
globalSettings: {
title: 'Системные настройки',
description: 'Настройки платформы, применяемые в режиме реального времени. Изменения сразу действуют для всех тенантов. Доступны только системным администраторам.',
loading: 'Загрузка...',
empty: 'Нет доступных для настройки параметров',
badgeRequiresRestart: 'Нужен перезапуск',
badgeSecret: 'Конфиденциально',
badgeOverride: 'Переопределено',
badgeOverrideTooltip: 'Это значение сохранено администратором в БД и переопределяет переменную окружения и значение по умолчанию.',
modifiedAt: 'Последнее изменение: {value}',
tagInputPlaceholder: 'Нажмите Enter, чтобы добавить запись, например: example.com / *.foo.com / 10.0.0.0/8',
priorityHint: {
title: 'О приоритете',
tier1: 'Параметры, сохранённые на этой странице (с пометкой «Переопределено»), всегда имеют приоритет — переменная окружения для них игнорируется.',
tier2: 'Параметры, не сохранённые здесь, берутся из переменной окружения, а если её нет — из встроенного значения по умолчанию.',
tier3: 'Чтобы вернуть параметр под управление переменной окружения, нажмите кнопку «Сбросить» в его строке.',
},
keyLabels: {
auth: {
registration_mode: 'Режим самостоятельной регистрации',
},
ssrf: {
whitelist: 'Белый список SSRF-защиты',
},
tenant: {
max_owned_per_user: 'Максимум тенантов на пользователя',
default_storage_quota_gb: 'Квота хранилища для новых тенантов по умолчанию (ГБ)',
},
},
enumLabels: {
auth: {
registration_mode: {
self_serve: 'Самостоятельная (любой может зарегистрироваться)',
invite_only: 'Только по приглашению (открытая регистрация отключена)',
},
},
},
confirm: {
header: 'Подтверждение опасного действия',
confirmBtn: 'Подтвердить сохранение',
cancelBtn: 'Отмена',
emptyValue: '(пусто)',
defaultBody: 'Вы собираетесь изменить «{label}» на: {value}',
bodyAuthRegistrationMode: 'Вы собираетесь изменить «{label}» на: {value}\n\nЕсли переключить на self_serve, любой пользователь публичного интернета сможет создать аккаунт — убедитесь, что это ожидаемое поведение.',
},
listConfirm: {
ssrf: {
whitelist: {
add: {
header: 'Добавить запись в белый список SSRF',
body: 'Добавить {entry} в белый список SSRF? Соответствующие хосты / IP / подсети будут обходить защиту от SSRF и смогут обращаться к внутренним сервисам через агентов. Добавляйте только полностью доверенные записи.',
confirmBtn: 'Добавить',
},
remove: {
header: 'Удалить запись из белого списка SSRF',
body: 'Удалить {entry} из белого списка SSRF? После удаления запись снова будет блокироваться защитой от SSRF.',
confirmBtn: 'Удалить',
},
},
},
},
messages: {
loadFailed: 'Не удалось загрузить системные настройки',
saveSuccess: 'Сохранено',
saveFailed: 'Ошибка сохранения'
},
reset: {
label: 'Сбросить',
tooltip: 'Очистить переопределение из UI и вернуться к переменной окружения или встроенному значению по умолчанию',
confirmBtn: 'Подтвердить сброс',
confirmBody: 'Сбросить «{label}»? Это удалит запись переопределения в БД и вернёт значение из переменной окружения или встроенное по умолчанию.',
success: 'Сброшено к значению по умолчанию',
failed: 'Ошибка сброса'
},
admins: {
label: 'Системные администраторы',
description: 'Пользователи с правами уровня платформы. Введите email и нажмите Enter, чтобы повысить пользователя до администратора; нажмите × на теге, чтобы отозвать права. Вы (текущий пользователь) являетесь администратором и не отображаетесь в списке — отозвать собственные права нельзя.',
placeholder: 'Введите email пользователя и нажмите Enter',
loadFailed: 'Не удалось загрузить системных администраторов',
saveSuccess: 'Системные администраторы обновлены',
saveFailed: 'Ошибка обновления системных администраторов',
confirm: {
promote: {
header: 'Повысить до системного администратора',
body: 'Повысить пользователя {email} до системного администратора? Пользователь получит права уровня платформы: доступ ко всем тенантам, изменение системных настроек и управление списком администраторов.',
confirmBtn: 'Повысить',
},
revoke: {
header: 'Отозвать права администратора',
body: 'Отозвать права системного администратора у {email}? После отзыва пользователь потеряет доступ ко всем системным функциям.',
confirmBtn: 'Отозвать',
},
},
},
bulkApply: {
label: 'Применить ко всем существующим тенантам',
tooltip: 'По умолчанию сохранённое значение применяется только к новым тенантам. Нажмите, чтобы также перезаписать всех существующих.',
confirmBtn: 'Подтвердить применение',
confirmBody: 'Перезаписать квоту хранилища всех существующих тенантов значением {value} ГБ. Тенанты, чью квоту вручную правили эксплуатация, также будут перезаписаны. Продолжить?',
success: 'Обновлена квота хранилища у {count} тенантов: {gb} ГБ',
failed: 'Ошибка применения ко всем тенантам'
}
}
},
mcp: {
+104 -1
View File
@@ -548,7 +548,7 @@ export default {
parserEngine: "解析引擎",
storageEngine: "存储引擎",
mcpService: "MCP服务",
systemSettings: "系统设置",
versionInfo: "版本信息",
tenantInfo: "空间信息",
apiInfo: "API信息",
navGroups: {
@@ -1793,6 +1793,109 @@ export default {
fetchFailed: "获取系统信息失败",
networkError: "网络错误,请稍后重试",
},
globalSettings: {
title: "系统设置",
description: "平台级运行时配置,保存后立即对所有租户生效。仅系统管理员可见可改。",
loading: "加载中...",
empty: "暂无可配置的系统设置",
badgeRequiresRestart: "需重启",
badgeSecret: "敏感",
badgeOverride: "已覆盖",
badgeOverrideTooltip: "该值已由管理员保存到数据库,覆盖了环境变量与默认值",
modifiedAt: "上次修改:{value}",
tagInputPlaceholder: "回车添加条目,例:example.com / *.foo.com / 10.0.0.0/8",
priorityHint: {
title: "关于优先级",
tier1: "在此页面保存过的项(带「已覆盖」徽章)— 始终以这里的值为准,环境变量会被忽略。",
tier2: "未在此处保存过的项 — 如果环境变量里有就用环境变量,否则用程序内置默认值。",
tier3: "若想让某项重新由环境变量控制,点击该行的「重置」按钮即可清除当前 UI 设置。",
},
keyLabels: {
auth: {
registration_mode: "自助注册模式",
},
ssrf: {
whitelist: "SSRF 防护白名单",
},
tenant: {
max_owned_per_user: "每用户最大租户数",
default_storage_quota_gb: "新租户默认存储配额 (GB)",
},
},
enumLabels: {
auth: {
registration_mode: {
self_serve: "自助注册(任何人可注册)",
invite_only: "仅邀请(关闭公网注册)",
},
},
},
confirm: {
header: "高危操作确认",
confirmBtn: "确认保存",
cancelBtn: "取消",
emptyValue: "(空)",
defaultBody: "即将把「{label}」改为:{value}",
bodyAuthRegistrationMode: "即将把「{label}」改为:{value}\n\n如果切到 self_serve,公网任何人都可以注册账号 — 务必确认是预期行为。",
},
listConfirm: {
ssrf: {
whitelist: {
add: {
header: "添加 SSRF 白名单条目",
body: "确认把 {entry} 加入 SSRF 白名单?该条目匹配到的主机 / IP / 网段会绕过 SSRF 防护,可能让 Agent 访问内网服务,请仅在确知用途时添加。",
confirmBtn: "确认添加",
},
remove: {
header: "移除 SSRF 白名单条目",
body: "确认从 SSRF 白名单中移除 {entry}?移除后该条目将重新受 SSRF 防护拦截。",
confirmBtn: "确认移除",
},
},
},
},
messages: {
loadFailed: "加载系统设置失败",
saveSuccess: "已保存",
saveFailed: "保存失败",
},
reset: {
label: "重置",
tooltip: "清除当前 UI 覆盖,恢复使用环境变量或内置默认值",
confirmBtn: "确认重置",
confirmBody: "确定要重置「{label}」吗?该操作会删除数据库中的覆盖值,回退到环境变量或内置默认值。",
success: "已重置为默认值",
failed: "重置失败",
},
admins: {
label: "系统管理员",
description: "拥有平台级权限的用户。在右侧输入邮箱并回车即可提升用户为管理员;点击 × 即为撤销其权限。当前你(自己)已是管理员,不在列表中显示,也无法被自己撤销。",
placeholder: "输入用户邮箱并回车",
loadFailed: "加载系统管理员失败",
saveSuccess: "已更新系统管理员",
saveFailed: "更新系统管理员失败",
confirm: {
promote: {
header: "提升为系统管理员",
body: "确认将 {email} 提升为系统管理员?该用户将获得平台级权限,可访问所有租户、修改系统设置、管理其他管理员。",
confirmBtn: "确认提升",
},
revoke: {
header: "撤销系统管理员",
body: "确认撤销 {email} 的系统管理员权限?撤销后该用户将无法再访问任何系统级功能。",
confirmBtn: "确认撤销",
},
},
},
bulkApply: {
label: "应用到所有现有租户",
tooltip: "保存的值默认只对之后新建的租户生效;点击此按钮将当前值同步写入所有现有租户。",
confirmBtn: "确认应用",
confirmBody: "将把所有现有租户的存储配额覆盖为 {value} GB。如有租户被运维单独调整过的配额,也会一并被覆盖。是否继续?",
success: "已将 {count} 个租户的存储配额更新为 {gb} GB",
failed: "应用到所有租户失败",
},
},
},
mcp: {
testResult: {
+18 -23
View File
@@ -140,32 +140,27 @@ const router = createRouter({
component: () => import("../views/organization/OrganizationList.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
// System administration area — gated to users with
// user.is_system_admin === true. The route guard below honours
// the meta.requiresSystemAdmin flag; non-admins are bounced to
// /platform/knowledge-bases. Real authorisation lives server-side.
// Compatibility redirects for legacy /platform/system/* URLs.
// The whole system administration surface — global settings
// and the system-admin roster — now lives as a single section
// inside the standard Settings modal. We keep the routes
// around so old bookmarks / external links don't 404.
{
path: "system",
component: () => import("../views/system/SystemLayout.vue"),
redirect: { path: "/platform/settings", query: { section: "system-global" } },
meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true },
},
{
path: "system/settings",
name: "systemSettings",
redirect: { path: "/platform/settings", query: { section: "system-global" } },
meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true },
},
{
path: "system/admins",
name: "systemAdmins",
redirect: { path: "/platform/settings", query: { section: "system-global" } },
meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true },
redirect: "/platform/system/admins",
children: [
{
// Kept as a compatibility URL. Global settings now live in
// the standard settings modal rather than a standalone
// routed page.
path: "settings",
name: "systemSettings",
redirect: { path: "/platform/settings", query: { section: "system-global" } },
meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true }
},
{
path: "admins",
name: "systemAdmins",
component: () => import("../views/system/SystemAdmins.vue"),
meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true }
},
],
},
],
},
+18 -6
View File
@@ -284,8 +284,8 @@ const navItems = computed(() => {
{ key: 'parser', icon: 'file-search', label: t('settings.parserEngine') },
{ key: 'storage', icon: 'cloud', label: t('settings.storageEngine') },
{ key: 'mcp', icon: 'tools', label: t('settings.mcpService') },
{ key: 'system', icon: 'info-circle', label: t('settings.systemSettings') },
{ key: 'system-global', icon: 'server', label: '全局设置' },
{ key: 'system', icon: 'info-circle', label: t('settings.versionInfo') },
{ key: 'system-global', icon: 'server', label: '系统设置' },
{ key: 'userprofile', icon: 'user', label: t('userProfile.title') },
{ key: 'tenant', icon: 'user-circle', label: t('settings.tenantInfo') },
{ key: 'members', icon: 'usergroup', label: t('tenantMember.title') },
@@ -376,7 +376,8 @@ const handleClose = () => {
uiStore.closeSettings()
// 如果当前路由是设置页,返回上一页
if (route.path === '/platform/settings') {
if (route.query.section === 'system-global') {
const sec = route.query.section
if (sec === 'system-global') {
router.push('/platform/knowledge-bases')
} else {
router.back()
@@ -480,8 +481,13 @@ onUnmounted(() => {
.settings-modal {
position: relative;
width: 100%;
max-width: 900px;
height: 700px;
// 1080×780 trades a touch of small-screen real estate for noticeably
// less cramped tables (member list, system settings rows). Outer
// padding is 20px so 1080 + 40 = 1120, comfortably within typical
// laptops (1280+). Below 1100px viewport the `width: 100%` kicks in
// and the modal shrinks to fit minus the 20px padding.
max-width: 1080px;
height: 780px;
background: var(--td-bg-color-container);
border-radius: 12px;
box-shadow: 0 6px 28px rgba(15, 23, 42, 0.08);
@@ -668,7 +674,13 @@ onUnmounted(() => {
}
.content-wrapper {
max-width: 600px;
// Bumped from 600 to 760 when the modal grew from 900→1080 (see
// .settings-modal). Without this, single-column panes (General,
// Tenant, API key, …) leave a wide right-hand gutter inside the
// wider modal. 760 keeps comfortable reading-width on long
// descriptions without the form fields stretching to the full
// panel width — which would look stranger than a small gutter.
max-width: 760px;
padding: 40px 48px;
/* 成员 / 审计表格列多,600px 会把操作列挤到贴边;铺满右侧内容列更稳。 */
-259
View File
@@ -1,259 +0,0 @@
<template>
<!--
SystemAdmins — list & manage the platform-wide system administrators.
Grants/revokes via the /api/v1/system/admin/{promote,revoke,list}
endpoints (server-side guarded by RequireSystemAdmin middleware).
P0 milestone scope is deliberately minimal:
- Paginated list of current system admins
- Promote a user by email
- Revoke an existing admin (with last-admin & self-revoke server guards)
Future milestones can layer richer UX on top — search, audit-log
drawer, bulk operations — but the API surface and gating are stable.
-->
<div class="system-admins">
<div class="page-header">
<div>
<h1 class="page-title">系统管理员</h1>
<p class="page-desc">
系统管理员独立于租户角色,拥有平台级管理权限(管理其他系统管理员、全局设置、内置模型等)。
</p>
</div>
<t-button theme="primary" @click="openPromoteDialog">
<template #icon><t-icon name="add" /></template>
提升用户为系统管理员
</t-button>
</div>
<t-card class="admins-card" :bordered="false">
<t-table
row-key="id"
:data="admins"
:columns="columns"
:loading="loading"
size="medium"
hover
stripe
>
<template #status="{ row }">
<t-tag v-if="row.is_active" theme="success" variant="light">
活跃
</t-tag>
<t-tag v-else theme="warning" variant="light">已停用</t-tag>
</template>
<template #actions="{ row }">
<t-button
theme="danger"
variant="text"
size="small"
:disabled="row.id === currentUserId"
@click="confirmRevoke(row)"
>
撤销权限
</t-button>
</template>
</t-table>
<div class="pagination-bar" v-if="total > 0">
<t-pagination
v-model="page"
v-model:page-size="pageSize"
:total="total"
:page-size-options="[20, 50, 100]"
@change="loadAdmins"
/>
</div>
</t-card>
<!-- Promote dialog -->
<t-dialog
v-model:visible="promoteDialogVisible"
header="提升用户为系统管理员"
:confirm-btn="{ content: '确认提升', loading: promoting }"
@confirm="submitPromote"
@close="resetPromoteDialog"
>
<p class="dialog-hint">
请输入要提升的用户的 ID。该用户必须已经在系统中注册过;操作幂等,已是管理员的用户不会被重复提升。
</p>
<t-input
v-model="promoteUserId"
placeholder="用户 ID(UUID 形式)"
:disabled="promoting"
clearable
/>
</t-dialog>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import { useAuthStore } from '@/stores/auth'
import {
listSystemAdmins,
promoteUserToSystemAdmin,
revokeSystemAdmin,
type SystemAdminUser,
} from '@/api/system'
const authStore = useAuthStore()
const currentUserId = computed(() => authStore.currentUserId)
const admins = ref<SystemAdminUser[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const promoteDialogVisible = ref(false)
const promoteUserId = ref('')
const promoting = ref(false)
// Columns are defined as a computed (vs a static const) so future
// localization/translation can hook in without component refactor.
const columns = [
{ colKey: 'username', title: '用户名', width: 180 },
{ colKey: 'email', title: '邮箱', width: 280 },
{ colKey: 'status', title: '状态', width: 100 },
{ colKey: 'created_at', title: '注册时间', width: 200 },
{ colKey: 'actions', title: '操作', width: 120, align: 'right' as const },
]
async function loadAdmins() {
loading.value = true
try {
const offset = (page.value - 1) * pageSize.value
// listSystemAdmins resolves to ListSystemAdminsResponse directly —
// utils/request.ts already unwraps axios's response.data wrapper at
// the interceptor layer (see line 97), so an extra `.data` here
// would explode at runtime as "Cannot read property 'admins' of
// undefined" and surface as the generic load-failed toast.
const res = await listSystemAdmins({ offset, limit: pageSize.value })
admins.value = res.admins ?? []
total.value = res.total ?? 0
} catch (err) {
// Surface a toast and bail — keeping prior list so the user isn't
// left staring at an empty table on a transient failure.
MessagePlugin.error('加载系统管理员列表失败')
console.error('listSystemAdmins failed:', err)
} finally {
loading.value = false
}
}
function openPromoteDialog() {
promoteUserId.value = ''
promoteDialogVisible.value = true
}
function resetPromoteDialog() {
promoteUserId.value = ''
promoting.value = false
}
async function submitPromote() {
const uid = promoteUserId.value.trim()
if (!uid) {
MessagePlugin.warning('请输入用户 ID')
return
}
promoting.value = true
try {
await promoteUserToSystemAdmin(uid)
MessagePlugin.success('已提升为系统管理员')
promoteDialogVisible.value = false
await loadAdmins()
} catch (err: any) {
// utils/request.ts 把后端的 {error: "..."} 提升到了顶层 message
// 字段(line 197-213),同时保留原始 data 字段。我们优先读 message
// —— 它已经是后端的 human-readable 错误文案,覆盖了 user-not-found
// / 自我撤销等业务错误场景。
const msg = err?.message || err?.error || '提升失败,请检查用户 ID 后重试'
MessagePlugin.error(msg)
} finally {
promoting.value = false
}
}
function confirmRevoke(row: SystemAdminUser) {
// Confirmation dialog is mandatory — revoking is destructive and
// the server's last-admin / self-revoke guards return 400 with a
// human-readable message which we re-surface in submitRevoke.
const confirmDialog = DialogPlugin.confirm({
header: '撤销系统管理员权限',
body: `确定要撤销用户 "${row.username}" (${row.email}) 的系统管理员权限吗?`,
confirmBtn: { content: '确认撤销', theme: 'danger' },
cancelBtn: '取消',
onConfirm: async () => {
await submitRevoke(row.id)
confirmDialog.destroy()
},
onClose: () => confirmDialog.destroy(),
})
}
async function submitRevoke(userId: string) {
try {
await revokeSystemAdmin(userId)
MessagePlugin.success('已撤销系统管理员权限')
await loadAdmins()
} catch (err: any) {
// 同 submitPromote 的注释 —— 后端 last-admin / self-revoke 保护
// 走 400 + {error: "..."},被拦截器抬到 err.message。
const msg = err?.message || err?.error || '撤销失败'
MessagePlugin.error(msg)
}
}
onMounted(() => {
loadAdmins()
})
</script>
<style scoped>
.system-admins {
max-width: 1100px;
}
.page-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
margin-bottom: 20px;
}
.page-title {
margin: 0 0 6px;
font-size: 22px;
font-weight: 600;
color: var(--td-text-color-primary, #000);
}
.page-desc {
margin: 0;
font-size: 13px;
line-height: 1.6;
color: var(--td-text-color-secondary, #666);
max-width: 720px;
}
.admins-card {
margin-top: 8px;
}
.pagination-bar {
margin-top: 16px;
display: flex;
justify-content: flex-end;
}
.dialog-hint {
margin: 0 0 12px;
font-size: 13px;
color: var(--td-text-color-secondary, #666);
line-height: 1.6;
}
</style>
-127
View File
@@ -1,127 +0,0 @@
<template>
<!--
SystemLayout — top-level shell for the platform-wide administration
area (/platform/system/*). Gated by meta.requiresSystemAdmin in the
router; reaching this component means the caller is an authenticated
SystemAdmin.
Sidebar is intentionally simple: global system settings live inside
the standard Settings modal, while this routed area keeps workflows
that need a table-oriented management surface.
-->
<div class="system-layout">
<aside class="system-sidebar">
<div class="system-sidebar-header">
<h2 class="system-sidebar-title">系统管理</h2>
<div class="system-sidebar-subtitle">SystemAdmin</div>
</div>
<nav class="system-nav">
<router-link
v-for="item in navItems"
:key="item.name"
:to="{ name: item.name }"
v-slot="{ isActive, navigate }"
custom
>
<div
:class="['system-nav-item', { active: isActive }]"
@click="navigate"
>
<t-icon :name="item.icon" class="system-nav-icon" />
<span class="system-nav-label">{{ item.label }}</span>
</div>
</router-link>
</nav>
</aside>
<main class="system-content">
<router-view />
</main>
</div>
</template>
<script setup lang="ts">
// Nav items are declared here (not in a separate config file) because
// the list is short and tightly coupled to which child routes exist.
// When a new child route is added in router/index.ts under /platform/system,
// add a matching entry here.
const navItems = [
{ name: 'systemAdmins', label: '系统管理员', icon: 'user-shield' },
]
</script>
<style scoped>
.system-layout {
display: flex;
height: 100%;
width: 100%;
background: var(--td-bg-color-page, #f5f5f5);
}
.system-sidebar {
width: 240px;
flex-shrink: 0;
background: var(--td-bg-color-container, #fff);
border-right: 1px solid var(--td-border-level-1-color, #e7e7e7);
padding: 20px 12px;
display: flex;
flex-direction: column;
gap: 16px;
}
.system-sidebar-header {
padding: 0 12px 12px;
border-bottom: 1px solid var(--td-border-level-1-color, #e7e7e7);
}
.system-sidebar-title {
margin: 0;
font-size: 16px;
font-weight: 600;
color: var(--td-text-color-primary, #000);
}
.system-sidebar-subtitle {
font-size: 11px;
color: var(--td-text-color-placeholder, #999);
margin-top: 4px;
letter-spacing: 0.5px;
}
.system-nav {
display: flex;
flex-direction: column;
gap: 2px;
}
.system-nav-item {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 12px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
color: var(--td-text-color-primary, #333);
transition: background-color 0.15s;
}
.system-nav-item:hover {
background: var(--td-bg-color-component-hover, #f3f3f3);
}
.system-nav-item.active {
background: var(--td-brand-color-light, #e0eaff);
color: var(--td-brand-color, #0052d9);
font-weight: 500;
}
.system-nav-icon {
font-size: 16px;
}
.system-content {
flex: 1;
overflow: auto;
padding: 24px 32px;
}
</style>
File diff suppressed because it is too large Load Diff
@@ -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.