package app
import (
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/netip"
"net/url"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
)
// publicFixture is fixtureService with the public endpoint enabled. Its public
// decision model forwards to the fixture model and counts the calls it gets.
func publicFixture(t *testing.T, perMinute, daily int) (*Service, *atomic.Int32) {
t.Helper()
s, _ := fixtureService(t)
public, err := openLog(filepath.Join(t.TempDir(), "public.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { public.db.Close() })
s.log.public = public
s.gate = newPublicGate(perMinute, daily)
target, _ := url.Parse(s.jev.URL)
var calls atomic.Int32
proxy := httputil.NewSingleHostReverseProxy(target)
clef := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
proxy.ServeHTTP(w, r)
}))
t.Cleanup(clef.Close)
s.publicJev = &Jev{URL: clef.URL, Key: "model-secret", Model: "clef-test", HTTP: clef.Client(), Log: s.log, slots: make(chan struct{}, 4)}
return s, &calls
}
func rows(t *testing.T, l *Log, table string) int {
t.Helper()
var n int
if err := l.db.QueryRow("select count(*) from " + table).Scan(&n); err != nil {
t.Fatal(err)
}
return n
}
const searchCall = `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"web_search","arguments":{"query":"request size","numResults":1}}}`
func TestPublicCallsAreServedWithoutATokenAndLoggedOnlyOnOptIn(t *testing.T) {
s, clefCalls := publicFixture(t, 100, 100)
h := s.handler()
if w := adminCall(h, "POST", "/mcp", searchCall, nil, nil); w.Code != 200 {
t.Fatalf("public call: %d %s", w.Code, w.Body.String())
}
if clefCalls.Load() == 0 {
t.Fatal("public call did not use the public decision model")
}
for _, table := range []string{"requests", "decisions"} {
if rows(t, s.log, table) != 0 || rows(t, s.log.public, table) != 0 {
t.Fatalf("a call without opt-in was logged in %s", table)
}
}
if w := adminCall(h, "POST", "/mcp", searchCall, nil, map[string]string{"X-Contribute": "1"}); w.Code != 200 {
t.Fatal(w.Code)
}
if w := adminCall(h, "POST", "/mcp/contribute", searchCall, nil, nil); w.Code != 200 {
t.Fatal(w.Code)
}
if rows(t, s.log.public, "requests") != 2 || rows(t, s.log.public, "decisions") == 0 {
t.Fatal("opted-in calls were not logged to the public log")
}
if rows(t, s.log, "requests") != 0 {
t.Fatal("public calls reached the main log")
}
before := clefCalls.Load()
if w := adminCall(h, "POST", "/mcp", searchCall, nil, map[string]string{"Authorization": "Bearer test-token"}); w.Code != 200 {
t.Fatal(w.Code)
}
if clefCalls.Load() != before || rows(t, s.log, "requests") != 1 {
t.Fatal("an authenticated call changed model or skipped the main log")
}
if w := adminCall(h, "POST", "/mcp", searchCall, nil, map[string]string{"Authorization": "Bearer wrong"}); w.Code != 401 {
t.Fatal("a wrong token fell through to public access")
}
if w := adminCall(h, "GET", "/", "", nil, nil); w.Code != 200 || w.Header().Get("Content-Type") != "text/html; charset=utf-8" {
t.Fatal("no notice page")
}
w := adminCall(h, "GET", "/docs", "", nil, nil)
for _, want := range []string{"web_search", "numResults", "integer", "query
string, required", "POST /mcp/contribute"} {
if w.Code != 200 || !strings.Contains(w.Body.String(), want) {
t.Fatalf("api page lacks %q", want)
}
}
}
func TestPublicAccessIsOffUnlessEnabled(t *testing.T) {
s, _ := fixtureService(t)
if w := adminCall(s.handler(), "POST", "/mcp", searchCall, nil, nil); w.Code != 401 {
t.Fatal(w.Code)
}
if w := adminCall(s.handler(), "GET", "/", "", nil, nil); w.Code != 401 {
t.Fatal(w.Code)
}
}
func TestPublicRateLimits(t *testing.T) {
s, _ := publicFixture(t, 3, 2)
h := s.handler()
list := `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`
// Two tool calls use up the day; a listing still works until the minute's limit.
for i, body := range []string{searchCall, searchCall, list} {
if w := adminCall(h, "POST", "/mcp", body, nil, nil); w.Code != 200 {
t.Fatalf("call %d: %d", i, w.Code)
}
}
w := adminCall(h, "POST", "/mcp", list, nil, nil)
if w.Code != 429 {
t.Fatal("per-minute limit not applied", w.Code)
}
if wait, err := strconv.Atoi(w.Header().Get("Retry-After")); err != nil || wait < 1 || wait > 60 {
t.Fatal("bad Retry-After", w.Header().Get("Retry-After"))
}
g := newPublicGate(3, 2)
now := time.Date(2026, 10, 17, 23, 59, 30, 0, time.UTC)
g.now = func() time.Time { return now }
a, b := netip.MustParseAddr("192.0.2.1"), netip.MustParseAddr("192.0.2.2")
for range 2 {
if ok, _ := g.admit(a, true); !ok {
t.Fatal("refused within limits")
}
}
if ok, wait := g.admit(b, true); ok || wait != 31 {
t.Fatal("daily limit not shared across clients", ok, wait)
}
if ok, _ := g.admit(b, false); !ok {
t.Fatal("a listing counted against the daily limit")
}
now = now.Add(time.Minute)
if ok, _ := g.admit(b, true); !ok {
t.Fatal("limits did not reset at midnight UTC")
}
v6 := newPublicGate(2, 0)
for _, addr := range []string{"2001:db8:1:2::a", "2001:db8:1:2::b"} {
if ok, _ := v6.admit(netip.MustParseAddr(addr), false); !ok {
t.Fatal("refused within limits")
}
}
if ok, _ := v6.admit(netip.MustParseAddr("2001:db8:1:2:ffff::1"), false); ok {
t.Fatal("addresses in one IPv6 /64 were counted separately")
}
if ok, _ := v6.admit(netip.MustParseAddr("2001:db8:1:3::1"), false); !ok {
t.Fatal("another /64 shared the limit")
}
unlimited := newPublicGate(1000, 0)
for range 600 {
if ok, _ := unlimited.admit(a, true); !ok {
t.Fatal("a zero daily limit capped calls")
}
}
}
func TestClientAddrTrustsOnlyConfiguredProxies(t *testing.T) {
proxy := []netip.Prefix{netip.MustParsePrefix("100.64.0.9/32")}
r := httptest.NewRequest("POST", "/mcp", nil)
r.Header.Set("X-Forwarded-For", "203.0.113.5, 198.51.100.7")
r.RemoteAddr = "100.64.0.9:41000"
if got := clientAddr(r, proxy); got != netip.MustParseAddr("198.51.100.7") {
t.Fatal("trusted proxy's appended address not used", got)
}
r.RemoteAddr = "192.0.2.9:41000"
if got := clientAddr(r, proxy); got != netip.MustParseAddr("192.0.2.9") {
t.Fatal("an untrusted peer chose its own address", got)
}
}
func TestPublicDecisionModelFallsBackWhenItFails(t *testing.T) {
s, clefCalls := publicFixture(t, 100, 0)
broken := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, `{"error":"out of daily allocation"}`, http.StatusTooManyRequests)
}))
t.Cleanup(broken.Close)
fallback := s.publicJev
s.publicJev = &Jev{URL: broken.URL, Key: "model-secret", Model: "clef-broken", HTTP: broken.Client(), Log: s.log, slots: make(chan struct{}, 4), Fallback: fallback}
w := adminCall(s.handler(), "POST", "/mcp/contribute", searchCall, nil, nil)
if w.Code != 200 || strings.Contains(w.Body.String(), `"isError":true`) {
t.Fatalf("search failed instead of falling back: %d %s", w.Code, w.Body.String())
}
if clefCalls.Load() == 0 {
t.Fatal("the fallback model was not called")
}
var models string
if err := s.log.public.db.QueryRow("select group_concat(distinct model) from decisions").Scan(&models); err != nil || !strings.Contains(models, "jev-test") {
t.Fatalf("decisions do not name the model that answered: %q %v", models, err)
}
}
|