Compare commits

...
Author SHA1 Message Date
BaaRai 09e1d8384a docs: correct the sandbox dialer comment about proxy redirects
The dialer sees each hop on a direct connection only. Through a proxy it sees
the proxy, and sandboxRedirectCheck checks the hop. The old comment claimed all
hops and redirects, which contradicted the redirect check added in this branch.
2026-12-02 16:39:41 +01:00
BaaRai 44644b075e agent: check WebFetch redirect hops against the sandbox egress policy
In ARTEX_SANDBOX=required mode the WebFetch tool checked only the first
URL of a call against the task's egress policy. Every later connection
goes through the sandbox dialer, but with an operator or recording proxy
configured that dialer only ever sees the proxy address, so a redirect
from an allowed URL to 169.254.169.254, a loopback or private address,
or a domain outside the task scope was requested from the proxy and
followed.

The WebFetch CheckRedirect is now wrapped in required mode: each hop is
checked with EgressPolicy.CheckURL first, and only a hop the policy
allows goes on to intercept.RedirectCheck, which keeps its target gate
and its redirect limit. A nil policy refuses every hop. Outside required
mode the redirect check is unchanged.
2026-12-02 14:31:07 +01:00
BaaRai e38f58d46e Merge pull request #829 from thecorporatetractor/fix/jwt-hardening
fix(auth): pin session tokens to HS256 and add iss and aud
2026-12-02 12:27:28 +01:00
BaaRai e14570a7ff Merge pull request #789 from IamLugus/fix/sandbox-exact-ip-egress
fix(sandbox): grant egress for exact_ip task allow rules
2026-12-02 12:27:18 +01:00
BaaRai f94294867f Merge pull request #794 from BaaRai/sec/dns-egress-fail-closed
security: fail closed on DNS errors and dual-A answers in sandbox egress
2026-12-02 12:27:04 +01:00
Marco Azarmaneche f856460889 fix(auth): pin session tokens to HS256 and add iss and aud
verifyJWT and jwtSubject accepted any HMAC algorithm, so a token signed
with HS384 or HS512 and the session key was valid. Both now parse through
parseSessionJWT, which accepts only HS256.

New tokens carry iss "artex" and aud "artex-api". When a token has either
claim, it must match. Tokens issued by earlier releases have neither claim
and are still accepted, so nobody is signed out by the upgrade.
2026-12-02 00:07:44 +02:00
BaaRai de16c16bdc security: fail closed on DNS errors and dual-A answers in sandbox egress
EgressPolicy.CheckURL, the check WebFetch, the shared browser and the
custom http tool run on a URL under ARTEX_SANDBOX=required, was fail-open
in two ways:
- a lookup error (or an empty answer) for a name in scope returned nil,
  so the URL was allowed;
- a name answering several addresses was allowed as soon as one of them
  was public, the others being private, loopback, IPv6 or the cloud
  metadata address (169.254.169.254).

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

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

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

Two existing tests expected an in-scope name that does not resolve to be
allowed, which only the fail-open lookup gave them: the scope drift test
(its resolver reached the proxy policy only, not the policy WebFetch and
the browser build) and the shared browser navigation test. Both now pass
an offline resolver through the context (sandbox.WithResolver); their
assertions are unchanged.
2026-12-01 22:40:10 +01:00
BaaRai 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 edd1a3c2b6 sandbox: let tests answer egress policy lookups through the context
The panel tools (WebFetch, the shared browser, the custom http tool) build
their EgressPolicy themselves, so a test could not hand them a resolver.
WithResolver carries one on the context; a policy without its own Resolver
uses it. Nothing in production sets it, and behaviour is unchanged.
2026-12-01 22:24:21 +01:00
BaaRai e736474085 Merge pull request #785 from BaaRai/sec/custom-http-egress-gate
security: enforce the task egress policy on custom HTTP tools
2026-12-01 22:17:27 +01:00
BaaRai 7455d7f706 Merge pull request #788 from leninworld/fix/responses-default-model
fix(llm): default openai-responses to gpt-6.2-sol before gpt-5 shuts down
2026-12-01 22:09:23 +01:00
BaaRai 0ced7302f3 Merge pull request #784 from thecorporatetractor/fix/sidequestion-test-yield
test(sidequestion): stop the fake stream when the consumer stops
2026-12-01 22:09:09 +01:00
BaaRai de63398481 Merge pull request #776 from amshivang/fix/husky-prepare-script
fix(web): run husky prepare from repo root so the pre-commit hook installs
2026-12-01 22:08:38 +01:00
BaaRai 9013eeeb6a Merge pull request #786 from BaaRai/chore/remove-php2shell
chore(skills): remove the experimental php2shell research skill
2026-12-01 22:08:33 +01:00
LugussandClaude Opus 5.5 3489f7443c fix(sandbox): grant egress for exact_ip task allow rules
taskSandboxRunInfo promoted task allow rules of kind "ip" to the egress
CIDRs, but the rule tables only store "exact_ip" (the CHECK constraint
and the save validator refuse "ip"), so an exact_ip allow rule granted
no egress. A task scoped to one private address could not reach it from
the sandbox, directly or through a name resolving only to it.

NewEgressPolicy already reads a bare address as a host prefix, so the
pattern is passed as is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:42:46 +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
46 changed files with 1837 additions and 109 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
+8
View File
@@ -7,10 +7,18 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **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.
- **Session tokens accept only HS256 and carry an issuer and audience.** Token checks accepted any HMAC algorithm (HS384, HS512) signed with the session key; they now accept only HS256. New tokens have `iss: artex` and `aud: artex-api`, and a token that has either claim with another value is rejected. Tokens issued by earlier releases have neither claim and stay valid until they expire, so upgrading does not sign anyone out.
- **`WebFetch` redirects through a proxy are checked against the sandbox egress policy.** In `ARTEX_SANDBOX=required` mode only the first URL of a `WebFetch` call was checked against the task's egress policy. With an operator or recording proxy configured, the sandbox dialer only connects to the proxy, so a redirect from an allowed URL to a cloud metadata address (169.254.169.254), a loopback or private address, or a domain outside the task scope was followed. Every redirect hop is now checked against the same egress policy before it is followed, and a hop the policy does not allow fails the call.
### 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
- **An `exact_ip` task allow rule grants sandbox egress**: the egress allowlist read task allow rules of kind `ip`, which the rule tables never store, so an `exact_ip` allow rule granted nothing. A task scoped to one private address (`10.0.0.5`) could not reach it from the sandbox, directly or through a name resolving only to it. `exact_ip` allow rules now join the allowed CIDRs as a host prefix, like `cidr` allow rules.
- **`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)
}
}
+41 -4
View File
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"net"
"net/http"
"path"
"path/filepath"
"strconv"
@@ -183,23 +184,43 @@ 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).
// RFC1918, and IPv6). It sees each hop on a direct connection; through a proxy
// it only sees the proxy, and sandboxRedirectCheck checks the hop.
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 {
@@ -210,6 +231,22 @@ func sandboxScopeDialContext(policy *sandbox.EgressPolicy, baseDial func(ctx con
}
}
// sandboxRedirectCheck refuses a WebFetch redirect hop to a URL the task's
// egress policy does not allow, before check runs. Through a proxy the sandbox
// 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 {
return func(req *http.Request, via []*http.Request) error {
if policy == nil {
return errors.New("sandbox WebFetch blocked redirect: missing task egress policy")
}
if err := policy.CheckURL(req.Context(), req.URL.String()); err != nil {
return fmt.Errorf("sandbox WebFetch blocked redirect: %w", err)
}
return check(req, via)
}
}
// sandboxScopeWebFetchTool gates WebFetch inputs against the task's
// sandbox.EgressPolicy before Norma issues any HTTP request.
type sandboxScopeWebFetchTool struct {
+100
View File
@@ -0,0 +1,100 @@
package agent
import (
"context"
"errors"
"net/http"
"strings"
"testing"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
)
func TestSandboxRedirectCheck(t *testing.T) {
pol, err := sandbox.NewEgressPolicy("rc", []string{"allowed.example"}, nil, nil)
if err != nil {
t.Fatal(err)
}
ctx := sandbox.WithResolver(context.Background(), offlineResolver(map[string]string{
"allowed.example": "203.0.113.10",
"evil.example": "203.0.113.66",
"rebind.example": "169.254.169.254",
}))
hop := func(rawURL string) *http.Request {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
t.Fatal(err)
}
return req
}
via := []*http.Request{hop("http://allowed.example/start")}
counting := func(calls *int, ret error) func(*http.Request, []*http.Request) error {
return func(*http.Request, []*http.Request) error {
*calls++
return ret
}
}
t.Run("allowed hop runs the redirect check", func(t *testing.T) {
var calls int
if err := sandboxRedirectCheck(pol, counting(&calls, nil))(hop("http://allowed.example/next"), via); err != nil {
t.Fatalf("allowed hop refused: %v", err)
}
if calls != 1 {
t.Fatalf("redirect check ran %d times, want 1", calls)
}
})
t.Run("redirect check result is returned", func(t *testing.T) {
var calls int
gate := errors.New("gate refused")
err := sandboxRedirectCheck(pol, counting(&calls, gate))(hop("http://allowed.example/next"), via)
if !errors.Is(err, gate) || calls != 1 {
t.Fatalf("err=%v calls=%d, want the redirect check's error after one call", err, calls)
}
})
t.Run("intercept redirect limit kept", func(t *testing.T) {
check := sandboxRedirectCheck(pol, intercept.RedirectCheck("WebFetch"))
if err := check(hop("http://allowed.example/next"), via); err != nil {
t.Fatalf("allowed hop refused: %v", err)
}
ten := make([]*http.Request, 10)
for i := range ten {
ten[i] = via[0]
}
err := check(hop("http://allowed.example/next"), ten)
if err == nil || !strings.Contains(err.Error(), "stopped after 10 redirects") {
t.Fatalf("11th hop: err=%v, want the intercept redirect limit", err)
}
})
t.Run("denied hops", func(t *testing.T) {
for _, u := range []string{
"http://169.254.169.254/latest/meta-data/",
"http://127.0.0.1:8080/",
"http://10.1.2.3/admin",
"http://evil.example/collect",
"http://rebind.example/",
"file:///etc/passwd",
} {
var calls int
err := sandboxRedirectCheck(pol, counting(&calls, nil))(hop(u), via)
if err == nil || !strings.Contains(err.Error(), "sandbox WebFetch blocked redirect") {
t.Fatalf("%s: err=%v, want a sandbox redirect refusal", u, err)
}
if calls != 0 {
t.Fatalf("%s: redirect check ran %d times after a refusal", u, calls)
}
}
})
t.Run("nil policy blocks", func(t *testing.T) {
var calls int
err := sandboxRedirectCheck(nil, counting(&calls, nil))(hop("http://allowed.example/next"), via)
if err == nil || !strings.Contains(err.Error(), "sandbox WebFetch blocked redirect") || calls != 0 {
t.Fatalf("err=%v calls=%d, want a refusal without running the redirect check", err, calls)
}
})
}
+7 -6
View File
@@ -23,23 +23,24 @@ import (
// adds it, so the tool list keeps its order. caCert is the recording proxy's
// CA, trusted to verify the HTTPS it re-signs. Each call goes through the shared
// egress governor (see governedFetch). tools is not modified.
// In ARTEX_SANDBOX=required mode each redirect hop is first checked against the
// task's egress policy (sandboxRedirectCheck): through a proxy the sandbox
// dialer only sees the proxy.
func withWebFetch(ctx context.Context, tools []actool.CoreTool, proxy, caCert string) []actool.CoreTool {
scope, scoped := intercept.TargetScopeFromContext(ctx)
gated := scoped && scope.Enabled != nil && scope.Enabled()
dialer := intercept.PinnedDialer("WebFetch", scoped)
disableDirect := gated
checkRedirect := intercept.RedirectCheck("WebFetch")
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)
checkRedirect = sandboxRedirectCheck(pol, checkRedirect)
disableDirect = true
}
webFetch := actool.NewWebFetch(actool.WebFetchConfig{Proxy: proxy, CACert: caCert, CheckRedirect: intercept.RedirectCheck("WebFetch"),
webFetch := actool.NewWebFetch(actool.WebFetchConfig{Proxy: proxy, CACert: caCert, CheckRedirect: checkRedirect,
DialContext: dialer, DisableDirectRetry: disableDirect})
var wrapped actool.CoreTool = governedFetch{webFetch}
if SandboxRequired() {
+132
View File
@@ -0,0 +1,132 @@
package agent
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/netip"
"strings"
"sync"
"testing"
"github.com/Autumn-27/artex/sandbox"
)
// offlineResolver answers sandbox policy lookups from answers, without the
// network; any other name fails to resolve.
func offlineResolver(answers map[string]string) func(context.Context, string) ([]netip.Addr, error) {
return func(_ context.Context, host string) ([]netip.Addr, error) {
if ip, ok := answers[strings.ToLower(host)]; ok {
return []netip.Addr{netip.MustParseAddr(ip)}, nil
}
return nil, fmt.Errorf("offline resolver: no answer for %q", host)
}
}
// redirectProxy is a plain-HTTP forward proxy that records the absolute URL of
// every request it receives. It answers first with a 302 to location and any
// other URL with 200 and PROXIED_BODY; it never connects anywhere itself.
func redirectProxy(t *testing.T, first, location string) (*httptest.Server, func() []string) {
t.Helper()
var mu sync.Mutex
var seen []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
seen = append(seen, r.URL.String())
mu.Unlock()
if r.URL.String() == first {
http.Redirect(w, r, location, http.StatusFound)
return
}
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write([]byte("PROXIED_BODY"))
}))
t.Cleanup(srv.Close)
return srv, func() []string {
mu.Lock()
defer mu.Unlock()
return append([]string(nil), seen...)
}
}
// sandboxRedirectCtx is the context of a run in scope allowed.example, with the
// loopback proxy in scope so the sandbox dialer lets WebFetch reach it. Names
// resolve offline.
func sandboxRedirectCtx() context.Context {
ctx := WithSandboxRunInfo(context.Background(), SandboxRunInfo{
TaskID: "wf-redirect",
ScopeDomains: []string{"allowed.example"},
ScopeCIDRs: []string{"127.0.0.1/32"},
})
return sandbox.WithResolver(ctx, offlineResolver(map[string]string{
"allowed.example": "203.0.113.10",
"www.allowed.example": "203.0.113.11",
"evil.example": "203.0.113.66",
}))
}
// In ARTEX_SANDBOX=required mode, WebFetch through a proxy checks every
// redirect hop against the task's egress policy: the sandbox dialer only sees
// the proxy, so a hop to IMDS, a private address or an out-of-scope domain
// must be refused before the proxy is asked for it.
func TestSandboxWebFetchProxyRedirectChecksEgressPolicy(t *testing.T) {
pinNoiseOff(t)
SetSandboxExecutor(&SandboxExecutor{Mode: sandbox.ModeRequired})
t.Cleanup(func() { SetSandboxExecutor(nil) })
const first = "http://allowed.example/start"
for name, location := range map[string]string{
"imds": "http://169.254.169.254/latest/meta-data/iam/security-credentials/",
"out-of-scope": "http://evil.example/collect",
"private-address": "http://10.1.2.3/admin",
"loopback-address": "http://127.0.0.2:8080/",
} {
t.Run(name, func(t *testing.T) {
proxy, seen := redirectProxy(t, first, location)
text, isErr := callWebFetch(t, sandboxRedirectCtx(), proxy.URL, first)
got := seen()
for _, u := range got {
if u == location {
t.Fatalf("the proxy was asked for the denied redirect target %s (proxy log %q)", location, got)
}
}
if len(got) != 1 || got[0] != first {
t.Fatalf("proxy log = %q, want only %s", got, first)
}
if !isErr || !strings.Contains(text, "sandbox WebFetch blocked redirect") {
t.Fatalf("want a sandbox redirect refusal, got isError=%v text=%q", isErr, text)
}
})
}
t.Run("in-scope hop is followed", func(t *testing.T) {
const location = "http://www.allowed.example/next"
proxy, seen := redirectProxy(t, first, location)
text, isErr := callWebFetch(t, sandboxRedirectCtx(), proxy.URL, first)
if got := seen(); len(got) != 2 || got[0] != first || got[1] != location {
t.Fatalf("proxy log = %q, want %s then %s", got, first, location)
}
if isErr || !strings.Contains(text, "PROXIED_BODY") {
t.Fatalf("want the in-scope hop fetched, got isError=%v text=%q", isErr, text)
}
})
}
// Outside ARTEX_SANDBOX=required mode the WebFetch redirect handling is
// unchanged: no egress policy applies, so the proxy is asked for the hop.
func TestWebFetchProxyRedirectSandboxOffUnchanged(t *testing.T) {
pinNoiseOff(t)
SetSandboxExecutor(nil)
const first = "http://allowed.example/start"
const location = "http://169.254.169.254/latest/meta-data/"
proxy, seen := redirectProxy(t, first, location)
text, isErr := callWebFetch(t, sandboxRedirectCtx(), proxy.URL, first)
if got := seen(); len(got) != 2 || got[0] != first || got[1] != location {
t.Fatalf("proxy log = %q, want %s then %s", got, first, location)
}
if isErr || !strings.Contains(text, "PROXIED_BODY") {
t.Fatalf("want the hop followed, got isError=%v text=%q", isErr, text)
}
}
+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")
}
}
+26 -11
View File
@@ -222,10 +222,23 @@ func isDefaultDeniedAddr(addr netip.Addr) bool {
return false
}
type resolverCtxKey struct{}
// WithResolver returns ctx carrying fn: a policy without its own Resolver
// resolves names through fn for calls made with ctx (or a context derived from
// it). It is the seam tests use to answer lookups without the network, for the
// policies the panel tools build themselves; production code does not set it.
func WithResolver(ctx context.Context, fn func(ctx context.Context, host string) ([]netip.Addr, error)) context.Context {
return context.WithValue(ctx, resolverCtxKey{}, fn)
}
func (p *EgressPolicy) resolve(ctx context.Context, host string) ([]netip.Addr, error) {
if p.Resolver != nil {
return p.Resolver(ctx, host)
}
if fn, ok := ctx.Value(resolverCtxKey{}).(func(ctx context.Context, host string) ([]netip.Addr, error)); ok && fn != nil {
return fn(ctx, host)
}
ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip", host)
if err != nil {
return nil, err
@@ -324,9 +337,11 @@ func (p *EgressPolicy) logDecision(host string, port int, ip, protocol, decision
// CheckURL validates a navigation/fetch URL against the task scope allowlist.
// Only http/https/ws/wss schemes are permitted. Literal IPs must match
// ScopeCIDRs (blocking IMDS, loopback, RFC1918, and arbitrary non-scope IPs).
// Domains must match ScopeDomains; if DNS resolution returns addresses, at
// least one address must be allowed (rejecting domains resolving solely to
// private/IMDS/IPv6 addresses).
// Domains must match ScopeDomains and must resolve, and every resolved address
// must be allowed: a lookup error or an empty answer is a denial, and so is a
// name answering a public address next to a private/IMDS/IPv6 one. CheckURL
// pins nothing, and the connection may be made by someone else (a proxy, the
// browser) that picks any of the answers.
func (p *EgressPolicy) CheckURL(ctx context.Context, rawURL string) error {
rawURL = strings.TrimSpace(rawURL)
if rawURL == "" {
@@ -357,15 +372,15 @@ func (p *EgressPolicy) CheckURL(ctx context.Context, rawURL string) error {
if !p.domainAllowed(host) {
return fmt.Errorf("egress denied: domain %q is not in task scope%s", host, egressScopeHint)
}
// If DNS resolves, reject if every resolved IP is disallowed/private/IMDS/IPv6.
if addrs, err := p.resolve(ctx, host); err == nil && len(addrs) > 0 {
for _, addr := range addrs {
addr = addr.Unmap()
if p.ipInScopeCIDR(addr) || !isDefaultDeniedAddr(addr) {
return nil
}
addrs, err := p.resolve(ctx, host)
if err != nil || len(addrs) == 0 {
return fmt.Errorf("egress denied: dns lookup failed for %q: %v", host, err)
}
for _, addr := range addrs {
addr = addr.Unmap()
if !p.ipInScopeCIDR(addr) && isDefaultDeniedAddr(addr) {
return fmt.Errorf("egress denied: %q resolved to disallowed/private/IPv6 address %s", host, addr)
}
return fmt.Errorf("egress denied: %q resolved only to disallowed/private/IPv6 address %s", host, addrs[0].Unmap())
}
return nil
}
+92
View File
@@ -0,0 +1,92 @@
package sandbox
import (
"context"
"errors"
"net/netip"
"strings"
"testing"
)
// tableResolver answers from a table; a name it does not know fails as a
// lookup error would.
func tableResolver(answers map[string][]string) func(context.Context, string) ([]netip.Addr, error) {
return func(_ context.Context, host string) ([]netip.Addr, error) {
ips, ok := answers[host]
if !ok {
return nil, errors.New("lookup " + host + ": no such host")
}
out := make([]netip.Addr, 0, len(ips))
for _, ip := range ips {
out = append(out, netip.MustParseAddr(ip))
}
return out, nil
}
}
func dnsPolicy(t *testing.T, cidrs []string, answers map[string][]string) *EgressPolicy {
t.Helper()
p, err := NewEgressPolicy("dns-egress", []string{"allowed.example"}, cidrs, nil)
if err != nil {
t.Fatal(err)
}
p.Resolver = tableResolver(answers)
return p
}
// A name in scope whose lookup fails, or answers nothing, is refused: CheckURL
// cannot tell where the connection would go.
func TestCheckURLDeniesOnDNSError(t *testing.T) {
p := dnsPolicy(t, nil, map[string][]string{"empty.allowed.example": {}})
for _, u := range []string{"http://nxdomain.allowed.example/", "https://empty.allowed.example/x"} {
err := p.CheckURL(context.Background(), u)
if err == nil || !strings.Contains(err.Error(), "egress denied") {
t.Fatalf("CheckURL(%s) = %v, want a denial", u, err)
}
}
}
// A name answering a public address next to the metadata address (or a private
// one) is refused whatever the order of the answers: the client or a proxy may
// connect to any of them.
func TestCheckURLDeniesDualAWithMetadata(t *testing.T) {
p := dnsPolicy(t, nil, map[string][]string{
"imds-first.allowed.example": {"169.254.169.254", "93.184.216.34"},
"public-first.allowed.example": {"93.184.216.34", "169.254.169.254"},
"private.allowed.example": {"93.184.216.34", "10.0.0.7"},
"v6-imds.allowed.example": {"93.184.216.34", "fd00:ec2::254"},
})
for _, host := range []string{"imds-first", "public-first", "private", "v6-imds"} {
u := "http://" + host + ".allowed.example/latest/meta-data/"
err := p.CheckURL(context.Background(), u)
if err == nil || !strings.Contains(err.Error(), "egress denied") {
t.Fatalf("CheckURL(%s) = %v, want a denial", u, err)
}
}
}
// Every answer allowed: public addresses, or an address listed in the scope
// CIDRs next to a public one, still pass.
func TestCheckURLAllowsWhenEveryAnswerAllowed(t *testing.T) {
p := dnsPolicy(t, []string{"10.0.0.0/24"}, map[string][]string{
"public.allowed.example": {"93.184.216.34", "93.184.216.35"},
"scoped.allowed.example": {"10.0.0.7", "93.184.216.34"},
})
for _, u := range []string{"http://public.allowed.example/", "http://scoped.allowed.example/"} {
if err := p.CheckURL(context.Background(), u); err != nil {
t.Fatalf("CheckURL(%s) = %v, want allowed", u, err)
}
}
}
// A policy without its own Resolver takes the one the context carries.
func TestResolverFromContext(t *testing.T) {
p, err := NewEgressPolicy("dns-egress", []string{"allowed.example"}, nil, nil)
if err != nil {
t.Fatal(err)
}
ctx := WithResolver(context.Background(), tableResolver(map[string][]string{"ok.allowed.example": {"93.184.216.34"}}))
if ip, err := p.ResolveAndCheck(ctx, "ok.allowed.example"); err != nil || ip.String() != "93.184.216.34" {
t.Fatalf("ResolveAndCheck = %v, %v; want the context resolver's answer", ip, err)
}
}
+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},
+37 -18
View File
@@ -13,6 +13,7 @@ import (
"net/url"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
@@ -175,6 +176,13 @@ func samePath(a, b string) bool {
return a == b
}
// jwtIssuer and jwtAudience go into every new session token. Tokens issued
// before they were added carry neither claim and are still accepted.
const (
jwtIssuer = "artex"
jwtAudience = "artex-api"
)
// sessionClaims carries the password version the token was signed under.
// Two changes in the same second get different versions, so a cutoff based on
// the issued-at second cannot leave the older token valid.
@@ -193,6 +201,8 @@ func signJWTVersion(key []byte, version int64) (string, error) {
return jwt.NewWithClaims(jwt.SigningMethodHS256, sessionClaims{
Pwd: version,
RegisteredClaims: jwt.RegisteredClaims{
Issuer: jwtIssuer,
Audience: jwt.ClaimStrings{jwtAudience},
Subject: "ARTEX",
ExpiresAt: jwt.NewNumericDate(time.Now().Add(jwtTTL)),
IssuedAt: jwt.NewNumericDate(time.Now()),
@@ -200,18 +210,33 @@ func signJWTVersion(key []byte, version int64) (string, error) {
}).SignedString(key)
}
// verifyJWT returns true when tokenStr is a valid, non-expired HS256 token.
// version 0 means no password change is stored yet, and any valid token is
// accepted. A later version requires the token's pwd claim to equal it.
func verifyJWT(tokenStr string, key []byte, version int64) bool {
// parseSessionJWT returns the claims of tokenStr when it is a valid,
// non-expired session token. Only HS256 is accepted. The iss and aud claims
// are checked when present; tokens issued before they were added have neither.
func parseSessionJWT(tokenStr string, key []byte) (*sessionClaims, bool) {
claims := &sessionClaims{}
t, err := jwt.ParseWithClaims(tokenStr, claims, func(t *jwt.Token) (any, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method")
}
t, err := jwt.ParseWithClaims(tokenStr, claims, func(*jwt.Token) (any, error) {
return key, nil
})
}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
if err != nil || !t.Valid {
return nil, false
}
if claims.Issuer != "" && claims.Issuer != jwtIssuer {
return nil, false
}
if len(claims.Audience) > 0 && !slices.Contains(claims.Audience, jwtAudience) {
return nil, false
}
return claims, true
}
// verifyJWT returns true when tokenStr is a valid, non-expired session token
// (parseSessionJWT). version 0 means no password change is stored yet, and any
// valid token is accepted. A later version requires the token's pwd claim to
// equal it.
func verifyJWT(tokenStr string, key []byte, version int64) bool {
claims, ok := parseSessionJWT(tokenStr, key)
if !ok {
return false
}
if version > 0 && claims.Pwd != version {
@@ -251,16 +276,10 @@ func (s *Server) applyPasswordVersion(n int64) {
}
// jwtSubject returns the subject of tokenStr when it is a valid, non-expired
// HS256 token, and "" otherwise.
// session token (parseSessionJWT), and "" otherwise.
func jwtSubject(tokenStr string, key []byte) string {
var claims jwt.RegisteredClaims
t, err := jwt.ParseWithClaims(tokenStr, &claims, func(t *jwt.Token) (any, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method")
}
return key, nil
})
if err != nil || !t.Valid {
claims, ok := parseSessionJWT(tokenStr, key)
if !ok {
return ""
}
return claims.Subject
+92
View File
@@ -0,0 +1,92 @@
package server
import (
"slices"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
)
func testJWTClaims(iss string, aud []string, pwd int64) sessionClaims {
return sessionClaims{
Pwd: pwd,
RegisteredClaims: jwt.RegisteredClaims{
Issuer: iss,
Audience: aud,
Subject: "ARTEX",
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
}
func signTestJWT(t *testing.T, method jwt.SigningMethod, key any, c sessionClaims) string {
t.Helper()
tok, err := jwt.NewWithClaims(method, c).SignedString(key)
if err != nil {
t.Fatal(err)
}
return tok
}
// New tokens carry iss and aud and are accepted.
func TestSignJWTSetsIssuerAndAudience(t *testing.T) {
key := []byte("0123456789abcdef0123456789abcdef")
tok, err := signJWTVersion(key, 3)
if err != nil {
t.Fatal(err)
}
claims, ok := parseSessionJWT(tok, key)
if !ok {
t.Fatal("new token rejected")
}
if claims.Issuer != jwtIssuer || !slices.Equal(claims.Audience, jwt.ClaimStrings{jwtAudience}) {
t.Errorf("iss=%q aud=%v, want %q and [%q]", claims.Issuer, claims.Audience, jwtIssuer, jwtAudience)
}
if !verifyJWT(tok, key, 3) || jwtSubject(tok, key) != "ARTEX" {
t.Error("new token not accepted by verifyJWT or jwtSubject")
}
}
func TestVerifyJWTClaimsAndAlgorithm(t *testing.T) {
key := []byte("0123456789abcdef0123456789abcdef")
aud := []string{jwtAudience}
for _, tc := range []struct {
name string
tok string
accept bool
}{
// Tokens issued by earlier releases have no iss or aud and keep working.
{"legacy claims, HS256", signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims("", nil, 0)), true},
{"iss without aud", signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims(jwtIssuer, nil, 0)), true},
{"aud without iss", signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims("", aud, 0)), true},
{"aud list with ours", signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims(jwtIssuer, []string{"other", jwtAudience}, 0)), true},
{"wrong iss", signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims("someone-else", aud, 0)), false},
{"wrong aud", signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims(jwtIssuer, []string{"other-api"}, 0)), false},
{"HS384", signTestJWT(t, jwt.SigningMethodHS384, key, testJWTClaims(jwtIssuer, aud, 0)), false},
{"HS512", signTestJWT(t, jwt.SigningMethodHS512, key, testJWTClaims(jwtIssuer, aud, 0)), false},
{"HS512 legacy claims", signTestJWT(t, jwt.SigningMethodHS512, key, testJWTClaims("", nil, 0)), false},
{"alg none", signTestJWT(t, jwt.SigningMethodNone, jwt.UnsafeAllowNoneSignatureType, testJWTClaims(jwtIssuer, aud, 0)), false},
{"other key", signTestJWT(t, jwt.SigningMethodHS256, []byte("another-key-another-key-another-k"), testJWTClaims(jwtIssuer, aud, 0)), false},
} {
if got := verifyJWT(tc.tok, key, 0); got != tc.accept {
t.Errorf("%s: verifyJWT=%v, want %v", tc.name, got, tc.accept)
}
if got := jwtSubject(tc.tok, key) == "ARTEX"; got != tc.accept {
t.Errorf("%s: jwtSubject accepted=%v, want %v", tc.name, got, tc.accept)
}
}
}
// The password version check still applies to legacy tokens.
func TestVerifyJWTLegacyTokenPasswordVersion(t *testing.T) {
key := []byte("0123456789abcdef0123456789abcdef")
tok := signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims("", nil, 2))
if !verifyJWT(tok, key, 2) {
t.Error("legacy token at the current password version rejected")
}
if verifyJWT(tok, key, 3) {
t.Error("legacy token at an old password version accepted")
}
}
+52 -1
View File
@@ -698,6 +698,18 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if strings.TrimSpace(rawURL) == "" {
return actool.Errorf("http url is empty"), nil
}
// ARTEX_SANDBOX=required: the request leaves from the panel process, not from
// the task's worker container and its egress proxy. The task's egress policy,
// the one WebFetch enforces, applies here to the URL, to every redirect hop
// and to every connection (see sandboxHTTPTransport); a refusal is final,
// there is no direct fallback.
var sbPolicy *sandbox.EgressPolicy
if agent.SandboxRequired() {
sbPolicy = agent.SandboxEgressPolicy(ctx)
if err := sbPolicy.CheckURL(ctx, rawURL); err != nil {
return actool.Errorf("sandbox http tool blocked: " + err.Error()), nil
}
}
// The hook saw the parameters, not the URL they render (nor a URL written in
// the template): the target gate reads the rendered URL here, before the
// tool's own timeout starts, so a wait for an approval does not consume it.
@@ -726,11 +738,18 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if intercept.ApplyAssessmentUserAgent(req) {
client.CheckRedirect = assessmentRedirectCheck(client.CheckRedirect)
}
if sbPolicy != nil {
client.CheckRedirect = sandboxRedirectCheck(sbPolicy, client.CheckRedirect)
}
// The current egress governor paces every request and redirect hop per host
// under the noise profile (off by default: the base transport itself). It is
// resolved per request, so a changed profile applies to the next call.
var base http.RoundTripper = http.DefaultTransport
if tr := s.httpToolTransport(ctx, key, spec); tr != nil {
tr := s.httpToolTransport(ctx, key, spec)
if sbPolicy != nil {
tr = sandboxHTTPTransport(tr, sbPolicy)
}
if tr != nil {
base = tr
}
client.Transport = egress.Current().Transport(key, base)
@@ -759,6 +778,38 @@ func assessmentRedirectCheck(check func(*http.Request, []*http.Request) error) f
}
}
// sandboxRedirectCheck refuses a redirect hop to a URL the task's egress policy
// does not allow, before check runs: the call fails instead of following it.
func sandboxRedirectCheck(policy *sandbox.EgressPolicy, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
return func(req *http.Request, via []*http.Request) error {
if err := policy.CheckURL(req.Context(), req.URL.String()); err != nil {
return fmt.Errorf("sandbox http tool blocked redirect: %w", err)
}
return check(req, via)
}
}
// sandboxHTTPTransport makes every connection of an http tool call go through
// the WebFetch sandbox dialer, which checks the host against the policy and
// dials only the IP it resolved and allowed. tr is httpToolTransport's result:
// with a proxy, the proxy is the connection checked; a direct call drops the
// environment proxy so the dialer sees the target, and keeps the pinned dialer
// of a gated scope underneath. Keep-alive is off on every one of them, proxy or
// not: no connection outlives the call it was checked for.
func sandboxHTTPTransport(tr *http.Transport, policy *sandbox.EgressPolicy) *http.Transport {
if tr == nil {
base, ok := http.DefaultTransport.(*http.Transport)
if !ok {
base = &http.Transport{}
}
tr = base.Clone()
tr.Proxy = nil
}
tr.DisableKeepAlives = true
tr.DialContext = agent.SandboxScopeDialContext("http tool", policy, tr.DialContext)
return tr
}
// httpToolTransport is the transport of one http tool call, or nil
// (http.DefaultTransport). A call through a proxy keeps httpProxyTransport: it
// dials the proxy, which makes the connection to the target. A direct call in
+103
View File
@@ -0,0 +1,103 @@
package server
import (
"context"
"errors"
"net/netip"
"strings"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
)
// dnsTable answers lookups from a table, without the network; a name it does
// not know fails as a lookup error would.
func dnsTable(answers map[string][]string) func(context.Context, string) ([]netip.Addr, error) {
return func(_ context.Context, host string) ([]netip.Addr, error) {
ips, ok := answers[host]
if !ok {
return nil, errors.New("lookup " + host + ": no such host")
}
out := make([]netip.Addr, 0, len(ips))
for _, ip := range ips {
out = append(out, netip.MustParseAddr(ip))
}
return out, nil
}
}
// proxyDNSCtx is a sandbox run whose scope lists allowed.example and the
// loopback proxy, with lookups answered by answers.
func proxyDNSCtx(answers map[string][]string) context.Context {
return sandbox.WithResolver(sandboxCtx([]string{"allowed.example"}, []string{"127.0.0.1/32"}), dnsTable(answers))
}
// Through an explicit proxy in scope, the panel dials the proxy and the proxy
// resolves the target: the target is checked by CheckURL alone. A target whose
// lookup fails is refused before the proxy is dialled; an in-scope target that
// resolves to a public address still goes through the same proxy.
func TestSandboxHTTPToolProxyRefusesTargetDNSError(t *testing.T) {
sandboxRequired(t)
proxy, proxyHits := canaryServer(t, "127.0.0.1", nil)
ctx := proxyDNSCtx(map[string][]string{"ok.allowed.example": {"203.0.113.10"}})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": "http://nxdomain.allowed.example/", "proxy": proxy.URL})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("target with a failed lookup not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := proxyHits.Load(); n != 0 {
t.Fatalf("proxy received %d request(s) for a target whose lookup failed", n)
}
res = runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": "http://ok.allowed.example/", "proxy": proxy.URL})
if res.IsError || !strings.Contains(res.Flatten(), "CANARY_BODY") || proxyHits.Load() != 1 {
t.Fatalf("resolved in-scope target through the proxy: isError=%v text=%q proxy hits=%d", res.IsError, res.Flatten(), proxyHits.Load())
}
}
// A target answering the metadata address next to a public one is refused
// before the proxy, which would pick its own answer, is dialled.
func TestSandboxHTTPToolProxyRefusesDualAMetadataTarget(t *testing.T) {
sandboxRequired(t)
proxy, proxyHits := canaryServer(t, "127.0.0.1", nil)
ctx := proxyDNSCtx(map[string][]string{"dual.allowed.example": {"169.254.169.254", "203.0.113.10"}})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": "http://dual.allowed.example/latest/meta-data/", "proxy": proxy.URL})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("dual-A metadata target not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := proxyHits.Load(); n != 0 {
t.Fatalf("proxy received %d request(s) for a dual-A metadata target", n)
}
}
// Every transport the sandbox builds for an http tool call has keep-alive off
// and the sandbox dialer: direct with the gate off or on, an operator proxy,
// and the recording proxy setting falling back to the global proxy.
func TestSandboxHTTPTransportKeepAlivesOff(t *testing.T) {
policy := agent.SandboxEgressPolicy(sandboxCtx([]string{"allowed.example"}, []string{"127.0.0.1/32"}))
gateOn := intercept.WithTargetScope(context.Background(), intercept.TargetScope{TaskID: "7", Enabled: func() bool { return true }})
s := &Server{m: &Manager{globalProxy: "http://127.0.0.1:3128"}}
direct := "http://api.allowed.example/"
for _, c := range []struct {
name string
ctx context.Context
spec httpExec
}{
{"direct, gate off", context.Background(), httpExec{URL: direct}},
{"direct, gate on", gateOn, httpExec{URL: direct}},
{"operator proxy", context.Background(), httpExec{URL: direct, Proxy: "http://127.0.0.1:8080"}},
{"operator proxy, gate on", gateOn, httpExec{URL: direct, Proxy: "127.0.0.1:8080"}},
{"recording proxy via the global proxy", context.Background(), httpExec{URL: direct, UseRecordingProxy: true}},
} {
tr := sandboxHTTPTransport(s.httpToolTransport(c.ctx, "probe", c.spec), policy)
if tr == nil || tr.DialContext == nil {
t.Fatalf("%s: transport %+v, want one with the sandbox dialer", c.name, tr)
}
if !tr.DisableKeepAlives {
t.Fatalf("%s: DisableKeepAlives = false, want keep-alive off on every sandbox transport", c.name)
}
}
}
+266
View File
@@ -0,0 +1,266 @@
package server
import (
"context"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/sandbox"
actool "github.com/Autumn-27/norma/tool"
)
// sandboxRequired puts the process in ARTEX_SANDBOX=required mode for one test.
func sandboxRequired(t *testing.T) {
t.Helper()
prev := agent.CurrentSandboxExecutor()
agent.SetSandboxExecutor(&agent.SandboxExecutor{Mode: sandbox.ModeRequired})
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
}
// canaryServer counts every request it receives. ip is the loopback address it
// listens on (127.0.0.1 or 127.0.0.2, both on lo).
func canaryServer(t *testing.T, ip string, h http.HandlerFunc) (*httptest.Server, *atomic.Int32) {
t.Helper()
hits := new(atomic.Int32)
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
if h != nil {
h(w, r)
return
}
_, _ = w.Write([]byte("CANARY_BODY"))
}))
ln, err := net.Listen("tcp", ip+":0")
if err != nil {
t.Fatalf("listen %s: %v", ip, err)
}
srv.Listener = ln
srv.Start()
t.Cleanup(srv.Close)
return srv, hits
}
func sandboxCtx(domains, cidrs []string) context.Context {
return agent.WithSandboxRunInfo(context.Background(), agent.SandboxRunInfo{
TaskID: "custom-http-egress", ScopeDomains: domains, ScopeCIDRs: cidrs,
})
}
func runHTTPSpec(t *testing.T, ctx context.Context, spec map[string]any) actool.Result {
t.Helper()
raw, _ := json.Marshal(spec)
res, err := (&Server{}).runHTTPTool(ctx, "probe", raw, map[string]any{}, nil)
if err != nil {
t.Fatalf("runHTTPTool: %v", err)
}
return res
}
// A URL outside the task scope is refused before any request leaves.
func TestSandboxHTTPToolRefusesOutOfScopeURL(t *testing.T) {
sandboxRequired(t)
srv, hits := canaryServer(t, "127.0.0.1", nil)
ctx := sandboxCtx([]string{"allowed.example"}, nil)
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": srv.URL + "/secret"})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("out-of-scope URL not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := hits.Load(); n != 0 {
t.Fatalf("out-of-scope server received %d request(s)", n)
}
}
// A name in scope that resolves only to loopback is not dialed: the policy
// treats it as WebFetch does (loopback is denied unless listed in the CIDRs).
func TestSandboxHTTPToolRefusesScopedNameResolvingToLoopback(t *testing.T) {
sandboxRequired(t)
srv, hits := canaryServer(t, "127.0.0.1", nil)
_, port, _ := net.SplitHostPort(srv.Listener.Addr().String())
ctx := sandboxCtx([]string{"localhost"}, nil)
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": "http://localhost:" + port + "/"})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("scoped name resolving to loopback not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := hits.Load(); n != 0 {
t.Fatalf("loopback server received %d request(s)", n)
}
}
// A redirect from an in-scope URL to a host outside the scope fails; the
// outside host never receives the request.
func TestSandboxHTTPToolRefusesRedirectOutOfScope(t *testing.T) {
sandboxRequired(t)
outside, outsideHits := canaryServer(t, "127.0.0.2", nil)
inScope, inHits := canaryServer(t, "127.0.0.1", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, outside.URL+"/stolen", http.StatusFound)
})
ctx := sandboxCtx(nil, []string{"127.0.0.1/32"})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": inScope.URL + "/start"})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("out-of-scope redirect not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := inHits.Load(); n != 1 {
t.Fatalf("in-scope server hits = %d, want 1", n)
}
if n := outsideHits.Load(); n != 0 {
t.Fatalf("out-of-scope redirect target received %d request(s)", n)
}
}
// A proxy configured on the tool is a connection the panel opens too: a proxy
// outside the scope is not dialed, even for an in-scope target.
func TestSandboxHTTPToolRefusesOutOfScopeProxy(t *testing.T) {
sandboxRequired(t)
target, targetHits := canaryServer(t, "127.0.0.1", nil)
proxy, proxyHits := canaryServer(t, "127.0.0.2", nil)
ctx := sandboxCtx(nil, []string{"127.0.0.1/32"})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": target.URL + "/", "proxy": proxy.URL})
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("out-of-scope proxy not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := proxyHits.Load(); n != 0 {
t.Fatalf("out-of-scope proxy received %d request(s)", n)
}
if n := targetHits.Load(); n != 0 {
t.Fatalf("target received %d request(s) around the proxy", n)
}
}
// An in-scope URL still works under the sandbox (loopback listed in the scope
// CIDRs, the seam the WebFetch sandbox test uses).
func TestSandboxHTTPToolAllowsInScopeURL(t *testing.T) {
sandboxRequired(t)
srv, hits := canaryServer(t, "127.0.0.1", nil)
ctx := sandboxCtx(nil, []string{"127.0.0.1/32"})
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": srv.URL + "/ok"})
if res.IsError || !strings.Contains(res.Flatten(), "CANARY_BODY") {
t.Fatalf("in-scope URL refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := hits.Load(); n != 1 {
t.Fatalf("in-scope server hits = %d, want 1", n)
}
}
// Sandbox off: the tool behaves as before, a loopback URL with no task scope
// and a redirect to another loopback host both go through.
func TestHTTPToolSandboxOffUnchanged(t *testing.T) {
prev := agent.CurrentSandboxExecutor()
agent.SetSandboxExecutor(nil)
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
other, otherHits := canaryServer(t, "127.0.0.2", nil)
srv, hits := canaryServer(t, "127.0.0.1", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, other.URL+"/next", http.StatusFound)
})
res := runHTTPSpec(t, context.Background(), map[string]any{"method": "GET", "url": srv.URL + "/"})
if res.IsError || !strings.Contains(res.Flatten(), "CANARY_BODY") {
t.Fatalf("sandbox-off call changed: isError=%v text=%q", res.IsError, res.Flatten())
}
if hits.Load() != 1 || otherHits.Load() != 1 {
t.Fatalf("hits = %d/%d, want 1/1", hits.Load(), otherHits.Load())
}
}
// customHTTPToolRow creates a Kind:"http" custom tool bound to the worker only,
// removed when the test ends.
func customHTTPToolRow(t *testing.T, pg *db.DB, key, rawURL string) *db.Tool {
t.Helper()
execRaw, _ := json.Marshal(map[string]any{"method": "GET", "url": rawURL})
row := &db.Tool{
Key: key, Description: "custom http egress probe", Kind: "http", Enabled: true,
Agents: []string{"worker"}, Exec: execRaw,
Schema: json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"}}}`),
}
_ = pg.DeleteCustomTool(key)
if err := pg.CreateCustomTool(row); err != nil {
t.Fatalf("create custom tool: %v", err)
}
t.Cleanup(func() {
_ = pg.DeleteCustomTool(key)
_, _ = pg.Exec(`DELETE FROM tool_usage WHERE tool_key=$1`, key)
})
return row
}
func openToolsPG(t *testing.T) *db.DB {
t.Helper()
dsn, _, err := db.DSN()
if err != nil {
db.SkipPGUnavailable(t, err)
}
pg, err := db.Open(dsn)
if err != nil {
db.SkipPGUnavailable(t, err)
}
t.Cleanup(func() { pg.Close() })
if err := pg.InitSecrets(t.TempDir()); err != nil {
t.Fatalf("init secrets: %v", err)
}
return pg
}
// The planner never receives a Kind:"http" custom tool bound to the worker,
// sandbox on or off; the worker does.
func TestCustomHTTPToolNotResolvedForPlanner(t *testing.T) {
pg := openToolsPG(t)
t.Setenv("AGENT_CORE_DISABLE_INTERACTIVE_SHELL", "1")
wireTools(pg, nil)
t.Cleanup(func() { agent.SetToolResolve(nil) })
s := &Server{m: &Manager{pg: pg}}
row := customHTTPToolRow(t, pg, "sec_http_egress_planner_probe", "http://127.0.0.1:1/")
base := []actool.CoreTool{s.buildCustomTool(row)}
for _, required := range []bool{false, true} {
if required {
sandboxRequired(t)
}
ctx := context.Background()
if _, ok := names(agent.ToolResolve()(ctx, "planner", base))[row.Key]; ok {
t.Fatalf("sandbox required=%v: planner received the Kind:http tool", required)
}
if _, ok := names(agent.ToolResolve()(ctx, "worker", base))[row.Key]; !ok {
t.Fatalf("sandbox required=%v: worker lost the Kind:http tool", required)
}
}
}
// End to end, as the worker gets it: the tool the worker resolves refuses a URL
// outside the task scope under the sandbox, and the target is never reached.
func TestCustomHTTPToolWorkerSandboxRefusesOutOfScope(t *testing.T) {
pg := openToolsPG(t)
t.Setenv("AGENT_CORE_DISABLE_INTERACTIVE_SHELL", "1")
wireTools(pg, nil)
t.Cleanup(func() { agent.SetToolResolve(nil) })
sandboxRequired(t)
srv, hits := canaryServer(t, "127.0.0.1", nil)
s := &Server{m: &Manager{pg: pg}}
row := customHTTPToolRow(t, pg, "sec_http_egress_worker_probe", srv.URL+"/secret?q={q}")
ctx := sandboxCtx([]string{"allowed.example"}, nil)
tool, ok := names(agent.ToolResolve()(ctx, "worker", []actool.CoreTool{s.buildCustomTool(row)}))[row.Key]
if !ok {
t.Fatal("worker did not receive the Kind:http tool")
}
res, err := tool.Call(ctx, json.RawMessage(`{"q":"x"}`), &actool.ToolContext{})
if err != nil {
t.Fatalf("call: %v", err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
t.Fatalf("worker Kind:http call outside the scope not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := hits.Load(); n != 0 {
t.Fatalf("out-of-scope server received %d request(s)", n)
}
}
+3 -1
View File
@@ -150,7 +150,9 @@ func taskSandboxRunInfo(pg *db.DB, dataDir, taskID string) agent.SandboxRunInfo
switch kind {
case "exact_domain", "domain_suffix":
addDom(pat)
case "cidr", "ip":
// The single-address kind is exact_ip (asset_intercept_match.go);
// NewEgressPolicy reads a bare address as a host prefix.
case "cidr", "exact_ip":
addCIDR(pat)
}
}
+76
View File
@@ -0,0 +1,76 @@
package server
import (
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/sandbox"
)
// TestSandboxEgressFromTaskAllowRules covers the operator's task allow rules
// as sandbox egress. An exact_ip allow rule used to grant none: the switch
// looked for an "ip" kind that the rule tables never store, so a task scoped
// to one address could not reach it from the sandbox.
func TestSandboxEgressFromTaskAllowRules(t *testing.T) {
dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN"))
if dsn == "" {
t.Skip("ARTEX_PG_DSN not set")
}
pg, err := db.Open(dsn)
if err != nil {
db.SkipPGUnavailable(t, err)
}
t.Cleanup(func() { _ = pg.Close() })
suffix := strconv.FormatInt(time.Now().UnixNano(), 36)
allowedDom := "allow-" + suffix + ".test"
rule := func(action, kind, pattern string, enabled bool) db.TaskInterceptRuleInput {
return db.TaskInterceptRuleInput{Action: action, Kind: kind, Pattern: pattern, Enabled: enabled}
}
task, err := pg.CreateTaskWithOptions("allow-egress-"+suffix, "goal", db.TaskCreateOptions{
InterceptRules: []db.TaskInterceptRuleInput{
rule("allow", "exact_ip", "10.20.30.40", true),
rule("allow", "cidr", "198.51.100.0/24", true),
rule("allow", "exact_domain", allowedDom, true),
rule("allow", "exact_ip", "10.20.30.41", false), // disabled
rule("block", "exact_ip", "10.20.30.42", true), // a block rule grants nothing
},
})
if err != nil {
t.Fatalf("CreateTaskWithOptions: %v", err)
}
t.Cleanup(func() { _ = pg.DeleteTask(task.ID) })
info := taskSandboxRunInfo(pg, t.TempDir(), strconv.FormatInt(task.ID, 10))
for _, want := range []string{"10.20.30.40", "198.51.100.0/24"} {
if !scopeHas(info.ScopeCIDRs, want) {
t.Fatalf("allow rule %s missing from ScopeCIDRs=%v", want, info.ScopeCIDRs)
}
}
for _, unwanted := range []string{"10.20.30.41", "10.20.30.42"} {
if scopeHas(info.ScopeCIDRs, unwanted) {
t.Fatalf("%s reached ScopeCIDRs=%v", unwanted, info.ScopeCIDRs)
}
}
if !scopeHas(info.ScopeDomains, allowedDom) {
t.Fatalf("allow rule %s missing from ScopeDomains=%v", allowedDom, info.ScopeDomains)
}
// The egress policy reads the bare address as a host prefix: the private
// address the operator allowed is reachable, its neighbour is not.
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
if err != nil {
t.Fatalf("NewEgressPolicy: %v", err)
}
ctx := t.Context()
if err := pol.CheckURL(ctx, "http://10.20.30.40/"); err != nil {
t.Fatalf("allowed address refused: %v", err)
}
if err := pol.CheckURL(ctx, "http://10.20.30.43/"); err == nil {
t.Fatal("an address outside the allow rules was accepted")
}
}
+3 -1
View File
@@ -100,7 +100,9 @@ func TestSandboxScopeDriftBlockedAcrossProxyWebFetchAndBrowser(t *testing.T) {
return resp.StatusCode, nil
}
ctx := agent.WithSandboxRunInfo(context.Background(), info)
// WebFetch and the browser build their own policy: the same offline
// resolver reaches it through the context (a failed lookup is a denial).
ctx := sandbox.WithResolver(agent.WithSandboxRunInfo(context.Background(), info), pol.Resolver)
wf := agent.NewWebFetchTool(ctx, "", "")
webFetchCheck = func(rawURL string) (bool, string) {
in, _ := json.Marshal(map[string]any{"url": rawURL})
+2
View File
@@ -187,6 +187,8 @@ func TestSandboxSharedBrowserBlocksNonScopeNavigation(t *testing.T) {
ScopeDomains: []string{"app.example.com"},
ScopeCIDRs: []string{"203.0.113.10/32"},
})
// The in-scope name resolves offline (a failed lookup is a denial).
ctx = sandbox.WithResolver(ctx, dnsTable(map[string][]string{"sub.app.example.com": {"203.0.113.10"}}))
blockedURLs := []string{
"http://169.254.169.254/latest/meta-data/",
+3 -1
View File
@@ -205,7 +205,9 @@ func TestMainSideConcurrencyAndIndependentCancellation(t *testing.T) {
p := fakeProvider{stream: func(ctx context.Context, _ llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(y func(llm.StreamEvent, error) bool) {
started <- struct{}{}
y(llm.StreamEvent{Type: llm.SEMessageStart, Usage: llm.Usage{InputTokens: 7}}, nil)
if !y(llm.StreamEvent{Type: llm.SEMessageStart, Usage: llm.Usage{InputTokens: 7}}, nil) {
return
}
<-ctx.Done()
y(llm.StreamEvent{}, ctx.Err())
}
+1 -1
View File
@@ -11,7 +11,7 @@
"format": "biome format --write",
"check": "biome check",
"check:fix": "biome check --write",
"prepare": "husky",
"prepare": "cd .. && husky web/.husky",
"generate:presets": "ts-node -P tsconfig.scripts.json src/scripts/generate-theme-presets.ts",
"test:polling": "node --test scripts/polling.test.mjs",
"test:replay": "node --test scripts/replay.test.mjs",
@@ -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"