package admin_test import ( "io" "net/http" "net/http/httptest" "testing" "scrabble/gateway/internal/admin" ) func newAdmin(t *testing.T) (*httptest.Server, func()) { t.Helper() backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/api/v1/admin/ping" { t.Errorf("backend path = %q, want /api/v1/admin/ping", r.URL.Path) } _, _ = w.Write([]byte("pong")) })) proxy, err := admin.NewProxy(backend.URL, "ops", "secret", nil) if err != nil { t.Fatalf("new proxy: %v", err) } front := httptest.NewServer(proxy) return front, func() { front.Close(); backend.Close() } } func TestAdminRejectsMissingCredentials(t *testing.T) { front, cleanup := newAdmin(t) defer cleanup() resp, err := http.Get(front.URL + "/admin/ping") if err != nil { t.Fatal(err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusUnauthorized { t.Fatalf("status = %d, want 401", resp.StatusCode) } } func TestAdminProxiesWithCredentials(t *testing.T) { front, cleanup := newAdmin(t) defer cleanup() req, _ := http.NewRequest(http.MethodGet, front.URL+"/admin/ping", nil) req.SetBasicAuth("ops", "secret") resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer func() { _ = resp.Body.Close() }() body, _ := io.ReadAll(resp.Body) if resp.StatusCode != http.StatusOK || string(body) != "pong" { t.Fatalf("status = %d body = %q, want 200 pong", resp.StatusCode, body) } } func TestAdminRejectsWrongPassword(t *testing.T) { front, cleanup := newAdmin(t) defer cleanup() req, _ := http.NewRequest(http.MethodGet, front.URL+"/admin/ping", nil) req.SetBasicAuth("ops", "wrong") resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusUnauthorized { t.Fatalf("status = %d, want 401", resp.StatusCode) } }