Skip to content

Commit 8c5b3df

Browse files
GWealecopybara-github
authored andcommitted
fix: check where a builder app name imports from
The builder YAML upload check decided whether an app name shadowed an importable module by comparing it with built-in and standard library names, so an app named after an installed package passed and its references loaded that package's code. The check now asks the import system where the name would load from, without running any module code, and refuses the references unless that is inside the app's own directory. Co-authored-by: George Weale <[email protected]> PiperOrigin-RevId: 991976594
1 parent 731ea30 commit 8c5b3df

2 files changed

Lines changed: 55 additions & 13 deletions

File tree

‎src/google/adk/cli/dev_server.py‎

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232

3333
import asyncio
3434
from collections.abc import AsyncIterator
35+
import importlib.util
3536
import json
3637
import logging
3738
import os
@@ -251,25 +252,38 @@ def _is_adk_built_in(reference: str) -> bool:
251252
return False
252253

253254

254-
def _app_name_shadows_module(app_name: str) -> bool:
255-
"""Whether the app name collides with a module that can be imported."""
256-
# "google" is a namespace package rather than a standard library module, so
257-
# it has to be named explicitly.
258-
return (
259-
app_name in sys.builtin_module_names
260-
or app_name in sys.stdlib_module_names
261-
or app_name == "google"
255+
def _app_name_shadows_module(app_name: str, app_root: Path) -> bool:
256+
"""Whether importing the app name would load code from outside the app."""
257+
# find_spec imports a dotted name's parents, so only look up the first part.
258+
try:
259+
spec = importlib.util.find_spec(app_name.partition(".")[0])
260+
except ValueError:
261+
return True
262+
if spec is None:
263+
return False
264+
locations = list(spec.submodule_search_locations or [])
265+
if spec.has_location and spec.origin is not None:
266+
locations.append(spec.origin)
267+
return not locations or not all(
268+
Path(location).resolve().is_relative_to(app_root)
269+
for location in locations
262270
)
263271

264272

265273
def _check_code_reference(
266-
reference: str, *, app_name: str, filename: str, field_name: str
274+
reference: str,
275+
*,
276+
app_name: str,
277+
app_root: Path,
278+
filename: str,
279+
field_name: str,
267280
) -> None:
268281
"""Checks that a code reference stays inside the app being edited.
269282
270283
Args:
271284
reference: The name found in the uploaded document.
272285
app_name: The app the document belongs to.
286+
app_root: The app's resolved directory.
273287
filename: The uploaded path, used in the error message.
274288
field_name: The config field the reference came from.
275289
@@ -287,7 +301,7 @@ def _check_code_reference(
287301
f" '{field_name}' field may only reference code under"
288302
f" '{app_name}' or an ADK built-in."
289303
)
290-
if _app_name_shadows_module(app_name):
304+
if _app_name_shadows_module(app_name, app_root):
291305
raise ValueError(
292306
f"Blocked code reference {reference!r} in {filename!r}. The app name"
293307
f" {app_name!r} shadows an importable Python module, so a reference to"
@@ -566,6 +580,7 @@ def _check_uploaded_yaml(
566580
content: bytes, *, filename: str, app_name: str
567581
) -> None:
568582
"""Raise if the YAML would let the loader run code outside the app."""
583+
app_root = _get_app_root(app_name)
569584
try:
570585
docs = list(yaml.safe_load_all(content))
571586
except yaml.YAMLError as exc:
@@ -585,6 +600,7 @@ def _walk(node: Any) -> None:
585600
_check_code_reference(
586601
reference,
587602
app_name=app_name,
603+
app_root=app_root,
588604
filename=filename,
589605
field_name=key,
590606
)

‎tests/unittests/cli/test_fast_api.py‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -781,6 +781,8 @@ def builder_test_client(
781781
"""Return a TestClient rooted in a temporary agents directory."""
782782
with (
783783
patch.object(signal, "signal", autospec=True, return_value=None),
784+
# Building the app adds tmp_path to sys.path; undo it for later tests.
785+
patch.object(sys, "path", list(sys.path)),
784786
patch.object(
785787
fast_api_module,
786788
"create_session_service_from_options",
@@ -3940,19 +3942,43 @@ def test_builder_save_rejects_external_schema_reference(builder_test_client):
39403942
assert "input_schema" in response.json()["detail"]
39413943

39423944

3945+
@pytest.mark.parametrize(
3946+
("app_name", "reference"),
3947+
[
3948+
("os", "os.system"),
3949+
("sys", "sys.exit"),
3950+
("google", "google.genai.Client"),
3951+
("dotenv", "dotenv.cli.run_command"),
3952+
],
3953+
)
39433954
def test_builder_save_rejects_reference_when_app_name_shadows_module(
3944-
builder_test_client,
3955+
builder_test_client, app_name, reference
39453956
):
39463957
"""An app named after a real module cannot vouch for its own references."""
39473958
response = _save_builder_yaml(
39483959
builder_test_client,
3949-
b"name: my_agent\ntools:\n - name: os.system\n",
3950-
app_name="os",
3960+
f"name: my_agent\ntools:\n - name: {reference}\n".encode(),
3961+
app_name=app_name,
39513962
)
39523963
assert response.status_code == 400
39533964
assert "shadows" in response.json()["detail"]
39543965

39553966

3967+
def test_builder_save_allows_reference_when_app_imports_from_its_directory(
3968+
builder_test_client, tmp_path, monkeypatch
3969+
):
3970+
"""An app that is importable passes when it imports from its own folder."""
3971+
(tmp_path / "importable_app").mkdir()
3972+
(tmp_path / "importable_app" / "__init__.py").touch()
3973+
monkeypatch.syspath_prepend(str(tmp_path))
3974+
response = _save_builder_yaml(
3975+
builder_test_client,
3976+
b"name: my_agent\ntools:\n - name: importable_app.tools.search\n",
3977+
app_name="importable_app",
3978+
)
3979+
assert response.status_code == 200
3980+
3981+
39563982
def test_builder_save_covers_every_code_config_field(builder_test_client):
39573983
"""Every config field holding a CodeConfig is checked on upload."""
39583984
code_config_fields = set()

0 commit comments

Comments
 (0)