Merge pull request 'feat(admin): 登录防暴力破解、登录审计和服务端退出 (#42)' (#52) from devin/1793407649-goods-42-admin-login-hardening into main
Merge pull request 'feat(admin): 登录防暴力破解、登录审计和服务端退出 (#42)' (#52)
This commit was merged in pull request #52.
This commit is contained in:
@@ -13,3 +13,4 @@ OPENGOODS_TRUSTED_PROXIES=
|
|||||||
GOODS_ADMIN_USER=admin
|
GOODS_ADMIN_USER=admin
|
||||||
GOODS_ADMIN_PASSWORD=change-me
|
GOODS_ADMIN_PASSWORD=change-me
|
||||||
GOODS_ADMIN_JWT_SECRET=change-me-to-a-long-random-string
|
GOODS_ADMIN_JWT_SECRET=change-me-to-a-long-random-string
|
||||||
|
GOODS_ADMIN_TOKEN_TTL=12h
|
||||||
|
|||||||
@@ -59,7 +59,8 @@ export default function App() {
|
|||||||
setView({ name: "list" });
|
setView({ name: "list" });
|
||||||
}
|
}
|
||||||
|
|
||||||
function logout() {
|
async function logout() {
|
||||||
|
await api.logout().catch(() => undefined);
|
||||||
clearToken();
|
clearToken();
|
||||||
setAuthed(false);
|
setAuthed(false);
|
||||||
setUsername("");
|
setUsername("");
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ export const api = {
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify({ username, password }),
|
body: JSON.stringify({ username, password }),
|
||||||
}),
|
}),
|
||||||
|
logout: () => request<void>("/logout", { method: "POST" }),
|
||||||
me: () => request<{ username: string }>("/me"),
|
me: () => request<{ username: string }>("/me"),
|
||||||
listProducts: (
|
listProducts: (
|
||||||
q: string,
|
q: string,
|
||||||
|
|||||||
@@ -34,6 +34,14 @@ func main() {
|
|||||||
dbURL := getenv("OPENGOODS_DATABASE_URL", "postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable")
|
dbURL := getenv("OPENGOODS_DATABASE_URL", "postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable")
|
||||||
basePath := getenv("GOODS_ADMIN_BASE_PATH", "/ping")
|
basePath := getenv("GOODS_ADMIN_BASE_PATH", "/ping")
|
||||||
username := getenv("GOODS_ADMIN_USER", "admin")
|
username := getenv("GOODS_ADMIN_USER", "admin")
|
||||||
|
tokenTTL := 12 * time.Hour
|
||||||
|
if value := os.Getenv("GOODS_ADMIN_TOKEN_TTL"); value != "" {
|
||||||
|
parsed, err := time.ParseDuration(value)
|
||||||
|
if err != nil || parsed <= 0 {
|
||||||
|
log.Fatalf("invalid GOODS_ADMIN_TOKEN_TTL %q: expected a positive duration", value)
|
||||||
|
}
|
||||||
|
tokenTTL = parsed
|
||||||
|
}
|
||||||
clientIPs, err := clientip.Parse(getenv("OPENGOODS_TRUSTED_PROXIES", ""))
|
clientIPs, err := clientip.Parse(getenv("OPENGOODS_TRUSTED_PROXIES", ""))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("invalid OPENGOODS_TRUSTED_PROXIES: %v", err)
|
log.Fatalf("invalid OPENGOODS_TRUSTED_PROXIES: %v", err)
|
||||||
@@ -75,7 +83,7 @@ func main() {
|
|||||||
log.Printf("warning: database not reachable at startup: %v", err)
|
log.Printf("warning: database not reachable at startup: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
authn := auth.New(username, passwordHash, secret, 12*time.Hour)
|
authn := auth.New(username, passwordHash, secret, tokenTTL)
|
||||||
redisURL := getenv("OPENGOODS_REDIS_URL", "redis://localhost:6379/0")
|
redisURL := getenv("OPENGOODS_REDIS_URL", "redis://localhost:6379/0")
|
||||||
usage := ratelimit.New(redisURL)
|
usage := ratelimit.New(redisURL)
|
||||||
readCache := cache.New(redisURL)
|
readCache := cache.New(redisURL)
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -31,6 +32,7 @@ type Handler struct {
|
|||||||
basePath string
|
basePath string
|
||||||
spa fs.FS
|
spa fs.FS
|
||||||
submitLimit *rateLimiter
|
submitLimit *rateLimiter
|
||||||
|
loginLimit *loginLimiter
|
||||||
usage *ratelimit.Limiter
|
usage *ratelimit.Limiter
|
||||||
cache cacheBumper
|
cache cacheBumper
|
||||||
clientIP *clientip.Resolver
|
clientIP *clientip.Resolver
|
||||||
@@ -49,6 +51,7 @@ func New(store *adminstore.Store, authn *auth.Authenticator, basePath string, sp
|
|||||||
basePath: basePath,
|
basePath: basePath,
|
||||||
spa: spa,
|
spa: spa,
|
||||||
submitLimit: newRateLimiter(5, 10*time.Minute),
|
submitLimit: newRateLimiter(5, 10*time.Minute),
|
||||||
|
loginLimit: newLoginLimiter(10, 20, 15*time.Minute),
|
||||||
clientIP: clientip.Default(),
|
clientIP: clientip.Default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -113,6 +116,7 @@ func (h *Handler) Router() http.Handler {
|
|||||||
r.Group(func(r chi.Router) {
|
r.Group(func(r chi.Router) {
|
||||||
r.Use(h.authn.Middleware)
|
r.Use(h.authn.Middleware)
|
||||||
r.Use(h.invalidateCache)
|
r.Use(h.invalidateCache)
|
||||||
|
r.Post("/api/logout", h.Logout)
|
||||||
r.Get("/api/me", h.Me)
|
r.Get("/api/me", h.Me)
|
||||||
r.Get("/api/stats", h.Stats)
|
r.Get("/api/stats", h.Stats)
|
||||||
r.Get("/api/audit", h.ListAllAudit)
|
r.Get("/api/audit", h.ListAllAudit)
|
||||||
@@ -203,14 +207,66 @@ func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, http.StatusBadRequest, "bad_request", "invalid body")
|
writeError(w, http.StatusBadRequest, "bad_request", "invalid body")
|
||||||
return
|
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)
|
token, err := h.authn.Login(body.Username, body.Password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
h.loginLimit.recordFailure(ip, body.Username)
|
||||||
|
h.logAdminSession(r, body.Username, "login_failure", ip)
|
||||||
writeError(w, http.StatusUnauthorized, "unauthorized", "用户名或密码错误")
|
writeError(w, http.StatusUnauthorized, "unauthorized", "用户名或密码错误")
|
||||||
return
|
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})
|
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.
|
// Me returns the current authenticated user.
|
||||||
func (h *Handler) Me(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) Me(w http.ResponseWriter, r *http.Request) {
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"username": auth.UserFrom(r.Context())})
|
writeJSON(w, http.StatusOK, map[string]string{"username": auth.UserFrom(r.Context())})
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package adminhandler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type loginLimiter struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
ipFailures map[string][]time.Time
|
||||||
|
usernameFailures map[string][]time.Time
|
||||||
|
ipLimit int
|
||||||
|
usernameLimit int
|
||||||
|
window time.Duration
|
||||||
|
lastPrune time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func newLoginLimiter(ipLimit, usernameLimit int, window time.Duration) *loginLimiter {
|
||||||
|
return &loginLimiter{
|
||||||
|
ipFailures: make(map[string][]time.Time),
|
||||||
|
usernameFailures: make(map[string][]time.Time),
|
||||||
|
ipLimit: ipLimit,
|
||||||
|
usernameLimit: usernameLimit,
|
||||||
|
window: window,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func loginUsernameKey(username string) string {
|
||||||
|
return strings.ToLower(strings.TrimSpace(username))
|
||||||
|
}
|
||||||
|
|
||||||
|
func pruneLoginFailures(failures []time.Time, cutoff time.Time) []time.Time {
|
||||||
|
kept := failures[:0]
|
||||||
|
for _, failure := range failures {
|
||||||
|
if failure.After(cutoff) {
|
||||||
|
kept = append(kept, failure)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return kept
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *loginLimiter) pruneExpired(now time.Time) {
|
||||||
|
if !l.lastPrune.IsZero() && now.Sub(l.lastPrune) < l.window {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cutoff := now.Add(-l.window)
|
||||||
|
for key, failures := range l.ipFailures {
|
||||||
|
kept := pruneLoginFailures(failures, cutoff)
|
||||||
|
if len(kept) == 0 {
|
||||||
|
delete(l.ipFailures, key)
|
||||||
|
} else {
|
||||||
|
l.ipFailures[key] = kept
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for key, failures := range l.usernameFailures {
|
||||||
|
kept := pruneLoginFailures(failures, cutoff)
|
||||||
|
if len(kept) == 0 {
|
||||||
|
delete(l.usernameFailures, key)
|
||||||
|
} else {
|
||||||
|
l.usernameFailures[key] = kept
|
||||||
|
}
|
||||||
|
}
|
||||||
|
l.lastPrune = now
|
||||||
|
}
|
||||||
|
|
||||||
|
func retryAfter(failures []time.Time, limit int, now time.Time, window time.Duration) time.Duration {
|
||||||
|
if len(failures) < limit || len(failures) == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
remaining := failures[0].Add(window).Sub(now)
|
||||||
|
if remaining < 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return remaining
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *loginLimiter) blocked(ip, username string) (bool, time.Duration) {
|
||||||
|
now := time.Now()
|
||||||
|
cutoff := now.Add(-l.window)
|
||||||
|
username = loginUsernameKey(username)
|
||||||
|
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
l.pruneExpired(now)
|
||||||
|
|
||||||
|
ipFailures := pruneLoginFailures(l.ipFailures[ip], cutoff)
|
||||||
|
if len(ipFailures) == 0 {
|
||||||
|
delete(l.ipFailures, ip)
|
||||||
|
} else {
|
||||||
|
l.ipFailures[ip] = ipFailures
|
||||||
|
}
|
||||||
|
userFailures := pruneLoginFailures(l.usernameFailures[username], cutoff)
|
||||||
|
if len(userFailures) == 0 {
|
||||||
|
delete(l.usernameFailures, username)
|
||||||
|
} else {
|
||||||
|
l.usernameFailures[username] = userFailures
|
||||||
|
}
|
||||||
|
|
||||||
|
ipRetry := retryAfter(ipFailures, l.ipLimit, now, l.window)
|
||||||
|
userRetry := retryAfter(userFailures, l.usernameLimit, now, l.window)
|
||||||
|
if userRetry > ipRetry {
|
||||||
|
ipRetry = userRetry
|
||||||
|
}
|
||||||
|
return ipRetry > 0, ipRetry
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *loginLimiter) recordFailure(ip, username string) {
|
||||||
|
now := time.Now()
|
||||||
|
cutoff := now.Add(-l.window)
|
||||||
|
username = loginUsernameKey(username)
|
||||||
|
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
l.pruneExpired(now)
|
||||||
|
|
||||||
|
ipFailures := pruneLoginFailures(l.ipFailures[ip], cutoff)
|
||||||
|
l.ipFailures[ip] = append(ipFailures, now)
|
||||||
|
userFailures := pruneLoginFailures(l.usernameFailures[username], cutoff)
|
||||||
|
l.usernameFailures[username] = append(userFailures, now)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *loginLimiter) clearIP(ip string) {
|
||||||
|
l.mu.Lock()
|
||||||
|
delete(l.ipFailures, ip)
|
||||||
|
l.mu.Unlock()
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
package adminhandler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/baicai2026-baicai/goods/api/internal/auth"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLoginLimiterBlocksByIPAndUsername(t *testing.T) {
|
||||||
|
limiter := newLoginLimiter(2, 3, time.Minute)
|
||||||
|
limiter.recordFailure("192.0.2.1", "Admin")
|
||||||
|
limiter.recordFailure("192.0.2.1", "admin")
|
||||||
|
|
||||||
|
blocked, retry := limiter.blocked("192.0.2.1", "admin")
|
||||||
|
if !blocked || retry <= 0 {
|
||||||
|
t.Fatalf("IP limit: blocked=%v retry=%v, want blocked with retry", blocked, retry)
|
||||||
|
}
|
||||||
|
|
||||||
|
limiter.recordFailure("192.0.2.2", "admin")
|
||||||
|
blocked, retry = limiter.blocked("192.0.2.2", "ADMIN")
|
||||||
|
if !blocked || retry <= 0 {
|
||||||
|
t.Fatalf("username limit: blocked=%v retry=%v, want blocked with retry", blocked, retry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginBlockedReturnsRetryAfterWithoutCheckingPassword(t *testing.T) {
|
||||||
|
h := New(nil, nil, "/ping", nil)
|
||||||
|
h.loginLimit = newLoginLimiter(1, 1, 2*time.Second)
|
||||||
|
h.loginLimit.recordFailure("192.0.2.10", "admin")
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/ping/api/login", strings.NewReader(
|
||||||
|
`{"username":"admin","password":"irrelevant"}`,
|
||||||
|
))
|
||||||
|
req.RemoteAddr = "192.0.2.10:1234"
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
h.Login(recorder, req)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusTooManyRequests)
|
||||||
|
}
|
||||||
|
if retryAfter := recorder.Header().Get("Retry-After"); retryAfter != "2" && retryAfter != "1" {
|
||||||
|
t.Fatalf("Retry-After = %q, want 1 or 2 seconds", retryAfter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginFailureRecordsIPAndUsername(t *testing.T) {
|
||||||
|
passwordHash, err := bcrypt.GenerateFromPassword([]byte("s3cret"), bcrypt.MinCost)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("hash password: %v", err)
|
||||||
|
}
|
||||||
|
h := New(nil, auth.New("admin", passwordHash, []byte("secret"), time.Hour), "/ping", nil)
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/ping/api/login", strings.NewReader(
|
||||||
|
`{"username":"admin","password":"wrong"}`,
|
||||||
|
))
|
||||||
|
req.RemoteAddr = "192.0.2.15:1234"
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
h.Login(recorder, req)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusUnauthorized)
|
||||||
|
}
|
||||||
|
if got := len(h.loginLimit.ipFailures["192.0.2.15"]); got != 1 {
|
||||||
|
t.Fatalf("IP failure count = %d, want 1", got)
|
||||||
|
}
|
||||||
|
if got := len(h.loginLimit.usernameFailures["admin"]); got != 1 {
|
||||||
|
t.Fatalf("username failure count = %d, want 1", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginSuccessClearsIPFailures(t *testing.T) {
|
||||||
|
passwordHash, err := bcrypt.GenerateFromPassword([]byte("s3cret"), bcrypt.MinCost)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("hash password: %v", err)
|
||||||
|
}
|
||||||
|
h := New(nil, auth.New("admin", passwordHash, []byte("secret"), time.Hour), "/ping", nil)
|
||||||
|
h.loginLimit.recordFailure("192.0.2.20", "admin")
|
||||||
|
h.loginLimit.recordFailure("192.0.2.20", "admin")
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/ping/api/login", strings.NewReader(
|
||||||
|
`{"username":"admin","password":"s3cret"}`,
|
||||||
|
))
|
||||||
|
req.RemoteAddr = "192.0.2.20:1234"
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
h.Login(recorder, req)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d, want %d: %s", recorder.Code, http.StatusOK, recorder.Body.String())
|
||||||
|
}
|
||||||
|
if blocked, _ := h.loginLimit.blocked("192.0.2.20", "admin"); blocked {
|
||||||
|
t.Fatal("successful login did not clear IP failures")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginLimiterRecoversAfterWindow(t *testing.T) {
|
||||||
|
limiter := newLoginLimiter(1, 1, 20*time.Millisecond)
|
||||||
|
limiter.recordFailure("192.0.2.30", "admin")
|
||||||
|
if blocked, _ := limiter.blocked("192.0.2.30", "admin"); !blocked {
|
||||||
|
t.Fatal("expected login to be blocked before window expires")
|
||||||
|
}
|
||||||
|
|
||||||
|
time.Sleep(30 * time.Millisecond)
|
||||||
|
if blocked, _ := limiter.blocked("192.0.2.30", "admin"); blocked {
|
||||||
|
t.Fatal("login remained blocked after window expired")
|
||||||
|
}
|
||||||
|
|
||||||
|
limiter.mu.Lock()
|
||||||
|
defer limiter.mu.Unlock()
|
||||||
|
if len(limiter.ipFailures) != 0 || len(limiter.usernameFailures) != 0 {
|
||||||
|
t.Fatalf("expired entries remain: ip=%d username=%d",
|
||||||
|
len(limiter.ipFailures), len(limiter.usernameFailures))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogoutRevokesCurrentToken(t *testing.T) {
|
||||||
|
passwordHash, err := bcrypt.GenerateFromPassword([]byte("s3cret"), bcrypt.MinCost)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("hash password: %v", err)
|
||||||
|
}
|
||||||
|
authn := auth.New("admin", passwordHash, []byte("secret"), time.Hour)
|
||||||
|
token, err := authn.Login("admin", "s3cret")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("login: %v", err)
|
||||||
|
}
|
||||||
|
h := New(nil, authn, "/ping", nil)
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/ping/api/logout", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
h.Router().ServeHTTP(recorder, req)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusNoContent {
|
||||||
|
t.Fatalf("logout status = %d, want %d", recorder.Code, http.StatusNoContent)
|
||||||
|
}
|
||||||
|
if _, err := authn.Verify(token); err == nil {
|
||||||
|
t.Fatal("logout did not revoke token")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -327,6 +327,11 @@ VALUES ($1,$2,$3,$4,$5,$6,$7)`, actor, action, entity, entityID, fields, bj, aj)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LogAdminSession records an admin authentication event without an entity ID.
|
||||||
|
func (s *Store) LogAdminSession(ctx context.Context, actor, action string, detail map[string]any) error {
|
||||||
|
return s.writeAudit(ctx, actor, action, "admin_session", nil, nil, nil, detail)
|
||||||
|
}
|
||||||
|
|
||||||
// ---------- images ----------
|
// ---------- images ----------
|
||||||
|
|
||||||
// AddImage inserts an image URL (manual source) and recomputes quality.
|
// AddImage inserts an image URL (manual source) and recomputes quality.
|
||||||
|
|||||||
@@ -6,12 +6,15 @@ package auth
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/hmac"
|
"crypto/hmac"
|
||||||
|
"crypto/rand"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
@@ -23,11 +26,16 @@ type Authenticator struct {
|
|||||||
passwordHash []byte
|
passwordHash []byte
|
||||||
secret []byte
|
secret []byte
|
||||||
ttl time.Duration
|
ttl time.Duration
|
||||||
|
mu sync.RWMutex
|
||||||
|
revoked map[string]int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// New builds an Authenticator. passwordHash must be a bcrypt hash.
|
// New builds an Authenticator. passwordHash must be a bcrypt hash.
|
||||||
func New(username string, passwordHash, secret []byte, ttl time.Duration) *Authenticator {
|
func New(username string, passwordHash, secret []byte, ttl time.Duration) *Authenticator {
|
||||||
return &Authenticator{username: username, passwordHash: passwordHash, secret: secret, ttl: ttl}
|
return &Authenticator{
|
||||||
|
username: username, passwordHash: passwordHash, secret: secret, ttl: ttl,
|
||||||
|
revoked: make(map[string]int64),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ErrInvalidCredentials is returned when login fails.
|
// ErrInvalidCredentials is returned when login fails.
|
||||||
@@ -49,6 +57,7 @@ func (a *Authenticator) Login(username, password string) (string, error) {
|
|||||||
type claims struct {
|
type claims struct {
|
||||||
Sub string `json:"sub"`
|
Sub string `json:"sub"`
|
||||||
Exp int64 `json:"exp"`
|
Exp int64 `json:"exp"`
|
||||||
|
JTI string `json:"jti"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func b64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }
|
func b64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }
|
||||||
@@ -61,7 +70,15 @@ func (a *Authenticator) sign(signingInput string) string {
|
|||||||
|
|
||||||
func (a *Authenticator) issue(sub string) (string, error) {
|
func (a *Authenticator) issue(sub string) (string, error) {
|
||||||
header := b64([]byte(`{"alg":"HS256","typ":"JWT"}`))
|
header := b64([]byte(`{"alg":"HS256","typ":"JWT"}`))
|
||||||
payloadJSON, err := json.Marshal(claims{Sub: sub, Exp: time.Now().Add(a.ttl).Unix()})
|
randomID := make([]byte, 16)
|
||||||
|
if _, err := rand.Read(randomID); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
payloadJSON, err := json.Marshal(claims{
|
||||||
|
Sub: sub,
|
||||||
|
Exp: time.Now().Add(a.ttl).Unix(),
|
||||||
|
JTI: hex.EncodeToString(randomID),
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@@ -70,30 +87,65 @@ func (a *Authenticator) issue(sub string) (string, error) {
|
|||||||
return signingInput + "." + a.sign(signingInput), nil
|
return signingInput + "." + a.sign(signingInput), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify checks a token's signature and expiry, returning the subject.
|
func (a *Authenticator) verifyClaims(token string) (claims, error) {
|
||||||
func (a *Authenticator) Verify(token string) (string, error) {
|
|
||||||
parts := strings.Split(token, ".")
|
parts := strings.Split(token, ".")
|
||||||
if len(parts) != 3 {
|
if len(parts) != 3 {
|
||||||
return "", errors.New("malformed token")
|
return claims{}, errors.New("malformed token")
|
||||||
}
|
}
|
||||||
signingInput := parts[0] + "." + parts[1]
|
signingInput := parts[0] + "." + parts[1]
|
||||||
if !hmac.Equal([]byte(a.sign(signingInput)), []byte(parts[2])) {
|
if !hmac.Equal([]byte(a.sign(signingInput)), []byte(parts[2])) {
|
||||||
return "", errors.New("bad signature")
|
return claims{}, errors.New("bad signature")
|
||||||
}
|
}
|
||||||
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
|
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return claims{}, err
|
||||||
}
|
}
|
||||||
var c claims
|
var c claims
|
||||||
if err := json.Unmarshal(payload, &c); err != nil {
|
if err := json.Unmarshal(payload, &c); err != nil {
|
||||||
return "", err
|
return claims{}, err
|
||||||
}
|
}
|
||||||
if time.Now().Unix() >= c.Exp {
|
if time.Now().Unix() >= c.Exp {
|
||||||
return "", errors.New("token expired")
|
return claims{}, errors.New("token expired")
|
||||||
|
}
|
||||||
|
if c.JTI == "" {
|
||||||
|
return claims{}, errors.New("token missing jti")
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify checks a token's signature, expiry, and revocation status.
|
||||||
|
func (a *Authenticator) Verify(token string) (string, error) {
|
||||||
|
c, err := a.verifyClaims(token)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
a.mu.RLock()
|
||||||
|
exp, revoked := a.revoked[c.JTI]
|
||||||
|
a.mu.RUnlock()
|
||||||
|
if revoked && time.Now().Unix() < exp {
|
||||||
|
return "", errors.New("token revoked")
|
||||||
}
|
}
|
||||||
return c.Sub, nil
|
return c.Sub, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Revoke verifies a token and records its identifier until it expires.
|
||||||
|
func (a *Authenticator) Revoke(token string) error {
|
||||||
|
c, err := a.verifyClaims(token)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
now := time.Now().Unix()
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
for jti, exp := range a.revoked {
|
||||||
|
if exp <= now {
|
||||||
|
delete(a.revoked, jti)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a.revoked[c.JTI] = c.Exp
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
type ctxKey int
|
type ctxKey int
|
||||||
|
|
||||||
const userKey ctxKey = 0
|
const userKey ctxKey = 0
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -60,3 +66,87 @@ func TestVerifyRejectsExpired(t *testing.T) {
|
|||||||
t.Fatal("expected expired token error")
|
t.Fatal("expected expired token error")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIssuedTokensHaveUniqueRandomJTI(t *testing.T) {
|
||||||
|
a := newTestAuth(t, time.Hour)
|
||||||
|
first, err := a.Login("admin", "s3cret")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("first login: %v", err)
|
||||||
|
}
|
||||||
|
second, err := a.Login("admin", "s3cret")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("second login: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
readJTI := func(token string) string {
|
||||||
|
t.Helper()
|
||||||
|
parts := strings.Split(token, ".")
|
||||||
|
if len(parts) != 3 {
|
||||||
|
t.Fatalf("token has %d parts, want 3", len(parts))
|
||||||
|
}
|
||||||
|
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("decode payload: %v", err)
|
||||||
|
}
|
||||||
|
var c claims
|
||||||
|
if err := json.Unmarshal(payload, &c); err != nil {
|
||||||
|
t.Fatalf("unmarshal claims: %v", err)
|
||||||
|
}
|
||||||
|
randomID, err := hex.DecodeString(c.JTI)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("decode jti: %v", err)
|
||||||
|
}
|
||||||
|
if len(randomID) != 16 {
|
||||||
|
t.Fatalf("jti length = %d bytes, want 16", len(randomID))
|
||||||
|
}
|
||||||
|
return c.JTI
|
||||||
|
}
|
||||||
|
|
||||||
|
if firstID, secondID := readJTI(first), readJTI(second); firstID == secondID {
|
||||||
|
t.Fatal("issued tokens have the same jti")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRevokeRejectsTokenInVerifyAndMiddleware(t *testing.T) {
|
||||||
|
a := newTestAuth(t, time.Hour)
|
||||||
|
token, err := a.Login("admin", "s3cret")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("login: %v", err)
|
||||||
|
}
|
||||||
|
if err := a.Revoke(token); err != nil {
|
||||||
|
t.Fatalf("revoke: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := a.Verify(token); err == nil {
|
||||||
|
t.Fatal("Verify accepted revoked token")
|
||||||
|
}
|
||||||
|
|
||||||
|
nextCalled := false
|
||||||
|
handler := a.Middleware(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||||
|
nextCalled = true
|
||||||
|
}))
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, req)
|
||||||
|
if recorder.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusUnauthorized)
|
||||||
|
}
|
||||||
|
if nextCalled {
|
||||||
|
t.Fatal("middleware called next for revoked token")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRevokePrunesExpiredEntries(t *testing.T) {
|
||||||
|
a := newTestAuth(t, time.Hour)
|
||||||
|
a.revoked["expired"] = time.Now().Add(-time.Minute).Unix()
|
||||||
|
token, err := a.Login("admin", "s3cret")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("login: %v", err)
|
||||||
|
}
|
||||||
|
if err := a.Revoke(token); err != nil {
|
||||||
|
t.Fatalf("revoke: %v", err)
|
||||||
|
}
|
||||||
|
if _, ok := a.revoked["expired"]; ok {
|
||||||
|
t.Fatal("Revoke retained an expired revocation")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+1
-1
@@ -53,6 +53,6 @@ location /api/public/ {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
后台凭据见 `.env` 的 `GOODS_ADMIN_USER` / `GOODS_ADMIN_PASSWORD` / `GOODS_ADMIN_JWT_SECRET`。新增迁移 `0005_admin`(`audit_log` 表 + `manual` 来源)随 `migrate ... up` 自动应用。
|
后台凭据见 `.env` 的 `GOODS_ADMIN_USER` / `GOODS_ADMIN_PASSWORD` / `GOODS_ADMIN_JWT_SECRET`;令牌有效期可通过 `GOODS_ADMIN_TOKEN_TTL` 设置(Go duration 格式,默认 `12h`)。登录失败按 IP(15 分钟 10 次)和用户名(15 分钟 20 次)限流,并将成功、失败和被限流的登录写入审计日志。退出会在当前进程内吊销令牌;服务重启后进程内吊销记录会丢失。若配置了持久的 `GOODS_ADMIN_JWT_SECRET`,未过期令牌仍有效至其过期;若未配置,服务每次启动会生成随机密钥,令牌会在重启后失效。新增迁移 `0005_admin`(`audit_log` 表 + `manual` 来源)随 `migrate ... up` 自动应用。
|
||||||
|
|
||||||
`OPENGOODS_TRUSTED_PROXIES` 用逗号分隔的 CIDR 或 IP 配置可信代理;留空时信任 loopback、私有 IPv4 与唯一本地 IPv6 网段,设置为 `none` 则不信任任何代理。Nginx 配置应保留上述反代头。
|
`OPENGOODS_TRUSTED_PROXIES` 用逗号分隔的 CIDR 或 IP 配置可信代理;留空时信任 loopback、私有 IPv4 与唯一本地 IPv6 网段,设置为 `none` 则不信任任何代理。Nginx 配置应保留上述反代头。
|
||||||
|
|||||||
Reference in New Issue
Block a user