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:
bwilliams committed 2026-10-15 17:47:40 +01:00
1 parent f3a91ad915
commit a279405cae
41 files changed
+3876 -78

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
// Package httpx holds small HTTP helpers shared by middleware and handlers.
package httpx
import (
"encoding/json"
"net/http"
)
// WriteJSON writes value as JSON with the given status. A nil value, or 204 No
// Content, writes no body.
func WriteJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
if value == nil || status == http.StatusNoContent {
return
}
json.NewEncoder(w).Encode(value) //nolint:errcheck,gosec // the client may have gone
}
+53
View File
@@ -8,6 +8,59 @@ import (
"testing"
)
func TestWriteJSON(t *testing.T) {
rec := httptest.NewRecorder()
WriteJSON(rec, http.StatusCreated, map[string]any{"id": "x", "n": 1})
if rec.Code != http.StatusCreated {
t.Errorf("status = %d; want 201", rec.Code)
}
ct := rec.Header().Get("Content-Type")
if ct != "application/json; charset=utf-8" {
t.Errorf("Content-Type = %q", ct)
}
if body := rec.Body.String(); body != `{"id":"x","n":1}`+"\n" {
t.Errorf("body = %q", body)
}
}
// A nil value, or 204 No Content, writes the status and headers but no body.
func TestWriteJSONNoBody(t *testing.T) {
tests := []struct {
name string
status int
v any
}{
{"nil value", http.StatusOK, nil},
{"no content", http.StatusNoContent, map[string]string{"ignored": "yes"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rec := httptest.NewRecorder()
WriteJSON(rec, tt.status, tt.v)
if rec.Code != tt.status || rec.Body.Len() != 0 {
t.Errorf(
"got %d %q; want %d and no body", rec.Code, rec.Body, tt.status,
)
}
ct := rec.Header().Get("Content-Type")
if ct != "application/json; charset=utf-8" {
t.Errorf("Content-Type = %q", ct)
}
})
}
}
// A value that can't be encoded still gets its status; the body is empty.
func TestWriteJSONUnencodable(t *testing.T) {
rec := httptest.NewRecorder()
WriteJSON(rec, http.StatusOK, func() {
})
if rec.Code != http.StatusOK || rec.Body.Len() != 0 {
t.Errorf("got %d %q; want 200 and no body", rec.Code, rec.Body)
}
}
func TestWriteProblem(t *testing.T) {
req := httptest.NewRequest("GET", "/api/items/1", nil)
req = req.WithContext(WithRequestID(req.Context(), "req-123"))
+2
View File
@@ -4,8 +4,10 @@ import (
"context"
)
// ctxKey is the type of this package's context keys.
type ctxKey int
// requestIDKey is the context key of the request ID.
const requestIDKey ctxKey = iota
// WithRequestID stores a request ID in the context.