server: start degraded where agent isolation cannot be built

The isolation self-test stopped every start it failed, so a non-root
server (the systemd unit), dev.sh, Windows and macOS no longer started
without -dev-insecure-no-isolation.

EnforceIsolation now decides from the platform and the privilege drop:

- self-test passed: isolated;
- Linux with the privilege drop on (root, the Docker image): a failure
  stops the start, unless -dev-insecure-no-isolation is set;
- elsewhere (not Linux, not root, -exec-uid=-1): the server starts
  degraded, without a flag.

A degraded start logs a banner with the self-test failure and what is
exposed, and GET /api/health reports the isolation status to a
signed-in caller; the web UI shows a red banner on every page while it
is degraded. The systemd deployment guide and dev.sh describe the mode.
This commit is contained in:
BaaRai
2026-11-22 09:50:09 +01:00
parent dd80fea140
commit f83659cd52
10 changed files with 196 additions and 46 deletions
+6 -4
View File
@@ -106,7 +106,7 @@ func run() int {
execUID = flag.Int("exec-uid", server.DefaultExecUID, "uid that agent processes run as (Bash, shell, custom tools, MCP stdio); -1 turns the drop off")
execGID = flag.Int("exec-gid", server.DefaultExecGID, "gid that agent processes run as")
// Development escape of the isolation self-test, off by default.
devNoIsolation = flag.Bool(server.DevNoIsolationFlag, false, "DEVELOPMENT ONLY: start even when the agent isolation self-test fails; agent processes and file tools may then read the server's keys, config and database credentials")
devNoIsolation = flag.Bool(server.DevNoIsolationFlag, false, "DEVELOPMENT ONLY: on Linux as root, start even when the agent isolation self-test fails; agent processes and file tools may then read the server's keys, config and database credentials")
)
flag.Parse()
@@ -190,11 +190,13 @@ func run() int {
return 1
}
// Before the stores open and any agent runs: check that the isolation above holds
// (server/isolation.go). A failure stops the start unless the escape is set.
// (server/isolation.go). On Linux as root a failure stops the start unless the
// escape is set; elsewhere the server starts degraded and says so.
selfTest := server.IsolationSelfTest(priv, server.IsolationTargets{
DataDir: *dataDir, KeyDir: keyDir, ConfigPath: cfgPath, SkillDir: skillDir, DSN: dsn,
})
if err := server.EnforceIsolation(selfTest, *devNoIsolation); err != nil {
isolation, err := server.EnforceIsolation(runtime.GOOS, priv, selfTest, *devNoIsolation)
if err != nil {
log.Printf("[config] %v", err)
return 1
}
@@ -210,7 +212,7 @@ func run() int {
}
defer mgr.Close()
srv := server.New(ctx, mgr, skillDir, *dataDir, keyDir, server.WithSecretScrub(), server.WithTrustedProxies(trusted), server.WithExecPrivilege(priv))
srv := server.New(ctx, mgr, skillDir, *dataDir, keyDir, server.WithSecretScrub(), server.WithTrustedProxies(trusted), server.WithExecPrivilege(priv), server.WithIsolationStatus(isolation))
// ReadTimeout bounds how long the request headers and body may take to arrive.
// It does not limit how long a handler runs, so an event stream stays open.
// WriteTimeout is left unset: a write deadline would cut that stream.
Executable → Regular
+4
View File
@@ -11,6 +11,10 @@ cleanup() { kill 0 2>/dev/null || true; }
trap cleanup EXIT INT TERM
# Backend (plain go run, frontend not embedded); the concurrent work agent count is configured under "System Settings".
# Run this script as your own user: the backend then starts with agent isolation degraded, which it logs in a
# banner and shows in the web UI (agents run as you and can read the keys, config and database credentials).
# Agent isolation needs Linux and a root server; use the Docker image for it. As root, a failed isolation
# self-test stops the start (server/isolation.go).
go run ./cmd/artex -addr :8787 -proxy 127.0.0.1:8788 &
# Frontend hot reload (Vite/Next dev server, /api reverse-proxied to :8787).
+9
View File
@@ -112,6 +112,15 @@ The unit runs `/opt/artex/artex` directly without an extra supervisor script. It
Because `docs/examples/artex.service` runs the server as the non-root `<artex-user>` (`User=artex`), the `-exec-uid`/`-exec-gid` privilege drop cannot be applied: `ResolveExecPrivilege` disables the drop when the server is not root (and errors if those flags are passed explicitly). The example unit deliberately omits `-exec-uid`/`-exec-gid`, so agents and spawned tools run under the `<artex-user>` service identity rather than a separate executor account. The root-owned run-directory layout and executor-group containment exist only when the server runs as root with explicit `-exec-uid`/`-exec-gid`; if you require unprivileged-executor containment, use the Docker deployment, which is the supported path for that isolation model.
At every start the server runs an agent isolation self-test before it opens its stores. Under this unit the self-test reports that the privilege drop is off, and the server starts in **degraded** isolation mode; no flag is needed and the unit needs no change. A degraded start:
- logs a banner that begins with `[isolation] !!!` and contains `AGENT ISOLATION IS DEGRADED` together with the self-test failure (see `journalctl -u artex.service`);
- shows a red banner on every page of the web UI (from the `isolation` field of `GET /api/health`, returned to signed-in users only).
In degraded mode agent shells, custom tools, MCP stdio servers and the file tools run as `<artex-user>`, which owns `config.json`, `keys/` and `data/`: they can read the JWT signing key, the secret key and the database password. Do not use this deployment on a server that holds real targets or credentials.
A Linux server that runs as root with the privilege drop on (the Docker image) is held to the self-test instead: when isolation is broken there, the server refuses to start. `-dev-insecure-no-isolation` lets it start degraded anyway, for development only. The same rule leaves Windows, macOS and `dev.sh` (run as your own user) in degraded mode, with the same banners.
## Web setup
On a new database, visit `http://127.0.0.1:8787/setup`, provide the one-time setup token from the private startup log or journal (`journalctl -u artex.service`), and choose a unique password of at least 12 characters. The username is `ARTEX`. Store the password in your password manager rather than in a plaintext file on disk.
+64 -24
View File
@@ -12,14 +12,42 @@ import (
// starts, and checks from inside it that it runs as the executor, cannot read the
// server's secrets or its process, sees only the allowlisted environment and cannot
// open a database session without the server's password; it also checks that the
// file tools cannot read the secrets. EnforceIsolation then decides the start: a
// failed or impossible self-test stops it, unless the development escape
// -dev-insecure-no-isolation is set, which is off by default and logs a warning
// banner that says what is exposed.
// file tools cannot read the secrets. EnforceIsolation then decides the start:
//
// - The self-test passes: the server starts isolated.
// - Linux with the privilege drop on (the server is root, as in the Docker image):
// isolation is expected there and the self-test shows it is broken, so the start
// stops. The development escape -dev-insecure-no-isolation, off by default, lets
// it go on degraded.
// - Anywhere else (not Linux, the server is not root, or -exec-uid=-1): isolation
// cannot be built on that host, so the server starts degraded without any flag.
// The systemd unit (non-root), dev.sh, Windows and macOS start as before.
//
// A degraded start logs a warning banner that says what is exposed, and reports the
// state in GET /api/health to a signed-in caller, which the web UI shows as a
// banner on every page.
// DevNoIsolationFlag is the command-line flag of the development escape.
const DevNoIsolationFlag = "dev-insecure-no-isolation"
// The isolation modes the server reports.
const (
IsolationIsolated = "isolated"
IsolationDegraded = "degraded"
)
// IsolationStatus is the agent isolation the server runs with.
type IsolationStatus struct {
Mode string `json:"mode"`
// Reason is the self-test failure of a degraded start.
Reason string `json:"reason,omitempty"`
}
// WithIsolationStatus records the result of EnforceIsolation for GET /api/health.
func WithIsolationStatus(st IsolationStatus) Option {
return func(s *Server) { s.isolation = st }
}
// IsolationTargets are the server's paths and database the self-test checks the
// executor cannot reach.
type IsolationTargets struct {
@@ -27,46 +55,58 @@ type IsolationTargets struct {
KeyDir string
ConfigPath string
SkillDir string
// DSN is the server's database DSN; only its host, port, user and database
// DSN is the server's database DSN; only its hosts, ports, user and database
// name reach the probe, never its password.
DSN string
}
// EnforceIsolation decides the start from the self-test result. A nil result
// passes. A failure stops the start with an error, unless devEscape is set: the
// warning banner is then logged and the start goes on.
func EnforceIsolation(selfTest error, devEscape bool) error {
// EnforceIsolation decides the start from the self-test result, the platform goos
// and the privilege drop p (see the rules above). It returns the status to report,
// or an error when the start must stop.
func EnforceIsolation(goos string, p ExecPrivilege, selfTest error, devEscape bool) (IsolationStatus, error) {
if selfTest == nil {
log.Printf("[isolation] self-test passed: agent processes and file tools run as the executor and cannot reach the server's secrets")
if devEscape {
log.Printf("[isolation] -%s is set and not needed: the self-test passed", DevNoIsolationFlag)
}
return nil
return IsolationStatus{Mode: IsolationIsolated}, nil
}
if !devEscape {
return fmt.Errorf("agent isolation self-test failed: %v. The server does not start without agent isolation: fix the cause above (run the server as root with -exec-uid, the Docker default), or pass -%s for development only", selfTest, DevNoIsolationFlag)
if isolationRequired(goos, p) && !devEscape {
return IsolationStatus{}, fmt.Errorf("agent isolation self-test failed: %v. A Linux server running as root with the privilege drop does not start without agent isolation: fix the cause above, or pass -%s for development only", selfTest, DevNoIsolationFlag)
}
logNoIsolationBanner(selfTest)
return nil
logDegradedBanner(selfTest, isolationRequired(goos, p))
return IsolationStatus{Mode: IsolationDegraded, Reason: selfTest.Error()}, nil
}
// noIsolationBanner is the warning the development escape logs at every start.
func noIsolationBanner(cause error) []string {
// isolationRequired reports whether the host can isolate agents, so that a failed
// self-test means broken isolation: Linux, with the privilege drop on (root).
func isolationRequired(goos string, p ExecPrivilege) bool {
return goos == "linux" && p.Enabled
}
// degradedBanner is the warning a degraded start logs. escaped is set when the start
// went on only through the development escape.
func degradedBanner(cause error, escaped bool) []string {
bar := strings.Repeat("!", 78)
return []string{
bar,
"!! AGENT ISOLATION IS OFF: -" + DevNoIsolationFlag + " is set. DEVELOPMENT ONLY.",
"!! Self-test failure: " + cause.Error(),
why := "!! This host cannot isolate agents: that needs Linux and a root server with the" +
"\n!! privilege drop (-exec-uid), as in the Docker image."
if escaped {
why = "!! -" + DevNoIsolationFlag + " is set. DEVELOPMENT ONLY."
}
lines := []string{bar, "!! AGENT ISOLATION IS DEGRADED."}
lines = append(lines, strings.Split(why, "\n")...)
return append(lines,
"!! Self-test failure: "+cause.Error(),
"!! Agent shells, custom tools, MCP stdio servers and the file tools may read the",
"!! server's keys (JWT signing key, secret key), its config, its database",
"!! credentials and its process, and may change skills and tools on disk.",
"!! Do not use this flag on a server that holds real targets or credentials.",
"!! Do not use this mode on a server that holds real targets or credentials.",
bar,
}
)
}
func logNoIsolationBanner(cause error) {
for _, line := range noIsolationBanner(cause) {
func logDegradedBanner(cause error, escaped bool) {
for _, line := range degradedBanner(cause, escaped) {
log.Print("[isolation] " + line)
}
}
+77 -16
View File
@@ -2,8 +2,10 @@ package server
import (
"bytes"
"encoding/json"
"errors"
"log"
"net/http/httptest"
"strings"
"testing"
)
@@ -20,35 +22,94 @@ func captureLog(t *testing.T, fn func()) string {
return buf.String()
}
// A failed self-test stops the start; the escape, off by default, lets it go on
// with the warning banner; a passing self-test starts either way.
// The start decision, branch by branch.
func TestEnforceIsolation(t *testing.T) {
cause := errors.New("Bash runs as uid 0, not the executor uid 10001")
root := ExecPrivilege{Enabled: true, UID: 10001, GID: 10001} // drop on: the server is root
off := ExecPrivilege{} // not root, or -exec-uid=-1
const banner = "AGENT ISOLATION IS DEGRADED"
var err error
out := captureLog(t, func() { err = EnforceIsolation(cause, false) })
var (
st IsolationStatus
err error
)
// Hard failure: Linux, root, self-test failed, no escape. No banner: no start.
out := captureLog(t, func() { st, err = EnforceIsolation("linux", root, cause, false) })
if err == nil || !strings.Contains(err.Error(), cause.Error()) || !strings.Contains(err.Error(), "-"+DevNoIsolationFlag) {
t.Fatalf("without the escape: err = %v, want the cause and the flag named", err)
t.Fatalf("linux root: err = %v, want the cause and the flag named", err)
}
if strings.Contains(out, "AGENT ISOLATION IS OFF") {
t.Fatalf("the banner belongs to the escape only:\n%s", out)
if st.Mode != "" || strings.Contains(out, banner) {
t.Fatalf("linux root: status %+v, banner in\n%s", st, out)
}
out = captureLog(t, func() { err = EnforceIsolation(cause, true) })
if err != nil {
t.Fatalf("with the escape the start goes on: %v", err)
// Linux, root, with the development escape: degraded, banner names the flag.
out = captureLog(t, func() { st, err = EnforceIsolation("linux", root, cause, true) })
if err != nil || st.Mode != IsolationDegraded || st.Reason != cause.Error() {
t.Fatalf("linux root with the escape: status %+v err %v, want degraded", st, err)
}
for _, want := range []string{"AGENT ISOLATION IS OFF", "-" + DevNoIsolationFlag, "DEVELOPMENT ONLY", cause.Error(), "keys", "database"} {
for _, want := range []string{banner, "-" + DevNoIsolationFlag, "DEVELOPMENT ONLY", cause.Error(), "keys", "database"} {
if !strings.Contains(out, want) {
t.Errorf("banner lacks %q:\n%s", want, out)
t.Errorf("escape banner lacks %q:\n%s", want, out)
}
}
for _, escape := range []bool{false, true} {
out = captureLog(t, func() { err = EnforceIsolation(nil, escape) })
if err != nil || !strings.Contains(out, "self-test passed") || strings.Contains(out, "AGENT ISOLATION IS OFF") {
t.Fatalf("passing self-test (escape %v): err=%v\n%s", escape, err, out)
// Degraded without any flag: Linux not root (the systemd unit, dev.sh), Windows,
// macOS (root or not). The banner says why and what is exposed.
for _, c := range []struct {
goos string
p ExecPrivilege
}{{"linux", off}, {"windows", off}, {"darwin", off}, {"darwin", root}} {
out = captureLog(t, func() { st, err = EnforceIsolation(c.goos, c.p, cause, false) })
if err != nil || st.Mode != IsolationDegraded || st.Reason != cause.Error() {
t.Fatalf("%s drop=%v: status %+v err %v, want a degraded start", c.goos, c.p.Enabled, st, err)
}
for _, want := range []string{banner, "cannot isolate agents", cause.Error(), "keys", "database"} {
if !strings.Contains(out, want) {
t.Errorf("%s drop=%v: banner lacks %q:\n%s", c.goos, c.p.Enabled, want, out)
}
}
if strings.Contains(out, "DEVELOPMENT ONLY") {
t.Errorf("%s drop=%v: the degraded banner is not the escape's:\n%s", c.goos, c.p.Enabled, out)
}
}
// A passing self-test starts isolated, escape or not, without a banner.
for _, escape := range []bool{false, true} {
out = captureLog(t, func() { st, err = EnforceIsolation("linux", root, nil, escape) })
if err != nil || st.Mode != IsolationIsolated || !strings.Contains(out, "self-test passed") || strings.Contains(out, banner) {
t.Fatalf("passing self-test (escape %v): status %+v err=%v\n%s", escape, st, err, out)
}
}
}
// GET /api/health reports the isolation status to a signed-in caller only: the web
// UI shows the degraded banner from it.
func TestHealthReportsIsolation(t *testing.T) {
key := []byte("0123456789abcdef0123456789abcdef")
s := &Server{jwtKey: key}
WithIsolationStatus(IsolationStatus{Mode: IsolationDegraded, Reason: "the server is not root"})(s)
w := httptest.NewRecorder()
s.health(w, httptest.NewRequest("GET", "/api/health", nil))
if got := strings.TrimSpace(w.Body.String()); got != `{"ok":true}` {
t.Fatalf("no token: %s, want no isolation status", got)
}
tok, err := signJWT(key)
if err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("GET", "/api/health", nil)
r.Header.Set("Authorization", "Bearer "+tok)
w = httptest.NewRecorder()
s.health(w, r)
var body struct {
Isolation *IsolationStatus `json:"isolation"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Isolation == nil ||
body.Isolation.Mode != IsolationDegraded || body.Isolation.Reason != "the server is not root" {
t.Fatalf("signed in: %s, want the degraded status", w.Body.String())
}
}
+6 -1
View File
@@ -54,7 +54,8 @@ type Server struct {
scrubSecrets bool // drop ARTEX_PG_DSN and the API keys from the environment once read (binary only)
execPriv ExecPrivilege // identity agent processes run under; zero keeps the server's own
execPriv ExecPrivilege // identity agent processes run under; zero keeps the server's own
isolation IsolationStatus // result of the startup isolation self-test (isolation.go); zero when not run
setupMu sync.Mutex
setupToken string // one-time token POST /api/auth/init requires; empty when none is active
@@ -1101,6 +1102,10 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) {
return
}
out := map[string]any{"ok": true, "service": "artex", "version": BuildVersion}
// The web UI shows a banner on every page for a degraded isolation (isolation.go).
if s.isolation.Mode != "" {
out["isolation"] = s.isolation
}
// Opt-in only (ARTEX_UPDATE_CHECK); off, this returns "" without any request.
if latest := updates.newerVersion(r.Context(), time.Now(), BuildVersion); latest != "" {
out["latest_version"] = latest
@@ -43,6 +43,8 @@ export function MainContent({ children }: { children: ReactNode }) {
const [version, setVersion] = useState("");
// Only set when the backend has the opt-in update check on (ARTEX_UPDATE_CHECK) and found a newer release.
const [latest, setLatest] = useState("");
// Set when the server started with agent isolation degraded (server/isolation.go): the self-test failure.
const [degraded, setDegraded] = useState<string | null>(null);
useEffect(() => {
api
@@ -51,10 +53,25 @@ export function MainContent({ children }: { children: ReactNode }) {
setVersion((h.version ?? "").replace(/^v(?=\d)/, ""));
const l = h.latest_version ?? "";
setLatest(l && getLocalStorageValue(UPDATE_DISMISSED_KEY) !== l ? l : "");
setDegraded(h.isolation?.mode === "degraded" ? (h.isolation.reason ?? "") : null);
})
.catch(() => setVersion(""));
}, []);
// Not dismissible: it stays as long as the server runs without agent isolation.
const isolationBanner =
degraded !== null ? (
<div
role="alert"
title={degraded}
className="flex shrink-0 items-center justify-center gap-2 border-b border-destructive/40 bg-destructive/10 px-4 py-1 text-destructive text-xs"
>
{t(
"Agent isolation is degraded: agent shells, tools and file tools run with the server's identity and may read its keys, config and database credentials.",
)}
</div>
) : null;
const updateBanner = latest ? (
<div className="flex shrink-0 items-center justify-center gap-2 border-b bg-muted/50 px-4 py-1 text-xs">
<a href={RELEASES_URL} target="_blank" rel="noreferrer" className="underline-offset-2 hover:underline">
@@ -77,6 +94,7 @@ export function MainContent({ children }: { children: ReactNode }) {
if (isFullBleed(pathname)) {
return (
<>
{isolationBanner}
{updateBanner}
{children}
</>
@@ -85,6 +103,7 @@ export function MainContent({ children }: { children: ReactNode }) {
return (
<>
{isolationBanner}
{updateBanner}
<header
className={cn(
+1
View File
@@ -214,6 +214,7 @@
"Agent": "Ajan",
"Agent \"{name}\" created": "\"{name}\" ajanı oluşturuldu",
"Agent \"{name}\" deleted": "\"{name}\" ajanı silindi",
"Agent isolation is degraded: agent shells, tools and file tools run with the server's identity and may read its keys, config and database credentials.": "Ajan yalıtımı düşürüldü: ajan kabukları, araçları ve dosya araçları sunucunun kimliğiyle çalışıyor ve anahtarlarını, yapılandırmasını ve veritabanı kimlik bilgilerini okuyabilir.",
"Agent is replying; type /btw to ask a side question…": "Ajan yanıt veriyor; yan soru sormak için /btw yazın…",
"Agent is running": "Ajan çalışıyor",
"Agent list": "Ajan listesi",
+1
View File
@@ -214,6 +214,7 @@
"Agent": "智能体",
"Agent \"{name}\" created": "已创建智能体“{name}”",
"Agent \"{name}\" deleted": "已删除智能体“{name}”",
"Agent isolation is degraded: agent shells, tools and file tools run with the server's identity and may read its keys, config and database credentials.": "Agent 隔离已降级:Agent 的 shell、工具和文件工具以服务器身份运行,可能读取其密钥、配置和数据库凭据。",
"Agent is replying; type /btw to ask a side question…": "Agent 正在回复,可输入 /btw 提问…",
"Agent is running": "Agent 正在运行",
"Agent list": "Agent 清单",
+9 -1
View File
@@ -271,7 +271,15 @@ function interceptPageQuery(page: number, size: number, filter: InterceptApprova
export const api = {
// Backend application version (injected via ldflags at release, default "dev").
health: () => get<{ ok: boolean; service: string; version: string; latest_version?: string }>("/health"),
// isolation: result of the startup agent isolation self-test; "degraded" shows a banner on every page.
health: () =>
get<{
ok: boolean;
service: string;
version: string;
latest_version?: string;
isolation?: { mode: "isolated" | "degraded"; reason?: string };
}>("/health"),
// ---- auth ----
authStatus: () => get<{ initialized: boolean }>("/auth/status"),