parsimony/internal/web/web_test.go
tgiachi ec8ca567ff feat(web): logo and favicon on the public pages
- Show the mark on every page, linking to the index, inline so the CSP needs no image source
- Add the favicon as a data: URI and allow img-src data: only
2026-11-10 12:13:53 +01:00

326 lines
12 KiB
Go

package web
import (
"encoding/base64"
"fmt"
"html"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"codeberg.org/squidd/parsimony/assets"
"codeberg.org/squidd/parsimony/internal/router"
"codeberg.org/squidd/parsimony/internal/store"
)
type fixture struct {
h http.Handler
s *store.Store
rt *router.Router
pub store.List
alice int64
bobTok string
}
func newFixture(t *testing.T) *fixture {
t.Helper()
s, err := store.Open(":memory:")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { s.Close() })
pub, _ := s.CreateList("dev", "example.org", "Dev <b>talk</b>")
s.SetPolicies(pub.ID, store.PostMembers, store.JoinOpen, store.ArchivePublic)
priv, _ := s.CreateList("secret", "example.org", "Secret")
s.SetPolicies(priv.ID, store.PostMembers, store.JoinOpen, store.ArchivePrivate)
off, _ := s.CreateList("off", "example.org", "Off")
s.SetPolicies(off.ID, store.PostMembers, store.JoinOpen, store.ArchiveOff)
s.AddMember(pub.ID, "alice@example.com", "Alice")
s.AddMember(pub.ID, "bob@example.com", "Bob")
ms, _ := s.Members(pub.ID)
rt := router.New(s)
return &fixture{h: New(s, rt), s: s, rt: rt, pub: pub, alice: ms[0].ID, bobTok: rt.UnsubscribeToken(ms[1].ID)}
}
func (f *fixture) add(t *testing.T, listID int64, id, subject, sender, body string, at int64, inReplyTo string) int64 {
t.Helper()
n, _, err := f.s.ArchiveMessage(listID, store.Message{
MessageID: id, InReplyTo: inReplyTo, Subject: subject, Sender: sender, Body: body, Date: time.Unix(at, 0).UTC(),
})
if err != nil {
t.Fatal(err)
}
return n
}
func get(t *testing.T, h http.Handler, path string) *httptest.ResponseRecorder {
t.Helper()
return request(t, h, "GET", path)
}
func request(t *testing.T, h http.Handler, method, path string) *httptest.ResponseRecorder {
t.Helper()
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(method, path, nil))
return rec
}
func wantStatus(t *testing.T, rec *httptest.ResponseRecorder, code int) {
t.Helper()
if rec.Code != code {
t.Fatalf("status = %d, want %d; body: %.300s", rec.Code, code, rec.Body.String())
}
}
func wantBody(t *testing.T, rec *httptest.ResponseRecorder, parts ...string) {
t.Helper()
for _, p := range parts {
if !strings.Contains(rec.Body.String(), p) {
t.Errorf("body lacks %q:\n%.800s", p, rec.Body.String())
}
}
}
func wantNoBody(t *testing.T, rec *httptest.ResponseRecorder, parts ...string) {
t.Helper()
for _, p := range parts {
if strings.Contains(rec.Body.String(), p) {
t.Errorf("body must not contain %q", p)
}
}
}
func TestIndexListsOnlyPublicLists(t *testing.T) {
f := newFixture(t)
rec := get(t, f.h, "/")
wantStatus(t, rec, 200)
wantBody(t, rec, "dev@example.org", `href="/archive/dev@example.org"`)
wantNoBody(t, rec, "secret@example.org", "off@example.org")
}
func TestIndexEscapesTitles(t *testing.T) {
f := newFixture(t)
rec := get(t, f.h, "/")
wantBody(t, rec, "Dev &lt;b&gt;talk&lt;/b&gt;")
wantNoBody(t, rec, "<b>talk</b>")
}
func TestIndexWithoutPublicLists(t *testing.T) {
s, _ := store.Open(":memory:")
defer s.Close()
rec := get(t, New(s, router.New(s)), "/")
wantStatus(t, rec, 200)
wantBody(t, rec, "No public archives")
}
func TestUnknownPathIs404(t *testing.T) {
f := newFixture(t)
wantStatus(t, get(t, f.h, "/nope"), 404)
}
func TestNonPublicOrUnknownArchivesAre404(t *testing.T) {
f := newFixture(t)
for _, p := range []string{"/archive/secret@example.org", "/archive/off@example.org", "/archive/ghost@example.org",
"/archive/not-an-address", "/archive/secret@example.org?q=x"} {
wantStatus(t, get(t, f.h, p), 404)
}
}
func TestArchivePageShowsMessagesNewestFirst(t *testing.T) {
f := newFixture(t)
f.add(t, f.pub.ID, "<1@x>", "Old topic", "Alice", "a", 1_700_000_000, "")
f.add(t, f.pub.ID, "<2@x>", "New topic", "Bob <i>", "b", 1_700_100_000, "")
rec := get(t, f.h, "/archive/dev@example.org")
wantStatus(t, rec, 200)
wantBody(t, rec, "Old topic", "New topic", "Bob &lt;i&gt;", "2023-11-14")
wantNoBody(t, rec, "Bob <i>")
if strings.Index(rec.Body.String(), "New topic") > strings.Index(rec.Body.String(), "Old topic") {
t.Fatal("newest message must come first")
}
}
func TestArchivePaging(t *testing.T) {
f := newFixture(t)
for i := 0; i < pageSize+3; i++ {
f.add(t, f.pub.ID, fmt.Sprintf("<m%d@x>", i), fmt.Sprintf("Subject number %d", i), "A", "b", 1_700_000_000+int64(i), "")
}
p1 := get(t, f.h, "/archive/dev@example.org")
wantBody(t, p1, fmt.Sprintf("Subject number %d", pageSize+2), "page=2")
wantNoBody(t, p1, "Subject number 0<", "page=0")
p2 := get(t, f.h, "/archive/dev@example.org?page=2")
wantStatus(t, p2, 200)
wantBody(t, p2, "Subject number 0<")
wantNoBody(t, p2, "page=3")
// A page past the end shows the last page instead of an empty one.
far := get(t, f.h, "/archive/dev@example.org?page=999")
wantBody(t, far, "Subject number 0<")
for _, bad := range []string{"?page=abc", "?page=0", "?page=-4", "?page=999"} {
wantStatus(t, get(t, f.h, "/archive/dev@example.org"+bad), 200)
}
}
func TestArchiveSearch(t *testing.T) {
f := newFixture(t)
f.add(t, f.pub.ID, "<1@x>", "Deploy", "A", "kubernetes rollout", 1_700_000_000, "")
f.add(t, f.pub.ID, "<2@x>", "Lunch", "B", "pizza", 1_700_000_001, "")
rec := get(t, f.h, "/archive/dev@example.org?q=kubernetes")
wantStatus(t, rec, 200)
wantBody(t, rec, "Deploy", "1 result")
wantNoBody(t, rec, "Lunch")
rec = get(t, f.h, "/archive/dev@example.org?q=zzzz")
wantBody(t, rec, "No messages found")
// The query is echoed back escaped and survives paging links.
rec = get(t, f.h, "/archive/dev@example.org?q="+url.QueryEscape(`"><script>x</script>`))
wantStatus(t, rec, 200)
wantNoBody(t, rec, "<script>x</script>")
}
func TestMessagePage(t *testing.T) {
f := newFixture(t)
root := f.add(t, f.pub.ID, "<root@x>", "Original topic", "Alice", "Write to carol@example.com <script>alert(1)</script>", 1_700_000_000, "")
reply := f.add(t, f.pub.ID, "<re@x>", "Re: Original topic", "Bob", "I agree", 1_700_000_100, "<root@x>")
rec := get(t, f.h, fmt.Sprintf("/archive/dev@example.org/%d", root))
wantStatus(t, rec, 200)
wantBody(t, rec, "Original topic", "Alice", "carol@…", "&lt;script&gt;alert(1)&lt;/script&gt;",
fmt.Sprintf(`href="/archive/dev@example.org/%d"`, reply), "Re: Original topic")
wantNoBody(t, rec, "carol@example.com", "<script>alert(1)</script>")
rec = get(t, f.h, fmt.Sprintf("/archive/dev@example.org/%d", reply))
wantStatus(t, rec, 200)
wantBody(t, rec, "I agree", fmt.Sprintf(`href="/archive/dev@example.org/%d"`, root))
}
func TestMessagePageHidesOtherListsAndPrivateOnes(t *testing.T) {
f := newFixture(t)
priv, _ := f.s.FindList("secret@example.org")
secretID := f.add(t, priv.ID, "<s@x>", "Top secret", "A", "classified", 1_700_000_000, "")
pubID := f.add(t, f.pub.ID, "<p@x>", "Public", "A", "hello", 1_700_000_000, "")
wantStatus(t, get(t, f.h, fmt.Sprintf("/archive/secret@example.org/%d", secretID)), 404)
// A public list URL must not reveal a message that belongs to another list.
wantStatus(t, get(t, f.h, fmt.Sprintf("/archive/dev@example.org/%d", secretID)), 404)
wantStatus(t, get(t, f.h, fmt.Sprintf("/archive/dev@example.org/%d", pubID)), 200)
for _, p := range []string{"/archive/dev@example.org/abc", "/archive/dev@example.org/0", "/archive/dev@example.org/999", "/archive/dev@example.org/-1"} {
wantStatus(t, get(t, f.h, p), 404)
}
}
func TestPrivacyOfOriginalSender(t *testing.T) {
f := newFixture(t)
id := f.add(t, f.pub.ID, "<1@x>", "Contact bob@secret.example", "bob", "ping", 1_700_000_000, "")
rec := get(t, f.h, fmt.Sprintf("/archive/dev@example.org/%d", id))
wantNoBody(t, rec, "bob@secret.example")
wantBody(t, rec, "bob@…")
rec = get(t, f.h, "/archive/dev@example.org")
wantNoBody(t, rec, "bob@secret.example")
}
func TestSecurityHeaders(t *testing.T) {
f := newFixture(t)
for _, p := range []string{"/", "/archive/dev@example.org", "/nope"} {
h := get(t, f.h, p).Header()
if h.Get("X-Content-Type-Options") != "nosniff" || h.Get("Referrer-Policy") != "no-referrer" ||
!strings.Contains(h.Get("Content-Security-Policy"), "default-src 'none'") ||
!strings.HasPrefix(h.Get("Content-Type"), "text/html") {
t.Errorf("%s: headers %v", p, h)
}
}
}
func TestOnlyGetOnArchive(t *testing.T) {
f := newFixture(t)
wantStatus(t, request(t, f.h, "POST", "/archive/dev@example.org"), 405)
wantStatus(t, request(t, f.h, "DELETE", "/"), 405)
}
func TestUnsubscribeConfirmPageDoesNotUnsubscribe(t *testing.T) {
f := newFixture(t)
rec := get(t, f.h, "/unsubscribe/"+f.bobTok)
wantStatus(t, rec, 200)
wantBody(t, rec, `method="post"`, "Dev &lt;b&gt;talk&lt;/b&gt;")
if ok, _ := f.s.IsMember(f.pub.ID, "bob@example.com"); !ok {
t.Fatal("a GET (link prefetch) must never unsubscribe")
}
h := rec.Header()
if h.Get("Cache-Control") != "no-store" || h.Get("Referrer-Policy") != "no-referrer" {
t.Errorf("token page headers: %v", h)
}
}
func TestUnsubscribePost(t *testing.T) {
f := newFixture(t)
rec := request(t, f.h, "POST", "/unsubscribe/"+f.bobTok)
wantStatus(t, rec, 200)
wantBody(t, rec, "unsubscribed")
if ok, _ := f.s.IsMember(f.pub.ID, "bob@example.com"); ok {
t.Fatal("bob must be unsubscribed")
}
if ok, _ := f.s.IsMember(f.pub.ID, "alice@example.com"); !ok {
t.Fatal("alice must stay")
}
// Repeated one-click requests and a later visit are harmless.
wantStatus(t, request(t, f.h, "POST", "/unsubscribe/"+f.bobTok), 200)
rec = get(t, f.h, "/unsubscribe/"+f.bobTok)
wantStatus(t, rec, 200)
wantBody(t, rec, "already unsubscribed")
}
func TestUnsubscribeRejectsBadTokens(t *testing.T) {
f := newFixture(t)
for _, tok := range []string{"x", "1-000000000000", "abc-def", f.bobTok + "0", "0-" + strings.Repeat("0", 12)} {
wantStatus(t, get(t, f.h, "/unsubscribe/"+tok), 404)
wantStatus(t, request(t, f.h, "POST", "/unsubscribe/"+tok), 404)
}
if n, _ := f.s.Members(f.pub.ID); len(n) != 2 {
t.Fatal("bad tokens must not remove anyone")
}
}
func TestUnsubscribeOneClickBodyIsAccepted(t *testing.T) {
f := newFixture(t)
req := httptest.NewRequest("POST", "/unsubscribe/"+f.bobTok, strings.NewReader("List-Unsubscribe=One-Click"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
f.h.ServeHTTP(rec, req)
wantStatus(t, rec, 200)
if ok, _ := f.s.IsMember(f.pub.ID, "bob@example.com"); ok {
t.Fatal("bob must be unsubscribed")
}
}
func TestEveryPageCarriesTheLogoAndTheFavicon(t *testing.T) {
f := newFixture(t)
id := f.add(t, f.pub.ID, "<1@x>", "Hello", "A", "body", 1_700_000_000, "")
favicon := "data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString([]byte(assets.Mark))
for _, p := range []string{"/", "/archive/dev@example.org", fmt.Sprintf("/archive/dev@example.org/%d", id), "/unsubscribe/" + f.bobTok, "/nope"} {
rec := get(t, f.h, p)
body := html.UnescapeString(rec.Body.String()) // html/template writes "+" in an attribute as &#43;
if !strings.Contains(body, `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Parsimony">`) {
t.Errorf("%s: no inline logo", p)
}
if !strings.Contains(body, `<link rel="icon" type="image/svg+xml" href="`+favicon+`">`) {
t.Errorf("%s: no favicon (a data: URI, because the CSP allows nothing else)", p)
}
if !strings.Contains(body, `<a class="brand" href="/" aria-label="All archives">`) {
t.Errorf("%s: the logo must lead back to the index", p)
}
}
}
func TestTheCSPAllowsOnlyDataImages(t *testing.T) {
f := newFixture(t)
csp := get(t, f.h, "/").Header().Get("Content-Security-Policy")
if !strings.Contains(csp, "img-src data:") || !strings.Contains(csp, "default-src 'none'") {
t.Fatalf("csp = %q", csp)
}
for _, loose := range []string{"*", "http:", "https:", "'unsafe-eval'", "script-src"} {
if strings.Contains(csp, loose) {
t.Errorf("the CSP must stay strict, it contains %q: %s", loose, csp)
}
}
}