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

+21 -1
View File
@@ -1,6 +1,7 @@
package handler
import (
"crypto/rand"
"net/http"
"strconv"
@@ -221,7 +222,13 @@ func BatchImportUsers(c *gin.Context) {
password := u.Password
if password == "" {
password = "admin123"
// 不再使用公开默认口令:随机生成并在响应中回传给管理员
gen, gerr := genPassword(14)
if gerr != nil {
errors = append(errors, "fail: "+u.Username+" 密码生成失败")
continue
}
password = gen
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
@@ -379,3 +386,16 @@ func ResetUserPassword(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"message": "Password reset successfully"})
}
// genPassword 生成 n 位随机密码(排除易混淆字符),用于批量导入未指定密码的用户
func genPassword(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
}