Files
magpie/internal/gateway/search_base_url_test.go
T
yetone 1c0eab7c84 gui, gateway: every search API takes a base URL of the user's own, under its key in Settings (#1580, xzhlksh)
The reporter has endpoints that answer as Tavily, Exa and others do, at
addresses that aren't the vendors', and Settings only took a key. The
saved SearchAPI already had a url, and the CLI's url= set it, but the
Settings row showed the field only for SearXNG and sent "" for the rest.

- Settings › Models › Web search: the add row has a base URL field on a
  line of its own under the key, for every API, with the vendor's own
  address as its placeholder (searchVendorJSON.base). Picking an API
  already added fills in its saved URL, so Add with a new key alone keeps
  it; Add with no key typed changes only the URL, the key kept (the key
  placeholder says so). Strings in zh, zh-TW, ja, de.
- provider: check() also refuses a URL with a ?query or #fragment, since
  the vendor's path goes after it.
- gateway: the key goes only to the URL set. Go drops Authorization on a
  redirect to another host but keeps Brave's X-Subscription-Token and
  Exa's x-api-key, so a search API's redirect to another host is not
  followed; the error names where it was sent. The request still goes
  through the gateway's client and so magpie's proxy settings.
- CLI: `magpie search add <api> <key>` keeps the url set before; `url=`
  with nothing after it puts the vendor's own back (was: a new key alone
  dropped the url).
- docs/subsystems/gateway-routing.md: "A search API's base URL";
  gui-shell.md: the field.
- search-api.test.cjs: Settings is drawn twice (/api/state, then
  /api/settings), so scrolling to the add row can hit a detached node
  (WebKit, 1 in ~6 runs here); it retries the scroll.

magpie ships and lists no third-party search endpoint; the URL is only
the user's.

Tests (sandbox HOME, pinned caches):
- TestSearchAPIAtItsOwnBaseURL: an httptest fake at <fake>/relay/<vendor>/
  gets tavily POST /relay/tavily/search with Bearer, exa POST
  /relay/exa/search with x-api-key, brave GET
  /relay/brave/res/v1/web/search with X-Subscription-Token, firecrawl
  POST /relay/firecrawl/v2/search with Bearer. Passes on the old gateway
  too: the backend already honoured a url.
- TestSearchKeyStaysAtItsBaseURL: with search_api.go put back, FAIL
  "a key reached another host: exa-secret / brave-secret".
- TestSearchCLI: with search_cli.go put back, FAIL "a new key took the
  base URL away"; with provider/search_api.go put back, FAIL
  "url=https://x.example.com/?k=1 taken".
- TestSearchAPIBaseURLFromSettings: POST /api/settings/search-api saves,
  keeps the key, refuses ftp/no-scheme/query URLs, lists vendor bases.
- search-api.test.cjs in Chromium and WebKit, en and zh, 980px and
  420px: 8/8; with the old app.js, FAIL "Tavily takes a base URL"
  (false !== true). WebKit 980px 10 runs in a row green after the retry.
  search-first, search-mcp, searcher-pick, i18n-keys, gui-ja, gui-de,
  gui-zh-tw, click-scroll with it: 45/45 in each engine.
- Screenshots at 980/420 in both engines checked by eye.
- go test -tags nogui -timeout 40m ./... on 5fa908c08 + this: all 48 packages ok. gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags nogui on ., internal/gateway, internal/gui, internal/provider: clean.

Not tried against a real third-party endpoint or a real vendor key.
2026-10-11 14:21:29 +08:00

115 lines
4.2 KiB
Go

package gateway
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A search API set at a base URL of the user's own (#1580: an endpoint
// that answers as Tavily, Exa… do) is asked there, at the vendor's path
// under it, with the key carried the vendor's way; the vendor's own
// address is never asked.
func TestSearchAPIAtItsOwnBaseURL(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
type got struct{ method, path, auth string }
var mu sync.Mutex
var asked []got
own := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
asked = append(asked, got{r.Method, r.URL.Path, r.Header.Get("Authorization") + r.Header.Get("x-api-key") + r.Header.Get("X-Subscription-Token")})
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
if strings.HasSuffix(r.URL.Path, "/res/v1/web/search") {
io.WriteString(w, `{"web":{"results":[{"title":"Go downloads","url":"https://go.dev/dl/","description":"Go 1.27.1"}]}}`)
return
}
if strings.HasSuffix(r.URL.Path, "/v2/search") {
io.WriteString(w, `{"success":true,"data":{"web":[{"title":"Go downloads","url":"https://go.dev/dl/","description":"Go 1.27.1"}]}}`)
return
}
io.WriteString(w, `{"results":[{"title":"Go downloads","url":"https://go.dev/dl/","content":"Go 1.27.1"}]}`)
}))
t.Cleanup(own.Close)
s := New()
for _, c := range []struct {
vendor, key string
want got
}{
{"tavily", "tvly-k", got{"POST", "/relay/tavily/search", "Bearer tvly-k"}},
{"exa", "exa-k", got{"POST", "/relay/exa/search", "exa-k"}},
{"brave", "brave-k", got{"GET", "/relay/brave/res/v1/web/search", "brave-k"}},
{"firecrawl", "fc-k", got{"POST", "/relay/firecrawl/v2/search", "Bearer fc-k"}},
} {
// as Settings saves it: the base URL typed with a slash at its end
if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: c.vendor, Key: c.key, URL: own.URL + "/relay/" + c.vendor + "/"}); err != nil {
t.Fatal(err)
}
var a provider.SearchAPI
for _, x := range provider.SearchAPIs() {
if x.Vendor == c.vendor {
a = x
}
}
mu.Lock()
asked = nil
mu.Unlock()
pages, err := s.askSearchAPIKeys(context.Background(), a, "latest go")
if err != nil || len(pages) != 1 || pages[0].URL != "https://go.dev/dl/" {
t.Errorf("%s: %v %+v", c.vendor, err, pages)
}
mu.Lock()
if len(asked) != 1 || asked[0] != c.want {
t.Errorf("%s asked %+v, want %+v", c.vendor, asked, c.want)
}
mu.Unlock()
}
}
// The key goes only to the base URL set: an endpoint there that sends the
// search on to another host doesn't take the key with it (Go keeps Brave's
// and Exa's own key headers across such a redirect), and the error says
// where it was sent.
func TestSearchKeyStaysAtItsBaseURL(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
var mu sync.Mutex
var elsewhere []string
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
elsewhere = append(elsewhere, r.Header.Get("Authorization")+r.Header.Get("x-api-key")+r.Header.Get("X-Subscription-Token"))
mu.Unlock()
io.WriteString(w, `{"results":[{"title":"Go downloads","url":"https://go.dev/dl/","content":"Go 1.27.1"}],"web":{"results":[{"title":"Go","url":"https://go.dev/dl/"}]}}`)
}))
t.Cleanup(other.Close)
// the same address by another name is another host
away := strings.Replace(other.URL, "127.0.0.1", "localhost", 1)
own := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, away+r.URL.Path, http.StatusTemporaryRedirect)
}))
t.Cleanup(own.Close)
s := New()
for _, vendor := range []string{"exa", "brave", "tavily"} {
a := provider.SearchAPI{Vendor: vendor, Key: vendor + "-secret", URL: own.URL}
_, err := s.askSearchAPIKeys(context.Background(), a, "q")
if err == nil || !strings.Contains(err.Error(), away) {
t.Errorf("%s: %v", vendor, err)
}
}
mu.Lock()
defer mu.Unlock()
for _, k := range elsewhere {
if k != "" {
t.Errorf("a key reached another host: %q", k)
}
}
if len(elsewhere) != 0 {
t.Errorf("the search was sent on to another host %d times", len(elsewhere))
}
}