mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
GHSA-39w9: POST /api/llm/test accepted any base_url and proxy, made a real request with them, returned the reply and the provider error text, and followed redirects without an address check, while POST /api/llm/models was already guarded. The test now validates the base URL and the proxy through the same guard, dials and revalidates every redirect through it, and never reads the *_PROXY environment. Only public addresses are accepted. The code-owned default Ollama endpoint keeps working; an exact host:port in ARTEX_LLM_PRIVATE_ENDPOINTS is the documented way to test a local model server. The test button refuses SOCKS5 proxies because the guard cannot see the destination behind them.
178 lines
7.4 KiB
Go
178 lines
7.4 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/netip"
|
|
"strings"
|
|
"sync/atomic"
|
|
"testing"
|
|
)
|
|
|
|
// POST /api/llm/test dials the base_url and proxy the form names, and returns
|
|
// the reply or the error text. It applies the same guard as POST
|
|
// /api/llm/models: the URLs are validated before anything is sent, and the
|
|
// connection is dialed through the guard.
|
|
|
|
// failDials returns a dial function that fails the test: a dial reaching it
|
|
// means a request left without the guard's consent. It never opens a socket.
|
|
func failDials(t *testing.T, what string) func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
return func(_ context.Context, network, addr string) (net.Conn, error) {
|
|
t.Errorf("%s dialed %s %s", what, network, addr)
|
|
return nil, errors.New("dial refused by the test")
|
|
}
|
|
}
|
|
|
|
// failDefaultTransportDials makes every client cloned from
|
|
// http.DefaultTransport fail the test on its first dial, for the duration of
|
|
// the test. No server-package test runs in parallel with a sequential one.
|
|
func failDefaultTransportDials(t *testing.T) {
|
|
orig := http.DefaultTransport
|
|
tr := orig.(*http.Transport).Clone()
|
|
tr.Proxy = nil
|
|
tr.DialContext = failDials(t, "a client cloned from http.DefaultTransport")
|
|
http.DefaultTransport = tr
|
|
t.Cleanup(func() { http.DefaultTransport = orig })
|
|
}
|
|
|
|
func llmTestResolver(_ context.Context, host string) ([]netip.Addr, error) {
|
|
switch host {
|
|
case "api.public.example":
|
|
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
|
|
case "metadata.attacker.example":
|
|
return []netip.Addr{netip.MustParseAddr("169.254.169.254")}, nil
|
|
case "intranet.attacker.example":
|
|
return []netip.Addr{netip.MustParseAddr("10.20.30.40")}, nil
|
|
}
|
|
return nil, &net.DNSError{Err: "no such host", Name: host}
|
|
}
|
|
|
|
// Loopback, private and metadata endpoints and proxies are refused before any
|
|
// dial, whether named by IP literal or by a name resolving there.
|
|
func TestLLMTestRefusesNonPublicTargetsBeforeDial(t *testing.T) {
|
|
t.Setenv(LLMPrivateEndpointsEnv, "")
|
|
failDefaultTransportDials(t)
|
|
s := &Server{modelLookupIP: llmTestResolver}
|
|
s.modelDialContext = failDials(t, "the guarded transport")
|
|
|
|
for _, tc := range []struct {
|
|
name, baseURL, proxy, noLeak string
|
|
}{
|
|
{"loopback", "http://127.0.0.1:8080/v1", "", "127.0.0.1"},
|
|
{"loopback_v6", "http://[::1]:8080/v1", "", "::1"},
|
|
{"localhost_name", "http://localhost:11434/v1", "", "127.0.0.1"},
|
|
{"metadata_ip", "http://169.254.169.254/latest/meta-data", "", "169.254.169.254"},
|
|
{"metadata_name", "http://metadata.attacker.example/v1", "", "169.254.169.254"},
|
|
{"alibaba_metadata", "http://100.100.100.200/latest", "", "100.100.100.200"},
|
|
{"private_name", "http://intranet.attacker.example:8080/v1", "", "10.20.30.40"},
|
|
{"loopback_proxy", "http://api.public.example/v1", "http://127.0.0.1:3128", "127.0.0.1"},
|
|
{"metadata_proxy", "http://api.public.example/v1", "http://169.254.169.254:80", "169.254.169.254"},
|
|
{"private_proxy_name", "http://api.public.example/v1", "http://intranet.attacker.example:3128", "10.20.30.40"},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
resp := postJSON(t, s.testLLM, "/api/llm/test", map[string]any{
|
|
"provider": "openai", "model": "m", "base_url": tc.baseURL, "proxy": tc.proxy,
|
|
"api_key": "sk-test", "streaming": false,
|
|
})
|
|
if resp["ok"] != false {
|
|
t.Fatalf("expected ok=false, got %v", resp)
|
|
}
|
|
errMsg, _ := resp["error"].(string)
|
|
if errMsg == "" || strings.Contains(errMsg, tc.noLeak) {
|
|
t.Fatalf("refusal %q must be non-empty and must not name %q", errMsg, tc.noLeak)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
const anthropicOKReply = `{"id":"m","type":"message","role":"assistant","model":"m","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`
|
|
|
|
// A public endpoint still works, and its request goes through the guarded
|
|
// transport: the injected resolver and dialer route it to a local fake, and a
|
|
// client cloned from http.DefaultTransport would fail the test.
|
|
func TestLLMTestPublicEndpointUsesGuardedTransport(t *testing.T) {
|
|
t.Setenv(LLMPrivateEndpointsEnv, "")
|
|
var hits atomic.Int32
|
|
var host atomic.Value
|
|
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
hits.Add(1)
|
|
host.Store(r.Host)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(anthropicOKReply))
|
|
}))
|
|
t.Cleanup(fake.Close)
|
|
failDefaultTransportDials(t)
|
|
s := &Server{modelLookupIP: llmTestResolver}
|
|
s.modelDialContext = dialTestServerForHosts(
|
|
map[string]string{"api.public.example:80": fake.Listener.Addr().String()},
|
|
failDials(t, "the guarded transport (unrouted address)"),
|
|
)
|
|
|
|
resp := postJSON(t, s.testLLM, "/api/llm/test", map[string]any{
|
|
"provider": "anthropic", "model": "m", "base_url": "http://api.public.example",
|
|
"api_key": "k", "streaming": false,
|
|
})
|
|
if resp["ok"] != true || hits.Load() != 1 {
|
|
t.Fatalf("public endpoint: resp=%v hits=%d", resp, hits.Load())
|
|
}
|
|
if h, _ := host.Load().(string); h != "api.public.example" {
|
|
t.Fatalf("request Host = %q, want api.public.example", h)
|
|
}
|
|
}
|
|
|
|
// A redirect from a public endpoint to a metadata address is refused before
|
|
// it is followed: through an HTTP proxy, the dial guard alone would not see it.
|
|
func TestLLMTestRefusesRedirectToMetadata(t *testing.T) {
|
|
t.Setenv(LLMPrivateEndpointsEnv, "")
|
|
var hits atomic.Int32
|
|
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
hits.Add(1)
|
|
http.Redirect(w, r, "http://169.254.169.254/latest/meta-data/", http.StatusTemporaryRedirect)
|
|
}))
|
|
t.Cleanup(fake.Close)
|
|
failDefaultTransportDials(t)
|
|
s := &Server{modelLookupIP: llmTestResolver}
|
|
s.modelDialContext = dialTestServerForHosts(
|
|
map[string]string{"api.public.example:80": fake.Listener.Addr().String()},
|
|
failDials(t, "the guarded transport (redirect target)"),
|
|
)
|
|
|
|
resp := postJSON(t, s.testLLM, "/api/llm/test", map[string]any{
|
|
"provider": "anthropic", "model": "m", "base_url": "http://api.public.example",
|
|
"api_key": "k", "streaming": false,
|
|
})
|
|
if resp["ok"] != false || hits.Load() == 0 {
|
|
t.Fatalf("redirect to metadata: resp=%v hits=%d", resp, hits.Load())
|
|
}
|
|
if errMsg, _ := resp["error"].(string); !strings.Contains(errMsg, "not allowed") {
|
|
t.Fatalf("redirect refusal = %q, want the guard's refusal", errMsg)
|
|
}
|
|
}
|
|
|
|
// The code-owned Ollama default (empty base_url) stays testable without an
|
|
// allow-list entry, as it is for the model listing.
|
|
func TestLLMTestDefaultOllamaAllowed(t *testing.T) {
|
|
t.Setenv(LLMPrivateEndpointsEnv, "")
|
|
var hits atomic.Int32
|
|
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
hits.Add(1)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"id":"c","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"OK"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`))
|
|
}))
|
|
t.Cleanup(fake.Close)
|
|
failDefaultTransportDials(t)
|
|
s := &Server{}
|
|
s.modelDialContext = dialTestServerForHosts(
|
|
map[string]string{"127.0.0.1:11434": fake.Listener.Addr().String()},
|
|
failDials(t, "the guarded transport (unrouted address)"),
|
|
)
|
|
resp := postJSON(t, s.testLLM, "/api/llm/test", map[string]any{
|
|
"provider": "ollama", "model": "llama3.2", "base_url": "", "streaming": false,
|
|
})
|
|
if resp["ok"] != true || hits.Load() != 1 {
|
|
t.Fatalf("default ollama: resp=%v hits=%d", resp, hits.Load())
|
|
}
|
|
}
|