feat(system-admin): implement bootstrap for system admin promotion and enhance system settings management
- Added WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL environment variable to promote a specified user to system admin on startup. - Introduced a new bootstrap process in `bootstrap.go` to handle the promotion logic. - Updated `.env.example` to document the new environment variable and its behavior. - Created new views for managing system administrators and system settings, including listing, promoting, and revoking admin privileges. - Enhanced the frontend to reflect the new system admin features, including UI elements for admin management and settings configuration. - Updated API interfaces to support system admin functionalities, ensuring proper data handling and user management.
This commit is contained in:
@@ -89,6 +89,15 @@ const (
|
||||
// initiates a _reindex (sync or async). Details payload: source
|
||||
// KB id, target KB id, sync-or-async, doc count if known.
|
||||
AuditActionOpenSearchReindexExecuted AuditAction = "opensearch.reindex_executed"
|
||||
|
||||
// AuditActionSystemSettingChanged fires when a SystemAdmin updates
|
||||
// a row in the platform-wide system_settings table via
|
||||
// PUT /api/v1/system/admin/settings/:key. Details payload carries
|
||||
// {key, value_type, old_value, new_value} — sensitive values are
|
||||
// redacted server-side before logging when is_secret=true (P3+;
|
||||
// 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"
|
||||
)
|
||||
|
||||
// AuditOutcome distinguishes successful mutations from middleware-level
|
||||
|
||||
@@ -31,6 +31,8 @@ const (
|
||||
// request lifecycle. Defined here (not inside the langfuse package) so
|
||||
// that logger.CloneContext can preserve it without importing langfuse.
|
||||
LangfuseTraceContextKey ContextKey = "LangfuseTrace"
|
||||
// SystemAdminContextKey is the context key indicating whether the user is a system administrator
|
||||
SystemAdminContextKey ContextKey = "SystemAdmin"
|
||||
)
|
||||
|
||||
// String returns the string representation of the context key
|
||||
|
||||
@@ -93,6 +93,16 @@ func TenantRoleFromContext(ctx context.Context) TenantRole {
|
||||
return v
|
||||
}
|
||||
|
||||
// IsSystemAdminFromContext extracts the system admin flag from ctx.
|
||||
// Returns false (fail-closed) when the key is absent.
|
||||
func IsSystemAdminFromContext(ctx context.Context) bool {
|
||||
v, ok := ctx.Value(SystemAdminContextKey).(bool)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// SessionTenantIDFromContext extracts the session-owner tenant ID from ctx.
|
||||
// Falls back to TenantIDFromContext when the session key is absent.
|
||||
func SessionTenantIDFromContext(ctx context.Context) (uint64, bool) {
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// SystemSettingRepository is the storage layer for the platform-wide
|
||||
// system_settings table. All methods are system-scoped — there is no
|
||||
// tenant_id; rows are global to the deployment.
|
||||
type SystemSettingRepository interface {
|
||||
// Get fetches a row by key. Returns (nil, nil) when the key is not
|
||||
// present — callers fall back to ENV / default at the service layer.
|
||||
Get(ctx context.Context, key string) (*types.SystemSetting, error)
|
||||
// List returns every row. Used by the management UI to render the
|
||||
// settings page; no pagination yet (the registry is small — single
|
||||
// digits in P1, expected to stay double-digits long-term).
|
||||
List(ctx context.Context) ([]*types.SystemSetting, error)
|
||||
// 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
|
||||
}
|
||||
|
||||
// SystemSettingService exposes both the 3-tier resolver (used by
|
||||
// production code paths that consume settings) and the management CRUD
|
||||
// (used by the SystemAdmin UI).
|
||||
//
|
||||
// 3-tier resolver priority: DB > ENV > built-in default. The service
|
||||
// owns the registry of legal keys; reading or writing an unknown key
|
||||
// returns an error from Update / falls through to default for Get.
|
||||
//
|
||||
// P1 ships with no in-memory cache: every GetXxx hits the DB. The
|
||||
// callers (file-upload size check, etc.) are not on a hot path so the
|
||||
// extra ~1ms is negligible. P2 may add Redis pubsub + a TTL cache;
|
||||
// the SubscribeRedis hook below is a placeholder for that.
|
||||
type SystemSettingService interface {
|
||||
// GetInt returns the resolved int64 value for `key`.
|
||||
//
|
||||
// envName is the legacy environment-variable name to consult when
|
||||
// the DB row is absent ("" means the key has no ENV fallback).
|
||||
// def is the built-in default used when both DB and ENV miss.
|
||||
//
|
||||
// Errors at the DB layer degrade gracefully: the function logs a
|
||||
// warning and falls through to ENV / default rather than returning
|
||||
// an error to upstream business code (which would have to bubble
|
||||
// it through every caller — we'd rather mis-serve a request with
|
||||
// the default than 500 a file upload).
|
||||
GetInt(ctx context.Context, key string, envName string, def int64) int64
|
||||
GetString(ctx context.Context, key string, envName string, def string) string
|
||||
GetBool(ctx context.Context, key string, envName string, def bool) bool
|
||||
// GetStringList resolves a comma-separated list of strings. envName
|
||||
// is treated as a comma-separated string at the ENV level (mirrors
|
||||
// the legacy SSRF_WHITELIST format). The slice returned is always
|
||||
// non-nil so callers can iterate without a nil check.
|
||||
GetStringList(ctx context.Context, key string, envName string, def []string) []string
|
||||
|
||||
// List, Get, Update are the management-CRUD surface called by the
|
||||
// SystemAdmin handlers (gated to user.is_system_admin = true at the
|
||||
// router layer). Update emits an audit log on success.
|
||||
List(ctx context.Context) ([]*types.SystemSetting, error)
|
||||
Get(ctx context.Context, key string) (*types.SystemSetting, error)
|
||||
// Update writes a new value for `key`, validating that:
|
||||
// 1. key is in the in-code registry (rejects 400 otherwise — UI
|
||||
// cannot inject arbitrary keys),
|
||||
// 2. rawValue's Go type matches the registry's expected type
|
||||
// (e.g. int64 / float64 for "int", string for "string", bool
|
||||
// for "bool"),
|
||||
// 3. the actor is captured from ctx (UserIDFromContext) and
|
||||
// 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)
|
||||
|
||||
// SubscribeRedis is a P2 hook: when implemented, it will subscribe
|
||||
// to a "weknora:system_settings:changed" channel and invalidate any
|
||||
// in-memory cache on receipt. P1 implementations may return a no-op
|
||||
// because there is no cache yet. Keeping the method in the interface
|
||||
// now means P2 can drop in a real implementation without changing
|
||||
// the container wiring.
|
||||
SubscribeRedis(ctx context.Context) error
|
||||
}
|
||||
@@ -65,6 +65,11 @@ type UserService interface {
|
||||
GetCurrentUser(ctx context.Context) (*types.User, error)
|
||||
// SearchUsers searches users by username or email
|
||||
SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error)
|
||||
// ListSystemAdmins lists users with IsSystemAdmin=true.
|
||||
// Returns the page of admins plus the total count (for pagination UI);
|
||||
// callers pass offset/limit to page through results. Used by the
|
||||
// /api/v1/system/admin/list endpoint, gated to SystemAdmin callers.
|
||||
ListSystemAdmins(ctx context.Context, offset, limit int) ([]*types.User, int64, error)
|
||||
// UpdateUserPreferences partially updates the calling user's
|
||||
// preferences blob (PATCH semantics: only keys present in `patch`
|
||||
// overwrite existing values). Returns the updated, persisted prefs.
|
||||
@@ -92,6 +97,11 @@ type UserRepository interface {
|
||||
DeleteUser(ctx context.Context, id string) error
|
||||
// ListUsers lists users with pagination
|
||||
ListUsers(ctx context.Context, offset, limit int) ([]*types.User, error)
|
||||
// ListSystemAdmins lists users where is_system_admin = true.
|
||||
// Walks the partial-friendly idx_users_is_system_admin index. Returns
|
||||
// the slice plus the total count for pagination metadata. Used by
|
||||
// the system-admin management endpoint.
|
||||
ListSystemAdmins(ctx context.Context, offset, limit int) ([]*types.User, int64, error)
|
||||
// SearchUsers searches users by username or email
|
||||
SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SystemSetting is a platform-wide (NOT tenant-scoped) tunable that
|
||||
// SystemAdmins can edit at runtime via the management UI without
|
||||
// restarting the service. Persisted in the system_settings table
|
||||
// (migration 000053).
|
||||
//
|
||||
// The 3-tier resolver in service.SystemSettingService reads in priority
|
||||
// order: DB row > os.Getenv(EnvName) > built-in default. The Service
|
||||
// owns the registry of legal keys + their default values + their ENV
|
||||
// names; this type is just the on-disk shape.
|
||||
//
|
||||
// Value is stored as JSONB so the same column can hold ints / strings /
|
||||
// booleans / arrays. ValueType ("int" | "string" | "bool") tells callers
|
||||
// (and the AsXxx helpers below) how to decode the raw bytes. Booleans
|
||||
// roundtrip as `true`/`false`, ints as `42`, strings as `"foo"`.
|
||||
type SystemSetting struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
Key string `gorm:"type:varchar(128);uniqueIndex;not null" json:"key"`
|
||||
Value JSON `gorm:"type:jsonb;not null" json:"value"`
|
||||
// ValueType is one of "int", "string", "bool". Service layer rejects
|
||||
// updates whose payload type does not match; UI uses it to pick
|
||||
// InputNumber vs Input vs Switch.
|
||||
ValueType string `gorm:"type:varchar(16);not null" json:"value_type"`
|
||||
// Category groups settings in the management UI ("limits", "agent",
|
||||
// "auth", ...). Free-form string so adding a new category is a
|
||||
// data-only change.
|
||||
Category string `gorm:"type:varchar(32);not null" json:"category"`
|
||||
Description string `gorm:"type:text;not null;default:''" json:"description"`
|
||||
// IsSecret reserves UI affordances for P3 (mask + reveal-with-confirm).
|
||||
// In P1 every row is is_secret=false; service Update accepts the
|
||||
// column but does not yet enforce special handling.
|
||||
IsSecret bool `gorm:"not null;default:false" json:"is_secret"`
|
||||
// RequiresRestart reserves UI affordances for P3 (banner "this
|
||||
// change won't take effect until the next restart"). In P1 the
|
||||
// only seeded key is per-request, so always false.
|
||||
RequiresRestart bool `gorm:"not null;default:false" json:"requires_restart"`
|
||||
LastModifiedBy string `gorm:"type:varchar(36);not null;default:''" json:"last_modified_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
||||
// Enum is populated by the service layer (NOT persisted) from the
|
||||
// in-code registry. Empty/nil means "free-form input"; non-empty
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// TableName pins the schema to migration 000053 — GORM's default
|
||||
// pluralisation would yield "system_settings" anyway, but spelling it
|
||||
// out shields against future renames.
|
||||
func (SystemSetting) TableName() string {
|
||||
return "system_settings"
|
||||
}
|
||||
|
||||
// AsInt decodes the raw JSON value as an int64. Returns an error if
|
||||
// ValueType is not "int" or the JSON does not parse as a number.
|
||||
//
|
||||
// Accepts both `42` (number literal) and `"42"` (quoted string) so
|
||||
// hand-edited DB rows are tolerated. The service-layer Update path
|
||||
// always writes a number literal.
|
||||
func (s *SystemSetting) AsInt() (int64, error) {
|
||||
if s.ValueType != "int" {
|
||||
return 0, fmt.Errorf("system_setting %q: value_type=%q, not int", s.Key, s.ValueType)
|
||||
}
|
||||
if len(s.Value) == 0 {
|
||||
return 0, fmt.Errorf("system_setting %q: empty value", s.Key)
|
||||
}
|
||||
// Try number first (canonical form).
|
||||
var n int64
|
||||
if err := json.Unmarshal(s.Value, &n); err == nil {
|
||||
return n, nil
|
||||
}
|
||||
// Fall back to quoted string ("42") — tolerate hand-edited rows.
|
||||
var raw string
|
||||
if err := json.Unmarshal(s.Value, &raw); err == nil {
|
||||
if v, err := strconv.ParseInt(raw, 10, 64); err == nil {
|
||||
return v, nil
|
||||
}
|
||||
}
|
||||
return 0, fmt.Errorf("system_setting %q: cannot parse %s as int", s.Key, string(s.Value))
|
||||
}
|
||||
|
||||
// AsString decodes the raw JSON value as a string. Requires ValueType
|
||||
// to be "string"; the JSON must be a JSON string ("foo"), not a number
|
||||
// or object.
|
||||
func (s *SystemSetting) AsString() (string, error) {
|
||||
if s.ValueType != "string" {
|
||||
return "", fmt.Errorf("system_setting %q: value_type=%q, not string", s.Key, s.ValueType)
|
||||
}
|
||||
if len(s.Value) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
var v string
|
||||
if err := json.Unmarshal(s.Value, &v); err != nil {
|
||||
return "", fmt.Errorf("system_setting %q: %w", s.Key, err)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// AsBool decodes the raw JSON value as a bool. Requires ValueType to
|
||||
// be "bool"; the JSON must be `true` or `false`.
|
||||
func (s *SystemSetting) AsBool() (bool, error) {
|
||||
if s.ValueType != "bool" {
|
||||
return false, fmt.Errorf("system_setting %q: value_type=%q, not bool", s.Key, s.ValueType)
|
||||
}
|
||||
if len(s.Value) == 0 {
|
||||
return false, errors.New("empty value")
|
||||
}
|
||||
var v bool
|
||||
if err := json.Unmarshal(s.Value, &v); err != nil {
|
||||
return false, fmt.Errorf("system_setting %q: %w", s.Key, err)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// AsStringList decodes the raw JSON value as []string. Requires
|
||||
// ValueType to be "string_list"; the JSON must be a JSON array of
|
||||
// strings, e.g. `["example.com", "*.foo.bar", "10.0.0.0/8"]`.
|
||||
//
|
||||
// Returns an empty (non-nil) slice for an empty list, so callers can
|
||||
// treat the absence of items uniformly and still iterate without nil checks.
|
||||
func (s *SystemSetting) AsStringList() ([]string, error) {
|
||||
if s.ValueType != "string_list" {
|
||||
return nil, fmt.Errorf("system_setting %q: value_type=%q, not string_list", s.Key, s.ValueType)
|
||||
}
|
||||
if len(s.Value) == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
var v []string
|
||||
if err := json.Unmarshal(s.Value, &v); err != nil {
|
||||
return nil, fmt.Errorf("system_setting %q: %w", s.Key, err)
|
||||
}
|
||||
if v == nil {
|
||||
v = []string{}
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
@@ -92,6 +92,8 @@ type User struct {
|
||||
IsActive bool `json:"is_active" gorm:"default:true"`
|
||||
// Whether the user can access all tenants (cross-tenant access)
|
||||
CanAccessAllTenants bool `json:"can_access_all_tenants" gorm:"default:false"`
|
||||
// Whether the user is a system administrator (independent of tenant roles)
|
||||
IsSystemAdmin bool `json:"is_system_admin" gorm:"default:false;index"`
|
||||
// Per-user UI/feature preferences (memory toggle, future knobs).
|
||||
// Stored as JSON (jsonb on Postgres, TEXT on SQLite) via the
|
||||
// driver.Valuer / sql.Scanner methods on UserPreferences.
|
||||
@@ -219,6 +221,7 @@ type UserInfo struct {
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
IsActive bool `json:"is_active"`
|
||||
CanAccessAllTenants bool `json:"can_access_all_tenants"`
|
||||
IsSystemAdmin bool `json:"is_system_admin"`
|
||||
Preferences UserPreferences `json:"preferences"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
@@ -234,6 +237,7 @@ func (u *User) ToUserInfo() *UserInfo {
|
||||
TenantID: u.TenantID,
|
||||
IsActive: u.IsActive,
|
||||
CanAccessAllTenants: u.CanAccessAllTenants,
|
||||
IsSystemAdmin: u.IsSystemAdmin,
|
||||
Preferences: u.Preferences,
|
||||
CreatedAt: u.CreatedAt,
|
||||
UpdatedAt: u.UpdatedAt,
|
||||
|
||||
Reference in New Issue
Block a user