Added the HTTP server and serve command, with proxy, CSRF, TLS and security header config; wsserve is now ws serve, alongside a new ws dial
The serve command runs internal/server: the API under /api (health, and the CSRF token endpoint) and the WebSocket hub under /ws, over HTTP or TLS, with an optional HTTP to HTTPS redirect, the PROXY protocol from trusted sources and a graceful shutdown that closes WebSockets first. Its middleware covers the client IP behind trusted proxies, request IDs, request logging, panic recovery, global and API rate limits, Host and body size checks, security response headers, compression, CSRF protection (cross-origin checks and signed double-submit tokens) and JSON-only API bodies. Middleware that logs takes a WithLogger option. New server config sections: proxy, csrf, tls, headers and frontend (not used yet), plus max_header_bytes, max_body_bytes, global and API rate limits and HTTP read, write and idle timeouts. Every setting documents what 0 or empty means, and internal/config/README.md is reorganised by section. server.timeouts.read_header must be greater than 0, and a header or idle timeout of 0 means no limit rather than the read timeout. WebSocket upgrades are protected by the Origin check: the server's own origin, or one of csrf.cross_origin_protection.trusted_origins, which the hub now takes with WithTrustedOrigins. wsserve becomes "ws serve". "ws dial" opens a WebSocket on /ws to test it: --ping sends a ping and waits for the pong, --message sends messages and prints the replies, --origin tests the Origin check, and with neither --ping nor --message each line of stdin is sent until Ctrl+C.
This commit is contained in:
1 parent
f3a91ad915
commit
a279405cae
41 files changed
+3876
-78
No files matched your search
@@ -0,0 +1,109 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.avsdev.uk/Go/job-search/internal/config"
|
||||
"git.avsdev.uk/Go/job-search/internal/httpx"
|
||||
"git.avsdev.uk/Go/job-search/internal/middleware"
|
||||
)
|
||||
|
||||
// routes builds the router. Middleware order (outermost first):
|
||||
//
|
||||
// RealIP -> RequestID -> Logger -> Recoverer -> [global rate limit + hooks]
|
||||
// -> RequestChecks (host, body cap) -> DefaultHeaders
|
||||
// /api : NoStore -> Compress -> [api rate limit + hooks] -> CSRF
|
||||
// -> RequireJSON
|
||||
// /ws : [ws rate limit + hooks] -> Origin check (hub)
|
||||
func (s *Server) routes() (http.Handler, error) {
|
||||
conf := s.conf
|
||||
router := chi.NewRouter()
|
||||
|
||||
router.Use(
|
||||
middleware.RealIP(middleware.RealIPOptions{
|
||||
Trusted: s.trusted,
|
||||
Headers: conf.Proxy.ClientIPHeaders,
|
||||
StripUntrusted: conf.Proxy.StripUntrusted,
|
||||
}),
|
||||
middleware.RequestID,
|
||||
middleware.Logger(middleware.WithLogger(s.untaggedLogger())),
|
||||
middleware.Recoverer(middleware.WithLogger(s.untaggedLogger())),
|
||||
)
|
||||
router.Use(s.groupStack(GroupGlobal, conf.RateLimits.Global)...)
|
||||
router.Use(
|
||||
middleware.RequestChecks(*conf),
|
||||
middleware.DefaultHeaders(conf.Headers),
|
||||
)
|
||||
|
||||
compress, err := middleware.Compress()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// API
|
||||
router.Route("/api", func(apiRouter chi.Router) {
|
||||
apiRouter.Use(middleware.NoStore, compress)
|
||||
apiRouter.Use(s.groupStack(GroupAPI, conf.RateLimits.API)...)
|
||||
apiRouter.Use(s.csrf.Protect, middleware.RequireJSON)
|
||||
|
||||
apiRouter.NotFound(func(w http.ResponseWriter, r *http.Request) {
|
||||
httpx.WriteProblem(w, r, http.StatusNotFound, "no such endpoint")
|
||||
})
|
||||
apiRouter.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
|
||||
httpx.WriteProblem(w, r, http.StatusMethodNotAllowed, "")
|
||||
})
|
||||
|
||||
apiRouter.Get("/health", s.health)
|
||||
if s.csrf.TokenEnabled() {
|
||||
apiRouter.Get("/csrf", s.csrf.IssueHandler)
|
||||
}
|
||||
})
|
||||
|
||||
// WebSocket (no compression middleware: permessage-deflate is separate)
|
||||
webSocketStack := s.groupStack(GroupWebSocket, conf.WebSocket.ConnectionLimit)
|
||||
router.With(webSocketStack...).Get("/ws", s.hub.ServeHTTP)
|
||||
|
||||
return router, nil
|
||||
}
|
||||
|
||||
// groupStack returns the rate-limit hook (configured or overridden) followed
|
||||
// by any user-supplied hook middleware for the group.
|
||||
func (s *Server) groupStack(
|
||||
group Group, rule config.JSCRateLimitRule,
|
||||
) []Middleware {
|
||||
var stack []Middleware
|
||||
if hook, ok := s.limiters[group]; ok && hook.set {
|
||||
if hook.limiter != nil {
|
||||
stack = append(stack, middleware.RateLimit(hook.limiter, hook.key))
|
||||
}
|
||||
} else if rule.Enabled && rule.PerSecond > 0 {
|
||||
limiter := middleware.NewKeyedLimiter(
|
||||
s.backgroundCtx,
|
||||
float64(rule.PerSecond),
|
||||
max(rule.Burst, 1),
|
||||
s.conf.RateLimits.IdleTTL,
|
||||
)
|
||||
stack = append(stack, middleware.RateLimit(limiter, middleware.KeyByIP))
|
||||
}
|
||||
return append(stack, s.hooks[group]...)
|
||||
}
|
||||
|
||||
// health serves GET /api/health: the server's status and uptime, the number
|
||||
// of WebSocket clients, and the client as the server sees it (after proxy
|
||||
// processing).
|
||||
func (s *Server) health(w http.ResponseWriter, r *http.Request) {
|
||||
client := middleware.Client(r)
|
||||
httpx.WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"status": "ok",
|
||||
"uptime": time.Since(s.started).Round(time.Second).String(),
|
||||
"wsClients": s.hub.Count(),
|
||||
"client": map[string]any{
|
||||
"ip": client.IP.String(),
|
||||
"scheme": client.Scheme,
|
||||
"viaProxy": client.ViaProxy,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
|
||||
"git.avsdev.uk/Go/job-search/internal/config"
|
||||
)
|
||||
|
||||
func freeAddr(t *testing.T) string {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln.Close()
|
||||
return ln.Addr().String()
|
||||
}
|
||||
|
||||
func startRun(
|
||||
t *testing.T, mutate func(*config.JSCServer),
|
||||
) (addr string, stop func() error) {
|
||||
t.Helper()
|
||||
cfg := defaultConf(t)
|
||||
addr = freeAddr(t)
|
||||
host, port, _ := net.SplitHostPort(addr)
|
||||
cfg.Host = host
|
||||
cfg.Port, _ = strconv.Atoi(port)
|
||||
cfg.Timeouts.ShutdownTimeout = 3 * time.Second
|
||||
if mutate != nil {
|
||||
mutate(cfg)
|
||||
}
|
||||
s, err := New(cfg, WithLogger(slog.New(slog.DiscardHandler)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- s.Run(ctx)
|
||||
}()
|
||||
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for {
|
||||
c, err := net.Dial("tcp", addr)
|
||||
if err == nil {
|
||||
c.Close()
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("server did not start")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
return addr, func() error {
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-time.After(5 * time.Second):
|
||||
return errors.New("shutdown timed out")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A PROXY v1 header from a trusted source sets the client IP.
|
||||
func TestProxyProtocol(t *testing.T) {
|
||||
addr, stop := startRun(t, func(c *config.JSCServer) {
|
||||
c.Proxy.ProxyProtocol.Enabled = true
|
||||
})
|
||||
defer stop()
|
||||
|
||||
conn, err := net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
io.WriteString(conn, "PROXY TCP4 198.51.100.7 10.0.0.1 51234 8080\r\n"+
|
||||
"GET /api/health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
|
||||
res, err := http.ReadResponse(bufio.NewReader(conn), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
var out map[string]map[string]any
|
||||
json.NewDecoder(res.Body).Decode(&out)
|
||||
if out["client"]["ip"] != "198.51.100.7" {
|
||||
t.Fatalf("PROXY header not applied: %v", out["client"])
|
||||
}
|
||||
|
||||
// Plain HTTP (no PROXY header) still works when not required.
|
||||
res2, err := http.Get("http://" + addr + "/api/health")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res2.Body.Close()
|
||||
if res2.StatusCode != 200 {
|
||||
t.Fatalf("plain request: %d", res2.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown closes live WebSockets with 1001 and Run returns cleanly.
|
||||
func TestGracefulShutdownClosesWebSockets(t *testing.T) {
|
||||
addr, stop := startRun(t, nil)
|
||||
jar, _ := cookiejar.New(nil)
|
||||
hc := &http.Client{
|
||||
Jar: jar,
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
url := "ws://" + addr + "/ws"
|
||||
conn, _, err := websocket.Dial(ctx, url, &websocket.DialOptions{
|
||||
HTTPClient: hc,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := conn.Read(ctx); err != nil { // welcome
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
readErr := make(chan error, 1)
|
||||
go func() {
|
||||
_, _, err := conn.Read(ctx)
|
||||
readErr <- err
|
||||
}()
|
||||
|
||||
if err := stop(); err != nil {
|
||||
t.Fatalf("Run returned error: %v", err)
|
||||
}
|
||||
err = <-readErr
|
||||
if websocket.CloseStatus(err) != websocket.StatusGoingAway {
|
||||
t.Fatalf("want close 1001, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "shutting down") {
|
||||
t.Fatalf("unexpected close reason: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The HTTP listener redirects to the same host and path over HTTPS, on the
|
||||
// TLS listener's port (left out when it is 443).
|
||||
func TestHTTPSRedirect(t *testing.T) {
|
||||
tests := []struct {
|
||||
tlsAddr, host, want string
|
||||
}{
|
||||
{"127.0.0.1:9393", "example.com:8080", "https://example.com:9393/x?y=1"},
|
||||
{"127.0.0.1:9393", "example.com", "https://example.com:9393/x?y=1"},
|
||||
{"127.0.0.1:443", "example.com:80", "https://example.com/x?y=1"},
|
||||
{"[::1]:9393", "[2001:db8::1]:8080", "https://[2001:db8::1]:9393/x?y=1"},
|
||||
{"[::1]:443", "[2001:db8::1]:80", "https://[2001:db8::1]/x?y=1"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
req := httptest.NewRequest("GET", "http://"+tt.host+"/x?y=1", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
httpsRedirect(tt.tlsAddr).ServeHTTP(rec, req)
|
||||
location := rec.Header().Get("Location")
|
||||
if rec.Code != http.StatusPermanentRedirect || location != tt.want {
|
||||
t.Errorf(
|
||||
"%s via %s: %d %q; want 308 %q",
|
||||
tt.host,
|
||||
tt.tlsAddr,
|
||||
rec.Code,
|
||||
location,
|
||||
tt.want,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
// Package server assembles the HTTP server for the serve command.
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pires/go-proxyproto"
|
||||
|
||||
"git.avsdev.uk/Go/job-search/internal/config"
|
||||
"git.avsdev.uk/Go/job-search/internal/middleware"
|
||||
"git.avsdev.uk/Go/job-search/internal/util"
|
||||
"git.avsdev.uk/Go/job-search/internal/websocket"
|
||||
)
|
||||
|
||||
// Group identifies where hook middleware is inserted.
|
||||
type Group int
|
||||
|
||||
// The route groups hook middleware can be added to (see WithMiddleware).
|
||||
const (
|
||||
// GroupGlobal is every request, after real-IP, request-ID and logging.
|
||||
GroupGlobal Group = iota
|
||||
// GroupAPI is /api/*, before CSRF protection.
|
||||
GroupAPI
|
||||
// GroupWebSocket is /ws upgrade requests.
|
||||
GroupWebSocket
|
||||
)
|
||||
|
||||
// Middleware is the standard net/http middleware shape.
|
||||
type Middleware = func(http.Handler) http.Handler
|
||||
|
||||
// Option customises a Server.
|
||||
type Option func(*Server)
|
||||
|
||||
// WithLogger makes the server, its middleware and its WebSocket hub log to
|
||||
// logger instead of slog.Default().
|
||||
func WithLogger(logger *slog.Logger) Option {
|
||||
return func(s *Server) {
|
||||
s.log = logger
|
||||
}
|
||||
}
|
||||
|
||||
// WithMiddleware appends middleware to a group. This is the generic hook
|
||||
// (auth, metrics, tracing, custom header rules, ...).
|
||||
func WithMiddleware(group Group, middlewares ...Middleware) Option {
|
||||
return func(server *Server) {
|
||||
server.hooks[group] = append(server.hooks[group], middlewares...)
|
||||
}
|
||||
}
|
||||
|
||||
// WithRateLimiter replaces the configured rate limiter of a group (for
|
||||
// example with a Redis-backed implementation). Pass a nil Limiter to
|
||||
// disable limiting for the group. A nil key defaults to the client IP.
|
||||
func WithRateLimiter(
|
||||
group Group, limiter middleware.Limiter, key middleware.KeyFunc,
|
||||
) Option {
|
||||
return func(server *Server) {
|
||||
server.limiters[group] = limiterHook{
|
||||
limiter: limiter,
|
||||
key: key,
|
||||
set: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// limiterHook is a group's rate limiter set by WithRateLimiter, replacing the
|
||||
// configured one. set distinguishes a nil limiter (no limiting) from none.
|
||||
type limiterHook struct {
|
||||
limiter middleware.Limiter
|
||||
key middleware.KeyFunc
|
||||
set bool
|
||||
}
|
||||
|
||||
// Server is the application server.
|
||||
type Server struct {
|
||||
conf *config.JSCServer
|
||||
log *slog.Logger
|
||||
hooks map[Group][]Middleware
|
||||
limiters map[Group]limiterHook
|
||||
|
||||
// trusted are the proxies whose forwarding headers are believed.
|
||||
trusted []netip.Prefix
|
||||
// proxyProtocolTrusted are the sources allowed to send a PROXY header.
|
||||
proxyProtocolTrusted []netip.Prefix
|
||||
csrf *middleware.CSRF
|
||||
hub *websocket.Hub
|
||||
started time.Time
|
||||
handler http.Handler
|
||||
// backgroundCtx is for background work, such as the rate limiters'
|
||||
// janitors; backgroundCancel stops it.
|
||||
backgroundCtx context.Context
|
||||
backgroundCancel context.CancelFunc
|
||||
}
|
||||
|
||||
// New builds the server and its router. It logs to slog.Default() unless
|
||||
// given WithLogger.
|
||||
func New(conf *config.JSCServer, opts ...Option) (*Server, error) {
|
||||
server := &Server{
|
||||
conf: conf,
|
||||
hooks: make(map[Group][]Middleware),
|
||||
limiters: make(map[Group]limiterHook),
|
||||
started: time.Now(),
|
||||
}
|
||||
for _, option := range opts {
|
||||
option(server)
|
||||
}
|
||||
|
||||
var err error
|
||||
server.trusted, err = util.ParseNetPrefixes(conf.Proxy.TrustedProxies)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parsing proxy.trusted: %w", err)
|
||||
}
|
||||
|
||||
proxyProtocolSources := conf.Proxy.ProxyProtocol.TrustedSources
|
||||
if len(proxyProtocolSources) == 0 {
|
||||
proxyProtocolSources = conf.Proxy.TrustedProxies
|
||||
}
|
||||
server.proxyProtocolTrusted, err = util.ParseNetPrefixes(
|
||||
proxyProtocolSources,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"parsing proxy.proxy_protocol.trusted_sources: %w", err,
|
||||
)
|
||||
}
|
||||
|
||||
server.csrf, err = middleware.NewCSRF(
|
||||
conf.CSRF, middleware.WithLogger(server.untaggedLogger()),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
server.hub = websocket.NewHub(
|
||||
conf.WebSocket,
|
||||
websocket.WithLogger(server.untaggedLogger()),
|
||||
websocket.WithTrustedOrigins(
|
||||
conf.CSRF.CrossOriginProtection.TrustedOrigins,
|
||||
),
|
||||
)
|
||||
|
||||
server.backgroundCtx, server.backgroundCancel = context.WithCancel(
|
||||
context.Background(),
|
||||
)
|
||||
server.handler, err = server.routes()
|
||||
if err != nil {
|
||||
server.backgroundCancel()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return server, nil
|
||||
}
|
||||
|
||||
// untaggedLogger returns the logger given WithLogger, or slog.Default(), for
|
||||
// the server's middleware and hub to tag with their own components.
|
||||
func (s *Server) untaggedLogger() *slog.Logger {
|
||||
if s.log == nil {
|
||||
return slog.Default()
|
||||
}
|
||||
return s.log
|
||||
}
|
||||
|
||||
// logger returns the logger the server logs to, tagged with its component.
|
||||
func (s *Server) logger() *slog.Logger {
|
||||
return s.untaggedLogger().With("component", "server")
|
||||
}
|
||||
|
||||
// Handler exposes the root handler (useful for httptest).
|
||||
func (s *Server) Handler() http.Handler { return s.handler }
|
||||
|
||||
// Run listens and serves until ctx is cancelled, then shuts down gracefully.
|
||||
// With TLS, it also serves an HTTP to HTTPS redirect if tls.redirect_http_port
|
||||
// is set.
|
||||
func (s *Server) Run(ctx context.Context) error {
|
||||
defer s.backgroundCancel()
|
||||
conf := s.conf
|
||||
|
||||
addr := net.JoinHostPort(conf.Host, strconv.Itoa(conf.Port))
|
||||
|
||||
listen, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("listen %s: %w", addr, err)
|
||||
}
|
||||
if conf.Proxy.ProxyProtocol.Enabled {
|
||||
listen = &proxyproto.Listener{
|
||||
Listener: listen,
|
||||
ConnPolicy: s.proxyPolicy,
|
||||
ReadHeaderTimeout: noLimitIfUnset(
|
||||
conf.Proxy.ProxyProtocol.ReadHeaderTimeout,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
httpServer := &http.Server{
|
||||
Handler: s.handler,
|
||||
ReadHeaderTimeout: noLimitIfUnset(conf.Timeouts.ReadHeaderTimeout),
|
||||
ReadTimeout: conf.Timeouts.ReadTimeout,
|
||||
WriteTimeout: conf.Timeouts.WriteTimeout,
|
||||
IdleTimeout: noLimitIfUnset(conf.Timeouts.IdleTimeout),
|
||||
MaxHeaderBytes: maxHeaderBytes(conf),
|
||||
ErrorLog: slog.NewLogLogger(
|
||||
s.logger().Handler(), slog.LevelWarn,
|
||||
),
|
||||
}
|
||||
|
||||
if conf.TLS.Enabled {
|
||||
minVersion := uint16(tls.VersionTLS12)
|
||||
if conf.TLS.MinVersion == "1.3" {
|
||||
minVersion = tls.VersionTLS13
|
||||
}
|
||||
httpServer.TLSConfig = &tls.Config{
|
||||
MinVersion: minVersion,
|
||||
}
|
||||
}
|
||||
|
||||
serveErrors := make(chan error, 2)
|
||||
go func() {
|
||||
s.logger().Info(
|
||||
"listening",
|
||||
"addr", listen.Addr().String(),
|
||||
"tls", conf.TLS.Enabled,
|
||||
"proxy_protocol", conf.Proxy.ProxyProtocol.Enabled,
|
||||
)
|
||||
var err error
|
||||
if conf.TLS.Enabled {
|
||||
err = httpServer.ServeTLS(listen, conf.TLS.CertFile, conf.TLS.KeyFile)
|
||||
} else {
|
||||
err = httpServer.Serve(listen)
|
||||
}
|
||||
serveErrors <- err
|
||||
}()
|
||||
|
||||
var redirect *http.Server
|
||||
if conf.TLS.Enabled && conf.TLS.RedirectHTTPPort != 0 {
|
||||
httpAddr := net.JoinHostPort(
|
||||
conf.Host, strconv.Itoa(conf.TLS.RedirectHTTPPort),
|
||||
)
|
||||
|
||||
redirect = &http.Server{
|
||||
Addr: httpAddr,
|
||||
Handler: middleware.RequestChecks(*conf)(httpsRedirect(addr)),
|
||||
ReadHeaderTimeout: noLimitIfUnset(conf.Timeouts.ReadHeaderTimeout),
|
||||
IdleTimeout: noLimitIfUnset(conf.Timeouts.IdleTimeout),
|
||||
}
|
||||
go func() {
|
||||
s.logger().Info("http->https redirect listening", "addr", httpAddr)
|
||||
serveErrors <- redirect.ListenAndServe()
|
||||
}()
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-serveErrors:
|
||||
if !errors.Is(err, http.ErrServerClosed) {
|
||||
return err
|
||||
}
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
s.logger().Info("shutting down")
|
||||
shutdownCtx, cancel := util.WithTimeout(
|
||||
context.Background(), conf.Timeouts.ShutdownTimeout,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
// Stop accepting first, then close WebSockets (hijacked connections are
|
||||
// not tracked by http.Server.Shutdown), then drain in-flight requests.
|
||||
var errs []error
|
||||
shutdownErr := make(chan error, 1)
|
||||
go func() {
|
||||
shutdownErr <- httpServer.Shutdown(shutdownCtx)
|
||||
}()
|
||||
if err := s.hub.Shutdown(shutdownCtx); err != nil {
|
||||
errs = append(errs, fmt.Errorf("websocket shutdown: %w", err))
|
||||
}
|
||||
if err := <-shutdownErr; err != nil {
|
||||
errs = append(errs, fmt.Errorf("http shutdown: %w", err))
|
||||
}
|
||||
if redirect != nil {
|
||||
redirect.Shutdown(shutdownCtx) //nolint:errcheck,gosec // only redirects; nothing to drain
|
||||
}
|
||||
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// noLimitIfUnset returns timeout for a field that reads 0 as some other
|
||||
// timeout, such as http.Server's ReadHeaderTimeout and IdleTimeout (which
|
||||
// use ReadTimeout) or the PROXY listener's ReadHeaderTimeout (10s): -1,
|
||||
// which those fields read as no limit, if timeout is 0 or less, as the
|
||||
// configuration's timeouts mean.
|
||||
func noLimitIfUnset(timeout time.Duration) time.Duration {
|
||||
if timeout <= 0 {
|
||||
return -1
|
||||
}
|
||||
return timeout
|
||||
}
|
||||
|
||||
// defaultMaxHeaderBytes is the largest request header block when
|
||||
// max_header_bytes is 0 or less: 8KB, as the configuration's default. The
|
||||
// configuration rejects -1 (no limit), as http.Server can't have one.
|
||||
const defaultMaxHeaderBytes = 8_000
|
||||
|
||||
// maxHeaderBytes is the largest request header block: max_header_bytes, or
|
||||
// defaultMaxHeaderBytes if that is 0 or less.
|
||||
func maxHeaderBytes(conf *config.JSCServer) int {
|
||||
if conf.MaxHeaderBytes <= 0 {
|
||||
return defaultMaxHeaderBytes
|
||||
}
|
||||
return int(conf.MaxHeaderBytes)
|
||||
}
|
||||
|
||||
// proxyPolicy decides per connection how to treat a PROXY header. Only
|
||||
// trusted sources may supply one. Untrusted peers are SKIPped (the header is
|
||||
// not parsed; a spoofed one becomes garbage to the HTTP parser and fails).
|
||||
// Never return a non-ErrInvalidUpstream error here: it would stop Accept.
|
||||
func (s *Server) proxyPolicy(
|
||||
options proxyproto.ConnPolicyOptions,
|
||||
) (proxyproto.Policy, error) {
|
||||
ip := addrOf(options.Upstream)
|
||||
for _, prefix := range s.proxyProtocolTrusted {
|
||||
if ip.IsValid() && prefix.Contains(ip) {
|
||||
if s.conf.Proxy.ProxyProtocol.Required {
|
||||
return proxyproto.REQUIRE, nil
|
||||
}
|
||||
return proxyproto.USE, nil
|
||||
}
|
||||
}
|
||||
return proxyproto.SKIP, nil
|
||||
}
|
||||
|
||||
// addrOf returns the IP address of a connection's address (unmapped to IPv4
|
||||
// if it is an IPv4-mapped IPv6 address), or the zero Addr if it has none.
|
||||
func addrOf(netAddr net.Addr) netip.Addr {
|
||||
switch tcpAddr := netAddr.(type) {
|
||||
case *net.TCPAddr:
|
||||
ip, _ := netip.AddrFromSlice(tcpAddr.IP)
|
||||
return ip.Unmap()
|
||||
default:
|
||||
addrPort, err := netip.ParseAddrPort(netAddr.String())
|
||||
if err != nil {
|
||||
return netip.Addr{}
|
||||
}
|
||||
return addrPort.Addr().Unmap()
|
||||
}
|
||||
}
|
||||
|
||||
// httpsRedirect redirects every request permanently to the same host and
|
||||
// path over HTTPS, on the port of tlsAddr (the TLS listener's address),
|
||||
// which is left out if it is 443.
|
||||
func httpsRedirect(tlsAddr string) http.Handler {
|
||||
_, port, _ := net.SplitHostPort(tlsAddr)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
host := r.Host
|
||||
if hostname, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = hostname
|
||||
}
|
||||
if strings.Contains(host, ":") { // bare IPv6
|
||||
host = "[" + host + "]"
|
||||
}
|
||||
if port != "" && port != "443" {
|
||||
host = net.JoinHostPort(strings.Trim(host, "[]"), port)
|
||||
}
|
||||
// The redirect only switches the scheme (and port) of the URL the
|
||||
// client asked for, on the host it asked for, so it can't send the
|
||||
// client anywhere else; RequestChecks has checked that host.
|
||||
http.Redirect( //nolint:gosec // G710: see above
|
||||
w, r, "https://"+host+r.URL.RequestURI(), http.StatusPermanentRedirect,
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"git.avsdev.uk/Go/job-search/internal/config"
|
||||
"git.avsdev.uk/Go/job-search/internal/middleware"
|
||||
ws "git.avsdev.uk/Go/job-search/internal/websocket"
|
||||
)
|
||||
|
||||
// defaultConf returns the server configuration's defaults, as Init would
|
||||
// load them with no config file or environment.
|
||||
func defaultConf(t *testing.T) *config.JSCServer {
|
||||
t.Helper()
|
||||
viper.Reset()
|
||||
t.Cleanup(viper.Reset)
|
||||
config.LoadDefaultConfig()
|
||||
var conf config.JobSearchConfig
|
||||
config.LoadFromViper(&conf)
|
||||
return &conf.Server
|
||||
}
|
||||
|
||||
func newTestServer(
|
||||
t *testing.T, mutate func(*config.JSCServer), opts ...Option,
|
||||
) *httptest.Server {
|
||||
t.Helper()
|
||||
cfg := defaultConf(t)
|
||||
if mutate != nil {
|
||||
mutate(cfg)
|
||||
}
|
||||
opts = append([]Option{WithLogger(slog.New(slog.DiscardHandler))}, opts...)
|
||||
s, err := New(cfg, opts...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ts := httptest.NewServer(s.Handler())
|
||||
t.Cleanup(func() {
|
||||
ts.Close()
|
||||
s.backgroundCancel()
|
||||
})
|
||||
return ts
|
||||
}
|
||||
|
||||
type csrfToken struct {
|
||||
Token string `json:"token"`
|
||||
Header string `json:"header"`
|
||||
}
|
||||
|
||||
func getToken(t *testing.T, c *http.Client, base string) csrfToken {
|
||||
t.Helper()
|
||||
res, err := c.Get(base + "/api/csrf")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
var tok csrfToken
|
||||
if err := json.NewDecoder(res.Body).Decode(&tok); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return tok
|
||||
}
|
||||
|
||||
func clientWithJar(t *testing.T) *http.Client {
|
||||
t.Helper()
|
||||
jar, err := cookiejar.New(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &http.Client{
|
||||
Jar: jar,
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// Unsafe API requests need the CSRF token: without it they are rejected
|
||||
// before routing; with it they reach the router (here, 405 from a GET-only
|
||||
// route).
|
||||
func TestAPICSRF(t *testing.T) {
|
||||
ts := newTestServer(t, nil)
|
||||
c := clientWithJar(t)
|
||||
tok := getToken(t, c, ts.URL)
|
||||
|
||||
post := func(withToken bool) int {
|
||||
req, _ := http.NewRequest(
|
||||
"POST", ts.URL+"/api/health", strings.NewReader("{}"),
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if withToken {
|
||||
req.Header.Set(tok.Header, tok.Token)
|
||||
}
|
||||
res, err := c.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
return res.StatusCode
|
||||
}
|
||||
if code := post(false); code != http.StatusForbidden {
|
||||
t.Errorf("POST without token: got %d, want 403", code)
|
||||
}
|
||||
if code := post(true); code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("POST with token: got %d, want 405", code)
|
||||
}
|
||||
}
|
||||
|
||||
// Every route group sees the ClientInfo built by RealIP, not the fallback
|
||||
// from middleware.Client: ViaProxy is only set when RealIP honoured a header.
|
||||
func TestRealIPCoversAllGroups(t *testing.T) {
|
||||
groups := map[Group]string{
|
||||
GroupGlobal: "/",
|
||||
GroupAPI: "/api/health",
|
||||
GroupWebSocket: "/ws",
|
||||
}
|
||||
for g, path := range groups {
|
||||
var ran, viaProxy bool
|
||||
hook := func(http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ran, viaProxy = true, middleware.Client(r).ViaProxy
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
}
|
||||
// 127.0.0.1 is trusted by default.
|
||||
ts := newTestServer(t, nil, WithMiddleware(g, hook))
|
||||
req, _ := http.NewRequest("GET", ts.URL+path, nil)
|
||||
req.Header.Set("X-Forwarded-For", "203.0.113.9")
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
if !ran || !viaProxy {
|
||||
t.Errorf(
|
||||
"group %d (%s): hook ran=%v, ViaProxy=%v", g, path, ran, viaProxy,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A WebSocket upgrade is refused from a foreign origin, accepted from an
|
||||
// origin in csrf.cross_origin_protection.trusted_origins, and the client then
|
||||
// gets replies.
|
||||
func TestWebSocket(t *testing.T) {
|
||||
ts := newTestServer(t, func(conf *config.JSCServer) {
|
||||
conf.CSRF.CrossOriginProtection.TrustedOrigins = []string{
|
||||
"https://admin.example.com",
|
||||
}
|
||||
})
|
||||
c := clientWithJar(t)
|
||||
wsURL := "ws" + strings.TrimPrefix(ts.URL, "http") + "/ws"
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
foreign := &websocket.DialOptions{
|
||||
HTTPClient: c,
|
||||
HTTPHeader: http.Header{"Origin": []string{"https://evil.example"}},
|
||||
}
|
||||
_, res, err := websocket.Dial(ctx, wsURL, foreign)
|
||||
if err == nil || res.StatusCode != http.StatusForbidden {
|
||||
t.Fatalf("foreign origin: expected 403, err=%v", err)
|
||||
}
|
||||
|
||||
trusted := &websocket.DialOptions{
|
||||
HTTPClient: c,
|
||||
HTTPHeader: http.Header{"Origin": []string{"https://admin.example.com"}},
|
||||
}
|
||||
conn, _, err := websocket.Dial(ctx, wsURL, trusted)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
|
||||
read := func() ws.Envelope {
|
||||
var e ws.Envelope
|
||||
if err := wsjson.Read(ctx, conn, &e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
if e := read(); e.Type != ws.TypeWelcome {
|
||||
t.Fatalf("want welcome, got %+v", e)
|
||||
}
|
||||
wsjson.Write(ctx, conn, ws.Envelope{
|
||||
Type: ws.TypePing,
|
||||
ID: "1",
|
||||
})
|
||||
if e := read(); e.Type != ws.TypePong || e.ID != "1" {
|
||||
t.Fatalf("want pong, got %+v", e)
|
||||
}
|
||||
|
||||
conn.Close(websocket.StatusNormalClosure, "")
|
||||
}
|
||||
|
||||
// A timeout of 0 or less is passed on as -1, which http.Server and the PROXY
|
||||
// listener read as no limit rather than as another timeout.
|
||||
func TestNoLimitIfUnset(t *testing.T) {
|
||||
tests := []struct {
|
||||
in, want time.Duration
|
||||
}{
|
||||
{0, -1},
|
||||
{-time.Second, -1},
|
||||
{time.Second, time.Second},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := noLimitIfUnset(tt.in); got != tt.want {
|
||||
t.Errorf("noLimitIfUnset(%v) = %v; want %v", tt.in, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user