package web import ( "bytes" "context" "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "strings" "testing" "time" "supermarket/internal/bridge" "supermarket/internal/content" "supermarket/internal/core" "supermarket/internal/db" "supermarket/internal/inventory" "supermarket/internal/mcpserver" "supermarket/internal/models" "supermarket/internal/profile" "supermarket/internal/secrets" ) const testToken = "0123456789abcdef0123456789abcdef" func newTestServer(t *testing.T, c *core.Core) (*Server, http.Handler) { t.Helper() dir := t.TempDir() d, err := db.Open(filepath.Join(dir, "app.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) sec, err := secrets.Open(filepath.Join(dir, "secrets.json")) if err != nil { t.Fatal(err) } s := &Server{ DB: d, Secrets: sec, Core: c, DataDir: dir, PublicURL: "http://localhost:8470", Version: "test", MCPToken: testToken, MCP: mcpserver.Handler(d, testToken, "test"), Log: slog.New(slog.NewTextHandler(io.Discard, nil)), } h, err := s.Handler() if err != nil { t.Fatal(err) } return s, h } func do(h http.Handler, method, target string, body io.Reader, hdr map[string]string) *httptest.ResponseRecorder { req := httptest.NewRequest(method, target, body) req.Host = "localhost:8470" for k, v := range hdr { req.Header.Set(k, v) } rec := httptest.NewRecorder() h.ServeHTTP(rec, req) return rec } func postForm(h http.Handler, target string, form url.Values) *httptest.ResponseRecorder { return do(h, http.MethodPost, target, strings.NewReader(form.Encode()), map[string]string{ "Content-Type": "application/x-www-form-urlencoded", "Origin": "http://localhost:8470", }) } func TestEveryPageRenders(t *testing.T) { for _, c := range []*core.Core{nil, {Domain: "example.com", Email: "pat@example.com", Name: "Pat"}} { s, h := newTestServer(t, c) // Some data, so templates' non-empty branches run too. if err := profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Products: []profile.Product{{Name: "Widget", Benefits: []string{"fast"}}}, Websites: []profile.Website{{URL: "https://acme.example", Repo: "r"}}}); err != nil { t.Fatal(err) } e := &inventory.Entry{Name: "Rival", Relationship: "competitor", Hashtags: []string{"rival"}} if err := inventory.Save(s.DB, e); err != nil { t.Fatal(err) } if err := bridge.Record(s.DB, bridge.Checkin{Agent: "hermes", MCPHubTools: []string{"espocrm_create_lead"}}); err != nil { t.Fatal(err) } if err := s.Secrets.Set(map[string]string{secrets.XAccessToken: "tok"}); err != nil { t.Fatal(err) } for _, path := range []string{"/", "/?msg=saved", "/settings/profile", "/inventory", "/inventory?relationship=partner", "/inventory/new", "/inventory/1", "/inventory/import", "/inventory/export", "/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/search", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz", "/content", "/content/1", "/content/1?dismissed=1", "/inbox", "/inbox?msg=drafted", "/content/scheduled", "/content/published"} { rec := do(h, http.MethodGet, path, nil, nil) if rec.Code != http.StatusOK { t.Errorf("core=%v GET %s: %d %s", c != nil, path, rec.Code, rec.Body.String()) } } if rec := do(h, http.MethodGet, "/inventory/999", nil, nil); rec.Code != http.StatusNotFound { t.Errorf("missing entry: %d", rec.Code) } } } func TestGuardRejectsForeignHostsAndCrossSitePosts(t *testing.T) { _, h := newTestServer(t, nil) req := httptest.NewRequest(http.MethodGet, "/", nil) req.Host = "evil.example:8470" // DNS rebinding rec := httptest.NewRecorder() h.ServeHTTP(rec, req) if rec.Code != http.StatusMisdirectedRequest { t.Errorf("foreign Host: got %d", rec.Code) } form := url.Values{"name": {"Acme"}, "description": {"x"}} rec = do(h, http.MethodPost, "/settings/profile", strings.NewReader(form.Encode()), map[string]string{ "Content-Type": "application/x-www-form-urlencoded", "Origin": "https://evil.example", }) if rec.Code != http.StatusForbidden { t.Errorf("cross-origin POST: got %d", rec.Code) } rec = do(h, http.MethodPost, "/settings/profile", strings.NewReader(form.Encode()), map[string]string{ "Content-Type": "application/x-www-form-urlencoded", "Sec-Fetch-Site": "cross-site", }) if rec.Code != http.StatusForbidden { t.Errorf("cross-site POST without Origin: got %d", rec.Code) } if rec := postForm(h, "/settings/profile", form); rec.Code != http.StatusSeeOther { t.Errorf("same-origin POST: got %d %s", rec.Code, rec.Body.String()) } } func TestProfileAndInventoryForms(t *testing.T) { s, h := newTestServer(t, nil) form := url.Values{ "name": {" Acme "}, "description": {"We make widgets."}, "keywords": {"widgets\n\nwidget software\nWidgets"}, "product_name": {"Widget", ""}, "product_url": {"https://a.example/w", ""}, "product_description": {"A widget", ""}, "product_pricing": {"$5", ""}, "product_benefits": {"cheap\nfast", ""}, "website_url": {"https://acme.example/", ""}, "website_repo": {"https://gitea.example/acme/site.git", ""}, "website_branch": {"", ""}, "website_plausible": {"", ""}, "website_gsc": {"", ""}, "website_bing": {"", ""}, "account_x": {"@acme"}, "subreddits": {"r/selfhosted\n/r/homelab"}, } if rec := postForm(h, "/settings/profile", form); rec.Code != http.StatusSeeOther { t.Fatalf("save profile: %d %s", rec.Code, rec.Body.String()) } p, _ := profile.Load(s.DB) if p.Name != "Acme" || len(p.Products) != 1 || len(p.Products[0].Benefits) != 2 { t.Errorf("profile products: %+v", p) } if len(p.Keywords) != 2 { t.Errorf("keywords should be de-duplicated case-insensitively: %q", p.Keywords) } if len(p.Websites) != 1 || p.Websites[0].URL != "https://acme.example" || p.Websites[0].Branch != "main" { t.Errorf("websites: %+v", p.Websites) } if p.Accounts.X != "acme" || strings.Join(p.Accounts.Subreddits, ",") != "selfhosted,homelab" { t.Errorf("accounts: %+v", p.Accounts) } // Missing description: the form comes back with an error, nothing saved. rec := postForm(h, "/settings/profile", url.Values{"name": {"Other"}}) if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "required") { t.Errorf("invalid profile: %d", rec.Code) } entry := url.Values{"name": {"Rival"}, "relationship": {"competitor"}, "hashtags": {"rival, #Other"}, "twitter_handle": {"@rival"}} if rec := postForm(h, "/inventory/save", entry); rec.Code != http.StatusSeeOther { t.Fatalf("save entry: %d %s", rec.Code, rec.Body.String()) } entries, _ := inventory.List(s.DB, "competitor") if len(entries) != 1 || entries[0].TwitterHandle != "rival" || entries[0].MentionPolicy != "category" || strings.Join(entries[0].Hashtags, " ") != "#rival #Other" { t.Fatalf("entry: %+v", entries) } // Same name, different case: refused. rec = postForm(h, "/inventory/save", url.Values{"name": {"RIVAL"}, "relationship": {"partner"}}) if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "already has that name") { t.Errorf("duplicate: %d", rec.Code) } rec = postForm(h, "/inventory/import", url.Values{"example": {"federated"}, "relationship": {"watch"}}) if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "21 added") { t.Errorf("import example: %d %s", rec.Code, rec.Body.String()) } partners, _ := inventory.List(s.DB, "partner") if len(partners) != 21 { t.Errorf("example entries are partners: got %d", len(partners)) } if rec := postForm(h, "/inventory/1/delete", nil); rec.Code != http.StatusSeeOther { t.Errorf("delete: %d", rec.Code) } } func TestAccountsKeepAndRemove(t *testing.T) { s, h := newTestServer(t, nil) postForm(h, "/settings/accounts", url.Values{secrets.XClientID: {" id-1 "}, secrets.YouTubeAPIKey: {"yt"}}) // Empty field keeps the value; remove clears it. postForm(h, "/settings/accounts", url.Values{secrets.XClientID: {""}, "remove:" + secrets.YouTubeAPIKey: {"on"}}) if got := s.Secrets.Get(secrets.XClientID); got != "id-1" { t.Errorf("x client id = %q", got) } if s.Secrets.Has(secrets.YouTubeAPIKey) { t.Error("youtube key should be removed") } // The AI keys aren't on this tab, so it can't change them. postForm(h, "/settings/accounts", url.Values{secrets.AnthropicAPIKey: {"sk-x"}}) if s.Secrets.Has(secrets.AnthropicAPIKey) { t.Error("the accounts form saved an AI key") } // From the page, a save sends back just that card, updated, not a redirect. rec := do(h, http.MethodPost, "/settings/accounts", strings.NewReader(url.Values{ "network": {"LinkedIn"}, secrets.LinkedInClientID: {"li"}, secrets.LinkedInClientSecret: {"ls"}}.Encode()), map[string]string{"Content-Type": "application/x-www-form-urlencoded", "Origin": "http://localhost:8470", "HX-Request": "true"}) card := rec.Body.String() if rec.Code != http.StatusOK || !strings.Contains(card, `id="network-LinkedIn"`) || strings.Contains(card, "set up the AI`) { t.Error("new entry without AI: no warning") } // The form comes back with what was typed, and says why. rec := postForm(h, "/inventory/fill", url.Values{"name": {"Rival"}, "relationship": {"competitor"}, "description": {"Typed."}, "draft_url": {"https://rival.example"}}) body := rec.Body.String() if rec.Code != http.StatusOK || !strings.Contains(body, "AI provider not configured") || !strings.Contains(body, "Typed.") { t.Errorf("fill without AI: %d", rec.Code) } rec = postForm(h, "/inventory/fill", url.Values{"name": {"Rival"}}) if !strings.Contains(rec.Body.String(), "Enter their website") { t.Error("fill without a website: no message") } } func TestProfileDraftNeedsAI(t *testing.T) { s, h := newTestServer(t, nil) body := do(h, http.MethodGet, "/settings/profile", nil, nil).Body.String() if !strings.Contains(body, `choose an AI provider`) || !strings.Contains(body, `class="secondary" disabled>Draft`) { t.Errorf("profile without AI:\n%s", body) } _ = s.Secrets.Set(map[string]string{secrets.AnthropicAPIKey: "k"}) if body := do(h, http.MethodGet, "/settings/profile", nil, nil).Body.String(); strings.Contains(body, "choose an AI provider") { t.Error("warning shown with an AI key saved") } } func TestLinkedInExpiryReminders(t *testing.T) { s, h := newTestServer(t, nil) _ = s.Secrets.Set(map[string]string{secrets.LinkedInAccessToken: "tok", secrets.LinkedInAuthorURN: "urn:li:person:1"}) day := 24 * time.Hour get := func(path string) string { return do(h, http.MethodGet, path, nil, nil).Body.String() } // Plenty of time: the card says until when, no reminders. _ = s.saveConnection("linkedin", Connection{At: time.Now(), Expires: time.Now().Add(50 * day)}) if !strings.Contains(get("/settings/accounts"), "The sign-in lasts until") || strings.Contains(get("/"), "Reconnect LinkedIn") { t.Error("50 days left: wrong reminders") } if !s.connected()["linkedin"] { t.Error("50 days left: should be connected") } // Saved before expiries were recorded, 50 days ago: 10 days left. _ = s.saveConnection("linkedin", Connection{At: time.Now().Add(-50 * day)}) for _, path := range []string{"/", "/inbox"} { if body := get(path); !strings.Contains(body, "LinkedIn's sign-in expires in 9 days") && !strings.Contains(body, "LinkedIn's sign-in expires in 10 days") { t.Errorf("%s: no 10-day reminder", path) } } // Expired: reminders, not connected, and publishing says why. _ = s.saveConnection("linkedin", Connection{At: time.Now().Add(-61 * day), Expires: time.Now().Add(-day)}) if body := get("/"); !strings.Contains(body, "LinkedIn's sign-in expired on") { t.Error("expired: no reminder on the Overview") } if !strings.Contains(get("/settings/accounts"), "The sign-in expired on") { t.Error("expired: the card doesn't say so") } if s.connected()["linkedin"] { t.Error("expired: still counted as connected") } if _, err := s.publishers()["linkedin"].Publish(context.Background(), content.Post{Text: "hi"}); err == nil || !strings.Contains(err.Error(), "reconnect LinkedIn") { t.Errorf("expired publish: %v", err) } }