27916bbe61
Tests · Go / test (push) Successful in 2m0s
Add the server-rendered operator console at /_gm, exposed publicly through the gateway behind the existing admin_accounts Basic Auth. Backend: - new internal/adminconsole package (html/template Renderer, stateless HMAC CSRF signer, embedded stylesheet) - /_gm route group reusing basicauth.Middleware(admin.Service) + a CSRF guard (per-operator token + same-origin check); dashboard landing page - BACKEND_ADMIN_CONSOLE_CSRF_KEY config (per-process random fallback) Gateway: - new "admin" public route class (per-IP rate limit, body + GET/HEAD/POST method limits) classifying /_gm traffic - reverse proxy to the backend /_gm surface, preserving Host and relaying the backend 401 Basic Auth challenge; 502 when the backend is unreachable - GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_ADMIN_* config dev-deploy: - Caddy routes /_gm/* to the gateway - bootstrap admin + stable CSRF key; enable Prometheus /metrics exporters on backend and gateway (forward-compat for a future Prometheus/Grafana stack) Docs: ARCHITECTURE 14.1/16, FUNCTIONAL 10.2.1 (+ru mirror), backend and gateway READMEs, new backend/docs/admin-console.md. Tests: renderer + CSRF unit tests; backend router auth/render/asset/CSRF; gateway classifier, proxy forwarding/Host/401/405/413/429/502.
199 lines
7.3 KiB
Go
199 lines
7.3 KiB
Go
package restapi
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"galaxy/gateway/internal/config"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
// proxyRequest builds a test request whose context carries a cancellation
|
|
// signal. A real http.Server always supplies one; httptest.NewRequest does not,
|
|
// and without it httputil.ReverseProxy falls back to the legacy CloseNotifier
|
|
// path, which panics under gin's ResponseWriter wrapping an
|
|
// httptest.ResponseRecorder. Cancelling at test cleanup keeps the context live
|
|
// for the synchronous ServeHTTP call.
|
|
func proxyRequest(t *testing.T, method, target string, body io.Reader) *http.Request {
|
|
t.Helper()
|
|
req := httptest.NewRequest(method, target, body)
|
|
ctx, cancel := context.WithCancel(req.Context())
|
|
t.Cleanup(cancel)
|
|
return req.WithContext(ctx)
|
|
}
|
|
|
|
func TestAdminConsoleProxyForwardsToBackend(t *testing.T) {
|
|
var gotPath, gotHost, gotAuth string
|
|
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
gotPath = r.URL.Path
|
|
gotHost = r.Host
|
|
gotAuth = r.Header.Get("Authorization")
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
_, _ = w.Write([]byte("<h1>Dashboard</h1>"))
|
|
}))
|
|
defer backend.Close()
|
|
|
|
proxy, err := NewBackendConsoleProxy(backend.URL, nil)
|
|
require.NoError(t, err)
|
|
handler := newPublicHandlerWithConfig(config.DefaultPublicHTTPConfig(), ServerDependencies{AdminConsoleProxy: proxy})
|
|
|
|
req := proxyRequest(t, http.MethodGet, "http://galaxy.lan/_gm/", nil)
|
|
req.SetBasicAuth("ops", "secret")
|
|
rec := httptest.NewRecorder()
|
|
handler.ServeHTTP(rec, req)
|
|
|
|
require.Equal(t, http.StatusOK, rec.Code)
|
|
assert.Contains(t, rec.Body.String(), "Dashboard")
|
|
assert.Equal(t, "/_gm/", gotPath)
|
|
assert.Equal(t, "galaxy.lan", gotHost, "inbound Host must be preserved for same-origin CSRF checks")
|
|
assert.True(t, strings.HasPrefix(gotAuth, "Basic "), "Authorization header must be forwarded to the backend")
|
|
}
|
|
|
|
func TestAdminConsoleProxyForwardsFormPost(t *testing.T) {
|
|
var gotPath, gotBody, gotContentType string
|
|
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
gotPath = r.URL.Path
|
|
gotContentType = r.Header.Get("Content-Type")
|
|
body, _ := io.ReadAll(r.Body)
|
|
gotBody = string(body)
|
|
w.WriteHeader(http.StatusSeeOther)
|
|
}))
|
|
defer backend.Close()
|
|
|
|
proxy, err := NewBackendConsoleProxy(backend.URL, nil)
|
|
require.NoError(t, err)
|
|
handler := newPublicHandlerWithConfig(config.DefaultPublicHTTPConfig(), ServerDependencies{AdminConsoleProxy: proxy})
|
|
|
|
const form = "_csrf=token&reason=spam"
|
|
req := proxyRequest(t, http.MethodPost, "http://galaxy.lan/_gm/users/1/sanctions", strings.NewReader(form))
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
req.SetBasicAuth("ops", "secret")
|
|
rec := httptest.NewRecorder()
|
|
handler.ServeHTTP(rec, req)
|
|
|
|
require.Equal(t, http.StatusSeeOther, rec.Code)
|
|
assert.Equal(t, "/_gm/users/1/sanctions", gotPath)
|
|
assert.Equal(t, form, gotBody, "request body must reach the backend intact through the anti-abuse buffer")
|
|
assert.Contains(t, gotContentType, "x-www-form-urlencoded")
|
|
}
|
|
|
|
func TestAdminConsoleProxyRelaysAuthChallenge(t *testing.T) {
|
|
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="galaxy-admin"`)
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
}))
|
|
defer backend.Close()
|
|
|
|
proxy, err := NewBackendConsoleProxy(backend.URL, nil)
|
|
require.NoError(t, err)
|
|
handler := newPublicHandlerWithConfig(config.DefaultPublicHTTPConfig(), ServerDependencies{AdminConsoleProxy: proxy})
|
|
|
|
req := proxyRequest(t, http.MethodGet, "http://galaxy.lan/_gm/", nil)
|
|
rec := httptest.NewRecorder()
|
|
handler.ServeHTTP(rec, req)
|
|
|
|
require.Equal(t, http.StatusUnauthorized, rec.Code)
|
|
assert.Contains(t, rec.Header().Get("WWW-Authenticate"), "Basic")
|
|
}
|
|
|
|
func TestAdminConsoleProxyRejectsDisallowedMethod(t *testing.T) {
|
|
var hits int32
|
|
backend := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
|
atomic.AddInt32(&hits, 1)
|
|
}))
|
|
defer backend.Close()
|
|
|
|
proxy, err := NewBackendConsoleProxy(backend.URL, nil)
|
|
require.NoError(t, err)
|
|
handler := newPublicHandlerWithConfig(config.DefaultPublicHTTPConfig(), ServerDependencies{AdminConsoleProxy: proxy})
|
|
|
|
req := proxyRequest(t, http.MethodDelete, "http://galaxy.lan/_gm/users/1", nil)
|
|
rec := httptest.NewRecorder()
|
|
handler.ServeHTTP(rec, req)
|
|
|
|
assert.Equal(t, http.StatusMethodNotAllowed, rec.Code)
|
|
assert.Equal(t, int32(0), atomic.LoadInt32(&hits), "backend must not be reached for a rejected method")
|
|
}
|
|
|
|
func TestAdminConsoleProxyRejectsOversizedBody(t *testing.T) {
|
|
backend := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
|
defer backend.Close()
|
|
|
|
proxy, err := NewBackendConsoleProxy(backend.URL, nil)
|
|
require.NoError(t, err)
|
|
cfg := config.DefaultPublicHTTPConfig()
|
|
cfg.AntiAbuse.Admin.MaxBodyBytes = 8
|
|
handler := newPublicHandlerWithConfig(cfg, ServerDependencies{AdminConsoleProxy: proxy})
|
|
|
|
req := proxyRequest(t, http.MethodPost, "http://galaxy.lan/_gm/users/1/sanctions",
|
|
strings.NewReader("this body is well beyond eight bytes"))
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
rec := httptest.NewRecorder()
|
|
handler.ServeHTTP(rec, req)
|
|
|
|
assert.Equal(t, http.StatusRequestEntityTooLarge, rec.Code)
|
|
}
|
|
|
|
func TestAdminConsoleProxyRateLimitsPerIP(t *testing.T) {
|
|
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
}))
|
|
defer backend.Close()
|
|
|
|
proxy, err := NewBackendConsoleProxy(backend.URL, nil)
|
|
require.NoError(t, err)
|
|
cfg := config.DefaultPublicHTTPConfig()
|
|
cfg.AntiAbuse.Admin.RateLimit = config.PublicRateLimitConfig{Requests: 1, Window: time.Minute, Burst: 1}
|
|
handler := newPublicHandlerWithConfig(cfg, ServerDependencies{AdminConsoleProxy: proxy})
|
|
|
|
do := func() int {
|
|
req := proxyRequest(t, http.MethodGet, "http://galaxy.lan/_gm/", nil)
|
|
req.RemoteAddr = "203.0.113.7:5555"
|
|
rec := httptest.NewRecorder()
|
|
handler.ServeHTTP(rec, req)
|
|
return rec.Code
|
|
}
|
|
|
|
assert.Equal(t, http.StatusOK, do(), "first request within budget")
|
|
assert.Equal(t, http.StatusTooManyRequests, do(), "second request exhausts the per-IP admin budget")
|
|
}
|
|
|
|
func TestAdminConsoleProxyReturns502WhenBackendUnreachable(t *testing.T) {
|
|
backend := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
|
backendURL := backend.URL
|
|
backend.Close() // close immediately so the next dial is refused
|
|
|
|
proxy, err := NewBackendConsoleProxy(backendURL, nil)
|
|
require.NoError(t, err)
|
|
handler := newPublicHandlerWithConfig(config.DefaultPublicHTTPConfig(), ServerDependencies{AdminConsoleProxy: proxy})
|
|
|
|
req := proxyRequest(t, http.MethodGet, "http://galaxy.lan/_gm/", nil)
|
|
rec := httptest.NewRecorder()
|
|
handler.ServeHTTP(rec, req)
|
|
|
|
assert.Equal(t, http.StatusBadGateway, rec.Code)
|
|
}
|
|
|
|
func TestAdminConsoleNotMountedWhenProxyNil(t *testing.T) {
|
|
handler := newPublicHandler(ServerDependencies{})
|
|
|
|
req := proxyRequest(t, http.MethodGet, "http://galaxy.lan/_gm/", nil)
|
|
rec := httptest.NewRecorder()
|
|
handler.ServeHTTP(rec, req)
|
|
|
|
assert.Equal(t, http.StatusNotFound, rec.Code)
|
|
}
|
|
|
|
func TestNewBackendConsoleProxyRejectsRelativeURL(t *testing.T) {
|
|
_, err := NewBackendConsoleProxy("/not-absolute", nil)
|
|
assert.Error(t, err)
|
|
}
|