Spaces:
Sleeping
Sleeping
File size: 7,446 Bytes
face17f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | // Package httpapi is the transport: JSON in, JSON out, with all policy living
// in core. Every error the API can produce is renderable from apierr.
package httpapi
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"runtime/debug"
"strconv"
"strings"
"time"
"github.com/archnemix/archx-eval/relay/internal/apierr"
"github.com/archnemix/archx-eval/relay/internal/config"
"github.com/archnemix/archx-eval/relay/internal/core"
)
// Server wraps the core service with HTTP concerns.
type Server struct {
cfg config.Config
svc *core.Service
log *slog.Logger
mux *http.ServeMux
admin string
metrics string
handler http.Handler
}
// New builds a Server. The returned value implements http.Handler.
func New(cfg config.Config, svc *core.Service, log *slog.Logger, adminToken string) *Server {
s := &Server{cfg: cfg, svc: svc, log: log, admin: adminToken, metrics: cfg.MetricsToken}
mux := http.NewServeMux()
mux.HandleFunc("GET /", s.handleIndex)
mux.HandleFunc("GET /health", s.handleHealth)
mux.HandleFunc("GET /healthz", s.handleHealth)
mux.HandleFunc("GET /v1/categories", s.handleCategories)
mux.HandleFunc("POST /v1/draw", s.handleDraw)
mux.HandleFunc("POST /v1/feedback", s.handleFeedback)
mux.HandleFunc("GET /v1/stale", s.handleStale)
mux.HandleFunc("POST /v1/erase", s.handleErase)
mux.HandleFunc("GET /metrics", s.handleMetrics)
s.mux = mux
// Cross-cutting middleware is layered here, outside ServeHTTP, so the
// health probe is cheap and everything else gets the full treatment.
s.handler = s.withSecurityHeaders(s.withBodyLimit(s.withTimeout(mux)))
return s
}
// ServeHTTP applies the cross-cutting concerns in a fixed order:
// panic safety, request id, security headers, body limit, timeout, access log.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := time.Now()
reqID := r.Header.Get("X-Request-Id")
if reqID == "" {
reqID = newRequestID()
} else if len(reqID) > 64 {
// Never echo an unbounded client-supplied value back in a header.
reqID = newRequestID()
}
w.Header().Set("X-Request-Id", reqID)
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
defer func() {
if p := recover(); p != nil {
// A panic must never reach the client as a stack trace or a 200.
s.log.Error("panic recovered",
"request_id", reqID,
"path", r.URL.Path,
"panic", p,
"stack", string(debug.Stack()),
)
if !rec.wrote {
writeError(rec, apierr.Internal("unexpected server error"))
}
}
}()
s.handler.ServeHTTP(rec, r)
s.log.Info("request",
"request_id", reqID,
"method", r.Method,
"path", r.URL.Path,
"status", rec.status,
"bytes", rec.bytes,
"duration_ms", time.Since(start).Milliseconds(),
)
}
// withSecurityHeaders sets the headers that cost nothing and remove whole
// classes of client-side trickery. Deliberately minimal: this is a JSON API,
// so a strict CSP can be maximal.
func (s *Server) withSecurityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Referrer-Policy", "no-referrer")
h.Set("Cache-Control", "no-store, max-age=0")
h.Set("Pragma", "no-cache")
h.Set("Cross-Origin-Resource-Policy", "same-origin")
h.Set("Cross-Origin-Opener-Policy", "same-origin")
h.Set("Content-Security-Policy",
"default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
h.Set("Permissions-Policy",
"geolocation=(), camera=(), microphone=(), interest-cohort=()")
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
h.Set("Server", "relay")
next.ServeHTTP(w, r)
})
}
// withBodyLimit caps every request body before any handler sees it.
func (s *Server) withBodyLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Body != nil {
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxBodyBytes)
}
if ct := r.Header.Get("Content-Type"); r.Method == http.MethodPost {
if !strings.HasPrefix(strings.ToLower(ct), "application/json") {
writeError(w, apierr.BadRequest("Content-Type must be application/json"))
return
}
}
next.ServeHTTP(w, r)
})
}
// withTimeout bounds handler work. Requests that overrun are cancelled rather
// than left to hold a connection open.
func (s *Server) withTimeout(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), s.cfg.RequestTimeout)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
type statusRecorder struct {
http.ResponseWriter
status int
bytes int
wrote bool
}
func (s *statusRecorder) WriteHeader(code int) {
if !s.wrote {
s.status = code
s.wrote = true
}
s.ResponseWriter.WriteHeader(code)
}
func (s *statusRecorder) Write(b []byte) (int, error) {
s.wrote = true
n, err := s.ResponseWriter.Write(b)
s.bytes += n
return n, err
}
// writeJSON emits a success envelope.
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
// Headers are already sent; nothing useful remains to do.
_ = err
}
}
// writeError renders an apierr.Error, or a generic 500 for anything else.
func writeError(w http.ResponseWriter, err error) {
e, ok := apierr.As(err)
if !ok {
e = apierr.Internal("unexpected server error")
}
if e.RetryAfter > 0 {
secs := int(e.RetryAfter.Round(time.Second) / time.Second)
if secs < 1 {
secs = 1
}
w.Header().Set("Retry-After", strconv.Itoa(secs))
}
writeJSON(w, e.Status, map[string]any{
"error": map[string]any{
"code": e.Code,
"message": e.Message,
},
})
}
// decodeJSON reads a strict JSON body: unknown fields and trailing data are
// rejected, which stops clients from silently sending something we ignore.
func decodeJSON(r *http.Request, dst any) error {
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
var maxErr *http.MaxBytesError
if errors.As(err, &maxErr) {
return apierr.BadRequest("request body is too large")
}
return apierr.BadRequest("malformed JSON body: " + err.Error())
}
if dec.More() {
return apierr.BadRequest("body must contain exactly one JSON object")
}
return nil
}
// requireAdmin gates operational endpoints behind a shared token.
func (s *Server) requireAdmin(w http.ResponseWriter, r *http.Request) bool {
if s.admin == "" {
writeError(w, apierr.Forbidden("ADMIN_DISABLED", "operational endpoints are disabled"))
return false
}
got := r.Header.Get("Authorization")
got = strings.TrimPrefix(got, "Bearer ")
if got == "" {
got = r.Header.Get("X-Admin-Token")
}
if !constantTimeEqual(got, s.admin) {
writeError(w, apierr.Forbidden("ADMIN_DENIED", "administrative token required"))
return false
}
return true
}
func constantTimeEqual(a, b string) bool {
if len(a) != len(b) {
return false
}
var diff byte
for i := 0; i < len(a); i++ {
diff |= a[i] ^ b[i]
}
return diff == 0
}
// MetricsToken returns the configured metrics token, for the handler.
func (s *Server) metricsToken() string { return s.metrics }
|