package server import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "os" "os/exec" "strings" "sync/atomic" "testing" "time" ) func TestHTMLProjectionChromium(t *testing.T) { if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" { t.Skip("opt-in Chromium") } s, token, domain := configFixture(t) s.mux.HandleFunc("/", s.handleHome) s.mux.HandleFunc("/o/", s.handleObjectView) s.mux.HandleFunc("/r/view/", s.handleRevisionView) s.mux.HandleFunc("/v/preview/", s.handlePreview) s.mux.HandleFunc("/_/view/print/", s.handlePrint) s.mux.HandleFunc("/u/", s.handleUserProfile) s.mux.HandleFunc("/e/", s.handleEditorRoute) s.mux.HandleFunc("/_/api/v1/render/markdown", s.handleMarkdownRenderAPI) s.mux.HandleFunc("/_/api/v1/revisions/save", s.handleSaveRevisionAPI) s.mux.HandleFunc("/v/children", s.handleChildrenProjection) body := projectionAttack + `

{{children:/guide}}

literal code
` object, err := s.store.CreatePageAtPathInDomain(domain, "/guide") if err != nil { t.Fatal(err) } if _, err = s.store.CreatePageAtPathInDomain(domain, "/guide/child"); err != nil { t.Fatal(err) } // A path-scoped author writes via the real API; a stronger administrator // subsequently renders those exact bytes in every normal display surface. author, err := s.store.CreatePasswordAccount(domain, "writer", "a long writer password", "Writer", "") if err != nil { t.Fatal(err) } authorToken, err := s.store.CreateAuthSession(domain, author.UUID) if err != nil { t.Fatal(err) } var role string if err = s.store.DB.QueryRow(`SELECT b.role_uuid FROM auth_role_bindings b JOIN domain_memberships m ON m.uuid=b.membership_uuid WHERE m.domain_uuid=? AND m.principal_uuid=?`, domain, author.UUID).Scan(&role); err != nil { t.Fatal(err) } if _, err = s.store.DB.Exec(`DELETE FROM auth_capability_grants WHERE role_uuid=?`, role); err != nil { t.Fatal(err) } for _, capability := range []string{"read", "write"} { if _, err = s.store.DB.Exec(`INSERT INTO auth_capability_grants(uuid,role_uuid,capability,target_type,target_id,created_at_ms) VALUES(?,?,?,'path','/guide',1)`, "writer-"+capability, role, capability); err != nil { t.Fatal(err) } } payload, _ := json.Marshal(map[string]any{"object_uuid": object, "body": body, "content_type": "text/html", "filename": "guide.html", "lang": "en"}) request := httptest.NewRequest("POST", "http://localhost/_/api/v1/revisions/save", bytes.NewReader(payload)) request.Header.Set("Authorization", "Bearer "+authorToken) request.Header.Set("Content-Type", "application/json") response := httptest.NewRecorder() s.withAuthorization(s.mux).ServeHTTP(response, request) if w := response; w.Code != 200 { t.Fatalf("author save=%d %s", w.Code, w.Body.String()) } rev, err := s.store.GetLatestRevisionForLanguages(object, []string{"en"}) if err != nil { t.Fatal(err) } userObject, err := s.store.CreatePageAtPathInDomain(domain, "/u/admin") if err != nil { t.Fatal(err) } if _, err = s.store.SaveRevisionContent(userObject, []byte(body), "", "en", "text/html", "profile.html"); err != nil { t.Fatal(err) } if err = s.store.SetConfigInDomain(domain, "home_path", "/guide"); err != nil { t.Fatal(err) } routes := []string{"/guide", "/", "/o/uuid:" + object, "/r/view/" + rev.UUID, "/v/preview/guide", "/_/view/print/path:/guide", "/u/admin", "/e/-/guide?edittype=html", "/e/-/guide?edittype=markdown"} script, err := os.ReadFile("internal/server/testdata/html-projection.js") if err != nil { t.Fatal(err) } var hits atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.Host = "localhost" r.Header.Set("Authorization", "Bearer "+token) switch r.URL.Path { case "/fixture": w.Header().Set("Content-Type", "text/html") _, _ = io.WriteString(w, `

HTML isolation regression

`) return case "/fixture-state": w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"routes": routes, "body": rev.Body, "hits": hits.Load()}) return case "/sentinel": hits.Add(1) w.WriteHeader(204) return case "/static/attack.js": w.Header().Set("Content-Type", "text/javascript") _, _ = io.WriteString(w, `document.documentElement.dataset.attack='external';fetch('/sentinel',{method:'POST'})`) return } if r.Method == http.MethodGet && (r.URL.Path == "/" || r.URL.Path == "/guide" || strings.HasPrefix(r.URL.Path, "/o/") || strings.HasPrefix(r.URL.Path, "/r/view/") || strings.HasPrefix(r.URL.Path, "/v/preview/") || strings.HasPrefix(r.URL.Path, "/_/view/print/") || strings.HasPrefix(r.URL.Path, "/u/") || strings.HasPrefix(r.URL.Path, "/e/")) { rec := httptest.NewRecorder() s.withAuthorization(s.mux).ServeHTTP(rec, r) for key, values := range rec.Header() { w.Header()[key] = values } w.WriteHeader(rec.Code) // Parser-inserted, deliberately unnonced probes test CSP separately // from sanitizer correctness, without disabling the real headers. probe := `` _, _ = io.WriteString(w, strings.Replace(rec.Body.String(), "", probe+"", 1)) return } s.withAuthorization(s.mux).ServeHTTP(w, r) })) defer server.Close() ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second) defer cancel() cmd := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", server.URL+"/fixture", t.TempDir()) if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("browser: %v %s", err, out) } if hits.Load() != 0 { t.Fatalf("authored content issued %d privileged requests", hits.Load()) } after, err := s.store.GetRevision(rev.UUID) if err != nil || after.DocumentHash != rev.DocumentHash || after.Body != rev.Body { t.Fatal("browser projection altered canonical source") } t.Log(fmt.Sprintf("verified %d display/editor routes as a stronger reader", len(routes))) } // Match CSP when installing only fixture-owned code. This does not disable CSP // and authored corpus nodes never receive the application's nonce. func TestHTMLProjectionCSPRejectsUnnoncedMarkup(t *testing.T) { s, token, _ := configFixture(t) s.mux.HandleFunc("/", s.handleHome) w := configRequest(s, token, "GET", "/", nil) if w.Code != 200 || strings.Contains(w.Header().Get("Content-Security-Policy"), "script-src 'self'") { t.Fatal("unsafe script origin allowlist") } }