~bigbes/lethe

ref: ef738a28b65454441af0c98c23a389cfa24fb22c lethe/internal/domain/savedsearch/handler_test.go -rw-r--r-- 12.8 KiB
ef738a28 — Eugene Blikh collector: align ingest sender with server response 24 days 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package savedsearch_test

import (
	"bytes"
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/go-chi/chi/v5"

	"sourcecraft.dev/bigbes/lethe/internal/domain/savedsearch"
	"sourcecraft.dev/bigbes/lethe/internal/server/auth"
)

// fakeAuthMiddleware injects a fixed Identity onto the request context so
// the handler can call auth.MustIdentity without a real Authenticator.
func fakeAuthMiddleware(id auth.Identity) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx := auth.WithIdentity(r.Context(), id)
			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}

// newHandler wires a Handler against a fresh in-memory database.
func newHandler(t *testing.T) *savedsearch.Handler {
	t.Helper()
	repo := newRepo(t)
	h := &savedsearch.Handler{Repo: repo}
	if err := h.Init(context.Background()); err != nil {
		t.Fatalf("handler.Init: %v", err)
	}
	return h
}

// mountWithIdentity builds a chi router with the fake auth middleware and
// the savedsearch handler mounted under /api/v1.
func mountWithIdentity(h *savedsearch.Handler, id auth.Identity) http.Handler {
	r := chi.NewRouter()
	r.Route("/api/v1", func(r chi.Router) {
		r.Use(fakeAuthMiddleware(id))
		h.Mount(r)
	})
	return r
}

// savedSearchListBody is the decoded JSON body from GET /saved-searches.
type savedSearchListBody struct {
	SavedSearches []json.RawMessage `json:"saved_searches"`
}

// problemBody captures RFC 7807 fields tests assert on.
type problemBody struct {
	Status int    `json:"status"`
	Code   string `json:"code"`
}

func doGET(t *testing.T, router http.Handler, path string) *httptest.ResponseRecorder {
	t.Helper()
	req := httptest.NewRequest(http.MethodGet, path, nil)
	rec := httptest.NewRecorder()
	router.ServeHTTP(rec, req)
	return rec
}

func doPOST(t *testing.T, router http.Handler, path string, body any) *httptest.ResponseRecorder {
	t.Helper()
	b, err := json.Marshal(body)
	if err != nil {
		t.Fatalf("marshal POST body: %v", err)
	}
	req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(b))
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()
	router.ServeHTTP(rec, req)
	return rec
}

func doPUT(t *testing.T, router http.Handler, path string, body any) *httptest.ResponseRecorder {
	t.Helper()
	b, err := json.Marshal(body)
	if err != nil {
		t.Fatalf("marshal PUT body: %v", err)
	}
	req := httptest.NewRequest(http.MethodPut, path, bytes.NewReader(b))
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()
	router.ServeHTTP(rec, req)
	return rec
}

func doDELETE(t *testing.T, router http.Handler, path string) *httptest.ResponseRecorder {
	t.Helper()
	req := httptest.NewRequest(http.MethodDelete, path, nil)
	rec := httptest.NewRecorder()
	router.ServeHTTP(rec, req)
	return rec
}

// TestHandler_List_Authenticated verifies GET /saved-searches returns 200
// with { saved_searches: [] } when no rows exist.
func TestHandler_List_Authenticated(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec := doGET(t, router, "/api/v1/saved-searches")
	if rec.Code != http.StatusOK {
		t.Fatalf("status=%d; want 200; body=%s", rec.Code, rec.Body.String())
	}
	var body savedSearchListBody
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("unmarshal: %v (body=%s)", err, rec.Body.String())
	}
	if body.SavedSearches == nil {
		t.Fatal("saved_searches key missing or null")
	}
	if len(body.SavedSearches) != 0 {
		t.Fatalf("expected empty list; got %d items", len(body.SavedSearches))
	}
}

// TestHandler_List_OwnerParamIgnored verifies that ?owner= is silently ignored
// (IV2) and the response is identical to a call without the param.
func TestHandler_List_OwnerParamIgnored(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec1 := doGET(t, router, "/api/v1/saved-searches")
	rec2 := doGET(t, router, "/api/v1/saved-searches?owner=alice")

	if rec1.Code != http.StatusOK || rec2.Code != http.StatusOK {
		t.Fatalf("status1=%d status2=%d; both want 200", rec1.Code, rec2.Code)
	}
	if rec1.Body.String() != rec2.Body.String() {
		t.Fatalf("bodies differ:\n  no-param: %s\n  with-param: %s",
			rec1.Body.String(), rec2.Body.String())
	}
}

// TestHandler_List_OwnerFieldAbsentInJSON verifies that Owner field is not
// present in the JSON output (json:"-").
func TestHandler_List_OwnerFieldAbsentInJSON(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	// Create a row first.
	doPOST(t, router, "/api/v1/saved-searches", map[string]string{"name": "test", "query": "q"})

	rec := doGET(t, router, "/api/v1/saved-searches")
	if rec.Code != http.StatusOK {
		t.Fatalf("status=%d; want 200; body=%s", rec.Code, rec.Body.String())
	}
	bodyStr := rec.Body.String()
	if strings.Contains(bodyStr, `"owner"`) {
		t.Fatalf("owner field should be absent in JSON; body=%s", bodyStr)
	}
}

// TestHandler_Create_EmptyNameReturns400 verifies validation of empty name.
func TestHandler_Create_EmptyNameReturns400(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec := doPOST(t, router, "/api/v1/saved-searches", map[string]string{"name": "", "query": "x"})
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("status=%d; want 400; body=%s", rec.Code, rec.Body.String())
	}
	var p problemBody
	_ = json.Unmarshal(rec.Body.Bytes(), &p)
	if p.Code != "VALIDATION" {
		t.Fatalf("expected VALIDATION; got %q (body=%s)", p.Code, rec.Body.String())
	}
}

// TestHandler_Create_SlashInNameReturns400 verifies that a name with "/" is
// rejected (IV7).
func TestHandler_Create_SlashInNameReturns400(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec := doPOST(t, router, "/api/v1/saved-searches", map[string]string{"name": "a/b", "query": "x"})
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("status=%d; want 400; body=%s", rec.Code, rec.Body.String())
	}
	var p problemBody
	_ = json.Unmarshal(rec.Body.Bytes(), &p)
	if p.Code != "VALIDATION" {
		t.Fatalf("expected VALIDATION; got %q (body=%s)", p.Code, rec.Body.String())
	}
}

// TestHandler_Create_NameTooLongReturns400 verifies the 64-char cap (UK1).
func TestHandler_Create_NameTooLongReturns400(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	longName := strings.Repeat("a", 65)
	rec := doPOST(t, router, "/api/v1/saved-searches", map[string]string{"name": longName, "query": "x"})
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("status=%d; want 400; body=%s", rec.Code, rec.Body.String())
	}
	var p problemBody
	_ = json.Unmarshal(rec.Body.Bytes(), &p)
	if p.Code != "VALIDATION" {
		t.Fatalf("expected VALIDATION; got %q (body=%s)", p.Code, rec.Body.String())
	}
}

// TestHandler_Create_EmptyQueryReturns400 verifies that an empty query is
// rejected.
func TestHandler_Create_EmptyQueryReturns400(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec := doPOST(t, router, "/api/v1/saved-searches", map[string]string{"name": "ok", "query": ""})
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("status=%d; want 400; body=%s", rec.Code, rec.Body.String())
	}
	var p problemBody
	_ = json.Unmarshal(rec.Body.Bytes(), &p)
	if p.Code != "VALIDATION" {
		t.Fatalf("expected VALIDATION; got %q (body=%s)", p.Code, rec.Body.String())
	}
}

// TestHandler_Create_Valid verifies that a valid POST returns 201 with the new row.
func TestHandler_Create_Valid(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec := doPOST(t, router, "/api/v1/saved-searches", map[string]string{"name": "mysearch", "query": "model:gpt-4"})
	if rec.Code != http.StatusCreated {
		t.Fatalf("status=%d; want 201; body=%s", rec.Code, rec.Body.String())
	}
	var got savedsearch.SavedSearch
	if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
		t.Fatalf("unmarshal: %v (body=%s)", err, rec.Body.String())
	}
	if got.Name != "mysearch" {
		t.Errorf("Name: got %q; want %q", got.Name, "mysearch")
	}
	if got.Query != "model:gpt-4" {
		t.Errorf("Query: got %q; want %q", got.Query, "model:gpt-4")
	}
}

// TestHandler_Create_DuplicateReturns409 verifies that a duplicate name for the
// same owner returns 409 CONFLICT with problem+json.
func TestHandler_Create_DuplicateReturns409(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	doPOST(t, router, "/api/v1/saved-searches", map[string]string{"name": "x", "query": "q1"})
	rec := doPOST(t, router, "/api/v1/saved-searches", map[string]string{"name": "x", "query": "q2"})
	if rec.Code != http.StatusConflict {
		t.Fatalf("status=%d; want 409; body=%s", rec.Code, rec.Body.String())
	}
	var p problemBody
	_ = json.Unmarshal(rec.Body.Bytes(), &p)
	if p.Code != "CONFLICT" {
		t.Fatalf("expected CONFLICT; got %q (body=%s)", p.Code, rec.Body.String())
	}
	// Verify content-type is problem+json.
	ct := rec.Header().Get("Content-Type")
	if !strings.Contains(ct, "application/problem+json") {
		t.Fatalf("expected application/problem+json; got %q", ct)
	}
}

// TestHandler_Update_NotFound verifies that PUT /saved-searches/missing returns 404.
func TestHandler_Update_NotFound(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec := doPUT(t, router, "/api/v1/saved-searches/missing", map[string]*string{"query": ptrStr("new")})
	if rec.Code != http.StatusNotFound {
		t.Fatalf("status=%d; want 404; body=%s", rec.Code, rec.Body.String())
	}
	var p problemBody
	_ = json.Unmarshal(rec.Body.Bytes(), &p)
	if p.Code != "NOT_FOUND" {
		t.Fatalf("expected NOT_FOUND; got %q (body=%s)", p.Code, rec.Body.String())
	}
}

// TestHandler_Update_RenameConflict verifies that renaming onto an existing name
// for the same owner returns 409 CONFLICT.
func TestHandler_Update_RenameConflict(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	doPOST(t, router, "/api/v1/saved-searches", map[string]string{"name": "x", "query": "q1"})
	doPOST(t, router, "/api/v1/saved-searches", map[string]string{"name": "y", "query": "q2"})

	rec := doPUT(t, router, "/api/v1/saved-searches/x", map[string]*string{"name": ptrStr("y")})
	if rec.Code != http.StatusConflict {
		t.Fatalf("status=%d; want 409; body=%s", rec.Code, rec.Body.String())
	}
	var p problemBody
	_ = json.Unmarshal(rec.Body.Bytes(), &p)
	if p.Code != "CONFLICT" {
		t.Fatalf("expected CONFLICT; got %q (body=%s)", p.Code, rec.Body.String())
	}
}

// TestHandler_Delete_Sequence verifies 204 on first delete and 404 on second.
func TestHandler_Delete_Sequence(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	// Create a row first.
	doPOST(t, router, "/api/v1/saved-searches", map[string]string{"name": "todel", "query": "q"})

	rec1 := doDELETE(t, router, "/api/v1/saved-searches/todel")
	if rec1.Code != http.StatusNoContent {
		t.Fatalf("first delete: status=%d; want 204; body=%s", rec1.Code, rec1.Body.String())
	}

	rec2 := doDELETE(t, router, "/api/v1/saved-searches/todel")
	if rec2.Code != http.StatusNotFound {
		t.Fatalf("second delete: status=%d; want 404; body=%s", rec2.Code, rec2.Body.String())
	}
	var p problemBody
	_ = json.Unmarshal(rec2.Body.Bytes(), &p)
	if p.Code != "NOT_FOUND" {
		t.Fatalf("expected NOT_FOUND; got %q", p.Code)
	}
}

// TestHandler_WritePaths_OwnerParamRejected verifies IV2 — every write path
// (POST/PUT/DELETE) returns 400 INVALID when ?owner= is set, regardless of
// the value. Owner derivation is exclusively from the auth identity.
func TestHandler_WritePaths_OwnerParamRejected(t *testing.T) {
	h := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	// Seed a row so the PUT/DELETE paths have a target name.
	doPOST(t, router, "/api/v1/saved-searches", map[string]string{"name": "x", "query": "q"})

	cases := []struct {
		name string
		send func() *httptest.ResponseRecorder
	}{
		{"POST", func() *httptest.ResponseRecorder {
			return doPOST(t, router, "/api/v1/saved-searches?owner=alice", map[string]string{"name": "y", "query": "q"})
		}},
		{"PUT", func() *httptest.ResponseRecorder {
			return doPUT(t, router, "/api/v1/saved-searches/x?owner=bob", map[string]*string{"query": ptrStr("q2")})
		}},
		{"DELETE", func() *httptest.ResponseRecorder {
			return doDELETE(t, router, "/api/v1/saved-searches/x?owner=*")
		}},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			rec := tc.send()
			if rec.Code != http.StatusBadRequest {
				t.Fatalf("status=%d; want 400; body=%s", rec.Code, rec.Body.String())
			}
			var p problemBody
			_ = json.Unmarshal(rec.Body.Bytes(), &p)
			if p.Code != "INVALID" {
				t.Fatalf("expected INVALID; got %q (body=%s)", p.Code, rec.Body.String())
			}
		})
	}
}