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()) } }