A Core sign-in, and a posting account's or Search Console's OAuth sign-in, now sets a short-lived cookie whose hash the flow keeps on the server. The callback refuses one without it (constant-time compare), clears the cookie either way, and the flow is used up regardless. This stops login CSRF: a callback URL brought to another browser signs nobody in. The cookie uses the __Host- prefix over https, so its Path is "/". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
295 lines
14 KiB
Go
295 lines
14 KiB
Go
package web
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"supermarket/internal/backlinks"
|
|
"supermarket/internal/inventory"
|
|
"supermarket/internal/oauth"
|
|
"supermarket/internal/profile"
|
|
"supermarket/internal/secrets"
|
|
"supermarket/internal/signals"
|
|
)
|
|
|
|
func TestSearchConsole(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch {
|
|
case r.URL.Path == "/token":
|
|
r.ParseForm()
|
|
if r.PostForm.Get("client_secret") != "sec" || (r.PostForm.Get("code") != "c0de" && r.PostForm.Get("grant_type") != "refresh_token") {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
json.NewEncoder(w).Encode(map[string]any{"access_token": "tok", "refresh_token": "ref", "expires_in": 3600})
|
|
case r.URL.Path == "/userinfo":
|
|
json.NewEncoder(w).Encode(map[string]any{"email": "me@example.com"})
|
|
case r.URL.Path == "/sites":
|
|
json.NewEncoder(w).Encode(map[string]any{"siteEntry": []any{map[string]any{"siteUrl": "sc-domain:us.example", "permissionLevel": "siteOwner"}}})
|
|
case strings.HasSuffix(r.URL.Path, "/searchAnalytics/query"):
|
|
var q struct {
|
|
StartDate string `json:"startDate"`
|
|
Dimensions []string `json:"dimensions"`
|
|
}
|
|
json.NewDecoder(r.Body).Decode(&q)
|
|
var rows []any
|
|
if q.StartDate <= "2026-11-10" && q.StartDate >= "2026-10-20" {
|
|
day := "2026-11-10"
|
|
switch strings.Join(q.Dimensions, ",") {
|
|
case "date":
|
|
rows = append(rows, map[string]any{"keys": []string{day}, "clicks": 63, "impressions": 4200, "position": 9})
|
|
case "date,page":
|
|
rows = append(rows, map[string]any{"keys": []string{day, "https://us.example/pricing/"}, "clicks": 0, "impressions": 4000, "position": 6.5},
|
|
map[string]any{"keys": []string{day, "https://us.example/"}, "clicks": 63, "impressions": 200, "position": 1.2})
|
|
case "date,page,query":
|
|
rows = append(rows, map[string]any{"keys": []string{day, "https://us.example/pricing/", "nextcloud hosting price"}, "clicks": 0, "impressions": 3000, "position": 6})
|
|
}
|
|
}
|
|
json.NewEncoder(w).Encode(map[string]any{"rows": rows})
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
oauth.SetGoogleURLs(srv.URL+"/auth", srv.URL+"/token", srv.URL+"/userinfo")
|
|
gscBase = srv.URL
|
|
defer func() {
|
|
oauth.SetGoogleURLs("https://accounts.google.com/o/oauth2/v2/auth", "https://oauth2.googleapis.com/token", "https://openidconnect.googleapis.com/v1/userinfo")
|
|
gscBase = ""
|
|
}()
|
|
|
|
s, h := newTestServer(t, nil)
|
|
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: "https://us.example"}}})
|
|
if body := do(h, http.MethodGet, "/seo", nil, nil).Body.String(); !strings.Contains(body, "Connect Google Search Console") {
|
|
t.Error("the SEO page doesn't say to connect")
|
|
}
|
|
postForm(h, "/settings/search", url.Values{secrets.GoogleClientID: {"cid"}, secrets.GoogleClientSecret: {"sec"}})
|
|
body := do(h, http.MethodGet, "/settings/search", nil, nil).Body.String()
|
|
if !strings.Contains(body, "/auth/google/callback") || !strings.Contains(body, "Connect Search Console") {
|
|
t.Fatal("no redirect URI or Connect button")
|
|
}
|
|
|
|
rec := postForm(h, "/auth/google/start", nil)
|
|
loc, _ := url.Parse(rec.Header().Get("Location"))
|
|
q := loc.Query()
|
|
if !strings.HasPrefix(loc.String(), srv.URL+"/auth") || q.Get("access_type") != "offline" || !strings.Contains(q.Get("scope"), "webmasters.readonly") || q.Get("code_challenge") == "" {
|
|
t.Fatalf("start: %s", loc)
|
|
}
|
|
rec = getWith(h, "/auth/google/callback?state="+url.QueryEscape(q.Get("state"))+"&code=c0de", cookieOf(rec, oauthFlowCookie))
|
|
if rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), "/settings/search?msg=google-connected") {
|
|
t.Fatalf("callback: %d %s %s", rec.Code, rec.Header().Get("Location"), rec.Body)
|
|
}
|
|
if s.Secrets.Get(secrets.GoogleRefreshToken) != "ref" {
|
|
t.Error("the refresh token wasn't saved")
|
|
}
|
|
body = do(h, http.MethodGet, "/settings/search", nil, nil).Body.String()
|
|
if !strings.Contains(body, "Connected as me@example.com") || !strings.Contains(body, `<option value="sc-domain:us.example"`) {
|
|
t.Fatalf("connected page: %s", body)
|
|
}
|
|
postForm(h, "/settings/search", url.Values{"property": {"sc-domain:us.example"}})
|
|
if p, _ := profile.Load(s.DB); p.Websites[0].SearchConsoleProperty != "sc-domain:us.example" {
|
|
t.Errorf("property: %+v", p.Websites)
|
|
}
|
|
if rec := postForm(h, "/settings/search/sync", url.Values{"back": {"/seo?site=0"}}); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("sync: %d %s", rec.Code, rec.Body)
|
|
}
|
|
body = do(h, http.MethodGet, "/seo", nil, nil).Body.String()
|
|
for _, want := range []string{"4,200", "/pricing/", "Shown 4,000 times at position 6.5, 0 clicks. 75% of its impressions come from “nextcloud hosting price”",
|
|
"nextcloud hosting price", "100.0% of the clicks come from searches Google doesn't name"} {
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("SEO page lacks %q", want)
|
|
}
|
|
}
|
|
|
|
// The morning check: last week has data, the week before none, so the
|
|
// pages are new.
|
|
body = do(h, http.MethodGet, "/seo/check", nil, nil).Body.String()
|
|
for _, want := range []string{"2026-11-04 to 2026-11-10", "/pricing/", "new", `class="chart line-chart"`, "<polyline class=\"this\""} {
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("check lacks %q", want)
|
|
}
|
|
}
|
|
if body := do(h, http.MethodGet, "/seo/report", nil, nil).Body.String(); !strings.Contains(body, "No report yet") {
|
|
t.Error("a report before one was written")
|
|
}
|
|
rec = postForm(h, "/seo/report?site=0", nil)
|
|
if rec.Code != http.StatusSeeOther || !strings.Contains(rec.Header().Get("Location"), "week=2026-11-10") {
|
|
t.Fatalf("write report: %d %s %s", rec.Code, rec.Header().Get("Location"), rec.Body)
|
|
}
|
|
body = do(h, http.MethodGet, "/seo/report", nil, nil).Body.String()
|
|
for _, want := range []string{"1. The week", "Waiting for your yes", "/pricing/", "4,200"} {
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("report lacks %q", want)
|
|
}
|
|
}
|
|
// Thresholds.
|
|
postForm(h, "/settings/search", url.Values{"min_clicks": {"10"}, "min_positions": {"2.5"}, "min_impressions": {"500"}, "email_report": {"on"}, "email_check": {"on"}})
|
|
if body := do(h, http.MethodGet, "/settings/search", nil, nil).Body.String(); !strings.Contains(body, `name="min_positions" inputmode="decimal" value="2.5"`) || !strings.Contains(body, `name="email_report" checked`) || !strings.Contains(body, `name="email_check" checked`) {
|
|
t.Error("thresholds weren't saved")
|
|
}
|
|
}
|
|
|
|
// A form that leads to a sign-in page is refused by the browser unless the
|
|
// page's security policy allows that host as a form target.
|
|
func TestSignInHostsAllowedAsFormTargets(t *testing.T) {
|
|
_, h := newTestServer(t, nil)
|
|
csp := do(h, http.MethodGet, "/", nil, nil).Header().Get("Content-Security-Policy")
|
|
for _, host := range []string{"https://twitter.com", "https://www.linkedin.com", "https://www.reddit.com", "https://accounts.google.com"} {
|
|
if !strings.Contains(csp, host) {
|
|
t.Errorf("form-action lacks %s: %s", host, csp)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestWhatToWriteNext(t *testing.T) {
|
|
s, h := newTestServer(t, nil)
|
|
p := &profile.Profile{Name: "Acme", Websites: []profile.Website{{URL: "https://acme.example", SearchConsoleProperty: "sc-domain:acme.example"}}}
|
|
if err := profile.Save(s.DB, p); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
sig := &signals.Signal{Name: "Leaving M365", Status: "testing"}
|
|
signals.Save(s.DB, sig)
|
|
signals.Record(s.DB, signals.Event{SignalID: sig.ID, Stage: signals.StageReplied, Channel: "email", Source: "manual", Subject: "contact:1", ExternalID: "r1", At: time.Now().AddDate(0, 0, -2)})
|
|
|
|
body := do(h, http.MethodGet, "/seo/next", nil, nil).Body.String()
|
|
if !strings.Contains(body, "Leaving M365") || !strings.Contains(body, "kind=landing&signal=") || !strings.Contains(body, "Ranked by impressions for now") {
|
|
t.Fatalf("next: %s", body)
|
|
}
|
|
rec := postForm(h, "/seo/next/dismiss?site=0", url.Values{"key": {"signal-page:" + strconv.FormatInt(sig.ID, 10)}})
|
|
if rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("dismiss: %d", rec.Code)
|
|
}
|
|
if body := do(h, http.MethodGet, "/seo/next", nil, nil).Body.String(); strings.Contains(body, "Leaving M365") {
|
|
t.Error("a dismissed suggestion still shows")
|
|
}
|
|
// The New pages form takes the suggestion's kind and signal.
|
|
if body := do(h, http.MethodGet, "/sites/pages?kind=landing&signal="+strconv.FormatInt(sig.ID, 10), nil, nil).Body.String(); strings.Contains(body, "<form method=\"post\" action=\"/sites/pages\"") &&
|
|
!strings.Contains(body, `value="landing" selected`) {
|
|
t.Error("New pages wasn't filled in")
|
|
}
|
|
}
|
|
|
|
func TestLinksFromBing(t *testing.T) {
|
|
b := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var d any
|
|
switch r.URL.Path {
|
|
case "/GetLinkCounts":
|
|
d = map[string]any{"TotalPages": 1, "Links": []map[string]any{{"Url": "https://acme.example/freescout", "Count": 2}}}
|
|
case "/GetUrlLinks":
|
|
d = map[string]any{"TotalPages": 1, "Details": []map[string]any{{"Url": "https://selfhosted.blog/hosts/", "AnchorText": "Acme hosting"}}}
|
|
}
|
|
json.NewEncoder(w).Encode(map[string]any{"d": d})
|
|
}))
|
|
defer b.Close()
|
|
bingBase = b.URL
|
|
defer func() { bingBase = "" }()
|
|
s, h := newTestServer(t, nil)
|
|
profile.Save(s.DB, &profile.Profile{Name: "Acme", Websites: []profile.Website{{URL: "https://acme.example/", SearchConsoleProperty: "sc-domain:acme.example"}}})
|
|
|
|
if body := do(h, http.MethodGet, "/seo/links", nil, nil).Body.String(); !strings.Contains(body, "Save a Bing Webmaster API key") {
|
|
t.Errorf("without a key: %s", body)
|
|
}
|
|
postForm(h, "/settings/search", url.Values{secrets.BingAPIKey: {"k"}})
|
|
if rec := postForm(h, "/seo/links/bing?site=0", nil); rec.Code != http.StatusSeeOther || !strings.Contains(rec.Header().Get("Location"), "msg=bing-read") {
|
|
t.Fatalf("read: %d %s", rec.Code, rec.Header().Get("Location"))
|
|
}
|
|
body := do(h, http.MethodGet, "/seo/links", nil, nil).Body.String()
|
|
for _, want := range []string{"selfhosted.blog", "“Acme hosting”", "/freescout/", "2 links to 1 page"} {
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("links page lacks %q", want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestLostLinks(t *testing.T) {
|
|
var site string
|
|
links := `<a href="SITE/freescout/">FreeScout hosting</a>`
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/freescout/":
|
|
fmt.Fprint(w, "<html><body>FreeScout</body></html>")
|
|
case "/their/list":
|
|
fmt.Fprint(w, "<html><body>"+strings.ReplaceAll(links, "SITE", site)+"</body></html>")
|
|
default:
|
|
http.NotFound(w, r)
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
// Our site and theirs on the same test server, told apart by host.
|
|
site = strings.Replace(srv.URL, "127.0.0.1", "localhost", 1)
|
|
theirs := srv.URL + "/their/list"
|
|
s, h := newTestServer(t, nil)
|
|
profile.Save(s.DB, &profile.Profile{Name: "Acme", Websites: []profile.Website{{URL: site + "/"}}})
|
|
|
|
if rec := postForm(h, "/seo/links/add?site=0", url.Values{"source": {theirs}}); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("add: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
p, _ := profile.Load(s.DB)
|
|
ls, _ := backlinks.Links(s.DB, p.Websites[0].URL)
|
|
if len(ls) != 1 || ls[0].Status != backlinks.StatusKept || ls[0].Target != "/freescout/" {
|
|
t.Fatalf("after adding: %+v", ls)
|
|
}
|
|
if body := postForm(h, "/seo/links/add?site=0", url.Values{"source": {site + "/blog/"}}).Body.String(); !strings.Contains(body, "a page of your own site") {
|
|
t.Error("took a page of the site itself")
|
|
}
|
|
|
|
// The page now links to a page of ours that's gone: a redirect fixes it.
|
|
links = `<a href="SITE/old-page/">old</a>`
|
|
s.DB.Exec(`UPDATE backlinks SET checked_at = '2020-01-01T00:00:00Z'`)
|
|
if rec := postForm(h, "/seo/links/check?site=0", nil); !strings.Contains(rec.Header().Get("Location"), "msg=links-checked&") && !strings.Contains(rec.Header().Get("Location"), "n1=1") {
|
|
t.Errorf("check: %s", rec.Header().Get("Location"))
|
|
}
|
|
body := do(h, http.MethodGet, "/seo/links", nil, nil).Body.String()
|
|
if !strings.Contains(body, "points at a 404") || !strings.Contains(body, "/old-page/") {
|
|
t.Errorf("links page: lost link not shown")
|
|
}
|
|
if body := do(h, http.MethodGet, "/seo/next", nil, nil).Body.String(); !strings.Contains(body, "Fix with a redirect") {
|
|
t.Errorf("next: no redirect suggestion")
|
|
}
|
|
}
|
|
|
|
func TestPartnerOpportunities(t *testing.T) {
|
|
var base string
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/":
|
|
fmt.Fprintf(w, `<html><body><a href="%s/hosting-providers/">Hosting</a></body></html>`, base)
|
|
case "/hosting-providers/":
|
|
fmt.Fprint(w, `<html><head><title>Hosting providers</title></head><body><a href="https://a.example/">A</a><a href="https://b.example/">B</a><a href="https://c.example/">C</a></body></html>`)
|
|
default:
|
|
http.NotFound(w, r)
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
base = srv.URL
|
|
s, h := newTestServer(t, nil)
|
|
profile.Save(s.DB, &profile.Profile{Name: "Acme", Websites: []profile.Website{{URL: "https://acme.example/"}}})
|
|
inventory.Save(s.DB, &inventory.Entry{Name: "FreeScout", Relationship: inventory.Partner, Websites: []string{srv.URL + "/"}})
|
|
|
|
rec := postForm(h, "/seo/links/partners?site=0", nil)
|
|
if !strings.Contains(rec.Header().Get("Location"), "msg=partners-read") || !strings.Contains(rec.Header().Get("Location"), "n1=1") {
|
|
t.Fatalf("partners: %d %s %s", rec.Code, rec.Header().Get("Location"), rec.Body.String())
|
|
}
|
|
body := do(h, http.MethodGet, "/seo/links", nil, nil).Body.String()
|
|
if !strings.Contains(body, "Hosting providers") || !strings.Contains(body, "partner FreeScout") || !strings.Contains(body, "I asked") {
|
|
t.Errorf("links page lacks the opportunity")
|
|
}
|
|
if body := do(h, http.MethodGet, "/seo/next", nil, nil).Body.String(); !strings.Contains(body, "Ask to be listed") {
|
|
t.Error("next: no opportunity")
|
|
}
|
|
prof, _ := profile.Load(s.DB)
|
|
siteKey := prof.Websites[0].URL
|
|
opps, _ := backlinks.Opportunities(s.DB, siteKey)
|
|
if rec := postForm(h, "/seo/links/opportunity?site=0", url.Values{"id": {strconv.FormatInt(opps[0].ID, 10)}, "status": {"asked"}}); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("asked: %d", rec.Code)
|
|
}
|
|
if opps, _ := backlinks.Opportunities(s.DB, siteKey); opps[0].Status != "asked" {
|
|
t.Errorf("status: %s", opps[0].Status)
|
|
}
|
|
}
|