Skip to content

fix(security): keep edit backups out of the user's working tree - #3992

Merged
kovtcharov-amd merged 3 commits into
amd:mainfrom
kovtcharov:claude/edit-backups-outside-tree
Sep 24, 2026
Merged

kovtcharov-amd merged 3 commits into
amd:mainfrom
kovtcharov:claude/edit-backups-outside-tree

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Every write_file and edit_file left a name.<timestamp>.bak beside the file it changed, and nothing ever removed it, so every repository the agent worked in slowly filled with backup files the user never asked for. Backups are still made, but now under ~/.gaia/cache/backups/, mirroring the original's full path, so the working tree stays clean. That holds for every edit tool, with or without a path validator. The backup directory is owner-only, and only the five newest backups of each file are kept. On 8 benchmark runs this left zero .bak files in any workspace while 86 backups landed in the cache. A backup that fails for a filesystem reason is skipped with a warning naming both paths; any other error now surfaces instead of being silently swallowed.

Test plan

  • pytest tests/unit/test_file_write_guardrails.py tests/unit/test_security_edge_cases.py tests/unit/agents/ tests/unit/test_replace_function_spans.py tests/unit/test_file_io_directory_path_errors.py: 1066 passed, 57 skipped. Covers the no-validator path, the per-file cap and the directory permissions.
  • The suite no longer writes backups into the real ~/.gaia/cache/backups: none appeared after a run.
  • black, isort, flake8 and pylint clean on the changed files
  • Ask the agent to edit a file in a repo, then confirm git status shows no .bak and the backup exists under ~/.gaia/cache/backups/<repo path>/
  • gaia eval agent has not been run on this change (it touches the edit tools' behaviour)

@github-actions github-actions Bot added documentation Documentation changes tests Test changes security Security-sensitive changes labels Sep 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Edit backups now land in GAIA's own cache instead of beside the file, so the agent stops littering .bak files in every repo it touches. The path-mirroring logic is correct (I checked drive letters, UNC shares, and files at the filesystem root) and the error handling change is a genuine improvement. Two loose ends keep this from being a clean approve.

The fix doesn't cover every path. Two of the edit tools still drop a .bak next to the file when an agent has no path validator attached. The flagship agent always has one, so the common case is fixed — but the guarantee the PR title makes isn't yet true everywhere, and the spec doc for one of those tools still describes the old behaviour.

Nothing ever cleans the new location. Backups used to pile up where the user could see and delete them; now they pile up invisibly in the cache directory, forever. gaia cache clear doesn't touch them. Worth either a retention limit or a way to clear them before this ships to users.

🔒 SECURITY CONCERN (hardening, not an exploit): @kovtcharov-amd — copies of edited files are now aggregated in the home cache under default directory permissions, and they outlive the project they came from. A file edited inside a private directory gets a long-lived copy in a more permissive one. Creating the backups root restrictively would close it.

Real-world evidence

No evidence bundle was produced for this run (evidence-bundle.md is absent), so the verdict rests on static review. The PR description reports a benchmark result — zero .bak files left in any workspace across 8 runs, 86 backups landing in the cache — but doesn't include the captured output, and the manual "edit a file in a repo, then check git status" item is still unchecked. I could not run the unit tests here either (no pytest in this environment), so the "1080 passed" claim is unverified on my side. Checking that one manual box, with the git status and ls ~/.gaia/cache/backups/... output pasted in, would close the gap for this surface. No agent eval is needed — no prompt, tool docstring, or schema changed.

🔍 Technical details

Issues

🟡 The no-validator fallback still writes beside the file (src/gaia/agents/tools/file_io_tools.py:552, :1259)

edit_file and replace_function fall back to backup_path = f"{file_path}.bak" when path_validator is None. ChatAgent sets one (hub/agents/chat/python/gaia_agent_chat/agent.py:252), so the flagship is covered — but any agent composing FileIOToolsMixin without a validator still litters, and the new TestEditingLeavesTheWorkspaceClean always attaches a validator so it can't catch this. Simplest fix: build a PathValidator lazily for the backup, or drop the beside-file copy entirely and skip the backup with a warning (which is what FileSearchToolsMixin already does — it has no .bak fallback at all).

🟡 No retention or cleanup for ~/.gaia/cache/backups (src/gaia/security.py:928)

Every edit adds a file and nothing prunes them. gaia cache clear --all only clears the Context7 cache (src/gaia/cli.py:5188), and gaia uninstall doesn't list the backups tree. Previously the litter was at least visible in git status; now it's invisible and permanent. A per-file generation cap (keep N newest per original) or a gaia cache clear --backups action would make this self-limiting.

🔒 🟡 Backups inherit the cache directory's permissions (src/gaia/security.py:933)

mirror.mkdir(parents=True, exist_ok=True) uses the default mode (0755 under a typical umask). copy2 preserves the file's own mode, but a file that was only reachable because its parent directory was 0700 now has a copy under a world-traversable path — and it persists after the original project is deleted. Creating the backups root with mode=0o700 on first use would bound this.

🟢 replace_function's spec still describes the old behaviour (docs/spec/file-io-tools-mixin.mdx:259)

The edit_file entry was updated but this one wasn't — same tool family, same backup parameter.

- `backup` (bool, optional): Create backup (default: True). With a
  `PathValidator` the copy goes to `~/.gaia/cache/backups/<original absolute
  path>/<name>.<timestamp>.bak`, never beside the file.

🟢 Deeply nested paths on Windows (src/gaia/security.py:936)

Mirroring the full absolute path under ~/.gaia/cache/backups/ adds ~30 characters plus the timestamp suffix. Without long-path support, editing an already-deep file can now push mkdir/copy2 past MAX_PATH, where it previously succeeded — the edit then proceeds with only a warning in the log. Worth a hashed-prefix fallback if it shows up on a Ryzen AI test machine.

Strengths

  • Narrowing except Exception to except OSError — and the test that asserts a RuntimeError now propagates — is exactly what the fail-loudly rule asks for, and the hoisted realpath/exists check keeps the try block to just the I/O.
  • The tests assert the absence of litter (sorted(p.name for p in work.iterdir()) == ["notes.md"]) rather than only the presence of the backup, which is what makes the regression actually catchable. Parametrizing across both mixins is the right instinct too.
  • Drive/UNC normalization is correct: I simulated C:\repo\src\app.py, \\server\share\docs\a.md, C:\a.txt, and /a.txt, and all produce sane, collision-free mirror directories.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

No edit tool puts a backup in the user's tree now, even on an agent without a path validator. Backups no longer pile up: each file keeps its five newest. The backup directory is now owner-only. The replace_function spec is updated. I left the Windows long-path fallback out; the reason is below.

🔍 Technical details

All changes are in 98cc7bc.

Review item Outcome
🟡 .bak beside the file without a validator (edit_python_file, replace_function) Fixed. The backup logic now lives in one function, gaia.security.backup_file. PathValidator.create_backup delegates to it, and both tools call it when no validator is set. A new parametrized test runs both tools with no validator and checks that the repo holds only the edited file and the backup is under ~/.gaia/cache/backups. test_replace_function_spans had pinned the old beside-the-file path; it now asserts the new location. edit_python_file's backup_created now reports whether a backup was actually made, not whether one was requested.
🟡 No retention for ~/.gaia/cache/backups I picked a per-file cap over a gaia cache clear action. It bounds growth without the user needing to know the directory exists, and gaia cache is scoped to the Context7 cache. BACKUP_GENERATIONS = 5: after each backup, older timestamped backups of that one file are removed. The match is exact (<name>.<YYYYmmdd_HHMMSS>.bak), so notes.md.orig's backups are never counted against notes.md. If pruning fails, a warning names the directory, and the new backup is still returned. Documented in both spec entries and the file-search spec.
🔒 🟡 Directory permissions The backups root and every mirrored directory under it are created 0o700, one level at a time, because mkdir(parents=True) ignores mode for parents. A root that already exists is narrowed. A POSIX test checks every level.
🟢 replace_function spec Updated with the same wording as edit_python_file, plus the cap and permissions.
🟢 Windows MAX_PATH Not done. When the path is too long, the copy fails with a warning naming both paths, and the edit itself is unaffected. A hashed fallback would be a second on-disk layout that the cap and the docs would both have to handle, and no Windows unit-test job could exercise it. I'd add it if a real deep path hits the limit on a test machine, as you suggested.

Also fixed. Moving backups to ~/.gaia meant every test that edits through a validator wrote into the developer's real home: 10 files per run here. Those fixtures now use mock_home, and a rerun wrote nothing to the real ~/.gaia/cache/backups. The layout test now expects the drive folder, so it holds on Windows too.

Tests: guardrails, security edge cases, tests/unit/agents/, replace-function spans and the directory-path-error suites: 1066 passed, 57 skipped. Across the 35 test files that exercise write/edit tools: 1979 passed. The 3 failures there are the flagship search_documentation checks, which need npx; they pass with npx on PATH. flake8 and pylint with the repo settings: clean.

The manual "edit a file in a repo, then git status" box stays unticked because it needs a live agent. Per your note, no eval is needed.

Every write_file and edit_file left name.<timestamp>.bak beside the edited
file and nothing removed it, so every repository the agent touched ended up
littered with backups. The backup is still made; it now goes under the
validator's state directory (~/.gaia/cache/backups, beside the audit log that
records it) at the original's absolute path, e.g.
~/.gaia/cache/backups/Users/me/repo/src/app.py.20260918_101500.bak. ".bak"
stays last (amd#3747). A drive letter or UNC share becomes one folder name.

Only a filesystem error now skips the backup, with a warning naming both
paths; any other exception propagates instead of being swallowed. The file
tools only report backup_path, so none of their callers changed.

- Backups are made by one function, backup_file, used with or without a
  validator, so no edit tool (edit_python_file and replace_function included)
  writes a backup into the user's tree.
- Only the five newest backups of each file are kept; older ones are
  removed when a new one lands.
- The backups directory and every directory below it is owner-only.
- edit_python_file reports backup_created from whether a backup was made.
- Tests that edit files now use a temporary home, so the suite no longer
  writes backups into the developer's real ~/.gaia.
@kovtcharov
kovtcharov force-pushed the claude/edit-backups-outside-tree branch from 5fbf778 to a61b34a Compare September 21, 2026 11:59
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Rebased onto current main as one commit. First in the file-edit stack, nothing to merge before it; #4029 builds on this.

@github-actions

Copy link
Copy Markdown
Contributor

🟡 The new doc text makes a claim that contradicts the code. Both edit_python_file and replace_function entries in docs/spec/file-io-tools-mixin.mdx now say backups go to ~/.gaia/cache/backups/ "with or without a PathValidator" — but the code returns an error immediately when path_validator is None, so no backup is written at all in that case. The "never beside the file" guarantee holds, but a reader will infer that backups are always created in the cache dir, which isn't true.

Drop "with or without a PathValidator" from both entries; the guarantee that matters is "never beside the file."

🔍 Technical details

docs/spec/file-io-tools-mixin.mdx:136 and :301:

- beside the file, with or without a `PathValidator`. The backups directory is
+ beside the file. The backups directory is

The behaviour for no-validator callers is already documented in the _missing_path_validator_write_error path (#3316): the tool returns {"status": "error", ...} before any I/O happens. Adding "with or without a PathValidator" implies backups are always created, which contradicts both the code and the test added in this same push (test_without_a_validator_the_edit_is_refused_and_leaves_nothing).

The file-search-mixin.mdx update does not have this wording and is fine.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Refreshed this branch against current main so it can merge again — the branch had fallen far enough behind that GitHub could no longer compute a merge.

The update was a clean merge: nothing was resolved by hand, and no commit on this branch was rewritten. CI now runs against an up-to-date base.

"never beside the file, with or without a PathValidator" implied a
backup is always created in the cache dir. The code returns an error
before any I/O when path_validator is None (_missing_path_validator_write_error)
-- no backup is written at all in that case. The guarantee that holds is
"never beside the file"; dropped the rest.

The other three findings from the same review (no-validator fallback
still writing beside the file, missing backup retention, default cache
directory permissions) are already fixed in the current code -- verified
against security.py's backup_file(), which already creates the backups
root at mode 0o700 and prunes to BACKUP_GENERATIONS.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 24, 2026
Merged via the queue into amd:main with commit 3ce81e6 Sep 24, 2026
39 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes security Security-sensitive changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants