Skip to content
2 changes: 2 additions & 0 deletions changelog.d/security-17251-climemory-nofollow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- The CLI-memory drain opens every agent memory file through an `os.Root` anchored at its store and truncates it through the descriptor it read, instead of reading and `os.Truncate`-ing by path after the listing. The store belongs to the agent and the drain runs with the hive's privileges, so an agent that swapped a listed `.md` (or the store directory) for a symlink between the listing and the open could have had the hive copy any file it can read into the knowledge vault, or empty any file it can write β€” `TruncateDrained` counts a file with no parseable fact as "fully stored". Such a path is now reported in `kept` and the drain error, never followed ([#17251](https://github.com/hivecommons/hive/issues/17251)).
- The drain also refuses a memory-file symlink whose target stays inside the store root (for a single-file store such as `GEMINI.md` that root is its parent, e.g. `~/.gemini/`), by `Lstat`ing each entry through the root and requiring the opened file to be the same inode, and `cliMemoryDrainSources` now resolves each store with `EvalSymlinks` and drops any that leaves the agent's own home β€” so a `~/.claude/projects/<slug>` pointed at another agent's store is never drained or truncated under this agent's name ([#17251](https://github.com/hivecommons/hive/issues/17251)).
40 changes: 39 additions & 1 deletion src/crux/agent/cli_memory_drain.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,26 @@ func (m *Manager) SetCLIMemoryDrainer(fn CLIMemoryDrainer) {
// cliMemoryDrainSources lists the agent's memory stores with the CLI that
// owns each. Same per-agent-home-only rule as cliMemoryStorePaths: a shared
// or bridged store is never drained under one agent's name.
//
// The store paths come from a Glob under the agent's home, which follows a
// symlink in any ancestor (`.claude`, `projects`, the project slug). The
// agent owns those directories and the drain runs with the hive's
// privileges, so a slug pointed at another agent's store, or at any
// hive-readable tree holding `memory/*.md`, would be drained under this
// agent's name and, with truncate, emptied. Each store is therefore resolved
// with EvalSymlinks and kept only if it still lies under the agent's own
// resolved home (or CODEX_HOME); the resolved path is what the drainer opens
// its store root at, so the listing and the open name the same directory,
// and two listings that resolve to one store are drained once.
func cliMemoryDrainSources(agent *AgentProcess, backend string) []CLIMemorySource {
homes := []string{AgentHome(agent.Name, agent.UID, backend), codexHomePath(agent.Name)}
for i, h := range homes {
if r, err := filepath.EvalSymlinks(h); err == nil {
homes[i] = r
}
}
var sources []CLIMemorySource
seen := map[string]bool{}
for _, p := range cliMemoryStorePaths(agent, backend) {
cli := cliMemoryCodex
switch {
Expand All @@ -71,11 +89,31 @@ func cliMemoryDrainSources(agent *AgentProcess, backend string) []CLIMemorySourc
case filepath.Base(p) == "memory":
cli = cliMemoryClaude
}
sources = append(sources, CLIMemorySource{CLI: cli, Path: p})
real, err := filepath.EvalSymlinks(p)
if err != nil || !pathUnderAny(real, homes) || seen[real] {
continue
}
seen[real] = true
sources = append(sources, CLIMemorySource{CLI: cli, Path: real})
}
return sources
}

// pathUnderAny reports whether path is one of, or strictly inside one of,
// the given directories. All arguments are expected to be symlink-resolved.
func pathUnderAny(path string, dirs []string) bool {
for _, d := range dirs {
rel, err := filepath.Rel(d, path)
if err != nil {
continue
}
if rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return true
}
}
return false
}

// drainCLIMemoryForKick runs the installed drainer over the agent's memory
// stores when agents.cli_memory.drain_to_knowledge is set. It is called
// before clearCLIMemoryForKick so the facts survive the wipe, and it is
Expand Down
52 changes: 52 additions & 0 deletions src/crux/agent/cli_memory_drain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,58 @@ func TestCLIMemoryDrainSources_ClassifiesStoresByCLI(t *testing.T) {
}
}

func TestCLIMemoryDrainSources_DropsStoresReachedThroughSymlinkedAncestors(t *testing.T) {
withSharedAgentHome(t)
prev := codexHomePrefix
codexHomePrefix = filepath.Join(t.TempDir(), ".codex-")
t.Cleanup(func() { codexHomePrefix = prev })

mk := func(p string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte("- fact\n"), 0o644); err != nil {
t.Fatal(err)
}
}
home := interactiveHomePath("scanner")
projects := filepath.Join(home, ".claude", "projects")
// An honest store, and a second slug that is a symlink to it: inside the
// agent's own home, so it is drained once, at its resolved path.
own := filepath.Join(projects, "-data-agents-scanner", "memory")
mk(filepath.Join(own, "MEMORY.md"))
if err := os.Symlink(filepath.Join(projects, "-data-agents-scanner"), filepath.Join(projects, "-alias")); err != nil {
t.Skip("symlinks unavailable")
}
// A slug pointed at another agent's store, and a Gemini store whose
// .gemini directory is a symlink out of the home: both must be dropped.
victim := filepath.Join(interactiveHomePath("victim"), ".claude", "projects", "-data-agents-victim", "memory")
mk(filepath.Join(victim, "MEMORY.md"))
if err := os.Symlink(filepath.Dir(victim), filepath.Join(projects, "-data-agents-victim")); err != nil {
t.Fatal(err)
}
outside := t.TempDir()
mk(filepath.Join(outside, geminiMemoryFileName))
if err := os.Symlink(outside, filepath.Join(home, ".gemini")); err != nil {
t.Fatal(err)
}

ap := &AgentProcess{Name: "scanner", UID: 1001, Config: config.AgentConfig{Backend: "claude"}}
got := cliMemoryDrainSources(ap, "claude")
wantOwn, _ := filepath.EvalSymlinks(own)
var paths []string
for _, s := range got {
paths = append(paths, s.Path)
if s.Path != wantOwn || s.CLI != cliMemoryClaude {
t.Errorf("source %+v reaches outside the agent's resolved home (want only %s)", s, wantOwn)
}
}
if len(got) != 1 {
t.Fatalf("sources = %v, want the honest store once", paths)
}
}

func TestDrainCLIMemoryForKick_RunsDrainerBeforeWipeOnlyWhenEnabled(t *testing.T) {
withSharedAgentHome(t)
prev := codexHomePrefix
Expand Down
23 changes: 19 additions & 4 deletions src/docs/design/cli-memory-drain.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,12 @@ A file whose drain fails part-way is left untouched and retried on the next
drain. That is safe because dedup makes the drain idempotent.

Reads and the truncate follow the same rules as #17040's
`cliMemoryStores`. Only stores private to the agent are drained; every path
component is checked with `Lstat`, so a planted symlink is never followed. The
truncate and remove run as the agent through the same `su-exec` path as
`cliMemoryRemover`. A store that is still shared (a legacy whole-directory
`cliMemoryStores`. Only stores private to the agent are drained. The plan
was to `Lstat` every path component and to truncate and remove as the agent
through the same `su-exec` path as `cliMemoryRemover`; as shipped, the drain
runs in the hive process and instead opens every memory file through an
`os.Root` anchored at its store (see "Phase 2 as shipped" below and #17251).
A store that is still shared (a legacy whole-directory
bridge, a UID 0 agent, `HIVE_SHARED_AGENT_HOME=1`) is **not** drained. It
cannot be attributed to one agent, and truncating it would wipe other agents'
memory. It is logged once per agent, exactly like `clear_on_kick`, and is left
Expand Down Expand Up @@ -418,6 +420,19 @@ shipped code differs from the plan above, the shipped code is authoritative:
`$CLAUDE_CONFIG_DIR/projects/<slug>/memory/`). Its request carries
`on_write`, which the hive answers as a no-op unless the agent has
`drain_on_write`.
- **Open through the store root (#17251).** The drain never reads or
truncates a memory file by path. Each `Source` is resolved with
`EvalSymlinks` and dropped unless it still lies under the agent's own
resolved home (a slug or `.claude` directory symlinked at another agent's
store is not drained). The store is then opened as an `os.Root` (the parent
directory for a single-file store such as `GEMINI.md`), checked with
`SameFile` against what `Lstat` saw, and every listed file is `Lstat`ed
through the root β€” a symlink entry is refused even when its target stays
inside the root β€” opened through it, required to be a regular file within
the size cap and the same inode `Lstat` reported, and `TruncateDrained`
truncates through that read descriptor. A path swapped for a symlink
between the listing and the open lands in `kept` and the drain error;
nothing outside the store is ever read or emptied.
- **Keys.** The new key is `agents.cli_memory.drain_on_write`, fleet-wide and
per agent, and it has no effect without `drain_to_knowledge`.
- **Seeding.** Not through `seedJSONFile`, which never touches an existing
Expand Down
22 changes: 19 additions & 3 deletions src/pkg/knowledge/climemory/drain.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ type Drainer struct {
type memFile struct {
cli, path, repo string
spoolDir string
// store is the opened source the file is read through; nil for a file
// being retried from the spool.
store *memoryStore
}

// drainRun is the state of one Drain call.
Expand Down Expand Up @@ -133,14 +136,23 @@ func (d *Drainer) Drain(req Request) Result {
}
var files []memFile
for _, src := range req.Sources {
paths, err := memoryFiles(src.Path)
paths, err := listMemoryFiles(src.Path)
if err != nil {
res.Errors = append(res.Errors, err)
continue
}
if len(paths) == 0 {
continue
}
store, err := openMemoryStore(src.Path)
if err != nil {
res.Errors = append(res.Errors, fmt.Errorf("cli-memory drain: opening %s: %w", src.Path, err))
continue
}
defer store.Close()
repo := repoFromClaudeSlug(src.Path, req.Repos)
for _, p := range paths {
files = append(files, memFile{cli: src.CLI, path: p, repo: repo})
files = append(files, memFile{cli: src.CLI, path: p, repo: repo, store: store})
}
}
seen, err := r.prepareVault()
Expand All @@ -165,7 +177,7 @@ func (d *Drainer) Drain(req Request) Result {
}
}
for _, f := range files {
content, err := os.ReadFile(f.path)
content, err := f.store.read(f.path)
if err != nil {
res.Errors = append(res.Errors, fmt.Errorf("cli-memory drain: reading %s: %w", f.path, err))
continue
Expand Down Expand Up @@ -346,6 +358,10 @@ func hashFromFrontmatter(path string) string {
return ""
}

// listMemoryFiles is memoryFiles behind a seam, so a test can hand Drain
// and TruncateDrained a listing the store no longer matches.
var listMemoryFiles = memoryFiles

// memoryFiles lists the markdown files under path (or path itself when it
// is a file), skipping temp files, hidden entries, symlinks and oversized
// files. A missing path is not an error: the CLI simply wrote nothing.
Expand Down
59 changes: 40 additions & 19 deletions src/pkg/knowledge/climemory/legacy.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ func LegacyClaudeSources(projectsDir string) ([]Source, error) {
// holding a fact the vault lacks β€” a write failed, the per-drain cap was
// hit β€” is left as it is and reported in kept, so truncation never loses a
// fact. A non-empty file with no fact to drain (a Claude index of links)
// counts as stored. Already-empty files are in neither list.
// counts as stored. Already-empty files are in neither list. Each file is
// read and truncated through one descriptor opened inside its store, so a
// path the agent swapped for a symlink since the listing is kept, not
// followed.
func (d *Drainer) TruncateDrained(sources []Source) (truncated, kept []string, err error) {
if d == nil || d.Dir == "" {
return nil, nil, errors.New("cli-memory drain: no target directory")
Expand All @@ -57,36 +60,54 @@ func (d *Drainer) TruncateDrained(sources []Source) (truncated, kept []string, e
}
var errs []error
for _, src := range sources {
files, err := memoryFiles(src.Path)
files, err := listMemoryFiles(src.Path)
if err != nil {
errs = append(errs, err)
continue
}
if len(files) == 0 {
continue
}
store, err := openMemoryStore(src.Path)
if err != nil {
errs = append(errs, fmt.Errorf("cli-memory drain: opening %s: %w", src.Path, err))
kept = append(kept, files...)
continue
}
for _, file := range files {
content, err := os.ReadFile(file)
t, k, err := truncateIfStored(store, src.CLI, file, seen)
if err != nil {
errs = append(errs, fmt.Errorf("cli-memory drain: reading %s: %w", file, err))
kept = append(kept, file)
continue
errs = append(errs, err)
}
if len(content) == 0 {
continue
}
if !allStored(ParseFor(src.CLI, string(content)), seen) {
kept = append(kept, file)
continue
}
if err := os.Truncate(file, 0); err != nil {
errs = append(errs, fmt.Errorf("cli-memory drain: truncating %s: %w", file, err))
kept = append(kept, file)
continue
}
truncated = append(truncated, file)
truncated, kept = append(truncated, t...), append(kept, k...)
}
store.Close()
}
return truncated, kept, errors.Join(errs...)
}

func truncateIfStored(store *memoryStore, cli, file string, seen map[string]string) (truncated, kept []string, err error) {
f, err := store.open(file, os.O_RDWR)
if err != nil {
return nil, []string{file}, fmt.Errorf("cli-memory drain: opening %s: %w", file, err)
}
defer f.Close()
content, err := readMemoryFile(f)
if err != nil {
return nil, []string{file}, fmt.Errorf("cli-memory drain: reading %s: %w", file, err)
}
if len(content) == 0 {
return nil, nil, nil
}
if !allStored(ParseFor(cli, string(content)), seen) {
return nil, []string{file}, nil
}
if err := f.Truncate(0); err != nil {
return nil, []string{file}, fmt.Errorf("cli-memory drain: truncating %s: %w", file, err)
}
return []string{file}, nil, nil
}

func allStored(facts []Fact, seen map[string]string) bool {
for _, f := range facts {
if _, ok := seen[Hash(f.Body)]; !ok {
Expand Down
Loading
Loading