合并最新 main

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
fu500f
2026-10-31 01:29:55 +00:00
co-authored by Devin AI
32 changed files with 1138 additions and 85 deletions
+105 -9
View File
@@ -8,6 +8,7 @@ import (
"errors"
"io/fs"
"log"
"net"
"net/http"
"strconv"
"strings"
@@ -19,6 +20,7 @@ import (
"github.com/baicai2026-baicai/goods/api/internal/adminstore"
"github.com/baicai2026-baicai/goods/api/internal/apikey"
"github.com/baicai2026-baicai/goods/api/internal/auth"
"github.com/baicai2026-baicai/goods/api/internal/clientip"
"github.com/baicai2026-baicai/goods/api/internal/gtin"
"github.com/baicai2026-baicai/goods/api/internal/ratelimit"
)
@@ -30,8 +32,11 @@ type Handler struct {
basePath string
spa fs.FS
submitLimit *rateLimiter
loginLimit *loginLimiter
usage usageLimiter
backflowRate int
cache cacheBumper
clientIP *clientip.Resolver
}
type usageLimiter interface {
@@ -39,6 +44,10 @@ type usageLimiter interface {
Usage(context.Context, string) ratelimit.UsageStat
}
type cacheBumper interface {
Bump(context.Context) error
}
// New constructs an admin Handler. basePath is e.g. "/ping" (no trailing slash).
func New(store *adminstore.Store, authn *auth.Authenticator, basePath string, spa fs.FS) *Handler {
basePath = "/" + strings.Trim(basePath, "/")
@@ -48,7 +57,9 @@ func New(store *adminstore.Store, authn *auth.Authenticator, basePath string, sp
basePath: basePath,
spa: spa,
submitLimit: newRateLimiter(5, 10*time.Minute),
loginLimit: newLoginLimiter(10, 20, 15*time.Minute),
backflowRate: 30,
clientIP: clientip.Default(),
}
}
@@ -65,11 +76,48 @@ func (h *Handler) WithBackflowRate(n int) *Handler {
return h
}
// WithCache attaches a cache epoch invalidator for successful admin writes.
func (h *Handler) WithCache(c cacheBumper) *Handler {
h.cache = c
return h
}
func (h *Handler) invalidateCache(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if h.cache == nil || r.Method == http.MethodGet || r.Method == http.MethodHead {
next.ServeHTTP(w, r)
return
}
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)
status := ww.Status()
if status == 0 {
status = http.StatusOK
}
if status < http.StatusOK || status >= http.StatusMultipleChoices {
return
}
if err := h.cache.Bump(context.WithoutCancel(r.Context())); err != nil {
log.Printf("admin cache invalidation failed: %v", err)
}
})
}
// WithClientIP sets the trusted-proxy resolver used to normalize request IPs.
func (h *Handler) WithClientIP(resolver *clientip.Resolver) *Handler {
if resolver == nil {
resolver = clientip.Default()
}
h.clientIP = resolver
return h
}
// Router builds the HTTP handler.
func (h *Handler) Router() http.Handler {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(h.clientIP.Middleware)
r.Use(middleware.Recoverer)
r.Route(h.basePath, func(r chi.Router) {
@@ -80,6 +128,8 @@ func (h *Handler) Router() http.Handler {
r.Group(func(r chi.Router) {
r.Use(h.authn.Middleware)
r.Use(h.invalidateCache)
r.Post("/api/logout", h.Logout)
r.Get("/api/me", h.Me)
r.Get("/api/stats", h.Stats)
r.Get("/api/audit", h.ListAllAudit)
@@ -170,14 +220,66 @@ func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "bad_request", "invalid body")
return
}
ip := loginIP(r)
if blocked, wait := h.loginLimit.blocked(ip, body.Username); blocked {
seconds := int(wait / time.Second)
if wait%time.Second != 0 {
seconds++
}
if seconds < 1 {
seconds = 1
}
w.Header().Set("Retry-After", strconv.Itoa(seconds))
h.logAdminSession(r, body.Username, "login_blocked", ip)
writeError(w, http.StatusTooManyRequests, "too_many_requests", "登录尝试过于频繁,请稍后重试")
return
}
token, err := h.authn.Login(body.Username, body.Password)
if err != nil {
h.loginLimit.recordFailure(ip, body.Username)
h.logAdminSession(r, body.Username, "login_failure", ip)
writeError(w, http.StatusUnauthorized, "unauthorized", "用户名或密码错误")
return
}
h.loginLimit.clearIP(ip)
h.logAdminSession(r, body.Username, "login_success", ip)
writeJSON(w, http.StatusOK, map[string]string{"token": token, "username": body.Username})
}
// Logout revokes the current bearer token.
func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) {
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if token == "" {
writeError(w, http.StatusUnauthorized, "unauthorized", "令牌无效")
return
}
if err := h.authn.Revoke(token); err != nil {
writeError(w, http.StatusUnauthorized, "unauthorized", "令牌无效")
return
}
username := auth.UserFrom(r.Context())
h.logAdminSession(r, username, "logout", loginIP(r))
w.WriteHeader(http.StatusNoContent)
}
func loginIP(r *http.Request) string {
ip := realIP(r)
if host, _, err := net.SplitHostPort(ip); err == nil {
return host
}
return ip
}
func (h *Handler) logAdminSession(r *http.Request, username, action, ip string) {
if h.store == nil {
return
}
detail := map[string]any{"ip": ip, "username": username}
if err := h.store.LogAdminSession(r.Context(), username, action, detail); err != nil {
log.Printf("admin session audit write failed: %v", err)
}
}
// Me returns the current authenticated user.
func (h *Handler) Me(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"username": auth.UserFrom(r.Context())})
@@ -781,14 +883,8 @@ func (h *Handler) RejectSubmission(w http.ResponseWriter, r *http.Request) {
// ---------- helpers ----------
func realIP(r *http.Request) string {
if ip := r.Header.Get("X-Forwarded-For"); ip != "" {
if i := strings.IndexByte(ip, ','); i >= 0 {
return strings.TrimSpace(ip[:i])
}
return strings.TrimSpace(ip)
}
if ip := r.Header.Get("X-Real-IP"); ip != "" {
return ip
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
return host
}
return r.RemoteAddr
}