安全加固(降低二进制泄露/逆向的信息面):
1. 初始密码随机化
- 首次启动生成 16 位随机密码(大小写+数字,排除 0/O/1/l/I 易混淆字符)
- 写入数据卷 initial-admin-password.txt(0600)并打印到首次启动日志
- admin 首次改密后自动删除该文件(seed.CleanupInitPassword)
- 支持 ADMIN_INIT_PASSWORD 环境变量指定(自动化部署 / 固定密码场景)
- 生成失败直接 Fatal 退出,不再降级到公开默认口令
2. 移除硬编码 admin123
- main.go 不再打印 "Default login: admin / admin123"
- 二进制内 admin123 命中:2 → 0
3. -trimpath
- build.sh / run.sh 编译加 -trimpath
- 二进制内 /app/backend/ 源码路径命中:66 → 0
4. 文档
- README 新增「第 4 步:获取管理员初始密码」
(docker compose exec / logs / docker cp / named volume 四种方式 + K8s 对应命令)
- .env.example 补 ADMIN_INIT_PASSWORD
- kubernetes/deployment.yaml 加 env 注释说明
验证(strings 对比加固前后二进制):
admin123 2 → 0
/app/backend/ 66 → 0
initial-admin-password.txt / ADMIN_INIT_PASSWORD / CleanupInitPassword 均存在
79 lines
2.3 KiB
Go
79 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"opsxloki/config"
|
|
"opsxloki/repository"
|
|
"opsxloki/routers"
|
|
"opsxloki/seed"
|
|
"opsxloki/services"
|
|
)
|
|
|
|
func main() {
|
|
cfg := config.GetConfig()
|
|
|
|
log.Println("Initializing database...")
|
|
if err := repository.InitDB(); err != nil {
|
|
log.Fatalf("Failed to init DB: %v", err)
|
|
}
|
|
|
|
log.Println("Seeding default data...")
|
|
seed.Seed()
|
|
|
|
// 安全迁移:历史明文 kubeconfig → 加密存储,并清理明文文件
|
|
services.MigrateClusterKubeconfigs()
|
|
|
|
// 孤儿部署状态恢复:进程重启会杀掉进行中的部署 goroutine,
|
|
// 残留的 "deploying" 状态将永远卡住(UI 无停止入口),启动时统一标记为失败。
|
|
repository.GetDB().RecoverOrphanDeployments()
|
|
|
|
services.StartAlertEngine()
|
|
defer services.StopAlertEngine()
|
|
|
|
r := routers.SetupRouter()
|
|
srv := &http.Server{
|
|
Addr: ":" + cfg.ServerPort,
|
|
Handler: r,
|
|
ReadTimeout: 30 * time.Second,
|
|
WriteTimeout: 130 * time.Second,
|
|
IdleTimeout: 120 * time.Second,
|
|
}
|
|
|
|
// 监听中断/终止信号,实现优雅关停:先停 HTTP(拒绝新请求、处理完在途请求),
|
|
// 再 flush 数据库,避免防抖/异步保存丢失最近写入。
|
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
go func() {
|
|
log.Printf("opsx-loki starting on port %s", cfg.ServerPort)
|
|
log.Printf("API: http://localhost:%s/api/v1", cfg.ServerPort)
|
|
// 初始密码:首次启动日志中的「已生成管理员账号」,或数据卷 initial-admin-password.txt
|
|
log.Printf("首次部署请查看启动日志或 %s/initial-admin-password.txt 获取 admin 初始密码", cfg.DataDir)
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Fatalf("Server failed: %v", err)
|
|
}
|
|
}()
|
|
|
|
<-ctx.Done()
|
|
log.Println("Shutdown signal received, draining connections...")
|
|
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
|
log.Printf("HTTP shutdown error: %v", err)
|
|
}
|
|
|
|
log.Println("Flushing database...")
|
|
if err := repository.Shutdown(); err != nil {
|
|
log.Printf("DB shutdown error: %v", err)
|
|
}
|
|
log.Println("LokiDeploy stopped")
|
|
}
|