package handlers import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "path/filepath" "strings" "testing" "adam-french.co.uk/job-tracker/internal/claude" "adam-french.co.uk/job-tracker/internal/services" "github.com/gin-gonic/gin" ) // The capture handlers themselves need a database, and the only driver in // go.mod is postgres, so what is covered here is everything around the // queries: the token gate, the URL key that decides whether a posting is // already tracked, the merge rule for a repeat capture, and the extract // route around the posting reader. func TestCaptureTokenMiddleware(t *testing.T) { gin.SetMode(gin.TestMode) serve := func(store *Store, header string) int { r := gin.New() r.GET("/x", store.CaptureTokenMiddleware, func(ctx *gin.Context) { ctx.Status(http.StatusOK) }) req := httptest.NewRequest(http.MethodGet, "/x", nil) if header != "" { req.Header.Set("Authorization", header) } rec := httptest.NewRecorder() r.ServeHTTP(rec, req) return rec.Code } newToken := func() *services.CaptureToken { tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json")) if err != nil { t.Fatalf("InitCaptureToken: %v", err) } return tok } // The case the middleware exists to get right: with no token generated, // a request presenting nothing (or an empty bearer) must not get in. t.Run("no token generated switches the routes off", func(t *testing.T) { store := &Store{CaptureToken: newToken()} for _, header := range []string{"", "Bearer ", "Bearer anything"} { if got := serve(store, header); got != http.StatusServiceUnavailable { t.Fatalf("header %q: status = %d, want 503", header, got) } } }) t.Run("a store built without the token service is off too", func(t *testing.T) { if got := serve(&Store{}, "Bearer x"); got != http.StatusServiceUnavailable { t.Fatalf("status = %d, want 503", got) } }) store := &Store{CaptureToken: newToken()} token, _, err := store.CaptureToken.Generate() if err != nil { t.Fatalf("Generate: %v", err) } cases := []struct { name string header string want int }{ {"the generated token is let through", "Bearer " + token, http.StatusOK}, {"a wrong token is refused", "Bearer nope", http.StatusUnauthorized}, {"no header is refused", "", http.StatusUnauthorized}, {"the bare token without the scheme is refused", token, http.StatusUnauthorized}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { if got := serve(store, c.header); got != c.want { t.Fatalf("status = %d, want %d", got, c.want) } }) } } // The admin endpoints, driven without the admin middleware (covered // elsewhere): generate shows the token once, status never does, and a second // generate or a revoke stops the first token working. func TestCaptureTokenAdminEndpoints(t *testing.T) { gin.SetMode(gin.TestMode) tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json")) if err != nil { t.Fatalf("InitCaptureToken: %v", err) } store := &Store{CaptureToken: tok} r := gin.New() r.GET("/t", store.GetCaptureToken) r.POST("/t", store.GenerateCaptureToken) r.DELETE("/t", store.RevokeCaptureToken) call := func(method string) (map[string]any, *httptest.ResponseRecorder) { rec := httptest.NewRecorder() r.ServeHTTP(rec, httptest.NewRequest(method, "/t", nil)) if rec.Code != http.StatusOK { t.Fatalf("%s: status = %d, body = %s", method, rec.Code, rec.Body) } var out map[string]any json.Unmarshal(rec.Body.Bytes(), &out) return out, rec } if out, _ := call(http.MethodGet); out["set"] != false { t.Fatalf("fresh status = %v", out) } out, rec := call(http.MethodPost) first, _ := out["token"].(string) if !tok.Verify(first) { t.Fatalf("generated token %q does not verify", first) } if rec.Header().Get("Cache-Control") != "no-store" { t.Fatal("the response carrying the token must not be cacheable") } out, _ = call(http.MethodGet) if out["set"] != true || out["createdAt"] == nil { t.Fatalf("status after generate = %v", out) } if _, leaked := out["token"]; leaked { t.Fatal("status must never return the token") } call(http.MethodPost) if tok.Verify(first) { t.Fatal("regenerating must invalidate the previous token") } if out, _ := call(http.MethodDelete); out["set"] != false { t.Fatalf("status after revoke = %v", out) } } // fakeExtractor answers every page with posting and err, recording the // arguments it was called with. type fakeExtractor struct { posting claude.JobPosting err error got []string } func (f *fakeExtractor) ExtractPosting(_ context.Context, url, title, text string) (claude.JobPosting, error) { f.got = []string{url, title, text} return f.posting, f.err } func extractRoute(f *fakeExtractor) func(body string) *httptest.ResponseRecorder { gin.SetMode(gin.TestMode) store := &Store{Extractor: f} r := gin.New() r.POST("/extract", store.JobCaptureExtract) return func(body string) *httptest.ResponseRecorder { rec := httptest.NewRecorder() r.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/extract", strings.NewReader(body))) return rec } } // Claude's own failure messages are worded for the popup and are relayed; // anything else (no API key, say) is logged and replaced. func TestJobCaptureExtractErrors(t *testing.T) { cases := []struct { name string err error want string }{ {"extractor failure is relayed", &claude.ReadError{Msg: "failed to parse the posting"}, "failed to parse the posting"}, {"missing key is not relayed", claude.ErrNotConfigured, "failed to read the page"}, {"anything else is not relayed", errors.New("boom"), "failed to read the page"}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { rec := extractRoute(&fakeExtractor{err: c.err})(`{"url": "https://x.com/1", "title": "t", "text": "page"}`) var body map[string]string json.Unmarshal(rec.Body.Bytes(), &body) if rec.Code != http.StatusBadGateway || body["error"] != c.want { t.Fatalf("status = %d, body = %s; want 502 %q", rec.Code, rec.Body, c.want) } }) } } // The extract handler runs without a database, so it can be driven whole: the // page text must be cut to maxPageRunes before it is sent to Claude. func TestJobCaptureExtractTruncatesAndRelays(t *testing.T) { london := "London" f := &fakeExtractor{posting: claude.JobPosting{JobTitle: "Engineer", Company: "Acme", Location: &london}} post := extractRoute(f) long, _ := json.Marshal(map[string]string{"url": "https://x.com/1", "title": "Engineer | Acme", "text": strings.Repeat("é", maxPageRunes+500)}) rec := post(string(long)) if rec.Code != http.StatusOK { t.Fatalf("status = %d, body = %s", rec.Code, rec.Body) } if f.got[0] != "https://x.com/1" || f.got[1] != "Engineer | Acme" { t.Fatalf("hints passed as %q", f.got[:2]) } if n := len([]rune(f.got[2])); n != maxPageRunes { t.Fatalf("forwarded %d runes, want %d", n, maxPageRunes) } // The body is the userscript's contract: these four keys. if rec.Body.String() != `{"jobTitle":"Engineer","company":"Acme","location":"London","notes":null}` { t.Fatalf("body = %s", rec.Body) } if rec := post(`{"url": "https://x.com/1", "text": " "}`); rec.Code != http.StatusBadRequest { t.Fatalf("blank text: status = %d", rec.Code) } if rec := post(`not json`); rec.Code != http.StatusBadRequest { t.Fatalf("bad body: status = %d", rec.Code) } }