diff --git a/cmd/pipelines-server/main.go b/cmd/pipelines-server/main.go index 9be36fa2..736618b2 100644 --- a/cmd/pipelines-server/main.go +++ b/cmd/pipelines-server/main.go @@ -51,8 +51,10 @@ func main() { if accessToken, err = servertoken.Read(*tokenFile); err != nil { log.Fatalf("server token: %v", err) } - // Stages, chat harnesses and their `pipelines` CLI calls inherit the - // file's location, never the token itself. + // Recorded for the server's own reads. Agent processes (stages, chat + // harnesses, `!` lines, checks) never inherit it: internal/agentenv + // drops it, and their `pipelines` CLI calls fall back to the default + // location (servertoken.DefaultPath). _ = os.Setenv(servertoken.EnvKey, *tokenFile) } else { log.Printf("no server token configured (-token-file): local clients reach this server without the shared secret") diff --git a/internal/agentenv/agentenv.go b/internal/agentenv/agentenv.go new file mode 100644 index 00000000..8bde526d --- /dev/null +++ b/internal/agentenv/agentenv.go @@ -0,0 +1,85 @@ +// Package agentenv builds the environment of every process the server starts +// on an agent's behalf: harness processes (stages and chats), `!` shell lines, +// check-stage commands and the tools those spawn. +// +// The server's own environment carries pointers to Pipelines' secrets (the +// server token, the web sign-in file with the cookie key, the update-signing +// key, harness service tokens). An agent has no use for them, and a +// prompt-injected one could follow them, so Scrub drops every such variable +// while keeping everything a harness legitimately needs (PATH, HOME, its own +// config directory and credentials, and the workspace's direnv/mise output). +// +// This only removes the pointers. The files themselves stay readable by the +// server's OS user: agents intentionally keep full host access (see +// docs/security-review.md, "Decisions"). +// The operator's interactive terminal is deliberately out of scope. +package agentenv + +import ( + "os" + "strings" +) + +// secretMarkers are name fragments that mark a PIPELINES_ variable as a +// secret, a credential or the path to one. +var secretMarkers = []string{"TOKEN", "SECRET", "PASSWORD", "PASSWD", "AUTH", "CREDENTIAL", "PRIVATE", "SIGNING", "KEY"} + +// publicSuffixes name PIPELINES_ variables that match a marker but carry no +// secret (a public verification key). +var publicSuffixes = []string{"_PUBLIC_KEY"} + +// Secret reports whether the variable name must not reach an agent process: +// any PIPELINES_ variable naming a token, password, auth file or key. +func Secret(name string) bool { + upper := strings.ToUpper(name) + if !strings.HasPrefix(upper, "PIPELINES_") { + return false + } + for _, suffix := range publicSuffixes { + if strings.HasSuffix(upper, suffix) { + return false + } + } + rest := strings.TrimPrefix(upper, "PIPELINES_") + for _, marker := range secretMarkers { + if strings.Contains(rest, marker) { + return true + } + } + return false +} + +// Scrub returns env without the secret variables. A nil env means "inherit +// the server's environment" (exec.Cmd's convention), so it scrubs +// os.Environ() instead: a command given the result never falls back to the +// unscrubbed server environment. The input slice is not modified. +func Scrub(env []string) []string { + if env == nil { + env = os.Environ() + } + out := make([]string, 0, len(env)) + for _, entry := range env { + name, _, _ := strings.Cut(entry, "=") + if Secret(name) { + continue + } + out = append(out, entry) + } + return out +} + +// Environ is the server's environment without secrets: the base for any agent +// process that would otherwise inherit os.Environ(). +func Environ() []string { return Scrub(nil) } + +// Leaks returns the secret entries left in env, for tests and diagnostics. +func Leaks(env []string) []string { + var leaks []string + for _, entry := range env { + name, _, _ := strings.Cut(entry, "=") + if Secret(name) { + leaks = append(leaks, entry) + } + } + return leaks +} diff --git a/internal/agentenv/agentenv_test.go b/internal/agentenv/agentenv_test.go new file mode 100644 index 00000000..7de718b5 --- /dev/null +++ b/internal/agentenv/agentenv_test.go @@ -0,0 +1,58 @@ +package agentenv + +import ( + "slices" + "testing" +) + +var planted = []string{ + "PIPELINES_SERVER_TOKEN_FILE", + "PIPELINES_WEB_AUTH_FILE", + "PIPELINES_WEB_AUTH", + "PIPELINES_WEB_PASSWORD", + "PIPELINES_UPDATE_SIGNING_KEY", + "PIPELINES_CLAUDE_TOKEN_FILE", + "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", + "PIPELINES_NTFY_TOKEN_FILE", + "PIPELINES_NTFY_TOKEN", + "PIPELINES_SOMETHING_SECRET", +} + +func TestSecretNames(t *testing.T) { + for _, name := range planted { + if !Secret(name) { + t.Errorf("%s should be secret", name) + } + } + for _, name := range []string{"PATH", "HOME", "CLAUDE_CONFIG_DIR", "CODEX_HOME", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY", + "PIPELINES_UPDATE_PUBLIC_KEY", "PIPELINES_DEFAULT_MODEL", "PIPELINES_WEB_PUBLIC_URL", "PIPELINES_NTFY_URL", "PIPELINES_ARTIFACTS_DIR", "PIPELINES_MDNS"} { + if Secret(name) { + t.Errorf("%s should be kept", name) + } + } +} + +func TestScrubKeepsOrderAndInput(t *testing.T) { + in := []string{"PATH=/bin", "PIPELINES_SERVER_TOKEN_FILE=/x", "HOME=/h", "PIPELINES_WEB_AUTH_FILE=/y", "MALFORMED"} + out := Scrub(in) + if want := []string{"PATH=/bin", "HOME=/h", "MALFORMED"}; !slices.Equal(out, want) { + t.Fatalf("Scrub = %v, want %v", out, want) + } + if in[1] != "PIPELINES_SERVER_TOKEN_FILE=/x" { + t.Fatal("Scrub modified its input") + } +} + +func TestScrubNilScrubsServerEnvironment(t *testing.T) { + for _, name := range planted { + t.Setenv(name, "/secret/"+name) + } + t.Setenv("KEEP_ME", "1") + out := Environ() + if !slices.Contains(out, "KEEP_ME=1") { + t.Fatal("ordinary variable dropped") + } + if leaks := Leaks(out); len(leaks) > 0 { + t.Fatalf("secrets leaked: %v", leaks) + } +} diff --git a/internal/claude/agentenv_scrub_test.go b/internal/claude/agentenv_scrub_test.go new file mode 100644 index 00000000..7fda37af --- /dev/null +++ b/internal/claude/agentenv_scrub_test.go @@ -0,0 +1,56 @@ +package claude + +import ( + "context" + "testing" +) + +// A chat's Claude Code process never sees Pipelines' own secret pointers, +// while the server still resolves its service token for it. +func TestChatProcessEnvironmentScrubsPipelinesSecrets(t *testing.T) { + chat := directoryChat(t) + t.Setenv("PIPELINES_SERVER_TOKEN_FILE", "/secret/server-token") + t.Setenv("PIPELINES_WEB_AUTH_FILE", "/secret/web-auth.json") + t.Setenv("PIPELINES_UPDATE_SIGNING_KEY", "/secret/update-signing-key.pem") + t.Setenv("FAKE_CLAUDE_ENV_KEYS", "PIPELINES_SERVER_TOKEN_FILE,PIPELINES_WEB_AUTH_FILE,PIPELINES_UPDATE_SIGNING_KEY,PIPELINES_CLAUDE_TOKEN_FILE,CLAUDE_CODE_OAUTH_TOKEN") + session := newCreatedChat(t, chat) + frames := subscribe(t, chat, session.ID) + if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil { + t.Fatal(err) + } + waitStepEnded(t, frames) + spawn := lastSpawn(t) + for _, key := range []string{"PIPELINES_SERVER_TOKEN_FILE", "PIPELINES_WEB_AUTH_FILE", "PIPELINES_UPDATE_SIGNING_KEY", ServiceTokenEnvKey} { + if got := envOf(spawn, key); got != "" { + t.Errorf("%s reached Claude Code: %q", key, got) + } + } + if envOf(spawn, "CLAUDE_CODE_OAUTH_TOKEN") != "service-token" { + t.Fatalf("service token no longer resolved for the chat: %v", spawn.Env) + } +} + +// A hosted chat's Claude Code (server -> pipelines-claude-host -> CLI) never +// sees them either. +func TestHostedChatProcessEnvironmentScrubsPipelinesSecrets(t *testing.T) { + hostedSetup(t) + t.Setenv("PIPELINES_SERVER_TOKEN_FILE", "/secret/server-token") + t.Setenv("PIPELINES_WEB_AUTH_FILE", "/secret/web-auth.json") + t.Setenv("FAKE_CLAUDE_ENV_KEYS", "PIPELINES_SERVER_TOKEN_FILE,PIPELINES_WEB_AUTH_FILE,CLAUDE_CONFIG_DIR") + chat := hostedChat(t) + session := newCreatedChat(t, chat) + frames := subscribe(t, chat, session.ID) + if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil { + t.Fatal(err) + } + waitStepEnded(t, frames) + spawn := lastSpawn(t) + for _, key := range []string{"PIPELINES_SERVER_TOKEN_FILE", "PIPELINES_WEB_AUTH_FILE"} { + if got := envOf(spawn, key); got != "" { + t.Errorf("%s reached the hosted Claude Code: %q", key, got) + } + } + if envOf(spawn, "CLAUDE_CONFIG_DIR") == "" { + t.Fatalf("harness config directory dropped: %v", spawn.Env) + } +} diff --git a/internal/claude/auth_env.go b/internal/claude/auth_env.go index fa519387..276173ba 100644 --- a/internal/claude/auth_env.go +++ b/internal/claude/auth_env.go @@ -10,6 +10,7 @@ import ( "sync" "time" + "git.a-wan.net/alan/pipelines/internal/agentenv" "git.a-wan.net/alan/pipelines/internal/workenv" ) @@ -124,7 +125,8 @@ func (c *Chat) processEnvFrom(ctx context.Context, directory string, base []stri if value, ok := envValue(env, "CLAUDE_CONFIG_DIR"); ok { rememberConfigDir(value) } - return workenv.WithPWD(env, directory), dir.Warnings + // Pipelines' own secrets never reach the CLI or its tools. + return workenv.WithPWD(agentenv.Scrub(env), directory), dir.Warnings } // HintDirectory tells the adapter the recorded directory of a session it has diff --git a/internal/claude/process.go b/internal/claude/process.go index c4531af5..d14a80a4 100644 --- a/internal/claude/process.go +++ b/internal/claude/process.go @@ -14,6 +14,7 @@ import ( "sync/atomic" "time" + "git.a-wan.net/alan/pipelines/internal/agentenv" "git.a-wan.net/alan/pipelines/internal/claudehost" "git.a-wan.net/alan/pipelines/internal/protocol" ) @@ -192,7 +193,7 @@ func (s *session) spawnOnce(ctx context.Context) (*process, error) { func (s *session) startDirect(args []string, mode string, env []string) (*process, error) { cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...) cmd.Dir = s.directory - cmd.Env = env + cmd.Env = agentenv.Scrub(env) cmd.WaitDelay = 5 * time.Second stdin, err := cmd.StdinPipe() if err != nil { diff --git a/internal/claudehost/client.go b/internal/claudehost/client.go index aa8878ac..a326b08b 100644 --- a/internal/claudehost/client.go +++ b/internal/claudehost/client.go @@ -15,6 +15,8 @@ import ( "sync" "syscall" "time" + + "git.a-wan.net/alan/pipelines/internal/agentenv" ) // Conn is a server's connection to one host. @@ -180,7 +182,8 @@ func Spawn(ctx context.Context, options SpawnOptions) (*exec.Cmd, error) { args = append(args, options.Args...) cmd := exec.Command(options.HostBinary, args...) cmd.Dir = options.Cwd - cmd.Env = options.Env + // The host and the CLI it starts never see Pipelines' own secrets. + cmd.Env = agentenv.Scrub(options.Env) cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} logFile, err := os.OpenFile(paths.Log, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) if err != nil { diff --git a/internal/claudehost/host.go b/internal/claudehost/host.go index dfed80c9..85065119 100644 --- a/internal/claudehost/host.go +++ b/internal/claudehost/host.go @@ -17,6 +17,8 @@ import ( "sync" "syscall" "time" + + "git.a-wan.net/alan/pipelines/internal/agentenv" ) // Defaults for a host started without explicit limits. @@ -197,7 +199,7 @@ func (h *host) start(command []string) error { _ = os.Chmod(h.paths.Socket, 0o600) h.listener = listener cmd := exec.Command(command[0], command[1:]...) - cmd.Env = os.Environ() + cmd.Env = agentenv.Environ() // Its own process group, so the CLI and its tool subprocesses stop together. cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} stdin, err := cmd.StdinPipe() diff --git a/internal/filediff/snapshot.go b/internal/filediff/snapshot.go index fda4dd7f..a1b5ee17 100644 --- a/internal/filediff/snapshot.go +++ b/internal/filediff/snapshot.go @@ -20,6 +20,7 @@ import ( "syscall" "unicode/utf8" + "git.a-wan.net/alan/pipelines/internal/agentenv" "git.a-wan.net/alan/pipelines/internal/protocol" "git.a-wan.net/alan/pipelines/internal/workenv" "github.com/pmezard/go-difflib/difflib" @@ -123,7 +124,7 @@ type Snapshot struct { // (workenv.WithEnvironment) when ctx carries one, as the stage's own git sees. func gitCommand(ctx context.Context, directory string, args ...string) *exec.Cmd { cmd := exec.CommandContext(ctx, "git", args...) - cmd.Env = workenv.CommandEnv(ctx, directory) + cmd.Env = agentenv.Scrub(workenv.CommandEnv(ctx, directory)) return cmd } diff --git a/internal/opencode/agentenv_scrub_test.go b/internal/opencode/agentenv_scrub_test.go new file mode 100644 index 00000000..7bee8e0d --- /dev/null +++ b/internal/opencode/agentenv_scrub_test.go @@ -0,0 +1,31 @@ +package opencode + +import ( + "os" + "slices" + "testing" + + "git.a-wan.net/alan/pipelines/internal/agentenv" +) + +// The OpenCode serve processes (chat service and owned stage services) and the +// tools they run never see Pipelines' own secret pointers. +func TestServiceEnvironmentScrubsPipelinesSecrets(t *testing.T) { + t.Setenv("PIPELINES_SERVER_TOKEN_FILE", "/secret/server-token") + t.Setenv("PIPELINES_WEB_AUTH_FILE", "/secret/web-auth.json") + t.Setenv("PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "/secret/opencode-password") + t.Setenv("KEEP_ME", "1") + for name, env := range map[string][]string{ + "chat service": serviceEnvironment(`{"a":1}`), + "stage service (server env)": serviceEnvironmentFrom(nil, ""), + "stage service (run env)": serviceEnvironmentFrom(append(os.Environ(), "PIPELINES_X_TOKEN=envrc"), ""), + "stage service (owned config)": serviceEnvironmentFrom(os.Environ(), `{"b":2}`), + } { + if leaks := agentenv.Leaks(env); len(leaks) > 0 { + t.Errorf("%s leaks %v", name, leaks) + } + if !slices.Contains(env, "KEEP_ME=1") { + t.Errorf("%s dropped an ordinary variable", name) + } + } +} diff --git a/internal/opencode/stage_limits.go b/internal/opencode/stage_limits.go index dd8f1dcc..842bb02e 100644 --- a/internal/opencode/stage_limits.go +++ b/internal/opencode/stage_limits.go @@ -6,6 +6,8 @@ import ( "os" "strconv" "strings" + + "git.a-wan.net/alan/pipelines/internal/agentenv" ) // Stage and chat OpenCode limits. OpenCode reads tool_output and compaction @@ -151,10 +153,11 @@ func serviceEnvironment(content string) []string { } // serviceEnvironmentFrom is serviceEnvironment over base instead of the -// server's own environment (a run directory's resolved environment). +// server's own environment (a run directory's resolved environment). Pipelines' +// own secrets never reach the serve process or the tools it runs. func serviceEnvironmentFrom(base []string, content string) []string { var env []string - for _, entry := range base { + for _, entry := range agentenv.Scrub(base) { if strings.HasPrefix(entry, "OPENCODE_SERVER_PASSWORD=") || strings.HasPrefix(entry, "OPENCODE_SERVER_USERNAME=") || (content != "" && strings.HasPrefix(entry, "OPENCODE_CONFIG_CONTENT=")) { continue diff --git a/internal/server/agentenv_scrub_test.go b/internal/server/agentenv_scrub_test.go new file mode 100644 index 00000000..1c93f86c --- /dev/null +++ b/internal/server/agentenv_scrub_test.go @@ -0,0 +1,81 @@ +package server + +import ( + "context" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/agentenv" + "git.a-wan.net/alan/pipelines/internal/workenv" + "git.a-wan.net/alan/pipelines/internal/workenv/workenvtest" +) + +func plantServerSecrets(t *testing.T) { + t.Helper() + t.Setenv("PIPELINES_SERVER_TOKEN_FILE", "/secret/server-token") + t.Setenv("PIPELINES_WEB_AUTH_FILE", "/secret/web-auth.json") + t.Setenv("PIPELINES_UPDATE_SIGNING_KEY", "/secret/update-signing-key.pem") +} + +func assertNoSecretLines(t *testing.T, what, output string) { + t.Helper() + if leaks := agentenv.Leaks(strings.Split(strings.ReplaceAll(output, "\r", ""), "\n")); len(leaks) > 0 { + t.Fatalf("%s leaks Pipelines secrets: %v", what, leaks) + } + if !strings.Contains(output, "PATH=") { + t.Fatalf("%s lost PATH: %q", what, output) + } +} + +// `!` shell lines run without Pipelines' own secret pointers. +func TestChatShellCommandEnvironmentIsScrubbed(t *testing.T) { + plantServerSecrets(t) + cmd := exec.Command("sh", "-c", "env") + reader, _, err := startChatShellCommand(cmd, 0, 0) + if err != nil { + t.Fatal(err) + } + output, _ := io.ReadAll(reader) // a pseudo-terminal ends with EIO + reader.Close() + _ = cmd.Wait() + assertNoSecretLines(t, "chat shell command", string(output)) +} + +// A delivery gate's check command runs without them too. +func TestDeliveryCheckEnvironmentIsScrubbed(t *testing.T) { + plantServerSecrets(t) + err := runDeliveryCheck(context.Background(), t.TempDir(), "env; exit 1") + if err == nil { + t.Fatal("the failing check passed") + } + assertNoSecretLines(t, "delivery check", err.Error()) +} + +// A run's resolved workspace environment, the base of every stage process, +// check and OpenCode stage service, starts from the scrubbed server +// environment. +func TestRunEnvironmentStartsScrubbed(t *testing.T) { + workenvtest.InstallDirenv(t) + plantServerSecrets(t) + project, _ := filepath.EvalSymlinks(t.TempDir()) + workenvtest.WriteEnvrc(t, project, true, map[string]*string{"SCRATCH_VAR": workenvtest.Str("from-envrc")}) + ctx, r, _ := concurrentStore(t) + r.dirEnv = &workenv.Resolver{} + env, _ := workenv.FromContext(r.withRunEnvironment(ctx, 1, project)) + if !env.Applies() { + t.Fatalf("the workspace environment did not apply: %+v", env) + } + if leaks := agentenv.Leaks(env.Env); len(leaks) > 0 { + t.Fatalf("run environment leaks %v", leaks) + } + if value, _ := envValue(env.Env, "SCRATCH_VAR"); value != "from-envrc" { + t.Fatalf("workspace variable missing: %v", env.Env) + } + if _, ok := envValue(env.Env, "HOME"); !ok && os.Getenv("HOME") != "" { + t.Fatal("HOME dropped") + } +} diff --git a/internal/server/chat_shell_terminal.go b/internal/server/chat_shell_terminal.go index e40ac85c..ba2ed8b1 100644 --- a/internal/server/chat_shell_terminal.go +++ b/internal/server/chat_shell_terminal.go @@ -8,17 +8,19 @@ import ( "syscall" "unicode/utf8" + "git.a-wan.net/alan/pipelines/internal/agentenv" "git.a-wan.net/alan/pipelines/internal/protocol" ) -// startChatShellCommand starts cmd with the server's environment, in a +// startChatShellCommand starts cmd with the server's environment (minus +// Pipelines' own secrets, agentenv), in a // pseudo-terminal of cols x rows where the platform has one (TERM is then // xterm-256color) and otherwise in its own process group with stdout and // stderr on one pipe. It returns the output reader and, in a terminal, the // terminal itself (the same file). func startChatShellCommand(cmd *exec.Cmd, cols, rows int) (reader, terminal *os.File, err error) { if chatShellTerminals { - cmd.Env = chatShellTerminalEnv(os.Environ()) + cmd.Env = chatShellTerminalEnv(agentenv.Environ()) terminal, err = startChatShellTerminal(cmd, cols, rows) return terminal, terminal, err } @@ -26,7 +28,7 @@ func startChatShellCommand(cmd *exec.Cmd, cols, rows int) (reader, terminal *os. if err != nil { return nil, nil, err } - cmd.Env = os.Environ() + cmd.Env = agentenv.Environ() cmd.Stdout, cmd.Stderr = writer, writer cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} err = cmd.Start() diff --git a/internal/server/delivery_gate.go b/internal/server/delivery_gate.go index 095cc690..fde1053c 100644 --- a/internal/server/delivery_gate.go +++ b/internal/server/delivery_gate.go @@ -13,6 +13,7 @@ import ( "syscall" "time" + "git.a-wan.net/alan/pipelines/internal/agentenv" "git.a-wan.net/alan/pipelines/internal/stage" "git.a-wan.net/alan/pipelines/internal/workenv" ) @@ -240,7 +241,7 @@ func cleanupDeliveryCandidate(workspace, candidate string) { func boundedCommandOutput(ctx context.Context, directory string, args ...string) ([]byte, error) { cmd := exec.CommandContext(ctx, "git", append([]string{"-C", directory}, args...)...) - cmd.Env = workenv.CommandEnv(ctx, directory) + cmd.Env = agentenv.Scrub(workenv.CommandEnv(ctx, directory)) var output boundedDeliveryOutput cmd.Stdout = &output cmd.Stderr = &output @@ -252,8 +253,8 @@ func runDeliveryCheck(ctx context.Context, directory, check string) error { cmd := exec.CommandContext(ctx, "sh", "-c", check) cmd.Dir = directory // The run workspace's own environment (direnv/mise), as a terminal there - // would have it; nil inherits the server's. - cmd.Env = workenv.CommandEnv(ctx, directory) + // would have it, else the server's; never Pipelines' own secrets. + cmd.Env = agentenv.Scrub(workenv.CommandEnv(ctx, directory)) var output boundedDeliveryOutput cmd.Stdout = &output cmd.Stderr = &output diff --git a/internal/server/run_environment.go b/internal/server/run_environment.go index 02065638..cc1966bb 100644 --- a/internal/server/run_environment.go +++ b/internal/server/run_environment.go @@ -3,9 +3,9 @@ package server import ( "context" "log" - "os" "time" + "git.a-wan.net/alan/pipelines/internal/agentenv" "git.a-wan.net/alan/pipelines/internal/protocol" "git.a-wan.net/alan/pipelines/internal/workenv" ) @@ -22,7 +22,9 @@ func (r *runner) withRunEnvironment(ctx context.Context, id int64, workspace str if resolver == nil { resolver = workenv.Default } - env := resolver.Environment(ctx, workspace, os.Environ()) + // Every process started from the run's environment (stages, checks, the + // OpenCode stage service) builds on the server's minus Pipelines' secrets. + env := resolver.Environment(ctx, workspace, agentenv.Environ()) for _, warning := range env.Warnings { log.Printf("run %d workspace %s: %s", id, workspace, warning) } diff --git a/internal/servertoken/servertoken.go b/internal/servertoken/servertoken.go index 1de434f2..b246c052 100644 --- a/internal/servertoken/servertoken.go +++ b/internal/servertoken/servertoken.go @@ -1,6 +1,8 @@ // Package servertoken is the shared secret between the Pipelines server and its -// local clients (the authenticated web proxy, the CLI, the TUI and the -// harnesses the server launches). +// local clients (the authenticated web proxy, the CLI and the TUI). Processes +// the server launches for agents do not inherit PIPELINES_SERVER_TOKEN_FILE +// (internal/agentenv); a `pipelines` CLI call from an agent finds the token +// only at the default location. // // The installer writes a random token to a private (0600) file next to the web // sign-in file, by default $XDG_CONFIG_HOME/pipelines/server-token (else diff --git a/internal/stage/agentenv_scrub_test.go b/internal/stage/agentenv_scrub_test.go new file mode 100644 index 00000000..491c3863 --- /dev/null +++ b/internal/stage/agentenv_scrub_test.go @@ -0,0 +1,120 @@ +package stage + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/agentenv" + "git.a-wan.net/alan/pipelines/internal/workenv" +) + +// plantSecrets puts Pipelines' secret pointers in the server environment and +// returns a run environment that (as a hostile .envrc might) carries one too. +func plantSecrets(t *testing.T) []string { + t.Helper() + t.Setenv("PIPELINES_SERVER_TOKEN_FILE", "/secret/server-token") + t.Setenv("PIPELINES_WEB_AUTH_FILE", "/secret/web-auth.json") + t.Setenv("PIPELINES_UPDATE_SIGNING_KEY", "/secret/update-signing-key.pem") + return append(os.Environ(), "PIPELINES_SOMETHING_TOKEN=from-envrc", "SCRATCH_VAR=kept") +} + +func assertScrubbed(t *testing.T, what string, env []string) { + t.Helper() + if leaks := agentenv.Leaks(env); len(leaks) > 0 { + t.Fatalf("%s leaks Pipelines secrets: %v", what, leaks) + } + if len(env) == 0 { + t.Fatalf("%s environment is empty", what) + } +} + +func envLines(t *testing.T, path string) []string { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return strings.Split(strings.TrimSpace(string(data)), "\n") +} + +func TestClaudeStageProcessEnvironmentIsScrubbed(t *testing.T) { + plantSecrets(t) + client, root, _ := fakeClaudeClient(t, "success") + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := client.Generate(ctx, claudeConfig(NewBudget(10, 1000)), "task"); err != nil { + t.Fatal(err) + } + env := envLines(t, filepath.Join(root, "env")) + assertScrubbed(t, "Claude stage", env) + if !strings.Contains(strings.Join(env, "\n"), "HOME="+root) { + t.Fatalf("HOME not kept: %v", env) + } +} + +func TestPiStageProcessEnvironmentIsScrubbed(t *testing.T) { + root := t.TempDir() + t.Setenv("XDG_CACHE_HOME", root) + t.Setenv("HOME", root) + t.Setenv("PIPELINES_PI_FIXTURE", "1") + t.Setenv("PI_FIXTURE_CASE", "success") + out := filepath.Join(root, "env.txt") + t.Setenv("PI_FIXTURE_ENV_OUT", out) + runEnv := plantSecrets(t) + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + wrapper := filepath.Join(root, "pi") + if err := os.WriteFile(wrapper, []byte("#!/bin/sh\nexec '"+executable+"' -test.run=^TestPiRPCFixture$\n"), 0700); err != nil { + t.Fatal(err) + } + workspace := t.TempDir() + ctx, cancel := context.WithTimeout(workenv.WithEnvironment(context.Background(), workenv.Environment{Directory: workspace, Env: runEnv, Key: "k"}), 5*time.Second) + defer cancel() + client := &PiClient{Executable: wrapper, Directory: workspace, Tools: []string{}} + if _, err := client.Generate(ctx, ModelConfig{Provider: "fixture", Model: "model", Budget: NewBudget(0, 100)}, "task"); err != nil { + t.Fatal(err) + } + env := envLines(t, out) + assertScrubbed(t, "Pi stage", env) + if !strings.Contains(strings.Join(env, "\n"), "SCRATCH_VAR=kept") { + t.Fatalf("workspace environment lost: %v", env) + } + // Without a run environment the server's own is scrubbed too. + assertScrubbed(t, "Pi stage (server environment)", piEnvironmentFrom(nil, root, "")) +} + +func TestOpenCodeStageCLIEnvironmentIsScrubbed(t *testing.T) { + runEnv := plantSecrets(t) + assertScrubbed(t, "OpenCode CLI (server environment)", openCodeCLIEnv(context.Background(), t.TempDir(), "/artifacts")) + directory := t.TempDir() + ctx := workenv.WithEnvironment(context.Background(), workenv.Environment{Directory: directory, Env: runEnv, Key: "k"}) + env := openCodeCLIEnv(ctx, directory, "/artifacts") + assertScrubbed(t, "OpenCode CLI (run environment)", env) + if env[len(env)-1] != ArtifactsEnv+"=/artifacts" { + t.Fatalf("artifacts directory missing: %v", env) + } +} + +func TestCheckCommandEnvironmentIsScrubbed(t *testing.T) { + runEnv := plantSecrets(t) + directory := t.TempDir() + for _, ctx := range []context.Context{ + context.Background(), + workenv.WithEnvironment(context.Background(), workenv.Environment{Directory: directory, Env: runEnv, Key: "k"}), + } { + result := runCheckCommand(ctx, directory, "env", 10*time.Second) + if result.Status != CheckStatusPassed { + t.Fatalf("check failed: %+v", result) + } + assertScrubbed(t, "check command", strings.Split(result.Output, "\n")) + if !strings.Contains(result.Output, "PATH=") { + t.Fatalf("PATH not kept: %s", result.Output) + } + } +} diff --git a/internal/stage/check.go b/internal/stage/check.go index 0d21927f..05a8e5a0 100644 --- a/internal/stage/check.go +++ b/internal/stage/check.go @@ -12,6 +12,7 @@ import ( "time" "unicode/utf8" + "git.a-wan.net/alan/pipelines/internal/agentenv" "git.a-wan.net/alan/pipelines/internal/workenv" ) @@ -219,7 +220,7 @@ func runCheckCommand(ctx context.Context, directory, command string, timeout tim defer cancel() cmd := exec.CommandContext(commandCtx, "sh", "-c", command) cmd.Dir = directory - cmd.Env = workenv.CommandEnv(ctx, directory) + cmd.Env = checkCommandEnv(ctx, directory) // A test suite starts children; a timeout kills the whole process group, // and WaitDelay bounds a child that keeps the output pipes open. cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} @@ -411,3 +412,9 @@ func (b *headTailBuffer) String() (string, bool) { text := b.first.String() + fmt.Sprintf("\n[... %d bytes omitted ...]\n", b.dropped) + string(tail) return strings.ToValidUTF8(strings.TrimRight(text, "\n"), "\uFFFD"), true } + +// checkCommandEnv is a check command's environment: the run directory's (or +// the server's) environment without Pipelines' own secrets. +func checkCommandEnv(ctx context.Context, directory string) []string { + return agentenv.Scrub(workenv.CommandEnv(ctx, directory)) +} diff --git a/internal/stage/claude_stage.go b/internal/stage/claude_stage.go index 3645045e..3ab9fd73 100644 --- a/internal/stage/claude_stage.go +++ b/internal/stage/claude_stage.go @@ -16,6 +16,7 @@ import ( "syscall" "time" + "git.a-wan.net/alan/pipelines/internal/agentenv" "git.a-wan.net/alan/pipelines/internal/claude" "git.a-wan.net/alan/pipelines/internal/workenv" ) @@ -355,10 +356,8 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr // fallback is added, as in a terminal opened there. func (c *ClaudeStageClient) environment(ctx context.Context) []string { run, _ := workenv.FromContext(ctx) - base := run.Command(c.Directory) - if base == nil { - base = os.Environ() - } + // Scrub(nil) is the server's own environment, minus Pipelines' secrets. + base := agentenv.Scrub(run.Command(c.Directory)) owned := map[string]bool{} for _, key := range workenv.AccountEnvKeys { owned[key] = true @@ -767,7 +766,7 @@ func (c *ClaudeStageClient) start(env, args []string, n int, prompt string) (*cl defer stderr.Close() cmd := exec.Command(c.Executable, args...) cmd.Dir = c.Directory - cmd.Env = env + cmd.Env = agentenv.Scrub(env) cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr if err = cmd.Start(); err != nil { diff --git a/internal/stage/claude_stage_test.go b/internal/stage/claude_stage_test.go index 852cd423..bc1659cb 100644 --- a/internal/stage/claude_stage_test.go +++ b/internal/stage/claude_stage_test.go @@ -20,6 +20,7 @@ import ( // prompt, then prints a canned stream-json conversation for FAKE_CLAUDE_CASE. const fakeClaude = `#!/bin/sh if [ "$1" = auth ]; then echo '{"loggedIn":true}'; exit 0; fi +env > "$FAKE_CLAUDE_OUT/env" session=""; model=""; resumed=0; prev="" for a in "$@"; do printf '%s\n' "$a" >> "$FAKE_CLAUDE_OUT/args" diff --git a/internal/stage/opencode.go b/internal/stage/opencode.go index b5e25b76..31cd2231 100644 --- a/internal/stage/opencode.go +++ b/internal/stage/opencode.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "git.a-wan.net/alan/pipelines/internal/agentenv" "git.a-wan.net/alan/pipelines/internal/opencode" "git.a-wan.net/alan/pipelines/internal/workenv" "io" @@ -138,13 +139,7 @@ func (c OpenCodeClient) call(ctx context.Context, method, path string, body any) cmd := opencode.CommandContext(ctx, opencode.Executable(), args...) cmd.Dir = directory // The run's directory environment (workenv.WithEnvironment), if any. - cmd.Env = workenv.CommandEnv(ctx, directory) - if c.ArtifactsDir != "" { - if cmd.Env == nil { - cmd.Env = os.Environ() - } - cmd.Env = append(cmd.Env, ArtifactsEnv+"="+c.ArtifactsDir) - } + cmd.Env = openCodeCLIEnv(ctx, directory, c.ArtifactsDir) if c.connection != nil { c.connection.PinCLI(cmd) } @@ -517,3 +512,14 @@ func (b *boundedBuffer) Write(p []byte) (int, error) { } var _ io.Writer = (*boundedBuffer)(nil) + +// openCodeCLIEnv is the environment of an OpenCode CLI call for a stage: the +// run directory's (or the server's) environment without Pipelines' own +// secrets, plus the stage's artifacts directory. +func openCodeCLIEnv(ctx context.Context, directory, artifactsDir string) []string { + env := agentenv.Scrub(workenv.CommandEnv(ctx, directory)) + if artifactsDir != "" { + env = append(env, ArtifactsEnv+"="+artifactsDir) + } + return env +} diff --git a/internal/stage/pi.go b/internal/stage/pi.go index 4adc94dd..ca79a981 100644 --- a/internal/stage/pi.go +++ b/internal/stage/pi.go @@ -17,6 +17,7 @@ import ( "syscall" "time" + "git.a-wan.net/alan/pipelines/internal/agentenv" "git.a-wan.net/alan/pipelines/internal/workenv" ) @@ -181,7 +182,7 @@ func (c *PiClient) Generate(ctx context.Context, config ModelConfig, prompt stri c.cmd = exec.Command(c.Executable, args...) c.cmd.Dir = c.Directory c.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} - c.cmd.Env = env + c.cmd.Env = agentenv.Scrub(env) stderr, err := os.OpenFile(filepath.Join(c.Reference, "stderr.log"), os.O_CREATE|os.O_WRONLY, 0600) if err != nil { return "", err @@ -404,9 +405,7 @@ func piEnvironment(reference, artifactsDir string) []string { // piEnvironmentFrom builds the Pi environment over inherited (the run directory's // environment), or over the server's own when inherited is nil. func piEnvironmentFrom(inherited []string, reference, artifactsDir string) []string { - if inherited == nil { - inherited = os.Environ() - } + inherited = agentenv.Scrub(inherited) env := make([]string, 0, len(inherited)+4) for _, entry := range inherited { if strings.HasPrefix(entry, ArtifactsEnv+"=") { diff --git a/internal/stage/pi_test.go b/internal/stage/pi_test.go index fd4a4b33..c22bc3db 100644 --- a/internal/stage/pi_test.go +++ b/internal/stage/pi_test.go @@ -8,6 +8,7 @@ import ( "fmt" "os" "path/filepath" + "strings" "testing" "time" ) @@ -21,7 +22,8 @@ func TestPiRPCFixture(t *testing.T) { sessionID := filepath.Base(root) _ = os.WriteFile(filepath.Join(root, "ready"), []byte("ready"), 0600) if out := os.Getenv("PI_FIXTURE_ENV_OUT"); out != "" { - _ = os.WriteFile(out, []byte("SCRATCH_VAR="+os.Getenv("SCRATCH_VAR")+"\nPWD="+os.Getenv("PWD")+"\n"), 0600) + // The whole environment, so tests can check what is (and is not) passed. + _ = os.WriteFile(out, []byte(strings.Join(os.Environ(), "\n")+"\n"), 0600) } message := map[string]any{"role": "assistant", "stopReason": "stop", "timestamp": 1, "content": []map[string]string{{"type": "text", "text": `# outcome success