/api/system/stats 改为公开只读并移除仅管理员限制(不再返回 401),前端首页对访客与管理员展示一致;README 同步权限表与接口说明。
220 lines
5.9 KiB
Go
220 lines
5.9 KiB
Go
// 鉴权
|
|
//
|
|
// 采用「单管理员密码 + HMAC 签名会话 Cookie」的轻量方案:
|
|
// - ADMIN_PASSWORD 通过环境变量配置;未设置时禁止登录(访客仍可看公开数据)。
|
|
// - 登录成功签发无状态 Cookie,值为 <过期时间戳>.<HMAC-SHA256 签名>。
|
|
// - SESSION_SECRET 用作签名密钥;未设置时随机生成(重启后已有登录失效)。
|
|
//
|
|
// 权限模型:
|
|
// - 访客(未登录):只能看到容器数量与容器列表(名称/镜像/状态)。
|
|
// - 管理员(已登录):可看到系统状态、容器资源占用、端口等全部信息。
|
|
package main
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
sessionCookieName = "jws_session"
|
|
sessionTTL = 7 * 24 * time.Hour
|
|
|
|
// 登录失败超过 maxLoginFailures 次后锁定 loginLockDuration。
|
|
maxLoginFailures = 5
|
|
loginLockDuration = time.Minute
|
|
)
|
|
|
|
var sessionSecret = loadSessionSecret()
|
|
|
|
func loadSessionSecret() []byte {
|
|
if s := strings.TrimSpace(os.Getenv("SESSION_SECRET")); s != "" {
|
|
sum := sha256.Sum256([]byte(s))
|
|
return sum[:]
|
|
}
|
|
// 没有配置就随机生成:重启后现有登录失效,但至少不是可预测的默认密钥。
|
|
b := make([]byte, 32)
|
|
if _, err := rand.Read(b); err != nil {
|
|
log.Fatalf("生成会话密钥失败: %v", err)
|
|
}
|
|
log.Printf("警告:未设置 SESSION_SECRET,已生成临时密钥,重启后所有登录会失效")
|
|
return b
|
|
}
|
|
|
|
func adminPassword() string {
|
|
return os.Getenv("ADMIN_PASSWORD")
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 会话令牌
|
|
// ---------------------------------------------------------------------------
|
|
|
|
func makeSessionToken(exp time.Time) string {
|
|
payload := strconv.FormatInt(exp.Unix(), 10)
|
|
mac := hmac.New(sha256.New, sessionSecret)
|
|
mac.Write([]byte(payload))
|
|
sig := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
|
return payload + "." + sig
|
|
}
|
|
|
|
func verifySessionToken(token string) bool {
|
|
parts := strings.SplitN(token, ".", 2)
|
|
if len(parts) != 2 {
|
|
return false
|
|
}
|
|
expUnix, err := strconv.ParseInt(parts[0], 10, 64)
|
|
if err != nil || time.Now().Unix() > expUnix {
|
|
return false
|
|
}
|
|
mac := hmac.New(sha256.New, sessionSecret)
|
|
mac.Write([]byte(parts[0]))
|
|
got, err := base64.RawURLEncoding.DecodeString(parts[1])
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return hmac.Equal(mac.Sum(nil), got)
|
|
}
|
|
|
|
// isAuthenticated 判断当前请求是否携带有效的管理员会话。
|
|
func isAuthenticated(r *http.Request) bool {
|
|
c, err := r.Cookie(sessionCookieName)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return verifySessionToken(c.Value)
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 登录失败节流(简单的内存计数,防暴力破解)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
var (
|
|
loginMu sync.Mutex
|
|
loginFailures int
|
|
loginLockedUntil time.Time
|
|
)
|
|
|
|
func loginLocked() bool {
|
|
loginMu.Lock()
|
|
defer loginMu.Unlock()
|
|
return time.Now().Before(loginLockedUntil)
|
|
}
|
|
|
|
func recordLoginFailure() {
|
|
loginMu.Lock()
|
|
defer loginMu.Unlock()
|
|
loginFailures++
|
|
if loginFailures >= maxLoginFailures {
|
|
loginLockedUntil = time.Now().Add(loginLockDuration)
|
|
loginFailures = 0
|
|
}
|
|
}
|
|
|
|
func resetLoginFailures() {
|
|
loginMu.Lock()
|
|
loginFailures = 0
|
|
loginLockedUntil = time.Time{}
|
|
loginMu.Unlock()
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// HTTP 处理
|
|
// ---------------------------------------------------------------------------
|
|
|
|
func handleAuthStatus(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"authenticated": isAuthenticated(r),
|
|
})
|
|
}
|
|
|
|
func handleLogin(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
if adminPassword() == "" {
|
|
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
|
|
"error": "服务端未配置 ADMIN_PASSWORD",
|
|
})
|
|
return
|
|
}
|
|
|
|
if loginLocked() {
|
|
writeJSON(w, http.StatusTooManyRequests, map[string]any{
|
|
"error": "尝试过于频繁,请稍后再试",
|
|
})
|
|
return
|
|
}
|
|
|
|
var body struct {
|
|
Password string `json:"password"`
|
|
}
|
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&body); err != nil {
|
|
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "请求格式错误"})
|
|
return
|
|
}
|
|
|
|
if subtle.ConstantTimeCompare([]byte(body.Password), []byte(adminPassword())) != 1 {
|
|
recordLoginFailure()
|
|
// 让暴力破解变慢。
|
|
time.Sleep(300 * time.Millisecond)
|
|
writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "密码错误"})
|
|
return
|
|
}
|
|
|
|
resetLoginFailures()
|
|
exp := time.Now().Add(sessionTTL)
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: sessionCookieName,
|
|
Value: makeSessionToken(exp),
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
SameSite: http.SameSiteLaxMode,
|
|
Secure: isTLS(r),
|
|
Expires: exp,
|
|
MaxAge: int(sessionTTL.Seconds()),
|
|
})
|
|
writeJSON(w, http.StatusOK, map[string]any{"authenticated": true})
|
|
}
|
|
|
|
func handleLogout(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: sessionCookieName,
|
|
Value: "",
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
SameSite: http.SameSiteLaxMode,
|
|
Secure: isTLS(r),
|
|
MaxAge: -1,
|
|
})
|
|
writeJSON(w, http.StatusOK, map[string]any{"authenticated": false})
|
|
}
|
|
|
|
// isTLS 判断原始请求是否为 HTTPS(生产环境由 nginx 反代,需要看 X-Forwarded-Proto)。
|
|
func isTLS(r *http.Request) bool {
|
|
return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
if err := json.NewEncoder(w).Encode(v); err != nil {
|
|
log.Printf("序列化响应失败: %v", err)
|
|
}
|
|
}
|