Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/security-17256-climemory-ancestor-nofollow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- The CLI-memory drain now reaches each memory store by opening its directories one component at a time from the filesystem root, refusing any component that is a symlink and requiring each opened directory to be the inode `Lstat` saw. `cliMemoryDrainSources` already resolved stores with `EvalSymlinks` and kept only those under the agent's own home, but the drain still opened the store root by path, so an agent that swapped `.claude`, `projects` or a project slug for a symlink after that listing could have had another agent's store (or any hive-readable `memory/*.md` tree) drained under its own name and, with `truncate`, emptied. Such a store is now reported in `kept` and the drain error, never followed ([#17256](https://github.com/hivecommons/hive/issues/17256)).
24 changes: 24 additions & 0 deletions src/pkg/knowledge/climemory/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package climemory

import (
"fmt"
"os"
"path/filepath"
"testing"
)

// TestMain points the temp dir at its symlink-free path. openMemoryStore
// refuses every symlinked ancestor, so on macOS, where $TMPDIR sits under
// /var -> /private/var, stores under a raw t.TempDir() could not be opened.
func TestMain(m *testing.M) {
resolved, err := filepath.EvalSymlinks(os.TempDir())
if err != nil {
fmt.Fprintf(os.Stderr, "resolve temp dir: %v\n", err)
os.Exit(1)
}
if err := os.Setenv("TMPDIR", resolved); err != nil {
fmt.Fprintf(os.Stderr, "set TMPDIR: %v\n", err)
os.Exit(1)
}
os.Exit(m.Run())
}
110 changes: 89 additions & 21 deletions src/pkg/knowledge/climemory/memstore.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io"
"os"
"path/filepath"
"strings"
)

// errNotMemoryFile marks a listed path that is no longer a regular memory
Expand All @@ -24,45 +25,112 @@ type memoryStore struct {
}

// openMemoryStore opens the store directory for path — path itself when it
// is a directory, its parent for a file store — and checks that the opened
// directory is the one Lstat sees at that path, so a store directory
// swapped for a symlink since memoryFiles listed it is refused rather than
// followed.
// is a directory, its parent for a file store. path is the store as the hive
// listed it with every symlink already resolved (the crux side resolves it
// with EvalSymlinks and keeps it only under the agent's own home), so no
// component of it may be a symlink by the time it is opened. The agent owns
// every directory from its home down and can swap any of them (`.claude`,
// `projects`, the project slug, the store itself) for a symlink after that
// listing; a path-based open would follow it to another agent's store or any
// hive-readable tree and drain, and with truncate empty, it under this
// agent's name. The directories are therefore opened one component at a time
// from the filesystem root, each refused when it is a symlink and checked to
// be the very inode Lstat saw, so the store root is reached without following
// a single symlink.
func openMemoryStore(path string) (*memoryStore, error) {
base := path
lfi, err := os.Lstat(path)
if !filepath.IsAbs(path) {
return nil, fmt.Errorf("%w: %s is not an absolute path", errNotMemoryFile, path)
}
path = filepath.Clean(path)
dir, name := filepath.Split(path)
if name == "" {
return nil, fmt.Errorf("%w: %s is not a memory store", errNotMemoryFile, path)
}
parent, err := openDirNoFollow(filepath.Clean(dir))
if err != nil {
return nil, err
}
// memoryFiles never lists a symlinked store, so one here was swapped in
// after the listing; refuse it before the file-store fallback below
// would otherwise open its (real) parent directory and pass SameFile.
if lfi.Mode()&os.ModeSymlink != 0 {
lfi, err := parent.Lstat(name)
switch {
case err != nil:
parent.Close()
return nil, err
case lfi.IsDir():
root, err := openChildDirNoFollow(parent, name, lfi)
parent.Close()
if err != nil {
return nil, err
}
return &memoryStore{root: root}, nil
case lfi.Mode()&os.ModeSymlink != 0:
// memoryFiles never lists a symlinked store, so one here was swapped
// in after the listing; refuse it rather than open its parent.
parent.Close()
return nil, fmt.Errorf("%w: %s is a symlink", errNotMemoryFile, path)
default:
// A single-file store is opened through the directory holding it;
// open checks the file itself.
return &memoryStore{root: parent}, nil
}
if !lfi.IsDir() {
base = filepath.Dir(path)
if lfi, err = os.Lstat(base); err != nil {
}

// openDirNoFollow opens the absolute, clean directory dir by walking it from
// the filesystem root one component at a time with openChildDirNoFollow, so
// a symlink anywhere in dir is refused instead of followed. The returned
// root's Name is dir.
func openDirNoFollow(dir string) (*os.Root, error) {
vol := filepath.VolumeName(dir)
root, err := os.OpenRoot(vol + string(filepath.Separator))
if err != nil {
return nil, err
}
rest := strings.Trim(dir[len(vol):], string(filepath.Separator))
if rest == "" {
return root, nil
}
for _, name := range strings.Split(rest, string(filepath.Separator)) {
lfi, err := root.Lstat(name)
if err != nil {
root.Close()
return nil, err
}
next, err := openChildDirNoFollow(root, name, lfi)
root.Close()
if err != nil {
return nil, err
}
root = next
}
return root, nil
}

// openChildDirNoFollow opens name, an entry directly inside parent that
// Lstat reported as lfi, as a root. A symlink or non-directory is refused,
// and the opened directory must be the very inode Lstat saw: os.Root follows
// a symlink that stays inside parent, so a directory swapped for one between
// the two calls would otherwise be opened at its target.
func openChildDirNoFollow(parent *os.Root, name string, lfi os.FileInfo) (*os.Root, error) {
path := filepath.Join(parent.Name(), name)
if lfi.Mode()&os.ModeSymlink != 0 {
return nil, fmt.Errorf("%w: %s is a symlink", errNotMemoryFile, path)
}
if !lfi.IsDir() {
return nil, fmt.Errorf("%w: %s is not a directory", errNotMemoryFile, base)
return nil, fmt.Errorf("%w: %s is not a directory", errNotMemoryFile, path)
}
root, err := os.OpenRoot(base)
child, err := parent.OpenRoot(name)
if err != nil {
return nil, err
}
rfi, err := root.Stat(".")
cfi, err := child.Stat(".")
if err != nil {
root.Close()
child.Close()
return nil, err
}
if !os.SameFile(lfi, rfi) {
root.Close()
return nil, fmt.Errorf("%w: %s changed while being opened", errNotMemoryFile, base)
if !os.SameFile(lfi, cfi) {
child.Close()
return nil, fmt.Errorf("%w: %s changed while being opened", errNotMemoryFile, path)
}
return &memoryStore{root: root}, nil
return child, nil
}

func (s *memoryStore) Close() error {
Expand Down
41 changes: 41 additions & 0 deletions src/pkg/knowledge/climemory/memstore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,47 @@ func TestOpenMemoryStoreRefusesSwappedStoreDirectory(t *testing.T) {
}
}

func TestTruncateDrainedNeverFollowsSymlinkedAncestorOfStore(t *testing.T) {
// The hive lists ~/.claude/projects/<slug>/memory with every symlink
// resolved, but the agent owns <slug> and can swap it for a symlink to
// another agent's project before the drain opens the store. The store
// path itself still Lstats as a real directory, so only refusing the
// symlinked ancestor keeps the other agent's store from being emptied.
base, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
otherProject := filepath.Join(base, "other", ".claude", "projects", "-data-agents-other")
victim := filepath.Join(otherProject, "memory", "MEMORY.md")
// No "- " bullets: zero facts count as fully stored, so a truncate that
// followed the symlink would empty it.
writeFile(t, victim, "# another agent's index\n")
slug := filepath.Join(base, "scanner", ".claude", "projects", "-data-agents-scanner")
store := filepath.Join(slug, "memory")
writeFile(t, filepath.Join(store, "MEMORY.md"), "# own index\n")
if err := os.Rename(slug, slug+".moved"); err != nil {
t.Fatal(err)
}
if err := os.Symlink(otherProject, slug); err != nil {
t.Skip("symlinks unavailable")
}

d := &Drainer{Dir: t.TempDir(), Now: fixedNow}
truncated, kept, err := d.TruncateDrained([]Source{{CLI: CLIClaude, Path: store}})
if len(truncated) != 0 {
t.Fatalf("truncated %v through a symlinked ancestor", truncated)
}
if len(kept) != 1 || kept[0] != filepath.Join(store, "MEMORY.md") {
t.Fatalf("kept = %v, want the listed file", kept)
}
if err == nil || !errors.Is(err, errNotMemoryFile) {
t.Fatalf("err = %v, want errNotMemoryFile", err)
}
if b, _ := os.ReadFile(victim); !strings.Contains(string(b), "another agent's index") {
t.Fatalf("store behind the symlinked ancestor was truncated: %q", b)
}
}

func TestMemoryStoreOpenKeepsSingleFileStoreWorking(t *testing.T) {
home := t.TempDir()
gemini := filepath.Join(home, "GEMINI.md")
Expand Down
Loading