Files
scrabble-game/gateway/internal/admin/admin.go
T
Ilia Denisov 7a48327ab6
Tests · Go / test (push) Successful in 7s
Tests · Integration / integration (push) Successful in 12s
Tests · UI / test (push) Failing after 51m19s
Stage 7 (wip): docs bake + stage renumber (insert UI Stage 8, shift +1)
- PLAN.md: new Stage 8 (UI social/account/history); Telegram->9, Admin->10, Linking->11, Polish->12; tracker + Stage 7 refinements; split the Stage 6 'wired in Stage 7' note between 7 and 8
- ARCHITECTURE: promote ui to current (slice scope, board-replay, codegen, theming, mock)
- FUNCTIONAL(+ru): client-app section with the Stage 7/8 split
- README + ui/README + CLAUDE.md: UI build/run/test, codegen, pnpm notes
- bumped Stage 8-11 refs (+1) across docs and code comments
2026-06-03 01:01:58 +02:00

65 lines
2.1 KiB
Go

// 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 10.
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
}