package server import ( "context" "encoding/json" "errors" "fmt" "html" "io" "net/http" "net/http/httptest" "net/url" "os" "os/exec" "path/filepath" "strings" "testing" "time" ) func searchServerFixture(t *testing.T) (*Server, string, string) { t.Helper() s, token, domain := configFixture(t) s.mux.HandleFunc("/v/search", s.handleSearch) for _, item := range []struct{ path, body, filename string }{ {"/docs/nebula guide?#%", `

Nebula Handbook

Introduction to the NEBULA and nearby stars.

<img src=x onerror=alert(1)>

`, "nebula .html"}, {"/docs/hidden", "nebula SECRET_EXCERPT", "SECRET_FILENAME.txt"}, } { object, err := s.store.CreatePageAtPathInDomain(domain, item.path) if err != nil { t.Fatal(err) } if _, err := s.store.SaveRevisionContent(object, []byte(item.body), "", "en", "text/html", item.filename); err != nil { t.Fatal(err) } } principal, err := s.store.PrincipalForSession(domain, token) 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=? LIMIT 1`, domain, principal.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 i, path := range []string{"/", "/docs/nebula guide?#%"} { if _, err := s.store.DB.Exec(`INSERT INTO auth_capability_grants(uuid,role_uuid,capability,target_type,target_id,created_at_ms) VALUES(?,?,'read','path',?,1)`, "search-read-"+string(rune('0'+i)), role, path); err != nil { t.Fatal(err) } } return s, token, domain } func TestSearchSuggestionsDirectACLAndHeading(t *testing.T) { s, token, _ := searchServerFixture(t) s.mux.HandleFunc("/_/api/v1/search/suggest", s.handleSearchSuggestAPI) response := configRequest(s, token, "GET", "/_/api/v1/search/suggest?q=handbook", nil) if response.Code != http.StatusOK { t.Fatalf("suggest: %d %s", response.Code, response.Body.String()) } var payload struct { Items []searchSuggestionItem `json:"items"` } if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil { t.Fatal(err) } if len(payload.Items) != 1 || payload.Items[0].Label != "Nebula Handbook" || payload.Items[0].Path != "/docs/nebula guide?#%" || payload.Items[0].Href != "/docs/nebula%20guide%3F%23%25" { t.Fatalf("suggestions: %#v", payload.Items) } response = configRequest(s, token, "GET", "/_/api/v1/search/suggest?q=Nebula%20Handbook", nil) if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &payload) != nil || len(payload.Items) == 0 || !payload.Items[0].Exact { t.Fatalf("exact suggestion: %d %s", response.Code, response.Body.String()) } response = configRequest(s, token, "GET", "/_/api/v1/search/suggest?q=SECRET", nil) payload.Items = nil if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &payload) != nil || len(payload.Items) != 0 { t.Fatalf("hidden suggestion leaked: %d %s", response.Code, response.Body.String()) } response = configRequest(s, token, "GET", "/_/api/v1/search/suggest?q=n", nil) if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"items":[]`) { t.Fatalf("short suggestion query: %d %s", response.Code, response.Body.String()) } } func TestSearchResultsSafeContextAndACL(t *testing.T) { s, token, _ := searchServerFixture(t) response := configRequest(s, token, "GET", "/v/search?q=nebula&scope=/", nil) if response.Code != http.StatusOK { t.Fatalf("search: %d %s", response.Code, response.Body.String()) } body := response.Body.String() for _, required := range []string{`class="search-result-name"`, `class="search-result-path"`, `class="search-result-excerpt"`, `data-match-source="path"`, `data-match-source="filename"`, `data-match-source="body"`, `NEBULA`, `/docs/nebula%20guide%3F%23%25`, `<svg onload=alert(1)>`, `data-search-view="list"`} { if !strings.Contains(body, required) { t.Errorf("missing search presentation %q", required) } } for _, forbidden := range []string{"SECRET_EXCERPT", "SECRET_FILENAME", "/docs/hidden", "PRIVATE_SCRIPT", "Hello & nebula.

`, "text/html", "nebula") if strings.Contains(value, "evil") || strings.Contains(value, "secret") || strings.Contains(value, "<") || !strings.Contains(value, "Hello & nebula") { t.Fatalf("HTML text extraction: %q", value) } long := strings.Repeat("遠い星 ", 100) + "NEBULA nearby context " + strings.Repeat("stars ", 100) value = searchExcerpt(long, "text/plain", "nebula") if !strings.Contains(value, "NEBULA") || len([]rune(value)) > 265 { t.Fatalf("context window: %q", value) } parts := highlightSearchText(`日本語 NEBULA ", 1)) return } s.withAuthorization(s.mux).ServeHTTP(w, r) })) defer server.Close() for _, view := range []struct{ name, width, height string }{{"desktop", "1440", "1000"}, {"mobile", "390", "844"}} { t.Run(view.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second) defer cancel() command := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", server.URL+"/v/search?q="+url.QueryEscape("nebula"), t.TempDir()) screenshot := "" if dir := os.Getenv("PAGESWIKI_BROWSER_ARTIFACTS"); dir != "" { if err := os.MkdirAll(dir, 0755); err != nil { t.Fatal(err) } screenshot = filepath.Join(dir, "search-results-"+view.name+".png") } command.Args = append(command.Args, screenshot, view.width, view.height) if out, err := command.CombinedOutput(); err != nil { t.Fatalf("browser: %v\n%s", err, out) } }) } }