// 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/ path to /api/v1/admin/. 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 }