mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-02 20:53:56 +08:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
de16c16bdc | ||
|
|
edd1a3c2b6 | ||
|
|
e736474085 | ||
|
|
7455d7f706 | ||
|
|
0ced7302f3 | ||
|
|
de63398481 | ||
|
|
9013eeeb6a | ||
|
|
d4fc42eb96 | ||
|
|
c8f057a039 | ||
|
|
a0948d8792 | ||
|
|
203a05ff48 |
@@ -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
@@ -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
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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})
|
||||
|
||||
@@ -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/",
|
||||
|
||||
@@ -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
@@ -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",
|
||||
|
||||
Reference in New Issue
Block a user