feat(admin-console): Stage 1 — pipe + skeleton behind the gateway
Tests · Go / test (push) Successful in 2m0s
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.
This commit is contained in:
@@ -178,6 +178,30 @@ bootstrap or asset traffic through a pluggable public handler or proxy.
|
||||
That traffic belongs to dedicated public route classes and must not share rate
|
||||
limit buckets or abuse counters with the public auth API.
|
||||
|
||||
### Operator Console Proxy (`/_gm`)
|
||||
|
||||
The gateway also fronts the backend operator console. The edge Caddy routes
|
||||
`/_gm` and `/_gm/*` to this public listener; the gateway classifies that
|
||||
traffic as the `admin` public route class and reverse-proxies it to the
|
||||
backend at `GATEWAY_BACKEND_HTTP_URL`, preserving the request path and the
|
||||
inbound `Host` header (so the backend's same-origin CSRF check observes the
|
||||
public host).
|
||||
|
||||
Authentication is delegated entirely to the backend (HTTP Basic Auth against
|
||||
`admin_accounts`): the backend's `401` challenge is relayed unchanged so the
|
||||
browser shows its native credential dialog. The gateway contributes only the
|
||||
edge anti-abuse layer — a per-IP rate limit, a body size limit, and a
|
||||
`GET`/`HEAD`/`POST` method allow-list for the class — and answers
|
||||
`502 bad_gateway` when the backend is unreachable.
|
||||
|
||||
The `admin` class carries its own budgets, isolated from the other public
|
||||
classes:
|
||||
|
||||
- `GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_ADMIN_MAX_BODY_BYTES` (default `65536`);
|
||||
- `GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_ADMIN_RATE_LIMIT_REQUESTS` (default `120`);
|
||||
- `GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_ADMIN_RATE_LIMIT_WINDOW` (default `1m`);
|
||||
- `GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_ADMIN_RATE_LIMIT_BURST` (default `40`).
|
||||
|
||||
### Operational Admin Surface
|
||||
|
||||
The gateway may expose one private operational HTTP listener used for metrics.
|
||||
|
||||
@@ -78,6 +78,15 @@ func run(ctx context.Context) (err error) {
|
||||
AuthService: authServiceAdapter{rest: backend.REST()},
|
||||
}
|
||||
|
||||
adminConsoleProxy, err := restapi.NewBackendConsoleProxy(cfg.Backend.HTTPBaseURL, logger)
|
||||
if err != nil {
|
||||
_ = backend.Close()
|
||||
_ = telemetryRuntime.Shutdown(context.Background())
|
||||
_ = logging.Sync(logger)
|
||||
return fmt.Errorf("build admin console proxy: %w", err)
|
||||
}
|
||||
publicRESTDeps.AdminConsoleProxy = adminConsoleProxy
|
||||
|
||||
grpcDeps, components, cleanup, err := newAuthenticatedGRPCDependencies(ctx, cfg, logger, telemetryRuntime, backend)
|
||||
if err != nil {
|
||||
_ = backend.Close()
|
||||
|
||||
@@ -276,6 +276,22 @@ const (
|
||||
// configures the public_misc rate-limit burst.
|
||||
publicMiscRateLimitBurstEnvVar = "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_PUBLIC_MISC_RATE_LIMIT_BURST"
|
||||
|
||||
// adminMaxBodyBytesEnvVar names the environment variable that configures
|
||||
// the maximum accepted request body size for the admin console class.
|
||||
adminMaxBodyBytesEnvVar = "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_ADMIN_MAX_BODY_BYTES"
|
||||
|
||||
// adminRateLimitRequestsEnvVar names the environment variable that
|
||||
// configures the admin console request budget per window.
|
||||
adminRateLimitRequestsEnvVar = "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_ADMIN_RATE_LIMIT_REQUESTS"
|
||||
|
||||
// adminRateLimitWindowEnvVar names the environment variable that configures
|
||||
// the admin console rate-limit window.
|
||||
adminRateLimitWindowEnvVar = "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_ADMIN_RATE_LIMIT_WINDOW"
|
||||
|
||||
// adminRateLimitBurstEnvVar names the environment variable that configures
|
||||
// the admin console rate-limit burst.
|
||||
adminRateLimitBurstEnvVar = "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_ADMIN_RATE_LIMIT_BURST"
|
||||
|
||||
// sendEmailCodeIdentityRateLimitRequestsEnvVar names the environment
|
||||
// variable that configures the send-email-code identity request budget per
|
||||
// window.
|
||||
@@ -372,6 +388,14 @@ const (
|
||||
defaultPublicMiscRateLimitRequests = 30
|
||||
defaultPublicMiscRateLimitBurst = 10
|
||||
|
||||
// Admin console class: sized for a human operator clicking through pages
|
||||
// and submitting forms, while still throttling Basic Auth brute-force at
|
||||
// the edge. The body budget accommodates form posts.
|
||||
defaultAdminMaxBodyBytes = int64(65536)
|
||||
|
||||
defaultAdminRateLimitRequests = 120
|
||||
defaultAdminRateLimitBurst = 40
|
||||
|
||||
defaultSendEmailCodeIdentityRateLimitRequests = 3
|
||||
defaultSendEmailCodeIdentityRateLimitBurst = 1
|
||||
|
||||
@@ -439,6 +463,11 @@ type PublicHTTPAntiAbuseConfig struct {
|
||||
// PublicMisc applies to the stable public_misc route class.
|
||||
PublicMisc PublicRoutePolicyConfig
|
||||
|
||||
// Admin applies to the stable admin route class — the `/_gm` operator
|
||||
// console reverse-proxied to the backend. Only per-IP limiting applies;
|
||||
// the class carries no identity buckets.
|
||||
Admin PublicRoutePolicyConfig
|
||||
|
||||
// SendEmailCodeIdentity applies the additional identity limiter for
|
||||
// send-email-code.
|
||||
SendEmailCodeIdentity PublicAuthIdentityPolicyConfig
|
||||
@@ -708,6 +737,14 @@ func DefaultPublicHTTPConfig() PublicHTTPConfig {
|
||||
Burst: defaultPublicMiscRateLimitBurst,
|
||||
},
|
||||
},
|
||||
Admin: PublicRoutePolicyConfig{
|
||||
MaxBodyBytes: defaultAdminMaxBodyBytes,
|
||||
RateLimit: PublicRateLimitConfig{
|
||||
Requests: defaultAdminRateLimitRequests,
|
||||
Window: defaultClassRateLimitWindow,
|
||||
Burst: defaultAdminRateLimitBurst,
|
||||
},
|
||||
},
|
||||
SendEmailCodeIdentity: PublicAuthIdentityPolicyConfig{
|
||||
RateLimit: PublicRateLimitConfig{
|
||||
Requests: defaultSendEmailCodeIdentityRateLimitRequests,
|
||||
@@ -1092,6 +1129,18 @@ func LoadFromEnv() (Config, error) {
|
||||
}
|
||||
cfg.PublicHTTP.AntiAbuse.PublicMisc = publicMiscPolicy
|
||||
|
||||
adminPolicy, err := loadPublicRoutePolicyConfigFromEnv(
|
||||
cfg.PublicHTTP.AntiAbuse.Admin,
|
||||
adminMaxBodyBytesEnvVar,
|
||||
adminRateLimitRequestsEnvVar,
|
||||
adminRateLimitWindowEnvVar,
|
||||
adminRateLimitBurstEnvVar,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
cfg.PublicHTTP.AntiAbuse.Admin = adminPolicy
|
||||
|
||||
sendIdentityPolicy, err := loadPublicAuthIdentityPolicyConfigFromEnv(
|
||||
cfg.PublicHTTP.AntiAbuse.SendEmailCodeIdentity,
|
||||
sendEmailCodeIdentityRateLimitRequestsEnvVar,
|
||||
@@ -1247,6 +1296,9 @@ func LoadFromEnv() (Config, error) {
|
||||
if err := validatePublicRoutePolicyConfig(cfg.PublicHTTP.AntiAbuse.PublicMisc, publicMiscMaxBodyBytesEnvVar, publicMiscRateLimitRequestsEnvVar, publicMiscRateLimitWindowEnvVar, publicMiscRateLimitBurstEnvVar); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if err := validatePublicRoutePolicyConfig(cfg.PublicHTTP.AntiAbuse.Admin, adminMaxBodyBytesEnvVar, adminRateLimitRequestsEnvVar, adminRateLimitWindowEnvVar, adminRateLimitBurstEnvVar); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if err := validatePublicAuthIdentityPolicyConfig(cfg.PublicHTTP.AntiAbuse.SendEmailCodeIdentity, sendEmailCodeIdentityRateLimitRequestsEnvVar, sendEmailCodeIdentityRateLimitWindowEnvVar, sendEmailCodeIdentityRateLimitBurstEnvVar); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package restapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// NewBackendConsoleProxy builds the reverse proxy that forwards operator
|
||||
// console traffic (`/_gm` and `/_gm/*`) to the backend at backendBaseURL.
|
||||
//
|
||||
// The proxy is intentionally thin: it preserves the inbound request path and
|
||||
// the inbound Host header — the latter so the backend's same-origin CSRF check
|
||||
// observes the public host rather than the internal upstream — and relays the
|
||||
// backend response unchanged, including its 401 Basic Auth challenge. It
|
||||
// answers 502 when the backend is unreachable. Authentication, rendering, and
|
||||
// every state change live in the backend; the gateway contributes only the
|
||||
// public anti-abuse layer that runs ahead of this handler.
|
||||
func NewBackendConsoleProxy(backendBaseURL string, logger *zap.Logger) (http.Handler, error) {
|
||||
target, err := url.Parse(backendBaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse backend base URL %q: %w", backendBaseURL, err)
|
||||
}
|
||||
if target.Scheme == "" || target.Host == "" {
|
||||
return nil, fmt.Errorf("backend base URL %q must be absolute", backendBaseURL)
|
||||
}
|
||||
|
||||
if logger == nil {
|
||||
logger = zap.NewNop()
|
||||
}
|
||||
logger = logger.Named("admin_console_proxy")
|
||||
|
||||
return &httputil.ReverseProxy{
|
||||
Rewrite: func(pr *httputil.ProxyRequest) {
|
||||
pr.SetURL(target)
|
||||
// SetURL clears Out.Host so the target host is used; restore the
|
||||
// inbound Host so the backend sees the public origin.
|
||||
pr.Out.Host = pr.In.Host
|
||||
},
|
||||
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
logger.Warn("admin console upstream error",
|
||||
zap.String("path", r.URL.Path), zap.Error(err))
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
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)
|
||||
}
|
||||
@@ -234,6 +234,8 @@ func publicRoutePolicyForClass(policy config.PublicHTTPAntiAbuseConfig, class Pu
|
||||
return policy.BrowserBootstrap
|
||||
case PublicRouteClassBrowserAsset:
|
||||
return policy.BrowserAsset
|
||||
case PublicRouteClassAdmin:
|
||||
return policy.Admin
|
||||
default:
|
||||
return policy.PublicMisc
|
||||
}
|
||||
@@ -252,6 +254,8 @@ func publicAuthIdentityPolicyForPath(requestPath string, policy config.PublicHTT
|
||||
|
||||
func allowedMethodsForRequestShape(r *http.Request) []string {
|
||||
switch {
|
||||
case isAdminConsolePath(r.URL.Path):
|
||||
return []string{http.MethodGet, http.MethodHead, http.MethodPost}
|
||||
case isPublicAuthPath(r.URL.Path):
|
||||
return []string{http.MethodPost}
|
||||
case isProbePath(r.URL.Path):
|
||||
@@ -284,6 +288,17 @@ func isPublicAuthPath(requestPath string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// isAdminConsoleRequest reports whether r targets the operator console surface.
|
||||
func isAdminConsoleRequest(r *http.Request) bool {
|
||||
return isAdminConsolePath(r.URL.Path)
|
||||
}
|
||||
|
||||
// isAdminConsolePath reports whether requestPath is the admin console root
|
||||
// (`/_gm`) or any path beneath it (`/_gm/...`).
|
||||
func isAdminConsolePath(requestPath string) bool {
|
||||
return requestPath == "/_gm" || strings.HasPrefix(requestPath, "/_gm/")
|
||||
}
|
||||
|
||||
func isProbePath(requestPath string) bool {
|
||||
switch requestPath {
|
||||
case "/healthz", "/readyz":
|
||||
|
||||
@@ -48,6 +48,10 @@ const (
|
||||
// PublicRouteClassPublicMisc identifies public traffic that does not match a
|
||||
// more specific class.
|
||||
PublicRouteClassPublicMisc PublicRouteClass = "public_misc"
|
||||
|
||||
// PublicRouteClassAdmin identifies operator console traffic reverse-proxied
|
||||
// to the backend under the `/_gm` prefix.
|
||||
PublicRouteClassAdmin PublicRouteClass = "admin"
|
||||
)
|
||||
|
||||
var configureGinModeOnce sync.Once
|
||||
@@ -60,6 +64,7 @@ func (c PublicRouteClass) Normalized() PublicRouteClass {
|
||||
case PublicRouteClassPublicAuth,
|
||||
PublicRouteClassBrowserBootstrap,
|
||||
PublicRouteClassBrowserAsset,
|
||||
PublicRouteClassAdmin,
|
||||
PublicRouteClassPublicMisc:
|
||||
return c
|
||||
default:
|
||||
@@ -110,6 +115,14 @@ type ServerDependencies struct {
|
||||
// Telemetry records low-cardinality edge metrics. When nil, metrics are
|
||||
// disabled.
|
||||
Telemetry *telemetry.Runtime
|
||||
|
||||
// AdminConsoleProxy, when non-nil, handles `/_gm` and `/_gm/*` by
|
||||
// reverse-proxying to the backend operator console after the public
|
||||
// anti-abuse layer (per-IP rate limit, body, and method checks for the
|
||||
// admin route class) has run. Authentication is delegated to the
|
||||
// backend's admin Basic Auth, whose 401 challenge passes straight back
|
||||
// to the browser. When nil, the admin console surface is not mounted.
|
||||
AdminConsoleProxy http.Handler
|
||||
}
|
||||
|
||||
// Server owns the public unauthenticated REST listener exposed by the gateway.
|
||||
@@ -229,6 +242,8 @@ type defaultPublicTrafficClassifier struct{}
|
||||
// later drive anti-abuse policy and rate limiting.
|
||||
func (defaultPublicTrafficClassifier) Classify(r *http.Request) PublicRouteClass {
|
||||
switch {
|
||||
case isAdminConsoleRequest(r):
|
||||
return PublicRouteClassAdmin
|
||||
case isPublicAuthRequest(r):
|
||||
return PublicRouteClassPublicAuth
|
||||
case isBrowserBootstrapRequest(r):
|
||||
@@ -290,6 +305,12 @@ func newPublicHandlerWithConfig(cfg config.PublicHTTPConfig, deps ServerDependen
|
||||
router.POST("/api/v1/public/auth/send-email-code", handleSendEmailCode(deps.AuthService, cfg.AuthUpstreamTimeout))
|
||||
router.POST("/api/v1/public/auth/confirm-email-code", handleConfirmEmailCode(deps.AuthService, cfg.AuthUpstreamTimeout))
|
||||
|
||||
if deps.AdminConsoleProxy != nil {
|
||||
adminConsole := gin.WrapH(deps.AdminConsoleProxy)
|
||||
router.Any("/_gm", adminConsole)
|
||||
router.Any("/_gm/*proxyPath", adminConsole)
|
||||
}
|
||||
|
||||
router.NoMethod(func(c *gin.Context) {
|
||||
allowMethods := allowedMethodsForPath(c.Request.URL.Path)
|
||||
if allowMethods != "" {
|
||||
|
||||
@@ -169,6 +169,31 @@ func TestDefaultPublicTrafficClassifier(t *testing.T) {
|
||||
accept: "text/html",
|
||||
wantClass: PublicRouteClassBrowserBootstrap,
|
||||
},
|
||||
{
|
||||
name: "admin console root",
|
||||
method: http.MethodGet,
|
||||
target: "/_gm",
|
||||
wantClass: PublicRouteClassAdmin,
|
||||
},
|
||||
{
|
||||
name: "admin console page wins over browser accept header",
|
||||
method: http.MethodGet,
|
||||
target: "/_gm/users",
|
||||
accept: "text/html",
|
||||
wantClass: PublicRouteClassAdmin,
|
||||
},
|
||||
{
|
||||
name: "admin console asset wins over browser asset shape",
|
||||
method: http.MethodGet,
|
||||
target: "/_gm/assets/console.css",
|
||||
wantClass: PublicRouteClassAdmin,
|
||||
},
|
||||
{
|
||||
name: "admin console form post",
|
||||
method: http.MethodPost,
|
||||
target: "/_gm/users/123/sanctions",
|
||||
wantClass: PublicRouteClassAdmin,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -215,6 +240,11 @@ func TestPublicRouteClassNormalized(t *testing.T) {
|
||||
input: PublicRouteClassPublicMisc,
|
||||
want: PublicRouteClassPublicMisc,
|
||||
},
|
||||
{
|
||||
name: "admin",
|
||||
input: PublicRouteClassAdmin,
|
||||
want: PublicRouteClassAdmin,
|
||||
},
|
||||
{
|
||||
name: "unknown collapses to misc",
|
||||
input: PublicRouteClass("unexpected"),
|
||||
|
||||
Reference in New Issue
Block a user