Files
pages/internal/server/public_periodical_test.go
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

218 lines
9.8 KiB
Go

package server
import (
"context"
"encoding/xml"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"testing"
"time"
"pageswiki/internal/store"
)
func TestPublicPeriodicalProjection(t *testing.T) {
s, _, source, actor := periodicalFixture(t)
s.mux.HandleFunc("/", s.handleHome)
ctx := context.Background()
check := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
d, err := s.store.GetDomainByUUID(source)
check(err)
check(s.store.CreateDomain(d.CampusUUID, "blog-public", "Public Blog", "blog.example.test", "local", "", "", true))
var target string
var id int64
check(s.store.DB.QueryRow(`SELECT uuid,id FROM domains WHERE name='blog-public'`).Scan(&target, &id))
for _, domain := range []string{source, target} {
_, err = s.store.DB.Exec(`INSERT INTO periodical_settings(domain_uuid,kind,enabled) VALUES(?,'blog',1) ON CONFLICT(domain_uuid,kind) DO UPDATE SET enabled=1`, domain)
check(err)
}
check(s.store.SetConfigInDomain(target, "home_layout", "blog"))
check(s.store.SetPeriodicalProjection(ctx, id, actor, "blog", source, "/blog"))
quarter, err := s.store.CreateZoneAtPath(source, actor, "quartier", "", "blog", "PRIVATE-ZONE", "", "/blog")
check(err)
page, err := s.store.CreatePageAtPathInDomain(source, "/blog/2026/09/17")
check(err)
_, err = s.store.SaveRevisionContent(page, []byte(`<h1>Approved heading</h1><p>Article body</p><a href="/blog/2026/09/18/keyword">Local article</a><script>UNSAFE_SCRIPT</script><img src="/v/raw/path:/blog/image" onerror="UNSAFE_HANDLER">`), "", "und", "text/html", "")
check(err)
_, err = s.store.DB.Exec(`INSERT INTO periodical_entries(domain_uuid,kind,page_uuid,owner_uuid,local_date,title,category,timezone) VALUES(?,'blog',?,?,'2026-09-20','Public registered title & notes','PRIVATE-CATEGORY','UTC')`, source, page, actor)
check(err)
for _, path := range []string{"/blog/2026/09/16", "/blog/2026/09/18/keyword"} {
other, err := s.store.CreatePageAtPathInDomain(source, path)
check(err)
_, err = s.store.SaveRevisionContent(other, []byte("<h1>Other heading</h1>"), "", "und", "text/html", "")
check(err)
}
for _, node := range []struct{ kind, id string }{{"domain", source}, {"quartier", quarter}} {
g, err := s.store.CityGovernance(ctx, source, actor, node.kind, node.id)
check(err)
policy := "public"
_, err = s.store.ChangeCityGovernance(ctx, source, actor, node.kind, node.id, store.CityGovernanceChange{Epoch: g.Epoch, TopologyVersion: g.TopologyVersion, Policy: &policy, ConfirmRelaxation: true}, false)
check(err)
}
p, err := s.store.LocalityPublication(ctx, source, actor, "quartier", quarter, nil)
check(err)
_, err = s.store.LocalityPublication(ctx, source, actor, "quartier", quarter, &store.PublicationChange{Epoch: p.Epoch, TopologyVersion: p.TopologyVersion, PublicationVersion: p.PublicationVersion, Enabled: true, Confirm: true, ImpactToken: p.ImpactToken})
check(err)
private, err := s.store.CreatePageAtPathInDomain(source, "/blog/2026/09/19/PRIVATE-PATH")
check(err)
_, err = s.store.SaveRevision(private, "PRIVATE-BODY", "")
check(err)
call := func(path, credential string) *httptest.ResponseRecorder {
r := httptest.NewRequest("GET", "http://blog.example.test"+path, nil)
if credential != "" {
r.Header.Set("Authorization", credential)
}
w := httptest.NewRecorder()
s.withAuthorization(s.mux).ServeHTTP(w, r)
return w
}
for _, mode := range []string{"legacy", "enforcing"} {
check(s.store.SetConfigInDomain(target, "authorization_mode", mode))
for _, path := range []string{"/", "/v/blog", "/v/blog/2026/09", "/v/blog/2026/09/17", "/2026/09/17"} {
w := call(path, "")
if w.Code != 200 || !strings.Contains(w.Body.String(), "Public registered title &amp; notes") || !strings.Contains(w.Body.String(), "Public Blog") {
t.Fatalf("%s %s: %d %s", mode, path, w.Code, w.Body.String())
}
for _, secret := range []string{"PRIVATE-", "data-periodical-compose", "data-periodical-add", "name=\"own\"", actor} {
if strings.Contains(w.Body.String(), secret) {
t.Fatalf("%s leaked %s", path, secret)
}
}
if w.Header().Get("Cache-Control") != "private, no-store" {
t.Fatal("cache policy")
}
}
if w := call("/", "Bearer invalid"); w.Code == 200 {
t.Fatal("credential fallback")
}
body := call("/2026/09/17", "").Body.String()
for _, fragment := range []string{`href="/2026/09/16"`, `href="/2026/09/18/keyword"`, `rel="prev"`, `rel="next"`, "periodical-calendar", "Article body"} {
if !strings.Contains(body, fragment) {
t.Fatal("missing article navigation/body", fragment)
}
}
if strings.Contains(body, "UNSAFE_") {
t.Fatal("unsafe article HTML")
}
if w := call("/2026/09/19/PRIVATE-PATH", ""); w.Code != 404 {
t.Fatal("private article", w.Code)
}
if w := call("/2026/09/18/keyword", ""); w.Code != 200 {
t.Fatal("keyword article", w.Code)
}
w := call("/rss.xml", "")
var feed periodicalRSS
check(xml.Unmarshal(w.Body.Bytes(), &feed))
var decoded struct {
Items []struct {
Content string `xml:"http://purl.org/rss/1.0/modules/content/ encoded"`
} `xml:"channel>item"`
}
check(xml.Unmarshal(w.Body.Bytes(), &decoded))
if len(decoded.Items) != 3 {
t.Fatal("RSS content namespace", w.Body.String())
}
content := decoded.Items[1].Content
for _, fragment := range []string{"<p>Article body</p>", `href="https://blog.example.test/2026/09/18/keyword"`, `/v/raw/path:/blog/image`} {
if !strings.Contains(content, fragment) {
t.Fatal("RSS body missing", fragment, content)
}
}
if strings.Contains(content, "UNSAFE_") || strings.Contains(w.Body.String(), "PRIVATE-") {
t.Fatal("unsafe RSS")
}
if w.Code != 200 || feed.Channel.Title != "Public Blog" || len(feed.Channel.Items) != 3 || feed.Channel.Items[1].Title != "Public registered title & notes" || feed.Channel.Items[1].Link != "https://blog.example.test/2026/09/17" || !strings.HasPrefix(w.Header().Get("Content-Type"), "application/rss+xml") {
t.Fatal("RSS", w.Code, w.Body.String())
}
}
if w := call("/v/blog/2026/09/20", ""); strings.Contains(w.Body.String(), "<h2><a") {
t.Fatal("private metadata date used")
}
if os.Getenv("PAGESWIKI_BROWSER_TEST") == "1" {
script, err := os.ReadFile("internal/server/testdata/public-periodical.js")
check(err)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Host = "blog.example.test"
if r.URL.Path == "/2026/09/17" {
rec := httptest.NewRecorder()
s.withAuthorization(s.mux).ServeHTTP(rec, r)
for k, v := range rec.Header() {
w.Header()[k] = v
}
w.WriteHeader(rec.Code)
_, _ = w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", browserFixtureScript(rec.Header(), script)+"</body>", 1)))
return
}
s.withAuthorization(s.mux).ServeHTTP(w, r)
}))
defer server.Close()
for _, width := range []string{"1440", "390"} {
ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
out, err := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", server.URL+"/2026/09/17", t.TempDir(), "", width).CombinedOutput()
cancel()
if err != nil {
t.Fatalf("public blog browser %s: %v %s", width, err, out)
}
}
}
_, err = s.store.SaveRevisionContent(page, []byte("<h1>PRIVATE-EDIT</h1>"), "", "und", "text/html", "")
check(err)
if w := call("/", ""); w.Code != 200 || strings.Contains(w.Body.String(), "Public registered title") || strings.Contains(w.Body.String(), "PRIVATE-") {
t.Fatal("stale publication", w.Code, w.Body.String())
}
if w := call("/2026/09/17", ""); w.Code != 404 {
t.Fatal("revoked body", w.Code)
}
if w := call("/rss.xml", ""); strings.Contains(w.Body.String(), "Public registered title") {
t.Fatal("revoked feed")
}
street, err := s.store.CreateZoneAtPath(source, actor, "street", quarter, "auto-day", "Auto Day", "", "/blog/2026/09/17")
check(err)
auto, err := s.store.AutoPublication(ctx, source, actor, "street", street, nil)
check(err)
_, err = s.store.AutoPublication(ctx, source, actor, "street", street, &store.AutoPublicationChange{Mode: "automatic", Version: auto.Version, Epoch: auto.Epoch, TopologyVersion: auto.TopologyVersion, Confirm: true, ImpactToken: auto.Impact.ImpactToken})
check(err)
if w := call("/", ""); w.Code != 200 || !strings.Contains(w.Body.String(), "Public registered title") {
t.Fatal("automatic title projection", w.Code, w.Body.String())
}
future, err := s.store.CreatePageAtPathInDomain(source, "/blog/2026/09/17/automatic")
check(err)
_, err = s.store.SaveRevisionContent(future, []byte("<h1>Automatic future article</h1>"), "", "und", "text/html", "")
check(err)
if w := call("/rss.xml", ""); w.Code != 200 || !strings.Contains(w.Body.String(), "Automatic future article") || strings.Contains(w.Body.String(), "PRIVATE-PATH") {
t.Fatal("automatic RSS projection", w.Code, w.Body.String())
}
_, err = s.store.DB.Exec(`UPDATE domains SET enabled=0 WHERE uuid=?`, source)
check(err)
if w := call("/", ""); w.Code == 200 {
t.Fatal("disabled source remained public")
}
}
func TestRSSContentCDATAAndAbsoluteAnchors(t *testing.T) {
item := periodicalRSSItem{Content: periodicalRSSContent{HTML: "<pre>before ]]> after &amp;</pre>"}}
raw, err := xml.Marshal(item)
if err != nil {
t.Fatal(err)
}
var decoded struct {
Content string `xml:"encoded"`
}
if err = xml.Unmarshal(raw, &decoded); err != nil || decoded.Content != item.Content.HTML {
t.Fatal("CDATA round trip", err, string(raw))
}
items := []periodicalItem{{PeriodicalEntry: store.PeriodicalEntry{Path: "/blog/2026/09/17"}, Href: "/2026/09/17"}}
content := projectedPeriodicalHTML(`<a href="#pw-doc-anchor">anchor</a><a href="../other">other</a>`, "/blog/2026/09/17", "source.example.test", items, "https://blog.example.test")
if !strings.Contains(content, `href="https://blog.example.test/2026/09/17#pw-doc-anchor"`) || !strings.Contains(content, `href="https://source.example.test/blog/2026/other"`) {
t.Fatal(content)
}
}