diff --git a/cmd/artex/main.go b/cmd/artex/main.go index c35a3f9..c392799 100644 --- a/cmd/artex/main.go +++ b/cmd/artex/main.go @@ -105,6 +105,8 @@ func run() int { // A negative uid turns the drop off; 0 (root) is refused. 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") ) flag.Parse() @@ -187,6 +189,15 @@ func run() int { log.Printf("[config] %v", err) 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. + selfTest := server.IsolationSelfTest(priv, server.IsolationTargets{ + DataDir: *dataDir, KeyDir: keyDir, ConfigPath: cfgPath, SkillDir: skillDir, DSN: dsn, + }) + if err := server.EnforceIsolation(selfTest, *devNoIsolation); err != nil { + log.Printf("[config] %v", err) + return 1 + } sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() diff --git a/server/execpriv_unix.go b/server/execpriv_unix.go index c23334c..9c6d730 100644 --- a/server/execpriv_unix.go +++ b/server/execpriv_unix.go @@ -583,7 +583,8 @@ func InstallBashShim(p ExecPrivilege) error { // RunExecShimIfRequested makes the process a privilege-drop shim when it was started // as one: as bash through the PATH shim, or as artex __artex-exec-drop for an MCP -// stdio command. It exits or execs the target; it returns only for an ordinary start. +// stdio command; or the isolation self-test probe (isolation_unix.go). It exits or +// execs the target; it returns only for an ordinary start. func RunExecShimIfRequested(argv []string) { if len(argv) == 0 { return @@ -594,6 +595,9 @@ func RunExecShimIfRequested(argv []string) { if len(argv) >= 2 && argv[1] == execDropArg { runDropShim(argv[2:]) } + if len(argv) >= 2 && argv[1] == isolationProbeArg { + runIsolationProbeMain() + } } func runBashShim(argv []string) { diff --git a/server/isolation.go b/server/isolation.go new file mode 100644 index 0000000..3935377 --- /dev/null +++ b/server/isolation.go @@ -0,0 +1,72 @@ +package server + +import ( + "fmt" + "log" + "strings" +) + +// Startup self-test of agent isolation. Before the stores open, the server checks +// that what an agent can run really is isolated from it: IsolationSelfTest +// (isolation_unix.go) starts a probe through the Bash shim, the way the agent's Bash +// 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. + +// DevNoIsolationFlag is the command-line flag of the development escape. +const DevNoIsolationFlag = "dev-insecure-no-isolation" + +// IsolationTargets are the server's paths and database the self-test checks the +// executor cannot reach. +type IsolationTargets struct { + DataDir string + KeyDir string + ConfigPath string + SkillDir string + // DSN is the server's database DSN; only its host, port, 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 { + 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 + } + 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) + } + logNoIsolationBanner(selfTest) + return nil +} + +// noIsolationBanner is the warning the development escape logs at every start. +func noIsolationBanner(cause error) []string { + bar := strings.Repeat("!", 78) + return []string{ + bar, + "!! AGENT ISOLATION IS OFF: -" + DevNoIsolationFlag + " is set. DEVELOPMENT ONLY.", + "!! 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.", + bar, + } +} + +func logNoIsolationBanner(cause error) { + for _, line := range noIsolationBanner(cause) { + log.Print("[isolation] " + line) + } +} diff --git a/server/isolation_other.go b/server/isolation_other.go new file mode 100644 index 0000000..0fe6105 --- /dev/null +++ b/server/isolation_other.go @@ -0,0 +1,9 @@ +//go:build !unix + +package server + +// IsolationSelfTest fails: agent processes cannot run as another identity on this +// platform, so they are never isolated from the server. +func IsolationSelfTest(p ExecPrivilege, t IsolationTargets) error { + return errExecUnsupported +} diff --git a/server/isolation_root_linux_test.go b/server/isolation_root_linux_test.go new file mode 100644 index 0000000..04c751c --- /dev/null +++ b/server/isolation_root_linux_test.go @@ -0,0 +1,101 @@ +//go:build linux + +package server + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "testing" +) + +// isolationRootFixture is newExecRootFixture with the Bash shim installed, a key +// directory like /app/keys (0700, jwt.key and secret.key 0600) and a 0600 config. +type isolationRootFixture struct { + *execRootFixture + keyDir, config string +} + +func newIsolationRootFixture(t *testing.T) *isolationRootFixture { + t.Helper() + f := newExecRootFixture(t) // skips without root + if err := InstallBashShim(f.priv); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(filepath.SplitList(os.Getenv("PATH"))[0]) }) + keyDir := filepath.Join(f.data, "..", filepath.Base(f.data)+"-keys") + if err := os.Mkdir(keyDir, 0o700); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(keyDir) }) + for _, name := range []string{"jwt.key", "secret.key"} { + if err := os.WriteFile(filepath.Join(keyDir, name), []byte("key-"+name), 0o600); err != nil { + t.Fatal(err) + } + } + config := filepath.Join(keyDir, "..", filepath.Base(f.data)+"-config.json") + if err := os.WriteFile(config, []byte(`{"database":{"dsn":"postgres://u:pw@h/db"}}`), 0o600); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Remove(config) }) + return &isolationRootFixture{execRootFixture: f, keyDir: keyDir, config: config} +} + +func (f *isolationRootFixture) targets() IsolationTargets { + return IsolationTargets{DataDir: f.data, KeyDir: f.keyDir, ConfigPath: f.config, DSN: os.Getenv("ARTEX_PG_DSN")} +} + +// The deployment the self-test is for: root server, executor drop, shim, root-only +// keys and config. It passes, through the real Bash shim, and with ARTEX_PG_DSN set +// it also finds that the executor cannot open a session on that database without +// the password (PostgreSQL asks for one on TCP). +func TestIsolationSelfTestPassesAsRoot(t *testing.T) { + f := newIsolationRootFixture(t) + if os.Getenv("ARTEX_PG_DSN") == "" { + t.Log("ARTEX_PG_DSN unset: the database check is not exercised") + } + if err := IsolationSelfTest(f.priv, f.targets()); err != nil { + t.Fatalf("self-test on an isolated setup: %v", err) + } +} + +// A secret the executor can read fails the self-test, for the Bash path and the +// file tool path both. +func TestIsolationSelfTestDetectsReadableSecretAsRoot(t *testing.T) { + f := newIsolationRootFixture(t) + key := filepath.Join(f.keyDir, "jwt.key") + if err := os.Chmod(f.keyDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Chmod(key, 0o644); 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) + } +} + +// Without the shim on PATH, "bash" is the real bash and runs as root: the self-test +// sees it. +func TestIsolationSelfTestDetectsMissingShimAsRoot(t *testing.T) { + f := newExecRootFixture(t) + err := IsolationSelfTest(f.priv, IsolationTargets{DataDir: f.data}) + if err == nil || !strings.Contains(err.Error(), "Bash runs as uid 0") { + t.Fatalf("self-test without the Bash shim: %v", err) + } +} + +// A database that lets the server's user in without a password fails the self-test: +// the probe, as the executor, opens a session on it. +func TestIsolationSelfTestDetectsPasswordlessDatabaseAsRoot(t *testing.T) { + f := newIsolationRootFixture(t) + host, port := fakeTrustPG(t) + tg := f.targets() + tg.DSN = "postgres://artex:server-password@" + host + ":" + strconv.Itoa(int(port)) + "/artex" + err := IsolationSelfTest(f.priv, tg) + if err == nil || !strings.Contains(err.Error(), `database session as "artex"`) { + t.Fatalf("self-test against a passwordless database: %v", err) + } +} diff --git a/server/isolation_test.go b/server/isolation_test.go new file mode 100644 index 0000000..129b3af --- /dev/null +++ b/server/isolation_test.go @@ -0,0 +1,61 @@ +package server + +import ( + "bytes" + "errors" + "log" + "strings" + "testing" +) + +// captureLog collects what the standard logger writes while fn runs. +func captureLog(t *testing.T, fn func()) string { + t.Helper() + var buf bytes.Buffer + prev, flags := log.Writer(), log.Flags() + log.SetOutput(&buf) + log.SetFlags(0) + defer func() { log.SetOutput(prev); log.SetFlags(flags) }() + fn() + 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. +func TestEnforceIsolation(t *testing.T) { + cause := errors.New("Bash runs as uid 0, not the executor uid 10001") + + var err error + out := captureLog(t, func() { err = EnforceIsolation(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) + } + if strings.Contains(out, "AGENT ISOLATION IS OFF") { + t.Fatalf("the banner belongs to the escape only:\n%s", out) + } + + out = captureLog(t, func() { err = EnforceIsolation(cause, true) }) + if err != nil { + t.Fatalf("with the escape the start goes on: %v", err) + } + for _, want := range []string{"AGENT ISOLATION IS OFF", "-" + DevNoIsolationFlag, "DEVELOPMENT ONLY", cause.Error(), "keys", "database"} { + if !strings.Contains(out, want) { + t.Errorf("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) + } + } +} + +// With the drop disabled (the server is not root, -exec-uid=-1, or no credentials +// on this platform) the self-test reports isolation as unavailable. +func TestIsolationSelfTestUnavailableWithoutDrop(t *testing.T) { + if err := IsolationSelfTest(ExecPrivilege{}, IsolationTargets{}); err == nil { + t.Fatal("a disabled drop must fail the self-test") + } +} diff --git a/server/isolation_unix.go b/server/isolation_unix.go new file mode 100644 index 0000000..1fc90c3 --- /dev/null +++ b/server/isolation_unix.go @@ -0,0 +1,251 @@ +//go:build unix + +package server + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/jackc/pgx/v5" + + "github.com/Autumn-27/artex/agent" +) + +// isolationProbeArg is the argv marker of the self-test probe: +// artex __artex-isolation-probe, with an isolationProbeSpec on stdin. +const isolationProbeArg = "__artex-isolation-probe" + +// isolationProbeTimeout bounds the probe, database attempt included. +const isolationProbeTimeout = 30 * time.Second + +// isolationProbeSpec is what the probe checks from inside an executor process. +type isolationProbeSpec struct { + UID uint32 `json:"uid"` + GID uint32 `json:"gid"` + ServerPID int `json:"server_pid"` + // Unreadable are files no agent process may open for reading. + Unreadable []string `json:"unreadable,omitempty"` + // Unwritable are directories no agent process may create an entry in. + Unwritable []string `json:"unwritable,omitempty"` + // DB names the server's database; the probe connects without a password. + DB *isolationProbeDB `json:"db,omitempty"` +} + +type isolationProbeDB struct { + Host string `json:"host"` + Port uint16 `json:"port"` + User string `json:"user"` + Database string `json:"database"` +} + +// isolationProbeReport is the probe's answer on stdout. +type isolationProbeReport struct { + Failures []string `json:"failures"` +} + +// IsolationSelfTest checks that agent processes and file tools are isolated from +// the server. It returns nil when every check passes, otherwise an error that names +// each failure. With the privilege drop disabled there is nothing to test: agent +// processes run as the server, and that is reported as the failure. +func IsolationSelfTest(p ExecPrivilege, t IsolationTargets) error { + if !p.Enabled { + return errors.New("agent processes run with the server's identity: the privilege drop is off (the server is not root, or -exec-uid is negative)") + } + spec := isolationSpec(p, t) + failures := fileToolIsolationFailures(spec.Unreadable) + rep, err := runIsolationProbe(spec) + if err != nil { + failures = append(failures, fmt.Sprintf("the probe did not run through the Bash shim: %v", err)) + } else { + failures = append(failures, rep.Failures...) + } + if len(failures) > 0 { + return errors.New(strings.Join(failures, "; ")) + } + return nil +} + +// isolationSpec builds the probe's checks from the server's paths. +func isolationSpec(p ExecPrivilege, t IsolationTargets) isolationProbeSpec { + spec := isolationProbeSpec{UID: p.UID, GID: p.GID, ServerPID: os.Getpid()} + if t.KeyDir != "" { + spec.Unreadable = append(spec.Unreadable, filepath.Join(t.KeyDir, "jwt.key"), filepath.Join(t.KeyDir, "secret.key")) + } + if t.ConfigPath != "" { + spec.Unreadable = append(spec.Unreadable, t.ConfigPath) + } + if t.DataDir != "" { + spec.Unreadable = append(spec.Unreadable, filepath.Join(t.DataDir, "traffic", "_ca", "mitmproxy-ca.pem")) + } + if t.DSN != "" { + if cfg, err := pgx.ParseConfig(t.DSN); err == nil { + spec.DB = &isolationProbeDB{Host: cfg.Host, Port: cfg.Port, User: cfg.User, Database: cfg.Database} + } + } + return spec +} + +// fileToolIsolationFailures opens each existing secret through the file tool +// identity (agent/filetools_identity.go): the open must be refused. +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 + if err := agent.RunAsFileToolIdentity(func() { + f, err := os.Open(path) + if err == nil { + f.Close() + } + openErr = err + }); 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)) + } + } + return failures +} + +// runIsolationProbe starts the probe the way the agent's Bash starts: "bash" looked +// up on PATH, where InstallBashShim put the shim that drops to the executor. bash +// then execs this binary as the probe, which gets the spec on stdin. +func runIsolationProbe(spec isolationProbeSpec) (isolationProbeReport, error) { + var rep isolationProbeReport + self, err := os.Executable() + if err != nil { + return rep, err + } + in, err := json.Marshal(spec) + if err != nil { + return rep, err + } + ctx, cancel := context.WithTimeout(context.Background(), isolationProbeTimeout) + defer cancel() + c := exec.CommandContext(ctx, "bash", "-c", `exec "$0" `+isolationProbeArg, self) + c.Dir = "/" + c.Stdin = bytes.NewReader(in) + var stderr bytes.Buffer + c.Stderr = &stderr + out, err := c.Output() + if err != nil { + return rep, fmt.Errorf("%v: %s", err, strings.TrimSpace(stderr.String())) + } + if err := json.Unmarshal(out, &rep); err != nil { + return rep, fmt.Errorf("unreadable probe report %q: %v", out, err) + } + return rep, nil +} + +// runIsolationProbeMain is the probe process: it reads the spec, checks, writes +// the report and exits. +func runIsolationProbeMain() { + var spec isolationProbeSpec + rep := isolationProbeReport{Failures: []string{}} + if err := json.NewDecoder(os.Stdin).Decode(&spec); err != nil { + rep.Failures = append(rep.Failures, fmt.Sprintf("probe: bad spec: %v", err)) + } else { + rep.Failures = append(rep.Failures, checkIsolationAsExecutor(spec)...) + } + _ = json.NewEncoder(os.Stdout).Encode(rep) + os.Exit(0) +} + +// bashOwnEnv are the variables bash itself exports to the programs it starts. +var bashOwnEnv = nameSet("PWD", "OLDPWD", "SHLVL", "_") + +// checkIsolationAsExecutor runs the checks of spec in the calling process and +// returns what failed. +func checkIsolationAsExecutor(spec isolationProbeSpec) []string { + var failures []string + fail := func(format string, args ...any) { failures = append(failures, fmt.Sprintf(format, args...)) } + + if uid, euid := os.Getuid(), os.Geteuid(); uid != int(spec.UID) || euid != int(spec.UID) { + fail("Bash runs as uid %d (effective %d), not the executor uid %d", uid, euid, spec.UID) + } + if gid := os.Getgid(); gid != int(spec.GID) { + fail("Bash runs as gid %d, not the executor gid %d", gid, spec.GID) + } + if groups, err := os.Getgroups(); err != nil || len(groups) != 1 || groups[0] != int(spec.GID) { + 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 spec.ServerPID > 0 { + if _, err := os.Stat("/proc/self"); err == nil { + for _, name := range []string{"environ", "mem"} { + path := "/proc/" + strconv.Itoa(spec.ServerPID) + "/" + name + if f, err := os.Open(path); err == nil { + f.Close() + fail("Bash can read the server's %s", path) + } + } + } + } + for _, dir := range spec.Unwritable { + if f, err := os.CreateTemp(dir, ".artex-isolation-probe-*"); err == nil { + name := f.Name() + f.Close() + os.Remove(name) + fail("Bash can create files in %s", dir) + } else if !errors.Is(err, fs.ErrPermission) && !errors.Is(err, fs.ErrNotExist) { + fail("Bash write check of %s: %v", dir, err) + } + } + for _, kv := range os.Environ() { + name, _, _ := strings.Cut(kv, "=") + if !executorEnvAllowed(name) && !bashOwnEnv[name] { + fail("the variable %s reached Bash: it is not on the agent environment allowlist", name) + } + } + if spec.DB != nil { + if err := connectWithoutPassword(spec.DB); err == nil { + fail("Bash opened a database session as %q on %s without the server's password", spec.DB.User, spec.DB.Host) + } + } + return failures +} + +// connectWithoutPassword tries a session on the server's database with its user +// and no password. nil means the database let the executor in. +// The default sslmode (prefer) is kept: TLS first, then plain, as a client in the +// agent's shell would try. +func connectWithoutPassword(db *isolationProbeDB) error { + quote := strings.NewReplacer(`\`, `\\`, `'`, `\'`).Replace + dsn := fmt.Sprintf("host='%s' port=%d user='%s' dbname='%s' connect_timeout=5", + quote(db.Host), db.Port, quote(db.User), quote(db.Database)) + cfg, err := pgx.ParseConfig(dsn) + if err != nil { + return err + } + cfg.Password = "" // not even one from a password file in the executor's home + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn, err := pgx.ConnectConfig(ctx, cfg) + if err != nil { + return err + } + conn.Close(context.Background()) + return nil +} diff --git a/server/isolation_unix_test.go b/server/isolation_unix_test.go new file mode 100644 index 0000000..579581b --- /dev/null +++ b/server/isolation_unix_test.go @@ -0,0 +1,170 @@ +//go:build unix + +package server + +import ( + "errors" + "net" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgproto3" +) + +// fakeTrustPG is a PostgreSQL wire endpoint that lets any user in without a +// password, like a server with trust authentication. It returns its address. +func fakeTrustPG(t *testing.T) (host string, port uint16) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go func(conn net.Conn) { + defer conn.Close() + be := pgproto3.NewBackend(conn, conn) + msg, err := be.ReceiveStartupMessage() + for err == nil { + switch msg.(type) { + case *pgproto3.SSLRequest, *pgproto3.GSSEncRequest: + if _, err = conn.Write([]byte("N")); err == nil { + msg, err = be.ReceiveStartupMessage() + } + continue + } + break + } + if err != nil { + return + } + be.Send(&pgproto3.AuthenticationOk{}) + be.Send(&pgproto3.ParameterStatus{Name: "server_version", Value: "16.0"}) + be.Send(&pgproto3.BackendKeyData{ProcessID: 1, SecretKey: []byte{0, 0, 0, 2}}) + be.Send(&pgproto3.ReadyForQuery{TxStatus: 'I'}) + if be.Flush() != nil { + return + } + for { + if _, err := be.Receive(); err != nil { + return + } + } + }(conn) + } + }() + addr := ln.Addr().(*net.TCPAddr) + return addr.IP.String(), uint16(addr.Port) +} + +func hasFailure(failures []string, sub string) bool { + for _, f := range failures { + if strings.Contains(f, sub) { + return true + } + } + return false +} + +// The probe's checks, run in the test process (not as the executor): each kind of +// exposure is reported. The process can read the file, write the directory, carries +// a variable outside the allowlist, is not the executor and reaches a database that +// takes no password. +func TestCheckIsolationReportsEachExposure(t *testing.T) { + dir := t.TempDir() + secret := filepath.Join(dir, "jwt.key") + if err := os.WriteFile(secret, []byte("k"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("ARTEX_ISOLATION_CANARY", "canary") + host, port := fakeTrustPG(t) + failures := checkIsolationAsExecutor(isolationProbeSpec{ + UID: 10001, GID: 10001, ServerPID: os.Getpid(), + Unreadable: []string{secret, filepath.Join(dir, "absent.key")}, + Unwritable: []string{dir}, + DB: &isolationProbeDB{Host: host, Port: port, User: "artex", Database: "artex"}, + }) + for _, want := range []string{ + "not the executor uid 10001", + "Bash can read " + secret, + "Bash can create files in " + dir, + "ARTEX_ISOLATION_CANARY reached Bash", + `database session as "artex"`, + } { + if !hasFailure(failures, want) { + t.Errorf("no failure %q in %q", want, failures) + } + } + if hasFailure(failures, "absent.key") { + t.Errorf("a missing file is not an exposure: %q", failures) + } + if entries, _ := os.ReadDir(dir); len(entries) != 1 { + t.Errorf("the write check left a file behind: %v", entries) + } +} + +// 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") + if err != nil { + t.Fatal(err) + } + port := uint16(ln.Addr().(*net.TCPAddr).Port) + ln.Close() // nothing listens there now + if err := connectWithoutPassword(&isolationProbeDB{Host: "127.0.0.1", Port: port, User: "artex", Database: "artex"}); err == nil { + t.Fatal("no database listening, yet a session opened") + } +} + +// Against the real test database: the server's user without its password is +// refused by PostgreSQL's authentication (it asks for the password on TCP). +func TestConnectWithoutPasswordRealPG(t *testing.T) { + dsn := os.Getenv("ARTEX_PG_DSN") + if dsn == "" { + t.Skip("ARTEX_PG_DSN not set") + } + spec := isolationSpec(ExecPrivilege{Enabled: true, UID: 10001, GID: 10001}, IsolationTargets{DSN: dsn}) + if spec.DB == nil { + t.Fatal("no database in the spec") + } + err := connectWithoutPassword(spec.DB) + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) || (pgErr.Code != "28P01" && pgErr.Code != "28000") { + t.Fatalf("connection without password: %v, want an authentication failure (28P01/28000)", err) + } + t.Logf("refused as expected: SQLSTATE %s", pgErr.Code) +} + +// The spec carries the server's paths and the database name, never its password. +func TestIsolationSpecHasNoPassword(t *testing.T) { + spec := isolationSpec(ExecPrivilege{Enabled: true, UID: 10001, GID: 10002}, IsolationTargets{ + DataDir: "/app/data", KeyDir: "/app/keys", ConfigPath: "/app/config.json", + DSN: "postgres://artex:s3cr3t-pw@postgres:5432/artex?sslmode=disable", + }) + for _, want := range []string{"/app/keys/jwt.key", "/app/keys/secret.key", "/app/config.json", "/app/data/traffic/_ca/mitmproxy-ca.pem"} { + found := false + for _, p := range spec.Unreadable { + found = found || p == want + } + if !found { + t.Errorf("%s missing from the unreadable files %v", want, spec.Unreadable) + } + } + if spec.DB == nil || spec.DB.Host != "postgres" || spec.DB.Port != 5432 || spec.DB.User != "artex" || spec.DB.Database != "artex" { + t.Fatalf("db = %+v", spec.DB) + } + if spec.UID != 10001 || spec.GID != 10002 || spec.ServerPID != os.Getpid() { + t.Fatalf("ids = %d:%d pid %d", spec.UID, spec.GID, spec.ServerPID) + } + if b := strings.Join(append(spec.Unreadable, spec.DB.Host, spec.DB.User), " "); strings.Contains(b, "s3cr3t") { + t.Fatal("the password reached the spec") + } +}