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.
221 lines
5.5 KiB
Go
221 lines
5.5 KiB
Go
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)
|
|
}
|
|
}
|
|
}
|