Compare commits

...
Author SHA1 Message Date
BaaRai de16c16bdc security: fail closed on DNS errors and dual-A answers in sandbox egress
EgressPolicy.CheckURL, the check WebFetch, the shared browser and the
custom http tool run on a URL under ARTEX_SANDBOX=required, was fail-open
in two ways:
- a lookup error (or an empty answer) for a name in scope returned nil,
  so the URL was allowed;
- a name answering several addresses was allowed as soon as one of them
  was public, the others being private, loopback, IPv6 or the cloud
  metadata address (169.254.169.254).

CheckURL pins nothing. On a direct call the sandbox dialer resolves again
and pins an allowed address, but through an explicit proxy the panel only
dials the proxy, which resolves the target itself and may pick any answer
(or reach a name the panel could not resolve); the shared browser
resolves on its own as well. For those paths CheckURL is the only check
on the target.

CheckURL now denies a lookup error or an empty answer, and requires every
answer to be allowed (in the scope CIDRs, or outside the default deny
list): a dual-A [IMDS, public] answer is refused, in either order. The
dialer path (ResolveAndCheck, also used by the egress proxy) is
unchanged: it already fails closed on a lookup error and dials only the
allowed address it pinned.

sandboxHTTPTransport now turns keep-alive off on every transport it
returns, not only on the one it builds when httpToolTransport returned
nil: an operator proxy, or the recording proxy setting without a CA file,
kept idle connections to the proxy.

Two existing tests expected an in-scope name that does not resolve to be
allowed, which only the fail-open lookup gave them: the scope drift test
(its resolver reached the proxy policy only, not the policy WebFetch and
the browser build) and the shared browser navigation test. Both now pass
an offline resolver through the context (sandbox.WithResolver); their
assertions are unchanged.
2026-12-01 22:40:10 +01:00
BaaRai edd1a3c2b6 sandbox: let tests answer egress policy lookups through the context
The panel tools (WebFetch, the shared browser, the custom http tool) build
their EgressPolicy themselves, so a test could not hand them a resolver.
WithResolver carries one on the context; a policy without its own Resolver
uses it. Nothing in production sets it, and behaviour is unchanged.
2026-12-01 22:24:21 +01:00
BaaRai e736474085 Merge pull request #785 from BaaRai/sec/custom-http-egress-gate
security: enforce the task egress policy on custom HTTP tools
2026-12-01 22:17:27 +01:00
BaaRai 7455d7f706 Merge pull request #788 from leninworld/fix/responses-default-model
fix(llm): default openai-responses to gpt-6.2-sol before gpt-5 shuts down
2026-12-01 22:09:23 +01:00
BaaRai 0ced7302f3 Merge pull request #784 from thecorporatetractor/fix/sidequestion-test-yield
test(sidequestion): stop the fake stream when the consumer stops
2026-12-01 22:09:09 +01:00
BaaRai de63398481 Merge pull request #776 from amshivang/fix/husky-prepare-script
fix(web): run husky prepare from repo root so the pre-commit hook installs
2026-12-01 22:08:38 +01:00
BaaRai 9013eeeb6a Merge pull request #786 from BaaRai/chore/remove-php2shell
chore(skills): remove the experimental php2shell research skill
2026-12-01 22:08:33 +01:00
Lenin Mookiah d4fc42eb96 fix(llm): default openai-responses to gpt-6.2-sol before gpt-5 shuts down
OpenAI shuts gpt-5 down on 2026-12-11 and lists gpt-6.2-sol as its
replacement. Use it as the openai-responses default in FromEnv and
ConfigFrom; an explicitly set model is kept.

Fixes #787
2026-12-01 12:41:54 -08:00
BaaRai c8f057a039 security: enforce the task egress policy on custom HTTP tools
A custom tool with Kind "http" bound to the worker ran its request from
the panel process with no sandbox check: under ARTEX_SANDBOX=required a
worker could reach a URL outside the task scope (a loopback service, an
internal address, another host) and follow a redirect anywhere, because
runHTTPTool and httpToolTransport never looked at SandboxRequired or at
the task's egress policy.

Decision: option 1, enforce the policy in the panel, as WebFetch does.
WebFetch already has a usable path for the same situation (a request made
by the panel, outside the worker container): the task's policy from
SandboxRunInfo (sandbox.NewEgressPolicy), CheckURL on the input, and
sandboxScopeDialContext on every connection, which resolves once, checks
every address against the scope and the default deny list, and dials the
pinned IP. Routing the tool through the per-task egress proxy is not
needed for that, and WebFetch does not do it either.

Under ARTEX_SANDBOX=required the http tool now:
- checks the rendered URL with the task policy before any approval or
  request (scheme, scope domain or CIDR, names resolving only to private,
  loopback, metadata or IPv6 addresses);
- checks every redirect hop with the same policy; a hop outside the scope
  fails the call instead of being followed;
- dials through the WebFetch sandbox dialer: the target for a direct call
  (environment proxy dropped, pinned dialer of a gated scope kept
  underneath), the proxy for a call with a proxy, so a proxy outside the
  scope is not dialed.

The policy resolution moves to agent.SandboxEgressPolicy, used by WebFetch
and the http tool, and the dialer is exported as
agent.SandboxScopeDialContext with a label; WebFetch keeps its messages.

Sandbox off: nothing changes, the new code is skipped. The planner still
does not receive a Kind "http" tool bound to the worker.
2026-12-01 21:31:54 +01:00
Marco Azarmaneche a0948d8792 test(sidequestion): stop the fake stream when the consumer stops
TestMainSideConcurrencyAndIndependentCancellation panics intermittently with
"range function continued iteration after function for loop body returned
false". The fake iterator ignored yield's result: when the side context is
cancelled before the first event is handled, Answer stops ranging, and the
iterator then called yield again after ctx.Done(). Return when yield returns
false. Test-only change.
2026-12-01 22:26:30 +02:00
Shivang Shukla 203a05ff48 fix(web): run husky prepare from repo root so the pre-commit hook installs 2026-12-01 18:48:51 +00:00
14 changed files with 606 additions and 25 deletions
+1
View File
@@ -11,6 +11,7 @@ All notable changes to this project are documented in this file. The format is b
### Fixed
- **`GET /api/tasks/{id}/scope` reports scope approval**: the query behind it did not select `approved_by_operator` or `expanded`, so every row came back with `approved_by_operator: false` and `expanded: false`, including operator-approved rows that grant sandbox egress. The rows now carry both columns as stored, for the task's own scope and for its source tasks' scope.
- **The OpenAI Responses format no longer defaults to `gpt-5`**: OpenAI shuts `gpt-5` down on 2026-12-11 and lists `gpt-6.2-sol` as its replacement, so `ARTEX_LLM_PROVIDER=openai-responses` without `ARTEX_LLM_MODEL` (or a profile saved through the API without a model) would start failing then. The default is now `gpt-6.2-sol`; a model set in the profile or in `ARTEX_LLM_MODEL` is kept as is. A gateway set with `ARTEX_LLM_BASE_URL` that does not serve `gpt-6.2-sol` needs `ARTEX_LLM_MODEL` set explicitly.
- **`start.sh` stops during a crash backoff**: a SIGTERM or SIGINT that arrived while the supervisor slept before a restart was handled only after the sleep, and the loop then started `artex` again and waited on it, so `docker stop` waited out its grace period and SIGKILLed a freshly started server. The backoff sleep can now be interrupted, and the loop checks for a pending stop before each launch. `scripts/test-start-sh.sh` covers it in CI.
### Removed
+7 -2
View File
@@ -232,6 +232,11 @@ func compactionConfig(windowTokens int) *compaction.Config {
return &compaction.Config{ContextWindow: windowTokens}
}
// defaultOpenAIResponsesModel is the model used by the openai-responses format
// when none is set. OpenAI shuts gpt-5 down on 2026-12-11 and lists
// gpt-6.2-sol as its replacement (platform deprecations page).
const defaultOpenAIResponsesModel = "gpt-6.2-sol"
// FromEnv resolves the LLM provider config:
//
// ARTEX_LLM_PROVIDER = anthropic|openai|openai-responses|ollama (default: inferred from keys)
@@ -276,7 +281,7 @@ func FromEnv() (Config, bool) {
c.Format = llm.FormatOpenAIResponses
c.APIKey = oaiKey
if c.Model == "" {
c.Model = "gpt-5"
c.Model = defaultOpenAIResponsesModel
}
case "ollama":
c.Format = FormatOllama
@@ -334,7 +339,7 @@ func ConfigFrom(provider, model, baseURL, apiKey, proxy string) Config {
// provider appends "/responses"; tolerate a full endpoint URL.
c.BaseURL = strings.TrimRight(strings.TrimSuffix(c.BaseURL, "/responses"), "/")
if c.Model == "" {
c.Model = "gpt-5"
c.Model = defaultOpenAIResponsesModel
}
case "ollama":
c.Format = FormatOllama
+27
View File
@@ -28,3 +28,30 @@ func TestConfigFromOpenAIResponses(t *testing.T) {
t.Fatalf("NewProvider: %v", err)
}
}
// TestOpenAIResponsesDefaultModel: with no model set, the openai-responses
// format defaults to a model OpenAI still serves. gpt-5 shuts down on
// 2026-12-11 (OpenAI deprecations page); its listed replacement is gpt-6.2-sol.
// An explicitly chosen model is kept as is.
func TestOpenAIResponsesDefaultModel(t *testing.T) {
const want = "gpt-6.2-sol"
if c := ConfigFrom("openai-responses", "", "", "sk-x", ""); c.Model != want {
t.Fatalf("ConfigFrom default model=%q, want %q", c.Model, want)
}
if c := ConfigFrom("openai-responses", " gpt-5 ", "", "sk-x", ""); c.Model != "gpt-5" {
t.Fatalf("ConfigFrom explicit model=%q, want gpt-5 kept", c.Model)
}
t.Setenv("ARTEX_LLM_PROVIDER", "openai-responses")
t.Setenv("OPENAI_API_KEY", "sk-oai")
t.Setenv("ARTEX_LLM_BASE_URL", "")
t.Setenv("ARTEX_LLM_MODEL", "")
c, ok := FromEnv()
if !ok || c.Model != want {
t.Fatalf("FromEnv default model=%q ok=%v, want %q", c.Model, ok, want)
}
t.Setenv("ARTEX_LLM_MODEL", "gpt-5")
if c, ok := FromEnv(); !ok || c.Model != "gpt-5" {
t.Fatalf("FromEnv explicit model=%q ok=%v, want gpt-5 kept", c.Model, ok)
}
}
+22 -3
View File
@@ -183,23 +183,42 @@ func formatSandboxExecResult(resp sandbox.ExecResponse, tc *actool.ToolContext)
return actool.Text(out)
}
// SandboxEgressPolicy is the task's sandbox.EgressPolicy for ctx, the one
// WebFetch enforces in ARTEX_SANDBOX=required mode: the scope domains and CIDRs
// of the run, or, when they do not parse or the run carries none, a policy that
// allows nothing.
func SandboxEgressPolicy(ctx context.Context) *sandbox.EgressPolicy {
info, _ := SandboxRunInfoFromContext(ctx)
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
if err != nil {
pol, _ = sandbox.NewEgressPolicy(info.TaskID, nil, nil, nil)
}
return pol
}
// sandboxScopeDialContext wraps baseDial so every TCP connection made by panel
// WebFetch in ARTEX_SANDBOX=required mode validates and pins the target IP via
// the task's sandbox.EgressPolicy (blocking non-scope IPs, IMDS, loopback,
// RFC1918, and IPv6 across all hops and redirects).
func sandboxScopeDialContext(policy *sandbox.EgressPolicy, baseDial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) {
return SandboxScopeDialContext("WebFetch", policy, baseDial)
}
// SandboxScopeDialContext is the WebFetch sandbox dialer for another panel tool
// that connects out from the panel process; label names the tool in a refusal.
func SandboxScopeDialContext(label string, policy *sandbox.EgressPolicy, baseDial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("sandbox WebFetch blocked invalid target %q: %w", addr, err)
return nil, fmt.Errorf("sandbox %s blocked invalid target %q: %w", label, addr, err)
}
port, err := strconv.Atoi(portStr)
if err != nil || port <= 0 || port > 65535 {
return nil, fmt.Errorf("sandbox WebFetch blocked invalid port %q", portStr)
return nil, fmt.Errorf("sandbox %s blocked invalid port %q", label, portStr)
}
pinnedIP, err := policy.ResolveAndCheck(ctx, host)
if err != nil {
return nil, fmt.Errorf("sandbox WebFetch blocked: %w", err)
return nil, fmt.Errorf("sandbox %s blocked: %w", label, err)
}
pinnedAddr := net.JoinHostPort(pinnedIP.String(), strconv.Itoa(port))
if baseDial != nil {
+1 -5
View File
@@ -30,11 +30,7 @@ func withWebFetch(ctx context.Context, tools []actool.CoreTool, proxy, caCert st
disableDirect := gated
var sbPolicy *sandbox.EgressPolicy
if SandboxRequired() {
info, _ := SandboxRunInfoFromContext(ctx)
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
if err != nil {
pol, _ = sandbox.NewEgressPolicy(info.TaskID, nil, nil, nil)
}
pol := SandboxEgressPolicy(ctx)
sbPolicy = pol
dialer = sandboxScopeDialContext(pol, dialer)
disableDirect = true
+26 -11
View File
@@ -222,10 +222,23 @@ func isDefaultDeniedAddr(addr netip.Addr) bool {
return false
}
type resolverCtxKey struct{}
// WithResolver returns ctx carrying fn: a policy without its own Resolver
// resolves names through fn for calls made with ctx (or a context derived from
// it). It is the seam tests use to answer lookups without the network, for the
// policies the panel tools build themselves; production code does not set it.
func WithResolver(ctx context.Context, fn func(ctx context.Context, host string) ([]netip.Addr, error)) context.Context {
return context.WithValue(ctx, resolverCtxKey{}, fn)
}
func (p *EgressPolicy) resolve(ctx context.Context, host string) ([]netip.Addr, error) {
if p.Resolver != nil {
return p.Resolver(ctx, host)
}
if fn, ok := ctx.Value(resolverCtxKey{}).(func(ctx context.Context, host string) ([]netip.Addr, error)); ok && fn != nil {
return fn(ctx, host)
}
ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip", host)
if err != nil {
return nil, err
@@ -324,9 +337,11 @@ func (p *EgressPolicy) logDecision(host string, port int, ip, protocol, decision
// CheckURL validates a navigation/fetch URL against the task scope allowlist.
// Only http/https/ws/wss schemes are permitted. Literal IPs must match
// ScopeCIDRs (blocking IMDS, loopback, RFC1918, and arbitrary non-scope IPs).
// Domains must match ScopeDomains; if DNS resolution returns addresses, at
// least one address must be allowed (rejecting domains resolving solely to
// private/IMDS/IPv6 addresses).
// Domains must match ScopeDomains and must resolve, and every resolved address
// must be allowed: a lookup error or an empty answer is a denial, and so is a
// name answering a public address next to a private/IMDS/IPv6 one. CheckURL
// pins nothing, and the connection may be made by someone else (a proxy, the
// browser) that picks any of the answers.
func (p *EgressPolicy) CheckURL(ctx context.Context, rawURL string) error {
rawURL = strings.TrimSpace(rawURL)
if rawURL == "" {
@@ -357,15 +372,15 @@ func (p *EgressPolicy) CheckURL(ctx context.Context, rawURL string) error {
if !p.domainAllowed(host) {
return fmt.Errorf("egress denied: domain %q is not in task scope%s", host, egressScopeHint)
}
// If DNS resolves, reject if every resolved IP is disallowed/private/IMDS/IPv6.
if addrs, err := p.resolve(ctx, host); err == nil && len(addrs) > 0 {
for _, addr := range addrs {
addr = addr.Unmap()
if p.ipInScopeCIDR(addr) || !isDefaultDeniedAddr(addr) {
return nil
}
addrs, err := p.resolve(ctx, host)
if err != nil || len(addrs) == 0 {
return fmt.Errorf("egress denied: dns lookup failed for %q: %v", host, err)
}
for _, addr := range addrs {
addr = addr.Unmap()
if !p.ipInScopeCIDR(addr) && isDefaultDeniedAddr(addr) {
return fmt.Errorf("egress denied: %q resolved to disallowed/private/IPv6 address %s", host, addr)
}
return fmt.Errorf("egress denied: %q resolved only to disallowed/private/IPv6 address %s", host, addrs[0].Unmap())
}
return nil
}
+92
View File
@@ -0,0 +1,92 @@
package sandbox
import (
"context"
"errors"
"net/netip"
"strings"
"testing"
)
// tableResolver answers from a table; a name it does not know fails as a
// lookup error would.
func tableResolver(answers map[string][]string) func(context.Context, string) ([]netip.Addr, error) {
return func(_ context.Context, host string) ([]netip.Addr, error) {
ips, ok := answers[host]
if !ok {
return nil, errors.New("lookup " + host + ": no such host")
}
out := make([]netip.Addr, 0, len(ips))
for _, ip := range ips {
out = append(out, netip.MustParseAddr(ip))
}
return out, nil
}
}
func dnsPolicy(t *testing.T, cidrs []string, answers map[string][]string) *EgressPolicy {
t.Helper()
p, err := NewEgressPolicy("dns-egress", []string{"allowed.example"}, cidrs, nil)
if err != nil {
t.Fatal(err)
}
p.Resolver = tableResolver(answers)
return p
}
// A name in scope whose lookup fails, or answers nothing, is refused: CheckURL
// cannot tell where the connection would go.
func TestCheckURLDeniesOnDNSError(t *testing.T) {
p := dnsPolicy(t, nil, map[string][]string{"empty.allowed.example": {}})
for _, u := range []string{"http://nxdomain.allowed.example/", "https://empty.allowed.example/x"} {
err := p.CheckURL(context.Background(), u)
if err == nil || !strings.Contains(err.Error(), "egress denied") {
t.Fatalf("CheckURL(%s) = %v, want a denial", u, err)
}
}
}
// A name answering a public address next to the metadata address (or a private
// one) is refused whatever the order of the answers: the client or a proxy may
// connect to any of them.
func TestCheckURLDeniesDualAWithMetadata(t *testing.T) {
p := dnsPolicy(t, nil, map[string][]string{
"imds-first.allowed.example": {"169.254.169.254", "93.184.216.34"},
"public-first.allowed.example": {"93.184.216.34", "169.254.169.254"},
"private.allowed.example": {"93.184.216.34", "10.0.0.7"},
"v6-imds.allowed.example": {"93.184.216.34", "fd00:ec2::254"},
})
for _, host := range []string{"imds-first", "public-first", "private", "v6-imds"} {
u := "http://" + host + ".allowed.example/latest/meta-data/"
err := p.CheckURL(context.Background(), u)
if err == nil || !strings.Contains(err.Error(), "egress denied") {
t.Fatalf("CheckURL(%s) = %v, want a denial", u, err)
}
}
}
// Every answer allowed: public addresses, or an address listed in the scope
// CIDRs next to a public one, still pass.
func TestCheckURLAllowsWhenEveryAnswerAllowed(t *testing.T) {
p := dnsPolicy(t, []string{"10.0.0.0/24"}, map[string][]string{
"public.allowed.example": {"93.184.216.34", "93.184.216.35"},
"scoped.allowed.example": {"10.0.0.7", "93.184.216.34"},
})
for _, u := range []string{"http://public.allowed.example/", "http://scoped.allowed.example/"} {
if err := p.CheckURL(context.Background(), u); err != nil {
t.Fatalf("CheckURL(%s) = %v, want allowed", u, err)
}
}
}
// A policy without its own Resolver takes the one the context carries.
func TestResolverFromContext(t *testing.T) {
p, err := NewEgressPolicy("dns-egress", []string{"allowed.example"}, nil, nil)
if err != nil {
t.Fatal(err)
}
ctx := WithResolver(context.Background(), tableResolver(map[string][]string{"ok.allowed.example": {"93.184.216.34"}}))
if ip, err := p.ResolveAndCheck(ctx, "ok.allowed.example"); err != nil || ip.String() != "93.184.216.34" {
t.Fatalf("ResolveAndCheck = %v, %v; want the context resolver's answer", ip, err)
}
}
+52 -1
View File
@@ -698,6 +698,18 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if strings.TrimSpace(rawURL) == "" {
return actool.Errorf("http url is empty"), 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
// and to every connection (see sandboxHTTPTransport); a refusal is final,
// there is no direct fallback.
var sbPolicy *sandbox.EgressPolicy
if agent.SandboxRequired() {
sbPolicy = agent.SandboxEgressPolicy(ctx)
if err := sbPolicy.CheckURL(ctx, rawURL); err != nil {
return actool.Errorf("sandbox http tool blocked: " + err.Error()), nil
}
}
// The hook saw the parameters, not the URL they render (nor a URL written in
// the template): the target gate reads the rendered URL here, before the
// tool's own timeout starts, so a wait for an approval does not consume it.
@@ -726,11 +738,18 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if intercept.ApplyAssessmentUserAgent(req) {
client.CheckRedirect = assessmentRedirectCheck(client.CheckRedirect)
}
if sbPolicy != nil {
client.CheckRedirect = sandboxRedirectCheck(sbPolicy, 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.
var base http.RoundTripper = http.DefaultTransport
if tr := s.httpToolTransport(ctx, key, spec); tr != nil {
tr := s.httpToolTransport(ctx, key, spec)
if sbPolicy != nil {
tr = sandboxHTTPTransport(tr, sbPolicy)
}
if tr != nil {
base = tr
}
client.Transport = egress.Current().Transport(key, base)
@@ -759,6 +778,38 @@ func assessmentRedirectCheck(check func(*http.Request, []*http.Request) error) f
}
}
// sandboxRedirectCheck refuses a redirect hop to a URL the task's egress policy
// does not allow, before check runs: the call fails instead of following it.
func sandboxRedirectCheck(policy *sandbox.EgressPolicy, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
return func(req *http.Request, via []*http.Request) error {
if err := policy.CheckURL(req.Context(), req.URL.String()); err != nil {
return fmt.Errorf("sandbox http tool blocked redirect: %w", err)
}
return check(req, via)
}
}
// sandboxHTTPTransport makes every connection of an http tool call go through
// the WebFetch sandbox dialer, which checks the host against the policy and
// dials only the IP it resolved and allowed. tr is httpToolTransport's result:
// with a proxy, the proxy is the connection checked; a direct call drops the
// environment proxy so the dialer sees the target, and keeps the pinned dialer
// of a gated scope underneath. Keep-alive is off on every one of them, proxy or
// not: no connection outlives the call it was checked for.
func sandboxHTTPTransport(tr *http.Transport, policy *sandbox.EgressPolicy) *http.Transport {
if tr == nil {
base, ok := http.DefaultTransport.(*http.Transport)
if !ok {
base = &http.Transport{}
}
tr = base.Clone()
tr.Proxy = nil
}
tr.DisableKeepAlives = true
tr.DialContext = agent.SandboxScopeDialContext("http tool", policy, tr.DialContext)
return tr
}
// 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
+103
View File
@@ -0,0 +1,103 @@
package server
import (
"context"
"errors"
"net/netip"
"strings"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
)
// dnsTable answers lookups from a table, without the network; a name it does
// not know fails as a lookup error would.
func dnsTable(answers map[string][]string) func(context.Context, string) ([]netip.Addr, error) {
return func(_ context.Context, host string) ([]netip.Addr, error) {
ips, ok := answers[host]
if !ok {
return nil, errors.New("lookup " + host + ": no such host")
}
out := make([]netip.Addr, 0, len(ips))
for _, ip := range ips {
out = append(out, netip.MustParseAddr(ip))
}
return out, nil
}
}
// proxyDNSCtx is a sandbox run whose scope lists allowed.example and the
// loopback proxy, with lookups answered by answers.
func proxyDNSCtx(answers map[string][]string) context.Context {
return sandbox.WithResolver(sandboxCtx([]string{"allowed.example"}, []string{"127.0.0.1/32"}), dnsTable(answers))
}
// Through an explicit proxy in scope, the panel dials the proxy and the proxy
// resolves the target: the target is checked by CheckURL alone. A target whose
// lookup fails is refused before the proxy is dialled; an in-scope target that
// resolves to a public address still goes through the same proxy.
func TestSandboxHTTPToolProxyRefusesTargetDNSError(t *testing.T) {
sandboxRequired(t)
proxy, proxyHits := canaryServer(t, "127.0.0.1", nil)
ctx := proxyDNSCtx(map[string][]string{"ok.allowed.example": {"203.0.113.10"}})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": "http://nxdomain.allowed.example/", "proxy": proxy.URL})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("target with a failed lookup not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := proxyHits.Load(); n != 0 {
t.Fatalf("proxy received %d request(s) for a target whose lookup failed", n)
}
res = runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": "http://ok.allowed.example/", "proxy": proxy.URL})
if res.IsError || !strings.Contains(res.Flatten(), "CANARY_BODY") || proxyHits.Load() != 1 {
t.Fatalf("resolved in-scope target through the proxy: isError=%v text=%q proxy hits=%d", res.IsError, res.Flatten(), proxyHits.Load())
}
}
// A target answering the metadata address next to a public one is refused
// before the proxy, which would pick its own answer, is dialled.
func TestSandboxHTTPToolProxyRefusesDualAMetadataTarget(t *testing.T) {
sandboxRequired(t)
proxy, proxyHits := canaryServer(t, "127.0.0.1", nil)
ctx := proxyDNSCtx(map[string][]string{"dual.allowed.example": {"169.254.169.254", "203.0.113.10"}})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": "http://dual.allowed.example/latest/meta-data/", "proxy": proxy.URL})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("dual-A metadata target not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := proxyHits.Load(); n != 0 {
t.Fatalf("proxy received %d request(s) for a dual-A metadata target", n)
}
}
// Every transport the sandbox builds for an http tool call has keep-alive off
// and the sandbox dialer: direct with the gate off or on, an operator proxy,
// and the recording proxy setting falling back to the global proxy.
func TestSandboxHTTPTransportKeepAlivesOff(t *testing.T) {
policy := agent.SandboxEgressPolicy(sandboxCtx([]string{"allowed.example"}, []string{"127.0.0.1/32"}))
gateOn := intercept.WithTargetScope(context.Background(), intercept.TargetScope{TaskID: "7", Enabled: func() bool { return true }})
s := &Server{m: &Manager{globalProxy: "http://127.0.0.1:3128"}}
direct := "http://api.allowed.example/"
for _, c := range []struct {
name string
ctx context.Context
spec httpExec
}{
{"direct, gate off", context.Background(), httpExec{URL: direct}},
{"direct, gate on", gateOn, httpExec{URL: direct}},
{"operator proxy", context.Background(), httpExec{URL: direct, Proxy: "http://127.0.0.1:8080"}},
{"operator proxy, gate on", gateOn, httpExec{URL: direct, Proxy: "127.0.0.1:8080"}},
{"recording proxy via the global proxy", context.Background(), httpExec{URL: direct, UseRecordingProxy: true}},
} {
tr := sandboxHTTPTransport(s.httpToolTransport(c.ctx, "probe", c.spec), policy)
if tr == nil || tr.DialContext == nil {
t.Fatalf("%s: transport %+v, want one with the sandbox dialer", c.name, tr)
}
if !tr.DisableKeepAlives {
t.Fatalf("%s: DisableKeepAlives = false, want keep-alive off on every sandbox transport", c.name)
}
}
}
+266
View File
@@ -0,0 +1,266 @@
package server
import (
"context"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/sandbox"
actool "github.com/Autumn-27/norma/tool"
)
// sandboxRequired puts the process in ARTEX_SANDBOX=required mode for one test.
func sandboxRequired(t *testing.T) {
t.Helper()
prev := agent.CurrentSandboxExecutor()
agent.SetSandboxExecutor(&agent.SandboxExecutor{Mode: sandbox.ModeRequired})
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
}
// canaryServer counts every request it receives. ip is the loopback address it
// listens on (127.0.0.1 or 127.0.0.2, both on lo).
func canaryServer(t *testing.T, ip string, h http.HandlerFunc) (*httptest.Server, *atomic.Int32) {
t.Helper()
hits := new(atomic.Int32)
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
if h != nil {
h(w, r)
return
}
_, _ = w.Write([]byte("CANARY_BODY"))
}))
ln, err := net.Listen("tcp", ip+":0")
if err != nil {
t.Fatalf("listen %s: %v", ip, err)
}
srv.Listener = ln
srv.Start()
t.Cleanup(srv.Close)
return srv, hits
}
func sandboxCtx(domains, cidrs []string) context.Context {
return agent.WithSandboxRunInfo(context.Background(), agent.SandboxRunInfo{
TaskID: "custom-http-egress", ScopeDomains: domains, ScopeCIDRs: cidrs,
})
}
func runHTTPSpec(t *testing.T, ctx context.Context, spec map[string]any) actool.Result {
t.Helper()
raw, _ := json.Marshal(spec)
res, err := (&Server{}).runHTTPTool(ctx, "probe", raw, map[string]any{}, nil)
if err != nil {
t.Fatalf("runHTTPTool: %v", err)
}
return res
}
// A URL outside the task scope is refused before any request leaves.
func TestSandboxHTTPToolRefusesOutOfScopeURL(t *testing.T) {
sandboxRequired(t)
srv, hits := canaryServer(t, "127.0.0.1", nil)
ctx := sandboxCtx([]string{"allowed.example"}, nil)
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": srv.URL + "/secret"})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("out-of-scope URL not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := hits.Load(); n != 0 {
t.Fatalf("out-of-scope server received %d request(s)", n)
}
}
// A name in scope that resolves only to loopback is not dialed: the policy
// treats it as WebFetch does (loopback is denied unless listed in the CIDRs).
func TestSandboxHTTPToolRefusesScopedNameResolvingToLoopback(t *testing.T) {
sandboxRequired(t)
srv, hits := canaryServer(t, "127.0.0.1", nil)
_, port, _ := net.SplitHostPort(srv.Listener.Addr().String())
ctx := sandboxCtx([]string{"localhost"}, nil)
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": "http://localhost:" + port + "/"})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("scoped name resolving to loopback not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := hits.Load(); n != 0 {
t.Fatalf("loopback server received %d request(s)", n)
}
}
// A redirect from an in-scope URL to a host outside the scope fails; the
// outside host never receives the request.
func TestSandboxHTTPToolRefusesRedirectOutOfScope(t *testing.T) {
sandboxRequired(t)
outside, outsideHits := canaryServer(t, "127.0.0.2", nil)
inScope, inHits := canaryServer(t, "127.0.0.1", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, outside.URL+"/stolen", http.StatusFound)
})
ctx := sandboxCtx(nil, []string{"127.0.0.1/32"})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": inScope.URL + "/start"})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("out-of-scope redirect not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := inHits.Load(); n != 1 {
t.Fatalf("in-scope server hits = %d, want 1", n)
}
if n := outsideHits.Load(); n != 0 {
t.Fatalf("out-of-scope redirect target received %d request(s)", n)
}
}
// A proxy configured on the tool is a connection the panel opens too: a proxy
// outside the scope is not dialed, even for an in-scope target.
func TestSandboxHTTPToolRefusesOutOfScopeProxy(t *testing.T) {
sandboxRequired(t)
target, targetHits := canaryServer(t, "127.0.0.1", nil)
proxy, proxyHits := canaryServer(t, "127.0.0.2", nil)
ctx := sandboxCtx(nil, []string{"127.0.0.1/32"})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": target.URL + "/", "proxy": proxy.URL})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("out-of-scope proxy not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := proxyHits.Load(); n != 0 {
t.Fatalf("out-of-scope proxy received %d request(s)", n)
}
if n := targetHits.Load(); n != 0 {
t.Fatalf("target received %d request(s) around the proxy", n)
}
}
// An in-scope URL still works under the sandbox (loopback listed in the scope
// CIDRs, the seam the WebFetch sandbox test uses).
func TestSandboxHTTPToolAllowsInScopeURL(t *testing.T) {
sandboxRequired(t)
srv, hits := canaryServer(t, "127.0.0.1", nil)
ctx := sandboxCtx(nil, []string{"127.0.0.1/32"})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": srv.URL + "/ok"})
if res.IsError || !strings.Contains(res.Flatten(), "CANARY_BODY") {
t.Fatalf("in-scope URL refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := hits.Load(); n != 1 {
t.Fatalf("in-scope server hits = %d, want 1", n)
}
}
// Sandbox off: the tool behaves as before, a loopback URL with no task scope
// and a redirect to another loopback host both go through.
func TestHTTPToolSandboxOffUnchanged(t *testing.T) {
prev := agent.CurrentSandboxExecutor()
agent.SetSandboxExecutor(nil)
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
other, otherHits := canaryServer(t, "127.0.0.2", nil)
srv, hits := canaryServer(t, "127.0.0.1", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, other.URL+"/next", http.StatusFound)
})
res := runHTTPSpec(t, context.Background(), map[string]any{"method": "GET", "url": srv.URL + "/"})
if res.IsError || !strings.Contains(res.Flatten(), "CANARY_BODY") {
t.Fatalf("sandbox-off call changed: isError=%v text=%q", res.IsError, res.Flatten())
}
if hits.Load() != 1 || otherHits.Load() != 1 {
t.Fatalf("hits = %d/%d, want 1/1", hits.Load(), otherHits.Load())
}
}
// customHTTPToolRow creates a Kind:"http" custom tool bound to the worker only,
// removed when the test ends.
func customHTTPToolRow(t *testing.T, pg *db.DB, key, rawURL string) *db.Tool {
t.Helper()
execRaw, _ := json.Marshal(map[string]any{"method": "GET", "url": rawURL})
row := &db.Tool{
Key: key, Description: "custom http egress probe", Kind: "http", Enabled: true,
Agents: []string{"worker"}, Exec: execRaw,
Schema: json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"}}}`),
}
_ = pg.DeleteCustomTool(key)
if err := pg.CreateCustomTool(row); err != nil {
t.Fatalf("create custom tool: %v", err)
}
t.Cleanup(func() {
_ = pg.DeleteCustomTool(key)
_, _ = pg.Exec(`DELETE FROM tool_usage WHERE tool_key=$1`, key)
})
return row
}
func openToolsPG(t *testing.T) *db.DB {
t.Helper()
dsn, _, err := db.DSN()
if err != nil {
db.SkipPGUnavailable(t, err)
}
pg, err := db.Open(dsn)
if err != nil {
db.SkipPGUnavailable(t, err)
}
t.Cleanup(func() { pg.Close() })
if err := pg.InitSecrets(t.TempDir()); err != nil {
t.Fatalf("init secrets: %v", err)
}
return pg
}
// The planner never receives a Kind:"http" custom tool bound to the worker,
// sandbox on or off; the worker does.
func TestCustomHTTPToolNotResolvedForPlanner(t *testing.T) {
pg := openToolsPG(t)
t.Setenv("AGENT_CORE_DISABLE_INTERACTIVE_SHELL", "1")
wireTools(pg, nil)
t.Cleanup(func() { agent.SetToolResolve(nil) })
s := &Server{m: &Manager{pg: pg}}
row := customHTTPToolRow(t, pg, "sec_http_egress_planner_probe", "http://127.0.0.1:1/")
base := []actool.CoreTool{s.buildCustomTool(row)}
for _, required := range []bool{false, true} {
if required {
sandboxRequired(t)
}
ctx := context.Background()
if _, ok := names(agent.ToolResolve()(ctx, "planner", base))[row.Key]; ok {
t.Fatalf("sandbox required=%v: planner received the Kind:http tool", required)
}
if _, ok := names(agent.ToolResolve()(ctx, "worker", base))[row.Key]; !ok {
t.Fatalf("sandbox required=%v: worker lost the Kind:http tool", required)
}
}
}
// End to end, as the worker gets it: the tool the worker resolves refuses a URL
// outside the task scope under the sandbox, and the target is never reached.
func TestCustomHTTPToolWorkerSandboxRefusesOutOfScope(t *testing.T) {
pg := openToolsPG(t)
t.Setenv("AGENT_CORE_DISABLE_INTERACTIVE_SHELL", "1")
wireTools(pg, nil)
t.Cleanup(func() { agent.SetToolResolve(nil) })
sandboxRequired(t)
srv, hits := canaryServer(t, "127.0.0.1", nil)
s := &Server{m: &Manager{pg: pg}}
row := customHTTPToolRow(t, pg, "sec_http_egress_worker_probe", srv.URL+"/secret?q={q}")
ctx := sandboxCtx([]string{"allowed.example"}, nil)
tool, ok := names(agent.ToolResolve()(ctx, "worker", []actool.CoreTool{s.buildCustomTool(row)}))[row.Key]
if !ok {
t.Fatal("worker did not receive the Kind:http tool")
}
res, err := tool.Call(ctx, json.RawMessage(`{"q":"x"}`), &actool.ToolContext{})
if err != nil {
t.Fatalf("call: %v", err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("worker Kind:http call outside the scope not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := hits.Load(); n != 0 {
t.Fatalf("out-of-scope server received %d request(s)", n)
}
}
+3 -1
View File
@@ -100,7 +100,9 @@ func TestSandboxScopeDriftBlockedAcrossProxyWebFetchAndBrowser(t *testing.T) {
return resp.StatusCode, nil
}
ctx := agent.WithSandboxRunInfo(context.Background(), info)
// WebFetch and the browser build their own policy: the same offline
// resolver reaches it through the context (a failed lookup is a denial).
ctx := sandbox.WithResolver(agent.WithSandboxRunInfo(context.Background(), info), pol.Resolver)
wf := agent.NewWebFetchTool(ctx, "", "")
webFetchCheck = func(rawURL string) (bool, string) {
in, _ := json.Marshal(map[string]any{"url": rawURL})
+2
View File
@@ -187,6 +187,8 @@ func TestSandboxSharedBrowserBlocksNonScopeNavigation(t *testing.T) {
ScopeDomains: []string{"app.example.com"},
ScopeCIDRs: []string{"203.0.113.10/32"},
})
// The in-scope name resolves offline (a failed lookup is a denial).
ctx = sandbox.WithResolver(ctx, dnsTable(map[string][]string{"sub.app.example.com": {"203.0.113.10"}}))
blockedURLs := []string{
"http://169.254.169.254/latest/meta-data/",
+3 -1
View File
@@ -205,7 +205,9 @@ func TestMainSideConcurrencyAndIndependentCancellation(t *testing.T) {
p := fakeProvider{stream: func(ctx context.Context, _ llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(y func(llm.StreamEvent, error) bool) {
started <- struct{}{}
y(llm.StreamEvent{Type: llm.SEMessageStart, Usage: llm.Usage{InputTokens: 7}}, nil)
if !y(llm.StreamEvent{Type: llm.SEMessageStart, Usage: llm.Usage{InputTokens: 7}}, nil) {
return
}
<-ctx.Done()
y(llm.StreamEvent{}, ctx.Err())
}
+1 -1
View File
@@ -11,7 +11,7 @@
"format": "biome format --write",
"check": "biome check",
"check:fix": "biome check --write",
"prepare": "husky",
"prepare": "cd .. && husky web/.husky",
"generate:presets": "ts-node -P tsconfig.scripts.json src/scripts/generate-theme-presets.ts",
"test:polling": "node --test scripts/polling.test.mjs",
"test:replay": "node --test scripts/replay.test.mjs",