Compare commits

..
Author SHA1 Message Date
BaaRai 8fb9e365e3 docs(changelog): dedupe the 0.7.1 notes and cover the CORS proof check
Five entries in the 0.7.1 Fixed section described the same change twice:
browser capture truncation, the #542 indexing move, the (host, ts) traffic
index, the traffic host delete directory guard, and the skill endpoint
error text. Each keeps the version that matches the code and the facts the
other copy added are folded in.

The CORS proof validation from #720 gets its entry: a CORS finding now
stays unverified unless the bound exchange carries a browser-serialized
Origin and an Access-Control-Allow-Origin that authorizes it.
2026-11-30 21:41:16 +01:00
BaaRai 1ba49e04f0 Merge pull request #720 from tausifzaman/fix/cors-origin-proof-validation
security: validate CORS Origin proof evidence
2026-11-30 21:40:26 +01:00
BaaRai 86a5eb9544 Merge pull request #722 from BaaRai/release/0.7.1-addons
security/release: 0.7.1 add-ons and stdio MCP sandbox guard
2026-11-30 21:36:52 +01:00
BaaRai 6c6b353dab docs(changelog): cover notable changes since 0.6.0
The 0.7.1 release notes now list the security, interception, workspace, traffic and data changes from the v0.6.0 window that were not already detailed in the 0.7.0 or 0.7.1 sections, with their pull request numbers.
2026-11-30 21:18:23 +01:00
BaaRai 518739be3b security(server): refuse stdio MCP discovery on the panel in sandbox mode
In ARTEX_SANDBOX=required the panel must not start agent-controlled local processes. discoverAndCacheMCP now refuses stdio before connectMCP, which covers startup auto-discovery, the operator add/refresh paths and ScopeSentry; the Auto agent's create_mcp and update_mcp reject stdio transports as well. HTTP and SSE MCP clients keep their existing checks. The canary test proves the command is not spawned.
2026-11-30 21:18:09 +01:00
BaaRai 2438d1f4c0 fix(docker): keep the worker's existing exec user
Dockerfile.worker already creates exec (10001:10001) with HOME=/home/exec; #708's artex-exec rename was unnecessary and would have changed the worker identity name. The panel image keeps the artex-exec entry it needed; the worker is unchanged. The changelog now says so.
2026-11-30 21:14:11 +01:00
KKhandBaaRai f7f097ec2c fix(isolation): verify secret reads under each probe identity with descriptor metadata
Rebase #700 onto P0's isolation changes in server/isolation_unix.go (preserving
LockDownKeyDir, keys/ dir checking, and fail-closed EnforceIsolation): probe
each protected path directly with O_RDONLY|O_NONBLOCK|O_NOCTTY under the file-
tool and Bash identities, report descriptor mode/uid/gid or unexpected open
errors, and add the 0.7.1 CHANGELOG entry.

Co-authored-by: BaaRai <130491490+BaaRai@users.noreply.github.com>
2026-11-30 21:13:50 +01:00
Jędrzej SierackiandBaaRai 2276a3a023 fix(docker): give the agent executor an artex-exec passwd entry in panel and worker images
Port #708 into the panel Dockerfile and Dockerfile.worker so uid/gid 10001
resolves to artex-exec in both images (fixing tools such as ssh that require
a passwd entry for the running UID) and add the 0.7.1 CHANGELOG entry.

Co-authored-by: BaaRai <130491490+BaaRai@users.noreply.github.com>
2026-11-30 21:13:50 +01:00
BaaRai 5bd3dd2c89 Merge pull request #718 from BaaRai/release/0.7.1
release: package the sandbox images for the 0.7.1 default
2026-11-30 21:13:30 +01:00
Tausif Zaman f3b0df7f2c security: validate CORS Origin proof evidence 2026-12-01 00:52:33 +06:00
12 changed files with 654 additions and 26 deletions
+17 -7
View File
@@ -8,11 +8,12 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **Per-task execution sandbox is the default.** `Bash`, custom command and script tools, and stdio MCP servers run in a disposable `artex-worker` container created by `artex-runner`, never in the panel container. The worker has uid/gid 10001, a read-only rootfs, `cap-drop ALL`, no key or database mount, only its task workspace, and only an internal task network. A per-task `artex-egress-proxy` enforces a deny-by-default domain and CIDR allowlist with DNS pinning, HTTP/HTTPS CONNECT and SOCKS5, blocks IMDS, RFC1918, loopback, link-local and IPv6 unless explicitly approved, and writes its audit log outside the worker workspace. The runner and the three images are part of `docker-compose.yml`, `docker-compose.ghcr.yml`, `install.sh` and `update.sh`; the release publishes the runner, worker and egress-proxy images beside the panel. `ARTEX_SANDBOX=off` is the explicit, loud degraded mode.
- **Per-task execution sandbox is the default.** `Bash`, custom command and script tools run in a disposable `artex-worker` container created by `artex-runner`, never in the panel container. Stdio MCP servers are not started on the panel in required mode; HTTP and SSE MCP clients keep their existing checks. The worker has uid/gid 10001, a read-only rootfs, `cap-drop ALL`, no key or database mount, only its task workspace, and only an internal task network. A per-task `artex-egress-proxy` enforces a deny-by-default domain and CIDR allowlist with DNS pinning, HTTP/HTTPS CONNECT and SOCKS5, blocks IMDS, RFC1918, loopback, link-local and IPv6 unless explicitly approved, and writes its audit log outside the worker workspace. The runner and the three images are part of `docker-compose.yml`, `docker-compose.ghcr.yml`, `install.sh` and `update.sh`; the release publishes the runner, worker and egress-proxy images beside the panel. `ARTEX_SANDBOX=off` is the explicit, loud degraded mode.
- **The sandbox egress allowlist is operator-owned, not agent-writable.** Migration `0023_task_scope_operator_approval.sql` adds `task_scope.approved_by_operator`. Only operator-approved rows (Task Scope UI, operator-selected companies, operator retarget) grant egress; `add_task_scope`, `insert_assets`, agent-spawned company scope and expanded rows are coverage-only. `WebFetch` and the shared browser use the same policy. Existing `source='manual'` rows are backfilled; goal-derived (`source='agent'`) and auto (`source='auto'`) scopes must be re-approved once in Task Scope. Target-gate approval clears only the tool-call gate, and the denial message says so.
- **Startup is fail-closed and key permissions are enforced.** The isolation self-test stops the server on every platform unless `ARTEX_ALLOW_UNISOLATED=1` is explicitly set. The key directory is tightened to 0700 and existing key files to 0600 at startup, so a host bind mount cannot mask the image permissions.
- **Secret rotation is atomic.** `db.RotateSecretKey`, `artex -rotate-secrets` and `scripts/rotate-secrets.sh` re-encrypt every sealed database value and bump `auth.password_version` in one transaction before the new key is moved into place. Existing sessions are invalidated.
- **Target gate backfill and a real kill switch.** Migration `0022_target_gate_backfill.sql` enables the gate on active scoped tasks that did not opt out, with `tasks.target_gate_opt_out` for the explicit opt-out. `Engine.Pause` and `Engine.BeginDelete` set `PR_SET_CHILD_SUBREAPER` and terminate the executor UID or task descendants from `/proc`; the sandbox kill scans `/proc` for uid 10001 and never trusts agent-writable state, with a container-removal fallback.
- **The panel does not start stdio MCP servers in sandbox mode.** Discovery, startup auto-discovery, the operator refresh path and the Auto agent's `create_mcp` / `update_mcp` tools reject stdio transports while `ARTEX_SANDBOX=required`; an agent-created stdio MCP cannot be launched on the panel at the next restart. HTTP and SSE MCP clients are unchanged. This closes the remaining panel-side local execution path.
- **Chat bridge approval buttons recheck access.** A member removed, a chat unlisted or the bridge disabled while a batch was queued can no longer spend a valid button. The handler re-reads the bridge, refuses when access or the enabled state changed, and the consume statement requires the current `config_version`. Reported privately by @jamesKhor.
### Breaking Changes
@@ -45,6 +46,8 @@ The execution-scope gap and its remediation were tracked in public before the No
- **Go vulnerability scanning in CI**: every push and pull request runs the official `govulncheck` action against packages reachable from `./...`, using the Go version declared by `go.mod`. Run the same check locally with `./scripts/verify.sh --security`.
### Fixed
- **Startup isolation self-test verifies secret opens under each probe identity and reports file metadata**: `fileToolIsolationFailures` and `checkIsolationAsExecutor` now open every protected target directly with `O_RDONLY|O_NONBLOCK|O_NOCTTY` (avoiding a server-identity `os.Stat` pre-check and never blocking on FIFOs), report the opened descriptor's `mode`, `uid` and `gid`, and surface unexpected open errors such as symlink loops (#700).
- **The panel executor uid/gid 10001 has a named `artex-exec` passwd/group entry**: programs that look up their own user, such as ssh-based stdio MCP servers, refuse to start without one. The worker image already had `exec` (10001:10001) with `/home/exec` and `/bin/bash`; the panel image now defines `artex-exec` (`/app/data/exec-home`, `/usr/sbin/nologin`). A custom `-exec-uid` still needs its own entry (#708).
- **Attached curl body flags no longer bypass the stateful target guard**: `ClassifyHTTPAction` required a separator after `-d`, `-F` and `-T`, but curl takes the value fully attached, so `curl -dfoo=1`, `-Tshell.php` and `-Ffile=@payload` were classified read-only. That skipped the pre-mutation baseline gate and let `RecordStatefulReadOnly` store the mutation itself as the host's read-only baseline, a fail-open on a safety invariant. The attached forms are now mutating, including a spaced value (`-T shell.php`), while `-D` (dump headers), `-f`, `-o` and wget's `-T` timeout stay read-only. A body flag inside a multi-letter cluster (`-sSd...`) is still not detected.
- **The chat agent filter no longer keeps a thread from another agent open**: switching the filter left the previously selected conversation in place, so a thread started with one agent could still be read while the filter showed another, and the draft could pick the wrong agent. The selection is now cleared when it does not belong to the new filter, and the draft uses the filtered agent. `npm run test:chat-filter` covers both helpers and now runs in CI.
- **Session tokens are no longer accepted from a URL query string**: the SSE, log and browser endpoints accepted `?token=`, which put a console JWT into browser history, proxy logs and `Referer` headers. Those endpoints now require the same Bearer header as the rest of the API; the console uses a `fetch` based SSE reader, the client-written auth cookie is gone, and the same-origin CORS preflight allows `Authorization` and `Last-Event-ID`. Login and uploads no longer carry a token in the URL either (#660).
@@ -63,12 +66,8 @@ The execution-scope gap and its remediation were tracked in public before the No
- **`traffic_get` keeps compressed binary responses encoded** (follow-up to #606): the decoded view judged a body as binary only by a NUL byte in its first 512 bytes, so a gzip `application/pdf` without one was shown as text. It now uses the response `Content-Type` as well, the same check the body index applies. The response head is read before the body, so an exchange without a `Content-Encoding` no longer loads its spilled blobs, and the request blob is never loaded.
- **`traffic_search` host matching**: a port search such as `host:8443` matched any capture of that host whose URL quoted `host:8443` in its query string (`?next=http://host:8443/`, typical of open-redirect and SSRF probes), because the authority prefix was not anchored to the scheme. It is now anchored to `http`, `https`, `ws` and `wss`. The recorded host keeps the client's case while the search is lowercased, so a capture of `https://Mixed.Example.com/` was not found by any host search; the comparison now ignores case. A compressed body with a bad checksum or trailing garbage now keeps the text decoded before the error instead of dropping out of the index, and the store directory guard on host delete ignores case for case-insensitive filesystems.
- **Browser capture keeps a bounded request map**: unfinished debugger requests are capped at 500, and a request that fails to load is dropped instead of waiting for eviction. A stored body longer than 256K JavaScript characters is cut and marked `[truncated by extension]`. That count is UTF-16 code units, not bytes; the server still enforces its byte cap on ingest.
- **Browser capture keeps a bounded request map**: unfinished debugger requests are capped at 500, and a stored request body is cut at the same 256 KiB limit as ingest.
- **The capture proxy no longer holds a response while indexing it** (#542): recording wrote the trigram full-text index of each body (up to 4 MiB) before the client got its response, under the recorder's global lock, so a 1 MB script added about 160 ms to its own response and to every response recorded behind it. The index is now written by a background worker. Body searches wait for entries queued before them, so they still find every exchange recorded before the search. An entry whose exchange was deleted in the meantime is dropped.
- **The capture proxy no longer holds a response while indexing it** (#542): recording wrote the trigram full-text index of each body (up to 4 MiB) before the client got its response, so a 1 MB script added about 160 ms to its own response. The index text is now committed with the exchange into `ex_fts_pending` and indexed by a background worker; with the indexer idle, recording a 1 MiB script takes about 5 ms. Under a burst of large bodies a recording can still wait behind the entry being indexed, since both need the recorder's write lock. Body searches wait (up to 30 s) for entries queued before them, so they still find every exchange recorded before the search. Entries left by a crash or a stop are indexed on the next start, and shutdown no longer drains the queue.
- **The capture proxy no longer holds a response while indexing it** (#542): recording wrote the trigram full-text index of each body (up to 4 MiB) before the client got its response, so a 1 MB script added about 160 ms to its own response. The index text is now committed with the exchange into `ex_fts_pending` and indexed by a background worker; with the indexer idle, recording a 1 MiB script takes about 5 ms. Under a burst of large bodies a recording can still wait behind the entry being indexed, since both need the recorder's write lock. Body searches wait (up to 30 s) for entries queued before them, so they still find every exchange recorded before the search. Entries left by a crash or a stop are indexed on the next start, and shutdown no longer drains the queue. An entry whose exchange was deleted after it was queued is dropped.
- **Host-filtered traffic searches no longer sort a host's whole history**: the capture index had `host` and `ts` indexed separately, so `traffic_search` and `Search` (`WHERE host=? ORDER BY ts DESC`) sorted every exchange of the host to return the newest few, and the host picker (`Hosts()`, polled every 5 s) scanned the table. A `(host, ts)` index replaces the `host` one. With 45k exchanges on one host, a host search drops from about 42 ms to 0.04 ms and the host list from 20 ms to 8 ms. The traffic page's own list (`Page()`) is unchanged. The index is built once, synchronously, on the first start after upgrading; on a store with millions of exchanges that delays startup and needs temporary disk space about the size of the index.
- **Traffic host lists no longer sort a host's whole history**: the capture index had `host` and `ts` indexed separately, so `traffic_search` and the traffic page's host filter sorted every exchange of the host to return the newest few, and the host picker (polled every 5 s) scanned the table. A `(host, ts)` index replaces the `host` one. With 45k exchanges on one host, a host search drops from about 42 ms to 0.04 ms and the host list from 20 ms to 8 ms.
- **Traffic host delete leaves the store directories in place**: a requested host whose sanitized name is `_index`, `_blobs`, `_ca`, `_delete_staging`, `.`, or `..` is not used as a directory. Those paths are the capture index, the blob store, the MITM CA, the delete staging area, or the traffic directory itself. Index rows for that host are still removed.
- **The SOCKS5 listener refuses non-loopback clients for every auth method**: username/password was offered to any client and accepted any credentials, so a remote client got past the loopback-only rule for no-auth by offering method `0x02`. Credentials are still not verified (the username carries only the pace marker), so both methods are now accepted from loopback clients only; binding `ARTEX_SOCKS5_ADDR` to a non-loopback address no longer exposes an open proxy.
- **Request bodies labelled multipart are capped**: the 32 MiB body cap skipped any request with a multipart `Content-Type`, so a JSON handler reading the body directly could be sent an unbounded body. Multipart bodies now get an upload-sized cap (the largest limit an upload handler sets).
- **The `traffic_search` host example no longer names a real IP**: the tool description shown to the model used a routable third-party address; it now uses `192.0.2.10` (RFC 5737).
@@ -77,7 +76,6 @@ The execution-scope gap and its remediation were tracked in public before the No
- **Asset insert applies the JSON body cap**: `POST /api/assets` decodes through the shared JSON limit, including a `multipart/` request that the upload middleware leaves uncapped. A body over the cap is rejected before the database is touched.
- **The LLM connection test honours the output-cap field name**: `POST /api/llm/test` never read a profile's `max_tokens_field`, so the Test button always sent the cap as `max_tokens`. An OpenAI reasoning model (o-series, GPT-5) rejects that with `unsupported_parameter` and a 400, so a profile set to `max_completion_tokens` failed the test even though conversations with it worked. The test now resolves the field from the form, falling back to the stored profile for the list-view test button, and normalises it the same way a profile save does (only the openai format with `max_completion_tokens` is kept).
- **Skill endpoints no longer return database driver text**: a failure loading skill usage, missing-skill stats, or skill visibility is logged on the server and the client receives a fixed message.
- **Skill endpoints no longer return database driver text**: a failure loading skill usage or missing-skill stats is logged on the server and the client receives a fixed message.
- **Hook `ReplaceAll` counts against the memory budget before it runs**: `strings.ReplaceAll`, `bytes.ReplaceAll` and `regexp.ReplaceAllString` built their result first and charged it after, so a hook that repeats a long string over many matches allocated far past the 4 MiB budget. With 1 MiB replaced into each byte of 1 MiB, the runtime asked for 1 TiB and the server process exited with `fatal error: runtime: out of memory`, in a dry run as on live traffic. The size of the result is now charged before it is built, and the hook stops with the memory limit.
- **Agent list tools cap their page size**: `list_worker_traces`, `list_assets`, and `list_untested_assets` clamp a model-supplied limit or page size to 100, and clamp the page number and offset. A limit is no longer used raw as a slice capacity or a SQL page size.
- **Legacy MCP SSE refuses an overlong line**: the endpoint announcement and the legacy event reader stop a line that grows past the existing JSON-RPC buffer cap, instead of buffering it with an unbounded read.
@@ -99,6 +97,18 @@ The execution-scope gap and its remediation were tracked in public before the No
- **Uploads do not follow a symlink**: chat and workspace uploads `Lstat` the destination and refuse to write when it is already a symlink. A dangling link is no longer treated as a free name.
- **Hardening follow-up for the upload and capture fixes**: existing spill blob directories and files are tightened on startup, hook `range` charges 32 bytes per pair, and uploads open with `O_NOFOLLOW` on Unix. The Windows upload path keeps the `Lstat` check.
- **Docker Compose database passwords with URL-special characters**: `docker-compose.yml` no longer pastes `POSTGRES_PASSWORD` into `ARTEX_PG_DSN`. The server builds the URL from `ARTEX_PG_HOST`, `ARTEX_PG_PORT`, `ARTEX_PG_USER`, `ARTEX_PG_PASSWORD`, `ARTEX_PG_DBNAME` and `ARTEX_PG_SSLMODE`, percent-encoding the user and password, so `/`, `?`, `%`, `@`, `:` and spaces connect. An explicit `ARTEX_PG_DSN` still wins and is not rewritten. `ARTEX_PG_PASSWORD` is removed from the environment with the other startup secrets (#450).
- **A CORS proof must use a browser-serialized origin and a matching response**: a finding could reach `verified` when the bound exchange carried an `Origin` header no browser sends, or a response that never authorized that origin, because verification only checked that the quoted body was present. CORS-class findings now parse the bound request and response heads, require an RFC 6454 serialized origin, and require `Access-Control-Allow-Origin` to be that exact origin or `*` without credentials; otherwise the finding stays `unverified` with the reason in the verification note. The check reads the finding's own class, so other verification paths are unchanged (#720).
### Other changes since 0.6.0
The full commit list is in the compare view. The notable changes not already detailed above:
- **Sessions and authentication**: sessions issued before a password change are rejected (#301); password-change guesses are rate-limited (#343).
- **Interception and scope**: `insert_assets` is refused when the intercept rules cannot be loaded (#336); an allow is recorded only after the gate decides (#355); target pins stay name-only behind a proxy (#370); deny and ask argv rules match across compound commands (#377); always-allow is denied for git, cmake, ctest and cpack (#385); `ExecuteExtraTool` and `Monitor` are gated by default (#389).
- **Workspace, network and execution boundaries**: `ask_operator` image paths are confined to the task directory (#337); workspace and skill paths are confined against symlink escapes (#372); the capture CA and index stay out of the workspace file API (#387); the model-list endpoint blocks SSRF (#390); agent execution is contained with the executor UID drop (#395); the optional DNS-driven egress allowlist is available as a compose overlay (#418).
- **Traffic and evidence**: WebSocket and SSE messages are recorded and shown (#254, #255); an edited request can be replayed through the recording proxy (#258); rewrite rules apply in the capture proxy (#309); rewrite provenance is recorded on snapshots and archives (#392, #394, #399); HAR 1.2 import and export are available (#412); SOCKS5, transparent TCP, UDP recording and constrained tampering hooks are opt-in (#431, #432, #433, #434); `record_fact` ties evidence to recorded activity and captures (#441).
- **Data and export**: formula cells are neutralized in the findings CSV export (#340); asset DSL length and parenthesis depth are bounded (#353); keyword-value and query DSN passwords are masked (#354); CR and LF are rejected in ingested methods and headers (#344).
- **Third-party code and install**: acquiring third-party code can require explicit operator approval (#417); the runtime image adds more recon staples (#442); `install.sh` stops using get.docker.com on unsupported distributions such as Kali (#443).
## [0.7.0] - 2026-11-21
+8
View File
@@ -291,6 +291,14 @@ RUN npm install -g "@playwright/mcp@${PLAYWRIGHT_MCP_VERSION}" "@playwright/cli@
# cache, which /root's 0711 lets the executor reach.
ENV PLAYWRIGHT_BROWSERS_PATH=/root/.cache/ms-playwright
WORKDIR /app
# A passwd and group entry for the agent executor (the default -exec-uid and
# -exec-gid, 10001). Agent processes and stdio MCP servers run as that uid, and
# programs that look their own user up refuse to start without an entry: ssh
# exits with "No user exists for uid 10001". The home is the executor home the
# server prepares under the data directory. A custom -exec-uid needs its own entry.
RUN groupadd --gid 10001 artex-exec \
&& useradd --uid 10001 --gid 10001 --no-create-home --home-dir /app/data/exec-home \
--shell /usr/sbin/nologin artex-exec
# Binary compiled from source in the build stage above.
COPY --from=build /out/artex /app/artex
# Daemon startup script: relaunches the process after a crash and forwards SIGTERM
+275
View File
@@ -0,0 +1,275 @@
package db
import (
"bufio"
"fmt"
"net/http"
"net/netip"
"net/textproto"
"strconv"
"strings"
)
// ValidateBrowserOrigin validates an Origin header value as a browser origin
// serialized by RFC 6454 / the Fetch standard. The opaque origin "null" is
// valid and is handled separately from network origins. The Fetch grammar is
// intentionally stricter than a general URL parser: browser serialization is
// lowercase ASCII, uses canonical IP literals, and omits default ports.
func ValidateBrowserOrigin(raw string) error {
if raw == "" {
return fmt.Errorf("origin is empty")
}
if raw == "null" {
return nil
}
for i := 0; i < len(raw); i++ {
if raw[i] < 0x21 || raw[i] > 0x7e {
return fmt.Errorf("origin contains a non-ASCII or whitespace byte")
}
}
separator := strings.Index(raw, "://")
if separator <= 0 {
return fmt.Errorf("origin must be a serialized origin")
}
scheme := raw[:separator]
if !validSerializedScheme(scheme) {
return fmt.Errorf("origin scheme is not a lowercase serialized scheme")
}
authority := raw[separator+3:]
if authority == "" {
return fmt.Errorf("origin host is empty")
}
host, port, hasPort, err := splitSerializedAuthority(authority)
if err != nil {
return err
}
if err := validateSerializedHost(host); err != nil {
return err
}
if hasPort {
if err := validateSerializedPort(port); err != nil {
return err
}
if port == defaultOriginPort(scheme) {
return fmt.Errorf("origin must omit the default port")
}
}
return nil
}
func validSerializedScheme(scheme string) bool {
if scheme == "" || scheme[0] < 'a' || scheme[0] > 'z' {
return false
}
for i := 1; i < len(scheme); i++ {
c := scheme[i]
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '+' && c != '-' && c != '.' {
return false
}
}
return true
}
func splitSerializedAuthority(authority string) (host, port string, hasPort bool, err error) {
if strings.HasPrefix(authority, "[") {
close := strings.IndexByte(authority, ']')
if close < 0 {
return "", "", false, fmt.Errorf("origin IPv6 host is not bracketed")
}
rest := authority[close+1:]
if rest != "" && rest[0] != ':' {
return "", "", false, fmt.Errorf("origin has an invalid authority")
}
if rest != "" {
return authority[1:close], rest[1:], true, nil
}
return authority[1:close], "", false, nil
}
if strings.ContainsAny(authority, "[]/@\\/?#") {
return "", "", false, fmt.Errorf("origin authority contains an invalid character")
}
if colon := strings.IndexByte(authority, ':'); colon >= 0 {
return authority[:colon], authority[colon+1:], true, nil
}
return authority, "", false, nil
}
func validateSerializedHost(host string) error {
if host == "" {
return fmt.Errorf("origin host is empty")
}
if strings.Contains(host, ":") {
addr, err := netip.ParseAddr(host)
if err != nil || !addr.Is6() || addr.String() != host {
return fmt.Errorf("origin IPv6 host is not canonical")
}
return nil
}
for _, label := range strings.Split(host, ".") {
if label == "" || !isSerializedDomainLabel(label) {
return fmt.Errorf("origin host is not a serialized domain")
}
}
return nil
}
func isSerializedDomainLabel(label string) bool {
if !isLowerAlphaNum(label[0]) || !isLowerAlphaNum(label[len(label)-1]) {
return false
}
for i := 1; i < len(label)-1; i++ {
if !isLowerAlphaNum(label[i]) && label[i] != '-' {
return false
}
}
return true
}
func isLowerAlphaNum(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
}
func validateSerializedPort(port string) error {
if port == "" || len(port) > 5 || (len(port) > 1 && port[0] == '0') {
return fmt.Errorf("origin port is not a serialized port")
}
for i := 0; i < len(port); i++ {
if port[i] < '0' || port[i] > '9' {
return fmt.Errorf("origin port is not a serialized port")
}
}
n, err := strconv.ParseUint(port, 10, 16)
if err != nil || n > 65535 {
return fmt.Errorf("origin port is out of range")
}
return nil
}
func defaultOriginPort(scheme string) string {
switch scheme {
case "http", "ws":
return "80"
case "https", "wss":
return "443"
case "ftp":
return "21"
default:
return ""
}
}
// ValidateCORSProof validates the request Origin and the response CORS
// headers that claim to authorize it.
func ValidateCORSProof(reqHeaders, respHeaders http.Header) error {
origin, err := singleHeaderValue(reqHeaders, "Origin")
if err != nil {
return fmt.Errorf("invalid Origin header: %w", err)
}
if err := ValidateBrowserOrigin(origin); err != nil {
return fmt.Errorf("invalid Origin header: %w", err)
}
acao, err := singleHeaderValue(respHeaders, "Access-Control-Allow-Origin")
if err != nil {
return fmt.Errorf("invalid Access-Control-Allow-Origin header: %w", err)
}
acao = strings.TrimSpace(acao)
if acao == "" {
return fmt.Errorf("Access-Control-Allow-Origin is empty")
}
acac, err := singleHeaderValueOptional(respHeaders, "Access-Control-Allow-Credentials")
if err != nil {
return fmt.Errorf("invalid Access-Control-Allow-Credentials header: %w", err)
}
if acao == "*" && strings.EqualFold(strings.TrimSpace(acac), "true") {
return fmt.Errorf("wildcard Access-Control-Allow-Origin is invalid with credentials")
}
if acao != "*" && acao != origin {
return fmt.Errorf("Access-Control-Allow-Origin %q does not match Origin %q", acao, origin)
}
return nil
}
// ValidateCORSProofHeads parses the raw request and response head blocks used
// by traffic evidence and validates their CORS headers.
func ValidateCORSProofHeads(reqHead, respHead string) error {
reqHeaders, err := parseStoredHeaders(reqHead)
if err != nil {
return fmt.Errorf("invalid request head: %w", err)
}
respHeaders, err := parseStoredHeaders(respHead)
if err != nil {
return fmt.Errorf("invalid response head: %w", err)
}
return ValidateCORSProof(reqHeaders, respHeaders)
}
// IsCORSFinding reports whether vulnclass identifies a CORS finding. Finding
// class is the canonical vulnerability type stored on a findings row; task
// categories are not part of this decision.
func IsCORSFinding(vulnClass string) bool {
for _, token := range strings.FieldsFunc(strings.ToLower(strings.TrimSpace(vulnClass)), func(r rune) bool {
return r < 'a' || r > 'z'
}) {
if token == "cors" {
return true
}
}
return false
}
func singleHeaderValue(headers http.Header, name string) (string, error) {
values := headerValues(headers, name)
if len(values) == 0 {
return "", fmt.Errorf("header is missing")
}
if len(values) != 1 {
return "", fmt.Errorf("header has multiple values")
}
return values[0], nil
}
func singleHeaderValueOptional(headers http.Header, name string) (string, error) {
values := headerValues(headers, name)
if len(values) == 0 {
return "", nil
}
if len(values) != 1 {
return "", fmt.Errorf("header has multiple values")
}
return values[0], nil
}
// headerValues performs a case-insensitive lookup even for maps constructed
// directly by callers rather than through Header.Set, while preserving duplicate
// values so malformed CORS responses fail closed.
func headerValues(headers http.Header, name string) []string {
var values []string
for key, current := range headers {
if strings.EqualFold(key, name) {
values = append(values, current...)
}
}
return values
}
// parseStoredHeaders parses the first-line-prefixed raw header format used by
// traffic evidence. MIMEHeader is deliberately used here instead of splitting
// on colons so folded/malformed header lines follow the standard parser.
func parseStoredHeaders(raw string) (http.Header, error) {
raw = strings.ReplaceAll(raw, "\r\n", "\n")
raw = strings.ReplaceAll(raw, "\r", "\n")
lineEnd := strings.IndexByte(raw, '\n')
if lineEnd < 0 {
return nil, fmt.Errorf("missing HTTP start line")
}
headerBlock := strings.ReplaceAll(raw[lineEnd+1:], "\n", "\r\n") + "\r\n"
mime, err := textproto.NewReader(bufio.NewReader(strings.NewReader(headerBlock))).ReadMIMEHeader()
if err != nil {
return nil, err
}
return http.Header(mime), nil
}
+128
View File
@@ -0,0 +1,128 @@
package db
import (
"net/http"
"strings"
"testing"
)
func TestValidateBrowserOrigin(t *testing.T) {
tests := []struct {
name string
origin string
wantOK bool
}{
{name: "https", origin: "https://evil.com", wantOK: true},
{name: "http port", origin: "http://attacker.example:8443", wantOK: true},
{name: "custom scheme", origin: "chrome-extension://abcdefghijklmnop", wantOK: true},
{name: "IPv6", origin: "https://[2001:db8::1]", wantOK: true},
{name: "opaque", origin: "null", wantOK: true},
{name: "missing scheme", origin: "evil.com"},
{name: "trailing slash", origin: "https://evil.com/"},
{name: "empty fragment", origin: "https://evil.com#"},
{name: "path", origin: "https://evil.com/path"},
{name: "query", origin: "https://evil.com?x=1"},
{name: "fragment", origin: "https://evil.com#frag"},
{name: "userinfo", origin: "https://user:pass@evil.com"},
{name: "internal whitespace", origin: "https://target.com\tevil.com"},
{name: "uppercase scheme", origin: "HTTPS://evil.com"},
{name: "uppercase host", origin: "https://EVIL.com"},
{name: "explicit default port", origin: "https://evil.com:443"},
{name: "leading zero port", origin: "https://evil.com:0443"},
{name: "empty port", origin: "https://evil.com:"},
{name: "invalid IPv6 serialization", origin: "https://[2001:0DB8::1]"},
{name: "domain underscore", origin: "https://evil_site.com"},
{name: "unicode host", origin: "https://例え.テスト"},
{name: "javascript", origin: "javascript:alert(1)"},
{name: "empty", origin: ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateBrowserOrigin(tt.origin)
if tt.wantOK && err != nil {
t.Fatalf("ValidateBrowserOrigin(%q) = %v, want success", tt.origin, err)
}
if !tt.wantOK && err == nil {
t.Fatalf("ValidateBrowserOrigin(%q) succeeded, want error", tt.origin)
}
})
}
}
func TestValidateCORSProof(t *testing.T) {
tests := []struct {
name string
origin string
acao string
acac string
wantOK bool
wantReason string
}{
{name: "wildcard without credentials", origin: "https://evil.com", acao: "*", wantOK: true},
{name: "wildcard credentials", origin: "https://evil.com", acao: "*", acac: "TrUe", wantReason: "wildcard"},
{name: "mismatch", origin: "https://evil.com", acao: "https://other.example", wantReason: "does not match"},
{name: "missing ACAO", origin: "https://evil.com", wantReason: "missing"},
{name: "valid reflection with credentials", origin: "https://evil.com", acao: "https://evil.com", acac: "true", wantOK: true},
{name: "opaque reflection", origin: "null", acao: "null", wantOK: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := http.Header{}
req.Set("Origin", tt.origin)
resp := http.Header{}
if tt.acao != "" {
resp.Set("Access-Control-Allow-Origin", tt.acao)
}
if tt.acac != "" {
resp.Set("Access-Control-Allow-Credentials", tt.acac)
}
err := ValidateCORSProof(req, resp)
if tt.wantOK && err != nil {
t.Fatalf("ValidateCORSProof() = %v, want success", err)
}
if !tt.wantOK {
if err == nil {
t.Fatal("ValidateCORSProof() succeeded, want error")
}
if !strings.Contains(strings.ToLower(err.Error()), strings.ToLower(tt.wantReason)) {
t.Fatalf("error %q does not contain %q", err, tt.wantReason)
}
}
})
}
}
func TestValidateCORSProofHeads(t *testing.T) {
err := ValidateCORSProofHeads(
"GET / HTTP/1.1\nOrigin: https://evil.com\n",
"HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: https://evil.com\nAccess-Control-Allow-Credentials: true\n",
)
if err != nil {
t.Fatalf("ValidateCORSProofHeads() = %v, want success", err)
}
err = ValidateCORSProofHeads(
"GET / HTTP/1.1\nOrigin: https://evil.com\n",
"HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: https://other.example\n",
)
if err == nil || !strings.Contains(err.Error(), "does not match") {
t.Fatalf("invalid head proof error = %v, want mismatch", err)
}
}
func TestIsCORSFinding(t *testing.T) {
for _, tc := range []struct {
class string
want bool
}{
{class: "CORS", want: true},
{class: "cors misconfiguration", want: true},
{class: "cors_misconfiguration", want: true},
{class: "course injection", want: false},
{class: "XSS", want: false},
} {
if got := IsCORSFinding(tc.class); got != tc.want {
t.Errorf("IsCORSFinding(%q) = %v, want %v", tc.class, got, tc.want)
}
}
}
+44
View File
@@ -0,0 +1,44 @@
package server
import (
"fmt"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
)
func TestCORSVerificationRejectsInvalidBoundProof(t *testing.T) {
s, finding, request := trafficEvidenceServer(t)
if _, err := s.m.pg.Exec(`UPDATE findings SET vulnclass='CORS' WHERE id=$1`, finding.FindingID); err != nil {
t.Fatal(err)
}
trafficID := "cors-invalid-proof"
_, err := s.m.traffic.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path)
VALUES(?,1,'evidence.local','GET','/','https://evidence.local/',200,'text/plain',0,?,'')`, trafficID, len("cors proof body"))
if err != nil {
t.Fatal(err)
}
_, err = s.m.traffic.DB().Exec(`INSERT INTO exchange_bodies(id,req_head,resp_head,req_body,resp_body)
VALUES(?, ?, ?, ?, ?)`, trafficID,
"GET / HTTP/1.1\nOrigin: https://evil.com\n",
"HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: https://other.example\n",
[]byte{}, []byte("cors proof body"))
if err != nil {
t.Fatal(err)
}
bindPath := fmt.Sprintf("/api/exploration/findings/%d/traffic", finding.FindingID)
if w := request("POST", bindPath, fmt.Sprintf(`{"traffic_refs":[{"traffic_id":%q,"role":"proof"}]}`, trafficID)); w.Code != 200 {
t.Fatalf("bind: %d %s", w.Code, w.Body)
}
msg, isErr := updateReport(t, s, finding.NodeID, `,"poe_level":3,"evidence_quotes":["cors proof body"]`)
if isErr || !strings.Contains(msg, "verification: unverified") {
t.Fatalf("unexpected result: err=%v %q", isErr, msg)
}
status, _, note, report := storedVerification(t, s, finding.FindingID)
if status != db.VerificationUnverified || !strings.Contains(note, "CORS proof validation failed") || report == "" {
t.Fatalf("stored: status=%s note=%q report=%q", status, note, report)
}
}
+14
View File
@@ -138,6 +138,13 @@ func readBoundResponse(store *evidence.Store, snap db.TrafficEvidenceSnapshot) (
// its bound traffic and the quotes the agent supplied. poe is the declared POE
// level (0 when absent). It never returns "verified" unless every rule passes.
func (s *Server) assessFindingVerification(ctx context.Context, findingID int64, poe int, quotes []string) (status, note string) {
finding, err := s.m.pg.GetFinding(findingID)
if err != nil {
return db.VerificationNotAssessed, "finding read error: " + err.Error()
}
if finding == nil {
return db.VerificationNotAssessed, "finding not found"
}
tr, err := s.m.pg.GetFindingTraffic(ctx, findingID)
if err != nil {
return db.VerificationNotAssessed, "binding read error: " + err.Error()
@@ -151,6 +158,13 @@ func (s *Server) assessFindingVerification(ctx context.Context, findingID int64,
if len(proofs) == 0 {
return db.VerificationUnverified, "no proof traffic bound"
}
if db.IsCORSFinding(finding.VulnClass) {
for _, proof := range proofs {
if err := db.ValidateCORSProofHeads(proof.Snapshot.ReqHead, proof.Snapshot.RespHead); err != nil {
return db.VerificationUnverified, "CORS proof validation failed: " + err.Error()
}
}
}
if poe < verificationMinPOE {
return db.VerificationUnverified, fmt.Sprintf("POE L%d below L3", poe)
}
+30 -2
View File
@@ -10,6 +10,7 @@ import (
"strings"
"syscall"
"testing"
"time"
)
// isolationRootFixture is newExecRootFixture with the Bash shim installed, a key
@@ -73,9 +74,36 @@ func TestIsolationSelfTestDetectsReadableSecretAsRoot(t *testing.T) {
if err := os.Chmod(key, 0o644); err != nil {
t.Fatal(err)
}
var st syscall.Stat_t
if err := syscall.Stat(key, &st); err != nil {
t.Fatal(err)
}
err := IsolationSelfTest(f.priv, f.targets())
if err == nil || !strings.Contains(err.Error(), "Bash can read "+key) || !strings.Contains(err.Error(), "the file tools can read "+key) {
t.Fatalf("self-test with a world-readable key: %v", err)
if err == nil {
t.Fatal("self-test accepted a world-readable key")
}
for _, actor := range []string{"Bash", "the file tools"} {
if !strings.Contains(err.Error(), actor+" opened "+key+" for reading (mode=-rw-r--r-- uid=0 gid="+strconv.FormatUint(uint64(st.Gid), 10)+")") {
t.Errorf("self-test with a world-readable key did not report its metadata for %s: %v", actor, err)
}
}
}
func TestSecretOpenFailureOnFIFO(t *testing.T) {
path := filepath.Join(t.TempDir(), "key")
if err := syscall.Mkfifo(path, 0o600); err != nil {
t.Fatal(err)
}
// A FIFO with no writer must still be reported without waiting for bytes.
done := make(chan string, 1)
go func() { done <- secretOpenFailure("probe", path) }()
select {
case msg := <-done:
if !strings.Contains(msg, "opened "+path+" for reading (mode=p") {
t.Fatalf("unexpected FIFO diagnostic: %q", msg)
}
case <-time.After(5 * time.Second):
t.Fatal("probe blocked on a FIFO with no writer")
}
}
+29 -16
View File
@@ -258,30 +258,44 @@ func skillTreeFailures(root string, execUID, execGID uint32) []string {
return failures
}
// fileToolIsolationFailures opens each existing secret through the file tool
// identity (agent/filetools_identity.go): the open must be refused.
// secretOpenFailure checks the open under the caller's identity. Inspect the
// descriptor so the diagnostic describes the object at the time of the probe.
func secretOpenFailure(actor, path string) string {
f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOCTTY, 0)
if errors.Is(err, fs.ErrNotExist) || errors.Is(err, fs.ErrPermission) {
return ""
}
if err != nil {
return fmt.Sprintf("%s could not check %s: %v", actor, path, err)
}
defer f.Close()
msg := fmt.Sprintf("%s opened %s for reading", actor, path)
info, err := f.Stat()
if err != nil {
return fmt.Sprintf("%s (stat failed: %v)", msg, err)
}
if st, ok := info.Sys().(*syscall.Stat_t); ok {
return fmt.Sprintf("%s (mode=%s uid=%d gid=%d)", msg, info.Mode(), st.Uid, st.Gid)
}
return fmt.Sprintf("%s (mode=%s)", msg, info.Mode())
}
// fileToolIsolationFailures checks each secret through the file tool identity.
func fileToolIsolationFailures(secrets []string) []string {
if !agent.FileToolIdentitySupported() {
return []string{"the agent's file tools run with the server's identity on this platform"}
}
var failures []string
for _, path := range secrets {
if _, err := os.Stat(path); err != nil {
continue
}
var openErr error
var failure string
if err := agent.RunAsFileToolIdentity(func() {
f, err := os.Open(path)
if err == nil {
f.Close()
}
openErr = err
failure = secretOpenFailure("the file tools", path)
}); err != nil {
failures = append(failures, fmt.Sprintf("the file tool identity cannot be applied: %v", err))
break
}
if openErr == nil {
failures = append(failures, fmt.Sprintf("the file tools can read %s", path))
if failure != "" {
failures = append(failures, failure)
}
}
return failures
@@ -350,9 +364,8 @@ func checkIsolationAsExecutor(spec isolationProbeSpec) []string {
fail("Bash has the supplementary groups %v, want only the executor gid %d", groups, spec.GID)
}
for _, path := range spec.Unreadable {
if f, err := os.Open(path); err == nil {
f.Close()
fail("Bash can read %s", path)
if failure := secretOpenFailure("Bash", path); failure != "" {
failures = append(failures, failure)
}
}
if spec.ServerPID > 0 {
+21 -1
View File
@@ -97,7 +97,7 @@ func TestCheckIsolationReportsEachExposure(t *testing.T) {
})
for _, want := range []string{
"not the executor uid 10001",
"Bash can read " + secret,
"Bash opened " + secret + " for reading (mode=-rw-------",
"Bash can create files in " + dir,
"ARTEX_ISOLATION_CANARY reached Bash",
`database session as "artex"`,
@@ -114,6 +114,26 @@ func TestCheckIsolationReportsEachExposure(t *testing.T) {
}
}
func TestSecretOpenFailureReportsUnexpectedError(t *testing.T) {
link := filepath.Join(t.TempDir(), "key")
if err := os.Symlink(link, link); err != nil {
t.Fatal(err)
}
if msg := secretOpenFailure("probe", link); !strings.HasPrefix(msg, "probe could not check "+link) {
t.Fatalf("unexpected diagnostic for a symlink loop: %q", msg)
}
}
func TestSecretOpenFailureDetectsReadableKeyDir(t *testing.T) {
dir := filepath.Join(t.TempDir(), "keys")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if msg := secretOpenFailure("Bash", dir); !strings.Contains(msg, "Bash opened "+dir+" for reading (mode=d") {
t.Fatalf("unexpected diagnostic for readable key dir: %q", msg)
}
}
// A database that asks for a password, or none listening, is not an exposure.
func TestConnectWithoutPasswordRefused(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
+13
View File
@@ -6,6 +6,7 @@ import (
"log"
"time"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/mcphttp"
"github.com/Autumn-27/norma/mcp"
@@ -51,9 +52,21 @@ func connectMCP(ctx context.Context, m *db.MCPServer, priv ExecPrivilege) (mcpCl
}
}
// sandboxBlocksStdioMCP reports whether this stdio MCP must not run on the
// panel. In ARTEX_SANDBOX=required the panel never starts agent-controlled
// local processes: stdio MCP servers stay unavailable until the per-task
// runner hosts them. HTTP and SSE MCP clients are platform-owned transports and
// keep their existing checks.
func sandboxBlocksStdioMCP(m *db.MCPServer) bool {
return agent.SandboxRequired() && (m.Transport == "" || m.Transport == "stdio")
}
// discoverAndCacheMCP connects to one MCP, lists its tools, and persists the tool
// names to mcp_tools_cache so the UI shows them without a live connection.
func (s *Server) discoverAndCacheMCP(ctx context.Context, m *db.MCPServer) error {
if sandboxBlocksStdioMCP(m) {
return fmt.Errorf("stdio MCP servers are not started on the panel while ARTEX_SANDBOX=required; use an HTTP/SSE MCP server or set ARTEX_SANDBOX=off")
}
cl, err := connectMCP(ctx, m, s.execPriv)
if err != nil {
_ = s.m.pg.UpdateMCPHealth(m.ID, false, err.Error())
+69
View File
@@ -0,0 +1,69 @@
package server
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/sandbox"
)
func withSandboxRequired(t *testing.T) {
t.Helper()
prev := agent.CurrentSandboxExecutor()
agent.SetSandboxExecutor(&agent.SandboxExecutor{Mode: sandbox.ModeRequired})
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
}
// The panel must never start a stdio MCP process in required mode. The canary
// command would create a file if connectMCP reached it; the guard returns before
// the process is spawned.
func TestSandboxSkipsStdioMCPDiscovery(t *testing.T) {
withSandboxRequired(t)
dir := t.TempDir()
canary := filepath.Join(dir, "stdio-mcp-ran")
args, _ := json.Marshal([]string{"-c", "touch " + canary})
m := &db.MCPServer{Name: "t-sandbox-stdio", Transport: "stdio", Command: "sh", Args: args, Enabled: true}
s := &Server{}
err := s.discoverAndCacheMCP(context.Background(), m)
if err == nil || !strings.Contains(err.Error(), "ARTEX_SANDBOX=required") {
t.Fatalf("discovery error = %v, want the sandbox refusal", err)
}
if _, statErr := os.Stat(canary); statErr == nil {
t.Fatal("stdio MCP command ran on the panel in required mode")
}
}
func TestSandboxMCPToolGuardsStdioOnly(t *testing.T) {
withSandboxRequired(t)
for _, tc := range []struct {
transport string
blocked bool
}{
{"", true},
{"stdio", true},
{"http", false},
{"sse", false},
} {
if got := sandboxBlocksStdioMCP(&db.MCPServer{Transport: tc.transport}); got != tc.blocked {
t.Errorf("transport %q blocked=%v, want %v", tc.transport, got, tc.blocked)
}
}
}
func TestSandboxCreateMCPRejectsStdio(t *testing.T) {
withSandboxRequired(t)
tool := (&Server{}).toolCreateMCP()
res, err := tool.Call(context.Background(), json.RawMessage(`{"name":"t-stdio","transport":"stdio","command":"sh"}`), nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "ARTEX_SANDBOX=required") {
t.Fatalf("create_mcp result = %q, want the sandbox refusal", res.Flatten())
}
}
+6
View File
@@ -370,6 +370,9 @@ func (s *Server) toolCreateMCP() actool.CoreTool {
if strings.TrimSpace(a.Name) == "" || strings.TrimSpace(a.Transport) == "" {
return actool.Errorf("name / transport are required"), nil
}
if sandboxBlocksStdioMCP(a.toDB()) {
return actool.Errorf("stdio MCP servers are unavailable while ARTEX_SANDBOX=required; use an HTTP/SSE MCP server or set ARTEX_SANDBOX=off"), nil
}
id, err := s.m.pg.SaveMCP(a.toDB())
if err != nil {
return actool.Errorf(err.Error()), nil
@@ -387,6 +390,9 @@ func (s *Server) toolUpdateMCP() actool.CoreTool {
if a.ID == 0 {
return actool.Errorf("id is required"), nil
}
if sandboxBlocksStdioMCP(a.toDB()) {
return actool.Errorf("stdio MCP servers are unavailable while ARTEX_SANDBOX=required; use an HTTP/SSE MCP server or set ARTEX_SANDBOX=off"), nil
}
if _, err := s.m.pg.SaveMCP(a.toDB()); err != nil {
return actool.Errorf(err.Error()), nil
}