mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-04 13:43:55 +08:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
618e16f9ad |
@@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b
|
||||
|
||||
### Security
|
||||
|
||||
- **Saved LLM profiles and run-time completions go through the model URL guard.** The connection test refused a `base_url` or proxy on a loopback, private or instance-metadata address, but saving a profile accepted it, and every completion of a task, chat or Agent bound to that profile was sent there with the profile's stored API key. Saving a profile (`POST /api/llm/profiles`) and the legacy `POST /api/llm` now refuse what the connection test refuses, and every completion provider the server builds validates the proxy and each request URL before sending, checks every connection on the address it dials (so a name that later resolves to a refused address is still refused), validates redirects and keeps them on the configured origin. The existing allowances are unchanged: an exact `host:port` listed in `ARTEX_LLM_PRIVATE_ENDPOINTS` (for example Ollama or vLLM on the host or the Docker network) is accepted at save and at run time, and an Ollama profile on the built-in default `http://127.0.0.1:11434/v1` (an empty base URL) keeps working without it. Behaviour change: a stored profile, or an `ARTEX_LLM_*` environment config, whose endpoint or proxy points at a loopback, LAN or Docker-network address not listed in `ARTEX_LLM_PRIVATE_ENDPOINTS` stops working (each request fails with the guard's refusal) until its `host:port` is added there; a SOCKS5 proxy on a profile is refused, as the connection test already refused it; and a profile host that does not resolve cannot be saved.
|
||||
- **The always-allow denylist refuses `sqlmap`, `sqlite3` and `nmap`.** An argv allow rule covers every flag, and each of these programs has a flag or script hook that runs code chosen by the caller: `sqlmap --eval`, `sqlite3 .shell` and `nmap --script` with a Lua NSE file. After an operator clicked "always allow" on a harmless call, later calls of the same program matched the rule and skipped the fallback judge, so those flags ran arbitrary code. The three names join the code-owned denylist; `sqlite3` is stored as `sqlite` because `argvProgramName` strips the version suffix, and `sqlmap.py`/`sqlmapapi.py` reduce to their bare names through the same extension stripping. Allow rules already stored for these programs stop matching because the denylist is checked again at match time: their calls go back to the judge or to an ask rule, and the rows stay in the rules table.
|
||||
- **HTTP custom tools bind stored headers and body to one origin.** A tool saved with a masked secret kept it while the literal url template stayed the same, so a template with a parameterized host (`https://{host}/collect`) could send the stored `X-API-Key` and body to an attacker-chosen host. A redirect from the configured host could also replay them to another origin: Go copies custom headers, and 307/308 replay the body. A secret-bearing HTTP tool now needs a fixed scheme, host and port in its url template, the rendered url must stay on that origin, and a redirect to another origin is refused; an edit that keeps a masked value may not add or change the proxy either (clearing it is allowed, the request then goes to the fixed origin). Tools without stored headers or body are unchanged. Every non-empty header value and body counts as stored, so a saved tool with a parameterized url and a constant header (`Content-Type`) or a body template is now refused at save and at run, and a secret-bearing tool whose API redirects to another host, port or scheme (apex to `www`, `http` to `https`, a CDN) now fails on that redirect.
|
||||
- **Panel-side asset enrichment obeys the sandbox egress policy.** `insert_assets` starts an HTTP probe in the panel process, and the probe dialed through the recording proxy whenever the target gate was off, with no destination check: a worker could submit a service URL for loopback, RFC1918 or the cloud metadata address and read the status, length and title with `list_assets`, or the full body through the traffic store. While `ARTEX_SANDBOX=required`, the probe now uses the task's `sandbox.EgressPolicy` for the URL, every redirect and every connection, resolves and pins the address itself, then hands that address to the target gate's pinned dialer as WebFetch and the http tool do (a probe without a target scope, or one a gated scope does not cover, still dials nothing), and uses neither the recording nor the environment proxy. A task without an approved scope probes nothing, as in the rest of the sandbox.
|
||||
|
||||
@@ -89,6 +89,7 @@ func TestRunIntentPollLoopEmitsAskOperatorActivityAndPausesWithHandoffCause(t *t
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
s := New(ctx, m, "", m.dir, m.dir)
|
||||
s.allowLoopbackModels = true // the mock LLM listens on loopback (test-only guard seam)
|
||||
t.Cleanup(func() { stopTestServer(t, s, cancel) })
|
||||
|
||||
pid, err := m.pg.SaveProfile(&db.LLMProfile{
|
||||
|
||||
@@ -117,6 +117,7 @@ func TestLegacyLLMEndpointDoesNotCarryGatewayHeaders(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
|
||||
s.allowLoopbackModels = true // the gateway addresses below are loopback (test-only guard seam)
|
||||
post := func(baseURL, token string) {
|
||||
t.Helper()
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
|
||||
@@ -64,6 +64,7 @@ func TestStartTaskEngineFailsTaskOnPlainTextDecomposer(t *testing.T) {
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
s := New(ctx, m, "", m.dir, m.dir)
|
||||
s.allowLoopbackModels = true // the mock LLM listens on loopback (test-only guard seam)
|
||||
t.Cleanup(func() { stopTestServer(t, s, cancel) })
|
||||
|
||||
pid, err := m.pg.SaveProfile(&db.LLMProfile{
|
||||
|
||||
@@ -31,6 +31,7 @@ func TestProfileRouteChangeNeedsKeyForEveryFormat(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
|
||||
s.allowLoopbackModels = true // the routes below are loopback addresses (test-only guard seam)
|
||||
|
||||
const oldKey = "synthetic-old-key"
|
||||
const header = "X-Example-Route: synthetic-route"
|
||||
@@ -122,6 +123,7 @@ func TestLegacyLLMEndpointProxyChangeClearsGatewayHeaders(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
|
||||
s.allowLoopbackModels = true // the routes below are loopback addresses (test-only guard seam)
|
||||
post := func(proxy, token string) int {
|
||||
t.Helper()
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
)
|
||||
|
||||
// The run-time client checks the address each connection dials, not only the
|
||||
// URL: a name that passed the URL check and then resolves to loopback (DNS
|
||||
// rebinding) is still refused, while an allow-listed host:port is dialled.
|
||||
func TestGuardModelConfigChecksEveryDial(t *testing.T) {
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
s := &Server{}
|
||||
fake, hits := fakeModelServer(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cfg := s.guardModelConfig(agent.ConfigFrom("openai", "probe-model", "https://model.example/v1", "synthetic-key", ""))
|
||||
tr, ok := cfg.HTTPTransport.(*guardedModelTransport)
|
||||
if !ok || cfg.RedirectPolicy == nil {
|
||||
t.Fatalf("guarded config has transport %T, redirect policy %v", cfg.HTTPTransport, cfg.RedirectPolicy)
|
||||
}
|
||||
if c, err := tr.base.DialContext(ctx, "tcp", fake.Listener.Addr().String()); err == nil {
|
||||
c.Close()
|
||||
t.Fatal("a connection to a loopback address was dialled")
|
||||
}
|
||||
if hits.Load() != 0 {
|
||||
t.Fatal("the loopback server was reached")
|
||||
}
|
||||
|
||||
t.Setenv(LLMPrivateEndpointsEnv, fake.Listener.Addr().String())
|
||||
cfg = s.guardModelConfig(agent.ConfigFrom("openai", "probe-model", fake.URL+"/v1", "synthetic-key", ""))
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, fake.URL+"/v1/models", nil)
|
||||
resp, err := cfg.HTTPTransport.RoundTrip(req)
|
||||
if err != nil {
|
||||
t.Fatalf("allow-listed endpoint: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
|
||||
// A SOCKS5 proxy hides the destination from the guard: it is refused at save,
|
||||
// as by the connection test, and every request through it is refused.
|
||||
func TestModelRouteRefusesSOCKSProxy(t *testing.T) {
|
||||
s := &Server{modelLookupIP: publicLookup}
|
||||
cfg := agent.ConfigFrom("openai", "probe-model", "", "synthetic-key", "socks5://proxy.example:1080")
|
||||
if err := s.checkModelRoute(context.Background(), cfg); err == nil {
|
||||
t.Fatal("a SOCKS5 proxy passed the save check")
|
||||
}
|
||||
req, _ := http.NewRequest(http.MethodPost, "https://api.openai.com/v1/chat/completions", nil)
|
||||
if _, err := s.guardModelConfig(cfg).HTTPTransport.RoundTrip(req); err == nil {
|
||||
t.Fatal("a request through a SOCKS5 proxy was sent")
|
||||
}
|
||||
}
|
||||
|
||||
// A redirect that leaves the configured origin is returned, not followed, as
|
||||
// the model client does without the guard.
|
||||
func TestGuardModelConfigKeepsRedirectsOnOrigin(t *testing.T) {
|
||||
s := &Server{modelLookupIP: publicLookup}
|
||||
cfg := s.guardModelConfig(agent.ConfigFrom("openai", "probe-model", "https://model.example/v1", "synthetic-key", ""))
|
||||
from := &http.Request{URL: &url.URL{Scheme: "https", Host: "model.example", Path: "/v1/chat/completions"}}
|
||||
to := &http.Request{URL: &url.URL{Scheme: "https", Host: "other.example", Path: "/v1/chat/completions"}}
|
||||
to = to.WithContext(context.Background())
|
||||
if err := cfg.RedirectPolicy.CheckRedirect(to, []*http.Request{from}); !errors.Is(err, http.ErrUseLastResponse) {
|
||||
t.Fatalf("cross-origin redirect: %v, want ErrUseLastResponse", err)
|
||||
}
|
||||
same := (&http.Request{URL: &url.URL{Scheme: "https", Host: "model.example", Path: "/v2/chat/completions"}}).WithContext(context.Background())
|
||||
if err := cfg.RedirectPolicy.CheckRedirect(same, []*http.Request{from}); err != nil {
|
||||
t.Fatalf("same-origin redirect: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
// fakeModelServer answers every request with one non-streaming chat completion
|
||||
// and counts the requests it received.
|
||||
func fakeModelServer(t *testing.T) (*httptest.Server, *atomic.Int64) {
|
||||
t.Helper()
|
||||
var hits atomic.Int64
|
||||
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":"1","object":"chat.completion","model":"probe-model","choices":[{"index":0,"message":{"role":"assistant","content":"OK"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`))
|
||||
}))
|
||||
t.Cleanup(fake.Close)
|
||||
return fake, &hits
|
||||
}
|
||||
|
||||
// publicLookup resolves every name to one public address (modelLookupIP seam).
|
||||
func publicLookup(context.Context, string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
|
||||
}
|
||||
|
||||
func runtimeGuardServer(t *testing.T) (*Manager, *Server) {
|
||||
t.Helper()
|
||||
skipWithoutDSN(t)
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { m.Close() })
|
||||
if m.pg == nil {
|
||||
db.SkipNoPG(t)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
return m, New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
|
||||
}
|
||||
|
||||
func completeOnce(p llm.Provider) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
_, _, _, err := p.Complete(ctx, llm.CompletionRequest{
|
||||
System: []string{"probe"},
|
||||
Messages: []llm.Message{llm.UserText("ping")},
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func saveProfileRequest(s *Server, profile map[string]any) *httptest.ResponseRecorder {
|
||||
body, _ := json.Marshal(profile)
|
||||
rec := httptest.NewRecorder()
|
||||
s.pgSaveProfile(rec, httptest.NewRequest(http.MethodPost, "/api/llm/profiles", bytes.NewReader(body)))
|
||||
return rec
|
||||
}
|
||||
|
||||
// A profile whose base_url the connection test refuses (here a loopback
|
||||
// address not listed in ARTEX_LLM_PRIVATE_ENDPOINTS) is refused when saved, and
|
||||
// one stored by an earlier release is never contacted at run time: neither the
|
||||
// per-profile provider nor the global one sends it a request or the stored key.
|
||||
func TestLLMRuntimeRefusesGuardedBaseURL(t *testing.T) {
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
m, s := runtimeGuardServer(t)
|
||||
fake, hits := fakeModelServer(t)
|
||||
base := fake.URL + "/v1"
|
||||
name := fmt.Sprintf("t-runtime-guard-%d", time.Now().UnixNano())
|
||||
t.Cleanup(func() { _, _ = m.pg.Exec(`DELETE FROM llm_profiles WHERE name LIKE $1`, name+"%") })
|
||||
|
||||
if rec := saveProfileRequest(s, map[string]any{"name": name + "-save", "format": "openai", "model": "probe-model", "base_url": base, "api_key": "synthetic-probe-key", "streaming": false}); rec.Code != http.StatusBadRequest {
|
||||
t.Errorf("saving a loopback base_url: HTTP %d %s, want 400", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := saveProfileRequest(s, map[string]any{"name": name + "-proxy", "format": "openai", "model": "probe-model", "proxy": "http://" + fake.Listener.Addr().String(), "api_key": "synthetic-probe-key", "streaming": false}); rec.Code != http.StatusBadRequest {
|
||||
t.Errorf("saving a loopback proxy: HTTP %d %s, want 400", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// A profile stored before the save check existed.
|
||||
id, err := m.pg.SaveProfile(&db.LLMProfile{Name: name + "-stored", Format: "openai", Model: "probe-model", BaseURL: base, APIKey: "synthetic-probe-key"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if prov, _, ok := s.providerForProfile(id); ok {
|
||||
if err := completeOnce(prov); err == nil {
|
||||
t.Error("a completion through the stored loopback profile succeeded")
|
||||
}
|
||||
}
|
||||
cfg, ok := s.loadProfileConfig(id)
|
||||
if !ok {
|
||||
t.Fatal("stored profile does not load")
|
||||
}
|
||||
if err := s.applyLLM(cfg); err == nil {
|
||||
s.cfgMu.Lock()
|
||||
direct := s.llmDirect
|
||||
s.cfgMu.Unlock()
|
||||
if err := completeOnce(direct); err == nil {
|
||||
t.Error("a completion through the global provider succeeded")
|
||||
}
|
||||
}
|
||||
if n := hits.Load(); n != 0 {
|
||||
t.Fatalf("the loopback model server received %d requests carrying the stored key, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Local model servers the guard allows keep working, at save and at run time:
|
||||
// an exact host:port listed in ARTEX_LLM_PRIVATE_ENDPOINTS, for an OpenAI
|
||||
// compatible server (vLLM) and an Ollama profile, and the built-in Ollama
|
||||
// default when the base URL is left empty.
|
||||
func TestLLMRuntimeKeepsAllowedLocalServers(t *testing.T) {
|
||||
m, s := runtimeGuardServer(t)
|
||||
fake, hits := fakeModelServer(t)
|
||||
t.Setenv(LLMPrivateEndpointsEnv, fake.Listener.Addr().String())
|
||||
name := fmt.Sprintf("t-runtime-local-%d", time.Now().UnixNano())
|
||||
t.Cleanup(func() { _, _ = m.pg.Exec(`DELETE FROM llm_profiles WHERE name LIKE $1`, name+"%") })
|
||||
|
||||
check := func(t *testing.T, profile map[string]any, want int64) {
|
||||
t.Helper()
|
||||
before := hits.Load()
|
||||
rec := saveProfileRequest(s, profile)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("save: HTTP %d %s, want 200", rec.Code, rec.Body.String())
|
||||
}
|
||||
var saved struct{ ID int64 }
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &saved); err != nil || saved.ID == 0 {
|
||||
t.Fatalf("save answer %q: %v", rec.Body.String(), err)
|
||||
}
|
||||
prov, _, ok := s.providerForProfile(saved.ID)
|
||||
if !ok {
|
||||
t.Fatal("no provider for the saved profile")
|
||||
}
|
||||
if err := completeOnce(prov); err != nil {
|
||||
t.Fatalf("completion: %v", err)
|
||||
}
|
||||
if got := hits.Load() - before; got != want {
|
||||
t.Fatalf("model server received %d requests, want %d", got, want)
|
||||
}
|
||||
}
|
||||
t.Run("vllm", func(t *testing.T) {
|
||||
check(t, map[string]any{"name": name + "-vllm", "format": "openai", "model": "probe-model", "base_url": fake.URL + "/v1", "api_key": "synthetic-vllm-key", "streaming": false}, 1)
|
||||
})
|
||||
t.Run("ollama", func(t *testing.T) {
|
||||
check(t, map[string]any{"name": name + "-ollama", "format": "ollama", "model": "probe-model", "base_url": fake.URL, "streaming": false}, 1)
|
||||
})
|
||||
t.Run("ollama default", func(t *testing.T) {
|
||||
u := strings.TrimPrefix(strings.TrimSuffix(agent.DefaultOllamaBaseURL, "/v1"), "http://")
|
||||
ln, err := net.Listen("tcp", u)
|
||||
if err != nil {
|
||||
t.Skipf("the default Ollama address %s is in use: %v", u, err)
|
||||
}
|
||||
def := httptest.NewUnstartedServer(fake.Config.Handler)
|
||||
def.Listener.Close()
|
||||
def.Listener = ln
|
||||
def.Start()
|
||||
t.Cleanup(def.Close)
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
check(t, map[string]any{"name": name + "-ollama-default", "format": "ollama", "model": "probe-model", "streaming": false}, 1)
|
||||
})
|
||||
}
|
||||
@@ -154,6 +154,9 @@ func TestMCPMaskedEnvDestinationGuard(t *testing.T) {
|
||||
func TestProxySecretsAPI(t *testing.T) {
|
||||
s, _, request := trafficEvidenceServer(t)
|
||||
pg := s.m.PG()
|
||||
// Profile saves pass the model URL guard: the example proxy hosts resolve
|
||||
// to a public address here.
|
||||
s.modelLookupIP = publicLookup
|
||||
t.Cleanup(func() {
|
||||
pg.Exec(`DELETE FROM settings WHERE key IN ('brave_search_api_key','tavily_search_api_key','keenable_search_api_key','web_search_proxy','global_proxy')`)
|
||||
pg.Exec(`DELETE FROM llm_profiles WHERE name='t-proxy'`)
|
||||
@@ -252,12 +255,12 @@ func TestProxySecretsAPI(t *testing.T) {
|
||||
t.Fatal("the placeholder replaced the stored profile proxy")
|
||||
}
|
||||
// The stored key only stays with the proxy it was saved for.
|
||||
save(`"socks5://llm2.example:1080"`, "", 400)
|
||||
save(`"http://llm2.example:1080"`, "", 400)
|
||||
if proxy() != "http://u:llmp-pass-0011@llm.example:3128" {
|
||||
t.Fatal("a refused proxy change replaced the stored profile proxy")
|
||||
}
|
||||
save(`"socks5://llm2.example:1080"`, "sk-rotated-0012", 200)
|
||||
if proxy() != "socks5://llm2.example:1080" {
|
||||
save(`"http://llm2.example:1080"`, "sk-rotated-0012", 200)
|
||||
if proxy() != "http://llm2.example:1080" {
|
||||
t.Fatal("explicit proxy not saved")
|
||||
}
|
||||
save(`""`, "sk-rotated-0013", 200)
|
||||
|
||||
+9
-2
@@ -591,7 +591,7 @@ func (s *Server) applyLLM(cfg agent.Config) error {
|
||||
}
|
||||
if prov == nil {
|
||||
var err error
|
||||
prov, err = cfg.NewProvider()
|
||||
prov, err = s.guardModelConfig(cfg).NewProvider()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -730,7 +730,9 @@ func (s *Server) providerForProfile(id int64) (llm.Provider, agent.Config, bool)
|
||||
if !ok {
|
||||
return nil, agent.Config{}, false
|
||||
}
|
||||
prov, err := cfg.NewProvider()
|
||||
// Only the client is built from the guarded copy: the cached cfg stays equal
|
||||
// to loadProfileConfig's, which applyLLM compares with the active profile.
|
||||
prov, err := s.guardModelConfig(cfg).NewProvider()
|
||||
if err != nil {
|
||||
log.Printf("[engine] build provider for LLM profile %d failed: %v", id, err)
|
||||
return nil, agent.Config{}, false
|
||||
@@ -1625,6 +1627,11 @@ func (s *Server) setLLM(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, "api_key required")
|
||||
return
|
||||
}
|
||||
// Same endpoint and proxy guard as a saved profile (checkModelRoute).
|
||||
if err := s.checkModelRoute(r.Context(), cfg); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
// Validate provider construction before persisting it as the active profile.
|
||||
if _, err := cfg.NewProvider(); err != nil {
|
||||
writeErr(w, 400, "provider init failed: "+err.Error())
|
||||
|
||||
@@ -2248,6 +2248,12 @@ func (s *Server) pgSaveProfile(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
p.UserAgent = ua
|
||||
// The endpoint and proxy pass the connection test's guard; the run-time
|
||||
// client enforces it again on every request (guardModelConfig).
|
||||
if err := s.checkModelRoute(r.Context(), agent.ConfigFrom(p.Format, p.Model, p.BaseURL, "", p.Proxy)); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
if p.Format == "bedrock-gateway" {
|
||||
validate := agent.ConfigFrom(p.Format, p.Model, p.BaseURL, p.APIKey, p.Proxy)
|
||||
validate.CustomHeaders = p.CustomHeaders
|
||||
@@ -2751,6 +2757,95 @@ func (s *Server) modelTransport(guard *modelURLGuard, proxyURL *url.URL) *http.T
|
||||
return transport
|
||||
}
|
||||
|
||||
// isDefaultOllama reports whether cfg is an Ollama config on the built-in
|
||||
// default URL, which an empty base URL becomes. That URL is code-owned.
|
||||
func isDefaultOllama(cfg agent.Config) bool {
|
||||
base := strings.TrimSpace(cfg.BaseURL)
|
||||
return cfg.Format == agent.FormatOllama && (base == "" || base == agent.DefaultOllamaBaseURL)
|
||||
}
|
||||
|
||||
// checkModelRoute applies the connection test's checks to the endpoint and
|
||||
// proxy of a model config that is about to be saved: both must pass the model
|
||||
// URL guard, except the built-in Ollama default.
|
||||
func (s *Server) checkModelRoute(ctx context.Context, cfg agent.Config) error {
|
||||
guard := newModelURLGuard(s)
|
||||
if p := strings.TrimSpace(cfg.Proxy); p != "" {
|
||||
if _, err := guard.validateURL(ctx, p, "proxy"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if isDefaultOllama(cfg) || strings.TrimSpace(cfg.BaseURL) == "" {
|
||||
return nil
|
||||
}
|
||||
_, err := guard.validateURL(ctx, cfg.BaseURL, "endpoint")
|
||||
return err
|
||||
}
|
||||
|
||||
// guardModelConfig returns cfg with an HTTP client that goes through the model
|
||||
// URL guard like the connection test's: the proxy and each request URL are
|
||||
// validated before the request is sent, every connection is checked on the
|
||||
// address it dials (a name that later resolves to a refused address is still
|
||||
// refused), and a redirect is validated and must stay on the configured origin.
|
||||
// Every completion provider the server builds uses it, so a stored profile the
|
||||
// guard refuses gets no request, and no key, at run time.
|
||||
func (s *Server) guardModelConfig(cfg agent.Config) agent.Config {
|
||||
guard := newModelURLGuard(s)
|
||||
checkURL := true
|
||||
if isDefaultOllama(cfg) {
|
||||
guard.allowDefaultOllama()
|
||||
checkURL = false
|
||||
}
|
||||
proxy := strings.TrimSpace(cfg.Proxy)
|
||||
var proxyURL *url.URL
|
||||
if u, err := url.Parse(proxy); proxy != "" && err == nil && (u.Scheme == "http" || u.Scheme == "https") {
|
||||
proxyURL = u
|
||||
}
|
||||
cfg.HTTPTransport = &guardedModelTransport{guard: guard, base: s.modelTransport(guard, proxyURL), proxy: proxy, checkURL: checkURL}
|
||||
cfg.RedirectPolicy = sameOriginModelRedirects{guard: guard}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// guardedModelTransport validates the proxy and the request URL with the guard
|
||||
// before each request (a refused proxy, SOCKS5 included, refuses every request).
|
||||
type guardedModelTransport struct {
|
||||
guard *modelURLGuard
|
||||
base *http.Transport
|
||||
proxy string
|
||||
checkURL bool
|
||||
}
|
||||
|
||||
func (t *guardedModelTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
refuse := func(err error) (*http.Response, error) {
|
||||
if req.Body != nil {
|
||||
_ = req.Body.Close()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if t.proxy != "" {
|
||||
if _, err := t.guard.validateURL(req.Context(), t.proxy, "proxy"); err != nil {
|
||||
return refuse(err)
|
||||
}
|
||||
}
|
||||
if t.checkURL {
|
||||
if _, err := t.guard.validateURL(req.Context(), req.URL.String(), "endpoint"); err != nil {
|
||||
return refuse(err)
|
||||
}
|
||||
}
|
||||
return t.base.RoundTrip(req)
|
||||
}
|
||||
|
||||
// sameOriginModelRedirects keeps the model client's own rule, a hop that
|
||||
// leaves the configured origin is returned as the final response so the
|
||||
// credentials are not replayed there, and validates the others with the guard.
|
||||
type sameOriginModelRedirects struct{ guard *modelURLGuard }
|
||||
|
||||
func (p sameOriginModelRedirects) CheckRedirect(req *http.Request, via []*http.Request) error {
|
||||
if origin := via[0].URL; !strings.EqualFold(req.URL.Scheme, origin.Scheme) || !strings.EqualFold(req.URL.Host, origin.Host) {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
return p.guard.CheckRedirect(req, via)
|
||||
}
|
||||
|
||||
// pgListModels fetches available models from the provider's API endpoint.
|
||||
// Supports OpenAI-format (GET /models), Anthropic-format (GET /v1/models) and
|
||||
// Ollama (keyless OpenAI-compatible GET /v1/models on the local server); for
|
||||
|
||||
@@ -78,6 +78,7 @@ func TestRunIntentSweepLoopEmitsGateConstantFactAndOperatorHandoff(t *testing.T)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
s := New(ctx, m, "", m.dir, m.dir)
|
||||
s.allowLoopbackModels = true // the mock LLM listens on loopback (test-only guard seam)
|
||||
t.Cleanup(func() { stopTestServer(t, s, cancel) })
|
||||
|
||||
pid, err := m.pg.SaveProfile(&db.LLMProfile{
|
||||
|
||||
@@ -79,7 +79,7 @@ func TestRotationConcurrentProvidersAndPrecedence(t *testing.T) {
|
||||
_, _ = m.pg.Exec(`DELETE FROM llm_usage WHERE task_id = $1`, task.ID)
|
||||
_, _ = m.DeleteTask(task.ID, DeleteTaskOptions{})
|
||||
}()
|
||||
s := &Server{m: m, provByProfile: map[int64]*provEntry{}}
|
||||
s := &Server{m: m, provByProfile: map[int64]*provEntry{}, allowLoopbackModels: true} // the endpoints listen on loopback (test-only guard seam)
|
||||
runtime := &taskLLMRuntime{s: s, taskID: task.ID, agentKey: "worker"}
|
||||
done := make(chan error, 3)
|
||||
dispatch := func(want int) {
|
||||
|
||||
Reference in New Issue
Block a user