~bigbes/lethe

ref: 3c45b48bd5d0d99f76d2063504adaa7b312b85bc lethe/internal/server/server_test.go -rw-r--r-- 7.6 KiB
3c45b48b — Eugene Blikh feat(http): chi server with middleware stack + RFC 7807 problem renderer a month ago
                                                                                
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
246
247
248
249
250
251
252
253
package server

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/go-chi/chi/v5"
	"go.bigb.es/auxilia/culpa"

	"sourcecraft.dev/bigbes/lethe/internal/config"
	"sourcecraft.dev/bigbes/lethe/internal/domain/ingest"
	"sourcecraft.dev/bigbes/lethe/internal/domain/session"
	"sourcecraft.dev/bigbes/lethe/internal/platform/health"
	"sourcecraft.dev/bigbes/lethe/internal/platform/observability"
	authpkg "sourcecraft.dev/bigbes/lethe/internal/server/auth"
)

// newTestServer wires a Server with hand-constructed dependencies so unit
// tests do not need to spin up the steward graph.
func newTestServer(t *testing.T, bind string) *Server {
	t.Helper()

	logger := &observability.Logger{Cfg: config.LoggingConfig{Level: "info", Format: "json"}}
	if err := logger.Init(context.Background()); err != nil {
		t.Fatalf("logger.Init: %v", err)
	}
	metrics := &observability.Metrics{}
	if err := metrics.Init(context.Background()); err != nil {
		t.Fatalf("metrics.Init: %v", err)
	}
	return &Server{
		Cfg: config.ServerConfig{
			Bind:          bind,
			ShutdownGrace: 5 * time.Second,
		},
		Log:      logger,
		Metrics:  metrics,
		Health:   &health.Set{},
		Auth:     &authpkg.Authenticator{},
		Ingest:   &ingest.Handler{},
		Sessions: &session.Handler{},
	}
}

func TestServerInit_RejectsNonLoopbackBind(t *testing.T) {
	s := newTestServer(t, "0.0.0.0:8080")
	err := s.Init(context.Background())
	if err == nil {
		t.Fatalf("Init: expected error for non-loopback bind")
	}
	var cd culpa.CodeDetail
	if !culpa.FindDetail(err, &cd) {
		t.Fatalf("Init: expected culpa CodeDetail; got %v", err)
	}
	if cd.Code != "CONFIG_INVALID" {
		t.Errorf("Init: code = %v; want CONFIG_INVALID", cd.Code)
	}
}

func TestServerInit_AcceptsLoopback(t *testing.T) {
	s := newTestServer(t, "127.0.0.1:0")
	if err := s.Init(context.Background()); err != nil {
		t.Fatalf("Init: %v", err)
	}
	if s.router == nil {
		t.Fatalf("Init: router not built")
	}
}

func TestRouter_RecoveryTurnsPanicInto500Problem(t *testing.T) {
	s := newTestServer(t, "127.0.0.1:0")
	if err := s.Init(context.Background()); err != nil {
		t.Fatalf("Init: %v", err)
	}
	// Mount a panicking route on the router *after* Init wired the
	// middleware chain so the recovery middleware sits in front of it.
	s.router.Get("/boom", func(http.ResponseWriter, *http.Request) {
		panic("kaboom")
	})

	req := httptest.NewRequest(http.MethodGet, "/boom", nil)
	rec := httptest.NewRecorder()
	s.router.ServeHTTP(rec, req)

	if rec.Code != http.StatusInternalServerError {
		t.Fatalf("status = %d; want 500", rec.Code)
	}
	if ct := rec.Header().Get("Content-Type"); ct != "application/problem+json" {
		t.Errorf("Content-Type = %q; want application/problem+json", ct)
	}
	var body map[string]any
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("unmarshal body: %v", err)
	}
	if body["status"].(float64) != 500 {
		t.Errorf("body.status = %v; want 500", body["status"])
	}
	if body["detail"] != "internal server error" {
		t.Errorf("body.detail = %v; want sanitized message", body["detail"])
	}
}

func TestRouter_RequestIDInResponseAndContext(t *testing.T) {
	s := newTestServer(t, "127.0.0.1:0")
	if err := s.Init(context.Background()); err != nil {
		t.Fatalf("Init: %v", err)
	}
	var fromCtx string
	s.router.Get("/probe", func(w http.ResponseWriter, r *http.Request) {
		fromCtx = observability.RequestIDFrom(r.Context())
		w.WriteHeader(http.StatusOK)
	})

	req := httptest.NewRequest(http.MethodGet, "/probe", nil)
	rec := httptest.NewRecorder()
	s.router.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d; want 200", rec.Code)
	}
	headerID := rec.Header().Get("X-Request-ID")
	if headerID == "" {
		t.Fatalf("X-Request-ID header missing")
	}
	if fromCtx == "" {
		t.Fatalf("request id missing from context")
	}
	if headerID != fromCtx {
		t.Errorf("ctx id %q != header id %q", fromCtx, headerID)
	}
}

func TestRouter_HealthzReturnsOK(t *testing.T) {
	s := newTestServer(t, "127.0.0.1:0")
	if err := s.Init(context.Background()); err != nil {
		t.Fatalf("Init: %v", err)
	}
	req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
	rec := httptest.NewRecorder()
	s.router.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d; want 200", rec.Code)
	}
	if rec.Body.String() != "ok" {
		t.Errorf("body = %q; want ok", rec.Body.String())
	}
}

func TestRouter_ReadyzAllOKWithEmptyChecks(t *testing.T) {
	s := newTestServer(t, "127.0.0.1:0")
	if err := s.Init(context.Background()); err != nil {
		t.Fatalf("Init: %v", err)
	}
	req := httptest.NewRequest(http.MethodGet, "/readyz", nil)
	rec := httptest.NewRecorder()
	s.router.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d; want 200", rec.Code)
	}
}

func TestRouter_MetricsExposesPrometheus(t *testing.T) {
	s := newTestServer(t, "127.0.0.1:0")
	if err := s.Init(context.Background()); err != nil {
		t.Fatalf("Init: %v", err)
	}
	req := httptest.NewRequest(http.MethodGet, "/metrics", nil)
	rec := httptest.NewRecorder()
	s.router.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d; want 200", rec.Code)
	}
	if got := rec.Body.String(); got == "" {
		t.Errorf("metrics body empty")
	}
}

// TestRouter_APIv1MountsAuthMiddleware is a smoke test: the auth middleware
// is the identity passthrough in Phase 5, but the /api/v1 group must still
// wire it in so Phase 6's replacement immediately takes effect on every
// route registered by the ingest/session handlers.
func TestRouter_APIv1MountsAuthMiddleware(t *testing.T) {
	s := newTestServer(t, "127.0.0.1:0")
	if err := s.Init(context.Background()); err != nil {
		t.Fatalf("Init: %v", err)
	}
	// Hang a probe route off the /api/v1 group via the same chi router.
	s.router.Route("/api/v1/probe", func(r chi.Router) {
		r.Get("/", func(w http.ResponseWriter, _ *http.Request) {
			w.WriteHeader(http.StatusTeapot)
		})
	})
	req := httptest.NewRequest(http.MethodGet, "/api/v1/probe", nil)
	rec := httptest.NewRecorder()
	s.router.ServeHTTP(rec, req)
	if rec.Code != http.StatusTeapot {
		t.Fatalf("status = %d; want 418", rec.Code)
	}
}

func TestRouter_NotFoundReturnsProblemJSON(t *testing.T) {
	srv := newTestServer(t, "127.0.0.1:0")
	if err := srv.Init(context.Background()); err != nil {
		t.Fatalf("Init: %v", err)
	}

	req := httptest.NewRequest(http.MethodGet, "/no-such-route", nil)
	rec := httptest.NewRecorder()
	srv.router.ServeHTTP(rec, req)

	if rec.Code != http.StatusNotFound {
		t.Fatalf("status: got %d, want 404", rec.Code)
	}
	if ct := rec.Header().Get("Content-Type"); ct != "application/problem+json" {
		t.Fatalf("Content-Type: got %q, want application/problem+json", ct)
	}
	var p map[string]any
	if err := json.Unmarshal(rec.Body.Bytes(), &p); err != nil {
		t.Fatalf("body is not JSON: %v", err)
	}
	if got, _ := p["code"].(string); got != "NOT_FOUND" {
		t.Fatalf("code: got %q, want NOT_FOUND", got)
	}
}

func TestRouter_MethodNotAllowedReturnsProblemJSON(t *testing.T) {
	srv := newTestServer(t, "127.0.0.1:0")
	if err := srv.Init(context.Background()); err != nil {
		t.Fatalf("Init: %v", err)
	}

	req := httptest.NewRequest(http.MethodPost, "/healthz", nil)
	rec := httptest.NewRecorder()
	srv.router.ServeHTTP(rec, req)

	if rec.Code != http.StatusMethodNotAllowed {
		t.Fatalf("status: got %d, want 405", rec.Code)
	}
	if ct := rec.Header().Get("Content-Type"); ct != "application/problem+json" {
		t.Fatalf("Content-Type: got %q, want application/problem+json", ct)
	}
	var p map[string]any
	if err := json.Unmarshal(rec.Body.Bytes(), &p); err != nil {
		t.Fatalf("body is not JSON: %v", err)
	}
	if got, _ := p["code"].(string); got != "METHOD_NOT_ALLOWED" {
		t.Fatalf("code: got %q, want METHOD_NOT_ALLOWED", got)
	}
}