Stage 6: gateway edge (Connect/FlatBuffers over h2c, platform/email/guest auth, sessions, rate-limit, admin passthrough, live push bridge)
New public ingress and the first network edge. Framework + a vertical slice of operations end-to-end; remaining ops reuse the same transcode pattern in Stage 7. Contracts (new module scrabble/pkg): - push.proto (backend->gateway gRPC server-stream) + scrabble.fbs (FlatBuffers edge payloads), committed generated Go; buf/flatc Makefiles (dev-time codegen). Backend: - REST handlers on the /api/v1 groups: internal session endpoints (telegram/guest/email login -> mint, resolve, revoke) and the user slice (profile, submit_play, state, lobby enqueue/poll, chat). - internal/notify in-process Publisher hub + internal/pushgrpc gRPC server (BACKEND_GRPC_ADDR) streaming your_turn/opponent_moved/chat/nudge/match_found; emission in game.commit, social, matchmaker. - migration 00005 accounts.is_guest; guests are durable rows excluded from stats; ProvisionGuest; email-as-login (RequestLoginCode/LoginWithCode). Gateway (new module scrabble/gateway): - Connect Gateway service over h2c (Execute + Subscribe), FlatBuffers<->JSON transcode registry, Telegram initData HMAC validator (seam), session cache, token-bucket rate limiter (3 classes), push fan-out hub, backend REST + push gRPC client, admin Basic-Auth reverse proxy. go.work: use ./pkg, ./gateway + replace scrabble/pkg. CI: gateway/**, pkg/** path filters; unit build/vet/test span all three modules. Docs (PLAN, ARCHITECTURE, FUNCTIONAL+ru, TESTING, READMEs) updated; gateway/pkg unit tests + guest/email-login integration tests.
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
// Package admin is the gateway's admin surface: HTTP Basic-Auth in front of a
|
||||
// reverse proxy to the backend admin API (docs/ARCHITECTURE.md §12). The gateway
|
||||
// validates the operator credential and forwards authenticated requests to
|
||||
// backend /api/v1/admin/*; the backend trusts the gateway on this segment. The
|
||||
// admin API itself is filled in Stage 9.
|
||||
package admin
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// backendAdminPrefix is where the backend mounts its admin API.
|
||||
const backendAdminPrefix = "/api/v1/admin"
|
||||
|
||||
// NewProxy returns a handler that checks Basic-Auth against user/password and
|
||||
// reverse-proxies the request to the backend admin API, mapping an inbound
|
||||
// /admin/<rest> path to <backendURL>/api/v1/admin/<rest>.
|
||||
func NewProxy(backendURL, user, password string, log *zap.Logger) (http.Handler, error) {
|
||||
target, err := url.Parse(backendURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("admin: parse backend url %q: %w", backendURL, err)
|
||||
}
|
||||
if log == nil {
|
||||
log = zap.NewNop()
|
||||
}
|
||||
proxy := &httputil.ReverseProxy{
|
||||
Rewrite: func(pr *httputil.ProxyRequest) {
|
||||
pr.SetURL(target)
|
||||
rel := strings.TrimPrefix(pr.In.URL.Path, "/admin")
|
||||
pr.Out.URL.Path = backendAdminPrefix + rel
|
||||
pr.Out.Host = pr.In.Host
|
||||
},
|
||||
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
log.Warn("admin proxy upstream error", zap.String("path", r.URL.Path), zap.Error(err))
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
},
|
||||
}
|
||||
return basicAuth(user, password, proxy), nil
|
||||
}
|
||||
|
||||
// basicAuth wraps next with a constant-time Basic-Auth check.
|
||||
func basicAuth(user, password string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
u, p, ok := r.BasicAuth()
|
||||
if !ok || !equal(u, user) || !equal(p, password) {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="scrabble-admin"`)
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// equal compares two strings in constant time.
|
||||
func equal(a, b string) bool {
|
||||
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user