~bigbes/lethe

ref: 8aeda698dc352ac3d1e93b667f56ad5dbd68d8b9 lethe/internal/domain/search/handler_test.go -rw-r--r-- 8.8 KiB
8aeda698 — Eugene Blikh feat: add search UI layer — SearchTable, SearchFilters, SaveSearchForm, route, and styles 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
package search_test

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

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

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

// fakeAuthMiddleware injects a fixed Identity onto the request context.
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 Repository against a fresh in-memory database and
// returns the Handler.
func newHandler(t *testing.T) (*search.Handler, *search.Repository) {
	t.Helper()
	repo, _ := newRepo(t)
	h := &search.Handler{Repo: repo}
	if err := h.Init(context.Background()); err != nil {
		t.Fatalf("handler.Init: %v", err)
	}
	return h, repo
}

// mountWithIdentity builds a chi router with fake auth and the search handler.
func mountWithIdentity(h *search.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
}

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

// doSearch performs GET /api/v1/search with the given query string.
func doSearch(t *testing.T, router http.Handler, query string) (*httptest.ResponseRecorder, search.Result) {
	t.Helper()
	req := httptest.NewRequest(http.MethodGet, "/api/v1/search", nil)
	if query != "" {
		req.URL.RawQuery = query[1:] // strip leading '?'
	}
	rec := httptest.NewRecorder()
	router.ServeHTTP(rec, req)
	var body search.Result
	if rec.Code == http.StatusOK {
		if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
			t.Fatalf("unmarshal search body: %v (body=%s)", err, rec.Body.String())
		}
	}
	return rec, body
}

func TestHandler_Mount_RegistersSearchRoute(t *testing.T) {
	h, _ := newHandler(t)
	router := chi.NewRouter()
	router.Route("/api/v1", func(r chi.Router) {
		r.Use(fakeAuthMiddleware(auth.Identity{User: "alice"}))
		h.Mount(r)
	})

	found := false
	_ = chi.Walk(router, func(method, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
		if method == http.MethodGet && route == "/api/v1/search" {
			found = true
		}
		return nil
	})
	if !found {
		t.Fatal("expected GET /api/v1/search registered")
	}
}

func TestHandler_MissingQueryReturns400(t *testing.T) {
	h, _ := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec, _ := doSearch(t, router, "")
	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", p.Code)
	}
}

func TestHandler_EmptyQueryReturns400(t *testing.T) {
	h, _ := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec, _ := doSearch(t, router, "?q=   ")
	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", p.Code)
	}
}

func TestHandler_BadSinceReturns400(t *testing.T) {
	h, _ := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec, _ := doSearch(t, router, "?q=hello&since=not-a-number")
	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", p.Code)
	}
}

func TestHandler_NonAdminOwnerParamReturns403(t *testing.T) {
	h, _ := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice", IsAdmin: false})

	for _, q := range []string{"?q=hello&owner=alice", "?q=hello&owner=bob", "?q=hello&owner=*"} {
		rec, _ := doSearch(t, router, q)
		if rec.Code != http.StatusForbidden {
			t.Fatalf("query %q: status=%d; want 403; body=%s", q, rec.Code, rec.Body.String())
		}
		var p problemBody
		_ = json.Unmarshal(rec.Body.Bytes(), &p)
		if p.Code != "FORBIDDEN" {
			t.Fatalf("query %q: code=%q; want FORBIDDEN", q, p.Code)
		}
	}
}

func TestHandler_AdminOwnerStarReturnsAllOwners(t *testing.T) {
	h, repo := newHandler(t)
	db := repo.Database.DB
	seedSession(t, db, "alice", "cc", "phoebe", "sa", 100, 110)
	seedTurn(t, db, "alice", "cc", "phoebe", "sa", "t1", 1, 101, "user", "needle alpha", nil)
	seedSession(t, db, "bob", "cc", "phoebe", "sb", 100, 110)
	seedTurn(t, db, "bob", "cc", "phoebe", "sb", "t1", 1, 101, "user", "needle beta", nil)

	router := mountWithIdentity(h, auth.Identity{User: "admin", IsAdmin: true})

	rec, body := doSearch(t, router, "?q=needle&owner=*")
	if rec.Code != http.StatusOK {
		t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
	}
	if len(body.Results) != 2 {
		t.Fatalf("expected 2 rows; got %d (%#v)", len(body.Results), body.Results)
	}
}

func TestHandler_BadCursorReturns400(t *testing.T) {
	h, _ := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec, _ := doSearch(t, router, "?q=hello&cursor=not-valid")
	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", p.Code)
	}
}

func TestHandler_SuccessfulResponseEnvelope(t *testing.T) {
	h, repo := newHandler(t)
	db := repo.Database.DB
	seedSession(t, db, "alice", "cc", "phoebe", "s1", 100, 110)
	seedTurn(t, db, "alice", "cc", "phoebe", "s1", "t1", 1, 101, "user", "needle in haystack", nil)

	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec, body := doSearch(t, router, "?q=needle&limit=10")
	if rec.Code != http.StatusOK {
		t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
	}
	if body.Limit != 10 {
		t.Fatalf("limit=%d; want 10", body.Limit)
	}
	if len(body.Results) != 1 {
		t.Fatalf("expected 1 result; got %d (%#v)", len(body.Results), body.Results)
	}
	if body.Results[0].SessionID != "s1" {
		t.Fatalf("expected session s1; got %#v", body.Results[0])
	}
	// NextCursor should be empty when results fit in one page.
	if body.NextCursor != "" {
		t.Fatalf("expected empty next_cursor for single page; got %q", body.NextCursor)
	}
}

func TestHandler_LimitClamping(t *testing.T) {
	h, _ := newHandler(t)
	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	// Missing limit → default 50
	rec, body := doSearch(t, router, "?q=hello")
	if rec.Code != http.StatusOK {
		t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
	}
	if body.Limit != 50 {
		t.Fatalf("default limit=%d; want 50", body.Limit)
	}

	// Over max → capped at 200
	rec, body = doSearch(t, router, "?q=hello&limit=999")
	if rec.Code != http.StatusOK {
		t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
	}
	if body.Limit != 200 {
		t.Fatalf("capped limit=%d; want 200", body.Limit)
	}
}

func TestHandler_IncludeToolOutputsParam(t *testing.T) {
	h, repo := newHandler(t)
	db := repo.Database.DB
	seedSession(t, db, "alice", "cc", "phoebe", "s1", 100, 110)
	seedTurn(t, db, "alice", "cc", "phoebe", "s1", "prose", 1, 101, "user", "needle in prose", nil)
	seedTurn(t, db, "alice", "cc", "phoebe", "s1", "tool", 2, 102, "assistant", "plain text", strptr(`{"output":"needle in shell"}`))

	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	// Default: prose only
	rec, body := doSearch(t, router, "?q=needle")
	if rec.Code != http.StatusOK {
		t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
	}
	if len(body.Results) != 1 || body.Results[0].MatchSource != search.SourceTurn {
		t.Fatalf("expected 1 prose result; got %#v", body.Results)
	}

	// Explicit include
	rec, body = doSearch(t, router, "?q=needle&include_tool_outputs=1")
	if rec.Code != http.StatusOK {
		t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
	}
	if len(body.Results) != 2 {
		t.Fatalf("expected 2 results; got %#v", body.Results)
	}
}

func TestHandler_PerUserIsolation(t *testing.T) {
	h, repo := newHandler(t)
	db := repo.Database.DB
	seedSession(t, db, "alice", "cc", "phoebe", "sa", 100, 110)
	seedTurn(t, db, "alice", "cc", "phoebe", "sa", "t1", 1, 101, "user", "alice needle", nil)
	seedSession(t, db, "bob", "cc", "phoebe", "sb", 100, 110)
	seedTurn(t, db, "bob", "cc", "phoebe", "sb", "t1", 1, 101, "user", "bob needle", nil)

	router := mountWithIdentity(h, auth.Identity{User: "alice"})

	rec, body := doSearch(t, router, "?q=needle")
	if rec.Code != http.StatusOK {
		t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
	}
	if len(body.Results) != 1 || body.Results[0].Owner != "alice" {
		t.Fatalf("alice should see only her row; got %#v", body.Results)
	}
}