Compare commits

...
Author SHA1 Message Date
BaaRai 618e16f9ad Guard saved LLM profiles and run-time completions like the connection test
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 bound to the profile was sent there with its stored API key.

Saving a profile and the legacy POST /api/llm now run the connection test's
checks on the endpoint and proxy. Every completion provider the server builds
uses a client that validates the proxy and each request URL before sending,
checks each connection on the address it dials, validates redirects and keeps
them on the configured origin. ARTEX_LLM_PRIVATE_ENDPOINTS and the built-in
Ollama default keep working at save and at run time.

Tests that save loopback routes or run completions against a loopback mock
on purpose use the existing loopback test seam, and the proxy secrets test
resolves its example hosts through the lookup seam and uses an HTTP proxy
instead of SOCKS5, which is now refused.
2026-12-03 23:24:52 +01:00
BaaRai d0645b6370 Merge pull request #940 from BaaRai/fix/alwaysallow-denylist
fix(intercept): refuse always-allow rules for sqlmap, sqlite3 and nmap
2026-12-03 23:24:03 +01:00
BaaRai 978b497ac4 intercept: deny always-allow for sqlmap, sqlite and nmap 2026-12-03 22:59:00 +01:00
BaaRai ba22ce4015 Merge pull request #944 from BaaRai/fix/customtool-secret-origin
fix(server): bind custom HTTP tool secrets to one origin
2026-12-03 22:58:48 +01:00
BaaRai ad5e4e8484 server: bind custom HTTP tool secrets to one origin 2026-12-03 22:34:47 +01:00
BaaRai c1bd9530fe Merge pull request #942 from BaaRai/fix/enrich-sandbox-egress
fix(enrich): apply the sandbox egress policy to panel HTTP probes
2026-12-03 22:34:35 +01:00
BaaRai 6045a2c80f enrich: apply the sandbox egress policy to panel HTTP probes 2026-12-03 22:11:20 +01:00
BaaRai 2653cf57ca enrich: apply the sandbox egress policy to panel HTTP probes 2026-12-03 22:11:11 +01:00
BaaRai 4a4fa45245 Merge pull request #941 from BaaRai/fix/ask-operator-root
fix(server): anchor ask_operator image reads at the task root
2026-12-03 22:10:59 +01:00
23 changed files with 1052 additions and 53 deletions
+4
View File
@@ -6,6 +6,10 @@ 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.
- **`ask_operator` reads run-directory images through a task-rooted handle.** The copy path resolved the asking run directory with `EvalSymlinks` and then opened the resolved path, so a worker that replaced its run directory with a symlink to `/` made the confinement root `/`: an absolute `image_path` to a symlink named `*.png` could have the panel copy `/proc/1/environ` or `/app/keys/jwt.key` into `tasks/<id>/uploads`, where the worker reads it. The read and the upload write are now both anchored with `os.Root` at `tasks/<id>`; the run directory must be a real directory, no path component may be a symlink, the opened file must be the one `Lstat` saw, and the copy is bounded to 10 MB. Existing `..`, outside-path and non-image refusals are unchanged.
- **Task archives no longer follow a directory swapped for a symlink while the task is packed.** The packer, running as root, listed each directory of the staged run tree and then opened its files by full path, so code running as the executor uid that kept a working directory inside the run tree could replace a listed directory with a symlink (for example to `/app/keys`) and have root-only files such as the session signing key copied into the archive, then read them back from the run directory after a restore. The packer now walks and opens the payload through an `os.Root` anchored at it, so no lookup can leave the payload, and refuses the archive when a file it opens is not the regular file the walk listed (device and inode compared). Symlinks already present in the run tree are still skipped and never followed. Behaviour change: an archive whose run tree changes this way while it is packed fails instead of completing, and the task stays in place.
- **Agent sessions no longer offer Norma's background-task tools.** Norma adds `Monitor`, `TaskOutput`, `TaskStop` and `TaskList` to every session that does not opt out, and only the connection test and the goal decomposer opted out. `Monitor` starts a shell command in the panel process, not through the sandbox that `Bash` uses, so in `ARTEX_SANDBOX=required` mode a worker, planner, chat or main-agent model could run commands in the panel container, outside the task's worker, and read or write other tasks' workspaces and transcripts. Every agent session is now built through one constructor. It turns these tools off while the sandbox is required, and always for a session that has neither `Bash` nor the interactive shell, so an orchestration agent cannot gain a shell through `Monitor`. Sessions that do have `Bash` or `shell_*` keep them when the sandbox is off: their background runs, PTY sessions and the pause kill switch depend on the same task manager. The constructor also turns a nil tool list into an empty one, because Norma reads nil as "use my own default tools" and installs its unconfined `Bash` and file tools; the tool catalogue resolver also returns an empty list instead of nil when the tools table cannot be read, the case of the Auto chat agent, whose base list is empty.
+60 -1
View File
@@ -27,6 +27,7 @@ import (
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/egress"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
"github.com/miekg/dns"
"github.com/projectdiscovery/dnsx/libs/dnsx"
@@ -67,6 +68,10 @@ type Engine struct {
resolv *dnsx.DNSX
client *http.Client
// sandboxPolicy returns the task's egress policy while the panel runs in
// ARTEX_SANDBOX=required mode, nil otherwise. It is set once, before jobs.
sandboxPolicy func(context.Context) *sandbox.EgressPolicy
jobs chan job
cool sync.Map // dedup/cooldown: "kind:id" -> time.Time (last run)
once sync.Once
@@ -256,6 +261,50 @@ func buildClient(proxy func() string) *http.Client {
}
}
// SetSandboxPolicy installs the source of the task egress policy applied to
// panel-side HTTP probes while ARTEX_SANDBOX=required. It must return nil when
// the sandbox is off; the probe then keeps the recording-proxy path. Set it once
// at construction, before any job is enqueued.
func (e *Engine) SetSandboxPolicy(policy func(context.Context) *sandbox.EgressPolicy) {
e.sandboxPolicy = policy
}
// sandboxClient probes through the task's sandbox egress policy: every connection
// is resolved, checked and pinned by the policy, with no proxy and no environment
// proxy, so a proxy cannot route around it. The pinned address then goes through
// the target gate's pinned dialer, as on the recording-proxy client: a probe
// without a target scope is refused, and a gated scope still needs a pin. This
// is the order the WebFetch and http tool sandbox dialers use. Redirects stay
// off, as on the recording-proxy client.
func sandboxClient(policy *sandbox.EgressPolicy) *http.Client {
gate := intercept.PinnedDialer("enrich", true)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DisableKeepAlives: true,
TLSHandshakeTimeout: httpTimeout,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("sandbox enrich blocked invalid target %q: %w", addr, err)
}
port, err := strconv.Atoi(portStr)
if err != nil || port <= 0 || port > 65535 {
return nil, fmt.Errorf("sandbox enrich blocked invalid port %q", portStr)
}
ip, err := policy.ResolveAndCheck(ctx, host)
if err != nil {
return nil, fmt.Errorf("sandbox enrich blocked: %w", err)
}
return gate(ctx, network, net.JoinHostPort(ip.String(), portStr))
},
}
return &http.Client{
Transport: egress.Dynamic("enrich", tr),
Timeout: httpTimeout,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
}
// ResolveDomain enqueues a DNS resolution for a domain asset (ungated). host is the
// FQDN. No-op for an empty engine.
func (e *Engine) ResolveDomain(id int64, host string) { e.enqueue(job{jobDNS, id, host, nil}) }
@@ -377,7 +426,17 @@ func (e *Engine) doHTTP(ctx context.Context, id int64, rawURL string) {
return
}
intercept.ApplyAssessmentUserAgent(req)
resp, err := e.client.Do(req)
client := e.client
if e.sandboxPolicy != nil {
if policy := e.sandboxPolicy(ctx); policy != nil {
if err := policy.CheckURL(ctx, rawURL); err != nil {
slog.Warn("[enrich] HTTP probe blocked by sandbox egress policy", "url", rawURL, "err", err)
return
}
client = sandboxClient(policy)
}
}
resp, err := client.Do(req)
if err != nil {
return
}
+182
View File
@@ -0,0 +1,182 @@
package enrich
import (
"context"
"errors"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
)
// A probe scheduled while ARTEX_SANDBOX=required must use the task egress policy,
// not the recording proxy: loopback, IMDS and RFC1918 are refused even when the
// target name is in scope and resolves there.
func TestSandboxPolicyBlocksInternalProbes(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
accepted := make(chan struct{}, 4)
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
accepted <- struct{}{}
c.Close()
}
}()
port := ln.Addr().(*net.TCPAddr).Port
policy, err := sandbox.NewEgressPolicy("t1", []string{"allowed.example"}, nil, nil)
if err != nil {
t.Fatal(err)
}
policy.Resolver = func(context.Context, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil
}
e := New(nil, nil, 1)
e.SetSandboxPolicy(func(context.Context) *sandbox.EgressPolicy { return policy })
defer e.Close()
for _, target := range []string{
"http://127.0.0.1:" + strconv.Itoa(port) + "/",
"http://169.254.169.254/",
"http://10.0.0.1/",
"http://allowed.example:" + strconv.Itoa(port) + "/",
} {
e.doHTTP(context.Background(), 1, target)
}
select {
case <-accepted:
t.Fatal("a sandboxed probe connected to a forbidden target")
case <-time.After(100 * time.Millisecond):
}
}
// The sandbox dialer resolves and pins the target itself: a name in scope that
// answers a private address is refused before any connection, even when the URL
// check is bypassed.
func TestSandboxDialerPinsResolvedAddress(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
accepted := make(chan struct{}, 1)
go func() {
c, err := ln.Accept()
if err == nil {
accepted <- struct{}{}
c.Close()
}
}()
port := ln.Addr().(*net.TCPAddr).Port
policy, err := sandbox.NewEgressPolicy("t1", []string{"allowed.example"}, nil, nil)
if err != nil {
t.Fatal(err)
}
policy.Resolver = func(context.Context, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil
}
if _, err := sandboxClient(policy).Get("http://allowed.example:" + strconv.Itoa(port) + "/"); err == nil {
t.Fatal("the sandbox dialer connected to a name resolving to loopback")
}
select {
case <-accepted:
t.Fatal("the sandbox dialer opened a connection to loopback")
case <-time.After(100 * time.Millisecond):
}
}
// A target explicitly inside the task scope CIDRs still probes normally through
// the sandbox transport.
func TestSandboxClientAllowsScopedTarget(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("ok"))
}))
defer srv.Close()
policy, err := sandbox.NewEgressPolicy("t1", nil, []string{"127.0.0.1/32"}, nil)
if err != nil {
t.Fatal(err)
}
ctx := intercept.WithTargetScope(context.Background(), intercept.TargetScope{TaskID: "t1"})
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
if err != nil {
t.Fatal(err)
}
resp, err := sandboxClient(policy).Do(req)
if err != nil {
t.Fatalf("scoped target refused: %v", err)
}
resp.Body.Close()
}
// The sandbox policy narrows the target gate, it does not replace it: a target
// inside the sandbox scope is still refused without a target scope, and under a
// gated scope that does not decide it.
func TestSandboxClientKeepsTargetGate(t *testing.T) {
var hits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
hits.Add(1)
}))
defer srv.Close()
policy, err := sandbox.NewEgressPolicy("t1", nil, []string{"127.0.0.1/32"}, nil)
if err != nil {
t.Fatal(err)
}
gated := intercept.WithTargetScope(context.Background(), intercept.TargetScope{
TaskID: "t1", Enabled: func() bool { return true },
})
for name, ctx := range map[string]context.Context{"no target scope": context.Background(), "gate on": gated} {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
if err != nil {
t.Fatal(err)
}
if resp, err := sandboxClient(policy).Do(req); err == nil {
resp.Body.Close()
t.Fatalf("%s: the sandbox client skipped the target gate", name)
}
}
if hits.Load() != 0 {
t.Fatalf("the target received %d request(s)", hits.Load())
}
}
type countingRoundTripper struct{ calls *atomic.Int32 }
func (c countingRoundTripper) RoundTrip(*http.Request) (*http.Response, error) {
c.calls.Add(1)
return nil, errors.New("normal client used")
}
// doHTTP must select the sandbox client when the policy hook is set: the normal
// recording-proxy client would otherwise be used even in required mode.
func TestDoHTTPUsesSandboxClient(t *testing.T) {
var normalCalls atomic.Int32
e := New(nil, nil, 1)
defer e.Close()
e.client = &http.Client{Transport: countingRoundTripper{calls: &normalCalls}}
policy, err := sandbox.NewEgressPolicy("t1", nil, nil, nil)
if err != nil {
t.Fatal(err)
}
e.SetSandboxPolicy(func(context.Context) *sandbox.EgressPolicy { return policy })
e.doHTTP(context.Background(), 1, "http://127.0.0.1:1/")
if n := normalCalls.Load(); n != 0 {
t.Fatalf("doHTTP used the normal client %d time(s) under a sandbox policy", n)
}
}
+3 -3
View File
@@ -19,8 +19,8 @@ func TestArgvAllowKeepsDenyAndTargetGate(t *testing.T) {
Pattern: "--force", Action: "deny", Message: "force push is forbidden"},
{ID: 2, Name: "argv allow curl", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["curl"]`, Action: "allow"},
{ID: 3, Name: "argv allow nmap", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["nmap"]`, Action: "allow"},
{ID: 3, Name: "argv allow whois", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["whois"]`, Action: "allow"},
})
g := NewWithInterceptor(ic)
gate := &fakeGate{t: t, check: unpinnedOnce, request: func(int, []intercept.TargetRequest, *intercept.Decision) intercept.TargetResult {
@@ -29,7 +29,7 @@ func TestArgvAllowKeepsDenyAndTargetGate(t *testing.T) {
g.gate = gate
ctx := gateOn(context.Background(), "7", time.Minute)
if block, msg := pre(g, ctx, "Bash", `{"command":"nmap --force 10.0.0.1"}`); !block || !strings.Contains(msg, "force push is forbidden") {
if block, msg := pre(g, ctx, "Bash", `{"command":"whois --force 10.0.0.1"}`); !block || !strings.Contains(msg, "force push is forbidden") {
t.Fatalf("deny over argv allow: block=%v msg=%q", block, msg)
}
if gate.checks != 0 {
+13 -1
View File
@@ -29,6 +29,9 @@ var alwaysAllowDenylist = func() map[string]bool {
"mvn gradle dotnet apt apt-get dpkg dnf yum rpm pacman apk brew snap flatpak",
// version control and build generators: run hooks, aliases and script files
"git cmake ctest cpack",
// tools whose flags run code chosen by the caller: a prefix covers every flag
// (sqlmapapi: sqlmap's REST API server; argvProgramName strips its .py launcher)
"sqlmap sqlmapapi sqlite nmap",
// orchestration: run images, playbooks and plans
"docker docker-compose podman nerdctl kubectl helm ansible ansible-playbook terraform pulumi vagrant",
// destructive
@@ -44,13 +47,22 @@ var alwaysAllowDenylist = func() map[string]bool {
}()
// argvProgramName normalises a program token for the denylist: the basename,
// in lower case, without a trailing version (python3.11, php8.2, perl5, pip3)
// in lower case, without an interpreter or launcher extension (sqlmap.py,
// sqlite3.exe), without a trailing version (python3.11, php8.2, perl5, pip3)
// and with every mkfs.* variant reduced to mkfs.
func argvProgramName(tok string) string {
name := strings.ToLower(path.Base(tok))
if strings.HasPrefix(name, "mkfs.") {
return "mkfs"
}
// A script or a Windows launcher runs the same program as its bare name:
// sqlmap.py, nmap.exe and sqlite3.exe must not slip past the denylist.
for _, ext := range []string{".exe", ".cmd", ".bat", ".ps1", ".py", ".pl", ".rb", ".sh", ".bash", ".lua", ".php", ".js"} {
if strings.HasSuffix(name, ext) {
name = strings.TrimSuffix(name, ext)
break
}
}
// Strip a trailing run of digits and dots, but only after a letter, so a
// name made only of digits (or ".") is kept as is.
end := len(name)
+18 -7
View File
@@ -14,12 +14,14 @@ func TestArgvAllowDenylist(t *testing.T) {
"env", "/usr/bin/env", "bash", "/bin/sh", "find", "rm", "mkfs", "mkfs.ext4", "/sbin/mkfs.xfs",
"docker", "kubectl", "npm", "sudo", "xargs", "Rscript", ".",
"git", "/usr/bin/git", "cmake", "cmake3", "/usr/bin/cmake", "ctest", "cpack",
"sqlmap", "/usr/bin/sqlmap", "sqlite", "sqlite3", "/usr/bin/sqlite3", "nmap", "/usr/bin/nmap",
"sqlmap.py", "/opt/sqlmap/sqlmap.py", "sqlmapapi", "/opt/sqlmap/sqlmapapi.py", "sqlite3.exe", "nmap.exe", "nmap.sh",
} {
if !ArgvAllowDenied(prog) {
t.Errorf("%q is not denied", prog)
}
}
for _, prog := range []string{"nmap", "curl", "ls", "gh", "x", "7z", "pythonic"} {
for _, prog := range []string{"whois", "curl", "ls", "gh", "x", "7z", "pythonic"} {
if ArgvAllowDenied(prog) {
t.Errorf("%q is denied, want allowable", prog)
}
@@ -34,8 +36,8 @@ func TestAlwaysAllowPrefix(t *testing.T) {
if got, err := AlwaysAllowPrefix("Bash", bash("gh pr list --limit 5")); err != nil || !slices.Equal(got, []string{"gh", "pr", "list"}) {
t.Fatalf("gh pr list: %q %v", got, err)
}
if got, err := AlwaysAllowPrefix("Bash", bash("nmap -p 80 10.0.0.1")); err != nil || !slices.Equal(got, []string{"nmap"}) {
t.Fatalf("nmap: %q %v", got, err)
if got, err := AlwaysAllowPrefix("Bash", bash("whois example.com")); err != nil || !slices.Equal(got, []string{"whois"}) {
t.Fatalf("whois: %q %v", got, err)
}
for name, c := range map[string]struct {
tool string
@@ -58,6 +60,14 @@ func TestAlwaysAllowPrefix(t *testing.T) {
"git config": {"Bash", bash("git config user.name x")},
"cmake": {"Bash", bash("cmake --version")},
"ctest": {"Bash", bash("ctest -N")},
"sqlmap": {"Bash", bash("sqlmap --version")},
"path to sqlmap": {"Bash", bash("/usr/bin/sqlmap -u http://127.0.0.1/")},
"sqlmap.py": {"Bash", bash("/opt/sqlmap/sqlmap.py -u http://127.0.0.1/")},
"sqlmapapi": {"Bash", bash("/opt/sqlmap/sqlmapapi.py --version")},
"sqlite3": {"Bash", bash("sqlite3 -version")},
"sqlite3.exe": {"Bash", bash("sqlite3.exe -version")},
"nmap": {"Bash", bash("nmap -sV -p 80 127.0.0.1")},
"path to nmap": {"Bash", bash("/usr/bin/nmap -p 80 127.0.0.1")},
} {
if got, err := AlwaysAllowPrefix(c.tool, c.input); err == nil {
t.Errorf("%s: prefix %q, want a refusal", name, got)
@@ -92,17 +102,18 @@ func TestArgvDenylistAtMatching(t *testing.T) {
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{
argv(1, `["python"]`, "allow"), argv(2, `["python3.11"]`, "allow"), argv(3, `["find"]`, "allow"),
argv(4, `["/usr/bin/env"]`, "allow"), argv(5, `["nmap"]`, "allow"), ask,
argv(4, `["/usr/bin/env"]`, "allow"), argv(5, `["nmap"]`, "allow"), argv(8, `["whois"]`, "allow"),
argv(9, `["sqlmap"]`, "allow"), argv(10, `["sqlite3"]`, "allow"), ask,
})
for _, cmd := range []string{"python x.py", "python3.11 -c 'import os'", "find . -name x", "/usr/bin/env"} {
for _, cmd := range []string{"python x.py", "python3.11 -c 'import os'", "find . -name x", "/usr/bin/env", "nmap -p 80 x", "sqlmap -u http://127.0.0.1/", "sqlite3 -version"} {
input, _ := json.Marshal(map[string]string{"command": cmd})
dec, ok := ic.Match("Bash", input)
if !ok || dec.Action != "ask" || dec.RuleID != 99 {
t.Errorf("%q: %+v %v, want the fallback ask rule", cmd, dec, ok)
}
}
if dec, ok := ic.Match("Bash", []byte(`{"command":"nmap -p 80 x"}`)); !ok || dec.Action != "allow" || dec.RuleID != 5 {
t.Errorf("nmap: %+v %v, want the argv allow", dec, ok)
if dec, ok := ic.Match("Bash", []byte(`{"command":"whois example.com"}`)); !ok || dec.Action != "allow" || dec.RuleID != 8 {
t.Errorf("whois: %+v %v, want the argv allow", dec, ok)
}
ic.SetRulesForTest([]db.InterceptRule{argv(1, `["python"]`, "allow"), argv(6, `["python"]`, "deny"), argv(7, `["find"]`, "ask")})
+19 -19
View File
@@ -231,20 +231,20 @@ func TestArgvAllowRemainsStrict(t *testing.T) {
cmd string
want bool
}{
{"nmap -p 80 x", true},
{"command nmap x", false},
{"nmap x; true", false},
{"bash -c 'nmap x'", false},
{"/usr/bin/nmap x", false},
{"sudo nmap x", false},
{"env FOO=1 nmap x", false},
{"nmap $(id)", false},
{"whois -p 80 x", true},
{"command whois x", false},
{"whois x; true", false},
{"bash -c 'whois x'", false},
{"/usr/bin/whois x", false},
{"sudo whois x", false},
{"env FOO=1 whois x", false},
{"whois $(id)", false},
}
for _, tc := range cases {
t.Run(tc.cmd, func(t *testing.T) {
_, got := matchSingleArgvRule("allow", `["nmap"]`, "Bash", bashInput(tc.cmd))
_, got := matchSingleArgvRule("allow", `["whois"]`, "Bash", bashInput(tc.cmd))
if got != tc.want {
t.Errorf("allow [\"nmap\"] on %q = %v, want %v", tc.cmd, got, tc.want)
t.Errorf("allow [\"whois\"] on %q = %v, want %v", tc.cmd, got, tc.want)
}
})
}
@@ -256,15 +256,15 @@ func TestArgvCompoundMalformedInputDoesNotPanic(t *testing.T) {
[]byte(``),
[]byte(`not json`),
[]byte(`{}`),
bashInput(`nmap 'unterminated`),
bashInput(`nmap $(`),
bashInput(`whois 'unterminated`),
bashInput(`whois $(`),
bashInput(`if then fi; (( (`),
bashInput(`bash -c "unterminated`),
bashInput(`eval "((("`),
}
for _, action := range []string{"deny", "ask", "allow"} {
for _, in := range inputs {
if dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", in); ok {
if dec, ok := matchSingleArgvRule(action, `["whois"]`, "Bash", in); ok {
t.Errorf("%s matched malformed input %q: %+v", action, string(in), dec)
}
}
@@ -274,18 +274,18 @@ func TestArgvCompoundMalformedInputDoesNotPanic(t *testing.T) {
func TestArgvPriorityPreservedWithCompoundDeny(t *testing.T) {
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{
{ID: 1, Name: "allow simple nmap", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"},
{ID: 2, Name: "deny compound nmap", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "deny"},
{ID: 1, Name: "allow simple whois", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["whois"]`, Action: "allow"},
{ID: 2, Name: "deny compound whois", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["whois"]`, Action: "deny"},
})
// Simple command hits the higher-priority allow rule.
dec, ok := ic.Match("Bash", bashInput("nmap -p 80 x"))
dec, ok := ic.Match("Bash", bashInput("whois -p 80 x"))
if !ok || dec.Action != "allow" || dec.RuleID != 1 {
t.Fatalf("simple nmap: got (%+v, %v), want allow rule 1", dec, ok)
t.Fatalf("simple whois: got (%+v, %v), want allow rule 1", dec, ok)
}
// Compound command fails the strict allow rule and falls through to the deny rule.
dec, ok = ic.Match("Bash", bashInput("nmap -p 80 x; true"))
dec, ok = ic.Match("Bash", bashInput("whois -p 80 x; true"))
if !ok || dec.Action != "deny" || dec.RuleID != 2 {
t.Fatalf("compound nmap: got (%+v, %v), want deny rule 2", dec, ok)
t.Fatalf("compound whois: got (%+v, %v), want deny rule 2", dec, ok)
}
}
+9 -9
View File
@@ -133,9 +133,9 @@ func TestArgvRejectsWrappers(t *testing.T) {
// no rule and the normal flow (judge, approval) continues.
func TestArgvParseFailureIsNoMatch(t *testing.T) {
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "argv allow nmap", Enabled: true, MatchTarget: "tool_input",
MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"}})
for _, input := range []string{`{"command":"nmap 'unterminated"}`, `{"command":"nmap $("}`, `{"command":""}`, `{}`, `not json`} {
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "argv allow whois", Enabled: true, MatchTarget: "tool_input",
MatchType: "argv", Pattern: `["whois"]`, Action: "allow"}})
for _, input := range []string{`{"command":"whois 'unterminated"}`, `{"command":"whois $("}`, `{"command":""}`, `{}`, `not json`} {
if dec, ok := ic.Match("Bash", []byte(input)); ok {
t.Errorf("%s matched: %+v", input, dec)
}
@@ -216,18 +216,18 @@ func TestArgvAllowBelowDeny(t *testing.T) {
ic.SetRulesForTest([]db.InterceptRule{
{ID: 1, Name: "no force flag", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "regex",
Pattern: `--force`, Action: "deny"},
{ID: 2, Name: "argv allow nmap", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["nmap"]`, Action: "allow"},
{ID: 2, Name: "argv allow whois", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["whois"]`, Action: "allow"},
})
dec, ok := ic.Match("Bash", []byte(`{"command":"nmap --force 10.0.0.1"}`))
dec, ok := ic.Match("Bash", []byte(`{"command":"whois --force 10.0.0.1"}`))
if !ok || dec.Action != "deny" || dec.RuleID != 1 {
t.Fatalf("force flag: %+v %v, want the deny rule", dec, ok)
}
dec, ok = ic.Match("Bash", []byte(`{"command":"nmap 10.0.0.1"}`))
dec, ok = ic.Match("Bash", []byte(`{"command":"whois 10.0.0.1"}`))
if !ok || dec.Action != "allow" || dec.RuleID != 2 {
t.Fatalf("nmap: %+v %v, want the argv allow", dec, ok)
t.Fatalf("whois: %+v %v, want the argv allow", dec, ok)
}
if _, ok := ic.Match("Bash", []byte(`{"command":"nmap 10.0.0.1; id"}`)); ok {
if _, ok := ic.Match("Bash", []byte(`{"command":"whois 10.0.0.1; id"}`)); ok {
t.Fatal("a compound command matched the argv rule")
}
if _, ok := compileRule(db.InterceptRule{MatchType: "argv", Pattern: `["-x"]`}); ok {
@@ -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{
+1
View File
@@ -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{
+138 -2
View File
@@ -12,6 +12,7 @@ import (
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/url"
"os"
@@ -413,8 +414,25 @@ func unmaskToolExec(storedKind string, stored json.RawMessage, kind string, in j
}
oldURL, _ := old["url"].(string)
newURL, _ := e["url"].(string)
if kept && (oldURL != newURL || storedKind != kind) {
return nil, fmt.Errorf("destination changed (url or kind) while a stored secret was kept: re-enter the masked header/proxy/body or clear it; stored secrets are not sent to a new destination")
oldProxy, _ := old["proxy"].(string)
newProxy, _ := e["proxy"].(string)
oldRecording, _ := old["use_recording_proxy"].(bool)
newRecording, _ := e["use_recording_proxy"].(bool)
if kept {
if oldURL != newURL || storedKind != kind || oldRecording != newRecording {
return nil, fmt.Errorf("destination or recording proxy changed while a stored secret was kept: re-enter the masked header/proxy/body or clear it; stored secrets are not sent to a new destination")
}
// Clearing the configured proxy sends the request to the tool's fixed
// destination, not to a third party. Switching to another proxy does not
// have that guarantee.
if newProxy != "" && newProxy != oldProxy {
return nil, fmt.Errorf("proxy changed while a stored secret was kept: re-enter the masked header/body or clear it; stored secrets are not sent to a new proxy")
}
}
if kind == "http" {
if err := validateHTTPToolExec(e); err != nil {
return nil, err
}
}
if !changed {
return in, nil
@@ -698,6 +716,13 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if strings.TrimSpace(rawURL) == "" {
return actool.Errorf("http url is empty"), nil
}
// A tool with stored headers or body may only send them to the origin it was
// configured for: the scheme, host and port of the url template cannot be
// parameters, and the rendered url must stay on that origin.
secretOrigin, originErr := httpToolSecretOrigin(spec, rawURL)
if originErr != nil {
return actool.Errorf(originErr.Error()), nil
}
// ARTEX_SANDBOX=required: the request leaves from the panel process, not from
// the task's worker container and its egress proxy. The task's egress policy,
// the one WebFetch enforces, applies here to the URL, to every redirect hop
@@ -741,6 +766,9 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if sbPolicy != nil {
client.CheckRedirect = sandboxRedirectCheck(sbPolicy, client.CheckRedirect)
}
if secretOrigin != "" {
client.CheckRedirect = secretOriginRedirectCheck(secretOrigin, client.CheckRedirect)
}
// The current egress governor paces every request and redirect hop per host
// under the noise profile (off by default: the base transport itself). It is
// resolved per request, so a changed profile applies to the next call.
@@ -765,6 +793,114 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
return actool.Text(actool.Capture(tc, string(b))), nil
}
// httpToolHasSecrets reports whether an HTTP tool carries stored values the API
// masks: any non-empty header value or body.
func httpToolHasSecrets(spec httpExec) bool {
for _, v := range spec.Headers {
if strings.TrimSpace(v) != "" {
return true
}
}
return strings.TrimSpace(spec.Body) != ""
}
// validateHTTPToolExec refuses a secret-bearing HTTP tool whose url authority is
// parameterized. The stored headers and body would otherwise follow the rendered
// host to any third party.
func validateHTTPToolExec(e map[string]any) error {
raw, err := json.Marshal(e)
if err != nil {
return nil
}
var spec httpExec
if json.Unmarshal(raw, &spec) != nil {
return errors.New("invalid HTTP tool exec")
}
if !httpToolHasSecrets(spec) {
return nil
}
if _, ok := fixedHTTPOrigin(spec.URL); !ok {
return errors.New("an HTTP tool with stored headers or body needs a fixed origin: the url scheme, host and port cannot contain parameters")
}
return nil
}
// httpToolSecretOrigin returns the origin a secret-bearing HTTP tool must stay
// on, or "" when the tool carries no stored header or body.
func httpToolSecretOrigin(spec httpExec, rawURL string) (string, error) {
if !httpToolHasSecrets(spec) {
return "", nil
}
fixed, ok := fixedHTTPOrigin(spec.URL)
if !ok {
return "", errors.New("this HTTP tool sends stored headers or body, so its url must have a fixed scheme, host and port (no parameters)")
}
u, err := url.Parse(rawURL)
if err != nil {
return "", errors.New("http url is invalid")
}
rendered, err := canonicalOrigin(u)
if err != nil || rendered != fixed {
return "", fmt.Errorf("this HTTP tool sends stored headers or body, so the rendered url must stay on %s", fixed)
}
return fixed, nil
}
// fixedHTTPOrigin returns the canonical origin of a url template whose scheme,
// host and port are literal. ok is false when a parameter or an invalid url
// makes the destination dynamic.
func fixedHTTPOrigin(template string) (string, bool) {
u, err := url.Parse(strings.TrimSpace(template))
if err != nil || u.Scheme == "" || u.Host == "" {
return "", false
}
if strings.ContainsAny(u.Scheme, "{}") || strings.ContainsAny(u.Host, "{}") ||
(u.User != nil && strings.ContainsAny(u.User.String(), "{}")) {
return "", false
}
origin, err := canonicalOrigin(u)
if err != nil {
return "", false
}
return origin, true
}
// canonicalOrigin normalizes scheme, host case and default port, so a redirect
// is same-origin only when it keeps all three.
func canonicalOrigin(u *url.URL) (string, error) {
scheme := strings.ToLower(strings.TrimSpace(u.Scheme))
if scheme != "http" && scheme != "https" {
return "", fmt.Errorf("scheme %q is not http or https", u.Scheme)
}
host := strings.ToLower(strings.TrimSuffix(u.Hostname(), "."))
if host == "" {
return "", errors.New("url has no host")
}
port := u.Port()
if (scheme == "http" && port == "80") || (scheme == "https" && port == "443") {
port = ""
}
if port != "" {
return scheme + "://" + net.JoinHostPort(host, port), nil
}
if strings.Contains(host, ":") {
return scheme + "://[" + host + "]", nil
}
return scheme + "://" + host, nil
}
// secretOriginRedirectCheck refuses a redirect hop that leaves the origin the
// tool's stored headers and body were configured for.
func secretOriginRedirectCheck(origin string, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
return func(req *http.Request, via []*http.Request) error {
next, err := canonicalOrigin(req.URL)
if err != nil || next != origin {
return errors.New("redirect to a different origin refused: this HTTP tool sends stored headers or body")
}
return check(req, via)
}
}
// assessmentRedirectCheck sheds the generated identifier on the first redirect
// to another origin. net/http copies headers from the initial request for each
// hop, so check the previous hop to keep the identifier off after that point.
+225
View File
@@ -0,0 +1,225 @@
package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/notify"
)
func TestFixedHTTPOrigin(t *testing.T) {
for _, tc := range []struct {
url string
want string
ok bool
}{
{"https://api.example.com/x", "https://api.example.com", true},
{"https://API.Example.com:443/x", "https://api.example.com", true},
{"http://api.example.com:80/x", "http://api.example.com", true},
{"http://api.example.com:8080/x", "http://api.example.com:8080", true},
{"https://api.example.com/{path}", "https://api.example.com", true},
{"https://[::1]:443/x", "https://[::1]", true},
{"https://[::1]:8443/x", "https://[::1]:8443", true},
{"https://{user}@api.example.com/x", "", false},
{"https://{host}/x", "", false},
{"https://api.{domain}/x", "", false},
{"https://api.example.com:{port}/x", "", false},
{"ftp://api.example.com/x", "", false},
{"/relative", "", false},
} {
got, ok := fixedHTTPOrigin(tc.url)
if ok != tc.ok || got != tc.want {
t.Errorf("fixedHTTPOrigin(%q) = %q, %v; want %q, %v", tc.url, got, ok, tc.want, tc.ok)
}
}
}
func TestHTTPToolSecretOrigin(t *testing.T) {
// A tool without stored headers or body may keep a parameterized authority.
if origin, err := httpToolSecretOrigin(httpExec{URL: "https://{host}/collect"}, "https://attacker.example/collect"); err != nil || origin != "" {
t.Fatalf("no-secret tool: origin=%q err=%v", origin, err)
}
// The rendered url must stay on the template origin.
if _, err := httpToolSecretOrigin(httpExec{
URL: "https://api.example.com/x",
Headers: map[string]string{"X-API-Key": "secret"},
}, "https://attacker.example/x"); err == nil {
t.Fatal("rendered url outside the template origin accepted")
}
}
func TestUnmaskToolExecRequiresFixedOriginForSecrets(t *testing.T) {
exec := func(url string, headers map[string]string) json.RawMessage {
b, _ := json.Marshal(map[string]any{"method": "GET", "url": url, "headers": headers})
return b
}
if _, err := unmaskToolExec("", nil, "http", exec("https://{host}/collect", map[string]string{"X-API-Key": "secret"})); err == nil {
t.Fatal("parameterized authority with a stored header accepted")
}
if _, err := unmaskToolExec("", nil, "http", exec("https://api.example.com/collect", map[string]string{"X-API-Key": "secret"})); err != nil {
t.Fatalf("fixed origin refused: %v", err)
}
if _, err := unmaskToolExec("", nil, "http", exec("https://{host}/collect", nil)); err != nil {
t.Fatalf("parameterized authority without secrets refused: %v", err)
}
if _, err := unmaskToolExec("", nil, "http", exec("https://api.example.com/{path}", map[string]string{"X-API-Key": "secret"})); err != nil {
t.Fatalf("path parameter with a fixed origin refused: %v", err)
}
}
func noSandbox(t *testing.T) {
t.Helper()
prev := agent.CurrentSandboxExecutor()
agent.SetSandboxExecutor(nil)
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
}
func TestHTTPToolRefusesParameterizedAuthorityWithSecrets(t *testing.T) {
noSandbox(t)
raw, _ := json.Marshal(map[string]any{
"method": "GET",
"url": "https://{host}/collect",
"headers": map[string]string{"X-API-Key": "secret"},
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, map[string]any{"host": "attacker.example"}, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "fixed scheme, host and port") {
t.Fatalf("parameterized authority not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
}
func TestUnmaskToolExecRejectsMalformedHTTPExec(t *testing.T) {
raw := json.RawMessage(`{"method":"GET","url":"https://api.example.com/","headers":{"X":1}}`)
if _, err := unmaskToolExec("", nil, "http", raw); err == nil {
t.Fatal("numeric header value accepted")
}
}
func TestUnmaskToolExecRefusesProxyChangeWithSecrets(t *testing.T) {
stored := json.RawMessage(`{"method":"GET","url":"https://api.example.com/collect","headers":{"X-API-Key":"secret"}}`)
masked := func(proxy string, recording bool) json.RawMessage {
m := map[string]any{
"method": "GET",
"url": "https://api.example.com/collect",
"headers": map[string]string{"X-API-Key": notify.MaskedPrefix},
}
if proxy != "" {
m["proxy"] = proxy
}
if recording {
m["use_recording_proxy"] = true
}
b, _ := json.Marshal(m)
return b
}
if _, err := unmaskToolExec("http", stored, "http", masked("http://attacker.example:8080", false)); err == nil {
t.Fatal("proxy change with a kept secret accepted")
}
if _, err := unmaskToolExec("http", stored, "http", masked("", true)); err == nil {
t.Fatal("recording proxy change with a kept secret accepted")
}
if _, err := unmaskToolExec("http", stored, "http", masked("", false)); err != nil {
t.Fatalf("unchanged destination refused: %v", err)
}
storedProxy := json.RawMessage(`{"method":"GET","url":"https://api.example.com/collect","headers":{"X-API-Key":"secret"},"proxy":"http://proxy.example:8080"}`)
if _, err := unmaskToolExec("http", storedProxy, "http", masked("", false)); err != nil {
t.Fatalf("clearing the configured proxy refused: %v", err)
}
}
func TestHTTPToolRefusesParameterizedAuthorityWithBodySecret(t *testing.T) {
noSandbox(t)
raw, _ := json.Marshal(map[string]any{
"method": "POST",
"url": "https://{host}/collect",
"body": "token=secret",
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, map[string]any{"host": "attacker.example"}, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "fixed scheme, host and port") {
t.Fatalf("body-bearing parameterized authority not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
}
func TestHTTPToolSecretStaysOnConfiguredOrigin(t *testing.T) {
noSandbox(t)
for _, code := range []int{http.StatusTemporaryRedirect, http.StatusPermanentRedirect} {
t.Run(http.StatusText(code), func(t *testing.T) {
var outsideHits atomic.Int32
outside := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
outsideHits.Add(1)
_, _ = w.Write([]byte("outside"))
}))
defer outside.Close()
var startHits atomic.Int32
start := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startHits.Add(1)
if got := r.Header.Get("X-API-Key"); got != "secret" {
t.Errorf("first hop header = %q, want secret", got)
}
http.Redirect(w, r, outside.URL+"/stolen", code)
}))
defer start.Close()
raw, _ := json.Marshal(map[string]any{
"method": "GET",
"url": start.URL + "/start",
"headers": map[string]string{"X-API-Key": "secret"},
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, nil, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "different origin") {
t.Fatalf("cross-origin redirect not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := outsideHits.Load(); n != 0 {
t.Fatalf("outside origin received %d request(s)", n)
}
if n := startHits.Load(); n != 1 {
t.Fatalf("start origin hits = %d, want 1", n)
}
})
}
}
func TestHTTPToolSecretAllowsSameOriginRedirect(t *testing.T) {
noSandbox(t)
var finalHits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/start" {
http.Redirect(w, r, "/final", http.StatusFound)
return
}
finalHits.Add(1)
_, _ = w.Write([]byte("final"))
}))
defer srv.Close()
raw, _ := json.Marshal(map[string]any{
"method": "GET",
"url": srv.URL + "/start",
"headers": map[string]string{"X-API-Key": "secret"},
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, nil, nil)
if err != nil {
t.Fatal(err)
}
if res.IsError {
t.Fatalf("same-origin redirect refused: %s", res.Flatten())
}
if n := finalHits.Load(); n != 1 {
t.Fatalf("final origin hits = %d, want 1", n)
}
}
+1
View File
@@ -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{
+5 -5
View File
@@ -7,7 +7,7 @@ import (
)
func TestValidateArgvRuleReq(t *testing.T) {
base := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"}
base := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: `["whois"]`, Action: "allow"}
if err := validateInterceptRuleReq(base); err != nil {
t.Fatalf("valid argv rule refused: %v", err)
}
@@ -15,8 +15,8 @@ func TestValidateArgvRuleReq(t *testing.T) {
"tool_name target": func(r *interceptRuleReq) { r.MatchTarget = "tool_name" },
"empty pattern": func(r *interceptRuleReq) { r.Pattern = "" },
"empty token": func(r *interceptRuleReq) { r.Pattern = `["git",""]` },
"flag token": func(r *interceptRuleReq) { r.Pattern = `["nmap","-C"]` },
"metacharacter": func(r *interceptRuleReq) { r.Pattern = `["nmap;id"]` },
"flag token": func(r *interceptRuleReq) { r.Pattern = `["whois","-C"]` },
"metacharacter": func(r *interceptRuleReq) { r.Pattern = `["whois;id"]` },
"nine tokens": func(r *interceptRuleReq) { r.Pattern = `["a","b","c","d","e","f","g","h","i"]` },
"not an array": func(r *interceptRuleReq) { r.Pattern = `git push` },
} {
@@ -31,7 +31,7 @@ func TestValidateArgvRuleReq(t *testing.T) {
// The manual rule form refuses an argv allow rule for a denylisted program,
// with the message of the "always allow" endpoint; deny and ask stay creatable.
func TestValidateArgvAllowDenylist(t *testing.T) {
for _, pattern := range []string{`["python"]`, `["python3.11"]`, `["/usr/bin/env"]`, `["find"]`, `["docker","run"]`, `["git","push"]`, `["cmake"]`} {
for _, pattern := range []string{`["python"]`, `["python3.11"]`, `["/usr/bin/env"]`, `["find"]`, `["docker","run"]`, `["git","push"]`, `["cmake"]`, `["nmap"]`, `["sqlmap"]`, `["sqlite3"]`} {
req := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: pattern, Action: "allow"}
tokens, _ := intercept.ParseArgvPattern(pattern)
want := intercept.CheckArgvAllow(tokens)
@@ -45,7 +45,7 @@ func TestValidateArgvAllowDenylist(t *testing.T) {
}
}
}
for _, pattern := range []string{`["nmap"]`, `["curl"]`} {
for _, pattern := range []string{`["whois"]`, `["curl"]`} {
req := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: pattern, Action: "allow"}
if err := validateInterceptRuleReq(req); err != nil {
t.Errorf("allow %s refused: %v", pattern, err)
+2
View File
@@ -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{
+76
View File
@@ -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)
}
}
+173
View File
@@ -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)
})
}
+10
View File
@@ -25,6 +25,7 @@ import (
"github.com/Autumn-27/artex/enrich"
"github.com/Autumn-27/artex/guard"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
"github.com/Autumn-27/artex/traffic"
"github.com/Autumn-27/artex/traffic/rewrite"
actool "github.com/Autumn-27/norma/tool"
@@ -582,6 +583,15 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
}
}
m.enrich = enrich.New(m.assets, m.ProxyAddr, 4)
// Panel-side asset probes are agent-triggered: while the sandbox is required,
// they leave through the task's sandbox egress policy, as WebFetch and custom
// HTTP tools do, instead of the recording proxy that has no destination check.
m.enrich.SetSandboxPolicy(func(ctx context.Context) *sandbox.EgressPolicy {
if !agent.SandboxRequired() {
return nil
}
return agent.SandboxEgressPolicy(ctx)
})
// Reconcile the seeded browser MCP with the persisted capture state, so a
// restart with capture already on keeps Playwright routed through the proxy.
m.syncBrowserMCPProxy()
+6 -3
View File
@@ -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
View File
@@ -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())
+95
View File
@@ -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
+1
View File
@@ -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{
+1 -1
View File
@@ -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) {