feat(searxng): enhance SearXNG configuration and validation

- Updated .env.example to clarify SEARXNG_SECRET generation and added SSRF_WHITELIST_EXTRA for improved security.
- Modified docker-compose files to bind SearXNG to localhost by default and introduced a one-time initialization service to set up settings.yml correctly.
- Enhanced SearxngProvider with stricter URL validation, ensuring no query or fragment is present in the base URL.
- Added unit tests for SearXNG validation and date parsing to ensure robustness.
- Updated frontend WebSearchSettings to reflect changes in SearXNG instance URL handling.

This commit improves the security and usability of the SearXNG integration, addressing potential misconfigurations and enhancing the developer experience.
This commit is contained in:
wizardchen
2026-05-10 22:51:24 +08:00
committed by lyingbug
parent d2a1006beb
commit 0f5dc41f4e
7 changed files with 232 additions and 14 deletions
@@ -16,7 +16,10 @@ import (
"github.com/Tencent/WeKnora/internal/utils"
)
const defaultSearxngTimeout = 15 * time.Second
// defaultSearxngTimeout is sized slightly above the SearXNG image's default
// outgoing.max_request_timeout (10s in docker/searxng/settings.yml) so a slow
// upstream engine surfaces as a SearXNG-side error instead of a client cancel.
const defaultSearxngTimeout = 12 * time.Second
// SearxngProvider implements web search using a self-hosted SearXNG instance.
//
@@ -49,6 +52,9 @@ func ValidateSearxngBaseURL(rawURL string) error {
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return fmt.Errorf("invalid SearXNG base_url scheme: %s", parsed.Scheme)
}
if parsed.RawQuery != "" || parsed.Fragment != "" {
return fmt.Errorf("invalid SearXNG base_url: must not contain query or fragment")
}
if err := utils.ValidateURLForSSRF(base); err != nil {
return fmt.Errorf("invalid SearXNG base_url: %w", err)
}
@@ -163,9 +169,10 @@ func (p *SearxngProvider) Search(
// searxngDateLayouts covers the formats different SearXNG engines emit for
// publishedDate. Order matters only for performance; first match wins.
// time.RFC3339 already accepts the nanosecond-precision form, so RFC3339Nano
// is intentionally omitted.
var searxngDateLayouts = []string{
time.RFC3339,
time.RFC3339Nano,
"2006-01-02T15:04:05",
"2006-01-02 15:04:05",
"2006-01-02",
@@ -187,7 +194,6 @@ func parseSearxngDate(s string) (time.Time, bool) {
}
type searxngResponse struct {
Query string `json:"query"`
Results []struct {
Title string `json:"title"`
URL string `json:"url"`
@@ -0,0 +1,111 @@
package web_search
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
)
func TestValidateSearxngBaseURL(t *testing.T) {
os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
defer os.Unsetenv("SSRF_WHITELIST")
cases := []struct {
name string
url string
wantErr bool
}{
{name: "empty", url: "", wantErr: true},
{name: "no scheme", url: "searxng:8080", wantErr: true},
{name: "bad scheme", url: "ftp://searxng:8080", wantErr: true},
{name: "with query", url: "http://127.0.0.1:8080/?x=1", wantErr: true},
{name: "with fragment", url: "http://127.0.0.1:8080/#frag", wantErr: true},
{name: "loopback ok via whitelist", url: "http://127.0.0.1:8888", wantErr: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := ValidateSearxngBaseURL(tc.url)
if (err != nil) != tc.wantErr {
t.Fatalf("ValidateSearxngBaseURL(%q) err=%v wantErr=%v", tc.url, err, tc.wantErr)
}
})
}
}
func TestParseSearxngDate(t *testing.T) {
cases := []struct {
in string
ok bool
}{
{"", false},
{"2024-05-01", true},
{"2024-05-01T12:30:45", true},
{"2024-05-01T12:30:45Z", true},
{"2024-05-01T12:30:45.123456789Z", true},
{"2024-05-01 12:30:45", true},
{"Wed, 01 May 2024 12:30:45 GMT", true},
{"not-a-date", false},
}
for _, tc := range cases {
t.Run(tc.in, func(t *testing.T) {
_, ok := parseSearxngDate(tc.in)
if ok != tc.ok {
t.Fatalf("parseSearxngDate(%q) ok=%v want=%v", tc.in, ok, tc.ok)
}
})
}
}
func TestSearxngProvider_Search(t *testing.T) {
os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
defer os.Unsetenv("SSRF_WHITELIST")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/search" {
http.NotFound(w, r)
return
}
if got := r.URL.Query().Get("format"); got != "json" {
t.Errorf("expected format=json, got %q", got)
}
if got := r.URL.Query().Get("q"); got != "hello" {
t.Errorf("expected q=hello, got %q", got)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"results": []map[string]any{
{"title": "T1", "url": "https://e/1", "content": "c1", "publishedDate": "2024-05-01"},
{"title": "", "url": "https://e/skip"},
{"title": "T2", "url": "https://e/2", "content": "c2"},
},
})
}))
defer srv.Close()
provider, err := NewSearxngProvider(types.WebSearchProviderParameters{BaseURL: srv.URL})
if err != nil {
t.Fatalf("NewSearxngProvider: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
results, err := provider.Search(ctx, "hello", 5, true)
if err != nil {
t.Fatalf("Search: %v", err)
}
if len(results) != 2 {
t.Fatalf("expected 2 results (one skipped), got %d", len(results))
}
if results[0].PublishedAt == nil {
t.Fatalf("expected first result PublishedAt to be set")
}
if got := results[0].Source; got != "searxng" {
t.Fatalf("unexpected source: %q", got)
}
}