Skip to content

Commit 1fa7cda

Browse files
committed
fix: block path traversal in Agent Builder file tools
Constrain resolved file paths to the project root so the write, read, and delete tools cannot escape it via `..` segments or absolute paths. Change-Id: I3881c230fbc48cda1bca8a75b1e822eecccb934c
1 parent faa5db6 commit 1fa7cda

3 files changed

Lines changed: 213 additions & 13 deletions

File tree

src/google/adk/cli/built_in_agents/utils/resolve_root_directory.py

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -42,33 +42,43 @@ def resolve_file_path(
4242
working_directory: Working directory to use as base (defaults to cwd)
4343
4444
Returns:
45-
Resolved absolute Path object
45+
Resolved absolute Path object, guaranteed to be within the root directory.
46+
47+
Raises:
48+
ValueError: If ``file_path`` resolves outside the root directory, e.g. via
49+
``..`` traversal or an absolute path pointing outside the root.
4650
"""
4751
normalized_path = sanitize_generated_file_path(file_path)
4852
file_path_obj = Path(normalized_path)
4953

50-
# If already absolute, use as-is
51-
if file_path_obj.is_absolute():
52-
return file_path_obj
53-
5454
# Get root directory from session state, default to "./"
5555
root_directory = "./"
5656
if session_state and "root_directory" in session_state:
5757
root_directory = session_state["root_directory"]
5858

59-
# Use the same resolution logic as the main function
6059
root_path_obj = Path(root_directory)
61-
6260
if root_path_obj.is_absolute():
6361
resolved_root = root_path_obj
62+
elif working_directory:
63+
resolved_root = Path(working_directory) / root_directory
6464
else:
65-
if working_directory:
66-
resolved_root = Path(working_directory) / root_directory
67-
else:
68-
resolved_root = Path(os.getcwd()) / root_directory
65+
resolved_root = Path(os.getcwd()) / root_directory
66+
resolved_root = resolved_root.resolve()
6967

70-
# Resolve file path relative to root directory
71-
return resolved_root / file_path_obj
68+
if file_path_obj.is_absolute():
69+
candidate = file_path_obj.resolve()
70+
else:
71+
candidate = (resolved_root / file_path_obj).resolve()
72+
73+
# Keep the resolved path within the root to block path-traversal escapes.
74+
try:
75+
candidate.relative_to(resolved_root)
76+
except ValueError as exc:
77+
raise ValueError(
78+
f"File path {file_path!r} resolves outside the root directory"
79+
f" {resolved_root}."
80+
) from exc
81+
return candidate
7282

7383

7484
def resolve_file_paths(
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Import-isolation guard for adk_web_server.
16+
17+
Importing ``adk_web_server`` must not eagerly pull in the Agent Builder agent
18+
stack. Doing so reaches ``google.adk.agents`` at import time and breaks
19+
downstream consumers that import ``adk_web_server`` while ``google.adk.agents``
20+
is still initializing.
21+
"""
22+
23+
from __future__ import annotations
24+
25+
import subprocess
26+
import sys
27+
28+
29+
def test_importing_adk_web_server_does_not_import_agent_builder():
30+
# Run in a fresh interpreter so the check is not polluted by modules that
31+
# other tests already imported into sys.modules.
32+
code = (
33+
"import google.adk.cli.adk_web_server\n"
34+
"import sys\n"
35+
"forbidden = [\n"
36+
" 'google.adk.cli.built_in_agents.agent',\n"
37+
" 'google.adk.cli.built_in_agents.adk_agent_builder_assistant',\n"
38+
"]\n"
39+
"loaded = [name for name in forbidden if name in sys.modules]\n"
40+
"assert not loaded, loaded\n"
41+
)
42+
43+
result = subprocess.run(
44+
[sys.executable, "-c", code],
45+
capture_output=True,
46+
text=True,
47+
check=False,
48+
)
49+
50+
assert result.returncode == 0, result.stderr
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Path-traversal containment tests for Agent Builder file tools."""
16+
17+
from __future__ import annotations
18+
19+
import os
20+
from pathlib import Path
21+
from unittest import mock
22+
23+
from google.adk.cli.built_in_agents.tools.delete_files import delete_files
24+
from google.adk.cli.built_in_agents.tools.read_files import read_files
25+
from google.adk.cli.built_in_agents.tools.write_files import write_files
26+
from google.adk.cli.built_in_agents.utils.resolve_root_directory import resolve_file_path
27+
import pytest
28+
29+
30+
def _tool_context(root: Path) -> mock.MagicMock:
31+
tool_context = mock.MagicMock()
32+
tool_context._invocation_context.session.state = {"root_directory": str(root)}
33+
return tool_context
34+
35+
36+
def test_resolve_file_path_allows_path_within_root(tmp_path):
37+
resolved = resolve_file_path(
38+
"sub/dir/file.txt", {"root_directory": str(tmp_path)}
39+
)
40+
assert resolved == (tmp_path / "sub" / "dir" / "file.txt").resolve()
41+
42+
43+
def test_resolve_file_path_allows_dot(tmp_path):
44+
resolved = resolve_file_path(".", {"root_directory": str(tmp_path)})
45+
assert resolved == tmp_path.resolve()
46+
47+
48+
def test_resolve_file_path_allows_interior_dotdot_within_root(tmp_path):
49+
resolved = resolve_file_path(
50+
"sub/../file.txt", {"root_directory": str(tmp_path)}
51+
)
52+
assert resolved == (tmp_path / "file.txt").resolve()
53+
54+
55+
def test_resolve_file_path_allows_absolute_within_root(tmp_path):
56+
target = tmp_path / "nested" / "ok.txt"
57+
resolved = resolve_file_path(str(target), {"root_directory": str(tmp_path)})
58+
assert resolved == target.resolve()
59+
60+
61+
def test_resolve_file_path_rejects_relative_traversal(tmp_path):
62+
with pytest.raises(ValueError):
63+
resolve_file_path("../../escape.txt", {"root_directory": str(tmp_path)})
64+
65+
66+
def test_resolve_file_path_rejects_absolute_outside_root(tmp_path):
67+
with pytest.raises(ValueError):
68+
resolve_file_path("/etc/passwd", {"root_directory": str(tmp_path)})
69+
70+
71+
async def test_write_files_blocks_relative_traversal(
72+
tmp_path, tmp_path_factory
73+
):
74+
outside = tmp_path_factory.mktemp("outside")
75+
payload = os.path.relpath(outside / "pwned.txt", tmp_path)
76+
77+
result = await write_files(
78+
files={payload: "PWNED"}, tool_context=_tool_context(tmp_path)
79+
)
80+
81+
assert not result["success"]
82+
assert not (outside / "pwned.txt").exists()
83+
84+
85+
async def test_write_files_blocks_absolute_outside_root(
86+
tmp_path, tmp_path_factory
87+
):
88+
outside = tmp_path_factory.mktemp("outside")
89+
target = outside / "abs.txt"
90+
91+
result = await write_files(
92+
files={str(target): "PWNED"}, tool_context=_tool_context(tmp_path)
93+
)
94+
95+
assert not result["success"]
96+
assert not target.exists()
97+
98+
99+
async def test_write_files_allows_path_within_root(tmp_path):
100+
result = await write_files(
101+
files={"sub/ok.txt": "hello"}, tool_context=_tool_context(tmp_path)
102+
)
103+
104+
assert result["success"]
105+
assert (tmp_path / "sub" / "ok.txt").read_text() == "hello"
106+
107+
108+
async def test_read_files_blocks_relative_traversal(tmp_path, tmp_path_factory):
109+
outside = tmp_path_factory.mktemp("outside")
110+
secret = outside / "secret.txt"
111+
secret.write_text("TOKEN=abc")
112+
payload = os.path.relpath(secret, tmp_path)
113+
114+
result = await read_files(
115+
file_paths=[payload], tool_context=_tool_context(tmp_path)
116+
)
117+
118+
assert not result["success"]
119+
assert all(
120+
"TOKEN=abc" not in info.get("content", "")
121+
for info in result["files"].values()
122+
)
123+
124+
125+
async def test_delete_files_blocks_relative_traversal(
126+
tmp_path, tmp_path_factory
127+
):
128+
outside = tmp_path_factory.mktemp("outside")
129+
victim = outside / "victim.txt"
130+
victim.write_text("bye")
131+
payload = os.path.relpath(victim, tmp_path)
132+
133+
result = await delete_files(
134+
file_paths=[payload],
135+
tool_context=_tool_context(tmp_path),
136+
confirm_deletion=True,
137+
)
138+
139+
assert not result["success"]
140+
assert victim.exists()

0 commit comments

Comments
 (0)