feat(auth): promote bootstrap system admin at sign-up (fixes #5001)

Evaluate WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL during userService.Register so a
matching email is promoted to system admin immediately at sign-up when no
system administrator exists yet, eliminating the restart required on fresh
deployments while retaining cmd/server startup promotion for pre-existing users.

- Share BootstrapSystemAdminEmailEnv between service and cmd/server/bootstrap.go.
- Log promotion only after CreateUser and EnsureOwner succeed (sanitizing the
  email), warn and fail closed if ListSystemAdmins fails, and keep all lines
  within the 120-character lll lint limit.
- Replace the broken TenantProvisioningNone test stub with real SQLite-backed
  registration tests covering case-insensitive matching, non-matching emails,
  existing-admin guard, and fail-closed error handling.
- Update bootstrap comments and website-docs to reflect immediate sign-up
  promotion alongside startup fallback.

Co-authored-by: NianJiu <180004567+NianJiuZst@users.noreply.github.com>
This commit is contained in:
chenzaiqiangandNianJiu authored and NianJiu committed 2026-11-21 12:36:33 +08:00
1 parent 9a98c3aaca
commit 4374bf340f
6 files changed
+183 -10

No files matched your search

+6 -3
View File
@@ -13,6 +13,7 @@ import (
"go.uber.org/dig"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
@@ -30,7 +31,7 @@ import (
// - Safe to leave set: once at least one system admin exists, the env
// var stops granting privileges. That prevents a UI revoke from being
// silently undone on the next restart.
const bootstrapEnvVar = "WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL"
const bootstrapEnvVar = service.BootstrapSystemAdminEmailEnv
// runStartupBootstrap consults the env and applies any one-shot
// bootstrap actions. Currently it only handles system-admin promotion;
@@ -74,8 +75,10 @@ func runStartupBootstrap(c *dig.Container) {
// The bootstrap intentionally does NOT create a user when the email is
// not yet registered: account creation is a workflow with side effects
// (password hashing, tenant assignment, audit) that we don't want to
// short-circuit. Operators should sign up normally first, then set the
// env var on the next restart.
// short-circuit. New sign-ups matching bootstrapEnvVar are promoted
// immediately inside userService.Register when no system admin exists;
// this startup hook remains for accounts that registered before the env
// var was configured.
func bootstrapSystemAdmin(ctx context.Context, userSvc interfaces.UserService, email string) {
user, err := userSvc.GetUserByEmail(ctx, email)
if err != nil {
+46
View File
@@ -31,6 +31,12 @@ import (
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// BootstrapSystemAdminEmailEnv names the environment variable identifying the
// initial system administrator email. When set and no system administrators
// exist yet, a matching account is promoted at sign-up (or on startup if the
// account was created before the variable was configured).
const BootstrapSystemAdminEmailEnv = "WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL"
var (
jwtSecretOnce sync.Once
jwtSecret string
@@ -198,6 +204,10 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest)
user.TenantID = createdTenant.ID
}
if shouldPromoteBootstrapSystemAdmin(ctx, s.userRepo, req.Email) {
user.IsSystemAdmin = true
}
err = s.userRepo.CreateUser(ctx, user)
if err != nil {
logger.Errorf(ctx, "Failed to create user: %v", err)
@@ -223,10 +233,46 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest)
}
}
if user.IsSystemAdmin {
logger.Infof(ctx,
"[bootstrap] promoted user %s (%s) to system admin via %s on registration",
user.ID, secutils.SanitizeForLog(user.Email), BootstrapSystemAdminEmailEnv,
)
}
logger.Info(ctx, "User registered successfully")
return user, nil
}
// shouldPromoteBootstrapSystemAdmin reports whether a newly registering email
// matches BootstrapSystemAdminEmailEnv while no system admins exist yet.
// Errors fail closed and only log a warning so registration itself is never
// blocked by a best-effort bootstrap check.
func shouldPromoteBootstrapSystemAdmin(
ctx context.Context, userRepo interfaces.UserRepository, email string,
) bool {
bootstrapEmail := strings.TrimSpace(os.Getenv(BootstrapSystemAdminEmailEnv))
if bootstrapEmail == "" || !strings.EqualFold(strings.TrimSpace(email), bootstrapEmail) {
return false
}
_, total, err := userRepo.ListSystemAdmins(ctx, 0, 1)
if err != nil {
logger.Warnf(ctx,
"[bootstrap] %s=%s: cannot verify existing system admins, skipping promotion: %v",
BootstrapSystemAdminEmailEnv, secutils.SanitizeForLog(bootstrapEmail), err,
)
return false
}
if total > 0 {
logger.Infof(ctx,
"[bootstrap] %s=%s: %d system admin(s) already exist; not promoting on registration",
BootstrapSystemAdminEmailEnv, secutils.SanitizeForLog(bootstrapEmail), total,
)
return false
}
return true
}
// Login authenticates a user and returns tokens
func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*types.LoginResponse, error) {
logger.Info(ctx, "Start user login")
@@ -2,16 +2,26 @@ package service
import (
"context"
"errors"
"path/filepath"
"testing"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type provisioningUserRepo struct {
interfaces.UserRepository
created *types.User
updatedTenant uint64
listAdminErr error
}
func (r *provisioningUserRepo) ListSystemAdmins(context.Context, int, int) ([]*types.User, int64, error) {
return nil, 0, r.listAdminErr
}
func (r *provisioningUserRepo) GetUserByEmail(context.Context, string) (*types.User, error) {
@@ -210,3 +220,117 @@ func TestBuildLoginMembershipsSynthsWhenMemberServiceMissing(t *testing.T) {
t.Fatalf("fallback memberships = %#v", got)
}
}
func newBootstrapUserRepo(t *testing.T) interfaces.UserRepository {
t.Helper()
db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "users.db")), &gorm.Config{})
if err != nil {
t.Fatalf("open sqlite db: %v", err)
}
sqlDB, err := db.DB()
if err != nil {
t.Fatalf("sql db: %v", err)
}
t.Cleanup(func() { _ = sqlDB.Close() })
if err := db.AutoMigrate(&types.User{}); err != nil {
t.Fatalf("migrate users: %v", err)
}
return apprepo.NewUserRepository(db)
}
func TestUserServiceRegisterPromotesBootstrapSystemAdmin(t *testing.T) {
ctx := context.Background()
t.Run("promotes matching email case-insensitively when no system admin exists", func(t *testing.T) {
t.Setenv(BootstrapSystemAdminEmailEnv, " Admin@Example.com ")
repo := newBootstrapUserRepo(t)
svc := &userService{userRepo: repo, tenantService: &provisioningTenantService{}}
user, err := svc.Register(ctx, &types.RegisterRequest{
Username: "admin",
Email: "admin@example.com",
Password: "password123",
TenantProvisioning: types.TenantProvisioningTenantless,
})
if err != nil {
t.Fatalf("Register failed: %v", err)
}
if !user.IsSystemAdmin {
t.Fatal("expected returned user to be promoted to system admin")
}
stored, err := repo.GetUserByEmail(ctx, "admin@example.com")
if err != nil {
t.Fatalf("GetUserByEmail: %v", err)
}
if !stored.IsSystemAdmin {
t.Fatal("expected persisted user row to have is_system_admin=true")
}
})
t.Run("does not promote non-matching email", func(t *testing.T) {
t.Setenv(BootstrapSystemAdminEmailEnv, "admin@example.com")
repo := newBootstrapUserRepo(t)
svc := &userService{userRepo: repo, tenantService: &provisioningTenantService{}}
user, err := svc.Register(ctx, &types.RegisterRequest{
Username: "alice",
Email: "alice@example.com",
Password: "password123",
TenantProvisioning: types.TenantProvisioningTenantless,
})
if err != nil {
t.Fatalf("Register failed: %v", err)
}
if user.IsSystemAdmin {
t.Fatal("non-matching email should not be promoted")
}
})
t.Run("does not promote when a system admin already exists", func(t *testing.T) {
t.Setenv(BootstrapSystemAdminEmailEnv, "second-admin@example.com")
repo := newBootstrapUserRepo(t)
if err := repo.CreateUser(ctx, &types.User{
ID: "existing-admin",
Username: "existing",
Email: "existing@example.com",
PasswordHash: "hash",
IsActive: true,
IsSystemAdmin: true,
}); err != nil {
t.Fatalf("seed existing admin: %v", err)
}
svc := &userService{userRepo: repo, tenantService: &provisioningTenantService{}}
user, err := svc.Register(ctx, &types.RegisterRequest{
Username: "second",
Email: "second-admin@example.com",
Password: "password123",
TenantProvisioning: types.TenantProvisioningTenantless,
})
if err != nil {
t.Fatalf("Register failed: %v", err)
}
if user.IsSystemAdmin {
t.Fatal("matching email must not be promoted when an admin already exists")
}
})
t.Run("fails closed when ListSystemAdmins returns an error", func(t *testing.T) {
t.Setenv(BootstrapSystemAdminEmailEnv, "admin@example.com")
repo := &provisioningUserRepo{listAdminErr: errors.New("db unavailable")}
svc := &userService{userRepo: repo, tenantService: &provisioningTenantService{}}
user, err := svc.Register(ctx, &types.RegisterRequest{
Username: "admin",
Email: "admin@example.com",
Password: "password123",
TenantProvisioning: types.TenantProvisioningTenantless,
})
if err != nil {
t.Fatalf("Register should still succeed on best-effort bootstrap error: %v", err)
}
if user.IsSystemAdmin {
t.Fatal("bootstrap check error must fail closed without granting admin")
}
})
}
@@ -33,7 +33,7 @@
::: tip 空间与平台权限
空间 Owner 管理所在空间的成员、模型和知识库。全局系统设置、平台任务队列及跨空间审计需要系统管理员身份,两类权限独立授予。
首次设置系统管理员时,先注册账号,再为 app 服务配置 `WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL=<该账号邮箱>` 并重启。该流程仅在部署尚无系统管理员时生效。完整步骤与限制见[平台管理与系统管理员](../03-features/20-platform-admin.md)。
首次设置系统管理员时,为 app 服务配置 `WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL=<管理员邮箱>` 后直接注册该邮箱即可自动成为系统管理员(无需重启);若账号先于变量配置注册,则在下次重启时自动提升。该流程仅在部署尚无系统管理员时生效。完整步骤与限制见[平台管理与系统管理员](../03-features/20-platform-admin.md)。
:::
## 创建知识库并配置模型 {#_3-创建知识库并配置模型}
@@ -244,7 +244,7 @@ AWS S3 的 `S3_ACCESS_KEY` / `S3_SECRET_KEY` 可以**同时留空**,此时走
| `OIDC_AUTH_JWKS_URI` | 空 | id_token 验签公钥集;可经 discovery 补全,与 issuer/audience/有效期共同校验 |
| `WEKNORA_INVITATION_TTL` | 168h | 邀请链接有效期 |
| `WEKNORA_AUDIT_RETENTION_DAYS` | 90 | 审计日志保留天数 |
| `WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL` | 空 | 引导第一个系统管理员。**不会创建用户**:该邮箱需先自行注册,下次启动时若部署内还没有任何系统管理员,才把它提升;已有管理员后本变量不再生效。详见[租户、用户与认证授权](../03-features/01-tenant-auth.md) |
| `WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL` | 空 | 引导第一个系统管理员。**不会创建用户**:部署尚无系统管理员时,该邮箱在注册时立即提升(无需重启);若账号先于变量配置注册,则在下次启动时提升;已有管理员后本变量不再生效。详见[租户、用户与认证授权](../03-features/01-tenant-auth.md) |
| `OIDC_AUTH_ENABLE` 及 `OIDC_AUTH_*` / `OIDC_USER_INFO_MAPPING_*` | false / 空 | OIDC 单点登录全套配置 |
| `SSRF_WHITELIST` / `SSRF_WHITELIST_EXTRA` | 空 / `searxng,qdrant,milvus,weaviate,doris-fe,doris-be,minio`(仅 app) | 出站请求 SSRF 白名单。`SSRF_WHITELIST` 为 app 与 docreader 共用;compose 只给 app 的 `SSRF_WHITELIST_EXTRA` 设了默认值,docreader 的同名变量默认为空 |
| `SSRF_DNS_WHITELIST_ONLY` | false | 仅允许白名单出站(app 与 docreader 均读取)。开启后,不在白名单的主机在 **DNS 查询前**即被拒绝,URL 校验处不在白名单的 IP 直连也一并拒绝;域名只按名字匹配,写在白名单里的 CIDR 不再对域名生效。取值按布尔解析(`1/t/true` 开、`0/f/false` 关),**非空且无法解析的取值按「开」处理**。开启前的准备见下文 |
@@ -20,13 +20,13 @@
## 设置首个系统管理员 {#_1-第一个系统管理员怎么来}
新部署需要先设置首个系统管理员:
新部署可通过环境变量引导首个系统管理员:
1. 先用正常流程注册一个账号;
2. 为 app 服务配置 `WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL=<该账号邮箱>`,重启;
3. 启动时仅在部署尚无系统管理员的情况下,将该邮箱对应的用户设为系统管理员。
1. 为 app 服务配置 `WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL=<管理员邮箱>`;
2. 正常注册该邮箱对应的账号——部署尚无系统管理员时,注册完成即自动授予系统管理员权限,无需重启;
3. 若账号在配置该变量之前已注册,配置变量后重启 app 同样会在启动时自动提升。
引导流程只提升已存在的账号。邮箱尚未注册时会记录告警,后续重启再次检查;配置错误不阻断服务启动。部署已有系统管理员后,该变量不再授予权限。
引导流程只提升真实注册的账号,不会自动建号;配置错误不阻断服务启动。部署已有系统管理员后,该变量不再授予权限。
后续可在界面中添加或撤销系统管理员。不能撤销自己,也不能撤销最后一位系统管理员。对应接口为 `POST /system/admin/promote` 和 `/revoke`;重复撤销非管理员返回 200,审计记录以 `changed=false` 标明未发生权限变更。