diff --git a/cmd/artex/main.go b/cmd/artex/main.go index c392799..19f9de6 100644 --- a/cmd/artex/main.go +++ b/cmd/artex/main.go @@ -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. diff --git a/dev.sh b/dev.sh old mode 100755 new mode 100644 index a76f881..6248a23 --- a/dev.sh +++ b/dev.sh @@ -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). diff --git a/docs/local-systemd-deployment.md b/docs/local-systemd-deployment.md index e98cd43..4c2adff 100644 --- a/docs/local-systemd-deployment.md +++ b/docs/local-systemd-deployment.md @@ -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 `` (`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 `` 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 ``, 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. diff --git a/server/isolation.go b/server/isolation.go index 3935377..ab5fd43 100644 --- a/server/isolation.go +++ b/server/isolation.go @@ -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) } } diff --git a/server/isolation_test.go b/server/isolation_test.go index 129b3af..46c1ec6 100644 --- a/server/isolation_test.go +++ b/server/isolation_test.go @@ -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()) } } diff --git a/server/server.go b/server/server.go index 241ad17..89b3e93 100644 --- a/server/server.go +++ b/server/server.go @@ -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 diff --git a/web/src/app/(main)/_components/main-content.tsx b/web/src/app/(main)/_components/main-content.tsx index 05bc8ed..fdf05cb 100644 --- a/web/src/app/(main)/_components/main-content.tsx +++ b/web/src/app/(main)/_components/main-content.tsx @@ -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(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 ? ( +
+ {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.", + )} +
+ ) : null; + const updateBanner = latest ? (
@@ -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}
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"),