Files
alan b4382b08ad Apply the chat directory's environment and account to Claude Code chats
Claude Code chats now start with the chat directory's own environment:
direnv (allowed .envrc only, via direnv export json) and mise (mise env
--json), cached per directory and invalidated when config, watched files or
allow records change. A blocked .envrc is logged and shown in the chat as a
notice and never applied. When the directory chooses the Claude account
(CLAUDE_CONFIG_DIR, API key or token variables), the server's service token
and login-file fallbacks are skipped and inherited credentials dropped.
Transcripts in a directory's CLAUDE_CONFIG_DIR are found for history,
resume and after a restart. PWD is set to the chat directory.
2026-11-02 16:37:20 +00:00

228 lines
8.2 KiB
Go

package claude
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// fakeDirenv exports .envrc.json for an allowed .envrc (marked by
// .envrc.allowed) and reports any other .envrc as blocked, like direnv.
const fakeDirenv = `#!/bin/sh
[ "$1 $2" = "export json" ] || exit 2
[ -f .envrc ] || exit 0
if [ ! -f .envrc.allowed ]; then
echo "direnv: error $PWD/.envrc is blocked. Run ` + "`direnv allow`" + ` to approve its content" >&2
exit 1
fi
cat .envrc.json
`
// directoryChat is a test chat whose server has a service token and an
// inherited OAuth token, and whose PATH has a fake direnv.
func directoryChat(t *testing.T) *Chat {
t.Helper()
chat := testChat(t)
bin := t.TempDir()
if err := os.WriteFile(filepath.Join(bin, "direnv"), []byte(fakeDirenv), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
token := filepath.Join(t.TempDir(), "claude-token")
if err := os.WriteFile(token, []byte("service-token\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv(ServiceTokenEnvKey, token)
t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "")
os.Unsetenv("CLAUDE_CODE_OAUTH_TOKEN")
t.Setenv("FAKE_CLAUDE_ENV_KEYS", "CLAUDE_CONFIG_DIR,CLAUDE_CODE_OAUTH_TOKEN,ANTHROPIC_API_KEY,GH_CONFIG_DIR,PWD")
chat.dirEnv = &workenv.Resolver{Timeout: 10 * time.Second}
return chat
}
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
func lastSpawn(t *testing.T) argsEntry {
t.Helper()
entries := readArgs(t, os.Getenv("FAKE_CLAUDE_LOG"))
if len(entries) == 0 {
t.Fatal("Claude Code was not started")
}
return entries[len(entries)-1]
}
func envOf(entry argsEntry, key string) string {
if value := entry.Env[key]; value != nil {
return *value
}
return "<unset>"
}
func TestDirectoryAccountWinsOverServerFallbacks(t *testing.T) {
chat := directoryChat(t)
t.Setenv("ANTHROPIC_API_KEY", "server-inherited-key")
directory := t.TempDir()
profile := filepath.Join(t.TempDir(), "profile")
writeFile(t, filepath.Join(directory, ".envrc"), "export CLAUDE_CONFIG_DIR=...\n")
writeFile(t, filepath.Join(directory, ".envrc.allowed"), "")
writeFile(t, filepath.Join(directory, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"`+profile+`","GH_CONFIG_DIR":"/dir/gh"}`)
session, err := chat.Create(context.Background(), "Directory account", directory)
if err != nil {
t.Fatal(err)
}
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)
if spawn.Cwd != directory && spawn.Cwd != "/private"+directory {
t.Fatalf("cwd = %q, want %q", spawn.Cwd, directory)
}
if envOf(spawn, "PWD") != directory {
t.Fatalf("PWD = %q", envOf(spawn, "PWD"))
}
if envOf(spawn, "CLAUDE_CONFIG_DIR") != profile || envOf(spawn, "GH_CONFIG_DIR") != "/dir/gh" {
t.Fatalf("directory environment not applied: %v", spawn.Env)
}
if envOf(spawn, "CLAUDE_CODE_OAUTH_TOKEN") != "<unset>" {
t.Fatal("the service token overrode the directory's account")
}
if envOf(spawn, "ANTHROPIC_API_KEY") != "<unset>" {
t.Fatal("an inherited server credential overrode the directory's account")
}
// The transcript lives in the directory's profile; history and resume find it.
if matches, _ := filepath.Glob(filepath.Join(profile, "projects", "*", session.ID+".jsonl")); len(matches) != 1 {
t.Fatalf("transcript not in the directory profile: %v", matches)
}
page, err := chat.Messages(context.Background(), session.ID, 50, "")
if err != nil || len(page.Messages) == 0 {
t.Fatalf("history from the directory profile: %+v %v", page, err)
}
chat.session(session.ID).closeProcess()
if err := chat.Prompt(context.Background(), session.ID, "again"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
if argValue(lastSpawn(t).Args, "--resume") != session.ID {
t.Fatalf("restart did not resume from the directory profile: %+v", lastSpawn(t).Args)
}
}
func TestBlockedEnvrcIsNotAppliedAndShownInChat(t *testing.T) {
chat := directoryChat(t)
directory := t.TempDir()
writeFile(t, filepath.Join(directory, ".envrc"), "export CLAUDE_CONFIG_DIR=...\n")
writeFile(t, filepath.Join(directory, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"/never"}`)
session, err := chat.Create(context.Background(), "Blocked", directory)
if err != nil {
t.Fatal(err)
}
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "environment notice", func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventTool && frame.Part != nil && frame.Part.Name == "Directory environment" &&
frame.Part.State != nil && frame.Part.State.Error != nil &&
strings.Contains(frame.Part.State.Error.Message, "not allowed") &&
strings.Contains(frame.Part.State.Error.Message, "direnv allow")
})
waitStepEnded(t, frames)
spawn := lastSpawn(t)
if envOf(spawn, "CLAUDE_CONFIG_DIR") == "/never" {
t.Fatal("a blocked .envrc was applied")
}
// Without a directory account the server's own fallback still signs in.
if envOf(spawn, "CLAUDE_CODE_OAUTH_TOKEN") != "service-token" {
t.Fatalf("service token fallback missing without a directory account: %v", spawn.Env)
}
if _, err := os.Stat(filepath.Join(directory, ".envrc.allowed")); err == nil {
t.Fatal("the .envrc was allowed by the server")
}
}
func TestDirectoryWithoutEnvironmentKeepsServerSignIn(t *testing.T) {
chat := directoryChat(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)
if spawn := lastSpawn(t); envOf(spawn, "CLAUDE_CODE_OAUTH_TOKEN") != "service-token" {
t.Fatalf("env: %v", spawn.Env)
}
}
func TestGitIdentityFollowsTheChatDirectory(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not installed")
}
chat := directoryChat(t)
root := t.TempDir()
repo := filepath.Join(root, "work", "repo")
if err := os.MkdirAll(repo, 0o755); err != nil {
t.Fatal(err)
}
if out, err := exec.Command("git", "init", "-q", repo).CombinedOutput(); err != nil {
t.Fatalf("git init: %v %s", err, out)
}
included := filepath.Join(root, "work.gitconfig")
writeFile(t, included, "[user]\n\temail = work@example.test\n")
global := filepath.Join(root, "global.gitconfig")
writeFile(t, global, "[user]\n\temail = personal@example.test\n[includeIf \"gitdir:"+filepath.Join(root, "work")+"/\"]\n\tpath = "+included+"\n")
t.Setenv("GIT_CONFIG_GLOBAL", global)
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
t.Setenv("FAKE_CLAUDE_GIT_EMAIL", "1")
session, err := chat.Create(context.Background(), "Git", repo)
if err != nil {
t.Fatal(err)
}
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
if got := envOf(lastSpawn(t), "git user.email"); got != "work@example.test" {
t.Fatalf("git identity in the chat directory = %q", got)
}
}
func TestHintDirectoryFindsATranscriptInTheDirectoryProfile(t *testing.T) {
chat := directoryChat(t)
directory := t.TempDir()
profile := filepath.Join(t.TempDir(), "hinted-profile")
writeFile(t, filepath.Join(directory, ".envrc"), "")
writeFile(t, filepath.Join(directory, ".envrc.allowed"), "")
writeFile(t, filepath.Join(directory, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"`+profile+`"}`)
id := "11111111-2222-4333-8444-555555555555"
projects := filepath.Join(profile, "projects", "x")
if err := os.MkdirAll(projects, 0o755); err != nil {
t.Fatal(err)
}
writeFile(t, filepath.Join(projects, id+".jsonl"), `{"type":"user","cwd":"`+directory+`","timestamp":"2026-01-01T00:00:00Z","message":{"role":"user","content":"hi"}}`+"\n")
if _, found, _ := chat.Session(context.Background(), id); found {
t.Fatal("found before the hint")
}
chat.HintDirectory(context.Background(), id, directory)
if session, found, err := chat.Session(context.Background(), id); err != nil || !found || session.Directory != directory {
t.Fatalf("after hint: %+v %v %v", session, found, err)
}
}