On the entry form, "Fill in the empty boxes" reads their website. Links, social accounts and feeds come straight from the pages (no guessing); the AI drafts the name if missing, a description, keywords, hashtags, and talking points set against the company profile for the relationship chosen. Typed values stay, nothing is saved until Save, and the form says which boxes were filled. Website reading moves from the profile draft into internal/site, shared by both, and now also collects links and declared RSS/Atom feeds (comment feeds skipped; Fill takes up to three). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
359 lines
15 KiB
Go
359 lines
15 KiB
Go
package web
|
|
|
|
import (
|
|
"bytes"
|
|
"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", "/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")
|
|
}
|
|
page := do(h, http.MethodGet, "/settings/accounts", nil, nil).Body.String()
|
|
if strings.Contains(page, "id-1") {
|
|
t.Error("the accounts page must never show a saved value")
|
|
}
|
|
}
|
|
|
|
func TestAIKeysOnTheAITab(t *testing.T) {
|
|
s, h := newTestServer(t, nil)
|
|
form := url.Values{"provider": {"anthropic"}, "model": {"claude-opus-5-5"}, "effort": {"medium"},
|
|
secrets.AnthropicAPIKey: {" sk-1 "}}
|
|
if rec := postForm(h, "/settings/ai", form); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("save: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if got := s.Secrets.Get(secrets.AnthropicAPIKey); got != "sk-1" {
|
|
t.Errorf("anthropic key = %q", got)
|
|
}
|
|
// A form that needs fixing still keeps the key typed into it.
|
|
rec := postForm(h, "/settings/ai", url.Values{"provider": {"openai"}, "model": {"m"}, secrets.OpenAIAPIKey: {"ok-2"}})
|
|
if rec.Code != http.StatusOK || s.Secrets.Get(secrets.OpenAIAPIKey) != "ok-2" {
|
|
t.Errorf("openai without address: %d, key %q", rec.Code, s.Secrets.Get(secrets.OpenAIAPIKey))
|
|
}
|
|
postForm(h, "/settings/ai", url.Values{"provider": {"anthropic"}, "model": {"m"}, "remove:" + secrets.AnthropicAPIKey: {"on"}})
|
|
if s.Secrets.Has(secrets.AnthropicAPIKey) {
|
|
t.Error("anthropic key should be removed")
|
|
}
|
|
if page := do(h, http.MethodGet, "/settings/ai", nil, nil).Body.String(); strings.Contains(page, "ok-2") {
|
|
t.Error("the AI page must never show a saved key")
|
|
}
|
|
}
|
|
|
|
func TestOldAddressesRedirect(t *testing.T) {
|
|
_, h := newTestServer(t, nil)
|
|
for old, now := range map[string]string{"/profile": "/settings/profile", "/core": "/settings/core",
|
|
"/settings/credentials": "/settings/accounts", "/settings": "/settings/profile"} {
|
|
rec := do(h, http.MethodGet, old, nil, nil)
|
|
if rec.Code/100 != 3 || rec.Header().Get("Location") != now {
|
|
t.Errorf("%s: %d → %q", old, rec.Code, rec.Header().Get("Location"))
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSearch(t *testing.T) {
|
|
s, h := newTestServer(t, nil)
|
|
if err := inventory.Save(s.DB, &inventory.Entry{Name: "Rival Corp", Relationship: "competitor", Description: "Makes gadgets."}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := content.SaveItems(s.DB, []models.ContentItem{{ID: "rss:1", AppName: "Rival Corp", Source: models.SourceRSS,
|
|
Title: "Gadget 2 launches", Body: "Faster gadgets for everyone", PublishedAt: time.Now()}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := content.CreateDrafts(s.DB, []content.Draft{{InventoryName: "Rival Corp", Kind: "competitor",
|
|
Channel: "x", Content: "Our widgets beat any gadget"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
body := do(h, http.MethodGet, "/search?q=GADGET", nil, nil).Body.String()
|
|
for _, want := range []string{"Rival Corp", "Gadget 2 launches", "Our widgets beat any gadget", `href="/content/1"`, `href="/inbox"`} {
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("search for gadget: missing %q", want)
|
|
}
|
|
}
|
|
// Every word must match.
|
|
if body := do(h, http.MethodGet, "/search?q=gadget+launches", nil, nil).Body.String(); strings.Contains(body, "Our widgets") {
|
|
t.Error("a draft without \"launches\" matched")
|
|
}
|
|
if body := do(h, http.MethodGet, "/search?q=anthropic+key", nil, nil).Body.String(); !strings.Contains(body, `href="/settings/ai"`) {
|
|
t.Error("settings search should find the AI tab")
|
|
}
|
|
}
|
|
|
|
func TestOAuthCallbackRejectsUnknownState(t *testing.T) {
|
|
_, h := newTestServer(t, nil)
|
|
rec := do(h, http.MethodGet, "/auth/x/callback?state=nope&code=c", nil, nil)
|
|
if rec.Code != http.StatusSeeOther || !strings.Contains(rec.Header().Get("Location"), "oauth-expired") {
|
|
t.Errorf("got %d %s", rec.Code, rec.Header().Get("Location"))
|
|
}
|
|
}
|
|
|
|
func TestMCPNeedsTokenAndChecksIn(t *testing.T) {
|
|
s, h := newTestServer(t, nil)
|
|
call := func(token string, body any) *httptest.ResponseRecorder {
|
|
raw, _ := json.Marshal(body)
|
|
hdr := map[string]string{"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
|
|
if token != "" {
|
|
hdr["Authorization"] = "Bearer " + token
|
|
}
|
|
return do(h, http.MethodPost, "/mcp", bytes.NewReader(raw), hdr)
|
|
}
|
|
list := map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
|
|
if rec := call("", list); rec.Code != http.StatusUnauthorized {
|
|
t.Errorf("no token: %d", rec.Code)
|
|
}
|
|
if rec := call("wrong", list); rec.Code != http.StatusUnauthorized {
|
|
t.Errorf("wrong token: %d", rec.Code)
|
|
}
|
|
rec := call(testToken, list)
|
|
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "bridge_checkin") {
|
|
t.Fatalf("tools/list: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
|
|
rec = call(testToken, map[string]any{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": map[string]any{
|
|
"name": "bridge_checkin",
|
|
"arguments": map[string]any{"agent": "hermes", "mcphub_tools": []string{"espocrm_list_leads"}},
|
|
}})
|
|
if rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), `"isError":true`) {
|
|
t.Fatalf("checkin: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
last, err := bridge.Last(s.DB)
|
|
if err != nil || last == nil || last.Agent != "hermes" || len(last.MCPHubTools) != 1 {
|
|
t.Fatalf("checkin not recorded: %+v %v", last, err)
|
|
}
|
|
}
|
|
|
|
func TestInventoryFillNeedsAI(t *testing.T) {
|
|
_, h := newTestServer(t, nil)
|
|
if body := do(h, http.MethodGet, "/inventory/new", nil, nil).Body.String(); !strings.Contains(body, `<a href="/settings/ai">set up the AI</a>`) {
|
|
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, `<a href="/settings/ai">choose an AI provider</a>`) || !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")
|
|
}
|
|
}
|