Compare commits

...
Author SHA1 Message Date
BaaRai 8f91643b78 Merge pull request #501 from YunzhouLi-hub/docs/operator-advisory-review
docs: describe operator review of public advisories
2026-12-01 22:33:55 +01:00
BaaRai 44f6f035ac Merge pull request #764 from renaesop/codex/runner-exec-cleanup
fix(sandbox): remove workers on failed execs and task deletion
2026-12-01 22:33:35 +01:00
BaaRai 33c24bbc63 Merge pull request #782 from IamLugus/feat/domain-suffix-intercept-rule
feat(db): add a domain_suffix asset interception rule kind
2026-12-01 22:33:30 +01:00
BaaRai 52131ab78d Merge pull request #675 from BaaRai/dependabot/github_actions/docker/build-push-action-7.4.0
deps(actions): bump docker/build-push-action from 6.19.2 to 7.4.0
2026-12-01 22:33:19 +01:00
BaaRai b1a48c8ef8 Merge pull request #674 from BaaRai/dependabot/github_actions/actions/setup-node-7.1.0
deps(actions): bump actions/setup-node from 4.4.0 to 7.1.0
2026-12-01 22:33:14 +01:00
BaaRai 8c9619672a Merge pull request #673 from BaaRai/dependabot/github_actions/docker/login-action-4.8.0
deps(actions): bump docker/login-action from 3.7.0 to 4.8.0
2026-12-01 22:33:09 +01:00
BaaRai 2fb715043b Merge pull request #671 from BaaRai/dependabot/github_actions/docker/metadata-action-6.2.0
deps(actions): bump docker/metadata-action from 5.10.0 to 6.2.0
2026-12-01 22:33:04 +01:00
BaaRai 8024a30c84 Merge pull request #669 from BaaRai/dependabot/github_actions/actions/setup-python-7.1.0
deps(actions): bump actions/setup-python from 5.6.0 to 7.1.0
2026-12-01 22:32:58 +01:00
BaaRai e736474085 Merge pull request #785 from BaaRai/sec/custom-http-egress-gate
security: enforce the task egress policy on custom HTTP tools
2026-12-01 22:17:27 +01:00
BaaRai 7455d7f706 Merge pull request #788 from leninworld/fix/responses-default-model
fix(llm): default openai-responses to gpt-6.2-sol before gpt-5 shuts down
2026-12-01 22:09:23 +01:00
BaaRai 0ced7302f3 Merge pull request #784 from thecorporatetractor/fix/sidequestion-test-yield
test(sidequestion): stop the fake stream when the consumer stops
2026-12-01 22:09:09 +01:00
BaaRai de63398481 Merge pull request #776 from amshivang/fix/husky-prepare-script
fix(web): run husky prepare from repo root so the pre-commit hook installs
2026-12-01 22:08:38 +01:00
BaaRai 9013eeeb6a Merge pull request #786 from BaaRai/chore/remove-php2shell
chore(skills): remove the experimental php2shell research skill
2026-12-01 22:08:33 +01:00
Lenin Mookiah d4fc42eb96 fix(llm): default openai-responses to gpt-6.2-sol before gpt-5 shuts down
OpenAI shuts gpt-5 down on 2026-12-11 and lists gpt-6.2-sol as its
replacement. Use it as the openai-responses default in FromEnv and
ConfigFrom; an explicitly set model is kept.

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

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

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

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

Sandbox off: nothing changes, the new code is skipped. The planner still
does not receive a Kind "http" tool bound to the worker.
2026-12-01 21:31:54 +01:00
Marco Azarmaneche a0948d8792 test(sidequestion): stop the fake stream when the consumer stops
TestMainSideConcurrencyAndIndependentCancellation panics intermittently with
"range function continued iteration after function for loop body returned
false". The fake iterator ignored yield's result: when the side context is
cancelled before the first event is handled, Answer stops ranging, and the
iterator then called yield again after ctx.Done(). Return when yield returns
false. Test-only change.
2026-12-01 22:26:30 +02:00
LugussandClaude Opus 5.5 d05740cad7 feat(db): add a domain_suffix asset interception rule kind
fuzzy_domain is a substring match, so an allow rule meant to cover a
site and its subdomains (".example.com") also admits names that merely
contain it, such as "a.example.com.other.net", whose owner chooses where
it resolves. There was no kind for "this domain and its subdomains" on a
label boundary.

domain_suffix matches the domain itself and any name ending in
"." + domain; "*.example.com" and ".example.com" are stored as
"example.com". This is the semantics the sandbox egress policy already
applies to scope domains, and taskSandboxRunInfo already read a
domain_suffix allow rule. fuzzy_domain is unchanged, so existing rules
keep their meaning.

Migration 0026 widens the kind CHECK constraint of asset_intercept_rules
and task_intercept_rules; schema.sql carries the same list for new
databases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:10:12 +01:00
Shivang Shukla 203a05ff48 fix(web): run husky prepare from repo root so the pre-commit hook installs 2026-12-01 18:48:51 +00:00
renaesop 7419ae5f77 fix(sandbox): remove workers on failed execs and task deletion 2026-12-02 00:01:05 +08:00
dependabot[bot] 2615f05fc9 deps(actions): bump docker/build-push-action from 6.19.2 to 7.4.0
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 6.19.2 to 7.4.0.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/10e90e3645eae34f1e60eeb005ba3a3d33f178e8...c3c9e263c25d99ce0380d002d59b67737d91b0dc)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-version: 7.4.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-30 20:15:21 +00:00
dependabot[bot] 175b423536 deps(actions): bump docker/metadata-action from 5.10.0 to 6.2.0
Bumps [docker/metadata-action](https://github.com/docker/metadata-action) from 5.10.0 to 6.2.0.
- [Release notes](https://github.com/docker/metadata-action/releases)
- [Commits](https://github.com/docker/metadata-action/compare/c299e40c65443455700f0fdfc63efafe5b349051...dc802804100637a589fabce1cb79ff13a1411302)

---
updated-dependencies:
- dependency-name: docker/metadata-action
  dependency-version: 6.2.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-30 20:15:21 +00:00
dependabot[bot] 4aaf5b3375 deps(actions): bump docker/login-action from 3.7.0 to 4.8.0
Bumps [docker/login-action](https://github.com/docker/login-action) from 3.7.0 to 4.8.0.
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/c94ce9fb468520275223c153574b00df6fe4bcc9...8aa5831fb8d48d8f76594c7ddde61ae58019f550)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: 4.8.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-30 20:15:19 +00:00
dependabot[bot] 0769120e1b deps(actions): bump actions/setup-node from 4.4.0 to 7.1.0
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 4.4.0 to 7.1.0.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/49933ea5288caeca8642d1e84afbd3f7d6820020...949feb2413d6458794dcd2491c4babbbce0c15c1)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: 7.1.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-28 18:25:27 +00:00
dependabot[bot] 442c48fddd deps(actions): bump actions/setup-python from 5.6.0 to 7.1.0
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 5.6.0 to 7.1.0.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/a26af69be951a213d495a4c3e4e4022e16d87065...6d4fd22b20465ccc0f7354476588e8df7c9ca0e0)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-version: 7.1.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-28 18:25:18 +00:00
李云周 5654a9d78f docs: move advisory review guide under docs 2026-11-28 11:22:36 +08:00
李云周 1b1eb1aa42 docs: describe operator review of public advisories 2026-11-23 10:33:07 +08:00
35 changed files with 1142 additions and 76 deletions
+2 -2
View File
@@ -206,7 +206,7 @@ jobs:
working-directory: web
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "22"
cache: npm
@@ -239,7 +239,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.12"
- run: python3 scripts/posture_check_test.py
+8 -8
View File
@@ -15,7 +15,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "22"
cache: npm
@@ -172,12 +172,12 @@ jobs:
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
- name: Log in to GitHub Container Registry
if: github.event_name == 'push'
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
- uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
id: meta
with:
images: ghcr.io/baarai/artex-${{ matrix.name }}
@@ -185,7 +185,7 @@ jobs:
type=ref,event=tag
type=semver,pattern={{version}}
type=raw,value=latest
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
with:
context: .
file: ${{ matrix.dockerfile }}
@@ -229,18 +229,18 @@ jobs:
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
- name: Log in to GitHub Container Registry
if: github.event_name == 'push'
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Log in to Docker Hub
if: github.event_name == 'push' && vars.DOCKERHUB_ENABLED == 'true'
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
- uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
id: meta
with:
images: |
@@ -250,7 +250,7 @@ jobs:
type=ref,event=tag
type=semver,pattern={{version}}
type=raw,value=latest
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
with:
context: .
platforms: linux/amd64,linux/arm64
+5
View File
@@ -8,9 +8,14 @@ All notable changes to this project are documented in this file. The format is b
- **Company egress is promoted only from operator-approved company scope.** A sandboxed worker could register assets with `insert_assets` (an attacker IP or domain attributed to the company through its domain or ICP rule), and the agent could add rules with `add_company_scope`; the next operator selection or re-approval of the company copied those hosts into `task_scope_egress`, persistently widening the approved sandbox egress. The approval snapshot now copies only `company_scope` domain and IP/CIDR rules with the new `approved_by_operator` flag (migration `0025_company_scope_approved.sql`), which only the operator company API sets; `add_company_scope` and the ScopeSentry sync store rules with the flag off. Existing rules are backfilled as approved. Behaviour change: a domain or IP discovered only in assets is no longer reachable from the sandbox until it is added explicitly to the company scope (operator) or to the task scope. Egress rows already frozen by earlier approvals are not purged by this change, and re-approving the company does not remove them (the snapshot only adds rows); removing the company from the task scope drops its rows, and approving it again rebuilds them from approved rules only.
### Added
- **`domain_suffix` asset interception rule kind**: a domain and its subdomains, matched on a label boundary. `example.com` matches `example.com` and `a.example.com`, but not `a.example.com.other.net` or `badexample.com`, which `fuzzy_domain`'s substring match also lets through; that makes it the kind to use for a task allow-list that covers a site. `*.example.com` and `.example.com` are stored as `example.com`. It is the label-boundary semantics the sandbox egress policy already applies, and a `domain_suffix` allow rule is now a scope domain for that policy too (`taskSandboxRunInfo` already read the kind). `fuzzy_domain` is unchanged. Migration `0026_asset_intercept_domain_suffix.sql` widens the `kind` CHECK constraint of both rule tables.
### 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
+5
View File
@@ -879,6 +879,11 @@ For a recurring problem, share the ARTEX version or commit, the model and versio
excerpt of the affected input and result. Remove credentials, target data, and other sensitive
content before sharing.
### Reviewing a published vulnerability advisory
See [Reviewing a published vulnerability advisory](docs/operator-advisory-review.md) for the
CVE and GHSA review workflow.
### Backups
`scripts/backup.sh` dumps the Postgres database (and optionally the data directory) with
+7 -2
View File
@@ -232,6 +232,11 @@ func compactionConfig(windowTokens int) *compaction.Config {
return &compaction.Config{ContextWindow: windowTokens}
}
// defaultOpenAIResponsesModel is the model used by the openai-responses format
// when none is set. OpenAI shuts gpt-5 down on 2026-12-11 and lists
// gpt-6.2-sol as its replacement (platform deprecations page).
const defaultOpenAIResponsesModel = "gpt-6.2-sol"
// FromEnv resolves the LLM provider config:
//
// ARTEX_LLM_PROVIDER = anthropic|openai|openai-responses|ollama (default: inferred from keys)
@@ -276,7 +281,7 @@ func FromEnv() (Config, bool) {
c.Format = llm.FormatOpenAIResponses
c.APIKey = oaiKey
if c.Model == "" {
c.Model = "gpt-5"
c.Model = defaultOpenAIResponsesModel
}
case "ollama":
c.Format = FormatOllama
@@ -334,7 +339,7 @@ func ConfigFrom(provider, model, baseURL, apiKey, proxy string) Config {
// provider appends "/responses"; tolerate a full endpoint URL.
c.BaseURL = strings.TrimRight(strings.TrimSuffix(c.BaseURL, "/responses"), "/")
if c.Model == "" {
c.Model = "gpt-5"
c.Model = defaultOpenAIResponsesModel
}
case "ollama":
c.Format = FormatOllama
+27
View File
@@ -28,3 +28,30 @@ func TestConfigFromOpenAIResponses(t *testing.T) {
t.Fatalf("NewProvider: %v", err)
}
}
// TestOpenAIResponsesDefaultModel: with no model set, the openai-responses
// format defaults to a model OpenAI still serves. gpt-5 shuts down on
// 2026-12-11 (OpenAI deprecations page); its listed replacement is gpt-6.2-sol.
// An explicitly chosen model is kept as is.
func TestOpenAIResponsesDefaultModel(t *testing.T) {
const want = "gpt-6.2-sol"
if c := ConfigFrom("openai-responses", "", "", "sk-x", ""); c.Model != want {
t.Fatalf("ConfigFrom default model=%q, want %q", c.Model, want)
}
if c := ConfigFrom("openai-responses", " gpt-5 ", "", "sk-x", ""); c.Model != "gpt-5" {
t.Fatalf("ConfigFrom explicit model=%q, want gpt-5 kept", c.Model)
}
t.Setenv("ARTEX_LLM_PROVIDER", "openai-responses")
t.Setenv("OPENAI_API_KEY", "sk-oai")
t.Setenv("ARTEX_LLM_BASE_URL", "")
t.Setenv("ARTEX_LLM_MODEL", "")
c, ok := FromEnv()
if !ok || c.Model != want {
t.Fatalf("FromEnv default model=%q ok=%v, want %q", c.Model, ok, want)
}
t.Setenv("ARTEX_LLM_MODEL", "gpt-5")
if c, ok := FromEnv(); !ok || c.Model != "gpt-5" {
t.Fatalf("FromEnv explicit model=%q ok=%v, want gpt-5 kept", c.Model, ok)
}
}
+22 -3
View File
@@ -183,23 +183,42 @@ func formatSandboxExecResult(resp sandbox.ExecResponse, tc *actool.ToolContext)
return actool.Text(out)
}
// SandboxEgressPolicy is the task's sandbox.EgressPolicy for ctx, the one
// WebFetch enforces in ARTEX_SANDBOX=required mode: the scope domains and CIDRs
// of the run, or, when they do not parse or the run carries none, a policy that
// allows nothing.
func SandboxEgressPolicy(ctx context.Context) *sandbox.EgressPolicy {
info, _ := SandboxRunInfoFromContext(ctx)
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
if err != nil {
pol, _ = sandbox.NewEgressPolicy(info.TaskID, nil, nil, nil)
}
return pol
}
// sandboxScopeDialContext wraps baseDial so every TCP connection made by panel
// WebFetch in ARTEX_SANDBOX=required mode validates and pins the target IP via
// the task's sandbox.EgressPolicy (blocking non-scope IPs, IMDS, loopback,
// RFC1918, and IPv6 across all hops and redirects).
func sandboxScopeDialContext(policy *sandbox.EgressPolicy, baseDial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) {
return SandboxScopeDialContext("WebFetch", policy, baseDial)
}
// SandboxScopeDialContext is the WebFetch sandbox dialer for another panel tool
// that connects out from the panel process; label names the tool in a refusal.
func SandboxScopeDialContext(label string, policy *sandbox.EgressPolicy, baseDial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("sandbox WebFetch blocked invalid target %q: %w", addr, err)
return nil, fmt.Errorf("sandbox %s blocked invalid target %q: %w", label, addr, err)
}
port, err := strconv.Atoi(portStr)
if err != nil || port <= 0 || port > 65535 {
return nil, fmt.Errorf("sandbox WebFetch blocked invalid port %q", portStr)
return nil, fmt.Errorf("sandbox %s blocked invalid port %q", label, portStr)
}
pinnedIP, err := policy.ResolveAndCheck(ctx, host)
if err != nil {
return nil, fmt.Errorf("sandbox WebFetch blocked: %w", err)
return nil, fmt.Errorf("sandbox %s blocked: %w", label, err)
}
pinnedAddr := net.JoinHostPort(pinnedIP.String(), strconv.Itoa(port))
if baseDial != nil {
+1 -5
View File
@@ -30,11 +30,7 @@ func withWebFetch(ctx context.Context, tools []actool.CoreTool, proxy, caCert st
disableDirect := gated
var sbPolicy *sandbox.EgressPolicy
if SandboxRequired() {
info, _ := SandboxRunInfoFromContext(ctx)
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
if err != nil {
pol, _ = sandbox.NewEgressPolicy(info.TaskID, nil, nil, nil)
}
pol := SandboxEgressPolicy(ctx)
sbPolicy = pol
dialer = sandboxScopeDialContext(pol, dialer)
disableDirect = true
+1 -1
View File
@@ -9,7 +9,7 @@ import "time"
type AssetInterceptRule struct {
ID int64 `json:"id"`
Enabled bool `json:"enabled"`
Kind string `json:"kind"` // exact_domain|exact_ip|exact_url|fuzzy_domain|fuzzy_ip|fuzzy_url|cidr
Kind string `json:"kind"` // exact_domain|exact_ip|exact_url|domain_suffix|fuzzy_domain|fuzzy_ip|fuzzy_url|cidr
Pattern string `json:"pattern"`
Note string `json:"note"`
Builtin bool `json:"builtin"`
+67
View File
@@ -0,0 +1,67 @@
package db
import (
"io/fs"
"testing"
)
// A database created before domain_suffix has the seven-kind CHECK constraints.
// Migration 0026 widens them, idempotently, on both rule tables; an unknown
// kind is still refused.
func TestDomainSuffixKindMigration0026(t *testing.T) {
d := openTargetDB(t)
const oldKinds = `('exact_domain','exact_ip','exact_url','fuzzy_domain','fuzzy_ip','fuzzy_url','cidr')`
if _, err := d.Exec(`
ALTER TABLE asset_intercept_rules DROP CONSTRAINT IF EXISTS asset_intercept_rules_kind_check;
ALTER TABLE asset_intercept_rules ADD CONSTRAINT asset_intercept_rules_kind_check CHECK (kind IN ` + oldKinds + `);
ALTER TABLE task_intercept_rules DROP CONSTRAINT IF EXISTS task_intercept_rules_kind_check;
ALTER TABLE task_intercept_rules ADD CONSTRAINT task_intercept_rules_kind_check CHECK (kind IN ` + oldKinds + `);`); err != nil {
t.Fatal(err)
}
migration, err := fs.ReadFile(migrationsFS(), "0026_asset_intercept_domain_suffix.sql")
if err != nil {
t.Fatal(err)
}
// Whatever happens below, leave the current constraints in place.
t.Cleanup(func() { _, _ = d.Exec(string(migration)) })
// Disabled, so the global rule cannot affect another test sharing the database.
global := func(kind string) error {
r, err := d.CreateAssetInterceptRule(kind, "example.com", "domain_suffix migration test", false)
if err == nil {
t.Cleanup(func() { _ = d.DeleteAssetInterceptRule(r.ID) })
}
return err
}
task, err := d.CreateTaskWithOptions("domain_suffix migration test", "goal", TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM tasks WHERE id=$1`, task.ID) })
perTask := func(kind string) error {
_, err := d.Assets().CreateTaskInterceptRule(task.ID, "allow", kind, "example.com", "", true)
return err
}
if global("domain_suffix") == nil || perTask("domain_suffix") == nil {
t.Fatal("the old constraints accepted a domain_suffix rule")
}
for range 2 { // idempotent
if _, err := d.Exec(string(migration)); err != nil {
t.Fatalf("apply migration: %v", err)
}
}
if err := global("domain_suffix"); err != nil {
t.Fatalf("global domain_suffix rule refused after the migration: %v", err)
}
if err := perTask("domain_suffix"); err != nil {
t.Fatalf("task domain_suffix rule refused after the migration: %v", err)
}
_, allow, err := d.Assets().TaskInterceptRulesSplit(task.ID)
if err != nil || len(allow) != 1 || allow[0].Kind != "domain_suffix" {
t.Fatalf("task allow rules = %+v, %v; want the domain_suffix rule", allow, err)
}
if global("domain_glob") == nil || perTask("domain_glob") == nil {
t.Fatal("an unknown kind was accepted")
}
}
+28
View File
@@ -31,6 +31,19 @@ func CanonicalInterceptDomain(s string) string {
return d
}
// DomainSuffixPattern canonicalizes a domain_suffix pattern: the domain itself,
// with one leading "*." or "." dropped, so "*.Example.com" and ".example.com"
// both mean example.com and its subdomains. Empty when nothing is left.
func DomainSuffixPattern(s string) string {
d := strings.TrimSpace(s)
if rest, ok := strings.CutPrefix(d, "*."); ok {
d = rest
} else {
d = strings.TrimPrefix(d, ".")
}
return CanonicalInterceptDomain(d)
}
// CanonicalInterceptIP canonicalizes one side of an IP comparison: IPv4-mapped
// IPv6 addresses are unmapped and any zone is dropped, so "0:0:0:0:0:0:0:1"
// and "::1" compare equal. ok is false when s is not an IP literal.
@@ -52,6 +65,8 @@ func AssetInterceptKindLabel(kind string) string {
return "IP (exact)"
case "exact_url":
return "URL (exact)"
case "domain_suffix":
return "Domain (suffix)"
case "fuzzy_domain":
return "Domain (fuzzy)"
case "fuzzy_ip":
@@ -119,6 +134,19 @@ func matchOne(r AssetInterceptRule, domains, ips, urls []string) (string, bool)
return u, true
}
}
case "domain_suffix":
// The domain and its subdomains, on a label boundary: "example.com"
// matches "a.example.com" but not "a.example.com.evil.net" or
// "badexample.com", which fuzzy_domain's substring match lets through.
want := DomainSuffixPattern(p)
if want == "" {
return "", false
}
for _, d := range domains {
if cd := CanonicalInterceptDomain(d); cd == want || strings.HasSuffix(cd, "."+want) {
return d, true
}
}
case "fuzzy_domain":
lp := CanonicalInterceptDomain(p)
if lp == "" {
+37
View File
@@ -44,6 +44,29 @@ func TestMatchAssetInterceptRules(t *testing.T) {
[]string{"xn--bcher-kva.example"}, nil, nil, true, "xn--bcher-kva.example"},
{"fuzzy domain uppercase trailing-dot rule", []AssetInterceptRule{rule("fuzzy_domain", "EXAMPLE.COM.", true)},
[]string{"api.example.com"}, nil, nil, true, "api.example.com"},
{"domain suffix hits the domain itself", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
[]string{"EXAMPLE.com."}, nil, nil, true, "EXAMPLE.com."},
{"domain suffix hits a subdomain", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
[]string{"a.b.example.com"}, nil, nil, true, "a.b.example.com"},
{"domain suffix wildcard spelling", []AssetInterceptRule{rule("domain_suffix", "*.Example.COM.", true)},
[]string{"api.example.com"}, nil, nil, true, "api.example.com"},
{"domain suffix leading-dot spelling", []AssetInterceptRule{rule("domain_suffix", ".example.com", true)},
[]string{"api.example.com"}, nil, nil, true, "api.example.com"},
{"domain suffix IDNA rule", []AssetInterceptRule{rule("domain_suffix", "bücher.example", true)},
[]string{"shop.xn--bcher-kva.example"}, nil, nil, true, "shop.xn--bcher-kva.example"},
// Where fuzzy_domain's substring match hits, a label-boundary suffix must not.
{"domain suffix misses a name that only contains it", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
[]string{"a.example.com.evil.net"}, nil, nil, false, ""},
{"domain suffix misses a longer last label", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
[]string{"a.example.community"}, nil, nil, false, ""},
{"domain suffix misses a longer first label", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
[]string{"badexample.com"}, nil, nil, false, ""},
{"domain suffix misses the parent domain", []AssetInterceptRule{rule("domain_suffix", "api.example.com", true)},
[]string{"example.com"}, nil, nil, false, ""},
{"fuzzy domain hits a name that only contains it", []AssetInterceptRule{rule("fuzzy_domain", ".example.com", true)},
[]string{"a.example.com.evil.net"}, nil, nil, true, "a.example.com.evil.net"},
{"empty domain suffix no hit", []AssetInterceptRule{rule("domain_suffix", "*.", true)},
[]string{"example.com"}, nil, nil, false, ""},
{"fuzzy IP uppercase rule", []AssetInterceptRule{rule("fuzzy_ip", "FE80::", true)},
nil, []string{"fe80::1"}, nil, true, "fe80::1"},
{"fuzzy IP prefix hit", []AssetInterceptRule{rule("fuzzy_ip", "203.0.113.", true)},
@@ -117,6 +140,20 @@ func TestEvaluateAssetGate(t *testing.T) {
); d.Allowed {
t.Fatal("interception should take priority over allow")
}
// 7. A domain_suffix allow-list admits the site and refuses look-alikes
// that fuzzy_domain would admit.
suffix := []AssetInterceptRule{rule("domain_suffix", "example.com", true)}
for host, want := range map[string]bool{
"example.com": true,
"api.example.com": true,
"api.example.com.evil.net": false,
"api.example.community": false,
} {
if d := EvaluateAssetGate(nil, suffix, []string{host}, nil, nil); d.Allowed != want {
t.Fatalf("domain_suffix allow-list: %s allowed=%v, want %v", host, d.Allowed, want)
}
}
}
func TestAssetInterceptCandidates(t *testing.T) {
@@ -0,0 +1,11 @@
-- domain_suffix: a domain and its subdomains, matched on a label boundary
-- (example.com, a.example.com; not a.example.com.other.net). Existing rules
-- keep their kind; the CHECK constraints only gain the new value.
ALTER TABLE asset_intercept_rules DROP CONSTRAINT IF EXISTS asset_intercept_rules_kind_check;
ALTER TABLE asset_intercept_rules ADD CONSTRAINT asset_intercept_rules_kind_check
CHECK (kind IN ('exact_domain', 'exact_ip', 'exact_url', 'domain_suffix',
'fuzzy_domain', 'fuzzy_ip', 'fuzzy_url', 'cidr'));
ALTER TABLE task_intercept_rules DROP CONSTRAINT IF EXISTS task_intercept_rules_kind_check;
ALTER TABLE task_intercept_rules ADD CONSTRAINT task_intercept_rules_kind_check
CHECK (kind IN ('exact_domain', 'exact_ip', 'exact_url', 'domain_suffix',
'fuzzy_domain', 'fuzzy_ip', 'fuzzy_url', 'cidr'));
+4 -3
View File
@@ -1374,8 +1374,9 @@ ALTER TABLE side_question_requests ADD COLUMN IF NOT EXISTS context_info JSONB N
-- Independent from §K command interception (intercept_rules): intercept_rules matches tool names/input text,
-- while this table matches "target assets" — exact/fuzzy domains, IPs, URLs, and CIDR ranges.
-- Rules only; the concrete match/intercept logic is implemented elsewhere.
-- Seven kinds:
-- Eight kinds:
-- exact_domain / exact_ip / exact_url —— exact match
-- domain_suffix —— a domain and its subdomains (label boundary)
-- fuzzy_domain / fuzzy_ip / fuzzy_url —— fuzzy match
-- cidr —— CIDR range
-- =====================================================================
@@ -1383,7 +1384,7 @@ CREATE TABLE IF NOT EXISTS asset_intercept_rules (
id BIGSERIAL PRIMARY KEY,
enabled BOOLEAN NOT NULL DEFAULT true,
kind TEXT NOT NULL CHECK (kind IN (
'exact_domain', 'exact_ip', 'exact_url',
'exact_domain', 'exact_ip', 'exact_url', 'domain_suffix',
'fuzzy_domain', 'fuzzy_ip', 'fuzzy_url',
'cidr')),
pattern TEXT NOT NULL,
@@ -1412,7 +1413,7 @@ CREATE TABLE IF NOT EXISTS task_intercept_rules (
enabled BOOLEAN NOT NULL DEFAULT true,
action TEXT NOT NULL DEFAULT 'block' CHECK (action IN ('block','allow')),
kind TEXT NOT NULL CHECK (kind IN (
'exact_domain', 'exact_ip', 'exact_url',
'exact_domain', 'exact_ip', 'exact_url', 'domain_suffix',
'fuzzy_domain', 'fuzzy_ip', 'fuzzy_url',
'cidr')),
pattern TEXT NOT NULL,
+22
View File
@@ -70,6 +70,28 @@ ARTEX_SANDBOX=off
## Security Hardening Notes
### Worker cleanup after execution errors
Command timeout, cancellation or a broken execution stream removes the worker
container that ran the command. The runner also removes it when Docker cannot
confirm that the exec has finished. This terminates detached children and **all
other concurrent commands and background services in that task**. The next exec
recreates the worker; the task's `/workspace` directory survives. Successful
commands keep their worker and may leave intentional background services running.
Cleanup uses the captured container ID, so a delayed completion cannot remove a
replacement worker or another task's worker. Failed removal returns an error and
keeps the worker tracked for retry. Deleting a task removes its worker before its
proxy and network, including when no application processes remain in the worker.
Run the unit and simulated Engine tests with `go test -race ./sandbox`. On a
dedicated Docker host with the sandbox images built, enable the detached-child
cleanup test with:
```bash
ARTEX_SANDBOX_DOCKER_TEST=1 go test ./sandbox -run TestDockerTimeoutRemovesDetachedChild -v
```
- **Tamper-proof egress audit log**: `artex-egress-<id>` writes JSONL connection logs to a proxy-only bind mount (`/app/data/egress-audit/<id>/egress.jsonl`, mounted at `/audit:rw` inside the proxy) and stdout. The worker container only mounts `/app/data/tasks/<id>:/workspace:rw` and cannot read, truncate, or forge the egress audit log.
- **Kernel-backed kill-switch (no agent-writable state)**: `artex-worker-<id>` runs `/usr/local/bin/artex-exec-wrap --init` as PID 1 (reaping all orphaned children). On `POST /v1/tasks/{id}/kill`, `artex-runner` executes `/usr/local/bin/artex-exec-wrap --kill-uid 10001` as uid `10001` (preserving `--cap-drop ALL`) scanning `/proc` directly (defeating `setsid`, `nohup`, nested double-forked daemons, `trap '' TERM`, and `/tmp` tampering), verifies zero non-PID-1 uid-10001 processes remain, and falls back to force-removing the worker container if any check fails.
- **Browser & `WebFetch` containment**: In `ARTEX_SANDBOX=required` mode, local stdio MCP servers (including the default private browser MCP) are skipped on the panel; `WebFetch` enforces the task's `sandbox.EgressPolicy` on every URL, redirect hop, and pinned dial (with direct retry disabled); and the opt-in panel-hosted shared browser MCP is only attached when `target_gate` is enabled or an explicit egress proxy is configured, with every browser navigation URL gated against the task's `sandbox.EgressPolicy` (execution containment + scope-gated panel fetch/browser; full subresource browser network isolation requires running the shared browser behind `egress-guard` in `EGRESS_MODE=enforce`).
+12
View File
@@ -0,0 +1,12 @@
# Reviewing a published vulnerability advisory
When a finding cites a CVE or GHSA identifier, look up that exact identifier in the
[NVD vulnerability search](https://nvd.nist.gov/vuln/search) or the
[GitHub Advisory Database](https://github.com/advisories). Check the issuer's advisory for the
affected product, version range and fixed versions. An identifier alone cannot confirm that an
installed version is affected.
Record the identifier, source URL, advisory's last-updated date when available, and the installed
version in your review notes. If the advisory and the observed version disagree, document the
difference and defer the applicability decision until you can confirm it. Search using public identifiers
and keep private hostnames, logs and credentials in your ARTEX instance.
+82 -34
View File
@@ -40,8 +40,8 @@ type taskContainers struct {
proxyID string
netName string
scopeHash string
// cleanupMu serializes Kill and Delete for this task. A pause racing a
// delete must not interleave two cleanup sequences over the same IDs.
// cleanupMu serializes creation, recovery on exec, and cleanup for this task.
// Commands may execute concurrently, but lifecycle changes share this lock.
cleanupMu sync.Mutex
}
@@ -441,14 +441,28 @@ func scopeFingerprint(domains, cidrs []string) string {
func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDomains, scopeCIDRs []string) (*taskContainers, error) {
b.mu.Lock()
tc := b.tasks[taskID]
if tc == nil {
tc = &taskContainers{taskID: taskID, netName: b.cfg.TaskNetPrefix + taskID}
b.tasks[taskID] = tc
}
b.mu.Unlock()
tc.cleanupMu.Lock()
defer tc.cleanupMu.Unlock()
// Delete may have completed while this request waited for the lifecycle lock.
b.mu.Lock()
current := b.tasks[taskID] == tc
b.mu.Unlock()
if !current {
return nil, fmt.Errorf("%w: task %s was deleted", ErrNotFound, taskID)
}
netName := b.cfg.TaskNetPrefix + taskID
tc.netName = netName
proxyName := "artex-egress-" + taskID
workerName := "artex-worker-" + taskID
sh := scopeFingerprint(scopeDomains, scopeCIDRs)
if tc != nil && tc.scopeHash == sh {
if tc.scopeHash == sh {
proxyOK := tc.proxyID != "" && b.startContainer(ctx, tc.proxyID) == nil
if !proxyOK && tc.proxyID != "" {
b.removeContainer(ctx, tc.proxyID)
@@ -488,7 +502,7 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma
}
// Recreate proxy if missing or scope changed.
if tc == nil || tc.proxyID == "" || tc.scopeHash != sh {
if tc.proxyID == "" || tc.scopeHash != sh {
b.removeContainer(ctx, proxyName)
proxySpec := map[string]any{
"Image": b.cfg.ProxyImage,
@@ -529,9 +543,6 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma
b.removeContainer(ctx, pid)
return nil, err
}
if tc == nil {
tc = &taskContainers{taskID: taskID, netName: netName}
}
tc.proxyID = pid
tc.scopeHash = sh
}
@@ -591,9 +602,6 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma
tc.workerID = wid
}
b.mu.Lock()
b.tasks[taskID] = tc
b.mu.Unlock()
return tc, nil
}
@@ -605,6 +613,12 @@ func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest
if err != nil {
return ExecResponse{}, err
}
tc.cleanupMu.Lock()
workerID := tc.workerID
tc.cleanupMu.Unlock()
if workerID == "" {
return ExecResponse{}, fmt.Errorf("%w: task %s worker was removed", ErrNotFound, taskID)
}
// Wrap argv with artex-exec-wrap so every exec gets its own process group,
// enforces timeout_ms (SIGTERM group -> 5s -> SIGKILL -> exit 124) without
@@ -623,7 +637,7 @@ func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest
}
sort.Strings(envList)
createResp, err := b.dockerDo(ctx, http.MethodPost, "/containers/"+url.PathEscape(tc.workerID)+"/exec", map[string]any{
createResp, err := b.dockerDo(ctx, http.MethodPost, "/containers/"+url.PathEscape(workerID)+"/exec", map[string]any{
"AttachStdout": true,
"AttachStderr": true,
"Tty": false,
@@ -656,28 +670,44 @@ func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest
"Tty": false,
})
if err != nil {
if ctx.Err() != nil {
_ = b.Kill(context.Background(), taskID)
}
return ExecResponse{}, err
return ExecResponse{}, errors.Join(err, b.removeExecWorker(ctx, tc, workerID))
}
defer startResp.Body.Close()
stdout, stderr, truncated, _ := demuxDockerStream(startResp.Body, MaxOutputBytes)
inspectResp, err := b.dockerDo(context.Background(), http.MethodGet, "/exec/"+url.PathEscape(created.ID)+"/json", nil)
exitCode := -1
if err == nil {
defer inspectResp.Body.Close()
var ins struct {
ExitCode int `json:"ExitCode"`
}
if json.NewDecoder(inspectResp.Body).Decode(&ins) == nil {
exitCode = ins.ExitCode
}
if startResp.StatusCode >= 300 {
return ExecResponse{}, errors.Join(fmt.Errorf("start exec: HTTP %d", startResp.StatusCode), b.removeExecWorker(ctx, tc, workerID))
}
stdout, stderr, truncated, streamErr := demuxDockerStream(startResp.Body, MaxOutputBytes)
if err := errors.Join(streamErr, execCtx.Err()); err != nil {
return ExecResponse{}, errors.Join(err, b.removeExecWorker(ctx, tc, workerID))
}
ic, cancelInspect := cleanupContext(ctx)
defer cancelInspect()
inspectResp, err := b.dockerDo(ic, http.MethodGet, "/exec/"+url.PathEscape(created.ID)+"/json", nil)
if err != nil {
return ExecResponse{}, errors.Join(err, b.removeExecWorker(ctx, tc, workerID))
}
defer inspectResp.Body.Close()
var ins struct {
ExitCode *int `json:"ExitCode"`
Running *bool `json:"Running"`
}
decodeErr := json.NewDecoder(inspectResp.Body).Decode(&ins)
completed := ins.ExitCode != nil && ins.Running != nil && !*ins.Running
if decodeErr != nil || inspectResp.StatusCode != http.StatusOK || !completed {
return ExecResponse{}, errors.Join(fmt.Errorf("cannot prove exec completed (HTTP %d): %v", inspectResp.StatusCode, decodeErr), b.removeExecWorker(ctx, tc, workerID))
}
exitCode := *ins.ExitCode
timedOut := exitCode == 124
if timedOut || ctx.Err() != nil {
// Process-group timeout cannot kill setsid/double-fork descendants.
// Destroy the captured container, including its PID namespace and cgroup.
if err := b.removeExecWorker(ctx, tc, workerID); err != nil {
return ExecResponse{}, err
}
}
return ExecResponse{
ExitCode: exitCode,
Stdout: stdout,
@@ -688,6 +718,21 @@ func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest
}, nil
}
// removeExecWorker removes the exact container that ran this exec. A timeout
// also terminates sibling execs in that task, while preserving /workspace.
// Never remove a replacement worker, or forget a failed cleanup.
func (b *DockerBackend) removeExecWorker(ctx context.Context, tc *taskContainers, workerID string) error {
tc.cleanupMu.Lock()
defer tc.cleanupMu.Unlock()
cctx, cancel := cleanupContext(ctx)
defer cancel()
if err := b.removeContainer(cctx, workerID); err != nil {
return fmt.Errorf("exec cleanup for task %s: %w", tc.taskID, err)
}
b.clearWorkerID(tc, workerID)
return nil
}
// Kill terminates EVERY uid-10001 process inside the task's worker container
// (excluding PID 1) by running a root exec scanning /proc directly — never
// trusting any agent-writable state. If root exec fails or reports surviving
@@ -751,7 +796,6 @@ func (b *DockerBackend) clearWorkerID(tc *taskContainers, workerID string) {
cur.workerID = ""
}
b.mu.Unlock()
tc.workerID = ""
}
func (b *DockerBackend) killWorkerByProcScan(ctx context.Context, workerID string) error {
@@ -827,9 +871,13 @@ func (b *DockerBackend) Delete(ctx context.Context, taskID string) error {
cctx, cancel := cleanupContext(ctx)
defer cancel()
if err := b.killCaptured(cctx, tc); err != nil {
return fmt.Errorf("delete task %s: %w", taskID, err)
// Removing the worker also stops its processes and detaches the network
// endpoint. A process scan alone leaves PID 1 and the endpoint alive.
workerID := tc.workerID
if err := b.removeContainer(cctx, workerID); err != nil {
return fmt.Errorf("delete task %s worker: %w", taskID, err)
}
b.clearWorkerID(tc, workerID)
var errs []error
if err := b.removeContainer(cctx, tc.proxyID); err != nil {
@@ -861,7 +909,7 @@ func demuxDockerStream(r io.Reader, maxBytes int) (stdout, stderr string, trunca
hdr := make([]byte, 8)
for {
if _, err := io.ReadFull(r, hdr); err != nil {
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
if errors.Is(err, io.EOF) {
break
}
return outBuf.String(), errBuf.String(), truncated, err
@@ -884,7 +932,7 @@ func demuxDockerStream(r io.Reader, maxBytes int) (stdout, stderr string, trunca
take = rem
truncated = true
}
if _, err := io.CopyN(dst, r, take); err != nil && !errors.Is(err, io.EOF) {
if _, err := io.CopyN(dst, r, take); err != nil {
return outBuf.String(), errBuf.String(), truncated, err
}
frameLen -= take
@@ -892,7 +940,7 @@ func demuxDockerStream(r io.Reader, maxBytes int) (stdout, stderr string, trunca
truncated = true
}
if frameLen > 0 {
if _, err := io.CopyN(io.Discard, r, frameLen); err != nil && !errors.Is(err, io.EOF) {
if _, err := io.CopyN(io.Discard, r, frameLen); err != nil {
return outBuf.String(), errBuf.String(), truncated, err
}
}
+73 -15
View File
@@ -15,11 +15,20 @@ import (
// the request sequence so tests can assert cleanup ordering, and lets each test
// fail specific delete calls.
type fakeDocker struct {
mu sync.Mutex
calls []string
execStatus int // POST /containers/{id}/exec, 0 means 200
deleteCode map[string]int // container name -> status, 0 means 204
networkCode int // 0 means 204
mu sync.Mutex
calls []string
execStatus int // POST /containers/{id}/exec, 0 means 200
deleteCode map[string]int // container name -> status, 0 means 204
networkCode int // 0 means 204
requireWorkerRemoval bool // model Docker rejecting a network with a live worker endpoint
execExitCode int
execRunning bool
execStream []byte
execStartCode int
inspectCode int
inspectBody string
streamReady chan struct{}
streamStarted bool
}
func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
@@ -29,6 +38,8 @@ func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Unlock()
switch {
case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/start"):
w.WriteHeader(http.StatusNoContent)
case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/exec"):
if f.execStatus != 0 {
w.WriteHeader(f.execStatus)
@@ -36,9 +47,37 @@ func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
_ = json.NewEncoder(w).Encode(map[string]string{"Id": "exec-1"})
case r.Method == http.MethodPost && strings.HasPrefix(p, "/exec/") && strings.HasSuffix(p, "/start"):
if f.execStartCode != 0 {
w.WriteHeader(f.execStartCode)
return
}
w.WriteHeader(http.StatusOK)
f.mu.Lock()
firstStream := f.streamReady != nil && !f.streamStarted
if firstStream {
f.streamStarted = true
}
f.mu.Unlock()
if firstStream {
w.(http.Flusher).Flush()
close(f.streamReady)
<-r.Context().Done()
return
}
_, _ = w.Write(f.execStream)
case r.Method == http.MethodGet && strings.HasPrefix(p, "/exec/"):
_ = json.NewEncoder(w).Encode(map[string]int{"ExitCode": 0})
if f.inspectBody != "" {
if f.inspectCode != 0 {
w.WriteHeader(f.inspectCode)
}
_, _ = w.Write([]byte(f.inspectBody))
return
}
if f.inspectCode != 0 {
w.WriteHeader(f.inspectCode)
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"ExitCode": f.execExitCode, "Running": f.execRunning})
case r.Method == http.MethodDelete && strings.HasPrefix(p, "/containers/"):
name := strings.TrimPrefix(p, "/containers/")
if code := f.deleteCode[name]; code >= 300 {
@@ -47,6 +86,10 @@ func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
w.WriteHeader(http.StatusNoContent)
case r.Method == http.MethodDelete && strings.HasPrefix(p, "/networks/"):
if f.requireWorkerRemoval && !f.seen("DELETE /containers/worker-1") {
http.Error(w, "network has active endpoints", http.StatusForbidden)
return
}
if f.networkCode >= 300 {
w.WriteHeader(f.networkCode)
return
@@ -68,7 +111,7 @@ func (f *fakeDocker) seen(prefix string) bool {
return false
}
func newFakeDockerBackend(t *testing.T, f *fakeDocker) *DockerBackend {
func newFakeDockerBackend(t *testing.T, f http.Handler) *DockerBackend {
t.Helper()
sock := filepath.Join(t.TempDir(), "docker.sock")
ln, err := net.Listen("unix", sock)
@@ -181,26 +224,26 @@ func TestDeleteKeepsStateWhenProxyRemovalFails(t *testing.T) {
if !f.seen("DELETE /containers/proxy-1") {
t.Fatal("Delete never attempted the proxy removal")
}
// The kill sequence must run before the proxy delete.
// Removing the worker stops its processes before the proxy is removed.
f.mu.Lock()
killIdx, proxyIdx := -1, -1
workerIdx, proxyIdx := -1, -1
for i, c := range f.calls {
if strings.HasPrefix(c, "POST /containers/worker-1/exec") {
killIdx = i
if c == "DELETE /containers/worker-1" {
workerIdx = i
}
if c == "DELETE /containers/proxy-1" {
proxyIdx = i
}
}
f.mu.Unlock()
if killIdx == -1 || proxyIdx == -1 || killIdx > proxyIdx {
t.Fatalf("Delete did not kill the worker before removing the proxy: %v", f.calls)
if workerIdx == -1 || proxyIdx == -1 || workerIdx > proxyIdx {
t.Fatalf("Delete did not remove the worker before removing the proxy: %v", f.calls)
}
}
// TestDeleteUnpublishesOnlyAfterFullSuccess covers the happy path.
func TestDeleteUnpublishesOnlyAfterFullSuccess(t *testing.T) {
f := &fakeDocker{}
f := &fakeDocker{requireWorkerRemoval: true}
b := newFakeDockerBackend(t, f)
seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
@@ -210,11 +253,26 @@ func TestDeleteUnpublishesOnlyAfterFullSuccess(t *testing.T) {
if _, ok := b.tasks["t1"]; ok {
t.Fatal("Delete left the task in the map after full success")
}
if !f.seen("DELETE /containers/proxy-1") || !f.seen("DELETE /networks/artex-task-t1") {
if !f.seen("DELETE /containers/worker-1") || !f.seen("DELETE /containers/proxy-1") || !f.seen("DELETE /networks/artex-task-t1") {
t.Fatalf("Delete skipped resources: %v", f.calls)
}
}
func TestDeleteRetainsWorkerAfterRemovalFailure(t *testing.T) {
f := &fakeDocker{deleteCode: map[string]int{"worker-1": http.StatusInternalServerError}}
b := newFakeDockerBackend(t, f)
tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
if err := b.Delete(context.Background(), "t1"); err == nil {
t.Fatal("Delete succeeded although the worker could not be removed")
}
if b.tasks["t1"] != tc || tc.workerID != "worker-1" {
t.Fatal("Delete lost the worker needed for a cleanup retry")
}
if f.seen("DELETE /networks/") {
t.Fatal("network deletion attempted while worker is still attached")
}
}
// TestDeleteUsesFreshContextAfterCancellation: deletion from a cancelled HTTP
// request must still stop the containers.
func TestDeleteUsesFreshContextAfterCancellation(t *testing.T) {
+72
View File
@@ -0,0 +1,72 @@
package sandbox
import (
"context"
"fmt"
"net/http"
"os"
"path/filepath"
"testing"
"time"
)
// A real Engine is needed to prove the kernel kills a detached child, not just
// that the runner requests removal. The child writes a canary and performs no
// network activity. Build the worker/proxy images before opting in.
func TestDockerTimeoutRemovesDetachedChild(t *testing.T) {
if os.Getenv("ARTEX_SANDBOX_DOCKER_TEST") != "1" {
t.Skip("requires live Docker and built sandbox images")
}
ws, au := t.TempDir(), t.TempDir()
id := fmt.Sprintf("timeout-%d", time.Now().UnixNano())
egressNet := "artex-test-egress-" + id
for _, dir := range []string{ws, au, filepath.Join(ws, id), filepath.Join(au, id)} {
if err := os.MkdirAll(dir, 0o777); err != nil {
t.Fatal(err)
}
if err := os.Chmod(dir, 0o777); err != nil {
t.Fatal(err)
}
}
b := NewDockerBackend(DockerConfig{WorkspaceRoot: ws, HostWorkspaceRoot: ws, AuditRoot: au, HostAuditRoot: au,
TaskNetPrefix: "artex-test-task-", EgressNet: egressNet})
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
t.Cleanup(func() {
_ = b.Delete(context.Background(), id)
_ = b.removeNetwork(context.Background(), egressNet)
})
if err := b.Ping(ctx); err != nil {
t.Fatal(err)
}
tc, err := b.ensureTask(ctx, id, nil, nil)
if err != nil {
t.Fatal(err)
}
worker := tc.workerID
script := `import subprocess,sys,time
child="import time; f=open('/workspace/timeout-canary','ab',buffering=0); [(f.write(b'x'),time.sleep(.05)) for _ in range(200)]"
subprocess.Popen([sys.executable,'-c',child],start_new_session=True,stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
time.sleep(10)`
res, err := b.Exec(ctx, id, ExecRequest{Argv: []string{"python3", "-c", script}, Workdir: "/workspace", TimeoutMS: 1000})
if err != nil || !res.TimedOut {
t.Fatalf("response=%+v error=%v", res, err)
}
r, err := b.dockerDo(ctx, http.MethodGet, "/containers/"+worker+"/json", nil)
if err != nil {
t.Fatal(err)
}
defer r.Body.Close()
if r.StatusCode != http.StatusNotFound {
t.Fatalf("timed-out worker still exists: HTTP %d", r.StatusCode)
}
before, err := os.ReadFile(filepath.Join(ws, id, "timeout-canary"))
if err != nil || len(before) == 0 {
t.Fatalf("child never ran: %v", err)
}
time.Sleep(200 * time.Millisecond)
after, err := os.ReadFile(filepath.Join(ws, id, "timeout-canary"))
if err != nil || len(after) != len(before) {
t.Fatalf("child continued after timeout: %v", err)
}
}
+108
View File
@@ -0,0 +1,108 @@
package sandbox
import (
"context"
"net/http"
"testing"
"time"
)
func TestExecFailsClosedAndRemovesWorker(t *testing.T) {
for _, test := range []struct {
name string
fake *fakeDocker
wantErr bool
}{
{"timeout", &fakeDocker{execExitCode: 124}, false},
{"still_running", &fakeDocker{execRunning: true}, true},
{"truncated_stream", &fakeDocker{execStream: []byte{1, 0, 0}}, true},
{"truncated_payload", &fakeDocker{execStream: []byte{1, 0, 0, 0, 0, 0, 0, 4, 'x'}}, true},
{"inspect_failure", &fakeDocker{inspectCode: http.StatusInternalServerError}, true},
{"missing_exit_code", &fakeDocker{inspectBody: `{"Running":false}`}, true},
{"missing_running_status", &fakeDocker{inspectBody: `{"ExitCode":0}`}, true},
{"malformed_inspect", &fakeDocker{inspectBody: `{`}, true},
{"start_failure", &fakeDocker{execStartCode: http.StatusInternalServerError}, true},
} {
t.Run(test.name, func(t *testing.T) {
b := newFakeDockerBackend(t, test.fake)
tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
tc.scopeHash = scopeFingerprint(nil, nil)
res, err := b.Exec(context.Background(), "t1", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000})
if (err != nil) != test.wantErr {
t.Fatalf("response=%+v error=%v", res, err)
}
if !test.wantErr && !res.TimedOut {
t.Fatalf("timeout lost: %+v", res)
}
if tc.workerID != "" || !test.fake.seen("DELETE /containers/worker-1") {
t.Fatal("worker survived failed/timed-out execution")
}
})
}
}
func TestExecCancellationCleansUpWithFreshContext(t *testing.T) {
f := &fakeDocker{streamReady: make(chan struct{})}
b := newFakeDockerBackend(t, f)
tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
tc.scopeHash = scopeFingerprint(nil, nil)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan error, 1)
go func() { _, err := b.Exec(ctx, "t1", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); done <- err }()
select {
case <-f.streamReady:
case <-time.After(3 * time.Second):
t.Fatal("exec did not start")
}
cancel()
select {
case err := <-done:
if err == nil {
t.Fatal("cancelled exec reported success")
}
case <-time.After(3 * time.Second):
t.Fatal("cleanup hung")
}
if tc.workerID != "" || !f.seen("DELETE /containers/worker-1") {
t.Fatal("cancelled exec left worker alive")
}
}
func TestExecTimeoutRemovalFailureKeepsWorker(t *testing.T) {
f := &fakeDocker{execExitCode: 124, deleteCode: map[string]int{"worker-1": 500}}
b := newFakeDockerBackend(t, f)
tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
tc.scopeHash = scopeFingerprint(nil, nil)
if _, err := b.Exec(context.Background(), "t1", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); err == nil {
t.Fatal("cleanup failure hidden")
}
if tc.workerID != "worker-1" {
t.Fatal("worker lost before cleanup was proven")
}
}
func TestSuccessfulExecPreservesWorker(t *testing.T) {
f := &fakeDocker{}
b := newFakeDockerBackend(t, f)
tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
tc.scopeHash = scopeFingerprint(nil, nil)
if _, err := b.Exec(context.Background(), "t1", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); err != nil {
t.Fatal(err)
}
if tc.workerID != "worker-1" || f.seen("DELETE /containers/worker-1") {
t.Fatal("successful exec lost its worker")
}
}
func TestDelayedExecCleanupPreservesReplacementWorker(t *testing.T) {
f := &fakeDocker{}
b := newFakeDockerBackend(t, f)
tc := seedTask(b, "t1", "replacement-worker", "proxy-1", "artex-task-t1")
if err := b.removeExecWorker(context.Background(), tc, "old-worker"); err != nil {
t.Fatal(err)
}
if tc.workerID != "replacement-worker" || f.seen("DELETE /containers/replacement-worker") || !f.seen("DELETE /containers/old-worker") {
t.Fatal("late cleanup targeted or forgot replacement worker")
}
}
+204
View File
@@ -0,0 +1,204 @@
package sandbox
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"sync"
"testing"
"time"
)
// A timed-out command removes its task's worker, ending sibling exec streams.
// An exec in another task must remain live until it finishes independently.
func TestExecTimeoutStopsSiblingsButPreservesOtherTask(t *testing.T) {
siblingStarted := make(chan struct{})
otherStarted := make(chan struct{})
workerRemoved := make(chan struct{})
finishOther := make(chan struct{})
var removedOnce sync.Once
var mu sync.Mutex
var removed []string
f := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p := r.URL.Path
switch {
case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/start"):
w.WriteHeader(http.StatusNoContent)
case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/exec"):
var spec struct{ Cmd []string }
if err := json.NewDecoder(r.Body).Decode(&spec); err != nil || len(spec.Cmd) == 0 {
http.Error(w, "missing command", http.StatusBadRequest)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"Id": spec.Cmd[len(spec.Cmd)-1]})
case p == "/exec/sibling/start" || p == "/exec/other/start":
w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush()
if p == "/exec/sibling/start" {
close(siblingStarted)
select {
case <-workerRemoved:
case <-r.Context().Done():
}
} else {
close(otherStarted)
select {
case <-finishOther:
case <-r.Context().Done():
}
}
case p == "/exec/timeout/start":
w.WriteHeader(http.StatusOK)
case p == "/exec/sibling/json":
http.Error(w, "worker removed", http.StatusNotFound)
case p == "/exec/timeout/json":
_ = json.NewEncoder(w).Encode(map[string]any{"ExitCode": 124, "Running": false})
case p == "/exec/other/json":
_ = json.NewEncoder(w).Encode(map[string]any{"ExitCode": 0, "Running": false})
case r.Method == http.MethodDelete && strings.HasPrefix(p, "/containers/"):
mu.Lock()
removed = append(removed, p)
mu.Unlock()
if p == "/containers/worker-a" {
removedOnce.Do(func() { close(workerRemoved) })
}
w.WriteHeader(http.StatusNoContent)
default:
http.NotFound(w, r)
}
})
b := newFakeDockerBackend(t, f)
a := seedTask(b, "a", "worker-a", "proxy-a", "net-a")
other := seedTask(b, "b", "worker-b", "proxy-b", "net-b")
a.scopeHash = scopeFingerprint(nil, nil)
other.scopeHash = a.scopeHash
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
siblingDone := make(chan error, 1)
otherDone := make(chan error, 1)
run := func(task, command string, done chan<- error) {
res, err := b.Exec(ctx, task, ExecRequest{Argv: []string{command}, TimeoutMS: 1000})
if err == nil && res.ExitCode != 0 {
err = errors.New("unexpected nonzero exit")
}
done <- err
}
go run("a", "sibling", siblingDone)
waitSignal(t, ctx, siblingStarted)
go run("b", "other", otherDone)
waitSignal(t, ctx, otherStarted)
res, err := b.Exec(ctx, "a", ExecRequest{Argv: []string{"timeout"}, TimeoutMS: 1000})
if err != nil || !res.TimedOut {
t.Fatalf("timeout response=%+v err=%v", res, err)
}
select {
case err := <-siblingDone:
if err == nil {
t.Fatal("sibling reported success after its worker was removed")
}
case <-ctx.Done():
t.Fatal("sibling did not finish after worker removal")
}
select {
case err := <-otherDone:
t.Fatalf("another task's exec stopped early: %v", err)
default:
}
mu.Lock()
deletions := append([]string(nil), removed...)
mu.Unlock()
for _, path := range deletions {
if path != "/containers/worker-a" {
t.Fatalf("removed an unrelated resource: %s", path)
}
}
if a.workerID != "" || other.workerID != "worker-b" {
t.Fatalf("worker state: task a=%q, task b=%q", a.workerID, other.workerID)
}
close(finishOther)
select {
case err := <-otherDone:
if err != nil {
t.Fatal(err)
}
case <-ctx.Done():
t.Fatal("other task did not finish")
}
}
func waitSignal(t *testing.T, ctx context.Context, signal <-chan struct{}) {
t.Helper()
select {
case <-signal:
case <-ctx.Done():
t.Fatal("timed out waiting for simulated Docker request")
}
}
// Delete must retain the lifecycle lock until resources and the map entry are
// removed. An exec waiting behind it must not recreate the deleted task.
func TestEnsureTaskDoesNotRecreateDuringDelete(t *testing.T) {
deleting := make(chan struct{})
releaseDelete := make(chan struct{})
creationAttempt := make(chan struct{}, 1)
f := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodDelete {
if r.URL.Path == "/containers/worker-1" {
close(deleting)
select {
case <-releaseDelete:
case <-r.Context().Done():
}
}
w.WriteHeader(http.StatusNoContent)
return
}
select {
case creationAttempt <- struct{}{}:
default:
}
http.NotFound(w, r)
})
b := newFakeDockerBackend(t, f)
tc := seedTask(b, "t1", "worker-1", "proxy-1", "net-1")
tc.scopeHash = scopeFingerprint(nil, nil)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var releaseOnce sync.Once
release := func() { releaseOnce.Do(func() { close(releaseDelete) }) }
defer release()
deleteDone := make(chan error, 1)
go func() { deleteDone <- b.Delete(ctx, "t1") }()
waitSignal(t, ctx, deleting)
ensureDone := make(chan error, 1)
go func() { _, err := b.ensureTask(ctx, "t1", nil, nil); ensureDone <- err }()
select {
case <-creationAttempt:
t.Fatal("ensureTask contacted Docker while Delete held the worker")
case err := <-ensureDone:
t.Fatalf("ensureTask returned before Delete completed: %v", err)
case <-time.After(50 * time.Millisecond):
}
release()
select {
case err := <-deleteDone:
if err != nil {
t.Fatal(err)
}
case <-ctx.Done():
t.Fatal("Delete did not finish")
}
select {
case err := <-ensureDone:
if !errors.Is(err, ErrNotFound) {
t.Fatalf("ensureTask after deletion: %v", err)
}
case <-ctx.Done():
t.Fatal("ensureTask did not finish")
}
if b.WorkerCount() != 0 {
t.Fatal("deleted task was re-registered")
}
}
+6
View File
@@ -147,6 +147,12 @@ func validateAssetInterceptRuleReq(req *assetInterceptRuleReq) error {
return fmt.Errorf("%s is not a valid domain: %s", req.Kind, req.Pattern)
}
req.Pattern = d
case "domain_suffix":
d := db.DomainSuffixPattern(req.Pattern)
if d == "" || strings.ContainsAny(d, "*/:") || strings.HasPrefix(d, ".") {
return fmt.Errorf("domain_suffix is not a valid domain (e.g. example.com): %s", req.Pattern)
}
req.Pattern = d
case "exact_ip":
ip, ok := db.CanonicalInterceptIP(req.Pattern)
if !ok {
+9
View File
@@ -22,6 +22,15 @@ func TestValidateAssetInterceptRuleCanonicalizes(t *testing.T) {
{"unicode domain is punycoded", "exact_domain", "bücher.example", "xn--bcher-kva.example", false},
{"bare dot domain is refused", "exact_domain", ".", "", true},
{"fuzzy domain is canonicalized", "fuzzy_domain", " .GOV.CN. ", ".gov.cn", false},
{"domain suffix is canonicalized", "domain_suffix", " Example.COM. ", "example.com", false},
{"domain suffix drops a wildcard label", "domain_suffix", "*.example.com", "example.com", false},
{"domain suffix drops a leading dot", "domain_suffix", ".example.com", "example.com", false},
{"unicode domain suffix is punycoded", "domain_suffix", "*.bücher.example", "xn--bcher-kva.example", false},
{"domain suffix wildcard inside a label is refused", "domain_suffix", "*example.com", "", true},
{"domain suffix deeper wildcard is refused", "domain_suffix", "api.*.example.com", "", true},
{"domain suffix double dot is refused", "domain_suffix", "..example.com", "", true},
{"domain suffix URL is refused", "domain_suffix", "https://example.com", "", true},
{"bare wildcard domain suffix is refused", "domain_suffix", "*.", "", true},
{"fuzzy IP is lower-cased", "fuzzy_ip", "FE80::", "fe80::", false},
{"CIDR is masked", "cidr", "192.168.1.5/16", "192.168.0.0/16", false},
{"invalid CIDR is refused", "cidr", "not-a-cidr", "", true},
+51 -1
View File
@@ -698,6 +698,18 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if strings.TrimSpace(rawURL) == "" {
return actool.Errorf("http url is empty"), nil
}
// ARTEX_SANDBOX=required: the request leaves from the panel process, not from
// the task's worker container and its egress proxy. The task's egress policy,
// the one WebFetch enforces, applies here to the URL, to every redirect hop
// and to every connection (see sandboxHTTPTransport); a refusal is final,
// there is no direct fallback.
var sbPolicy *sandbox.EgressPolicy
if agent.SandboxRequired() {
sbPolicy = agent.SandboxEgressPolicy(ctx)
if err := sbPolicy.CheckURL(ctx, rawURL); err != nil {
return actool.Errorf("sandbox http tool blocked: " + err.Error()), nil
}
}
// The hook saw the parameters, not the URL they render (nor a URL written in
// the template): the target gate reads the rendered URL here, before the
// tool's own timeout starts, so a wait for an approval does not consume it.
@@ -726,11 +738,18 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if intercept.ApplyAssessmentUserAgent(req) {
client.CheckRedirect = assessmentRedirectCheck(client.CheckRedirect)
}
if sbPolicy != nil {
client.CheckRedirect = sandboxRedirectCheck(sbPolicy, client.CheckRedirect)
}
// The current egress governor paces every request and redirect hop per host
// under the noise profile (off by default: the base transport itself). It is
// resolved per request, so a changed profile applies to the next call.
var base http.RoundTripper = http.DefaultTransport
if tr := s.httpToolTransport(ctx, key, spec); tr != nil {
tr := s.httpToolTransport(ctx, key, spec)
if sbPolicy != nil {
tr = sandboxHTTPTransport(tr, sbPolicy)
}
if tr != nil {
base = tr
}
client.Transport = egress.Current().Transport(key, base)
@@ -759,6 +778,37 @@ 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.
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
+266
View File
@@ -0,0 +1,266 @@
package server
import (
"context"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/sandbox"
actool "github.com/Autumn-27/norma/tool"
)
// sandboxRequired puts the process in ARTEX_SANDBOX=required mode for one test.
func sandboxRequired(t *testing.T) {
t.Helper()
prev := agent.CurrentSandboxExecutor()
agent.SetSandboxExecutor(&agent.SandboxExecutor{Mode: sandbox.ModeRequired})
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
}
// canaryServer counts every request it receives. ip is the loopback address it
// listens on (127.0.0.1 or 127.0.0.2, both on lo).
func canaryServer(t *testing.T, ip string, h http.HandlerFunc) (*httptest.Server, *atomic.Int32) {
t.Helper()
hits := new(atomic.Int32)
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
if h != nil {
h(w, r)
return
}
_, _ = w.Write([]byte("CANARY_BODY"))
}))
ln, err := net.Listen("tcp", ip+":0")
if err != nil {
t.Fatalf("listen %s: %v", ip, err)
}
srv.Listener = ln
srv.Start()
t.Cleanup(srv.Close)
return srv, hits
}
func sandboxCtx(domains, cidrs []string) context.Context {
return agent.WithSandboxRunInfo(context.Background(), agent.SandboxRunInfo{
TaskID: "custom-http-egress", ScopeDomains: domains, ScopeCIDRs: cidrs,
})
}
func runHTTPSpec(t *testing.T, ctx context.Context, spec map[string]any) actool.Result {
t.Helper()
raw, _ := json.Marshal(spec)
res, err := (&Server{}).runHTTPTool(ctx, "probe", raw, map[string]any{}, nil)
if err != nil {
t.Fatalf("runHTTPTool: %v", err)
}
return res
}
// A URL outside the task scope is refused before any request leaves.
func TestSandboxHTTPToolRefusesOutOfScopeURL(t *testing.T) {
sandboxRequired(t)
srv, hits := canaryServer(t, "127.0.0.1", nil)
ctx := sandboxCtx([]string{"allowed.example"}, nil)
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": srv.URL + "/secret"})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("out-of-scope URL not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := hits.Load(); n != 0 {
t.Fatalf("out-of-scope server received %d request(s)", n)
}
}
// A name in scope that resolves only to loopback is not dialed: the policy
// treats it as WebFetch does (loopback is denied unless listed in the CIDRs).
func TestSandboxHTTPToolRefusesScopedNameResolvingToLoopback(t *testing.T) {
sandboxRequired(t)
srv, hits := canaryServer(t, "127.0.0.1", nil)
_, port, _ := net.SplitHostPort(srv.Listener.Addr().String())
ctx := sandboxCtx([]string{"localhost"}, nil)
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": "http://localhost:" + port + "/"})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("scoped name resolving to loopback not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := hits.Load(); n != 0 {
t.Fatalf("loopback server received %d request(s)", n)
}
}
// A redirect from an in-scope URL to a host outside the scope fails; the
// outside host never receives the request.
func TestSandboxHTTPToolRefusesRedirectOutOfScope(t *testing.T) {
sandboxRequired(t)
outside, outsideHits := canaryServer(t, "127.0.0.2", nil)
inScope, inHits := canaryServer(t, "127.0.0.1", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, outside.URL+"/stolen", http.StatusFound)
})
ctx := sandboxCtx(nil, []string{"127.0.0.1/32"})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": inScope.URL + "/start"})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("out-of-scope redirect not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := inHits.Load(); n != 1 {
t.Fatalf("in-scope server hits = %d, want 1", n)
}
if n := outsideHits.Load(); n != 0 {
t.Fatalf("out-of-scope redirect target received %d request(s)", n)
}
}
// A proxy configured on the tool is a connection the panel opens too: a proxy
// outside the scope is not dialed, even for an in-scope target.
func TestSandboxHTTPToolRefusesOutOfScopeProxy(t *testing.T) {
sandboxRequired(t)
target, targetHits := canaryServer(t, "127.0.0.1", nil)
proxy, proxyHits := canaryServer(t, "127.0.0.2", nil)
ctx := sandboxCtx(nil, []string{"127.0.0.1/32"})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": target.URL + "/", "proxy": proxy.URL})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("out-of-scope proxy not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := proxyHits.Load(); n != 0 {
t.Fatalf("out-of-scope proxy received %d request(s)", n)
}
if n := targetHits.Load(); n != 0 {
t.Fatalf("target received %d request(s) around the proxy", n)
}
}
// An in-scope URL still works under the sandbox (loopback listed in the scope
// CIDRs, the seam the WebFetch sandbox test uses).
func TestSandboxHTTPToolAllowsInScopeURL(t *testing.T) {
sandboxRequired(t)
srv, hits := canaryServer(t, "127.0.0.1", nil)
ctx := sandboxCtx(nil, []string{"127.0.0.1/32"})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": srv.URL + "/ok"})
if res.IsError || !strings.Contains(res.Flatten(), "CANARY_BODY") {
t.Fatalf("in-scope URL refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := hits.Load(); n != 1 {
t.Fatalf("in-scope server hits = %d, want 1", n)
}
}
// Sandbox off: the tool behaves as before, a loopback URL with no task scope
// and a redirect to another loopback host both go through.
func TestHTTPToolSandboxOffUnchanged(t *testing.T) {
prev := agent.CurrentSandboxExecutor()
agent.SetSandboxExecutor(nil)
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
other, otherHits := canaryServer(t, "127.0.0.2", nil)
srv, hits := canaryServer(t, "127.0.0.1", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, other.URL+"/next", http.StatusFound)
})
res := runHTTPSpec(t, context.Background(), map[string]any{"method": "GET", "url": srv.URL + "/"})
if res.IsError || !strings.Contains(res.Flatten(), "CANARY_BODY") {
t.Fatalf("sandbox-off call changed: isError=%v text=%q", res.IsError, res.Flatten())
}
if hits.Load() != 1 || otherHits.Load() != 1 {
t.Fatalf("hits = %d/%d, want 1/1", hits.Load(), otherHits.Load())
}
}
// customHTTPToolRow creates a Kind:"http" custom tool bound to the worker only,
// removed when the test ends.
func customHTTPToolRow(t *testing.T, pg *db.DB, key, rawURL string) *db.Tool {
t.Helper()
execRaw, _ := json.Marshal(map[string]any{"method": "GET", "url": rawURL})
row := &db.Tool{
Key: key, Description: "custom http egress probe", Kind: "http", Enabled: true,
Agents: []string{"worker"}, Exec: execRaw,
Schema: json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"}}}`),
}
_ = pg.DeleteCustomTool(key)
if err := pg.CreateCustomTool(row); err != nil {
t.Fatalf("create custom tool: %v", err)
}
t.Cleanup(func() {
_ = pg.DeleteCustomTool(key)
_, _ = pg.Exec(`DELETE FROM tool_usage WHERE tool_key=$1`, key)
})
return row
}
func openToolsPG(t *testing.T) *db.DB {
t.Helper()
dsn, _, err := db.DSN()
if err != nil {
db.SkipPGUnavailable(t, err)
}
pg, err := db.Open(dsn)
if err != nil {
db.SkipPGUnavailable(t, err)
}
t.Cleanup(func() { pg.Close() })
if err := pg.InitSecrets(t.TempDir()); err != nil {
t.Fatalf("init secrets: %v", err)
}
return pg
}
// The planner never receives a Kind:"http" custom tool bound to the worker,
// sandbox on or off; the worker does.
func TestCustomHTTPToolNotResolvedForPlanner(t *testing.T) {
pg := openToolsPG(t)
t.Setenv("AGENT_CORE_DISABLE_INTERACTIVE_SHELL", "1")
wireTools(pg, nil)
t.Cleanup(func() { agent.SetToolResolve(nil) })
s := &Server{m: &Manager{pg: pg}}
row := customHTTPToolRow(t, pg, "sec_http_egress_planner_probe", "http://127.0.0.1:1/")
base := []actool.CoreTool{s.buildCustomTool(row)}
for _, required := range []bool{false, true} {
if required {
sandboxRequired(t)
}
ctx := context.Background()
if _, ok := names(agent.ToolResolve()(ctx, "planner", base))[row.Key]; ok {
t.Fatalf("sandbox required=%v: planner received the Kind:http tool", required)
}
if _, ok := names(agent.ToolResolve()(ctx, "worker", base))[row.Key]; !ok {
t.Fatalf("sandbox required=%v: worker lost the Kind:http tool", required)
}
}
}
// End to end, as the worker gets it: the tool the worker resolves refuses a URL
// outside the task scope under the sandbox, and the target is never reached.
func TestCustomHTTPToolWorkerSandboxRefusesOutOfScope(t *testing.T) {
pg := openToolsPG(t)
t.Setenv("AGENT_CORE_DISABLE_INTERACTIVE_SHELL", "1")
wireTools(pg, nil)
t.Cleanup(func() { agent.SetToolResolve(nil) })
sandboxRequired(t)
srv, hits := canaryServer(t, "127.0.0.1", nil)
s := &Server{m: &Manager{pg: pg}}
row := customHTTPToolRow(t, pg, "sec_http_egress_worker_probe", srv.URL+"/secret?q={q}")
ctx := sandboxCtx([]string{"allowed.example"}, nil)
tool, ok := names(agent.ToolResolve()(ctx, "worker", []actool.CoreTool{s.buildCustomTool(row)}))[row.Key]
if !ok {
t.Fatal("worker did not receive the Kind:http tool")
}
res, err := tool.Call(ctx, json.RawMessage(`{"q":"x"}`), &actool.ToolContext{})
if err != nil {
t.Fatalf("call: %v", err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("worker Kind:http call outside the scope not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := hits.Load(); n != 0 {
t.Fatalf("out-of-scope server received %d request(s)", n)
}
}
+3 -1
View File
@@ -205,7 +205,9 @@ func TestMainSideConcurrencyAndIndependentCancellation(t *testing.T) {
p := fakeProvider{stream: func(ctx context.Context, _ llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(y func(llm.StreamEvent, error) bool) {
started <- struct{}{}
y(llm.StreamEvent{Type: llm.SEMessageStart, Usage: llm.Usage{InputTokens: 7}}, nil)
if !y(llm.StreamEvent{Type: llm.SEMessageStart, Usage: llm.Usage{InputTokens: 7}}, nil) {
return
}
<-ctx.Done()
y(llm.StreamEvent{}, ctx.Err())
}
+1 -1
View File
@@ -11,7 +11,7 @@
"format": "biome format --write",
"check": "biome check",
"check:fix": "biome check --write",
"prepare": "husky",
"prepare": "cd .. && husky web/.husky",
"generate:presets": "ts-node -P tsconfig.scripts.json src/scripts/generate-theme-presets.ts",
"test:polling": "node --test scripts/polling.test.mjs",
"test:replay": "node --test scripts/replay.test.mjs",
@@ -1101,6 +1101,7 @@ const TASK_RULE_KIND_OPTIONS: { value: AssetInterceptKind; label: string; placeh
{ value: "exact_domain", label: t("Domain (exact)"), placeholder: "example.gov.cn" },
{ value: "exact_ip", label: t("IP (exact)"), placeholder: "203.0.113.10" },
{ value: "exact_url", label: t("URL (exact)"), placeholder: "https://example.com/login" },
{ value: "domain_suffix", label: t("Domain (suffix)"), placeholder: "example.com" },
{ value: "fuzzy_domain", label: t("Domain (fuzzy)"), placeholder: ".gov.cn" },
{ value: "fuzzy_ip", label: t("IP (fuzzy)"), placeholder: "203.0.113." },
{ value: "fuzzy_url", label: t("URL (fuzzy)"), placeholder: "/admin" },
@@ -26,6 +26,7 @@ const KIND_OPTIONS: { value: AssetInterceptKind; label: string; group: string; p
{ value: "exact_domain", label: t("Domain (exact)"), group: "Exact match", placeholder: "example.gov.cn" },
{ value: "exact_ip", label: t("IP (exact)"), group: "Exact match", placeholder: "203.0.113.10" },
{ value: "exact_url", label: t("URL (exact)"), group: "Exact match", placeholder: "https://example.gov.cn/login" },
{ value: "domain_suffix", label: t("Domain (suffix)"), group: "Exact match", placeholder: "example.gov.cn" },
{ value: "fuzzy_domain", label: t("Domain (fuzzy)"), group: "Fuzzy match", placeholder: ".gov.cn" },
{ value: "fuzzy_ip", label: t("IP (fuzzy)"), group: "Fuzzy match", placeholder: "203.0.113." },
{ value: "fuzzy_url", label: t("URL (fuzzy)"), group: "Fuzzy match", placeholder: "/admin" },
@@ -18,6 +18,7 @@ export const ASSET_INTERCEPT_KIND_OPTIONS: {
{ value: "exact_domain", label: t("Domain (exact)"), placeholder: "example.gov.cn" },
{ value: "exact_ip", label: t("IP (exact)"), placeholder: "203.0.113.10" },
{ value: "exact_url", label: t("URL (exact)"), placeholder: "https://example.com/login" },
{ value: "domain_suffix", label: t("Domain (suffix)"), placeholder: "example.com" },
{ value: "fuzzy_domain", label: t("Domain (fuzzy)"), placeholder: ".gov.cn" },
{ value: "fuzzy_ip", label: t("IP (fuzzy)"), placeholder: "203.0.113." },
{ value: "fuzzy_url", label: t("URL (fuzzy)"), placeholder: "/admin" },
+1
View File
@@ -789,6 +789,7 @@
"domain (e.g. target.example.com)": "domínio (por exemplo, target.example.com)",
"Domain (exact)": "Domínio (exato)",
"Domain (fuzzy)": "Domínio (aproximado)",
"Domain (suffix)": "Domínio (sufixo)",
"Domain (root domain/subdomain/service domain)": "Domínio (domínio raiz/subdomínio/domínio de serviço)",
"Domain or IP": "Domínio ou IP",
"Done": "Concluído",
+1
View File
@@ -789,6 +789,7 @@
"domain (e.g. target.example.com)": "alan adı (ör. target.example.com)",
"Domain (exact)": "Alan adı (tam)",
"Domain (fuzzy)": "Alan adı (bulanık)",
"Domain (suffix)": "Alan adı (sonek)",
"Domain (root domain/subdomain/service domain)": "Alan adı (kök alan adı/alt alan adı/servis alan adı)",
"Domain or IP": "Alan adı veya IP",
"Done": "Bitti",
+1
View File
@@ -789,6 +789,7 @@
"domain (e.g. target.example.com)": "tên miền (ví dụ target.example.com)",
"Domain (exact)": "Tên miền (chính xác)",
"Domain (fuzzy)": "Tên miền (mờ)",
"Domain (suffix)": "Tên miền (hậu tố)",
"Domain (root domain/subdomain/service domain)": "Tên miền (tên miền gốc/tên miền con/tên miền dịch vụ)",
"Domain or IP": "Tên miền hoặc IP",
"Done": "Xong",
+1
View File
@@ -789,6 +789,7 @@
"domain (e.g. target.example.com)": "域名(例如 target.example.com)",
"Domain (exact)": "域名(全等)",
"Domain (fuzzy)": "域名(模糊)",
"Domain (suffix)": "域名(后缀)",
"Domain (root domain/subdomain/service domain)": "域名(根域名/子域名/服务域名)",
"Domain or IP": "域名或 IP",
"Done": "完成",
+1
View File
@@ -1437,6 +1437,7 @@ export type AssetInterceptKind =
| "exact_domain"
| "exact_ip"
| "exact_url"
| "domain_suffix"
| "fuzzy_domain"
| "fuzzy_ip"
| "fuzzy_url"