feat(security): 默认账号随机初始密码(不再硬编码 admin123)

参考 lokistack 的实现:

1. 首次启动生成 16 位随机密码(大小写+数字,排除 0/O/1/l/I 易混淆字符)
   - 4 个默认账号共用:admin / dba / auditor / developer
   - 写入数据目录 initial-admin-password.txt(0600)
   - 打印到启动日志(含账号列表、密码、文件路径、docker/kubectl 获取命令)

2. 支持 ADMIN_INIT_PASSWORD 环境变量覆盖(自动化部署 / 需要固定密码时)

3. 生成失败直接 log.Fatalf 退出,不降级到公开默认口令

4. 批量导入用户 BatchImportUsers:空密码不再默认 admin123,
   改为随机 14 位(新增 genPassword),保证每个导入用户密码不可预测

5. 幂等:已存在的账号不重建、不改密码;只有缺失的账号才创建

6. imagePullPolicy: IfNotPresent → Always
   原因:latest tag 配 IfNotPresent 会导致节点一直复用缓存的旧镜像,
        新 push 的镜像不生效(本次实测踩到:Pod imageID 仍是旧 digest)

7. 文档
   - README 新增「首次部署获取默认账号密码」章节(含 4 账号角色表 + 3 种获取方式)
   - docker-compose.yml 加 ADMIN_INIT_PASSWORD 环境变量
   - kubernetes/deployment.yaml 加 env 注释

验证(清空 DB 后全新 seed):
  镜像 sha256:eaf0affd8d93
  /app/data/initial-admin-password.txt  199B  权限 0600
  内容含 "适用账号: [admin dba auditor developer]" + 随机密码
  启动日志完整打印获取方式
  登录实测:admin / dba / developer 用新密码均返回 access_token;
           admin123 登录失败(已失效)
  二进制 strings:admin123 命中 0
This commit is contained in:
opsx committed 2026-10-26 17:37:21 +00:00
1 parent 396df57c9c
commit d584b64813
5 files changed
+184 -26

No files matched your search

+101 -24
View File
@@ -1,7 +1,11 @@
package main
import (
"crypto/rand"
"fmt"
"log"
"os"
"path/filepath"
"sql-platform/internal/model"
@@ -20,6 +24,32 @@ func seedAll(db *gorm.DB) {
log.Println("[seed] Default data initialized")
}
// InitPasswordFile 首次启动生成的默认账号初始密码文件名。
// 默认账号(admin/dba/auditor/developer)共用这一个密码,登录后请尽快修改。
const InitPasswordFile = "initial-admin-password.txt"
// randomPassword 生成 n 位随机密码(大小写字母 + 数字,排除 0/O/1/l/I 等易混淆字符)
func randomPassword(n int) (string, error) {
const charset = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"
buf := make([]byte, n)
if _, err := rand.Read(buf); err != nil {
return "", err
}
for i := range buf {
buf[i] = charset[int(buf[i])%len(charset)]
}
return string(buf), nil
}
// dataDir 返回数据目录(由 DB_PATH 决定),用于存放初始密码文件
func dataDir() string {
dbPath := os.Getenv("DB_PATH")
if dbPath == "" {
dbPath = "/app/data/sqlite3.db"
}
return filepath.Dir(dbPath)
}
// seedDefaultUsers creates default users if they don't exist.
func seedDefaultUsers(db *gorm.DB) {
type seedUser struct {
@@ -27,37 +57,84 @@ func seedDefaultUsers(db *gorm.DB) {
displayName string
email string
role string
password string
active bool
}
users := []seedUser{
{"admin", "超级管理员", "admin@opsx.local", "admin", "admin123", true},
{"dba", "DBA管理员", "dba@opsx.local", "dba", "admin123", true},
{"auditor", "审计员", "auditor@opsx.local", "auditor", "admin123", true},
{"developer", "开发者", "developer@opsx.local", "developer", "admin123", true},
}
users := []seedUser{
{"admin", "超级管理员", "admin@opsx.local", "admin"},
{"dba", "DBA管理员", "dba@opsx.local", "dba"},
{"auditor", "审计员", "auditor@opsx.local", "auditor"},
{"developer", "开发者", "developer@opsx.local", "developer"},
}
// 先找出缺失的默认账号;一个都不缺就直接返回,不生成任何密码
var missing []seedUser
for _, u := range users {
var existing model.User
if db.Where("username = ?", u.username).First(&existing).Error != nil {
hash, _ := bcrypt.GenerateFromPassword([]byte(u.password), bcrypt.DefaultCost)
email := u.email
active := u.active
user := model.User{
Username: u.username,
DisplayName: u.displayName,
Email: &email,
HashedPassword: string(hash),
Role: u.role,
IsActive: &active,
}
if err := db.Create(&user).Error; err != nil {
log.Printf("[seed] Failed to create user %s: %v", u.username, err)
} else {
log.Printf("[seed] Created user: %s (%s)", u.username, u.role)
}
missing = append(missing, u)
}
}
if len(missing) == 0 {
return
}
// 决定初始密码:ADMIN_INIT_PASSWORD 优先,否则随机生成
pwd := os.Getenv("ADMIN_INIT_PASSWORD")
generated := false
if pwd == "" {
var err error
if pwd, err = randomPassword(16); err != nil {
log.Fatalf("[seed] 生成随机初始密码失败: %v;请通过 ADMIN_INIT_PASSWORD 环境变量指定初始密码", err)
}
generated = true
}
var created []string
for _, u := range missing {
hash, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
email := u.email
active := true
user := model.User{
Username: u.username,
DisplayName: u.displayName,
Email: &email,
HashedPassword: string(hash),
Role: u.role,
IsActive: &active,
}
if err := db.Create(&user).Error; err != nil {
log.Printf("[seed] Failed to create user %s: %v", u.username, err)
} else {
created = append(created, u.username)
log.Printf("[seed] Created user: %s (%s)", u.username, u.role)
}
}
if len(created) == 0 {
return
}
if generated {
path := filepath.Join(dataDir(), InitPasswordFile)
content := fmt.Sprintf("# opsxsql 默认账号初始密码(首次启动生成)\n"+
"# 登录后请立即修改;确认无需保留时可删除本文件\n"+
"# 适用账号: %v\n"+
"密码: %s\n", created, pwd)
if err := os.WriteFile(path, []byte(content), 0600); err != nil {
log.Printf("[seed] 写入初始密码文件失败: %v", err)
}
log.Printf("============================================================")
log.Printf(" 首次启动:已创建默认账号 %v", created)
log.Printf(" 初始密码 : %s", pwd)
log.Printf(" 已保存到 : %s", path)
log.Printf(" 获取方式 :")
log.Printf(" docker compose exec <服务名> cat %s", path)
log.Printf(" kubectl -n <ns> exec deploy/opsxsql -- cat %s", path)
log.Printf(" ⚠️ 所有默认账号共用此密码,登录后请立即修改")
log.Printf("============================================================")
} else {
log.Printf("[seed] 默认账号初始密码来自环境变量 ADMIN_INIT_PASSWORD")
}
}
// seedDefaultWorkflow creates a default approval workflow if none exists.