Skip to content
Closed
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
27 changes: 12 additions & 15 deletions src/agent_env/providers/env_providers/env_gateway_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@
from agent_env.env.envs.service_db import (
CONSOLE_SERVICE_NAMES,
DATABASE_SERVICE_NAME,
DB_MCP_CONTAINER_PORT,
DB_MCP_PORT,
DB_MCP_SERVICE_NAME,
DB_WEB_PORT,
Expand Down Expand Up @@ -887,8 +886,11 @@ async def _deploy_via_vm(
vm_kwargs["cpu"] = cpu
if memory_mb is not None:
vm_kwargs["memory"] = memory_mb
# The SQL consoles are never tunnelled: the gateway serves them behind its control token. Only the local
# provider gets a host port for them (its own free port, published on 127.0.0.1), so two local envs don't clash.
console_ports = [DB_WEB_PORT, DB_MCP_PORT] if sandbox_provider.ON_THIS_MACHINE else []

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Remote provider test fails

The new ON_THIS_MACHINE check breaks test_deploy_via_vm_asks_for_no_tunnel_to_the_sql_consoles. That test creates an unconfigured MagicMock, whose ON_THIS_MACHINE attribute is truthy. Both console ports therefore enter exposed_ports, and the assertions excluding them fail. Set ON_THIS_MACHINE=False on the test's provider mock so it represents a remote provider.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agent_env/providers/env_providers/env_gateway_provider.py
Line: 891

Comment:
**Remote provider test fails**

The new `ON_THIS_MACHINE` check breaks `test_deploy_via_vm_asks_for_no_tunnel_to_the_sql_consoles`. That test creates an unconfigured `MagicMock`, whose `ON_THIS_MACHINE` attribute is truthy. Both console ports therefore enter `exposed_ports`, and the assertions excluding them fail. Set `ON_THIS_MACHINE=False` on the test's provider mock so it represents a remote provider.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Cursor Fix in Claude Code Fix in Codex

self._sandbox = await sandbox_provider.create_vm(
exposed_ports=[gateway_port, DB_WEB_PORT, DB_MCP_PORT] + [sc.host_port for sc in sidecars],
exposed_ports=[gateway_port, *console_ports] + [sc.host_port for sc in sidecars],
timeout=ttl_seconds,
disk_size_gb=disk_size_gb,
attribution=attribution,
Expand Down Expand Up @@ -1020,13 +1022,9 @@ async def _stand_up(_spec):
logger.warning(f"{name} container not found")

gateway_url = tunnel_url(gateway_port)
db_web_base_url = tunnel_url(DB_WEB_PORT) if PGWEB_SERVICE_NAME in sidecar_names else None
db_web_url = f"{db_web_base_url}/" if db_web_base_url else None
db_mcp_base_url = tunnel_url(DB_MCP_PORT) if DB_MCP_SERVICE_NAME in sidecar_names else None
db_mcp_url = f"{db_mcp_base_url}/mcp" if db_mcp_base_url else None
logger.info(f"pgweb URL: {db_web_url}")
if db_mcp_url:
logger.info(f"DB MCP endpoint: {db_mcp_url}")
# No public tunnel reaches the unauthenticated SQL consoles; the records name the gateway's guarded routes.
db_web_url = None
db_mcp_url = None

# Wait for the tunnel to serve the env card, which the deploy records
card = await self._wait_for_tunnel(gateway_url, timeout=120)
Expand Down Expand Up @@ -1130,8 +1128,6 @@ async def _deploy_via_containers(
external: list[ExternalChild] = []

mcp_results: list[tuple[str, "Sandbox"]] = []
pgweb_sb = None
db_mcp_sb = None
consoles: dict[str, str] = {}
errors: list[BaseException] = []
for i, r in enumerate(all_results):
Expand All @@ -1150,10 +1146,8 @@ async def _deploy_via_containers(
if r.private_host:
consoles[spec.name] = f"http://{r.private_host}:{spec.port}"
if spec.name == PGWEB_SERVICE_NAME:
pgweb_sb = r
self._pgweb_sandbox = r
elif spec.name == DB_MCP_SERVICE_NAME:
db_mcp_sb = r
self._db_mcp_sandbox = r

if errors:
Expand Down Expand Up @@ -1203,8 +1197,9 @@ async def _deploy_via_containers(
card_read_at_utc = datetime.now(timezone.utc).isoformat()
await self._refuse_tool_name_clashes(gateway_url)

db_web_url = pgweb_sb.tunnel_urls[DB_WEB_PORT] + "/" if pgweb_sb else None
db_mcp_url = db_mcp_sb.tunnel_urls[DB_MCP_CONTAINER_PORT] + "/mcp" if db_mcp_sb else None
# The sidecars have no public tunnel; the gateway serves them behind its control token.
db_web_url = None
db_mcp_url = None
served = await self._served_consoles(gateway_url, consoles, control_token)
return DeployedGateway(
gateway_url=gateway_url,
Expand Down Expand Up @@ -1438,6 +1433,7 @@ async def _provision_sidecar(self, deploy: _ContainerDeploy, spec) -> Sandbox:
disk_size_gb=deploy.disk_size_gb, timeout=deploy.ttl_seconds,
attribution=deploy.attribution,
private_network=True,
expose_externally=False,
)
self._container_sandboxes.append(sb)
return sb
Expand Down Expand Up @@ -1538,6 +1534,7 @@ async def _provision_mcp(
disk_size_gb=deploy.disk_size_gb, timeout=deploy.ttl_seconds,
attribution=deploy.attribution,
private_network=True,
expose_externally=False,
)
self._container_sandboxes.append(sb)
return cfg.environment_name, sb
Expand Down
3 changes: 2 additions & 1 deletion src/agent_env/providers/env_state/local_postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,8 @@ def render_sidecar_containers(
"""The pgweb + db-mcp direct-SQL browse UIs (VM/compose path), each gated on the
servicedb's health. Beyond the mandatory readiness service."""
# Opened from the host only, so kept off the bridge address containers reach the host through.
host_ips = host_ips[:1]
# A remote VM gives no address; a bare binding would publish the unauthenticated consoles on every interface.
host_ips = host_ips[:1] or ("127.0.0.1",)
publish = host_port or (lambda port: port)
cfg = self.service_db_config
lines: list[str] = []
Expand Down
24 changes: 18 additions & 6 deletions tst/unit/providers/compose_host_port_publish_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,9 @@ def test_gateway_compose_defaults_to_identity(stub_postgres):
state_instance=_StateInstance(),
)

assert f'"{DB_WEB_PORT}:{DB_WEB_PORT}"' in compose
assert f'"{DB_MCP_PORT}:{DB_MCP_CONTAINER_PORT}"' in compose
# The consoles stay on loopback when no host IP is given; a sidecar keeps its bare binding.
assert f'"127.0.0.1:{DB_WEB_PORT}:{DB_WEB_PORT}"' in compose
assert f'"127.0.0.1:{DB_MCP_PORT}:{DB_MCP_CONTAINER_PORT}"' in compose
assert '"18768:8000"' in compose


Expand All @@ -230,17 +231,28 @@ def test_postgres_sidecar_fragment_resolves_host_ports(stub_postgres):
stub_postgres.render_sidecar_containers(["slack"], host_port=lambda p: p + OFFSET),
)

assert f'"{DB_WEB_PORT + OFFSET}:{DB_WEB_PORT}"' in lines
assert f'"{DB_MCP_PORT + OFFSET}:{DB_MCP_CONTAINER_PORT}"' in lines
assert f'"127.0.0.1:{DB_WEB_PORT + OFFSET}:{DB_WEB_PORT}"' in lines
assert f'"127.0.0.1:{DB_MCP_PORT + OFFSET}:{DB_MCP_CONTAINER_PORT}"' in lines
# Container side untouched: it is the env's internal contract.
assert f'"{DB_WEB_PORT}:{DB_WEB_PORT}"' not in lines


def test_postgres_sidecar_fragment_defaults_to_identity(stub_postgres):
lines = "\n".join(stub_postgres.render_sidecar_containers(["slack"]))

assert f'"{DB_WEB_PORT}:{DB_WEB_PORT}"' in lines
assert f'"{DB_MCP_PORT}:{DB_MCP_CONTAINER_PORT}"' in lines
assert f'"127.0.0.1:{DB_WEB_PORT}:{DB_WEB_PORT}"' in lines
assert f'"127.0.0.1:{DB_MCP_PORT}:{DB_MCP_CONTAINER_PORT}"' in lines


def test_sql_consoles_are_never_published_on_every_interface(stub_postgres):
"""A remote VM gives no host IP. The unauthenticated SQL consoles must still bind to loopback only."""
for host_ips in ((), ("127.0.0.1",)):
specs = [
line.strip() for line in stub_postgres.render_sidecar_containers(["slack"], host_ips=host_ips)
if _PORT_PAIR.search(line)
]
assert len(specs) == 2
assert all(spec.startswith('- "127.0.0.1:') for spec in specs), specs


@pytest.mark.parametrize("host_ips", [("127.0.0.1",), ("127.0.0.1", "172.17.0.1")], ids=["loopback", "loopback-and-bridge"])
Expand Down
69 changes: 69 additions & 0 deletions tst/unit/providers/env_providers/env_gateway_provider_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1495,6 +1495,75 @@ def _fake_env_get(env_id, *a, **k):
assert sidecar_art in loaded, "sidecar image_artifact was not side-loaded onto the VM"


@pytest.mark.asyncio
async def test_a_container_sidecar_is_created_with_no_public_tunnel():
"""pgweb and db-mcp answer SQL without authentication, so the gateway alone reaches them, over the private network."""
from agent_env.providers.env_providers.env_gateway_provider import _ContainerDeploy

sandbox_provider = MagicMock()
sandbox_provider.create_container = AsyncMock(return_value=MagicMock())
deploy = _ContainerDeploy(sandbox_provider=sandbox_provider, cpu=None, disk_size_gb=10, ttl_seconds=60, attribution=None)
spec = MagicMock(image="pgweb:test", port=8081, env={}, command=None)
spec.name = "pgweb"

await EnvironmentGatewayProvider()._provision_sidecar(deploy, spec)

kwargs = sandbox_provider.create_container.call_args.kwargs
assert kwargs["expose_externally"] is False
assert kwargs["private_network"] is True


@pytest.mark.asyncio
async def test_deploy_via_vm_asks_for_no_tunnel_to_the_sql_consoles():
"""A VM exposes the gateway port, never the unauthenticated pgweb and db-mcp ports."""
from agent_env.env.envs.service_db import DB_MCP_PORT, DB_WEB_PORT
from agent_env.env.gateway import GatewayMode
from agent_env.providers.env_state import DatabaseStateProvider

gp = EnvironmentGatewayProvider()
state_provider = MagicMock(spec=DatabaseStateProvider)
state_provider.prepare = AsyncMock()
gp._state_provider = state_provider
gp._state_instance = MagicMock()
sandbox_provider = MagicMock()
sandbox_provider.create_vm = AsyncMock(return_value=AsyncMock())

class _Stop(Exception):
pass

def _fake_env_get(env_id, *a, **k):
env = MagicMock(docker_image_artifact=_loadable(env_id)); env.environment_name = env_id; return env

with patch("agent_env.env.env.Env.get", side_effect=_fake_env_get), \
patch("agent_env.config.get_config", return_value=MagicMock(default_gateway_env_id="gw-id")), \
patch.object(gp, "create_docker_compose", side_effect=_Stop):
with pytest.raises(_Stop):
await gp._deploy_via_vm(
sandbox_provider=sandbox_provider,
mcp_servers=[MCPServerConfig(image="mcp-slack", environment_name="slack")],
mcp_server_images=[_loadable("mcp-slack")],
gateway_port=18765,
website_configs=None,
website_images=None,
gateway_mode=GatewayMode.PERFORMANCE,
ttl_seconds=60,
disk_size_gb=10,
sidecars=[],
)

exposed = sandbox_provider.create_vm.call_args.kwargs["exposed_ports"]
assert 18765 in exposed
assert DB_WEB_PORT not in exposed
assert DB_MCP_PORT not in exposed


def test_a_local_deploy_still_gets_its_own_host_ports_for_the_consoles():
"""Local envs need separate host ports for the loopback-only consoles so two deploys do not clash."""
import inspect
src = inspect.getsource(EnvironmentGatewayProvider._deploy_via_vm)
assert "if sandbox_provider.ON_THIS_MACHINE else []" in src


# --- name injection: SERVICE_NAME + ENVIRONMENT_NAME --------------------------
#
# The compose emitter injects the env's own name into every environment container so the
Expand Down
12 changes: 6 additions & 6 deletions tst/unit/providers/env_providers/stack_layout_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def _execs(vm: _RecordingVm) -> list[tuple]:
async def test_default_deploy_runs_todays_commands_on_todays_paths_and_ports():
vm, result, _ = await _deploy()

assert vm.exposed_ports == [AGENT_ENV_GATEWAY_MCP_PORT, DB_WEB_PORT, DB_MCP_PORT, SIDECAR_HOST_PORT]
assert vm.exposed_ports == [AGENT_ENV_GATEWAY_MCP_PORT, SIDECAR_HOST_PORT]
scripts = _scripts(vm)
assert scripts[0] == "mkdir -p /app"
assert _written(scripts[1])[0] == "/app/init-schemas.sql"
Expand All @@ -144,8 +144,8 @@ async def test_default_deploy_runs_todays_commands_on_todays_paths_and_ports():
assert ("sudo", "docker", "compose", "-f", "/app/docker-compose.yml", "ps", "-a", "-q", service) in execs
assert not any("-p" in e or "--status" in e for e in execs)
assert result.gateway_url == f"https://tunnel-{AGENT_ENV_GATEWAY_MCP_PORT}"
assert result.db_web_url == f"https://tunnel-{DB_WEB_PORT}/"
assert result.db_mcp_url == f"https://tunnel-{DB_MCP_PORT}/mcp"
assert result.db_web_url is None
assert result.db_mcp_url is None


SLOT_1_PORTS = [p + 2000 for p in (AGENT_ENV_GATEWAY_MCP_PORT, DB_WEB_PORT, DB_MCP_PORT, SIDECAR_HOST_PORT)]
Expand All @@ -167,7 +167,7 @@ async def test_slot_deploy_uses_its_own_dir_project_and_host_ports():
path, compose = _written(scripts[2])
assert path == "/app/s1/docker-compose.yml"
assert f'"{AGENT_ENV_GATEWAY_MCP_PORT + 2000}:{AGENT_ENV_GATEWAY_MCP_PORT}"' in compose
assert f'"{DB_WEB_PORT + 2000}:{DB_WEB_PORT}"' in compose
assert f'"127.0.0.1:{DB_WEB_PORT + 2000}:{DB_WEB_PORT}"' in compose
assert f'"{SIDECAR_HOST_PORT + 2000}:80"' in compose
assert f"MCP_PORT={AGENT_ENV_GATEWAY_MCP_PORT}" in compose
assert scripts[3:] == ["cd /app/s1 && docker compose -p s1 up -d"]
Expand All @@ -176,8 +176,8 @@ async def test_slot_deploy_uses_its_own_dir_project_and_host_ports():
assert (*compose_ps, "-a", "-q", "gateway") in _execs(vm)
assert ("sudo", "docker", "ps") not in _execs(vm)
assert result.gateway_url == f"https://tunnel-{AGENT_ENV_GATEWAY_MCP_PORT + 2000}"
assert result.db_web_url == f"https://tunnel-{DB_WEB_PORT + 2000}/"
assert result.db_mcp_url == f"https://tunnel-{DB_MCP_PORT + 2000}/mcp"
assert result.db_web_url is None
assert result.db_mcp_url is None
assert gp.stack_layout == slot


Expand Down
Loading