Merge remote-tracking branch 'origin/main' into devin/1793408183-goods-47-admin-api-tests
This commit is contained in:
@@ -21,7 +21,7 @@ type apiKeyView struct {
|
||||
// ListAPIKeys returns all issued keys with usage stats merged in.
|
||||
func (h *Handler) ListAPIKeys(w http.ResponseWriter, r *http.Request) {
|
||||
keys, err := h.store.ListAPIKeys(r.Context())
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
views := make([]apiKeyView, 0, len(keys))
|
||||
@@ -51,7 +51,7 @@ func (h *Handler) CreateAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
plaintext, row, err := h.store.CreateAPIKey(r.Context(), in, auth.UserFrom(r.Context()))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
@@ -63,7 +63,7 @@ func (h *Handler) CreateAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// RevokeAPIKey disables a key. Subsequent requests with it are rejected.
|
||||
func (h *Handler) RevokeAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
if err := h.store.RevokeAPIKey(r.Context(), chi.URLParam(r, "id")); h.handleErr(w, err) {
|
||||
if err := h.store.RevokeAPIKey(r.Context(), chi.URLParam(r, "id")); h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "revoked"})
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package adminhandler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
|
||||
"github.com/baicai2026-baicai/goods/api/internal/ratelimit"
|
||||
)
|
||||
|
||||
type fakeUsageLimiter struct {
|
||||
result ratelimit.Result
|
||||
key string
|
||||
limit int
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
func (f *fakeUsageLimiter) Allow(_ context.Context, key string, limit int, window time.Duration) ratelimit.Result {
|
||||
f.key = key
|
||||
f.limit = limit
|
||||
f.window = window
|
||||
return f.result
|
||||
}
|
||||
|
||||
func (*fakeUsageLimiter) Usage(context.Context, string) ratelimit.UsageStat {
|
||||
return ratelimit.UsageStat{}
|
||||
}
|
||||
|
||||
func TestBackflowRateLimitReturnsRetryAfter(t *testing.T) {
|
||||
usage := &fakeUsageLimiter{
|
||||
result: ratelimit.Result{
|
||||
Allowed: false,
|
||||
ResetUnix: time.Now().Add(2 * time.Minute).Unix(),
|
||||
},
|
||||
}
|
||||
h := New(nil, nil, "/ping", nil)
|
||||
h.usage = usage
|
||||
h.WithBackflowRate(7)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/public/backflow", nil)
|
||||
if h.allowBackflow(recorder, req, "key-id") {
|
||||
t.Fatal("allowBackflow returned true for a denied request")
|
||||
}
|
||||
if recorder.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusTooManyRequests)
|
||||
}
|
||||
retryAfter, err := strconv.Atoi(recorder.Header().Get("Retry-After"))
|
||||
if err != nil || retryAfter <= 0 {
|
||||
t.Fatalf("Retry-After = %q, want positive integer", recorder.Header().Get("Retry-After"))
|
||||
}
|
||||
if usage.key != "backflow:key-id" || usage.limit != 7 || usage.window != time.Hour {
|
||||
t.Fatalf("Allow called with key=%q limit=%d window=%v", usage.key, usage.limit, usage.window)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInternalErrorDoesNotExposeDetailsAndLogsRequestID(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
previousOutput := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
t.Cleanup(func() { log.SetOutput(previousOutput) })
|
||||
|
||||
h := New(nil, nil, "/ping", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/ping/api/products", nil)
|
||||
req.Header.Set(middleware.RequestIDHeader, "request-123")
|
||||
handler := middleware.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h.handleErr(w, r, errors.New("sensitive database detail"))
|
||||
}))
|
||||
handler.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusInternalServerError)
|
||||
}
|
||||
if strings.Contains(recorder.Body.String(), "sensitive database detail") {
|
||||
t.Fatalf("response exposed internal error: %s", recorder.Body.String())
|
||||
}
|
||||
if !strings.Contains(recorder.Body.String(), "服务器内部错误") || !strings.Contains(recorder.Body.String(), "internal_error") {
|
||||
t.Fatalf("response missing generic internal error: %s", recorder.Body.String())
|
||||
}
|
||||
if !strings.Contains(logs.String(), "sensitive database detail") || !strings.Contains(logs.String(), "request-123") {
|
||||
t.Fatalf("log missing error or request ID: %s", logs.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package adminhandler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeCacheBumper struct {
|
||||
calls int
|
||||
err error
|
||||
contexts []context.Context
|
||||
}
|
||||
|
||||
func (f *fakeCacheBumper) Bump(ctx context.Context) error {
|
||||
f.calls++
|
||||
f.contexts = append(f.contexts, ctx)
|
||||
return f.err
|
||||
}
|
||||
|
||||
func TestInvalidateCache(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
status int
|
||||
write bool
|
||||
want int
|
||||
}{
|
||||
{name: "successful write", method: http.MethodPost, status: http.StatusCreated, write: true, want: 1},
|
||||
{name: "implicit success", method: http.MethodPost, status: http.StatusOK, want: 1},
|
||||
{name: "client error", method: http.MethodPost, status: http.StatusBadRequest, write: true},
|
||||
{name: "server error", method: http.MethodPost, status: http.StatusInternalServerError, write: true},
|
||||
{name: "get", method: http.MethodGet, status: http.StatusCreated, write: true},
|
||||
{name: "head", method: http.MethodHead, status: http.StatusCreated, write: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
bumper := &fakeCacheBumper{}
|
||||
h := New(nil, nil, "/ping", nil).WithCache(bumper)
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if tt.write {
|
||||
w.WriteHeader(tt.status)
|
||||
}
|
||||
})
|
||||
handler := h.invalidateCache(next)
|
||||
req := httptest.NewRequest(tt.method, "/", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, req)
|
||||
if bumper.calls != tt.want {
|
||||
t.Fatalf("Bump calls = %d, want %d", bumper.calls, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidateCacheDoesNotFailResponseAndUsesUncancelledContext(t *testing.T) {
|
||||
bumper := &fakeCacheBumper{err: errors.New("redis unavailable")}
|
||||
h := New(nil, nil, "/ping", nil).WithCache(bumper)
|
||||
handler := h.invalidateCache(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}))
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
req := httptest.NewRequest(http.MethodPost, "/", nil).WithContext(ctx)
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusCreated {
|
||||
t.Fatalf("response status = %d, want %d", recorder.Code, http.StatusCreated)
|
||||
}
|
||||
if bumper.calls != 1 {
|
||||
t.Fatalf("Bump calls = %d, want 1", bumper.calls)
|
||||
}
|
||||
select {
|
||||
case <-bumper.contexts[0].Done():
|
||||
t.Fatal("Bump context was canceled")
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,14 @@
|
||||
package adminhandler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -16,29 +20,46 @@ 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"
|
||||
)
|
||||
|
||||
// Handler holds the admin dependencies.
|
||||
type Handler struct {
|
||||
store *adminstore.Store
|
||||
authn *auth.Authenticator
|
||||
basePath string
|
||||
spa fs.FS
|
||||
submitLimit *rateLimiter
|
||||
usage *ratelimit.Limiter
|
||||
store *adminstore.Store
|
||||
authn *auth.Authenticator
|
||||
basePath string
|
||||
spa fs.FS
|
||||
submitLimit *rateLimiter
|
||||
loginLimit *loginLimiter
|
||||
usage usageLimiter
|
||||
backflowRate int
|
||||
cache cacheBumper
|
||||
clientIP *clientip.Resolver
|
||||
}
|
||||
|
||||
type usageLimiter interface {
|
||||
Allow(context.Context, string, int, time.Duration) ratelimit.Result
|
||||
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, "/")
|
||||
return &Handler{
|
||||
store: store,
|
||||
authn: authn,
|
||||
basePath: basePath,
|
||||
spa: spa,
|
||||
submitLimit: newRateLimiter(5, 10*time.Minute),
|
||||
store: store,
|
||||
authn: authn,
|
||||
basePath: basePath,
|
||||
spa: spa,
|
||||
submitLimit: newRateLimiter(5, 10*time.Minute),
|
||||
loginLimit: newLoginLimiter(10, 20, 15*time.Minute),
|
||||
backflowRate: 30,
|
||||
clientIP: clientip.Default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,11 +70,54 @@ func (h *Handler) WithUsage(l *ratelimit.Limiter) *Handler {
|
||||
return h
|
||||
}
|
||||
|
||||
// WithBackflowRate configures the per-key hourly backflow request limit.
|
||||
func (h *Handler) WithBackflowRate(n int) *Handler {
|
||||
h.backflowRate = n
|
||||
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) {
|
||||
@@ -64,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)
|
||||
@@ -154,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())})
|
||||
@@ -176,7 +294,7 @@ func (h *Handler) ListProducts(w http.ResponseWriter, r *http.Request) {
|
||||
order := r.URL.Query().Get("order")
|
||||
page, size := pageParams(r)
|
||||
items, total, err := h.store.ListProducts(r.Context(), q, sort, order, size, (page-1)*size)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
@@ -188,7 +306,7 @@ func (h *Handler) ListProducts(w http.ResponseWriter, r *http.Request) {
|
||||
// GetProduct returns full editable detail.
|
||||
func (h *Handler) GetProduct(w http.ResponseWriter, r *http.Request) {
|
||||
d, err := h.store.GetProduct(r.Context(), chi.URLParam(r, "id"))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, d)
|
||||
@@ -211,7 +329,7 @@ func (h *Handler) CreateProduct(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusConflict, "duplicate_gtin", "该条码(GTIN)已被其它商品使用")
|
||||
return
|
||||
}
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, d)
|
||||
@@ -220,7 +338,7 @@ func (h *Handler) CreateProduct(w http.ResponseWriter, r *http.Request) {
|
||||
// Stats returns the dashboard overview counters.
|
||||
func (h *Handler) Stats(w http.ResponseWriter, r *http.Request) {
|
||||
st, err := h.store.Stats(r.Context())
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
@@ -230,7 +348,7 @@ func (h *Handler) Stats(w http.ResponseWriter, r *http.Request) {
|
||||
func (h *Handler) ListAllAudit(w http.ResponseWriter, r *http.Request) {
|
||||
page, size := pageParams(r)
|
||||
items, total, err := h.store.ListAllAudit(r.Context(), size, (page-1)*size)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
@@ -281,7 +399,7 @@ func (h *Handler) BulkProducts(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "未选择任何商品")
|
||||
return
|
||||
}
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"status": "ok", "affected": affected})
|
||||
@@ -299,7 +417,7 @@ func (h *Handler) UpdateProduct(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
d, err := h.store.UpdateProduct(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, d)
|
||||
@@ -308,7 +426,7 @@ func (h *Handler) UpdateProduct(w http.ResponseWriter, r *http.Request) {
|
||||
// ListAudit returns audit history for a product.
|
||||
func (h *Handler) ListAudit(w http.ResponseWriter, r *http.Request) {
|
||||
items, err := h.store.ListAudit(r.Context(), chi.URLParam(r, "id"), 100)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
@@ -325,7 +443,7 @@ func (h *Handler) AddImage(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
im, err := h.store.AddImage(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), body.URL, body.Kind)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, im)
|
||||
@@ -334,7 +452,7 @@ func (h *Handler) AddImage(w http.ResponseWriter, r *http.Request) {
|
||||
// DeleteImage removes an image.
|
||||
func (h *Handler) DeleteImage(w http.ResponseWriter, r *http.Request) {
|
||||
err := h.store.DeleteImage(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "imageID"), auth.UserFrom(r.Context()))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||
@@ -348,7 +466,7 @@ func (h *Handler) AddMSRP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
m, err := h.store.AddMSRP(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, m)
|
||||
@@ -357,7 +475,7 @@ func (h *Handler) AddMSRP(w http.ResponseWriter, r *http.Request) {
|
||||
// DeleteMSRP removes an MSRP snapshot.
|
||||
func (h *Handler) DeleteMSRP(w http.ResponseWriter, r *http.Request) {
|
||||
err := h.store.DeleteMSRP(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "msrpID"), auth.UserFrom(r.Context()))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||
@@ -375,7 +493,7 @@ func (h *Handler) AddBarcode(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
b, err := h.store.AddBarcode(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
||||
if h.handleBarcodeErr(w, err) {
|
||||
if h.handleBarcodeErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, b)
|
||||
@@ -384,7 +502,7 @@ func (h *Handler) AddBarcode(w http.ResponseWriter, r *http.Request) {
|
||||
// DeleteBarcode removes a barcode; a primary one is replaced automatically.
|
||||
func (h *Handler) DeleteBarcode(w http.ResponseWriter, r *http.Request) {
|
||||
err := h.store.DeleteBarcode(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "barcodeID"), auth.UserFrom(r.Context()))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||
@@ -393,7 +511,7 @@ func (h *Handler) DeleteBarcode(w http.ResponseWriter, r *http.Request) {
|
||||
// SetPrimaryBarcode marks one barcode primary and mirrors it to product.gtin.
|
||||
func (h *Handler) SetPrimaryBarcode(w http.ResponseWriter, r *http.Request) {
|
||||
b, err := h.store.SetPrimaryBarcode(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "barcodeID"), auth.UserFrom(r.Context()))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, b)
|
||||
@@ -401,7 +519,7 @@ func (h *Handler) SetPrimaryBarcode(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// handleBarcodeErr maps barcode-specific errors (GTIN validation, ownership
|
||||
// conflict) to client-facing statuses, falling back to handleErr otherwise.
|
||||
func (h *Handler) handleBarcodeErr(w http.ResponseWriter, err error) bool {
|
||||
func (h *Handler) handleBarcodeErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
@@ -422,13 +540,13 @@ func (h *Handler) handleBarcodeErr(w http.ResponseWriter, err error) bool {
|
||||
writeError(w, http.StatusBadRequest, "invalid_gtin", err.Error())
|
||||
return true
|
||||
}
|
||||
return h.handleErr(w, err)
|
||||
return h.handleErr(w, r, err)
|
||||
}
|
||||
|
||||
// ListBrands returns brand options.
|
||||
func (h *Handler) ListBrands(w http.ResponseWriter, r *http.Request) {
|
||||
items, err := h.store.ListBrands(r.Context())
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
@@ -442,7 +560,7 @@ func (h *Handler) ListKindFields(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
items, err := h.store.ListKindFields(r.Context(), kind)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items, "kind": kind})
|
||||
@@ -451,7 +569,7 @@ func (h *Handler) ListKindFields(w http.ResponseWriter, r *http.Request) {
|
||||
// ListCategories returns category options.
|
||||
func (h *Handler) ListCategories(w http.ResponseWriter, r *http.Request) {
|
||||
items, err := h.store.ListCategories(r.Context())
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
@@ -469,7 +587,7 @@ func (h *Handler) CreateCategory(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
c, err := h.store.CreateCategory(r.Context(), auth.UserFrom(r.Context()), in)
|
||||
if h.handleCategoryErr(w, err) {
|
||||
if h.handleCategoryErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, c)
|
||||
@@ -487,7 +605,7 @@ func (h *Handler) UpdateCategory(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
c, err := h.store.UpdateCategory(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
||||
if h.handleCategoryErr(w, err) {
|
||||
if h.handleCategoryErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, c)
|
||||
@@ -496,7 +614,7 @@ func (h *Handler) UpdateCategory(w http.ResponseWriter, r *http.Request) {
|
||||
// DeleteCategory removes a leaf category that no product uses.
|
||||
func (h *Handler) DeleteCategory(w http.ResponseWriter, r *http.Request) {
|
||||
err := h.store.DeleteCategory(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
|
||||
if h.handleCategoryErr(w, err) {
|
||||
if h.handleCategoryErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||
@@ -504,7 +622,7 @@ func (h *Handler) DeleteCategory(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// handleCategoryErr maps category-specific errors to client statuses, falling
|
||||
// back to handleErr otherwise.
|
||||
func (h *Handler) handleCategoryErr(w http.ResponseWriter, err error) bool {
|
||||
func (h *Handler) handleCategoryErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
@@ -522,7 +640,7 @@ func (h *Handler) handleCategoryErr(w http.ResponseWriter, err error) bool {
|
||||
writeError(w, http.StatusBadRequest, "invalid_parent", "上级分类无效(不存在或不能移动到自身/子级下)")
|
||||
return true
|
||||
}
|
||||
return h.handleErr(w, err)
|
||||
return h.handleErr(w, r, err)
|
||||
}
|
||||
|
||||
type brandInput struct {
|
||||
@@ -545,7 +663,7 @@ func (h *Handler) CreateBrand(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
b, err := h.store.CreateBrand(r.Context(), auth.UserFrom(r.Context()), in.Name)
|
||||
if h.handleBrandErr(w, err) {
|
||||
if h.handleBrandErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, b)
|
||||
@@ -563,7 +681,7 @@ func (h *Handler) UpdateBrand(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
b, err := h.store.UpdateBrand(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in.Name)
|
||||
if h.handleBrandErr(w, err) {
|
||||
if h.handleBrandErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, b)
|
||||
@@ -581,7 +699,7 @@ func (h *Handler) MergeBrands(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
b, err := h.store.MergeBrands(r.Context(), chi.URLParam(r, "id"), in.TargetID, auth.UserFrom(r.Context()))
|
||||
if h.handleBrandErr(w, err) {
|
||||
if h.handleBrandErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, b)
|
||||
@@ -590,14 +708,14 @@ func (h *Handler) MergeBrands(w http.ResponseWriter, r *http.Request) {
|
||||
// DeleteBrand removes a brand no product references.
|
||||
func (h *Handler) DeleteBrand(w http.ResponseWriter, r *http.Request) {
|
||||
err := h.store.DeleteBrand(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
|
||||
if h.handleBrandErr(w, err) {
|
||||
if h.handleBrandErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||
}
|
||||
|
||||
// handleBrandErr maps brand-specific errors to client statuses.
|
||||
func (h *Handler) handleBrandErr(w http.ResponseWriter, err error) bool {
|
||||
func (h *Handler) handleBrandErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
@@ -612,7 +730,7 @@ func (h *Handler) handleBrandErr(w http.ResponseWriter, err error) bool {
|
||||
writeError(w, http.StatusBadRequest, "invalid_merge", "合并目标无效(不存在或与源品牌相同)")
|
||||
return true
|
||||
}
|
||||
return h.handleErr(w, err)
|
||||
return h.handleErr(w, r, err)
|
||||
}
|
||||
|
||||
// ---------- submissions ----------
|
||||
@@ -634,7 +752,7 @@ func (h *Handler) CreateSubmission(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
id, err := h.store.CreateSubmission(r.Context(), in, realIP(r))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
|
||||
internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"id": id, "status": "pending"})
|
||||
@@ -653,12 +771,16 @@ func (h *Handler) Backflow(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusUnauthorized, "invalid_api_key", "API key 格式无效")
|
||||
return
|
||||
}
|
||||
if _, err := h.store.APIKeyByHash(r.Context(), apikey.Hash(raw)); err != nil {
|
||||
key, err := h.store.APIKeyByHash(r.Context(), apikey.Hash(raw))
|
||||
if err != nil {
|
||||
if errors.Is(err, adminstore.ErrNotFound) {
|
||||
writeError(w, http.StatusUnauthorized, "invalid_api_key", "API key 无效或已吊销")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
|
||||
internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
if !h.allowBackflow(w, r, key.ID) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -679,12 +801,29 @@ func (h *Handler) Backflow(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
sum, err := h.store.CreateBackflowSubmissions(r.Context(), items, realIP(r))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
|
||||
internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, sum)
|
||||
}
|
||||
|
||||
func (h *Handler) allowBackflow(w http.ResponseWriter, r *http.Request, keyID string) bool {
|
||||
if h.usage == nil {
|
||||
return true
|
||||
}
|
||||
res := h.usage.Allow(r.Context(), "backflow:"+keyID, h.backflowRate, time.Hour)
|
||||
if res.Allowed {
|
||||
return true
|
||||
}
|
||||
retryAfter := res.ResetUnix - time.Now().Unix()
|
||||
if retryAfter < 1 {
|
||||
retryAfter = 1
|
||||
}
|
||||
w.Header().Set("Retry-After", strconv.FormatInt(retryAfter, 10))
|
||||
writeError(w, http.StatusTooManyRequests, "rate_limited", "回流请求超过每小时限制")
|
||||
return false
|
||||
}
|
||||
|
||||
// presentedAPIKey extracts a public API key from X-API-Key or a Bearer token.
|
||||
func presentedAPIKey(r *http.Request) string {
|
||||
if v := strings.TrimSpace(r.Header.Get("X-API-Key")); v != "" {
|
||||
@@ -701,7 +840,7 @@ func (h *Handler) ListSubmissions(w http.ResponseWriter, r *http.Request) {
|
||||
status := r.URL.Query().Get("status")
|
||||
page, size := pageParams(r)
|
||||
items, total, err := h.store.ListSubmissions(r.Context(), status, size, (page-1)*size)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
pending, _ := h.store.PendingSubmissionCount(r.Context())
|
||||
@@ -713,7 +852,7 @@ func (h *Handler) ListSubmissions(w http.ResponseWriter, r *http.Request) {
|
||||
// GetSubmission returns full submission detail (admin).
|
||||
func (h *Handler) GetSubmission(w http.ResponseWriter, r *http.Request) {
|
||||
d, err := h.store.GetSubmission(r.Context(), chi.URLParam(r, "id"))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, d)
|
||||
@@ -722,7 +861,7 @@ func (h *Handler) GetSubmission(w http.ResponseWriter, r *http.Request) {
|
||||
// ApproveSubmission applies a contribution to the product store (admin).
|
||||
func (h *Handler) ApproveSubmission(w http.ResponseWriter, r *http.Request) {
|
||||
d, err := h.store.ApproveSubmission(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, d)
|
||||
@@ -735,7 +874,7 @@ func (h *Handler) RejectSubmission(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
err := h.store.RejectSubmission(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), body.Note)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "rejected"})
|
||||
@@ -744,19 +883,18 @@ 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
|
||||
}
|
||||
|
||||
func (h *Handler) handleErr(w http.ResponseWriter, err error) bool {
|
||||
func internalError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
log.Printf("adminhandler: internal error request_id=%s: %v", middleware.GetReqID(r.Context()), err)
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "服务器内部错误")
|
||||
}
|
||||
|
||||
func (h *Handler) handleErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
@@ -768,7 +906,7 @@ func (h *Handler) handleErr(w http.ResponseWriter, err error) bool {
|
||||
writeError(w, http.StatusConflict, "conflict", "该投稿已被处理")
|
||||
return true
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
|
||||
internalError(w, r, err)
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ func (h *Handler) ImportBypos(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
result, err := h.store.ImportByposRecords(r.Context(), records)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "import_error", err.Error())
|
||||
internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user