Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ Accepted gap: when a task has no allow-list, there is no allow rule to apply (bl

## Outbound Model Listing (`POST /api/llm/models`)

`POST /api/llm/models` fetches model lists from the provider endpoint and optional HTTP proxy supplied in the request. By default, ARTEX allows only `http` and `https` URLs whose hosts resolve exclusively to public IP addresses (blocking loopback, RFC1918 private networks, IPv6 unique-local `fc00::/7`, link-local/cloud metadata such as `169.254.169.254`, unspecified, and multicast addresses), and enforces the same checks on redirects and at dial time. The built-in local Ollama default (`http://127.0.0.1:11434/v1`) is permitted only when the request leaves `base_url` empty for the `ollama` provider.
`POST /api/llm/models` fetches model lists from the provider endpoint and optional HTTP proxy supplied in the request. By default, ARTEX allows only `http` and `https` URLs whose hosts resolve exclusively to public IP addresses (blocking loopback, RFC1918 private networks, IPv6 unique-local `fc00::/7`, link-local/cloud metadata such as `169.254.169.254`, unspecified, and multicast addresses, carrier-grade NAT `100.64.0.0/10`, the benchmarking range `198.18.0.0/15`, `192.0.0.0/24` and the reserved block `240.0.0.0/4`; a NAT64 `64:ff9b::/96` or 6to4 `2002::/16` address is judged by the IPv4 address it embeds), and enforces the same checks on redirects and at dial time. A non-200 answer from the endpoint is reported by its status only; its body is not returned. The built-in local Ollama default (`http://127.0.0.1:11434/v1`) is permitted only when the request leaves `base_url` empty for the `ollama` provider.

Operators running self-hosted LLM gateways or Ollama on a LAN or Docker bridge can allow specific endpoints with `ARTEX_LLM_PRIVATE_ENDPOINTS`, a comma-separated list of exact `host:port` entries (for example, `127.0.0.1:11434,host.docker.internal:11434,192.168.1.10:11434`). A URL whose `host:port` matches an entry may resolve to a loopback or private address while scheme restrictions, link-local/cloud-metadata blocks, and redirect validation still apply; everything else stays refused. Leaving `ARTEX_LLM_PRIVATE_ENDPOINTS` unset or empty keeps the strict public-only policy.
Operators running self-hosted LLM gateways or Ollama on a LAN or Docker bridge can allow specific endpoints with `ARTEX_LLM_PRIVATE_ENDPOINTS`, a comma-separated list of exact `host:port` entries (for example, `127.0.0.1:11434,host.docker.internal:11434,192.168.1.10:11434`). A URL whose `host:port` matches an entry may resolve to a loopback or private address, or to an address in `100.64.0.0/10` or `198.18.0.0/15` (an overlay network, a fake-IP resolver), while scheme restrictions, link-local/cloud-metadata blocks, the other reserved ranges above, and redirect validation still apply; everything else stays refused. Leaving `ARTEX_LLM_PRIVATE_ENDPOINTS` unset or empty keeps the strict public-only policy.

## Agent Process Isolation

Expand Down
40 changes: 40 additions & 0 deletions guard/guard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package guard

import (
"context"
"database/sql"
"encoding/json"
"strings"
"testing"
Expand Down Expand Up @@ -240,4 +241,43 @@ func TestShortBlockReasonUnchanged(t *testing.T) {
}
}

// A rule store that cannot be read blocks the call end to end, in the full guard
// (workers, chat) and in the target-only guard (planner, main agent), instead of
// letting it run unchecked. The handle is closed before its first query, so no
// server is contacted.
func TestUnreadableRuleStoreBlocksCalls(t *testing.T) {
closed := func() *intercept.Interceptor {
sqlDB, err := sql.Open("pgx", "postgres://u:p@127.0.0.1:1/unreachable")
if err != nil {
t.Fatal(err)
}
if err := sqlDB.Close(); err != nil {
t.Fatal(err)
}
return intercept.New(&db.DB{DB: sqlDB})
}
for name, g := range map[string]*Guard{
"full guard": NewWithInterceptor(closed()),
"target-only guard": NewTargetOnly(closed()),
} {
for _, call := range []struct{ tool, input string }{
{"Bash", `{"command":"ls -la"}`},
{"Monitor", `{"command":"tail -f /dev/null"}`},
{"create_mcp", `{"name":"x","command":"sh"}`},
} {
block, msg := pre(g, context.Background(), call.tool, call.input)
if !block || !strings.HasPrefix(msg, "[ARTEX platform control, not target defense]") ||
!strings.Contains(msg, "intercept rules could not be loaded") {
t.Errorf("%s: %s block=%v msg=%q, want a block that names the unreadable rule store", name, call.tool, block, msg)
}
}
}
// The blocked call is recorded as a block, never as an allow.
g := NewWithInterceptor(closed())
pre(g, context.Background(), "Bash", `{"command":"ls -la"}`)
if a := g.Audit(); len(a) != 1 || a[0].Action != "block" {
t.Errorf("audit = %+v, want one block entry", a)
}
}

var _ = hook.PreToolUse
58 changes: 46 additions & 12 deletions intercept/intercept.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"net"
"regexp"
"strconv"
Expand Down Expand Up @@ -111,15 +112,17 @@ func TargetScopeFromContext(ctx context.Context) (s TargetScope, ok bool) {
}

// compiledRule is an InterceptRule with the regex pre-compiled (nil for string rules)
// and the argv tokens pre-parsed (nil for non-argv rules).
// and the argv tokens pre-parsed (nil for non-argv rules). bad marks a deny or
// ask rule whose pattern does not compile: it matches every call, as a deny.
type compiledRule struct {
db.InterceptRule
re *regexp.Regexp
argv []string
bad bool
}

// compileRule prepares a rule for matching. ok is false for a rule whose
// pattern does not compile; such a rule is skipped rather than crashing.
// pattern does not compile; see loadLocked for what happens to it.
func compileRule(r db.InterceptRule) (compiledRule, bool) {
cr := compiledRule{InterceptRule: r}
switch r.MatchType {
Expand Down Expand Up @@ -205,6 +208,7 @@ type Interceptor struct {
mu sync.RWMutex
cached []compiledRule // sorted by priority DESC; nil means not loaded yet
enabledTools map[string]bool // nil means not loaded yet
loadFailed bool // the last load failed; its error has been logged
pending *pendingManager
reviewer Reviewer // nil = freeform LLM fallback judge not wired
completer Completer // nil = closed-question judge not wired
Expand Down Expand Up @@ -289,30 +293,53 @@ func (i *Interceptor) Invalidate() {
i.mu.Unlock()
}

// loadLocked reads the rules and the enabled-tools setting. It installs both or,
// when either read fails, neither: the callers then fail closed (IsToolEnabled
// answers true, the matchers deny). The error is logged once per outage.
func (i *Interceptor) loadLocked() error {
rules, err := i.db.ListInterceptRules()
var val string
var ok bool
if err == nil {
val, ok, err = i.db.GetSetting("intercept_enabled_tools")
}
if err != nil {
if !i.loadFailed {
i.loadFailed = true
log.Printf("[intercept] the rule store cannot be read; every tool call is denied until it can: %v", err)
}
return err
}
i.loadFailed = false
var out []compiledRule
for _, r := range rules {
if !r.Enabled {
continue
}
cr, ok := compileRule(r)
if !ok {
continue // skip rules with a bad pattern rather than crashing
if r.Action != "deny" && r.Action != "ask" {
continue // an allow rule with a bad pattern allows nothing
}
// A deny or ask rule that cannot be evaluated must not fail open.
cr.bad, cr.Action = true, "deny"
cr.Message = "intercept rule [" + r.Name + "] has a pattern that does not compile; calls are blocked until the rule is fixed or disabled"
}
out = append(out, cr)
}
i.cached = out

// Load enabled-tools set from settings, falling back to hard-coded defaults.
val, ok, _ := i.db.GetSetting("intercept_enabled_tools")
// Enabled-tools set from settings, falling back to hard-coded defaults.
i.enabledTools = enabledToolsFromSetting(val, ok)
return nil
}

// storeUnreadableDecision is what the matchers answer when the rules cannot be
// loaded: a deny, so that a call is never let through unchecked.
func storeUnreadableDecision() Decision {
return Decision{Action: "deny", Message: "the intercept rules could not be loaded, so the call cannot be checked; it is blocked until the rule store is readable again"}
}

// enabledToolsFromSetting maps the stored intercept_enabled_tools value to the
// gate's set. A malformed value must not silently disable the gate, so it falls
// back to the same defaults as an unset setting.
Expand Down Expand Up @@ -357,7 +384,8 @@ func (i *Interceptor) rules() ([]compiledRule, error) {

// IsToolEnabled returns true if the named tool is in the intercept-enabled set
// (i.e. it should enter the rule-matching path). Uses the same double-check lock
// pattern as rules().
// pattern as rules(). When the set cannot be loaded it answers true for every
// tool, so the call reaches the rule path, where Match denies it.
func (i *Interceptor) IsToolEnabled(name string) bool {
i.mu.RLock()
if i.enabledTools != nil {
Expand All @@ -370,7 +398,9 @@ func (i *Interceptor) IsToolEnabled(name string) bool {
i.mu.Lock()
defer i.mu.Unlock()
if i.enabledTools == nil {
_ = i.loadLocked()
if err := i.loadLocked(); err != nil {
return true
}
}
return i.enabledTools[name]
}
Expand Down Expand Up @@ -676,11 +706,12 @@ func judgeActionLabel(action string) string {

// Match evaluates the rule list (priority DESC) against a tool call.
// Returns (Decision, true) for the first matching enabled rule, or
// (Decision{}, false) if no rule matches.
// (Decision{}, false) if no rule matches. When the rules cannot be loaded it
// returns a deny.
func (i *Interceptor) Match(toolName string, input []byte) (Decision, bool) {
rules, err := i.rules()
if err != nil || len(rules) == 0 {
return Decision{}, false
if err != nil {
return storeUnreadableDecision(), true
}
for _, r := range rules {
if ruleMatches(r, toolName, input) {
Expand Down Expand Up @@ -712,7 +743,7 @@ const builtinRulePrefix = "[built-in]"
// enter the rule system. It returns the first match in priority order. User rules,
// allow and ask rules, and the judge are not consulted. The planner and the main
// agent use it (#124, F11). An interceptor without a database and without loaded
// rules matches nothing.
// rules matches nothing. When the rules cannot be loaded it returns a deny.
func (i *Interceptor) MatchBuiltin(toolName string, input []byte) (Decision, bool) {
i.mu.RLock()
loaded := i.cached != nil
Expand All @@ -725,7 +756,7 @@ func (i *Interceptor) MatchBuiltin(toolName string, input []byte) (Decision, boo
}
rules, err := i.rules()
if err != nil {
return Decision{}, false
return storeUnreadableDecision(), true
}
for _, r := range rules {
if r.Action != "deny" || !strings.HasPrefix(r.Name, builtinRulePrefix) || !ruleMatches(r, toolName, input) {
Expand Down Expand Up @@ -772,6 +803,9 @@ func (i *Interceptor) SetRulesForTest(rules []db.InterceptRule) {
}

func ruleMatches(r compiledRule, toolName string, input []byte) bool {
if r.bad {
return true
}
if r.MatchType == "argv" {
// Bash only, on the parsed command; match_target is always tool_input.
// Allow rules stay strictly limited to a single simple command with
Expand Down
2 changes: 1 addition & 1 deletion intercept/persistence.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func (i *Interceptor) MatchPersistence(toolName string, input []byte) (Decision,
}
rules, err := i.rules()
if err != nil {
return Decision{}, false
return storeUnreadableDecision(), true
}
var ask *compiledRule
for idx := range rules {
Expand Down
132 changes: 132 additions & 0 deletions intercept/store_error_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package intercept

import (
"bytes"
"database/sql"
"log"
"strings"
"testing"

"github.com/Autumn-27/artex/db"
)

// closedStore returns a store whose every read fails. No server is contacted:
// the handle is closed before its first query.
func closedStore(t *testing.T) *db.DB {
t.Helper()
sqlDB, err := sql.Open("pgx", "postgres://u:p@127.0.0.1:1/unreachable")
if err != nil {
t.Fatal(err)
}
if err := sqlDB.Close(); err != nil {
t.Fatal(err)
}
return &db.DB{DB: sqlDB}
}

// A rule store that cannot be read must not open the gate: every tool enters the
// rule path, and every matcher denies. The error is logged once, not per call.
func TestStoreErrorFailsClosed(t *testing.T) {
var logged bytes.Buffer
prev := log.Writer()
log.SetOutput(&logged)
t.Cleanup(func() { log.SetOutput(prev) })

ic := New(closedStore(t))
input := []byte(`{"command":"ls -la"}`)
for _, tool := range []string{"Bash", "ExecuteExtraTool", "Monitor", "Read", "my_custom_tool"} {
if !ic.IsToolEnabled(tool) {
t.Errorf("IsToolEnabled(%q) = false with an unreadable store, want true", tool)
}
}
for name, match := range map[string]func(string, []byte) (Decision, bool){
"Match": ic.Match,
"MatchBuiltin": ic.MatchBuiltin,
"MatchPersistence": ic.MatchPersistence,
} {
tool := "Bash"
if name == "MatchPersistence" {
tool = "create_mcp"
}
dec, ok := match(tool, input)
if !ok || dec.Action != "deny" || !strings.Contains(dec.Message, "could not be loaded") {
t.Errorf("%s with an unreadable store = %+v, %v; want a deny that names the cause", name, dec, ok)
}
}
if n := strings.Count(logged.String(), "rule store cannot be read"); n != 1 {
t.Errorf("the store error was logged %d times, want once:\n%s", n, logged.String())
}
if !strings.Contains(logged.String(), "sql: database is closed") {
t.Errorf("the log line does not carry the error:\n%s", logged.String())
}
}

// A malformed intercept_enabled_tools value read from the store keeps the
// defaults: ExecuteExtraTool and Monitor stay gated, read-only tools stay out.
func TestMalformedEnabledToolsSettingKeepsDefaults(t *testing.T) {
d := targetTestDB(t)
const key = "intercept_enabled_tools"
prev, had, err := d.GetSetting(key)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if had {
_ = d.SetSetting(key, prev)
return
}
_, _ = d.Exec(`DELETE FROM settings WHERE key=$1`, key)
})
for _, val := range []string{"{not json", `"Bash"`, `{"Bash":true}`} {
if err := d.SetSetting(key, val); err != nil {
t.Fatal(err)
}
ic := New(d)
for _, tool := range defaultEnabledTools {
if !ic.IsToolEnabled(tool) {
t.Errorf("setting %q: default tool %q is not gated", val, tool)
}
}
if ic.IsToolEnabled("Read") {
t.Errorf("setting %q: Read is gated, want the defaults only", val)
}
}
}

// A deny or ask rule whose pattern does not compile cannot be evaluated; it
// matches as a deny instead of being skipped. A broken allow rule allows nothing.
func TestUncompilableRuleFailsClosed(t *testing.T) {
d := targetTestDB(t)
create := func(name, matchType, pattern, action string, priority int) db.InterceptRule {
t.Helper()
r, err := d.CreateInterceptRule(name, "tool_input", matchType, pattern, action, "", priority, true, false, 0, "deny")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.DeleteInterceptRule(r.ID) })
return r
}
input := []byte(`{"command":"ls -la"}`)

allow := create("broken allow", "regex", "(", "allow", 1000002)
if dec, ok := New(d).Match("Bash", input); ok && dec.RuleID == allow.ID {
t.Fatalf("a broken allow rule matched: %+v", dec)
}
for n, tc := range []struct{ matchType, pattern, action string }{
{"regex", "(", "ask"},
{"regex", "[z-a]", "deny"},
{"argv", `"unterminated`, "deny"},
} {
r := create("broken "+tc.action, tc.matchType, tc.pattern, tc.action, 1000001-n)
ic := New(d)
dec, ok := ic.Match("Bash", input)
if !ok || dec.Action != "deny" || dec.RuleID != r.ID || !strings.Contains(dec.Message, "does not compile") {
t.Errorf("%s %s rule %q: Match = %+v, %v; want a deny by rule %d", tc.matchType, tc.action, tc.pattern, dec, ok, r.ID)
}
// A user rule, broken or not, is not a built-in rule.
if dec, ok := ic.MatchBuiltin("Bash", input); ok {
t.Errorf("MatchBuiltin matched a broken user rule: %+v", dec)
}
_ = d.DeleteInterceptRule(r.ID)
}
}
Loading
Loading