// SPDX-License-Identifier: AGPL-3.0-or-later package spa import ( "net/http" "net/http/httptest" "net/url" "strings" "sync/atomic" "testing" "testing/fstest" ) func TestEndpoint(t *testing.T) { cases := map[string]string{ "/p/abc123": "/api/v1/previews/pages/abc123", "/share/tok_-9": "/api/v1/previews/share/tok_-9", "/share/tok/p/page1": "/api/v1/previews/share/tok?page=page1", "/p/abc/r/db/row": "", "/settings/account": "", "/p/../../admin": "", "/share/tok/p/a'b": "", "/share/tok/extra/path": "", } for in, want := range cases { if got := endpoint(in); got != want { t.Errorf("endpoint(%q) = %q, want %q", in, got, want) } } } func TestBotsGetPreviewMetaTags(t *testing.T) { var calls atomic.Int32 api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1) switch r.URL.Path { case "/api/v1/previews/pages/p1": w.Write([]byte(`{"title":"Q4 ","description":"","site":"Acme"}`)) case "/api/v1/previews/share/tok": w.Write([]byte(`{"title":"Handbook","description":"How we \"work\"","site":"Acme"}`)) default: http.Error(w, `{"error":"not_found"}`, http.StatusNotFound) } })) defer api.Close() u, _ := url.Parse(api.URL) files := fstest.MapFS{"index.html": {Data: []byte("Docwell")}} h := Handler(Options{Files: files, PreviewAPI: u}) fetch := func(path, ua string) string { req := httptest.NewRequest("GET", path, nil) req.Header.Set("User-Agent", ua) rec := httptest.NewRecorder() h.ServeHTTP(rec, req) return rec.Body.String() } body := fetch("/p/p1", "Slackbot-LinkExpanding 1.0 (+https://api.slack.com/robots)") if !strings.Contains(body, ``) || !strings.Contains(body, `Q4 <plan>`) || strings.Contains(body, "Docwell") { t.Errorf("bot page = %s", body) } body = fetch("/share/tok", "Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)") if !strings.Contains(body, `og:description" content="How we "work""`) { t.Errorf("bot share = %s", body) } // People's browsers get the plain shell and cause no lookup. before := calls.Load() body = fetch("/p/p1", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/142.0 Safari/537.36") if strings.Contains(body, "og:title") || calls.Load() != before { t.Errorf("browser got a preview: %s", body) } // Search engines too: they must not learn private titles. if body = fetch("/p/p1", "Mozilla/5.0 (compatible; Googlebot/2.1)"); strings.Contains(body, "og:title") { t.Errorf("search engine got a preview: %s", body) } // No preview (URL previews off): the plain shell. if body = fetch("/p/other", "Slackbot 1.0"); strings.Contains(body, "og:title") { t.Errorf("unknown page got a preview: %s", body) } // Answers are cached for a minute. before = calls.Load() fetch("/p/p1", "Slackbot 1.0") if calls.Load() != before { t.Error("second lookup was not cached") } }